patch
stringlengths
17
31.2k
y
int64
1
1
oldf
stringlengths
0
2.21M
idx
int64
1
1
id
int64
4.29k
68.4k
msg
stringlengths
8
843
proj
stringclasses
212 values
lang
stringclasses
9 values
@@ -58,12 +58,13 @@ const ( type LabelSelector string const ( - MayaAPIServerLabelSelector LabelSelector = "name=maya-apiserver" - OpenEBSProvisionerLabelSelector LabelSelector = "name=openebs-provisioner" - OpenEBSSnapshotOperatorLabelSelector LabelSelector = "name=openebs-snapshot-operator" - OpenEBSAdmissionServerLabelSelector LabelSelector = "app=admission-webhook" - OpenEBSNDMLabelSelector LabelSelector = "name=openebs-ndm" - OpenEBSCStorPoolLabelSelector LabelSelector = "app=cstor-pool" + MayaAPIServerLabelSelector LabelSelector = "name=maya-apiserver" + OpenEBSProvisionerLabelSelector LabelSelector = "name=openebs-provisioner" + OpenEBSLocalPVProvisionerLabelSelector LabelSelector = "name=openebs-localpv-provisioner" + OpenEBSSnapshotOperatorLabelSelector LabelSelector = "name=openebs-snapshot-operator" + OpenEBSAdmissionServerLabelSelector LabelSelector = "app=admission-webhook" + OpenEBSNDMLabelSelector LabelSelector = "name=openebs-ndm" + OpenEBSCStorPoolLabelSelector LabelSelector = "app=cstor-pool" ) func parseK8sYaml(yamls string) (k8s.UnstructedList, []error) {
1
// Copyright © 2019 The OpenEBS Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package artifacts import ( "errors" "io/ioutil" "strings" k8s "github.com/openebs/maya/pkg/client/k8s/v1alpha1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "github.com/openebs/maya/pkg/artifact/v1alpha1" ) // ArtifactSource holds the path to fetch artifacts type ArtifactSource string type Artifact string const ( OpenEBSArtifacts ArtifactSource = "../artifacts/openebs-ci.yaml" CStorPVCArtifacts ArtifactSource = "../artifacts/cstor-pvc.yaml" JivaPVCArtifacts ArtifactSource = "../artifacts/jiva-pvc.yaml" SingleReplicaSC ArtifactSource = "../artifacts/storageclass-1r.yaml" CVRArtifact ArtifactSource = "../artifacts/cvr-schema.yaml" CRArtifact ArtifactSource = "../artifacts/cr-schema.yaml" ) // PodName holds the name of the pod type PodName string const ( // MayaAPIServerPodName is the name of the maya api server pod MayaAPIServerPodName PodName = "maya-apiserver" ) // Namespace holds the name of the namespace type Namespace string const ( // OpenebsNamespace is the name of the openebs namespace OpenebsNamespace Namespace = "openebs" ) // LabelSelector holds the label got openebs components type LabelSelector string const ( MayaAPIServerLabelSelector LabelSelector = "name=maya-apiserver" OpenEBSProvisionerLabelSelector LabelSelector = "name=openebs-provisioner" OpenEBSSnapshotOperatorLabelSelector LabelSelector = "name=openebs-snapshot-operator" OpenEBSAdmissionServerLabelSelector LabelSelector = "app=admission-webhook" OpenEBSNDMLabelSelector LabelSelector = "name=openebs-ndm" OpenEBSCStorPoolLabelSelector LabelSelector = "app=cstor-pool" ) func parseK8sYaml(yamls string) (k8s.UnstructedList, []error) { sepYamlfiles := strings.Split(yamls, "---") artifacts := v1alpha1.ArtifactList{} for _, f := range sepYamlfiles { if f == "\n" || f == "" { // ignore empty cases continue } f = strings.TrimSpace(f) artifacts.Items = append(artifacts.Items, &v1alpha1.Artifact{Doc: f}) } return artifacts.ToUnstructuredList() } // parseK8sYamlFromFile parses the kubernetes yaml and returns the objects in a UnstructuredList func parseK8sYamlFromFile(filename string) (k8s.UnstructedList, []error) { fileBytes, err := ioutil.ReadFile(filename) if err != nil { return k8s.UnstructedList{}, []error{err} } fileAsString := string(fileBytes[:]) return parseK8sYaml(fileAsString) } // GetArtifactsListUnstructuredFromFile returns the unstructured list of openebs components func GetArtifactsListUnstructuredFromFile(a ArtifactSource) ([]*unstructured.Unstructured, []error) { ulist, err := parseK8sYamlFromFile(string(a)) if err != nil { return nil, err } nList := ulist.MapAllIfAny([]k8s.UnstructuredMiddleware{}) return nList.Items, err } // GetArtifactUnstructuredFromFile returns the unstructured list of openebs components func GetArtifactUnstructuredFromFile(a ArtifactSource) (*unstructured.Unstructured, error) { ulist, err := parseK8sYamlFromFile(string(a)) if len(err) != 0 { return nil, err[0] } if len(ulist.Items) != 1 { return nil, errors.New("more than one artifacts found") } nList := ulist.MapAllIfAny([]k8s.UnstructuredMiddleware{}) return nList.Items[0], nil } // GetArtifactsListUnstructured returns the unstructured list of openebs components func GetArtifactsListUnstructured(a Artifact) ([]*unstructured.Unstructured, []error) { ulist, err := parseK8sYaml(strings.TrimSpace(string(a))) if err != nil { return nil, err } nList := ulist.MapAllIfAny([]k8s.UnstructuredMiddleware{}) return nList.Items, err } // GetArtifactUnstructured returns the unstructured list of openebs components func GetArtifactUnstructured(a Artifact) (*unstructured.Unstructured, error) { ulist, err := parseK8sYaml(string(a)) if len(err) != 0 { return nil, err[0] } if len(ulist.Items) != 1 { return nil, errors.New("more than one artifacts found") } nList := ulist.MapAllIfAny([]k8s.UnstructuredMiddleware{}) return nList.Items[0], nil }
1
15,951
The latest yaml in openebs/master has changed to name=admission-webhook. cc: @prateekpandey14
openebs-maya
go
@@ -3,7 +3,7 @@ # Purpose: # sns-ruby-example-send-message.rb demonstrates how to send a message using the Amazon Simple Notification Services (SNS) topic using -# the AWS SDK for JavaScript (v3). +# the AWS SDK for Ruby. # Inputs: # - REGION
1
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 # Purpose: # sns-ruby-example-send-message.rb demonstrates how to send a message using the Amazon Simple Notification Services (SNS) topic using # the AWS SDK for JavaScript (v3). # Inputs: # - REGION # - SNS_TOPIC_ARN # - MESSAGE # snippet-start:[sns.Ruby.sendMessage] require 'aws-sdk-sns' # v2: require 'aws-sdk' def message_sent?(sns_client, topic_arn, message) sns_client.publish(topic_arn: topic_arn, message: message) rescue StandardError => e puts "Error while sending the message: #{e.message}" end def run_me topic_arn = 'SNS_TOPIC_ARN' region = 'REGION' message = 'MESSAGE' # The text of the message to send. sns_client = Aws::SNS::Client.new(region: region) puts "Message sending." if message_sent?(sns_client, topic_arn, message) puts 'The message was sent.' else puts 'The message was not sent. Stopping program.' exit 1 end end run_me if $PROGRAM_NAME == __FILE__ # snippet-end:[sns.Ruby.sendMessage]
1
20,567
using **an** Amazon Simple... Simple Notification **Service** (singular)
awsdocs-aws-doc-sdk-examples
rb
@@ -55,7 +55,7 @@ void CHECK_RGROUP(RGroupRows::const_iterator &it, std::string expected, } std::string result = str.str(); - if (expected != result) { + if (1 || expected != result) { std::cerr << "Expected: " << expected << std::endl; std::cerr << "Got: " << result << std::endl; }
1
// Copyright (c) 2017, Novartis Institutes for BioMedical Research Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Novartis Institutes for BioMedical Research Inc. // nor the names of its contributors may be used to endorse or promote // products derived from this software without specific prior written // permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // #include <RDGeneral/test.h> #include <RDGeneral/RDLog.h> #include <RDGeneral/utils.h> #include <GraphMol/RDKitBase.h> #include <string> #include <iostream> #include <GraphMol/SmilesParse/SmilesParse.h> #include <GraphMol/SmilesParse/SmilesWrite.h> #include <GraphMol/RGroupDecomposition/RGroupDecomp.h> #include <GraphMol/FileParsers/FileParsers.h> #include <GraphMol/FileParsers/MolSupplier.h> #include <RDGeneral/Exceptions.h> using namespace RDKit; void CHECK_RGROUP(RGroupRows::const_iterator &it, std::string expected, bool doassert = true) { std::ostringstream str; int i = 0; for (auto rgroups = it->begin(); rgroups != it->end(); ++rgroups, ++i) { if (i) str << " "; // rlabel:smiles str << rgroups->first << ":" << MolToSmiles(*rgroups->second.get(), true); } std::string result = str.str(); if (expected != result) { std::cerr << "Expected: " << expected << std::endl; std::cerr << "Got: " << result << std::endl; } if (doassert) TEST_ASSERT(result == expected); } void DUMP_RGROUP(RGroupRows::const_iterator &it, std::string &result) { std::ostringstream str; for (const auto &rgroups : *it) { // rlabel:smiles str << rgroups.first << "\t" << MolToSmiles(*rgroups.second.get(), true) << "\t"; } std::cerr << str.str() << std::endl; result = str.str(); } const char *symdata[5] = {"c1(Cl)ccccc1", "c1c(Cl)cccc1", "c1c(Cl)cccc1", "c1cc(Cl)ccc1", "c1ccc(Cl)cc1"}; void testSymmetryMatching() { BOOST_LOG(rdInfoLog) << "********************************************************\n"; BOOST_LOG(rdInfoLog) << "test rgroup decomp symmetry matching" << std::endl; RWMol *core = SmilesToMol("c1ccccc1"); RGroupDecomposition decomp(*core); for (int i = 0; i < 5; ++i) { ROMol *mol = SmilesToMol(symdata[i]); int res = decomp.add(*mol); TEST_ASSERT(res == i); delete mol; } decomp.process(); RGroupRows rows = decomp.getRGroupsAsRows(); std::ostringstream str; // All Cl's should be labeled with the same rgroup for (RGroupRows::const_iterator it = rows.begin(); it != rows.end(); ++it) { CHECK_RGROUP(it, "Core:c1ccc([*:1])cc1 R1:Cl[*:1]"); } delete core; } const char *matchRGroupOnlyData[5] = { "c1(Cl)ccccc1", "c1c(Cl)cccc1", "c1cc(Cl)ccc1", "c1ccc(Cl)cc1", "c1c(Cl)cccc(I)1", }; void testRGroupOnlyMatching() { BOOST_LOG(rdInfoLog) << "********************************************************\n"; BOOST_LOG(rdInfoLog) << "test rgroup decomp rgroup only matching" << std::endl; RWMol *core = SmilesToMol("c1ccccc1[1*]"); RGroupDecompositionParameters params(IsotopeLabels); params.onlyMatchAtRGroups = true; RGroupDecomposition decomp(*core, params); for (int i = 0; i < 5; ++i) { ROMol *mol = SmilesToMol(matchRGroupOnlyData[i]); int res = decomp.add(*mol); if (i < 4) { TEST_ASSERT(res == i); } else { TEST_ASSERT(res == -1); } delete mol; } decomp.process(); RGroupRows rows = decomp.getRGroupsAsRows(); std::ostringstream str; // All Cl's should be labeled with the same rgroup int i = 0; for (RGroupRows::const_iterator it = rows.begin(); it != rows.end(); ++it, ++i) { CHECK_RGROUP(it, "Core:c1ccc([*:1])cc1 R1:Cl[*:1]"); } delete core; } const char *ringData[3] = {"c1cocc1", "c1c[nH]cc1", "c1cscc1"}; const char *ringDataRes[3] = {"Core:c1cc:[*:1]:c1 R1:o(:[*:1]):[*:1]", "Core:c1cc:[*:1]:c1 R1:[H]n(:[*:1]):[*:1]", "Core:c1cc:[*:1]:c1 R1:s(:[*:1]):[*:1]"}; void testRingMatching() { BOOST_LOG(rdInfoLog) << "********************************************************\n"; BOOST_LOG(rdInfoLog) << "test rgroup decomp ring matching" << std::endl; RWMol *core = SmilesToMol("c1ccc[1*]1"); RGroupDecompositionParameters params(IsotopeLabels); RGroupDecomposition decomp(*core, params); for (int i = 0; i < 3; ++i) { ROMol *mol = SmilesToMol(ringData[i]); int res = decomp.add(*mol); TEST_ASSERT(res == i); delete mol; } decomp.process(); RGroupRows rows = decomp.getRGroupsAsRows(); std::ostringstream str; // All Cl's should be labeled with the same rgroup int i = 0; for (RGroupRows::const_iterator it = rows.begin(); it != rows.end(); ++it, ++i) { CHECK_RGROUP(it, ringDataRes[i]); } delete core; } const char *ringData2[3] = {"c1cocc1CCl", "c1c[nH]cc1CI", "c1cscc1CF"}; const char *ringDataRes2[3] = { "Core:*1**[*:1](C[*:2])*1 R1:[H]c1oc([H])c([*:1])c1[H] R2:Cl[*:2]", "Core:*1**[*:1](C[*:2])*1 R1:[H]c1c([*:1])c([H])n([H])c1[H] " "R2:I[*:2]", "Core:*1**[*:1](C[*:2])*1 R1:[H]c1sc([H])c([*:1])c1[H] R2:F[*:2]"}; void testRingMatching2() { BOOST_LOG(rdInfoLog) << "********************************************************\n"; BOOST_LOG(rdInfoLog) << "test rgroup decomp full ring dummy core" << std::endl; RWMol *core = SmartsToMol("*1***[*:1]1C[*:2]"); RGroupDecompositionParameters params; RGroupDecomposition decomp(*core, params); for (int i = 0; i < 3; ++i) { ROMol *mol = SmilesToMol(ringData2[i]); int res = decomp.add(*mol); TEST_ASSERT(res == i); delete mol; } decomp.process(); RGroupRows rows = decomp.getRGroupsAsRows(); std::ostringstream str; // All Cl's should be labeled with the same rgroup int i = 0; for (RGroupRows::const_iterator it = rows.begin(); it != rows.end(); ++it, ++i) { CHECK_RGROUP(it, ringDataRes2[i]); } delete core; } const char *ringData3[3] = {"c1cocc1CCl", "c1c[nH]cc1CI", "c1cscc1CF"}; const char *ringDataRes3[3] = { "Core:c1co([*:2])cc1[*:1] R1:[H]C([H])(Cl)[*:1]", "Core:c1cn([*:2])cc1[*:1] R1:[H]C([H])(I)[*:1] R2:[H][*:2]", "Core:c1cs([*:2])cc1[*:1] R1:[H]C([H])(F)[*:1]"}; void testRingMatching3() { BOOST_LOG(rdInfoLog) << "********************************************************\n"; BOOST_LOG(rdInfoLog) << "test rgroup decomp full ring dummy core" << std::endl; RWMol *core = SmartsToMol("*1***[*:1]1"); RGroupDecompositionParameters params; RGroupDecomposition decomp(*core, params); for (int i = 0; i < 3; ++i) { ROMol *mol = SmilesToMol(ringData3[i]); int res = decomp.add(*mol); delete mol; TEST_ASSERT(res == i); } decomp.process(); RGroupRows rows = decomp.getRGroupsAsRows(); std::ostringstream str; // All Cl's should be labeled with the same rgroup int i = 0; for (RGroupRows::const_iterator it = rows.begin(); it != rows.end(); ++it, ++i) { CHECK_RGROUP(it, ringDataRes3[i]); } delete core; } const char *coreSmi[] = { "C1CCNC(Cl)CC1", "C1CC(Cl)NCCC1", "C1CCNC(I)CC1", "C1CC(I)NCCC1", "C1CCSC(Cl)CC1", "C1CC(Cl)SCCC1", "C1CCSC(I)CC1", "C1CC(I)SCCC1", "C1CCOC(Cl)CC1", "C1CC(Cl)OCCC1", "C1CCOC(I)CC1", "C1CC(I)OCCC1"}; const char *coreSmiRes[] = {"Core:C1CCC([*:2])N([*:1])CC1 R1:Cl[*:1].[H][*:1]", "Core:C1CCC([*:2])N([*:1])CC1 R1:Cl[*:1].[H][*:1]", "Core:C1CCC([*:2])N([*:1])CC1 R1:I[*:1].[H][*:1]", "Core:C1CCC([*:2])N([*:1])CC1 R1:I[*:1].[H][*:1]", "Core:C1CCSC([*:1])CC1 R1:Cl[*:1].[H][*:1]", "Core:C1CCSC([*:1])CC1 R1:Cl[*:1].[H][*:1]", "Core:C1CCSC([*:1])CC1 R1:I[*:1].[H][*:1]", "Core:C1CCSC([*:1])CC1 R1:I[*:1].[H][*:1]", "Core:C1CCOC([*:1])CC1 R1:Cl[*:1].[H][*:1]", "Core:C1CCOC([*:1])CC1 R1:Cl[*:1].[H][*:1]", "Core:C1CCOC([*:1])CC1 R1:I[*:1].[H][*:1]", "Core:C1CCOC([*:1])CC1 R1:I[*:1].[H][*:1]"}; void testMultiCore() { BOOST_LOG(rdInfoLog) << "********************************************************\n"; BOOST_LOG(rdInfoLog) << "test multi core" << std::endl; std::vector<ROMOL_SPTR> cores; cores.push_back(ROMOL_SPTR(SmartsToMol("C1CCNCCC1"))); cores.push_back(ROMOL_SPTR(SmilesToMol("C1CCOCCC1"))); cores.push_back(ROMOL_SPTR(SmilesToMol("C1CCSCCC1"))); RGroupDecomposition decomp(cores); for (unsigned int i = 0; i < sizeof(coreSmi) / sizeof(const char *); ++i) { ROMol *mol = SmilesToMol(coreSmi[i]); unsigned int res = decomp.add(*mol); delete mol; TEST_ASSERT(res == i); } decomp.process(); RGroupRows rows = decomp.getRGroupsAsRows(); std::ostringstream str; // All Cl's should be labeled with the same rgroup int i = 0; for (RGroupRows::const_iterator it = rows.begin(); it != rows.end(); ++it, ++i) { CHECK_RGROUP(it, coreSmiRes[i]); } } void testGithub1550() { BOOST_LOG(rdInfoLog) << "********************************************************\n"; BOOST_LOG(rdInfoLog) << "test Github #1550: Kekulization error from R-group decomposition" << std::endl; RWMol *core = SmilesToMol("O=c1oc2ccccc2cc1"); RGroupDecompositionParameters params; RGroupDecomposition decomp(*core, params); const char *smilesData[3] = {"O=c1cc(Cn2ccnc2)c2ccc(Oc3ccccc3)cc2o1", "O=c1oc2ccccc2c(Cn2ccnc2)c1-c1ccccc1", "COc1ccc2c(Cn3cncn3)cc(=O)oc2c1"}; for (int i = 0; i < 3; ++i) { ROMol *mol = SmilesToMol(smilesData[i]); int res = decomp.add(*mol); delete mol; TEST_ASSERT(res == i); } decomp.process(); RGroupColumns groups = decomp.getRGroupsAsColumns(); RWMol *coreRes = (RWMol *)groups["Core"][0].get(); TEST_ASSERT(coreRes->getNumAtoms() == 14); MolOps::Kekulize(*coreRes); RWMol *rg2 = (RWMol *)groups["R2"][0].get(); TEST_ASSERT(rg2->getNumAtoms() == 12); MolOps::Kekulize(*rg2); delete core; } void testRemoveHs() { BOOST_LOG(rdInfoLog) << "********************************************************\n"; BOOST_LOG(rdInfoLog) << "test remove sidechain Hs" << std::endl; RWMol *core = SmilesToMol("O=c1oc2ccccc2cc1"); { RGroupDecompositionParameters params; RGroupDecomposition decomp(*core, params); const char *smilesData[3] = {"O=c1cc(Cn2ccnc2)c2ccc(Oc3ccccc3)cc2o1", "O=c1oc2ccccc2c(Cn2ccnc2)c1-c1ccccc1", "COc1ccc2c(Cn3cncn3)cc(=O)oc2c1"}; for (int i = 0; i < 3; ++i) { ROMol *mol = SmilesToMol(smilesData[i]); int res = decomp.add(*mol); delete mol; TEST_ASSERT(res == i); } decomp.process(); RGroupColumns groups = decomp.getRGroupsAsColumns(); RWMol *rg2 = (RWMol *)groups["R2"][0].get(); TEST_ASSERT(rg2->getNumAtoms() == 12); } { RGroupDecompositionParameters params; params.removeHydrogensPostMatch = true; RGroupDecomposition decomp(*core, params); const char *smilesData[3] = {"O=c1cc(Cn2ccnc2)c2ccc(Oc3ccccc3)cc2o1", "O=c1oc2ccccc2c(Cn2ccnc2)c1-c1ccccc1", "COc1ccc2c(Cn3cncn3)cc(=O)oc2c1"}; for (int i = 0; i < 3; ++i) { ROMol *mol = SmilesToMol(smilesData[i]); int res = decomp.add(*mol); delete mol; TEST_ASSERT(res == i); } decomp.process(); RGroupColumns groups = decomp.getRGroupsAsColumns(); RWMol *rg2 = (RWMol *)groups["R2"][0].get(); TEST_ASSERT(rg2->getNumAtoms() == 7); } delete core; } void testGitHubIssue1705() { BOOST_LOG(rdInfoLog) << "********************************************************\n"; BOOST_LOG(rdInfoLog) << "test preferring grouping non hydrogens over hydrogens if possible" << std::endl; #if 1 { RWMol *core = SmilesToMol("Oc1ccccc1"); RGroupDecompositionParameters params; RGroupDecomposition decomp(*core, params); const char *smilesData[5] = {"Oc1ccccc1", "Oc1c(F)cccc1", "Oc1ccccc1F", "Oc1c(F)cc(N)cc1", "Oc1ccccc1Cl"}; for (int i = 0; i < 5; ++i) { ROMol *mol = SmilesToMol(smilesData[i]); int res = decomp.add(*mol); delete mol; TEST_ASSERT(res == i); } decomp.process(); std::stringstream ss; RGroupColumns groups = decomp.getRGroupsAsColumns(); for (auto &column : groups) { ss << "Rgroup===" << column.first << std::endl; for (auto &rgroup : column.second) { ss << MolToSmiles(*rgroup) << std::endl; } } delete core; // std::cerr<<ss.str()<<std::endl; TEST_ASSERT(ss.str() == R"RES(Rgroup===Core Oc1ccc([*:1])cc1[*:2] Oc1ccc([*:1])cc1[*:2] Oc1ccc([*:1])cc1[*:2] Oc1ccc([*:1])cc1[*:2] Oc1ccc([*:1])cc1[*:2] Rgroup===R1 [H][*:1] [H][*:1] [H][*:1] [H]N([H])[*:1] [H][*:1] Rgroup===R2 [H][*:2] F[*:2] F[*:2] F[*:2] Cl[*:2] )RES"); } #endif // std::cerr<<"n\n\n\n\n\n--------------------------------------------------------------\n\n\n\n\n"; { RWMol *core = SmilesToMol("Cc1ccccc1"); RGroupDecompositionParameters params; RGroupDecomposition decomp(*core, params); std::vector<std::string> smilesData = {"c1ccccc1C", "Fc1ccccc1C", "c1cccc(F)c1C", "Fc1cccc(F)c1C"}; for (const auto &smi : smilesData) { ROMol *mol = SmilesToMol(smi); int res = decomp.add(*mol); delete mol; } decomp.process(); std::stringstream ss; RGroupColumns groups = decomp.getRGroupsAsColumns(); for (auto &column : groups) { ss << "Rgroup===" << column.first << std::endl; for (auto &rgroup : column.second) { ss << MolToSmiles(*rgroup) << std::endl; } } delete core; // std::cerr<<ss.str()<<std::endl; TEST_ASSERT(ss.str() == R"RES(Rgroup===Core Cc1c([*:1])cccc1[*:2] Cc1c([*:1])cccc1[*:2] Cc1c([*:1])cccc1[*:2] Cc1c([*:1])cccc1[*:2] Rgroup===R1 [H][*:1] F[*:1] F[*:1] F[*:1] Rgroup===R2 [H][*:2] [H][*:2] [H][*:2] F[*:2] )RES"); } } void testMatchOnlyAtRgroupHs() { BOOST_LOG(rdInfoLog) << "********************************************************\n"; BOOST_LOG(rdInfoLog) << "test matching only rgroups but allows Hs" << std::endl; RWMol *core = SmilesToMol("*OCC"); RGroupDecompositionParameters params; params.onlyMatchAtRGroups = true; RGroupDecomposition decomp(*core, params); const char *smilesData[2] = {"OCC", "COCC"}; for (int i = 0; i < 2; ++i) { ROMol *mol = SmilesToMol(smilesData[i]); decomp.add(*mol); delete mol; } decomp.process(); std::stringstream ss; RGroupColumns groups = decomp.getRGroupsAsColumns(); for (auto &column : groups) { ss << "Rgroup===" << column.first << std::endl; for (auto &rgroup : column.second) { ss << MolToSmiles(*rgroup) << std::endl; } } std::cerr << ss.str() << std::endl; delete core; TEST_ASSERT(ss.str() == "Rgroup===Core\nCCO[*:1]\nCCO[*:1]\nRgroup===R1\n[H][*:1]\n[H]C([" "H])([H])[*:1]\n"); } void testGithub2332() { BOOST_LOG(rdInfoLog) << "********************************************************\n"; BOOST_LOG(rdInfoLog) << "test github #2332: RGroupDecomposition: addHs() " "call should set coords " << std::endl; auto core = "*OCC"_smiles; RGroupDecompositionParameters params; params.onlyMatchAtRGroups = true; RGroupDecomposition decomp(*core, params); std::string chains[2] = { R"CTAB( Mrv1810 03291913362D 4 3 0 0 0 0 999 V2000 2.0625 -0.7145 0.0000 Cl 0 0 0 0 0 0 0 0 0 0 0 0 1.2375 -0.7145 0.0000 O 0 0 0 0 0 0 0 0 0 0 0 0 0.8250 0.0000 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 0.0000 0.0000 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 1 2 1 0 0 0 0 2 3 1 0 0 0 0 3 4 1 0 0 0 0 M END )CTAB", R"CTAB( Mrv1810 03291913362D 3 2 0 0 0 0 999 V2000 1.2375 -0.7145 0.0000 O 0 0 0 0 0 0 0 0 0 0 0 0 0.8250 0.0000 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 0.0000 0.0000 0.0000 C 0 0 0 0 0 0 0 0 0 0 0 0 1 2 1 0 0 0 0 2 3 1 0 0 0 0 M END )CTAB"}; for (int i = 0; i < 2; ++i) { ROMol *mol = MolBlockToMol(chains[i]); decomp.add(*mol); delete mol; } decomp.process(); std::stringstream ss; RGroupColumns groups = decomp.getRGroupsAsColumns(); auto &r1 = groups["R1"]; TEST_ASSERT(r1.size() == 2); TEST_ASSERT(r1[1]->getAtomWithIdx(0)->getAtomicNum() == 1); auto conf = r1[1]->getConformer(); TEST_ASSERT(!feq(conf.getAtomPos(0).x, 0.0)); TEST_ASSERT(!feq(conf.getAtomPos(0).y, 0.0)); TEST_ASSERT(feq(conf.getAtomPos(0).z, 0.0)); } int main() { RDLog::InitLogs(); BOOST_LOG(rdInfoLog) << "********************************************************\n"; BOOST_LOG(rdInfoLog) << "Testing R-Group Decomposition \n"; #if 1 testSymmetryMatching(); testRGroupOnlyMatching(); testRingMatching(); testRingMatching3(); testMultiCore(); testGithub1550(); testRemoveHs(); testMatchOnlyAtRgroupHs(); #endif testRingMatching2(); testGitHubIssue1705(); testGithub2332(); BOOST_LOG(rdInfoLog) << "********************************************************\n"; return 0; }
1
19,277
Probably don't intend for this `1 ||` to still be here
rdkit-rdkit
cpp
@@ -353,14 +353,6 @@ bool cvdescriptorset::ValidateDescriptorSetLayoutCreateInfo( VK_KHR_PUSH_DESCRIPTOR_EXTENSION_NAME); } - const bool host_only_pool_set = static_cast<bool>(create_info->flags & VK_DESCRIPTOR_SET_LAYOUT_CREATE_HOST_ONLY_POOL_BIT_VALVE); - if (push_descriptor_set && host_only_pool_set) { - skip |= val_obj->LogError(val_obj->device, "VUID-VkDescriptorSetLayoutCreateInfo-flags-04590", - "vkCreateDescriptorSetLayout(): pCreateInfo->flags cannot contain both " - "VK_DESCRIPTOR_SET_LAYOUT_CREATE_PUSH_DESCRIPTOR_BIT_KHR and " - "VK_DESCRIPTOR_SET_LAYOUT_CREATE_HOST_ONLY_POOL_BIT_VALVE."); - } - const bool update_after_bind_set = !!(create_info->flags & VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT); if (update_after_bind_set && !descriptor_indexing_ext) { skip |= val_obj->LogError(
1
/* Copyright (c) 2015-2021 The Khronos Group Inc. * Copyright (c) 2015-2021 Valve Corporation * Copyright (c) 2015-2021 LunarG, Inc. * Copyright (C) 2015-2021 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Author: Tobin Ehlis <[email protected]> * John Zulauf <[email protected]> * Jeremy Kniager <[email protected]> */ #include "chassis.h" #include "core_validation_error_enums.h" #include "core_validation.h" #include "descriptor_sets.h" #include "hash_vk_types.h" #include "vk_enum_string_helper.h" #include "vk_safe_struct.h" #include "vk_typemap_helper.h" #include "buffer_validation.h" #include <sstream> #include <algorithm> #include <array> #include <memory> // ExtendedBinding collects a VkDescriptorSetLayoutBinding and any extended // state that comes from a different array/structure so they can stay together // while being sorted by binding number. struct ExtendedBinding { ExtendedBinding(const VkDescriptorSetLayoutBinding *l, VkDescriptorBindingFlags f) : layout_binding(l), binding_flags(f) {} const VkDescriptorSetLayoutBinding *layout_binding; VkDescriptorBindingFlags binding_flags; }; struct BindingNumCmp { bool operator()(const ExtendedBinding &a, const ExtendedBinding &b) const { return a.layout_binding->binding < b.layout_binding->binding; } }; using DescriptorSet = cvdescriptorset::DescriptorSet; using DescriptorSetLayout = cvdescriptorset::DescriptorSetLayout; using DescriptorSetLayoutDef = cvdescriptorset::DescriptorSetLayoutDef; using DescriptorSetLayoutId = cvdescriptorset::DescriptorSetLayoutId; // Canonical dictionary of DescriptorSetLayoutDef (without any handle/device specific information) cvdescriptorset::DescriptorSetLayoutDict descriptor_set_layout_dict; DescriptorSetLayoutId GetCanonicalId(const VkDescriptorSetLayoutCreateInfo *p_create_info) { return descriptor_set_layout_dict.look_up(DescriptorSetLayoutDef(p_create_info)); } // Construct DescriptorSetLayout instance from given create info // Proactively reserve and resize as possible, as the reallocation was visible in profiling cvdescriptorset::DescriptorSetLayoutDef::DescriptorSetLayoutDef(const VkDescriptorSetLayoutCreateInfo *p_create_info) : flags_(p_create_info->flags), binding_count_(0), descriptor_count_(0), dynamic_descriptor_count_(0) { const auto *flags_create_info = LvlFindInChain<VkDescriptorSetLayoutBindingFlagsCreateInfo>(p_create_info->pNext); binding_type_stats_ = {0, 0}; std::set<ExtendedBinding, BindingNumCmp> sorted_bindings; const uint32_t input_bindings_count = p_create_info->bindingCount; // Sort the input bindings in binding number order, eliminating duplicates for (uint32_t i = 0; i < input_bindings_count; i++) { VkDescriptorBindingFlags flags = 0; if (flags_create_info && flags_create_info->bindingCount == p_create_info->bindingCount) { flags = flags_create_info->pBindingFlags[i]; } sorted_bindings.emplace(p_create_info->pBindings + i, flags); } // Store the create info in the sorted order from above uint32_t index = 0; binding_count_ = static_cast<uint32_t>(sorted_bindings.size()); bindings_.reserve(binding_count_); binding_flags_.reserve(binding_count_); binding_to_index_map_.reserve(binding_count_); for (const auto &input_binding : sorted_bindings) { // Add to binding and map, s.t. it is robust to invalid duplication of binding_num const auto binding_num = input_binding.layout_binding->binding; binding_to_index_map_[binding_num] = index++; bindings_.emplace_back(input_binding.layout_binding); auto &binding_info = bindings_.back(); binding_flags_.emplace_back(input_binding.binding_flags); descriptor_count_ += binding_info.descriptorCount; if (binding_info.descriptorCount > 0) { non_empty_bindings_.insert(binding_num); } if (IsDynamicDescriptor(binding_info.descriptorType)) { dynamic_descriptor_count_ += binding_info.descriptorCount; } // Get stats depending on descriptor type for caching later if (IsBufferDescriptor(binding_info.descriptorType)) { if (IsDynamicDescriptor(binding_info.descriptorType)) { binding_type_stats_.dynamic_buffer_count++; } else { binding_type_stats_.non_dynamic_buffer_count++; } } } assert(bindings_.size() == binding_count_); assert(binding_flags_.size() == binding_count_); uint32_t global_index = 0; global_index_range_.reserve(binding_count_); // Vector order is finalized so build vectors of descriptors and dynamic offsets by binding index for (uint32_t i = 0; i < binding_count_; ++i) { auto final_index = global_index + bindings_[i].descriptorCount; global_index_range_.emplace_back(global_index, final_index); global_index = final_index; } } size_t cvdescriptorset::DescriptorSetLayoutDef::hash() const { hash_util::HashCombiner hc; hc << flags_; hc.Combine(bindings_); hc.Combine(binding_flags_); return hc.Value(); } // // Return valid index or "end" i.e. binding_count_; // The asserts in "Get" are reduced to the set where no valid answer(like null or 0) could be given // Common code for all binding lookups. uint32_t cvdescriptorset::DescriptorSetLayoutDef::GetIndexFromBinding(uint32_t binding) const { const auto &bi_itr = binding_to_index_map_.find(binding); if (bi_itr != binding_to_index_map_.cend()) return bi_itr->second; return GetBindingCount(); } VkDescriptorSetLayoutBinding const *cvdescriptorset::DescriptorSetLayoutDef::GetDescriptorSetLayoutBindingPtrFromIndex( const uint32_t index) const { if (index >= bindings_.size()) return nullptr; return bindings_[index].ptr(); } // Return descriptorCount for given index, 0 if index is unavailable uint32_t cvdescriptorset::DescriptorSetLayoutDef::GetDescriptorCountFromIndex(const uint32_t index) const { if (index >= bindings_.size()) return 0; return bindings_[index].descriptorCount; } // For the given index, return descriptorType VkDescriptorType cvdescriptorset::DescriptorSetLayoutDef::GetTypeFromIndex(const uint32_t index) const { assert(index < bindings_.size()); if (index < bindings_.size()) return bindings_[index].descriptorType; return VK_DESCRIPTOR_TYPE_MAX_ENUM; } // For the given index, return stageFlags VkShaderStageFlags cvdescriptorset::DescriptorSetLayoutDef::GetStageFlagsFromIndex(const uint32_t index) const { assert(index < bindings_.size()); if (index < bindings_.size()) return bindings_[index].stageFlags; return VkShaderStageFlags(0); } // Return binding flags for given index, 0 if index is unavailable VkDescriptorBindingFlags cvdescriptorset::DescriptorSetLayoutDef::GetDescriptorBindingFlagsFromIndex(const uint32_t index) const { if (index >= binding_flags_.size()) return 0; return binding_flags_[index]; } const cvdescriptorset::IndexRange &cvdescriptorset::DescriptorSetLayoutDef::GetGlobalIndexRangeFromIndex(uint32_t index) const { const static IndexRange k_invalid_range = {0xFFFFFFFF, 0xFFFFFFFF}; if (index >= binding_flags_.size()) return k_invalid_range; return global_index_range_[index]; } // For the given binding, return the global index range (half open) // As start and end are often needed in pairs, get both with a single lookup. const cvdescriptorset::IndexRange &cvdescriptorset::DescriptorSetLayoutDef::GetGlobalIndexRangeFromBinding( const uint32_t binding) const { uint32_t index = GetIndexFromBinding(binding); return GetGlobalIndexRangeFromIndex(index); } // For given binding, return ptr to ImmutableSampler array VkSampler const *cvdescriptorset::DescriptorSetLayoutDef::GetImmutableSamplerPtrFromBinding(const uint32_t binding) const { const auto &bi_itr = binding_to_index_map_.find(binding); if (bi_itr != binding_to_index_map_.end()) { return bindings_[bi_itr->second].pImmutableSamplers; } return nullptr; } // Move to next valid binding having a non-zero binding count uint32_t cvdescriptorset::DescriptorSetLayoutDef::GetNextValidBinding(const uint32_t binding) const { auto it = non_empty_bindings_.upper_bound(binding); assert(it != non_empty_bindings_.cend()); if (it != non_empty_bindings_.cend()) return *it; return GetMaxBinding() + 1; } // For given index, return ptr to ImmutableSampler array VkSampler const *cvdescriptorset::DescriptorSetLayoutDef::GetImmutableSamplerPtrFromIndex(const uint32_t index) const { if (index < bindings_.size()) { return bindings_[index].pImmutableSamplers; } return nullptr; } // If our layout is compatible with rh_ds_layout, return true. bool cvdescriptorset::DescriptorSetLayout::IsCompatible(DescriptorSetLayout const *rh_ds_layout) const { bool compatible = (this == rh_ds_layout) || (GetLayoutDef() == rh_ds_layout->GetLayoutDef()); return compatible; } // TODO: Find a way to add smarts to the autogenerated version of this static std::string smart_string_VkShaderStageFlags(VkShaderStageFlags stage_flags) { if (stage_flags == VK_SHADER_STAGE_ALL) { return string_VkShaderStageFlagBits(VK_SHADER_STAGE_ALL); } return string_VkShaderStageFlags(stage_flags); } // If our layout is compatible with bound_dsl, return true, // else return false and fill in error_msg will description of what causes incompatibility bool cvdescriptorset::VerifySetLayoutCompatibility(const debug_report_data *report_data, DescriptorSetLayout const *layout_dsl, DescriptorSetLayout const *bound_dsl, std::string *error_msg) { // Short circuit the detailed check. if (layout_dsl->IsCompatible(bound_dsl)) return true; // Do a detailed compatibility check of this lhs def (referenced by layout_dsl), vs. the rhs (layout and def) // Should only be run if trivial accept has failed, and in that context should return false. VkDescriptorSetLayout layout_dsl_handle = layout_dsl->GetDescriptorSetLayout(); VkDescriptorSetLayout bound_dsl_handle = bound_dsl->GetDescriptorSetLayout(); DescriptorSetLayoutDef const *layout_ds_layout_def = layout_dsl->GetLayoutDef(); DescriptorSetLayoutDef const *bound_ds_layout_def = bound_dsl->GetLayoutDef(); // Check descriptor counts const auto bound_total_count = bound_ds_layout_def->GetTotalDescriptorCount(); if (layout_ds_layout_def->GetTotalDescriptorCount() != bound_ds_layout_def->GetTotalDescriptorCount()) { std::stringstream error_str; error_str << report_data->FormatHandle(layout_dsl_handle) << " from pipeline layout has " << layout_ds_layout_def->GetTotalDescriptorCount() << " total descriptors, but " << report_data->FormatHandle(bound_dsl_handle) << ", which is bound, has " << bound_total_count << " total descriptors."; *error_msg = error_str.str(); return false; // trivial fail case } // Descriptor counts match so need to go through bindings one-by-one // and verify that type and stageFlags match for (const auto &layout_binding : layout_ds_layout_def->GetBindings()) { // TODO : Do we also need to check immutable samplers? const auto bound_binding = bound_ds_layout_def->GetBindingInfoFromBinding(layout_binding.binding); if (layout_binding.descriptorCount != bound_binding->descriptorCount) { std::stringstream error_str; error_str << "Binding " << layout_binding.binding << " for " << report_data->FormatHandle(layout_dsl_handle) << " from pipeline layout has a descriptorCount of " << layout_binding.descriptorCount << " but binding " << layout_binding.binding << " for " << report_data->FormatHandle(bound_dsl_handle) << ", which is bound, has a descriptorCount of " << bound_binding->descriptorCount; *error_msg = error_str.str(); return false; } else if (layout_binding.descriptorType != bound_binding->descriptorType) { std::stringstream error_str; error_str << "Binding " << layout_binding.binding << " for " << report_data->FormatHandle(layout_dsl_handle) << " from pipeline layout is type '" << string_VkDescriptorType(layout_binding.descriptorType) << "' but binding " << layout_binding.binding << " for " << report_data->FormatHandle(bound_dsl_handle) << ", which is bound, is type '" << string_VkDescriptorType(bound_binding->descriptorType) << "'"; *error_msg = error_str.str(); return false; } else if (layout_binding.stageFlags != bound_binding->stageFlags) { std::stringstream error_str; error_str << "Binding " << layout_binding.binding << " for " << report_data->FormatHandle(layout_dsl_handle) << " from pipeline layout has stageFlags " << smart_string_VkShaderStageFlags(layout_binding.stageFlags) << " but binding " << layout_binding.binding << " for " << report_data->FormatHandle(bound_dsl_handle) << ", which is bound, has stageFlags " << smart_string_VkShaderStageFlags(bound_binding->stageFlags); *error_msg = error_str.str(); return false; } } const auto &ds_layout_flags = layout_ds_layout_def->GetBindingFlags(); const auto &bound_layout_flags = bound_ds_layout_def->GetBindingFlags(); if (bound_layout_flags != ds_layout_flags) { std::stringstream error_str; assert(ds_layout_flags.size() == bound_layout_flags.size()); size_t i; for (i = 0; i < ds_layout_flags.size(); i++) { if (ds_layout_flags[i] != bound_layout_flags[i]) break; } error_str << report_data->FormatHandle(layout_dsl_handle) << " from pipeline layout does not have the same binding flags at binding " << i << " ( " << string_VkDescriptorBindingFlagsEXT(ds_layout_flags[i]) << " ) as " << report_data->FormatHandle(bound_dsl_handle) << " ( " << string_VkDescriptorBindingFlagsEXT(bound_layout_flags[i]) << " ), which is bound"; *error_msg = error_str.str(); return false; } // No detailed check should succeed if the trivial check failed -- or the dictionary has failed somehow. bool compatible = true; assert(!compatible); return compatible; } bool cvdescriptorset::DescriptorSetLayoutDef::IsNextBindingConsistent(const uint32_t binding) const { if (!binding_to_index_map_.count(binding + 1)) return false; auto const &bi_itr = binding_to_index_map_.find(binding); if (bi_itr != binding_to_index_map_.end()) { const auto &next_bi_itr = binding_to_index_map_.find(binding + 1); if (next_bi_itr != binding_to_index_map_.end()) { auto type = bindings_[bi_itr->second].descriptorType; auto stage_flags = bindings_[bi_itr->second].stageFlags; auto immut_samp = bindings_[bi_itr->second].pImmutableSamplers ? true : false; auto flags = binding_flags_[bi_itr->second]; if ((type != bindings_[next_bi_itr->second].descriptorType) || (stage_flags != bindings_[next_bi_itr->second].stageFlags) || (immut_samp != (bindings_[next_bi_itr->second].pImmutableSamplers ? true : false)) || (flags != binding_flags_[next_bi_itr->second])) { return false; } return true; } } return false; } // The DescriptorSetLayout stores the per handle data for a descriptor set layout, and references the common defintion for the // handle invariant portion cvdescriptorset::DescriptorSetLayout::DescriptorSetLayout(const VkDescriptorSetLayoutCreateInfo *p_create_info, const VkDescriptorSetLayout layout) : BASE_NODE(layout, kVulkanObjectTypeDescriptorSetLayout), layout_id_(GetCanonicalId(p_create_info)) {} // Validate descriptor set layout create info bool cvdescriptorset::ValidateDescriptorSetLayoutCreateInfo( const ValidationObject *val_obj, const VkDescriptorSetLayoutCreateInfo *create_info, const bool push_descriptor_ext, const uint32_t max_push_descriptors, const bool descriptor_indexing_ext, const VkPhysicalDeviceVulkan12Features *core12_features, const VkPhysicalDeviceInlineUniformBlockFeaturesEXT *inline_uniform_block_features, const VkPhysicalDeviceInlineUniformBlockPropertiesEXT *inline_uniform_block_props, const DeviceExtensions *device_extensions) { bool skip = false; layer_data::unordered_set<uint32_t> bindings; uint64_t total_descriptors = 0; const auto *flags_create_info = LvlFindInChain<VkDescriptorSetLayoutBindingFlagsCreateInfo>(create_info->pNext); const bool push_descriptor_set = !!(create_info->flags & VK_DESCRIPTOR_SET_LAYOUT_CREATE_PUSH_DESCRIPTOR_BIT_KHR); if (push_descriptor_set && !push_descriptor_ext) { skip |= val_obj->LogError( val_obj->device, kVUID_Core_DrawState_ExtensionNotEnabled, "vkCreateDescriptorSetLayout(): Attempted to use %s in %s but its required extension %s has not been enabled.\n", "VK_DESCRIPTOR_SET_LAYOUT_CREATE_PUSH_DESCRIPTOR_BIT_KHR", "VkDescriptorSetLayoutCreateInfo::flags", VK_KHR_PUSH_DESCRIPTOR_EXTENSION_NAME); } const bool host_only_pool_set = static_cast<bool>(create_info->flags & VK_DESCRIPTOR_SET_LAYOUT_CREATE_HOST_ONLY_POOL_BIT_VALVE); if (push_descriptor_set && host_only_pool_set) { skip |= val_obj->LogError(val_obj->device, "VUID-VkDescriptorSetLayoutCreateInfo-flags-04590", "vkCreateDescriptorSetLayout(): pCreateInfo->flags cannot contain both " "VK_DESCRIPTOR_SET_LAYOUT_CREATE_PUSH_DESCRIPTOR_BIT_KHR and " "VK_DESCRIPTOR_SET_LAYOUT_CREATE_HOST_ONLY_POOL_BIT_VALVE."); } const bool update_after_bind_set = !!(create_info->flags & VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT); if (update_after_bind_set && !descriptor_indexing_ext) { skip |= val_obj->LogError( val_obj->device, kVUID_Core_DrawState_ExtensionNotEnabled, "vkCreateDescriptorSetLayout(): Attemped to use %s in %s but its required extension %s has not been enabled.\n", "VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT", "VkDescriptorSetLayoutCreateInfo::flags", VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME); } auto valid_type = [push_descriptor_set](const VkDescriptorType type) { return !push_descriptor_set || ((type != VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC) && (type != VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC) && (type != VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT)); }; uint32_t max_binding = 0; for (uint32_t i = 0; i < create_info->bindingCount; ++i) { const auto &binding_info = create_info->pBindings[i]; max_binding = std::max(max_binding, binding_info.binding); if (!bindings.insert(binding_info.binding).second) { skip |= val_obj->LogError(val_obj->device, "VUID-VkDescriptorSetLayoutCreateInfo-binding-00279", "vkCreateDescriptorSetLayout(): pBindings[%u] has duplicated binding number (%u).", i, binding_info.binding); } if (!valid_type(binding_info.descriptorType)) { skip |= val_obj->LogError(val_obj->device, (binding_info.descriptorType == VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT) ? "VUID-VkDescriptorSetLayoutCreateInfo-flags-02208" : "VUID-VkDescriptorSetLayoutCreateInfo-flags-00280", "vkCreateDescriptorSetLayout(): pBindings[%u] has invalid type %s , for push descriptors.", i, string_VkDescriptorType(binding_info.descriptorType)); } if (binding_info.descriptorType == VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT) { if (!inline_uniform_block_features->inlineUniformBlock) { skip |= val_obj->LogError(val_obj->device, "VUID-VkDescriptorSetLayoutBinding-descriptorType-04604", "vkCreateDescriptorSetLayout(): pBindings[%u] is creating VkDescriptorSetLayout with " "descriptor type VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT " "but the inlineUniformBlock feature is not enabled", i); } else { if ((binding_info.descriptorCount % 4) != 0) { skip |= val_obj->LogError(val_obj->device, "VUID-VkDescriptorSetLayoutBinding-descriptorType-02209", "vkCreateDescriptorSetLayout(): pBindings[%u] has descriptorCount =(%" PRIu32 ") but must be a multiple of 4", i, binding_info.descriptorCount); } if (binding_info.descriptorCount > inline_uniform_block_props->maxInlineUniformBlockSize) { skip |= val_obj->LogError(val_obj->device, "VUID-VkDescriptorSetLayoutBinding-descriptorType-02210", "vkCreateDescriptorSetLayout(): pBindings[%u] has descriptorCount =(%" PRIu32 ") but must be less than or equal to maxInlineUniformBlockSize (%u)", i, binding_info.descriptorCount, inline_uniform_block_props->maxInlineUniformBlockSize); } } } if ((binding_info.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER || binding_info.descriptorType == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER) && binding_info.pImmutableSamplers && device_extensions->vk_ext_custom_border_color) { const CoreChecks *core_checks = reinterpret_cast<const CoreChecks *>(val_obj); for (uint32_t j = 0; j < binding_info.descriptorCount; j++) { const SAMPLER_STATE *sampler_state = core_checks->GetSamplerState(binding_info.pImmutableSamplers[j]); if (sampler_state && (sampler_state->createInfo.borderColor == VK_BORDER_COLOR_INT_CUSTOM_EXT || sampler_state->createInfo.borderColor == VK_BORDER_COLOR_FLOAT_CUSTOM_EXT)) { skip |= val_obj->LogError( val_obj->device, "VUID-VkDescriptorSetLayoutBinding-pImmutableSamplers-04009", "vkCreateDescriptorSetLayout(): pBindings[%u].pImmutableSamplers[%u] has VkSampler %s" " presented as immutable has a custom border color", i, j, val_obj->report_data->FormatHandle(binding_info.pImmutableSamplers[j]).c_str()); } } } total_descriptors += binding_info.descriptorCount; } if (flags_create_info) { if (flags_create_info->bindingCount != 0 && flags_create_info->bindingCount != create_info->bindingCount) { skip |= val_obj->LogError(val_obj->device, "VUID-VkDescriptorSetLayoutBindingFlagsCreateInfo-bindingCount-03002", "vkCreateDescriptorSetLayout(): VkDescriptorSetLayoutCreateInfo::bindingCount (%d) != " "VkDescriptorSetLayoutBindingFlagsCreateInfo::bindingCount (%d)", create_info->bindingCount, flags_create_info->bindingCount); } if (flags_create_info->bindingCount == create_info->bindingCount) { for (uint32_t i = 0; i < create_info->bindingCount; ++i) { const auto &binding_info = create_info->pBindings[i]; if (flags_create_info->pBindingFlags[i] & VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT) { if (!update_after_bind_set) { skip |= val_obj->LogError(val_obj->device, "VUID-VkDescriptorSetLayoutCreateInfo-flags-03000", "vkCreateDescriptorSetLayout(): pBindings[%u] does not have " "VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT.", i); } if (binding_info.descriptorType == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER && !core12_features->descriptorBindingUniformBufferUpdateAfterBind) { skip |= val_obj->LogError( val_obj->device, "VUID-VkDescriptorSetLayoutBindingFlagsCreateInfo-" "descriptorBindingUniformBufferUpdateAfterBind-03005", "vkCreateDescriptorSetLayout(): pBindings[%u] can't have VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT " "for %s since descriptorBindingUniformBufferUpdateAfterBind is not enabled.", i, string_VkDescriptorType(binding_info.descriptorType)); } if ((binding_info.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER || binding_info.descriptorType == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER || binding_info.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE) && !core12_features->descriptorBindingSampledImageUpdateAfterBind) { skip |= val_obj->LogError( val_obj->device, "VUID-VkDescriptorSetLayoutBindingFlagsCreateInfo-" "descriptorBindingSampledImageUpdateAfterBind-03006", "vkCreateDescriptorSetLayout(): pBindings[%u] can't have VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT " "for %s since descriptorBindingSampledImageUpdateAfterBind is not enabled.", i, string_VkDescriptorType(binding_info.descriptorType)); } if (binding_info.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE && !core12_features->descriptorBindingStorageImageUpdateAfterBind) { skip |= val_obj->LogError( val_obj->device, "VUID-VkDescriptorSetLayoutBindingFlagsCreateInfo-" "descriptorBindingStorageImageUpdateAfterBind-03007", "vkCreateDescriptorSetLayout(): pBindings[%u] can't have VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT " "for %s since descriptorBindingStorageImageUpdateAfterBind is not enabled.", i, string_VkDescriptorType(binding_info.descriptorType)); } if (binding_info.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER && !core12_features->descriptorBindingStorageBufferUpdateAfterBind) { skip |= val_obj->LogError( val_obj->device, "VUID-VkDescriptorSetLayoutBindingFlagsCreateInfo-" "descriptorBindingStorageBufferUpdateAfterBind-03008", "vkCreateDescriptorSetLayout(): pBindings[%u] can't have VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT " "for %s since descriptorBindingStorageBufferUpdateAfterBind is not enabled.", i, string_VkDescriptorType(binding_info.descriptorType)); } if (binding_info.descriptorType == VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER && !core12_features->descriptorBindingUniformTexelBufferUpdateAfterBind) { skip |= val_obj->LogError( val_obj->device, "VUID-VkDescriptorSetLayoutBindingFlagsCreateInfo-" "descriptorBindingUniformTexelBufferUpdateAfterBind-03009", "vkCreateDescriptorSetLayout(): pBindings[%u] can't have VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT " "for %s since descriptorBindingUniformTexelBufferUpdateAfterBind is not enabled.", i, string_VkDescriptorType(binding_info.descriptorType)); } if (binding_info.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER && !core12_features->descriptorBindingStorageTexelBufferUpdateAfterBind) { skip |= val_obj->LogError( val_obj->device, "VUID-VkDescriptorSetLayoutBindingFlagsCreateInfo-" "descriptorBindingStorageTexelBufferUpdateAfterBind-03010", "vkCreateDescriptorSetLayout(): pBindings[%u] can't have VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT " "for %s since descriptorBindingStorageTexelBufferUpdateAfterBind is not enabled.", i, string_VkDescriptorType(binding_info.descriptorType)); } if ((binding_info.descriptorType == VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT || binding_info.descriptorType == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC || binding_info.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC)) { skip |= val_obj->LogError(val_obj->device, "VUID-VkDescriptorSetLayoutBindingFlagsCreateInfo-None-03011", "vkCreateDescriptorSetLayout(): pBindings[%u] can't have " "VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT for %s.", i, string_VkDescriptorType(binding_info.descriptorType)); } if (binding_info.descriptorType == VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT && !inline_uniform_block_features->descriptorBindingInlineUniformBlockUpdateAfterBind) { skip |= val_obj->LogError( val_obj->device, "VUID-VkDescriptorSetLayoutBindingFlagsCreateInfo-" "descriptorBindingInlineUniformBlockUpdateAfterBind-02211", "vkCreateDescriptorSetLayout(): pBindings[%u] can't have VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT " "for %s since descriptorBindingInlineUniformBlockUpdateAfterBind is not enabled.", i, string_VkDescriptorType(binding_info.descriptorType)); } } if (flags_create_info->pBindingFlags[i] & VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT) { if (!core12_features->descriptorBindingUpdateUnusedWhilePending) { skip |= val_obj->LogError( val_obj->device, "VUID-VkDescriptorSetLayoutBindingFlagsCreateInfo-descriptorBindingUpdateUnusedWhilePending-03012", "vkCreateDescriptorSetLayout(): pBindings[%u] can't have " "VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT for %s since " "descriptorBindingUpdateUnusedWhilePending is not enabled.", i, string_VkDescriptorType(binding_info.descriptorType)); } } if (flags_create_info->pBindingFlags[i] & VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT) { if (!core12_features->descriptorBindingPartiallyBound) { skip |= val_obj->LogError( val_obj->device, "VUID-VkDescriptorSetLayoutBindingFlagsCreateInfo-descriptorBindingPartiallyBound-03013", "vkCreateDescriptorSetLayout(): pBindings[%u] can't have VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT for " "%s since descriptorBindingPartiallyBound is not enabled.", i, string_VkDescriptorType(binding_info.descriptorType)); } } if (flags_create_info->pBindingFlags[i] & VK_DESCRIPTOR_BINDING_VARIABLE_DESCRIPTOR_COUNT_BIT) { if (binding_info.binding != max_binding) { skip |= val_obj->LogError( val_obj->device, "VUID-VkDescriptorSetLayoutBindingFlagsCreateInfo-pBindingFlags-03004", "vkCreateDescriptorSetLayout(): pBindings[%u] has VK_DESCRIPTOR_BINDING_VARIABLE_DESCRIPTOR_COUNT_BIT " "but %u is the largest value of all the bindings.", i, binding_info.binding); } if (!core12_features->descriptorBindingVariableDescriptorCount) { skip |= val_obj->LogError( val_obj->device, "VUID-VkDescriptorSetLayoutBindingFlagsCreateInfo-descriptorBindingVariableDescriptorCount-03014", "vkCreateDescriptorSetLayout(): pBindings[%u] can't have " "VK_DESCRIPTOR_BINDING_VARIABLE_DESCRIPTOR_COUNT_BIT for %s since " "descriptorBindingVariableDescriptorCount is not enabled.", i, string_VkDescriptorType(binding_info.descriptorType)); } if ((binding_info.descriptorType == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC) || (binding_info.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC)) { skip |= val_obj->LogError(val_obj->device, "VUID-VkDescriptorSetLayoutBindingFlagsCreateInfo-pBindingFlags-03015", "vkCreateDescriptorSetLayout(): pBindings[%u] can't have " "VK_DESCRIPTOR_BINDING_VARIABLE_DESCRIPTOR_COUNT_BIT for %s.", i, string_VkDescriptorType(binding_info.descriptorType)); } } if (push_descriptor_set && (flags_create_info->pBindingFlags[i] & (VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT | VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT | VK_DESCRIPTOR_BINDING_VARIABLE_DESCRIPTOR_COUNT_BIT))) { skip |= val_obj->LogError( val_obj->device, "VUID-VkDescriptorSetLayoutBindingFlagsCreateInfo-flags-03003", "vkCreateDescriptorSetLayout(): pBindings[%u] can't have VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT, " "VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT, or " "VK_DESCRIPTOR_BINDING_VARIABLE_DESCRIPTOR_COUNT_BIT for with " "VK_DESCRIPTOR_SET_LAYOUT_CREATE_PUSH_DESCRIPTOR_BIT_KHR.", i); } } } } if ((push_descriptor_set) && (total_descriptors > max_push_descriptors)) { const char *undefined = push_descriptor_ext ? "" : " -- undefined"; skip |= val_obj->LogError( val_obj->device, "VUID-VkDescriptorSetLayoutCreateInfo-flags-00281", "vkCreateDescriptorSetLayout(): for push descriptor, total descriptor count in layout (%" PRIu64 ") must not be greater than VkPhysicalDevicePushDescriptorPropertiesKHR::maxPushDescriptors (%" PRIu32 "%s).", total_descriptors, max_push_descriptors, undefined); } return skip; } void cvdescriptorset::AllocateDescriptorSetsData::Init(uint32_t count) { layout_nodes.resize(count); } cvdescriptorset::DescriptorSet::DescriptorSet(const VkDescriptorSet set, DESCRIPTOR_POOL_STATE *pool_state, const std::shared_ptr<DescriptorSetLayout const> &layout, uint32_t variable_count, const cvdescriptorset::DescriptorSet::StateTracker *state_data) : BASE_NODE(set, kVulkanObjectTypeDescriptorSet), some_update_(false), pool_state_(pool_state), layout_(layout), state_data_(state_data), variable_count_(variable_count), change_count_(0) { if (pool_state_) { pool_state_->AddParent(this); } // Foreach binding, create default descriptors of given type descriptors_.reserve(layout_->GetTotalDescriptorCount()); descriptor_store_.resize(layout_->GetTotalDescriptorCount()); auto free_descriptor = descriptor_store_.data(); for (uint32_t i = 0; i < layout_->GetBindingCount(); ++i) { auto type = layout_->GetTypeFromIndex(i); switch (type) { case VK_DESCRIPTOR_TYPE_SAMPLER: { auto immut_sampler = layout_->GetImmutableSamplerPtrFromIndex(i); for (uint32_t di = 0; di < layout_->GetDescriptorCountFromIndex(i); ++di) { if (immut_sampler) { descriptors_.emplace_back(new ((free_descriptor++)->Sampler()) SamplerDescriptor(state_data, immut_sampler + di)); some_update_ = true; // Immutable samplers are updated at creation } else { descriptors_.emplace_back(new ((free_descriptor++)->Sampler()) SamplerDescriptor(state_data, nullptr)); } descriptors_.back()->AddParent(this); } break; } case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER: { auto immut = layout_->GetImmutableSamplerPtrFromIndex(i); for (uint32_t di = 0; di < layout_->GetDescriptorCountFromIndex(i); ++di) { if (immut) { descriptors_.emplace_back(new ((free_descriptor++)->ImageSampler()) ImageSamplerDescriptor(state_data, immut + di)); some_update_ = true; // Immutable samplers are updated at creation } else { descriptors_.emplace_back(new ((free_descriptor++)->ImageSampler()) ImageSamplerDescriptor(state_data, nullptr)); } descriptors_.back()->AddParent(this); } break; } // ImageDescriptors case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE: case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT: case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE: for (uint32_t di = 0; di < layout_->GetDescriptorCountFromIndex(i); ++di) { descriptors_.emplace_back(new ((free_descriptor++)->Image()) ImageDescriptor(type)); descriptors_.back()->AddParent(this); } break; case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER: case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER: for (uint32_t di = 0; di < layout_->GetDescriptorCountFromIndex(i); ++di) { descriptors_.emplace_back(new ((free_descriptor++)->Texel()) TexelDescriptor(type)); descriptors_.back()->AddParent(this); } break; case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER: case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER: for (uint32_t di = 0; di < layout_->GetDescriptorCountFromIndex(i); ++di) { descriptors_.emplace_back(new ((free_descriptor++)->Buffer()) BufferDescriptor(type)); descriptors_.back()->AddParent(this); } break; case VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT: for (uint32_t di = 0; di < layout_->GetDescriptorCountFromIndex(i); ++di) { descriptors_.emplace_back(new ((free_descriptor++)->InlineUniform()) InlineUniformDescriptor(type)); descriptors_.back()->AddParent(this); } break; case VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_NV: case VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR: for (uint32_t di = 0; di < layout_->GetDescriptorCountFromIndex(i); ++di) { descriptors_.emplace_back(new ((free_descriptor++)->AccelerationStructure()) AccelerationStructureDescriptor(type)); descriptors_.back()->AddParent(this); } break; case VK_DESCRIPTOR_TYPE_MUTABLE_VALVE: for (uint32_t di = 0; di < layout_->GetDescriptorCountFromIndex(i); ++di) { descriptors_.emplace_back(new ((free_descriptor++)->InlineUniform()) MutableDescriptor()); descriptors_.back()->AddParent(this); } break; default: if (IsDynamicDescriptor(type) && IsBufferDescriptor(type)) { for (uint32_t di = 0; di < layout_->GetDescriptorCountFromIndex(i); ++di) { dynamic_offset_idx_to_descriptor_list_.push_back(descriptors_.size()); descriptors_.emplace_back(new ((free_descriptor++)->Buffer()) BufferDescriptor(type)); descriptors_.back()->AddParent(this); } } else { assert(0); // Bad descriptor type specified } break; } } } void cvdescriptorset::DescriptorSet::Destroy() { if (pool_state_) { pool_state_->RemoveParent(this); } for (auto &desc: descriptors_) { desc->RemoveParent(this); } BASE_NODE::Destroy(); } static std::string StringDescriptorReqViewType(descriptor_req req) { std::string result(""); for (unsigned i = 0; i <= VK_IMAGE_VIEW_TYPE_CUBE_ARRAY; i++) { if (req & (1 << i)) { if (result.size()) result += ", "; result += string_VkImageViewType(VkImageViewType(i)); } } if (!result.size()) result = "(none)"; return result; } static char const *StringDescriptorReqComponentType(descriptor_req req) { if (req & DESCRIPTOR_REQ_COMPONENT_TYPE_SINT) return "SINT"; if (req & DESCRIPTOR_REQ_COMPONENT_TYPE_UINT) return "UINT"; if (req & DESCRIPTOR_REQ_COMPONENT_TYPE_FLOAT) return "FLOAT"; return "(none)"; } unsigned DescriptorRequirementsBitsFromFormat(VkFormat fmt) { if (FormatIsSInt(fmt)) return DESCRIPTOR_REQ_COMPONENT_TYPE_SINT; if (FormatIsUInt(fmt)) return DESCRIPTOR_REQ_COMPONENT_TYPE_UINT; if (FormatIsDepthAndStencil(fmt)) return DESCRIPTOR_REQ_COMPONENT_TYPE_FLOAT | DESCRIPTOR_REQ_COMPONENT_TYPE_UINT; if (fmt == VK_FORMAT_UNDEFINED) return 0; // everything else -- UNORM/SNORM/FLOAT/USCALED/SSCALED is all float in the shader. return DESCRIPTOR_REQ_COMPONENT_TYPE_FLOAT; } // Validate that the state of this set is appropriate for the given bindings and dynamic_offsets at Draw time // This includes validating that all descriptors in the given bindings are updated, // that any update buffers are valid, and that any dynamic offsets are within the bounds of their buffers. // Return true if state is acceptable, or false and write an error message into error string bool CoreChecks::ValidateDrawState(const DescriptorSet *descriptor_set, const BindingReqMap &bindings, const std::vector<uint32_t> &dynamic_offsets, const CMD_BUFFER_STATE *cb_node, const std::vector<IMAGE_VIEW_STATE *> *attachments, const std::vector<SUBPASS_INFO> *subpasses, const char *caller, const DrawDispatchVuid &vuids) const { layer_data::optional<layer_data::unordered_map<VkImageView, VkImageLayout>> checked_layouts; if (descriptor_set->GetTotalDescriptorCount() > cvdescriptorset::PrefilterBindRequestMap::kManyDescriptors_) { checked_layouts.emplace(); } bool result = false; VkFramebuffer framebuffer = cb_node->activeFramebuffer ? cb_node->activeFramebuffer->framebuffer() : VK_NULL_HANDLE; for (const auto &binding_pair : bindings) { const auto binding = binding_pair.first; DescriptorSetLayout::ConstBindingIterator binding_it(descriptor_set->GetLayout().get(), binding); if (binding_it.AtEnd()) { // End at construction is the condition for an invalid binding. auto set = descriptor_set->GetSet(); result |= LogError(set, vuids.descriptor_valid, "%s encountered the following validation error at %s time: Attempting to " "validate DrawState for binding #%u which is an invalid binding for this descriptor set.", report_data->FormatHandle(set).c_str(), caller, binding); return result; } if (binding_it.GetDescriptorBindingFlags() & (VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT | VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT)) { // Can't validate the descriptor because it may not have been updated, // or the view could have been destroyed continue; } // // This is a record time only path const bool record_time_validate = true; result |= ValidateDescriptorSetBindingData(cb_node, descriptor_set, dynamic_offsets, binding_pair, framebuffer, attachments, subpasses, record_time_validate, caller, vuids, checked_layouts); } return result; } bool CoreChecks::ValidateDescriptorSetBindingData(const CMD_BUFFER_STATE *cb_node, const DescriptorSet *descriptor_set, const std::vector<uint32_t> &dynamic_offsets, const std::pair<const uint32_t, DescriptorRequirement> &binding_info, VkFramebuffer framebuffer, const std::vector<IMAGE_VIEW_STATE *> *attachments, const std::vector<SUBPASS_INFO> *subpasses, bool record_time_validate, const char *caller, const DrawDispatchVuid &vuids, layer_data::optional<layer_data::unordered_map<VkImageView, VkImageLayout>> &checked_layouts) const { using DescriptorClass = cvdescriptorset::DescriptorClass; using BufferDescriptor = cvdescriptorset::BufferDescriptor; using ImageDescriptor = cvdescriptorset::ImageDescriptor; using ImageSamplerDescriptor = cvdescriptorset::ImageSamplerDescriptor; using SamplerDescriptor = cvdescriptorset::SamplerDescriptor; using TexelDescriptor = cvdescriptorset::TexelDescriptor; using AccelerationStructureDescriptor = cvdescriptorset::AccelerationStructureDescriptor; const auto binding = binding_info.first; bool skip = false; DescriptorSetLayout::ConstBindingIterator binding_it(descriptor_set->GetLayout().get(), binding); { // Copy the range, the end range is subject to update based on variable length descriptor arrays. cvdescriptorset::IndexRange index_range = binding_it.GetGlobalIndexRange(); auto array_idx = 0; // Track array idx if we're dealing with array descriptors if (binding_it.IsVariableDescriptorCount()) { // Only validate the first N descriptors if it uses variable_count index_range.end = index_range.start + descriptor_set->GetVariableDescriptorCount(); } for (uint32_t i = index_range.start; !skip && i < index_range.end; ++i, ++array_idx) { uint32_t index = i - index_range.start; const auto *descriptor = descriptor_set->GetDescriptorFromGlobalIndex(i); const auto descriptor_class = descriptor->GetClass(); if (descriptor_class == DescriptorClass::InlineUniform) { // Can't validate the descriptor because it may not have been updated. continue; } else if (!descriptor->updated) { auto set = descriptor_set->GetSet(); return LogError( set, vuids.descriptor_valid, "Descriptor set %s encountered the following validation error at %s time: Descriptor in binding #%" PRIu32 " index %" PRIu32 " is being used in draw but has never been updated via vkUpdateDescriptorSets() or a similar call.", report_data->FormatHandle(set).c_str(), caller, binding, index); } switch (descriptor_class) { case DescriptorClass::GeneralBuffer: { const auto *buffer_desc = static_cast<const BufferDescriptor *>(descriptor); skip = ValidateGeneralBufferDescriptor(caller, vuids, cb_node, descriptor_set, *buffer_desc, binding_info, index); } break; case DescriptorClass::ImageSampler: { const auto *image_sampler_desc = static_cast<const ImageSamplerDescriptor *>(descriptor); skip = ValidateImageDescriptor(caller, vuids, cb_node, descriptor_set, *image_sampler_desc, binding_info, index, record_time_validate, attachments, subpasses, framebuffer, binding_it.GetType(), checked_layouts); if (!skip) { skip = ValidateSamplerDescriptor(caller, vuids, cb_node, descriptor_set, binding_info, index, image_sampler_desc->GetSampler(), image_sampler_desc->IsImmutableSampler(), image_sampler_desc->GetSamplerState()); } } break; case DescriptorClass::Image: { const auto *image_desc = static_cast<const ImageDescriptor *>(descriptor); skip = ValidateImageDescriptor(caller, vuids, cb_node, descriptor_set, *image_desc, binding_info, index, record_time_validate, attachments, subpasses, framebuffer, binding_it.GetType(), checked_layouts); } break; case DescriptorClass::PlainSampler: { const auto *sampler_desc = static_cast<const SamplerDescriptor *>(descriptor); skip = ValidateSamplerDescriptor(caller, vuids, cb_node, descriptor_set, binding_info, index, sampler_desc->GetSampler(), sampler_desc->IsImmutableSampler(), sampler_desc->GetSamplerState()); } break; case DescriptorClass::TexelBuffer: { const auto *texel_desc = static_cast<const TexelDescriptor *>(descriptor); skip = ValidateTexelDescriptor(caller, vuids, cb_node, descriptor_set, *texel_desc, binding_info, index); } break; case DescriptorClass::AccelerationStructure: { const auto *accel_desc = static_cast<const AccelerationStructureDescriptor *>(descriptor); skip = ValidateAccelerationDescriptor(caller, vuids, cb_node, descriptor_set, *accel_desc, binding_info, index); } break; default: break; } } } return skip; } bool CoreChecks::ValidateGeneralBufferDescriptor(const char *caller, const DrawDispatchVuid &vuids, const CMD_BUFFER_STATE *cb_node, const cvdescriptorset::DescriptorSet *descriptor_set, const cvdescriptorset::BufferDescriptor &descriptor, const std::pair<const uint32_t, DescriptorRequirement> &binding_info, uint32_t index) const { // Verify that buffers are valid auto buffer = descriptor.GetBuffer(); auto buffer_node = descriptor.GetBufferState(); if ((!buffer_node && !enabled_features.robustness2_features.nullDescriptor) || (buffer_node && buffer_node->Destroyed())) { auto set = descriptor_set->GetSet(); return LogError(set, vuids.descriptor_valid, "Descriptor set %s encountered the following validation error at %s time: Descriptor in " "binding #%" PRIu32 " index %" PRIu32 " is using buffer %s that is invalid or has been destroyed.", report_data->FormatHandle(set).c_str(), caller, binding_info.first, index, report_data->FormatHandle(buffer).c_str()); } if (buffer) { if (buffer_node && !buffer_node->sparse) { for (const auto &item: buffer_node->GetBoundMemory()) { auto &binding = item.second; if (binding.mem_state->Destroyed()) { auto set = descriptor_set->GetSet(); return LogError(set, vuids.descriptor_valid, "Descriptor set %s encountered the following validation error at %s time: Descriptor in " "binding #%" PRIu32 " index %" PRIu32 " is uses buffer %s that references invalid memory %s.", report_data->FormatHandle(set).c_str(), caller, binding_info.first, index, report_data->FormatHandle(buffer).c_str(), report_data->FormatHandle(binding.mem_state->mem()).c_str()); } } } if (enabled_features.core11.protectedMemory == VK_TRUE) { if (ValidateProtectedBuffer(cb_node, buffer_node, caller, vuids.unprotected_command_buffer, "Buffer is in a descriptorSet")) { return true; } if (binding_info.second.is_writable && ValidateUnprotectedBuffer(cb_node, buffer_node, caller, vuids.protected_command_buffer, "Buffer is in a descriptorSet")) { return true; } } } return false; } bool CoreChecks::ValidateImageDescriptor(const char *caller, const DrawDispatchVuid &vuids, const CMD_BUFFER_STATE *cb_node, const cvdescriptorset::DescriptorSet *descriptor_set, const cvdescriptorset::ImageDescriptor &image_descriptor, const std::pair<const uint32_t, DescriptorRequirement> &binding_info, uint32_t index, bool record_time_validate, const std::vector<IMAGE_VIEW_STATE *> *attachments, const std::vector<SUBPASS_INFO> *subpasses, VkFramebuffer framebuffer, VkDescriptorType descriptor_type, layer_data::optional<layer_data::unordered_map<VkImageView, VkImageLayout>> &checked_layouts) const { std::vector<const SAMPLER_STATE *> sampler_states; VkImageView image_view = image_descriptor.GetImageView(); const IMAGE_VIEW_STATE *image_view_state = image_descriptor.GetImageViewState(); VkImageLayout image_layout = image_descriptor.GetImageLayout(); const auto binding = binding_info.first; const auto reqs = binding_info.second.reqs; if (image_descriptor.GetClass() == cvdescriptorset::DescriptorClass::ImageSampler) { sampler_states.emplace_back( static_cast<const cvdescriptorset::ImageSamplerDescriptor &>(image_descriptor).GetSamplerState()); } else { if (binding_info.second.samplers_used_by_image.size() > index) { for (auto &sampler : binding_info.second.samplers_used_by_image[index]) { // NOTE: This check _shouldn't_ be necessary due to the checks made in IsSpecificDescriptorType in // shader_validation.cpp. However, without this check some traces still crash. if (sampler.second && (sampler.second->GetClass() == cvdescriptorset::DescriptorClass::PlainSampler)) { const auto *sampler_state = static_cast<const cvdescriptorset::SamplerDescriptor *>(sampler.second)->GetSamplerState(); if (sampler_state) sampler_states.emplace_back(sampler_state); } } } } if ((!image_view_state && !enabled_features.robustness2_features.nullDescriptor) || (image_view_state && image_view_state->Destroyed())) { // Image view must have been destroyed since initial update. Could potentially flag the descriptor // as "invalid" (updated = false) at DestroyImageView() time and detect this error at bind time auto set = descriptor_set->GetSet(); return LogError(set, vuids.descriptor_valid, "Descriptor set %s encountered the following validation error at %s time: Descriptor in " "binding #%" PRIu32 " index %" PRIu32 " is using imageView %s that is invalid or has been destroyed.", report_data->FormatHandle(set).c_str(), caller, binding, index, report_data->FormatHandle(image_view).c_str()); } if (image_view) { const auto &image_view_ci = image_view_state->create_info; const auto *image_state = image_view_state->image_state.get(); if (reqs & DESCRIPTOR_REQ_ALL_VIEW_TYPE_BITS) { if (~reqs & (1 << image_view_ci.viewType)) { auto set = descriptor_set->GetSet(); return LogError(set, vuids.descriptor_valid, "Descriptor set %s encountered the following validation error at %s time: Descriptor " "in binding #%" PRIu32 " index %" PRIu32 " requires an image view of type %s but got %s.", report_data->FormatHandle(set).c_str(), caller, binding, index, StringDescriptorReqViewType(reqs).c_str(), string_VkImageViewType(image_view_ci.viewType)); } if (!(reqs & image_view_state->descriptor_format_bits)) { // bad component type auto set = descriptor_set->GetSet(); return LogError(set, vuids.descriptor_valid, "Descriptor set %s encountered the following validation error at %s time: " "Descriptor in binding " "#%" PRIu32 " index %" PRIu32 " requires %s component type, but bound descriptor format is %s.", report_data->FormatHandle(set).c_str(), caller, binding, index, StringDescriptorReqComponentType(reqs), string_VkFormat(image_view_ci.format)); } } // NOTE: Submit time validation of UPDATE_AFTER_BIND image layout is not possible with the // image layout tracking as currently implemented, so only record_time_validation is done if (!disabled[image_layout_validation] && record_time_validate) { // Verify Image Layout // No "invalid layout" VUID required for this call, since the optimal_layout parameter is UNDEFINED. // The caller provides a checked_layouts map when there are a large number of layouts to check, // making it worthwhile to keep track of verified layouts and not recheck them. bool already_validated = false; if (checked_layouts) { auto search = checked_layouts->find(image_view); if (search != checked_layouts->end() && search->second == image_layout) { already_validated = true; } } if (!already_validated) { bool hit_error = false; VerifyImageLayout(cb_node, image_state, image_view_state->normalized_subresource_range, image_view_ci.subresourceRange.aspectMask, image_layout, VK_IMAGE_LAYOUT_UNDEFINED, caller, kVUIDUndefined, "VUID-VkDescriptorImageInfo-imageLayout-00344", &hit_error); if (hit_error) { auto set = descriptor_set->GetSet(); return LogError(set, vuids.descriptor_valid, "Descriptor set %s encountered the following validation error at %s time: Image layout " "specified " "at vkUpdateDescriptorSet* or vkCmdPushDescriptorSet* time " "doesn't match actual image layout at time descriptor is used. See previous error callback for " "specific details.", report_data->FormatHandle(set).c_str(), caller); } if (checked_layouts) { checked_layouts->emplace(image_view, image_layout); } } } // Verify Sample counts if ((reqs & DESCRIPTOR_REQ_SINGLE_SAMPLE) && image_view_state->samples != VK_SAMPLE_COUNT_1_BIT) { auto set = descriptor_set->GetSet(); return LogError(set, vuids.descriptor_valid, "Descriptor set %s encountered the following validation error at %s time: Descriptor in " "binding #%" PRIu32 " index %" PRIu32 " requires bound image to have VK_SAMPLE_COUNT_1_BIT but got %s.", report_data->FormatHandle(set).c_str(), caller, binding, index, string_VkSampleCountFlagBits(image_view_state->samples)); } if ((reqs & DESCRIPTOR_REQ_MULTI_SAMPLE) && image_view_state->samples == VK_SAMPLE_COUNT_1_BIT) { auto set = descriptor_set->GetSet(); return LogError(set, vuids.descriptor_valid, "Descriptor set %s encountered the following validation error at %s time: Descriptor " "in binding #%" PRIu32 " index %" PRIu32 " requires bound image to have multiple samples, but got VK_SAMPLE_COUNT_1_BIT.", report_data->FormatHandle(set).c_str(), caller, binding, index); } // Verify VK_FORMAT_FEATURE_STORAGE_IMAGE_ATOMIC_BIT if ((reqs & DESCRIPTOR_REQ_VIEW_ATOMIC_OPERATION) && (descriptor_type == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE) && !(image_view_state->format_features & VK_FORMAT_FEATURE_STORAGE_IMAGE_ATOMIC_BIT)) { auto set = descriptor_set->GetSet(); LogObjectList objlist(set); objlist.add(image_view); return LogError(objlist, vuids.imageview_atomic, "Descriptor set %s encountered the following validation error at %s time: Descriptor " "in binding #%" PRIu32 " index %" PRIu32 ", %s, format %s, doesn't " "contain VK_FORMAT_FEATURE_STORAGE_IMAGE_ATOMIC_BIT.", report_data->FormatHandle(set).c_str(), caller, binding, index, report_data->FormatHandle(image_view).c_str(), string_VkFormat(image_view_ci.format)); } // Verify if attachments are used in DescriptorSet if (attachments && attachments->size() > 0 && subpasses && (descriptor_type != VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT)) { bool ds_aspect = (image_view_state->normalized_subresource_range.aspectMask & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) ? true : false; uint32_t att_index = 0; for (const auto &view_state : *attachments) { const SUBPASS_INFO& subpass = (*subpasses)[att_index]; if (!subpass.used || !view_state || view_state->Destroyed()) { continue; } if (ds_aspect && subpass.usage == VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) { if ((image_layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL || image_layout == VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_OPTIMAL || image_layout == VK_IMAGE_LAYOUT_STENCIL_READ_ONLY_OPTIMAL) && (subpass.layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL || subpass.layout == VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_OPTIMAL || subpass.layout == VK_IMAGE_LAYOUT_STENCIL_READ_ONLY_OPTIMAL)) { continue; } if ((image_layout == VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL && subpass.layout == VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL) || (subpass.layout == VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL && image_layout == VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL)) { continue; } } if (view_state->image_view() == image_view) { auto set = descriptor_set->GetSet(); LogObjectList objlist(set); objlist.add(image_view); objlist.add(framebuffer); return LogError(objlist, vuids.image_subresources, "Descriptor set %s encountered the following validation error at %s time: %s is used in " "Descriptor in binding #%" PRIu32 " index %" PRIu32 " and %s attachment # %" PRIu32 ".", report_data->FormatHandle(set).c_str(), caller, report_data->FormatHandle(image_view).c_str(), binding, index, report_data->FormatHandle(framebuffer).c_str(), att_index); } else { if (image_view_state->OverlapSubresource(*view_state)) { auto set = descriptor_set->GetSet(); LogObjectList objlist(set); objlist.add(image_view); objlist.add(framebuffer); objlist.add(view_state->image_view()); return LogError( objlist, vuids.image_subresources, "Descriptor set %s encountered the following validation error at %s time: " "Image subresources of %s in " "Descriptor in binding #%" PRIu32 " index %" PRIu32 " and %s in %s attachment # %" PRIu32 " overlap.", report_data->FormatHandle(set).c_str(), caller, report_data->FormatHandle(image_view).c_str(), binding, index, report_data->FormatHandle(view_state->image_view()).c_str(), report_data->FormatHandle(framebuffer).c_str(), att_index); } } ++att_index; } if (enabled_features.core11.protectedMemory == VK_TRUE) { if (ValidateProtectedImage(cb_node, image_view_state->image_state.get(), caller, vuids.unprotected_command_buffer, "Image is in a descriptorSet")) { return true; } if (binding_info.second.is_writable && ValidateUnprotectedImage(cb_node, image_view_state->image_state.get(), caller, vuids.protected_command_buffer, "Image is in a descriptorSet")) { return true; } } } for (const auto *sampler_state : sampler_states) { if (!sampler_state || sampler_state->Destroyed()) { continue; } // TODO: Validate 04015 for DescriptorClass::PlainSampler if ((sampler_state->createInfo.borderColor == VK_BORDER_COLOR_INT_CUSTOM_EXT || sampler_state->createInfo.borderColor == VK_BORDER_COLOR_FLOAT_CUSTOM_EXT) && (sampler_state->customCreateInfo.format == VK_FORMAT_UNDEFINED)) { if (image_view_state->create_info.format == VK_FORMAT_B4G4R4A4_UNORM_PACK16 || image_view_state->create_info.format == VK_FORMAT_B5G6R5_UNORM_PACK16 || image_view_state->create_info.format == VK_FORMAT_B5G5R5A1_UNORM_PACK16) { auto set = descriptor_set->GetSet(); LogObjectList objlist(set); objlist.add(sampler_state->sampler()); objlist.add(image_view_state->image_view()); return LogError(objlist, "VUID-VkSamplerCustomBorderColorCreateInfoEXT-format-04015", "Descriptor set %s encountered the following validation error at %s time: Sampler %s in " "binding #%" PRIu32 " index %" PRIu32 " has a custom border color with format = VK_FORMAT_UNDEFINED and is used to " "sample an image view %s with format %s", report_data->FormatHandle(set).c_str(), caller, report_data->FormatHandle(sampler_state->sampler()).c_str(), binding, index, report_data->FormatHandle(image_view_state->image_view()).c_str(), string_VkFormat(image_view_state->create_info.format)); } } VkFilter sampler_mag_filter = sampler_state->createInfo.magFilter; VkFilter sampler_min_filter = sampler_state->createInfo.minFilter; VkBool32 sampler_compare_enable = sampler_state->createInfo.compareEnable; if ((sampler_mag_filter == VK_FILTER_LINEAR || sampler_min_filter == VK_FILTER_LINEAR) && (sampler_compare_enable == VK_FALSE) && !(image_view_state->format_features & VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT)) { auto set = descriptor_set->GetSet(); LogObjectList objlist(set); objlist.add(sampler_state->sampler()); objlist.add(image_view_state->image_view()); return LogError(objlist, vuids.linear_sampler, "Descriptor set %s encountered the following validation error at %s time: Sampler " "(%s) is set to use VK_FILTER_LINEAR with " "compareEnable is set to VK_TRUE, but image view's (%s) format (%s) does not " "contain VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT in its format features.", report_data->FormatHandle(set).c_str(), caller, report_data->FormatHandle(sampler_state->sampler()).c_str(), report_data->FormatHandle(image_view_state->image_view()).c_str(), string_VkFormat(image_view_state->create_info.format)); } if (sampler_mag_filter == VK_FILTER_CUBIC_EXT || sampler_min_filter == VK_FILTER_CUBIC_EXT) { if (!(image_view_state->format_features & VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_CUBIC_BIT_EXT)) { auto set = descriptor_set->GetSet(); LogObjectList objlist(set); objlist.add(sampler_state->sampler()); objlist.add(image_view_state->image_view()); return LogError(objlist, vuids.cubic_sampler, "Descriptor set %s encountered the following validation error at %s time: " "Sampler (%s) is set to use VK_FILTER_CUBIC_EXT, then " "image view's (%s) format (%s) MUST contain " "VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_CUBIC_BIT_EXT in its format features.", report_data->FormatHandle(set).c_str(), caller, report_data->FormatHandle(sampler_state->sampler()).c_str(), report_data->FormatHandle(image_view_state->image_view()).c_str(), string_VkFormat(image_view_state->create_info.format)); } if (IsExtEnabled(device_extensions.vk_ext_filter_cubic)) { const auto reduction_mode_info = LvlFindInChain<VkSamplerReductionModeCreateInfo>(sampler_state->createInfo.pNext); if (reduction_mode_info && (reduction_mode_info->reductionMode == VK_SAMPLER_REDUCTION_MODE_MIN || reduction_mode_info->reductionMode == VK_SAMPLER_REDUCTION_MODE_MAX) && !image_view_state->filter_cubic_props.filterCubicMinmax) { auto set = descriptor_set->GetSet(); LogObjectList objlist(set); objlist.add(sampler_state->sampler()); objlist.add(image_view_state->image_view()); return LogError(objlist, vuids.filter_cubic_min_max, "Descriptor set %s encountered the following validation error at %s time: " "Sampler (%s) is set to use VK_FILTER_CUBIC_EXT & %s, " "but image view (%s) doesn't support filterCubicMinmax.", report_data->FormatHandle(set).c_str(), caller, report_data->FormatHandle(sampler_state->sampler()).c_str(), string_VkSamplerReductionMode(reduction_mode_info->reductionMode), report_data->FormatHandle(image_view_state->image_view()).c_str()); } if (!image_view_state->filter_cubic_props.filterCubic) { auto set = descriptor_set->GetSet(); LogObjectList objlist(set); objlist.add(sampler_state->sampler()); objlist.add(image_view_state->image_view()); return LogError(objlist, vuids.filter_cubic, "Descriptor set %s encountered the following validation error at %s time: " "Sampler (%s) is set to use VK_FILTER_CUBIC_EXT, " "but image view (%s) doesn't support filterCubic.", report_data->FormatHandle(set).c_str(), caller, report_data->FormatHandle(sampler_state->sampler()).c_str(), report_data->FormatHandle(image_view_state->image_view()).c_str()); } } if (IsExtEnabled(device_extensions.vk_img_filter_cubic)) { if (image_view_state->create_info.viewType & (VK_IMAGE_VIEW_TYPE_3D | VK_IMAGE_VIEW_TYPE_CUBE | VK_IMAGE_VIEW_TYPE_CUBE_ARRAY)) { auto set = descriptor_set->GetSet(); LogObjectList objlist(set); objlist.add(sampler_state->sampler()); objlist.add(image_view_state->image_view()); return LogError(objlist, vuids.img_filter_cubic, "Descriptor set %s encountered the following validation error at %s time: Sampler " "(%s)is set to use VK_FILTER_CUBIC_EXT while the VK_IMG_filter_cubic extension " "is enabled, but image view (%s) has an invalid imageViewType (%s).", report_data->FormatHandle(set).c_str(), caller, report_data->FormatHandle(sampler_state->sampler()).c_str(), report_data->FormatHandle(image_view_state->image_view()).c_str(), string_VkImageViewType(image_view_state->create_info.viewType)); } } } if ((image_state->createInfo.flags & VK_IMAGE_CREATE_CORNER_SAMPLED_BIT_NV) && (sampler_state->createInfo.addressModeU != VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE || sampler_state->createInfo.addressModeV != VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE || sampler_state->createInfo.addressModeW != VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE)) { std::string address_mode_letter = (sampler_state->createInfo.addressModeU != VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE) ? "U" : (sampler_state->createInfo.addressModeV != VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE) ? "V" : "W"; VkSamplerAddressMode address_mode = (sampler_state->createInfo.addressModeU != VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE) ? sampler_state->createInfo.addressModeU : (sampler_state->createInfo.addressModeV != VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE) ? sampler_state->createInfo.addressModeV : sampler_state->createInfo.addressModeW; auto set = descriptor_set->GetSet(); LogObjectList objlist(set); objlist.add(sampler_state->sampler()); objlist.add(image_state->image()); objlist.add(image_view_state->image_view()); return LogError(objlist, vuids.corner_sampled_address_mode, "Descriptor set %s encountered the following validation error at %s time: Image " "(%s) in image view (%s) is created with flag " "VK_IMAGE_CREATE_CORNER_SAMPLED_BIT_NV and can only be sampled using " "VK_SAMPLER_ADDRESS_MODE_CLAMP_EDGE, but sampler (%s) has " "createInfo.addressMode%s set to %s.", report_data->FormatHandle(set).c_str(), caller, report_data->FormatHandle(image_state->image()).c_str(), report_data->FormatHandle(image_view_state->image_view()).c_str(), report_data->FormatHandle(sampler_state->sampler()).c_str(), address_mode_letter.c_str(), string_VkSamplerAddressMode(address_mode)); } // UnnormalizedCoordinates sampler validations if (sampler_state->createInfo.unnormalizedCoordinates) { // If ImageView is used by a unnormalizedCoordinates sampler, it needs to check ImageView type if (image_view_ci.viewType == VK_IMAGE_VIEW_TYPE_3D || image_view_ci.viewType == VK_IMAGE_VIEW_TYPE_CUBE || image_view_ci.viewType == VK_IMAGE_VIEW_TYPE_1D_ARRAY || image_view_ci.viewType == VK_IMAGE_VIEW_TYPE_2D_ARRAY || image_view_ci.viewType == VK_IMAGE_VIEW_TYPE_CUBE_ARRAY) { auto set = descriptor_set->GetSet(); LogObjectList objlist(set); objlist.add(image_view); objlist.add(sampler_state->sampler()); return LogError(objlist, vuids.sampler_imageview_type, "Descriptor set %s encountered the following validation error at %s time: %s, type: %s in " "Descriptor in binding #%" PRIu32 " index %" PRIu32 "is used by %s.", report_data->FormatHandle(set).c_str(), caller, report_data->FormatHandle(image_view).c_str(), string_VkImageViewType(image_view_ci.viewType), binding, index, report_data->FormatHandle(sampler_state->sampler()).c_str()); } // sampler must not be used with any of the SPIR-V OpImageSample* or OpImageSparseSample* // instructions with ImplicitLod, Dref or Proj in their name if (reqs & DESCRIPTOR_REQ_SAMPLER_IMPLICITLOD_DREF_PROJ) { auto set = descriptor_set->GetSet(); LogObjectList objlist(set); objlist.add(image_view); objlist.add(sampler_state->sampler()); return LogError(objlist, vuids.sampler_implicitLod_dref_proj, "Descriptor set %s encountered the following validation error at %s time: %s in " "Descriptor in binding #%" PRIu32 " index %" PRIu32 " is used by %s that uses invalid operator.", report_data->FormatHandle(set).c_str(), caller, report_data->FormatHandle(image_view).c_str(), binding, index, report_data->FormatHandle(sampler_state->sampler()).c_str()); } // sampler must not be used with any of the SPIR-V OpImageSample* or OpImageSparseSample* // instructions that includes a LOD bias or any offset values if (reqs & DESCRIPTOR_REQ_SAMPLER_BIAS_OFFSET) { auto set = descriptor_set->GetSet(); LogObjectList objlist(set); objlist.add(image_view); objlist.add(sampler_state->sampler()); return LogError(objlist, vuids.sampler_bias_offset, "Descriptor set %s encountered the following validation error at %s time: %s in " "Descriptor in binding #%" PRIu32 " index %" PRIu32 " is used by %s that uses invalid bias or offset operator.", report_data->FormatHandle(set).c_str(), caller, report_data->FormatHandle(image_view).c_str(), binding, index, report_data->FormatHandle(sampler_state->sampler()).c_str()); } } } } return false; } bool CoreChecks::ValidateTexelDescriptor(const char *caller, const DrawDispatchVuid &vuids, const CMD_BUFFER_STATE *cb_node, const cvdescriptorset::DescriptorSet *descriptor_set, const cvdescriptorset::TexelDescriptor &texel_descriptor, const std::pair<const uint32_t, DescriptorRequirement> &binding_info, uint32_t index) const { auto buffer_view = texel_descriptor.GetBufferView(); auto buffer_view_state = texel_descriptor.GetBufferViewState(); const auto binding = binding_info.first; const auto reqs = binding_info.second.reqs; if ((!buffer_view_state && !enabled_features.robustness2_features.nullDescriptor) || (buffer_view_state && buffer_view_state->Destroyed())) { auto set = descriptor_set->GetSet(); return LogError(set, vuids.descriptor_valid, "Descriptor set %s encountered the following validation error at %s time: Descriptor in " "binding #%" PRIu32 " index %" PRIu32 " is using bufferView %s that is invalid or has been destroyed.", report_data->FormatHandle(set).c_str(), caller, binding, index, report_data->FormatHandle(buffer_view).c_str()); } if (buffer_view) { auto buffer = buffer_view_state->create_info.buffer; auto buffer_state = buffer_view_state->buffer_state.get(); if (buffer_state->Destroyed()) { auto set = descriptor_set->GetSet(); return LogError(set, vuids.descriptor_valid, "Descriptor set %s encountered the following validation error at %s time: Descriptor in " "binding #%" PRIu32 " index %" PRIu32 " is using buffer %s that has been destroyed.", report_data->FormatHandle(set).c_str(), caller, binding, index, report_data->FormatHandle(buffer).c_str()); } auto format_bits = DescriptorRequirementsBitsFromFormat(buffer_view_state->create_info.format); if (!(reqs & format_bits)) { // bad component type auto set = descriptor_set->GetSet(); return LogError(set, vuids.descriptor_valid, "Descriptor set %s encountered the following validation error at %s time: Descriptor in " "binding #%" PRIu32 " index %" PRIu32 " requires %s component type, but bound descriptor format is %s.", report_data->FormatHandle(set).c_str(), caller, binding, index, StringDescriptorReqComponentType(reqs), string_VkFormat(buffer_view_state->create_info.format)); } // Verify VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_ATOMIC_BIT if ((reqs & DESCRIPTOR_REQ_VIEW_ATOMIC_OPERATION) && (descriptor_set->GetTypeFromBinding(binding) == VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER) && !(buffer_view_state->format_features & VK_FORMAT_FEATURE_STORAGE_TEXEL_BUFFER_ATOMIC_BIT)) { auto set = descriptor_set->GetSet(); LogObjectList objlist(set); objlist.add(buffer_view); return LogError(objlist, "UNASSIGNED-None-MismatchAtomicBufferFeature", "Descriptor set %s encountered the following validation error at %s time: Descriptor " "in binding #%" PRIu32 " index %" PRIu32 ", %s, format %s, doesn't " "contain VK_FORMAT_FEATURE_STORAGE_IMAGE_ATOMIC_BIT.", report_data->FormatHandle(set).c_str(), caller, binding, index, report_data->FormatHandle(buffer_view).c_str(), string_VkFormat(buffer_view_state->create_info.format)); } if (enabled_features.core11.protectedMemory == VK_TRUE) { if (ValidateProtectedBuffer(cb_node, buffer_view_state->buffer_state.get(), caller, vuids.unprotected_command_buffer, "Buffer is in a descriptorSet")) { return true; } if (binding_info.second.is_writable && ValidateUnprotectedBuffer(cb_node, buffer_view_state->buffer_state.get(), caller, vuids.protected_command_buffer, "Buffer is in a descriptorSet")) { return true; } } } return false; } bool CoreChecks::ValidateAccelerationDescriptor(const char *caller, const DrawDispatchVuid &vuids, const CMD_BUFFER_STATE *cb_node, const cvdescriptorset::DescriptorSet *descriptor_set, const cvdescriptorset::AccelerationStructureDescriptor &descriptor, const std::pair<const uint32_t, DescriptorRequirement> &binding_info, uint32_t index) const { // Verify that acceleration structures are valid const auto binding = binding_info.first; if (descriptor.is_khr()) { auto acc = descriptor.GetAccelerationStructure(); auto acc_node = descriptor.GetAccelerationStructureStateKHR(); if (!acc_node || acc_node->Destroyed()) { if (acc != VK_NULL_HANDLE || !enabled_features.robustness2_features.nullDescriptor) { auto set = descriptor_set->GetSet(); return LogError(set, vuids.descriptor_valid, "Descriptor set %s encountered the following validation error at %s time: " "Descriptor in binding #%" PRIu32 " index %" PRIu32 " is using acceleration structure %s that is invalid or has been destroyed.", report_data->FormatHandle(set).c_str(), caller, binding, index, report_data->FormatHandle(acc).c_str()); } } else { for (const auto &item: acc_node->GetBoundMemory()) { auto &mem_binding = item.second; if (mem_binding.mem_state->Destroyed()) { auto set = descriptor_set->GetSet(); return LogError(set, vuids.descriptor_valid, "Descriptor set %s encountered the following validation error at %s time: Descriptor in " "binding #%" PRIu32 " index %" PRIu32 " is using acceleration structure %s that references invalid memory %s.", report_data->FormatHandle(set).c_str(), caller, binding, index, report_data->FormatHandle(acc).c_str(), report_data->FormatHandle(mem_binding.mem_state->mem()).c_str()); } } } } else { auto acc = descriptor.GetAccelerationStructureNV(); auto acc_node = descriptor.GetAccelerationStructureStateNV(); if (!acc_node || acc_node->Destroyed()) { if (acc != VK_NULL_HANDLE || !enabled_features.robustness2_features.nullDescriptor) { auto set = descriptor_set->GetSet(); return LogError(set, vuids.descriptor_valid, "Descriptor set %s encountered the following validation error at %s time: " "Descriptor in binding #%" PRIu32 " index %" PRIu32 " is using acceleration structure %s that is invalid or has been destroyed.", report_data->FormatHandle(set).c_str(), caller, binding, index, report_data->FormatHandle(acc).c_str()); } } else { for (const auto &item : acc_node->GetBoundMemory()) { auto &mem_binding = item.second; if (mem_binding.mem_state->Destroyed()) { auto set = descriptor_set->GetSet(); return LogError(set, vuids.descriptor_valid, "Descriptor set %s encountered the following validation error at %s time: Descriptor in " "binding #%" PRIu32 " index %" PRIu32 " is using acceleration structure %s that references invalid memory %s.", report_data->FormatHandle(set).c_str(), caller, binding, index, report_data->FormatHandle(acc).c_str(), report_data->FormatHandle(mem_binding.mem_state->mem()).c_str()); } } } } return false; } // If the validation is related to both of image and sampler, // please leave it in (descriptor_class == DescriptorClass::ImageSampler || descriptor_class == // DescriptorClass::Image) Here is to validate for only sampler. bool CoreChecks::ValidateSamplerDescriptor(const char *caller, const DrawDispatchVuid &vuids, const CMD_BUFFER_STATE *cb_node, const cvdescriptorset::DescriptorSet *descriptor_set, const std::pair<const uint32_t, DescriptorRequirement> &binding_info, uint32_t index, VkSampler sampler, bool is_immutable, const SAMPLER_STATE *sampler_state) const { // Verify Sampler still valid if (!sampler_state || sampler_state->Destroyed()) { auto set = descriptor_set->GetSet(); return LogError(set, vuids.descriptor_valid, "Descriptor set %s encountered the following validation error at %s time: Descriptor in " "binding #%" PRIu32 " index %" PRIu32 " is using sampler %s that is invalid or has been destroyed.", report_data->FormatHandle(set).c_str(), caller, binding_info.first, index, report_data->FormatHandle(sampler).c_str()); } else { if (sampler_state->samplerConversion && !is_immutable) { auto set = descriptor_set->GetSet(); return LogError(set, vuids.descriptor_valid, "Descriptor set %s encountered the following validation error at %s time: sampler (%s) " "in the descriptor set (%s) contains a YCBCR conversion (%s), then the sampler MUST " "also exist as an immutable sampler.", report_data->FormatHandle(set).c_str(), caller, report_data->FormatHandle(sampler).c_str(), report_data->FormatHandle(descriptor_set->GetSet()).c_str(), report_data->FormatHandle(sampler_state->samplerConversion).c_str()); } } return false; } // Loop through the write updates to do for a push descriptor set, ignoring dstSet void cvdescriptorset::DescriptorSet::PerformPushDescriptorsUpdate(ValidationStateTracker *dev_data, uint32_t write_count, const VkWriteDescriptorSet *p_wds) { assert(IsPushDescriptor()); for (uint32_t i = 0; i < write_count; i++) { PerformWriteUpdate(dev_data, &p_wds[i]); } push_descriptor_set_writes.clear(); push_descriptor_set_writes.reserve(static_cast<std::size_t>(write_count)); for (uint32_t i = 0; i < write_count; i++) { push_descriptor_set_writes.push_back(safe_VkWriteDescriptorSet(&p_wds[i])); } } // Perform write update in given update struct void cvdescriptorset::DescriptorSet::PerformWriteUpdate(ValidationStateTracker *dev_data, const VkWriteDescriptorSet *update) { // Perform update on a per-binding basis as consecutive updates roll over to next binding auto descriptors_remaining = update->descriptorCount; auto offset = update->dstArrayElement; auto orig_binding = DescriptorSetLayout::ConstBindingIterator(layout_.get(), update->dstBinding); auto current_binding = orig_binding; uint32_t update_index = 0; // Verify next consecutive binding matches type, stage flags & immutable sampler use and if AtEnd while (descriptors_remaining && orig_binding.IsConsistent(current_binding)) { const auto &index_range = current_binding.GetGlobalIndexRange(); auto global_idx = index_range.start + offset; // global_idx is which descriptor is needed to update. If global_idx > index_range.end, it means the descriptor isn't in // this binding, maybe in next binding. if (global_idx >= index_range.end) { offset -= current_binding.GetDescriptorCount(); ++current_binding; continue; } // Loop over the updates for a single binding at a time uint32_t update_count = std::min(descriptors_remaining, current_binding.GetDescriptorCount() - offset); for (uint32_t di = 0; di < update_count; ++di, ++update_index) { descriptors_[global_idx + di]->WriteUpdate(this, state_data_, update, update_index); } // Roll over to next binding in case of consecutive update descriptors_remaining -= update_count; if (descriptors_remaining) { // Starting offset is beyond the current binding. Check consistency, update counters and advance to the next binding, // looking for the start point. All bindings (even those skipped) must be consistent with the update and with the // original binding. offset = 0; ++current_binding; } } if (update->descriptorCount) { some_update_ = true; change_count_++; } if (!IsPushDescriptor() && !(layout_->GetDescriptorBindingFlagsFromBinding(update->dstBinding) & (VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT | VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT))) { Invalidate(false); } } // Validate Copy update bool CoreChecks::ValidateCopyUpdate(const VkCopyDescriptorSet *update, const DescriptorSet *dst_set, const DescriptorSet *src_set, const char *func_name, std::string *error_code, std::string *error_msg) const { auto dst_layout = dst_set->GetLayout().get(); auto src_layout = src_set->GetLayout().get(); // Verify dst layout still valid if (dst_layout->Destroyed()) { *error_code = "VUID-VkCopyDescriptorSet-dstSet-parameter"; std::ostringstream str; str << "Cannot call " << func_name << " to perform copy update on dstSet " << report_data->FormatHandle(dst_set->GetSet()) << " created with destroyed " << report_data->FormatHandle(dst_layout->GetDescriptorSetLayout()) << "."; *error_msg = str.str(); return false; } // Verify src layout still valid if (src_layout->Destroyed()) { *error_code = "VUID-VkCopyDescriptorSet-srcSet-parameter"; std::ostringstream str; str << "Cannot call " << func_name << " to perform copy update on dstSet " << report_data->FormatHandle(dst_set->GetSet()) << " from srcSet " << report_data->FormatHandle(src_set->GetSet()) << " created with destroyed " << report_data->FormatHandle(src_layout->GetDescriptorSetLayout()) << "."; *error_msg = str.str(); return false; } if (!dst_layout->HasBinding(update->dstBinding)) { *error_code = "VUID-VkCopyDescriptorSet-dstBinding-00347"; std::stringstream error_str; error_str << "DescriptorSet " << report_data->FormatHandle(dst_set->GetSet()) << " does not have copy update dest binding of " << update->dstBinding; *error_msg = error_str.str(); return false; } if (!src_set->HasBinding(update->srcBinding)) { *error_code = "VUID-VkCopyDescriptorSet-srcBinding-00345"; std::stringstream error_str; error_str << "DescriptorSet " << report_data->FormatHandle(src_set->GetSet()) << " does not have copy update src binding of " << update->srcBinding; *error_msg = error_str.str(); return false; } // Verify idle ds if (dst_set->InUse() && !(dst_layout->GetDescriptorBindingFlagsFromBinding(update->dstBinding) & (VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT | VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT))) { // TODO : Re-using Free Idle error code, need copy update idle error code *error_code = "VUID-vkFreeDescriptorSets-pDescriptorSets-00309"; std::stringstream error_str; error_str << "Cannot call " << func_name << " to perform copy update on descriptor set " << report_data->FormatHandle(dst_set->GetSet()) << " that is in use by a command buffer"; *error_msg = error_str.str(); return false; } // src & dst set bindings are valid // Check bounds of src & dst auto src_start_idx = src_set->GetGlobalIndexRangeFromBinding(update->srcBinding).start + update->srcArrayElement; if ((src_start_idx + update->descriptorCount) > src_set->GetTotalDescriptorCount()) { // SRC update out of bounds *error_code = "VUID-VkCopyDescriptorSet-srcArrayElement-00346"; std::stringstream error_str; error_str << "Attempting copy update from descriptorSet " << report_data->FormatHandle(update->srcSet) << " binding#" << update->srcBinding << " with offset index of " << src_set->GetGlobalIndexRangeFromBinding(update->srcBinding).start << " plus update array offset of " << update->srcArrayElement << " and update of " << update->descriptorCount << " descriptors oversteps total number of descriptors in set: " << src_set->GetTotalDescriptorCount(); *error_msg = error_str.str(); return false; } auto dst_start_idx = dst_layout->GetGlobalIndexRangeFromBinding(update->dstBinding).start + update->dstArrayElement; if ((dst_start_idx + update->descriptorCount) > dst_layout->GetTotalDescriptorCount()) { // DST update out of bounds *error_code = "VUID-VkCopyDescriptorSet-dstArrayElement-00348"; std::stringstream error_str; error_str << "Attempting copy update to descriptorSet " << report_data->FormatHandle(dst_set->GetSet()) << " binding#" << update->dstBinding << " with offset index of " << dst_layout->GetGlobalIndexRangeFromBinding(update->dstBinding).start << " plus update array offset of " << update->dstArrayElement << " and update of " << update->descriptorCount << " descriptors oversteps total number of descriptors in set: " << dst_layout->GetTotalDescriptorCount(); *error_msg = error_str.str(); return false; } // Check that types match // TODO : Base default error case going from here is "VUID-VkAcquireNextImageInfoKHR-semaphore-parameter" 2ba which covers all // consistency issues, need more fine-grained error codes *error_code = "VUID-VkCopyDescriptorSet-srcSet-00349"; auto src_type = src_set->GetTypeFromBinding(update->srcBinding); auto dst_type = dst_layout->GetTypeFromBinding(update->dstBinding); if (src_type != VK_DESCRIPTOR_TYPE_MUTABLE_VALVE && dst_type != VK_DESCRIPTOR_TYPE_MUTABLE_VALVE && src_type != dst_type) { *error_code = "VUID-VkCopyDescriptorSet-dstBinding-02632"; std::stringstream error_str; error_str << "Attempting copy update to descriptorSet " << report_data->FormatHandle(dst_set->GetSet()) << " binding #" << update->dstBinding << " with type " << string_VkDescriptorType(dst_type) << " from descriptorSet " << report_data->FormatHandle(src_set->GetSet()) << " binding #" << update->srcBinding << " with type " << string_VkDescriptorType(src_type) << ". Types do not match"; *error_msg = error_str.str(); return false; } // Verify consistency of src & dst bindings if update crosses binding boundaries if ((!VerifyUpdateConsistency(report_data, DescriptorSetLayout::ConstBindingIterator(src_layout, update->srcBinding), update->srcArrayElement, update->descriptorCount, "copy update from", src_set->GetSet(), error_msg)) || (!VerifyUpdateConsistency(report_data, DescriptorSetLayout::ConstBindingIterator(dst_layout, update->dstBinding), update->dstArrayElement, update->descriptorCount, "copy update to", dst_set->GetSet(), error_msg))) { return false; } if ((src_layout->GetCreateFlags() & VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT) && !(dst_layout->GetCreateFlags() & VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT)) { *error_code = "VUID-VkCopyDescriptorSet-srcSet-01918"; std::stringstream error_str; error_str << "If pname:srcSet's (" << report_data->FormatHandle(update->srcSet) << ") layout was created with the " "ename:VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT flag " "set, then pname:dstSet's (" << report_data->FormatHandle(update->dstSet) << ") layout must: also have been created with the " "ename:VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT flag set"; *error_msg = error_str.str(); return false; } if (device_extensions.vk_valve_mutable_descriptor_type) { if (!(src_layout->GetCreateFlags() & (VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT | VK_DESCRIPTOR_SET_LAYOUT_CREATE_HOST_ONLY_POOL_BIT_VALVE)) && (dst_layout->GetCreateFlags() & VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT)) { *error_code = "VUID-VkCopyDescriptorSet-srcSet-04885"; std::stringstream error_str; error_str << "If pname:srcSet's (" << report_data->FormatHandle(update->srcSet) << ") layout was created with neither ename:VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT nor " "ename:VK_DESCRIPTOR_SET_LAYOUT_CREATE_HOST_ONLY_POOL_BIT_VALVE flags set, then pname:dstSet's (" << report_data->FormatHandle(update->dstSet) << ") layout must: have been created without the " "ename:VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT flag set"; *error_msg = error_str.str(); return false; } } else { if (!(src_layout->GetCreateFlags() & VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT) && (dst_layout->GetCreateFlags() & VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT)) { *error_code = "VUID-VkCopyDescriptorSet-srcSet-04886"; std::stringstream error_str; error_str << "If pname:srcSet's (" << report_data->FormatHandle(update->srcSet) << ") layout was created without the ename:VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT flag " "set, then pname:dstSet's (" << report_data->FormatHandle(update->dstSet) << ") layout must: also have been created without the " "ename:VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT flag set"; *error_msg = error_str.str(); return false; } } if ((src_set->GetPoolState()->createInfo.flags & VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT) && !(dst_set->GetPoolState()->createInfo.flags & VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT)) { *error_code = "VUID-VkCopyDescriptorSet-srcSet-01920"; std::stringstream error_str; error_str << "If the descriptor pool from which pname:srcSet (" << report_data->FormatHandle(update->srcSet) << ") was allocated was created " "with the ename:VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT flag " "set, then the descriptor pool from which pname:dstSet (" << report_data->FormatHandle(update->dstSet) << ") was allocated must: " "also have been created with the ename:VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT flag set"; *error_msg = error_str.str(); return false; } if (device_extensions.vk_valve_mutable_descriptor_type) { if (!(src_set->GetPoolState()->createInfo.flags & (VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT | VK_DESCRIPTOR_POOL_CREATE_HOST_ONLY_BIT_VALVE)) && (dst_set->GetPoolState()->createInfo.flags & VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT)) { *error_code = "VUID-VkCopyDescriptorSet-srcSet-04887"; std::stringstream error_str; error_str << "If the descriptor pool from which pname:srcSet (" << report_data->FormatHandle(update->srcSet) << ") was allocated was created with neither ename:VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT nor " "ename:VK_DESCRIPTOR_POOL_CREATE_HOST_ONLY_BIT_VALVE flags set, then the descriptor pool from which " "pname:dstSet (" << report_data->FormatHandle(update->dstSet) << ") was allocated must: have been created without the " "ename:VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT flag set"; *error_msg = error_str.str(); return false; } } else { if (!(src_set->GetPoolState()->createInfo.flags & VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT) && (dst_set->GetPoolState()->createInfo.flags & VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT)) { *error_code = "VUID-VkCopyDescriptorSet-srcSet-04888"; std::stringstream error_str; error_str << "If the descriptor pool from which pname:srcSet (" << report_data->FormatHandle(update->srcSet) << ") was allocated was created without the ename:VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT flag set, " "then the descriptor pool from which pname:dstSet (" << report_data->FormatHandle(update->dstSet) << ") was allocated must: also have been created without the " "ename:VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT flag set"; *error_msg = error_str.str(); return false; } } if (src_type == VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT) { if ((update->srcArrayElement % 4) != 0) { *error_code = "VUID-VkCopyDescriptorSet-srcBinding-02223"; std::stringstream error_str; error_str << "Attempting copy update to VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT binding with " << "srcArrayElement " << update->srcArrayElement << " not a multiple of 4"; *error_msg = error_str.str(); return false; } if ((update->dstArrayElement % 4) != 0) { *error_code = "VUID-VkCopyDescriptorSet-dstBinding-02224"; std::stringstream error_str; error_str << "Attempting copy update to VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT binding with " << "dstArrayElement " << update->dstArrayElement << " not a multiple of 4"; *error_msg = error_str.str(); return false; } if ((update->descriptorCount % 4) != 0) { *error_code = "VUID-VkCopyDescriptorSet-srcBinding-02225"; std::stringstream error_str; error_str << "Attempting copy update to VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT binding with " << "descriptorCount " << update->descriptorCount << " not a multiple of 4"; *error_msg = error_str.str(); return false; } } // Update parameters all look good and descriptor updated so verify update contents if (!VerifyCopyUpdateContents(update, src_set, src_type, src_start_idx, dst_set, dst_type, dst_start_idx, func_name, error_code, error_msg)) { return false; } // All checks passed so update is good return true; } // Perform Copy update void cvdescriptorset::DescriptorSet::PerformCopyUpdate(ValidationStateTracker *dev_data, const VkCopyDescriptorSet *update, const DescriptorSet *src_set) { auto src_start_idx = src_set->GetGlobalIndexRangeFromBinding(update->srcBinding).start + update->srcArrayElement; auto dst_start_idx = layout_->GetGlobalIndexRangeFromBinding(update->dstBinding).start + update->dstArrayElement; // Update parameters all look good so perform update for (uint32_t di = 0; di < update->descriptorCount; ++di) { auto src = src_set->descriptors_[src_start_idx + di].get(); auto dst = descriptors_[dst_start_idx + di].get(); if (src->updated) { dst->CopyUpdate(this, state_data_, src); some_update_ = true; change_count_++; } else { dst->updated = false; } } if (!(layout_->GetDescriptorBindingFlagsFromBinding(update->dstBinding) & (VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT | VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT))) { Invalidate(false); } } // Update the drawing state for the affected descriptors. // Set cb_node to this set and this set to cb_node. // Add the bindings of the descriptor // Set the layout based on the current descriptor layout (will mask subsequent layer mismatch errors) // TODO: Modify the UpdateDrawState virtural functions to *only* set initial layout and not change layouts // Prereq: This should be called for a set that has been confirmed to be active for the given cb_node, meaning it's going // to be used in a draw by the given cb_node void cvdescriptorset::DescriptorSet::UpdateDrawState(ValidationStateTracker *device_data, CMD_BUFFER_STATE *cb_node, CMD_TYPE cmd_type, const PIPELINE_STATE *pipe, const BindingReqMap &binding_req_map, const char *function) { if (!device_data->disabled[command_buffer_state] && !IsPushDescriptor()) { cb_node->AddChild(this); } // Descriptor UpdateDrawState only call image layout validation callbacks. If it is disabled, skip the entire loop. if (device_data->disabled[image_layout_validation]) { return; } // For the active slots, use set# to look up descriptorSet from boundDescriptorSets, and bind all of that descriptor set's // resources CMD_BUFFER_STATE::CmdDrawDispatchInfo cmd_info = {}; for (const auto &binding_req_pair : binding_req_map) { auto index = layout_->GetIndexFromBinding(binding_req_pair.first); // We aren't validating descriptors created with PARTIALLY_BOUND or UPDATE_AFTER_BIND, so don't record state auto flags = layout_->GetDescriptorBindingFlagsFromIndex(index); if (flags & (VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT | VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT)) { if (!(flags & VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT)) { cmd_info.binding_infos.emplace_back(binding_req_pair); } continue; } auto range = layout_->GetGlobalIndexRangeFromIndex(index); for (uint32_t i = range.start; i < range.end; ++i) { const auto descriptor_class = descriptors_[i]->GetClass(); switch (descriptor_class) { case DescriptorClass::Image: case DescriptorClass::ImageSampler: { auto *image_desc = static_cast<ImageDescriptor *>(descriptors_[i].get()); image_desc->UpdateDrawState(device_data, cb_node); break; } default: break; } } } if (cmd_info.binding_infos.size() > 0) { cmd_info.cmd_type = cmd_type; cmd_info.function = function; if (cb_node->activeFramebuffer) { cmd_info.framebuffer = cb_node->activeFramebuffer->framebuffer(); cmd_info.attachments = cb_node->active_attachments; cmd_info.subpasses = cb_node->active_subpasses; } cb_node->validate_descriptorsets_in_queuesubmit[GetSet()].emplace_back(cmd_info); } } void cvdescriptorset::DescriptorSet::FilterOneBindingReq(const BindingReqMap::value_type &binding_req_pair, BindingReqMap *out_req, const TrackedBindings &bindings, uint32_t limit) { if (bindings.size() < limit) { const auto it = bindings.find(binding_req_pair.first); if (it == bindings.cend()) out_req->emplace(binding_req_pair); } } void cvdescriptorset::DescriptorSet::FilterBindingReqs(const CMD_BUFFER_STATE &cb_state, const PIPELINE_STATE &pipeline, const BindingReqMap &in_req, BindingReqMap *out_req) const { // For const cleanliness we have to find in the maps... const auto validated_it = cached_validation_.find(&cb_state); if (validated_it == cached_validation_.cend()) { // We have nothing validated, copy in to out for (const auto &binding_req_pair : in_req) { out_req->emplace(binding_req_pair); } return; } const auto &validated = validated_it->second; const auto image_sample_version_it = validated.image_samplers.find(&pipeline); const VersionedBindings *image_sample_version = nullptr; if (image_sample_version_it != validated.image_samplers.cend()) { image_sample_version = &(image_sample_version_it->second); } const auto &dynamic_buffers = validated.dynamic_buffers; const auto &non_dynamic_buffers = validated.non_dynamic_buffers; const auto &stats = layout_->GetBindingTypeStats(); for (const auto &binding_req_pair : in_req) { auto binding = binding_req_pair.first; VkDescriptorSetLayoutBinding const *layout_binding = layout_->GetDescriptorSetLayoutBindingPtrFromBinding(binding); if (!layout_binding) { continue; } // Caching criteria differs per type. // If image_layout have changed , the image descriptors need to be validated against them. if (IsBufferDescriptor(layout_binding->descriptorType)) { if (IsDynamicDescriptor(layout_binding->descriptorType)) { FilterOneBindingReq(binding_req_pair, out_req, dynamic_buffers, stats.dynamic_buffer_count); } else { FilterOneBindingReq(binding_req_pair, out_req, non_dynamic_buffers, stats.non_dynamic_buffer_count); } } else { // This is rather crude, as the changed layouts may not impact the bound descriptors, // but the simple "versioning" is a simple "dirt" test. bool stale = true; if (image_sample_version) { const auto version_it = image_sample_version->find(binding); if (version_it != image_sample_version->cend() && (version_it->second == cb_state.image_layout_change_count)) { stale = false; } } if (stale) { out_req->emplace(binding_req_pair); } } } } void cvdescriptorset::DescriptorSet::UpdateValidationCache(const CMD_BUFFER_STATE &cb_state, const PIPELINE_STATE &pipeline, const BindingReqMap &updated_bindings) { // For const cleanliness we have to find in the maps... auto &validated = cached_validation_[&cb_state]; auto &image_sample_version = validated.image_samplers[&pipeline]; auto &dynamic_buffers = validated.dynamic_buffers; auto &non_dynamic_buffers = validated.non_dynamic_buffers; for (const auto &binding_req_pair : updated_bindings) { auto binding = binding_req_pair.first; VkDescriptorSetLayoutBinding const *layout_binding = layout_->GetDescriptorSetLayoutBindingPtrFromBinding(binding); if (!layout_binding) { continue; } // Caching criteria differs per type. if (IsBufferDescriptor(layout_binding->descriptorType)) { if (IsDynamicDescriptor(layout_binding->descriptorType)) { dynamic_buffers.emplace(binding); } else { non_dynamic_buffers.emplace(binding); } } else { // Save the layout change version... image_sample_version[binding] = cb_state.image_layout_change_count; } } } cvdescriptorset::SamplerDescriptor::SamplerDescriptor(const ValidationStateTracker *dev_data, const VkSampler *immut) : Descriptor(PlainSampler), immutable_(false) { if (immut) { sampler_state_ = dev_data->GetConstCastShared<SAMPLER_STATE>(*immut); immutable_ = true; updated = true; } } // Validate given sampler. Currently this only checks to make sure it exists in the samplerMap bool CoreChecks::ValidateSampler(const VkSampler sampler) const { return (GetSamplerState(sampler) != nullptr); } bool CoreChecks::ValidateImageUpdate(VkImageView image_view, VkImageLayout image_layout, VkDescriptorType type, const char *func_name, std::string *error_code, std::string *error_msg) const { auto iv_state = GetImageViewState(image_view); assert(iv_state); // Note that when an imageview is created, we validated that memory is bound so no need to re-check here // Validate that imageLayout is compatible with aspect_mask and image format // and validate that image usage bits are correct for given usage VkImageAspectFlags aspect_mask = iv_state->normalized_subresource_range.aspectMask; VkImage image = iv_state->create_info.image; VkFormat format = VK_FORMAT_MAX_ENUM; VkImageUsageFlags usage = 0; auto image_node = GetImageState(image); assert(image_node); format = image_node->createInfo.format; usage = image_node->createInfo.usage; const auto stencil_usage_info = LvlFindInChain<VkImageStencilUsageCreateInfo>(image_node->createInfo.pNext); if (stencil_usage_info) { usage |= stencil_usage_info->stencilUsage; } // Validate that memory is bound to image if (ValidateMemoryIsBoundToImage(image_node, func_name, "UNASSIGNED-CoreValidation-BoundResourceFreedMemoryAccess")) { *error_code = "UNASSIGNED-CoreValidation-BoundResourceFreedMemoryAccess"; *error_msg = "No memory bound to image."; return false; } // KHR_maintenance1 allows rendering into 2D or 2DArray views which slice a 3D image, // but not binding them to descriptor sets. if (image_node->createInfo.imageType == VK_IMAGE_TYPE_3D && (iv_state->create_info.viewType == VK_IMAGE_VIEW_TYPE_2D || iv_state->create_info.viewType == VK_IMAGE_VIEW_TYPE_2D_ARRAY)) { *error_code = "VUID-VkDescriptorImageInfo-imageView-00343"; *error_msg = "ImageView must not be a 2D or 2DArray view of a 3D image"; return false; } // TODO : The various image aspect and format checks here are based on general spec language in 11.5 Image Views section under // vkCreateImageView(). What's the best way to create unique id for these cases? *error_code = "UNASSIGNED-CoreValidation-DrawState-InvalidImageView"; bool ds = FormatIsDepthOrStencil(format); switch (image_layout) { case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL: // Only Color bit must be set if ((aspect_mask & VK_IMAGE_ASPECT_COLOR_BIT) != VK_IMAGE_ASPECT_COLOR_BIT) { std::stringstream error_str; error_str << "ImageView (" << report_data->FormatHandle(image_view) << ") uses layout VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL but does not have VK_IMAGE_ASPECT_COLOR_BIT set."; *error_msg = error_str.str(); return false; } // format must NOT be DS if (ds) { std::stringstream error_str; error_str << "ImageView (" << report_data->FormatHandle(image_view) << ") uses layout VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL but the image format is " << string_VkFormat(format) << " which is not a color format."; *error_msg = error_str.str(); return false; } break; case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL: case VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL: // Depth or stencil bit must be set, but both must NOT be set if (aspect_mask & VK_IMAGE_ASPECT_DEPTH_BIT) { if (aspect_mask & VK_IMAGE_ASPECT_STENCIL_BIT) { // both must NOT be set std::stringstream error_str; error_str << "ImageView (" << report_data->FormatHandle(image_view) << ") has both STENCIL and DEPTH aspects set"; *error_msg = error_str.str(); return false; } } else if (!(aspect_mask & VK_IMAGE_ASPECT_STENCIL_BIT)) { // Neither were set std::stringstream error_str; error_str << "ImageView (" << report_data->FormatHandle(image_view) << ") has layout " << string_VkImageLayout(image_layout) << " but does not have STENCIL or DEPTH aspects set"; *error_msg = error_str.str(); return false; } // format must be DS if (!ds) { std::stringstream error_str; error_str << "ImageView (" << report_data->FormatHandle(image_view) << ") has layout " << string_VkImageLayout(image_layout) << " but the image format is " << string_VkFormat(format) << " which is not a depth/stencil format."; *error_msg = error_str.str(); return false; } break; default: // For other layouts if the source is depth/stencil image, both aspect bits must not be set if (ds) { if (aspect_mask & VK_IMAGE_ASPECT_DEPTH_BIT) { if (aspect_mask & VK_IMAGE_ASPECT_STENCIL_BIT) { // both must NOT be set std::stringstream error_str; error_str << "ImageView (" << report_data->FormatHandle(image_view) << ") has layout " << string_VkImageLayout(image_layout) << " and is using depth/stencil image of format " << string_VkFormat(format) << " but it has both STENCIL and DEPTH aspects set, which is illegal. When using a depth/stencil " "image in a descriptor set, please only set either VK_IMAGE_ASPECT_DEPTH_BIT or " "VK_IMAGE_ASPECT_STENCIL_BIT depending on whether it will be used for depth reads or stencil " "reads respectively."; *error_code = "VUID-VkDescriptorImageInfo-imageView-01976"; *error_msg = error_str.str(); return false; } } } break; } // Now validate that usage flags are correctly set for given type of update // As we're switching per-type, if any type has specific layout requirements, check those here as well // TODO : The various image usage bit requirements are in general spec language for VkImageUsageFlags bit block in 11.3 Images // under vkCreateImage() const char *error_usage_bit = nullptr; switch (type) { case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE: if (iv_state->samplerConversion != VK_NULL_HANDLE) { *error_code = "VUID-VkWriteDescriptorSet-descriptorType-01946"; std::stringstream error_str; error_str << "ImageView (" << report_data->FormatHandle(image_view) << ")" << "used as a VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE can't be created with VkSamplerYcbcrConversion"; *error_msg = error_str.str(); return false; } // drop through case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER: { if (!(usage & VK_IMAGE_USAGE_SAMPLED_BIT)) { error_usage_bit = "VK_IMAGE_USAGE_SAMPLED_BIT"; *error_code = "VUID-VkWriteDescriptorSet-descriptorType-00337"; } break; } case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE: { if (!(usage & VK_IMAGE_USAGE_STORAGE_BIT)) { error_usage_bit = "VK_IMAGE_USAGE_STORAGE_BIT"; *error_code = "VUID-VkWriteDescriptorSet-descriptorType-00339"; } else if ((VK_IMAGE_LAYOUT_GENERAL != image_layout) && (!device_extensions.vk_khr_shared_presentable_image || (VK_IMAGE_LAYOUT_SHARED_PRESENT_KHR != image_layout))) { *error_code = "VUID-VkWriteDescriptorSet-descriptorType-04152"; std::stringstream error_str; error_str << "Descriptor update with descriptorType VK_DESCRIPTOR_TYPE_STORAGE_IMAGE" << " is being updated with invalid imageLayout " << string_VkImageLayout(image_layout) << " for image " << report_data->FormatHandle(image) << " in imageView " << report_data->FormatHandle(image_view) << ". Allowed layouts are: VK_IMAGE_LAYOUT_GENERAL"; if (device_extensions.vk_khr_shared_presentable_image) { error_str << " or VK_IMAGE_LAYOUT_SHARED_PRESENT_KHR"; } *error_msg = error_str.str(); return false; } break; } case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT: { if (!(usage & VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT)) { error_usage_bit = "VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT"; *error_code = "VUID-VkWriteDescriptorSet-descriptorType-00338"; } break; } default: break; } if (error_usage_bit) { std::stringstream error_str; error_str << "ImageView (" << report_data->FormatHandle(image_view) << ") with usage mask " << std::hex << std::showbase << usage << " being used for a descriptor update of type " << string_VkDescriptorType(type) << " does not have " << error_usage_bit << " set."; *error_msg = error_str.str(); return false; } // All the following types share the same image layouts // checkf or Storage Images above if ((type == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE) || (type == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER) || (type == VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT)) { // Test that the layout is compatible with the descriptorType for the two sampled image types const static std::array<VkImageLayout, 3> valid_layouts = { {VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL}}; struct ExtensionLayout { VkImageLayout layout; ExtEnabled DeviceExtensions::*extension; }; const static std::array<ExtensionLayout, 5> extended_layouts{{ // Note double brace req'd for aggregate initialization {VK_IMAGE_LAYOUT_SHARED_PRESENT_KHR, &DeviceExtensions::vk_khr_shared_presentable_image}, {VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL, &DeviceExtensions::vk_khr_maintenance2}, {VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL, &DeviceExtensions::vk_khr_maintenance2}, {VK_IMAGE_LAYOUT_READ_ONLY_OPTIMAL_KHR, &DeviceExtensions::vk_khr_synchronization2}, {VK_IMAGE_LAYOUT_ATTACHMENT_OPTIMAL_KHR, &DeviceExtensions::vk_khr_synchronization2}, }}; auto is_layout = [image_layout, this](const ExtensionLayout &ext_layout) { return device_extensions.*(ext_layout.extension) && (ext_layout.layout == image_layout); }; bool valid_layout = (std::find(valid_layouts.cbegin(), valid_layouts.cend(), image_layout) != valid_layouts.cend()) || std::any_of(extended_layouts.cbegin(), extended_layouts.cend(), is_layout); if (!valid_layout) { // The following works as currently all 3 descriptor types share the same set of valid layouts switch (type) { case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE: *error_code = "VUID-VkWriteDescriptorSet-descriptorType-04149"; break; case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER: *error_code = "VUID-VkWriteDescriptorSet-descriptorType-04150"; break; case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT: *error_code = "VUID-VkWriteDescriptorSet-descriptorType-04151"; break; default: break; } std::stringstream error_str; error_str << "Descriptor update with descriptorType " << string_VkDescriptorType(type) << " is being updated with invalid imageLayout " << string_VkImageLayout(image_layout) << " for image " << report_data->FormatHandle(image) << " in imageView " << report_data->FormatHandle(image_view) << ". Allowed layouts are: VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL, " << "VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL"; for (auto &ext_layout : extended_layouts) { if (device_extensions.*(ext_layout.extension)) { error_str << ", " << string_VkImageLayout(ext_layout.layout); } } *error_msg = error_str.str(); return false; } } if ((type == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE) || (type == VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT)) { const VkComponentMapping components = iv_state->create_info.components; if (IsIdentitySwizzle(components) == false) { *error_code = "VUID-VkWriteDescriptorSet-descriptorType-00336"; std::stringstream error_str; error_str << "ImageView (" << report_data->FormatHandle(image_view) << ") has a non-identiy swizzle component, " << " r swizzle = " << string_VkComponentSwizzle(components.r) << "," << " g swizzle = " << string_VkComponentSwizzle(components.g) << "," << " b swizzle = " << string_VkComponentSwizzle(components.b) << "," << " a swizzle = " << string_VkComponentSwizzle(components.a) << "."; *error_msg = error_str.str(); return false; } } return true; } // Helper template to change shared pointer members of a Descriptor, while // correctly managing links to the parent DescriptorSet. // src and dst are shared pointers. template <typename T> static void ReplaceStatePtr(DescriptorSet *set_state, T &dst, const T &src) { if (dst) { dst->RemoveParent(set_state); } dst = src; if (dst) { dst->AddParent(set_state); } } void cvdescriptorset::SamplerDescriptor::WriteUpdate(DescriptorSet *set_state, const ValidationStateTracker *dev_data, const VkWriteDescriptorSet *update, const uint32_t index) { if (!immutable_) { ReplaceStatePtr(set_state, sampler_state_ , dev_data->GetConstCastShared<SAMPLER_STATE>(update->pImageInfo[index].sampler)); } updated = true; } void cvdescriptorset::SamplerDescriptor::CopyUpdate(DescriptorSet *set_state, const ValidationStateTracker *dev_data, const Descriptor *src) { updated = true; // Mutable descriptors not currently tracked or validated. If copied from mutable, set to mutable to keep from validating. if (src->descriptor_class == Mutable) { this->descriptor_class = Mutable; return; } auto *sampler_src = static_cast<const SamplerDescriptor *>(src); if (!immutable_) { ReplaceStatePtr(set_state, sampler_state_, sampler_src->sampler_state_); } } cvdescriptorset::ImageSamplerDescriptor::ImageSamplerDescriptor(const ValidationStateTracker *dev_data, const VkSampler *immut) : ImageDescriptor(ImageSampler), immutable_(false) { if (immut) { sampler_state_ = dev_data->GetConstCastShared<SAMPLER_STATE>(*immut); immutable_ = true; } } void cvdescriptorset::ImageSamplerDescriptor::WriteUpdate(DescriptorSet *set_state, const ValidationStateTracker *dev_data, const VkWriteDescriptorSet *update, const uint32_t index) { updated = true; const auto &image_info = update->pImageInfo[index]; if (!immutable_) { ReplaceStatePtr(set_state, sampler_state_, dev_data->GetConstCastShared<SAMPLER_STATE>(image_info.sampler)); } image_layout_ = image_info.imageLayout; ReplaceStatePtr(set_state, image_view_state_, dev_data->GetConstCastShared<IMAGE_VIEW_STATE>(image_info.imageView)); } void cvdescriptorset::ImageSamplerDescriptor::CopyUpdate(DescriptorSet *set_state, const ValidationStateTracker *dev_data, const Descriptor *src) { updated = true; // Mutable descriptors not currently tracked or validated. If copied from mutable, set to mutable to keep from validating. if (src->descriptor_class == Mutable) { this->descriptor_class = Mutable; return; } auto *image_src = static_cast<const ImageSamplerDescriptor *>(src); if (!immutable_) { ReplaceStatePtr(set_state, sampler_state_, image_src->sampler_state_); } ImageDescriptor::CopyUpdate(set_state, dev_data, src); } cvdescriptorset::ImageDescriptor::ImageDescriptor(const VkDescriptorType type) : Descriptor(Image), image_layout_(VK_IMAGE_LAYOUT_UNDEFINED) {} cvdescriptorset::ImageDescriptor::ImageDescriptor(DescriptorClass class_) : Descriptor(class_), image_layout_(VK_IMAGE_LAYOUT_UNDEFINED) {} void cvdescriptorset::ImageDescriptor::WriteUpdate(DescriptorSet *set_state, const ValidationStateTracker *dev_data, const VkWriteDescriptorSet *update, const uint32_t index) { updated = true; const auto &image_info = update->pImageInfo[index]; image_layout_ = image_info.imageLayout; image_view_state_ = dev_data->GetConstCastShared<IMAGE_VIEW_STATE>(image_info.imageView); } void cvdescriptorset::ImageDescriptor::CopyUpdate(DescriptorSet *set_state, const ValidationStateTracker *dev_data, const Descriptor *src) { updated = true; // Mutable descriptors not currently tracked or validated. If copied from mutable, set to mutable to keep from validating. if (src->descriptor_class == Mutable) { this->descriptor_class = Mutable; return; } auto *image_src = static_cast<const ImageDescriptor *>(src); image_layout_ = image_src->image_layout_; ReplaceStatePtr(set_state, image_view_state_, image_src->image_view_state_); } void cvdescriptorset::ImageDescriptor::UpdateDrawState(ValidationStateTracker *dev_data, CMD_BUFFER_STATE *cb_node) { // Add binding for image auto iv_state = GetImageViewState(); if (iv_state) { dev_data->CallSetImageViewInitialLayoutCallback(cb_node, *iv_state, image_layout_); } } cvdescriptorset::BufferDescriptor::BufferDescriptor(const VkDescriptorType type) : Descriptor(GeneralBuffer), offset_(0), range_(0) {} void cvdescriptorset::BufferDescriptor::WriteUpdate(DescriptorSet *set_state, const ValidationStateTracker *dev_data, const VkWriteDescriptorSet *update, const uint32_t index) { updated = true; const auto &buffer_info = update->pBufferInfo[index]; offset_ = buffer_info.offset; range_ = buffer_info.range; ReplaceStatePtr(set_state, buffer_state_, dev_data->GetConstCastShared<BUFFER_STATE>(buffer_info.buffer)); } void cvdescriptorset::BufferDescriptor::CopyUpdate(DescriptorSet* set_state, const ValidationStateTracker *dev_data, const Descriptor *src) { updated = true; // Mutable descriptors not currently tracked or validated. If copied from mutable, set to mutable to keep from validating. if (src->descriptor_class == Mutable) { this->descriptor_class = Mutable; return; } const auto buff_desc = static_cast<const BufferDescriptor *>(src); offset_ = buff_desc->offset_; range_ = buff_desc->range_; ReplaceStatePtr(set_state, buffer_state_, buff_desc->buffer_state_); } cvdescriptorset::TexelDescriptor::TexelDescriptor(const VkDescriptorType type) : Descriptor(TexelBuffer) {} void cvdescriptorset::TexelDescriptor::WriteUpdate(DescriptorSet *set_state, const ValidationStateTracker *dev_data, const VkWriteDescriptorSet *update, const uint32_t index) { updated = true; ReplaceStatePtr(set_state, buffer_view_state_, dev_data->GetConstCastShared<BUFFER_VIEW_STATE>(update->pTexelBufferView[index])); } void cvdescriptorset::TexelDescriptor::CopyUpdate(DescriptorSet *set_state, const ValidationStateTracker *dev_data, const Descriptor *src) { updated = true; // Mutable descriptors not currently tracked or validated. If copied from mutable, set to mutable to keep from validating. if (src->descriptor_class == Mutable) { this->descriptor_class = Mutable; return; } ReplaceStatePtr(set_state, buffer_view_state_, static_cast<const TexelDescriptor *>(src)->buffer_view_state_); } cvdescriptorset::AccelerationStructureDescriptor::AccelerationStructureDescriptor(const VkDescriptorType type) : Descriptor(AccelerationStructure), acc_(VK_NULL_HANDLE), acc_nv_(VK_NULL_HANDLE) { is_khr_ = false; } void cvdescriptorset::AccelerationStructureDescriptor::WriteUpdate(DescriptorSet *set_state, const ValidationStateTracker *dev_data, const VkWriteDescriptorSet *update, const uint32_t index) { const auto *acc_info = LvlFindInChain<VkWriteDescriptorSetAccelerationStructureKHR>(update->pNext); const auto *acc_info_nv = LvlFindInChain<VkWriteDescriptorSetAccelerationStructureNV>(update->pNext); assert(acc_info || acc_info_nv); is_khr_ = (acc_info != NULL); updated = true; if (is_khr_) { acc_ = acc_info->pAccelerationStructures[index]; ReplaceStatePtr(set_state, acc_state_, dev_data->GetConstCastShared<ACCELERATION_STRUCTURE_STATE_KHR>(acc_)); } else { acc_nv_ = acc_info_nv->pAccelerationStructures[index]; ReplaceStatePtr(set_state, acc_state_nv_, dev_data->GetConstCastShared<ACCELERATION_STRUCTURE_STATE>(acc_nv_)); } } void cvdescriptorset::AccelerationStructureDescriptor::CopyUpdate(DescriptorSet *set_state, const ValidationStateTracker *dev_data, const Descriptor *src) { auto acc_desc = static_cast<const AccelerationStructureDescriptor *>(src); updated = true; // Mutable descriptors not currently tracked or validated. If copied from mutable, set to mutable to keep from validating. if (src->descriptor_class == Mutable) { this->descriptor_class = Mutable; return; } if (is_khr_) { acc_ = acc_desc->acc_; ReplaceStatePtr(set_state, acc_state_, dev_data->GetConstCastShared<ACCELERATION_STRUCTURE_STATE_KHR>(acc_)); } else { acc_nv_ = acc_desc->acc_nv_; ReplaceStatePtr(set_state, acc_state_nv_, dev_data->GetConstCastShared<ACCELERATION_STRUCTURE_STATE>(acc_nv_)); } } cvdescriptorset::MutableDescriptor::MutableDescriptor() : Descriptor(Mutable) { active_descriptor_class_ = NoDescriptorClass; } void cvdescriptorset::MutableDescriptor::WriteUpdate(DescriptorSet *set_state, const ValidationStateTracker *dev_data, const VkWriteDescriptorSet *update, const uint32_t index) { updated = true; } void cvdescriptorset::MutableDescriptor::CopyUpdate(DescriptorSet *set_state, const ValidationStateTracker *dev_data, const Descriptor *src) { updated = true; } // This is a helper function that iterates over a set of Write and Copy updates, pulls the DescriptorSet* for updated // sets, and then calls their respective Validate[Write|Copy]Update functions. // If the update hits an issue for which the callback returns "true", meaning that the call down the chain should // be skipped, then true is returned. // If there is no issue with the update, then false is returned. bool CoreChecks::ValidateUpdateDescriptorSets(uint32_t write_count, const VkWriteDescriptorSet *p_wds, uint32_t copy_count, const VkCopyDescriptorSet *p_cds, const char *func_name) const { bool skip = false; // Validate Write updates for (uint32_t i = 0; i < write_count; i++) { auto dest_set = p_wds[i].dstSet; auto set_node = GetSetNode(dest_set); if (!set_node) { skip |= LogError(dest_set, kVUID_Core_DrawState_InvalidDescriptorSet, "Cannot call %s on %s that has not been allocated in pDescriptorWrites[%u].", func_name, report_data->FormatHandle(dest_set).c_str(), i); } else { std::string error_code; std::string error_str; if (!ValidateWriteUpdate(set_node, &p_wds[i], func_name, &error_code, &error_str)) { skip |= LogError(dest_set, error_code, "%s pDescriptorWrites[%u] failed write update validation for %s with error: %s.", func_name, i, report_data->FormatHandle(dest_set).c_str(), error_str.c_str()); } } if (p_wds[i].pNext) { const auto *pnext_struct = LvlFindInChain<VkWriteDescriptorSetAccelerationStructureKHR>(p_wds[i].pNext); if (pnext_struct) { for (uint32_t j = 0; j < pnext_struct->accelerationStructureCount; ++j) { const ACCELERATION_STRUCTURE_STATE_KHR *as_state = GetAccelerationStructureStateKHR(pnext_struct->pAccelerationStructures[j]); if (as_state && (as_state->create_infoKHR.sType == VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_CREATE_INFO_KHR && (as_state->create_infoKHR.type != VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_KHR && as_state->create_infoKHR.type != VK_ACCELERATION_STRUCTURE_TYPE_GENERIC_KHR))) { skip |= LogError(dest_set, "VUID-VkWriteDescriptorSetAccelerationStructureKHR-pAccelerationStructures-03579", "%s: For pDescriptorWrites[%u] acceleration structure in pAccelerationStructures[%u] must " "have been created with " "VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_KHR or VK_ACCELERATION_STRUCTURE_TYPE_GENERIC_KHR.", func_name, i, j); } } } const auto *pnext_struct_nv = LvlFindInChain<VkWriteDescriptorSetAccelerationStructureNV>(p_wds[i].pNext); if (pnext_struct_nv) { for (uint32_t j = 0; j < pnext_struct_nv->accelerationStructureCount; ++j) { const ACCELERATION_STRUCTURE_STATE *as_state = GetAccelerationStructureStateNV(pnext_struct_nv->pAccelerationStructures[j]); if (as_state && (as_state->create_infoNV.sType == VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_CREATE_INFO_NV && as_state->create_infoNV.info.type != VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_NV)) { skip |= LogError(dest_set, "VUID-VkWriteDescriptorSetAccelerationStructureNV-pAccelerationStructures-03748", "%s: For pDescriptorWrites[%u] acceleration structure in pAccelerationStructures[%u] must " "have been created with" " VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_NV.", func_name, i, j); } } } } } // Now validate copy updates for (uint32_t i = 0; i < copy_count; ++i) { auto dst_set = p_cds[i].dstSet; auto src_set = p_cds[i].srcSet; auto src_node = GetSetNode(src_set); auto dst_node = GetSetNode(dst_set); // Object_tracker verifies that src & dest descriptor set are valid assert(src_node); assert(dst_node); std::string error_code; std::string error_str; if (!ValidateCopyUpdate(&p_cds[i], dst_node, src_node, func_name, &error_code, &error_str)) { LogObjectList objlist(dst_set); objlist.add(src_set); skip |= LogError(objlist, error_code, "%s pDescriptorCopies[%u] failed copy update from %s to %s with error: %s.", func_name, i, report_data->FormatHandle(src_set).c_str(), report_data->FormatHandle(dst_set).c_str(), error_str.c_str()); } } return skip; } // This is a helper function that iterates over a set of Write and Copy updates, pulls the DescriptorSet* for updated // sets, and then calls their respective Perform[Write|Copy]Update functions. // Prerequisite : ValidateUpdateDescriptorSets() should be called and return "false" prior to calling PerformUpdateDescriptorSets() // with the same set of updates. // This is split from the validate code to allow validation prior to calling down the chain, and then update after // calling down the chain. void cvdescriptorset::PerformUpdateDescriptorSets(ValidationStateTracker *dev_data, uint32_t write_count, const VkWriteDescriptorSet *p_wds, uint32_t copy_count, const VkCopyDescriptorSet *p_cds) { // Write updates first uint32_t i = 0; for (i = 0; i < write_count; ++i) { auto dest_set = p_wds[i].dstSet; auto set_node = dev_data->GetSetNode(dest_set); if (set_node) { set_node->PerformWriteUpdate(dev_data, &p_wds[i]); } } // Now copy updates for (i = 0; i < copy_count; ++i) { auto dst_set = p_cds[i].dstSet; auto src_set = p_cds[i].srcSet; auto src_node = dev_data->GetSetNode(src_set); auto dst_node = dev_data->GetSetNode(dst_set); if (src_node && dst_node) { dst_node->PerformCopyUpdate(dev_data, &p_cds[i], src_node); } } } cvdescriptorset::DecodedTemplateUpdate::DecodedTemplateUpdate(const ValidationStateTracker *device_data, VkDescriptorSet descriptorSet, const TEMPLATE_STATE *template_state, const void *pData, VkDescriptorSetLayout push_layout) { auto const &create_info = template_state->create_info; inline_infos.resize(create_info.descriptorUpdateEntryCount); // Make sure we have one if we need it inline_infos_khr.resize(create_info.descriptorUpdateEntryCount); inline_infos_nv.resize(create_info.descriptorUpdateEntryCount); desc_writes.reserve(create_info.descriptorUpdateEntryCount); // emplaced, so reserved without initialization VkDescriptorSetLayout effective_dsl = create_info.templateType == VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_DESCRIPTOR_SET ? create_info.descriptorSetLayout : push_layout; auto layout_obj = device_data->GetDescriptorSetLayoutShared(effective_dsl); // Create a WriteDescriptorSet struct for each template update entry for (uint32_t i = 0; i < create_info.descriptorUpdateEntryCount; i++) { auto binding_count = layout_obj->GetDescriptorCountFromBinding(create_info.pDescriptorUpdateEntries[i].dstBinding); auto binding_being_updated = create_info.pDescriptorUpdateEntries[i].dstBinding; auto dst_array_element = create_info.pDescriptorUpdateEntries[i].dstArrayElement; desc_writes.reserve(desc_writes.size() + create_info.pDescriptorUpdateEntries[i].descriptorCount); for (uint32_t j = 0; j < create_info.pDescriptorUpdateEntries[i].descriptorCount; j++) { desc_writes.emplace_back(); auto &write_entry = desc_writes.back(); size_t offset = create_info.pDescriptorUpdateEntries[i].offset + j * create_info.pDescriptorUpdateEntries[i].stride; char *update_entry = (char *)(pData) + offset; if (dst_array_element >= binding_count) { dst_array_element = 0; binding_being_updated = layout_obj->GetNextValidBinding(binding_being_updated); } write_entry.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; write_entry.pNext = NULL; write_entry.dstSet = descriptorSet; write_entry.dstBinding = binding_being_updated; write_entry.dstArrayElement = dst_array_element; write_entry.descriptorCount = 1; write_entry.descriptorType = create_info.pDescriptorUpdateEntries[i].descriptorType; switch (create_info.pDescriptorUpdateEntries[i].descriptorType) { case VK_DESCRIPTOR_TYPE_SAMPLER: case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER: case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE: case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE: case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT: write_entry.pImageInfo = reinterpret_cast<VkDescriptorImageInfo *>(update_entry); break; case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER: case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER: case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC: case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC: write_entry.pBufferInfo = reinterpret_cast<VkDescriptorBufferInfo *>(update_entry); break; case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER: case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER: write_entry.pTexelBufferView = reinterpret_cast<VkBufferView *>(update_entry); break; case VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT: { VkWriteDescriptorSetInlineUniformBlockEXT *inline_info = &inline_infos[i]; inline_info->sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_INLINE_UNIFORM_BLOCK_EXT; inline_info->pNext = nullptr; inline_info->dataSize = create_info.pDescriptorUpdateEntries[i].descriptorCount; inline_info->pData = update_entry; write_entry.pNext = inline_info; // descriptorCount must match the dataSize member of the VkWriteDescriptorSetInlineUniformBlockEXT structure write_entry.descriptorCount = inline_info->dataSize; // skip the rest of the array, they just represent bytes in the update j = create_info.pDescriptorUpdateEntries[i].descriptorCount; break; } case VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR: { VkWriteDescriptorSetAccelerationStructureKHR *inline_info_khr = &inline_infos_khr[i]; inline_info_khr->sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_ACCELERATION_STRUCTURE_KHR; inline_info_khr->pNext = nullptr; inline_info_khr->accelerationStructureCount = create_info.pDescriptorUpdateEntries[i].descriptorCount; inline_info_khr->pAccelerationStructures = reinterpret_cast<VkAccelerationStructureKHR *>(update_entry); write_entry.pNext = inline_info_khr; break; } case VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_NV: { VkWriteDescriptorSetAccelerationStructureNV *inline_info_nv = &inline_infos_nv[i]; inline_info_nv->sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET_ACCELERATION_STRUCTURE_NV; inline_info_nv->pNext = nullptr; inline_info_nv->accelerationStructureCount = create_info.pDescriptorUpdateEntries[i].descriptorCount; inline_info_nv->pAccelerationStructures = reinterpret_cast<VkAccelerationStructureNV *>(update_entry); write_entry.pNext = inline_info_nv; break; } default: assert(0); break; } dst_array_element++; } } } // These helper functions carry out the validate and record descriptor updates peformed via update templates. They decode // the templatized data and leverage the non-template UpdateDescriptor helper functions. bool CoreChecks::ValidateUpdateDescriptorSetsWithTemplateKHR(VkDescriptorSet descriptorSet, const TEMPLATE_STATE *template_state, const void *pData) const { // Translate the templated update into a normal update for validation... cvdescriptorset::DecodedTemplateUpdate decoded_update(this, descriptorSet, template_state, pData); return ValidateUpdateDescriptorSets(static_cast<uint32_t>(decoded_update.desc_writes.size()), decoded_update.desc_writes.data(), 0, NULL, "vkUpdateDescriptorSetWithTemplate()"); } std::string cvdescriptorset::DescriptorSet::StringifySetAndLayout() const { std::string out; auto layout_handle = layout_->GetDescriptorSetLayout(); if (IsPushDescriptor()) { std::ostringstream str; str << "Push Descriptors defined with " << state_data_->report_data->FormatHandle(layout_handle); out = str.str(); } else { std::ostringstream str; str << state_data_->report_data->FormatHandle(GetSet()) << " allocated with " << state_data_->report_data->FormatHandle(layout_handle); out = str.str(); } return out; }; // Loop through the write updates to validate for a push descriptor set, ignoring dstSet bool CoreChecks::ValidatePushDescriptorsUpdate(const DescriptorSet *push_set, uint32_t write_count, const VkWriteDescriptorSet *p_wds, const char *func_name) const { assert(push_set->IsPushDescriptor()); bool skip = false; for (uint32_t i = 0; i < write_count; i++) { std::string error_code; std::string error_str; if (!ValidateWriteUpdate(push_set, &p_wds[i], func_name, &error_code, &error_str)) { skip |= LogError(push_set->GetDescriptorSetLayout(), error_code, "%s VkWriteDescriptorSet[%u] failed update validation: %s.", func_name, i, error_str.c_str()); } } return skip; } // For the given buffer, verify that its creation parameters are appropriate for the given type // If there's an error, update the error_msg string with details and return false, else return true bool cvdescriptorset::ValidateBufferUsage(debug_report_data *report_data, BUFFER_STATE const *buffer_node, VkDescriptorType type, std::string *error_code, std::string *error_msg) { // Verify that usage bits set correctly for given type auto usage = buffer_node->createInfo.usage; const char *error_usage_bit = nullptr; switch (type) { case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER: if (!(usage & VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT)) { *error_code = "VUID-VkWriteDescriptorSet-descriptorType-00334"; error_usage_bit = "VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT"; } break; case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER: if (!(usage & VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT)) { *error_code = "VUID-VkWriteDescriptorSet-descriptorType-00335"; error_usage_bit = "VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT"; } break; case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER: case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC: if (!(usage & VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT)) { *error_code = "VUID-VkWriteDescriptorSet-descriptorType-00330"; error_usage_bit = "VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT"; } break; case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER: case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC: if (!(usage & VK_BUFFER_USAGE_STORAGE_BUFFER_BIT)) { *error_code = "VUID-VkWriteDescriptorSet-descriptorType-00331"; error_usage_bit = "VK_BUFFER_USAGE_STORAGE_BUFFER_BIT"; } break; default: break; } if (error_usage_bit) { std::stringstream error_str; error_str << "Buffer (" << report_data->FormatHandle(buffer_node->buffer()) << ") with usage mask " << std::hex << std::showbase << usage << " being used for a descriptor update of type " << string_VkDescriptorType(type) << " does not have " << error_usage_bit << " set."; *error_msg = error_str.str(); return false; } return true; } // For buffer descriptor updates, verify the buffer usage and VkDescriptorBufferInfo struct which includes: // 1. buffer is valid // 2. buffer was created with correct usage flags // 3. offset is less than buffer size // 4. range is either VK_WHOLE_SIZE or falls in (0, (buffer size - offset)] // 5. range and offset are within the device's limits // If there's an error, update the error_msg string with details and return false, else return true bool CoreChecks::ValidateBufferUpdate(VkDescriptorBufferInfo const *buffer_info, VkDescriptorType type, const char *func_name, std::string *error_code, std::string *error_msg) const { // First make sure that buffer is valid auto buffer_node = GetBufferState(buffer_info->buffer); // Any invalid buffer should already be caught by object_tracker assert(buffer_node); if (ValidateMemoryIsBoundToBuffer(buffer_node, func_name, "VUID-VkWriteDescriptorSet-descriptorType-00329")) { *error_code = "VUID-VkWriteDescriptorSet-descriptorType-00329"; *error_msg = "No memory bound to buffer."; return false; } // Verify usage bits if (!cvdescriptorset::ValidateBufferUsage(report_data, buffer_node, type, error_code, error_msg)) { // error_msg will have been updated by ValidateBufferUsage() return false; } // offset must be less than buffer size if (buffer_info->offset >= buffer_node->createInfo.size) { *error_code = "VUID-VkDescriptorBufferInfo-offset-00340"; std::stringstream error_str; error_str << "VkDescriptorBufferInfo offset of " << buffer_info->offset << " is greater than or equal to buffer " << report_data->FormatHandle(buffer_node->buffer()) << " size of " << buffer_node->createInfo.size; *error_msg = error_str.str(); return false; } if (buffer_info->range != VK_WHOLE_SIZE) { // Range must be VK_WHOLE_SIZE or > 0 if (!buffer_info->range) { *error_code = "VUID-VkDescriptorBufferInfo-range-00341"; std::stringstream error_str; error_str << "For buffer " << report_data->FormatHandle(buffer_node->buffer()) << " VkDescriptorBufferInfo range is not VK_WHOLE_SIZE and is zero, which is not allowed."; *error_msg = error_str.str(); return false; } // Range must be VK_WHOLE_SIZE or <= (buffer size - offset) if (buffer_info->range > (buffer_node->createInfo.size - buffer_info->offset)) { *error_code = "VUID-VkDescriptorBufferInfo-range-00342"; std::stringstream error_str; error_str << "For buffer " << report_data->FormatHandle(buffer_node->buffer()) << " VkDescriptorBufferInfo range is " << buffer_info->range << " which is greater than buffer size (" << buffer_node->createInfo.size << ") minus requested offset of " << buffer_info->offset; *error_msg = error_str.str(); return false; } } // Check buffer update sizes against device limits const auto &limits = phys_dev_props.limits; if (VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER == type || VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC == type) { auto max_ub_range = limits.maxUniformBufferRange; if (buffer_info->range != VK_WHOLE_SIZE && buffer_info->range > max_ub_range) { *error_code = "VUID-VkWriteDescriptorSet-descriptorType-00332"; std::stringstream error_str; error_str << "For buffer " << report_data->FormatHandle(buffer_node->buffer()) << " VkDescriptorBufferInfo range is " << buffer_info->range << " which is greater than this device's maxUniformBufferRange (" << max_ub_range << ")"; *error_msg = error_str.str(); return false; } else if (buffer_info->range == VK_WHOLE_SIZE && (buffer_node->createInfo.size - buffer_info->offset) > max_ub_range) { *error_code = "VUID-VkWriteDescriptorSet-descriptorType-00332"; std::stringstream error_str; error_str << "For buffer " << report_data->FormatHandle(buffer_node->buffer()) << " VkDescriptorBufferInfo range is VK_WHOLE_SIZE but effective range " << "(" << (buffer_node->createInfo.size - buffer_info->offset) << ") is greater than this device's " << "maxUniformBufferRange (" << max_ub_range << ")"; *error_msg = error_str.str(); return false; } } else if (VK_DESCRIPTOR_TYPE_STORAGE_BUFFER == type || VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC == type) { auto max_sb_range = limits.maxStorageBufferRange; if (buffer_info->range != VK_WHOLE_SIZE && buffer_info->range > max_sb_range) { *error_code = "VUID-VkWriteDescriptorSet-descriptorType-00333"; std::stringstream error_str; error_str << "For buffer " << report_data->FormatHandle(buffer_node->buffer()) << " VkDescriptorBufferInfo range is " << buffer_info->range << " which is greater than this device's maxStorageBufferRange (" << max_sb_range << ")"; *error_msg = error_str.str(); return false; } else if (buffer_info->range == VK_WHOLE_SIZE && (buffer_node->createInfo.size - buffer_info->offset) > max_sb_range) { *error_code = "VUID-VkWriteDescriptorSet-descriptorType-00333"; std::stringstream error_str; error_str << "For buffer " << report_data->FormatHandle(buffer_node->buffer()) << " VkDescriptorBufferInfo range is VK_WHOLE_SIZE but effective range " << "(" << (buffer_node->createInfo.size - buffer_info->offset) << ") is greater than this device's " << "maxStorageBufferRange (" << max_sb_range << ")"; *error_msg = error_str.str(); return false; } } return true; } template <typename T> bool CoreChecks::ValidateAccelerationStructureUpdate(T acc_node, const char *func_name, std::string *error_code, std::string *error_msg) const { // Any invalid acc struct should already be caught by object_tracker assert(acc_node); if (ValidateMemoryIsBoundToAccelerationStructure(acc_node, func_name, kVUIDUndefined)) { *error_code = kVUIDUndefined; *error_msg = "No memory bound to acceleration structure."; return false; } return true; } // Verify that the contents of the update are ok, but don't perform actual update bool CoreChecks::VerifyCopyUpdateContents(const VkCopyDescriptorSet *update, const DescriptorSet *src_set, VkDescriptorType src_type, uint32_t src_index, const DescriptorSet *dst_set, VkDescriptorType dst_type, uint32_t dst_index, const char *func_name, std::string *error_code, std::string *error_msg) const { // Note : Repurposing some Write update error codes here as specific details aren't called out for copy updates like they are // for write updates using DescriptorClass = cvdescriptorset::DescriptorClass; using BufferDescriptor = cvdescriptorset::BufferDescriptor; using ImageDescriptor = cvdescriptorset::ImageDescriptor; using ImageSamplerDescriptor = cvdescriptorset::ImageSamplerDescriptor; using SamplerDescriptor = cvdescriptorset::SamplerDescriptor; using TexelDescriptor = cvdescriptorset::TexelDescriptor; auto device_data = this; if (dst_type == VK_DESCRIPTOR_TYPE_SAMPLER) { for (uint32_t di = 0; di < update->descriptorCount; ++di) { const auto dst_desc = dst_set->GetDescriptorFromGlobalIndex(dst_index + di); if (!dst_desc->updated) continue; if (dst_desc->IsImmutableSampler()) { *error_code = "VUID-VkCopyDescriptorSet-dstBinding-02753"; std::stringstream error_str; error_str << "Attempted copy update to an immutable sampler descriptor."; *error_msg = error_str.str(); return false; } } } switch (src_set->GetDescriptorFromGlobalIndex(src_index)->descriptor_class) { case DescriptorClass::PlainSampler: { for (uint32_t di = 0; di < update->descriptorCount; ++di) { const auto src_desc = src_set->GetDescriptorFromGlobalIndex(src_index + di); if (!src_desc->updated) continue; if (!src_desc->IsImmutableSampler()) { auto update_sampler = static_cast<const SamplerDescriptor *>(src_desc)->GetSampler(); if (!ValidateSampler(update_sampler)) { *error_code = "VUID-VkWriteDescriptorSet-descriptorType-00325"; std::stringstream error_str; error_str << "Attempted copy update to sampler descriptor with invalid sampler: " << report_data->FormatHandle(update_sampler) << "."; *error_msg = error_str.str(); return false; } } else { // TODO : Warn here } } break; } case DescriptorClass::ImageSampler: { for (uint32_t di = 0; di < update->descriptorCount; ++di) { const auto src_desc = src_set->GetDescriptorFromGlobalIndex(src_index + di); if (!src_desc->updated) continue; auto img_samp_desc = static_cast<const ImageSamplerDescriptor *>(src_desc); // First validate sampler if (!img_samp_desc->IsImmutableSampler()) { auto update_sampler = img_samp_desc->GetSampler(); if (!ValidateSampler(update_sampler)) { *error_code = "VUID-VkWriteDescriptorSet-descriptorType-00325"; std::stringstream error_str; error_str << "Attempted copy update to sampler descriptor with invalid sampler: " << report_data->FormatHandle(update_sampler) << "."; *error_msg = error_str.str(); return false; } } else { // TODO : Warn here } // Validate image auto image_view = img_samp_desc->GetImageView(); auto image_layout = img_samp_desc->GetImageLayout(); if (image_view) { if (!ValidateImageUpdate(image_view, image_layout, src_type, func_name, error_code, error_msg)) { std::stringstream error_str; error_str << "Attempted copy update to combined image sampler descriptor failed due to: " << error_msg->c_str(); *error_msg = error_str.str(); return false; } } } break; } case DescriptorClass::Image: { for (uint32_t di = 0; di < update->descriptorCount; ++di) { const auto src_desc = src_set->GetDescriptorFromGlobalIndex(src_index + di); if (!src_desc->updated) continue; auto img_desc = static_cast<const ImageDescriptor *>(src_desc); auto image_view = img_desc->GetImageView(); auto image_layout = img_desc->GetImageLayout(); if (image_view) { if (!ValidateImageUpdate(image_view, image_layout, src_type, func_name, error_code, error_msg)) { std::stringstream error_str; error_str << "Attempted copy update to image descriptor failed due to: " << error_msg->c_str(); *error_msg = error_str.str(); return false; } } } break; } case DescriptorClass::TexelBuffer: { for (uint32_t di = 0; di < update->descriptorCount; ++di) { const auto src_desc = src_set->GetDescriptorFromGlobalIndex(src_index + di); if (!src_desc->updated) continue; auto buffer_view = static_cast<const TexelDescriptor *>(src_desc)->GetBufferView(); if (buffer_view) { auto bv_state = device_data->GetBufferViewState(buffer_view); if (!bv_state) { *error_code = "VUID-VkWriteDescriptorSet-descriptorType-02994"; std::stringstream error_str; error_str << "Attempted copy update to texel buffer descriptor with invalid buffer view: " << report_data->FormatHandle(buffer_view); *error_msg = error_str.str(); return false; } auto buffer = bv_state->create_info.buffer; if (!cvdescriptorset::ValidateBufferUsage(report_data, GetBufferState(buffer), src_type, error_code, error_msg)) { std::stringstream error_str; error_str << "Attempted copy update to texel buffer descriptor failed due to: " << error_msg->c_str(); *error_msg = error_str.str(); return false; } } } break; } case DescriptorClass::GeneralBuffer: { for (uint32_t di = 0; di < update->descriptorCount; ++di) { const auto src_desc = src_set->GetDescriptorFromGlobalIndex(src_index + di); if (!src_desc->updated) continue; auto buffer = static_cast<const BufferDescriptor *>(src_desc)->GetBuffer(); if (buffer) { if (!cvdescriptorset::ValidateBufferUsage(report_data, GetBufferState(buffer), src_type, error_code, error_msg)) { std::stringstream error_str; error_str << "Attempted copy update to buffer descriptor failed due to: " << error_msg->c_str(); *error_msg = error_str.str(); return false; } } } break; } case DescriptorClass::InlineUniform: case DescriptorClass::AccelerationStructure: case DescriptorClass::Mutable: break; default: assert(0); // We've already verified update type so should never get here break; } // All checks passed so update contents are good return true; } // Verify that the state at allocate time is correct, but don't actually allocate the sets yet bool CoreChecks::ValidateAllocateDescriptorSets(const VkDescriptorSetAllocateInfo *p_alloc_info, const cvdescriptorset::AllocateDescriptorSetsData *ds_data) const { bool skip = false; auto pool_state = GetDescriptorPoolState(p_alloc_info->descriptorPool); for (uint32_t i = 0; i < p_alloc_info->descriptorSetCount; i++) { auto layout = GetDescriptorSetLayoutShared(p_alloc_info->pSetLayouts[i]); if (layout) { // nullptr layout indicates no valid layout handle for this device, validated/logged in object_tracker if (layout->IsPushDescriptor()) { skip |= LogError(p_alloc_info->pSetLayouts[i], "VUID-VkDescriptorSetAllocateInfo-pSetLayouts-00308", "%s specified at pSetLayouts[%" PRIu32 "] in vkAllocateDescriptorSets() was created with invalid flag %s set.", report_data->FormatHandle(p_alloc_info->pSetLayouts[i]).c_str(), i, "VK_DESCRIPTOR_SET_LAYOUT_CREATE_PUSH_DESCRIPTOR_BIT_KHR"); } if (layout->GetCreateFlags() & VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT && !(pool_state->createInfo.flags & VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT)) { skip |= LogError( device, "VUID-VkDescriptorSetAllocateInfo-pSetLayouts-03044", "vkAllocateDescriptorSets(): Descriptor set layout create flags and pool create flags mismatch for index (%d)", i); } if (layout->GetCreateFlags() & VK_DESCRIPTOR_SET_LAYOUT_CREATE_HOST_ONLY_POOL_BIT_VALVE && !(pool_state->createInfo.flags & VK_DESCRIPTOR_POOL_CREATE_HOST_ONLY_BIT_VALVE)) { skip |= LogError(device, "VUID-VkDescriptorSetAllocateInfo-pSetLayouts-04610", "vkAllocateDescriptorSets(): pSetLayouts[%d].flags contain " "VK_DESCRIPTOR_SET_LAYOUT_CREATE_HOST_ONLY_POOL_BIT_VALVE bit, but the pool was not created " "with the VK_DESCRIPTOR_POOL_CREATE_HOST_ONLY_BIT_VALVE bit.", i); } } } if (!device_extensions.vk_khr_maintenance1) { // Track number of descriptorSets allowable in this pool if (pool_state->availableSets < p_alloc_info->descriptorSetCount) { skip |= LogError(pool_state->pool, "VUID-VkDescriptorSetAllocateInfo-descriptorSetCount-00306", "vkAllocateDescriptorSets(): Unable to allocate %u descriptorSets from %s" ". This pool only has %d descriptorSets remaining.", p_alloc_info->descriptorSetCount, report_data->FormatHandle(pool_state->pool).c_str(), pool_state->availableSets); } // Determine whether descriptor counts are satisfiable for (auto it = ds_data->required_descriptors_by_type.begin(); it != ds_data->required_descriptors_by_type.end(); ++it) { auto count_iter = pool_state->availableDescriptorTypeCount.find(it->first); uint32_t available_count = (count_iter != pool_state->availableDescriptorTypeCount.end()) ? count_iter->second : 0; if (ds_data->required_descriptors_by_type.at(it->first) > available_count) { skip |= LogError(pool_state->pool, "VUID-VkDescriptorSetAllocateInfo-descriptorPool-00307", "vkAllocateDescriptorSets(): Unable to allocate %u descriptors of type %s from %s" ". This pool only has %d descriptors of this type remaining.", ds_data->required_descriptors_by_type.at(it->first), string_VkDescriptorType(VkDescriptorType(it->first)), report_data->FormatHandle(pool_state->pool).c_str(), available_count); } } } const auto *count_allocate_info = LvlFindInChain<VkDescriptorSetVariableDescriptorCountAllocateInfo>(p_alloc_info->pNext); if (count_allocate_info) { if (count_allocate_info->descriptorSetCount != 0 && count_allocate_info->descriptorSetCount != p_alloc_info->descriptorSetCount) { skip |= LogError(device, "VUID-VkDescriptorSetVariableDescriptorCountAllocateInfo-descriptorSetCount-03045", "vkAllocateDescriptorSets(): VkDescriptorSetAllocateInfo::descriptorSetCount (%d) != " "VkDescriptorSetVariableDescriptorCountAllocateInfo::descriptorSetCount (%d)", p_alloc_info->descriptorSetCount, count_allocate_info->descriptorSetCount); } if (count_allocate_info->descriptorSetCount == p_alloc_info->descriptorSetCount) { for (uint32_t i = 0; i < p_alloc_info->descriptorSetCount; i++) { auto layout = GetDescriptorSetLayoutShared(p_alloc_info->pSetLayouts[i]); if (count_allocate_info->pDescriptorCounts[i] > layout->GetDescriptorCountFromBinding(layout->GetMaxBinding())) { skip |= LogError(device, "VUID-VkDescriptorSetVariableDescriptorCountAllocateInfo-pSetLayouts-03046", "vkAllocateDescriptorSets(): pDescriptorCounts[%d] = (%d), binding's descriptorCount = (%d)", i, count_allocate_info->pDescriptorCounts[i], layout->GetDescriptorCountFromBinding(layout->GetMaxBinding())); } } } } return skip; } const BindingReqMap &cvdescriptorset::PrefilterBindRequestMap::FilteredMap(const CMD_BUFFER_STATE &cb_state, const PIPELINE_STATE &pipeline) { if (IsManyDescriptors()) { filtered_map_.reset(new BindingReqMap); descriptor_set_.FilterBindingReqs(cb_state, pipeline, orig_map_, filtered_map_.get()); return *filtered_map_; } return orig_map_; } // Starting at offset descriptor of given binding, parse over update_count // descriptor updates and verify that for any binding boundaries that are crossed, the next binding(s) are all consistent // Consistency means that their type, stage flags, and whether or not they use immutable samplers matches // If so, return true. If not, fill in error_msg and return false bool cvdescriptorset::VerifyUpdateConsistency(debug_report_data *report_data, DescriptorSetLayout::ConstBindingIterator current_binding, uint32_t offset, uint32_t update_count, const char *type, const VkDescriptorSet set, std::string *error_msg) { bool pass = true; // Verify consecutive bindings match (if needed) auto orig_binding = current_binding; while (pass && update_count) { // First, it's legal to offset beyond your own binding so handle that case if (offset > 0) { const auto &index_range = current_binding.GetGlobalIndexRange(); // index_range.start + offset is which descriptor is needed to update. If it > index_range.end, it means the descriptor // isn't in this binding, maybe in next binding. if ((index_range.start + offset) >= index_range.end) { // Advance to next binding, decrement offset by binding size offset -= current_binding.GetDescriptorCount(); ++current_binding; // Verify next consecutive binding matches type, stage flags & immutable sampler use and if AtEnd if (!orig_binding.IsConsistent(current_binding)) { pass = false; } continue; } } update_count -= std::min(update_count, current_binding.GetDescriptorCount() - offset); if (update_count) { // Starting offset is beyond the current binding. Check consistency, update counters and advance to the next binding, // looking for the start point. All bindings (even those skipped) must be consistent with the update and with the // original binding. offset = 0; ++current_binding; // Verify next consecutive binding matches type, stage flags & immutable sampler use and if AtEnd if (!orig_binding.IsConsistent(current_binding)) { pass = false; } } } if (!pass) { std::stringstream error_str; error_str << "Attempting " << type; if (current_binding.Layout()->IsPushDescriptor()) { error_str << " push descriptors"; } else { error_str << " descriptor set " << report_data->FormatHandle(set); } error_str << " binding #" << orig_binding.Binding() << " with #" << update_count << " descriptors being updated but this update oversteps the bounds of this binding and the next binding is " "not consistent with current binding"; // Get what was not consistent in IsConsistent() as a more detailed error message const auto *binding_ci = orig_binding.GetDescriptorSetLayoutBindingPtr(); const auto *other_binding_ci = current_binding.GetDescriptorSetLayoutBindingPtr(); if (binding_ci == nullptr || other_binding_ci == nullptr) { error_str << " (No two valid DescriptorSetLayoutBinding to compare)"; } else if (binding_ci->descriptorType != other_binding_ci->descriptorType) { error_str << " (" << string_VkDescriptorType(binding_ci->descriptorType) << " != " << string_VkDescriptorType(other_binding_ci->descriptorType) << ")"; } else if (binding_ci->stageFlags != other_binding_ci->stageFlags) { error_str << " (" << string_VkShaderStageFlags(binding_ci->stageFlags) << " != " << string_VkShaderStageFlags(other_binding_ci->stageFlags) << ")"; } else if (!hash_util::similar_for_nullity(binding_ci->pImmutableSamplers, other_binding_ci->pImmutableSamplers)) { error_str << " (pImmutableSamplers don't match)"; } else if (orig_binding.GetDescriptorBindingFlags() != current_binding.GetDescriptorBindingFlags()) { error_str << " (" << string_VkDescriptorBindingFlags(orig_binding.GetDescriptorBindingFlags()) << " != " << string_VkDescriptorBindingFlags(current_binding.GetDescriptorBindingFlags()) << ")"; } error_str << " so this update is invalid"; *error_msg = error_str.str(); } return pass; } // Validate the state for a given write update but don't actually perform the update // If an error would occur for this update, return false and fill in details in error_msg string bool CoreChecks::ValidateWriteUpdate(const DescriptorSet *dest_set, const VkWriteDescriptorSet *update, const char *func_name, std::string *error_code, std::string *error_msg) const { const auto dest_layout = dest_set->GetLayout().get(); // Verify dst layout still valid if (dest_layout->Destroyed()) { *error_code = "VUID-VkWriteDescriptorSet-dstSet-00320"; std::ostringstream str; str << "Cannot call " << func_name << " to perform write update on " << dest_set->StringifySetAndLayout() << " which has been destroyed"; *error_msg = str.str(); return false; } // Verify dst binding exists if (!dest_layout->HasBinding(update->dstBinding)) { *error_code = "VUID-VkWriteDescriptorSet-dstBinding-00315"; std::stringstream error_str; error_str << dest_set->StringifySetAndLayout() << " does not have binding " << update->dstBinding; *error_msg = error_str.str(); return false; } DescriptorSetLayout::ConstBindingIterator dest(dest_layout, update->dstBinding); // Make sure binding isn't empty if (0 == dest.GetDescriptorCount()) { *error_code = "VUID-VkWriteDescriptorSet-dstBinding-00316"; std::stringstream error_str; error_str << dest_set->StringifySetAndLayout() << " cannot updated binding " << update->dstBinding << " that has 0 descriptors"; *error_msg = error_str.str(); return false; } // Verify idle ds if (dest_set->InUse() && !(dest.GetDescriptorBindingFlags() & (VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT | VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT))) { // TODO : Re-using Free Idle error code, need write update idle error code *error_code = "VUID-vkFreeDescriptorSets-pDescriptorSets-00309"; std::stringstream error_str; error_str << "Cannot call " << func_name << " to perform write update on " << dest_set->StringifySetAndLayout() << " that is in use by a command buffer"; *error_msg = error_str.str(); return false; } // We know that binding is valid, verify update and do update on each descriptor auto start_idx = dest.GetGlobalIndexRange().start + update->dstArrayElement; auto type = dest.GetType(); if ((type != VK_DESCRIPTOR_TYPE_MUTABLE_VALVE) && (type != update->descriptorType)) { *error_code = "VUID-VkWriteDescriptorSet-descriptorType-00319"; std::stringstream error_str; error_str << "Attempting write update to " << dest_set->StringifySetAndLayout() << " binding #" << update->dstBinding << " with type " << string_VkDescriptorType(type) << " but update type is " << string_VkDescriptorType(update->descriptorType); *error_msg = error_str.str(); return false; } if (type == VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT) { if ((update->dstArrayElement % 4) != 0) { *error_code = "VUID-VkWriteDescriptorSet-descriptorType-02219"; std::stringstream error_str; error_str << "Attempting write update to " << dest_set->StringifySetAndLayout() << " binding #" << update->dstBinding << " with " << "dstArrayElement " << update->dstArrayElement << " not a multiple of 4"; *error_msg = error_str.str(); return false; } if ((update->descriptorCount % 4) != 0) { *error_code = "VUID-VkWriteDescriptorSet-descriptorType-02220"; std::stringstream error_str; error_str << "Attempting write update to " << dest_set->StringifySetAndLayout() << " binding #" << update->dstBinding << " with " << "descriptorCount " << update->descriptorCount << " not a multiple of 4"; *error_msg = error_str.str(); return false; } const auto *write_inline_info = LvlFindInChain<VkWriteDescriptorSetInlineUniformBlockEXT>(update->pNext); if (!write_inline_info || write_inline_info->dataSize != update->descriptorCount) { *error_code = "VUID-VkWriteDescriptorSet-descriptorType-02221"; std::stringstream error_str; if (!write_inline_info) { error_str << "Attempting write update to " << dest_set->StringifySetAndLayout() << " binding #" << update->dstBinding << " with " << "VkWriteDescriptorSetInlineUniformBlockEXT missing"; } else { error_str << "Attempting write update to " << dest_set->StringifySetAndLayout() << " binding #" << update->dstBinding << " with " << "VkWriteDescriptorSetInlineUniformBlockEXT dataSize " << write_inline_info->dataSize << " not equal to " << "VkWriteDescriptorSet descriptorCount " << update->descriptorCount; } *error_msg = error_str.str(); return false; } // This error is probably unreachable due to the previous two errors if (write_inline_info && (write_inline_info->dataSize % 4) != 0) { *error_code = "VUID-VkWriteDescriptorSetInlineUniformBlockEXT-dataSize-02222"; std::stringstream error_str; error_str << "Attempting write update to " << dest_set->StringifySetAndLayout() << " binding #" << update->dstBinding << " with " << "VkWriteDescriptorSetInlineUniformBlockEXT dataSize " << write_inline_info->dataSize << " not a multiple of 4"; *error_msg = error_str.str(); return false; } } // Verify all bindings update share identical properties across all items if (update->descriptorCount > 0) { // Save first binding information and error if something different is found DescriptorSetLayout::ConstBindingIterator current_binding(dest_layout, update->dstBinding); VkShaderStageFlags stage_flags = current_binding.GetStageFlags(); VkDescriptorType descriptor_type = current_binding.GetType(); bool immutable_samplers = (current_binding.GetImmutableSamplerPtr() == nullptr); uint32_t dst_array_element = update->dstArrayElement; for (uint32_t i = 0; i < update->descriptorCount;) { if (current_binding.AtEnd() == true) { break; // prevents setting error here if bindings don't exist } // Check for consistent stageFlags and descriptorType if ((current_binding.GetStageFlags() != stage_flags) || (current_binding.GetType() != descriptor_type)) { *error_code = "VUID-VkWriteDescriptorSet-descriptorCount-00317"; std::stringstream error_str; error_str << "Attempting write update to " << dest_set->StringifySetAndLayout() << " binding index #" << current_binding.GetIndex() << " (" << i << " from dstBinding offset)" << " with a different stageFlag and/or descriptorType from previous bindings." << " All bindings must have consecutive stageFlag and/or descriptorType across a VkWriteDescriptorSet"; *error_msg = error_str.str(); return false; } // Check if all immutableSamplers or not if ((current_binding.GetImmutableSamplerPtr() == nullptr) != immutable_samplers) { *error_code = "VUID-VkWriteDescriptorSet-descriptorCount-00318"; std::stringstream error_str; error_str << "Attempting write update to " << dest_set->StringifySetAndLayout() << " binding index #" << current_binding.GetIndex() << " (" << i << " from dstBinding offset)" << " with a different usage of immutable samplers from previous bindings." << " All bindings must have all or none usage of immutable samplers across a VkWriteDescriptorSet"; *error_msg = error_str.str(); return false; } // Skip the remaining descriptors for this binding, and move to the next binding i += (current_binding.GetDescriptorCount() - dst_array_element); dst_array_element = 0; ++current_binding; } } // Verify consecutive bindings match (if needed) if (!VerifyUpdateConsistency(report_data, DescriptorSetLayout::ConstBindingIterator(dest_layout, update->dstBinding), update->dstArrayElement, update->descriptorCount, "write update to", dest_set->GetSet(), error_msg)) { *error_code = "VUID-VkWriteDescriptorSet-dstArrayElement-00321"; return false; } // Verify write to variable descriptor if (dest_set->IsVariableDescriptorCount(update->dstBinding)) { if ((update->dstArrayElement + update->descriptorCount) > dest_set->GetVariableDescriptorCount()) { std::stringstream error_str; *error_code = "VUID-VkWriteDescriptorSet-dstArrayElement-00321"; error_str << "Attempting write update to " << dest_set->StringifySetAndLayout() << " binding index #" << update->dstBinding << " array element " << update->dstArrayElement << " with " << update->descriptorCount << " writes but variable descriptor size is " << dest_set->GetVariableDescriptorCount(); *error_msg = error_str.str(); return false; } } // Update is within bounds and consistent so last step is to validate update contents if (!VerifyWriteUpdateContents(dest_set, update, start_idx, func_name, error_code, error_msg)) { std::stringstream error_str; error_str << "Write update to " << dest_set->StringifySetAndLayout() << " binding #" << update->dstBinding << " failed with error message: " << error_msg->c_str(); *error_msg = error_str.str(); return false; } // All checks passed, update is clean return true; } // Verify that the contents of the update are ok, but don't perform actual update bool CoreChecks::VerifyWriteUpdateContents(const DescriptorSet *dest_set, const VkWriteDescriptorSet *update, const uint32_t index, const char *func_name, std::string *error_code, std::string *error_msg) const { using ImageSamplerDescriptor = cvdescriptorset::ImageSamplerDescriptor; using Descriptor = cvdescriptorset::Descriptor; switch (update->descriptorType) { case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER: { for (uint32_t di = 0; di < update->descriptorCount; ++di) { // Validate image auto image_view = update->pImageInfo[di].imageView; auto image_layout = update->pImageInfo[di].imageLayout; auto sampler = update->pImageInfo[di].sampler; auto iv_state = GetImageViewState(image_view); const ImageSamplerDescriptor *desc = (const ImageSamplerDescriptor *)dest_set->GetDescriptorFromGlobalIndex(index + di); if (image_view) { auto image_state = iv_state->image_state.get(); if (!ValidateImageUpdate(image_view, image_layout, update->descriptorType, func_name, error_code, error_msg)) { std::stringstream error_str; error_str << "Attempted write update to combined image sampler descriptor failed due to: " << error_msg->c_str(); *error_msg = error_str.str(); return false; } if (device_extensions.vk_khr_sampler_ycbcr_conversion) { if (desc->IsImmutableSampler()) { auto sampler_state = GetSamplerState(desc->GetSampler()); if (iv_state && sampler_state) { if (iv_state->samplerConversion != sampler_state->samplerConversion) { *error_code = "VUID-VkWriteDescriptorSet-descriptorType-01948"; std::stringstream error_str; error_str << "Attempted write update to combined image sampler and image view and sampler ycbcr " "conversions are not identical, sampler: " << report_data->FormatHandle(desc->GetSampler()) << " image view: " << report_data->FormatHandle(iv_state->image_view()) << "."; *error_msg = error_str.str(); return false; } } } else { if (iv_state && (iv_state->samplerConversion != VK_NULL_HANDLE)) { *error_code = "VUID-VkWriteDescriptorSet-descriptorType-02738"; std::stringstream error_str; error_str << "Because dstSet (" << report_data->FormatHandle(update->dstSet) << ") is bound to image view (" << report_data->FormatHandle(iv_state->image_view()) << ") that includes a YCBCR conversion, it must have been allocated with a layout that " "includes an immutable sampler."; *error_msg = error_str.str(); return false; } } } // If there is an immutable sampler then |sampler| isn't used, so the following VU does not apply. if (sampler && !desc->IsImmutableSampler() && FormatIsMultiplane(image_state->createInfo.format)) { // multiplane formats must be created with mutable format bit if (0 == (image_state->createInfo.flags & VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT)) { *error_code = "VUID-VkDescriptorImageInfo-sampler-01564"; std::stringstream error_str; error_str << "image " << report_data->FormatHandle(image_state->image()) << " combined image sampler is a multi-planar " << "format and was not was not created with the VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT"; *error_msg = error_str.str(); return false; } // image view need aspect mask for only the planes supported of format VkImageAspectFlags legal_aspect_flags = (VK_IMAGE_ASPECT_PLANE_0_BIT | VK_IMAGE_ASPECT_PLANE_1_BIT); legal_aspect_flags |= (FormatPlaneCount(image_state->createInfo.format) == 3) ? VK_IMAGE_ASPECT_PLANE_2_BIT : 0; if (0 != (iv_state->create_info.subresourceRange.aspectMask & (~legal_aspect_flags))) { *error_code = "VUID-VkDescriptorImageInfo-sampler-01564"; std::stringstream error_str; error_str << "image " << report_data->FormatHandle(image_state->image()) << " combined image sampler is a multi-planar " << "format and " << report_data->FormatHandle(iv_state->image_view()) << " aspectMask must only include " << string_VkImageAspectFlags(legal_aspect_flags); *error_msg = error_str.str(); return false; } } // Verify portability auto sampler_state = GetSamplerState(sampler); if (sampler_state) { if (ExtEnabled::kNotEnabled != device_extensions.vk_khr_portability_subset) { if ((VK_FALSE == enabled_features.portability_subset_features.mutableComparisonSamplers) && (VK_FALSE != sampler_state->createInfo.compareEnable)) { LogError(device, "VUID-VkDescriptorImageInfo-mutableComparisonSamplers-04450", "%s (portability error): sampler comparison not available.", func_name); } } } } } } // Fall through case VK_DESCRIPTOR_TYPE_SAMPLER: { for (uint32_t di = 0; di < update->descriptorCount; ++di) { const auto *desc = static_cast<const Descriptor *>(dest_set->GetDescriptorFromGlobalIndex(index + di)); if (!desc->IsImmutableSampler()) { if (!ValidateSampler(update->pImageInfo[di].sampler)) { *error_code = "VUID-VkWriteDescriptorSet-descriptorType-00325"; std::stringstream error_str; error_str << "Attempted write update to sampler descriptor with invalid sampler: " << report_data->FormatHandle(update->pImageInfo[di].sampler) << "."; *error_msg = error_str.str(); return false; } } else if (update->descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER) { *error_code = "VUID-VkWriteDescriptorSet-descriptorType-02752"; std::stringstream error_str; error_str << "Attempted write update to an immutable sampler descriptor."; *error_msg = error_str.str(); return false; } } break; } case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE: case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT: case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE: { for (uint32_t di = 0; di < update->descriptorCount; ++di) { auto image_view = update->pImageInfo[di].imageView; auto image_layout = update->pImageInfo[di].imageLayout; if (image_view) { if (!ValidateImageUpdate(image_view, image_layout, update->descriptorType, func_name, error_code, error_msg)) { std::stringstream error_str; error_str << "Attempted write update to image descriptor failed due to: " << error_msg->c_str(); *error_msg = error_str.str(); return false; } } } break; } case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER: case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER: { for (uint32_t di = 0; di < update->descriptorCount; ++di) { auto buffer_view = update->pTexelBufferView[di]; if (buffer_view) { auto bv_state = GetBufferViewState(buffer_view); if (!bv_state) { *error_code = "VUID-VkWriteDescriptorSet-descriptorType-02994"; std::stringstream error_str; error_str << "Attempted write update to texel buffer descriptor with invalid buffer view: " << report_data->FormatHandle(buffer_view); *error_msg = error_str.str(); return false; } auto buffer = bv_state->create_info.buffer; auto buffer_state = GetBufferState(buffer); // Verify that buffer underlying the view hasn't been destroyed prematurely if (!buffer_state) { *error_code = "VUID-VkWriteDescriptorSet-descriptorType-02994"; std::stringstream error_str; error_str << "Attempted write update to texel buffer descriptor failed because underlying buffer (" << report_data->FormatHandle(buffer) << ") has been destroyed: " << error_msg->c_str(); *error_msg = error_str.str(); return false; } else if (!cvdescriptorset::ValidateBufferUsage(report_data, buffer_state, update->descriptorType, error_code, error_msg)) { std::stringstream error_str; error_str << "Attempted write update to texel buffer descriptor failed due to: " << error_msg->c_str(); *error_msg = error_str.str(); return false; } } } break; } case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER: case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC: case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER: case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC: { for (uint32_t di = 0; di < update->descriptorCount; ++di) { if (update->pBufferInfo[di].buffer) { if (!ValidateBufferUpdate(update->pBufferInfo + di, update->descriptorType, func_name, error_code, error_msg)) { std::stringstream error_str; error_str << "Attempted write update to buffer descriptor failed due to: " << error_msg->c_str(); *error_msg = error_str.str(); return false; } } } break; } case VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT: break; case VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_NV: { const auto *acc_info = LvlFindInChain<VkWriteDescriptorSetAccelerationStructureNV>(update->pNext); for (uint32_t di = 0; di < update->descriptorCount; ++di) { if (!ValidateAccelerationStructureUpdate(GetAccelerationStructureStateNV(acc_info->pAccelerationStructures[di]), func_name, error_code, error_msg)) { std::stringstream error_str; error_str << "Attempted write update to acceleration structure descriptor failed due to: " << error_msg->c_str(); *error_msg = error_str.str(); return false; } } } break; // KHR acceleration structures don't require memory to be bound manually to them. case VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR: break; default: assert(0); // We've already verified update type so should never get here break; } // All checks passed so update contents are good return true; }
1
18,148
Looks like this is failing to compile on Windows (VS 2015 I think).
KhronosGroup-Vulkan-ValidationLayers
cpp
@@ -91,6 +91,15 @@ func (q *Query) Limit(n int) *Query { return q } +// BeforeQuery takes a callback function that will be called before the Query is +// executed to the underlying provider's query functionality. The callback takes +// a parameter, asFunc, that converts its argument to provider-specific types. +// See https://godoc.org/gocloud.dev#hdr-As for background information. +func (q *Query) BeforeQuery(beforeQuery func(asFunc func(interface{}) bool) error) *Query { + q.dq.BeforeQuery = beforeQuery + return q +} + // Get returns an iterator for retrieving the documents specified by the query. If // field paths are provided, only those paths are set in the resulting documents. //
1
// Copyright 2019 The Go Cloud Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package docstore import ( "context" "io" "reflect" "gocloud.dev/internal/docstore/driver" "gocloud.dev/internal/gcerr" ) // Query represents a query over a collection. type Query struct { coll *Collection dq *driver.Query err error } // Query creates a new Query over the collection. func (c *Collection) Query() *Query { return &Query{coll: c, dq: &driver.Query{}} } // Where expresses a condition on the query. // Valid ops are: "=", ">", "<", ">=", "<=". func (q *Query) Where(fieldpath, op string, value interface{}) *Query { fp, err := parseFieldPath(FieldPath(fieldpath)) if err != nil { q.err = err } if !validOp[op] { q.err = gcerr.Newf(gcerr.InvalidArgument, nil, "invalid filter operator: %q. Use one of: =, >, <, >=, <=", op) } if !validFilterValue(value) { q.err = gcerr.Newf(gcerr.InvalidArgument, nil, "invalid filter value: %v", value) } if q.err != nil { return q } q.dq.Filters = append(q.dq.Filters, driver.Filter{ FieldPath: fp, Op: op, Value: value, }) return q } var validOp = map[string]bool{ "=": true, ">": true, "<": true, ">=": true, "<=": true, } func validFilterValue(v interface{}) bool { if v == nil { return false } switch reflect.TypeOf(v).Kind() { case reflect.String: return true case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return true case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: return true case reflect.Float32, reflect.Float64: return true default: return false } } // Limit will limit the results to at most n documents. func (q *Query) Limit(n int) *Query { q.dq.Limit = n return q } // Get returns an iterator for retrieving the documents specified by the query. If // field paths are provided, only those paths are set in the resulting documents. // // Call Stop on the iterator when finished. func (q *Query) Get(ctx context.Context, fps ...FieldPath) *DocumentIterator { if err := q.init(fps); err != nil { return &DocumentIterator{err: err} } it, err := q.coll.driver.RunGetQuery(ctx, q.dq) return &DocumentIterator{iter: it, err: err} } func (q *Query) init(fps []FieldPath) error { if q.err != nil { return q.err } if q.dq.FieldPaths == nil { for _, fp := range fps { fp, err := parseFieldPath(fp) if err != nil { q.err = err return err } q.dq.FieldPaths = append(q.dq.FieldPaths, fp) } } return nil } // DocumentIterator iterates over documents. // // Always call Stop on the iterator. type DocumentIterator struct { iter driver.DocumentIterator err error } // Next stores the next document in dst. It returns io.EOF if there are no more // documents. // Once Next returns an error, it will always return the same error. func (it *DocumentIterator) Next(ctx context.Context, dst Document) error { if it.err != nil { return it.err } ddoc, err := driver.NewDocument(dst) if err != nil { it.err = err return err } it.err = it.iter.Next(ctx, ddoc) return it.err } // Stop stops the iterator. Calling Next on a stopped iterator will return io.EOF, or // the error that Next previously returned. func (it *DocumentIterator) Stop() { if it.err != nil { return } it.err = io.EOF it.iter.Stop() } // Plan describes how the query would be executed if its Get method were called with // the given field paths. Plan uses only information available to the client, so it // cannot know whether a service uses indexes or scans internally. func (q *Query) Plan(fps ...FieldPath) (string, error) { if err := q.init(fps); err != nil { return "", err } return q.coll.driver.QueryPlan(q.dq) }
1
17,003
nit: call the arg something simple like `f` to avoid repeating "beforeQuery".
google-go-cloud
go
@@ -18,8 +18,15 @@ package auth import ( "context" + + "github.com/libopenstorage/openstorage/pkg/correlation" ) +func init() { + correlation.RegisterComponent("auth") + correlation.RegisterGlobalHook() +} + const ( systemGuestRoleName = "system.guest" )
1
/* Package auth can be used for authentication and authorization Copyright 2018 Portworx Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package auth import ( "context" ) const ( systemGuestRoleName = "system.guest" ) var ( systemTokenInst TokenGenerator = &noauth{} // Inst returns the instance of system token manager. // This function can be overridden for testing purposes InitSystemTokenManager = func(tg TokenGenerator) { systemTokenInst = tg } // SystemTokenManagerInst returns the systemTokenManager instance SystemTokenManagerInst = func() TokenGenerator { return systemTokenInst } ) // Authenticator interface validates and extracts the claims from a raw token type Authenticator interface { // AuthenticateToken validates the token and returns the claims AuthenticateToken(context.Context, string) (*Claims, error) // Username returns the unique id according to the configuration. Default // it will return the value for "sub" in the token claims, but it can be // configured to return the email or name as the unique id. Username(*Claims) string } // Enabled returns whether or not auth is enabled. func Enabled() bool { return len(systemTokenInst.Issuer()) != 0 }
1
8,908
do you think this should be `osd/auth` as a pkg to make it more unique and void conflicts with other `auth` packages?
libopenstorage-openstorage
go
@@ -36,10 +36,12 @@ namespace Microsoft.DotNet.Build.Tasks public bool DebugOnly { get; set; } + [Output] + public string Message { get; set; } + public override bool Execute() { - bool result = true; - + Message = ""; try { using (_resxReader = new ResXResourceReader(ResxFilePath))
1
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Resources; using System.Text; namespace Microsoft.DotNet.Build.Tasks { public class GenerateResourcesCode : Task { private TargetLanguage _targetLanguage = TargetLanguage.CSharp; private ResXResourceReader _resxReader; private StreamWriter _targetStream; private string _intermediateFile; private StringBuilder _debugCode = new StringBuilder(); private Dictionary<string, int> _keys; [Required] public string ResxFilePath { get; set; } [Required] public string IntermediateFilePath { get; set; } [Required] public string OutputSourceFilePath { get; set; } [Required] public string AssemblyName { get; set; } public bool DebugOnly { get; set; } public override bool Execute() { bool result = true; try { using (_resxReader = new ResXResourceReader(ResxFilePath)) { _intermediateFile = IntermediateFilePath + ".temp"; using (_targetStream = File.CreateText(_intermediateFile)) { if (String.Equals(Path.GetExtension(OutputSourceFilePath), ".vb", StringComparison.OrdinalIgnoreCase)) { _targetLanguage = TargetLanguage.VB; } _keys = new Dictionary<string, int>(); WriteClassHeader(); RunOnResFile(); WriteDebugCode(); WriteClassEnd(); } } ProcessTargetFile(); } catch (Exception e) { Log.LogMessage(e.Message); if (e is System.UnauthorizedAccessException) { Log.LogMessage("The generated {0} file needs to be updated but the file is read-only.", OutputSourceFilePath); } result = false; // fail the task } if (result) { // don't fail the task if this operation failed as we just updating intermediate file and the task already did the needed functionality of generating the code try { File.Move(_intermediateFile, IntermediateFilePath); } catch { } } return result; } private void WriteClassHeader() { string commentPrefix = _targetLanguage == TargetLanguage.CSharp ? "// " : "' "; _targetStream.WriteLine(commentPrefix + "Do not edit this file manually it is auto-generated during the build based on the .resx file for this project."); if (_targetLanguage == TargetLanguage.CSharp) { _targetStream.WriteLine("namespace System"); _targetStream.WriteLine("{"); _targetStream.WriteLine(" internal static partial class SR"); _targetStream.WriteLine(" {"); _targetStream.WriteLine("#pragma warning disable 0414"); _targetStream.WriteLine(" private const string s_resourcesName = \"{0}\"; // assembly Name + .resources", AssemblyName + ".resources"); _targetStream.WriteLine("#pragma warning restore 0414"); _targetStream.WriteLine(""); if (!DebugOnly) _targetStream.WriteLine("#if !DEBUGRESOURCES"); } else { _targetStream.WriteLine("Namespace System"); _targetStream.WriteLine(" Friend Partial Class SR"); _targetStream.WriteLine(" "); _targetStream.WriteLine(" Private Const s_resourcesName As String = \"{0}\" ' assembly Name + .resources", AssemblyName + ".resources"); _targetStream.WriteLine(""); if (!DebugOnly) _targetStream.WriteLine("#If Not DEBUGRESOURCES Then"); } } private void RunOnResFile() { IDictionaryEnumerator dict = _resxReader.GetEnumerator(); while (dict.MoveNext()) { StoreValues((string)dict.Key, (string)dict.Value); } } private void StoreValues(string leftPart, string rightPart) { int value; if (_keys.TryGetValue(leftPart, out value)) { return; } _keys[leftPart] = 0; StringBuilder sb = new StringBuilder(rightPart.Length); for (var i = 0; i < rightPart.Length; i++) { // duplicate '"' for VB and C# if (rightPart[i] == '\"' && (_targetLanguage == TargetLanguage.VB || _targetLanguage == TargetLanguage.CSharp)) { sb.Append("\""); } sb.Append(rightPart[i]); } if (_targetLanguage == TargetLanguage.CSharp) { _debugCode.AppendFormat(" internal static string {0} {2}\n get {2} return SR.GetResourceString(\"{0}\", @\"{1}\"); {3}\n {3}\n", leftPart, sb.ToString(), "{", "}"); } else { _debugCode.AppendFormat(" Friend Shared ReadOnly Property {0} As String\n Get\n Return SR.GetResourceString(\"{0}\", \"{1}\")\n End Get\n End Property\n", leftPart, sb.ToString()); } if (!DebugOnly) { if (_targetLanguage == TargetLanguage.CSharp) { _targetStream.WriteLine(" internal static string {0} {2}\n get {2} return SR.GetResourceString(\"{0}\", {1}); {3}\n {3}", leftPart, "null", "{", "}"); } else { _targetStream.WriteLine(" Friend Shared ReadOnly Property {0} As String\n Get\n Return SR.GetResourceString(\"{0}\", {1})\n End Get\n End Property", leftPart, "Nothing"); } } } private void WriteDebugCode() { if (_targetLanguage == TargetLanguage.CSharp) { if (!DebugOnly) _targetStream.WriteLine("#else"); _targetStream.WriteLine(_debugCode.ToString()); if (!DebugOnly) _targetStream.WriteLine("#endif"); } else { if (!DebugOnly) _targetStream.WriteLine("#Else"); _targetStream.WriteLine(_debugCode.ToString()); if (!DebugOnly) _targetStream.WriteLine("#End If"); } } private void WriteClassEnd() { if (_targetLanguage == TargetLanguage.CSharp) { _targetStream.WriteLine(" }"); _targetStream.WriteLine("}"); } else { _targetStream.WriteLine(" End Class"); _targetStream.WriteLine("End Namespace"); } } private void ProcessTargetFile() { string intermediateContent = File.ReadAllText(_intermediateFile); if (File.Exists(OutputSourceFilePath)) { string srContent = File.ReadAllText(OutputSourceFilePath); if (intermediateContent == srContent) return; // nothing need to get updated } File.WriteAllText(OutputSourceFilePath, intermediateContent); } private enum TargetLanguage { CSharp, VB } } }
1
5,805
Why are you passing out the Message?
dotnet-buildtools
.cs
@@ -135,8 +135,8 @@ func (p *Provider) RegisterSpanProcessor(s SpanProcessor) { // UnregisterSpanProcessor removes the given SpanProcessor from the list of SpanProcessors func (p *Provider) UnregisterSpanProcessor(s SpanProcessor) { - mu.Lock() - defer mu.Unlock() + p.mu.Lock() + defer p.mu.Unlock() new := make(spanProcessorMap) if old, ok := p.spanProcessors.Load().(spanProcessorMap); ok { for k, v := range old {
1
// Copyright The OpenTelemetry Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package trace import ( "sync" "sync/atomic" export "go.opentelemetry.io/otel/sdk/export/trace" "go.opentelemetry.io/otel/sdk/instrumentation" "go.opentelemetry.io/otel/sdk/resource" apitrace "go.opentelemetry.io/otel/api/trace" ) const ( defaultTracerName = "go.opentelemetry.io/otel/sdk/tracer" ) // batcher contains export.SpanBatcher and its options. type batcher struct { b export.SpanBatcher opts []BatchSpanProcessorOption } // ProviderOptions type ProviderOptions struct { syncers []export.SpanSyncer batchers []batcher config Config } type ProviderOption func(*ProviderOptions) type Provider struct { mu sync.Mutex namedTracer map[instrumentation.Library]*tracer spanProcessors atomic.Value config atomic.Value // access atomically } var _ apitrace.Provider = &Provider{} // NewProvider creates an instance of trace provider. Optional // parameter configures the provider with common options applicable // to all tracer instances that will be created by this provider. func NewProvider(opts ...ProviderOption) (*Provider, error) { o := &ProviderOptions{} for _, opt := range opts { opt(o) } tp := &Provider{ namedTracer: make(map[instrumentation.Library]*tracer), } tp.config.Store(&Config{ DefaultSampler: ParentSample(AlwaysSample()), IDGenerator: defIDGenerator(), MaxAttributesPerSpan: DefaultMaxAttributesPerSpan, MaxEventsPerSpan: DefaultMaxEventsPerSpan, MaxLinksPerSpan: DefaultMaxLinksPerSpan, }) for _, syncer := range o.syncers { ssp := NewSimpleSpanProcessor(syncer) tp.RegisterSpanProcessor(ssp) } for _, batcher := range o.batchers { bsp, err := NewBatchSpanProcessor(batcher.b, batcher.opts...) if err != nil { return nil, err } tp.RegisterSpanProcessor(bsp) } tp.ApplyConfig(o.config) return tp, nil } // Tracer with the given name. If a tracer for the given name does not exist, // it is created first. If the name is empty, DefaultTracerName is used. func (p *Provider) Tracer(name string, opts ...apitrace.TracerOption) apitrace.Tracer { c := new(apitrace.TracerConfig) for _, o := range opts { o(c) } p.mu.Lock() defer p.mu.Unlock() if name == "" { name = defaultTracerName } il := instrumentation.Library{ Name: name, Version: c.InstrumentationVersion, } t, ok := p.namedTracer[il] if !ok { t = &tracer{ provider: p, instrumentationLibrary: il, } p.namedTracer[il] = t } return t } // RegisterSpanProcessor adds the given SpanProcessor to the list of SpanProcessors func (p *Provider) RegisterSpanProcessor(s SpanProcessor) { p.mu.Lock() defer p.mu.Unlock() new := make(spanProcessorMap) if old, ok := p.spanProcessors.Load().(spanProcessorMap); ok { for k, v := range old { new[k] = v } } new[s] = &sync.Once{} p.spanProcessors.Store(new) } // UnregisterSpanProcessor removes the given SpanProcessor from the list of SpanProcessors func (p *Provider) UnregisterSpanProcessor(s SpanProcessor) { mu.Lock() defer mu.Unlock() new := make(spanProcessorMap) if old, ok := p.spanProcessors.Load().(spanProcessorMap); ok { for k, v := range old { new[k] = v } } if stopOnce, ok := new[s]; ok && stopOnce != nil { stopOnce.Do(func() { s.Shutdown() }) } delete(new, s) p.spanProcessors.Store(new) } // ApplyConfig changes the configuration of the provider. // If a field in the configuration is empty or nil then its original value is preserved. func (p *Provider) ApplyConfig(cfg Config) { p.mu.Lock() defer p.mu.Unlock() c := *p.config.Load().(*Config) if cfg.DefaultSampler != nil { c.DefaultSampler = cfg.DefaultSampler } if cfg.IDGenerator != nil { c.IDGenerator = cfg.IDGenerator } if cfg.MaxEventsPerSpan > 0 { c.MaxEventsPerSpan = cfg.MaxEventsPerSpan } if cfg.MaxAttributesPerSpan > 0 { c.MaxAttributesPerSpan = cfg.MaxAttributesPerSpan } if cfg.MaxLinksPerSpan > 0 { c.MaxLinksPerSpan = cfg.MaxLinksPerSpan } if cfg.Resource != nil { c.Resource = cfg.Resource } p.config.Store(&c) } // WithSyncer options appends the syncer to the existing list of Syncers. // This option can be used multiple times. // The Syncers are wrapped into SimpleSpanProcessors and registered // with the provider. func WithSyncer(syncer export.SpanSyncer) ProviderOption { return func(opts *ProviderOptions) { opts.syncers = append(opts.syncers, syncer) } } // WithBatcher options appends the batcher to the existing list of Batchers. // This option can be used multiple times. // The Batchers are wrapped into BatchedSpanProcessors and registered // with the provider. func WithBatcher(b export.SpanBatcher, bopts ...BatchSpanProcessorOption) ProviderOption { return func(opts *ProviderOptions) { opts.batchers = append(opts.batchers, batcher{b, bopts}) } } // WithConfig option sets the configuration to provider. func WithConfig(config Config) ProviderOption { return func(opts *ProviderOptions) { opts.config = config } } // WithResource option attaches a resource to the provider. // The resource is added to the span when it is started. func WithResource(r *resource.Resource) ProviderOption { return func(opts *ProviderOptions) { opts.config.Resource = r } }
1
13,185
Yikes, this was a bug :grimacing:
open-telemetry-opentelemetry-go
go
@@ -58,7 +58,7 @@ func (h *Handler) FetchX509SVID(_ *workload.X509SVIDRequest, stream workload.Spi selectors := attestor.New(&config).Attest(pid) - subscriber := h.Manager.Subscribe(selectors) + subscriber := h.Manager.NewSubscriber(selectors) defer subscriber.Finish() for {
1
package workload import ( "context" "crypto/x509" "errors" "fmt" "time" "github.com/sirupsen/logrus" "github.com/spiffe/spire/pkg/agent/attestor/workload" "github.com/spiffe/spire/pkg/agent/auth" "github.com/spiffe/spire/pkg/agent/catalog" "github.com/spiffe/spire/pkg/agent/manager" "github.com/spiffe/spire/pkg/agent/manager/cache" "github.com/spiffe/spire/pkg/common/telemetry" "github.com/spiffe/spire/proto/api/workload" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" ) // Handler implements the Workload API interface type Handler struct { Manager manager.Manager Catalog catalog.Catalog L logrus.FieldLogger T telemetry.Sink } const ( workloadApi = "workload_api" workloadPid = "workload_pid" ) func (h *Handler) FetchX509SVID(_ *workload.X509SVIDRequest, stream workload.SpiffeWorkloadAPI_FetchX509SVIDServer) error { md, ok := metadata.FromIncomingContext(stream.Context()) if !ok || len(md["workload.spiffe.io"]) != 1 || md["workload.spiffe.io"][0] != "true" { return grpc.Errorf(codes.InvalidArgument, "Security header missing from request") } pid, err := h.callerPID(stream.Context()) if err != nil { return grpc.Errorf(codes.Internal, "Is this a supported system? Please report this bug: %v", err) } tLabels := []telemetry.Label{{workloadPid, string(pid)}} h.T.IncrCounterWithLabels([]string{workloadApi, "connection"}, 1, tLabels) h.T.IncrCounterWithLabels([]string{workloadApi, "connections"}, 1, tLabels) defer h.T.IncrCounterWithLabels([]string{workloadApi, "connections"}, -1, tLabels) config := attestor.Config{ Catalog: h.Catalog, L: h.L, T: h.T, } selectors := attestor.New(&config).Attest(pid) subscriber := h.Manager.Subscribe(selectors) defer subscriber.Finish() for { select { case update := <-subscriber.Updates(): h.T.IncrCounterWithLabels([]string{workloadApi, "update"}, 1, tLabels) start := time.Now() err := h.sendResponse(update, stream) if err != nil { return err } h.T.MeasureSinceWithLabels([]string{workloadApi, "update_latency"}, start, tLabels) if time.Since(start) > (1 * time.Second) { h.L.Warnf("Took %v seconds to send update to PID %v", time.Since(start).Seconds, pid) } case <-stream.Context().Done(): return nil } } } func (h *Handler) sendResponse(update *cache.WorkloadUpdate, stream workload.SpiffeWorkloadAPI_FetchX509SVIDServer) error { if len(update.Entries) == 0 { return grpc.Errorf(codes.PermissionDenied, "no identity issued") } resp, err := h.composeResponse(update) if err != nil { return grpc.Errorf(codes.Unavailable, "Could not serialize response: %v", err) } return stream.Send(resp) } func (h *Handler) composeResponse(update *cache.WorkloadUpdate) (*workload.X509SVIDResponse, error) { resp := new(workload.X509SVIDResponse) resp.Svids = []*workload.X509SVID{} bundle := []byte{} for _, c := range update.Bundle { bundle = append(bundle, c.Raw...) } for _, e := range update.Entries { id := e.RegistrationEntry.SpiffeId keyData, err := x509.MarshalPKCS8PrivateKey(e.PrivateKey) if err != nil { return nil, fmt.Errorf("marshal key for %v: %v", id, err) } svid := &workload.X509SVID{ SpiffeId: id, X509Svid: e.SVID.Raw, X509SvidKey: keyData, Bundle: bundle, } resp.Svids = append(resp.Svids, svid) } return resp, nil } // callerPID takes a grpc context, and returns the PID of the caller which has issued // the request. Returns an error if the call was not made locally, if the necessary // syscalls aren't unsupported, or if the transport security was not properly configured. // See the auth package for more information. func (h *Handler) callerPID(ctx context.Context) (pid int32, err error) { info, ok := auth.CallerFromContext(ctx) if !ok { return 0, errors.New("Unable to fetch credentials from context") } if info.Err != nil { return 0, fmt.Errorf("Unable to resolve caller PID: %s", info.Err) } // If PID is 0, something is wrong... if info.PID == 0 { return 0, errors.New("Unable to resolve caller PID") } return info.PID, nil }
1
9,397
I am not sure which one of these is considered idiomatic go... maybe @azdagron has an opinion here? /me prefers the verb since it's shorter. I guess I don't care _too_ much, but it would be good to get some general agreement so we are all following the same conventions
spiffe-spire
go
@@ -62,9 +62,7 @@ var LocalDevSequelproCmd = &cobra.Command{ "root", //dbuser )) - if scaffold != true { - exec.Command("open", tmpFilePath).Run() - } + exec.Command("open", tmpFilePath).Run() color.Cyan("sequelpro command finished successfully!")
1
package cmd import ( "fmt" "log" "os" "os/exec" "path" "strconv" "strings" "github.com/drud/ddev/pkg/plugins/platform" "github.com/drud/drud-go/utils/dockerutil" "github.com/fatih/color" "github.com/spf13/cobra" ) // LocalDevSequelproCmd represents the sequelpro command var LocalDevSequelproCmd = &cobra.Command{ Use: "sequelpro [app_name] [environment_name]", Short: "Easily connect local site to sequelpro", Long: `A helper command for easily using sequelpro with a drud app that has been initialized locally.`, Run: func(cmd *cobra.Command, args []string) { app := platform.PluginMap[strings.ToLower(plugin)] opts := platform.AppOptions{ Name: activeApp, Environment: activeDeploy, } app.SetOpts(opts) nameContainer := fmt.Sprintf("%s-db", app.ContainerName()) if !dockerutil.IsRunning(nameContainer) { Failed("App not running locally. Try `drud legacy add`.") } mysqlContainer, err := dockerutil.GetContainer(nameContainer) if err != nil { log.Fatal(err) } dbPort, err := dockerutil.GetDockerPublicPort(mysqlContainer, int64(3306)) if err != nil { log.Fatal(err) } tmpFilePath := path.Join(app.AbsPath(), "sequelpro.spf") tmpFile, err := os.Create(tmpFilePath) if err != nil { log.Fatalln(err) } defer tmpFile.Close() tmpFile.WriteString(fmt.Sprintf( platform.SequelproTemplate, "data", //dbname "127.0.0.1", //host mysqlContainer.Names[0], //container name "root", // dbpass strconv.FormatInt(dbPort, 10), // port "root", //dbuser )) if scaffold != true { exec.Command("open", tmpFilePath).Run() } color.Cyan("sequelpro command finished successfully!") }, } func init() { LocalDevSequelproCmd.Flags().BoolVarP(&scaffold, "scaffold", "s", false, "Add the app but don't run or config it.") RootCmd.AddCommand(LocalDevSequelproCmd) //RootCmd.AddCommand(SequelproCmd) }
1
10,615
Please check this for error and emit appropriate debugging information. I know this was pre-existing code, but we just have to fix things like this as we go.
drud-ddev
php
@@ -140,7 +140,7 @@ func InitialURL(c client.Client, cd *hivev1.ClusterDeployment) (string, error) { // the ClusterDeployment to determine if the remote cluster is reachable. func Unreachable(cd *hivev1.ClusterDeployment) (unreachable bool, lastCheck time.Time) { cond := utils.FindClusterDeploymentCondition(cd.Status.Conditions, hivev1.UnreachableCondition) - if cond.Status == corev1.ConditionUnknown { + if cond == nil || cond.Status == corev1.ConditionUnknown { unreachable = true return }
1
package remoteclient //go:generate mockgen -source=./remoteclient.go -destination=./mock/remoteclient_generated.go -package=mock import ( "context" "time" "github.com/pkg/errors" log "github.com/sirupsen/logrus" "k8s.io/apimachinery/pkg/runtime" corev1 "k8s.io/api/core/v1" "k8s.io/client-go/dynamic" kubeclient "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" "k8s.io/client-go/tools/clientcmd" "sigs.k8s.io/controller-runtime/pkg/client" openshiftapiv1 "github.com/openshift/api/config/v1" routev1 "github.com/openshift/api/route/v1" autoscalingv1 "github.com/openshift/cluster-autoscaler-operator/pkg/apis/autoscaling/v1" autoscalingv1beta1 "github.com/openshift/cluster-autoscaler-operator/pkg/apis/autoscaling/v1beta1" machineapi "github.com/openshift/machine-api-operator/pkg/apis/machine/v1beta1" hivev1 "github.com/openshift/hive/apis/hive/v1" "github.com/openshift/hive/pkg/constants" "github.com/openshift/hive/pkg/controller/utils" ) // Builder is used to build API clients to the remote cluster type Builder interface { // Build will return a static controller-runtime client for the remote cluster. Build() (client.Client, error) // BuildDynamic will return a dynamic kubeclient for the remote cluster. BuildDynamic() (dynamic.Interface, error) // BuildKubeClient will return a kubernetes client for the remote cluster. BuildKubeClient() (kubeclient.Interface, error) // RESTConfig returns the config for a REST client that connects to the remote cluster. RESTConfig() (*rest.Config, error) // UsePrimaryAPIURL will use the primary API URL. If there is an API URL override, then that is the primary. // Otherwise, the primary is the default API URL. UsePrimaryAPIURL() Builder // UseSecondaryAPIURL will use the secondary API URL. If there is an API URL override, then the initial API URL // is the secondary. UseSecondaryAPIURL() Builder } // NewBuilder creates a new Builder for creating a client to connect to the remote cluster associated with the specified // ClusterDeployment. // The controllerName is needed for metrics. // If the ClusterDeployment carries the fake cluster annotation, a fake client will be returned populated with // runtime.Objects we need to query for in all our controllers. func NewBuilder(c client.Client, cd *hivev1.ClusterDeployment, controllerName hivev1.ControllerName) Builder { if utils.IsFakeCluster(cd) { return &fakeBuilder{ urlToUse: activeURL, } } return &builder{ c: c, cd: cd, controllerName: controllerName, urlToUse: activeURL, } } // ConnectToRemoteCluster connects to a remote cluster using the specified builder. // If the ClusterDeployment is marked as unreachable, then no connection will be made. // If there are problems connecting, then the specified clusterdeployment will be marked as unreachable. func ConnectToRemoteCluster( cd *hivev1.ClusterDeployment, remoteClientBuilder Builder, localClient client.Client, logger log.FieldLogger, ) (remoteClient client.Client, unreachable, requeue bool) { var rawRemoteClient interface{} rawRemoteClient, unreachable, requeue = connectToRemoteCluster( cd, remoteClientBuilder, localClient, logger, func(builder Builder) (interface{}, error) { return builder.Build() }, ) if unreachable { return } remoteClient = rawRemoteClient.(client.Client) return } func connectToRemoteCluster( cd *hivev1.ClusterDeployment, remoteClientBuilder Builder, localClient client.Client, logger log.FieldLogger, buildFunc func(builder Builder) (interface{}, error), ) (remoteClient interface{}, unreachable, requeue bool) { if u, _ := Unreachable(cd); u { logger.Debug("skipping cluster with unreachable condition") unreachable = true return } var err error remoteClient, err = buildFunc(remoteClientBuilder) if err == nil { return } unreachable = true logger.WithError(err).Info("remote cluster is unreachable") SetUnreachableCondition(cd, err) if err := localClient.Status().Update(context.Background(), cd); err != nil { logger.WithError(err).Log(utils.LogLevel(err), "could not update clusterdeployment with unreachable condition") requeue = true } return } // InitialURL returns the initial API URL for the ClusterDeployment. func InitialURL(c client.Client, cd *hivev1.ClusterDeployment) (string, error) { if utils.IsFakeCluster(cd) { return "https://example.com/veryfakeapi", nil } cfg, err := unadulteratedRESTConfig(c, cd) if err != nil { return "", err } return cfg.Host, nil } // Unreachable returns true if Hive has not been able to reach the remote cluster. // Note that this function will not attempt to reach the remote cluster. It only checks the current conditions on // the ClusterDeployment to determine if the remote cluster is reachable. func Unreachable(cd *hivev1.ClusterDeployment) (unreachable bool, lastCheck time.Time) { cond := utils.FindClusterDeploymentCondition(cd.Status.Conditions, hivev1.UnreachableCondition) if cond.Status == corev1.ConditionUnknown { unreachable = true return } return cond.Status == corev1.ConditionTrue, cond.LastProbeTime.Time } // IsPrimaryURLActive returns true if the remote cluster is reachable via the primary API URL. func IsPrimaryURLActive(cd *hivev1.ClusterDeployment) bool { if cd.Spec.ControlPlaneConfig.APIURLOverride == "" { return true } cond := utils.FindClusterDeploymentCondition(cd.Status.Conditions, hivev1.ActiveAPIURLOverrideCondition) return cond != nil && cond.Status == corev1.ConditionTrue } // SetUnreachableCondition sets the Unreachable condition on the ClusterDeployment based on the specified error // encountered when attempting to connect to the remote cluster. func SetUnreachableCondition(cd *hivev1.ClusterDeployment, connectionError error) (changed bool) { status := corev1.ConditionFalse reason := "ClusterReachable" message := "cluster is reachable" // This needs to always update so that the probe time is updated. The probe time is used to determine when to // perform the next connectivity check. updateCheck := utils.UpdateConditionAlways if connectionError != nil { status = corev1.ConditionTrue reason = "ErrorConnectingToCluster" message = connectionError.Error() updateCheck = utils.UpdateConditionIfReasonOrMessageChange } cd.Status.Conditions, changed = utils.SetClusterDeploymentConditionWithChangeCheck( cd.Status.Conditions, hivev1.UnreachableCondition, status, reason, message, updateCheck, ) return } type builder struct { c client.Client cd *hivev1.ClusterDeployment controllerName hivev1.ControllerName urlToUse int } const ( activeURL = iota primaryURL secondaryURL ) func buildScheme() (*runtime.Scheme, error) { scheme := runtime.NewScheme() if err := machineapi.AddToScheme(scheme); err != nil { return nil, err } if err := autoscalingv1.SchemeBuilder.AddToScheme(scheme); err != nil { return nil, err } if err := autoscalingv1beta1.SchemeBuilder.AddToScheme(scheme); err != nil { return nil, err } if err := openshiftapiv1.Install(scheme); err != nil { return nil, err } if err := routev1.Install(scheme); err != nil { return nil, err } return scheme, nil } func (b *builder) Build() (client.Client, error) { cfg, err := b.RESTConfig() if err != nil { return nil, err } scheme, err := buildScheme() if err != nil { return nil, err } return client.New(cfg, client.Options{ Scheme: scheme, }) } func (b *builder) BuildDynamic() (dynamic.Interface, error) { cfg, err := b.RESTConfig() if err != nil { return nil, err } client, err := dynamic.NewForConfig(cfg) if err != nil { return nil, err } return client, nil } func (b *builder) BuildKubeClient() (kubeclient.Interface, error) { cfg, err := b.RESTConfig() if err != nil { return nil, err } client, err := kubeclient.NewForConfig(cfg) if err != nil { return nil, err } return client, nil } func (b *builder) UsePrimaryAPIURL() Builder { b.urlToUse = primaryURL return b } func (b *builder) UseSecondaryAPIURL() Builder { b.urlToUse = secondaryURL return b } func (b *builder) RESTConfig() (*rest.Config, error) { cfg, err := unadulteratedRESTConfig(b.c, b.cd) if err != nil { return nil, err } utils.AddControllerMetricsTransportWrapper(cfg, b.controllerName, true) if override := b.cd.Spec.ControlPlaneConfig.APIURLOverride; override != "" { if b.urlToUse == primaryURL || (b.urlToUse == activeURL && IsPrimaryURLActive(b.cd)) { cfg.Host = override } } return cfg, nil } func unadulteratedRESTConfig(c client.Client, cd *hivev1.ClusterDeployment) (*rest.Config, error) { kubeconfigSecret := &corev1.Secret{} if err := c.Get( context.Background(), client.ObjectKey{Namespace: cd.Namespace, Name: cd.Spec.ClusterMetadata.AdminKubeconfigSecretRef.Name}, kubeconfigSecret, ); err != nil { return nil, errors.Wrap(err, "could not get admin kubeconfig secret") } return restConfigFromSecret(kubeconfigSecret) } func restConfigFromSecret(kubeconfigSecret *corev1.Secret) (*rest.Config, error) { kubeconfigData, ok := kubeconfigSecret.Data[constants.KubeconfigSecretKey] if !ok { return nil, errors.Errorf("kubeconfig secret does not contain %q data", constants.KubeconfigSecretKey) } config, err := clientcmd.Load(kubeconfigData) if err != nil { return nil, err } kubeConfig := clientcmd.NewDefaultClientConfig(*config, &clientcmd.ConfigOverrides{}) return kubeConfig.ClientConfig() }
1
18,378
This seems unrelated, should be a separate PR.
openshift-hive
go
@@ -20,6 +20,7 @@ //-- #include "algorithms/engines/mt2203/mt2203.h" +#include "../engine_create_dispatcher.h" #include "mt2203_batch_impl.h" namespace daal
1
/* file: mt2203.cpp */ /******************************************************************************* * Copyright 2014-2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ //++ // Implementation of mt2203 engine //-- #include "algorithms/engines/mt2203/mt2203.h" #include "mt2203_batch_impl.h" namespace daal { namespace algorithms { namespace engines { namespace mt2203 { namespace interface1 { using namespace daal::services; using namespace mt2203::internal; template <typename algorithmFPType, Method method> SharedPtr<Batch<algorithmFPType, method> > Batch<algorithmFPType, method>::create(size_t seed, services::Status * st) { SharedPtr<Batch<algorithmFPType, method> > engPtr; int cpuid = (int)Environment::getInstance()->getCpuId(); switch (cpuid) { #ifdef DAAL_KERNEL_AVX512 case avx512: DAAL_KERNEL_AVX512_ONLY_CODE(engPtr.reset(new BatchImpl<avx512, algorithmFPType, method>(seed, st))); break; #endif #ifdef DAAL_KERNEL_AVX512_MIC case avx512_mic: DAAL_KERNEL_AVX512_MIC_ONLY_CODE(engPtr.reset(new BatchImpl<avx512_mic, algorithmFPType, method>(seed, st))); break; #endif #ifdef DAAL_KERNEL_AVX2 case avx2: DAAL_KERNEL_AVX2_ONLY_CODE(engPtr.reset(new BatchImpl<avx2, algorithmFPType, method>(seed, st))); break; #endif #ifdef DAAL_KERNEL_AVX case avx: DAAL_KERNEL_AVX_ONLY_CODE(engPtr.reset(new BatchImpl<avx, algorithmFPType, method>(seed, st))); break; #endif #ifdef DAAL_KERNEL_SSE42 case sse42: DAAL_KERNEL_SSE42_ONLY_CODE(engPtr.reset(new BatchImpl<sse42, algorithmFPType, method>(seed, st))); break; #endif #ifdef DAAL_KERNEL_SSSE3 case ssse3: DAAL_KERNEL_SSSE3_ONLY_CODE(engPtr.reset(new BatchImpl<ssse3, algorithmFPType, method>(seed, st))); break; #endif default: engPtr.reset(new BatchImpl<sse2, algorithmFPType, method>(seed, st)); break; }; return engPtr; } template class Batch<double, defaultDense>; template class Batch<float, defaultDense>; } // namespace interface1 } // namespace mt2203 } // namespace engines } // namespace algorithms } // namespace daal
1
19,549
Never use relative includes, prefer full path
oneapi-src-oneDAL
cpp
@@ -397,6 +397,17 @@ class TestArgument: assert str(excinfo.value) == "Argument marked as both count/win_id!" + def test_zero_count_and_zero_count_arg(self): + with pytest.raises(TypeError) as excinfo: + @cmdutils.argument('arg', count=False, + zero_count=True) + def fun(arg=0): + """Blah.""" + pass + + assert str(excinfo.value) == ("Zero_count Argument" + + " cannot exist without count!") + def test_no_docstring(self, caplog): with caplog.at_level(logging.WARNING): @cmdutils.register()
1
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2015-2016 Florian Bruhin (The Compiler) <[email protected]> # # This file is part of qutebrowser. # # qutebrowser is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # qutebrowser is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with qutebrowser. If not, see <http://www.gnu.org/licenses/>. # pylint: disable=unused-variable """Tests for qutebrowser.commands.cmdutils.""" import sys import logging import types import pytest from qutebrowser.commands import cmdutils, cmdexc, argparser, command from qutebrowser.utils import usertypes, typing @pytest.fixture(autouse=True) def clear_globals(monkeypatch): """Clear the cmdutils globals between each test.""" monkeypatch.setattr(cmdutils, 'cmd_dict', {}) monkeypatch.setattr(cmdutils, 'aliases', []) def _get_cmd(*args, **kwargs): """Get a command object created via @cmdutils.register. Args: Passed to @cmdutils.register decorator """ @cmdutils.register(*args, **kwargs) def fun(): """Blah.""" pass return cmdutils.cmd_dict['fun'] class TestCheckOverflow: def test_good(self): cmdutils.check_overflow(1, 'int') def test_bad(self): int32_max = 2 ** 31 - 1 with pytest.raises(cmdexc.CommandError) as excinfo: cmdutils.check_overflow(int32_max + 1, 'int') expected_str = ("Numeric argument is too large for internal int " "representation.") assert str(excinfo.value) == expected_str class TestCheckExclusive: @pytest.mark.parametrize('flags', [[], [False, True], [False, False]]) def test_good(self, flags): cmdutils.check_exclusive(flags, []) def test_bad(self): with pytest.raises(cmdexc.CommandError) as excinfo: cmdutils.check_exclusive([True, True], 'xyz') assert str(excinfo.value) == "Only one of -x/-y/-z can be given!" class TestRegister: def test_simple(self): @cmdutils.register() def fun(): """Blah.""" pass cmd = cmdutils.cmd_dict['fun'] assert cmd.handler is fun assert cmd.name == 'fun' assert len(cmdutils.cmd_dict) == 1 assert not cmdutils.aliases def test_underlines(self): """Make sure the function name is normalized correctly (_ -> -).""" @cmdutils.register() def eggs_bacon(): """Blah.""" pass assert cmdutils.cmd_dict['eggs-bacon'].name == 'eggs-bacon' assert 'eggs_bacon' not in cmdutils.cmd_dict def test_lowercasing(self): """Make sure the function name is normalized correctly (uppercase).""" @cmdutils.register() def Test(): # pylint: disable=invalid-name """Blah.""" pass assert cmdutils.cmd_dict['test'].name == 'test' assert 'Test' not in cmdutils.cmd_dict def test_explicit_name(self): """Test register with explicit name.""" @cmdutils.register(name='foobar') def fun(): """Blah.""" pass assert cmdutils.cmd_dict['foobar'].name == 'foobar' assert 'fun' not in cmdutils.cmd_dict assert len(cmdutils.cmd_dict) == 1 assert not cmdutils.aliases def test_multiple_names(self): """Test register with name being a list.""" @cmdutils.register(name=['foobar', 'blub']) def fun(): """Blah.""" pass assert cmdutils.cmd_dict['foobar'].name == 'foobar' assert cmdutils.cmd_dict['blub'].name == 'foobar' assert 'fun' not in cmdutils.cmd_dict assert len(cmdutils.cmd_dict) == 2 assert cmdutils.aliases == ['blub'] def test_multiple_registrations(self): """Make sure registering the same name twice raises ValueError.""" @cmdutils.register(name=['foobar', 'blub']) def fun(): """Blah.""" pass with pytest.raises(ValueError): @cmdutils.register(name=['blah', 'blub']) def fun2(): """Blah.""" pass def test_instance(self): """Make sure the instance gets passed to Command.""" @cmdutils.register(instance='foobar') def fun(self): """Blah.""" pass assert cmdutils.cmd_dict['fun']._instance == 'foobar' def test_kwargs(self): """Make sure the other keyword arguments get passed to Command.""" @cmdutils.register(hide=True) def fun(): """Blah.""" pass assert cmdutils.cmd_dict['fun'].hide def test_star_args(self): """Check handling of *args.""" @cmdutils.register() def fun(*args): """Blah.""" pass with pytest.raises(argparser.ArgumentParserError): cmdutils.cmd_dict['fun'].parser.parse_args([]) def test_star_args_optional(self): """Check handling of *args withstar_args_optional.""" @cmdutils.register(star_args_optional=True) def fun(*args): """Blah.""" assert not args cmd = cmdutils.cmd_dict['fun'] cmd.namespace = cmd.parser.parse_args([]) args, kwargs = cmd._get_call_args(win_id=0) fun(*args, **kwargs) @pytest.mark.parametrize('inp, expected', [ (['--arg'], True), (['-a'], True), ([], False)]) def test_flag(self, inp, expected): @cmdutils.register() def fun(arg=False): """Blah.""" assert arg == expected cmd = cmdutils.cmd_dict['fun'] cmd.namespace = cmd.parser.parse_args(inp) assert cmd.namespace.arg == expected def test_flag_argument(self): @cmdutils.register() @cmdutils.argument('arg', flag='b') def fun(arg=False): """Blah.""" assert arg cmd = cmdutils.cmd_dict['fun'] with pytest.raises(argparser.ArgumentParserError): cmd.parser.parse_args(['-a']) cmd.namespace = cmd.parser.parse_args(['-b']) assert cmd.namespace.arg args, kwargs = cmd._get_call_args(win_id=0) fun(*args, **kwargs) def test_partial_arg(self): """Test with only some arguments decorated with @cmdutils.argument.""" @cmdutils.register() @cmdutils.argument('arg1', flag='b') def fun(arg1=False, arg2=False): """Blah.""" pass def test_win_id(self): @cmdutils.register() @cmdutils.argument('win_id', win_id=True) def fun(win_id): """Blah.""" pass assert cmdutils.cmd_dict['fun']._get_call_args(42) == ([42], {}) def test_count(self): @cmdutils.register() @cmdutils.argument('count', count=True) def fun(count=0): """Blah.""" pass assert cmdutils.cmd_dict['fun']._get_call_args(42) == ([0], {}) def test_count_without_default(self): with pytest.raises(TypeError) as excinfo: @cmdutils.register() @cmdutils.argument('count', count=True) def fun(count): """Blah.""" pass expected = "fun: handler has count parameter without default!" assert str(excinfo.value) == expected @pytest.mark.parametrize('hide', [True, False]) def test_pos_args(self, hide): @cmdutils.register() @cmdutils.argument('arg', hide=hide) def fun(arg): """Blah.""" pass pos_args = cmdutils.cmd_dict['fun'].pos_args if hide: assert pos_args == [] else: assert pos_args == [('arg', 'arg')] Enum = usertypes.enum('Test', ['x', 'y']) @pytest.mark.parametrize('typ, inp, choices, expected', [ (int, '42', None, 42), (int, 'x', None, cmdexc.ArgumentTypeError), (str, 'foo', None, 'foo'), (typing.Union[str, int], 'foo', None, 'foo'), (typing.Union[str, int], '42', None, 42), # Choices (str, 'foo', ['foo'], 'foo'), (str, 'bar', ['foo'], cmdexc.ArgumentTypeError), # Choices with Union: only checked when it's a str (typing.Union[str, int], 'foo', ['foo'], 'foo'), (typing.Union[str, int], 'bar', ['foo'], cmdexc.ArgumentTypeError), (typing.Union[str, int], '42', ['foo'], 42), (Enum, 'x', None, Enum.x), (Enum, 'z', None, cmdexc.ArgumentTypeError), ]) def test_typed_args(self, typ, inp, choices, expected): @cmdutils.register() @cmdutils.argument('arg', choices=choices) def fun(arg: typ): """Blah.""" assert arg == expected cmd = cmdutils.cmd_dict['fun'] cmd.namespace = cmd.parser.parse_args([inp]) if expected is cmdexc.ArgumentTypeError: with pytest.raises(cmdexc.ArgumentTypeError): cmd._get_call_args(win_id=0) else: args, kwargs = cmd._get_call_args(win_id=0) assert args == [expected] assert kwargs == {} fun(*args, **kwargs) def test_choices_no_annotation(self): # https://github.com/The-Compiler/qutebrowser/issues/1871 @cmdutils.register() @cmdutils.argument('arg', choices=['foo', 'bar']) def fun(arg): """Blah.""" pass cmd = cmdutils.cmd_dict['fun'] cmd.namespace = cmd.parser.parse_args(['fish']) with pytest.raises(cmdexc.ArgumentTypeError): cmd._get_call_args(win_id=0) def test_choices_no_annotation_kwonly(self): # https://github.com/The-Compiler/qutebrowser/issues/1871 @cmdutils.register() @cmdutils.argument('arg', choices=['foo', 'bar']) def fun(*, arg): """Blah.""" pass cmd = cmdutils.cmd_dict['fun'] cmd.namespace = cmd.parser.parse_args(['--arg=fish']) with pytest.raises(cmdexc.ArgumentTypeError): cmd._get_call_args(win_id=0) def test_pos_arg_info(self): @cmdutils.register() @cmdutils.argument('foo', choices=('a', 'b')) @cmdutils.argument('bar', choices=('x', 'y')) @cmdutils.argument('opt') def fun(foo, bar, opt=False): """Blah.""" pass cmd = cmdutils.cmd_dict['fun'] assert cmd.get_pos_arg_info(0) == command.ArgInfo(choices=('a', 'b')) assert cmd.get_pos_arg_info(1) == command.ArgInfo(choices=('x', 'y')) with pytest.raises(IndexError): cmd.get_pos_arg_info(2) class TestArgument: """Test the @cmdutils.argument decorator.""" def test_invalid_argument(self): with pytest.raises(ValueError) as excinfo: @cmdutils.argument('foo') def fun(bar): """Blah.""" pass assert str(excinfo.value) == "fun has no argument foo!" def test_storage(self): @cmdutils.argument('foo', flag='x') @cmdutils.argument('bar', flag='y') def fun(foo, bar): """Blah.""" pass expected = { 'foo': command.ArgInfo(flag='x'), 'bar': command.ArgInfo(flag='y') } assert fun.qute_args == expected def test_wrong_order(self): """When @cmdutils.argument is used above (after) @register, fail.""" with pytest.raises(ValueError) as excinfo: @cmdutils.argument('bar', flag='y') @cmdutils.register() def fun(bar): """Blah.""" pass text = ("@cmdutils.argument got called above (after) " "@cmdutils.register for fun!") assert str(excinfo.value) == text def test_count_and_win_id_same_arg(self): with pytest.raises(TypeError) as excinfo: @cmdutils.argument('arg', count=True, win_id=True) def fun(arg=0): """Blah.""" pass assert str(excinfo.value) == "Argument marked as both count/win_id!" def test_no_docstring(self, caplog): with caplog.at_level(logging.WARNING): @cmdutils.register() def fun(): # no docstring pass assert len(caplog.records) == 1 msg = caplog.records[0].message assert msg.endswith('test_cmdutils.py has no docstring') def test_no_docstring_with_optimize(self, monkeypatch): """With -OO we'd get a warning on start, but no warning afterwards.""" monkeypatch.setattr(sys, 'flags', types.SimpleNamespace(optimize=2)) @cmdutils.register() def fun(): # no docstring pass class TestRun: @pytest.fixture(autouse=True) def patching(self, mode_manager, fake_args): fake_args.backend = 'webkit' @pytest.mark.parametrize('backend, used, ok', [ (usertypes.Backend.QtWebEngine, 'webengine', True), (usertypes.Backend.QtWebEngine, 'webkit', False), (usertypes.Backend.QtWebKit, 'webengine', False), (usertypes.Backend.QtWebKit, 'webkit', True), (None, 'webengine', True), (None, 'webkit', True), ]) def test_backend(self, fake_args, backend, used, ok): fake_args.backend = used cmd = _get_cmd(backend=backend) if ok: cmd.run(win_id=0) else: with pytest.raises(cmdexc.PrerequisitesError) as excinfo: cmd.run(win_id=0) assert str(excinfo.value).endswith(' backend.') def test_no_args(self): cmd = _get_cmd() cmd.run(win_id=0) def test_instance_unavailable_with_backend(self, fake_args): """Test what happens when a backend doesn't have an objreg object. For example, QtWebEngine doesn't have 'hintmanager' registered. We make sure the backend checking happens before resolving the instance, so we display an error instead of crashing. """ @cmdutils.register(instance='doesnotexist', backend=usertypes.Backend.QtWebEngine) def fun(self): """Blah.""" pass fake_args.backend = 'webkit' cmd = cmdutils.cmd_dict['fun'] with pytest.raises(cmdexc.PrerequisitesError) as excinfo: cmd.run(win_id=0) assert str(excinfo.value).endswith(' backend.')
1
16,575
This should fit on the line above without going over the 79-char limit, no?
qutebrowser-qutebrowser
py
@@ -22,7 +22,6 @@ describe VideosController do user = create(:subscriber) video = create(:video) create(:license, user: user, licenseable: video.watchable) - controller.stubs(:signed_in?).returns(true) stub_current_user_with(user) get :show, id: video
1
require "rails_helper" include StubCurrentUserHelper describe VideosController do describe "#index" do it "renders RSS" do get :index, format: :rss expect(response).to be_success end it "doesn't recognize other formats" do expect do get :index, format: :html end.to raise_exception(ActionController::UnknownFormat) end end describe "#show when viewing a video as user with a license" do it "renders the licensed show so they can watch video" do user = create(:subscriber) video = create(:video) create(:license, user: user, licenseable: video.watchable) controller.stubs(:signed_in?).returns(true) stub_current_user_with(user) get :show, id: video expect(response).to render_template "show_licensed" end it "doesn't recognize other formats" do expect do get :show, id: create(:video), format: :json end.to raise_exception(ActionController::UnknownFormat) end end describe "#show when viewing a video with preview without a license" do it "renders the licensed show so they can watch video" do video = create(:video, :with_preview) get :show, id: video expect(response).to render_template "show" end end describe "#show when viewing a video without a preview without a license" do it "renders the licensed show so they can watch video" do video = create(:video) get :show, id: video expect(response).to redirect_to video.watchable end end end
1
13,160
Is this related to the other contents of this pull request?
thoughtbot-upcase
rb
@@ -356,6 +356,7 @@ type WorkloadOpts struct { Aliases []string Tags map[string]string // Used by App Runner workloads to tag App Runner service resources NestedStack *WorkloadNestedStackOpts // Outputs from nested stacks such as the addons stack. + AddonsExtraParams string // Additional user defined Parameters for the addons stack. Sidecars []*SidecarOpts LogConfig *LogConfigOpts Autoscaling *AutoscalingOpts
1
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package template import ( "bytes" "fmt" "text/template" "github.com/dustin/go-humanize/english" "github.com/google/uuid" "github.com/aws/aws-sdk-go/aws" ) // Constants for template paths. const ( // Paths of workload cloudformation templates under templates/workloads/. fmtWkldCFTemplatePath = "workloads/%s/%s/cf.yml" fmtWkldPartialsCFTemplatePath = "workloads/partials/cf/%s.yml" // Directories under templates/workloads/. servicesDirName = "services" jobDirName = "jobs" // Names of workload templates. lbWebSvcTplName = "lb-web" rdWebSvcTplName = "rd-web" backendSvcTplName = "backend" workerSvcTplName = "worker" scheduledJobTplName = "scheduled-job" ) // Constants for workload options. const ( // AWS VPC networking configuration. EnablePublicIP = "ENABLED" DisablePublicIP = "DISABLED" PublicSubnetsPlacement = "PublicSubnets" PrivateSubnetsPlacement = "PrivateSubnets" // RuntimePlatform configuration. OSLinux = "LINUX" OSWindowsServerFull = "WINDOWS_SERVER_2019_FULL" OSWindowsServerCore = "WINDOWS_SERVER_2019_CORE" ArchX86 = "X86_64" ) // Constants for ARN options. const ( snsARNPattern = "arn:%s:sns:%s:%s:%s-%s-%s-%s" ) var ( // Template names under "workloads/partials/cf/". partialsWorkloadCFTemplateNames = []string{ "loggroup", "envvars-container", "envvars-common", "secrets", "executionrole", "taskrole", "workload-container", "fargate-taskdef-base-properties", "service-base-properties", "servicediscovery", "addons", "sidecars", "logconfig", "autoscaling", "eventrule", "state-machine", "state-machine-definition.json", "efs-access-point", "env-controller", "mount-points", "volumes", "image-overrides", "instancerole", "accessrole", "publish", "subscribe", } // Operating systems to determine Fargate platform versions. osFamiliesForPV100 = []string{ OSWindowsServerFull, OSWindowsServerCore, } ) // WorkloadNestedStackOpts holds configuration that's needed if the workload stack has a nested stack. type WorkloadNestedStackOpts struct { StackName string VariableOutputs []string SecretOutputs []string PolicyOutputs []string SecurityGroupOutputs []string } // SidecarOpts holds configuration that's needed if the service has sidecar containers. type SidecarOpts struct { Name *string Image *string Essential *bool Port *string Protocol *string CredsParam *string Variables map[string]string Secrets map[string]string Storage SidecarStorageOpts DockerLabels map[string]string DependsOn map[string]string EntryPoint []string Command []string HealthCheck *ContainerHealthCheck } // SidecarStorageOpts holds data structures for rendering Mount Points inside of a sidecar. type SidecarStorageOpts struct { MountPoints []*MountPoint } // StorageOpts holds data structures for rendering Volumes and Mount Points type StorageOpts struct { Ephemeral *int Volumes []*Volume MountPoints []*MountPoint EFSPerms []*EFSPermission ManagedVolumeInfo *ManagedVolumeCreationInfo // Used for delegating CreationInfo for Copilot-managed EFS. } // requiresEFSCreation returns true if managed volume information is specified; false otherwise. func (s *StorageOpts) requiresEFSCreation() bool { return s.ManagedVolumeInfo != nil } // EFSPermission holds information needed to render an IAM policy statement. type EFSPermission struct { FilesystemID *string Write bool AccessPointID *string } // MountPoint holds information needed to render a MountPoint in a containerdefinition. type MountPoint struct { ContainerPath *string ReadOnly *bool SourceVolume *string } // Volume contains fields that render a volume, its name, and EFSVolumeConfiguration type Volume struct { Name *string EFS *EFSVolumeConfiguration } // ManagedVolumeCreationInfo holds information about how to create Copilot-managed access points. type ManagedVolumeCreationInfo struct { Name *string DirName *string UID *uint32 GID *uint32 } // EFSVolumeConfiguration contains information about how to specify externally managed file systems. type EFSVolumeConfiguration struct { // EFSVolumeConfiguration Filesystem *string RootDirectory *string // "/" or empty are equivalent // Authorization Config AccessPointID *string IAM *string // ENABLED or DISABLED } // LogConfigOpts holds configuration that's needed if the service is configured with Firelens to route // its logs. type LogConfigOpts struct { Image *string Destination map[string]string EnableMetadata *string SecretOptions map[string]string ConfigFile *string } // HTTPHealthCheckOpts holds configuration that's needed for HTTP Health Check. type HTTPHealthCheckOpts struct { HealthCheckPath string SuccessCodes string HealthyThreshold *int64 UnhealthyThreshold *int64 Interval *int64 Timeout *int64 DeregistrationDelay *int64 GracePeriod *int64 } // AdvancedCount holds configuration for autoscaling and capacity provider // parameters. type AdvancedCount struct { Spot *int Autoscaling *AutoscalingOpts Cps []*CapacityProviderStrategy } // ContainerHealthCheck holds configuration for container health check. type ContainerHealthCheck struct { Command []string Interval *int64 Retries *int64 StartPeriod *int64 Timeout *int64 } // CapacityProviderStrategy holds the configuration needed for a // CapacityProviderStrategyItem on a Service type CapacityProviderStrategy struct { Base *int Weight *int CapacityProvider string } // AutoscalingOpts holds configuration that's needed for Auto Scaling. type AutoscalingOpts struct { MinCapacity *int MaxCapacity *int CPU *float64 Memory *float64 Requests *float64 ResponseTime *float64 QueueDelay *AutoscalingQueueDelayOpts } // AutoscalingQueueDelayOpts holds configuration to scale SQS queues. type AutoscalingQueueDelayOpts struct { AcceptableBacklogPerTask int } // ExecuteCommandOpts holds configuration that's needed for ECS Execute Command. type ExecuteCommandOpts struct{} // StateMachineOpts holds configuration needed for State Machine retries and timeout. type StateMachineOpts struct { Timeout *int Retries *int } // PublishOpts holds configuration needed if the service has publishers. type PublishOpts struct { Topics []*Topic } // Topic holds information needed to render a SNSTopic in a container definition. type Topic struct { Name *string Region string Partition string AccountID string App string Env string Svc string } // SubscribeOpts holds configuration needed if the service has subscriptions. type SubscribeOpts struct { Topics []*TopicSubscription Queue *SQSQueue } // HasTopicQueues returns true if any individual subscription has a dedicated queue. func (s *SubscribeOpts) HasTopicQueues() bool { for _, t := range s.Topics { if t.Queue != nil { return true } } return false } // TopicSubscription holds information needed to render a SNS Topic Subscription in a container definition. type TopicSubscription struct { Name *string Service *string Queue *SQSQueue } // SQSQueue holds information needed to render a SQS Queue in a container definition. type SQSQueue struct { Retention *int64 Delay *int64 Timeout *int64 DeadLetter *DeadLetterQueue } // DeadLetterQueue holds information needed to render a dead-letter SQS Queue in a container definition. type DeadLetterQueue struct { Tries *uint16 } // NetworkOpts holds AWS networking configuration for the workloads. type NetworkOpts struct { AssignPublicIP string SubnetsType string SecurityGroups []string } func defaultNetworkOpts() *NetworkOpts { return &NetworkOpts{ AssignPublicIP: EnablePublicIP, SubnetsType: PublicSubnetsPlacement, } } // RuntimePlatformOpts holds configuration needed for Platform configuration. type RuntimePlatformOpts struct { OS string Arch string } // IsDefault returns true if the platform matches the default docker image platform of "linux/amd64". func (p RuntimePlatformOpts) IsDefault() bool { if p.isEmpty() { return true } if p.OS == OSLinux && p.Arch == ArchX86 { return true } return false } // Version returns the Fargate platform version based on the selected os family. func (p RuntimePlatformOpts) Version() string { for _, os := range osFamiliesForPV100 { if p.OS == os { return "1.0.0" } } return "LATEST" } func (p RuntimePlatformOpts) isEmpty() bool { return p.OS == "" && p.Arch == "" } // WorkloadOpts holds optional data that can be provided to enable features in a workload stack template. type WorkloadOpts struct { // Additional options that are common between **all** workload templates. Variables map[string]string Secrets map[string]string Aliases []string Tags map[string]string // Used by App Runner workloads to tag App Runner service resources NestedStack *WorkloadNestedStackOpts // Outputs from nested stacks such as the addons stack. Sidecars []*SidecarOpts LogConfig *LogConfigOpts Autoscaling *AutoscalingOpts CapacityProviders []*CapacityProviderStrategy DesiredCountOnSpot *int Storage *StorageOpts Network *NetworkOpts ExecuteCommand *ExecuteCommandOpts Platform RuntimePlatformOpts EntryPoint []string Command []string DomainAlias string DockerLabels map[string]string DependsOn map[string]string Publish *PublishOpts ServiceDiscoveryEndpoint string // Additional options for service templates. WorkloadType string HealthCheck *ContainerHealthCheck HTTPHealthCheck HTTPHealthCheckOpts DeregistrationDelay *int64 AllowedSourceIps []string // Lambda functions. RulePriorityLambda string DesiredCountLambda string EnvControllerLambda string CredentialsParameter string BacklogPerTaskCalculatorLambda string // Additional options for job templates. ScheduleExpression string StateMachine *StateMachineOpts // Additional options for worker service templates. Subscribe *SubscribeOpts } // ParseRequestDrivenWebServiceInput holds data that can be provided to enable features for a request-driven web service stack. type ParseRequestDrivenWebServiceInput struct { Variables map[string]string StartCommand *string Tags map[string]string // Used by App Runner workloads to tag App Runner service resources NestedStack *WorkloadNestedStackOpts // Outputs from nested stacks such as the addons stack. EnableHealthCheck bool EnvControllerLambda string Publish *PublishOpts Platform RuntimePlatformOpts // Input needed for the custom resource that adds a custom domain to the service. Alias *string ScriptBucketName *string CustomDomainLambda *string AWSSDKLayer *string AppDNSDelegationRole *string AppDNSName *string } // ParseLoadBalancedWebService parses a load balanced web service's CloudFormation template // with the specified data object and returns its content. func (t *Template) ParseLoadBalancedWebService(data WorkloadOpts) (*Content, error) { if data.Network == nil { data.Network = defaultNetworkOpts() } return t.parseSvc(lbWebSvcTplName, data, withSvcParsingFuncs()) } // ParseRequestDrivenWebService parses a request-driven web service's CloudFormation template // with the specified data object and returns its content. func (t *Template) ParseRequestDrivenWebService(data ParseRequestDrivenWebServiceInput) (*Content, error) { return t.parseSvc(rdWebSvcTplName, data, withSvcParsingFuncs()) } // ParseBackendService parses a backend service's CloudFormation template with the specified data object and returns its content. func (t *Template) ParseBackendService(data WorkloadOpts) (*Content, error) { if data.Network == nil { data.Network = defaultNetworkOpts() } return t.parseSvc(backendSvcTplName, data, withSvcParsingFuncs()) } // ParseWorkerService parses a worker service's CloudFormation template with the specified data object and returns its content. func (t *Template) ParseWorkerService(data WorkloadOpts) (*Content, error) { if data.Network == nil { data.Network = defaultNetworkOpts() } return t.parseSvc(workerSvcTplName, data, withSvcParsingFuncs()) } // ParseScheduledJob parses a scheduled job's Cloudformation Template func (t *Template) ParseScheduledJob(data WorkloadOpts) (*Content, error) { if data.Network == nil { data.Network = defaultNetworkOpts() } return t.parseJob(scheduledJobTplName, data, withSvcParsingFuncs()) } // parseSvc parses a service's CloudFormation template with the specified data object and returns its content. func (t *Template) parseSvc(name string, data interface{}, options ...ParseOption) (*Content, error) { return t.parseWkld(name, servicesDirName, data, options...) } // parseJob parses a job's Cloudformation template with the specified data object and returns its content. func (t *Template) parseJob(name string, data interface{}, options ...ParseOption) (*Content, error) { return t.parseWkld(name, jobDirName, data, options...) } func (t *Template) parseWkld(name, wkldDirName string, data interface{}, options ...ParseOption) (*Content, error) { tpl, err := t.parse("base", fmt.Sprintf(fmtWkldCFTemplatePath, wkldDirName, name), options...) if err != nil { return nil, err } for _, templateName := range partialsWorkloadCFTemplateNames { nestedTpl, err := t.parse(templateName, fmt.Sprintf(fmtWkldPartialsCFTemplatePath, templateName), options...) if err != nil { return nil, err } _, err = tpl.AddParseTree(templateName, nestedTpl.Tree) if err != nil { return nil, fmt.Errorf("add parse tree of %s to base template: %w", templateName, err) } } buf := &bytes.Buffer{} if err := tpl.Execute(buf, data); err != nil { return nil, fmt.Errorf("execute template %s with data %v: %w", name, data, err) } return &Content{buf}, nil } func withSvcParsingFuncs() ParseOption { return func(t *template.Template) *template.Template { return t.Funcs(map[string]interface{}{ "toSnakeCase": ToSnakeCaseFunc, "hasSecrets": hasSecrets, "fmtSlice": FmtSliceFunc, "quoteSlice": QuoteSliceFunc, "randomUUID": randomUUIDFunc, "jsonMountPoints": generateMountPointJSON, "jsonSNSTopics": generateSNSJSON, "jsonQueueURIs": generateQueueURIJSON, "envControllerParams": envControllerParameters, "logicalIDSafe": StripNonAlphaNumFunc, "wordSeries": english.WordSeries, "pluralWord": english.PluralWord, }) } } func hasSecrets(opts WorkloadOpts) bool { if len(opts.Secrets) > 0 { return true } if opts.NestedStack != nil && (len(opts.NestedStack.SecretOutputs) > 0) { return true } return false } func randomUUIDFunc() (string, error) { id, err := uuid.NewRandom() if err != nil { return "", fmt.Errorf("generate random uuid: %w", err) } return id.String(), err } // envControllerParameters determines which parameters to include in the EnvController template. func envControllerParameters(o WorkloadOpts) []string { parameters := []string{} if o.WorkloadType == "Load Balanced Web Service" { parameters = append(parameters, []string{"ALBWorkloads,", "Aliases,"}...) // YAML needs the comma separator; resolved in EnvContr. } if o.Network.SubnetsType == PrivateSubnetsPlacement { parameters = append(parameters, "NATWorkloads,") // YAML needs the comma separator; resolved in EnvContr. } if o.Storage != nil && o.Storage.requiresEFSCreation() { parameters = append(parameters, "EFSWorkloads,") } return parameters } // ARN determines the arn for a topic using the SNSTopic name and account information func (t Topic) ARN() string { return fmt.Sprintf(snsARNPattern, t.Partition, t.Region, t.AccountID, t.App, t.Env, t.Svc, aws.StringValue(t.Name)) }
1
19,842
Should this be `*string`?
aws-copilot-cli
go
@@ -51,16 +51,7 @@ var _ = Context("etcd connection interruption", func() { BeforeEach(func() { felixes, etcd, client = infrastructure.StartNNodeEtcdTopology(2, infrastructure.DefaultTopologyOptions()) - - // Install a default profile that allows all ingress and egress, in the absence of any Policy. - defaultProfile := api.NewProfile() - defaultProfile.Name = "default" - defaultProfile.Spec.LabelsToApply = map[string]string{"default": ""} - defaultProfile.Spec.Egress = []api.Rule{{Action: api.Allow}} - defaultProfile.Spec.Ingress = []api.Rule{{Action: api.Allow}} - _, err := client.Profiles().Create(utils.Ctx, defaultProfile, utils.NoOptions) - Expect(err).NotTo(HaveOccurred()) - + infrastructure.CreateDefaultProfile(client, "default", map[string]string{"default": ""}, "") // Wait until the tunl0 device appears; it is created when felix inserts the ipip module // into the kernel. Eventually(func() error {
1
// +build fvtests // Copyright (c) 2018 Tigera, Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package fv_test import ( "regexp" "strings" "time" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/sirupsen/logrus" "errors" "fmt" "github.com/vishvananda/netlink" "github.com/projectcalico/felix/fv/containers" "github.com/projectcalico/felix/fv/infrastructure" "github.com/projectcalico/felix/fv/metrics" "github.com/projectcalico/felix/fv/utils" "github.com/projectcalico/felix/fv/workload" api "github.com/projectcalico/libcalico-go/lib/apis/v3" client "github.com/projectcalico/libcalico-go/lib/clientv3" ) var _ = Context("etcd connection interruption", func() { var ( etcd *containers.Container felixes []*infrastructure.Felix client client.Interface w [2]*workload.Workload cc *workload.ConnectivityChecker ) BeforeEach(func() { felixes, etcd, client = infrastructure.StartNNodeEtcdTopology(2, infrastructure.DefaultTopologyOptions()) // Install a default profile that allows all ingress and egress, in the absence of any Policy. defaultProfile := api.NewProfile() defaultProfile.Name = "default" defaultProfile.Spec.LabelsToApply = map[string]string{"default": ""} defaultProfile.Spec.Egress = []api.Rule{{Action: api.Allow}} defaultProfile.Spec.Ingress = []api.Rule{{Action: api.Allow}} _, err := client.Profiles().Create(utils.Ctx, defaultProfile, utils.NoOptions) Expect(err).NotTo(HaveOccurred()) // Wait until the tunl0 device appears; it is created when felix inserts the ipip module // into the kernel. Eventually(func() error { links, err := netlink.LinkList() if err != nil { return err } for _, link := range links { if link.Attrs().Name == "tunl0" { return nil } } return errors.New("tunl0 wasn't auto-created") }).Should(BeNil()) // Create workloads, using that profile. One on each "host". for ii := range w { wIP := fmt.Sprintf("10.65.%d.2", ii) wName := fmt.Sprintf("w%d", ii) w[ii] = workload.Run(felixes[ii], wName, "default", wIP, "8055", "tcp") w[ii].Configure(client) } cc = &workload.ConnectivityChecker{} }) AfterEach(func() { if CurrentGinkgoTestDescription().Failed { for _, felix := range felixes { felix.Exec("iptables-save", "-c") felix.Exec("ipset", "list") felix.Exec("ip", "r") } } for _, wl := range w { wl.Stop() } for _, felix := range felixes { felix.Stop() } if CurrentGinkgoTestDescription().Failed { etcd.Exec("etcdctl", "ls", "--recursive", "/") } etcd.Stop() }) It("shouldn't use excessive CPU when etcd is stopped", func() { By("having initial workload to workload connectivity", func() { cc.ExpectSome(w[0], w[1]) cc.ExpectSome(w[1], w[0]) cc.CheckConnectivity() }) etcd.Stop() delay := 10 * time.Second startCPU, err := metrics.GetFelixMetricFloat(felixes[0].IP, "process_cpu_seconds_total") Expect(err).NotTo(HaveOccurred()) time.Sleep(delay) endCPU, err := metrics.GetFelixMetricFloat(felixes[0].IP, "process_cpu_seconds_total") Expect(err).NotTo(HaveOccurred()) cpuPct := (endCPU - startCPU) / delay.Seconds() * 100 Expect(cpuPct).To(BeNumerically("<", 50)) }) It("should detect and reconnect after the etcd connection is black-holed", func() { By("having initial workload to workload connectivity", func() { cc.ExpectSome(w[0], w[1]) cc.ExpectSome(w[1], w[0]) cc.CheckConnectivity() }) By("silently dropping etcd packets", func() { // Normally, if a connection closes at either end, the other peer's traffic will get // FIN or RST responses, which cleanly shut down the connection. However, in order // to test the GRPC-level keep-alives, we want to simulate a network or NAT change that // starts to black-hole the TCP connection so that there are no responses of any kind. var portRegexp = regexp.MustCompile(`sport=(\d+).*dport=2379`) for _, felix := range felixes { // Use conntrack to identify the source port that Felix is using. out, err := felix.ExecOutput("conntrack", "-L") Expect(err).NotTo(HaveOccurred()) logrus.WithField("output", out).WithError(err).Info("Conntrack entries") found := false for _, line := range strings.Split(out, "\n") { matches := portRegexp.FindStringSubmatch(line) if len(matches) < 2 { continue } found = true // Use the raw table to drop the TCP connections (to etcd) that felix is using, // in both directions, based on source and destination port. felix.Exec("iptables", "-w", "10", // Retry this for 10 seconds, e.g. if something else is holding the lock "-W", "100000", // How often to probe the lock in microsecs. "-t", "raw", "-I", "PREROUTING", "-p", "tcp", "-s", etcd.IP, "-m", "multiport", "--destination-ports", matches[1], "-j", "DROP") felix.Exec("iptables", "-w", "10", // Retry this for 10 seconds, e.g. if something else is holding the lock "-W", "100000", // How often to probe the lock in microsecs. "-t", "raw", "-I", "OUTPUT", "-p", "tcp", "-d", etcd.IP, "-m", "multiport", "--source-ports", matches[1], "-j", "DROP") } Expect(found).To(BeTrue(), "Failed to detect any felix->etcd connections") felix.Exec("conntrack", "-D", "--orig-dst", etcd.IP) } }) By("updating policy again", func() { // Create a Policy that denies all traffic, after we've already cut the etcd connection. deny := api.NewGlobalNetworkPolicy() deny.Name = "deny-all" deny.Spec.Selector = "all()" deny.Spec.Egress = []api.Rule{{Action: api.Deny}} deny.Spec.Ingress = []api.Rule{{Action: api.Deny}} _, err := client.GlobalNetworkPolicies().Create(utils.Ctx, deny, utils.NoOptions) Expect(err).NotTo(HaveOccurred()) // Felix should start applying policy again when it detects the connection failure. cc.ResetExpectations() cc.ExpectNone(w[0], w[1]) cc.ExpectNone(w[1], w[0]) cc.CheckConnectivityWithTimeout(120 * time.Second) }) }) })
1
16,909
In the old code here there was no Source Selector, but CreateDefaultProfile will specify a Source Selector of `""`. Is that equivalent?
projectcalico-felix
go
@@ -8,10 +8,12 @@ module RSpec # Temporarily support old and new APIs while we transition the other # rspec libs to use a hash for the 2nd arg and no version arg data = Hash === replacement_or_hash ? replacement_or_hash : { :replacement => replacement_or_hash } + call_site = caller.find { |line| line !~ %r{/lib/rspec/(core|mocks|expectations|matchers|rails)/} } + RSpec.configuration.reporter.deprecation( { :deprecated => deprecated, - :call_site => caller(0)[2] + :call_site => call_site }.merge(data) ) end
1
module RSpec module Core module Deprecation # @private # # Used internally to print deprecation warnings def deprecate(deprecated, replacement_or_hash={}, ignore_version=nil) # Temporarily support old and new APIs while we transition the other # rspec libs to use a hash for the 2nd arg and no version arg data = Hash === replacement_or_hash ? replacement_or_hash : { :replacement => replacement_or_hash } RSpec.configuration.reporter.deprecation( { :deprecated => deprecated, :call_site => caller(0)[2] }.merge(data) ) end # @private # # Used internally to print deprecation warnings def warn_deprecation(message) RSpec.configuration.reporter.deprecation :message => message end end end extend(Core::Deprecation) end
1
9,403
We should pick this across for all our deprecation specs
rspec-rspec-core
rb
@@ -45,8 +45,8 @@ func init() { } var ( - kindBinary = flag.String("kindBinary", "kind", "path to the kind binary") - managerImageTar = flag.String("managerImageTar", "", "a script to load the manager Docker image into Docker") + kindBinary = flag.String("kindBinary", "kind", "path to the kind binary") + kubectlBinary = flag.String("kubectlBinary", "kubectl", "path to the kubectl binary") ) // Cluster represents the running state of a KIND cluster.
1
/* Copyright 2018 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package kind import ( "bytes" "flag" "fmt" "io" "io/ioutil" "os" "os/exec" "strings" "github.com/onsi/ginkgo" "github.com/onsi/ginkgo/config" "github.com/onsi/gomega" "k8s.io/client-go/kubernetes" restclient "k8s.io/client-go/rest" "k8s.io/client-go/tools/clientcmd" ) func init() { // Turn on verbose by default to get spec names config.DefaultReporterConfig.Verbose = true // Turn on EmitSpecProgress to get spec progress (especially on interrupt) config.GinkgoConfig.EmitSpecProgress = true } var ( kindBinary = flag.String("kindBinary", "kind", "path to the kind binary") managerImageTar = flag.String("managerImageTar", "", "a script to load the manager Docker image into Docker") ) // Cluster represents the running state of a KIND cluster. // An empty struct is enough to call Setup() on. type Cluster struct { Name string tmpDir string kubepath string } // Setup creates a kind cluster and returns a path to the kubeconfig func (c *Cluster) Setup() { var err error c.tmpDir, err = ioutil.TempDir("", "kind-home") gomega.Expect(err).To(gomega.BeNil()) fmt.Fprintf(ginkgo.GinkgoWriter, "creating Kind cluster named %q\n", c.Name) c.run(exec.Command(*kindBinary, "create", "cluster", "--name", c.Name)) path := c.runWithOutput(exec.Command(*kindBinary, "get", "kubeconfig-path", "--name", c.Name)) c.kubepath = strings.TrimSpace(string(path)) fmt.Fprintf(ginkgo.GinkgoWriter, "kubeconfig path: %q. Can use the following to access the cluster:\n", c.kubepath) fmt.Fprintf(ginkgo.GinkgoWriter, "export KUBECONFIG=%s\n", c.kubepath) if *managerImageTar != "" { fmt.Fprintf( ginkgo.GinkgoWriter, "loading image %q into Kind node\n", *managerImageTar) c.run(exec.Command(*kindBinary, "load", "image-archive", "--name", c.Name, *managerImageTar)) } c.applyYAML() } // Teardown attempts to delete the KIND cluster func (c *Cluster) Teardown() { c.run(exec.Command(*kindBinary, "delete", "cluster", "--name", c.Name)) os.RemoveAll(c.tmpDir) } // applyYAML takes the provided providerComponentsYAML applies them to a cluster given by the kubeconfig path kubeConfig. func (c *Cluster) applyYAML() { // TODO: Update this step to account for separate capi, capa, and cabpk provider yaml } // RestConfig returns a rest configuration pointed at the provisioned cluster func (c *Cluster) RestConfig() *restclient.Config { cfg, err := clientcmd.BuildConfigFromFlags("", c.kubepath) gomega.ExpectWithOffset(1, err).To(gomega.BeNil()) return cfg } // KubeClient returns a Kubernetes client pointing at the provisioned cluster func (c *Cluster) KubeClient() kubernetes.Interface { cfg := c.RestConfig() client, err := kubernetes.NewForConfig(cfg) gomega.ExpectWithOffset(1, err).To(gomega.BeNil()) return client } func (c *Cluster) runWithOutput(cmd *exec.Cmd) []byte { var stdout bytes.Buffer cmd.Stdout = &stdout c.run(cmd) return stdout.Bytes() } func (c *Cluster) run(cmd *exec.Cmd) { errPipe, err := cmd.StderrPipe() gomega.ExpectWithOffset(1, err).To(gomega.BeNil()) cmd.Env = append( cmd.Env, // KIND positions the configuration file relative to HOME. // To prevent clobbering an existing KIND installation, override this // n.b. HOME isn't always set inside BAZEL fmt.Sprintf("HOME=%s", c.tmpDir), //needed for Docker. TODO(EKF) Should be properly hermetic fmt.Sprintf("PATH=%s", os.Getenv("PATH")), ) // Log output go captureOutput(errPipe, "stderr") if cmd.Stdout == nil { outPipe, err := cmd.StdoutPipe() gomega.ExpectWithOffset(1, err).To(gomega.BeNil()) go captureOutput(outPipe, "stdout") } gomega.ExpectWithOffset(1, cmd.Run()).To(gomega.BeNil()) } func captureOutput(pipe io.ReadCloser, label string) { buffer := &bytes.Buffer{} defer pipe.Close() for { n, _ := buffer.ReadFrom(pipe) if n == 0 { return } fmt.Fprintf(ginkgo.GinkgoWriter, "[%s] %s\n", label, buffer.String()) } }
1
11,119
Longer term, I think it could be valuable to move this to cluster-api, and then other repos could take advantage of this as well.
kubernetes-sigs-cluster-api-provider-aws
go
@@ -1416,7 +1416,7 @@ func describeBPFTests(opts ...bpfTestOpt) bool { if testOpts.connTimeEnabled { Skip("FIXME externalClient also does conntime balancing") } - + externalClient.EnsureBinary("test-connection") cc.ExpectSome(externalClient, TargetIP(felixes[1].IP), npPort) cc.CheckConnectivity() })
1
// Copyright (c) 2020 Tigera, Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // +build fvtests package fv_test import ( "context" "encoding/json" "fmt" "net" "os" "regexp" "sort" "strconv" "strings" "time" "github.com/davecgh/go-spew/spew" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/pkg/errors" log "github.com/sirupsen/logrus" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/intstr" "k8s.io/client-go/kubernetes" "github.com/projectcalico/libcalico-go/lib/apiconfig" api "github.com/projectcalico/libcalico-go/lib/apis/v3" client "github.com/projectcalico/libcalico-go/lib/clientv3" "github.com/projectcalico/libcalico-go/lib/ipam" cnet "github.com/projectcalico/libcalico-go/lib/net" "github.com/projectcalico/libcalico-go/lib/numorstring" options2 "github.com/projectcalico/libcalico-go/lib/options" "github.com/projectcalico/felix/bpf" "github.com/projectcalico/felix/bpf/conntrack" "github.com/projectcalico/felix/bpf/nat" . "github.com/projectcalico/felix/fv/connectivity" "github.com/projectcalico/felix/fv/containers" "github.com/projectcalico/felix/fv/infrastructure" "github.com/projectcalico/felix/fv/utils" "github.com/projectcalico/felix/fv/workload" ) // We run with and without connection-time load balancing for a couple of reasons: // - We can only test the non-connection time NAT logic (and node ports) with it disabled. // - Since the connection time program applies to the whole host, the different felix nodes actually share the // connection-time program. This is a bit of a broken test but it's better than nothing since all felix nodes // should be programming the same NAT mappings. var _ = describeBPFTests(withProto("tcp"), withConnTimeLoadBalancingEnabled(), withNonProtocolDependentTests()) var _ = describeBPFTests(withProto("udp"), withConnTimeLoadBalancingEnabled()) var _ = describeBPFTests(withProto("udp"), withConnTimeLoadBalancingEnabled(), withUDPUnConnected()) var _ = describeBPFTests(withProto("tcp")) var _ = describeBPFTests(withProto("udp")) var _ = describeBPFTests(withProto("udp"), withUDPUnConnected()) var _ = describeBPFTests(withProto("udp"), withUDPConnectedRecvMsg(), withConnTimeLoadBalancingEnabled()) var _ = describeBPFTests(withTunnel("ipip"), withProto("tcp"), withConnTimeLoadBalancingEnabled()) var _ = describeBPFTests(withTunnel("ipip"), withProto("udp"), withConnTimeLoadBalancingEnabled()) var _ = describeBPFTests(withTunnel("ipip"), withProto("tcp")) var _ = describeBPFTests(withTunnel("ipip"), withProto("udp")) var _ = describeBPFTests(withProto("tcp"), withDSR()) var _ = describeBPFTests(withProto("udp"), withDSR()) var _ = describeBPFTests(withTunnel("ipip"), withProto("tcp"), withDSR()) var _ = describeBPFTests(withTunnel("ipip"), withProto("udp"), withDSR()) // Run a stripe of tests with BPF logging disabled since the compiler tends to optimise the code differently // with debug disabled and that can lead to verifier issues. var _ = describeBPFTests(withProto("tcp"), withConnTimeLoadBalancingEnabled(), withBPFLogLevel("info")) type bpfTestOptions struct { connTimeEnabled bool protocol string udpUnConnected bool bpfLogLevel string tunnel string dsr bool udpConnRecvMsg bool nonProtoTests bool } type bpfTestOpt func(opts *bpfTestOptions) func withProto(proto string) bpfTestOpt { return func(opts *bpfTestOptions) { opts.protocol = proto } } func withConnTimeLoadBalancingEnabled() bpfTestOpt { return func(opts *bpfTestOptions) { opts.connTimeEnabled = true } } func withNonProtocolDependentTests() bpfTestOpt { return func(opts *bpfTestOptions) { opts.nonProtoTests = true } } func withBPFLogLevel(level string) bpfTestOpt { return func(opts *bpfTestOptions) { opts.bpfLogLevel = level } } func withTunnel(tunnel string) bpfTestOpt { return func(opts *bpfTestOptions) { opts.tunnel = tunnel } } func withUDPUnConnected() bpfTestOpt { return func(opts *bpfTestOptions) { opts.udpUnConnected = true } } func withDSR() bpfTestOpt { return func(opts *bpfTestOptions) { opts.dsr = true } } func withUDPConnectedRecvMsg() bpfTestOpt { return func(opts *bpfTestOptions) { opts.udpConnRecvMsg = true } } const expectedRouteDump = `10.65.0.0/16: remote in-pool nat-out 10.65.0.2/32: local workload in-pool nat-out idx - 10.65.0.3/32: local workload in-pool nat-out idx - 10.65.0.4/32: local workload in-pool nat-out idx - 10.65.1.0/26: remote workload in-pool nat-out nh FELIX_1 10.65.2.0/26: remote workload in-pool nat-out nh FELIX_2 FELIX_0/32: local host idx - FELIX_1/32: remote host FELIX_2/32: remote host` const expectedRouteDumpIPIP = `10.65.0.0/16: remote in-pool nat-out 10.65.0.1/32: local host 10.65.0.2/32: local workload in-pool nat-out idx - 10.65.0.3/32: local workload in-pool nat-out idx - 10.65.0.4/32: local workload in-pool nat-out idx - 10.65.1.0/26: remote workload in-pool nat-out nh FELIX_1 10.65.2.0/26: remote workload in-pool nat-out nh FELIX_2 FELIX_0/32: local host idx - FELIX_1/32: remote host FELIX_2/32: remote host` const extIP = "10.1.2.3" func describeBPFTests(opts ...bpfTestOpt) bool { testOpts := bpfTestOptions{ bpfLogLevel: "debug", tunnel: "none", } for _, o := range opts { o(&testOpts) } protoExt := "" if testOpts.udpUnConnected { protoExt = "-unconnected" } if testOpts.udpConnRecvMsg { protoExt = "-conn-recvmsg" } desc := fmt.Sprintf("_BPF_ _BPF-SAFE_ BPF tests (%s%s, ct=%v, log=%s, tunnel=%s, dsr=%v)", testOpts.protocol, protoExt, testOpts.connTimeEnabled, testOpts.bpfLogLevel, testOpts.tunnel, testOpts.dsr, ) return infrastructure.DatastoreDescribe(desc, []apiconfig.DatastoreType{apiconfig.Kubernetes}, func(getInfra infrastructure.InfraFactory) { var ( infra infrastructure.DatastoreInfra felixes []*infrastructure.Felix calicoClient client.Interface cc *Checker externalClient *containers.Container deadWorkload *workload.Workload bpfLog *containers.Container options infrastructure.TopologyOptions numericProto uint8 expectedRoutes string ) switch testOpts.protocol { case "tcp": numericProto = 6 case "udp": numericProto = 17 default: Fail("bad protocol option") } BeforeEach(func() { if os.Getenv("FELIX_FV_ENABLE_BPF") != "true" { Skip("Skipping BPF test in non-BPF run.") } bpfLog = containers.Run("bpf-log", containers.RunOpts{AutoRemove: true}, "--privileged", "calico/bpftool:v5.3-amd64", "/bpftool", "prog", "tracelog") infra = getInfra() cc = &Checker{ CheckSNAT: true, } cc.Protocol = testOpts.protocol if testOpts.protocol == "udp" && testOpts.udpUnConnected { cc.Protocol += "-noconn" } if testOpts.protocol == "udp" && testOpts.udpConnRecvMsg { cc.Protocol += "-recvmsg" } options = infrastructure.DefaultTopologyOptions() options.FelixLogSeverity = "debug" options.NATOutgoingEnabled = true switch testOpts.tunnel { case "none": options.IPIPEnabled = false options.IPIPRoutesEnabled = false expectedRoutes = expectedRouteDump case "ipip": options.IPIPEnabled = true options.IPIPRoutesEnabled = true expectedRoutes = expectedRouteDumpIPIP default: Fail("bad tunnel option") } options.ExtraEnvVars["FELIX_BPFConnectTimeLoadBalancingEnabled"] = fmt.Sprint(testOpts.connTimeEnabled) options.ExtraEnvVars["FELIX_BPFLogLevel"] = fmt.Sprint(testOpts.bpfLogLevel) if testOpts.dsr { options.ExtraEnvVars["FELIX_BPFExternalServiceMode"] = "dsr" } }) JustAfterEach(func() { if CurrentGinkgoTestDescription().Failed { currBpfsvcs, currBpfeps := dumpNATmaps(felixes) for i, felix := range felixes { felix.Exec("iptables-save", "-c") felix.Exec("ip", "r") felix.Exec("ip", "route", "show", "cached") felix.Exec("calico-bpf", "ipsets", "dump") felix.Exec("calico-bpf", "routes", "dump") felix.Exec("calico-bpf", "nat", "dump") felix.Exec("calico-bpf", "conntrack", "dump") log.Infof("[%d]FrontendMap: %+v", i, currBpfsvcs[i]) log.Infof("[%d]NATBackend: %+v", i, currBpfeps[i]) log.Infof("[%d]SendRecvMap: %+v", i, dumpSendRecvMap(felix)) } externalClient.Exec("ip", "route", "show", "cached") } }) AfterEach(func() { log.Info("AfterEach starting") for _, f := range felixes { f.Exec("calico-bpf", "connect-time", "clean") f.Stop() } infra.Stop() externalClient.Stop() bpfLog.Stop() log.Info("AfterEach done") }) createPolicy := func(policy *api.GlobalNetworkPolicy) *api.GlobalNetworkPolicy { log.WithField("policy", dumpResource(policy)).Info("Creating policy") policy, err := calicoClient.GlobalNetworkPolicies().Create(utils.Ctx, policy, utils.NoOptions) Expect(err).NotTo(HaveOccurred()) return policy } updatePolicy := func(policy *api.GlobalNetworkPolicy) *api.GlobalNetworkPolicy { log.WithField("policy", dumpResource(policy)).Info("Updating policy") policy, err := calicoClient.GlobalNetworkPolicies().Update(utils.Ctx, policy, utils.NoOptions) Expect(err).NotTo(HaveOccurred()) return policy } _ = updatePolicy Describe("with a single node and an allow-all policy", func() { var ( hostW *workload.Workload w [2]*workload.Workload ) if !testOpts.connTimeEnabled { // These tests don't depend on NAT. return } JustBeforeEach(func() { felixes, calicoClient = infrastructure.StartNNodeTopology(1, options, infra) hostW = workload.Run( felixes[0], "host", "default", felixes[0].IP, // Same IP as felix means "run in the host's namespace" "8055", testOpts.protocol) // Start a couple of workloads so we can check workload-to-workload and workload-to-host. for i := 0; i < 2; i++ { wIP := fmt.Sprintf("10.65.0.%d", i+2) w[i] = workload.Run(felixes[0], fmt.Sprintf("w%d", i), "default", wIP, "8055", testOpts.protocol) w[i].WorkloadEndpoint.Labels = map[string]string{"name": w[i].Name} w[i].ConfigureInDatastore(infra) } err := infra.AddDefaultDeny() Expect(err).NotTo(HaveOccurred()) pol := api.NewGlobalNetworkPolicy() pol.Namespace = "fv" pol.Name = "policy-1" pol.Spec.Ingress = []api.Rule{{Action: "Allow"}} pol.Spec.Egress = []api.Rule{{Action: "Allow"}} pol.Spec.Selector = "all()" pol = createPolicy(pol) }) Describe("with DefaultEndpointToHostAction=DROP", func() { BeforeEach(func() { options.ExtraEnvVars["FELIX_DefaultEndpointToHostAction"] = "DROP" }) It("should only allow traffic from workload to workload", func() { cc.ExpectSome(w[0], w[1]) cc.ExpectSome(w[1], w[0]) cc.ExpectNone(w[1], hostW) cc.ExpectSome(hostW, w[0]) cc.CheckConnectivity() }) }) getMapIDByPath := func(felix *infrastructure.Felix, filename string) (int, error) { out, err := felix.ExecOutput("bpftool", "map", "show", "pinned", filename, "-j") if err != nil { return 0, err } var mapMeta struct { ID int `json:"id"` Error string `json:"error"` } err = json.Unmarshal([]byte(out), &mapMeta) if err != nil { return 0, err } if mapMeta.Error != "" { return 0, errors.New(mapMeta.Error) } return mapMeta.ID, nil } mustGetMapIDByPath := func(felix *infrastructure.Felix, filename string) int { var mapID int Eventually(func() error { var err error mapID, err = getMapIDByPath(felix, filename) return err }, "5s").ShouldNot(HaveOccurred()) return mapID } Describe("with DefaultEndpointToHostAction=ACCEPT", func() { BeforeEach(func() { options.ExtraEnvVars["FELIX_DefaultEndpointToHostAction"] = "ACCEPT" }) It("should traffic from workload to workload and to/from host", func() { cc.ExpectSome(w[0], w[1]) cc.ExpectSome(w[1], w[0]) cc.ExpectSome(w[1], hostW) cc.ExpectSome(hostW, w[0]) cc.CheckConnectivity() }) }) if testOpts.protocol != "udp" { // No need to run these tests per-protocol. mapPath := conntrack.Map(&bpf.MapContext{}).Path() Describe("with map repinning enabled", func() { BeforeEach(func() { options.ExtraEnvVars["FELIX_DebugBPFMapRepinEnabled"] = "true" }) It("should repin maps", func() { // Wait for the first felix to create its maps. mapID := mustGetMapIDByPath(felixes[0], mapPath) // Now, start a completely independent felix, which will get its own bpffs. It should re-pin the // maps, picking up the ones from the first felix. extraFelix, _ := infrastructure.StartSingleNodeTopology(options, infra) defer extraFelix.Stop() secondMapID := mustGetMapIDByPath(extraFelix, mapPath) Expect(mapID).NotTo(BeNumerically("==", 0)) Expect(mapID).To(BeNumerically("==", secondMapID)) }) }) Describe("with map repinning disabled", func() { It("should repin maps", func() { // Wait for the first felix to create its maps. mapID := mustGetMapIDByPath(felixes[0], mapPath) // Now, start a completely independent felix, which will get its own bpffs. It should make its own // maps. extraFelix, _ := infrastructure.StartSingleNodeTopology(options, infra) defer extraFelix.Stop() secondMapID := mustGetMapIDByPath(extraFelix, mapPath) Expect(mapID).NotTo(BeNumerically("==", 0)) Expect(mapID).NotTo(BeNumerically("==", secondMapID)) }) }) } if testOpts.nonProtoTests { // We can only test that felix _sets_ this because the flag is one-way and cannot be unset. It("should enable the kernel.unprivileged_bpf_disabled sysctl", func() { Eventually(func() string { out, err := felixes[0].ExecOutput("sysctl", "kernel.unprivileged_bpf_disabled") if err != nil { log.WithError(err).Error("Failed to run sysctl") } return out }).Should(ContainSubstring("kernel.unprivileged_bpf_disabled = 1")) }) } }) const numNodes = 3 Describe(fmt.Sprintf("with a %d node cluster", numNodes), func() { var ( w [numNodes][2]*workload.Workload hostW [numNodes]*workload.Workload ) BeforeEach(func() { felixes, calicoClient = infrastructure.StartNNodeTopology(numNodes, options, infra) addWorkload := func(run bool, ii, wi, port int, labels map[string]string) *workload.Workload { if labels == nil { labels = make(map[string]string) } wIP := fmt.Sprintf("10.65.%d.%d", ii, wi+2) wName := fmt.Sprintf("w%d%d", ii, wi) w := workload.New(felixes[ii], wName, "default", wIP, strconv.Itoa(port), testOpts.protocol) if run { w.Start() } labels["name"] = w.Name labels["workload"] = "regular" w.WorkloadEndpoint.Labels = labels w.ConfigureInDatastore(infra) // Assign the workload's IP in IPAM, this will trigger calculation of routes. err := calicoClient.IPAM().AssignIP(context.Background(), ipam.AssignIPArgs{ IP: cnet.MustParseIP(wIP), HandleID: &w.Name, Attrs: map[string]string{ ipam.AttributeNode: felixes[ii].Hostname, }, Hostname: felixes[ii].Hostname, }) Expect(err).NotTo(HaveOccurred()) return w } // Start a host networked workload on each host for connectivity checks. for ii := range felixes { // We tell each host-networked workload to open: // TODO: Copied from another test // - its normal (uninteresting) port, 8055 // - port 2379, which is both an inbound and an outbound failsafe port // - port 22, which is an inbound failsafe port. // This allows us to test the interaction between do-not-track policy and failsafe // ports. hostW[ii] = workload.Run( felixes[ii], fmt.Sprintf("host%d", ii), "default", felixes[ii].IP, // Same IP as felix means "run in the host's namespace" "8055", testOpts.protocol) hostW[ii].WorkloadEndpoint.Labels = map[string]string{"name": hostW[ii].Name} hostW[ii].ConfigureInDatastore(infra) // Two workloads on each host so we can check the same host and other host cases. w[ii][0] = addWorkload(true, ii, 0, 8055, map[string]string{"port": "8055"}) w[ii][1] = addWorkload(true, ii, 1, 8056, nil) } // Create a workload on node 0 that does not run, but we can use it to set up paths deadWorkload = addWorkload(false, 0, 2, 8057, nil) // We will use this container to model an external client trying to connect into // workloads on a host. Create a route in the container for the workload CIDR. // TODO: Copied from another test externalClient = containers.Run("external-client", containers.RunOpts{AutoRemove: true}, "--privileged", // So that we can add routes inside the container. utils.Config.BusyboxImage, "/bin/sh", "-c", "sleep 1000") _ = externalClient err := infra.AddDefaultDeny() Expect(err).NotTo(HaveOccurred()) }) It("should have correct routes", func() { dumpRoutes := func() string { out, err := felixes[0].ExecOutput("calico-bpf", "routes", "dump") if err != nil { return fmt.Sprint(err) } lines := strings.Split(out, "\n") var filteredLines []string idxRE := regexp.MustCompile(`idx \d+`) for _, l := range lines { l = strings.TrimLeft(l, " ") if len(l) == 0 { continue } l = strings.ReplaceAll(l, felixes[0].IP, "FELIX_0") l = strings.ReplaceAll(l, felixes[1].IP, "FELIX_1") l = strings.ReplaceAll(l, felixes[2].IP, "FELIX_2") l = idxRE.ReplaceAllLiteralString(l, "idx -") filteredLines = append(filteredLines, l) } sort.Strings(filteredLines) return strings.Join(filteredLines, "\n") } Eventually(dumpRoutes).Should(Equal(expectedRoutes)) }) It("should only allow traffic from the local host by default", func() { // Same host, other workload. cc.ExpectNone(w[0][0], w[0][1]) cc.ExpectNone(w[0][1], w[0][0]) // Workloads on other host. cc.ExpectNone(w[0][0], w[1][0]) cc.ExpectNone(w[1][0], w[0][0]) // Hosts. cc.ExpectSome(felixes[0], w[0][0]) cc.ExpectNone(felixes[1], w[0][0]) cc.CheckConnectivity() }) Context("with a policy allowing ingress to w[0][0] from all regular workloads", func() { var ( pol *api.GlobalNetworkPolicy k8sClient *kubernetes.Clientset ) BeforeEach(func() { pol = api.NewGlobalNetworkPolicy() pol.Namespace = "fv" pol.Name = "policy-1" pol.Spec.Ingress = []api.Rule{ { Action: "Allow", Source: api.EntityRule{ Selector: "workload=='regular'", }, }, } pol.Spec.Egress = []api.Rule{ { Action: "Allow", Source: api.EntityRule{ Selector: "workload=='regular'", }, }, } pol.Spec.Selector = "workload=='regular'" pol = createPolicy(pol) k8sClient = infra.(*infrastructure.K8sDatastoreInfra).K8sClient _ = k8sClient }) It("should handle NAT outgoing", func() { By("SNATting outgoing traffic with the flag set") cc.ExpectSNAT(w[0][0], felixes[0].IP, hostW[1]) cc.CheckConnectivity() if testOpts.tunnel == "none" { By("Leaving traffic alone with the flag clear") pool, err := calicoClient.IPPools().Get(context.TODO(), "test-pool", options2.GetOptions{}) Expect(err).NotTo(HaveOccurred()) pool.Spec.NATOutgoing = false pool, err = calicoClient.IPPools().Update(context.TODO(), pool, options2.SetOptions{}) Expect(err).NotTo(HaveOccurred()) cc.ResetExpectations() cc.ExpectSNAT(w[0][0], w[0][0].IP, hostW[1]) cc.CheckConnectivity() By("SNATting again with the flag set") pool.Spec.NATOutgoing = true pool, err = calicoClient.IPPools().Update(context.TODO(), pool, options2.SetOptions{}) Expect(err).NotTo(HaveOccurred()) cc.ResetExpectations() cc.ExpectSNAT(w[0][0], felixes[0].IP, hostW[1]) cc.CheckConnectivity() } }) It("connectivity from all workloads via workload 0's main IP", func() { cc.ExpectSome(w[0][1], w[0][0]) cc.ExpectSome(w[1][0], w[0][0]) cc.ExpectSome(w[1][1], w[0][0]) cc.CheckConnectivity() }) It("should not be able to spoof IP", func() { if testOpts.protocol != "udp" { return } By("allowing any traffic", func() { pol.Spec.Ingress = []api.Rule{ { Action: "Allow", Source: api.EntityRule{ Nets: []string{ "0.0.0.0/0", }, }, }, } pol = updatePolicy(pol) cc.ExpectSome(w[1][0], w[0][0]) cc.ExpectSome(w[1][1], w[0][0]) cc.CheckConnectivity() }) By("testing that packet sent by another workload is dropped", func() { tcpdump := w[0][0].AttachTCPDump() tcpdump.SetLogEnabled(true) matcher := fmt.Sprintf("IP %s\\.30444 > %s\\.30444: UDP", w[1][0].IP, w[0][0].IP) tcpdump.AddMatcher("UDP-30444", regexp.MustCompile(matcher)) tcpdump.Start(testOpts.protocol, "port", "30444", "or", "port", "30445") defer tcpdump.Stop() // send a packet from the correct workload to create a conntrack entry _, err := w[1][0].RunCmd("/pktgen", w[1][0].IP, w[0][0].IP, "udp", "--port-src", "30444", "--port-dst", "30444") Expect(err).NotTo(HaveOccurred()) // We must eventually see the packet at the target Eventually(func() int { return tcpdump.MatchCount("UDP-30444") }). Should(BeNumerically("==", 1), matcher) // Send a spoofed packet from a different pod. Since we hit the // conntrack we would not do the WEP only RPF check. _, err = w[1][1].RunCmd("/pktgen", w[1][0].IP, w[0][0].IP, "udp", "--port-src", "30444", "--port-dst", "30444") Expect(err).NotTo(HaveOccurred()) // Since the packet will get dropped, we would not see it at the dest. // So we send another good packet from the spoofing workload, that we // will see at the dest. matcher2 := fmt.Sprintf("IP %s\\.30445 > %s\\.30445: UDP", w[1][1].IP, w[0][0].IP) tcpdump.AddMatcher("UDP-30445", regexp.MustCompile(matcher2)) _, err = w[1][1].RunCmd("/pktgen", w[1][1].IP, w[0][0].IP, "udp", "--port-src", "30445", "--port-dst", "30445") Expect(err).NotTo(HaveOccurred()) // Wait for the good packet from the bad workload Eventually(func() int { return tcpdump.MatchCount("UDP-30445") }). Should(BeNumerically("==", 1), matcher2) // Check that we have not seen the spoofed packet. If there was not // packet reordering, which in out setup is guaranteed not to happen, // we know that the spoofed packet was dropped. Expect(tcpdump.MatchCount("UDP-30444")).To(BeNumerically("==", 1), matcher) }) var eth20, eth30 *workload.Workload defer func() { if eth20 != nil { eth20.Stop() } if eth30 != nil { eth30.Stop() } }() fakeWorkloadIP := "10.65.15.15" By("setting up node's fake external ifaces", func() { // We name the ifaces ethXY since such ifaces are // treated by felix as external to the node // // Using a test-workload creates the namespaces and the // interfaces to emulate the host NICs eth20 = &workload.Workload{ Name: "eth20", C: felixes[1].Container, IP: "192.168.20.1", Ports: "57005", // 0xdead Protocol: testOpts.protocol, InterfaceName: "eth20", } eth20.Start() // assign address to eth20 and add route to the .20 network felixes[1].Exec("ip", "route", "add", "192.168.20.0/24", "dev", "eth20") felixes[1].Exec("ip", "addr", "add", "10.0.0.20/32", "dev", "eth20") _, err := eth20.RunCmd("ip", "route", "add", "10.0.0.20/32", "dev", "eth0") Expect(err).NotTo(HaveOccurred()) // Add a route to the test workload to the fake external // client emulated by the test-workload _, err = eth20.RunCmd("ip", "route", "add", w[1][1].IP+"/32", "via", "10.0.0.20") Expect(err).NotTo(HaveOccurred()) eth30 = &workload.Workload{ Name: "eth30", C: felixes[1].Container, IP: "192.168.30.1", Ports: "57005", // 0xdead Protocol: testOpts.protocol, InterfaceName: "eth30", } eth30.Start() // assign address to eth30 and add route to the .30 network felixes[1].Exec("ip", "route", "add", "192.168.30.0/24", "dev", "eth30") felixes[1].Exec("ip", "addr", "add", "10.0.0.30/32", "dev", "eth30") _, err = eth30.RunCmd("ip", "route", "add", "10.0.0.30/32", "dev", "eth0") Expect(err).NotTo(HaveOccurred()) // Add a route to the test workload to the fake external // client emulated by the test-workload _, err = eth30.RunCmd("ip", "route", "add", w[1][1].IP+"/32", "via", "10.0.0.30") Expect(err).NotTo(HaveOccurred()) // Make sure that networking with the .20 and .30 networks works cc.ResetExpectations() cc.ExpectSome(w[1][1], TargetIP(eth20.IP), 0xdead) cc.ExpectSome(w[1][1], TargetIP(eth30.IP), 0xdead) cc.CheckConnectivity() }) By("testing that external traffic updates the RPF check if routing changes", func() { // set the route to the fake workload to .20 network felixes[1].Exec("ip", "route", "add", fakeWorkloadIP+"/32", "dev", "eth20") tcpdump := w[1][1].AttachTCPDump() tcpdump.SetLogEnabled(true) matcher := fmt.Sprintf("IP %s\\.30446 > %s\\.30446: UDP", fakeWorkloadIP, w[1][1].IP) tcpdump.AddMatcher("UDP-30446", regexp.MustCompile(matcher)) tcpdump.Start() defer tcpdump.Stop() _, err := eth20.RunCmd("/pktgen", fakeWorkloadIP, w[1][1].IP, "udp", "--port-src", "30446", "--port-dst", "30446") Expect(err).NotTo(HaveOccurred()) // Expect to receive the packet from the .20 as the routing is correct Eventually(func() int { return tcpdump.MatchCount("UDP-30446") }). Should(BeNumerically("==", 1), matcher) ctBefore := dumpCTMap(felixes[1]) k := conntrack.NewKey(17, net.ParseIP(w[1][1].IP).To4(), 30446, net.ParseIP(fakeWorkloadIP).To4(), 30446) Expect(ctBefore).To(HaveKey(k)) // XXX Since the same code is used to do the drop of spoofed // packet between pods, we do not repeat it here as it is not 100% // bulletproof. // // We should perhaps compare the iptables counter and see if the // packet was dropped by the RPF check. // Change the routing to be from the .30 felixes[1].Exec("ip", "route", "del", fakeWorkloadIP+"/32", "dev", "eth20") felixes[1].Exec("ip", "route", "add", fakeWorkloadIP+"/32", "dev", "eth30") _, err = eth30.RunCmd("/pktgen", fakeWorkloadIP, w[1][1].IP, "udp", "--port-src", "30446", "--port-dst", "30446") Expect(err).NotTo(HaveOccurred()) // Expect the packet from the .30 to make it through as RPF will // allow it and we will update the expected interface Eventually(func() int { return tcpdump.MatchCount("UDP-30446") }). Should(BeNumerically("==", 2), matcher) ctAfter := dumpCTMap(felixes[1]) Expect(ctAfter).To(HaveKey(k)) // Ifindex must have changed // B2A because of IPA > IPB - deterministic Expect(ctBefore[k].Data().B2A.Ifindex).NotTo(BeNumerically("==", 0)) Expect(ctAfter[k].Data().B2A.Ifindex).NotTo(BeNumerically("==", 0)) Expect(ctBefore[k].Data().B2A.Ifindex). NotTo(BeNumerically("==", ctAfter[k].Data().B2A.Ifindex)) }) }) Describe("Test Load balancer service with external IP", func() { srcIPRange := []string{} externalIP := []string{extIP} testSvcName := "test-lb-service-extip" tgtPort := 8055 var testSvc *v1.Service var ip []string var port uint16 BeforeEach(func() { if testOpts.connTimeEnabled { Skip("FIXME externalClient also does conntime balancing") } externalClient.EnsureBinary("test-connection") externalClient.Exec("ip", "route", "add", extIP, "via", felixes[0].IP) testSvc = k8sCreateLBServiceWithEndPoints(k8sClient, testSvcName, "10.101.0.10", w[0][0], 80, tgtPort, testOpts.protocol, externalIP, srcIPRange) // when we point Load Balancer to a node in GCE it adds local routes to the external IP on the hosts. // Similarity add local routes for externalIP on felixes[0], felixes[1] felixes[1].Exec("ip", "route", "add", "local", extIP, "dev", "eth0") felixes[0].Exec("ip", "route", "add", "local", extIP, "dev", "eth0") ip = testSvc.Spec.ExternalIPs port = uint16(testSvc.Spec.Ports[0].Port) pol.Spec.Ingress = []api.Rule{ { Action: "Allow", Source: api.EntityRule{ Nets: []string{ externalClient.IP + "/32", w[0][1].IP + "/32", w[1][0].IP + "/32", w[1][1].IP + "/32", }, }, }, } pol = updatePolicy(pol) }) It("should have connectivity from workloads[1][0],[1][1], [0][1] and external client via external IP to workload 0", func() { cc.ExpectSome(w[1][0], TargetIP(ip[0]), port) cc.ExpectSome(w[1][1], TargetIP(ip[0]), port) cc.ExpectSome(w[0][1], TargetIP(ip[0]), port) cc.ExpectSome(externalClient, TargetIP(ip[0]), port) cc.CheckConnectivity() }) }) Context("Test load balancer service with src ranges", func() { var testSvc *v1.Service tgtPort := 8055 externalIP := []string{extIP} srcIPRange := []string{"10.65.1.3/24"} testSvcName := "test-lb-service-extip" var ip []string var port uint16 BeforeEach(func() { testSvc = k8sCreateLBServiceWithEndPoints(k8sClient, testSvcName, "10.101.0.10", w[0][0], 80, tgtPort, testOpts.protocol, externalIP, srcIPRange) felixes[1].Exec("ip", "route", "add", "local", extIP, "dev", "eth0") felixes[0].Exec("ip", "route", "add", "local", extIP, "dev", "eth0") ip = testSvc.Spec.ExternalIPs port = uint16(testSvc.Spec.Ports[0].Port) }) It("should have connectivity from workloads[1][0],[1][1] via external IP to workload 0", func() { cc.ExpectSome(w[1][0], TargetIP(ip[0]), port) cc.ExpectSome(w[1][1], TargetIP(ip[0]), port) cc.ExpectNone(w[0][1], TargetIP(ip[0]), port) cc.CheckConnectivity() }) }) Describe("Test load balancer service with external Client,src ranges", func() { var testSvc *v1.Service tgtPort := 8055 externalIP := []string{extIP} testSvcName := "test-lb-service-extip" var ip []string var port uint16 var srcIPRange []string BeforeEach(func() { if testOpts.connTimeEnabled { Skip("FIXME externalClient also does conntime balancing") } externalClient.Exec("ip", "route", "add", extIP, "via", felixes[0].IP) externalClient.EnsureBinary("test-connection") pol.Spec.Ingress = []api.Rule{ { Action: "Allow", Source: api.EntityRule{ Nets: []string{ externalClient.IP + "/32", }, }, }, } pol = updatePolicy(pol) felixes[1].Exec("ip", "route", "add", "local", extIP, "dev", "eth0") felixes[0].Exec("ip", "route", "add", "local", extIP, "dev", "eth0") srcIPRange = []string{"10.65.1.3/24"} }) Context("Test LB-service with external Client's IP not in src range", func() { BeforeEach(func() { testSvc = k8sCreateLBServiceWithEndPoints(k8sClient, testSvcName, "10.101.0.10", w[0][0], 80, tgtPort, testOpts.protocol, externalIP, srcIPRange) ip = testSvc.Spec.ExternalIPs port = uint16(testSvc.Spec.Ports[0].Port) }) It("should not have connectivity from external Client via external IP to workload 0", func() { cc.ExpectNone(externalClient, TargetIP(ip[0]), port) cc.CheckConnectivity() }) }) Context("Test LB-service with external Client's IP in src range", func() { BeforeEach(func() { srcIPRange = []string{externalClient.IP + "/32"} testSvc = k8sCreateLBServiceWithEndPoints(k8sClient, testSvcName, "10.101.0.10", w[0][0], 80, tgtPort, testOpts.protocol, externalIP, srcIPRange) ip = testSvc.Spec.ExternalIPs port = uint16(testSvc.Spec.Ports[0].Port) }) It("should have connectivity from external Client via external IP to workload 0", func() { cc.ExpectSome(externalClient, TargetIP(ip[0]), port) cc.CheckConnectivity() }) }) }) Context("with test-service configured 10.101.0.10:80 -> w[0][0].IP:8055", func() { var ( testSvc *v1.Service testSvcNamespace string ) testSvcName := "test-service" tgtPort := 8055 BeforeEach(func() { testSvc = k8sService(testSvcName, "10.101.0.10", w[0][0], 80, tgtPort, 0, testOpts.protocol) testSvcNamespace = testSvc.ObjectMeta.Namespace _, err := k8sClient.CoreV1().Services(testSvcNamespace).Create(testSvc) Expect(err).NotTo(HaveOccurred()) Eventually(k8sGetEpsForServiceFunc(k8sClient, testSvc), "10s").Should(HaveLen(1), "Service endpoints didn't get created? Is controller-manager happy?") }) It("should have connectivity from all workloads via a service to workload 0", func() { ip := testSvc.Spec.ClusterIP port := uint16(testSvc.Spec.Ports[0].Port) cc.ExpectSome(w[0][1], TargetIP(ip), port) cc.ExpectSome(w[1][0], TargetIP(ip), port) cc.ExpectSome(w[1][1], TargetIP(ip), port) cc.CheckConnectivity() }) if testOpts.connTimeEnabled { It("workload should have connectivity to self via a service", func() { ip := testSvc.Spec.ClusterIP port := uint16(testSvc.Spec.Ports[0].Port) cc.ExpectSome(w[0][0], TargetIP(ip), port) cc.CheckConnectivity() }) It("should only have connectivity from the local host via a service to workload 0", func() { // Local host is always white-listed (for kubelet health checks). ip := testSvc.Spec.ClusterIP port := uint16(testSvc.Spec.Ports[0].Port) cc.ExpectSome(felixes[0], TargetIP(ip), port) cc.ExpectNone(felixes[1], TargetIP(ip), port) cc.CheckConnectivity() }) } else { It("should not have connectivity from the local host via a service to workload 0", func() { // Local host is always white-listed (for kubelet health checks). ip := testSvc.Spec.ClusterIP port := uint16(testSvc.Spec.Ports[0].Port) cc.ExpectNone(felixes[0], TargetIP(ip), port) cc.ExpectNone(felixes[1], TargetIP(ip), port) cc.CheckConnectivity() }) } if testOpts.connTimeEnabled { Describe("after updating the policy to allow traffic from hosts", func() { BeforeEach(func() { pol.Spec.Ingress = []api.Rule{ { Action: "Allow", Source: api.EntityRule{ Nets: []string{ felixes[0].IP + "/32", felixes[1].IP + "/32", }, }, }, } switch testOpts.tunnel { case "ipip": pol.Spec.Ingress[0].Source.Nets = append(pol.Spec.Ingress[0].Source.Nets, felixes[0].ExpectedIPIPTunnelAddr+"/32", felixes[1].ExpectedIPIPTunnelAddr+"/32", ) } pol = updatePolicy(pol) }) It("should have connectivity from the hosts via a service to workload 0", func() { ip := testSvc.Spec.ClusterIP port := uint16(testSvc.Spec.Ports[0].Port) cc.ExpectSome(felixes[0], TargetIP(ip), port) cc.ExpectSome(felixes[1], TargetIP(ip), port) cc.ExpectNone(w[0][1], TargetIP(ip), port) cc.ExpectNone(w[1][0], TargetIP(ip), port) cc.CheckConnectivity() }) }) } It("should create sane conntrack entries and clean them up", func() { By("Generating some traffic") ip := testSvc.Spec.ClusterIP port := uint16(testSvc.Spec.Ports[0].Port) cc.ExpectSome(w[0][1], TargetIP(ip), port) cc.ExpectSome(w[1][0], TargetIP(ip), port) cc.CheckConnectivity() By("Checking timestamps on conntrack entries are sane") // This test verifies that we correctly interpret conntrack entry timestamps by reading them back // and checking that they're (a) in the past and (b) sensibly recent. ctDump, err := felixes[0].ExecOutput("calico-bpf", "conntrack", "dump") Expect(err).NotTo(HaveOccurred()) re := regexp.MustCompile(`LastSeen:\s*(\d+)`) matches := re.FindAllStringSubmatch(ctDump, -1) Expect(matches).ToNot(BeEmpty(), "didn't find any conntrack entries") for _, match := range matches { lastSeenNanos, err := strconv.ParseInt(match[1], 10, 64) Expect(err).NotTo(HaveOccurred()) nowNanos := bpf.KTimeNanos() age := time.Duration(nowNanos - lastSeenNanos) Expect(age).To(BeNumerically(">", 0)) Expect(age).To(BeNumerically("<", 60*time.Second)) } By("Checking conntrack entries are cleaned up") // We have UTs that check that all kinds of entries eventually get cleaned up. This // test is mainly to check that the cleanup code actually runs and is able to actually delete // entries. numWl0ConntrackEntries := func() int { ctDump, err := felixes[0].ExecOutput("calico-bpf", "conntrack", "dump") Expect(err).NotTo(HaveOccurred()) return strings.Count(ctDump, w[0][0].IP) } startingCTEntries := numWl0ConntrackEntries() Expect(startingCTEntries).To(BeNumerically(">", 0)) // TODO reduce timeouts just for this test. Eventually(numWl0ConntrackEntries, "180s", "5s").Should(BeNumerically("<", startingCTEntries)) }) Context("with test-service port updated", func() { var ( testSvcUpdated *v1.Service natBackBeforeUpdate []nat.BackendMapMem natBeforeUpdate []nat.MapMem ) BeforeEach(func() { ip := testSvc.Spec.ClusterIP portOld := uint16(testSvc.Spec.Ports[0].Port) ipv4 := net.ParseIP(ip) oldK := nat.NewNATKey(ipv4, portOld, numericProto) // Wait for the NAT maps to converge... log.Info("Waiting for NAT maps to converge...") startTime := time.Now() for { if time.Since(startTime) > 5*time.Second { Fail("NAT maps failed to converge") } natBeforeUpdate, natBackBeforeUpdate = dumpNATmaps(felixes) for i, m := range natBeforeUpdate { if natV, ok := m[oldK]; !ok { goto retry } else { bckCnt := natV.Count() if bckCnt != 1 { log.Debugf("Expected single backend, not %d; retrying...", bckCnt) goto retry } bckID := natV.ID() bckK := nat.NewNATBackendKey(bckID, 0) if _, ok := natBackBeforeUpdate[i][bckK]; !ok { log.Debugf("Backend not found %v; retrying...", bckK) goto retry } } } break retry: time.Sleep(100 * time.Millisecond) } log.Info("NAT maps converged.") testSvcUpdated = k8sService(testSvcName, "10.101.0.10", w[0][0], 88, 8055, 0, testOpts.protocol) svc, err := k8sClient.CoreV1(). Services(testSvcNamespace). Get(testSvcName, metav1.GetOptions{}) testSvcUpdated.ObjectMeta.ResourceVersion = svc.ObjectMeta.ResourceVersion _, err = k8sClient.CoreV1().Services(testSvcNamespace).Update(testSvcUpdated) Expect(err).NotTo(HaveOccurred()) Eventually(k8sGetEpsForServiceFunc(k8sClient, testSvc), "10s").Should(HaveLen(1), "Service endpoints didn't get created? Is controller-manager happy?") }) It("should have connectivity from all workloads via the new port", func() { ip := testSvcUpdated.Spec.ClusterIP port := uint16(testSvcUpdated.Spec.Ports[0].Port) cc.ExpectSome(w[0][1], TargetIP(ip), port) cc.ExpectSome(w[1][0], TargetIP(ip), port) cc.ExpectSome(w[1][1], TargetIP(ip), port) cc.CheckConnectivity() }) It("should not have connectivity from all workloads via the old port", func() { ip := testSvc.Spec.ClusterIP port := uint16(testSvc.Spec.Ports[0].Port) cc.ExpectNone(w[0][1], TargetIP(ip), port) cc.ExpectNone(w[1][0], TargetIP(ip), port) cc.ExpectNone(w[1][1], TargetIP(ip), port) cc.CheckConnectivity() natmaps, natbacks := dumpNATmaps(felixes) ipv4 := net.ParseIP(ip) portOld := uint16(testSvc.Spec.Ports[0].Port) oldK := nat.NewNATKey(ipv4, portOld, numericProto) portNew := uint16(testSvcUpdated.Spec.Ports[0].Port) natK := nat.NewNATKey(ipv4, portNew, numericProto) for i := range felixes { Expect(natmaps[i]).To(HaveKey(natK)) Expect(natmaps[i]).NotTo(HaveKey(nat.NewNATKey(ipv4, portOld, numericProto))) Expect(natBeforeUpdate[i]).To(HaveKey(oldK)) oldV := natBeforeUpdate[i][oldK] natV := natmaps[i][natK] bckCnt := natV.Count() bckID := natV.ID() log.WithField("backCnt", bckCnt).Debug("Backend count.") for ord := uint32(0); ord < uint32(bckCnt); ord++ { bckK := nat.NewNATBackendKey(bckID, ord) oldBckK := nat.NewNATBackendKey(oldV.ID(), ord) Expect(natbacks[i]).To(HaveKey(bckK)) Expect(natBackBeforeUpdate[i]).To(HaveKey(oldBckK)) Expect(natBackBeforeUpdate[i][oldBckK]).To(Equal(natbacks[i][bckK])) } } }) It("after removing service, should not have connectivity from workloads via a service to workload 0", func() { ip := testSvcUpdated.Spec.ClusterIP port := uint16(testSvcUpdated.Spec.Ports[0].Port) natK := nat.NewNATKey(net.ParseIP(ip), port, numericProto) var prevBpfsvcs []nat.MapMem Eventually(func() bool { prevBpfsvcs, _ = dumpNATmaps(felixes) for _, m := range prevBpfsvcs { if _, ok := m[natK]; !ok { return false } } return true }, "5s").Should(BeTrue(), "service NAT key didn't show up") err := k8sClient.CoreV1(). Services(testSvcNamespace). Delete(testSvcName, &metav1.DeleteOptions{}) Expect(err).NotTo(HaveOccurred()) Eventually(k8sGetEpsForServiceFunc(k8sClient, testSvc), "10s").Should(HaveLen(0)) cc.ExpectNone(w[0][1], TargetIP(ip), port) cc.ExpectNone(w[1][0], TargetIP(ip), port) cc.ExpectNone(w[1][1], TargetIP(ip), port) cc.CheckConnectivity() for i, f := range felixes { natV := prevBpfsvcs[i][natK] bckCnt := natV.Count() bckID := natV.ID() Eventually(func() bool { svcs := dumpNATMap(f) eps := dumpEPMap(f) if _, ok := svcs[natK]; ok { return false } for ord := uint32(0); ord < uint32(bckCnt); ord++ { bckK := nat.NewNATBackendKey(bckID, ord) if _, ok := eps[bckK]; ok { return false } } return true }, "5s").Should(BeTrue(), "service NAT key wasn't removed correctly") } }) }) }) Context("with test-service configured 10.101.0.10:80 -> w[*][0].IP:8055 and affinity", func() { var ( testSvc *v1.Service testSvcNamespace string ) testSvcName := "test-service" BeforeEach(func() { testSvc = k8sService(testSvcName, "10.101.0.10", w[0][0], 80, 8055, 0, testOpts.protocol) testSvcNamespace = testSvc.ObjectMeta.Namespace // select all pods with port 8055 testSvc.Spec.Selector = map[string]string{"port": "8055"} testSvc.Spec.SessionAffinity = "ClientIP" _, err := k8sClient.CoreV1().Services(testSvcNamespace).Create(testSvc) Expect(err).NotTo(HaveOccurred()) Eventually(k8sGetEpsForServiceFunc(k8sClient, testSvc), "10s").Should(HaveLen(1), "Service endpoints didn't get created? Is controller-manager happy?") }) It("should have connectivity from a workload to a service with multiple backends", func() { ip := testSvc.Spec.ClusterIP port := uint16(testSvc.Spec.Ports[0].Port) cc.ExpectSome(w[1][1], TargetIP(ip), port) cc.ExpectSome(w[1][1], TargetIP(ip), port) cc.ExpectSome(w[1][1], TargetIP(ip), port) cc.CheckConnectivity() if !testOpts.connTimeEnabled { // FIXME we can only do the test with regular NAT as // cgroup shares one random affinity map aff := dumpAffMap(felixes[1]) Expect(aff).To(HaveLen(1)) } }) }) npPort := uint16(30333) nodePortsTest := func(localOnly bool) { var ( testSvc *v1.Service testSvcNamespace string ) testSvcName := "test-service" BeforeEach(func() { k8sClient := infra.(*infrastructure.K8sDatastoreInfra).K8sClient testSvc = k8sService(testSvcName, "10.101.0.10", w[0][0], 80, 8055, int32(npPort), testOpts.protocol) if localOnly { testSvc.Spec.ExternalTrafficPolicy = "Local" } testSvcNamespace = testSvc.ObjectMeta.Namespace _, err := k8sClient.CoreV1().Services(testSvcNamespace).Create(testSvc) Expect(err).NotTo(HaveOccurred()) Eventually(k8sGetEpsForServiceFunc(k8sClient, testSvc), "10s").Should(HaveLen(1), "Service endpoints didn't get created? Is controller-manager happy?") }) It("should have connectivity from all workloads via a service to workload 0", func() { clusterIP := testSvc.Spec.ClusterIP port := uint16(testSvc.Spec.Ports[0].Port) cc.ExpectSome(w[0][1], TargetIP(clusterIP), port) cc.ExpectSome(w[1][0], TargetIP(clusterIP), port) cc.ExpectSome(w[1][1], TargetIP(clusterIP), port) cc.CheckConnectivity() }) if localOnly { It("should not have connectivity from all workloads via a nodeport to non-local workload 0", func() { node0IP := felixes[0].IP node1IP := felixes[1].IP // Via remote nodeport, should fail. cc.ExpectNone(w[0][1], TargetIP(node1IP), npPort) cc.ExpectNone(w[1][0], TargetIP(node1IP), npPort) cc.ExpectNone(w[1][1], TargetIP(node1IP), npPort) // Include a check that goes via the local nodeport to make sure the dataplane has converged. cc.ExpectSome(w[0][1], TargetIP(node0IP), npPort) cc.CheckConnectivity() }) } else { It("should have connectivity from all workloads via a nodeport to workload 0", func() { node1IP := felixes[1].IP cc.ExpectSome(w[0][1], TargetIP(node1IP), npPort) cc.ExpectSome(w[1][0], TargetIP(node1IP), npPort) cc.ExpectSome(w[1][1], TargetIP(node1IP), npPort) cc.CheckConnectivity() }) } if !localOnly { It("should have connectivity from a workload via a nodeport on another node to workload 0", func() { ip := felixes[1].IP cc.ExpectSome(w[2][1], TargetIP(ip), npPort) cc.CheckConnectivity() }) } It("workload should have connectivity to self via local/remote node", func() { if !testOpts.connTimeEnabled { Skip("FIXME pod cannot connect to self without connect time lb") } cc.ExpectSome(w[0][0], TargetIP(felixes[1].IP), npPort) cc.ExpectSome(w[0][0], TargetIP(felixes[0].IP), npPort) cc.CheckConnectivity() }) It("should not have connectivity from external to w[0] via local/remote node", func() { cc.ExpectNone(externalClient, TargetIP(felixes[1].IP), npPort) cc.ExpectNone(externalClient, TargetIP(felixes[0].IP), npPort) // Include a check that goes via the local nodeport to make sure the dataplane has converged. cc.ExpectSome(w[0][1], TargetIP(felixes[0].IP), npPort) cc.CheckConnectivity() }) Describe("after updating the policy to allow traffic from externalClient", func() { BeforeEach(func() { pol.Spec.Ingress = []api.Rule{ { Action: "Allow", Source: api.EntityRule{ Nets: []string{ externalClient.IP + "/32", }, }, }, } pol = updatePolicy(pol) }) if localOnly { It("should not have connectivity from external to w[0] via node1->node0 fwd", func() { if testOpts.connTimeEnabled { Skip("FIXME externalClient also does conntime balancing") } cc.ExpectNone(externalClient, TargetIP(felixes[1].IP), npPort) // Include a check that goes via the nodeport with a local backing pod to make sure the dataplane has converged. cc.ExpectSome(externalClient, TargetIP(felixes[0].IP), npPort) cc.CheckConnectivity() }) } else { It("should have connectivity from external to w[0] via node1->node0 fwd", func() { if testOpts.connTimeEnabled { Skip("FIXME externalClient also does conntime balancing") } cc.ExpectSome(externalClient, TargetIP(felixes[1].IP), npPort) cc.CheckConnectivity() }) It("should have connectivity from external to w[0] via node1IP2 -> nodeIP1 -> node0 fwd", func() { // 192.168.20.1 +----------|---------+ // | | | | // v | | V // eth20 eth0 | eth0 // 10.0.0.20:30333 --> felixes[1].IP | felixes[0].IP // | | // | V // | caliXYZ // | w[0][0].IP:8055 // | // node1 | node0 if testOpts.dsr { return // When DSR is enabled, we need to have away how to pass the // original traffic back. // // felixes[0].Exec("ip", "route", "add", "192.168.20.0/24", "via", felixes[1].IP) // // This does not work since the other node would treat it as // DNAT due to the existing CT entries and NodePort traffix // otherwise :-/ } if testOpts.connTimeEnabled { Skip("FIXME externalClient also does conntime balancing") } var eth20 *workload.Workload defer func() { if eth20 != nil { eth20.Stop() } }() By("setting up node's fake external iface", func() { // We name the iface eth20 since such ifaces are // treated by felix as external to the node // // Using a test-workload creates the namespaces and the // interfaces to emulate the host NICs eth20 = &workload.Workload{ Name: "eth20", C: felixes[1].Container, IP: "192.168.20.1", Ports: "57005", // 0xdead Protocol: testOpts.protocol, InterfaceName: "eth20", } eth20.Start() // assign address to eth20 and add route to the .20 network felixes[1].Exec("ip", "route", "add", "192.168.20.0/24", "dev", "eth20") felixes[1].Exec("ip", "addr", "add", "10.0.0.20/32", "dev", "eth20") _, err := eth20.RunCmd("ip", "route", "add", "10.0.0.20/32", "dev", "eth0") Expect(err).NotTo(HaveOccurred()) // Add a route to felix[1] to be able to reach the nodeport _, err = eth20.RunCmd("ip", "route", "add", felixes[1].IP+"/32", "via", "10.0.0.20") Expect(err).NotTo(HaveOccurred()) // This multi-NIC scenario works only if the kernel's RPF check // is not strict so we need to override it for the test and must // be set properly when product is deployed. We reply on // iptables to do require check for us. felixes[1].Exec("sysctl", "-w", "net.ipv4.conf.eth0.rp_filter=2") felixes[1].Exec("sysctl", "-w", "net.ipv4.conf.eth20.rp_filter=2") }) By("setting up routes to .20 net on dest node to trigger RPF check", func() { // set up a dummy interface just for the routing purpose felixes[0].Exec("ip", "link", "add", "dummy1", "type", "dummy") felixes[0].Exec("ip", "link", "set", "dummy1", "up") // set up route to the .20 net through the dummy iface. This // makes the .20 a universaly reachable external world from the // internal/private eth0 network felixes[0].Exec("ip", "route", "add", "192.168.20.0/24", "dev", "dummy1") // This multi-NIC scenario works only if the kernel's RPF check // is not strict so we need to override it for the test and must // be set properly when product is deployed. We reply on // iptables to do require check for us. felixes[0].Exec("sysctl", "-w", "net.ipv4.conf.eth0.rp_filter=2") felixes[0].Exec("sysctl", "-w", "net.ipv4.conf.dummy1.rp_filter=2") }) By("Allowing traffic from the eth20 network", func() { pol.Spec.Ingress = []api.Rule{ { Action: "Allow", Source: api.EntityRule{ Nets: []string{ eth20.IP + "/32", }, }, }, } pol = updatePolicy(pol) }) By("Checking that there is connectivity from eth20 network", func() { cc.ExpectSome(eth20, TargetIP(felixes[1].IP), npPort) cc.CheckConnectivity() }) }) if testOpts.protocol == "tcp" && !testOpts.connTimeEnabled { const ( npEncapOverhead = 50 hostIfaceMTU = 1500 podIfaceMTU = 1410 sendLen = hostIfaceMTU recvLen = podIfaceMTU - npEncapOverhead ) Context("with TCP, tx/rx close to MTU size on NP via node1->node0 ", func() { negative := "" adjusteMTU := podIfaceMTU - npEncapOverhead if testOpts.dsr { negative = "not " adjusteMTU = 0 } It("should "+negative+"adjust MTU on workload side", func() { // force non-GSO packets when workload replies _, err := w[0][0].RunCmd("ethtool", "-K", "eth0", "gso", "off") Expect(err).NotTo(HaveOccurred()) _, err = w[0][0].RunCmd("ethtool", "-K", "eth0", "tso", "off") Expect(err).NotTo(HaveOccurred()) pmtu, err := w[0][0].PathMTU(externalClient.IP) Expect(err).NotTo(HaveOccurred()) Expect(pmtu).To(Equal(0)) // nothing specific for this path yet port := []uint16{npPort} cc.ExpectConnectivity(externalClient, TargetIP(felixes[1].IP), port, ExpectWithSendLen(sendLen), ExpectWithRecvLen(recvLen), ExpectWithClientAdjustedMTU(hostIfaceMTU, hostIfaceMTU), ) cc.CheckConnectivity() pmtu, err = w[0][0].PathMTU(externalClient.IP) Expect(err).NotTo(HaveOccurred()) Expect(pmtu).To(Equal(adjusteMTU)) }) It("should not adjust MTU on client side if GRO off on nodes", func() { // force non-GSO packets on node ingress err := felixes[1].ExecMayFail("ethtool", "-K", "eth0", "gro", "off") Expect(err).NotTo(HaveOccurred()) port := []uint16{npPort} cc.ExpectConnectivity(externalClient, TargetIP(felixes[1].IP), port, ExpectWithSendLen(sendLen), ExpectWithRecvLen(recvLen), ExpectWithClientAdjustedMTU(hostIfaceMTU, hostIfaceMTU), ) cc.CheckConnectivity() }) }) } } It("should have connectivity from external to w[0] via node0", func() { if testOpts.connTimeEnabled { Skip("FIXME externalClient also does conntime balancing") } log.WithFields(log.Fields{ "externalClientIP": externalClient.IP, "nodePortIP": felixes[1].IP, }).Infof("external->nodeport connection") cc.ExpectSome(externalClient, TargetIP(felixes[0].IP), npPort) cc.CheckConnectivity() }) }) } Context("with test-service being a nodeport @ "+strconv.Itoa(int(npPort)), func() { nodePortsTest(false) }) // FIXME connect time shares the same NAT table and it is a lottery which one it gets if !testOpts.connTimeEnabled { Context("with test-service being a nodeport @ "+strconv.Itoa(int(npPort))+ " ExternalTrafficPolicy=local", func() { nodePortsTest(true) }) } Context("with icmp blocked from workloads, external client", func() { var ( testSvc *v1.Service testSvcNamespace string ) testSvcName := "test-service" BeforeEach(func() { icmpProto := numorstring.ProtocolFromString("icmp") pol.Spec.Ingress = []api.Rule{ { Action: "Allow", Source: api.EntityRule{ Nets: []string{"0.0.0.0/0"}, }, }, } pol.Spec.Egress = []api.Rule{ { Action: "Allow", Source: api.EntityRule{ Nets: []string{"0.0.0.0/0"}, }, }, { Action: "Deny", Protocol: &icmpProto, }, } pol = updatePolicy(pol) }) var tgtPort int var tgtWorkload *workload.Workload JustBeforeEach(func() { k8sClient := infra.(*infrastructure.K8sDatastoreInfra).K8sClient testSvc = k8sService(testSvcName, "10.101.0.10", tgtWorkload, 80, tgtPort, int32(npPort), testOpts.protocol) testSvcNamespace = testSvc.ObjectMeta.Namespace _, err := k8sClient.CoreV1().Services(testSvcNamespace).Create(testSvc) Expect(err).NotTo(HaveOccurred()) Eventually(k8sGetEpsForServiceFunc(k8sClient, testSvc), "10s").Should(HaveLen(1), "Service endpoints didn't get created? Is controller-manager happy?") // sync with NAT table being applied natFtKey := nat.NewNATKey(net.ParseIP(felixes[1].IP), npPort, numericProto) Eventually(func() bool { m := dumpNATMap(felixes[1]) v, ok := m[natFtKey] return ok && v.Count() > 0 }, 5*time.Second).Should(BeTrue()) // Sync with policy cc.ExpectSome(w[1][0], w[0][0]) cc.CheckConnectivity() }) Describe("with dead workload", func() { BeforeEach(func() { tgtPort = 8057 tgtWorkload = deadWorkload }) It("should get host unreachable from nodeport via node1->node0 fwd", func() { if testOpts.connTimeEnabled { Skip("FIXME externalClient also does conntime balancing") } err := felixes[0].ExecMayFail("ip", "route", "add", "unreachable", deadWorkload.IP) Expect(err).NotTo(HaveOccurred()) tcpdump := externalClient.AttachTCPDump("any") tcpdump.SetLogEnabled(true) matcher := fmt.Sprintf("IP %s > %s: ICMP host %s unreachable", felixes[1].IP, externalClient.IP, felixes[1].IP) tcpdump.AddMatcher("ICMP", regexp.MustCompile(matcher)) tcpdump.Start(testOpts.protocol, "port", strconv.Itoa(int(npPort)), "or", "icmp") defer tcpdump.Stop() cc.ExpectNone(externalClient, TargetIP(felixes[1].IP), npPort) cc.CheckConnectivity() Eventually(func() int { return tcpdump.MatchCount("ICMP") }). Should(BeNumerically(">", 0), matcher) }) }) Describe("with wrong target port", func() { // TCP would send RST instead of ICMP, it is enough to test one way of // triggering the ICMP message if testOpts.protocol != "udp" { return } BeforeEach(func() { tgtPort = 0xdead tgtWorkload = w[0][0] }) It("should get port unreachable via node1->node0 fwd", func() { if testOpts.connTimeEnabled { Skip("FIXME externalClient also does conntime balancing") } tcpdump := externalClient.AttachTCPDump("any") tcpdump.SetLogEnabled(true) matcher := fmt.Sprintf("IP %s > %s: ICMP %s udp port %d unreachable", felixes[1].IP, externalClient.IP, felixes[1].IP, npPort) tcpdump.AddMatcher("ICMP", regexp.MustCompile(matcher)) tcpdump.Start(testOpts.protocol, "port", strconv.Itoa(int(npPort)), "or", "icmp") defer tcpdump.Stop() cc.ExpectNone(externalClient, TargetIP(felixes[1].IP), npPort) cc.CheckConnectivity() Eventually(func() int { return tcpdump.MatchCount("ICMP") }). Should(BeNumerically(">", 0), matcher) }) It("should get port unreachable workload to workload", func() { tcpdump := w[1][1].AttachTCPDump() tcpdump.SetLogEnabled(true) matcher := fmt.Sprintf("IP %s > %s: ICMP %s udp port %d unreachable", tgtWorkload.IP, w[1][1].IP, tgtWorkload.IP, tgtPort) tcpdump.AddMatcher("ICMP", regexp.MustCompile(matcher)) tcpdump.Start(testOpts.protocol, "port", strconv.Itoa(tgtPort), "or", "icmp") defer tcpdump.Stop() cc.ExpectNone(w[1][1], TargetIP(tgtWorkload.IP), uint16(tgtPort)) cc.CheckConnectivity() Eventually(func() int { return tcpdump.MatchCount("ICMP") }). Should(BeNumerically(">", 0), matcher) }) It("should get port unreachable workload to workload through NP", func() { tcpdump := w[1][1].AttachTCPDump() tcpdump.SetLogEnabled(true) var matcher string if testOpts.connTimeEnabled { matcher = fmt.Sprintf("IP %s > %s: ICMP %s udp port %d unreachable", tgtWorkload.IP, w[1][1].IP, w[0][0].IP, tgtPort) tcpdump.AddMatcher("ICMP", regexp.MustCompile(matcher)) tcpdump.Start(testOpts.protocol, "port", strconv.Itoa(tgtPort), "or", "icmp") } else { matcher = fmt.Sprintf("IP %s > %s: ICMP %s udp port %d unreachable", tgtWorkload.IP, w[1][1].IP, felixes[1].IP, npPort) tcpdump.AddMatcher("ICMP", regexp.MustCompile(matcher)) tcpdump.Start(testOpts.protocol, "port", strconv.Itoa(int(npPort)), "or", "icmp") } defer tcpdump.Stop() cc.ExpectNone(w[1][1], TargetIP(felixes[1].IP), npPort) cc.CheckConnectivity() Eventually(func() int { return tcpdump.MatchCount("ICMP") }). Should(BeNumerically(">", 0), matcher) }) }) }) }) }) }) } func typeMetaV1(kind string) metav1.TypeMeta { return metav1.TypeMeta{ Kind: kind, APIVersion: "v1", } } func objectMetaV1(name string) metav1.ObjectMeta { return metav1.ObjectMeta{ Name: name, Namespace: "default", } } func dumpNATmaps(felixes []*infrastructure.Felix) ([]nat.MapMem, []nat.BackendMapMem) { bpfsvcs := make([]nat.MapMem, len(felixes)) bpfeps := make([]nat.BackendMapMem, len(felixes)) for i, felix := range felixes { bpfsvcs[i], bpfeps[i] = dumpNATMaps(felix) } return bpfsvcs, bpfeps } func dumpNATMaps(felix *infrastructure.Felix) (nat.MapMem, nat.BackendMapMem) { return dumpNATMap(felix), dumpEPMap(felix) } func dumpBPFMap(felix *infrastructure.Felix, m bpf.Map, iter bpf.MapIter) { // Wait for the map to exist before trying to access it. Otherwise, we // might fail a test that was retrying this dump anyway. Eventually(func() bool { return felix.FileExists(m.Path()) }).Should(BeTrue(), fmt.Sprintf("dumpBPFMap: map %s didn't show up inside container", m.Path())) cmd, err := bpf.DumpMapCmd(m) Expect(err).NotTo(HaveOccurred(), "Failed to get BPF map dump command: "+m.Path()) log.WithField("cmd", cmd).Debug("dumpBPFMap") out, err := felix.ExecOutput(cmd...) Expect(err).NotTo(HaveOccurred(), "Failed to get dump BPF map: "+m.Path()) err = bpf.IterMapCmdOutput([]byte(out), iter) Expect(err).NotTo(HaveOccurred(), "Failed to parse BPF map dump: "+m.Path()) } func dumpNATMap(felix *infrastructure.Felix) nat.MapMem { bm := nat.FrontendMap(&bpf.MapContext{}) m := make(nat.MapMem) dumpBPFMap(felix, bm, nat.MapMemIter(m)) return m } func dumpEPMap(felix *infrastructure.Felix) nat.BackendMapMem { bm := nat.BackendMap(&bpf.MapContext{}) m := make(nat.BackendMapMem) dumpBPFMap(felix, bm, nat.BackendMapMemIter(m)) return m } func dumpAffMap(felix *infrastructure.Felix) nat.AffinityMapMem { bm := nat.AffinityMap(&bpf.MapContext{}) m := make(nat.AffinityMapMem) dumpBPFMap(felix, bm, nat.AffinityMapMemIter(m)) return m } func dumpCTMap(felix *infrastructure.Felix) conntrack.MapMem { bm := conntrack.Map(&bpf.MapContext{}) m := make(conntrack.MapMem) dumpBPFMap(felix, bm, conntrack.MapMemIter(m)) return m } func dumpSendRecvMap(felix *infrastructure.Felix) nat.SendRecvMsgMapMem { bm := nat.SendRecvMsgMap(&bpf.MapContext{}) m := make(nat.SendRecvMsgMapMem) dumpBPFMap(felix, bm, nat.SendRecvMsgMapMemIter(m)) return m } func k8sService(name, clusterIP string, w *workload.Workload, port, tgtPort int, nodePort int32, protocol string) *v1.Service { k8sProto := v1.ProtocolTCP if protocol == "udp" { k8sProto = v1.ProtocolUDP } svcType := v1.ServiceTypeClusterIP if nodePort != 0 { svcType = v1.ServiceTypeNodePort } return &v1.Service{ TypeMeta: typeMetaV1("Service"), ObjectMeta: objectMetaV1(name), Spec: v1.ServiceSpec{ ClusterIP: clusterIP, Type: svcType, Selector: map[string]string{ "name": w.Name, }, Ports: []v1.ServicePort{ { Protocol: k8sProto, Port: int32(port), NodePort: nodePort, Name: fmt.Sprintf("port-%d", tgtPort), TargetPort: intstr.FromInt(tgtPort), }, }, }, } } func k8sLBService(name, clusterIP string, w *workload.Workload, port, tgtPort int, protocol string, externalIPs, srcRange []string) *v1.Service { k8sProto := v1.ProtocolTCP if protocol == "udp" { k8sProto = v1.ProtocolUDP } svcType := v1.ServiceTypeLoadBalancer return &v1.Service{ TypeMeta: typeMetaV1("Service"), ObjectMeta: objectMetaV1(name), Spec: v1.ServiceSpec{ ClusterIP: clusterIP, Type: svcType, LoadBalancerSourceRanges: srcRange, ExternalIPs: externalIPs, Selector: map[string]string{ "name": w.Name, }, Ports: []v1.ServicePort{ { Protocol: k8sProto, Port: int32(port), Name: fmt.Sprintf("port-%d", tgtPort), TargetPort: intstr.FromInt(tgtPort), }, }, }, } } func k8sGetEpsForService(k8s kubernetes.Interface, svc *v1.Service) []v1.EndpointSubset { ep, _ := k8s.CoreV1(). Endpoints(svc.ObjectMeta.Namespace). Get(svc.ObjectMeta.Name, metav1.GetOptions{}) log.WithField("endpoints", spew.Sprint(ep)).Infof("Got endpoints for %s", svc.ObjectMeta.Name) return ep.Subsets } func k8sGetEpsForServiceFunc(k8s kubernetes.Interface, svc *v1.Service) func() []v1.EndpointSubset { return func() []v1.EndpointSubset { return k8sGetEpsForService(k8s, svc) } } func k8sCreateLBServiceWithEndPoints(k8sClient kubernetes.Interface, name, clusterIP string, w *workload.Workload, port, tgtPort int, protocol string, externalIPs, srcRange []string) *v1.Service { var ( testSvc *v1.Service testSvcNamespace string ) testSvc = k8sLBService(name, clusterIP, w, 80, tgtPort, protocol, externalIPs, srcRange) testSvcNamespace = testSvc.ObjectMeta.Namespace _, err := k8sClient.CoreV1().Services(testSvcNamespace).Create(testSvc) Expect(err).NotTo(HaveOccurred()) Eventually(k8sGetEpsForServiceFunc(k8sClient, testSvc), "10s").Should(HaveLen(1), "Service endpoints didn't get created? Is controller-manager happy?") return testSvc }
1
17,989
Is this a related change?
projectcalico-felix
c
@@ -400,6 +400,12 @@ func (a *Actuator) Update(ctx context.Context, cluster *clusterv1.Cluster, machi return errors.Errorf("failed to ensure tags: %+v", err) } + scope.MachineStatus.InstanceState = &instanceDescription.State + + if err := a.reconcileLBAttachment(scope, machine, instanceDescription); err != nil { + return errors.Errorf("failed to reconcile load balancer attachment: %+v", err) + } + return nil }
1
/* Copyright 2018 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package machine // should not need to import the ec2 sdk here import ( "context" "fmt" "path" "time" "github.com/aws/aws-sdk-go/aws" "github.com/go-logr/logr" "github.com/pkg/errors" corev1 "k8s.io/client-go/kubernetes/typed/core/v1" "k8s.io/client-go/tools/clientcmd" clientcmdapi "k8s.io/client-go/tools/clientcmd/api" "k8s.io/klog/klogr" "sigs.k8s.io/cluster-api-provider-aws/pkg/apis/awsprovider/v1alpha1" "sigs.k8s.io/cluster-api-provider-aws/pkg/cloud/aws/actuators" "sigs.k8s.io/cluster-api-provider-aws/pkg/cloud/aws/services/ec2" "sigs.k8s.io/cluster-api-provider-aws/pkg/cloud/aws/services/elb" "sigs.k8s.io/cluster-api-provider-aws/pkg/deployer" "sigs.k8s.io/cluster-api-provider-aws/pkg/record" "sigs.k8s.io/cluster-api-provider-aws/pkg/tokens" clusterv1 "sigs.k8s.io/cluster-api/pkg/apis/cluster/v1alpha1" client "sigs.k8s.io/cluster-api/pkg/client/clientset_generated/clientset/typed/cluster/v1alpha1" controllerError "sigs.k8s.io/cluster-api/pkg/controller/error" ) const ( defaultTokenTTL = 10 * time.Minute waitForClusterInfrastructureReadyDuration = 15 * time.Second waitForControlPlaneMachineExistenceDuration = 5 * time.Second waitForControlPlaneReadyDuration = 5 * time.Second ) //+kubebuilder:rbac:groups=awsprovider.k8s.io,resources=awsmachineproviderconfigs;awsmachineproviderstatuses,verbs=get;list;watch;create;update;patch;delete //+kubebuilder:rbac:groups=cluster.k8s.io,resources=machines;machines/status;machinedeployments;machinedeployments/status;machinesets;machinesets/status;machineclasses,verbs=get;list;watch;create;update;patch;delete //+kubebuilder:rbac:groups=cluster.k8s.io,resources=clusters;clusters/status,verbs=get;list;watch //+kubebuilder:rbac:groups="",resources=nodes;events,verbs=get;list;watch;create;update;patch;delete // Actuator is responsible for performing machine reconciliation. type Actuator struct { *deployer.Deployer coreClient corev1.CoreV1Interface clusterClient client.ClusterV1alpha1Interface log logr.Logger controlPlaneInitLocker ControlPlaneInitLocker } // ActuatorParams holds parameter information for Actuator. type ActuatorParams struct { CoreClient corev1.CoreV1Interface ClusterClient client.ClusterV1alpha1Interface LoggingContext string ControlPlaneInitLocker ControlPlaneInitLocker } // NewActuator returns an actuator. func NewActuator(params ActuatorParams) *Actuator { log := klogr.New().WithName(params.LoggingContext) locker := params.ControlPlaneInitLocker if locker == nil { locker = newControlPlaneInitLocker(log, params.CoreClient) } return &Actuator{ Deployer: deployer.New(deployer.Params{ScopeGetter: actuators.DefaultScopeGetter}), coreClient: params.CoreClient, clusterClient: params.ClusterClient, log: log, controlPlaneInitLocker: locker, } } // GetControlPlaneMachines retrieves all non-deleted control plane nodes from a MachineList func GetControlPlaneMachines(machineList *clusterv1.MachineList) []*clusterv1.Machine { var cpm []*clusterv1.Machine for _, m := range machineList.Items { if m.DeletionTimestamp.IsZero() && m.Spec.Versions.ControlPlane != "" { cpm = append(cpm, m.DeepCopy()) } } return cpm } // defining equality as name and namespace are equivalent and not checking any other fields. func machinesEqual(m1 *clusterv1.Machine, m2 *clusterv1.Machine) bool { return m1.Name == m2.Name && m1.Namespace == m2.Namespace } // Create creates a machine and is invoked by the machine controller. func (a *Actuator) Create(ctx context.Context, cluster *clusterv1.Cluster, machine *clusterv1.Machine) error { if cluster == nil { return errors.Errorf("missing cluster for machine %s/%s", machine.Namespace, machine.Name) } log := a.log.WithValues("machine-name", machine.Name, "namespace", machine.Namespace, "cluster-name", cluster.Name) log.Info("Processing machine creation") if cluster.Annotations[v1alpha1.AnnotationClusterInfrastructureReady] != v1alpha1.ValueReady { log.Info("Cluster infrastructure is not ready yet - requeuing machine") return &controllerError.RequeueAfterError{RequeueAfter: waitForClusterInfrastructureReadyDuration} } scope, err := actuators.NewMachineScope(actuators.MachineScopeParams{Machine: machine, Cluster: cluster, Client: a.clusterClient, Logger: log}) if err != nil { return errors.Errorf("failed to create scope: %+v", err) } defer scope.Close() ec2svc := ec2.NewService(scope.Scope) log.Info("Retrieving machines for cluster") clusterMachines, err := scope.MachineClient.List(actuators.ListOptionsForCluster(cluster.Name)) if err != nil { return errors.Wrapf(err, "failed to retrieve machines in cluster %q", cluster.Name) } controlPlaneMachines := GetControlPlaneMachines(clusterMachines) if len(controlPlaneMachines) == 0 { log.Info("No control plane machines exist yet - requeuing") return &controllerError.RequeueAfterError{RequeueAfter: waitForControlPlaneMachineExistenceDuration} } join, err := a.isNodeJoin(log, cluster, machine) if err != nil { return err } var bootstrapToken string if join { coreClient, err := a.coreV1Client(cluster) if err != nil { return errors.Wrapf(err, "unable to proceed until control plane is ready (error creating client) for cluster %q", path.Join(cluster.Namespace, cluster.Name)) } log.Info("Machine will join the cluster") bootstrapToken, err = tokens.NewBootstrap(coreClient, defaultTokenTTL) if err != nil { return errors.Wrapf(err, "failed to create new bootstrap token") } } else { log.Info("Machine will init the cluster") } i, err := ec2svc.CreateOrGetMachine(scope, bootstrapToken) if err != nil { return errors.Errorf("failed to create or get machine: %+v", err) } scope.MachineStatus.InstanceID = &i.ID scope.MachineStatus.InstanceState = &i.State if machine.Annotations == nil { machine.Annotations = map[string]string{} } machine.Annotations["cluster-api-provider-aws"] = "true" if err := a.reconcileLBAttachment(scope, machine, i); err != nil { return errors.Errorf("failed to reconcile LB attachment: %+v", err) } log.Info("Create completed") return nil } func (a *Actuator) isNodeJoin(log logr.Logger, cluster *clusterv1.Cluster, machine *clusterv1.Machine) (bool, error) { if cluster.Annotations[v1alpha1.AnnotationControlPlaneReady] == v1alpha1.ValueReady { return true, nil } if machine.Labels["set"] != "controlplane" { // This isn't a control plane machine - have to wait log.Info("No control plane machines exist yet - requeuing") return true, &controllerError.RequeueAfterError{RequeueAfter: waitForControlPlaneMachineExistenceDuration} } if a.controlPlaneInitLocker.Acquire(cluster) { return false, nil } log.Info("Unable to acquire control plane configmap lock - requeuing") return true, &controllerError.RequeueAfterError{RequeueAfter: waitForControlPlaneReadyDuration} } func (a *Actuator) coreV1Client(cluster *clusterv1.Cluster) (corev1.CoreV1Interface, error) { controlPlaneDNSName, err := a.GetIP(cluster, nil) if err != nil { return nil, errors.Errorf("failed to retrieve controlplane (GetIP): %+v", err) } controlPlaneURL := fmt.Sprintf("https://%s:6443", controlPlaneDNSName) kubeConfig, err := a.GetKubeConfig(cluster, nil) if err != nil { return nil, errors.Wrapf(err, "failed to retrieve kubeconfig for cluster %q.", cluster.Name) } clientConfig, err := clientcmd.BuildConfigFromKubeconfigGetter(controlPlaneURL, func() (*clientcmdapi.Config, error) { return clientcmd.Load([]byte(kubeConfig)) }) if err != nil { return nil, errors.Wrapf(err, "failed to get client config for cluster at %q", controlPlaneURL) } return corev1.NewForConfig(clientConfig) } func (a *Actuator) reconcileLBAttachment(scope *actuators.MachineScope, m *clusterv1.Machine, i *v1alpha1.Instance) error { elbsvc := elb.NewService(scope.Scope) if m.ObjectMeta.Labels["set"] == "controlplane" { if err := elbsvc.RegisterInstanceWithAPIServerELB(i.ID); err != nil { return errors.Wrapf(err, "could not register control plane instance %q with load balancer", i.ID) } } return nil } // Delete deletes a machine and is invoked by the Machine Controller func (a *Actuator) Delete(ctx context.Context, cluster *clusterv1.Cluster, machine *clusterv1.Machine) error { if cluster == nil { return errors.Errorf("missing cluster for machine %s/%s", machine.Namespace, machine.Name) } a.log.Info("Deleting machine in cluster", "machine-name", machine.Name, "machine-namespace", machine.Namespace, "cluster-name", cluster.Name) scope, err := actuators.NewMachineScope(actuators.MachineScopeParams{Machine: machine, Cluster: cluster, Client: a.clusterClient, Logger: a.log}) if err != nil { return errors.Errorf("failed to create scope: %+v", err) } defer scope.Close() ec2svc := ec2.NewService(scope.Scope) instance, err := ec2svc.InstanceIfExists(scope.MachineStatus.InstanceID) if err != nil { return errors.Errorf("failed to get instance: %+v", err) } if instance == nil { instance, err = ec2svc.InstanceByTags(scope) if err != nil { return errors.Errorf("failed to query instance by tags: %+v", err) } else if instance == nil { // The machine hasn't been created yet a.log.V(3).Info("Instance is nil and therefore does not exist") return nil } } // Check the instance state. If it's already shutting down or terminated, // do nothing. Otherwise attempt to delete it. // This decision is based on the ec2-instance-lifecycle graph at // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-lifecycle.html switch instance.State { case v1alpha1.InstanceStateShuttingDown, v1alpha1.InstanceStateTerminated: a.log.Info("Machine instance is shutting down or already terminated") return nil default: a.log.Info("Terminating machine") if err := ec2svc.TerminateInstance(instance.ID); err != nil { record.Warnf(machine, "FailedTerminate", "Failed to terminate instance %q: %v", instance.ID, err) return errors.Errorf("failed to terminate instance: %+v", err) } record.Eventf(machine, "SuccessfulTerminate", "Terminated instance %q", instance.ID) } return nil } // isMachineOudated checks that no immutable fields have been updated in an // Update request. // Returns a slice of errors representing attempts to change immutable state func (a *Actuator) isMachineOutdated(machineSpec *v1alpha1.AWSMachineProviderSpec, instance *v1alpha1.Instance) (errs []error) { // Instance Type if machineSpec.InstanceType != instance.Type { errs = append(errs, errors.Errorf("instance type cannot be mutated from %q to %q", instance.Type, machineSpec.InstanceType)) } // IAM Profile if machineSpec.IAMInstanceProfile != instance.IAMProfile { errs = append(errs, errors.Errorf("instance IAM profile cannot be mutated from %q to %q", instance.IAMProfile, machineSpec.IAMInstanceProfile)) } // SSH Key Name if machineSpec.KeyName != aws.StringValue(instance.KeyName) { errs = append(errs, errors.Errorf("SSH key name cannot be mutated from %q to %q", aws.StringValue(instance.KeyName), machineSpec.KeyName)) } // Root Device Size if machineSpec.RootDeviceSize > 0 && machineSpec.RootDeviceSize != instance.RootDeviceSize { errs = append(errs, errors.Errorf("Root volume size cannot be mutated from %v to %v", instance.RootDeviceSize, machineSpec.RootDeviceSize)) } // Subnet ID // machineSpec.Subnet is a *AWSResourceReference and could technically be // a *string, ARN or Filter. However, elsewhere in the code it is only used // as a *string, so do the same here. if machineSpec.Subnet != nil { if aws.StringValue(machineSpec.Subnet.ID) != instance.SubnetID { errs = append(errs, errors.Errorf("machine subnet ID cannot be mutated from %q to %q", instance.SubnetID, aws.StringValue(machineSpec.Subnet.ID))) } } // PublicIP check is a little more complicated as the machineConfig is a // simple bool indicating if the instance should have a public IP or not, // while the instanceDescription contains the public IP assigned to the // instance. // Work out whether the instance already has a public IP or not based on // the length of the PublicIP string. Anything >0 is assumed to mean it does // have a public IP. instanceHasPublicIP := false if len(aws.StringValue(instance.PublicIP)) > 0 { instanceHasPublicIP = true } if aws.BoolValue(machineSpec.PublicIP) != instanceHasPublicIP { errs = append(errs, errors.Errorf(`public IP setting cannot be mutated from "%v" to "%v"`, instanceHasPublicIP, aws.BoolValue(machineSpec.PublicIP))) } return errs } // Update updates a machine and is invoked by the Machine Controller. // If the Update attempts to mutate any immutable state, the method will error // and no updates will be performed. func (a *Actuator) Update(ctx context.Context, cluster *clusterv1.Cluster, machine *clusterv1.Machine) error { if cluster == nil { return errors.Errorf("missing cluster for machine %s/%s", machine.Namespace, machine.Name) } a.log.Info("Updating machine in cluster", "machine-name", machine.Name, "machine-namespace", machine.Namespace, "cluster-name", cluster.Name) scope, err := actuators.NewMachineScope(actuators.MachineScopeParams{Machine: machine, Cluster: cluster, Client: a.clusterClient, Logger: a.log}) if err != nil { return errors.Errorf("failed to create scope: %+v", err) } defer scope.Close() ec2svc := ec2.NewService(scope.Scope) // Get the current instance description from AWS. instanceDescription, err := ec2svc.InstanceIfExists(scope.MachineStatus.InstanceID) if err != nil { return errors.Errorf("failed to get instance: %+v", err) } // We can now compare the various AWS state to the state we were passed. // We will check immutable state first, in order to fail quickly before // moving on to state that we can mutate. if errs := a.isMachineOutdated(scope.MachineConfig, instanceDescription); len(errs) > 0 { return errors.Errorf("found attempt to change immutable state for machine %q: %+q", machine.Name, errs) } existingSecurityGroups, err := ec2svc.GetInstanceSecurityGroups(*scope.MachineStatus.InstanceID) if err != nil { return err } // Ensure that the security groups are correct. _, err = a.ensureSecurityGroups( ec2svc, scope, *scope.MachineStatus.InstanceID, scope.MachineConfig.AdditionalSecurityGroups, existingSecurityGroups, ) if err != nil { return errors.Errorf("failed to apply security groups: %+v", err) } // Ensure that the tags are correct. _, err = a.ensureTags(ec2svc, machine, scope.MachineStatus.InstanceID, scope.MachineConfig.AdditionalTags) if err != nil { return errors.Errorf("failed to ensure tags: %+v", err) } return nil } // Exists test for the existence of a machine and is invoked by the Machine Controller func (a *Actuator) Exists(ctx context.Context, cluster *clusterv1.Cluster, machine *clusterv1.Machine) (bool, error) { if cluster == nil { return false, errors.Errorf("missing cluster for machine %s/%s", machine.Namespace, machine.Name) } a.log.Info("Checking if machine exists in cluster", "machine-name", machine.Name, "machine-namespace", machine.Namespace, "cluster-name", cluster.Name) scope, err := actuators.NewMachineScope(actuators.MachineScopeParams{Machine: machine, Cluster: cluster, Client: a.clusterClient, Logger: a.log}) if err != nil { return false, errors.Errorf("failed to create scope: %+v", err) } defer scope.Close() ec2svc := ec2.NewService(scope.Scope) // TODO worry about pointers. instance if exists returns *any* instance if scope.MachineStatus.InstanceID == nil { return false, nil } instance, err := ec2svc.InstanceIfExists(scope.MachineStatus.InstanceID) if err != nil { return false, errors.Errorf("failed to retrieve instance: %+v", err) } if instance == nil { return false, nil } a.log.Info("Found instance for machine", "machine-name", machine.Name, "machine-namespace", machine.Namespace, "instance", instance) switch instance.State { case v1alpha1.InstanceStateRunning: a.log.Info("Machine instance is running", "instance-id", *scope.MachineStatus.InstanceID) case v1alpha1.InstanceStatePending: a.log.Info("Machine instance is pending", "instance-id", *scope.MachineStatus.InstanceID) default: return false, nil } scope.MachineStatus.InstanceState = &instance.State if err := a.reconcileLBAttachment(scope, machine, instance); err != nil { return true, err } if machine.Spec.ProviderID == nil || *machine.Spec.ProviderID == "" { providerID := fmt.Sprintf("aws:////%s", *scope.MachineStatus.InstanceID) scope.Machine.Spec.ProviderID = &providerID } return true, nil }
1
10,077
Given that this is repeated, can we do it outside here and the Create call, what do you think about moving it outside?
kubernetes-sigs-cluster-api-provider-aws
go
@@ -44,6 +44,10 @@ function UndoRedo(instance) { return; } + arrayEach(changes, (change) => { + change[1] = instance.propToCol(change[1]); + }); + const selected = changesLen > 1 ? this.getSelected() : [[changes[0][0], changes[0][1]]]; plugin.done(new UndoRedo.ChangeAction(changes, selected));
1
/** * Handsontable UndoRedo class */ import Hooks from './../../pluginHooks'; import { arrayMap, arrayEach } from './../../helpers/array'; import { rangeEach } from './../../helpers/number'; import { inherit, deepClone } from './../../helpers/object'; import { stopImmediatePropagation, isImmediatePropagationStopped } from './../../helpers/dom/event'; import { align } from './../contextMenu/utils'; /** * @description * Handsontable UndoRedo plugin allows to undo and redo certain actions done in the table. * * __Note__, that not all actions are currently undo-able. The UndoRedo plugin is enabled by default. * * @example * ```js * undo: true * ``` * @class UndoRedo * @plugin UndoRedo */ function UndoRedo(instance) { const plugin = this; this.instance = instance; this.doneActions = []; this.undoneActions = []; this.ignoreNewActions = false; instance.addHook('afterChange', function(changes, source) { const changesLen = changes && changes.length; if (!changesLen || ['UndoRedo.undo', 'UndoRedo.redo', 'MergeCells'].includes(source)) { return; } const hasDifferences = changes.find((change) => { const [,, oldValue, newValue] = change; return oldValue !== newValue; }); if (!hasDifferences) { return; } const selected = changesLen > 1 ? this.getSelected() : [[changes[0][0], changes[0][1]]]; plugin.done(new UndoRedo.ChangeAction(changes, selected)); }); instance.addHook('afterCreateRow', (index, amount, source) => { if (source === 'UndoRedo.undo' || source === 'UndoRedo.undo' || source === 'auto') { return; } const action = new UndoRedo.CreateRowAction(index, amount); plugin.done(action); }); instance.addHook('beforeRemoveRow', (index, amount, logicRows, source) => { if (source === 'UndoRedo.undo' || source === 'UndoRedo.redo' || source === 'auto') { return; } const originalData = plugin.instance.getSourceDataArray(); const rowIndex = (originalData.length + index) % originalData.length; const physicalRowIndex = instance.toPhysicalRow(rowIndex); const removedData = deepClone(originalData.slice(physicalRowIndex, physicalRowIndex + amount)); plugin.done(new UndoRedo.RemoveRowAction(rowIndex, removedData)); }); instance.addHook('afterCreateCol', (index, amount, source) => { if (source === 'UndoRedo.undo' || source === 'UndoRedo.redo' || source === 'auto') { return; } plugin.done(new UndoRedo.CreateColumnAction(index, amount)); }); instance.addHook('beforeRemoveCol', (index, amount, logicColumns, source) => { if (source === 'UndoRedo.undo' || source === 'UndoRedo.redo' || source === 'auto') { return; } const originalData = plugin.instance.getSourceDataArray(); const columnIndex = (plugin.instance.countCols() + index) % plugin.instance.countCols(); const removedData = []; const headers = []; const indexes = []; rangeEach(originalData.length - 1, (i) => { const column = []; const origRow = originalData[i]; rangeEach(columnIndex, columnIndex + (amount - 1), (j) => { column.push(origRow[instance.runHooks('modifyCol', j)]); }); removedData.push(column); }); rangeEach(amount - 1, (i) => { indexes.push(instance.runHooks('modifyCol', columnIndex + i)); }); if (Array.isArray(instance.getSettings().colHeaders)) { rangeEach(amount - 1, (i) => { headers.push(instance.getSettings().colHeaders[instance.runHooks('modifyCol', columnIndex + i)] || null); }); } const manualColumnMovePlugin = plugin.instance.getPlugin('manualColumnMove'); const columnsMap = manualColumnMovePlugin.isEnabled() ? manualColumnMovePlugin.columnsMapper.__arrayMap : []; const action = new UndoRedo.RemoveColumnAction(columnIndex, indexes, removedData, headers, columnsMap); plugin.done(action); }); instance.addHook('beforeCellAlignment', (stateBefore, range, type, alignment) => { const action = new UndoRedo.CellAlignmentAction(stateBefore, range, type, alignment); plugin.done(action); }); instance.addHook('beforeFilter', (conditionsStack) => { plugin.done(new UndoRedo.FiltersAction(conditionsStack)); }); instance.addHook('beforeRowMove', (movedRows, target) => { if (movedRows === false) { return; } plugin.done(new UndoRedo.RowMoveAction(movedRows, target)); }); instance.addHook('beforeMergeCells', (cellRange, auto) => { if (auto) { return; } plugin.done(new UndoRedo.MergeCellsAction(instance, cellRange)); }); instance.addHook('afterUnmergeCells', (cellRange, auto) => { if (auto) { return; } plugin.done(new UndoRedo.UnmergeCellsAction(instance, cellRange)); }); } UndoRedo.prototype.done = function(action) { if (!this.ignoreNewActions) { this.doneActions.push(action); this.undoneActions.length = 0; } }; /** * Undo the last action performed to the table. * * @function undo * @memberof UndoRedo# * @fires Hooks#beforeUndo * @fires Hooks#afterUndo */ UndoRedo.prototype.undo = function() { if (this.isUndoAvailable()) { const action = this.doneActions.pop(); const actionClone = deepClone(action); const instance = this.instance; const continueAction = instance.runHooks('beforeUndo', actionClone); if (continueAction === false) { return; } this.ignoreNewActions = true; const that = this; action.undo(this.instance, () => { that.ignoreNewActions = false; that.undoneActions.push(action); }); instance.runHooks('afterUndo', actionClone); } }; /** * Redo the previous action performed to the table (used to reverse an undo). * * @function redo * @memberof UndoRedo# * @fires Hooks#beforeRedo * @fires Hooks#afterRedo */ UndoRedo.prototype.redo = function() { if (this.isRedoAvailable()) { const action = this.undoneActions.pop(); const actionClone = deepClone(action); const instance = this.instance; const continueAction = instance.runHooks('beforeRedo', actionClone); if (continueAction === false) { return; } this.ignoreNewActions = true; const that = this; action.redo(this.instance, () => { that.ignoreNewActions = false; that.doneActions.push(action); }); instance.runHooks('afterRedo', actionClone); } }; /** * Checks if undo action is available. * * @function isUndoAvailable * @memberof UndoRedo# * @return {Boolean} Return `true` if undo can be performed, `false` otherwise. */ UndoRedo.prototype.isUndoAvailable = function() { return this.doneActions.length > 0; }; /** * Checks if redo action is available. * * @function isRedoAvailable * @memberof UndoRedo# * @return {Boolean} Return `true` if redo can be performed, `false` otherwise. */ UndoRedo.prototype.isRedoAvailable = function() { return this.undoneActions.length > 0; }; /** * Clears undo history. * * @function clear * @memberof UndoRedo# */ UndoRedo.prototype.clear = function() { this.doneActions.length = 0; this.undoneActions.length = 0; }; UndoRedo.Action = function() {}; UndoRedo.Action.prototype.undo = function() {}; UndoRedo.Action.prototype.redo = function() {}; /** * Change action. * * @private */ UndoRedo.ChangeAction = function(changes, selected) { this.changes = changes; this.selected = selected; this.actionType = 'change'; }; inherit(UndoRedo.ChangeAction, UndoRedo.Action); UndoRedo.ChangeAction.prototype.undo = function(instance, undoneCallback) { const data = deepClone(this.changes); const emptyRowsAtTheEnd = instance.countEmptyRows(true); const emptyColsAtTheEnd = instance.countEmptyCols(true); for (let i = 0, len = data.length; i < len; i++) { data[i].splice(3, 1); } instance.addHookOnce('afterChange', undoneCallback); instance.setDataAtRowProp(data, null, null, 'UndoRedo.undo'); for (let i = 0, len = data.length; i < len; i++) { const [row, column] = data[i]; if (instance.getSettings().minSpareRows && row + 1 + instance.getSettings().minSpareRows === instance.countRows() && emptyRowsAtTheEnd === instance.getSettings().minSpareRows) { instance.alter('remove_row', parseInt(row + 1, 10), instance.getSettings().minSpareRows); instance.undoRedo.doneActions.pop(); } if (instance.getSettings().minSpareCols && column + 1 + instance.getSettings().minSpareCols === instance.countCols() && emptyColsAtTheEnd === instance.getSettings().minSpareCols) { instance.alter('remove_col', parseInt(column + 1, 10), instance.getSettings().minSpareCols); instance.undoRedo.doneActions.pop(); } } instance.selectCells(this.selected, false, false); }; UndoRedo.ChangeAction.prototype.redo = function(instance, onFinishCallback) { const data = deepClone(this.changes); for (let i = 0, len = data.length; i < len; i++) { data[i].splice(2, 1); } instance.addHookOnce('afterChange', onFinishCallback); instance.setDataAtRowProp(data, null, null, 'UndoRedo.redo'); if (this.selected) { instance.selectCells(this.selected, false, false); } }; /** * Create row action. * * @private */ UndoRedo.CreateRowAction = function(index, amount) { this.index = index; this.amount = amount; this.actionType = 'insert_row'; }; inherit(UndoRedo.CreateRowAction, UndoRedo.Action); UndoRedo.CreateRowAction.prototype.undo = function(instance, undoneCallback) { const rowCount = instance.countRows(); const minSpareRows = instance.getSettings().minSpareRows; if (this.index >= rowCount && this.index - minSpareRows < rowCount) { this.index -= minSpareRows; // work around the situation where the needed row was removed due to an 'undo' of a made change } instance.addHookOnce('afterRemoveRow', undoneCallback); instance.alter('remove_row', this.index, this.amount, 'UndoRedo.undo'); }; UndoRedo.CreateRowAction.prototype.redo = function(instance, redoneCallback) { instance.addHookOnce('afterCreateRow', redoneCallback); instance.alter('insert_row', this.index, this.amount, 'UndoRedo.redo'); }; /** * Remove row action. * * @private */ UndoRedo.RemoveRowAction = function(index, data) { this.index = index; this.data = data; this.actionType = 'remove_row'; }; inherit(UndoRedo.RemoveRowAction, UndoRedo.Action); UndoRedo.RemoveRowAction.prototype.undo = function(instance, undoneCallback) { instance.alter('insert_row', this.index, this.data.length, 'UndoRedo.undo'); instance.addHookOnce('afterRender', undoneCallback); instance.populateFromArray(this.index, 0, this.data, void 0, void 0, 'UndoRedo.undo'); }; UndoRedo.RemoveRowAction.prototype.redo = function(instance, redoneCallback) { instance.addHookOnce('afterRemoveRow', redoneCallback); instance.alter('remove_row', this.index, this.data.length, 'UndoRedo.redo'); }; /** * Create column action. * * @private */ UndoRedo.CreateColumnAction = function(index, amount) { this.index = index; this.amount = amount; this.actionType = 'insert_col'; }; inherit(UndoRedo.CreateColumnAction, UndoRedo.Action); UndoRedo.CreateColumnAction.prototype.undo = function(instance, undoneCallback) { instance.addHookOnce('afterRemoveCol', undoneCallback); instance.alter('remove_col', this.index, this.amount, 'UndoRedo.undo'); }; UndoRedo.CreateColumnAction.prototype.redo = function(instance, redoneCallback) { instance.addHookOnce('afterCreateCol', redoneCallback); instance.alter('insert_col', this.index, this.amount, 'UndoRedo.redo'); }; /** * Remove column action. * * @private */ UndoRedo.RemoveColumnAction = function(index, indexes, data, headers, columnPositions) { this.index = index; this.indexes = indexes; this.data = data; this.amount = this.data[0].length; this.headers = headers; this.columnPositions = columnPositions.slice(0); this.actionType = 'remove_col'; }; inherit(UndoRedo.RemoveColumnAction, UndoRedo.Action); UndoRedo.RemoveColumnAction.prototype.undo = function(instance, undoneCallback) { let row; const ascendingIndexes = this.indexes.slice(0).sort(); const sortByIndexes = (elem, j, arr) => arr[this.indexes.indexOf(ascendingIndexes[j])]; const sortedData = []; rangeEach(this.data.length - 1, (i) => { sortedData[i] = arrayMap(this.data[i], sortByIndexes); }); let sortedHeaders = []; sortedHeaders = arrayMap(this.headers, sortByIndexes); const changes = []; // TODO: Temporary hook for undo/redo mess instance.runHooks('beforeCreateCol', this.indexes[0], this.indexes.length, 'UndoRedo.undo'); rangeEach(this.data.length - 1, (i) => { row = instance.getSourceDataAtRow(i); rangeEach(ascendingIndexes.length - 1, (j) => { row.splice(ascendingIndexes[j], 0, sortedData[i][j]); changes.push([i, ascendingIndexes[j], null, sortedData[i][j]]); }); }); // TODO: Temporary hook for undo/redo mess if (instance.getPlugin('formulas')) { instance.getPlugin('formulas').onAfterSetDataAtCell(changes); } if (typeof this.headers !== 'undefined') { rangeEach(sortedHeaders.length - 1, (j) => { instance.getSettings().colHeaders.splice(ascendingIndexes[j], 0, sortedHeaders[j]); }); } if (instance.getPlugin('manualColumnMove')) { instance.getPlugin('manualColumnMove').columnsMapper.__arrayMap = this.columnPositions; } instance.addHookOnce('afterRender', undoneCallback); // TODO: Temporary hook for undo/redo mess instance.runHooks('afterCreateCol', this.indexes[0], this.indexes.length, 'UndoRedo.undo'); if (instance.getPlugin('formulas')) { instance.getPlugin('formulas').recalculateFull(); } instance.render(); }; UndoRedo.RemoveColumnAction.prototype.redo = function(instance, redoneCallback) { instance.addHookOnce('afterRemoveCol', redoneCallback); instance.alter('remove_col', this.index, this.amount, 'UndoRedo.redo'); }; /** * Cell alignment action. * * @private */ UndoRedo.CellAlignmentAction = function(stateBefore, range, type, alignment) { this.stateBefore = stateBefore; this.range = range; this.type = type; this.alignment = alignment; }; UndoRedo.CellAlignmentAction.prototype.undo = function(instance, undoneCallback) { arrayEach(this.range, ({ from, to }) => { for (let row = from.row; row <= to.row; row += 1) { for (let col = from.col; col <= to.col; col += 1) { instance.setCellMeta(row, col, 'className', this.stateBefore[row][col] || ' htLeft'); } } }); instance.addHookOnce('afterRender', undoneCallback); instance.render(); }; UndoRedo.CellAlignmentAction.prototype.redo = function(instance, undoneCallback) { align(this.range, this.type, this.alignment, (row, col) => instance.getCellMeta(row, col), (row, col, key, value) => instance.setCellMeta(row, col, key, value)); instance.addHookOnce('afterRender', undoneCallback); instance.render(); }; /** * Filters action. * * @private */ UndoRedo.FiltersAction = function(conditionsStack) { this.conditionsStack = conditionsStack; this.actionType = 'filter'; }; inherit(UndoRedo.FiltersAction, UndoRedo.Action); UndoRedo.FiltersAction.prototype.undo = function(instance, undoneCallback) { const filters = instance.getPlugin('filters'); instance.addHookOnce('afterRender', undoneCallback); filters.conditionCollection.importAllConditions(this.conditionsStack.slice(0, this.conditionsStack.length - 1)); filters.filter(); }; UndoRedo.FiltersAction.prototype.redo = function(instance, redoneCallback) { const filters = instance.getPlugin('filters'); instance.addHookOnce('afterRender', redoneCallback); filters.conditionCollection.importAllConditions(this.conditionsStack); filters.filter(); }; /** * Merge Cells action. * @util */ class MergeCellsAction extends UndoRedo.Action { constructor(instance, cellRange) { super(); this.cellRange = cellRange; this.rangeData = instance.getData(cellRange.from.row, cellRange.from.col, cellRange.to.row, cellRange.to.col); } undo(instance, undoneCallback) { const mergeCellsPlugin = instance.getPlugin('mergeCells'); instance.addHookOnce('afterRender', undoneCallback); mergeCellsPlugin.unmergeRange(this.cellRange, true); instance.populateFromArray(this.cellRange.from.row, this.cellRange.from.col, this.rangeData, void 0, void 0, 'MergeCells'); } redo(instance, redoneCallback) { const mergeCellsPlugin = instance.getPlugin('mergeCells'); instance.addHookOnce('afterRender', redoneCallback); mergeCellsPlugin.mergeRange(this.cellRange); } } UndoRedo.MergeCellsAction = MergeCellsAction; /** * Unmerge Cells action. * @util */ class UnmergeCellsAction extends UndoRedo.Action { constructor(instance, cellRange) { super(); this.cellRange = cellRange; } undo(instance, undoneCallback) { const mergeCellsPlugin = instance.getPlugin('mergeCells'); instance.addHookOnce('afterRender', undoneCallback); mergeCellsPlugin.mergeRange(this.cellRange, true); } redo(instance, redoneCallback) { const mergeCellsPlugin = instance.getPlugin('mergeCells'); instance.addHookOnce('afterRender', redoneCallback); mergeCellsPlugin.unmergeRange(this.cellRange, true); instance.render(); } } UndoRedo.UnmergeCellsAction = UnmergeCellsAction; /** * ManualRowMove action. * * @private * @TODO: removeRow undo should works on logical index */ UndoRedo.RowMoveAction = function(movedRows, target) { this.rows = movedRows.slice(); this.target = target; }; inherit(UndoRedo.RowMoveAction, UndoRedo.Action); UndoRedo.RowMoveAction.prototype.undo = function(instance, undoneCallback) { const manualRowMove = instance.getPlugin('manualRowMove'); instance.addHookOnce('afterRender', undoneCallback); const mod = this.rows[0] < this.target ? -1 * this.rows.length : 0; const newTarget = this.rows[0] > this.target ? this.rows[0] + this.rows.length : this.rows[0]; const newRows = []; const rowsLen = this.rows.length + mod; for (let i = mod; i < rowsLen; i += 1) { newRows.push(this.target + i); } manualRowMove.moveRows(newRows.slice(), newTarget); instance.render(); instance.selectCell(this.rows[0], 0, this.rows[this.rows.length - 1], instance.countCols() - 1, false, false); }; UndoRedo.RowMoveAction.prototype.redo = function(instance, redoneCallback) { const manualRowMove = instance.getPlugin('manualRowMove'); instance.addHookOnce('afterRender', redoneCallback); manualRowMove.moveRows(this.rows.slice(), this.target); instance.render(); const startSelection = this.rows[0] < this.target ? this.target - this.rows.length : this.target; instance.selectCell(startSelection, 0, startSelection + this.rows.length - 1, instance.countCols() - 1, false, false); }; function init() { const instance = this; const pluginEnabled = typeof instance.getSettings().undo === 'undefined' || instance.getSettings().undo; if (pluginEnabled) { if (!instance.undoRedo) { /** * Instance of Handsontable.UndoRedo Plugin {@link Handsontable.UndoRedo} * * @alias undoRedo * @memberof! Handsontable.Core# * @type {UndoRedo} */ instance.undoRedo = new UndoRedo(instance); exposeUndoRedoMethods(instance); instance.addHook('beforeKeyDown', onBeforeKeyDown); instance.addHook('afterChange', onAfterChange); } } else if (instance.undoRedo) { delete instance.undoRedo; removeExposedUndoRedoMethods(instance); instance.removeHook('beforeKeyDown', onBeforeKeyDown); instance.removeHook('afterChange', onAfterChange); } } function onBeforeKeyDown(event) { if (isImmediatePropagationStopped(event)) { return; } const instance = this; const editor = instance.getActiveEditor(); if (editor && editor.isOpened()) { return; } const { altKey, ctrlKey, keyCode, metaKey, shiftKey, } = event; const isCtrlDown = (ctrlKey || metaKey) && !altKey; if (!isCtrlDown) { return; } const isRedoHotkey = keyCode === 89 || (shiftKey && keyCode === 90); if (isRedoHotkey) { // CTRL + Y or CTRL + SHIFT + Z instance.undoRedo.redo(); stopImmediatePropagation(event); } else if (keyCode === 90) { // CTRL + Z instance.undoRedo.undo(); stopImmediatePropagation(event); } } function onAfterChange(changes, source) { const instance = this; if (source === 'loadData') { return instance.undoRedo.clear(); } } function exposeUndoRedoMethods(instance) { /** * {@link UndoRedo#undo} * @alias undo * @memberof! Handsontable.Core# */ instance.undo = function() { return instance.undoRedo.undo(); }; /** * {@link UndoRedo#redo} * @alias redo * @memberof! Handsontable.Core# */ instance.redo = function() { return instance.undoRedo.redo(); }; /** * {@link UndoRedo#isUndoAvailable} * @alias isUndoAvailable * @memberof! Handsontable.Core# */ instance.isUndoAvailable = function() { return instance.undoRedo.isUndoAvailable(); }; /** * {@link UndoRedo#isRedoAvailable} * @alias isRedoAvailable * @memberof! Handsontable.Core# */ instance.isRedoAvailable = function() { return instance.undoRedo.isRedoAvailable(); }; /** * {@link UndoRedo#clear} * @alias clearUndo * @memberof! Handsontable.Core# */ instance.clearUndo = function() { return instance.undoRedo.clear(); }; } function removeExposedUndoRedoMethods(instance) { delete instance.undo; delete instance.redo; delete instance.isUndoAvailable; delete instance.isRedoAvailable; delete instance.clearUndo; } const hook = Hooks.getSingleton(); hook.add('afterInit', init); hook.add('afterUpdateSettings', init); hook.register('beforeUndo'); hook.register('afterUndo'); hook.register('beforeRedo'); hook.register('afterRedo'); export default UndoRedo;
1
15,930
Changing `prop`=>`col` by reference? I think you can prepare map `prop`=>`col` in L51.
handsontable-handsontable
js
@@ -106,6 +106,7 @@ std::string FlatCompiler::GetUsageString(const char *program_name) const { " --grpc Generate GRPC interfaces for the specified languages\n" " --schema Serialize schemas instead of JSON (use with -b)\n" " --bfbs-comments Add doc comments to the binary schema files.\n" + " --bfbs-builtin-attrs Add builtin attributes to the binary schema files.\n" " --conform FILE Specify a schema the following schemas should be\n" " an evolution of. Gives errors if not.\n" " --conform-includes Include path for the schema given with --conform\n"
1
/* * Copyright 2014 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "flatbuffers/flatc.h" #include <list> #define FLATC_VERSION "1.9.0 (" __DATE__ " " __TIME__ ")" namespace flatbuffers { void FlatCompiler::ParseFile( flatbuffers::Parser &parser, const std::string &filename, const std::string &contents, std::vector<const char *> &include_directories) const { auto local_include_directory = flatbuffers::StripFileName(filename); include_directories.push_back(local_include_directory.c_str()); include_directories.push_back(nullptr); if (!parser.Parse(contents.c_str(), &include_directories[0], filename.c_str())) Error(parser.error_, false, false); include_directories.pop_back(); include_directories.pop_back(); } void FlatCompiler::Warn(const std::string &warn, bool show_exe_name) const { params_.warn_fn(this, warn, show_exe_name); } void FlatCompiler::Error(const std::string &err, bool usage, bool show_exe_name) const { params_.error_fn(this, err, usage, show_exe_name); } std::string FlatCompiler::GetUsageString(const char *program_name) const { std::stringstream ss; ss << "Usage: " << program_name << " [OPTION]... FILE... [-- FILE...]\n"; for (size_t i = 0; i < params_.num_generators; ++i) { const Generator &g = params_.generators[i]; std::stringstream full_name; full_name << std::setw(12) << std::left << g.generator_opt_long; const char *name = g.generator_opt_short ? g.generator_opt_short : " "; const char *help = g.generator_help; ss << " " << full_name.str() << " " << name << " " << help << ".\n"; } // clang-format off ss << " -o PATH Prefix PATH to all generated files.\n" " -I PATH Search for includes in the specified path.\n" " -M Print make rules for generated files.\n" " --version Print the version number of flatc and exit.\n" " --strict-json Strict JSON: field names must be / will be quoted,\n" " no trailing commas in tables/vectors.\n" " --allow-non-utf8 Pass non-UTF-8 input through parser and emit nonstandard\n" " \\x escapes in JSON. (Default is to raise parse error on\n" " non-UTF-8 input.)\n" " --defaults-json Output fields whose value is the default when\n" " writing JSON\n" " --unknown-json Allow fields in JSON that are not defined in the\n" " schema. These fields will be discared when generating\n" " binaries.\n" " --no-prefix Don\'t prefix enum values with the enum type in C++.\n" " --scoped-enums Use C++11 style scoped and strongly typed enums.\n" " also implies --no-prefix.\n" " --gen-includes (deprecated), this is the default behavior.\n" " If the original behavior is required (no include\n" " statements) use --no-includes.\n" " --no-includes Don\'t generate include statements for included\n" " schemas the generated file depends on (C++).\n" " --gen-mutable Generate accessors that can mutate buffers in-place.\n" " --gen-onefile Generate single output file for C# and Go.\n" " --gen-name-strings Generate type name functions for C++.\n" " --gen-object-api Generate an additional object-based API.\n" " --cpp-ptr-type T Set object API pointer type (default std::unique_ptr)\n" " --cpp-str-type T Set object API string type (default std::string)\n" " T::c_str() and T::length() must be supported\n" " --gen-nullable Add Clang _Nullable for C++ pointer. or @Nullable for Java\n" " --object-prefix Customise class prefix for C++ object-based API.\n" " --object-suffix Customise class suffix for C++ object-based API.\n" " Default value is \"T\"\n" " --no-js-exports Removes Node.js style export lines in JS.\n" " --goog-js-export Uses goog.exports* for closure compiler exporting in JS.\n" " --go-namespace Generate the overrided namespace in Golang.\n" " --go-import Generate the overrided import for flatbuffers in Golang.\n" " (default is \"github.com/google/flatbuffers/go\")\n" " --raw-binary Allow binaries without file_indentifier to be read.\n" " This may crash flatc given a mismatched schema.\n" " --size-prefixed Input binaries are size prefixed buffers.\n" " --proto Input is a .proto, translate to .fbs.\n" " --oneof-union Translate .proto oneofs to flatbuffer unions.\n" " --grpc Generate GRPC interfaces for the specified languages\n" " --schema Serialize schemas instead of JSON (use with -b)\n" " --bfbs-comments Add doc comments to the binary schema files.\n" " --conform FILE Specify a schema the following schemas should be\n" " an evolution of. Gives errors if not.\n" " --conform-includes Include path for the schema given with --conform\n" " PATH \n" " --include-prefix Prefix this path to any generated include statements.\n" " PATH\n" " --keep-prefix Keep original prefix of schema include statement.\n" " --no-fb-import Don't include flatbuffers import statement for TypeScript.\n" " --no-ts-reexport Don't re-export imported dependencies for TypeScript.\n" " --reflect-types Add minimal type reflection to code generation.\n" " --reflect-names Add minimal type/name reflection.\n" "FILEs may be schemas (must end in .fbs), or JSON files (conforming to preceding\n" "schema). FILEs after the -- must be binary flatbuffer format files.\n" "Output files are named using the base file name of the input,\n" "and written to the current directory or the path given by -o.\n" "example: " << program_name << " -c -b schema1.fbs schema2.fbs data.json\n"; // clang-format on return ss.str(); } int FlatCompiler::Compile(int argc, const char **argv) { if (params_.generators == nullptr || params_.num_generators == 0) { return 0; } flatbuffers::IDLOptions opts; std::string output_path; bool any_generator = false; bool print_make_rules = false; bool raw_binary = false; bool schema_binary = false; bool grpc_enabled = false; std::vector<std::string> filenames; std::list<std::string> include_directories_storage; std::vector<const char *> include_directories; std::vector<const char *> conform_include_directories; std::vector<bool> generator_enabled(params_.num_generators, false); size_t binary_files_from = std::numeric_limits<size_t>::max(); std::string conform_to_schema; for (int argi = 0; argi < argc; argi++) { std::string arg = argv[argi]; if (arg[0] == '-') { if (filenames.size() && arg[1] != '-') Error("invalid option location: " + arg, true); if (arg == "-o") { if (++argi >= argc) Error("missing path following: " + arg, true); output_path = flatbuffers::ConCatPathFileName( flatbuffers::PosixPath(argv[argi]), ""); } else if (arg == "-I") { if (++argi >= argc) Error("missing path following" + arg, true); include_directories_storage.push_back( flatbuffers::PosixPath(argv[argi])); include_directories.push_back( include_directories_storage.back().c_str()); } else if (arg == "--conform") { if (++argi >= argc) Error("missing path following" + arg, true); conform_to_schema = flatbuffers::PosixPath(argv[argi]); } else if (arg == "--conform-includes") { if (++argi >= argc) Error("missing path following" + arg, true); include_directories_storage.push_back( flatbuffers::PosixPath(argv[argi])); conform_include_directories.push_back( include_directories_storage.back().c_str()); } else if (arg == "--include-prefix") { if (++argi >= argc) Error("missing path following" + arg, true); opts.include_prefix = flatbuffers::ConCatPathFileName( flatbuffers::PosixPath(argv[argi]), ""); } else if (arg == "--keep-prefix") { opts.keep_include_path = true; } else if (arg == "--strict-json") { opts.strict_json = true; } else if (arg == "--allow-non-utf8") { opts.allow_non_utf8 = true; } else if (arg == "--no-js-exports") { opts.skip_js_exports = true; } else if (arg == "--goog-js-export") { opts.use_goog_js_export_format = true; } else if (arg == "--go-namespace") { if (++argi >= argc) Error("missing golang namespace" + arg, true); opts.go_namespace = argv[argi]; } else if (arg == "--go-import") { if (++argi >= argc) Error("missing golang import" + arg, true); opts.go_import = argv[argi]; } else if (arg == "--defaults-json") { opts.output_default_scalars_in_json = true; } else if (arg == "--unknown-json") { opts.skip_unexpected_fields_in_json = true; } else if (arg == "--no-prefix") { opts.prefixed_enums = false; } else if (arg == "--scoped-enums") { opts.prefixed_enums = false; opts.scoped_enums = true; } else if (arg == "--no-union-value-namespacing") { opts.union_value_namespacing = false; } else if (arg == "--gen-mutable") { opts.mutable_buffer = true; } else if (arg == "--gen-name-strings") { opts.generate_name_strings = true; } else if (arg == "--gen-object-api") { opts.generate_object_based_api = true; } else if (arg == "--cpp-ptr-type") { if (++argi >= argc) Error("missing type following" + arg, true); opts.cpp_object_api_pointer_type = argv[argi]; } else if (arg == "--cpp-str-type") { if (++argi >= argc) Error("missing type following" + arg, true); opts.cpp_object_api_string_type = argv[argi]; } else if (arg == "--gen-nullable") { opts.gen_nullable = true; } else if (arg == "--object-prefix") { if (++argi >= argc) Error("missing prefix following" + arg, true); opts.object_prefix = argv[argi]; } else if (arg == "--object-suffix") { if (++argi >= argc) Error("missing suffix following" + arg, true); opts.object_suffix = argv[argi]; } else if (arg == "--gen-all") { opts.generate_all = true; opts.include_dependence_headers = false; } else if (arg == "--gen-includes") { // Deprecated, remove this option some time in the future. printf("warning: --gen-includes is deprecated (it is now default)\n"); } else if (arg == "--no-includes") { opts.include_dependence_headers = false; } else if (arg == "--gen-onefile") { opts.one_file = true; } else if (arg == "--raw-binary") { raw_binary = true; } else if (arg == "--size-prefixed") { opts.size_prefixed = true; } else if (arg == "--") { // Separator between text and binary inputs. binary_files_from = filenames.size(); } else if (arg == "--proto") { opts.proto_mode = true; } else if (arg == "--oneof-union") { opts.proto_oneof_union = true; } else if (arg == "--schema") { schema_binary = true; } else if (arg == "-M") { print_make_rules = true; } else if (arg == "--version") { printf("flatc version %s\n", FLATC_VERSION); exit(0); } else if (arg == "--grpc") { grpc_enabled = true; } else if (arg == "--bfbs-comments") { opts.binary_schema_comments = true; } else if (arg == "--no-fb-import") { opts.skip_flatbuffers_import = true; } else if (arg == "--no-ts-reexport") { opts.reexport_ts_modules = false; } else if (arg == "--reflect-types") { opts.mini_reflect = IDLOptions::kTypes; } else if (arg == "--reflect-names") { opts.mini_reflect = IDLOptions::kTypesAndNames; } else { for (size_t i = 0; i < params_.num_generators; ++i) { if (arg == params_.generators[i].generator_opt_long || (params_.generators[i].generator_opt_short && arg == params_.generators[i].generator_opt_short)) { generator_enabled[i] = true; any_generator = true; opts.lang_to_generate |= params_.generators[i].lang; goto found; } } Error("unknown commandline argument: " + arg, true); found:; } } else { filenames.push_back(flatbuffers::PosixPath(argv[argi])); } } if (!filenames.size()) Error("missing input files", false, true); if (opts.proto_mode) { if (any_generator) Error("cannot generate code directly from .proto files", true); } else if (!any_generator && conform_to_schema.empty()) { Error("no options: specify at least one generator.", true); } flatbuffers::Parser conform_parser; if (!conform_to_schema.empty()) { std::string contents; if (!flatbuffers::LoadFile(conform_to_schema.c_str(), true, &contents)) Error("unable to load schema: " + conform_to_schema); ParseFile(conform_parser, conform_to_schema, contents, conform_include_directories); } std::unique_ptr<flatbuffers::Parser> parser(new flatbuffers::Parser(opts)); for (auto file_it = filenames.begin(); file_it != filenames.end(); ++file_it) { auto &filename = *file_it; std::string contents; if (!flatbuffers::LoadFile(filename.c_str(), true, &contents)) Error("unable to load file: " + filename); bool is_binary = static_cast<size_t>(file_it - filenames.begin()) >= binary_files_from; auto ext = flatbuffers::GetExtension(filename); auto is_schema = ext == "fbs" || ext == "proto"; if (is_binary) { parser->builder_.Clear(); parser->builder_.PushFlatBuffer( reinterpret_cast<const uint8_t *>(contents.c_str()), contents.length()); if (!raw_binary) { // Generally reading binaries that do not correspond to the schema // will crash, and sadly there's no way around that when the binary // does not contain a file identifier. // We'd expect that typically any binary used as a file would have // such an identifier, so by default we require them to match. if (!parser->file_identifier_.length()) { Error("current schema has no file_identifier: cannot test if \"" + filename + "\" matches the schema, use --raw-binary to read this file" " anyway."); } else if (!flatbuffers::BufferHasIdentifier( contents.c_str(), parser->file_identifier_.c_str(), opts.size_prefixed)) { Error("binary \"" + filename + "\" does not have expected file_identifier \"" + parser->file_identifier_ + "\", use --raw-binary to read this file anyway."); } } } else { // Check if file contains 0 bytes. if (contents.length() != strlen(contents.c_str())) { Error("input file appears to be binary: " + filename, true); } if (is_schema) { // If we're processing multiple schemas, make sure to start each // one from scratch. If it depends on previous schemas it must do // so explicitly using an include. parser.reset(new flatbuffers::Parser(opts)); } ParseFile(*parser.get(), filename, contents, include_directories); if (!is_schema && !parser->builder_.GetSize()) { // If a file doesn't end in .fbs, it must be json/binary. Ensure we // didn't just parse a schema with a different extension. Error( "input file is neither json nor a .fbs (schema) file: " + filename, true); } if (is_schema && !conform_to_schema.empty()) { auto err = parser->ConformTo(conform_parser); if (!err.empty()) Error("schemas don\'t conform: " + err); } if (schema_binary) { parser->Serialize(); parser->file_extension_ = reflection::SchemaExtension(); } } std::string filebase = flatbuffers::StripPath(flatbuffers::StripExtension(filename)); for (size_t i = 0; i < params_.num_generators; ++i) { parser->opts.lang = params_.generators[i].lang; if (generator_enabled[i]) { if (!print_make_rules) { flatbuffers::EnsureDirExists(output_path); if ((!params_.generators[i].schema_only || is_schema) && !params_.generators[i].generate(*parser.get(), output_path, filebase)) { Error(std::string("Unable to generate ") + params_.generators[i].lang_name + " for " + filebase); } } else { std::string make_rule = params_.generators[i].make_rule( *parser.get(), output_path, filename); if (!make_rule.empty()) printf("%s\n", flatbuffers::WordWrap(make_rule, 80, " ", " \\").c_str()); } if (grpc_enabled) { if (params_.generators[i].generateGRPC != nullptr) { if (!params_.generators[i].generateGRPC(*parser.get(), output_path, filebase)) { Error(std::string("Unable to generate GRPC interface for") + params_.generators[i].lang_name); } } else { Warn(std::string("GRPC interface generator not implemented for ") + params_.generators[i].lang_name); } } } } if (opts.proto_mode) GenerateFBS(*parser.get(), output_path, filebase); // We do not want to generate code for the definitions in this file // in any files coming up next. parser->MarkGenerated(); } return 0; } } // namespace flatbuffers
1
13,411
I hate to ask, but can we make this flag shorter so it lines up? :(
google-flatbuffers
java
@@ -19,9 +19,9 @@ import ( appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" - "k8s.io/apimachinery/pkg/api/errors" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/discovery"
1
package hive import ( "context" "crypto/md5" "encoding/hex" "fmt" "os" "reflect" "time" log "github.com/sirupsen/logrus" hivev1 "github.com/openshift/hive/apis/hive/v1" "github.com/openshift/hive/pkg/resource" "github.com/openshift/library-go/pkg/operator/events" appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" "k8s.io/apimachinery/pkg/api/errors" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/discovery" "k8s.io/client-go/dynamic" kubeinformers "k8s.io/client-go/informers" "k8s.io/client-go/kubernetes" corev1listers "k8s.io/client-go/listers/core/v1" "k8s.io/client-go/rest" "k8s.io/client-go/tools/cache" "k8s.io/client-go/util/workqueue" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/controller" "sigs.k8s.io/controller-runtime/pkg/event" "sigs.k8s.io/controller-runtime/pkg/handler" "sigs.k8s.io/controller-runtime/pkg/manager" "sigs.k8s.io/controller-runtime/pkg/predicate" "sigs.k8s.io/controller-runtime/pkg/reconcile" "sigs.k8s.io/controller-runtime/pkg/source" "github.com/openshift/hive/pkg/constants" "github.com/openshift/hive/pkg/operator/metrics" "github.com/openshift/hive/pkg/operator/util" ) const ( ControllerName = hivev1.HiveControllerName hiveOperatorDeploymentName = "hive-operator" managedConfigNamespace = "openshift-config-managed" aggregatorCAConfigMapName = "kube-apiserver-aggregator-client-ca" // HiveOperatorNamespaceEnvVar is the environment variable we expect to be given with the namespace the hive-operator is running in. HiveOperatorNamespaceEnvVar = "HIVE_OPERATOR_NS" // watchResyncInterval is used for a couple handcrafted watches we do with our own informers. watchResyncInterval = 30 * time.Minute ) var ( // HiveConfigConditions are the HiveConfig conditions controlled by // hive controller HiveConfigConditions = []hivev1.HiveConfigConditionType{ hivev1.HiveReadyCondition, } ) // Add creates a new Hive Controller and adds it to the Manager with default RBAC. The Manager will set fields on the Controller // and Start it when the Manager is Started. func Add(mgr manager.Manager) error { return add(mgr, newReconciler(mgr)) } // newReconciler returns a new reconcile.Reconciler func newReconciler(mgr manager.Manager) reconcile.Reconciler { return &ReconcileHiveConfig{ Client: mgr.GetClient(), scheme: mgr.GetScheme(), restConfig: mgr.GetConfig(), mgr: mgr, } } // add adds a new Controller to mgr with r as the reconcile.Reconciler func add(mgr manager.Manager, r reconcile.Reconciler) error { // Create a new controller c, err := controller.New("hive-controller", mgr, controller.Options{Reconciler: r}) if err != nil { return err } // Provide a ref to the controller on the reconciler, which is used to establish a watch on // secrets in the hive namespace, which isn't known until we have a HiveConfig. r.(*ReconcileHiveConfig).ctrlr = c r.(*ReconcileHiveConfig).kubeClient, err = kubernetes.NewForConfig(mgr.GetConfig()) if err != nil { return err } r.(*ReconcileHiveConfig).discoveryClient, err = discovery.NewDiscoveryClientForConfig(mgr.GetConfig()) if err != nil { return err } r.(*ReconcileHiveConfig).dynamicClient, err = dynamic.NewForConfig(mgr.GetConfig()) if err != nil { return err } // Regular manager client is not fully initialized here, create our own for some // initialization API communication: tempClient, err := client.New(mgr.GetConfig(), client.Options{Scheme: mgr.GetScheme()}) if err != nil { return err } hiveOperatorNS := os.Getenv(HiveOperatorNamespaceEnvVar) r.(*ReconcileHiveConfig).hiveOperatorNamespace = hiveOperatorNS log.Infof("hive operator NS: %s", hiveOperatorNS) // Determine if the openshift-config-managed namespace exists (> v4.0). If so, setup a watch // for configmaps in that namespace. ns := &corev1.Namespace{} log.Debugf("checking for existence of the %s namespace", managedConfigNamespace) err = tempClient.Get(context.TODO(), types.NamespacedName{Name: managedConfigNamespace}, ns) if err != nil && !errors.IsNotFound(err) { log.WithError(err).Errorf("error checking existence of the %s namespace", managedConfigNamespace) return err } if err == nil { log.Debugf("the %s namespace exists, setting up a watch for configmaps on it", managedConfigNamespace) // Create an informer that only listens to events in the OpenShift managed namespace kubeInformerFactory := kubeinformers.NewSharedInformerFactoryWithOptions(r.(*ReconcileHiveConfig).kubeClient, watchResyncInterval, kubeinformers.WithNamespace(managedConfigNamespace)) configMapInformer := kubeInformerFactory.Core().V1().ConfigMaps().Informer() mgr.Add(&informerRunnable{informer: configMapInformer}) // Watch for changes to cm/kube-apiserver-aggregator-client-ca in the OpenShift managed namespace err = c.Watch(&source.Informer{Informer: configMapInformer}, handler.EnqueueRequestsFromMapFunc(handler.MapFunc(aggregatorCAConfigMapHandler))) if err != nil { return err } r.(*ReconcileHiveConfig).syncAggregatorCA = true r.(*ReconcileHiveConfig).managedConfigCMLister = kubeInformerFactory.Core().V1().ConfigMaps().Lister() } else { log.Debugf("the %s namespace was not found, skipping watch for the aggregator CA configmap", managedConfigNamespace) } // Watch for changes to HiveConfig: err = c.Watch(&source.Kind{Type: &hivev1.HiveConfig{}}, &handler.EnqueueRequestForObject{}) if err != nil { return err } err = mgr.GetFieldIndexer().IndexField(context.TODO(), &hivev1.HiveConfig{}, "spec.secrets.secretName", func(o client.Object) []string { var res []string instance := o.(*hivev1.HiveConfig) // add all the secret objects to res that should trigger resync of HiveConfig for _, lObj := range instance.Spec.AdditionalCertificateAuthoritiesSecretRef { res = append(res, lObj.Name) } return res }) if err != nil { return err } // Monitor changes to DaemonSets: err = c.Watch(&source.Kind{Type: &appsv1.DaemonSet{}}, &handler.EnqueueRequestForOwner{ OwnerType: &hivev1.HiveConfig{}, }) if err != nil { return err } // Monitor changes to Deployments: err = c.Watch(&source.Kind{Type: &appsv1.Deployment{}}, &handler.EnqueueRequestForOwner{ OwnerType: &hivev1.HiveConfig{}, }) if err != nil { return err } // Monitor changes to Services: err = c.Watch(&source.Kind{Type: &corev1.Service{}}, &handler.EnqueueRequestForOwner{ OwnerType: &hivev1.HiveConfig{}, }) if err != nil { return err } // Monitor changes to StatefulSets: err = c.Watch(&source.Kind{Type: &appsv1.StatefulSet{}}, &handler.EnqueueRequestForOwner{ OwnerType: &hivev1.HiveConfig{}, }) if err != nil { return err } // Monitor CRDs so that we can keep latest list of supported contracts err = c.Watch(&source.Kind{Type: &apiextv1.CustomResourceDefinition{}}, handler.EnqueueRequestsFromMapFunc(func(_ client.Object) []reconcile.Request { retval := []reconcile.Request{} configList := &hivev1.HiveConfigList{} err := r.(*ReconcileHiveConfig).List(context.TODO(), configList) // reconcile all HiveConfigs if err != nil { log.WithError(err).Errorf("error listing hive configs for CRD reconcile") return retval } for _, config := range configList.Items { retval = append(retval, reconcile.Request{NamespacedName: types.NamespacedName{ Name: config.Name, }}) } log.WithField("configs", retval).Debug("reconciled for change in CRD") return retval })) if err != nil { return err } // Monitor the hive namespace so we can reconcile labels for monitoring. We do this with a map // func instead of an owner reference because we can't be sure we'll be the one to create it. err = c.Watch(&source.Kind{Type: &corev1.Namespace{}}, handler.EnqueueRequestsFromMapFunc(func(o client.Object) []reconcile.Request { retval := []reconcile.Request{} nsName := o.GetName() configList := &hivev1.HiveConfigList{} err := r.(*ReconcileHiveConfig).List(context.TODO(), configList) if err != nil { log.WithError(err).Errorf("error listing hive configs for namespace %s reconcile", nsName) return retval } shouldEnqueue := func(targetNS string) bool { // Always enqueue all HiveConfigs if the operator ns was updated if nsName == hiveOperatorNS { return true } // Enqueue all HiveConfigs that point to the namespace that triggered us // TODO: Is this default const'ed somewhere? if targetNS == "" && nsName == "hive" { return true } return targetNS == nsName } for _, config := range configList.Items { if shouldEnqueue(config.Spec.TargetNamespace) { retval = append(retval, reconcile.Request{NamespacedName: types.NamespacedName{ Name: config.Name, }}) } } log.WithField("configs", retval).Debugf("reconciled for change in namespace %s", nsName) return retval })) if err != nil { return err } // Lookup the hive-operator Deployment. We will assume hive components should all be // using the same image, pull policy, node selector, and tolerations as the operator. operatorDeployment := &appsv1.Deployment{} err = tempClient.Get(context.Background(), types.NamespacedName{Name: hiveOperatorDeploymentName, Namespace: hiveOperatorNS}, operatorDeployment) if err == nil { img := operatorDeployment.Spec.Template.Spec.Containers[0].Image pullPolicy := operatorDeployment.Spec.Template.Spec.Containers[0].ImagePullPolicy log.Debugf("loaded hive image from hive-operator deployment: %s (%s)", img, pullPolicy) r.(*ReconcileHiveConfig).hiveImage = img r.(*ReconcileHiveConfig).hiveImagePullPolicy = pullPolicy nodeSelector := operatorDeployment.Spec.Template.Spec.NodeSelector log.Debugf("loaded nodeSelector from hive-operator deployment: %v", nodeSelector) r.(*ReconcileHiveConfig).nodeSelector = nodeSelector tolerations := operatorDeployment.Spec.Template.Spec.Tolerations log.Debugf("loaded tolerations from hive-operator deployment: %v", tolerations) r.(*ReconcileHiveConfig).tolerations = tolerations } else { log.WithError(err).Fatal("unable to look up hive-operator Deployment") } // TODO: Monitor CRDs but do not try to use an owner ref. (as they are global, // and our config is namespaced) // TODO: it would be nice to monitor the global resources ValidatingWebhookConfiguration // and APIService, CRDs, but these cannot have OwnerReferences (which are not namespaced) as they // are global. Need to use a different predicate to the Watch function. return nil } var _ reconcile.Reconciler = &ReconcileHiveConfig{} // ReconcileHiveConfig reconciles a Hive object type ReconcileHiveConfig struct { client.Client scheme *runtime.Scheme kubeClient kubernetes.Interface discoveryClient discovery.DiscoveryInterface dynamicClient dynamic.Interface restConfig *rest.Config hiveImage string hiveOperatorNamespace string hiveImagePullPolicy corev1.PullPolicy nodeSelector map[string]string tolerations []corev1.Toleration syncAggregatorCA bool managedConfigCMLister corev1listers.ConfigMapLister ctrlr controller.Controller hiveSecretLister corev1listers.SecretLister secretWatchEstablished bool mgr manager.Manager } // Reconcile reads that state of the cluster for a Hive object and makes changes based on the state read // and what is in the Hive.Spec func (r *ReconcileHiveConfig) Reconcile(ctx context.Context, request reconcile.Request) (reconcile.Result, error) { hLog := log.WithField("controller", "hive") hLog.Info("Reconciling Hive components") recobsrv := metrics.NewReconcileObserver(ControllerName, hLog) defer recobsrv.ObserveControllerReconcileTime() // Fetch the Hive instance instance := &hivev1.HiveConfig{} // We only support one HiveConfig per cluster, and it must be called "hive". This prevents installing // Hive more than once in the cluster. if request.NamespacedName.Name != constants.HiveConfigName { hLog.WithField("hiveConfig", request.NamespacedName.Name).Warn( "invalid HiveConfig name, only one HiveConfig supported per cluster and must be named 'hive'") return reconcile.Result{}, nil } // NOTE: ignoring the Namespace that seems to get set on request when syncing on namespaced objects, // when our HiveConfig is ClusterScoped. err := r.Get(context.TODO(), types.NamespacedName{Name: request.NamespacedName.Name}, instance) if err != nil { if errors.IsNotFound(err) { // Object not found, return. Created objects are automatically garbage collected. // For additional cleanup logic use finalizers. hLog.Debug("HiveConfig not found, deleted?") r.secretWatchEstablished = false return reconcile.Result{}, nil } // Error reading the object - requeue the request. hLog.WithError(err).Error("error reading HiveConfig") return reconcile.Result{}, err } origHiveConfig := instance.DeepCopy() hiveNSName := getHiveNamespace(instance) // Initialize HiveConfig conditions if not present newConditions := util.InitializeHiveConfigConditions(instance.Status.Conditions, HiveConfigConditions) if len(newConditions) > len(origHiveConfig.Status.Conditions) { instance.Status.Conditions = newConditions hLog.Info("initializing hive controller conditions") err = r.updateHiveConfigStatus(origHiveConfig, instance, hLog, false) return reconcile.Result{}, err } if err := r.establishSecretWatch(hLog, hiveNSName); err != nil { instance.Status.Conditions = util.SetHiveConfigCondition(instance.Status.Conditions, hivev1.HiveReadyCondition, corev1.ConditionFalse, "ErrorEstablishingSecretWatch", err.Error()) r.updateHiveConfigStatus(origHiveConfig, instance, hLog, false) return reconcile.Result{}, err } recorder := events.NewRecorder(r.kubeClient.CoreV1().Events(r.hiveOperatorNamespace), "hive-operator", &corev1.ObjectReference{ Name: request.Name, Namespace: r.hiveOperatorNamespace, }) // Ensure the target namespace for hive components exists and create if not: hiveNamespace := &corev1.Namespace{ ObjectMeta: metav1.ObjectMeta{ Name: hiveNSName, }, } if err := r.Client.Create(context.Background(), hiveNamespace); err != nil { if apierrors.IsAlreadyExists(err) { hLog.WithField("hiveNS", hiveNSName).Debug("target namespace already exists") } else { hLog.WithError(err).Error("error creating hive target namespace") instance.Status.Conditions = util.SetHiveConfigCondition(instance.Status.Conditions, hivev1.HiveReadyCondition, corev1.ConditionFalse, "ErrorCreatingHiveNamespace", err.Error()) r.updateHiveConfigStatus(origHiveConfig, instance, hLog, false) return reconcile.Result{}, err } } else { hLog.WithField("hiveNS", hiveNSName).Info("target namespace created") } if r.syncAggregatorCA { // We use the configmap lister and not the regular client which only watches resources in the hive namespace aggregatorCAConfigMap, err := r.managedConfigCMLister.ConfigMaps(managedConfigNamespace).Get(aggregatorCAConfigMapName) // If an error other than not found, retry. If not found, it means we don't need to do anything with // admission pods yet. cmLog := hLog.WithField("configmap", fmt.Sprintf("%s/%s", managedConfigNamespace, aggregatorCAConfigMapName)) switch { case errors.IsNotFound(err): cmLog.Warningf("configmap was not found, will not sync aggregator CA with admission pods") case err != nil: cmLog.WithError(err).Errorf("cannot retrieve configmap") return reconcile.Result{}, err default: caHash := computeHash(aggregatorCAConfigMap.Data) cmLog.WithField("hash", caHash).Debugf("computed hash for configmap") if instance.Status.AggregatorClientCAHash != caHash { cmLog.WithField("oldHash", instance.Status.AggregatorClientCAHash). Info("configmap has changed, admission pods will restart on the next sync") instance.Status.AggregatorClientCAHash = caHash cmLog.Debugf("updating status with new aggregator CA configmap hash") err := r.updateHiveConfigStatus(origHiveConfig, instance, cmLog, true) if err != nil { cmLog.WithError(err).Error("cannot update hash in config status") } return reconcile.Result{}, err } cmLog.Debug("configmap unchanged, nothing to do") } } h, err := resource.NewHelperFromRESTConfig(r.restConfig, hLog) if err != nil { hLog.WithError(err).Error("error creating resource helper") instance.Status.Conditions = util.SetHiveConfigCondition(instance.Status.Conditions, hivev1.HiveReadyCondition, corev1.ConditionFalse, "ErrorCreatingResourceHelper", err.Error()) r.updateHiveConfigStatus(origHiveConfig, instance, hLog, false) return reconcile.Result{}, err } managedDomainsConfigMap, err := r.configureManagedDomains(hLog, instance) if err != nil { hLog.WithError(err).Error("error setting up managed domains") instance.Status.Conditions = util.SetHiveConfigCondition(instance.Status.Conditions, hivev1.HiveReadyCondition, corev1.ConditionFalse, "ErrorSettingUpManagedDomains", err.Error()) r.updateHiveConfigStatus(origHiveConfig, instance, hLog, false) return reconcile.Result{}, err } plConfigHash, err := r.deployAWSPrivateLinkConfigMap(hLog, h, instance) if err != nil { hLog.WithError(err).Error("error deploying aws privatelink configmap") instance.Status.Conditions = util.SetHiveConfigCondition(instance.Status.Conditions, hivev1.HiveReadyCondition, corev1.ConditionFalse, "ErrorDeployingAWSPrivatelinkConfigmap", err.Error()) r.updateHiveConfigStatus(origHiveConfig, instance, hLog, false) return reconcile.Result{}, err } scConfigHash, err := r.deploySupportedContractsConfigMap(hLog, h, instance) if err != nil { hLog.WithError(err).Error("error deploying supported contracts configmap") r.updateHiveConfigStatus(origHiveConfig, instance, hLog, false) return reconcile.Result{}, err } confighash, err := r.deployHiveControllersConfigMap(hLog, h, instance, plConfigHash) if err != nil { hLog.WithError(err).Error("error deploying controllers configmap") instance.Status.Conditions = util.SetHiveConfigCondition(instance.Status.Conditions, hivev1.HiveReadyCondition, corev1.ConditionFalse, "ErrorDeployingControllersConfigmap", err.Error()) r.updateHiveConfigStatus(origHiveConfig, instance, hLog, false) return reconcile.Result{}, err } fgConfigHash, err := r.deployFeatureGatesConfigMap(hLog, h, instance) if err != nil { hLog.WithError(err).Error("error deploying feature gates configmap") instance.Status.Conditions = util.SetHiveConfigCondition(instance.Status.Conditions, hivev1.HiveReadyCondition, corev1.ConditionFalse, "ErrorDeployingFeatureGatesConfigmap", err.Error()) r.updateHiveConfigStatus(origHiveConfig, instance, hLog, false) return reconcile.Result{}, err } err = r.deployHive(hLog, h, instance, recorder, managedDomainsConfigMap, confighash) if err != nil { hLog.WithError(err).Error("error deploying Hive") instance.Status.Conditions = util.SetHiveConfigCondition(instance.Status.Conditions, hivev1.HiveReadyCondition, corev1.ConditionFalse, "ErrorDeployingHive", err.Error()) r.updateHiveConfigStatus(origHiveConfig, instance, hLog, false) return reconcile.Result{}, err } err = r.deployClusterSync(hLog, h, instance, confighash) if err != nil { hLog.WithError(err).Error("error deploying ClusterSync") instance.Status.Conditions = util.SetHiveConfigCondition(instance.Status.Conditions, hivev1.HiveReadyCondition, corev1.ConditionFalse, "ErrorDeployingClusterSync", err.Error()) r.updateHiveConfigStatus(origHiveConfig, instance, hLog, false) return reconcile.Result{}, err } err = r.reconcileMonitoring(hLog, h, instance) if err != nil { hLog.WithError(err).Error("error deploying monitoring") instance.Status.Conditions = util.SetHiveConfigCondition(instance.Status.Conditions, hivev1.HiveReadyCondition, corev1.ConditionFalse, "ErrorDeployingMonitoring", err.Error()) r.updateHiveConfigStatus(origHiveConfig, instance, hLog, false) return reconcile.Result{}, err } // Cleanup legacy objects: if err := r.cleanupLegacyObjects(hLog); err != nil { return reconcile.Result{}, err } err = r.deployHiveAdmission(hLog, h, instance, recorder, managedDomainsConfigMap, fgConfigHash, plConfigHash, scConfigHash) if err != nil { hLog.WithError(err).Error("error deploying HiveAdmission") instance.Status.Conditions = util.SetHiveConfigCondition(instance.Status.Conditions, hivev1.HiveReadyCondition, corev1.ConditionFalse, "ErrorDeployingHiveAdmission", err.Error()) r.updateHiveConfigStatus(origHiveConfig, instance, hLog, false) return reconcile.Result{}, err } if err := r.cleanupLegacySyncSetInstances(hLog); err != nil { hLog.WithError(err).Error("error cleaning up legacy SyncSetInstances") instance.Status.Conditions = util.SetHiveConfigCondition(instance.Status.Conditions, hivev1.HiveReadyCondition, corev1.ConditionFalse, "ErrorDeletingLegacySyncSetInstances", err.Error()) r.updateHiveConfigStatus(origHiveConfig, instance, hLog, false) return reconcile.Result{}, err } instance.Status.Conditions = util.SetHiveConfigCondition(instance.Status.Conditions, hivev1.HiveReadyCondition, corev1.ConditionTrue, "DeploymentSuccess", "Hive is deployed successfully") if err := r.updateHiveConfigStatus(origHiveConfig, instance, hLog, true); err != nil { return reconcile.Result{}, err } return reconcile.Result{}, nil } func (r *ReconcileHiveConfig) establishSecretWatch(hLog *log.Entry, hiveNSName string) error { // We need to establish a watch on Secret in the Hive namespace, one time only. We do not know this namespace until // we have a HiveConfig. if !r.secretWatchEstablished { hLog.WithField("namespace", hiveNSName).Info("establishing watch on secrets in hive namespace") // Create an informer that only listens to events in the OpenShift managed namespace kubeInformerFactory := kubeinformers.NewSharedInformerFactoryWithOptions(r.kubeClient, watchResyncInterval, kubeinformers.WithNamespace(hiveNSName)) secretsInformer := kubeInformerFactory.Core().V1().Secrets().Informer() r.hiveSecretLister = kubeInformerFactory.Core().V1().Secrets().Lister() if err := r.mgr.Add(&informerRunnable{informer: secretsInformer}); err != nil { hLog.WithError(err).Error("error adding secret informer to manager") return err } // Watch Secrets in hive namespace, so we can detect changes to the hiveadmission serving cert secret and // force a deployment rollout. err := r.ctrlr.Watch(&source.Informer{Informer: secretsInformer}, handler.Funcs{ CreateFunc: func(e event.CreateEvent, q workqueue.RateLimitingInterface) { hLog.Debug("eventHandler CreateFunc") q.Add(reconcile.Request{NamespacedName: types.NamespacedName{Name: constants.HiveConfigName}}) }, UpdateFunc: func(e event.UpdateEvent, q workqueue.RateLimitingInterface) { hLog.Debug("eventHandler UpdateFunc") q.Add(reconcile.Request{NamespacedName: types.NamespacedName{Name: constants.HiveConfigName}}) }, }, predicate.Funcs{ CreateFunc: func(e event.CreateEvent) bool { hLog.WithField("predicateResponse", e.Object.GetName() == hiveAdmissionServingCertSecretName).Debug("secret CreateEvent") return e.Object.GetName() == hiveAdmissionServingCertSecretName }, UpdateFunc: func(e event.UpdateEvent) bool { hLog.WithField("predicateResponse", e.ObjectNew.GetName() == hiveAdmissionServingCertSecretName).Debug("secret UpdateEvent") return e.ObjectNew.GetName() == hiveAdmissionServingCertSecretName }, }) if err != nil { hLog.WithError(err).Error("error establishing secret watch") return err } // Watch secrets in HiveConfig that should trigger reconcile on change. err = r.ctrlr.Watch(&source.Informer{Informer: secretsInformer}, handler.EnqueueRequestsFromMapFunc(func(a client.Object) []reconcile.Request { retval := []reconcile.Request{} secret, ok := a.(*corev1.Secret) if !ok { // Wasn't a Secret, bail out. This should not happen. hLog.Errorf("Error converting MapObject.Object to Secret. Value: %+v", a) return retval } configWithSecrets := &hivev1.HiveConfigList{} err := r.mgr.GetClient().List(context.Background(), configWithSecrets, client.MatchingFields{"spec.secrets.secretName": secret.Name}) if err != nil { hLog.Errorf("Error listing HiveConfigs for secret %s: %v", secret.Name, err) return retval } for _, config := range configWithSecrets.Items { retval = append(retval, reconcile.Request{NamespacedName: types.NamespacedName{ Name: config.Name, }}) } hLog.WithField("secretName", secret.Name).WithField("configs", retval).Debug("secret change trigger reconcile for HiveConfigs") return retval })) if err != nil { return err } r.secretWatchEstablished = true } else { hLog.Debug("secret watch already established") } return nil } func (r *ReconcileHiveConfig) cleanupLegacyObjects(hLog log.FieldLogger) error { gvrNSNames := []gvrNSName{ {group: "rbac.authorization.k8s.io", version: "v1", resource: "clusterroles", name: "manager-role"}, {group: "rbac.authorization.k8s.io", version: "v1", resource: "clusterrolebindings", name: "manager-rolebinding"}, } for _, gvrnsn := range gvrNSNames { if err := dynamicDelete(r.dynamicClient, gvrnsn, hLog); err != nil { return err } } return nil } type informerRunnable struct { informer cache.SharedIndexInformer } func (r *informerRunnable) Start(ctx context.Context) error { stopch := ctx.Done() r.informer.Run(stopch) cache.WaitForCacheSync(stopch, r.informer.HasSynced) return nil } func aggregatorCAConfigMapHandler(o client.Object) []reconcile.Request { if o.GetName() == aggregatorCAConfigMapName { return []reconcile.Request{{NamespacedName: types.NamespacedName{Name: constants.HiveConfigName}}} } return nil } func computeHash(data map[string]string) string { hasher := md5.New() hasher.Write([]byte(fmt.Sprintf("%v", data))) return hex.EncodeToString(hasher.Sum(nil)) } func (r *ReconcileHiveConfig) updateHiveConfigStatus(origHiveConfig, newHiveConfig *hivev1.HiveConfig, logger log.FieldLogger, succeeded bool) error { newHiveConfig.Status.ObservedGeneration = newHiveConfig.Generation newHiveConfig.Status.ConfigApplied = succeeded if reflect.DeepEqual(origHiveConfig, newHiveConfig) { logger.Debug("HiveConfig unchanged, no update required") return nil } logger.Info("HiveConfig has changed, updating") err := r.Status().Update(context.TODO(), newHiveConfig) if err != nil { logger.WithError(err).Error("failed to update HiveConfig status") } return err }
1
20,231
Note to reviewers: latent, dedup import
openshift-hive
go
@@ -20,3 +20,18 @@ package agent func (i *Initializer) setupExternalConnectivity() error { return nil } + +// prepareHostNetwork returns immediately on Linux. +func (i *Initializer) prepareHostNetwork() error { + return nil +} + +// prepareOVSBridge returns immediately on Linux. +func (i *Initializer) prepareOVSBridge() error { + return nil +} + +// initHostNetworkFlows returns immediately on Linux. +func (i *Initializer) initHostNetworkFlows() error { + return nil +}
1
// +build linux // Copyright 2020 Antrea Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package agent // setupExternalConnectivity returns immediately on Linux. The corresponding functions are provided in routeClient. func (i *Initializer) setupExternalConnectivity() error { return nil }
1
14,977
Seems this func is no more needed after your refactoring.
antrea-io-antrea
go
@@ -67,6 +67,7 @@ public class MemoryUsage { Tuple.of("^java\\.", "Java mutable @ "), Tuple.of("^fj\\.", "Functional Java persistent @ "), Tuple.of("^org\\.pcollections", "PCollections persistent @ "), + Tuple.of("^io\\.usethesource", "Steindorfer persistent @ "), Tuple.of("^org\\.eclipse\\.collections", "Eclipse Collections persistent @ "), Tuple.of("^clojure\\.", "Clojure persistent @ "), Tuple.of("^scalaz\\.Heap", "Scalaz persistent @ "),
1
/* __ __ __ __ __ ___ * \ \ / / \ \ / / __/ * \ \/ / /\ \ \/ / / * \____/__/ \__\____/__/ * * Copyright 2014-2017 Vavr, http://vavr.io * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.vavr; import io.vavr.collection.*; import org.openjdk.jol.info.GraphLayout; import java.text.DecimalFormat; import java.util.function.Predicate; import java.util.regex.Pattern; import static java.lang.Math.max; public class MemoryUsage { private static final DecimalFormat FORMAT = new DecimalFormat("#,##0"); private static Map<Integer, LinkedHashSet<Seq<CharSeq>>> memoryUsages = TreeMap.empty(); // if forked, this will be reset every time /** Calculate the occupied memory of different internals */ static void printAndReset() { for (Tuple2<Integer, LinkedHashSet<Seq<CharSeq>>> entry : memoryUsages) { final Seq<Integer> columnSizes = columnSizes(entry._1); System.out.println(String.format("\nfor `%d` elements", entry._1)); for (Seq<CharSeq> stats : entry._2) { final String format = String.format(" %s → %s bytes", stats.get(0).padTo(columnSizes.get(0), ' '), stats.get(1).leftPadTo(columnSizes.get(1), ' ') ); System.out.println(format); } } memoryUsages = memoryUsages.take(0); // reset } private static Seq<Integer> columnSizes(int size) { return memoryUsages.get(size) .map(rows -> rows.map(row -> row.map(CharSeq::length))).get() .reduce((row1, row2) -> row1.zip(row2).map(ts -> max(ts._1, ts._2))); } static void storeMemoryUsages(int elementCount, Object target) { memoryUsages = memoryUsages.put(elementCount, memoryUsages.get(elementCount).getOrElse(LinkedHashSet.empty()).add(Array.of( toHumanReadableName(target), toHumanReadableByteSize(target) ).map(CharSeq::of))); } private static String toHumanReadableByteSize(Object target) { return FORMAT.format(byteSize(target)); } private static long byteSize(Object target) { return GraphLayout.parseInstance(target).totalSize(); } private static HashMap<Predicate<String>, String> names = HashMap.ofEntries( Tuple.of("^java\\.", "Java mutable @ "), Tuple.of("^fj\\.", "Functional Java persistent @ "), Tuple.of("^org\\.pcollections", "PCollections persistent @ "), Tuple.of("^org\\.eclipse\\.collections", "Eclipse Collections persistent @ "), Tuple.of("^clojure\\.", "Clojure persistent @ "), Tuple.of("^scalaz\\.Heap", "Scalaz persistent @ "), Tuple.of("^scala\\.collection.immutable", "Scala persistent @ "), Tuple.of("^scala\\.collection.mutable", "Scala mutable @ "), Tuple.of("^io\\.usethesource", "Capsule persistent @ "), Tuple.of("^io\\.vavr\\.", "Vavr persistent @ ") ).mapKeys(r -> Pattern.compile(r).asPredicate()); private static String toHumanReadableName(Object target) { final Class<?> type = target.getClass(); return prefix(type) + type.getSimpleName(); } private static String prefix(Class<?> type) { return names.find(p -> p._1.test(type.getName())).get()._2; } }
1
12,811
already added (see several rows below)
vavr-io-vavr
java
@@ -614,6 +614,8 @@ func (m *bpfEndpointManager) attachDataIfaceProgram(ifaceName string, polDirecti epType := tc.EpTypeHost if ifaceName == "tunl0" { epType = tc.EpTypeTunnel + } else if ifaceName == "wireguard.cali" { + epType = tc.EpTypeWireguard } ap := m.calculateTCAttachPoint(epType, polDirection, ifaceName) ap.HostIP = m.hostIP
1
// Copyright (c) 2020 Tigera, Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package intdataplane import ( "bytes" "encoding/binary" "encoding/json" "fmt" "net" "os/exec" "regexp" "strings" "sync" "time" "github.com/pkg/errors" "golang.org/x/sys/unix" "github.com/projectcalico/felix/bpf" "github.com/projectcalico/felix/bpf/polprog" "github.com/projectcalico/felix/bpf/tc" "github.com/projectcalico/felix/idalloc" "github.com/projectcalico/felix/ifacemonitor" log "github.com/sirupsen/logrus" "github.com/projectcalico/libcalico-go/lib/set" "github.com/projectcalico/felix/proto" ) type epIface struct { ifacemonitor.State jumpMapFD map[PolDirection]bpf.MapFD } type bpfEndpointManager struct { // Caches. Updated immediately for now. wlEps map[proto.WorkloadEndpointID]*proto.WorkloadEndpoint policies map[proto.PolicyID]*proto.Policy profiles map[proto.ProfileID]*proto.Profile ifaces map[string]epIface // Indexes policiesToWorkloads map[proto.PolicyID]set.Set /*proto.WorkloadEndpointID*/ profilesToWorkloads map[proto.ProfileID]set.Set /*proto.WorkloadEndpointID*/ dirtyWorkloads set.Set dirtyIfaces set.Set bpfLogLevel string hostname string hostIP net.IP fibLookupEnabled bool dataIfaceRegex *regexp.Regexp ipSetIDAlloc *idalloc.IDAllocator epToHostDrop bool vxlanMTU int dsrEnabled bool ipSetMap bpf.Map stateMap bpf.Map } func newBPFEndpointManager( bpfLogLevel string, hostname string, fibLookupEnabled bool, epToHostDrop bool, dataIfaceRegex *regexp.Regexp, ipSetIDAlloc *idalloc.IDAllocator, vxlanMTU int, dsrEnabled bool, ipSetMap bpf.Map, stateMap bpf.Map, ) *bpfEndpointManager { return &bpfEndpointManager{ wlEps: map[proto.WorkloadEndpointID]*proto.WorkloadEndpoint{}, policies: map[proto.PolicyID]*proto.Policy{}, profiles: map[proto.ProfileID]*proto.Profile{}, ifaces: map[string]epIface{}, policiesToWorkloads: map[proto.PolicyID]set.Set{}, profilesToWorkloads: map[proto.ProfileID]set.Set{}, dirtyWorkloads: set.New(), dirtyIfaces: set.New(), bpfLogLevel: bpfLogLevel, hostname: hostname, fibLookupEnabled: fibLookupEnabled, dataIfaceRegex: dataIfaceRegex, ipSetIDAlloc: ipSetIDAlloc, epToHostDrop: epToHostDrop, vxlanMTU: vxlanMTU, dsrEnabled: dsrEnabled, ipSetMap: ipSetMap, stateMap: stateMap, } } func (m *bpfEndpointManager) OnUpdate(msg interface{}) { switch msg := msg.(type) { // Updates from the dataplane: // Interface updates. case *ifaceUpdate: m.onInterfaceUpdate(msg) // Updates from the datamodel: // Workloads. case *proto.WorkloadEndpointUpdate: m.onWorkloadEndpointUpdate(msg) case *proto.WorkloadEndpointRemove: m.onWorkloadEnpdointRemove(msg) // Policies. case *proto.ActivePolicyUpdate: m.onPolicyUpdate(msg) case *proto.ActivePolicyRemove: m.onPolicyRemove(msg) // Profiles. case *proto.ActiveProfileUpdate: m.onProfileUpdate(msg) case *proto.ActiveProfileRemove: m.onProfileRemove(msg) case *proto.HostMetadataUpdate: if msg.Hostname == m.hostname { log.WithField("HostMetadataUpdate", msg).Info("Host IP changed") ip := net.ParseIP(msg.Ipv4Addr) if ip != nil { m.hostIP = ip for iface := range m.ifaces { m.dirtyIfaces.Add(iface) } } else { log.WithField("HostMetadataUpdate", msg).Warn("Cannot parse IP, no change applied") } } } } func (m *bpfEndpointManager) onInterfaceUpdate(update *ifaceUpdate) { if update.State == ifacemonitor.StateUnknown { log.WithField("iface", update.Name).Debug("Interface no longer present.") if iface, ok := m.ifaces[update.Name]; ok { for _, fd := range iface.jumpMapFD { _ = fd.Close() } delete(m.ifaces, update.Name) m.dirtyIfaces.Add(update.Name) } } else { log.WithFields(log.Fields{ "name": update.Name, "state": update.State, }).Debug("Interface state updated.") iface := m.ifaces[update.Name] if iface.State != update.State { iface.State = update.State m.ifaces[update.Name] = iface m.dirtyIfaces.Add(update.Name) } } } // onWorkloadEndpointUpdate adds/updates the workload in the cache along with the index from active policy to // workloads using that policy. func (m *bpfEndpointManager) onWorkloadEndpointUpdate(msg *proto.WorkloadEndpointUpdate) { log.WithField("wep", msg.Endpoint).Debug("Workload endpoint update") wlID := *msg.Id oldWL := m.wlEps[wlID] wl := msg.Endpoint if oldWL != nil { for _, t := range oldWL.Tiers { for _, pol := range t.IngressPolicies { polSet := m.policiesToWorkloads[proto.PolicyID{ Tier: t.Name, Name: pol, }] if polSet == nil { continue } polSet.Discard(wlID) } for _, pol := range t.EgressPolicies { polSet := m.policiesToWorkloads[proto.PolicyID{ Tier: t.Name, Name: pol, }] if polSet == nil { continue } polSet.Discard(wlID) } } for _, profName := range oldWL.ProfileIds { profID := proto.ProfileID{Name: profName} profSet := m.profilesToWorkloads[profID] if profSet == nil { continue } profSet.Discard(wlID) } } m.wlEps[wlID] = msg.Endpoint for _, t := range wl.Tiers { for _, pol := range t.IngressPolicies { polID := proto.PolicyID{ Tier: t.Name, Name: pol, } if m.policiesToWorkloads[polID] == nil { m.policiesToWorkloads[polID] = set.New() } m.policiesToWorkloads[polID].Add(wlID) } for _, pol := range t.EgressPolicies { polID := proto.PolicyID{ Tier: t.Name, Name: pol, } if m.policiesToWorkloads[polID] == nil { m.policiesToWorkloads[polID] = set.New() } m.policiesToWorkloads[polID].Add(wlID) } for _, profName := range wl.ProfileIds { profID := proto.ProfileID{Name: profName} profSet := m.profilesToWorkloads[profID] if profSet == nil { profSet = set.New() m.profilesToWorkloads[profID] = profSet } profSet.Add(wlID) } } m.dirtyWorkloads.Add(wlID) } // onWorkloadEndpointRemove removes the workload from the cache and the index, which maps from policy to workload. func (m *bpfEndpointManager) onWorkloadEnpdointRemove(msg *proto.WorkloadEndpointRemove) { wlID := *msg.Id log.WithField("id", wlID).Debug("Workload endpoint removed") wl := m.wlEps[wlID] for _, t := range wl.Tiers { for _, pol := range t.IngressPolicies { polSet := m.policiesToWorkloads[proto.PolicyID{ Tier: t.Name, Name: pol, }] if polSet == nil { continue } polSet.Discard(wlID) } for _, pol := range t.EgressPolicies { polSet := m.policiesToWorkloads[proto.PolicyID{ Tier: t.Name, Name: pol, }] if polSet == nil { continue } polSet.Discard(wlID) } } delete(m.wlEps, wlID) m.dirtyWorkloads.Add(wlID) } // onPolicyUpdate stores the policy in the cache and marks any endpoints using it dirty. func (m *bpfEndpointManager) onPolicyUpdate(msg *proto.ActivePolicyUpdate) { polID := *msg.Id log.WithField("id", polID).Debug("Policy update") m.policies[polID] = msg.Policy m.markPolicyUsersDirty(polID) } // onPolicyRemove removes the policy from the cache and marks any endpoints using it dirty. // The latter should be a no-op due to the ordering guarantees of the calc graph. func (m *bpfEndpointManager) onPolicyRemove(msg *proto.ActivePolicyRemove) { polID := *msg.Id log.WithField("id", polID).Debug("Policy removed") m.markPolicyUsersDirty(polID) delete(m.policies, polID) delete(m.policiesToWorkloads, polID) } // onProfileUpdate stores the profile in the cache and marks any endpoints that use it as dirty. func (m *bpfEndpointManager) onProfileUpdate(msg *proto.ActiveProfileUpdate) { profID := *msg.Id log.WithField("id", profID).Debug("Profile update") m.profiles[profID] = msg.Profile m.markProfileUsersDirty(profID) } // onProfileRemove removes the profile from the cache and marks any endpoints that were using it as dirty. // The latter should be a no-op due to the ordering guarantees of the calc graph. func (m *bpfEndpointManager) onProfileRemove(msg *proto.ActiveProfileRemove) { profID := *msg.Id log.WithField("id", profID).Debug("Profile removed") m.markProfileUsersDirty(profID) delete(m.profiles, profID) delete(m.profilesToWorkloads, profID) } func (m *bpfEndpointManager) markPolicyUsersDirty(id proto.PolicyID) { wls := m.policiesToWorkloads[id] if wls == nil { // Hear about the policy before the endpoint. return } wls.Iter(func(item interface{}) error { m.dirtyWorkloads.Add(item) return nil }) } func (m *bpfEndpointManager) markProfileUsersDirty(id proto.ProfileID) { wls := m.profilesToWorkloads[id] if wls == nil { // Hear about the policy before the endpoint. return } wls.Iter(func(item interface{}) error { m.dirtyWorkloads.Add(item) return nil }) } func (m *bpfEndpointManager) CompleteDeferredWork() error { m.applyProgramsToDirtyDataInterfaces() m.applyProgramsToDirtyWorkloadEndpoints() // TODO: handle cali interfaces with no WEP return nil } func (m *bpfEndpointManager) setAcceptLocal(iface string, val bool) error { numval := "0" if val { numval = "1" } path := fmt.Sprintf("/proc/sys/net/ipv4/conf/%s/accept_local", iface) err := writeProcSys(path, numval) if err != nil { log.WithField("err", err).Errorf("Failed to set %s to %s", path, numval) return err } log.Infof("%s set to %s", path, numval) return nil } func (m *bpfEndpointManager) applyProgramsToDirtyDataInterfaces() { var mutex sync.Mutex errs := map[string]error{} var wg sync.WaitGroup m.dirtyIfaces.Iter(func(item interface{}) error { iface := item.(string) if !m.dataIfaceRegex.MatchString(iface) { log.WithField("iface", iface).Debug( "Ignoring interface that doesn't match the host data interface regex") return set.RemoveItem } if m.ifaces[iface].State != ifacemonitor.StateUp { log.WithField("iface", iface).Debug("Ignoring interface that is down") return set.RemoveItem } wg.Add(1) go func() { defer wg.Done() err := m.attachDataIfaceProgram(iface, PolDirnIngress) if err == nil { err = m.attachDataIfaceProgram(iface, PolDirnEgress) } if err == nil { // This is required to allow NodePort forwarding with // encapsulation with the host's IP as the source address err = m.setAcceptLocal(iface, true) } mutex.Lock() errs[iface] = err mutex.Unlock() }() return nil }) wg.Wait() m.dirtyIfaces.Iter(func(item interface{}) error { iface := item.(string) err := errs[iface] if err == nil { log.WithField("id", iface).Info("Applied program to host interface") return set.RemoveItem } if err == tc.ErrDeviceNotFound { log.WithField("iface", iface).Debug( "Tried to apply BPF program to interface but the interface wasn't present. " + "Will retry if it shows up.") } log.WithError(err).Warn("Failed to apply policy to interface") return nil }) } func (m *bpfEndpointManager) applyProgramsToDirtyWorkloadEndpoints() { var mutex sync.Mutex errs := map[proto.WorkloadEndpointID]error{} var wg sync.WaitGroup m.dirtyWorkloads.Iter(func(item interface{}) error { wg.Add(1) go func() { defer wg.Done() wlID := item.(proto.WorkloadEndpointID) err := m.applyPolicy(wlID) mutex.Lock() errs[wlID] = err mutex.Unlock() }() return nil }) wg.Wait() if m.dirtyWorkloads.Len() > 0 { // Clean up any left-over jump maps in the background... go tc.CleanUpJumpMaps() } m.dirtyWorkloads.Iter(func(item interface{}) error { wlID := item.(proto.WorkloadEndpointID) err := errs[wlID] if err == nil { log.WithField("id", wlID).Info("Applied policy to workload") return set.RemoveItem } if err == tc.ErrDeviceNotFound { log.WithField("wep", wlID).Debug( "Tried to apply BPF program to interface but the interface wasn't present. " + "Will retry if it shows up.") } log.WithError(err).Warn("Failed to apply policy to endpoint") return nil }) } // applyPolicy actually applies the policy to the given workload. func (m *bpfEndpointManager) applyPolicy(wlID proto.WorkloadEndpointID) error { startTime := time.Now() wep := m.wlEps[wlID] if wep == nil { // TODO clean up old workloads return nil } var ingressErr, egressErr error var wg sync.WaitGroup wg.Add(2) go func() { defer wg.Done() ingressErr = m.attachWorkloadProgram(wep, PolDirnIngress) }() go func() { defer wg.Done() egressErr = m.attachWorkloadProgram(wep, PolDirnEgress) }() wg.Wait() if ingressErr != nil { return ingressErr } if egressErr != nil { return egressErr } applyTime := time.Since(startTime) log.WithField("timeTaken", applyTime).Info("Finished applying BPF programs for workload") return nil } var calicoRouterIP = net.IPv4(169, 254, 1, 1).To4() func (m *bpfEndpointManager) attachWorkloadProgram(endpoint *proto.WorkloadEndpoint, polDirection PolDirection) error { ap := m.calculateTCAttachPoint(tc.EpTypeWorkload, polDirection, endpoint.Name) // Host side of the veth is always configured as 169.254.1.1. ap.HostIP = calicoRouterIP // * VXLAN MTU should be the host ifaces MTU -50, in order to allow space for VXLAN. // * We also expect that to be the MTU used on veths. // * We do encap on the veths, and there's a bogus kernel MTU check in the BPF helper // for resizing the packet, so we have to reduce the apparent MTU by another 50 bytes // when we cannot encap the packet - non-GSO & too close to veth MTU ap.TunnelMTU = uint16(m.vxlanMTU - 50) var tier *proto.TierInfo if len(endpoint.Tiers) != 0 { tier = endpoint.Tiers[0] } rules := m.extractRules(tier, endpoint.ProfileIds, polDirection) iface := m.ifaces[endpoint.Name] if iface.jumpMapFD[polDirection] == 0 { // We don't have a program attached to this interface yet, attach one now. err := ap.AttachProgram() if err != nil { return err } jumpMapFD, err := FindJumpMap(ap) if err != nil { return errors.Wrap(err, "failed to look up jump map") } if iface.jumpMapFD == nil { iface.jumpMapFD = map[PolDirection]bpf.MapFD{} } iface.jumpMapFD[polDirection] = jumpMapFD m.ifaces[endpoint.Name] = iface } return m.updatePolicyProgram(iface.jumpMapFD[polDirection], rules) } func (m *bpfEndpointManager) updatePolicyProgram(jumpMapFD bpf.MapFD, rules [][][]*proto.Rule) error { pg := polprog.NewBuilder(m.ipSetIDAlloc, m.ipSetMap.MapFD(), m.stateMap.MapFD(), jumpMapFD) insns, err := pg.Instructions(rules) if err != nil { return errors.Wrap(err, "failed to generate policy bytecode") } progFD, err := bpf.LoadBPFProgramFromInsns(insns, "Apache-2.0") if err != nil { return errors.Wrap(err, "failed to load BPF policy program") } k := make([]byte, 4) v := make([]byte, 4) binary.LittleEndian.PutUint32(v, uint32(progFD)) err = bpf.UpdateMapEntry(jumpMapFD, k, v) if err != nil { return errors.Wrap(err, "failed to update jump map") } return nil } func FindJumpMap(ap tc.AttachPoint) (bpf.MapFD, error) { tcCmd := exec.Command("tc", "filter", "show", "dev", ap.Iface, string(ap.Hook)) out, err := tcCmd.Output() if err != nil { return 0, errors.Wrap(err, "failed to find TC filter for interface "+ap.Iface) } progName := ap.ProgramName() for _, line := range bytes.Split(out, []byte("\n")) { line := string(line) if strings.Contains(line, progName) { re := regexp.MustCompile(`id (\d+)`) m := re.FindStringSubmatch(line) if len(m) > 0 { progIDStr := m[1] bpftool := exec.Command("bpftool", "prog", "show", "id", progIDStr, "--json") output, err := bpftool.Output() if err != nil { return 0, errors.Wrap(err, "failed to get map metadata") } var prog struct { MapIDs []int `json:"map_ids"` } err = json.Unmarshal(output, &prog) if err != nil { return 0, errors.Wrap(err, "failed to parse bpftool output") } for _, mapID := range prog.MapIDs { mapFD, err := bpf.GetMapFDByID(mapID) if err != nil { return 0, errors.Wrap(err, "failed to get map FD from ID") } mapInfo, err := bpf.GetMapInfo(mapFD) if err != nil { err = mapFD.Close() if err != nil { log.WithError(err).Panic("Failed to close FD.") } return 0, errors.Wrap(err, "failed to get map info") } if mapInfo.Type == unix.BPF_MAP_TYPE_PROG_ARRAY { return mapFD, nil } } } return 0, errors.New("failed to find map") } } return 0, errors.New("failed to find TC program") } func (m *bpfEndpointManager) attachDataIfaceProgram(ifaceName string, polDirection PolDirection) error { epType := tc.EpTypeHost if ifaceName == "tunl0" { epType = tc.EpTypeTunnel } ap := m.calculateTCAttachPoint(epType, polDirection, ifaceName) ap.HostIP = m.hostIP ap.TunnelMTU = uint16(m.vxlanMTU) return ap.AttachProgram() } // PolDirection is the Calico datamodel direction of policy. On a host endpoint, ingress is towards the host. // On a workload endpoint, ingress is towards the workload. type PolDirection string const ( PolDirnIngress PolDirection = "ingress" PolDirnEgress PolDirection = "egress" ) func (m *bpfEndpointManager) calculateTCAttachPoint(endpointType tc.EndpointType, policyDirection PolDirection, ifaceName string) tc.AttachPoint { var ap tc.AttachPoint if endpointType == tc.EpTypeWorkload { // Policy direction is relative to the workload so, from the host namespace it's flipped. if policyDirection == PolDirnIngress { ap.Hook = tc.HookEgress } else { ap.Hook = tc.HookIngress } } else { // Host endpoints have the natural relationship between policy direction and hook. if policyDirection == PolDirnIngress { ap.Hook = tc.HookIngress } else { ap.Hook = tc.HookEgress } } var toOrFrom tc.ToOrFromEp if ap.Hook == tc.HookIngress { toOrFrom = tc.FromEp } else { toOrFrom = tc.ToEp } ap.Iface = ifaceName ap.Type = endpointType ap.ToOrFrom = toOrFrom ap.ToHostDrop = m.epToHostDrop ap.FIB = m.fibLookupEnabled ap.DSR = m.dsrEnabled ap.LogLevel = m.bpfLogLevel return ap } func (m *bpfEndpointManager) extractRules(tier *proto.TierInfo, profileNames []string, direction PolDirection) [][][]*proto.Rule { var allRules [][][]*proto.Rule if tier != nil { var pols [][]*proto.Rule directionalPols := tier.IngressPolicies if direction == PolDirnEgress { directionalPols = tier.EgressPolicies } if len(directionalPols) > 0 { for _, polName := range directionalPols { pol := m.policies[proto.PolicyID{Tier: tier.Name, Name: polName}] if direction == PolDirnIngress { pols = append(pols, pol.InboundRules) } else { pols = append(pols, pol.OutboundRules) } } allRules = append(allRules, pols) } } var profs [][]*proto.Rule for _, profName := range profileNames { prof := m.profiles[proto.ProfileID{Name: profName}] if direction == PolDirnIngress { profs = append(profs, prof.InboundRules) } else { profs = append(profs, prof.OutboundRules) } } allRules = append(allRules, profs) return allRules }
1
18,141
nit: a switch perhaps?
projectcalico-felix
go
@@ -170,7 +170,7 @@ func (c *workflowSizeChecker) failWorkflowSizeExceedsLimit() (bool, error) { tag.WorkflowEventCount(historyCount)) attributes := &decisionpb.FailWorkflowExecutionDecisionAttributes{ - Failure: failure.NewServerFailure(common.FailureReasonSizeExceedsLimit, false), + Failure: failure.NewServerFailure(common.FailureReasonSizeExceedsLimit, true), } if _, err := c.mutableState.AddFailWorkflowEvent(c.completedID, enumspb.RETRY_STATUS_NON_RETRYABLE_FAILURE, attributes); err != nil {
1
// The MIT License // // Copyright (c) 2020 Temporal Technologies Inc. All rights reserved. // // Copyright (c) 2020 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package history import ( "fmt" "strings" "time" "github.com/pborman/uuid" commonpb "go.temporal.io/api/common/v1" decisionpb "go.temporal.io/api/decision/v1" enumspb "go.temporal.io/api/enums/v1" "go.temporal.io/api/serviceerror" taskqueuepb "go.temporal.io/api/taskqueue/v1" "go.temporal.io/server/common" "go.temporal.io/server/common/backoff" "go.temporal.io/server/common/cache" "go.temporal.io/server/common/convert" "go.temporal.io/server/common/elasticsearch/validator" "go.temporal.io/server/common/failure" "go.temporal.io/server/common/log" "go.temporal.io/server/common/log/tag" "go.temporal.io/server/common/metrics" "go.temporal.io/server/common/persistence" ) type ( decisionAttrValidator struct { namespaceCache cache.NamespaceCache maxIDLengthLimit int searchAttributesValidator *validator.SearchAttributesValidator } workflowSizeChecker struct { blobSizeLimitWarn int blobSizeLimitError int historySizeLimitWarn int historySizeLimitError int historyCountLimitWarn int historyCountLimitError int completedID int64 mutableState mutableState executionStats *persistence.ExecutionStats metricsScope metrics.Scope logger log.Logger } ) const ( reservedTaskQueuePrefix = "/__temporal_sys/" ) func newDecisionAttrValidator( namespaceCache cache.NamespaceCache, config *Config, logger log.Logger, ) *decisionAttrValidator { return &decisionAttrValidator{ namespaceCache: namespaceCache, maxIDLengthLimit: config.MaxIDLengthLimit(), searchAttributesValidator: validator.NewSearchAttributesValidator( logger, config.ValidSearchAttributes, config.SearchAttributesNumberOfKeysLimit, config.SearchAttributesSizeOfValueLimit, config.SearchAttributesTotalSizeLimit, ), } } func newWorkflowSizeChecker( blobSizeLimitWarn int, blobSizeLimitError int, historySizeLimitWarn int, historySizeLimitError int, historyCountLimitWarn int, historyCountLimitError int, completedID int64, mutableState mutableState, executionStats *persistence.ExecutionStats, metricsScope metrics.Scope, logger log.Logger, ) *workflowSizeChecker { return &workflowSizeChecker{ blobSizeLimitWarn: blobSizeLimitWarn, blobSizeLimitError: blobSizeLimitError, historySizeLimitWarn: historySizeLimitWarn, historySizeLimitError: historySizeLimitError, historyCountLimitWarn: historyCountLimitWarn, historyCountLimitError: historyCountLimitError, completedID: completedID, mutableState: mutableState, executionStats: executionStats, metricsScope: metricsScope, logger: logger, } } func (c *workflowSizeChecker) failWorkflowIfPayloadSizeExceedsLimit( decisionTypeTag metrics.Tag, payloadSize int, message string, ) (bool, error) { executionInfo := c.mutableState.GetExecutionInfo() err := common.CheckEventBlobSizeLimit( payloadSize, c.blobSizeLimitWarn, c.blobSizeLimitError, executionInfo.NamespaceID, executionInfo.WorkflowID, executionInfo.RunID, c.metricsScope.Tagged(decisionTypeTag), c.logger, tag.BlobSizeViolationOperation(decisionTypeTag.Value()), ) if err == nil { return false, nil } attributes := &decisionpb.FailWorkflowExecutionDecisionAttributes{ Failure: failure.NewServerFailure(message, true), } if _, err := c.mutableState.AddFailWorkflowEvent(c.completedID, enumspb.RETRY_STATUS_NON_RETRYABLE_FAILURE, attributes); err != nil { return false, err } return true, nil } func (c *workflowSizeChecker) failWorkflowSizeExceedsLimit() (bool, error) { historyCount := int(c.mutableState.GetNextEventID()) - 1 historySize := int(c.executionStats.HistorySize) if historySize > c.historySizeLimitError || historyCount > c.historyCountLimitError { executionInfo := c.mutableState.GetExecutionInfo() c.logger.Error("history size exceeds error limit.", tag.WorkflowNamespaceID(executionInfo.NamespaceID), tag.WorkflowID(executionInfo.WorkflowID), tag.WorkflowRunID(executionInfo.RunID), tag.WorkflowHistorySize(historySize), tag.WorkflowEventCount(historyCount)) attributes := &decisionpb.FailWorkflowExecutionDecisionAttributes{ Failure: failure.NewServerFailure(common.FailureReasonSizeExceedsLimit, false), } if _, err := c.mutableState.AddFailWorkflowEvent(c.completedID, enumspb.RETRY_STATUS_NON_RETRYABLE_FAILURE, attributes); err != nil { return false, err } return true, nil } if historySize > c.historySizeLimitWarn || historyCount > c.historyCountLimitWarn { executionInfo := c.mutableState.GetExecutionInfo() c.logger.Warn("history size exceeds warn limit.", tag.WorkflowNamespaceID(executionInfo.NamespaceID), tag.WorkflowID(executionInfo.WorkflowID), tag.WorkflowRunID(executionInfo.RunID), tag.WorkflowHistorySize(historySize), tag.WorkflowEventCount(historyCount)) return false, nil } return false, nil } func (v *decisionAttrValidator) validateActivityScheduleAttributes( namespaceID string, targetNamespaceID string, attributes *decisionpb.ScheduleActivityTaskDecisionAttributes, runTimeout int32, ) error { if err := v.validateCrossNamespaceCall( namespaceID, targetNamespaceID, ); err != nil { return err } if attributes == nil { return serviceerror.NewInvalidArgument("ScheduleActivityTaskDecisionAttributes is not set on decision.") } defaultTaskQueueName := "" if _, err := v.validatedTaskQueue(attributes.TaskQueue, defaultTaskQueueName); err != nil { return err } if attributes.GetActivityId() == "" { return serviceerror.NewInvalidArgument("ActivityId is not set on decision.") } if attributes.ActivityType == nil || attributes.ActivityType.GetName() == "" { return serviceerror.NewInvalidArgument("ActivityType is not set on decision.") } if err := common.ValidateRetryPolicy(attributes.RetryPolicy); err != nil { return err } if len(attributes.GetActivityId()) > v.maxIDLengthLimit { return serviceerror.NewInvalidArgument("ActivityID exceeds length limit.") } if len(attributes.GetActivityType().GetName()) > v.maxIDLengthLimit { return serviceerror.NewInvalidArgument("ActivityType exceeds length limit.") } if len(attributes.GetNamespace()) > v.maxIDLengthLimit { return serviceerror.NewInvalidArgument("Namespace exceeds length limit.") } // Only attempt to deduce and fill in unspecified timeouts only when all timeouts are non-negative. if attributes.GetScheduleToCloseTimeoutSeconds() < 0 || attributes.GetScheduleToStartTimeoutSeconds() < 0 || attributes.GetStartToCloseTimeoutSeconds() < 0 || attributes.GetHeartbeatTimeoutSeconds() < 0 { return serviceerror.NewInvalidArgument("A valid timeout may not be negative.") } validScheduleToClose := attributes.GetScheduleToCloseTimeoutSeconds() > 0 validScheduleToStart := attributes.GetScheduleToStartTimeoutSeconds() > 0 validStartToClose := attributes.GetStartToCloseTimeoutSeconds() > 0 if validScheduleToClose { if validScheduleToStart { attributes.ScheduleToStartTimeoutSeconds = common.MinInt32(attributes.GetScheduleToStartTimeoutSeconds(), attributes.GetScheduleToCloseTimeoutSeconds()) } else { attributes.ScheduleToStartTimeoutSeconds = attributes.GetScheduleToCloseTimeoutSeconds() } if validStartToClose { attributes.StartToCloseTimeoutSeconds = common.MinInt32(attributes.GetStartToCloseTimeoutSeconds(), attributes.GetScheduleToCloseTimeoutSeconds()) } else { attributes.StartToCloseTimeoutSeconds = attributes.GetScheduleToCloseTimeoutSeconds() } } else if validStartToClose { // We are in !validScheduleToClose due to the first if above attributes.ScheduleToCloseTimeoutSeconds = runTimeout if !validScheduleToStart { attributes.ScheduleToStartTimeoutSeconds = runTimeout } } else { // Deduction failed as there's not enough information to fill in missing timeouts. return serviceerror.NewInvalidArgument("A valid StartToClose or ScheduleToCloseTimeout is not set on decision.") } // ensure activity timeout never larger than workflow timeout if runTimeout > 0 { if attributes.GetScheduleToCloseTimeoutSeconds() > runTimeout { attributes.ScheduleToCloseTimeoutSeconds = runTimeout } if attributes.GetScheduleToStartTimeoutSeconds() > runTimeout { attributes.ScheduleToStartTimeoutSeconds = runTimeout } if attributes.GetStartToCloseTimeoutSeconds() > runTimeout { attributes.StartToCloseTimeoutSeconds = runTimeout } if attributes.GetHeartbeatTimeoutSeconds() > runTimeout { attributes.HeartbeatTimeoutSeconds = runTimeout } } if attributes.GetHeartbeatTimeoutSeconds() > attributes.GetScheduleToCloseTimeoutSeconds() { attributes.HeartbeatTimeoutSeconds = attributes.GetScheduleToCloseTimeoutSeconds() } return nil } func (v *decisionAttrValidator) validateTimerScheduleAttributes( attributes *decisionpb.StartTimerDecisionAttributes, ) error { if attributes == nil { return serviceerror.NewInvalidArgument("StartTimerDecisionAttributes is not set on decision.") } if attributes.GetTimerId() == "" { return serviceerror.NewInvalidArgument("TimerId is not set on decision.") } if len(attributes.GetTimerId()) > v.maxIDLengthLimit { return serviceerror.NewInvalidArgument("TimerId exceeds length limit.") } if attributes.GetStartToFireTimeoutSeconds() <= 0 { return serviceerror.NewInvalidArgument("A valid StartToFireTimeoutSeconds is not set on decision.") } return nil } func (v *decisionAttrValidator) validateActivityCancelAttributes( attributes *decisionpb.RequestCancelActivityTaskDecisionAttributes, ) error { if attributes == nil { return serviceerror.NewInvalidArgument("RequestCancelActivityTaskDecisionAttributes is not set on decision.") } if attributes.GetScheduledEventId() <= 0 { return serviceerror.NewInvalidArgument("ScheduledEventId is not set on decision.") } return nil } func (v *decisionAttrValidator) validateTimerCancelAttributes( attributes *decisionpb.CancelTimerDecisionAttributes, ) error { if attributes == nil { return serviceerror.NewInvalidArgument("CancelTimerDecisionAttributes is not set on decision.") } if attributes.GetTimerId() == "" { return serviceerror.NewInvalidArgument("TimerId is not set on decision.") } if len(attributes.GetTimerId()) > v.maxIDLengthLimit { return serviceerror.NewInvalidArgument("TimerId exceeds length limit.") } return nil } func (v *decisionAttrValidator) validateRecordMarkerAttributes( attributes *decisionpb.RecordMarkerDecisionAttributes, ) error { if attributes == nil { return serviceerror.NewInvalidArgument("RecordMarkerDecisionAttributes is not set on decision.") } if attributes.GetMarkerName() == "" { return serviceerror.NewInvalidArgument("MarkerName is not set on decision.") } if len(attributes.GetMarkerName()) > v.maxIDLengthLimit { return serviceerror.NewInvalidArgument("MarkerName exceeds length limit.") } return nil } func (v *decisionAttrValidator) validateCompleteWorkflowExecutionAttributes( attributes *decisionpb.CompleteWorkflowExecutionDecisionAttributes, ) error { if attributes == nil { return serviceerror.NewInvalidArgument("CompleteWorkflowExecutionDecisionAttributes is not set on decision.") } return nil } func (v *decisionAttrValidator) validateFailWorkflowExecutionAttributes( attributes *decisionpb.FailWorkflowExecutionDecisionAttributes, ) error { if attributes == nil { return serviceerror.NewInvalidArgument("FailWorkflowExecutionDecisionAttributes is not set on decision.") } if attributes.GetFailure() == nil { return serviceerror.NewInvalidArgument("Failure is not set on decision.") } return nil } func (v *decisionAttrValidator) validateCancelWorkflowExecutionAttributes( attributes *decisionpb.CancelWorkflowExecutionDecisionAttributes, ) error { if attributes == nil { return serviceerror.NewInvalidArgument("CancelWorkflowExecutionDecisionAttributes is not set on decision.") } return nil } func (v *decisionAttrValidator) validateCancelExternalWorkflowExecutionAttributes( namespaceID string, targetNamespaceID string, attributes *decisionpb.RequestCancelExternalWorkflowExecutionDecisionAttributes, ) error { if err := v.validateCrossNamespaceCall( namespaceID, targetNamespaceID, ); err != nil { return err } if attributes == nil { return serviceerror.NewInvalidArgument("RequestCancelExternalWorkflowExecutionDecisionAttributes is not set on decision.") } if attributes.GetWorkflowId() == "" { return serviceerror.NewInvalidArgument("WorkflowId is not set on decision.") } if len(attributes.GetNamespace()) > v.maxIDLengthLimit { return serviceerror.NewInvalidArgument("Namespace exceeds length limit.") } if len(attributes.GetWorkflowId()) > v.maxIDLengthLimit { return serviceerror.NewInvalidArgument("WorkflowId exceeds length limit.") } runID := attributes.GetRunId() if runID != "" && uuid.Parse(runID) == nil { return serviceerror.NewInvalidArgument("Invalid RunId set on decision.") } return nil } func (v *decisionAttrValidator) validateSignalExternalWorkflowExecutionAttributes( namespaceID string, targetNamespaceID string, attributes *decisionpb.SignalExternalWorkflowExecutionDecisionAttributes, ) error { if err := v.validateCrossNamespaceCall( namespaceID, targetNamespaceID, ); err != nil { return err } if attributes == nil { return serviceerror.NewInvalidArgument("SignalExternalWorkflowExecutionDecisionAttributes is not set on decision.") } if attributes.Execution == nil { return serviceerror.NewInvalidArgument("Execution is nil on decision.") } if attributes.Execution.GetWorkflowId() == "" { return serviceerror.NewInvalidArgument("WorkflowId is not set on decision.") } if len(attributes.GetNamespace()) > v.maxIDLengthLimit { return serviceerror.NewInvalidArgument("Namespace exceeds length limit.") } if len(attributes.Execution.GetWorkflowId()) > v.maxIDLengthLimit { return serviceerror.NewInvalidArgument("WorkflowId exceeds length limit.") } targetRunID := attributes.Execution.GetRunId() if targetRunID != "" && uuid.Parse(targetRunID) == nil { return serviceerror.NewInvalidArgument("Invalid RunId set on decision.") } if attributes.GetSignalName() == "" { return serviceerror.NewInvalidArgument("SignalName is not set on decision.") } return nil } func (v *decisionAttrValidator) validateUpsertWorkflowSearchAttributes( namespace string, attributes *decisionpb.UpsertWorkflowSearchAttributesDecisionAttributes, ) error { if attributes == nil { return serviceerror.NewInvalidArgument("UpsertWorkflowSearchAttributesDecisionAttributes is not set on decision.") } if attributes.SearchAttributes == nil { return serviceerror.NewInvalidArgument("SearchAttributes is not set on decision.") } if len(attributes.GetSearchAttributes().GetIndexedFields()) == 0 { return serviceerror.NewInvalidArgument("IndexedFields is empty on decision.") } return v.searchAttributesValidator.ValidateSearchAttributes(attributes.GetSearchAttributes(), namespace) } func (v *decisionAttrValidator) validateContinueAsNewWorkflowExecutionAttributes( attributes *decisionpb.ContinueAsNewWorkflowExecutionDecisionAttributes, executionInfo *persistence.WorkflowExecutionInfo, ) error { if attributes == nil { return serviceerror.NewInvalidArgument("ContinueAsNewWorkflowExecutionDecisionAttributes is not set on decision.") } // Inherit workflow type from previous execution if not provided on decision if attributes.WorkflowType == nil || attributes.WorkflowType.GetName() == "" { attributes.WorkflowType = &commonpb.WorkflowType{Name: executionInfo.WorkflowTypeName} } if len(attributes.WorkflowType.GetName()) > v.maxIDLengthLimit { return serviceerror.NewInvalidArgument("WorkflowType exceeds length limit.") } // Inherit Taskqueue from previous execution if not provided on decision taskQueue, err := v.validatedTaskQueue(attributes.TaskQueue, executionInfo.TaskQueue) if err != nil { return err } attributes.TaskQueue = taskQueue // Reduce runTimeout if it is going to exceed WorkflowExpirationTime // Note that this calculation can produce negative result // handleDecisionContinueAsNewWorkflow must handle negative runTimeout value timeoutTime := executionInfo.WorkflowExpirationTime if !timeoutTime.IsZero() { runTimeout := convert.Int32Ceil(timeoutTime.Sub(time.Now()).Seconds()) if attributes.GetWorkflowRunTimeoutSeconds() > 0 { runTimeout = common.MinInt32(runTimeout, attributes.GetWorkflowRunTimeoutSeconds()) } else { runTimeout = common.MinInt32(runTimeout, executionInfo.WorkflowRunTimeout) } attributes.WorkflowRunTimeoutSeconds = runTimeout } else if attributes.GetWorkflowRunTimeoutSeconds() == 0 { attributes.WorkflowRunTimeoutSeconds = executionInfo.WorkflowRunTimeout } // Inherit decision task timeout from previous execution if not provided on decision if attributes.GetWorkflowTaskTimeoutSeconds() <= 0 { attributes.WorkflowTaskTimeoutSeconds = executionInfo.WorkflowTaskTimeout } // Check next run decision task delay if attributes.GetBackoffStartIntervalInSeconds() < 0 { return serviceerror.NewInvalidArgument("BackoffStartInterval is less than 0.") } namespaceEntry, err := v.namespaceCache.GetNamespaceByID(executionInfo.NamespaceID) if err != nil { return err } return v.searchAttributesValidator.ValidateSearchAttributes(attributes.GetSearchAttributes(), namespaceEntry.GetInfo().Name) } func (v *decisionAttrValidator) validateStartChildExecutionAttributes( namespaceID string, targetNamespaceID string, attributes *decisionpb.StartChildWorkflowExecutionDecisionAttributes, parentInfo *persistence.WorkflowExecutionInfo, ) error { if err := v.validateCrossNamespaceCall( namespaceID, targetNamespaceID, ); err != nil { return err } if attributes == nil { return serviceerror.NewInvalidArgument("StartChildWorkflowExecutionDecisionAttributes is not set on decision.") } if attributes.GetWorkflowId() == "" { return serviceerror.NewInvalidArgument("Required field WorkflowId is not set on decision.") } if attributes.WorkflowType == nil || attributes.WorkflowType.GetName() == "" { return serviceerror.NewInvalidArgument("Required field WorkflowType is not set on decision.") } if len(attributes.GetNamespace()) > v.maxIDLengthLimit { return serviceerror.NewInvalidArgument("Namespace exceeds length limit.") } if len(attributes.GetWorkflowId()) > v.maxIDLengthLimit { return serviceerror.NewInvalidArgument("WorkflowId exceeds length limit.") } if len(attributes.WorkflowType.GetName()) > v.maxIDLengthLimit { return serviceerror.NewInvalidArgument("WorkflowType exceeds length limit.") } if err := common.ValidateRetryPolicy(attributes.RetryPolicy); err != nil { return err } if err := backoff.ValidateSchedule(attributes.GetCronSchedule()); err != nil { return err } // Inherit taskqueue from parent workflow execution if not provided on decision taskQueue, err := v.validatedTaskQueue(attributes.TaskQueue, parentInfo.TaskQueue) if err != nil { return err } attributes.TaskQueue = taskQueue // Inherit workflow timeout from parent workflow execution if not provided on decision if attributes.GetWorkflowExecutionTimeoutSeconds() <= 0 { attributes.WorkflowExecutionTimeoutSeconds = parentInfo.WorkflowExecutionTimeout } // Inherit workflow timeout from parent workflow execution if not provided on decision if attributes.GetWorkflowRunTimeoutSeconds() <= 0 { attributes.WorkflowRunTimeoutSeconds = parentInfo.WorkflowRunTimeout } // Inherit decision task timeout from parent workflow execution if not provided on decision if attributes.GetWorkflowTaskTimeoutSeconds() <= 0 { attributes.WorkflowTaskTimeoutSeconds = parentInfo.WorkflowTaskTimeout } return nil } func (v *decisionAttrValidator) validatedTaskQueue( taskQueue *taskqueuepb.TaskQueue, defaultVal string, ) (*taskqueuepb.TaskQueue, error) { if taskQueue == nil { taskQueue = &taskqueuepb.TaskQueue{} } if taskQueue.GetName() == "" { if defaultVal == "" { return taskQueue, serviceerror.NewInvalidArgument("missing task queue name") } taskQueue.Name = defaultVal return taskQueue, nil } name := taskQueue.GetName() if len(name) > v.maxIDLengthLimit { return taskQueue, serviceerror.NewInvalidArgument(fmt.Sprintf("task queue name exceeds length limit of %v", v.maxIDLengthLimit)) } if strings.HasPrefix(name, reservedTaskQueuePrefix) { return taskQueue, serviceerror.NewInvalidArgument(fmt.Sprintf("task queue name cannot start with reserved prefix %v", reservedTaskQueuePrefix)) } return taskQueue, nil } func (v *decisionAttrValidator) validateCrossNamespaceCall( namespaceID string, targetNamespaceID string, ) error { // same name, no check needed if namespaceID == targetNamespaceID { return nil } namespaceEntry, err := v.namespaceCache.GetNamespaceByID(namespaceID) if err != nil { return err } targetNamespaceEntry, err := v.namespaceCache.GetNamespaceByID(targetNamespaceID) if err != nil { return err } // both local namespace if !namespaceEntry.IsGlobalNamespace() && !targetNamespaceEntry.IsGlobalNamespace() { return nil } namespaceClusters := namespaceEntry.GetReplicationConfig().Clusters targetNamespaceClusters := targetNamespaceEntry.GetReplicationConfig().Clusters // one is local namespace, another one is global namespace or both global namespace // treat global namespace with one replication cluster as local namespace if len(namespaceClusters) == 1 && len(targetNamespaceClusters) == 1 { if namespaceClusters[0] == targetNamespaceClusters[0] { return nil } return v.createCrossNamespaceCallError(namespaceEntry, targetNamespaceEntry) } return v.createCrossNamespaceCallError(namespaceEntry, targetNamespaceEntry) } func (v *decisionAttrValidator) createCrossNamespaceCallError( namespaceEntry *cache.NamespaceCacheEntry, targetNamespaceEntry *cache.NamespaceCacheEntry, ) error { return serviceerror.NewInvalidArgument(fmt.Sprintf("cannot make cross namespace call between %v and %v", namespaceEntry.GetInfo().Name, targetNamespaceEntry.GetInfo().Name)) }
1
9,816
Great you caught this. Super critical to not retry these errors.
temporalio-temporal
go
@@ -77,7 +77,7 @@ enum CoreAdminOperation implements CoreAdminOp { String coreName = params.required().get(CoreAdminParams.NAME); Map<String, String> coreParams = buildCoreParams(params); CoreContainer coreContainer = it.handler.coreContainer; - Path instancePath = coreContainer.getCoreRootDirectory().resolve(coreName); + Path instancePath; // TODO: Should we nuke setting odd instance paths? They break core discovery, generally String instanceDir = it.req.getParams().get(CoreAdminParams.INSTANCE_DIR);
1
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.solr.handler.admin; import java.io.IOException; import java.lang.invoke.MethodHandles; import java.nio.file.Path; import java.util.Locale; import java.util.Map; import java.util.Optional; import org.apache.commons.lang3.StringUtils; import org.apache.solr.cloud.CloudDescriptor; import org.apache.solr.cloud.ZkController; import org.apache.solr.common.SolrException; import org.apache.solr.common.SolrException.ErrorCode; import org.apache.solr.common.params.CoreAdminParams; import org.apache.solr.common.params.SolrParams; import org.apache.solr.common.util.NamedList; import org.apache.solr.common.util.SimpleOrderedMap; import org.apache.solr.common.util.Utils; import org.apache.solr.core.CoreContainer; import org.apache.solr.core.CoreDescriptor; import org.apache.solr.core.SolrCore; import org.apache.solr.core.SolrInfoBean; import org.apache.solr.core.snapshots.SolrSnapshotManager; import org.apache.solr.core.snapshots.SolrSnapshotMetaDataManager; import org.apache.solr.core.snapshots.SolrSnapshotMetaDataManager.SnapshotMetaData; import org.apache.solr.handler.admin.CoreAdminHandler.CoreAdminOp; import org.apache.solr.metrics.SolrMetricManager; import org.apache.solr.search.SolrIndexSearcher; import org.apache.solr.update.UpdateLog; import org.apache.solr.util.NumberUtils; import org.apache.solr.util.PropertiesUtil; import org.apache.solr.util.RefCounted; import org.apache.solr.util.TestInjection; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.apache.solr.common.params.CommonParams.NAME; import static org.apache.solr.common.params.CoreAdminParams.COLLECTION; import static org.apache.solr.common.params.CoreAdminParams.CoreAdminAction.*; import static org.apache.solr.common.params.CoreAdminParams.REPLICA; import static org.apache.solr.common.params.CoreAdminParams.REPLICA_TYPE; import static org.apache.solr.common.params.CoreAdminParams.SHARD; import static org.apache.solr.handler.admin.CoreAdminHandler.COMPLETED; import static org.apache.solr.handler.admin.CoreAdminHandler.CallInfo; import static org.apache.solr.handler.admin.CoreAdminHandler.FAILED; import static org.apache.solr.handler.admin.CoreAdminHandler.RESPONSE; import static org.apache.solr.handler.admin.CoreAdminHandler.RESPONSE_MESSAGE; import static org.apache.solr.handler.admin.CoreAdminHandler.RESPONSE_STATUS; import static org.apache.solr.handler.admin.CoreAdminHandler.RUNNING; import static org.apache.solr.handler.admin.CoreAdminHandler.buildCoreParams; import static org.apache.solr.handler.admin.CoreAdminHandler.normalizePath; enum CoreAdminOperation implements CoreAdminOp { CREATE_OP(CREATE, it -> { assert TestInjection.injectRandomDelayInCoreCreation(); SolrParams params = it.req.getParams(); log().info("core create command {}", params); String coreName = params.required().get(CoreAdminParams.NAME); Map<String, String> coreParams = buildCoreParams(params); CoreContainer coreContainer = it.handler.coreContainer; Path instancePath = coreContainer.getCoreRootDirectory().resolve(coreName); // TODO: Should we nuke setting odd instance paths? They break core discovery, generally String instanceDir = it.req.getParams().get(CoreAdminParams.INSTANCE_DIR); if (instanceDir == null) instanceDir = it.req.getParams().get("property.instanceDir"); if (instanceDir != null) { instanceDir = PropertiesUtil.substituteProperty(instanceDir, coreContainer.getContainerProperties()); instancePath = coreContainer.getCoreRootDirectory().resolve(instanceDir).normalize(); } boolean newCollection = params.getBool(CoreAdminParams.NEW_COLLECTION, false); coreContainer.create(coreName, instancePath, coreParams, newCollection); it.rsp.add("core", coreName); }), UNLOAD_OP(UNLOAD, it -> { SolrParams params = it.req.getParams(); String cname = params.required().get(CoreAdminParams.CORE); boolean deleteIndexDir = params.getBool(CoreAdminParams.DELETE_INDEX, false); boolean deleteDataDir = params.getBool(CoreAdminParams.DELETE_DATA_DIR, false); boolean deleteInstanceDir = params.getBool(CoreAdminParams.DELETE_INSTANCE_DIR, false); boolean deleteMetricsHistory = params.getBool(CoreAdminParams.DELETE_METRICS_HISTORY, false); CoreDescriptor cdescr = it.handler.coreContainer.getCoreDescriptor(cname); it.handler.coreContainer.unload(cname, deleteIndexDir, deleteDataDir, deleteInstanceDir); if (deleteMetricsHistory) { MetricsHistoryHandler historyHandler = it.handler.coreContainer.getMetricsHistoryHandler(); if (historyHandler != null) { CloudDescriptor cd = cdescr != null ? cdescr.getCloudDescriptor() : null; String registry; if (cd == null) { registry = SolrMetricManager.getRegistryName(SolrInfoBean.Group.core, cname); } else { String replicaName = Utils.parseMetricsReplicaName(cd.getCollectionName(), cname); registry = SolrMetricManager.getRegistryName(SolrInfoBean.Group.core, cd.getCollectionName(), cd.getShardId(), replicaName); } historyHandler.checkSystemCollection(); historyHandler.removeHistory(registry); } } assert TestInjection.injectNonExistentCoreExceptionAfterUnload(cname); }), RELOAD_OP(RELOAD, it -> { SolrParams params = it.req.getParams(); String cname = params.required().get(CoreAdminParams.CORE); it.handler.coreContainer.reload(cname); }), STATUS_OP(STATUS, new StatusOp()), SWAP_OP(SWAP, it -> { final SolrParams params = it.req.getParams(); final String cname = params.required().get(CoreAdminParams.CORE); String other = params.required().get(CoreAdminParams.OTHER); it.handler.coreContainer.swap(cname, other); }), RENAME_OP(RENAME, it -> { SolrParams params = it.req.getParams(); String name = params.required().get(CoreAdminParams.OTHER); String cname = params.required().get(CoreAdminParams.CORE); if (cname.equals(name)) return; it.handler.coreContainer.rename(cname, name); }), MERGEINDEXES_OP(MERGEINDEXES, new MergeIndexesOp()), SPLIT_OP(SPLIT, new SplitOp()), PREPRECOVERY_OP(PREPRECOVERY, new PrepRecoveryOp()), REQUESTRECOVERY_OP(REQUESTRECOVERY, it -> { final SolrParams params = it.req.getParams(); final String cname = params.required().get(CoreAdminParams.CORE); log().info("It has been requested that we recover: core=" + cname); try (SolrCore core = it.handler.coreContainer.getCore(cname)) { if (core != null) { // This can take a while, but doRecovery is already async so don't worry about it here core.getUpdateHandler().getSolrCoreState().doRecovery(it.handler.coreContainer, core.getCoreDescriptor()); } else { throw new SolrException(ErrorCode.BAD_REQUEST, "Unable to locate core " + cname); } } }), REQUESTSYNCSHARD_OP(REQUESTSYNCSHARD, new RequestSyncShardOp()), REQUESTBUFFERUPDATES_OP(REQUESTBUFFERUPDATES, it -> { SolrParams params = it.req.getParams(); String cname = params.required().get(CoreAdminParams.NAME); log().info("Starting to buffer updates on core:" + cname); try (SolrCore core = it.handler.coreContainer.getCore(cname)) { if (core == null) throw new SolrException(ErrorCode.BAD_REQUEST, "Core [" + cname + "] does not exist"); UpdateLog updateLog = core.getUpdateHandler().getUpdateLog(); if (updateLog.getState() != UpdateLog.State.ACTIVE) { throw new SolrException(ErrorCode.SERVER_ERROR, "Core " + cname + " not in active state"); } updateLog.bufferUpdates(); it.rsp.add("core", cname); it.rsp.add("status", "BUFFERING"); } catch (Throwable e) { if (e instanceof SolrException) throw (SolrException) e; else throw new SolrException(ErrorCode.SERVER_ERROR, "Could not start buffering updates", e); } finally { if (it.req != null) it.req.close(); } }), REQUESTAPPLYUPDATES_OP(REQUESTAPPLYUPDATES, new RequestApplyUpdatesOp()), REQUESTSTATUS_OP(REQUESTSTATUS, it -> { SolrParams params = it.req.getParams(); String requestId = params.required().get(CoreAdminParams.REQUESTID); log().info("Checking request status for : " + requestId); if (it.handler.getRequestStatusMap(RUNNING).containsKey(requestId)) { it.rsp.add(RESPONSE_STATUS, RUNNING); } else if (it.handler.getRequestStatusMap(COMPLETED).containsKey(requestId)) { it.rsp.add(RESPONSE_STATUS, COMPLETED); it.rsp.add(RESPONSE, it.handler.getRequestStatusMap(COMPLETED).get(requestId).getRspObject()); } else if (it.handler.getRequestStatusMap(FAILED).containsKey(requestId)) { it.rsp.add(RESPONSE_STATUS, FAILED); it.rsp.add(RESPONSE, it.handler.getRequestStatusMap(FAILED).get(requestId).getRspObject()); } else { it.rsp.add(RESPONSE_STATUS, "notfound"); it.rsp.add(RESPONSE_MESSAGE, "No task found in running, completed or failed tasks"); } }), OVERSEEROP_OP(OVERSEEROP, it -> { ZkController zkController = it.handler.coreContainer.getZkController(); if (zkController != null) { String op = it.req.getParams().get("op"); String electionNode = it.req.getParams().get("electionNode"); if (electionNode != null) { zkController.rejoinOverseerElection(electionNode, "rejoinAtHead".equals(op)); } else { log().info("electionNode is required param"); } } }), REJOINLEADERELECTION_OP(REJOINLEADERELECTION, it -> { ZkController zkController = it.handler.coreContainer.getZkController(); if (zkController != null) { zkController.rejoinShardLeaderElection(it.req.getParams()); } else { log().warn("zkController is null in CoreAdminHandler.handleRequestInternal:REJOINLEADERELECTION. No action taken."); } }), INVOKE_OP(INVOKE, new InvokeOp()), BACKUPCORE_OP(BACKUPCORE, new BackupCoreOp()), RESTORECORE_OP(RESTORECORE, new RestoreCoreOp()), CREATESNAPSHOT_OP(CREATESNAPSHOT, new CreateSnapshotOp()), DELETESNAPSHOT_OP(DELETESNAPSHOT, new DeleteSnapshotOp()), LISTSNAPSHOTS_OP(LISTSNAPSHOTS, it -> { final SolrParams params = it.req.getParams(); String cname = params.required().get(CoreAdminParams.CORE); CoreContainer cc = it.handler.getCoreContainer(); try ( SolrCore core = cc.getCore(cname) ) { if (core == null) { throw new SolrException(ErrorCode.BAD_REQUEST, "Unable to locate core " + cname); } SolrSnapshotMetaDataManager mgr = core.getSnapshotMetaDataManager(); NamedList result = new NamedList(); for (String name : mgr.listSnapshots()) { Optional<SnapshotMetaData> metadata = mgr.getSnapshotMetaData(name); if ( metadata.isPresent() ) { NamedList<String> props = new NamedList<>(); props.add(SolrSnapshotManager.GENERATION_NUM, String.valueOf(metadata.get().getGenerationNumber())); props.add(SolrSnapshotManager.INDEX_DIR_PATH, metadata.get().getIndexDirPath()); result.add(name, props); } } it.rsp.add(SolrSnapshotManager.SNAPSHOTS_INFO, result); } }); final CoreAdminParams.CoreAdminAction action; final CoreAdminOp fun; CoreAdminOperation(CoreAdminParams.CoreAdminAction action, CoreAdminOp fun) { this.action = action; this.fun = fun; } private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); static Logger log() { return log; } /** * Returns the core status for a particular core. * @param cores - the enclosing core container * @param cname - the core to return * @param isIndexInfoNeeded - add what may be expensive index information. NOT returned if the core is not loaded * @return - a named list of key/value pairs from the core. * @throws IOException - LukeRequestHandler can throw an I/O exception */ static NamedList<Object> getCoreStatus(CoreContainer cores, String cname, boolean isIndexInfoNeeded) throws IOException { NamedList<Object> info = new SimpleOrderedMap<>(); if (cores.isCoreLoading(cname)) { info.add(NAME, cname); info.add("isLoaded", "false"); info.add("isLoading", "true"); } else { if (!cores.isLoaded(cname)) { // Lazily-loaded core, fill in what we can. // It would be a real mistake to load the cores just to get the status CoreDescriptor desc = cores.getUnloadedCoreDescriptor(cname); if (desc != null) { info.add(NAME, desc.getName()); info.add("instanceDir", desc.getInstanceDir()); // None of the following are guaranteed to be present in a not-yet-loaded core. String tmp = desc.getDataDir(); if (StringUtils.isNotBlank(tmp)) info.add("dataDir", tmp); tmp = desc.getConfigName(); if (StringUtils.isNotBlank(tmp)) info.add("config", tmp); tmp = desc.getSchemaName(); if (StringUtils.isNotBlank(tmp)) info.add("schema", tmp); info.add("isLoaded", "false"); } } else { try (SolrCore core = cores.getCore(cname)) { if (core != null) { info.add(NAME, core.getName()); info.add("instanceDir", core.getInstancePath().toString()); info.add("dataDir", normalizePath(core.getDataDir())); info.add("config", core.getConfigResource()); info.add("schema", core.getSchemaResource()); info.add("startTime", core.getStartTimeStamp()); info.add("uptime", core.getUptimeMs()); if (cores.isZooKeeperAware()) { info.add("lastPublished", core.getCoreDescriptor().getCloudDescriptor().getLastPublished().toString().toLowerCase(Locale.ROOT)); info.add("configVersion", core.getSolrConfig().getZnodeVersion()); SimpleOrderedMap cloudInfo = new SimpleOrderedMap<>(); cloudInfo.add(COLLECTION, core.getCoreDescriptor().getCloudDescriptor().getCollectionName()); cloudInfo.add(SHARD, core.getCoreDescriptor().getCloudDescriptor().getShardId()); cloudInfo.add(REPLICA, core.getCoreDescriptor().getCloudDescriptor().getCoreNodeName()); cloudInfo.add(REPLICA_TYPE, core.getCoreDescriptor().getCloudDescriptor().getReplicaType().name()); info.add("cloud", cloudInfo); } if (isIndexInfoNeeded) { RefCounted<SolrIndexSearcher> searcher = core.getSearcher(); try { SimpleOrderedMap<Object> indexInfo = LukeRequestHandler.getIndexInfo(searcher.get().getIndexReader()); long size = core.getIndexSize(); indexInfo.add("sizeInBytes", size); indexInfo.add("size", NumberUtils.readableSize(size)); info.add("index", indexInfo); } finally { searcher.decref(); } } } } } } return info; } @Override public void execute(CallInfo it) throws Exception { try { fun.execute(it); } catch (SolrException | InterruptedException e) { // No need to re-wrap; throw as-is. throw e; } catch (Exception e) { throw new SolrException(ErrorCode.SERVER_ERROR, "Error handling '" + action.name() + "' action", e); } } }
1
34,526
Just a little change to make the var effectively final, which is clearer.
apache-lucene-solr
java
@@ -30,8 +30,8 @@ def flowdetails(state, flow: http.HTTPFlow): if sc is not None: text.append(urwid.Text([("head", "Server Connection:")])) parts = [ - ["Address", "{}:{}".format(sc.address[0], sc.address[1])], - ["Resolved Address", "{}:{}".format(sc.ip_address[0], sc.ip_address[1])], + ["Address", "{}".format(human.format_address(sc.address))], + ["Resolved Address", "{}".format(human.format_address(sc.ip_address))], ] if resp: parts.append(["HTTP Version", resp.http_version])
1
import urwid from mitmproxy import http from mitmproxy.tools.console import common, searchable from mitmproxy.utils import human from mitmproxy.utils import strutils def maybe_timestamp(base, attr): if base is not None and getattr(base, attr): return human.format_timestamp_with_milli(getattr(base, attr)) else: return "active" def flowdetails(state, flow: http.HTTPFlow): text = [] sc = flow.server_conn cc = flow.client_conn req = flow.request resp = flow.response metadata = flow.metadata if metadata is not None and len(metadata) > 0: parts = [[str(k), repr(v)] for k, v in metadata.items()] text.append(urwid.Text([("head", "Metadata:")])) text.extend(common.format_keyvals(parts, key="key", val="text", indent=4)) if sc is not None: text.append(urwid.Text([("head", "Server Connection:")])) parts = [ ["Address", "{}:{}".format(sc.address[0], sc.address[1])], ["Resolved Address", "{}:{}".format(sc.ip_address[0], sc.ip_address[1])], ] if resp: parts.append(["HTTP Version", resp.http_version]) if sc.alpn_proto_negotiated: parts.append(["ALPN", sc.alpn_proto_negotiated]) text.extend( common.format_keyvals(parts, key="key", val="text", indent=4) ) c = sc.cert if c: text.append(urwid.Text([("head", "Server Certificate:")])) parts = [ ["Type", "%s, %s bits" % c.keyinfo], ["SHA1 digest", c.digest("sha1")], ["Valid to", str(c.notafter)], ["Valid from", str(c.notbefore)], ["Serial", str(c.serial)], [ "Subject", urwid.BoxAdapter( urwid.ListBox( common.format_keyvals( c.subject, key="highlight", val="text" ) ), len(c.subject) ) ], [ "Issuer", urwid.BoxAdapter( urwid.ListBox( common.format_keyvals( c.issuer, key="highlight", val="text" ) ), len(c.issuer) ) ] ] if c.altnames: parts.append( [ "Alt names", ", ".join(strutils.bytes_to_escaped_str(x) for x in c.altnames) ] ) text.extend( common.format_keyvals(parts, key="key", val="text", indent=4) ) if cc is not None: text.append(urwid.Text([("head", "Client Connection:")])) parts = [ ["Address", "{}:{}".format(cc.address[0], cc.address[1])], ] if req: parts.append(["HTTP Version", req.http_version]) if cc.tls_version: parts.append(["TLS Version", cc.tls_version]) if cc.sni: parts.append(["Server Name Indication", cc.sni]) if cc.cipher_name: parts.append(["Cipher Name", cc.cipher_name]) if cc.alpn_proto_negotiated: parts.append(["ALPN", cc.alpn_proto_negotiated]) text.extend( common.format_keyvals(parts, key="key", val="text", indent=4) ) parts = [] if cc is not None and cc.timestamp_start: parts.append( [ "Client conn. established", maybe_timestamp(cc, "timestamp_start") ] ) if cc.ssl_established: parts.append( [ "Client conn. TLS handshake", maybe_timestamp(cc, "timestamp_ssl_setup") ] ) if sc is not None and sc.timestamp_start: parts.append( [ "Server conn. initiated", maybe_timestamp(sc, "timestamp_start") ] ) parts.append( [ "Server conn. TCP handshake", maybe_timestamp(sc, "timestamp_tcp_setup") ] ) if sc.ssl_established: parts.append( [ "Server conn. TLS handshake", maybe_timestamp(sc, "timestamp_ssl_setup") ] ) if req is not None and req.timestamp_start: parts.append( [ "First request byte", maybe_timestamp(req, "timestamp_start") ] ) parts.append( [ "Request complete", maybe_timestamp(req, "timestamp_end") ] ) if resp is not None and resp.timestamp_start: parts.append( [ "First response byte", maybe_timestamp(resp, "timestamp_start") ] ) parts.append( [ "Response complete", maybe_timestamp(resp, "timestamp_end") ] ) if parts: # sort operations by timestamp parts = sorted(parts, key=lambda p: p[1]) text.append(urwid.Text([("head", "Timing:")])) text.extend(common.format_keyvals(parts, key="key", val="text", indent=4)) return searchable.Searchable(state, text)
1
13,126
Using `"{}".format(...)` is a bit beside the point...
mitmproxy-mitmproxy
py
@@ -149,8 +149,8 @@ class JsonFormatterTest(unittest.TestCase): def test_logger_name(self): JsonLogFormatter.init_from_settings({"project_name": "kintowe"}) f = JsonLogFormatter() - record = logging.LogRecord("app.log", logging.DEBUG, "", 0, "coucou", (), None) - result = f.format(record) + obj = logging.LogRecord("app.log", logging.DEBUG, "", 0, "coucou", (), None) + result = f.format(obj) logged = json.loads(result) self.assertEqual(logged["Logger"], "kintowe") self.assertEqual(logged["Type"], "app.log")
1
import json import logging import unittest from unittest import mock from pyramid import testing from kinto.core import DEFAULT_SETTINGS, initialization, JsonLogFormatter from .support import BaseWebTest class RequestSummaryTest(BaseWebTest, unittest.TestCase): def setUp(self): super().setUp() config = testing.setUp() config.registry.settings = DEFAULT_SETTINGS initialization.setup_logging(config) patch = mock.patch("kinto.core.initialization.summary_logger") self.mocked = patch.start() self.addCleanup(patch.stop) def logger_context(self): args, kwargs = self.mocked.info.call_args_list[-1] return kwargs["extra"] def test_standard_info_is_bound(self): headers = {"User-Agent": "Smith", **self.headers} self.app.get("/", headers=headers) event_dict = self.logger_context() self.assertEqual(event_dict["path"], "/v0/") self.assertEqual(event_dict["method"], "GET") self.assertEqual(event_dict["code"], 200) self.assertEqual(event_dict["agent"], "Smith") self.assertIsNotNone(event_dict["uid"]) self.assertIsNotNone(event_dict["time"]) self.assertIsNotNone(event_dict["t"]) self.assertEqual(event_dict["errno"], 0) self.assertNotIn("lang", event_dict) self.assertNotIn("headers", event_dict) self.assertNotIn("body", event_dict) def test_userid_is_none_when_anonymous(self): self.app.get("/") event_dict = self.logger_context() self.assertNotIn("uid", event_dict) def test_lang_is_not_none_when_provided(self): self.app.get("/", headers={"Accept-Language": "fr-FR"}) event_dict = self.logger_context() self.assertEqual(event_dict["lang"], "fr-FR") def test_agent_is_not_none_when_provided(self): self.app.get("/", headers={"User-Agent": "webtest/x.y.z"}) event_dict = self.logger_context() self.assertEqual(event_dict["agent"], "webtest/x.y.z") def test_errno_is_specified_on_error(self): self.app.get("/unknown", status=404) event_dict = self.logger_context() self.assertEqual(event_dict["errno"], 111) def test_basic_authn_type_is_bound(self): app = self.make_app({"multiauth.policies": "basicauth"}) app.get("/mushrooms", headers={"Authorization": "Basic bWF0OjE="}) event_dict = self.logger_context() self.assertEqual(event_dict["authn_type"], "basicauth") def test_headers_and_body_when_level_is_debug(self): self.mocked.level = logging.DEBUG body = b'{"boom": 1}' self.app.post("/batch", body, headers=self.headers, status=400) event_dict = self.logger_context() self.assertEqual( event_dict["headers"], { "Authorization": "Basic bWF0OnNlY3JldA==", "Content-Length": "11", "Content-Type": "application/json", "Host": "localhost:80", }, ) self.assertEqual(event_dict["body"], body) self.maxDiff = None responseBody = event_dict["response"]["body"] self.assertEqual(json.loads(responseBody.decode("utf-8"))["error"], "Invalid parameters") responseHeaders = event_dict["response"]["headers"] self.assertEqual( sorted(responseHeaders.keys()), [ "Access-Control-Expose-Headers", "Content-Length", "Content-Type", "X-Content-Type-Options", ], ) class BatchSubrequestTest(BaseWebTest, unittest.TestCase): def setUp(self): super().setUp() patch = mock.patch("kinto.core.views.batch.subrequest_logger") self.subrequest_mocked = patch.start() self.addCleanup(patch.stop) patch = mock.patch("kinto.core.initialization.summary_logger") self.summary_mocked = patch.start() self.addCleanup(patch.stop) headers = {**self.headers, "User-Agent": "readinglist"} body = { "requests": [ {"path": "/unknown", "headers": {"User-Agent": "foo"}}, {"path": "/unknown2"}, ] } self.app.post_json("/batch", body, headers=headers) def test_batch_global_request_is_preserved(self): args, kwargs = self.summary_mocked.info.call_args_list[-1] extra = kwargs["extra"] self.assertEqual(extra["code"], 200) self.assertEqual(extra["path"], "/v0/batch") self.assertEqual(extra["agent"], "readinglist") def test_batch_size_is_bound(self): args, kwargs = self.summary_mocked.info.call_args_list[-1] extra = kwargs["extra"] self.assertEqual(extra["batch_size"], 2) def test_subrequests_are_not_logged_as_request_summary(self): self.assertEqual(self.summary_mocked.info.call_count, 1) def test_subrequests_are_logged_as_subrequest_summary(self): self.assertEqual(self.subrequest_mocked.info.call_count, 2) args, kwargs = self.subrequest_mocked.info.call_args_list[-1] extra = kwargs["extra"] self.assertEqual(extra["path"], "/v0/unknown2") args, kwargs = self.subrequest_mocked.info.call_args_list[-2] extra = kwargs["extra"] self.assertEqual(extra["path"], "/v0/unknown") class JsonFormatterTest(unittest.TestCase): def test_logger_name(self): JsonLogFormatter.init_from_settings({"project_name": "kintowe"}) f = JsonLogFormatter() record = logging.LogRecord("app.log", logging.DEBUG, "", 0, "coucou", (), None) result = f.format(record) logged = json.loads(result) self.assertEqual(logged["Logger"], "kintowe") self.assertEqual(logged["Type"], "app.log") # See https://github.com/mozilla/mozilla-cloud-services-logger/issues/2 self.assertEqual(logged["Fields"]["msg"], "coucou")
1
12,009
I think these should remain as they are.
Kinto-kinto
py
@@ -14,6 +14,8 @@ module Beaker WINDOWS_PACKAGES = ['curl'] SLES_PACKAGES = ['curl', 'ntp'] DEBIAN_PACKAGES = ['curl', 'ntpdate', 'lsb-release'] + # Packages added at runtime + @@additional_pkgs = [] ETC_HOSTS_PATH = "/etc/hosts" ETC_HOSTS_PATH_SOLARIS = "/etc/inet/hosts" ROOT_KEYS_SCRIPT = "https://raw.githubusercontent.com/puppetlabs/puppetlabs-sshkeys/master/templates/scripts/manage_root_authorized_keys"
1
[ 'command', "dsl/patterns" ].each do |lib| require "beaker/#{lib}" end module Beaker #Provides convienience methods for commonly run actions on hosts module HostPrebuiltSteps include Beaker::DSL::Patterns NTPSERVER = 'pool.ntp.org' SLEEPWAIT = 5 TRIES = 5 UNIX_PACKAGES = ['curl', 'ntpdate'] WINDOWS_PACKAGES = ['curl'] SLES_PACKAGES = ['curl', 'ntp'] DEBIAN_PACKAGES = ['curl', 'ntpdate', 'lsb-release'] ETC_HOSTS_PATH = "/etc/hosts" ETC_HOSTS_PATH_SOLARIS = "/etc/inet/hosts" ROOT_KEYS_SCRIPT = "https://raw.githubusercontent.com/puppetlabs/puppetlabs-sshkeys/master/templates/scripts/manage_root_authorized_keys" ROOT_KEYS_SYNC_CMD = "curl -k -o - -L #{ROOT_KEYS_SCRIPT} | %s" APT_CFG = %q{ Acquire::http::Proxy "http://proxy.puppetlabs.net:3128/"; } IPS_PKG_REPO="http://solaris-11-internal-repo.delivery.puppetlabs.net" #Run timesync on the provided hosts # @param [Host, Array<Host>] host One or more hosts to act upon # @param [Hash{Symbol=>String}] opts Options to alter execution. # @option opts [Beaker::Logger] :logger A {Beaker::Logger} object def timesync host, opts logger = opts[:logger] block_on host do |host| logger.notify "Update system time sync for '#{host.name}'" if host['platform'].include? 'windows' # The exit code of 5 is for Windows 2008 systems where the w32tm /register command # is not actually necessary. host.exec(Command.new("w32tm /register"), :acceptable_exit_codes => [0,5]) host.exec(Command.new("net start w32time"), :acceptable_exit_codes => [0,2]) host.exec(Command.new("w32tm /config /manualpeerlist:#{NTPSERVER} /syncfromflags:manual /update")) host.exec(Command.new("w32tm /resync")) logger.notify "NTP date succeeded on #{host}" else case when host['platform'] =~ /solaris-10/ ntp_command = "sleep 10 && ntpdate -w #{NTPSERVER}" when host['platform'] =~ /sles-/ ntp_command = "sntp #{NTPSERVER}" else ntp_command = "ntpdate -t 20 #{NTPSERVER}" end success=false try = 0 until try >= TRIES do try += 1 if host.exec(Command.new(ntp_command), :acceptable_exit_codes => (0..255)).exit_code == 0 success=true break end sleep SLEEPWAIT end if success logger.notify "NTP date succeeded on #{host} after #{try} tries" else raise "NTP date was not successful after #{try} tries" end end end rescue => e report_and_raise(logger, e, "timesync (--ntp)") end #Validate that hosts are prepared to be used as SUTs, if packages are missing attempt to #install them. Verifies the presence of #{HostPrebuiltSteps::UNIX_PACKAGES} on unix platform hosts, #{HostPrebuiltSteps::SLES_PACKAGES} on SUSE platform hosts, #{HostPrebuiltSteps::DEBIAN_PACKAGES on debian platform #hosts and {HostPrebuiltSteps::WINDOWS_PACKAGES} on windows #platforms. # @param [Host, Array<Host>, String, Symbol] host One or more hosts to act upon # @param [Hash{Symbol=>String}] opts Options to alter execution. # @option opts [Beaker::Logger] :logger A {Beaker::Logger} object def validate_host host, opts logger = opts[:logger] if opts[:collect_perf_data] UNIX_PACKAGES << "sysstat" if !UNIX_PACKAGES.include? "sysstat" SLES_PACKAGES << "sysstat" if !SLES_PACKAGES.include? "sysstat" end block_on host do |host| case when host['platform'] =~ /sles-/ SLES_PACKAGES.each do |pkg| if not host.check_for_package pkg host.install_package pkg end end when host['platform'] =~ /debian/ DEBIAN_PACKAGES.each do |pkg| if not host.check_for_package pkg host.install_package pkg end end when host['platform'] =~ /windows/ WINDOWS_PACKAGES.each do |pkg| if not host.check_for_package pkg host.install_package pkg end end when host['platform'] !~ /debian|aix|solaris|windows|sles-|osx-/ UNIX_PACKAGES.each do |pkg| if not host.check_for_package pkg host.install_package pkg end end end end rescue => e report_and_raise(logger, e, "validate") end #Install a set of authorized keys using {HostPrebuiltSteps::ROOT_KEYS_SCRIPT}. This is a #convenience method to allow for easy login to hosts after they have been provisioned with #Beaker. # @param [Host, Array<Host>] host One or more hosts to act upon # @param [Hash{Symbol=>String}] opts Options to alter execution. # @option opts [Beaker::Logger] :logger A {Beaker::Logger} object def sync_root_keys host, opts # JJM This step runs on every system under test right now. We're anticipating # issues on Windows and maybe Solaris. We will likely need to filter this step # but we're deliberately taking the approach of "assume it will work, fix it # when reality dictates otherwise" logger = opts[:logger] block_on host do |host| logger.notify "Sync root authorized_keys from github on #{host.name}" # Allow all exit code, as this operation is unlikely to cause problems if it fails. if host['platform'].include? 'solaris' host.exec(Command.new(ROOT_KEYS_SYNC_CMD % "bash"), :acceptable_exit_codes => (0..255)) else host.exec(Command.new(ROOT_KEYS_SYNC_CMD % "env PATH=/usr/gnu/bin:$PATH bash"), :acceptable_exit_codes => (0..255)) end end rescue => e report_and_raise(logger, e, "sync_root_keys") end #Determine the Extra Packages for Enterprise Linux URL for the provided Enterprise Linux host. # @param [Host] host One host to act upon # @return [String] The URL for EPL for the provided host # @raise [Exception] Raises an error if the host provided's platform != /el-(5|6)/ def epel_info_for! host version = host['platform'].match(/el-(\d+)/) if not version raise "epel_info_for! not available for #{host.name} on platform #{host['platform']}" end version = version[1] if version == '6' pkg = 'epel-release-6-8.noarch.rpm' url = "http://mirror.itc.virginia.edu/fedora-epel/6/i386/#{pkg}" elsif version == '5' pkg = 'epel-release-5-4.noarch.rpm' url = "http://archive.linux.duke.edu/pub/epel/5/i386/#{pkg}" else raise "epel_info_for! does not support el version #{version}, on #{host.name}" end return url end #Run 'apt-get update' on the provided host or hosts. If the platform of the provided host is not #ubuntu or debian do nothing. # @param [Host, Array<Host>] hosts One or more hosts to act upon def apt_get_update hosts block_on hosts do |host| if host[:platform] =~ /(ubuntu)|(debian)/ host.exec(Command.new("apt-get update")) end end end #Create a file on host or hosts at the provided file path with the provided file contents. # @param [Host, Array<Host>] host One or more hosts to act upon # @param [String] file_path The path at which the new file will be created on the host or hosts. # @param [String] file_content The contents of the file to be created on the host or hosts. def copy_file_to_remote(host, file_path, file_content) block_on host do |host| Tempfile.open 'beaker' do |tempfile| File.open(tempfile.path, 'w') {|file| file.puts file_content } host.do_scp_to(tempfile.path, file_path, @options) end end end #Alter apt configuration on ubuntu and debian host or hosts to internal Puppet Labs # proxy {HostPrebuiltSteps::APT_CFG} proxy, alter pkg on solaris-11 host or hosts # to point to interal Puppetlabs proxy {HostPrebuiltSteps::IPS_PKG_REPO}. Do nothing # on non-ubuntu, debian or solaris-11 platform host or hosts. # @param [Host, Array<Host>] host One or more hosts to act upon # @param [Hash{Symbol=>String}] opts Options to alter execution. # @option opts [Beaker::Logger] :logger A {Beaker::Logger} object def proxy_config( host, opts ) # repo_proxy # supports ubuntu, debian and solaris platforms logger = opts[:logger] block_on host do |host| case when host['platform'] =~ /ubuntu/ host.exec(Command.new("if test -f /etc/apt/apt.conf; then mv /etc/apt/apt.conf /etc/apt/apt.conf.bk; fi")) copy_file_to_remote(host, '/etc/apt/apt.conf', APT_CFG) apt_get_update(host) when host['platform'] =~ /debian/ host.exec(Command.new("if test -f /etc/apt/apt.conf; then mv /etc/apt/apt.conf /etc/apt/apt.conf.bk; fi")) copy_file_to_remote(host, '/etc/apt/apt.conf', APT_CFG) apt_get_update(host) when host['platform'] =~ /solaris-11/ host.exec(Command.new("/usr/bin/pkg unset-publisher solaris || :")) host.exec(Command.new("/usr/bin/pkg set-publisher -g %s solaris" % IPS_PKG_REPO)) else logger.debug "#{host}: repo proxy configuration not modified" end end rescue => e report_and_raise(logger, e, "proxy_config") end #Install EPEL on host or hosts with platform = /el-(5|6)/. Do nothing on host or hosts of other platforms. # @param [Host, Array<Host>] host One or more hosts to act upon # @param [Hash{Symbol=>String}] opts Options to alter execution. # @option opts [Boolean] :debug If true, print verbose rpm information when installing EPEL # @option opts [Beaker::Logger] :logger A {Beaker::Logger} object def add_el_extras( host, opts ) #add_el_extras #only supports el-* platforms logger = opts[:logger] debug_opt = opts[:debug] ? 'vh' : '' block_on host do |host| case when host['platform'] =~ /el-(5|6)/ result = host.exec(Command.new('rpm -qa | grep epel-release'), :acceptable_exit_codes => [0,1]) if result.exit_code == 1 url = epel_info_for! host host.exec(Command.new("rpm -i#{debug_opt} #{url}")) host.exec(Command.new('yum clean all && yum makecache')) end else logger.debug "#{host}: package repo configuration not modified" end end rescue => e report_and_raise(logger, e, "add_repos") end #Determine the domain name of the provided host from its /etc/resolv.conf # @param [Host] host the host to act upon def get_domain_name(host) domain = nil search = nil resolv_conf = host.exec(Command.new("cat /etc/resolv.conf")).stdout resolv_conf.each_line { |line| if line =~ /^\s*domain\s+(\S+)/ domain = $1 elsif line =~ /^\s*search\s+(\S+)/ search = $1 end } return domain if domain return search if search end #Determine the ip address of the provided host # @param [Host] host the host to act upon # @deprecated use {Host#get_ip} def get_ip(host) host.get_ip end #Append the provided string to the /etc/hosts file of the provided host # @param [Host] host the host to act upon # @param [String] etc_hosts The string to append to the /etc/hosts file def set_etc_hosts(host, etc_hosts) host.exec(Command.new("echo '#{etc_hosts}' > /etc/hosts")) end #Make it possible to log in as root by copying the current users ssh keys to the root account # @param [Host, Array<Host>] host One or more hosts to act upon # @param [Hash{Symbol=>String}] opts Options to alter execution. # @option opts [Beaker::Logger] :logger A {Beaker::Logger} object def copy_ssh_to_root host, opts logger = opts[:logger] block_on host do |host| logger.debug "Give root a copy of current user's keys, on #{host.name}" if host['platform'] =~ /windows/ host.exec(Command.new('cp -r .ssh /cygdrive/c/Users/Administrator/.')) host.exec(Command.new('chown -R Administrator /cygdrive/c/Users/Administrator/.ssh')) else host.exec(Command.new('sudo su -c "cp -r .ssh /root/."'), {:pty => true}) end end end #Update /etc/hosts to make it possible for each provided host to reach each other host by name. #Assumes that each provided host has host[:ip] set. # @param [Host, Array<Host>] hosts An array of hosts to act upon # @param [Hash{Symbol=>String}] opts Options to alter execution. # @option opts [Beaker::Logger] :logger A {Beaker::Logger} object def hack_etc_hosts hosts, opts etc_hosts = "127.0.0.1\tlocalhost localhost.localdomain\n" hosts.each do |host| etc_hosts += "#{host['ip'].to_s}\t#{host[:vmhostname] || host.name}\n" end hosts.each do |host| set_etc_hosts(host, etc_hosts) end end #Update sshd_config on debian, ubuntu, centos, el, redhat and fedora boxes to allow for root login, does nothing on other platfoms # @param [Host, Array<Host>] host One or more hosts to act upon # @param [Hash{Symbol=>String}] opts Options to alter execution. # @option opts [Beaker::Logger] :logger A {Beaker::Logger} object def enable_root_login host, opts logger = opts[:logger] block_on host do |host| logger.debug "Update /etc/ssh/sshd_config to allow root login" host.exec(Command.new("sudo su -c \"sed -i 's/PermitRootLogin no/PermitRootLogin yes/' /etc/ssh/sshd_config\""), {:pty => true} ) #restart sshd if host['platform'] =~ /debian|ubuntu/ host.exec(Command.new("sudo su -c \"service ssh restart\""), {:pty => true}) elsif host['platform'] =~ /centos|el-|redhat|fedora/ host.exec(Command.new("sudo su -c \"service sshd restart\""), {:pty => true}) else @logger.warn("Attempting to update ssh on non-supported platform: #{host.name}: #{host['platform']}") end end end #Disable SELinux on centos, does nothing on other platforms # @param [Host, Array<Host>] host One or more hosts to act upon # @param [Hash{Symbol=>String}] opts Options to alter execution. # @option opts [Beaker::Logger] :logger A {Beaker::Logger} object def disable_se_linux host, opts logger = opts[:logger] block_on host do |host| if host['platform'] =~ /centos|el-|redhat|fedora/ @logger.debug("Disabling se_linux on #{host.name}") host.exec(Command.new("sudo su -c \"setenforce 0\""), {:pty => true}) else @logger.warn("Attempting to disable SELinux on non-supported platform: #{host.name}: #{host['platform']}") end end end #Disable iptables on centos, does nothing on other platforms # @param [Host, Array<Host>] host One or more hosts to act upon # @param [Hash{Symbol=>String}] opts Options to alter execution. # @option opts [Beaker::Logger] :logger A {Beaker::Logger} object def disable_iptables host, opts logger = opts[:logger] block_on host do |host| if host['platform'] =~ /centos|el-|redhat|fedora/ logger.debug("Disabling iptables on #{host.name}") host.exec(Command.new("sudo su -c \"/etc/init.d/iptables stop\""), {:pty => true}) else logger.warn("Attempting to disable iptables on non-supported platform: #{host.name}: #{host['platform']}") end end end # Setup files for enabling requests to pass to a proxy server # This works for the APT package manager on debian and ubuntu # and YUM package manager on el, centos, fedora and redhat. # @param [Host, Array<Host>, String, Symbol] host One or more hosts to act upon # @param [Hash{Symbol=>String}] opts Options to alter execution. # @option opts [Beaker::Logger] :logger A {Beaker::Logger} object def package_proxy host, opts logger = opts[:logger] block_on host do |host| logger.debug("enabling proxy support on #{host.name}") case host['platform'] when /ubuntu/, /debian/ host.exec(Command.new("echo 'Acquire::http::Proxy \"#{opts[:package_proxy]}/\";' >> /etc/apt/apt.conf.d/10proxy")) when /^el-/, /centos/, /fedora/, /redhat/ host.exec(Command.new("echo 'proxy=#{opts[:package_proxy]}/' >> /etc/yum.conf")) else logger.debug("Attempting to enable package manager proxy support on non-supported platform: #{host.name}: #{host['platform']}") end end end end end
1
7,208
Let's just call this PERF_PACKAGES and have them in the same format as WINDOWS/SLES/DEBIAN_PACKAGES constants - since it is only a single package and, as written, you'd have to update the code to add more package names anyway. Might as well be consistent with the rest of the code.
voxpupuli-beaker
rb
@@ -224,6 +224,18 @@ String getTaskValueName(taskIndex_t TaskIndex, uint8_t TaskValueIndex) { return ExtraTaskSettings.TaskDeviceValueNames[TaskValueIndex]; } +/********************************************************************************************* + * get the taskPluginID with required checks, INVALID_PLUGIN_ID when invalid + ********************************************************************************************/ +pluginID_t getTaskDevicePluginID(taskIndex_t TaskIndex) { + if (validTaskIndex(TaskIndex)) { + const deviceIndex_t DeviceIndex = getDeviceIndex_from_TaskIndex(TaskIndex); + + return (validDeviceIndex(DeviceIndex) ? Device[DeviceIndex].Number : INVALID_PLUGIN_ID); + } + return INVALID_PLUGIN_ID; +} + /********************************************************************************************\ If RX and TX tied together, perform emergency reset to get the system out of boot loops \*********************************************************************************************/
1
#include "../Helpers/Misc.h" #include "../../ESPEasy-Globals.h" #include "../../ESPEasy_common.h" #include "../../_Plugin_Helper.h" #include "../ESPEasyCore/ESPEasy_backgroundtasks.h" #include "../ESPEasyCore/Serial.h" #include "../Globals/ESPEasy_time.h" #include "../Globals/Statistics.h" #include "../Helpers/ESPEasy_FactoryDefault.h" #include "../Helpers/ESPEasy_Storage.h" #include "../Helpers/Numerical.h" #include "../Helpers/PeriodicalActions.h" #include "../Helpers/StringConverter.h" #include "../Helpers/StringParser.h" bool remoteConfig(struct EventStruct *event, const String& string) { // FIXME TD-er: Why have an event here as argument? It is not used. #ifndef BUILD_NO_RAM_TRACKER checkRAM(F("remoteConfig")); #endif bool success = false; String command = parseString(string, 1); if (command == F("config")) { success = true; if (parseString(string, 2) == F("task")) { String configTaskName = parseStringKeepCase(string, 3); // FIXME TD-er: This command is not using the tolerance setting // tolerantParseStringKeepCase(Line, 4); String configCommand = parseStringToEndKeepCase(string, 4); if ((configTaskName.isEmpty()) || (configCommand.isEmpty())) { return success; // TD-er: Should this be return false? } taskIndex_t index = findTaskIndexByName(configTaskName); if (validTaskIndex(index)) { event->setTaskIndex(index); success = PluginCall(PLUGIN_SET_CONFIG, event, configCommand); } } } return success; } /********************************************************************************************\ delay in milliseconds with background processing \*********************************************************************************************/ void delayBackground(unsigned long dsdelay) { unsigned long timer = millis() + dsdelay; while (!timeOutReached(timer)) { backgroundtasks(); } } /********************************************************************************************\ Toggle controller enabled state \*********************************************************************************************/ bool setControllerEnableStatus(controllerIndex_t controllerIndex, bool enabled) { if (!validControllerIndex(controllerIndex)) { return false; } #ifndef BUILD_NO_RAM_TRACKER checkRAM(F("setControllerEnableStatus")); #endif // Only enable controller if it has a protocol configured if ((Settings.Protocol[controllerIndex] != 0) || !enabled) { Settings.ControllerEnabled[controllerIndex] = enabled; return true; } return false; } /********************************************************************************************\ Toggle task enabled state \*********************************************************************************************/ bool setTaskEnableStatus(struct EventStruct *event, bool enabled) { if (!validTaskIndex(event->TaskIndex)) { return false; } #ifndef BUILD_NO_RAM_TRACKER checkRAM(F("setTaskEnableStatus")); #endif // Only enable task if it has a Plugin configured if (validPluginID(Settings.TaskDeviceNumber[event->TaskIndex]) || !enabled) { String dummy; if (!enabled) { PluginCall(PLUGIN_EXIT, event, dummy); } Settings.TaskDeviceEnabled[event->TaskIndex] = enabled; if (enabled) { if (!PluginCall(PLUGIN_INIT, event, dummy)) { return false; } // Schedule the task to be executed almost immediately Scheduler.schedule_task_device_timer(event->TaskIndex, millis() + 10); } return true; } return false; } /********************************************************************************************\ Clear task settings for given task \*********************************************************************************************/ void taskClear(taskIndex_t taskIndex, bool save) { if (!validTaskIndex(taskIndex)) { return; } #ifndef BUILD_NO_RAM_TRACKER checkRAM(F("taskClear")); #endif Settings.clearTask(taskIndex); ExtraTaskSettings.clear(); // Invalidate any cached values. ExtraTaskSettings.TaskIndex = taskIndex; if (save) { SaveTaskSettings(taskIndex); SaveSettings(); } } /********************************************************************************************\ check the program memory hash The const MD5_MD5_MD5_MD5_BoundariesOfTheSegmentsGoHere... needs to remain unchanged as it will be replaced by - 16 bytes md5 hash, followed by - 4 * uint32_t start of memory segment 1-4 - 4 * uint32_t end of memory segment 1-4 currently there are only two segemts included in the hash. Unused segments have start adress 0. Execution time 520kb @80Mhz: 236ms Returns: 0 if hash compare fails, number of checked bytes otherwise. The reference hash is calculated by a .py file and injected into the binary. Caution: currently the hash sits in an unchecked segment. If it ever moves to a checked segment, make sure it is excluded from the calculation ! \*********************************************************************************************/ #if defined(ARDUINO_ESP8266_RELEASE_2_3_0) void dump(uint32_t addr) { // Seems already included in core 2.4 ... serialPrint(String(addr, HEX)); serialPrint(": "); for (uint32_t a = addr; a < addr + 16; a++) { serialPrint(String(pgm_read_byte(a), HEX)); serialPrint(" "); } serialPrintln(""); } #endif // if defined(ARDUINO_ESP8266_RELEASE_2_3_0) /* uint32_t progMemMD5check(){ checkRAM(F("progMemMD5check")); #define BufSize 10 uint32_t calcBuffer[BufSize]; CRCValues.numberOfCRCBytes = 0; memcpy (calcBuffer,CRCValues.compileTimeMD5,16); // is there still the dummy in memory ? - the dummy needs to be replaced by the real md5 after linking. if( memcmp (calcBuffer, "MD5_MD5_MD5_",12)==0){ // do not memcmp with CRCdummy directly or it will get optimized away. addLog(LOG_LEVEL_INFO, F("CRC : No program memory checksum found. Check output of crc2.py")); return 0; } MD5Builder md5; md5.begin(); for (int l = 0; l<4; l++){ // check max segments, if the pointer is not 0 uint32_t *ptrStart = (uint32_t *)&CRCValues.compileTimeMD5[16+l*4]; uint32_t *ptrEnd = (uint32_t *)&CRCValues.compileTimeMD5[16+4*4+l*4]; if ((*ptrStart) == 0) break; // segment not used. for (uint32_t i = *ptrStart; i< (*ptrEnd) ; i=i+sizeof(calcBuffer)){ // "<" includes last byte for (int buf = 0; buf < BufSize; buf ++){ calcBuffer[buf] = pgm_read_dword((uint32_t*)i+buf); // read 4 bytes CRCValues.numberOfCRCBytes+=sizeof(calcBuffer[0]); } md5.add((uint8_t *)&calcBuffer[0],(*ptrEnd-i)<sizeof(calcBuffer) ? (*ptrEnd-i):sizeof(calcBuffer) ); // add buffer to md5. At the end not the whole buffer. md5 ptr to data in ram. } } md5.calculate(); md5.getBytes(CRCValues.runTimeMD5); if ( CRCValues.checkPassed()) { addLog(LOG_LEVEL_INFO, F("CRC : program checksum ...OK")); return CRCValues.numberOfCRCBytes; } addLog(LOG_LEVEL_INFO, F("CRC : program checksum ...FAIL")); return 0; } */ /********************************************************************************************\ Handler for keeping ExtraTaskSettings up to date using cache \*********************************************************************************************/ String getTaskDeviceName(taskIndex_t TaskIndex) { LoadTaskSettings(TaskIndex); return ExtraTaskSettings.TaskDeviceName; } /********************************************************************************************\ Handler for getting Value Names from TaskIndex - value names can be accessed with task variable index - maximum number of variables <= defined number of variables in plugin \*********************************************************************************************/ String getTaskValueName(taskIndex_t TaskIndex, uint8_t TaskValueIndex) { TaskValueIndex = (TaskValueIndex < getValueCountForTask(TaskIndex) ? TaskValueIndex : getValueCountForTask(TaskIndex)); LoadTaskSettings(TaskIndex); return ExtraTaskSettings.TaskDeviceValueNames[TaskValueIndex]; } /********************************************************************************************\ If RX and TX tied together, perform emergency reset to get the system out of boot loops \*********************************************************************************************/ void emergencyReset() { // Direct Serial is allowed here, since this is only an emergency task. Serial.begin(115200); Serial.write(0xAA); Serial.write(0x55); delay(1); if (Serial.available() == 2) { if ((Serial.read() == 0xAA) && (Serial.read() == 0x55)) { serialPrintln(F("\n\n\rSystem will reset to factory defaults in 10 seconds...")); delay(10000); ResetFactory(); } } } /********************************************************************************************\ Delayed reboot, in case of issues, do not reboot with high frequency as it might not help... \*********************************************************************************************/ void delayedReboot(int rebootDelay, ESPEasy_Scheduler::IntendedRebootReason_e reason) { // Direct Serial is allowed here, since this is only an emergency task. while (rebootDelay != 0) { serialPrint(F("Delayed Reset ")); serialPrintln(String(rebootDelay)); rebootDelay--; delay(1000); } reboot(reason); } void reboot(ESPEasy_Scheduler::IntendedRebootReason_e reason) { prepareShutdown(reason); #if defined(ESP32) ESP.restart(); #else // if defined(ESP32) ESP.reset(); #endif // if defined(ESP32) } void FeedSW_watchdog() { #ifdef ESP8266 ESP.wdtFeed(); #endif } void SendValueLogger(taskIndex_t TaskIndex) { #if !defined(BUILD_NO_DEBUG) || defined(FEATURE_SD) bool featureSD = false; String logger; # ifdef FEATURE_SD featureSD = true; # endif // ifdef FEATURE_SD if (featureSD || loglevelActiveFor(LOG_LEVEL_DEBUG)) { const deviceIndex_t DeviceIndex = getDeviceIndex_from_TaskIndex(TaskIndex); if (validDeviceIndex(DeviceIndex)) { LoadTaskSettings(TaskIndex); const uint8_t valueCount = getValueCountForTask(TaskIndex); for (uint8_t varNr = 0; varNr < valueCount; varNr++) { logger += node_time.getDateString('-'); logger += ' '; logger += node_time.getTimeString(':'); logger += ','; logger += Settings.Unit; logger += ','; logger += getTaskDeviceName(TaskIndex); logger += ','; logger += ExtraTaskSettings.TaskDeviceValueNames[varNr]; logger += ','; logger += formatUserVarNoCheck(TaskIndex, varNr); logger += "\r\n"; } addLog(LOG_LEVEL_DEBUG, logger); } } #endif // if !defined(BUILD_NO_DEBUG) || defined(FEATURE_SD) #ifdef FEATURE_SD String filename = F("VALUES.CSV"); File logFile = SD.open(filename, FILE_WRITE); if (logFile) { logFile.print(logger); } logFile.close(); #endif // ifdef FEATURE_SD } // ####################################################################################################### // ############################ quite acurate but slow color converter#################################### // ####################################################################################################### // uses H 0..360 S 1..100 I/V 1..100 (according to homie convention) // Source https://blog.saikoled.com/post/44677718712/how-to-convert-from-hsi-to-rgb-white void HSV2RGB(float H, float S, float I, int rgb[3]) { int r, g, b; H = fmod(H, 360); // cycle H around to 0-360 degrees H = 3.14159f * H / (float)180; // Convert to radians. S = S / 100; S = S > 0 ? (S < 1 ? S : 1) : 0; // clamp S and I to interval [0,1] I = I / 100; I = I > 0 ? (I < 1 ? I : 1) : 0; // Math! Thanks in part to Kyle Miller. if (H < 2.09439f) { r = 255 * I / 3 * (1 + S * cos(H) / cos(1.047196667f - H)); g = 255 * I / 3 * (1 + S * (1 - cos(H) / cos(1.047196667f - H))); b = 255 * I / 3 * (1 - S); } else if (H < 4.188787f) { H = H - 2.09439f; g = 255 * I / 3 * (1 + S * cos(H) / cos(1.047196667f - H)); b = 255 * I / 3 * (1 + S * (1 - cos(H) / cos(1.047196667f - H))); r = 255 * I / 3 * (1 - S); } else { H = H - 4.188787f; b = 255 * I / 3 * (1 + S * cos(H) / cos(1.047196667f - H)); r = 255 * I / 3 * (1 + S * (1 - cos(H) / cos(1.047196667f - H))); g = 255 * I / 3 * (1 - S); } rgb[0] = r; rgb[1] = g; rgb[2] = b; } // uses H 0..360 S 1..100 I/V 1..100 (according to homie convention) // Source https://blog.saikoled.com/post/44677718712/how-to-convert-from-hsi-to-rgb-white void HSV2RGBW(float H, float S, float I, int rgbw[4]) { int r, g, b, w; float cos_h, cos_1047_h; H = fmod(H, 360); // cycle H around to 0-360 degrees H = 3.14159f * H / (float)180; // Convert to radians. S = S / 100; S = S > 0 ? (S < 1 ? S : 1) : 0; // clamp S and I to interval [0,1] I = I / 100; I = I > 0 ? (I < 1 ? I : 1) : 0; if (H < 2.09439f) { cos_h = cos(H); cos_1047_h = cos(1.047196667f - H); r = S * 255 * I / 3 * (1 + cos_h / cos_1047_h); g = S * 255 * I / 3 * (1 + (1 - cos_h / cos_1047_h)); b = 0; w = 255 * (1 - S) * I; } else if (H < 4.188787f) { H = H - 2.09439f; cos_h = cos(H); cos_1047_h = cos(1.047196667f - H); g = S * 255 * I / 3 * (1 + cos_h / cos_1047_h); b = S * 255 * I / 3 * (1 + (1 - cos_h / cos_1047_h)); r = 0; w = 255 * (1 - S) * I; } else { H = H - 4.188787f; cos_h = cos(H); cos_1047_h = cos(1.047196667f - H); b = S * 255 * I / 3 * (1 + cos_h / cos_1047_h); r = S * 255 * I / 3 * (1 + (1 - cos_h / cos_1047_h)); g = 0; w = 255 * (1 - S) * I; } rgbw[0] = r; rgbw[1] = g; rgbw[2] = b; rgbw[3] = w; } // Simple bitwise get/set functions uint8_t get8BitFromUL(uint32_t number, uint8_t bitnr) { return (number >> bitnr) & 0xFF; } void set8BitToUL(uint32_t& number, uint8_t bitnr, uint8_t value) { uint32_t mask = (0xFFUL << bitnr); uint32_t newvalue = ((value << bitnr) & mask); number = (number & ~mask) | newvalue; } uint8_t get4BitFromUL(uint32_t number, uint8_t bitnr) { return (number >> bitnr) & 0x0F; } void set4BitToUL(uint32_t& number, uint8_t bitnr, uint8_t value) { uint32_t mask = (0x0FUL << bitnr); uint32_t newvalue = ((value << bitnr) & mask); number = (number & ~mask) | newvalue; } float getCPUload() { return 100.0f - Scheduler.getIdleTimePct(); } int getLoopCountPerSec() { return loopCounterLast / 30; } int getUptimeMinutes() { return wdcounter / 2; } #ifndef BUILD_NO_RAM_TRACKER void logMemUsageAfter(const __FlashStringHelper * function, int value) { // Store free memory in an int, as subtracting may sometimes result in negative value. // The recorded used memory is not an exact value, as background (or interrupt) tasks may also allocate or free heap memory. static int last_freemem = ESP.getFreeHeap(); const int freemem_end = ESP.getFreeHeap(); if (loglevelActiveFor(LOG_LEVEL_DEBUG)) { String log; log.reserve(128); log = F("After "); log += function; if (value >= 0) { log += value; } while (log.length() < 30) log += ' '; log += F("Free mem after: "); log += freemem_end; while (log.length() < 55) log += ' '; log += F("diff: "); log += last_freemem - freemem_end; addLog(LOG_LEVEL_DEBUG, log); } last_freemem = freemem_end; } #endif
1
22,431
We don't have a `getPluginIDfromTaskIndex` function? I think it should be implemented in Globals/Plugins.h / .cpp
letscontrolit-ESPEasy
cpp
@@ -910,8 +910,12 @@ public class QueryComponent extends SearchComponent additionalAdded = addFL(additionalFL, "score", additionalAdded); } } else { - // reset so that only unique key is requested in shard requests - sreq.params.set(CommonParams.FL, rb.req.getSchema().getUniqueKeyField().getName()); + if (rb.req.getSearcher().enableLazyFieldLoading) { + // reset so that only unique key is requested in shard requests + sreq.params.set(CommonParams.FL, rb.req.getSchema().getUniqueKeyField().getName()); + } else { + sreq.params.set(CommonParams.FL, "*"); + } if (shardQueryIncludeScore) { additionalAdded = addFL(additionalFL, "score", additionalAdded); }
1
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.solr.handler.component; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.invoke.MethodHandles; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import org.apache.lucene.index.IndexReaderContext; import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.index.ReaderUtil; import org.apache.lucene.index.Term; import org.apache.lucene.search.DocIdSetIterator; import org.apache.lucene.search.FieldComparator; import org.apache.lucene.search.LeafFieldComparator; import org.apache.lucene.search.MatchNoDocsQuery; import org.apache.lucene.search.Query; import org.apache.lucene.search.Scorer; import org.apache.lucene.search.Sort; import org.apache.lucene.search.SortField; import org.apache.lucene.search.Weight; import org.apache.lucene.search.grouping.GroupDocs; import org.apache.lucene.search.grouping.SearchGroup; import org.apache.lucene.search.grouping.TopGroups; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.InPlaceMergeSorter; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; import org.apache.solr.common.SolrException; import org.apache.solr.common.params.CommonParams; import org.apache.solr.common.params.CursorMarkParams; import org.apache.solr.common.params.GroupParams; import org.apache.solr.common.params.ModifiableSolrParams; import org.apache.solr.common.params.ShardParams; import org.apache.solr.common.params.SolrParams; import org.apache.solr.common.util.NamedList; import org.apache.solr.common.util.SimpleOrderedMap; import org.apache.solr.common.util.StrUtils; import org.apache.solr.request.SolrQueryRequest; import org.apache.solr.response.BasicResultContext; import org.apache.solr.response.ResultContext; import org.apache.solr.response.SolrQueryResponse; import org.apache.solr.schema.FieldType; import org.apache.solr.schema.IndexSchema; import org.apache.solr.schema.SchemaField; import org.apache.solr.search.CursorMark; import org.apache.solr.search.DocIterator; import org.apache.solr.search.DocList; import org.apache.solr.search.DocListAndSet; import org.apache.solr.search.DocSlice; import org.apache.solr.search.Grouping; import org.apache.solr.search.QParser; import org.apache.solr.search.QParserPlugin; import org.apache.solr.search.QueryCommand; import org.apache.solr.search.QueryParsing; import org.apache.solr.search.QueryResult; import org.apache.solr.search.RankQuery; import org.apache.solr.search.ReturnFields; import org.apache.solr.search.SolrIndexSearcher; import org.apache.solr.search.SolrReturnFields; import org.apache.solr.search.SortSpec; import org.apache.solr.search.SortSpecParsing; import org.apache.solr.search.SyntaxError; import org.apache.solr.search.grouping.CommandHandler; import org.apache.solr.search.grouping.GroupingSpecification; import org.apache.solr.search.grouping.distributed.ShardRequestFactory; import org.apache.solr.search.grouping.distributed.ShardResponseProcessor; import org.apache.solr.search.grouping.distributed.command.QueryCommand.Builder; import org.apache.solr.search.grouping.distributed.command.SearchGroupsFieldCommand; import org.apache.solr.search.grouping.distributed.command.TopGroupsFieldCommand; import org.apache.solr.search.grouping.distributed.requestfactory.SearchGroupsRequestFactory; import org.apache.solr.search.grouping.distributed.requestfactory.StoredFieldsShardRequestFactory; import org.apache.solr.search.grouping.distributed.requestfactory.TopGroupsShardRequestFactory; import org.apache.solr.search.grouping.distributed.responseprocessor.SearchGroupShardResponseProcessor; import org.apache.solr.search.grouping.distributed.responseprocessor.StoredFieldsShardResponseProcessor; import org.apache.solr.search.grouping.distributed.responseprocessor.TopGroupsShardResponseProcessor; import org.apache.solr.search.grouping.distributed.shardresultserializer.SearchGroupsResultTransformer; import org.apache.solr.search.grouping.distributed.shardresultserializer.TopGroupsResultTransformer; import org.apache.solr.search.grouping.endresulttransformer.EndResultTransformer; import org.apache.solr.search.grouping.endresulttransformer.GroupedEndResultTransformer; import org.apache.solr.search.grouping.endresulttransformer.MainEndResultTransformer; import org.apache.solr.search.grouping.endresulttransformer.SimpleEndResultTransformer; import org.apache.solr.search.stats.StatsCache; import org.apache.solr.util.SolrPluginUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * TODO! * * * @since solr 1.3 */ public class QueryComponent extends SearchComponent { public static final String COMPONENT_NAME = "query"; private static final Logger LOG = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); @Override public void prepare(ResponseBuilder rb) throws IOException { SolrQueryRequest req = rb.req; SolrParams params = req.getParams(); if (!params.getBool(COMPONENT_NAME, true)) { return; } SolrQueryResponse rsp = rb.rsp; // Set field flags ReturnFields returnFields = new SolrReturnFields( req ); rsp.setReturnFields( returnFields ); int flags = 0; if (returnFields.wantsScore()) { flags |= SolrIndexSearcher.GET_SCORES; } rb.setFieldFlags( flags ); String defType = params.get(QueryParsing.DEFTYPE, QParserPlugin.DEFAULT_QTYPE); // get it from the response builder to give a different component a chance // to set it. String queryString = rb.getQueryString(); if (queryString == null) { // this is the normal way it's set. queryString = params.get( CommonParams.Q ); rb.setQueryString(queryString); } try { QParser parser = QParser.getParser(rb.getQueryString(), defType, req); Query q = parser.getQuery(); if (q == null) { // normalize a null query to a query that matches nothing q = new MatchNoDocsQuery(); } rb.setQuery( q ); String rankQueryString = rb.req.getParams().get(CommonParams.RQ); if(rankQueryString != null) { QParser rqparser = QParser.getParser(rankQueryString, defType, req); Query rq = rqparser.getQuery(); if(rq instanceof RankQuery) { RankQuery rankQuery = (RankQuery)rq; rb.setRankQuery(rankQuery); MergeStrategy mergeStrategy = rankQuery.getMergeStrategy(); if(mergeStrategy != null) { rb.addMergeStrategy(mergeStrategy); if(mergeStrategy.handlesMergeFields()) { rb.mergeFieldHandler = mergeStrategy; } } } else { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,"rq parameter must be a RankQuery"); } } rb.setSortSpec( parser.getSort(true) ); rb.setQparser(parser); final String cursorStr = rb.req.getParams().get(CursorMarkParams.CURSOR_MARK_PARAM); if (null != cursorStr) { final CursorMark cursorMark = new CursorMark(rb.req.getSchema(), rb.getSortSpec()); cursorMark.parseSerializedTotem(cursorStr); rb.setCursorMark(cursorMark); } String[] fqs = req.getParams().getParams(CommonParams.FQ); if (fqs!=null && fqs.length!=0) { List<Query> filters = rb.getFilters(); // if filters already exists, make a copy instead of modifying the original filters = filters == null ? new ArrayList<Query>(fqs.length) : new ArrayList<>(filters); for (String fq : fqs) { if (fq != null && fq.trim().length()!=0) { QParser fqp = QParser.getParser(fq, null, req); filters.add(fqp.getQuery()); } } // only set the filters if they are not empty otherwise // fq=&someotherParam= will trigger all docs filter for every request // if filter cache is disabled if (!filters.isEmpty()) { rb.setFilters( filters ); } } } catch (SyntaxError e) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e); } if (params.getBool(GroupParams.GROUP, false)) { prepareGrouping(rb); } else { //Validate only in case of non-grouping search. if(rb.getSortSpec().getCount() < 0) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "'rows' parameter cannot be negative"); } } //Input validation. if (rb.getSortSpec().getOffset() < 0) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "'start' parameter cannot be negative"); } } protected void prepareGrouping(ResponseBuilder rb) throws IOException { SolrQueryRequest req = rb.req; SolrParams params = req.getParams(); if (null != rb.getCursorMark()) { // It's hard to imagine, conceptually, what it would mean to combine // grouping with a cursor - so for now we just don't allow the combination at all throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Can not use Grouping with " + CursorMarkParams.CURSOR_MARK_PARAM); } SolrIndexSearcher searcher = rb.req.getSearcher(); GroupingSpecification groupingSpec = new GroupingSpecification(); rb.setGroupingSpec(groupingSpec); final SortSpec sortSpec = rb.getSortSpec(); //TODO: move weighting of sort Sort groupSort = searcher.weightSort(sortSpec.getSort()); if (groupSort == null) { groupSort = Sort.RELEVANCE; } // groupSort defaults to sort String groupSortStr = params.get(GroupParams.GROUP_SORT); //TODO: move weighting of sort Sort sortWithinGroup = groupSortStr == null ? groupSort : searcher.weightSort(SortSpecParsing.parseSortSpec(groupSortStr, req).getSort()); if (sortWithinGroup == null) { sortWithinGroup = Sort.RELEVANCE; } groupingSpec.setSortWithinGroup(sortWithinGroup); groupingSpec.setGroupSort(groupSort); String formatStr = params.get(GroupParams.GROUP_FORMAT, Grouping.Format.grouped.name()); Grouping.Format responseFormat; try { responseFormat = Grouping.Format.valueOf(formatStr); } catch (IllegalArgumentException e) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, String.format(Locale.ROOT, "Illegal %s parameter", GroupParams.GROUP_FORMAT)); } groupingSpec.setResponseFormat(responseFormat); groupingSpec.setFields(params.getParams(GroupParams.GROUP_FIELD)); groupingSpec.setQueries(params.getParams(GroupParams.GROUP_QUERY)); groupingSpec.setFunctions(params.getParams(GroupParams.GROUP_FUNC)); groupingSpec.setGroupOffset(params.getInt(GroupParams.GROUP_OFFSET, 0)); groupingSpec.setGroupLimit(params.getInt(GroupParams.GROUP_LIMIT, 1)); groupingSpec.setOffset(sortSpec.getOffset()); groupingSpec.setLimit(sortSpec.getCount()); groupingSpec.setIncludeGroupCount(params.getBool(GroupParams.GROUP_TOTAL_COUNT, false)); groupingSpec.setMain(params.getBool(GroupParams.GROUP_MAIN, false)); groupingSpec.setNeedScore((rb.getFieldFlags() & SolrIndexSearcher.GET_SCORES) != 0); groupingSpec.setTruncateGroups(params.getBool(GroupParams.GROUP_TRUNCATE, false)); } /** * Actually run the query */ @Override public void process(ResponseBuilder rb) throws IOException { LOG.debug("process: {}", rb.req.getParams()); SolrQueryRequest req = rb.req; SolrParams params = req.getParams(); if (!params.getBool(COMPONENT_NAME, true)) { return; } SolrIndexSearcher searcher = req.getSearcher(); StatsCache statsCache = req.getCore().getStatsCache(); int purpose = params.getInt(ShardParams.SHARDS_PURPOSE, ShardRequest.PURPOSE_GET_TOP_IDS); if ((purpose & ShardRequest.PURPOSE_GET_TERM_STATS) != 0) { statsCache.returnLocalStats(rb, searcher); return; } // check if we need to update the local copy of global dfs if ((purpose & ShardRequest.PURPOSE_SET_TERM_STATS) != 0) { // retrieve from request and update local cache statsCache.receiveGlobalStats(req); } SolrQueryResponse rsp = rb.rsp; IndexSchema schema = searcher.getSchema(); // Optional: This could also be implemented by the top-level searcher sending // a filter that lists the ids... that would be transparent to // the request handler, but would be more expensive (and would preserve score // too if desired). String ids = params.get(ShardParams.IDS); if (ids != null) { SchemaField idField = schema.getUniqueKeyField(); List<String> idArr = StrUtils.splitSmart(ids, ",", true); int[] luceneIds = new int[idArr.size()]; int docs = 0; for (int i=0; i<idArr.size(); i++) { int id = searcher.getFirstMatch( new Term(idField.getName(), idField.getType().toInternal(idArr.get(i)))); if (id >= 0) luceneIds[docs++] = id; } DocListAndSet res = new DocListAndSet(); res.docList = new DocSlice(0, docs, luceneIds, null, docs, 0); if (rb.isNeedDocSet()) { // TODO: create a cache for this! List<Query> queries = new ArrayList<>(); queries.add(rb.getQuery()); List<Query> filters = rb.getFilters(); if (filters != null) queries.addAll(filters); res.docSet = searcher.getDocSet(queries); } rb.setResults(res); ResultContext ctx = new BasicResultContext(rb); rsp.addResponse(ctx); return; } // -1 as flag if not set. long timeAllowed = params.getLong(CommonParams.TIME_ALLOWED, -1L); if (null != rb.getCursorMark() && 0 < timeAllowed) { // fundamentally incompatible throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Can not search using both " + CursorMarkParams.CURSOR_MARK_PARAM + " and " + CommonParams.TIME_ALLOWED); } QueryCommand cmd = rb.getQueryCommand(); cmd.setTimeAllowed(timeAllowed); req.getContext().put(SolrIndexSearcher.STATS_SOURCE, statsCache.get(req)); QueryResult result = new QueryResult(); cmd.setSegmentTerminateEarly(params.getBool(CommonParams.SEGMENT_TERMINATE_EARLY, CommonParams.SEGMENT_TERMINATE_EARLY_DEFAULT)); if (cmd.getSegmentTerminateEarly()) { result.setSegmentTerminatedEarly(Boolean.FALSE); } // // grouping / field collapsing // GroupingSpecification groupingSpec = rb.getGroupingSpec(); if (groupingSpec != null) { cmd.setSegmentTerminateEarly(false); // not supported, silently ignore any segmentTerminateEarly flag try { boolean needScores = (cmd.getFlags() & SolrIndexSearcher.GET_SCORES) != 0; if (params.getBool(GroupParams.GROUP_DISTRIBUTED_FIRST, false)) { CommandHandler.Builder topsGroupsActionBuilder = new CommandHandler.Builder() .setQueryCommand(cmd) .setNeedDocSet(false) // Order matters here .setIncludeHitCount(true) .setSearcher(searcher); for (String field : groupingSpec.getFields()) { topsGroupsActionBuilder.addCommandField(new SearchGroupsFieldCommand.Builder() .setField(schema.getField(field)) .setGroupSort(groupingSpec.getGroupSort()) .setTopNGroups(cmd.getOffset() + cmd.getLen()) .setIncludeGroupCount(groupingSpec.isIncludeGroupCount()) .build() ); } CommandHandler commandHandler = topsGroupsActionBuilder.build(); commandHandler.execute(); SearchGroupsResultTransformer serializer = new SearchGroupsResultTransformer(searcher); rsp.add("firstPhase", commandHandler.processResult(result, serializer)); rsp.add("totalHitCount", commandHandler.getTotalHitCount()); rb.setResult(result); return; } else if (params.getBool(GroupParams.GROUP_DISTRIBUTED_SECOND, false)) { CommandHandler.Builder secondPhaseBuilder = new CommandHandler.Builder() .setQueryCommand(cmd) .setTruncateGroups(groupingSpec.isTruncateGroups() && groupingSpec.getFields().length > 0) .setSearcher(searcher); for (String field : groupingSpec.getFields()) { SchemaField schemaField = schema.getField(field); String[] topGroupsParam = params.getParams(GroupParams.GROUP_DISTRIBUTED_TOPGROUPS_PREFIX + field); if (topGroupsParam == null) { topGroupsParam = new String[0]; } List<SearchGroup<BytesRef>> topGroups = new ArrayList<>(topGroupsParam.length); for (String topGroup : topGroupsParam) { SearchGroup<BytesRef> searchGroup = new SearchGroup<>(); if (!topGroup.equals(TopGroupsShardRequestFactory.GROUP_NULL_VALUE)) { searchGroup.groupValue = new BytesRef(schemaField.getType().readableToIndexed(topGroup)); } topGroups.add(searchGroup); } secondPhaseBuilder.addCommandField( new TopGroupsFieldCommand.Builder() .setField(schemaField) .setGroupSort(groupingSpec.getGroupSort()) .setSortWithinGroup(groupingSpec.getSortWithinGroup()) .setFirstPhaseGroups(topGroups) .setMaxDocPerGroup(groupingSpec.getGroupOffset() + groupingSpec.getGroupLimit()) .setNeedScores(needScores) .setNeedMaxScore(needScores) .build() ); } for (String query : groupingSpec.getQueries()) { secondPhaseBuilder.addCommandField(new Builder() .setDocsToCollect(groupingSpec.getOffset() + groupingSpec.getLimit()) .setSort(groupingSpec.getGroupSort()) .setQuery(query, rb.req) .setDocSet(searcher) .build() ); } CommandHandler commandHandler = secondPhaseBuilder.build(); commandHandler.execute(); TopGroupsResultTransformer serializer = new TopGroupsResultTransformer(rb); rsp.add("secondPhase", commandHandler.processResult(result, serializer)); rb.setResult(result); return; } int maxDocsPercentageToCache = params.getInt(GroupParams.GROUP_CACHE_PERCENTAGE, 0); boolean cacheSecondPassSearch = maxDocsPercentageToCache >= 1 && maxDocsPercentageToCache <= 100; Grouping.TotalCount defaultTotalCount = groupingSpec.isIncludeGroupCount() ? Grouping.TotalCount.grouped : Grouping.TotalCount.ungrouped; int limitDefault = cmd.getLen(); // this is normally from "rows" Grouping grouping = new Grouping(searcher, result, cmd, cacheSecondPassSearch, maxDocsPercentageToCache, groupingSpec.isMain()); grouping.setGroupSort(groupingSpec.getGroupSort()) .setWithinGroupSort(groupingSpec.getSortWithinGroup()) .setDefaultFormat(groupingSpec.getResponseFormat()) .setLimitDefault(limitDefault) .setDefaultTotalCount(defaultTotalCount) .setDocsPerGroupDefault(groupingSpec.getGroupLimit()) .setGroupOffsetDefault(groupingSpec.getGroupOffset()) .setGetGroupedDocSet(groupingSpec.isTruncateGroups()); if (groupingSpec.getFields() != null) { for (String field : groupingSpec.getFields()) { grouping.addFieldCommand(field, rb.req); } } if (groupingSpec.getFunctions() != null) { for (String groupByStr : groupingSpec.getFunctions()) { grouping.addFunctionCommand(groupByStr, rb.req); } } if (groupingSpec.getQueries() != null) { for (String groupByStr : groupingSpec.getQueries()) { grouping.addQueryCommand(groupByStr, rb.req); } } if( rb.isNeedDocList() || rb.isDebug() ){ // we need a single list of the returned docs cmd.setFlags(SolrIndexSearcher.GET_DOCLIST); } grouping.execute(); if (grouping.isSignalCacheWarning()) { rsp.add( "cacheWarning", String.format(Locale.ROOT, "Cache limit of %d percent relative to maxdoc has exceeded. Please increase cache size or disable caching.", maxDocsPercentageToCache) ); } rb.setResult(result); if (grouping.mainResult != null) { ResultContext ctx = new BasicResultContext(rb, grouping.mainResult); rsp.addResponse(ctx); rsp.getToLog().add("hits", grouping.mainResult.matches()); } else if (!grouping.getCommands().isEmpty()) { // Can never be empty since grouping.execute() checks for this. rsp.add("grouped", result.groupedResults); rsp.getToLog().add("hits", grouping.getCommands().get(0).getMatches()); } return; } catch (SyntaxError e) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e); } } // normal search result searcher.search(result, cmd); rb.setResult(result); ResultContext ctx = new BasicResultContext(rb); rsp.addResponse(ctx); rsp.getToLog().add("hits", rb.getResults().docList.matches()); if ( ! rb.req.getParams().getBool(ShardParams.IS_SHARD,false) ) { if (null != rb.getNextCursorMark()) { rb.rsp.add(CursorMarkParams.CURSOR_MARK_NEXT, rb.getNextCursorMark().getSerializedTotem()); } } if(rb.mergeFieldHandler != null) { rb.mergeFieldHandler.handleMergeFields(rb, searcher); } else { doFieldSortValues(rb, searcher); } doPrefetch(rb); } protected void doFieldSortValues(ResponseBuilder rb, SolrIndexSearcher searcher) throws IOException { SolrQueryRequest req = rb.req; SolrQueryResponse rsp = rb.rsp; // The query cache doesn't currently store sort field values, and SolrIndexSearcher doesn't // currently have an option to return sort field values. Because of this, we // take the documents given and re-derive the sort values. // // TODO: See SOLR-5595 boolean fsv = req.getParams().getBool(ResponseBuilder.FIELD_SORT_VALUES,false); if(fsv){ NamedList<Object[]> sortVals = new NamedList<>(); // order is important for the sort fields IndexReaderContext topReaderContext = searcher.getTopReaderContext(); List<LeafReaderContext> leaves = topReaderContext.leaves(); LeafReaderContext currentLeaf = null; if (leaves.size()==1) { // if there is a single segment, use that subReader and avoid looking up each time currentLeaf = leaves.get(0); leaves=null; } DocList docList = rb.getResults().docList; // sort ids from lowest to highest so we can access them in order int nDocs = docList.size(); final long[] sortedIds = new long[nDocs]; final float[] scores = new float[nDocs]; // doc scores, parallel to sortedIds DocList docs = rb.getResults().docList; DocIterator it = docs.iterator(); for (int i=0; i<nDocs; i++) { sortedIds[i] = (((long)it.nextDoc()) << 32) | i; scores[i] = docs.hasScores() ? it.score() : Float.NaN; } // sort ids and scores together new InPlaceMergeSorter() { @Override protected void swap(int i, int j) { long tmpId = sortedIds[i]; float tmpScore = scores[i]; sortedIds[i] = sortedIds[j]; scores[i] = scores[j]; sortedIds[j] = tmpId; scores[j] = tmpScore; } @Override protected int compare(int i, int j) { return Long.compare(sortedIds[i], sortedIds[j]); } }.sort(0, sortedIds.length); SortSpec sortSpec = rb.getSortSpec(); Sort sort = searcher.weightSort(sortSpec.getSort()); SortField[] sortFields = sort==null ? new SortField[]{SortField.FIELD_SCORE} : sort.getSort(); List<SchemaField> schemaFields = sortSpec.getSchemaFields(); for (int fld = 0; fld < schemaFields.size(); fld++) { SchemaField schemaField = schemaFields.get(fld); FieldType ft = null == schemaField? null : schemaField.getType(); SortField sortField = sortFields[fld]; SortField.Type type = sortField.getType(); // :TODO: would be simpler to always serialize every position of SortField[] if (type==SortField.Type.SCORE || type==SortField.Type.DOC) continue; FieldComparator<?> comparator = null; LeafFieldComparator leafComparator = null; Object[] vals = new Object[nDocs]; int lastIdx = -1; int idx = 0; for (int i = 0; i < sortedIds.length; ++i) { long idAndPos = sortedIds[i]; float score = scores[i]; int doc = (int)(idAndPos >>> 32); int position = (int)idAndPos; if (leaves != null) { idx = ReaderUtil.subIndex(doc, leaves); currentLeaf = leaves.get(idx); if (idx != lastIdx) { // we switched segments. invalidate comparator. comparator = null; } } if (comparator == null) { comparator = sortField.getComparator(1,0); leafComparator = comparator.getLeafComparator(currentLeaf); } doc -= currentLeaf.docBase; // adjust for what segment this is in leafComparator.setScorer(new FakeScorer(doc, score)); leafComparator.copy(0, doc); Object val = comparator.value(0); if (null != ft) val = ft.marshalSortValue(val); vals[position] = val; } sortVals.add(sortField.getField(), vals); } rsp.add("sort_values", sortVals); } } protected void doPrefetch(ResponseBuilder rb) throws IOException { SolrQueryRequest req = rb.req; SolrQueryResponse rsp = rb.rsp; //pre-fetch returned documents if (!req.getParams().getBool(ShardParams.IS_SHARD,false) && rb.getResults().docList != null && rb.getResults().docList.size()<=50) { SolrPluginUtils.optimizePreFetchDocs(rb, rb.getResults().docList, rb.getQuery(), req, rsp); } } @Override public int distributedProcess(ResponseBuilder rb) throws IOException { if (rb.grouping()) { return groupedDistributedProcess(rb); } else { return regularDistributedProcess(rb); } } protected int groupedDistributedProcess(ResponseBuilder rb) { int nextStage = ResponseBuilder.STAGE_DONE; ShardRequestFactory shardRequestFactory = null; if (rb.stage < ResponseBuilder.STAGE_PARSE_QUERY) { nextStage = ResponseBuilder.STAGE_PARSE_QUERY; } else if (rb.stage == ResponseBuilder.STAGE_PARSE_QUERY) { createDistributedStats(rb); nextStage = ResponseBuilder.STAGE_TOP_GROUPS; } else if (rb.stage < ResponseBuilder.STAGE_TOP_GROUPS) { nextStage = ResponseBuilder.STAGE_TOP_GROUPS; } else if (rb.stage == ResponseBuilder.STAGE_TOP_GROUPS) { shardRequestFactory = new SearchGroupsRequestFactory(); nextStage = ResponseBuilder.STAGE_EXECUTE_QUERY; } else if (rb.stage < ResponseBuilder.STAGE_EXECUTE_QUERY) { nextStage = ResponseBuilder.STAGE_EXECUTE_QUERY; } else if (rb.stage == ResponseBuilder.STAGE_EXECUTE_QUERY) { shardRequestFactory = new TopGroupsShardRequestFactory(); nextStage = ResponseBuilder.STAGE_GET_FIELDS; } else if (rb.stage < ResponseBuilder.STAGE_GET_FIELDS) { nextStage = ResponseBuilder.STAGE_GET_FIELDS; } else if (rb.stage == ResponseBuilder.STAGE_GET_FIELDS) { shardRequestFactory = new StoredFieldsShardRequestFactory(); nextStage = ResponseBuilder.STAGE_DONE; } if (shardRequestFactory != null) { for (ShardRequest shardRequest : shardRequestFactory.constructRequest(rb)) { rb.addRequest(this, shardRequest); } } return nextStage; } protected int regularDistributedProcess(ResponseBuilder rb) { if (rb.stage < ResponseBuilder.STAGE_PARSE_QUERY) return ResponseBuilder.STAGE_PARSE_QUERY; if (rb.stage == ResponseBuilder.STAGE_PARSE_QUERY) { createDistributedStats(rb); return ResponseBuilder.STAGE_EXECUTE_QUERY; } if (rb.stage < ResponseBuilder.STAGE_EXECUTE_QUERY) return ResponseBuilder.STAGE_EXECUTE_QUERY; if (rb.stage == ResponseBuilder.STAGE_EXECUTE_QUERY) { createMainQuery(rb); return ResponseBuilder.STAGE_GET_FIELDS; } if (rb.stage < ResponseBuilder.STAGE_GET_FIELDS) return ResponseBuilder.STAGE_GET_FIELDS; if (rb.stage == ResponseBuilder.STAGE_GET_FIELDS && !rb.onePassDistributedQuery) { createRetrieveDocs(rb); return ResponseBuilder.STAGE_DONE; } return ResponseBuilder.STAGE_DONE; } @Override public void handleResponses(ResponseBuilder rb, ShardRequest sreq) { if (rb.grouping()) { handleGroupedResponses(rb, sreq); } else { handleRegularResponses(rb, sreq); } } protected void handleGroupedResponses(ResponseBuilder rb, ShardRequest sreq) { ShardResponseProcessor responseProcessor = null; if ((sreq.purpose & ShardRequest.PURPOSE_GET_TOP_GROUPS) != 0) { responseProcessor = new SearchGroupShardResponseProcessor(); } else if ((sreq.purpose & ShardRequest.PURPOSE_GET_TOP_IDS) != 0) { responseProcessor = new TopGroupsShardResponseProcessor(); } else if ((sreq.purpose & ShardRequest.PURPOSE_GET_FIELDS) != 0) { responseProcessor = new StoredFieldsShardResponseProcessor(); } if (responseProcessor != null) { responseProcessor.process(rb, sreq); } } protected void handleRegularResponses(ResponseBuilder rb, ShardRequest sreq) { if ((sreq.purpose & ShardRequest.PURPOSE_GET_TOP_IDS) != 0) { mergeIds(rb, sreq); } if ((sreq.purpose & ShardRequest.PURPOSE_GET_TERM_STATS) != 0) { updateStats(rb, sreq); } if ((sreq.purpose & ShardRequest.PURPOSE_GET_FIELDS) != 0) { returnFields(rb, sreq); } } @Override public void finishStage(ResponseBuilder rb) { if (rb.stage != ResponseBuilder.STAGE_GET_FIELDS) { return; } if (rb.grouping()) { groupedFinishStage(rb); } else { regularFinishStage(rb); } } protected static final EndResultTransformer MAIN_END_RESULT_TRANSFORMER = new MainEndResultTransformer(); protected static final EndResultTransformer SIMPLE_END_RESULT_TRANSFORMER = new SimpleEndResultTransformer(); @SuppressWarnings("unchecked") protected void groupedFinishStage(final ResponseBuilder rb) { // To have same response as non-distributed request. GroupingSpecification groupSpec = rb.getGroupingSpec(); if (rb.mergedTopGroups.isEmpty()) { for (String field : groupSpec.getFields()) { rb.mergedTopGroups.put(field, new TopGroups(null, null, 0, 0, new GroupDocs[]{}, Float.NaN)); } rb.resultIds = new HashMap<>(); } EndResultTransformer.SolrDocumentSource solrDocumentSource = doc -> { ShardDoc solrDoc = (ShardDoc) doc; return rb.retrievedDocuments.get(solrDoc.id); }; EndResultTransformer endResultTransformer; if (groupSpec.isMain()) { endResultTransformer = MAIN_END_RESULT_TRANSFORMER; } else if (Grouping.Format.grouped == groupSpec.getResponseFormat()) { endResultTransformer = new GroupedEndResultTransformer(rb.req.getSearcher()); } else if (Grouping.Format.simple == groupSpec.getResponseFormat() && !groupSpec.isMain()) { endResultTransformer = SIMPLE_END_RESULT_TRANSFORMER; } else { return; } Map<String, Object> combinedMap = new LinkedHashMap<>(); combinedMap.putAll(rb.mergedTopGroups); combinedMap.putAll(rb.mergedQueryCommandResults); endResultTransformer.transform(combinedMap, rb, solrDocumentSource); } protected void regularFinishStage(ResponseBuilder rb) { // We may not have been able to retrieve all the docs due to an // index change. Remove any null documents. for (Iterator<SolrDocument> iter = rb.getResponseDocs().iterator(); iter.hasNext();) { if (iter.next() == null) { iter.remove(); rb.getResponseDocs().setNumFound(rb.getResponseDocs().getNumFound()-1); } } rb.rsp.addResponse(rb.getResponseDocs()); if (null != rb.getNextCursorMark()) { rb.rsp.add(CursorMarkParams.CURSOR_MARK_NEXT, rb.getNextCursorMark().getSerializedTotem()); } } protected void createDistributedStats(ResponseBuilder rb) { StatsCache cache = rb.req.getCore().getStatsCache(); if ( (rb.getFieldFlags() & SolrIndexSearcher.GET_SCORES)!=0 || rb.getSortSpec().includesScore()) { ShardRequest sreq = cache.retrieveStatsRequest(rb); if (sreq != null) { rb.addRequest(this, sreq); } } } protected void updateStats(ResponseBuilder rb, ShardRequest sreq) { StatsCache cache = rb.req.getCore().getStatsCache(); cache.mergeToGlobalStats(rb.req, sreq.responses); } protected void createMainQuery(ResponseBuilder rb) { ShardRequest sreq = new ShardRequest(); sreq.purpose = ShardRequest.PURPOSE_GET_TOP_IDS; String keyFieldName = rb.req.getSchema().getUniqueKeyField().getName(); // one-pass algorithm if only id and score fields are requested, but not if fl=score since that's the same as fl=*,score ReturnFields fields = rb.rsp.getReturnFields(); // distrib.singlePass=true forces a one-pass query regardless of requested fields boolean distribSinglePass = rb.req.getParams().getBool(ShardParams.DISTRIB_SINGLE_PASS, false); if(distribSinglePass || (fields != null && fields.wantsField(keyFieldName) && fields.getRequestedFieldNames() != null && (!fields.hasPatternMatching() && Arrays.asList(keyFieldName, "score").containsAll(fields.getRequestedFieldNames())))) { sreq.purpose |= ShardRequest.PURPOSE_GET_FIELDS; rb.onePassDistributedQuery = true; } sreq.params = new ModifiableSolrParams(rb.req.getParams()); // TODO: base on current params or original params? // don't pass through any shards param sreq.params.remove(ShardParams.SHARDS); // set the start (offset) to 0 for each shard request so we can properly merge // results from the start. if(rb.shards_start > -1) { // if the client set shards.start set this explicitly sreq.params.set(CommonParams.START,rb.shards_start); } else { sreq.params.set(CommonParams.START, "0"); } // TODO: should we even use the SortSpec? That's obtained from the QParser, and // perhaps we shouldn't attempt to parse the query at this level? // Alternate Idea: instead of specifying all these things at the upper level, // we could just specify that this is a shard request. if(rb.shards_rows > -1) { // if the client set shards.rows set this explicity sreq.params.set(CommonParams.ROWS,rb.shards_rows); } else { sreq.params.set(CommonParams.ROWS, rb.getSortSpec().getOffset() + rb.getSortSpec().getCount()); } sreq.params.set(ResponseBuilder.FIELD_SORT_VALUES,"true"); boolean shardQueryIncludeScore = (rb.getFieldFlags() & SolrIndexSearcher.GET_SCORES) != 0 || rb.getSortSpec().includesScore(); StringBuilder additionalFL = new StringBuilder(); boolean additionalAdded = false; if (distribSinglePass) { String[] fls = rb.req.getParams().getParams(CommonParams.FL); if (fls != null && fls.length > 0 && (fls.length != 1 || !fls[0].isEmpty())) { // If the outer request contains actual FL's use them... sreq.params.set(CommonParams.FL, fls); if (!fields.wantsField(keyFieldName)) { additionalAdded = addFL(additionalFL, keyFieldName, additionalAdded); } } else { // ... else we need to explicitly ask for all fields, because we are going to add // additional fields below sreq.params.set(CommonParams.FL, "*"); } if (!fields.wantsScore() && shardQueryIncludeScore) { additionalAdded = addFL(additionalFL, "score", additionalAdded); } } else { // reset so that only unique key is requested in shard requests sreq.params.set(CommonParams.FL, rb.req.getSchema().getUniqueKeyField().getName()); if (shardQueryIncludeScore) { additionalAdded = addFL(additionalFL, "score", additionalAdded); } } // TODO: should this really sendGlobalDfs if just includeScore? if (shardQueryIncludeScore) { StatsCache statsCache = rb.req.getCore().getStatsCache(); statsCache.sendGlobalStats(rb, sreq); } if (additionalAdded) sreq.params.add(CommonParams.FL, additionalFL.toString()); rb.addRequest(this, sreq); } protected boolean addFL(StringBuilder fl, String field, boolean additionalAdded) { if (additionalAdded) fl.append(","); fl.append(field); return true; } protected void mergeIds(ResponseBuilder rb, ShardRequest sreq) { List<MergeStrategy> mergeStrategies = rb.getMergeStrategies(); if(mergeStrategies != null) { Collections.sort(mergeStrategies, MergeStrategy.MERGE_COMP); boolean idsMerged = false; for(MergeStrategy mergeStrategy : mergeStrategies) { mergeStrategy.merge(rb, sreq); if(mergeStrategy.mergesIds()) { idsMerged = true; } } if(idsMerged) { return; //ids were merged above so return. } } SortSpec ss = rb.getSortSpec(); Sort sort = ss.getSort(); SortField[] sortFields = null; if(sort != null) sortFields = sort.getSort(); else { sortFields = new SortField[]{SortField.FIELD_SCORE}; } IndexSchema schema = rb.req.getSchema(); SchemaField uniqueKeyField = schema.getUniqueKeyField(); // id to shard mapping, to eliminate any accidental dups HashMap<Object,String> uniqueDoc = new HashMap<>(); // Merge the docs via a priority queue so we don't have to sort *all* of the // documents... we only need to order the top (rows+start) ShardFieldSortedHitQueue queue; queue = new ShardFieldSortedHitQueue(sortFields, ss.getOffset() + ss.getCount(), rb.req.getSearcher()); NamedList<Object> shardInfo = null; if(rb.req.getParams().getBool(ShardParams.SHARDS_INFO, false)) { shardInfo = new SimpleOrderedMap<>(); rb.rsp.getValues().add(ShardParams.SHARDS_INFO,shardInfo); } long numFound = 0; Float maxScore=null; boolean partialResults = false; Boolean segmentTerminatedEarly = null; for (ShardResponse srsp : sreq.responses) { SolrDocumentList docs = null; NamedList<?> responseHeader = null; if(shardInfo!=null) { SimpleOrderedMap<Object> nl = new SimpleOrderedMap<>(); if (srsp.getException() != null) { Throwable t = srsp.getException(); if(t instanceof SolrServerException) { t = ((SolrServerException)t).getCause(); } nl.add("error", t.toString() ); StringWriter trace = new StringWriter(); t.printStackTrace(new PrintWriter(trace)); nl.add("trace", trace.toString() ); if (srsp.getShardAddress() != null) { nl.add("shardAddress", srsp.getShardAddress()); } } else { responseHeader = (NamedList<?>)srsp.getSolrResponse().getResponse().get("responseHeader"); final Object rhste = (responseHeader == null ? null : responseHeader.get(SolrQueryResponse.RESPONSE_HEADER_SEGMENT_TERMINATED_EARLY_KEY)); if (rhste != null) { nl.add(SolrQueryResponse.RESPONSE_HEADER_SEGMENT_TERMINATED_EARLY_KEY, rhste); } docs = (SolrDocumentList)srsp.getSolrResponse().getResponse().get("response"); nl.add("numFound", docs.getNumFound()); nl.add("maxScore", docs.getMaxScore()); nl.add("shardAddress", srsp.getShardAddress()); } if(srsp.getSolrResponse()!=null) { nl.add("time", srsp.getSolrResponse().getElapsedTime()); } shardInfo.add(srsp.getShard(), nl); } // now that we've added the shard info, let's only proceed if we have no error. if (srsp.getException() != null) { partialResults = true; continue; } if (docs == null) { // could have been initialized in the shards info block above docs = (SolrDocumentList)srsp.getSolrResponse().getResponse().get("response"); } if (responseHeader == null) { // could have been initialized in the shards info block above responseHeader = (NamedList<?>)srsp.getSolrResponse().getResponse().get("responseHeader"); } if (responseHeader != null) { if (Boolean.TRUE.equals(responseHeader.get(SolrQueryResponse.RESPONSE_HEADER_PARTIAL_RESULTS_KEY))) { partialResults = true; } if (!Boolean.TRUE.equals(segmentTerminatedEarly)) { final Object ste = responseHeader.get(SolrQueryResponse.RESPONSE_HEADER_SEGMENT_TERMINATED_EARLY_KEY); if (Boolean.TRUE.equals(ste)) { segmentTerminatedEarly = Boolean.TRUE; } else if (Boolean.FALSE.equals(ste)) { segmentTerminatedEarly = Boolean.FALSE; } } } // calculate global maxScore and numDocsFound if (docs.getMaxScore() != null) { maxScore = maxScore==null ? docs.getMaxScore() : Math.max(maxScore, docs.getMaxScore()); } numFound += docs.getNumFound(); NamedList sortFieldValues = (NamedList)(srsp.getSolrResponse().getResponse().get("sort_values")); NamedList unmarshalledSortFieldValues = unmarshalSortValues(ss, sortFieldValues, schema); // go through every doc in this response, construct a ShardDoc, and // put it in the priority queue so it can be ordered. for (int i=0; i<docs.size(); i++) { SolrDocument doc = docs.get(i); Object id = doc.getFieldValue(uniqueKeyField.getName()); String prevShard = uniqueDoc.put(id, srsp.getShard()); if (prevShard != null) { // duplicate detected numFound--; // For now, just always use the first encountered since we can't currently // remove the previous one added to the priority queue. If we switched // to the Java5 PriorityQueue, this would be easier. continue; // make which duplicate is used deterministic based on shard // if (prevShard.compareTo(srsp.shard) >= 0) { // TODO: remove previous from priority queue // continue; // } } ShardDoc shardDoc = new ShardDoc(); shardDoc.id = id; shardDoc.shard = srsp.getShard(); shardDoc.orderInShard = i; Object scoreObj = doc.getFieldValue("score"); if (scoreObj != null) { if (scoreObj instanceof String) { shardDoc.score = Float.parseFloat((String)scoreObj); } else { shardDoc.score = (Float)scoreObj; } } shardDoc.sortFieldValues = unmarshalledSortFieldValues; queue.insertWithOverflow(shardDoc); } // end for-each-doc-in-response } // end for-each-response // The queue now has 0 -> queuesize docs, where queuesize <= start + rows // So we want to pop the last documents off the queue to get // the docs offset -> queuesize int resultSize = queue.size() - ss.getOffset(); resultSize = Math.max(0, resultSize); // there may not be any docs in range Map<Object,ShardDoc> resultIds = new HashMap<>(); for (int i=resultSize-1; i>=0; i--) { ShardDoc shardDoc = queue.pop(); shardDoc.positionInResponse = i; // Need the toString() for correlation with other lists that must // be strings (like keys in highlighting, explain, etc) resultIds.put(shardDoc.id.toString(), shardDoc); } // Add hits for distributed requests // https://issues.apache.org/jira/browse/SOLR-3518 rb.rsp.addToLog("hits", numFound); SolrDocumentList responseDocs = new SolrDocumentList(); if (maxScore!=null) responseDocs.setMaxScore(maxScore); responseDocs.setNumFound(numFound); responseDocs.setStart(ss.getOffset()); // size appropriately for (int i=0; i<resultSize; i++) responseDocs.add(null); // save these results in a private area so we can access them // again when retrieving stored fields. // TODO: use ResponseBuilder (w/ comments) or the request context? rb.resultIds = resultIds; rb.setResponseDocs(responseDocs); populateNextCursorMarkFromMergedShards(rb); if (partialResults) { if(rb.rsp.getResponseHeader().get(SolrQueryResponse.RESPONSE_HEADER_PARTIAL_RESULTS_KEY) == null) { rb.rsp.getResponseHeader().add(SolrQueryResponse.RESPONSE_HEADER_PARTIAL_RESULTS_KEY, Boolean.TRUE); } } if (segmentTerminatedEarly != null) { final Object existingSegmentTerminatedEarly = rb.rsp.getResponseHeader().get(SolrQueryResponse.RESPONSE_HEADER_SEGMENT_TERMINATED_EARLY_KEY); if (existingSegmentTerminatedEarly == null) { rb.rsp.getResponseHeader().add(SolrQueryResponse.RESPONSE_HEADER_SEGMENT_TERMINATED_EARLY_KEY, segmentTerminatedEarly); } else if (!Boolean.TRUE.equals(existingSegmentTerminatedEarly) && Boolean.TRUE.equals(segmentTerminatedEarly)) { rb.rsp.getResponseHeader().remove(SolrQueryResponse.RESPONSE_HEADER_SEGMENT_TERMINATED_EARLY_KEY); rb.rsp.getResponseHeader().add(SolrQueryResponse.RESPONSE_HEADER_SEGMENT_TERMINATED_EARLY_KEY, segmentTerminatedEarly); } } } /** * Inspects the state of the {@link ResponseBuilder} and populates the next * {@link ResponseBuilder#setNextCursorMark} as appropriate based on the merged * sort values from individual shards * * @param rb A <code>ResponseBuilder</code> that already contains merged * <code>ShardDocs</code> in <code>resultIds</code>, may or may not be * part of a Cursor based request (method will NOOP if not needed) */ protected void populateNextCursorMarkFromMergedShards(ResponseBuilder rb) { final CursorMark lastCursorMark = rb.getCursorMark(); if (null == lastCursorMark) { // Not a cursor based request return; // NOOP } assert null != rb.resultIds : "resultIds was not set in ResponseBuilder"; Collection<ShardDoc> docsOnThisPage = rb.resultIds.values(); if (0 == docsOnThisPage.size()) { // nothing more matching query, re-use existing totem so user can "resume" // search later if it makes sense for this sort. rb.setNextCursorMark(lastCursorMark); return; } ShardDoc lastDoc = null; // ShardDoc and rb.resultIds are weird structures to work with... for (ShardDoc eachDoc : docsOnThisPage) { if (null == lastDoc || lastDoc.positionInResponse < eachDoc.positionInResponse) { lastDoc = eachDoc; } } SortField[] sortFields = lastCursorMark.getSortSpec().getSort().getSort(); List<Object> nextCursorMarkValues = new ArrayList<>(sortFields.length); for (SortField sf : sortFields) { if (sf.getType().equals(SortField.Type.SCORE)) { nextCursorMarkValues.add(lastDoc.score); } else { assert null != sf.getField() : "SortField has null field"; List<Object> fieldVals = (List<Object>) lastDoc.sortFieldValues.get(sf.getField()); nextCursorMarkValues.add(fieldVals.get(lastDoc.orderInShard)); } } CursorMark nextCursorMark = lastCursorMark.createNext(nextCursorMarkValues); assert null != nextCursorMark : "null nextCursorMark"; rb.setNextCursorMark(nextCursorMark); } protected NamedList unmarshalSortValues(SortSpec sortSpec, NamedList sortFieldValues, IndexSchema schema) { NamedList unmarshalledSortValsPerField = new NamedList(); if (0 == sortFieldValues.size()) return unmarshalledSortValsPerField; List<SchemaField> schemaFields = sortSpec.getSchemaFields(); SortField[] sortFields = sortSpec.getSort().getSort(); int marshalledFieldNum = 0; for (int sortFieldNum = 0; sortFieldNum < sortFields.length; sortFieldNum++) { final SortField sortField = sortFields[sortFieldNum]; final SortField.Type type = sortField.getType(); // :TODO: would be simpler to always serialize every position of SortField[] if (type==SortField.Type.SCORE || type==SortField.Type.DOC) continue; final String sortFieldName = sortField.getField(); final String valueFieldName = sortFieldValues.getName(marshalledFieldNum); assert sortFieldName.equals(valueFieldName) : "sortFieldValues name key does not match expected SortField.getField"; List sortVals = (List)sortFieldValues.getVal(marshalledFieldNum); final SchemaField schemaField = schemaFields.get(sortFieldNum); if (null == schemaField) { unmarshalledSortValsPerField.add(sortField.getField(), sortVals); } else { FieldType fieldType = schemaField.getType(); List unmarshalledSortVals = new ArrayList(); for (Object sortVal : sortVals) { unmarshalledSortVals.add(fieldType.unmarshalSortValue(sortVal)); } unmarshalledSortValsPerField.add(sortField.getField(), unmarshalledSortVals); } marshalledFieldNum++; } return unmarshalledSortValsPerField; } protected void createRetrieveDocs(ResponseBuilder rb) { // TODO: in a system with nTiers > 2, we could be passed "ids" here // unless those requests always go to the final destination shard // for each shard, collect the documents for that shard. HashMap<String, Collection<ShardDoc>> shardMap = new HashMap<>(); for (ShardDoc sdoc : rb.resultIds.values()) { Collection<ShardDoc> shardDocs = shardMap.get(sdoc.shard); if (shardDocs == null) { shardDocs = new ArrayList<>(); shardMap.put(sdoc.shard, shardDocs); } shardDocs.add(sdoc); } SchemaField uniqueField = rb.req.getSchema().getUniqueKeyField(); // Now create a request for each shard to retrieve the stored fields for (Collection<ShardDoc> shardDocs : shardMap.values()) { ShardRequest sreq = new ShardRequest(); sreq.purpose = ShardRequest.PURPOSE_GET_FIELDS; sreq.shards = new String[] {shardDocs.iterator().next().shard}; sreq.params = new ModifiableSolrParams(); // add original params sreq.params.add( rb.req.getParams()); // no need for a sort, we already have order sreq.params.remove(CommonParams.SORT); sreq.params.remove(CursorMarkParams.CURSOR_MARK_PARAM); // we already have the field sort values sreq.params.remove(ResponseBuilder.FIELD_SORT_VALUES); if(!rb.rsp.getReturnFields().wantsField(uniqueField.getName())) { sreq.params.add(CommonParams.FL, uniqueField.getName()); } ArrayList<String> ids = new ArrayList<>(shardDocs.size()); for (ShardDoc shardDoc : shardDocs) { // TODO: depending on the type, we may need more tha a simple toString()? ids.add(shardDoc.id.toString()); } sreq.params.add(ShardParams.IDS, StrUtils.join(ids, ',')); rb.addRequest(this, sreq); } } protected void returnFields(ResponseBuilder rb, ShardRequest sreq) { // Keep in mind that this could also be a shard in a multi-tiered system. // TODO: if a multi-tiered system, it seems like some requests // could/should bypass middlemen (like retrieving stored fields) // TODO: merge fsv to if requested if ((sreq.purpose & ShardRequest.PURPOSE_GET_FIELDS) != 0) { boolean returnScores = (rb.getFieldFlags() & SolrIndexSearcher.GET_SCORES) != 0; String keyFieldName = rb.req.getSchema().getUniqueKeyField().getName(); boolean removeKeyField = !rb.rsp.getReturnFields().wantsField(keyFieldName); for (ShardResponse srsp : sreq.responses) { if (srsp.getException() != null) { // Don't try to get the documents if there was an exception in the shard if(rb.req.getParams().getBool(ShardParams.SHARDS_INFO, false)) { @SuppressWarnings("unchecked") NamedList<Object> shardInfo = (NamedList<Object>) rb.rsp.getValues().get(ShardParams.SHARDS_INFO); @SuppressWarnings("unchecked") SimpleOrderedMap<Object> nl = (SimpleOrderedMap<Object>) shardInfo.get(srsp.getShard()); if (nl.get("error") == null) { // Add the error to the shards info section if it wasn't added before Throwable t = srsp.getException(); if(t instanceof SolrServerException) { t = ((SolrServerException)t).getCause(); } nl.add("error", t.toString() ); StringWriter trace = new StringWriter(); t.printStackTrace(new PrintWriter(trace)); nl.add("trace", trace.toString() ); } } continue; } SolrDocumentList docs = (SolrDocumentList) srsp.getSolrResponse().getResponse().get("response"); for (SolrDocument doc : docs) { Object id = doc.getFieldValue(keyFieldName); ShardDoc sdoc = rb.resultIds.get(id.toString()); if (sdoc != null) { if (returnScores) { doc.setField("score", sdoc.score); } else { // Score might have been added (in createMainQuery) to shard-requests (and therefore in shard-response-docs) // Remove score if the outer request did not ask for it returned doc.remove("score"); } if (removeKeyField) { doc.removeFields(keyFieldName); } rb.getResponseDocs().set(sdoc.positionInResponse, doc); } } } } } ///////////////////////////////////////////// /// SolrInfoMBean //////////////////////////////////////////// @Override public String getDescription() { return "query"; } @Override public URL[] getDocs() { return null; } /** * Fake scorer for a single document * * TODO: when SOLR-5595 is fixed, this wont be needed, as we dont need to recompute sort values here from the comparator */ protected static class FakeScorer extends Scorer { final int docid; final float score; FakeScorer(int docid, float score) { super(null); this.docid = docid; this.score = score; } @Override public int docID() { return docid; } @Override public float score() throws IOException { return score; } @Override public int freq() throws IOException { throw new UnsupportedOperationException(); } @Override public DocIdSetIterator iterator() { throw new UnsupportedOperationException(); } @Override public Weight getWeight() { throw new UnsupportedOperationException(); } @Override public Collection<ChildScorer> getChildren() { throw new UnsupportedOperationException(); } } }
1
26,054
@shalinmangar If lazy field loading isn't enabled, I don't think this actually changes the behavior of `SolrIndexSearcher`, since it was previously ignoring the fields list anyway. What it _should_ do is allow certain distributed queries, like the ones in `DistribJoinFromCollectionTest`, to co-exist with `SolrIndexSearcher#doc()` respecting the `fields` set instead of just discarding it.
apache-lucene-solr
java
@@ -5,7 +5,7 @@ package ddevapp const DDevComposeTemplate = `version: '2' services: - {{ .plugin }}-{{.name }}-db: + db: container_name: {{ .plugin }}-${DDEV_SITENAME}-db image: $DDEV_DBIMAGE volumes:
1
package ddevapp // DDevComposeTemplate is used to create the docker-compose.yaml for // legacy sites in the ddev env const DDevComposeTemplate = `version: '2' services: {{ .plugin }}-{{.name }}-db: container_name: {{ .plugin }}-${DDEV_SITENAME}-db image: $DDEV_DBIMAGE volumes: - "./data:/db" restart: always environment: - TCP_PORT=$DDEV_HOSTNAME:{{ .dbport }} ports: - 3306 labels: com.ddev.site-name: ${DDEV_SITENAME} com.ddev.container-type: db com.ddev.platform: {{ .plugin }} com.ddev.app-type: {{ .appType }} com.ddev.docroot: $DDEV_DOCROOT com.ddev.approot: $DDEV_APPROOT com.ddev.app-url: $DDEV_URL {{ .plugin }}-{{ .name }}-web: container_name: {{ .plugin }}-${DDEV_SITENAME}-web image: $DDEV_WEBIMAGE volumes: - "{{ .docroot }}/:/var/www/html/docroot" restart: always depends_on: - {{ .plugin }}-${DDEV_SITENAME}-db links: - {{ .plugin }}-${DDEV_SITENAME}-db:$DDEV_HOSTNAME - {{ .plugin }}-${DDEV_SITENAME}-db:db ports: - "80" - {{ .mailhogport }} working_dir: "/var/www/html/docroot" environment: - DEPLOY_NAME=local - VIRTUAL_HOST=$DDEV_HOSTNAME - VIRTUAL_PORT=80,{{ .mailhogport }} labels: com.ddev.site-name: ${DDEV_SITENAME} com.ddev.container-type: web com.ddev.platform: {{ .plugin }} com.ddev.app-type: {{ .appType }} com.ddev.docroot: $DDEV_DOCROOT com.ddev.approot: $DDEV_APPROOT com.ddev.app-url: $DDEV_URL {{ .plugin }}-{{ .name }}-dba: container_name: local-${DDEV_SITENAME}-dba image: $DDEV_DBAIMAGE restart: always labels: com.ddev.site-name: ${DDEV_SITENAME} com.ddev.container-type: dba com.ddev.platform: {{ .plugin }} com.ddev.app-type: {{ .appType }} com.ddev.docroot: $DDEV_DOCROOT com.ddev.approot: $DDEV_APPROOT com.ddev.app-url: $DDEV_URL depends_on: - local-${DDEV_SITENAME}-db links: - local-${DDEV_SITENAME}-db:db ports: - "80" environment: - PMA_USER=root - PMA_PASSWORD=root - VIRTUAL_HOST=$DDEV_HOSTNAME - VIRTUAL_PORT={{ .dbaport }} networks: default: external: name: ddev_default `
1
11,103
Should we be using version 3 now?
drud-ddev
go
@@ -24,7 +24,11 @@ class PluginListFactory public function __invoke(string $current_dir, ?string $config_file_path = null): PluginList { - $config_file = new ConfigFile($current_dir, $config_file_path); + try { + $config_file = new ConfigFile($current_dir, $config_file_path); + } catch (\RuntimeException $exception) { + $config_file = null; + } $composer_lock = new ComposerLock($this->findLockFiles()); return new PluginList($config_file, $composer_lock);
1
<?php namespace Psalm\Internal\PluginManager; use Psalm\Internal\Composer; use function array_filter; use const DIRECTORY_SEPARATOR; use function json_encode; use function rtrim; use function urlencode; class PluginListFactory { /** @var string */ private $project_root; /** @var string */ private $psalm_root; public function __construct(string $project_root, string $psalm_root) { $this->project_root = $project_root; $this->psalm_root = $psalm_root; } public function __invoke(string $current_dir, ?string $config_file_path = null): PluginList { $config_file = new ConfigFile($current_dir, $config_file_path); $composer_lock = new ComposerLock($this->findLockFiles()); return new PluginList($config_file, $composer_lock); } /** @return non-empty-array<int,string> */ private function findLockFiles(): array { // use cases // 1. plugins are installed into project vendors - composer.lock is PROJECT_ROOT/composer.lock // 2. plugins are installed into separate composer environment (either global or bamarni-bin) // - composer.lock is PSALM_ROOT/../../../composer.lock // 3. plugins are installed into psalm vendors - composer.lock is PSALM_ROOT/composer.lock // 4. none of the above - use stub (empty virtual composer.lock) if ($this->psalm_root === $this->project_root) { // managing plugins for psalm itself $composer_lock_filenames = [ Composer::getLockFilePath(rtrim($this->psalm_root, DIRECTORY_SEPARATOR)), ]; } else { $composer_lock_filenames = [ Composer::getLockFilePath(rtrim($this->project_root, DIRECTORY_SEPARATOR)), Composer::getLockFilePath(rtrim($this->psalm_root, DIRECTORY_SEPARATOR) . '/../../..'), Composer::getLockFilePath(rtrim($this->psalm_root, DIRECTORY_SEPARATOR)), ]; } $composer_lock_filenames = array_filter($composer_lock_filenames, 'is_readable'); if (empty($composer_lock_filenames)) { $stub_composer_lock = (object)[ 'packages' => [], 'packages-dev' => [], ]; $composer_lock_filenames[] = 'data:application/json,' . urlencode(json_encode($stub_composer_lock)); } return $composer_lock_filenames; } }
1
9,376
Would be better to throw a more specific exception, but for now it will do.
vimeo-psalm
php
@@ -17,8 +17,6 @@ package org.hyperledger.besu.tests.acceptance.dsl.blockchain; import static org.web3j.utils.Convert.Unit.ETHER; import static org.web3j.utils.Convert.Unit.WEI; -import org.hyperledger.besu.ethereum.core.Wei; - import java.math.BigDecimal; import java.math.BigInteger;
1
/* * Copyright ConsenSys AG. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * SPDX-License-Identifier: Apache-2.0 */ package org.hyperledger.besu.tests.acceptance.dsl.blockchain; import static org.web3j.utils.Convert.Unit.ETHER; import static org.web3j.utils.Convert.Unit.WEI; import org.hyperledger.besu.ethereum.core.Wei; import java.math.BigDecimal; import java.math.BigInteger; import org.web3j.utils.Convert; import org.web3j.utils.Convert.Unit; public class Amount { private BigDecimal value; private Unit unit; private Amount(final BigDecimal value, final Unit unit) { this.value = value; this.unit = unit; } public static Amount ether(final long value) { return new Amount(BigDecimal.valueOf(value), ETHER); } public static Amount wei(final BigInteger value) { return new Amount(new BigDecimal(value), WEI); } public static Amount wei(final Wei wei) { return wei(new BigInteger(wei.toUnprefixedHexString(), 16)); } public BigDecimal getValue() { return value; } public Unit getUnit() { return unit; } public Amount subtract(final Amount subtracting) { final Unit denominator; if (unit.getWeiFactor().compareTo(subtracting.unit.getWeiFactor()) < 0) { denominator = unit; } else { denominator = subtracting.unit; } final BigDecimal result = Convert.fromWei( Convert.toWei(value, unit).subtract(Convert.toWei(subtracting.value, subtracting.unit)), denominator); return new Amount(result, denominator); } }
1
20,673
We should not replace Wei with a type that is shared across multiple units. We need this as `Wei` for type and unit safety.
hyperledger-besu
java
@@ -653,8 +653,7 @@ func drupalEnsureWritePerms(app *DdevApp) error { for _, o := range makeWritable { stat, err := os.Stat(o) - // If the file doesn't exist, don't try to set the permissions. - if os.IsNotExist(err) { + if err != nil { continue }
1
package ddevapp import ( "fmt" "github.com/drud/ddev/pkg/appports" "github.com/drud/ddev/pkg/output" "github.com/drud/ddev/pkg/util" "io/ioutil" "os" "path" "path/filepath" "text/template" "github.com/drud/ddev/pkg/dockerutil" "github.com/drud/ddev/pkg/fileutil" "github.com/drud/ddev/pkg/archive" ) // DrupalSettings encapsulates all the configurations for a Drupal site. type DrupalSettings struct { DeployName string DeployURL string DatabaseName string DatabaseUsername string DatabasePassword string DatabaseHost string DatabaseDriver string DatabasePort string DatabasePrefix string HashSalt string Signature string SitePath string SiteSettings string SiteSettingsLocal string SyncDir string } // NewDrupalSettings produces a DrupalSettings object with default. func NewDrupalSettings() *DrupalSettings { return &DrupalSettings{ DatabaseName: "db", DatabaseUsername: "db", DatabasePassword: "db", DatabaseHost: "db", DatabaseDriver: "mysql", DatabasePort: appports.GetPort("db"), DatabasePrefix: "", HashSalt: util.RandString(64), Signature: DdevFileSignature, SitePath: path.Join("sites", "default"), SiteSettings: "settings.php", SiteSettingsLocal: "settings.ddev.php", SyncDir: path.Join("files", "sync"), } } // DrushConfig encapsulates configuration for a drush settings file. type DrushConfig struct { DatabasePort int DatabaseHost string } // NewDrushConfig produces a DrushConfig object with default. func NewDrushConfig(app *DdevApp) *DrushConfig { dockerIP, _ := dockerutil.GetDockerIP() dbPublishedPort, _ := app.GetPublishedPort("db") return &DrushConfig{ DatabaseHost: dockerIP, DatabasePort: dbPublishedPort, } } // drupal8SettingsTemplate defines the template that will become a Drupal 8 app's settings.php // in the event that one does not already exist. const drupal8SettingsTemplate = `<?php {{ $config := . }} // {{ $config.Signature }}: Automatically generated Drupal settings file. if (file_exists($app_root . '/' . $site_path . '/{{ $config.SiteSettingsLocal }}')) { include $app_root . '/' . $site_path . '/{{ $config.SiteSettingsLocal }}'; } ` // drupal8SettingsAppendTemplate defines the template that will be appended to // a Drupal 8 app's settings.php in the event that one exists. const drupal8SettingsAppendTemplate = `{{ $config := . }} // Automatically generated include for settings managed by ddev. if (file_exists($app_root . '/' . $site_path . '/{{ $config.SiteSettingsLocal }}')) { include $app_root . '/' . $site_path . '/{{ $config.SiteSettingsLocal }}'; } ` // drupal7SettingsTemplate defines the template that will become a Drupal 7 app's settings.php // in the event that one does not already exist. const drupal7SettingsTemplate = `<?php {{ $config := . }} // {{ $config.Signature }}: Automatically generated Drupal settings file. $ddev_settings = dirname(__FILE__) . '/{{ $config.SiteSettingsLocal }}'; if (is_readable($ddev_settings)) { require $ddev_settings; } ` // drupal7SettingsAppendTemplate defines the template that will be appended to // a Drupal 7 app's settings.php in the event that one exists. const drupal7SettingsAppendTemplate = `{{ $config := . }} // Automatically generated include for settings managed by ddev. $ddev_settings = dirname(__FILE__) . '/{{ $config.SiteSettingsLocal }}'; if (is_readable($ddev_settings)) { require $ddev_settings; } ` // drupal6SettingsTemplate defines the template that will become a Drupal 6 app's settings.php // in the event that one does not already exist. const drupal6SettingsTemplate = drupal7SettingsTemplate // drupal7SettingsAppendTemplate defines the template that will be appended to // a Drupal 7 app's settings.php in the event that one exists. const drupal6SettingsAppendTemplate = drupal7SettingsAppendTemplate const ( drupal8DdevSettingsTemplate = `<?php {{ $config := . }} /** {{ $config.Signature }}: Automatically generated Drupal settings file. ddev manages this file and may delete or overwrite the file unless this comment is removed. */ $databases['default']['default'] = array( 'database' => "{{ $config.DatabaseName }}", 'username' => "{{ $config.DatabaseUsername }}", 'password' => "{{ $config.DatabasePassword }}", 'host' => "{{ $config.DatabaseHost }}", 'driver' => "{{ $config.DatabaseDriver }}", 'port' => {{ $config.DatabasePort }}, 'prefix' => "{{ $config.DatabasePrefix }}", ); ini_set('session.gc_probability', 1); ini_set('session.gc_divisor', 100); ini_set('session.gc_maxlifetime', 200000); ini_set('session.cookie_lifetime', 2000000); $settings['hash_salt'] = '{{ $config.HashSalt }}'; $settings['file_scan_ignore_directories'] = [ 'node_modules', 'bower_components', ]; // This will prevent Drupal from setting read-only permissions on sites/default. $settings['skip_permissions_hardening'] = TRUE; // This will ensure the site can only be accessed through the intended host names. // Additional host patterns can be added for custom configurations. $settings['trusted_host_patterns'] = ['.*']; // This specifies the default configuration sync directory. if (empty($config_directories[CONFIG_SYNC_DIRECTORY])) { $config_directories[CONFIG_SYNC_DIRECTORY] = '{{ joinPath $config.SitePath $config.SyncDir }}'; } // This determines whether or not drush should include a custom settings file which allows // it to work both within a docker container and natively on the host system. $drush_settings = __DIR__ . '/ddev_drush_settings.php'; if (empty(getenv('DDEV_PHP_VERSION')) && file_exists($drush_settings)) { include $drush_settings; } ` ) const ( drupal7DdevSettingsTemplate = `<?php {{ $config := . }} /** {{ $config.Signature }}: Automatically generated Drupal settings file. ddev manages this file and may delete or overwrite the file unless this comment is removed. */ $databases['default']['default'] = array( 'database' => "{{ $config.DatabaseName }}", 'username' => "{{ $config.DatabaseUsername }}", 'password' => "{{ $config.DatabasePassword }}", 'host' => "{{ $config.DatabaseHost }}", 'driver' => "{{ $config.DatabaseDriver }}", 'port' => {{ $config.DatabasePort }}, 'prefix' => "{{ $config.DatabasePrefix }}", ); ini_set('session.gc_probability', 1); ini_set('session.gc_divisor', 100); ini_set('session.gc_maxlifetime', 200000); ini_set('session.cookie_lifetime', 2000000); $drupal_hash_salt = '{{ $config.HashSalt }}'; // This determines whether or not drush should include a custom settings file which allows // it to work both within a docker container and natively on the host system. $drush_settings = __DIR__ . '/ddev_drush_settings.php'; if (empty(getenv('DDEV_PHP_VERSION')) && file_exists($drush_settings)) { include $drush_settings; } ` ) const ( drupal6DdevSettingsTemplate = `<?php {{ $config := . }} /** {{ $config.Signature }}: Automatically generated Drupal settings file. ddev manages this file and may delete or overwrite the file unless this comment is removed. */ $db_url = '{{ $config.DatabaseDriver }}://{{ $config.DatabaseUsername }}:{{ $config.DatabasePassword }}@{{ $config.DatabaseHost }}:{{ $config.DatabasePort }}/{{ $config.DatabaseName }}'; ini_set('session.gc_probability', 1); ini_set('session.gc_divisor', 100); ini_set('session.gc_maxlifetime', 200000); ini_set('session.cookie_lifetime', 2000000); // This determines whether or not drush should include a custom settings file which allows // it to work both within a docker container and natively on the host system. $drush_settings = __DIR__ . '/ddev_drush_settings.php'; if (empty(getenv('DDEV_PHP_VERSION')) && file_exists($drush_settings)) { include $drush_settings; } ` ) const drushTemplate = `<?php {{ $config := . }} $version = ""; if (defined("\Drupal::VERSION")) { $version = \Drupal::VERSION; } else if (defined("VERSION")) { $version = VERSION; } // Use the array format for D7+ if (version_compare($version, "7.0") > 0) { $databases['default']['default'] = array( 'database' => "db", 'username' => "db", 'password' => "db", 'host' => "{{ $config.DatabaseHost }}", 'driver' => "mysql", 'port' => {{ $config.DatabasePort }}, 'prefix' => "", ); } else { // or the old db_url format for d6 $db_url = 'mysql://db:db@{{ $config.DatabaseHost }}:{{ $config.DatabasePort }}/db'; } ` // manageDrupalSettingsFile will direct inspecting and writing of settings.php. func manageDrupalSettingsFile(app *DdevApp, drupalConfig *DrupalSettings, settingsTemplate, appendTemplate string) error { // We'll be writing/appending to the settings files and parent directory, make sure we have permissions to do so if err := drupalEnsureWritePerms(app); err != nil { return err } if !fileutil.FileExists(app.SiteSettingsPath) { output.UserOut.Printf("No %s file exists, creating one", drupalConfig.SiteSettings) if err := writeDrupalSettingsFile(drupalConfig, app.SiteSettingsPath, settingsTemplate); err != nil { return fmt.Errorf("failed to write %s: %v", app.SiteSettingsPath, err) } } included, err := settingsHasInclude(drupalConfig, app.SiteSettingsPath) if err != nil { return fmt.Errorf("failed to check for include in %s: %v", app.SiteSettingsPath, err) } if included { output.UserOut.Printf("Existing %s file includes %s", drupalConfig.SiteSettings, drupalConfig.SiteSettingsLocal) } else { output.UserOut.Printf("Existing %s file does not include %s, modifying to include ddev settings", drupalConfig.SiteSettings, drupalConfig.SiteSettingsLocal) if err := appendIncludeToDrupalSettingsFile(drupalConfig, app.SiteSettingsPath, appendTemplate); err != nil { return fmt.Errorf("failed to include %s in %s: %v", drupalConfig.SiteSettingsLocal, drupalConfig.SiteSettings, err) } } return nil } // writeDrupalSettingsFile creates the app's settings.php or equivalent, // which does nothing more than import the ddev-managed settings.ddev.php. func writeDrupalSettingsFile(drupalConfig *DrupalSettings, filePath string, versionTemplate string) error { tmpl, err := template.New("settings").Funcs(getTemplateFuncMap()).Parse(versionTemplate) if err != nil { return err } // Ensure target directory exists and is writable dir := filepath.Dir(filePath) if err = os.Chmod(dir, 0755); os.IsNotExist(err) { if err = os.MkdirAll(dir, 0755); err != nil { return err } } else if err != nil { return err } // Create file file, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE, 0644) if err != nil { return err } defer util.CheckClose(file) if err := tmpl.Execute(file, drupalConfig); err != nil { return err } return nil } // createDrupal7SettingsFile manages creation and modification of settings.php and settings.ddev.php. // If a settings.php file already exists, it will be modified to ensure that it includes // settings.ddev.php, which contains ddev-specific configuration. func createDrupal7SettingsFile(app *DdevApp) (string, error) { // Currently there isn't any customization done for the drupal config, but // we may want to do some kind of customization in the future. drupalConfig := NewDrupalSettings() if err := manageDrupalSettingsFile(app, drupalConfig, drupal7SettingsTemplate, drupal7SettingsAppendTemplate); err != nil { return "", err } if err := writeDrupal7DdevSettingsFile(drupalConfig, app.SiteLocalSettingsPath); err != nil { return "", fmt.Errorf("failed to write Drupal settings file %s: %v", app.SiteLocalSettingsPath, err) } return app.SiteLocalSettingsPath, nil } // createDrupal8SettingsFile manages creation and modification of settings.php and settings.ddev.php. // If a settings.php file already exists, it will be modified to ensure that it includes // settings.ddev.php, which contains ddev-specific configuration. func createDrupal8SettingsFile(app *DdevApp) (string, error) { // Currently there isn't any customization done for the drupal config, but // we may want to do some kind of customization in the future. drupalConfig := NewDrupalSettings() if err := manageDrupalSettingsFile(app, drupalConfig, drupal8SettingsTemplate, drupal8SettingsAppendTemplate); err != nil { return "", err } if err := writeDrupal8DdevSettingsFile(drupalConfig, app.SiteLocalSettingsPath); err != nil { return "", fmt.Errorf("failed to write Drupal settings file %s: %v", app.SiteLocalSettingsPath, err) } return app.SiteLocalSettingsPath, nil } // createDrupal6SettingsFile manages creation and modification of settings.php and settings.ddev.php. // If a settings.php file already exists, it will be modified to ensure that it includes // settings.ddev.php, which contains ddev-specific configuration. func createDrupal6SettingsFile(app *DdevApp) (string, error) { // Currently there isn't any customization done for the drupal config, but // we may want to do some kind of customization in the future. drupalConfig := NewDrupalSettings() if err := manageDrupalSettingsFile(app, drupalConfig, drupal6SettingsTemplate, drupal6SettingsAppendTemplate); err != nil { return "", err } if err := writeDrupal6DdevSettingsFile(drupalConfig, app.SiteLocalSettingsPath); err != nil { return "", fmt.Errorf("failed to write Drupal settings file %s: %v", app.SiteLocalSettingsPath, err) } return app.SiteLocalSettingsPath, nil } // writeDrupal8DdevSettingsFile dynamically produces valid settings.ddev.php file by combining a configuration // object with a data-driven template. func writeDrupal8DdevSettingsFile(settings *DrupalSettings, filePath string) error { tmpl, err := template.New("settings").Funcs(getTemplateFuncMap()).Parse(drupal8DdevSettingsTemplate) if err != nil { return err } // Ensure target directory exists and is writable dir := filepath.Dir(filePath) if err = os.Chmod(dir, 0755); os.IsNotExist(err) { if err = os.MkdirAll(dir, 0755); err != nil { return err } } else if err != nil { return err } file, err := os.Create(filePath) if err != nil { return err } defer util.CheckClose(file) if err := tmpl.Execute(file, settings); err != nil { return err } return nil } // writeDrupal7DdevSettingsFile dynamically produces valid settings.ddev.php file by combining a configuration // object with a data-driven template. func writeDrupal7DdevSettingsFile(settings *DrupalSettings, filePath string) error { tmpl, err := template.New("settings").Funcs(getTemplateFuncMap()).Parse(drupal7DdevSettingsTemplate) if err != nil { return err } // Ensure target directory exists and is writable dir := filepath.Dir(filePath) if err = os.Chmod(dir, 0755); os.IsNotExist(err) { if err = os.MkdirAll(dir, 0755); err != nil { return err } } else if err != nil { return err } file, err := os.Create(filePath) if err != nil { return err } err = tmpl.Execute(file, settings) if err != nil { return err } util.CheckClose(file) return nil } // writeDrupal6DdevSettingsFile dynamically produces valid settings.ddev.php file by combining a configuration // object with a data-driven template. func writeDrupal6DdevSettingsFile(settings *DrupalSettings, filePath string) error { tmpl, err := template.New("settings").Funcs(getTemplateFuncMap()).Parse(drupal6DdevSettingsTemplate) if err != nil { return err } // Ensure target directory exists and is writable dir := filepath.Dir(filePath) if err = os.Chmod(dir, 0755); os.IsNotExist(err) { if err = os.MkdirAll(dir, 0755); err != nil { return err } } else if err != nil { return err } file, err := os.Create(filePath) if err != nil { return err } err = tmpl.Execute(file, settings) if err != nil { return err } util.CheckClose(file) return nil } // WriteDrushConfig writes out a drush config based on passed-in values. func WriteDrushConfig(drushConfig *DrushConfig, filePath string) error { tmpl, err := template.New("drushConfig").Funcs(getTemplateFuncMap()).Parse(drushTemplate) if err != nil { return err } // Ensure target directory exists and is writable dir := filepath.Dir(filePath) if err = os.Chmod(dir, 0755); os.IsNotExist(err) { if err = os.MkdirAll(dir, 0755); err != nil { return err } } else if err != nil { return err } file, err := os.Create(filePath) if err != nil { return err } err = tmpl.Execute(file, drushConfig) if err != nil { return err } util.CheckClose(file) return nil } // getDrupalUploadDir will return a custom upload dir if defined, returning a default path if not. func getDrupalUploadDir(app *DdevApp) string { if app.UploadDir == "" { return "sites/default/files" } return app.UploadDir } // Drupal8Hooks adds a d8-specific hooks example for post-import-db const Drupal8Hooks = ` # post-import-db: # - exec: drush cr # - exec: drush updb ` // Drupal7Hooks adds a d7-specific hooks example for post-import-db const Drupal7Hooks = ` # post-import-db: # - exec: drush cc all` // getDrupal7Hooks for appending as byte array func getDrupal7Hooks() []byte { return []byte(Drupal7Hooks) } // getDrupal6Hooks for appending as byte array func getDrupal6Hooks() []byte { // We don't have anything new to add yet, so just use Drupal7 version return []byte(Drupal7Hooks) } // getDrupal8Hooks for appending as byte array func getDrupal8Hooks() []byte { return []byte(Drupal8Hooks) } // setDrupalSiteSettingsPaths sets the paths to settings.php/settings.ddev.php // for templating. func setDrupalSiteSettingsPaths(app *DdevApp) { drupalConfig := NewDrupalSettings() settingsFileBasePath := filepath.Join(app.AppRoot, app.Docroot) app.SiteSettingsPath = filepath.Join(settingsFileBasePath, drupalConfig.SitePath, drupalConfig.SiteSettings) app.SiteLocalSettingsPath = filepath.Join(settingsFileBasePath, drupalConfig.SitePath, drupalConfig.SiteSettingsLocal) } // isDrupal7App returns true if the app is of type drupal7 func isDrupal7App(app *DdevApp) bool { if _, err := os.Stat(filepath.Join(app.AppRoot, app.Docroot, "misc/ajax.js")); err == nil { return true } return false } // isDrupal8App returns true if the app is of type drupal8 func isDrupal8App(app *DdevApp) bool { if _, err := os.Stat(filepath.Join(app.AppRoot, app.Docroot, "core/scripts/drupal.sh")); err == nil { return true } return false } // isDrupal6App returns true if the app is of type Drupal6 func isDrupal6App(app *DdevApp) bool { if _, err := os.Stat(filepath.Join(app.AppRoot, app.Docroot, "misc/ahah.js")); err == nil { return true } return false } // drupal7ConfigOverrideAction sets a safe php_version for D7 func drupal7ConfigOverrideAction(app *DdevApp) error { app.PHPVersion = PHP71 return nil } // drupal6ConfigOverrideAction overrides php_version for D6, since it is incompatible // with php7+ func drupal6ConfigOverrideAction(app *DdevApp) error { app.PHPVersion = PHP56 return nil } // drupal8PostStartAction handles default post-start actions for D8 apps, like ensuring // useful permissions settings on sites/default. func drupal8PostStartAction(app *DdevApp) error { if err := createDrupal8SyncDir(app); err != nil { return err } if err := drupalEnsureWritePerms(app); err != nil { return err } // Drush config has to be written after start because we don't know the ports until it's started drushConfig := NewDrushConfig(app) err := WriteDrushConfig(drushConfig, filepath.Join(filepath.Dir(app.SiteSettingsPath), "ddev_drush_settings.php")) if err != nil { util.Warning("Failed to WriteDrushConfig: %v", err) } return nil } // drupal7PostStartAction handles default post-start actions for D7 apps, like ensuring // useful permissions settings on sites/default. func drupal7PostStartAction(app *DdevApp) error { if err := drupalEnsureWritePerms(app); err != nil { return err } // Drush config has to be written after start because we don't know the ports until it's started drushConfig := NewDrushConfig(app) err := WriteDrushConfig(drushConfig, filepath.Join(filepath.Dir(app.SiteSettingsPath), "ddev_drush_settings.php")) if err != nil { util.Warning("Failed to WriteDrushConfig: %v", err) } return nil } // drupal6PostStartAction handles default post-start actions for D6 apps, like ensuring // useful permissions settings on sites/default. func drupal6PostStartAction(app *DdevApp) error { if err := drupalEnsureWritePerms(app); err != nil { return err } // Drush config has to be written after start because we don't know the ports until it's started drushConfig := NewDrushConfig(app) err := WriteDrushConfig(drushConfig, filepath.Join(filepath.Dir(app.SiteSettingsPath), "ddev_drush_settings.php")) if err != nil { util.Warning("Failed to WriteDrushConfig: %v", err) } return nil } // drupalEnsureWritePerms will ensure sites/default and sites/default/settings.php will // have the appropriate permissions for development. func drupalEnsureWritePerms(app *DdevApp) error { output.UserOut.Printf("Ensuring write permissions for %s", app.GetName()) var writePerms os.FileMode = 0200 settingsDir := path.Dir(app.SiteSettingsPath) makeWritable := []string{ settingsDir, app.SiteSettingsPath, app.SiteLocalSettingsPath, path.Join(settingsDir, "services.yml"), } for _, o := range makeWritable { stat, err := os.Stat(o) // If the file doesn't exist, don't try to set the permissions. if os.IsNotExist(err) { continue } if err := os.Chmod(o, stat.Mode()|writePerms); err != nil { // Warn the user, but continue. util.Warning("Unable to set permissions: %v", err) } } return nil } // createDrupal8SyncDir creates a Drupal 8 app's sync directory func createDrupal8SyncDir(app *DdevApp) error { // Currently there isn't any customization done for the drupal config, but // we may want to do some kind of customization in the future. drupalConfig := NewDrupalSettings() syncDirPath := path.Join(app.GetAppRoot(), app.GetDocroot(), drupalConfig.SyncDir) if fileutil.FileExists(syncDirPath) { return nil } if err := os.MkdirAll(syncDirPath, 0755); err != nil { return fmt.Errorf("failed to create sync directory (%s): %v", syncDirPath, err) } return nil } // settingsHasInclude determines if the settings.php or equivalent includes settings.ddev.php or equivalent. // This is done by looking for the ddev settings file (settings.ddev.php) in settings.php. func settingsHasInclude(drupalConfig *DrupalSettings, siteSettingsPath string) (bool, error) { included, err := fileutil.FgrepStringInFile(siteSettingsPath, drupalConfig.SiteSettingsLocal) if err != nil { return false, err } return included, nil } // appendIncludeToDrupalSettingsFile modifies the settings.php file to include the settings.ddev.php // file, which contains ddev-specific configuration. func appendIncludeToDrupalSettingsFile(drupalConfig *DrupalSettings, siteSettingsPath string, appendTemplate string) error { // Check if file is empty contents, err := ioutil.ReadFile(siteSettingsPath) if err != nil { return err } // If the file is empty, write the complete settings template and return if len(contents) == 0 { return writeDrupalSettingsFile(drupalConfig, siteSettingsPath, appendTemplate) } // The file is not empty, open it for appending file, err := os.OpenFile(siteSettingsPath, os.O_RDWR|os.O_APPEND, 0644) if err != nil { return err } defer util.CheckClose(file) tmpl, err := template.New("settings").Funcs(getTemplateFuncMap()).Parse(appendTemplate) if err != nil { return err } // Write the template to the file if err := tmpl.Execute(file, drupalConfig); err != nil { return err } return nil } // drupalImportFilesAction defines the Drupal workflow for importing project files. func drupalImportFilesAction(app *DdevApp, importPath, extPath string) error { destPath := filepath.Join(app.GetAppRoot(), app.GetDocroot(), app.GetUploadDir()) // parent of destination dir should exist if !fileutil.FileExists(filepath.Dir(destPath)) { return fmt.Errorf("unable to import to %s: parent directory does not exist", destPath) } // parent of destination dir should be writable. if err := os.Chmod(filepath.Dir(destPath), 0755); err != nil { return err } // If the destination path exists, remove it as was warned if fileutil.FileExists(destPath) { if err := os.RemoveAll(destPath); err != nil { return fmt.Errorf("failed to cleanup %s before import: %v", destPath, err) } } if isTar(importPath) { if err := archive.Untar(importPath, destPath, extPath); err != nil { return fmt.Errorf("failed to extract provided archive: %v", err) } return nil } if isZip(importPath) { if err := archive.Unzip(importPath, destPath, extPath); err != nil { return fmt.Errorf("failed to extract provided archive: %v", err) } return nil } if err := fileutil.CopyDir(importPath, destPath); err != nil { return err } return nil }
1
13,138
I'm pretty sure this should emit a util.Warning*(), since we're skipping by here and never hitting anything that will give them a warning about what's happened.
drud-ddev
go
@@ -23,6 +23,12 @@ type aspParser struct { // newAspParser creates and returns a new asp.Parser. func newAspParser(state *core.BuildState) *asp.Parser { + p := GetParserWithBuiltins(state) + return p +} + +// GetParserWithBuiltins returns a asp.Parser object with all the builtins loaded +func GetParserWithBuiltins(state *core.BuildState) *asp.Parser { p := asp.NewParser(state) log.Debug("Loading built-in build rules...") dir, _ := rules.AssetDir("")
1
package parse import ( "fmt" "io" "sort" "strings" "core" "parse/asp" "parse/rules" ) // InitParser initialises the parser engine. This is guaranteed to be called exactly once before any calls to Parse(). func InitParser(state *core.BuildState) { state.Parser = &aspParser{asp: newAspParser(state)} } // An aspParser implements the core.Parser interface around our asp package. type aspParser struct { asp *asp.Parser } // newAspParser creates and returns a new asp.Parser. func newAspParser(state *core.BuildState) *asp.Parser { p := asp.NewParser(state) log.Debug("Loading built-in build rules...") dir, _ := rules.AssetDir("") sort.Strings(dir) for _, filename := range dir { if strings.HasSuffix(filename, ".gob") { srcFile := strings.TrimSuffix(filename, ".gob") src, _ := rules.Asset(srcFile) p.MustLoadBuiltins("src/parse/rules/"+srcFile, src, rules.MustAsset(filename)) } } for _, preload := range state.Config.Parse.PreloadBuildDefs { log.Debug("Preloading build defs from %s...", preload) p.MustLoadBuiltins(preload, nil, nil) } log.Debug("Parser initialised") return p } func (p *aspParser) ParseFile(state *core.BuildState, pkg *core.Package, filename string) error { return p.asp.ParseFile(pkg, filename) } func (p *aspParser) ParseReader(state *core.BuildState, pkg *core.Package, reader io.ReadSeeker) error { _, err := p.asp.ParseReader(pkg, reader) return err } func (p *aspParser) UndeferAnyParses(state *core.BuildState, target *core.BuildTarget) { } func (p *aspParser) RunPreBuildFunction(threadID int, state *core.BuildState, target *core.BuildTarget) error { return p.runBuildFunction(threadID, state, target, "pre", func() error { return target.PreBuildFunction.Call(target) }) } func (p *aspParser) RunPostBuildFunction(threadID int, state *core.BuildState, target *core.BuildTarget, output string) error { return p.runBuildFunction(threadID, state, target, "post", func() error { log.Debug("Running post-build function for %s. Build output:\n%s", target.Label, output) return target.PostBuildFunction.Call(target, output) }) } // runBuildFunction runs either the pre- or post-build function. func (p *aspParser) runBuildFunction(tid int, state *core.BuildState, target *core.BuildTarget, callbackType string, f func() error) error { state.LogBuildResult(tid, target.Label, core.PackageParsing, fmt.Sprintf("Running %s-build function for %s", callbackType, target.Label)) pkg := state.Graph.PackageByLabel(target.Label) changed, err := pkg.EnterBuildCallback(f) if err != nil { state.LogBuildError(tid, target.Label, core.ParseFailed, err, "Failed %s-build function for %s", callbackType, target.Label) } else { rescanDeps(state, changed) state.LogBuildResult(tid, target.Label, core.TargetBuilding, fmt.Sprintf("Finished %s-build function for %s", callbackType, target.Label)) } return err }
1
8,435
This function isn't useful? it's just a clone of GetParserWithBuiltins?
thought-machine-please
go
@@ -229,9 +229,13 @@ public class SolrConfig extends XmlConfigFile implements MapSerializable { enableLazyFieldLoading = getBool("query/enableLazyFieldLoading", false); useCircuitBreakers = getBool("circuitBreaker/useCircuitBreakers", false); + isCpuCircuitBreakerEnabled = getBool("circuitBreaker/isCpuCircuitBreakerEnabled", false); + isMemoryCircuitBreakerEnabled = getBool("circuitBreaker/isMemoryCircuitBreakerEnabled", false); memoryCircuitBreakerThresholdPct = getInt("circuitBreaker/memoryCircuitBreakerThresholdPct", 95); - validateMemoryBreakerThreshold(); + cpuCircuitBreakerThreshold = getInt("circuitBreaker/cpuCircuitBreakerThreshold", 95); + + validateCircuitBreakerThresholds(); filterCacheConfig = CacheConfig.getConfig(this, "query/filterCache"); queryResultCacheConfig = CacheConfig.getConfig(this, "query/queryResultCache");
1
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.solr.core; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPathConstants; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.invoke.MethodHandles; import java.net.MalformedURLException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.text.ParseException; import java.util.ArrayList; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.google.common.collect.ImmutableList; import org.apache.commons.io.FileUtils; import org.apache.lucene.index.IndexDeletionPolicy; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.util.Version; import org.apache.solr.client.solrj.io.stream.expr.Expressible; import org.apache.solr.cloud.RecoveryStrategy; import org.apache.solr.cloud.ZkSolrResourceLoader; import org.apache.solr.common.MapSerializable; import org.apache.solr.common.SolrException; import org.apache.solr.common.SolrException.ErrorCode; import org.apache.solr.common.util.IOUtils; import org.apache.solr.handler.component.SearchComponent; import org.apache.solr.pkg.PackageListeners; import org.apache.solr.pkg.PackageLoader; import org.apache.solr.request.SolrRequestHandler; import org.apache.solr.response.QueryResponseWriter; import org.apache.solr.response.transform.TransformerFactory; import org.apache.solr.rest.RestManager; import org.apache.solr.schema.IndexSchema; import org.apache.solr.schema.IndexSchemaFactory; import org.apache.solr.search.CacheConfig; import org.apache.solr.search.CaffeineCache; import org.apache.solr.search.QParserPlugin; import org.apache.solr.search.SolrCache; import org.apache.solr.search.ValueSourceParser; import org.apache.solr.search.stats.StatsCache; import org.apache.solr.servlet.SolrRequestParsers; import org.apache.solr.spelling.QueryConverter; import org.apache.solr.update.SolrIndexConfig; import org.apache.solr.update.UpdateLog; import org.apache.solr.update.processor.UpdateRequestProcessorChain; import org.apache.solr.update.processor.UpdateRequestProcessorFactory; import org.apache.solr.util.DOMUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import static org.apache.solr.common.params.CommonParams.NAME; import static org.apache.solr.common.params.CommonParams.PATH; import static org.apache.solr.common.util.Utils.fromJSON; import static org.apache.solr.common.util.Utils.makeMap; import static org.apache.solr.core.ConfigOverlay.ZNODEVER; import static org.apache.solr.core.SolrConfig.PluginOpts.LAZY; import static org.apache.solr.core.SolrConfig.PluginOpts.MULTI_OK; import static org.apache.solr.core.SolrConfig.PluginOpts.NOOP; import static org.apache.solr.core.SolrConfig.PluginOpts.REQUIRE_CLASS; import static org.apache.solr.core.SolrConfig.PluginOpts.REQUIRE_NAME; import static org.apache.solr.core.SolrConfig.PluginOpts.REQUIRE_NAME_IN_OVERLAY; /** * Provides a static reference to a Config object modeling the main * configuration data for a Solr instance -- typically found in * "solrconfig.xml". */ public class SolrConfig extends XmlConfigFile implements MapSerializable { private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); public static final String DEFAULT_CONF_FILE = "solrconfig.xml"; private RequestParams requestParams; public enum PluginOpts { MULTI_OK, REQUIRE_NAME, REQUIRE_NAME_IN_OVERLAY, REQUIRE_CLASS, LAZY, // EnumSet.of and/or EnumSet.copyOf(Collection) are annoying // because of type determination NOOP } private int multipartUploadLimitKB; private int formUploadLimitKB; private boolean enableRemoteStreams; private boolean enableStreamBody; private boolean handleSelect; private boolean addHttpRequestToContext; private final SolrRequestParsers solrRequestParsers; /** * TEST-ONLY: Creates a configuration instance from an instance directory and file name * @param instanceDir the directory used to create the resource loader * @param name the configuration name used by the loader if the stream is null */ public SolrConfig(Path instanceDir, String name) throws ParserConfigurationException, IOException, SAXException { this(new SolrResourceLoader(instanceDir), name, true, null); } public static SolrConfig readFromResourceLoader(SolrResourceLoader loader, String name, boolean isConfigsetTrusted, Properties substitutableProperties) { try { return new SolrConfig(loader, name, isConfigsetTrusted, substitutableProperties); } catch (Exception e) { String resource; if (loader instanceof ZkSolrResourceLoader) { resource = name; } else { resource = Paths.get(loader.getConfigDir()).resolve(name).toString(); } throw new SolrException(ErrorCode.SERVER_ERROR, "Error loading solr config from " + resource, e); } } /** * Creates a configuration instance from a resource loader, a configuration name and a stream. * If the stream is null, the resource loader will open the configuration stream. * If the stream is not null, no attempt to load the resource will occur (the name is not used). * @param loader the resource loader * @param name the configuration name * @param isConfigsetTrusted false if configset was uploaded using unsecured configset upload API, true otherwise * @param substitutableProperties optional properties to substitute into the XML */ private SolrConfig(SolrResourceLoader loader, String name, boolean isConfigsetTrusted, Properties substitutableProperties) throws ParserConfigurationException, IOException, SAXException { // insist we have non-null substituteProperties; it might get overlayed super(loader, name, null, "/config/", substitutableProperties == null ? new Properties() : substitutableProperties); getOverlay();//just in case it is not initialized getRequestParams(); initLibs(loader, isConfigsetTrusted); luceneMatchVersion = SolrConfig.parseLuceneVersionString(getVal(IndexSchema.LUCENE_MATCH_VERSION_PARAM, true)); log.info("Using Lucene MatchVersion: {}", luceneMatchVersion); String indexConfigPrefix; // Old indexDefaults and mainIndex sections are deprecated and fails fast for luceneMatchVersion=>LUCENE_4_0_0. // For older solrconfig.xml's we allow the old sections, but never mixed with the new <indexConfig> boolean hasDeprecatedIndexConfig = (getNode("indexDefaults", false) != null) || (getNode("mainIndex", false) != null); if (hasDeprecatedIndexConfig) { throw new SolrException(ErrorCode.FORBIDDEN, "<indexDefaults> and <mainIndex> configuration sections are discontinued. Use <indexConfig> instead."); } else { indexConfigPrefix = "indexConfig"; } assertWarnOrFail("The <nrtMode> config has been discontinued and NRT mode is always used by Solr." + " This config will be removed in future versions.", getNode(indexConfigPrefix + "/nrtMode", false) == null, true ); assertWarnOrFail("Solr no longer supports forceful unlocking via the 'unlockOnStartup' option. "+ "This is no longer necessary for the default lockType except in situations where "+ "it would be dangerous and should not be done. For other lockTypes and/or "+ "directoryFactory options it may also be dangerous and users must resolve "+ "problematic locks manually.", null == getNode(indexConfigPrefix + "/unlockOnStartup", false), true // 'fail' in trunk ); // Parse indexConfig section, using mainIndex as backup in case old config is used indexConfig = new SolrIndexConfig(this, "indexConfig", null); booleanQueryMaxClauseCount = getInt("query/maxBooleanClauses", IndexSearcher.getMaxClauseCount()); if (IndexSearcher.getMaxClauseCount() < booleanQueryMaxClauseCount) { log.warn("solrconfig.xml: <maxBooleanClauses> of {} is greater than global limit of {} {}" , booleanQueryMaxClauseCount, IndexSearcher.getMaxClauseCount() , "and will have no effect set 'maxBooleanClauses' in solr.xml to increase global limit"); } // Warn about deprecated / discontinued parameters // boolToFilterOptimizer has had no effect since 3.1 if (get("query/boolTofilterOptimizer", null) != null) log.warn("solrconfig.xml: <boolTofilterOptimizer> is currently not implemented and has no effect."); if (get("query/HashDocSet", null) != null) log.warn("solrconfig.xml: <HashDocSet> is deprecated and no longer used."); // TODO: Old code - in case somebody wants to re-enable. Also see SolrIndexSearcher#search() // filtOptEnabled = getBool("query/boolTofilterOptimizer/@enabled", false); // filtOptCacheSize = getInt("query/boolTofilterOptimizer/@cacheSize",32); // filtOptThreshold = getFloat("query/boolTofilterOptimizer/@threshold",.05f); useFilterForSortedQuery = getBool("query/useFilterForSortedQuery", false); queryResultWindowSize = Math.max(1, getInt("query/queryResultWindowSize", 1)); queryResultMaxDocsCached = getInt("query/queryResultMaxDocsCached", Integer.MAX_VALUE); enableLazyFieldLoading = getBool("query/enableLazyFieldLoading", false); useCircuitBreakers = getBool("circuitBreaker/useCircuitBreakers", false); memoryCircuitBreakerThresholdPct = getInt("circuitBreaker/memoryCircuitBreakerThresholdPct", 95); validateMemoryBreakerThreshold(); filterCacheConfig = CacheConfig.getConfig(this, "query/filterCache"); queryResultCacheConfig = CacheConfig.getConfig(this, "query/queryResultCache"); documentCacheConfig = CacheConfig.getConfig(this, "query/documentCache"); CacheConfig conf = CacheConfig.getConfig(this, "query/fieldValueCache"); if (conf == null) { Map<String, String> args = new HashMap<>(); args.put(NAME, "fieldValueCache"); args.put("size", "10000"); args.put("initialSize", "10"); args.put("showItems", "-1"); conf = new CacheConfig(CaffeineCache.class, args, null); } fieldValueCacheConfig = conf; useColdSearcher = getBool("query/useColdSearcher", false); dataDir = get("dataDir", null); if (dataDir != null && dataDir.length() == 0) dataDir = null; org.apache.solr.search.SolrIndexSearcher.initRegenerators(this); if (get("jmx", null) != null) { log.warn("solrconfig.xml: <jmx> is no longer supported, use solr.xml:/metrics/reporter section instead"); } httpCachingConfig = new HttpCachingConfig(this); maxWarmingSearchers = getInt("query/maxWarmingSearchers", 1); slowQueryThresholdMillis = getInt("query/slowQueryThresholdMillis", -1); for (SolrPluginInfo plugin : plugins) loadPluginInfo(plugin); Map<String, CacheConfig> userCacheConfigs = CacheConfig.getMultipleConfigs(this, "query/cache"); List<PluginInfo> caches = getPluginInfos(SolrCache.class.getName()); if (!caches.isEmpty()) { for (PluginInfo c : caches) { userCacheConfigs.put(c.name, CacheConfig.getConfig(this, "cache", c.attributes, null)); } } this.userCacheConfigs = Collections.unmodifiableMap(userCacheConfigs); updateHandlerInfo = loadUpdatehandlerInfo(); multipartUploadLimitKB = getInt( "requestDispatcher/requestParsers/@multipartUploadLimitInKB", Integer.MAX_VALUE); if (multipartUploadLimitKB == -1) multipartUploadLimitKB = Integer.MAX_VALUE; formUploadLimitKB = getInt( "requestDispatcher/requestParsers/@formdataUploadLimitInKB", Integer.MAX_VALUE); if (formUploadLimitKB == -1) formUploadLimitKB = Integer.MAX_VALUE; enableRemoteStreams = getBool( "requestDispatcher/requestParsers/@enableRemoteStreaming", false); enableStreamBody = getBool( "requestDispatcher/requestParsers/@enableStreamBody", false); handleSelect = getBool( "requestDispatcher/@handleSelect", false); addHttpRequestToContext = getBool( "requestDispatcher/requestParsers/@addHttpRequestToContext", false); List<PluginInfo> argsInfos = getPluginInfos(InitParams.class.getName()); if (argsInfos != null) { Map<String, InitParams> argsMap = new HashMap<>(); for (PluginInfo p : argsInfos) { InitParams args = new InitParams(p); argsMap.put(args.name == null ? String.valueOf(args.hashCode()) : args.name, args); } this.initParams = Collections.unmodifiableMap(argsMap); } solrRequestParsers = new SolrRequestParsers(this); log.debug("Loaded SolrConfig: {}", name); } private static final AtomicBoolean versionWarningAlreadyLogged = new AtomicBoolean(false); public static final Version parseLuceneVersionString(final String matchVersion) { final Version version; try { version = Version.parseLeniently(matchVersion); } catch (ParseException pe) { throw new SolrException(ErrorCode.SERVER_ERROR, "Invalid luceneMatchVersion. Should be of the form 'V.V.V' (e.g. 4.8.0)", pe); } if (version == Version.LATEST && !versionWarningAlreadyLogged.getAndSet(true)) { log.warn("You should not use LATEST as luceneMatchVersion property: " + "if you use this setting, and then Solr upgrades to a newer release of Lucene, " + "sizable changes may happen. If precise back compatibility is important " + "then you should instead explicitly specify an actual Lucene version."); } return version; } public static final List<SolrPluginInfo> plugins = ImmutableList.<SolrPluginInfo>builder() .add(new SolrPluginInfo(SolrRequestHandler.class, SolrRequestHandler.TYPE, REQUIRE_NAME, REQUIRE_CLASS, MULTI_OK, LAZY)) .add(new SolrPluginInfo(QParserPlugin.class, "queryParser", REQUIRE_NAME, REQUIRE_CLASS, MULTI_OK)) .add(new SolrPluginInfo(Expressible.class, "expressible", REQUIRE_NAME, REQUIRE_CLASS, MULTI_OK)) .add(new SolrPluginInfo(QueryResponseWriter.class, "queryResponseWriter", REQUIRE_NAME, REQUIRE_CLASS, MULTI_OK, LAZY)) .add(new SolrPluginInfo(ValueSourceParser.class, "valueSourceParser", REQUIRE_NAME, REQUIRE_CLASS, MULTI_OK)) .add(new SolrPluginInfo(TransformerFactory.class, "transformer", REQUIRE_NAME, REQUIRE_CLASS, MULTI_OK)) .add(new SolrPluginInfo(SearchComponent.class, "searchComponent", REQUIRE_NAME, REQUIRE_CLASS, MULTI_OK)) .add(new SolrPluginInfo(UpdateRequestProcessorFactory.class, "updateProcessor", REQUIRE_NAME, REQUIRE_CLASS, MULTI_OK)) .add(new SolrPluginInfo(SolrCache.class, "cache", REQUIRE_NAME, REQUIRE_CLASS, MULTI_OK)) // TODO: WTF is up with queryConverter??? // it apparently *only* works as a singleton? - SOLR-4304 // and even then -- only if there is a single SpellCheckComponent // because of queryConverter.setIndexAnalyzer .add(new SolrPluginInfo(QueryConverter.class, "queryConverter", REQUIRE_NAME, REQUIRE_CLASS)) // this is hackish, since it picks up all SolrEventListeners, // regardless of when/how/why they are used (or even if they are // declared outside of the appropriate context) but there's no nice // way around that in the PluginInfo framework .add(new SolrPluginInfo(InitParams.class, InitParams.TYPE, MULTI_OK, REQUIRE_NAME_IN_OVERLAY)) .add(new SolrPluginInfo(SolrEventListener.class, "//listener", REQUIRE_CLASS, MULTI_OK, REQUIRE_NAME_IN_OVERLAY)) .add(new SolrPluginInfo(DirectoryFactory.class, "directoryFactory", REQUIRE_CLASS)) .add(new SolrPluginInfo(RecoveryStrategy.Builder.class, "recoveryStrategy")) .add(new SolrPluginInfo(IndexDeletionPolicy.class, "indexConfig/deletionPolicy", REQUIRE_CLASS)) .add(new SolrPluginInfo(CodecFactory.class, "codecFactory", REQUIRE_CLASS)) .add(new SolrPluginInfo(IndexReaderFactory.class, "indexReaderFactory", REQUIRE_CLASS)) .add(new SolrPluginInfo(UpdateRequestProcessorChain.class, "updateRequestProcessorChain", MULTI_OK)) .add(new SolrPluginInfo(UpdateLog.class, "updateHandler/updateLog")) .add(new SolrPluginInfo(IndexSchemaFactory.class, "schemaFactory", REQUIRE_CLASS)) .add(new SolrPluginInfo(RestManager.class, "restManager")) .add(new SolrPluginInfo(StatsCache.class, "statsCache", REQUIRE_CLASS)) .build(); public static final Map<String, SolrPluginInfo> classVsSolrPluginInfo; static { Map<String, SolrPluginInfo> map = new HashMap<>(); for (SolrPluginInfo plugin : plugins) map.put(plugin.clazz.getName(), plugin); classVsSolrPluginInfo = Collections.unmodifiableMap(map); } public static class SolrPluginInfo { @SuppressWarnings({"rawtypes"}) public final Class clazz; public final String tag; public final Set<PluginOpts> options; @SuppressWarnings({"unchecked", "rawtypes"}) private SolrPluginInfo(Class clz, String tag, PluginOpts... opts) { this.clazz = clz; this.tag = tag; this.options = opts == null ? Collections.EMPTY_SET : EnumSet.of(NOOP, opts); } public String getCleanTag() { return tag.replaceAll("/", ""); } public String getTagCleanLower() { return getCleanTag().toLowerCase(Locale.ROOT); } } @SuppressWarnings({"unchecked", "rawtypes"}) public static ConfigOverlay getConfigOverlay(SolrResourceLoader loader) { InputStream in = null; InputStreamReader isr = null; try { try { in = loader.openResource(ConfigOverlay.RESOURCE_NAME); } catch (IOException e) { // TODO: we should be explicitly looking for file not found exceptions // and logging if it's not the expected IOException // hopefully no problem, assume no overlay.json file return new ConfigOverlay(Collections.EMPTY_MAP, -1); } int version = 0; // will be always 0 for file based resourceLoader if (in instanceof ZkSolrResourceLoader.ZkByteArrayInputStream) { version = ((ZkSolrResourceLoader.ZkByteArrayInputStream) in).getStat().getVersion(); log.debug("Config overlay loaded. version : {} ", version); } Map m = (Map) fromJSON(in); return new ConfigOverlay(m, version); } catch (Exception e) { throw new SolrException(ErrorCode.SERVER_ERROR, "Error reading config overlay", e); } finally { IOUtils.closeQuietly(isr); IOUtils.closeQuietly(in); } } private Map<String, InitParams> initParams = Collections.emptyMap(); public Map<String, InitParams> getInitParams() { return initParams; } protected UpdateHandlerInfo loadUpdatehandlerInfo() { return new UpdateHandlerInfo(get("updateHandler/@class", null), getInt("updateHandler/autoCommit/maxDocs", -1), getInt("updateHandler/autoCommit/maxTime", -1), convertHeapOptionStyleConfigStringToBytes(get("updateHandler/autoCommit/maxSize", "")), getBool("updateHandler/indexWriter/closeWaitsForMerges", true), getBool("updateHandler/autoCommit/openSearcher", true), getInt("updateHandler/autoSoftCommit/maxDocs", -1), getInt("updateHandler/autoSoftCommit/maxTime", -1), getBool("updateHandler/commitWithin/softCommit", true)); } /** * Converts a Java heap option-like config string to bytes. Valid suffixes are: 'k', 'm', 'g' * (case insensitive). If there is no suffix, the default unit is bytes. * For example, 50k = 50KB, 20m = 20MB, 4g = 4GB, 300 = 300 bytes * @param configStr the config setting to parse * @return the size, in bytes. -1 if the given config string is empty */ protected static long convertHeapOptionStyleConfigStringToBytes(String configStr) { if (configStr.isEmpty()) { return -1; } long multiplier = 1; String numericValueStr = configStr; char suffix = Character.toLowerCase(configStr.charAt(configStr.length() - 1)); if (Character.isLetter(suffix)) { if (suffix == 'k') { multiplier = FileUtils.ONE_KB; } else if (suffix == 'm') { multiplier = FileUtils.ONE_MB; } else if (suffix == 'g') { multiplier = FileUtils.ONE_GB; } else { throw new RuntimeException("Invalid suffix. Valid suffixes are 'k' (KB), 'm' (MB), 'g' (G). " + "No suffix means the amount is in bytes. "); } numericValueStr = configStr.substring(0, configStr.length() - 1); } try { return Long.parseLong(numericValueStr) * multiplier; } catch (NumberFormatException e) { throw new RuntimeException("Invalid format. The config setting should be a long with an " + "optional letter suffix. Valid suffixes are 'k' (KB), 'm' (MB), 'g' (G). " + "No suffix means the amount is in bytes."); } } private void loadPluginInfo(SolrPluginInfo pluginInfo) { boolean requireName = pluginInfo.options.contains(REQUIRE_NAME); boolean requireClass = pluginInfo.options.contains(REQUIRE_CLASS); List<PluginInfo> result = readPluginInfos(pluginInfo.tag, requireName, requireClass); if (1 < result.size() && !pluginInfo.options.contains(MULTI_OK)) { throw new SolrException (SolrException.ErrorCode.SERVER_ERROR, "Found " + result.size() + " configuration sections when at most " + "1 is allowed matching expression: " + pluginInfo.getCleanTag()); } if (!result.isEmpty()) pluginStore.put(pluginInfo.clazz.getName(), result); } public List<PluginInfo> readPluginInfos(String tag, boolean requireName, boolean requireClass) { ArrayList<PluginInfo> result = new ArrayList<>(); NodeList nodes = (NodeList) evaluate(tag, XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); i++) { PluginInfo pluginInfo = new PluginInfo(nodes.item(i), "[solrconfig.xml] " + tag, requireName, requireClass); if (pluginInfo.isEnabled()) result.add(pluginInfo); } return result; } public SolrRequestParsers getRequestParsers() { return solrRequestParsers; } /* The set of materialized parameters: */ public final int booleanQueryMaxClauseCount; // SolrIndexSearcher - nutch optimizer -- Disabled since 3.1 // public final boolean filtOptEnabled; // public final int filtOptCacheSize; // public final float filtOptThreshold; // SolrIndexSearcher - caches configurations public final CacheConfig filterCacheConfig; public final CacheConfig queryResultCacheConfig; public final CacheConfig documentCacheConfig; public final CacheConfig fieldValueCacheConfig; public final Map<String, CacheConfig> userCacheConfigs; // SolrIndexSearcher - more... public final boolean useFilterForSortedQuery; public final int queryResultWindowSize; public final int queryResultMaxDocsCached; public final boolean enableLazyFieldLoading; // Circuit Breaker Configuration public final boolean useCircuitBreakers; public final int memoryCircuitBreakerThresholdPct; // IndexConfig settings public final SolrIndexConfig indexConfig; protected UpdateHandlerInfo updateHandlerInfo; private Map<String, List<PluginInfo>> pluginStore = new LinkedHashMap<>(); public final int maxWarmingSearchers; public final boolean useColdSearcher; public final Version luceneMatchVersion; protected String dataDir; public final int slowQueryThresholdMillis; // threshold above which a query is considered slow private final HttpCachingConfig httpCachingConfig; public HttpCachingConfig getHttpCachingConfig() { return httpCachingConfig; } public static class HttpCachingConfig implements MapSerializable { /** * config xpath prefix for getting HTTP Caching options */ private final static String CACHE_PRE = "requestDispatcher/httpCaching/"; /** * For extracting Expires "ttl" from <cacheControl> config */ private final static Pattern MAX_AGE = Pattern.compile("\\bmax-age=(\\d+)"); @Override public Map<String, Object> toMap(Map<String, Object> map) { return makeMap("never304", never304, "etagSeed", etagSeed, "lastModFrom", lastModFrom.name().toLowerCase(Locale.ROOT), "cacheControl", cacheControlHeader); } public static enum LastModFrom { OPENTIME, DIRLASTMOD, BOGUS; /** * Input must not be null */ public static LastModFrom parse(final String s) { try { return valueOf(s.toUpperCase(Locale.ROOT)); } catch (Exception e) { log.warn("Unrecognized value for lastModFrom: {}", s, e); return BOGUS; } } } private final boolean never304; private final String etagSeed; private final String cacheControlHeader; private final Long maxAge; private final LastModFrom lastModFrom; private HttpCachingConfig(SolrConfig conf) { never304 = conf.getBool(CACHE_PRE + "@never304", false); etagSeed = conf.get(CACHE_PRE + "@etagSeed", "Solr"); lastModFrom = LastModFrom.parse(conf.get(CACHE_PRE + "@lastModFrom", "openTime")); cacheControlHeader = conf.get(CACHE_PRE + "cacheControl", null); Long tmp = null; // maxAge if (null != cacheControlHeader) { try { final Matcher ttlMatcher = MAX_AGE.matcher(cacheControlHeader); final String ttlStr = ttlMatcher.find() ? ttlMatcher.group(1) : null; tmp = (null != ttlStr && !"".equals(ttlStr)) ? Long.valueOf(ttlStr) : null; } catch (Exception e) { log.warn("Ignoring exception while attempting to extract max-age from cacheControl config: {}" , cacheControlHeader, e); } } maxAge = tmp; } public boolean isNever304() { return never304; } public String getEtagSeed() { return etagSeed; } /** * null if no Cache-Control header */ public String getCacheControlHeader() { return cacheControlHeader; } /** * null if no max age limitation */ public Long getMaxAge() { return maxAge; } public LastModFrom getLastModFrom() { return lastModFrom; } } public static class UpdateHandlerInfo implements MapSerializable { public final String className; public final int autoCommmitMaxDocs, autoCommmitMaxTime, autoSoftCommmitMaxDocs, autoSoftCommmitMaxTime; public final long autoCommitMaxSizeBytes; public final boolean indexWriterCloseWaitsForMerges; public final boolean openSearcher; // is opening a new searcher part of hard autocommit? public final boolean commitWithinSoftCommit; /** * @param autoCommmitMaxDocs set -1 as default * @param autoCommmitMaxTime set -1 as default * @param autoCommitMaxSize set -1 as default */ public UpdateHandlerInfo(String className, int autoCommmitMaxDocs, int autoCommmitMaxTime, long autoCommitMaxSize, boolean indexWriterCloseWaitsForMerges, boolean openSearcher, int autoSoftCommmitMaxDocs, int autoSoftCommmitMaxTime, boolean commitWithinSoftCommit) { this.className = className; this.autoCommmitMaxDocs = autoCommmitMaxDocs; this.autoCommmitMaxTime = autoCommmitMaxTime; this.autoCommitMaxSizeBytes = autoCommitMaxSize; this.indexWriterCloseWaitsForMerges = indexWriterCloseWaitsForMerges; this.openSearcher = openSearcher; this.autoSoftCommmitMaxDocs = autoSoftCommmitMaxDocs; this.autoSoftCommmitMaxTime = autoSoftCommmitMaxTime; this.commitWithinSoftCommit = commitWithinSoftCommit; } @Override @SuppressWarnings({"unchecked", "rawtypes"}) public Map<String, Object> toMap(Map<String, Object> map) { LinkedHashMap result = new LinkedHashMap(); result.put("indexWriter", makeMap("closeWaitsForMerges", indexWriterCloseWaitsForMerges)); result.put("commitWithin", makeMap("softCommit", commitWithinSoftCommit)); result.put("autoCommit", makeMap( "maxDocs", autoCommmitMaxDocs, "maxTime", autoCommmitMaxTime, "openSearcher", openSearcher )); result.put("autoSoftCommit", makeMap("maxDocs", autoSoftCommmitMaxDocs, "maxTime", autoSoftCommmitMaxTime)); return result; } } // public Map<String, List<PluginInfo>> getUpdateProcessorChainInfo() { return updateProcessorChainInfo; } public UpdateHandlerInfo getUpdateHandlerInfo() { return updateHandlerInfo; } public String getDataDir() { return dataDir; } /** * SolrConfig keeps a repository of plugins by the type. The known interfaces are the types. * * @param type The key is FQN of the plugin class there are a few known types : SolrFormatter, SolrFragmenter * SolrRequestHandler,QParserPlugin, QueryResponseWriter,ValueSourceParser, * SearchComponent, QueryConverter, SolrEventListener, DirectoryFactory, * IndexDeletionPolicy, IndexReaderFactory, {@link TransformerFactory} */ @SuppressWarnings({"unchecked", "rawtypes"}) public List<PluginInfo> getPluginInfos(String type) { List<PluginInfo> result = pluginStore.get(type); SolrPluginInfo info = classVsSolrPluginInfo.get(type); if (info != null && (info.options.contains(REQUIRE_NAME) || info.options.contains(REQUIRE_NAME_IN_OVERLAY))) { Map<String, Map> infos = overlay.getNamedPlugins(info.getCleanTag()); if (!infos.isEmpty()) { LinkedHashMap<String, PluginInfo> map = new LinkedHashMap<>(); if (result != null) for (PluginInfo pluginInfo : result) { //just create a UUID for the time being so that map key is not null String name = pluginInfo.name == null ? UUID.randomUUID().toString().toLowerCase(Locale.ROOT) : pluginInfo.name; map.put(name, pluginInfo); } for (Map.Entry<String, Map> e : infos.entrySet()) { map.put(e.getKey(), new PluginInfo(info.getCleanTag(), e.getValue())); } result = new ArrayList<>(map.values()); } } return result == null ? Collections.<PluginInfo>emptyList() : result; } public PluginInfo getPluginInfo(String type) { List<PluginInfo> result = pluginStore.get(type); if (result == null || result.isEmpty()) { return null; } if (1 == result.size()) { return result.get(0); } throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Multiple plugins configured for type: " + type); } private void initLibs(SolrResourceLoader loader, boolean isConfigsetTrusted) { // TODO Want to remove SolrResourceLoader.getInstancePath; it can be on a Standalone subclass. // For Zk subclass, it's needed for the time being as well. We could remove that one if we remove two things // in SolrCloud: (1) instancePath/lib and (2) solrconfig lib directives with relative paths. Can wait till 9.0. Path instancePath = loader.getInstancePath(); List<URL> urls = new ArrayList<>(); Path libPath = instancePath.resolve("lib"); if (Files.exists(libPath)) { try { urls.addAll(SolrResourceLoader.getURLs(libPath)); } catch (IOException e) { log.warn("Couldn't add files from {} to classpath: {}", libPath, e); } } NodeList nodes = (NodeList) evaluate("lib", XPathConstants.NODESET); if (nodes == null || nodes.getLength() == 0) return; if (!isConfigsetTrusted) { throw new SolrException(ErrorCode.UNAUTHORIZED, "The configset for this collection was uploaded without any authentication in place," + " and use of <lib> is not available for collections with untrusted configsets. To use this component, re-upload the configset" + " after enabling authentication and authorization."); } for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); String baseDir = DOMUtil.getAttr(node, "dir"); String path = DOMUtil.getAttr(node, PATH); if (null != baseDir) { // :TODO: add support for a simpler 'glob' mutually exclusive of regex Path dir = instancePath.resolve(baseDir); String regex = DOMUtil.getAttr(node, "regex"); try { if (regex == null) urls.addAll(SolrResourceLoader.getURLs(dir)); else urls.addAll(SolrResourceLoader.getFilteredURLs(dir, regex)); } catch (IOException e) { log.warn("Couldn't add files from {} filtered by {} to classpath: {}", dir, regex, e); } } else if (null != path) { final Path dir = instancePath.resolve(path); try { urls.add(dir.toUri().toURL()); } catch (MalformedURLException e) { log.warn("Couldn't add file {} to classpath: {}", dir, e); } } else { throw new RuntimeException("lib: missing mandatory attributes: 'dir' or 'path'"); } } loader.addToClassLoader(urls); loader.reloadLuceneSPI(); } private void validateMemoryBreakerThreshold() { if (useCircuitBreakers) { if (memoryCircuitBreakerThresholdPct > 95 || memoryCircuitBreakerThresholdPct < 50) { throw new IllegalArgumentException("Valid value range of memoryCircuitBreakerThresholdPct is 50 - 95"); } } } public int getMultipartUploadLimitKB() { return multipartUploadLimitKB; } public int getFormUploadLimitKB() { return formUploadLimitKB; } public boolean isHandleSelect() { return handleSelect; } public boolean isAddHttpRequestToContext() { return addHttpRequestToContext; } public boolean isEnableRemoteStreams() { return enableRemoteStreams; } public boolean isEnableStreamBody() { return enableStreamBody; } @Override public int getInt(String path) { return getInt(path, 0); } @Override public int getInt(String path, int def) { Object val = overlay.getXPathProperty(path); if (val != null) return Integer.parseInt(val.toString()); return super.getInt(path, def); } @Override public boolean getBool(String path, boolean def) { Object val = overlay.getXPathProperty(path); if (val != null) return Boolean.parseBoolean(val.toString()); return super.getBool(path, def); } @Override public String get(String path) { Object val = overlay.getXPathProperty(path, true); return val != null ? val.toString() : super.get(path); } @Override public String get(String path, String def) { Object val = overlay.getXPathProperty(path, true); return val != null ? val.toString() : super.get(path, def); } @Override @SuppressWarnings({"unchecked", "rawtypes"}) public Map<String, Object> toMap(Map<String, Object> result) { if (getZnodeVersion() > -1) result.put(ZNODEVER, getZnodeVersion()); result.put(IndexSchema.LUCENE_MATCH_VERSION_PARAM, luceneMatchVersion); result.put("updateHandler", getUpdateHandlerInfo()); Map m = new LinkedHashMap(); result.put("query", m); m.put("useFilterForSortedQuery", useFilterForSortedQuery); m.put("queryResultWindowSize", queryResultWindowSize); m.put("queryResultMaxDocsCached", queryResultMaxDocsCached); m.put("enableLazyFieldLoading", enableLazyFieldLoading); m.put("maxBooleanClauses", booleanQueryMaxClauseCount); m.put("useCircuitBreakers", useCircuitBreakers); m.put("memoryCircuitBreakerThresholdPct", memoryCircuitBreakerThresholdPct); for (SolrPluginInfo plugin : plugins) { List<PluginInfo> infos = getPluginInfos(plugin.clazz.getName()); if (infos == null || infos.isEmpty()) continue; String tag = plugin.getCleanTag(); tag = tag.replace("/", ""); if (plugin.options.contains(PluginOpts.REQUIRE_NAME)) { LinkedHashMap items = new LinkedHashMap(); for (PluginInfo info : infos) { //TODO remove after fixing https://issues.apache.org/jira/browse/SOLR-13706 if (info.type.equals("searchComponent") && info.name.equals("highlight")) continue; items.put(info.name, info); } for (Map.Entry e : overlay.getNamedPlugins(plugin.tag).entrySet()) items.put(e.getKey(), e.getValue()); result.put(tag, items); } else { if (plugin.options.contains(MULTI_OK)) { ArrayList<MapSerializable> l = new ArrayList<>(); for (PluginInfo info : infos) l.add(info); result.put(tag, l); } else { result.put(tag, infos.get(0)); } } } addCacheConfig(m, filterCacheConfig, queryResultCacheConfig, documentCacheConfig, fieldValueCacheConfig); m = new LinkedHashMap(); result.put("requestDispatcher", m); m.put("handleSelect", handleSelect); if (httpCachingConfig != null) m.put("httpCaching", httpCachingConfig); m.put("requestParsers", makeMap("multipartUploadLimitKB", multipartUploadLimitKB, "formUploadLimitKB", formUploadLimitKB, "addHttpRequestToContext", addHttpRequestToContext)); if (indexConfig != null) result.put("indexConfig", indexConfig); //TODO there is more to add return result; } @SuppressWarnings({"unchecked", "rawtypes"}) private void addCacheConfig(Map queryMap, CacheConfig... cache) { if (cache == null) return; for (CacheConfig config : cache) if (config != null) queryMap.put(config.getNodeName(), config); } @Override public Properties getSubstituteProperties() { Map<String, Object> p = getOverlay().getUserProps(); if (p == null || p.isEmpty()) return super.getSubstituteProperties(); Properties result = new Properties(super.getSubstituteProperties()); result.putAll(p); return result; } private ConfigOverlay overlay; public ConfigOverlay getOverlay() { if (overlay == null) { overlay = getConfigOverlay(getResourceLoader()); } return overlay; } public RequestParams getRequestParams() { if (requestParams == null) { return refreshRequestParams(); } return requestParams; } /** * The version of package that should be loaded for a given package name * This information is stored in the params.json in the same configset * If params.json is absent or there is no corresponding version specified for a given package, * this returns a null and the latest is used by the caller */ public String maxPackageVersion(String pkg) { RequestParams.ParamSet p = getRequestParams().getParams(PackageListeners.PACKAGE_VERSIONS); if (p == null) { return null; } Object o = p.get().get(pkg); if (o == null || PackageLoader.LATEST.equals(o)) return null; return o.toString(); } public RequestParams refreshRequestParams() { requestParams = RequestParams.getFreshRequestParams(getResourceLoader(), requestParams); if (log.isDebugEnabled()) { log.debug("current version of requestparams : {}", requestParams.getZnodeVersion()); } return requestParams; } }
1
36,274
I'm not sure if the boolean flags should always contain `is`, also I generally hate too long names... ;) we already know this is a section for circuit breakers, so the name doesn't have to repeat all of it. How about `cpuBreakerEnabled`, `memoryBreakerEnabled` etc?
apache-lucene-solr
java
@@ -42,4 +42,13 @@ public interface RewriteFiles extends SnapshotUpdate<RewriteFiles> { * @return this for method chaining */ RewriteFiles rewriteFiles(Set<DataFile> filesToDelete, Set<DataFile> filesToAdd); + + /** + * Add a rewrite that replaces one set of deletes with another that contains the same deleted rows. + * + * @param deletesToDelete files that will be replaced, cannot be null or empty. + * @param deletesToAdd files that will be added, cannot be null or empty. + * @return this for method chaining + */ + RewriteFiles rewriteDeletes(Set<DeleteFile> deletesToDelete, Set<DeleteFile> deletesToAdd); }
1
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.iceberg; import java.util.Set; import org.apache.iceberg.exceptions.ValidationException; /** * API for replacing files in a table. * <p> * This API accumulates file additions and deletions, produces a new {@link Snapshot} of the * changes, and commits that snapshot as the current. * <p> * When committing, these changes will be applied to the latest table snapshot. Commit conflicts * will be resolved by applying the changes to the new latest snapshot and reattempting the commit. * If any of the deleted files are no longer in the latest snapshot when reattempting, the commit * will throw a {@link ValidationException}. */ public interface RewriteFiles extends SnapshotUpdate<RewriteFiles> { /** * Add a rewrite that replaces one set of files with another set that contains the same data. * * @param filesToDelete files that will be replaced (deleted), cannot be null or empty. * @param filesToAdd files that will be added, cannot be null or empty. * @return this for method chaining */ RewriteFiles rewriteFiles(Set<DataFile> filesToDelete, Set<DataFile> filesToAdd); }
1
33,317
Before we start the replacing equality deletes with position deletes, I think we need to refactor the RewriteFiles API to adjust more cases: 1. Rewrite data files and remove all the delete rows. The files to delete will be a set of data files and a set of delete files, and the files to add will be a set of data files. 2. Replace equality deletes with position deletes, the files to delete will be a set of equality delete files (we will need to ensure that all delete files are equality delete files ? ) , the files to add will be a set of position delete files. 3. Merging small delete files into a bigger delete files. The files to delete will be a set of equality/position delete files, the files to add will be a set of equality/position delete files.
apache-iceberg
java
@@ -9,10 +9,16 @@ module Blacklight::BlacklightHelperBehavior ## # Get the name of this application from an i18n string # key: blacklight.application_name + # Try first in the current locale, then the default locale # # @return [String] the application name def application_name - t('blacklight.application_name') + # It's important that we don't use ActionView::Helpers::CacheHelper#cache here + # because it returns nil. + Rails.cache.fetch 'blacklight/application_name' do + t('blacklight.application_name', + default: t('blacklight.application_name', locale: I18n.default_locale)) + end end ##
1
# frozen_string_literal: true # Methods added to this helper will be available to all templates in the hosting application module Blacklight::BlacklightHelperBehavior include UrlHelperBehavior include HashAsHiddenFieldsHelperBehavior include LayoutHelperBehavior include IconHelperBehavior ## # Get the name of this application from an i18n string # key: blacklight.application_name # # @return [String] the application name def application_name t('blacklight.application_name') end ## # Get the page's HTML title # # @return [String] def render_page_title (content_for(:page_title) if content_for?(:page_title)) || @page_title || application_name end ## # Create <link rel="alternate"> links from a documents dynamically # provided export formats. # # Returns empty string if no links available. # # @param [SolrDocument] document # @param [Hash] options # @option options [Boolean] :unique ensures only one link is output for every # content type, e.g. as required by atom # @option options [Array<String>] :exclude array of format shortnames to not include in the output def render_link_rel_alternates(document = @document, options = {}) return if document.nil? presenter(document).link_rel_alternates(options) end ## # Render OpenSearch headers for this search # @return [String] def render_opensearch_response_metadata render partial: 'catalog/opensearch_response_metadata' end ## # Render classes for the <body> element # @return [String] def render_body_class extra_body_classes.join " " end ## # List of classes to be applied to the <body> element # @see render_body_class # @return [Array<String>] def extra_body_classes @extra_body_classes ||= ['blacklight-' + controller.controller_name, 'blacklight-' + [controller.controller_name, controller.action_name].join('-')] end ## # Render the search navbar # @return [String] def render_search_bar search_bar_presenter.render end def search_bar_presenter @search_bar ||= search_bar_presenter_class.new(controller, blacklight_config) end ## # Determine whether to render a given field in the index view. # # @param [SolrDocument] document # @param [Blacklight::Configuration::Field] field_config # @return [Boolean] def should_render_index_field? document, field_config should_render_field?(field_config, document) && document_has_value?(document, field_config) end ## # Determine whether to render a given field in the show view # # @param [SolrDocument] document # @param [Blacklight::Configuration::Field] field_config # @return [Boolean] def should_render_show_field? document, field_config should_render_field?(field_config, document) && document_has_value?(document, field_config) end ## # Check if a document has (or, might have, in the case of accessor methods) a value for # the given solr field # @param [SolrDocument] document # @param [Blacklight::Configuration::Field] field_config # @return [Boolean] def document_has_value? document, field_config document.has?(field_config.field) || (document.has_highlight_field? field_config.field if field_config.highlight) || field_config.accessor end ## # Determine whether to display spellcheck suggestions # # @param [Blacklight::Solr::Response] response # @return [Boolean] def should_show_spellcheck_suggestions? response response.total <= spell_check_max && response.spelling.words.any? end ## # Render the index field label for a document # # Translations for index field labels should go under blacklight.search.fields # They are picked up from there by a value "%{label}" in blacklight.search.index.label # # @overload render_index_field_label(options) # Use the default, document-agnostic configuration # @param [Hash] opts # @option opts [String] :field # @overload render_index_field_label(document, options) # Allow an extention point where information in the document # may drive the value of the field # @param [SolrDocument] doc # @param [Hash] opts # @option opts [String] :field def render_index_field_label *args options = args.extract_options! document = args.first field = options[:field] html_escape t(:"blacklight.search.index.#{document_index_view_type}.label", default: :'blacklight.search.index.label', label: index_field_label(document, field)) end ## # Render the show field label for a document # # @overload render_document_show_field_label(options) # Use the default, document-agnostic configuration # @param [Hash] opts # @option opts [String] :field # @overload render_document_show_field_label(document, options) # Allow an extention point where information in the document # may drive the value of the field # @param [SolrDocument] doc # @param [Hash] opts # @option opts [String] :field def render_document_show_field_label *args options = args.extract_options! document = args.first field = options[:field] t(:'blacklight.search.show.label', label: document_show_field_label(document, field)) end ## # Get the value of the document's "title" field, or a placeholder # value (if empty) # # @param [SolrDocument] document # @return [String] def document_heading document = nil document ||= @document presenter(document).heading end ## # Get the document's "title" to display in the <title> element. # (by default, use the #document_heading) # # @see #document_heading # @param [SolrDocument] document # @return [String] def document_show_html_title document = nil document ||= @document presenter(document).html_title end ## # Render the document "heading" (title) in a content tag # @overload render_document_heading(document, options) # @param [SolrDocument] document # @param [Hash] options # @option options [Symbol] :tag # @overload render_document_heading(options) # @param [Hash] options # @option options [Symbol] :tag def render_document_heading(*args) options = args.extract_options! document = args.first tag = options.fetch(:tag, :h4) document ||= @document content_tag(tag, presenter(document).heading, itemprop: "name") end ## # Get the current "view type" (and ensure it is a valid type) # # @param [Hash] query_params the query parameters to check # @return [Symbol] def document_index_view_type query_params = params view_param = query_params[:view] view_param ||= session[:preferred_view] if view_param && document_index_views.keys.include?(view_param.to_sym) view_param.to_sym else default_document_index_view_type end end ## # Render a partial of an arbitrary format inside a # template of a different format. (e.g. render an HTML # partial from an XML template) # code taken from: # http://stackoverflow.com/questions/339130/how-do-i-render-a-partial-of-a-different-format-in-rails (zgchurch) # # @param [String] format suffix # @yield def with_format(format) old_formats = formats self.formats = [format] yield self.formats = old_formats nil end ## # Should we render a grouped response (because the response # contains a grouped response instead of the normal response) def render_grouped_response? response = @response response.grouped? end ## # Returns a document presenter for the given document # TODO: Move this to the controller. It can just pass a presenter or set of presenters. def presenter(document) case action_name when 'show', 'citation' show_presenter(document) when 'index' index_presenter(document) end end def show_presenter(document) show_presenter_class(document).new(document, self) end def index_presenter(document) index_presenter_class(document).new(document, self) end ## # Override this method if you want to use a different presenter class def show_presenter_class(_document) blacklight_config.show.document_presenter_class end def index_presenter_class(_document) blacklight_config.index.document_presenter_class end def search_bar_presenter_class blacklight_config.index.search_bar_presenter_class end ## # Open Search discovery tag for HTML <head> links def opensearch_description_tag title, href tag :link, href: href, title: title, type: "application/opensearchdescription+xml", rel: "search" end end
1
7,458
Layout/TrailingWhitespace: Trailing whitespace detected.
projectblacklight-blacklight
rb
@@ -80,8 +80,12 @@ public class LibraryManager { List<ShortcutCategoryDTO> shortcuts = new ArrayList<>(); for (Map.Entry<String, List<ShortcutDTO>> entry : categoryMap.entrySet()) { entry.getValue().sort(ShortcutDTO.nameComparator()); - ShortcutCategoryDTO category = new ShortcutCategoryDTO.Builder().withId(entry.getKey()) - .withName(entry.getKey()).withShortcuts(entry.getValue()).build(); + ShortcutCategoryDTO category = new ShortcutCategoryDTO.Builder() + .withId(entry.getKey()) + .withName(entry.getKey()) + .withShortcuts(entry.getValue()) + .withIcon(entry.getValue().get(0).getCategoryIcon()) // choose one category icon + .build(); shortcuts.add(tr(category)); }
1
/* * Copyright (C) 2015-2017 PÂRIS Quentin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package org.phoenicis.library; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.phoenicis.configuration.security.Safe; import org.phoenicis.library.dto.ShortcutCategoryDTO; import org.phoenicis.library.dto.ShortcutDTO; import org.phoenicis.library.dto.ShortcutInfoDTO; import org.phoenicis.multithreading.functional.NullRunnable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.*; import static org.phoenicis.configuration.localisation.Localisation.tr; @Safe public class LibraryManager { private final static Logger LOGGER = LoggerFactory.getLogger(LibraryManager.class); private final String shortcutDirectory; private ObjectMapper objectMapper; private Runnable onUpdate = new NullRunnable(); public LibraryManager(String shortcutDirectory, ObjectMapper objectMapper) { this.shortcutDirectory = shortcutDirectory; this.objectMapper = objectMapper; } public List<ShortcutCategoryDTO> fetchShortcuts() { final File shortcutDirectoryFile = new File(this.shortcutDirectory); if (!shortcutDirectoryFile.exists()) { shortcutDirectoryFile.mkdirs(); return Collections.emptyList(); } final File[] directoryContent = shortcutDirectoryFile.listFiles(); if (directoryContent == null) { return Collections.emptyList(); } HashMap<String, List<ShortcutDTO>> categoryMap = new HashMap<>(); for (File file : directoryContent) { if ("shortcut".equals(FilenameUtils.getExtension(file.getName()))) { ShortcutDTO shortcut = fetchShortcutDTO(shortcutDirectoryFile, file); String categoryId = shortcut.getInfo().getCategory(); if (!categoryMap.containsKey(categoryId)) { categoryMap.put(categoryId, new ArrayList<>()); } categoryMap.get(categoryId).add(shortcut); } } List<ShortcutCategoryDTO> shortcuts = new ArrayList<>(); for (Map.Entry<String, List<ShortcutDTO>> entry : categoryMap.entrySet()) { entry.getValue().sort(ShortcutDTO.nameComparator()); ShortcutCategoryDTO category = new ShortcutCategoryDTO.Builder().withId(entry.getKey()) .withName(entry.getKey()).withShortcuts(entry.getValue()).build(); shortcuts.add(tr(category)); } return shortcuts; } public ShortcutDTO fetchShortcutsFromName(String name) { for (ShortcutCategoryDTO shortcutCategoryDTO : fetchShortcuts()) { for (ShortcutDTO shortcutDTO : shortcutCategoryDTO.getShortcuts()) { if (name.equals(shortcutDTO.getInfo().getName())) { return shortcutDTO; } } } return null; } public void setOnUpdate(Runnable onUpdate) { this.onUpdate = onUpdate; } private ShortcutDTO fetchShortcutDTO(File shortcutDirectory, File file) { final String baseName = FilenameUtils.getBaseName(file.getName()); final File infoFile = new File(shortcutDirectory, baseName + ".info"); final File iconFile = new File(shortcutDirectory, baseName + ".icon"); final File miniatureFile = new File(shortcutDirectory, baseName + ".miniature"); final ShortcutInfoDTO.Builder shortcutInfoDTOBuilder; if (infoFile.exists()) { final ShortcutInfoDTO shortcutInfoDTOFromJsonFile = unSerializeShortcutInfo(infoFile); shortcutInfoDTOBuilder = new ShortcutInfoDTO.Builder(shortcutInfoDTOFromJsonFile); } else { shortcutInfoDTOBuilder = new ShortcutInfoDTO.Builder(); shortcutInfoDTOBuilder.withName(baseName); } if (StringUtils.isBlank(shortcutInfoDTOBuilder.getName())) { shortcutInfoDTOBuilder.withName(baseName); } if (StringUtils.isBlank(shortcutInfoDTOBuilder.getCategory())) { shortcutInfoDTOBuilder.withCategory("Other"); } final ShortcutInfoDTO shortcutInfoDTO = shortcutInfoDTOBuilder.build(); try { final URI icon = iconFile.exists() ? iconFile.toURI() : getClass().getResource("phoenicis.png").toURI(); final URI miniature = miniatureFile.exists() ? miniatureFile.toURI() : getClass().getResource("defaultMiniature.png").toURI(); return new ShortcutDTO.Builder() .withId(baseName) .withInfo(shortcutInfoDTO) .withScript(IOUtils.toString(new FileInputStream(file), "UTF-8")) .withIcon(icon) .withMiniature(miniature) .build(); } catch (URISyntaxException | IOException e) { throw new IllegalStateException(e); } } public void refresh() { onUpdate.run(); } private ShortcutInfoDTO unSerializeShortcutInfo(File jsonFile) { try { return this.objectMapper.readValue(jsonFile, ShortcutInfoDTO.class); } catch (IOException e) { LOGGER.debug("JSON file not found"); return new ShortcutInfoDTO.Builder().build(); } } }
1
14,264
Is it possible that the shortcuts list is empty?
PhoenicisOrg-phoenicis
java
@@ -692,6 +692,10 @@ func runBackup(opts BackupOptions, gopts GlobalOptions, term *termstatus.Termina p.V("start backup on %v", targets) } _, id, err := arch.Snapshot(gopts.ctx, targets, snapshotOpts) + if errors.Cause(err) == context.Canceled { + return errors.Fatal("canceled") + } + if err != nil { return errors.Fatalf("unable to save snapshot: %v", err) }
1
package main import ( "bufio" "bytes" "context" "fmt" "io" "io/ioutil" "os" "path" "path/filepath" "runtime" "strconv" "strings" "time" "github.com/spf13/cobra" tomb "gopkg.in/tomb.v2" "github.com/restic/restic/internal/archiver" "github.com/restic/restic/internal/debug" "github.com/restic/restic/internal/errors" "github.com/restic/restic/internal/fs" "github.com/restic/restic/internal/repository" "github.com/restic/restic/internal/restic" "github.com/restic/restic/internal/textfile" "github.com/restic/restic/internal/ui" "github.com/restic/restic/internal/ui/json" "github.com/restic/restic/internal/ui/termstatus" ) var cmdBackup = &cobra.Command{ Use: "backup [flags] FILE/DIR [FILE/DIR] ...", Short: "Create a new backup of files and/or directories", Long: ` The "backup" command creates a new snapshot and saves the files and directories given as the arguments. EXIT STATUS =========== Exit status is 0 if the command was successful. Exit status is 1 if there was a fatal error (no snapshot created). Exit status is 3 if some source data could not be read (incomplete snapshot created). `, PreRun: func(cmd *cobra.Command, args []string) { if backupOptions.Host == "" { hostname, err := os.Hostname() if err != nil { debug.Log("os.Hostname() returned err: %v", err) return } backupOptions.Host = hostname } }, DisableAutoGenTag: true, RunE: func(cmd *cobra.Command, args []string) error { var t tomb.Tomb term := termstatus.New(globalOptions.stdout, globalOptions.stderr, globalOptions.Quiet) t.Go(func() error { term.Run(t.Context(globalOptions.ctx)); return nil }) err := runBackup(backupOptions, globalOptions, term, args) if err != nil { return err } t.Kill(nil) return t.Wait() }, } // BackupOptions bundles all options for the backup command. type BackupOptions struct { Parent string Force bool Excludes []string InsensitiveExcludes []string ExcludeFiles []string InsensitiveExcludeFiles []string ExcludeOtherFS bool ExcludeIfPresent []string ExcludeCaches bool ExcludeLargerThan string Stdin bool StdinFilename string Tags restic.TagList Host string FilesFrom []string FilesFromVerbatim []string FilesFromRaw []string TimeStamp string WithAtime bool IgnoreInode bool UseFsSnapshot bool } var backupOptions BackupOptions // ErrInvalidSourceData is used to report an incomplete backup var ErrInvalidSourceData = errors.New("failed to read all source data during backup") func init() { cmdRoot.AddCommand(cmdBackup) f := cmdBackup.Flags() f.StringVar(&backupOptions.Parent, "parent", "", "use this parent `snapshot` (default: last snapshot in the repo that has the same target files/directories)") f.BoolVarP(&backupOptions.Force, "force", "f", false, `force re-reading the target files/directories (overrides the "parent" flag)`) f.StringArrayVarP(&backupOptions.Excludes, "exclude", "e", nil, "exclude a `pattern` (can be specified multiple times)") f.StringArrayVar(&backupOptions.InsensitiveExcludes, "iexclude", nil, "same as --exclude `pattern` but ignores the casing of filenames") f.StringArrayVar(&backupOptions.ExcludeFiles, "exclude-file", nil, "read exclude patterns from a `file` (can be specified multiple times)") f.StringArrayVar(&backupOptions.InsensitiveExcludeFiles, "iexclude-file", nil, "same as --exclude-file but ignores casing of `file`names in patterns") f.BoolVarP(&backupOptions.ExcludeOtherFS, "one-file-system", "x", false, "exclude other file systems") f.StringArrayVar(&backupOptions.ExcludeIfPresent, "exclude-if-present", nil, "takes `filename[:header]`, exclude contents of directories containing filename (except filename itself) if header of that file is as provided (can be specified multiple times)") f.BoolVar(&backupOptions.ExcludeCaches, "exclude-caches", false, `excludes cache directories that are marked with a CACHEDIR.TAG file. See https://bford.info/cachedir/ for the Cache Directory Tagging Standard`) f.StringVar(&backupOptions.ExcludeLargerThan, "exclude-larger-than", "", "max `size` of the files to be backed up (allowed suffixes: k/K, m/M, g/G, t/T)") f.BoolVar(&backupOptions.Stdin, "stdin", false, "read backup from stdin") f.StringVar(&backupOptions.StdinFilename, "stdin-filename", "stdin", "`filename` to use when reading from stdin") f.Var(&backupOptions.Tags, "tag", "add `tags` for the new snapshot in the format `tag[,tag,...]` (can be specified multiple times)") f.StringVarP(&backupOptions.Host, "host", "H", "", "set the `hostname` for the snapshot manually. To prevent an expensive rescan use the \"parent\" flag") f.StringVar(&backupOptions.Host, "hostname", "", "set the `hostname` for the snapshot manually") f.MarkDeprecated("hostname", "use --host") f.StringArrayVar(&backupOptions.FilesFrom, "files-from", nil, "read the files to backup from `file` (can be combined with file args; can be specified multiple times)") f.StringArrayVar(&backupOptions.FilesFromVerbatim, "files-from-verbatim", nil, "read the files to backup from `file` (can be combined with file args; can be specified multiple times)") f.StringArrayVar(&backupOptions.FilesFromRaw, "files-from-raw", nil, "read the files to backup from `file` (can be combined with file args; can be specified multiple times)") f.StringVar(&backupOptions.TimeStamp, "time", "", "`time` of the backup (ex. '2012-11-01 22:08:41') (default: now)") f.BoolVar(&backupOptions.WithAtime, "with-atime", false, "store the atime for all files and directories") f.BoolVar(&backupOptions.IgnoreInode, "ignore-inode", false, "ignore inode number changes when checking for modified files") if runtime.GOOS == "windows" { f.BoolVar(&backupOptions.UseFsSnapshot, "use-fs-snapshot", false, "use filesystem snapshot where possible (currently only Windows VSS)") } } // filterExisting returns a slice of all existing items, or an error if no // items exist at all. func filterExisting(items []string) (result []string, err error) { for _, item := range items { _, err := fs.Lstat(item) if err != nil && os.IsNotExist(errors.Cause(err)) { Warnf("%v does not exist, skipping\n", item) continue } result = append(result, item) } if len(result) == 0 { return nil, errors.Fatal("all target directories/files do not exist") } return } // readLines reads all lines from the named file and returns them as a // string slice. // // If filename is empty, readPatternsFromFile returns an empty slice. // If filename is a dash (-), readPatternsFromFile will read the lines from the // standard input. func readLines(filename string) ([]string, error) { if filename == "" { return nil, nil } var ( data []byte err error ) if filename == "-" { data, err = ioutil.ReadAll(os.Stdin) } else { data, err = textfile.Read(filename) } if err != nil { return nil, err } var lines []string scanner := bufio.NewScanner(bytes.NewReader(data)) for scanner.Scan() { lines = append(lines, scanner.Text()) } if err := scanner.Err(); err != nil { return nil, err } return lines, nil } // readFilenamesFromFileRaw reads a list of filenames from the given file, // or stdin if filename is "-". Each filename is terminated by a zero byte, // which is stripped off. func readFilenamesFromFileRaw(filename string) (names []string, err error) { f := os.Stdin if filename != "-" { if f, err = os.Open(filename); err != nil { return nil, err } defer f.Close() } return readFilenamesRaw(f) } func readFilenamesRaw(r io.Reader) (names []string, err error) { br := bufio.NewReader(r) for { name, err := br.ReadString(0) switch err { case nil: case io.EOF: if name == "" { return names, nil } return nil, errors.Fatal("--files-from-raw: trailing zero byte missing") default: return nil, err } name = name[:len(name)-1] if name == "" { // The empty filename is never valid. Handle this now to // prevent downstream code from erroneously backing up // filepath.Clean("") == ".". return nil, errors.Fatal("--files-from-raw: empty filename in listing") } names = append(names, name) } } // Check returns an error when an invalid combination of options was set. func (opts BackupOptions) Check(gopts GlobalOptions, args []string) error { if gopts.password == "" { filesFrom := append(append(opts.FilesFrom, opts.FilesFromVerbatim...), opts.FilesFromRaw...) for _, filename := range filesFrom { if filename == "-" { return errors.Fatal("unable to read password from stdin when data is to be read from stdin, use --password-file or $RESTIC_PASSWORD") } } } if opts.Stdin { if len(opts.FilesFrom) > 0 { return errors.Fatal("--stdin and --files-from cannot be used together") } if len(opts.FilesFromVerbatim) > 0 { return errors.Fatal("--stdin and --files-from-verbatim cannot be used together") } if len(opts.FilesFromRaw) > 0 { return errors.Fatal("--stdin and --files-from-raw cannot be used together") } if len(args) > 0 { return errors.Fatal("--stdin was specified and files/dirs were listed as arguments") } } return nil } // collectRejectByNameFuncs returns a list of all functions which may reject data // from being saved in a snapshot based on path only func collectRejectByNameFuncs(opts BackupOptions, repo *repository.Repository, targets []string) (fs []RejectByNameFunc, err error) { // exclude restic cache if repo.Cache != nil { f, err := rejectResticCache(repo) if err != nil { return nil, err } fs = append(fs, f) } // add patterns from file if len(opts.ExcludeFiles) > 0 { excludes, err := readExcludePatternsFromFiles(opts.ExcludeFiles) if err != nil { return nil, err } opts.Excludes = append(opts.Excludes, excludes...) } if len(opts.InsensitiveExcludeFiles) > 0 { excludes, err := readExcludePatternsFromFiles(opts.InsensitiveExcludeFiles) if err != nil { return nil, err } opts.InsensitiveExcludes = append(opts.InsensitiveExcludes, excludes...) } if len(opts.InsensitiveExcludes) > 0 { fs = append(fs, rejectByInsensitivePattern(opts.InsensitiveExcludes)) } if len(opts.Excludes) > 0 { fs = append(fs, rejectByPattern(opts.Excludes)) } if opts.ExcludeCaches { opts.ExcludeIfPresent = append(opts.ExcludeIfPresent, "CACHEDIR.TAG:Signature: 8a477f597d28d172789f06886806bc55") } for _, spec := range opts.ExcludeIfPresent { f, err := rejectIfPresent(spec) if err != nil { return nil, err } fs = append(fs, f) } return fs, nil } // collectRejectFuncs returns a list of all functions which may reject data // from being saved in a snapshot based on path and file info func collectRejectFuncs(opts BackupOptions, repo *repository.Repository, targets []string) (fs []RejectFunc, err error) { // allowed devices if opts.ExcludeOtherFS && !opts.Stdin { f, err := rejectByDevice(targets) if err != nil { return nil, err } fs = append(fs, f) } if len(opts.ExcludeLargerThan) != 0 && !opts.Stdin { f, err := rejectBySize(opts.ExcludeLargerThan) if err != nil { return nil, err } fs = append(fs, f) } return fs, nil } // readExcludePatternsFromFiles reads all exclude files and returns the list of // exclude patterns. For each line, leading and trailing white space is removed // and comment lines are ignored. For each remaining pattern, environment // variables are resolved. For adding a literal dollar sign ($), write $$ to // the file. func readExcludePatternsFromFiles(excludeFiles []string) ([]string, error) { getenvOrDollar := func(s string) string { if s == "$" { return "$" } return os.Getenv(s) } var excludes []string for _, filename := range excludeFiles { err := func() (err error) { data, err := textfile.Read(filename) if err != nil { return err } scanner := bufio.NewScanner(bytes.NewReader(data)) for scanner.Scan() { line := strings.TrimSpace(scanner.Text()) // ignore empty lines if line == "" { continue } // strip comments if strings.HasPrefix(line, "#") { continue } line = os.Expand(line, getenvOrDollar) excludes = append(excludes, line) } return scanner.Err() }() if err != nil { return nil, err } } return excludes, nil } // collectTargets returns a list of target files/dirs from several sources. func collectTargets(opts BackupOptions, args []string) (targets []string, err error) { if opts.Stdin { return nil, nil } for _, file := range opts.FilesFrom { fromfile, err := readLines(file) if err != nil { return nil, err } // expand wildcards for _, line := range fromfile { line = strings.TrimSpace(line) if line == "" || line[0] == '#' { // '#' marks a comment. continue } var expanded []string expanded, err := filepath.Glob(line) if err != nil { return nil, errors.WithMessage(err, fmt.Sprintf("pattern: %s", line)) } if len(expanded) == 0 { Warnf("pattern %q does not match any files, skipping\n", line) } targets = append(targets, expanded...) } } for _, file := range opts.FilesFromVerbatim { fromfile, err := readLines(file) if err != nil { return nil, err } for _, line := range fromfile { if line == "" { continue } targets = append(targets, line) } } for _, file := range opts.FilesFromRaw { fromfile, err := readFilenamesFromFileRaw(file) if err != nil { return nil, err } targets = append(targets, fromfile...) } // Merge args into files-from so we can reuse the normal args checks // and have the ability to use both files-from and args at the same time. targets = append(targets, args...) if len(targets) == 0 && !opts.Stdin { return nil, errors.Fatal("nothing to backup, please specify target files/dirs") } targets, err = filterExisting(targets) if err != nil { return nil, err } return targets, nil } // parent returns the ID of the parent snapshot. If there is none, nil is // returned. func findParentSnapshot(ctx context.Context, repo restic.Repository, opts BackupOptions, targets []string) (parentID *restic.ID, err error) { // Force using a parent if !opts.Force && opts.Parent != "" { id, err := restic.FindSnapshot(ctx, repo, opts.Parent) if err != nil { return nil, errors.Fatalf("invalid id %q: %v", opts.Parent, err) } parentID = &id } // Find last snapshot to set it as parent, if not already set if !opts.Force && parentID == nil { id, err := restic.FindLatestSnapshot(ctx, repo, targets, []restic.TagList{}, []string{opts.Host}) if err == nil { parentID = &id } else if err != restic.ErrNoSnapshotFound { return nil, err } } return parentID, nil } func runBackup(opts BackupOptions, gopts GlobalOptions, term *termstatus.Terminal, args []string) error { err := opts.Check(gopts, args) if err != nil { return err } targets, err := collectTargets(opts, args) if err != nil { return err } timeStamp := time.Now() if opts.TimeStamp != "" { timeStamp, err = time.ParseInLocation(TimeFormat, opts.TimeStamp, time.Local) if err != nil { return errors.Fatalf("error in time option: %v\n", err) } } var t tomb.Tomb if gopts.verbosity >= 2 && !gopts.JSON { Verbosef("open repository\n") } repo, err := OpenRepository(gopts) if err != nil { return err } type ArchiveProgressReporter interface { CompleteItem(item string, previous, current *restic.Node, s archiver.ItemStats, d time.Duration) StartFile(filename string) CompleteBlob(filename string, bytes uint64) ScannerError(item string, fi os.FileInfo, err error) error ReportTotal(item string, s archiver.ScanStats) SetMinUpdatePause(d time.Duration) Run(ctx context.Context) error Error(item string, fi os.FileInfo, err error) error Finish(snapshotID restic.ID) // ui.StdioWrapper Stdout() io.WriteCloser Stderr() io.WriteCloser // ui.Message E(msg string, args ...interface{}) P(msg string, args ...interface{}) V(msg string, args ...interface{}) VV(msg string, args ...interface{}) } var p ArchiveProgressReporter if gopts.JSON { p = json.NewBackup(term, gopts.verbosity) } else { p = ui.NewBackup(term, gopts.verbosity) } // use the terminal for stdout/stderr prevStdout, prevStderr := gopts.stdout, gopts.stderr defer func() { gopts.stdout, gopts.stderr = prevStdout, prevStderr }() gopts.stdout, gopts.stderr = p.Stdout(), p.Stderr() if s, ok := os.LookupEnv("RESTIC_PROGRESS_FPS"); ok { fps, err := strconv.Atoi(s) if err == nil && fps >= 1 { if fps > 60 { fps = 60 } p.SetMinUpdatePause(time.Second / time.Duration(fps)) } } t.Go(func() error { return p.Run(t.Context(gopts.ctx)) }) if !gopts.JSON { p.V("lock repository") } lock, err := lockRepo(gopts.ctx, repo) defer unlockRepo(lock) if err != nil { return err } // rejectByNameFuncs collect functions that can reject items from the backup based on path only rejectByNameFuncs, err := collectRejectByNameFuncs(opts, repo, targets) if err != nil { return err } // rejectFuncs collect functions that can reject items from the backup based on path and file info rejectFuncs, err := collectRejectFuncs(opts, repo, targets) if err != nil { return err } if !gopts.JSON { p.V("load index files") } err = repo.LoadIndex(gopts.ctx) if err != nil { return err } parentSnapshotID, err := findParentSnapshot(gopts.ctx, repo, opts, targets) if err != nil { return err } if !gopts.JSON { if parentSnapshotID != nil { p.P("using parent snapshot %v\n", parentSnapshotID.Str()) } else { p.P("no parent snapshot found, will read all files\n") } } selectByNameFilter := func(item string) bool { for _, reject := range rejectByNameFuncs { if reject(item) { return false } } return true } selectFilter := func(item string, fi os.FileInfo) bool { for _, reject := range rejectFuncs { if reject(item, fi) { return false } } return true } var targetFS fs.FS = fs.Local{} if runtime.GOOS == "windows" && opts.UseFsSnapshot { if err = fs.HasSufficientPrivilegesForVSS(); err != nil { return err } errorHandler := func(item string, err error) error { return p.Error(item, nil, err) } messageHandler := func(msg string, args ...interface{}) { if !gopts.JSON { p.P(msg, args...) } } localVss := fs.NewLocalVss(errorHandler, messageHandler) defer localVss.DeleteSnapshots() targetFS = localVss } if opts.Stdin { if !gopts.JSON { p.V("read data from stdin") } filename := path.Join("/", opts.StdinFilename) targetFS = &fs.Reader{ ModTime: timeStamp, Name: filename, Mode: 0644, ReadCloser: os.Stdin, } targets = []string{filename} } sc := archiver.NewScanner(targetFS) sc.SelectByName = selectByNameFilter sc.Select = selectFilter sc.Error = p.ScannerError sc.Result = p.ReportTotal if !gopts.JSON { p.V("start scan on %v", targets) } t.Go(func() error { return sc.Scan(t.Context(gopts.ctx), targets) }) arch := archiver.New(repo, targetFS, archiver.Options{}) arch.SelectByName = selectByNameFilter arch.Select = selectFilter arch.WithAtime = opts.WithAtime success := true arch.Error = func(item string, fi os.FileInfo, err error) error { success = false return p.Error(item, fi, err) } arch.CompleteItem = p.CompleteItem arch.StartFile = p.StartFile arch.CompleteBlob = p.CompleteBlob arch.IgnoreInode = opts.IgnoreInode if parentSnapshotID == nil { parentSnapshotID = &restic.ID{} } snapshotOpts := archiver.SnapshotOptions{ Excludes: opts.Excludes, Tags: opts.Tags, Time: timeStamp, Hostname: opts.Host, ParentSnapshot: *parentSnapshotID, } if !gopts.JSON { p.V("start backup on %v", targets) } _, id, err := arch.Snapshot(gopts.ctx, targets, snapshotOpts) if err != nil { return errors.Fatalf("unable to save snapshot: %v", err) } // cleanly shutdown all running goroutines t.Kill(nil) // let's see if one returned an error err = t.Wait() // Report finished execution p.Finish(id) if !gopts.JSON { p.P("snapshot %s saved\n", id.Str()) } if !success { return ErrInvalidSourceData } // Return error if any return err }
1
14,674
This just changes the error message from `unable to save snapshot: [...] context canceled` to `canceled`.
restic-restic
go
@@ -141,7 +141,9 @@ public abstract class AbstractRestInvocation { if (response.getHeaders().getHeaderMap() != null) { for (Entry<String, List<Object>> entry : response.getHeaders().getHeaderMap().entrySet()) { for (Object value : entry.getValue()) { - responseEx.addHeader(entry.getKey(), String.valueOf(value)); + if (!entry.getKey().equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH)) { + responseEx.addHeader(entry.getKey(), String.valueOf(value)); + } } } }
1
/* * Copyright 2017 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.servicecomb.common.rest; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Response.Status; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.netty.buffer.Unpooled; import io.servicecomb.common.rest.codec.produce.ProduceProcessor; import io.servicecomb.common.rest.codec.produce.ProduceProcessorManager; import io.servicecomb.common.rest.definition.RestOperationMeta; import io.servicecomb.common.rest.filter.HttpServerFilter; import io.servicecomb.core.Const; import io.servicecomb.core.Invocation; import io.servicecomb.foundation.common.utils.JsonUtils; import io.servicecomb.foundation.vertx.http.HttpServletRequestEx; import io.servicecomb.foundation.vertx.http.HttpServletResponseEx; import io.servicecomb.foundation.vertx.stream.BufferOutputStream; import io.servicecomb.swagger.invocation.Response; import io.servicecomb.swagger.invocation.exception.InvocationException; public abstract class AbstractRestInvocation { private static final Logger LOGGER = LoggerFactory.getLogger(AbstractRestInvocation.class); protected RestOperationMeta restOperationMeta; protected Invocation invocation; protected HttpServletRequestEx requestEx; protected HttpServletResponseEx responseEx; protected ProduceProcessor produceProcessor; protected List<HttpServerFilter> httpServerFilters = Collections.emptyList(); public void setHttpServerFilters(List<HttpServerFilter> httpServerFilters) { this.httpServerFilters = httpServerFilters; } protected void initProduceProcessor() { produceProcessor = restOperationMeta.ensureFindProduceProcessor(requestEx); if (produceProcessor == null) { String msg = String.format("Accept %s is not supported", requestEx.getHeader(HttpHeaders.ACCEPT)); throw new InvocationException(Status.NOT_ACCEPTABLE, msg); } } protected void setContext() throws Exception { String strCseContext = requestEx.getHeader(Const.CSE_CONTEXT); if (StringUtils.isEmpty(strCseContext)) { return; } @SuppressWarnings("unchecked") Map<String, String> cseContext = JsonUtils.readValue(strCseContext.getBytes(StandardCharsets.UTF_8), Map.class); invocation.setContext(cseContext); } public void invoke() { try { Response response = prepareInvoke(); if (response != null) { sendResponseQuietly(response); return; } doInvoke(); } catch (Throwable e) { LOGGER.error("unknown rest exception.", e); sendFailResponse(e); } } protected Response prepareInvoke() throws Throwable { this.initProduceProcessor(); this.setContext(); invocation.getHandlerContext().put(RestConst.REST_REQUEST, requestEx); for (HttpServerFilter filter : httpServerFilters) { Response response = filter.afterReceiveRequest(invocation, requestEx); if (response != null) { return response; } } return null; } protected abstract void doInvoke() throws Throwable; public void sendFailResponse(Throwable throwable) { if (produceProcessor == null) { produceProcessor = ProduceProcessorManager.DEFAULT_PROCESSOR; } Response response = Response.createProducerFail(throwable); sendResponseQuietly(response); } protected void sendResponseQuietly(Response response) { try { sendResponse(response); } catch (Throwable e) { LOGGER.error("Failed to send rest response, operation:{}.", invocation.getMicroserviceQualifiedName(), e); } finally { requestEx.getAsyncContext().complete(); } } @SuppressWarnings("deprecation") protected void sendResponse(Response response) throws Exception { if (response.getHeaders().getHeaderMap() != null) { for (Entry<String, List<Object>> entry : response.getHeaders().getHeaderMap().entrySet()) { for (Object value : entry.getValue()) { responseEx.addHeader(entry.getKey(), String.valueOf(value)); } } } responseEx.setStatus(response.getStatusCode(), response.getReasonPhrase()); responseEx.setContentType(produceProcessor.getName()); Object body = response.getResult(); if (response.isFailed()) { body = ((InvocationException) body).getErrorData(); } try (BufferOutputStream output = new BufferOutputStream(Unpooled.compositeBuffer())) { produceProcessor.encodeResponse(output, body); responseEx.setBodyBuffer(output.getBuffer()); for (HttpServerFilter filter : httpServerFilters) { filter.beforeSendResponse(invocation, responseEx); } responseEx.flushBuffer(); } } }
1
7,121
maybe it's better to remove HttpHeaders.CONTENT_LENGTH after the loop
apache-servicecomb-java-chassis
java
@@ -679,6 +679,12 @@ public interface List<T> extends LinearSeq<T>, Stack<T> { @Override default List<T> dropRight(int n) { + if (n <= 0) { + return this; + } + if (n >= length()) { + return empty(); + } return reverse().drop(n).reverse(); }
1
/* / \____ _ ______ _____ / \____ ____ _____ * / \__ \/ \ / \__ \ / __// \__ \ / \/ __ \ Javaslang * _/ // _\ \ \/ / _\ \\_ \/ // _\ \ /\ \__/ / Copyright 2014-2015 Daniel Dietrich * /___/ \_____/\____/\_____/____/\___\_____/_/ \_/____/ Licensed under the Apache License, Version 2.0 */ package javaslang.collection; import javaslang.Kind; import javaslang.Lazy; import javaslang.Tuple; import javaslang.Tuple2; import javaslang.control.None; import javaslang.control.Option; import javaslang.control.Some; import java.io.*; import java.util.*; import java.util.function.*; import java.util.stream.Collector; /** * An immutable {@code List} is an eager sequence of elements. Its immutability makes it suitable for concurrent programming. * <p> * A {@code List} is composed of a {@code head} element and a {@code tail} {@code List}. * <p> * There are two implementations of the {@code List} interface: * <ul> * <li>{@link Nil}, which represents the empty {@code List}.</li> * <li>{@link Cons}, which represents a {@code List} containing one or more elements.</li> * </ul> * Methods to obtain a {@code List}: * <pre> * <code> * // factory methods * List.empty() // = List.of() = Nil.instance() * List.of(x) // = new Cons&lt;&gt;(x, Nil.instance()) * List.of(Object...) // e.g. List.of(1, 2, 3) * List.ofAll(Iterable) // e.g. List.ofAll(Stream.of(1, 2, 3)) = 1, 2, 3 * List.ofAll(&lt;primitive array&gt;) // e.g. List.ofAll(new int[] {1, 2, 3}) = 1, 2, 3 * * // int sequences * List.range(0, 3) // = 0, 1, 2 * List.rangeClosed(0, 3) // = 0, 1, 2, 3 * </code> * </pre> * * Note: A {@code List} is primary a {@code Seq} and extends {@code Stack} for technical reasons (so {@code Stack} does not need to wrap {@code List}). * * * Factory method applications: * * <pre> * <code> * List&lt;Integer&gt; s1 = List.of(1); * List&lt;Integer&gt; s2 = List.of(1, 2, 3); * // = List.of(new Integer[] {1, 2, 3}); * * List&lt;int[]&gt; s3 = List.of(new int[] {1, 2, 3}); * List&lt;List&lt;Integer&gt;&gt; s4 = List.of(List.of(1, 2, 3)); * * List&lt;Integer&gt; s5 = List.ofAll(new int[] {1, 2, 3}); * List&lt;Integer&gt; s6 = List.ofAll(List.of(1, 2, 3)); * * // cuckoo's egg * List&lt;Integer[]&gt; s7 = List.&lt;Integer[]&gt; of(new Integer[] {1, 2, 3}); * //!= List.&lt;Integer[]&gt; of(1, 2, 3); * </code> * </pre> * * Example: Converting a String to digits * * <pre> * <code> * // = List(1, 2, 3) * List.of("123".toCharArray()).map(c -&gt; Character.digit(c, 10)) * </code> * </pre> * * See Okasaki, Chris: <em>Purely Functional Data Structures</em> (p. 7 ff.). Cambridge, 2003. * * @param <T> Component type of the List * @since 1.1.0 */ public interface List<T> extends LinearSeq<T>, Stack<T> { /** * Returns a {@link java.util.stream.Collector} which may be used in conjunction with * {@link java.util.stream.Stream#collect(java.util.stream.Collector)} to obtain a {@link javaslang.collection.List}s. * * @param <T> Component type of the List. * @return A javaslang.collection.List Collector. */ static <T> Collector<T, ArrayList<T>, List<T>> collector() { final Supplier<ArrayList<T>> supplier = ArrayList::new; final BiConsumer<ArrayList<T>, T> accumulator = ArrayList::add; final BinaryOperator<ArrayList<T>> combiner = (left, right) -> { left.addAll(right); return left; }; final Function<ArrayList<T>, List<T>> finisher = List::ofAll; return Collector.of(supplier, accumulator, combiner, finisher); } /** * Returns the single instance of Nil. Convenience method for {@code Nil.instance()} . * <p> * Note: this method intentionally returns type {@code List} and not {@code Nil}. This comes handy when folding. * If you explicitly need type {@code Nil} use {@linkplain Nil#instance()}. * * @param <T> Component type of Nil, determined by type inference in the particular context. * @return The empty list. */ static <T> List<T> empty() { return Nil.instance(); } /** * Returns a singleton {@code List}, i.e. a {@code List} of one element. * * @param element An element. * @param <T> The component type * @return A new List instance containing the given element */ static <T> List<T> of(T element) { return new Cons<>(element, Nil.instance()); } /** * <p> * Creates a List of the given elements. * </p> * * <pre> * <code> List.of(1, 2, 3, 4) * = Nil.instance().prepend(4).prepend(3).prepend(2).prepend(1) * = new Cons(1, new Cons(2, new Cons(3, new Cons(4, Nil.instance()))))</code> * </pre> * * @param <T> Component type of the List. * @param elements Zero or more elements. * @return A list containing the given elements in the same order. * @throws NullPointerException if {@code elements} is null */ @SafeVarargs static <T> List<T> of(T... elements) { Objects.requireNonNull(elements, "elements is null"); List<T> result = Nil.<T> instance(); for (int i = elements.length - 1; i >= 0; i--) { result = result.prepend(elements[i]); } return result; } /** * Creates a List of the given elements. * * The resulting list has the same iteration order as the given iterable of elements * if the iteration order of the elements is stable. * * @param <T> Component type of the List. * @param elements An Iterable of elements. * @return A list containing the given elements in the same order. * @throws NullPointerException if {@code elements} is null */ @SuppressWarnings("unchecked") static <T> List<T> ofAll(Iterable<? extends T> elements) { Objects.requireNonNull(elements, "elements is null"); if (elements instanceof List) { return (List<T>) elements; } else if (elements instanceof java.util.List) { List<T> result = Nil.instance(); final java.util.List<T> list = (java.util.List<T>) elements; final ListIterator<T> iterator = list.listIterator(list.size()); while (iterator.hasPrevious()) { result = result.prepend(iterator.previous()); } return result; } else if (elements instanceof NavigableSet) { List<T> result = Nil.instance(); final java.util.Iterator<T> iterator = ((NavigableSet<T>) elements).descendingIterator(); while (iterator.hasNext()) { result = result.prepend(iterator.next()); } return result; } else { List<T> result = Nil.instance(); for (T element : elements) { result = result.prepend(element); } return result.reverse(); } } /** * Creates a List based on the elements of a boolean array. * * @param array a boolean array * @return A new List of Boolean values */ static List<Boolean> ofAll(boolean[] array) { Objects.requireNonNull(array, "array is null"); return List.ofAll(() -> new Iterator<Boolean>() { int i = 0; @Override public boolean hasNext() { return i < array.length; } @Override public Boolean next() { return array[i++]; } }); } /** * Creates a List based on the elements of a byte array. * * @param array a byte array * @return A new List of Byte values */ static List<Byte> ofAll(byte[] array) { Objects.requireNonNull(array, "array is null"); return List.ofAll(() -> new Iterator<Byte>() { int i = 0; @Override public boolean hasNext() { return i < array.length; } @Override public Byte next() { return array[i++]; } }); } /** * Creates a List based on the elements of a char array. * * @param array a char array * @return A new List of Character values */ static List<Character> ofAll(char[] array) { Objects.requireNonNull(array, "array is null"); return List.ofAll(() -> new Iterator<Character>() { int i = 0; @Override public boolean hasNext() { return i < array.length; } @Override public Character next() { return array[i++]; } }); } /** * Creates a List based on the elements of a double array. * * @param array a double array * @return A new List of Double values */ static List<Double> ofAll(double[] array) { Objects.requireNonNull(array, "array is null"); return List.ofAll(() -> new Iterator<Double>() { int i = 0; @Override public boolean hasNext() { return i < array.length; } @Override public Double next() { return array[i++]; } }); } /** * Creates a List based on the elements of a float array. * * @param array a float array * @return A new List of Float values */ static List<Float> ofAll(float[] array) { Objects.requireNonNull(array, "array is null"); return List.ofAll(() -> new Iterator<Float>() { int i = 0; @Override public boolean hasNext() { return i < array.length; } @Override public Float next() { return array[i++]; } }); } /** * Creates a List based on the elements of an int array. * * @param array an int array * @return A new List of Integer values */ static List<Integer> ofAll(int[] array) { Objects.requireNonNull(array, "array is null"); return List.ofAll(() -> new Iterator<Integer>() { int i = 0; @Override public boolean hasNext() { return i < array.length; } @Override public Integer next() { return array[i++]; } }); } /** * Creates a List based on the elements of a long array. * * @param array a long array * @return A new List of Long values */ static List<Long> ofAll(long[] array) { Objects.requireNonNull(array, "array is null"); return List.ofAll(() -> new Iterator<Long>() { int i = 0; @Override public boolean hasNext() { return i < array.length; } @Override public Long next() { return array[i++]; } }); } /** * Creates a List based on the elements of a short array. * * @param array a short array * @return A new List of Short values */ static List<Short> ofAll(short[] array) { Objects.requireNonNull(array, "array is null"); return List.ofAll(() -> new Iterator<Short>() { int i = 0; @Override public boolean hasNext() { return i < array.length; } @Override public Short next() { return array[i++]; } }); } /** * Creates a List of int numbers starting from {@code from}, extending to {@code toExclusive - 1}. * <p> * Examples: * <pre> * <code> * List.range(0, 0) // = List() * List.range(2, 0) // = List() * List.range(-2, 2) // = List(-2, -1, 0, 1) * </code> * </pre> * * @param from the first number * @param toExclusive the last number + 1 * @return a range of int values as specified or the empty range if {@code from >= toExclusive} */ static List<Integer> range(int from, int toExclusive) { return List.rangeBy(from, toExclusive, 1); } /** * Creates a List of int numbers starting from {@code from}, extending to {@code toExclusive - 1}, * with {@code step}. * <p> * Examples: * <pre> * <code> * List.rangeBy(1, 3, 1) // = List(1, 2) * List.rangeBy(1, 4, 2) // = List(1, 3) * List.rangeBy(4, 1, -2) // = List(4, 2) * List.rangeBy(4, 1, 2) // = List() * </code> * </pre> * * @param from the first number * @param toExclusive the last number + 1 * @param step the step * @return a range of long values as specified or the empty range if<br> * {@code from >= toInclusive} and {@code step > 0} or<br> * {@code from <= toInclusive} and {@code step < 0} * @throws IllegalArgumentException if {@code step} is zero */ static List<Integer> rangeBy(int from, int toExclusive, int step) { if (step == 0) { throw new IllegalArgumentException("step cannot be 0"); } else if (from == toExclusive || step * (from - toExclusive) > 0) { return List.empty(); } else { final int one = (from < toExclusive) ? 1 : -1; return List.rangeClosedBy(from, toExclusive - one, step); } } /** * Creates a List of long numbers starting from {@code from}, extending to {@code toExclusive - 1}. * <p> * Examples: * <pre> * <code> * List.range(0L, 0L) // = List() * List.range(2L, 0L) // = List() * List.range(-2L, 2L) // = List(-2L, -1L, 0L, 1L) * </code> * </pre> * * @param from the first number * @param toExclusive the last number + 1 * @return a range of long values as specified or the empty range if {@code from >= toExclusive} */ static List<Long> range(long from, long toExclusive) { return List.rangeBy(from, toExclusive, 1); } /** * Creates a List of long numbers starting from {@code from}, extending to {@code toExclusive - 1}, * with {@code step}. * <p> * Examples: * <pre> * <code> * List.rangeBy(1L, 3L, 1L) // = List(1L, 2L) * List.rangeBy(1L, 4L, 2L) // = List(1L, 3L) * List.rangeBy(4L, 1L, -2L) // = List(4L, 2L) * List.rangeBy(4L, 1L, 2L) // = List() * </code> * </pre> * * @param from the first number * @param toExclusive the last number + 1 * @param step the step * @return a range of long values as specified or the empty range if<br> * {@code from >= toInclusive} and {@code step > 0} or<br> * {@code from <= toInclusive} and {@code step < 0} * @throws IllegalArgumentException if {@code step} is zero */ static List<Long> rangeBy(long from, long toExclusive, long step) { if (step == 0) { throw new IllegalArgumentException("step cannot be 0"); } else if (from == toExclusive || step * (from - toExclusive) > 0) { return List.empty(); } else { final int one = (from < toExclusive) ? 1 : -1; return List.rangeClosedBy(from, toExclusive - one, step); } } /** * Creates a List of int numbers starting from {@code from}, extending to {@code toInclusive}. * <p> * Examples: * <pre> * <code> * List.rangeClosed(0, 0) // = List(0) * List.rangeClosed(2, 0) // = List() * List.rangeClosed(-2, 2) // = List(-2, -1, 0, 1, 2) * </code> * </pre> * * @param from the first number * @param toInclusive the last number * @return a range of int values as specified or the empty range if {@code from > toInclusive} */ static List<Integer> rangeClosed(int from, int toInclusive) { return List.rangeClosedBy(from, toInclusive, 1); } /** * Creates a List of int numbers starting from {@code from}, extending to {@code toInclusive}, * with {@code step}. * <p> * Examples: * <pre> * <code> * List.rangeClosedBy(1, 3, 1) // = List(1, 2, 3) * List.rangeClosedBy(1, 4, 2) // = List(1, 3) * List.rangeClosedBy(4, 1, -2) // = List(4, 2) * List.rangeClosedBy(4, 1, 2) // = List() * </code> * </pre> * * @param from the first number * @param toInclusive the last number * @param step the step * @return a range of int values as specified or the empty range if<br> * {@code from > toInclusive} and {@code step > 0} or<br> * {@code from < toInclusive} and {@code step < 0} * @throws IllegalArgumentException if {@code step} is zero */ static List<Integer> rangeClosedBy(int from, int toInclusive, int step) { if (step == 0) { throw new IllegalArgumentException("step cannot be 0"); } else if (from == toInclusive) { return List.of(from); } else if (step * (from - toInclusive) > 0) { return List.empty(); } else { final int gap = (from - toInclusive) % step; final int signum = (from < toInclusive) ? -1 : 1; final int bound = from * signum; List<Integer> result = List.empty(); for (int i = toInclusive + gap; i * signum <= bound; i -= step) { result = result.prepend(i); } return result; } } /** * Creates a List of long numbers starting from {@code from}, extending to {@code toInclusive}. * <p> * Examples: * <pre> * <code> * List.rangeClosed(0L, 0L) // = List(0L) * List.rangeClosed(2L, 0L) // = List() * List.rangeClosed(-2L, 2L) // = List(-2L, -1L, 0L, 1L, 2L) * </code> * </pre> * * @param from the first number * @param toInclusive the last number * @return a range of long values as specified or the empty range if {@code from > toInclusive} */ static List<Long> rangeClosed(long from, long toInclusive) { return List.rangeClosedBy(from, toInclusive, 1L); } /** * Creates a List of long numbers starting from {@code from}, extending to {@code toInclusive}, * with {@code step}. * <p> * Examples: * <pre> * <code> * List.rangeClosedBy(1L, 3L, 1L) // = List(1L, 2L, 3L) * List.rangeClosedBy(1L, 4L, 2L) // = List(1L, 3L) * List.rangeClosedBy(4L, 1L, -2L) // = List(4L, 2L) * List.rangeClosedBy(4L, 1L, 2L) // = List() * </code> * </pre> * * @param from the first number * @param toInclusive the last number * @param step the step * @return a range of int values as specified or the empty range if<br> * {@code from > toInclusive} and {@code step > 0} or<br> * {@code from < toInclusive} and {@code step < 0} * @throws IllegalArgumentException if {@code step} is zero */ static List<Long> rangeClosedBy(long from, long toInclusive, long step) { if (step == 0) { throw new IllegalArgumentException("step cannot be 0"); } else if (from == toInclusive) { return List.of(from); } else if (step * (from - toInclusive) > 0) { return List.empty(); } else { final long gap = (from - toInclusive) % step; final int signum = (from < toInclusive) ? -1 : 1; final long bound = from * signum; List<Long> result = List.empty(); for (long i = toInclusive + gap; i * signum <= bound; i -= step) { result = result.prepend(i); } return result; } } @Override default List<T> append(T element) { return foldRight(List.of(element), (x, xs) -> xs.prepend(x)); } @Override default List<T> appendAll(Iterable<? extends T> elements) { Objects.requireNonNull(elements, "elements is null"); return foldRight(List.ofAll(elements), (x, xs) -> xs.prepend(x)); } @Override default List<Tuple2<T, T>> cartesianProduct() { return cartesianProduct(this); } @Override default <U> List<Tuple2<T, U>> cartesianProduct(Iterable<? extends U> that) { Objects.requireNonNull(that, "that is null"); final List<? extends U> other = List.ofAll(that); return flatMap(a -> other.map(b -> Tuple.of(a, b))); } @Override default List<T> clear() { return Nil.instance(); } @Override default List<List<T>> combinations() { return List.rangeClosed(0, length()).map(this::combinations).flatMap(Function.identity()); } @Override default List<List<T>> combinations(int k) { class Recursion { List<List<T>> combinations(List<T> elements, int k) { return (k == 0) ? List.of(List.empty()) : elements.zipWithIndex().flatMap(t -> combinations(elements.drop(t._2 + 1), (k - 1)) .map((List<T> c) -> c.prepend(t._1))); } } return new Recursion().combinations(this, Math.max(k, 0)); } @Override default List<T> distinct() { return distinctBy(Function.identity()); } @Override default List<T> distinctBy(Comparator<? super T> comparator) { Objects.requireNonNull(comparator, "comparator is null"); final java.util.Set<T> seen = new java.util.TreeSet<>(comparator); return filter(seen::add); } @Override default <U> List<T> distinctBy(Function<? super T, ? extends U> keyExtractor) { Objects.requireNonNull(keyExtractor, "keyExtractor is null"); final java.util.Set<U> seen = new java.util.HashSet<>(); return filter(t -> seen.add(keyExtractor.apply(t))); } @Override default List<T> drop(int n) { List<T> list = this; for (int i = n; i > 0 && !list.isEmpty(); i--) { list = list.tail(); } return list; } @Override default List<T> dropRight(int n) { return reverse().drop(n).reverse(); } @Override default List<T> dropWhile(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); List<T> list = this; while (!list.isEmpty() && predicate.test(list.head())) { list = list.tail(); } return list; } @Override default List<T> filter(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); return isEmpty() ? this : foldLeft(List.<T> empty(), (xs, x) -> predicate.test(x) ? xs.prepend(x) : xs).reverse(); } @Override default List<Some<T>> filterOption(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); return isEmpty() ? List.empty() : foldLeft(List.<Some<T>> empty(), (xs, x) -> predicate.test(x) ? xs.prepend(new Some<>(x)) : xs).reverse(); } @Override default List<T> findAll(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); return filter(predicate); } @Override default <U> List<U> flatMap(Function<? super T, ? extends Iterable<? extends U>> mapper) { Objects.requireNonNull(mapper, "mapper is null"); if (isEmpty()) { return empty(); } else { List<U> list = empty(); for (T t : this) { for (U u : mapper.apply(t)) { list = list.prepend(u); } } return list.reverse(); } } @SuppressWarnings("unchecked") @Override default <U> List<U> flatMapM(Function<? super T, ? extends Kind<? extends IterableKind<?>, ? extends U>> mapper) { return flatMap((Function<? super T, ? extends Iterable<? extends U>>) mapper); } @Override List<Object> flatten(); @Override default void forEach(Consumer<? super T> action) { Objects.requireNonNull(action, "action is null"); Stack.super.forEach(action); } @Override default boolean forAll(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); return Stack.super.forAll(predicate); } @Override default T get(int index) { if (isEmpty()) { throw new IndexOutOfBoundsException("get(" + index + ") on Nil"); } if (index < 0) { throw new IndexOutOfBoundsException("get(" + index + ")"); } List<T> list = this; for (int i = index - 1; i >= 0; i--) { list = list.tail(); if (list.isEmpty()) { throw new IndexOutOfBoundsException(String.format("get(%s) on List of length %s", index, index - i)); } } return list.head(); } @Override default <C> Map<C, List<T>> groupBy(Function<? super T, ? extends C> classifier) { Map<C, List<T>> result = HashMap.empty(); for (T t : this) { final C key = classifier.apply(t); final List<T> list = result.get(key); result = result.put(key, (list == null) ? List.of(t) : list.prepend(t)); } return result; } @Override default List<List<T>> grouped(int size) { return sliding(size, size); } @Override default int indexOf(T element, int from) { int index = 0; for (List<T> list = this; !list.isEmpty(); list = list.tail(), index++) { if (index >= from && Objects.equals(list.head(), element)) { return index; } } return -1; } @Override List<T> init(); @Override Option<List<T>> initOption(); @Override int length(); @Override default List<T> insert(int index, T element) { if (index < 0) { throw new IndexOutOfBoundsException("insert(" + index + ", e)"); } List<T> preceding = Nil.instance(); List<T> tail = this; for (int i = index; i > 0; i--, tail = tail.tail()) { if (tail.isEmpty()) { throw new IndexOutOfBoundsException("insert(" + index + ", e) on List of length " + length()); } preceding = preceding.prepend(tail.head()); } List<T> result = tail.prepend(element); for (T next : preceding) { result = result.prepend(next); } return result; } @Override default List<T> insertAll(int index, Iterable<? extends T> elements) { Objects.requireNonNull(elements, "elements is null"); if (index < 0) { throw new IndexOutOfBoundsException("insertAll(" + index + ", elements)"); } List<T> preceding = Nil.instance(); List<T> tail = this; for (int i = index; i > 0; i--, tail = tail.tail()) { if (tail.isEmpty()) { throw new IndexOutOfBoundsException("insertAll(" + index + ", elements) on List of length " + length()); } preceding = preceding.prepend(tail.head()); } List<T> result = tail.prependAll(elements); for (T next : preceding) { result = result.prepend(next); } return result; } @Override default List<T> intersperse(T element) { return isEmpty() ? Nil.instance() : foldRight(empty(), (x, xs) -> xs.isEmpty() ? xs.prepend(x) : xs.prepend(element).prepend(x)); } @Override default int lastIndexOf(T element, int end) { int result = -1, index = 0; for (List<T> list = this; index <= end && !list.isEmpty(); list = list.tail(), index++) { if (Objects.equals(list.head(), element)) { result = index; } } return result; } @Override default <U> List<U> map(Function<? super T, ? extends U> mapper) { Objects.requireNonNull(mapper, "mapper is null"); List<U> list = empty(); for (T t : this) { list = list.prepend(mapper.apply(t)); } return list.reverse(); } @Override default Tuple2<List<T>, List<T>> partition(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); final java.util.List<T> left = new ArrayList<>(), right = new ArrayList<>(); for (T t : this) { (predicate.test(t) ? left : right).add(t); } return Tuple.of(List.ofAll(left), List.ofAll(right)); } @Override default T peek() { return head(); } /** * Performs an action on the head element of this {@code List}. * * @param action A {@code Consumer} * @return this {@code List} */ @Override default List<T> peek(Consumer<? super T> action) { Objects.requireNonNull(action, "action is null"); if (!isEmpty()) { action.accept(head()); } return this; } @Override default List<List<T>> permutations() { if (isEmpty()) { return Nil.instance(); } else { final List<T> tail = tail(); if (tail.isEmpty()) { return List.of(this); } else { final List<List<T>> zero = Nil.instance(); // TODO: IntelliJ IDEA 14.1.1 needs a redundant cast here, jdk 1.8.0_40 compiles fine return distinct().foldLeft(zero, (xs, x) -> xs.appendAll(remove(x).permutations().map((Function<List<T>, List<T>>) l -> l.prepend(x)))); } } } @Override default List<T> pop() { return tail(); } @Override Option<List<T>> popOption(); @Override default Tuple2<T, List<T>> pop2() { return Tuple.of(head(), tail()); } @Override Option<Tuple2<T, List<T>>> pop2Option(); @Override default List<T> prepend(T element) { return new Cons<>(element, this); } @Override default List<T> prependAll(Iterable<? extends T> elements) { Objects.requireNonNull(elements, "elements is null"); return isEmpty() ? List.ofAll(elements) : List.ofAll(elements).reverse().foldLeft(this, List::prepend); } @Override default List<T> push(T element) { return new Cons<>(element, this); } @SuppressWarnings("unchecked") @Override default List<T> push(T... elements) { Objects.requireNonNull(elements, "elements is null"); List<T> result = Nil.<T> instance(); for (T element : elements) { result = result.prepend(element); } return result; } @Override default List<T> pushAll(Iterable<T> elements) { Objects.requireNonNull(elements, "elements is null"); List<T> result = Nil.<T> instance(); for (T element : elements) { result = result.prepend(element); } return result; } @Override default List<T> remove(T element) { List<T> preceding = Nil.instance(); List<T> tail = this; boolean found = false; while (!found && !tail.isEmpty()) { final T head = tail.head(); if (head.equals(element)) { found = true; } else { preceding = preceding.prepend(head); } tail = tail.tail(); } List<T> result = tail; for (T next : preceding) { result = result.prepend(next); } return result; } @Override default List<T> removeFirst(Predicate<T> predicate) { List<T> init = List.empty(); List<T> tail = this; while (!tail.isEmpty() && !predicate.test(tail.head())) { init = init.prepend(tail.head()); tail = tail.tail(); } if (!tail.isEmpty()) { tail = tail.tail(); } return init.foldLeft(tail, List::prepend); } @Override default List<T> removeLast(Predicate<T> predicate) { return reverse().removeFirst(predicate).reverse(); } @Override List<T> removeAt(int indx); @Override default List<T> removeAll(T removed) { List<T> result = Nil.instance(); for (T element : this) { if (!element.equals(removed)) { result = result.prepend(element); } } return result.reverse(); } @Override default List<T> removeAll(Iterable<? extends T> elements) { Objects.requireNonNull(elements, "elements is null"); List<T> removed = List.ofAll(elements).distinct(); List<T> result = Nil.instance(); for (T element : this) { if (!removed.contains(element)) { result = result.prepend(element); } } return result.reverse(); } @Override default List<T> replace(T currentElement, T newElement) { List<T> preceding = Nil.instance(); List<T> tail = this; while (!tail.isEmpty() && !Objects.equals(tail.head(), currentElement)) { preceding = preceding.prepend(tail.head()); tail = tail.tail(); } if (tail.isEmpty()) { return this; } // skip the current head element because it is replaced List<T> result = tail.tail().prepend(newElement); for (T next : preceding) { result = result.prepend(next); } return result; } @Override default List<T> replaceAll(T currentElement, T newElement) { List<T> result = Nil.instance(); for (List<T> list = this; !list.isEmpty(); list = list.tail()) { final T head = list.head(); final T elem = Objects.equals(head, currentElement) ? newElement : head; result = result.prepend(elem); } return result.reverse(); } @Override default List<T> replaceAll(UnaryOperator<T> operator) { Objects.requireNonNull(operator, "operator is null"); List<T> result = Nil.instance(); for (T element : this) { result = result.prepend(operator.apply(element)); } return result.reverse(); } @Override default List<T> retainAll(Iterable<? extends T> elements) { Objects.requireNonNull(elements, "elements is null"); final List<T> keeped = List.ofAll(elements).distinct(); List<T> result = Nil.instance(); for (T element : this) { if (keeped.contains(element)) { result = result.prepend(element); } } return result.reverse(); } @Override default List<T> reverse() { return isEmpty() ? this : foldLeft(empty(), List::prepend); } @Override default List<T> set(int index, T element) { if (isEmpty()) { throw new IndexOutOfBoundsException("set(" + index + ", e) on Nil"); } if (index < 0) { throw new IndexOutOfBoundsException("set(" + index + ", e)"); } List<T> preceding = Nil.instance(); List<T> tail = this; for (int i = index; i > 0; i--, tail = tail.tail()) { if (tail.isEmpty()) { throw new IndexOutOfBoundsException("set(" + index + ", e) on List of length " + length()); } preceding = preceding.prepend(tail.head()); } if (tail.isEmpty()) { throw new IndexOutOfBoundsException("set(" + index + ", e) on List of length " + length()); } // skip the current head element because it is replaced List<T> result = tail.tail().prepend(element); for (T next : preceding) { result = result.prepend(next); } return result; } @Override default List<List<T>> sliding(int size) { return sliding(size, 1); } @Override default List<List<T>> sliding(int size, int step) { if (size <= 0 || step <= 0) { throw new IllegalArgumentException(String.format("size: %s or step: %s not positive", size, step)); } List<List<T>> result = Nil.instance(); List<T> list = this; while (!list.isEmpty()) { final Tuple2<List<T>, List<T>> split = list.splitAt(size); result = result.prepend(split._1); list = split._2.isEmpty() ? Nil.instance() : list.drop(step); } return result.reverse(); } @Override default List<T> sort() { return isEmpty() ? this : toJavaStream().sorted().collect(List.collector()); } @Override default List<T> sort(Comparator<? super T> comparator) { Objects.requireNonNull(comparator, "comparator is null"); return isEmpty() ? this : toJavaStream().sorted(comparator).collect(List.collector()); } @Override default Tuple2<List<T>, List<T>> span(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); return Tuple.of(takeWhile(predicate), dropWhile(predicate)); } @Override Tuple2<List<T>, List<T>> splitAt(int n); @Override Tuple2<List<T>, List<T>> splitAt(Predicate<? super T> predicate); @Override Tuple2<List<T>, List<T>> splitAtInclusive(Predicate<? super T> predicate); @Override default Spliterator<T> spliterator() { return Spliterators.spliterator(iterator(), length(), Spliterator.ORDERED | Spliterator.IMMUTABLE); } @Override default List<T> subsequence(int beginIndex) { if (beginIndex < 0) { throw new IndexOutOfBoundsException("subsequence(" + beginIndex + ")"); } List<T> result = this; for (int i = 0; i < beginIndex; i++, result = result.tail()) { if (result.isEmpty()) { throw new IndexOutOfBoundsException( String.format("subsequence(%s) on List of length %s", beginIndex, i)); } } return result; } @Override default List<T> subsequence(int beginIndex, int endIndex) { if (beginIndex < 0 || beginIndex > endIndex) { throw new IndexOutOfBoundsException( String.format("subsequence(%s, %s) on List of length %s", beginIndex, endIndex, length())); } List<T> result = Nil.instance(); List<T> list = this; for (int i = 0; i < endIndex; i++, list = list.tail()) { if (list.isEmpty()) { throw new IndexOutOfBoundsException( String.format("subsequence(%s, %s) on List of length %s", beginIndex, endIndex, i)); } if (i >= beginIndex) { result = result.prepend(list.head()); } } return result.reverse(); } @Override List<T> tail(); @Override Option<List<T>> tailOption(); @Override default List<T> take(int n) { List<T> result = Nil.instance(); List<T> list = this; for (int i = 0; i < n && !list.isEmpty(); i++, list = list.tail()) { result = result.prepend(list.head()); } return result.reverse(); } @Override default List<T> takeRight(int n) { return reverse().take(n).reverse(); } @Override default List<T> takeWhile(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); List<T> result = Nil.instance(); for (List<T> list = this; !list.isEmpty() && predicate.test(list.head()); list = list.tail()) { result = result.prepend(list.head()); } return result.reverse(); } @Override default <U> List<U> unit(Iterable<? extends U> iterable) { return List.ofAll(iterable); } @Override default <T1, T2> Tuple2<List<T1>, List<T2>> unzip( Function<? super T, Tuple2<? extends T1, ? extends T2>> unzipper) { Objects.requireNonNull(unzipper, "unzipper is null"); List<T1> xs = Nil.instance(); List<T2> ys = Nil.instance(); for (T element : this) { final Tuple2<? extends T1, ? extends T2> t = unzipper.apply(element); xs = xs.prepend(t._1); ys = ys.prepend(t._2); } return Tuple.of(xs.reverse(), ys.reverse()); } @Override default <U> List<Tuple2<T, U>> zip(Iterable<U> that) { Objects.requireNonNull(that, "that is null"); List<Tuple2<T, U>> result = Nil.instance(); List<T> list1 = this; java.util.Iterator<U> list2 = that.iterator(); while (!list1.isEmpty() && list2.hasNext()) { result = result.prepend(Tuple.of(list1.head(), list2.next())); list1 = list1.tail(); } return result.reverse(); } @Override default <U> List<Tuple2<T, U>> zipAll(Iterable<U> that, T thisElem, U thatElem) { Objects.requireNonNull(that, "that is null"); List<Tuple2<T, U>> result = Nil.instance(); Iterator<T> list1 = this.iterator(); java.util.Iterator<U> list2 = that.iterator(); while (list1.hasNext() || list2.hasNext()) { final T elem1 = list1.hasNext() ? list1.next() : thisElem; final U elem2 = list2.hasNext() ? list2.next() : thatElem; result = result.prepend(Tuple.of(elem1, elem2)); } return result.reverse(); } @Override default List<Tuple2<T, Integer>> zipWithIndex() { List<Tuple2<T, Integer>> result = Nil.instance(); int index = 0; for (List<T> list = this; !list.isEmpty(); list = list.tail()) { result = result.prepend(Tuple.of(list.head(), index++)); } return result.reverse(); } /** * Non-empty {@code List}, consisting of a {@code head} and a {@code tail}. * * @param <T> Component type of the List. * @since 1.1.0 */ // DEV NOTE: class declared final because of serialization proxy pattern (see Effective Java, 2nd ed., p. 315) final class Cons<T> implements List<T>, Serializable { private static final long serialVersionUID = 1L; private final T head; private final List<T> tail; private final int length; private final transient Lazy<Integer> hashCode = Lazy.of(() -> Traversable.hash(this)); /** * Creates a List consisting of a head value and a trailing List. * * @param head The head * @param tail The tail */ public Cons(T head, List<T> tail) { this.head = head; this.tail = tail; this.length = 1 + tail.length(); } @Override public List<Object> flatten() { return flatMap(t -> (t instanceof Iterable) ? List.ofAll((Iterable<?>) t).flatten() : List.of(t)); } @Override public T head() { return head; } @Override public Some<T> headOption() { return new Some<>(head); } @Override public List<T> init() { return dropRight(1); } @Override public Some<List<T>> initOption() { return new Some<>(init()); } @Override public int length() { return length; } @Override public Tuple2<List<T>, List<T>> splitAt(int n) { List<T> init = Nil.instance(); List<T> tail = this; while (n > 0 && !tail.isEmpty()) { init = init.prepend(tail.head()); tail = tail.tail(); n--; } return Tuple.of(init.reverse(), tail); } @Override public Tuple2<List<T>, List<T>> splitAt(Predicate<? super T> predicate) { final Tuple2<List<T>, List<T>> t = splitByPredicateReversed(this, predicate); if (t._2.isEmpty()) { return Tuple.of(this, empty()); } else { return Tuple.of(t._1.reverse(), t._2); } } @Override public Tuple2<List<T>, List<T>> splitAtInclusive(Predicate<? super T> predicate) { final Tuple2<List<T>, List<T>> t = splitByPredicateReversed(this, predicate); if (t._2.isEmpty() || t._2.tail().isEmpty()) { return Tuple.of(this, empty()); } else { return Tuple.of(t._1.prepend(t._2.head()).reverse(), t._2.tail()); } } private static <T> Tuple2<List<T>, List<T>> splitByPredicateReversed(List<T> source, Predicate<? super T> predicate) { List<T> init = Nil.instance(); List<T> tail = source; while (!tail.isEmpty() && !predicate.test(tail.head())) { init = init.prepend(tail.head()); tail = tail.tail(); } return Tuple.of(init, tail); } @Override public Some<T> peekOption() { return new Some<>(head()); } @Override public Some<List<T>> popOption() { return new Some<>(tail()); } @Override public Some<Tuple2<T, List<T>>> pop2Option() { return new Some<>(Tuple.of(head(), tail())); } @Override public List<T> removeAt(int indx) { if(indx < 0) { throw new IndexOutOfBoundsException("removeAt(" + indx + ")"); } List<T> init = Nil.instance(); List<T> tail = this; while (indx > 0 && !tail.isEmpty()) { init = init.prepend(tail.head()); tail = tail.tail(); indx--; } if(indx > 0 && tail.isEmpty()) { throw new IndexOutOfBoundsException("removeAt() on Nil"); } return init.reverse().appendAll(tail.tail()); } @Override public List<T> tail() { return tail; } @Override public Some<List<T>> tailOption() { return new Some<>(tail); } @Override public boolean isEmpty() { return false; } @Override public boolean equals(Object o) { if (o == this) { return true; } else if (o instanceof List) { List<?> list1 = this; List<?> list2 = (List<?>) o; while (!list1.isEmpty() && !list2.isEmpty()) { final boolean isEqual = Objects.equals(list1.head(), list2.head()); if (!isEqual) { return false; } list1 = list1.tail(); list2 = list2.tail(); } return list1.isEmpty() && list2.isEmpty(); } else { return false; } } @Override public int hashCode() { return hashCode.get(); } @Override public String toString() { return map(String::valueOf).join(", ", "List(", ")"); } /** * <p> * {@code writeReplace} method for the serialization proxy pattern. * </p> * <p> * The presence of this method causes the serialization system to emit a SerializationProxy instance instead of * an instance of the enclosing class. * </p> * * @return A SerialiationProxy for this enclosing class. */ private Object writeReplace() { return new SerializationProxy<>(this); } /** * <p> * {@code readObject} method for the serialization proxy pattern. * </p> * Guarantees that the serialization system will never generate a serialized instance of the enclosing class. * * @param stream An object serialization stream. * @throws java.io.InvalidObjectException This method will throw with the message "Proxy required". */ private void readObject(ObjectInputStream stream) throws InvalidObjectException { throw new InvalidObjectException("Proxy required"); } /** * A serialization proxy which, in this context, is used to deserialize immutable, linked Lists with final * instance fields. * * @param <T> The component type of the underlying list. */ // DEV NOTE: The serialization proxy pattern is not compatible with non-final, i.e. extendable, // classes. Also, it may not be compatible with circular object graphs. private static final class SerializationProxy<T> implements Serializable { private static final long serialVersionUID = 1L; // the instance to be serialized/deserialized private transient Cons<T> list; /** * Constructor for the case of serialization, called by {@link Cons#writeReplace()}. * <p/> * The constructor of a SerializationProxy takes an argument that concisely represents the logical state of * an instance of the enclosing class. * * @param list a Cons */ SerializationProxy(Cons<T> list) { this.list = list; } /** * Write an object to a serialization stream. * * @param s An object serialization stream. * @throws java.io.IOException If an error occurs writing to the stream. */ private void writeObject(ObjectOutputStream s) throws IOException { s.defaultWriteObject(); s.writeInt(list.length()); for (List<T> l = list; !l.isEmpty(); l = l.tail()) { s.writeObject(l.head()); } } /** * Read an object from a deserialization stream. * * @param s An object deserialization stream. * @throws ClassNotFoundException If the object's class read from the stream cannot be found. * @throws InvalidObjectException If the stream contains no list elements. * @throws IOException If an error occurs reading from the stream. */ private void readObject(ObjectInputStream s) throws ClassNotFoundException, IOException { s.defaultReadObject(); final int size = s.readInt(); if (size <= 0) { throw new InvalidObjectException("No elements"); } List<T> temp = Nil.instance(); for (int i = 0; i < size; i++) { @SuppressWarnings("unchecked") final T element = (T) s.readObject(); temp = temp.prepend(element); } list = (Cons<T>) temp.reverse(); } /** * <p> * {@code readResolve} method for the serialization proxy pattern. * </p> * Returns a logically equivalent instance of the enclosing class. The presence of this method causes the * serialization system to translate the serialization proxy back into an instance of the enclosing class * upon deserialization. * * @return A deserialized instance of the enclosing class. */ private Object readResolve() { return list; } } } /** * Representation of the singleton empty {@code List}. * * @param <T> Component type of the List. * @since 1.1.0 */ final class Nil<T> implements List<T>, Serializable { private static final long serialVersionUID = 1L; private static final Nil<?> INSTANCE = new Nil<>(); // hidden private Nil() { } /** * Returns the singleton instance of the liked list. * * @param <T> Component type of the List * @return the singleton instance of the linked list. */ @SuppressWarnings("unchecked") public static <T> Nil<T> instance() { return (Nil<T>) INSTANCE; } @Override public Nil<Object> flatten() { return Nil.instance(); } @Override public T head() { throw new NoSuchElementException("head of empty list"); } @Override public None<T> headOption() { return None.instance(); } @Override public List<T> init() { throw new UnsupportedOperationException("init of empty list"); } @Override public None<List<T>> initOption() { return None.instance(); } @Override public int length() { return 0; } @Override public Tuple2<List<T>, List<T>> splitAt(int n) { return Tuple.of(empty(), empty()); } @Override public Tuple2<List<T>, List<T>> splitAt(Predicate<? super T> predicate) { return Tuple.of(empty(), empty()); } @Override public Tuple2<List<T>, List<T>> splitAtInclusive(Predicate<? super T> predicate) { return Tuple.of(empty(), empty()); } @Override public None<T> peekOption() { return None.instance(); } @Override public None<List<T>> popOption() { return None.instance(); } @Override public None<Tuple2<T, List<T>>> pop2Option() { return None.instance(); } @Override public List<T> removeAt(int indx) { throw new IndexOutOfBoundsException("removeAt() on Nil"); } @Override public List<T> tail() { throw new UnsupportedOperationException("tail of empty list"); } @Override public None<List<T>> tailOption() { return None.instance(); } @Override public boolean isEmpty() { return true; } @Override public boolean equals(Object o) { return o == this; } @Override public int hashCode() { return Traversable.hash(this); } @Override public String toString() { return "List()"; } /** * Instance control for object serialization. * * @return The singleton instance of Nil. * @see java.io.Serializable */ private Object readResolve() { return INSTANCE; } } }
1
6,176
Very cool. We are now collecting the fruits after your length implementation!
vavr-io-vavr
java
@@ -0,0 +1,8 @@ +rules: + - name: all pubs are in whitelist + project: '*' + network: '*' + is_external_network: True + whitelist: + - xpn-master:xpn-network + - content-insights:default
1
1
26,493
Is this the same copy of the rules file from above? If so, can just use the copy from above, and this can be dropped.
forseti-security-forseti-security
py
@@ -264,6 +264,13 @@ func (acsSession *session) startACSSession(client wsclient.ClientServer, timer t client.AddRequestHandler(refreshCredsHandler.handlerFunc()) + // Add handler to ack ENI attach message + eniAttachHandler := newAttachENIHandler(acsSession.ctx, cfg.Cluster, acsSession.containerInstanceARN, client, acsSession.taskEngine, acsSession.stateManager) + eniAttachHandler.start() + defer eniAttachHandler.stop() + + client.AddRequestHandler(eniAttachHandler.handlerFunc()) + // Add request handler for handling payload messages from ACS payloadHandler := newPayloadRequestHandler( acsSession.ctx,
1
// Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"). You may // not use this file except in compliance with the License. A copy of the // License is located at // // http://aws.amazon.com/apache2.0/ // // or in the "license" file accompanying this file. This file is distributed // on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either // express or implied. See the License for the specific language governing // permissions and limitations under the License. // Package handler deals with appropriately reacting to all ACS messages as well // as maintaining the connection to ACS. package handler import ( "io" "net/url" "strconv" "strings" "time" "golang.org/x/net/context" acsclient "github.com/aws/amazon-ecs-agent/agent/acs/client" "github.com/aws/amazon-ecs-agent/agent/acs/model/ecsacs" "github.com/aws/amazon-ecs-agent/agent/acs/update_handler" "github.com/aws/amazon-ecs-agent/agent/api" "github.com/aws/amazon-ecs-agent/agent/config" rolecredentials "github.com/aws/amazon-ecs-agent/agent/credentials" "github.com/aws/amazon-ecs-agent/agent/engine" "github.com/aws/amazon-ecs-agent/agent/eventhandler" "github.com/aws/amazon-ecs-agent/agent/eventstream" "github.com/aws/amazon-ecs-agent/agent/statemanager" "github.com/aws/amazon-ecs-agent/agent/utils" "github.com/aws/amazon-ecs-agent/agent/utils/ttime" "github.com/aws/amazon-ecs-agent/agent/version" "github.com/aws/amazon-ecs-agent/agent/wsclient" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/cihub/seelog" ) const ( // heartbeatTimeout is the maximum time to wait between heartbeats // without disconnecting heartbeatTimeout = 5 * time.Minute heartbeatJitter = 3 * time.Minute inactiveInstanceReconnectDelay = 1 * time.Hour connectionBackoffMin = 250 * time.Millisecond connectionBackoffMax = 2 * time.Minute connectionBackoffJitter = 0.2 connectionBackoffMultiplier = 1.5 // payloadMessageBufferSize is the maximum number of payload messages // to queue up without having handled previous ones. payloadMessageBufferSize = 10 // sendCredentialsURLParameterName is the name of the URL parameter // in the ACS URL that is used to indicate if ACS should send // credentials for all tasks on establishing the connection sendCredentialsURLParameterName = "sendCredentials" inactiveInstanceExceptionPrefix = "InactiveInstanceException:" ) // Session defines an interface for handler's long-lived connection with ACS. type Session interface { Start() error } // session encapsulates all arguments needed by the handler to connect to ACS // and to handle messages recieved by ACS. The Session.Start() method can be used // to start processing messages from ACS. type session struct { containerInstanceARN string credentialsProvider *credentials.Credentials agentConfig *config.Config deregisterInstanceEventStream *eventstream.EventStream taskEngine engine.TaskEngine ecsClient api.ECSClient stateManager statemanager.StateManager credentialsManager rolecredentials.Manager taskHandler *eventhandler.TaskHandler ctx context.Context cancel context.CancelFunc backoff utils.Backoff resources sessionResources _heartbeatTimeout time.Duration _heartbeatJitter time.Duration _inactiveInstanceReconnectDelay time.Duration } // sessionResources defines the resource creator interface for starting // a session with ACS. This interface is intended to define methods // that create resources used to establish the connection to ACS // It is confined to just the createACSClient() method for now. It can be // extended to include the acsWsURL() and newDisconnectionTimer() methods // when needed // The goal is to make it easier to test and inject dependencies type sessionResources interface { // createACSClient creates a new websocket client createACSClient(url string, cfg *config.Config) wsclient.ClientServer sessionState } // acsSessionResources implements resource creator and session state interfaces // to create resources needed to connect to ACS and to record session state // for the same type acsSessionResources struct { credentialsProvider *credentials.Credentials // sendCredentials is used to set the 'sendCredentials' URL parameter // used to connect to ACS // It is set to 'true' for the very first successful connection on // agent start. It is set to false for all successive connections sendCredentials bool } // sessionState defines state recorder interface for the // session established with ACS. It can be used to record and // retrieve data shared across multiple connections to ACS type sessionState interface { // connectedToACS callback indicates that the client has // connected to ACS connectedToACS() // getSendCredentialsURLParameter retrieves the value for // the 'sendCredentials' URL parameter getSendCredentialsURLParameter() string } // NewSession creates a new Session object func NewSession(ctx context.Context, config *config.Config, deregisterInstanceEventStream *eventstream.EventStream, containerInstanceArn string, credentialsProvider *credentials.Credentials, ecsClient api.ECSClient, stateManager statemanager.StateManager, taskEngine engine.TaskEngine, credentialsManager rolecredentials.Manager, taskHandler *eventhandler.TaskHandler) Session { resources := newSessionResources(credentialsProvider) backoff := utils.NewSimpleBackoff(connectionBackoffMin, connectionBackoffMax, connectionBackoffJitter, connectionBackoffMultiplier) derivedContext, cancel := context.WithCancel(ctx) return &session{ agentConfig: config, deregisterInstanceEventStream: deregisterInstanceEventStream, containerInstanceARN: containerInstanceArn, credentialsProvider: credentialsProvider, ecsClient: ecsClient, stateManager: stateManager, taskEngine: taskEngine, credentialsManager: credentialsManager, taskHandler: taskHandler, ctx: derivedContext, cancel: cancel, backoff: backoff, resources: resources, _heartbeatTimeout: heartbeatTimeout, _heartbeatJitter: heartbeatJitter, _inactiveInstanceReconnectDelay: inactiveInstanceReconnectDelay, } } // Start starts the session. It'll forever keep trying to connect to ACS unless // the context is cancelled. // // If the context is cancelled, Start() would return with the error code returned // by the context. // If the instance is deregistered, Start() would emit an event to the // deregister-instance event stream and sets the connection backoff time to 1 hour. func (acsSession *session) Start() error { // connectToACS channel is used to inidcate the intent to connect to ACS // It's processed by the select loop to connect to ACS connectToACS := make(chan struct{}) // This is required to trigger the first connection to ACS. Subsequent // connections are triggered by the handleACSError() method go func() { connectToACS <- struct{}{} }() for { select { case <-connectToACS: seelog.Debugf("Received connect to ACS message") // Start a session with ACS acsError := acsSession.startSessionOnce() // Session with ACS was stopped with some error, start processing the error isInactiveInstance := isInactiveInstanceError(acsError) if isInactiveInstance { // If the instance was deregistered, send an event to the event stream // for the same seelog.Debug("Container instance is deregistered, notifying listeners") err := acsSession.deregisterInstanceEventStream.WriteToEventStream(struct{}{}) if err != nil { seelog.Debugf("Failed to write to deregister container instance event stream, err: %v", err) } } if shouldReconnectWithoutBackoff(acsError) { // If ACS closed the connection, there's no need to backoff, // reconnect immediately acsSession.backoff.Reset() sendEmptyMessageOnChannel(connectToACS) } else { // Disconnected unexpectedly from ACS, compute backoff duration to // reconnect reconnectDelay := acsSession.computeReconnectDelay(isInactiveInstance) seelog.Debugf("Reconnecting to ACS in: %v", reconnectDelay) waitComplete := acsSession.waitForDuration(reconnectDelay) if waitComplete { // If the context was not cancelled and we've waited for the // wait duration without any errors, send the message to the channel // to reconnect to ACS sendEmptyMessageOnChannel(connectToACS) } else { // Wait was interrupted. We expect the session to close as canelling // the session context is the only way to end up here. Print a message // to indicate the same seelog.Info("Interrupted waiting for reconnect delay to elapse; Expect session to close") } } case <-acsSession.ctx.Done(): seelog.Debugf("context done") return acsSession.ctx.Err() } } } // startSessionOnce creates a session with ACS and handles requests using the passed // in arguments func (acsSession *session) startSessionOnce() error { acsEndpoint, err := acsSession.ecsClient.DiscoverPollEndpoint(acsSession.containerInstanceARN) if err != nil { seelog.Errorf("Unable to discover poll endpoint, err: %v", err) return err } url := acsWsURL(acsEndpoint, acsSession.agentConfig.Cluster, acsSession.containerInstanceARN, acsSession.taskEngine, acsSession.resources) client := acsSession.resources.createACSClient(url, acsSession.agentConfig) defer client.Close() // Start inactivity timer for closing the connection timer := newDisconnectionTimer(client, acsSession.heartbeatTimeout(), acsSession.heartbeatJitter()) defer timer.Stop() return acsSession.startACSSession(client, timer) } // startACSSession starts a session with ACS. It adds request handlers for various // kinds of messages expected from ACS. It returns on server disconnection or when // the context is cancelled func (acsSession *session) startACSSession(client wsclient.ClientServer, timer ttime.Timer) error { // Any message from the server resets the disconnect timeout client.SetAnyRequestHandler(anyMessageHandler(timer)) cfg := acsSession.agentConfig refreshCredsHandler := newRefreshCredentialsHandler(acsSession.ctx, cfg.Cluster, acsSession.containerInstanceARN, client, acsSession.credentialsManager, acsSession.taskEngine) defer refreshCredsHandler.clearAcks() refreshCredsHandler.start() defer refreshCredsHandler.stop() client.AddRequestHandler(refreshCredsHandler.handlerFunc()) // Add request handler for handling payload messages from ACS payloadHandler := newPayloadRequestHandler( acsSession.ctx, acsSession.taskEngine, acsSession.ecsClient, cfg.Cluster, acsSession.containerInstanceARN, client, acsSession.stateManager, refreshCredsHandler, acsSession.credentialsManager, acsSession.taskHandler) // Clear the acks channel on return because acks of messageids don't have any value across sessions defer payloadHandler.clearAcks() payloadHandler.start() defer payloadHandler.stop() client.AddRequestHandler(payloadHandler.handlerFunc()) // Ignore heartbeat messages; anyMessageHandler gets 'em client.AddRequestHandler(func(*ecsacs.HeartbeatMessage) {}) updater.AddAgentUpdateHandlers(client, cfg, acsSession.stateManager, acsSession.taskEngine) err := client.Connect() if err != nil { seelog.Errorf("Error connecting to ACS: %v", err) return err } acsSession.resources.connectedToACS() backoffResetTimer := time.AfterFunc( utils.AddJitter(acsSession.heartbeatTimeout(), acsSession.heartbeatJitter()), func() { // If we do not have an error connecting and remain connected for at // least 5 or so minutes, reset the backoff. This prevents disconnect // errors that only happen infrequently from damaging the // reconnectability as significantly. acsSession.backoff.Reset() }) defer backoffResetTimer.Stop() serveErr := make(chan error, 1) go func() { serveErr <- client.Serve() }() for { select { case <-acsSession.ctx.Done(): // Stop receiving and sending messages from and to ACS when // the context received from the main function is canceled return acsSession.ctx.Err() case err := <-serveErr: // Stop receiving and sending messages from and to ACS when // client.Serve returns an error. This can happen when the // the connection is closed by ACS or the agent return err } } } func (acsSession *session) computeReconnectDelay(isInactiveInstance bool) time.Duration { if isInactiveInstance { return acsSession._inactiveInstanceReconnectDelay } return acsSession.backoff.Duration() } // waitForDuration waits for the specified duration of time. If the wait is interrupted, // it returns a false value. Else, it returns true, indicating completion of wait time. func (acsSession *session) waitForDuration(delay time.Duration) bool { reconnectTimer := time.NewTimer(delay) select { case <-reconnectTimer.C: return true case <-acsSession.ctx.Done(): reconnectTimer.Stop() return false } } func (acsSession *session) heartbeatTimeout() time.Duration { return acsSession._heartbeatTimeout } func (acsSession *session) heartbeatJitter() time.Duration { return acsSession._heartbeatJitter } // createACSClient creates the ACS Client using the specified URL func (acsResources *acsSessionResources) createACSClient(url string, cfg *config.Config) wsclient.ClientServer { return acsclient.New(url, cfg, acsResources.credentialsProvider) } // connectedToACS records a successful connection to ACS // It sets sendCredentials to false on such an event func (acsResources *acsSessionResources) connectedToACS() { acsResources.sendCredentials = false } // getSendCredentialsURLParameter gets the value to be set for the // 'sendCredentials' URL parameter func (acsResources *acsSessionResources) getSendCredentialsURLParameter() string { return strconv.FormatBool(acsResources.sendCredentials) } func newSessionResources(credentialsProvider *credentials.Credentials) sessionResources { return &acsSessionResources{ credentialsProvider: credentialsProvider, sendCredentials: true, } } // acsWsURL returns the websocket url for ACS given the endpoint func acsWsURL(endpoint, cluster, containerInstanceArn string, taskEngine engine.TaskEngine, acsSessionState sessionState) string { acsUrl := endpoint if endpoint[len(endpoint)-1] != '/' { acsUrl += "/" } acsUrl += "ws" query := url.Values{} query.Set("clusterArn", cluster) query.Set("containerInstanceArn", containerInstanceArn) query.Set("agentHash", version.GitHashString()) query.Set("agentVersion", version.Version) query.Set("seqNum", "1") if dockerVersion, err := taskEngine.Version(); err == nil { query.Set("dockerVersion", "DockerVersion: "+dockerVersion) } query.Set(sendCredentialsURLParameterName, acsSessionState.getSendCredentialsURLParameter()) return acsUrl + "?" + query.Encode() } // newDisconnectionTimer creates a new time object, with a callback to // disconnect from ACS on inactivity func newDisconnectionTimer(client wsclient.ClientServer, timeout time.Duration, jitter time.Duration) ttime.Timer { timer := time.AfterFunc(utils.AddJitter(timeout, jitter), func() { seelog.Warn("ACS Connection hasn't had any activity for too long; closing connection") closeErr := client.Close() if closeErr != nil { seelog.Warnf("Error disconnecting: %v", closeErr) } }) return timer } // anyMessageHandler handles any server message. Any server message means the // connection is active and thus the heartbeat disconnect should not occur func anyMessageHandler(timer ttime.Timer) func(interface{}) { return func(interface{}) { seelog.Debug("ACS activity occured") timer.Reset(utils.AddJitter(heartbeatTimeout, heartbeatJitter)) } } func shouldReconnectWithoutBackoff(acsError error) bool { return acsError == nil || acsError == io.EOF } func isInactiveInstanceError(acsError error) bool { return acsError != nil && strings.HasPrefix(acsError.Error(), inactiveInstanceExceptionPrefix) } // sendEmptyMessageOnChannel sends an empty message using a go-routine on the // sepcified channel func sendEmptyMessageOnChannel(channel chan<- struct{}) { go func() { channel <- struct{}{} }() }
1
15,297
Please break this into multiple lines.
aws-amazon-ecs-agent
go
@@ -120,7 +120,7 @@ namespace Datadog.Trace.ClrProfiler.AutoInstrumentation.AspNet { scope.Span.SetHeaderTags<IHeadersCollection>(httpContext.Response.Headers.Wrap(), Tracer.Instance.Settings.HeaderTags, defaultTagPrefix: SpanContextPropagator.HttpResponseHeadersTagPrefix); } - + HttpContextHelpers.AddHeaderTagsFromHttpResponse(httpContext, scope); scope.Span.SetHttpStatusCode(responseMessage.DuckCast<HttpResponseMessageStruct>().StatusCode, isServer: true); scope.Dispose(); }
1
// <copyright file="ApiController_ExecuteAsync_Integration.cs" company="Datadog"> // Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. // This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. // </copyright> #if NETFRAMEWORK using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Web; using Datadog.Trace.ClrProfiler.CallTarget; using Datadog.Trace.ClrProfiler.Emit; using Datadog.Trace.ClrProfiler.Integrations; using Datadog.Trace.ClrProfiler.Integrations.AspNet; using Datadog.Trace.Configuration; using Datadog.Trace.DuckTyping; using Datadog.Trace.ExtensionMethods; using Datadog.Trace.Headers; using Datadog.Trace.Tagging; namespace Datadog.Trace.ClrProfiler.AutoInstrumentation.AspNet { /// <summary> /// System.Web.Http.ApiController.ExecuteAsync calltarget instrumentation /// </summary> [InstrumentMethod( AssemblyName = SystemWebHttpAssemblyName, TypeName = "System.Web.Http.ApiController", MethodName = "ExecuteAsync", ReturnTypeName = ClrNames.HttpResponseMessageTask, ParameterTypeNames = new[] { HttpControllerContextTypeName, ClrNames.CancellationToken }, MinimumVersion = Major5Minor1, MaximumVersion = Major5MinorX, IntegrationName = IntegrationName)] // ReSharper disable once InconsistentNaming public class ApiController_ExecuteAsync_Integration { private const string SystemWebHttpAssemblyName = "System.Web.Http"; private const string HttpControllerContextTypeName = "System.Web.Http.Controllers.HttpControllerContext"; private const string Major5Minor1 = "5.1"; private const string Major5MinorX = "5"; private const string IntegrationName = nameof(IntegrationIds.AspNetWebApi2); /// <summary> /// OnMethodBegin callback /// </summary> /// <typeparam name="TTarget">Type of the target</typeparam> /// <typeparam name="TController">Type of the controller context</typeparam> /// <param name="instance">Instance value, aka `this` of the instrumented method.</param> /// <param name="controllerContext">The context of the controller</param> /// <param name="cancellationToken">The cancellation token</param> /// <returns>Calltarget state value</returns> public static CallTargetState OnMethodBegin<TTarget, TController>(TTarget instance, TController controllerContext, CancellationToken cancellationToken) where TController : IHttpControllerContext { // Make sure to box the controllerContext proxy only once var boxedControllerContext = (IHttpControllerContext)controllerContext; var scope = AspNetWebApi2Integration.CreateScope(boxedControllerContext, out _); if (scope != null) { return new CallTargetState(scope, boxedControllerContext); } return CallTargetState.GetDefault(); } /// <summary> /// OnAsyncMethodEnd callback /// </summary> /// <typeparam name="TTarget">Type of the target</typeparam> /// <typeparam name="TResponse">Type of the response, in an async scenario will be T of Task of T</typeparam> /// <param name="instance">Instance value, aka `this` of the instrumented method.</param> /// <param name="responseMessage">HttpResponse message instance</param> /// <param name="exception">Exception instance in case the original code threw an exception.</param> /// <param name="state">Calltarget state value</param> /// <returns>A response value, in an async scenario will be T of Task of T</returns> public static TResponse OnAsyncMethodEnd<TTarget, TResponse>(TTarget instance, TResponse responseMessage, Exception exception, CallTargetState state) { var scope = state.Scope; if (scope is null) { return responseMessage; } var controllerContext = (IHttpControllerContext)state.State; // some fields aren't set till after execution, so populate anything missing AspNetWebApi2Integration.UpdateSpan(controllerContext, scope.Span, (AspNetTags)scope.Span.Tags, Enumerable.Empty<KeyValuePair<string, string>>()); if (exception != null) { scope.Span.SetException(exception); // We don't have access to the final status code at this point // Ask the HttpContext to call us back to that we can get it var httpContext = HttpContext.Current; if (httpContext != null) { // We don't know how long it'll take for ASP.NET to invoke the callback, // so we store the real finish time var now = scope.Span.Context.TraceContext.UtcNow; httpContext.AddOnRequestCompleted(h => OnRequestCompleted(h, scope, now)); } else { // Looks like we won't be able to get the final status code scope.Dispose(); } } else { var httpContext = HttpContext.Current; if (httpContext != null && HttpRuntime.UsingIntegratedPipeline) { scope.Span.SetHeaderTags<IHeadersCollection>(httpContext.Response.Headers.Wrap(), Tracer.Instance.Settings.HeaderTags, defaultTagPrefix: SpanContextPropagator.HttpResponseHeadersTagPrefix); } scope.Span.SetHttpStatusCode(responseMessage.DuckCast<HttpResponseMessageStruct>().StatusCode, isServer: true); scope.Dispose(); } return responseMessage; } private static void OnRequestCompleted(HttpContext httpContext, Scope scope, DateTimeOffset finishTime) { if (HttpRuntime.UsingIntegratedPipeline) { scope.Span.SetHeaderTags<IHeadersCollection>(httpContext.Response.Headers.Wrap(), Tracer.Instance.Settings.HeaderTags, defaultTagPrefix: SpanContextPropagator.HttpResponseHeadersTagPrefix); } scope.Span.SetHttpStatusCode(httpContext.Response.StatusCode, isServer: true); scope.Span.Finish(finishTime); scope.Dispose(); } } } #endif
1
21,530
Shouldn't this new line replace the few lines above?
DataDog-dd-trace-dotnet
.cs
@@ -2,9 +2,9 @@ package options import ( "github.com/influxdata/flux" - "github.com/influxdata/flux/functions/transformations" + "github.com/influxdata/flux/stdlib/universe" ) func init() { - flux.RegisterBuiltInOption("now", transformations.SystemTime()) + flux.RegisterBuiltInOption("now", universe.SystemTime()) }
1
package options import ( "github.com/influxdata/flux" "github.com/influxdata/flux/functions/transformations" ) func init() { flux.RegisterBuiltInOption("now", transformations.SystemTime()) }
1
9,542
Perhaps this belongs in universe?
influxdata-flux
go
@@ -25,8 +25,11 @@ std::chrono::duration<double, std::milli> hist_time; std::chrono::duration<double, std::milli> find_split_time; std::chrono::duration<double, std::milli> split_time; std::chrono::duration<double, std::milli> ordered_bin_time; +std::chrono::duration<double, std::milli> refit_leaves_time; #endif // TIMETAG +double EPS = 1e-12; + SerialTreeLearner::SerialTreeLearner(const Config* config) :config_(config) { random_ = Random(config_->feature_fraction_seed);
1
/*! * Copyright (c) 2016 Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE file in the project root for license information. */ #include "serial_tree_learner.h" #include <LightGBM/network.h> #include <LightGBM/objective_function.h> #include <LightGBM/utils/array_args.h> #include <LightGBM/utils/common.h> #include <algorithm> #include <queue> #include <unordered_map> #include <utility> #include "cost_effective_gradient_boosting.hpp" namespace LightGBM { #ifdef TIMETAG std::chrono::duration<double, std::milli> init_train_time; std::chrono::duration<double, std::milli> init_split_time; std::chrono::duration<double, std::milli> hist_time; std::chrono::duration<double, std::milli> find_split_time; std::chrono::duration<double, std::milli> split_time; std::chrono::duration<double, std::milli> ordered_bin_time; #endif // TIMETAG SerialTreeLearner::SerialTreeLearner(const Config* config) :config_(config) { random_ = Random(config_->feature_fraction_seed); #pragma omp parallel #pragma omp master { num_threads_ = omp_get_num_threads(); } } SerialTreeLearner::~SerialTreeLearner() { #ifdef TIMETAG Log::Info("SerialTreeLearner::init_train costs %f", init_train_time * 1e-3); Log::Info("SerialTreeLearner::init_split costs %f", init_split_time * 1e-3); Log::Info("SerialTreeLearner::hist_build costs %f", hist_time * 1e-3); Log::Info("SerialTreeLearner::find_split costs %f", find_split_time * 1e-3); Log::Info("SerialTreeLearner::split costs %f", split_time * 1e-3); Log::Info("SerialTreeLearner::ordered_bin costs %f", ordered_bin_time * 1e-3); #endif } void SerialTreeLearner::Init(const Dataset* train_data, bool is_constant_hessian) { train_data_ = train_data; num_data_ = train_data_->num_data(); num_features_ = train_data_->num_features(); is_constant_hessian_ = is_constant_hessian; int max_cache_size = 0; // Get the max size of pool if (config_->histogram_pool_size <= 0) { max_cache_size = config_->num_leaves; } else { size_t total_histogram_size = 0; for (int i = 0; i < train_data_->num_features(); ++i) { total_histogram_size += sizeof(HistogramBinEntry) * train_data_->FeatureNumBin(i); } max_cache_size = static_cast<int>(config_->histogram_pool_size * 1024 * 1024 / total_histogram_size); } // at least need 2 leaves max_cache_size = std::max(2, max_cache_size); max_cache_size = std::min(max_cache_size, config_->num_leaves); histogram_pool_.DynamicChangeSize(train_data_, config_, max_cache_size, config_->num_leaves); // push split information for all leaves best_split_per_leaf_.resize(config_->num_leaves); // get ordered bin train_data_->CreateOrderedBins(&ordered_bins_); // check existing for ordered bin for (int i = 0; i < static_cast<int>(ordered_bins_.size()); ++i) { if (ordered_bins_[i] != nullptr) { has_ordered_bin_ = true; break; } } // initialize splits for leaf smaller_leaf_splits_.reset(new LeafSplits(train_data_->num_data())); larger_leaf_splits_.reset(new LeafSplits(train_data_->num_data())); // initialize data partition data_partition_.reset(new DataPartition(num_data_, config_->num_leaves)); is_feature_used_.resize(num_features_); valid_feature_indices_ = train_data_->ValidFeatureIndices(); // initialize ordered gradients and hessians ordered_gradients_.resize(num_data_); ordered_hessians_.resize(num_data_); // if has ordered bin, need to allocate a buffer to fast split if (has_ordered_bin_) { is_data_in_leaf_.resize(num_data_); std::fill(is_data_in_leaf_.begin(), is_data_in_leaf_.end(), static_cast<char>(0)); ordered_bin_indices_.clear(); for (int i = 0; i < static_cast<int>(ordered_bins_.size()); i++) { if (ordered_bins_[i] != nullptr) { ordered_bin_indices_.push_back(i); } } } Log::Info("Number of data: %d, number of used features: %d", num_data_, num_features_); if (CostEfficientGradientBoosting::IsEnable(config_)) { cegb_.reset(new CostEfficientGradientBoosting(this)); cegb_->Init(); } } void SerialTreeLearner::ResetTrainingData(const Dataset* train_data) { train_data_ = train_data; num_data_ = train_data_->num_data(); CHECK(num_features_ == train_data_->num_features()); // get ordered bin train_data_->CreateOrderedBins(&ordered_bins_); // initialize splits for leaf smaller_leaf_splits_->ResetNumData(num_data_); larger_leaf_splits_->ResetNumData(num_data_); // initialize data partition data_partition_->ResetNumData(num_data_); // initialize ordered gradients and hessians ordered_gradients_.resize(num_data_); ordered_hessians_.resize(num_data_); // if has ordered bin, need to allocate a buffer to fast split if (has_ordered_bin_) { is_data_in_leaf_.resize(num_data_); std::fill(is_data_in_leaf_.begin(), is_data_in_leaf_.end(), static_cast<char>(0)); } if (cegb_ != nullptr) { cegb_->Init(); } } void SerialTreeLearner::ResetConfig(const Config* config) { if (config_->num_leaves != config->num_leaves) { config_ = config; int max_cache_size = 0; // Get the max size of pool if (config->histogram_pool_size <= 0) { max_cache_size = config_->num_leaves; } else { size_t total_histogram_size = 0; for (int i = 0; i < train_data_->num_features(); ++i) { total_histogram_size += sizeof(HistogramBinEntry) * train_data_->FeatureNumBin(i); } max_cache_size = static_cast<int>(config_->histogram_pool_size * 1024 * 1024 / total_histogram_size); } // at least need 2 leaves max_cache_size = std::max(2, max_cache_size); max_cache_size = std::min(max_cache_size, config_->num_leaves); histogram_pool_.DynamicChangeSize(train_data_, config_, max_cache_size, config_->num_leaves); // push split information for all leaves best_split_per_leaf_.resize(config_->num_leaves); data_partition_->ResetLeaves(config_->num_leaves); } else { config_ = config; } histogram_pool_.ResetConfig(config_); if (CostEfficientGradientBoosting::IsEnable(config_)) { cegb_.reset(new CostEfficientGradientBoosting(this)); cegb_->Init(); } } Tree* SerialTreeLearner::Train(const score_t* gradients, const score_t *hessians, bool is_constant_hessian, const Json& forced_split_json) { gradients_ = gradients; hessians_ = hessians; is_constant_hessian_ = is_constant_hessian; #ifdef TIMETAG auto start_time = std::chrono::steady_clock::now(); #endif // some initial works before training BeforeTrain(); #ifdef TIMETAG init_train_time += std::chrono::steady_clock::now() - start_time; #endif auto tree = std::unique_ptr<Tree>(new Tree(config_->num_leaves)); // root leaf int left_leaf = 0; int cur_depth = 1; // only root leaf can be splitted on first time int right_leaf = -1; int init_splits = 0; bool aborted_last_force_split = false; if (!forced_split_json.is_null()) { init_splits = ForceSplits(tree.get(), forced_split_json, &left_leaf, &right_leaf, &cur_depth, &aborted_last_force_split); } for (int split = init_splits; split < config_->num_leaves - 1; ++split) { #ifdef TIMETAG start_time = std::chrono::steady_clock::now(); #endif // some initial works before finding best split if (!aborted_last_force_split && BeforeFindBestSplit(tree.get(), left_leaf, right_leaf)) { #ifdef TIMETAG init_split_time += std::chrono::steady_clock::now() - start_time; #endif // find best threshold for every feature FindBestSplits(); } else if (aborted_last_force_split) { aborted_last_force_split = false; } // Get a leaf with max split gain int best_leaf = static_cast<int>(ArrayArgs<SplitInfo>::ArgMax(best_split_per_leaf_)); // Get split information for best leaf const SplitInfo& best_leaf_SplitInfo = best_split_per_leaf_[best_leaf]; // cannot split, quit if (best_leaf_SplitInfo.gain <= 0.0) { Log::Warning("No further splits with positive gain, best gain: %f", best_leaf_SplitInfo.gain); break; } #ifdef TIMETAG start_time = std::chrono::steady_clock::now(); #endif // split tree with best leaf Split(tree.get(), best_leaf, &left_leaf, &right_leaf); #ifdef TIMETAG split_time += std::chrono::steady_clock::now() - start_time; #endif cur_depth = std::max(cur_depth, tree->leaf_depth(left_leaf)); } Log::Debug("Trained a tree with leaves = %d and max_depth = %d", tree->num_leaves(), cur_depth); return tree.release(); } Tree* SerialTreeLearner::FitByExistingTree(const Tree* old_tree, const score_t* gradients, const score_t *hessians) const { auto tree = std::unique_ptr<Tree>(new Tree(*old_tree)); CHECK(data_partition_->num_leaves() >= tree->num_leaves()); OMP_INIT_EX(); #pragma omp parallel for schedule(static) for (int i = 0; i < tree->num_leaves(); ++i) { OMP_LOOP_EX_BEGIN(); data_size_t cnt_leaf_data = 0; auto tmp_idx = data_partition_->GetIndexOnLeaf(i, &cnt_leaf_data); double sum_grad = 0.0f; double sum_hess = kEpsilon; for (data_size_t j = 0; j < cnt_leaf_data; ++j) { auto idx = tmp_idx[j]; sum_grad += gradients[idx]; sum_hess += hessians[idx]; } double output = FeatureHistogram::CalculateSplittedLeafOutput(sum_grad, sum_hess, config_->lambda_l1, config_->lambda_l2, config_->max_delta_step); auto old_leaf_output = tree->LeafOutput(i); auto new_leaf_output = output * tree->shrinkage(); tree->SetLeafOutput(i, config_->refit_decay_rate * old_leaf_output + (1.0 - config_->refit_decay_rate) * new_leaf_output); OMP_LOOP_EX_END(); } OMP_THROW_EX(); return tree.release(); } Tree* SerialTreeLearner::FitByExistingTree(const Tree* old_tree, const std::vector<int>& leaf_pred, const score_t* gradients, const score_t *hessians) { data_partition_->ResetByLeafPred(leaf_pred, old_tree->num_leaves()); return FitByExistingTree(old_tree, gradients, hessians); } std::vector<int8_t> SerialTreeLearner::GetUsedFeatures(bool is_tree_level) { std::vector<int8_t> ret(num_features_, 1); if (config_->feature_fraction >= 1.0f && is_tree_level) { return ret; } if (config_->feature_fraction_bynode >= 1.0f && !is_tree_level) { return ret; } std::memset(ret.data(), 0, sizeof(int8_t) * num_features_); const int min_used_features = std::min(2, static_cast<int>(valid_feature_indices_.size())); if (is_tree_level) { int used_feature_cnt = static_cast<int>(std::round(valid_feature_indices_.size() * config_->feature_fraction)); used_feature_cnt = std::max(used_feature_cnt, min_used_features); used_feature_indices_ = random_.Sample(static_cast<int>(valid_feature_indices_.size()), used_feature_cnt); int omp_loop_size = static_cast<int>(used_feature_indices_.size()); #pragma omp parallel for schedule(static, 512) if (omp_loop_size >= 1024) for (int i = 0; i < omp_loop_size; ++i) { int used_feature = valid_feature_indices_[used_feature_indices_[i]]; int inner_feature_index = train_data_->InnerFeatureIndex(used_feature); CHECK(inner_feature_index >= 0); ret[inner_feature_index] = 1; } } else if (used_feature_indices_.size() <= 0) { int used_feature_cnt = static_cast<int>(std::round(valid_feature_indices_.size() * config_->feature_fraction_bynode)); used_feature_cnt = std::max(used_feature_cnt, min_used_features); auto sampled_indices = random_.Sample(static_cast<int>(valid_feature_indices_.size()), used_feature_cnt); int omp_loop_size = static_cast<int>(sampled_indices.size()); #pragma omp parallel for schedule(static, 512) if (omp_loop_size >= 1024) for (int i = 0; i < omp_loop_size; ++i) { int used_feature = valid_feature_indices_[sampled_indices[i]]; int inner_feature_index = train_data_->InnerFeatureIndex(used_feature); CHECK(inner_feature_index >= 0); ret[inner_feature_index] = 1; } } else { int used_feature_cnt = static_cast<int>(std::round(used_feature_indices_.size() * config_->feature_fraction_bynode)); used_feature_cnt = std::max(used_feature_cnt, min_used_features); auto sampled_indices = random_.Sample(static_cast<int>(used_feature_indices_.size()), used_feature_cnt); int omp_loop_size = static_cast<int>(sampled_indices.size()); #pragma omp parallel for schedule(static, 512) if (omp_loop_size >= 1024) for (int i = 0; i < omp_loop_size; ++i) { int used_feature = valid_feature_indices_[used_feature_indices_[sampled_indices[i]]]; int inner_feature_index = train_data_->InnerFeatureIndex(used_feature); CHECK(inner_feature_index >= 0); ret[inner_feature_index] = 1; } } return ret; } void SerialTreeLearner::BeforeTrain() { // reset histogram pool histogram_pool_.ResetMap(); if (config_->feature_fraction < 1.0f) { is_feature_used_ = GetUsedFeatures(true); } else { #pragma omp parallel for schedule(static, 512) if (num_features_ >= 1024) for (int i = 0; i < num_features_; ++i) { is_feature_used_[i] = 1; } } // initialize data partition data_partition_->Init(); // reset the splits for leaves for (int i = 0; i < config_->num_leaves; ++i) { best_split_per_leaf_[i].Reset(); } // Sumup for root if (data_partition_->leaf_count(0) == num_data_) { // use all data smaller_leaf_splits_->Init(gradients_, hessians_); } else { // use bagging, only use part of data smaller_leaf_splits_->Init(0, data_partition_.get(), gradients_, hessians_); } larger_leaf_splits_->Init(); // if has ordered bin, need to initialize the ordered bin if (has_ordered_bin_) { #ifdef TIMETAG auto start_time = std::chrono::steady_clock::now(); #endif if (data_partition_->leaf_count(0) == num_data_) { // use all data, pass nullptr OMP_INIT_EX(); #pragma omp parallel for schedule(static) for (int i = 0; i < static_cast<int>(ordered_bin_indices_.size()); ++i) { OMP_LOOP_EX_BEGIN(); ordered_bins_[ordered_bin_indices_[i]]->Init(nullptr, config_->num_leaves); OMP_LOOP_EX_END(); } OMP_THROW_EX(); } else { // bagging, only use part of data // mark used data const data_size_t* indices = data_partition_->indices(); data_size_t begin = data_partition_->leaf_begin(0); data_size_t end = begin + data_partition_->leaf_count(0); #pragma omp parallel for schedule(static, 512) if (end - begin >= 1024) for (data_size_t i = begin; i < end; ++i) { is_data_in_leaf_[indices[i]] = 1; } OMP_INIT_EX(); // initialize ordered bin #pragma omp parallel for schedule(static) for (int i = 0; i < static_cast<int>(ordered_bin_indices_.size()); ++i) { OMP_LOOP_EX_BEGIN(); ordered_bins_[ordered_bin_indices_[i]]->Init(is_data_in_leaf_.data(), config_->num_leaves); OMP_LOOP_EX_END(); } OMP_THROW_EX(); #pragma omp parallel for schedule(static, 512) if (end - begin >= 1024) for (data_size_t i = begin; i < end; ++i) { is_data_in_leaf_[indices[i]] = 0; } } #ifdef TIMETAG ordered_bin_time += std::chrono::steady_clock::now() - start_time; #endif } } bool SerialTreeLearner::BeforeFindBestSplit(const Tree* tree, int left_leaf, int right_leaf) { // check depth of current leaf if (config_->max_depth > 0) { // only need to check left leaf, since right leaf is in same level of left leaf if (tree->leaf_depth(left_leaf) >= config_->max_depth) { best_split_per_leaf_[left_leaf].gain = kMinScore; if (right_leaf >= 0) { best_split_per_leaf_[right_leaf].gain = kMinScore; } return false; } } data_size_t num_data_in_left_child = GetGlobalDataCountInLeaf(left_leaf); data_size_t num_data_in_right_child = GetGlobalDataCountInLeaf(right_leaf); // no enough data to continue if (num_data_in_right_child < static_cast<data_size_t>(config_->min_data_in_leaf * 2) && num_data_in_left_child < static_cast<data_size_t>(config_->min_data_in_leaf * 2)) { best_split_per_leaf_[left_leaf].gain = kMinScore; if (right_leaf >= 0) { best_split_per_leaf_[right_leaf].gain = kMinScore; } return false; } parent_leaf_histogram_array_ = nullptr; // only have root if (right_leaf < 0) { histogram_pool_.Get(left_leaf, &smaller_leaf_histogram_array_); larger_leaf_histogram_array_ = nullptr; } else if (num_data_in_left_child < num_data_in_right_child) { // put parent(left) leaf's histograms into larger leaf's histograms if (histogram_pool_.Get(left_leaf, &larger_leaf_histogram_array_)) { parent_leaf_histogram_array_ = larger_leaf_histogram_array_; } histogram_pool_.Move(left_leaf, right_leaf); histogram_pool_.Get(left_leaf, &smaller_leaf_histogram_array_); } else { // put parent(left) leaf's histograms to larger leaf's histograms if (histogram_pool_.Get(left_leaf, &larger_leaf_histogram_array_)) { parent_leaf_histogram_array_ = larger_leaf_histogram_array_; } histogram_pool_.Get(right_leaf, &smaller_leaf_histogram_array_); } // split for the ordered bin if (has_ordered_bin_ && right_leaf >= 0) { #ifdef TIMETAG auto start_time = std::chrono::steady_clock::now(); #endif // mark data that at left-leaf const data_size_t* indices = data_partition_->indices(); const auto left_cnt = data_partition_->leaf_count(left_leaf); const auto right_cnt = data_partition_->leaf_count(right_leaf); char mark = 1; data_size_t begin = data_partition_->leaf_begin(left_leaf); data_size_t end = begin + left_cnt; if (left_cnt > right_cnt) { begin = data_partition_->leaf_begin(right_leaf); end = begin + right_cnt; mark = 0; } #pragma omp parallel for schedule(static, 512) if (end - begin >= 1024) for (data_size_t i = begin; i < end; ++i) { is_data_in_leaf_[indices[i]] = 1; } OMP_INIT_EX(); // split the ordered bin #pragma omp parallel for schedule(static) for (int i = 0; i < static_cast<int>(ordered_bin_indices_.size()); ++i) { OMP_LOOP_EX_BEGIN(); ordered_bins_[ordered_bin_indices_[i]]->Split(left_leaf, right_leaf, is_data_in_leaf_.data(), mark); OMP_LOOP_EX_END(); } OMP_THROW_EX(); #pragma omp parallel for schedule(static, 512) if (end - begin >= 1024) for (data_size_t i = begin; i < end; ++i) { is_data_in_leaf_[indices[i]] = 0; } #ifdef TIMETAG ordered_bin_time += std::chrono::steady_clock::now() - start_time; #endif } return true; } void SerialTreeLearner::FindBestSplits() { std::vector<int8_t> is_feature_used(num_features_, 0); #pragma omp parallel for schedule(static, 1024) if (num_features_ >= 2048) for (int feature_index = 0; feature_index < num_features_; ++feature_index) { if (!is_feature_used_[feature_index]) continue; if (parent_leaf_histogram_array_ != nullptr && !parent_leaf_histogram_array_[feature_index].is_splittable()) { smaller_leaf_histogram_array_[feature_index].set_is_splittable(false); continue; } is_feature_used[feature_index] = 1; } bool use_subtract = parent_leaf_histogram_array_ != nullptr; ConstructHistograms(is_feature_used, use_subtract); FindBestSplitsFromHistograms(is_feature_used, use_subtract); } void SerialTreeLearner::ConstructHistograms(const std::vector<int8_t>& is_feature_used, bool use_subtract) { #ifdef TIMETAG auto start_time = std::chrono::steady_clock::now(); #endif // construct smaller leaf HistogramBinEntry* ptr_smaller_leaf_hist_data = smaller_leaf_histogram_array_[0].RawData() - 1; train_data_->ConstructHistograms(is_feature_used, smaller_leaf_splits_->data_indices(), smaller_leaf_splits_->num_data_in_leaf(), smaller_leaf_splits_->LeafIndex(), &ordered_bins_, gradients_, hessians_, ordered_gradients_.data(), ordered_hessians_.data(), is_constant_hessian_, ptr_smaller_leaf_hist_data); if (larger_leaf_histogram_array_ != nullptr && !use_subtract) { // construct larger leaf HistogramBinEntry* ptr_larger_leaf_hist_data = larger_leaf_histogram_array_[0].RawData() - 1; train_data_->ConstructHistograms(is_feature_used, larger_leaf_splits_->data_indices(), larger_leaf_splits_->num_data_in_leaf(), larger_leaf_splits_->LeafIndex(), &ordered_bins_, gradients_, hessians_, ordered_gradients_.data(), ordered_hessians_.data(), is_constant_hessian_, ptr_larger_leaf_hist_data); } #ifdef TIMETAG hist_time += std::chrono::steady_clock::now() - start_time; #endif } void SerialTreeLearner::FindBestSplitsFromHistograms(const std::vector<int8_t>& is_feature_used, bool use_subtract) { #ifdef TIMETAG auto start_time = std::chrono::steady_clock::now(); #endif std::vector<SplitInfo> smaller_best(num_threads_); std::vector<SplitInfo> larger_best(num_threads_); std::vector<int8_t> smaller_node_used_features(num_features_, 1); std::vector<int8_t> larger_node_used_features(num_features_, 1); if (config_->feature_fraction_bynode < 1.0f) { smaller_node_used_features = GetUsedFeatures(false); larger_node_used_features = GetUsedFeatures(false); } OMP_INIT_EX(); // find splits #pragma omp parallel for schedule(static) for (int feature_index = 0; feature_index < num_features_; ++feature_index) { OMP_LOOP_EX_BEGIN(); if (!is_feature_used[feature_index]) { continue; } const int tid = omp_get_thread_num(); SplitInfo smaller_split; train_data_->FixHistogram(feature_index, smaller_leaf_splits_->sum_gradients(), smaller_leaf_splits_->sum_hessians(), smaller_leaf_splits_->num_data_in_leaf(), smaller_leaf_histogram_array_[feature_index].RawData()); int real_fidx = train_data_->RealFeatureIndex(feature_index); smaller_leaf_histogram_array_[feature_index].FindBestThreshold( smaller_leaf_splits_->sum_gradients(), smaller_leaf_splits_->sum_hessians(), smaller_leaf_splits_->num_data_in_leaf(), smaller_leaf_splits_->min_constraint(), smaller_leaf_splits_->max_constraint(), &smaller_split); smaller_split.feature = real_fidx; if (cegb_ != nullptr) { smaller_split.gain -= cegb_->DetlaGain(feature_index, real_fidx, smaller_leaf_splits_->LeafIndex(), smaller_leaf_splits_->num_data_in_leaf(), smaller_split); } if (smaller_split > smaller_best[tid] && smaller_node_used_features[feature_index]) { smaller_best[tid] = smaller_split; } // only has root leaf if (larger_leaf_splits_ == nullptr || larger_leaf_splits_->LeafIndex() < 0) { continue; } if (use_subtract) { larger_leaf_histogram_array_[feature_index].Subtract(smaller_leaf_histogram_array_[feature_index]); } else { train_data_->FixHistogram(feature_index, larger_leaf_splits_->sum_gradients(), larger_leaf_splits_->sum_hessians(), larger_leaf_splits_->num_data_in_leaf(), larger_leaf_histogram_array_[feature_index].RawData()); } SplitInfo larger_split; // find best threshold for larger child larger_leaf_histogram_array_[feature_index].FindBestThreshold( larger_leaf_splits_->sum_gradients(), larger_leaf_splits_->sum_hessians(), larger_leaf_splits_->num_data_in_leaf(), larger_leaf_splits_->min_constraint(), larger_leaf_splits_->max_constraint(), &larger_split); larger_split.feature = real_fidx; if (cegb_ != nullptr) { larger_split.gain -= cegb_->DetlaGain(feature_index, real_fidx, larger_leaf_splits_->LeafIndex(), larger_leaf_splits_->num_data_in_leaf(), larger_split); } if (larger_split > larger_best[tid] && larger_node_used_features[feature_index]) { larger_best[tid] = larger_split; } OMP_LOOP_EX_END(); } OMP_THROW_EX(); auto smaller_best_idx = ArrayArgs<SplitInfo>::ArgMax(smaller_best); int leaf = smaller_leaf_splits_->LeafIndex(); best_split_per_leaf_[leaf] = smaller_best[smaller_best_idx]; if (larger_leaf_splits_ != nullptr && larger_leaf_splits_->LeafIndex() >= 0) { leaf = larger_leaf_splits_->LeafIndex(); auto larger_best_idx = ArrayArgs<SplitInfo>::ArgMax(larger_best); best_split_per_leaf_[leaf] = larger_best[larger_best_idx]; } #ifdef TIMETAG find_split_time += std::chrono::steady_clock::now() - start_time; #endif } int32_t SerialTreeLearner::ForceSplits(Tree* tree, const Json& forced_split_json, int* left_leaf, int* right_leaf, int *cur_depth, bool *aborted_last_force_split) { int32_t result_count = 0; // start at root leaf *left_leaf = 0; std::queue<std::pair<Json, int>> q; Json left = forced_split_json; Json right; bool left_smaller = true; std::unordered_map<int, SplitInfo> forceSplitMap; q.push(std::make_pair(forced_split_json, *left_leaf)); while (!q.empty()) { // before processing next node from queue, store info for current left/right leaf // store "best split" for left and right, even if they might be overwritten by forced split if (BeforeFindBestSplit(tree, *left_leaf, *right_leaf)) { FindBestSplits(); } // then, compute own splits SplitInfo left_split; SplitInfo right_split; if (!left.is_null()) { const int left_feature = left["feature"].int_value(); const double left_threshold_double = left["threshold"].number_value(); const int left_inner_feature_index = train_data_->InnerFeatureIndex(left_feature); const uint32_t left_threshold = train_data_->BinThreshold( left_inner_feature_index, left_threshold_double); auto leaf_histogram_array = (left_smaller) ? smaller_leaf_histogram_array_ : larger_leaf_histogram_array_; auto left_leaf_splits = (left_smaller) ? smaller_leaf_splits_.get() : larger_leaf_splits_.get(); leaf_histogram_array[left_inner_feature_index].GatherInfoForThreshold( left_leaf_splits->sum_gradients(), left_leaf_splits->sum_hessians(), left_threshold, left_leaf_splits->num_data_in_leaf(), &left_split); left_split.feature = left_feature; forceSplitMap[*left_leaf] = left_split; if (left_split.gain < 0) { forceSplitMap.erase(*left_leaf); } } if (!right.is_null()) { const int right_feature = right["feature"].int_value(); const double right_threshold_double = right["threshold"].number_value(); const int right_inner_feature_index = train_data_->InnerFeatureIndex(right_feature); const uint32_t right_threshold = train_data_->BinThreshold( right_inner_feature_index, right_threshold_double); auto leaf_histogram_array = (left_smaller) ? larger_leaf_histogram_array_ : smaller_leaf_histogram_array_; auto right_leaf_splits = (left_smaller) ? larger_leaf_splits_.get() : smaller_leaf_splits_.get(); leaf_histogram_array[right_inner_feature_index].GatherInfoForThreshold( right_leaf_splits->sum_gradients(), right_leaf_splits->sum_hessians(), right_threshold, right_leaf_splits->num_data_in_leaf(), &right_split); right_split.feature = right_feature; forceSplitMap[*right_leaf] = right_split; if (right_split.gain < 0) { forceSplitMap.erase(*right_leaf); } } std::pair<Json, int> pair = q.front(); q.pop(); int current_leaf = pair.second; // split info should exist because searching in bfs fashion - should have added from parent if (forceSplitMap.find(current_leaf) == forceSplitMap.end()) { *aborted_last_force_split = true; break; } SplitInfo current_split_info = forceSplitMap[current_leaf]; const int inner_feature_index = train_data_->InnerFeatureIndex( current_split_info.feature); auto threshold_double = train_data_->RealThreshold( inner_feature_index, current_split_info.threshold); // split tree, will return right leaf *left_leaf = current_leaf; if (train_data_->FeatureBinMapper(inner_feature_index)->bin_type() == BinType::NumericalBin) { *right_leaf = tree->Split(current_leaf, inner_feature_index, current_split_info.feature, current_split_info.threshold, threshold_double, static_cast<double>(current_split_info.left_output), static_cast<double>(current_split_info.right_output), static_cast<data_size_t>(current_split_info.left_count), static_cast<data_size_t>(current_split_info.right_count), static_cast<double>(current_split_info.left_sum_hessian), static_cast<double>(current_split_info.right_sum_hessian), static_cast<float>(current_split_info.gain), train_data_->FeatureBinMapper(inner_feature_index)->missing_type(), current_split_info.default_left); data_partition_->Split(current_leaf, train_data_, inner_feature_index, &current_split_info.threshold, 1, current_split_info.default_left, *right_leaf); } else { std::vector<uint32_t> cat_bitset_inner = Common::ConstructBitset( current_split_info.cat_threshold.data(), current_split_info.num_cat_threshold); std::vector<int> threshold_int(current_split_info.num_cat_threshold); for (int i = 0; i < current_split_info.num_cat_threshold; ++i) { threshold_int[i] = static_cast<int>(train_data_->RealThreshold( inner_feature_index, current_split_info.cat_threshold[i])); } std::vector<uint32_t> cat_bitset = Common::ConstructBitset( threshold_int.data(), current_split_info.num_cat_threshold); *right_leaf = tree->SplitCategorical(current_leaf, inner_feature_index, current_split_info.feature, cat_bitset_inner.data(), static_cast<int>(cat_bitset_inner.size()), cat_bitset.data(), static_cast<int>(cat_bitset.size()), static_cast<double>(current_split_info.left_output), static_cast<double>(current_split_info.right_output), static_cast<data_size_t>(current_split_info.left_count), static_cast<data_size_t>(current_split_info.right_count), static_cast<double>(current_split_info.left_sum_hessian), static_cast<double>(current_split_info.right_sum_hessian), static_cast<float>(current_split_info.gain), train_data_->FeatureBinMapper(inner_feature_index)->missing_type()); data_partition_->Split(current_leaf, train_data_, inner_feature_index, cat_bitset_inner.data(), static_cast<int>(cat_bitset_inner.size()), current_split_info.default_left, *right_leaf); } if (current_split_info.left_count < current_split_info.right_count) { left_smaller = true; smaller_leaf_splits_->Init(*left_leaf, data_partition_.get(), current_split_info.left_sum_gradient, current_split_info.left_sum_hessian); larger_leaf_splits_->Init(*right_leaf, data_partition_.get(), current_split_info.right_sum_gradient, current_split_info.right_sum_hessian); } else { left_smaller = false; smaller_leaf_splits_->Init(*right_leaf, data_partition_.get(), current_split_info.right_sum_gradient, current_split_info.right_sum_hessian); larger_leaf_splits_->Init(*left_leaf, data_partition_.get(), current_split_info.left_sum_gradient, current_split_info.left_sum_hessian); } left = Json(); right = Json(); if ((pair.first).object_items().count("left") > 0) { left = (pair.first)["left"]; if (left.object_items().count("feature") > 0 && left.object_items().count("threshold") > 0) { q.push(std::make_pair(left, *left_leaf)); } } if ((pair.first).object_items().count("right") > 0) { right = (pair.first)["right"]; if (right.object_items().count("feature") > 0 && right.object_items().count("threshold") > 0) { q.push(std::make_pair(right, *right_leaf)); } } result_count++; *(cur_depth) = std::max(*(cur_depth), tree->leaf_depth(*left_leaf)); } return result_count; } void SerialTreeLearner::Split(Tree* tree, int best_leaf, int* left_leaf, int* right_leaf) { const SplitInfo& best_split_info = best_split_per_leaf_[best_leaf]; const int inner_feature_index = train_data_->InnerFeatureIndex(best_split_info.feature); if (cegb_ != nullptr) { cegb_->UpdateLeafBestSplits(tree, best_leaf, &best_split_info, &best_split_per_leaf_); } // left = parent *left_leaf = best_leaf; bool is_numerical_split = train_data_->FeatureBinMapper(inner_feature_index)->bin_type() == BinType::NumericalBin; if (is_numerical_split) { auto threshold_double = train_data_->RealThreshold(inner_feature_index, best_split_info.threshold); // split tree, will return right leaf *right_leaf = tree->Split(best_leaf, inner_feature_index, best_split_info.feature, best_split_info.threshold, threshold_double, static_cast<double>(best_split_info.left_output), static_cast<double>(best_split_info.right_output), static_cast<data_size_t>(best_split_info.left_count), static_cast<data_size_t>(best_split_info.right_count), static_cast<double>(best_split_info.left_sum_hessian), static_cast<double>(best_split_info.right_sum_hessian), static_cast<float>(best_split_info.gain), train_data_->FeatureBinMapper(inner_feature_index)->missing_type(), best_split_info.default_left); data_partition_->Split(best_leaf, train_data_, inner_feature_index, &best_split_info.threshold, 1, best_split_info.default_left, *right_leaf); } else { std::vector<uint32_t> cat_bitset_inner = Common::ConstructBitset(best_split_info.cat_threshold.data(), best_split_info.num_cat_threshold); std::vector<int> threshold_int(best_split_info.num_cat_threshold); for (int i = 0; i < best_split_info.num_cat_threshold; ++i) { threshold_int[i] = static_cast<int>(train_data_->RealThreshold(inner_feature_index, best_split_info.cat_threshold[i])); } std::vector<uint32_t> cat_bitset = Common::ConstructBitset(threshold_int.data(), best_split_info.num_cat_threshold); *right_leaf = tree->SplitCategorical(best_leaf, inner_feature_index, best_split_info.feature, cat_bitset_inner.data(), static_cast<int>(cat_bitset_inner.size()), cat_bitset.data(), static_cast<int>(cat_bitset.size()), static_cast<double>(best_split_info.left_output), static_cast<double>(best_split_info.right_output), static_cast<data_size_t>(best_split_info.left_count), static_cast<data_size_t>(best_split_info.right_count), static_cast<double>(best_split_info.left_sum_hessian), static_cast<double>(best_split_info.right_sum_hessian), static_cast<float>(best_split_info.gain), train_data_->FeatureBinMapper(inner_feature_index)->missing_type()); data_partition_->Split(best_leaf, train_data_, inner_feature_index, cat_bitset_inner.data(), static_cast<int>(cat_bitset_inner.size()), best_split_info.default_left, *right_leaf); } #ifdef DEBUG CHECK(best_split_info.left_count == data_partition_->leaf_count(best_leaf)); #endif auto p_left = smaller_leaf_splits_.get(); auto p_right = larger_leaf_splits_.get(); // init the leaves that used on next iteration if (best_split_info.left_count < best_split_info.right_count) { smaller_leaf_splits_->Init(*left_leaf, data_partition_.get(), best_split_info.left_sum_gradient, best_split_info.left_sum_hessian); larger_leaf_splits_->Init(*right_leaf, data_partition_.get(), best_split_info.right_sum_gradient, best_split_info.right_sum_hessian); } else { smaller_leaf_splits_->Init(*right_leaf, data_partition_.get(), best_split_info.right_sum_gradient, best_split_info.right_sum_hessian); larger_leaf_splits_->Init(*left_leaf, data_partition_.get(), best_split_info.left_sum_gradient, best_split_info.left_sum_hessian); p_right = smaller_leaf_splits_.get(); p_left = larger_leaf_splits_.get(); } p_left->SetValueConstraint(best_split_info.min_constraint, best_split_info.max_constraint); p_right->SetValueConstraint(best_split_info.min_constraint, best_split_info.max_constraint); if (is_numerical_split) { double mid = (best_split_info.left_output + best_split_info.right_output) / 2.0f; if (best_split_info.monotone_type < 0) { p_left->SetValueConstraint(mid, best_split_info.max_constraint); p_right->SetValueConstraint(best_split_info.min_constraint, mid); } else if (best_split_info.monotone_type > 0) { p_left->SetValueConstraint(best_split_info.min_constraint, mid); p_right->SetValueConstraint(mid, best_split_info.max_constraint); } } } void SerialTreeLearner::RenewTreeOutput(Tree* tree, const ObjectiveFunction* obj, std::function<double(const label_t*, int)> residual_getter, data_size_t total_num_data, const data_size_t* bag_indices, data_size_t bag_cnt) const { if (obj != nullptr && obj->IsRenewTreeOutput()) { CHECK(tree->num_leaves() <= data_partition_->num_leaves()); const data_size_t* bag_mapper = nullptr; if (total_num_data != num_data_) { CHECK(bag_cnt == num_data_); bag_mapper = bag_indices; } std::vector<int> n_nozeroworker_perleaf(tree->num_leaves(), 1); int num_machines = Network::num_machines(); #pragma omp parallel for schedule(static) for (int i = 0; i < tree->num_leaves(); ++i) { const double output = static_cast<double>(tree->LeafOutput(i)); data_size_t cnt_leaf_data = 0; auto index_mapper = data_partition_->GetIndexOnLeaf(i, &cnt_leaf_data); if (cnt_leaf_data > 0) { // bag_mapper[index_mapper[i]] const double new_output = obj->RenewTreeOutput(output, residual_getter, index_mapper, bag_mapper, cnt_leaf_data); tree->SetLeafOutput(i, new_output); } else { CHECK(num_machines > 1); tree->SetLeafOutput(i, 0.0); n_nozeroworker_perleaf[i] = 0; } } if (num_machines > 1) { std::vector<double> outputs(tree->num_leaves()); for (int i = 0; i < tree->num_leaves(); ++i) { outputs[i] = static_cast<double>(tree->LeafOutput(i)); } outputs = Network::GlobalSum(&outputs); n_nozeroworker_perleaf = Network::GlobalSum(&n_nozeroworker_perleaf); for (int i = 0; i < tree->num_leaves(); ++i) { tree->SetLeafOutput(i, outputs[i] / n_nozeroworker_perleaf[i]); } } } } } // namespace LightGBM
1
20,770
there is a `kEpsilon` you can use directly.
microsoft-LightGBM
cpp
@@ -17,9 +17,10 @@ limitations under the License. package ec2 import ( - "sigs.k8s.io/cluster-api/util/conditions" "strings" + "sigs.k8s.io/cluster-api/util/conditions" + "sigs.k8s.io/cluster-api-provider-aws/pkg/cloud/awserrors" "sigs.k8s.io/cluster-api-provider-aws/pkg/cloud/services/wait" "sigs.k8s.io/cluster-api-provider-aws/pkg/record"
1
/* Copyright 2018 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ec2 import ( "sigs.k8s.io/cluster-api/util/conditions" "strings" "sigs.k8s.io/cluster-api-provider-aws/pkg/cloud/awserrors" "sigs.k8s.io/cluster-api-provider-aws/pkg/cloud/services/wait" "sigs.k8s.io/cluster-api-provider-aws/pkg/record" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/ec2" "github.com/pkg/errors" infrav1 "sigs.k8s.io/cluster-api-provider-aws/api/v1alpha3" "sigs.k8s.io/cluster-api-provider-aws/pkg/cloud/converters" "sigs.k8s.io/cluster-api-provider-aws/pkg/cloud/filter" "sigs.k8s.io/cluster-api-provider-aws/pkg/cloud/tags" ) const ( anyIPv4CidrBlock = "0.0.0.0/0" mainRouteTableInVPCKey = "main" ) func (s *Service) reconcileRouteTables() error { if s.scope.VPC().IsUnmanaged(s.scope.Name()) { s.scope.V(4).Info("Skipping routing tables reconcile in unmanaged mode") return nil } s.scope.V(2).Info("Reconciling routing tables") subnetRouteMap, err := s.describeVpcRouteTablesBySubnet() if err != nil { return err } for i := range s.scope.Subnets() { // We need to compile the minimum routes for this subnet first, so we can compare it or create them. var routes []*ec2.Route sn := s.scope.Subnets()[i] if sn.IsPublic { if s.scope.VPC().InternetGatewayID == nil { return errors.Errorf("failed to create routing tables: internet gateway for %q is nil", s.scope.VPC().ID) } routes = append(routes, s.getGatewayPublicRoute()) } else { natGatewayID, err := s.getNatGatewayForSubnet(sn) if err != nil { return err } routes = append(routes, s.getNatGatewayPrivateRoute(natGatewayID)) } if rt, ok := subnetRouteMap[sn.ID]; ok { s.scope.V(2).Info("Subnet is already associated with route table", "subnet-id", sn.ID, "route-table-id", *rt.RouteTableId) // TODO(vincepri): check that everything is in order, e.g. routes match the subnet type. // For managed environments we need to reconcile the routes of our tables if there is a mistmatch. // For example, a gateway can be deleted and our controller will re-create it, then we replace the route // for the subnet to allow traffic to flow. for _, currentRoute := range rt.Routes { for i := range routes { // Routes destination cidr blocks must be unique within a routing table. // If there is a mistmatch, we replace the routing association. specRoute := routes[i] if *currentRoute.DestinationCidrBlock == *specRoute.DestinationCidrBlock && ((currentRoute.GatewayId != nil && *currentRoute.GatewayId != *specRoute.GatewayId) || (currentRoute.NatGatewayId != nil && *currentRoute.NatGatewayId != *specRoute.NatGatewayId)) { if err := wait.WaitForWithRetryable(wait.NewBackoff(), func() (bool, error) { if _, err := s.scope.EC2.ReplaceRoute(&ec2.ReplaceRouteInput{ RouteTableId: rt.RouteTableId, DestinationCidrBlock: specRoute.DestinationCidrBlock, GatewayId: specRoute.GatewayId, NatGatewayId: specRoute.NatGatewayId, }); err != nil { return false, err } return true, nil }); err != nil { record.Warnf(s.scope.AWSCluster, "FailedReplaceRoute", "Failed to replace outdated route on managed RouteTable %q: %v", *rt.RouteTableId, err) return errors.Wrapf(err, "failed to replace outdated route on route table %q", *rt.RouteTableId) } } } } // Make sure tags are up to date. if err := wait.WaitForWithRetryable(wait.NewBackoff(), func() (bool, error) { if err := tags.Ensure(converters.TagsToMap(rt.Tags), &tags.ApplyParams{ EC2Client: s.scope.EC2, BuildParams: s.getRouteTableTagParams(*rt.RouteTableId, sn.IsPublic, sn.AvailabilityZone), }); err != nil { return false, err } return true, nil }, awserrors.RouteTableNotFound); err != nil { record.Warnf(s.scope.AWSCluster, "FailedTagRouteTable", "Failed to tag managed RouteTable %q: %v", *rt.RouteTableId, err) return errors.Wrapf(err, "failed to ensure tags on route table %q", *rt.RouteTableId) } // Not recording "SuccessfulTagRouteTable" here as we don't know if this was a no-op or an actual change continue } // For each subnet that doesn't have a routing table associated with it, // create a new table with the appropriate default routes and associate it to the subnet. rt, err := s.createRouteTableWithRoutes(routes, sn.IsPublic, sn.AvailabilityZone) if err != nil { return err } if err := wait.WaitForWithRetryable(wait.NewBackoff(), func() (bool, error) { if err := s.associateRouteTable(rt, sn.ID); err != nil { return false, err } return true, nil }, awserrors.RouteTableNotFound, awserrors.SubnetNotFound); err != nil { return err } s.scope.V(2).Info("Subnet has been associated with route table", "subnet-id", sn.ID, "route-table-id", rt.ID) sn.RouteTableID = aws.String(rt.ID) } conditions.MarkTrue(s.scope.AWSCluster, infrav1.RouteTablesReadyCondition) return nil } func (s *Service) describeVpcRouteTablesBySubnet() (map[string]*ec2.RouteTable, error) { rts, err := s.describeVpcRouteTables() if err != nil { return nil, err } // Amazon allows a subnet to be associated only with a single routing table // https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html. res := make(map[string]*ec2.RouteTable) for _, rt := range rts { for _, as := range rt.Associations { if as.Main != nil && *as.Main { res[mainRouteTableInVPCKey] = rt } if as.SubnetId == nil { continue } res[*as.SubnetId] = rt } } return res, nil } func (s *Service) deleteRouteTables() error { if s.scope.VPC().IsUnmanaged(s.scope.Name()) { s.scope.V(4).Info("Skipping routing tables deletion in unmanaged mode") return nil } rts, err := s.describeVpcRouteTables() if err != nil { return errors.Wrapf(err, "failed to describe route tables in vpc %q", s.scope.VPC().ID) } for _, rt := range rts { for _, as := range rt.Associations { if as.SubnetId == nil { continue } if _, err := s.scope.EC2.DisassociateRouteTable(&ec2.DisassociateRouteTableInput{AssociationId: as.RouteTableAssociationId}); err != nil { record.Warnf(s.scope.AWSCluster, "FailedDisassociateRouteTable", "Failed to disassociate managed RouteTable %q from Subnet %q: %v", *rt.RouteTableId, *as.SubnetId, err) return errors.Wrapf(err, "failed to disassociate route table %q from subnet %q", *rt.RouteTableId, *as.SubnetId) } record.Eventf(s.scope.AWSCluster, "SuccessfulDisassociateRouteTable", "Disassociated managed RouteTable %q from subnet %q", *rt.RouteTableId, *as.SubnetId) s.scope.Info("Deleted association between route table and subnet", "route-table-id", *rt.RouteTableId, "subnet-id", *as.SubnetId) } if _, err := s.scope.EC2.DeleteRouteTable(&ec2.DeleteRouteTableInput{RouteTableId: rt.RouteTableId}); err != nil { record.Warnf(s.scope.AWSCluster, "FailedDeleteRouteTable", "Failed to delete managed RouteTable %q: %v", *rt.RouteTableId, err) return errors.Wrapf(err, "failed to delete route table %q", *rt.RouteTableId) } record.Eventf(s.scope.AWSCluster, "SuccessfulDeleteRouteTable", "Deleted managed RouteTable %q", *rt.RouteTableId) s.scope.Info("Deleted route table", "route-table-id", *rt.RouteTableId) } return nil } func (s *Service) describeVpcRouteTables() ([]*ec2.RouteTable, error) { filters := []*ec2.Filter{ filter.EC2.VPC(s.scope.VPC().ID), } if !s.scope.VPC().IsUnmanaged(s.scope.Name()) { filters = append(filters, filter.EC2.Cluster(s.scope.Name())) } out, err := s.scope.EC2.DescribeRouteTables(&ec2.DescribeRouteTablesInput{ Filters: filters, }) if err != nil { record.Eventf(s.scope.AWSCluster, "FailedDescribeVPCRouteTable", "Failed to describe route tables in vpc %q: %v", s.scope.VPC().ID, err) return nil, errors.Wrapf(err, "failed to describe route tables in vpc %q", s.scope.VPC().ID) } return out.RouteTables, nil } func (s *Service) createRouteTableWithRoutes(routes []*ec2.Route, isPublic bool, zone string) (*infrav1.RouteTable, error) { out, err := s.scope.EC2.CreateRouteTable(&ec2.CreateRouteTableInput{ VpcId: aws.String(s.scope.VPC().ID), }) if err != nil { record.Warnf(s.scope.AWSCluster, "FailedCreateRouteTable", "Failed to create managed RouteTable: %v", err) return nil, errors.Wrapf(err, "failed to create route table in vpc %q", s.scope.VPC().ID) } record.Eventf(s.scope.AWSCluster, "SuccessfulCreateRouteTable", "Created managed RouteTable %q", *out.RouteTable.RouteTableId) if err := wait.WaitForWithRetryable(wait.NewBackoff(), func() (bool, error) { if err := tags.Apply(&tags.ApplyParams{ EC2Client: s.scope.EC2, BuildParams: s.getRouteTableTagParams(*out.RouteTable.RouteTableId, isPublic, zone), }); err != nil { return false, err } return true, nil }, awserrors.RouteTableNotFound); err != nil { record.Warnf(s.scope.AWSCluster, "FailedTagRouteTable", "Failed to tag managed RouteTable %q: %v", *out.RouteTable.RouteTableId, err) return nil, errors.Wrapf(err, "failed to tag route table %q", *out.RouteTable.RouteTableId) } record.Eventf(s.scope.AWSCluster, "SuccessfulTagRouteTable", "Tagged managed RouteTable %q", *out.RouteTable.RouteTableId) for i := range routes { route := routes[i] if err := wait.WaitForWithRetryable(wait.NewBackoff(), func() (bool, error) { if _, err := s.scope.EC2.CreateRoute(&ec2.CreateRouteInput{ RouteTableId: out.RouteTable.RouteTableId, DestinationCidrBlock: route.DestinationCidrBlock, DestinationIpv6CidrBlock: route.DestinationIpv6CidrBlock, EgressOnlyInternetGatewayId: route.EgressOnlyInternetGatewayId, GatewayId: route.GatewayId, InstanceId: route.InstanceId, NatGatewayId: route.NatGatewayId, NetworkInterfaceId: route.NetworkInterfaceId, VpcPeeringConnectionId: route.VpcPeeringConnectionId, }); err != nil { return false, err } return true, nil }, awserrors.RouteTableNotFound, awserrors.NATGatewayNotFound, awserrors.GatewayNotFound); err != nil { // TODO(vincepri): cleanup the route table if this fails. record.Warnf(s.scope.AWSCluster, "FailedCreateRoute", "Failed to create route %s for RouteTable %q: %v", route.GoString(), *out.RouteTable.RouteTableId, err) return nil, errors.Wrapf(err, "failed to create route in route table %q: %s", *out.RouteTable.RouteTableId, route.GoString()) } record.Eventf(s.scope.AWSCluster, "SuccessfulCreateRoute", "Created route %s for RouteTable %q", route.GoString(), *out.RouteTable.RouteTableId) } return &infrav1.RouteTable{ ID: *out.RouteTable.RouteTableId, }, nil } func (s *Service) associateRouteTable(rt *infrav1.RouteTable, subnetID string) error { _, err := s.scope.EC2.AssociateRouteTable(&ec2.AssociateRouteTableInput{ RouteTableId: aws.String(rt.ID), SubnetId: aws.String(subnetID), }) if err != nil { record.Warnf(s.scope.AWSCluster, "FailedAssociateRouteTable", "Failed to associate managed RouteTable %q with Subnet %q: %v", rt.ID, subnetID, err) return errors.Wrapf(err, "failed to associate route table %q to subnet %q", rt.ID, subnetID) } record.Eventf(s.scope.AWSCluster, "SuccessfulAssociateRouteTable", "Associated managed RouteTable %q with subnet %q", rt.ID, subnetID) return nil } func (s *Service) getNatGatewayPrivateRoute(natGatewayID string) *ec2.Route { return &ec2.Route{ DestinationCidrBlock: aws.String(anyIPv4CidrBlock), NatGatewayId: aws.String(natGatewayID), } } func (s *Service) getGatewayPublicRoute() *ec2.Route { return &ec2.Route{ DestinationCidrBlock: aws.String(anyIPv4CidrBlock), GatewayId: aws.String(*s.scope.VPC().InternetGatewayID), } } func (s *Service) getRouteTableTagParams(id string, public bool, zone string) infrav1.BuildParams { var name strings.Builder name.WriteString(s.scope.Name()) name.WriteString("-rt-") if public { name.WriteString("public") } else { name.WriteString("private") } name.WriteString("-") name.WriteString(zone) return infrav1.BuildParams{ ClusterName: s.scope.Name(), ResourceID: id, Lifecycle: infrav1.ResourceLifecycleOwned, Name: aws.String(name.String()), Role: aws.String(infrav1.CommonRoleTagValue), Additional: s.scope.AdditionalTags(), } }
1
15,501
This should be grouped with the below imports, and the two separate groups of imports below should likely also be grouped together
kubernetes-sigs-cluster-api-provider-aws
go
@@ -888,11 +888,11 @@ void cvdescriptorset::DescriptorSet::PerformWriteUpdate(const VkWriteDescriptorS } // Validate Copy update bool cvdescriptorset::DescriptorSet::ValidateCopyUpdate(const debug_report_data *report_data, const VkCopyDescriptorSet *update, - const DescriptorSet *src_set, std::string *error_code, + const DescriptorSet *src_set, std::string &error_code, std::string *error_msg) { // Verify dst layout still valid if (p_layout_->IsDestroyed()) { - *error_code = "VUID-VkCopyDescriptorSet-dstSet-parameter"; + error_code = "VUID-VkCopyDescriptorSet-dstSet-parameter"; string_sprintf(error_msg, "Cannot call vkUpdateDescriptorSets() to perform copy update on descriptor set dstSet 0x%" PRIxLEAST64 " created with destroyed VkDescriptorSetLayout 0x%" PRIxLEAST64,
1
/* Copyright (c) 2015-2016 The Khronos Group Inc. * Copyright (c) 2015-2016 Valve Corporation * Copyright (c) 2015-2016 LunarG, Inc. * Copyright (C) 2015-2016 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Author: Tobin Ehlis <[email protected]> * John Zulauf <[email protected]> */ // Allow use of STL min and max functions in Windows #define NOMINMAX #include "descriptor_sets.h" #include "hash_vk_types.h" #include "vk_enum_string_helper.h" #include "vk_safe_struct.h" #include "vk_typemap_helper.h" #include "buffer_validation.h" #include <sstream> #include <algorithm> #include <memory> // ExtendedBinding collects a VkDescriptorSetLayoutBinding and any extended // state that comes from a different array/structure so they can stay together // while being sorted by binding number. struct ExtendedBinding { ExtendedBinding(const VkDescriptorSetLayoutBinding *l, VkDescriptorBindingFlagsEXT f) : layout_binding(l), binding_flags(f) {} const VkDescriptorSetLayoutBinding *layout_binding; VkDescriptorBindingFlagsEXT binding_flags; }; struct BindingNumCmp { bool operator()(const ExtendedBinding &a, const ExtendedBinding &b) const { return a.layout_binding->binding < b.layout_binding->binding; } }; using DescriptorSetLayoutDef = cvdescriptorset::DescriptorSetLayoutDef; using DescriptorSetLayoutId = cvdescriptorset::DescriptorSetLayoutId; // Canonical dictionary of DescriptorSetLayoutDef (without any handle/device specific information) cvdescriptorset::DescriptorSetLayoutDict descriptor_set_layout_dict; DescriptorSetLayoutId get_canonical_id(const VkDescriptorSetLayoutCreateInfo *p_create_info) { return descriptor_set_layout_dict.look_up(DescriptorSetLayoutDef(p_create_info)); } // Construct DescriptorSetLayout instance from given create info // Proactively reserve and resize as possible, as the reallocation was visible in profiling cvdescriptorset::DescriptorSetLayoutDef::DescriptorSetLayoutDef(const VkDescriptorSetLayoutCreateInfo *p_create_info) : flags_(p_create_info->flags), binding_count_(0), descriptor_count_(0), dynamic_descriptor_count_(0) { const auto *flags_create_info = lvl_find_in_chain<VkDescriptorSetLayoutBindingFlagsCreateInfoEXT>(p_create_info->pNext); binding_type_stats_ = {0, 0, 0}; std::set<ExtendedBinding, BindingNumCmp> sorted_bindings; const uint32_t input_bindings_count = p_create_info->bindingCount; // Sort the input bindings in binding number order, eliminating duplicates for (uint32_t i = 0; i < input_bindings_count; i++) { VkDescriptorBindingFlagsEXT flags = 0; if (flags_create_info && flags_create_info->bindingCount == p_create_info->bindingCount) { flags = flags_create_info->pBindingFlags[i]; } sorted_bindings.insert(ExtendedBinding(p_create_info->pBindings + i, flags)); } // Store the create info in the sorted order from above std::map<uint32_t, uint32_t> binding_to_dyn_count; uint32_t index = 0; binding_count_ = static_cast<uint32_t>(sorted_bindings.size()); bindings_.reserve(binding_count_); binding_flags_.reserve(binding_count_); binding_to_index_map_.reserve(binding_count_); for (auto input_binding : sorted_bindings) { // Add to binding and map, s.t. it is robust to invalid duplication of binding_num const auto binding_num = input_binding.layout_binding->binding; binding_to_index_map_[binding_num] = index++; bindings_.emplace_back(input_binding.layout_binding); auto &binding_info = bindings_.back(); binding_flags_.emplace_back(input_binding.binding_flags); descriptor_count_ += binding_info.descriptorCount; if (binding_info.descriptorCount > 0) { non_empty_bindings_.insert(binding_num); } if (binding_info.descriptorType == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC || binding_info.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC) { binding_to_dyn_count[binding_num] = binding_info.descriptorCount; dynamic_descriptor_count_ += binding_info.descriptorCount; binding_type_stats_.dynamic_buffer_count++; } else if ((binding_info.descriptorType == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER) || (binding_info.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER)) { binding_type_stats_.non_dynamic_buffer_count++; } else { binding_type_stats_.image_sampler_count++; } } assert(bindings_.size() == binding_count_); assert(binding_flags_.size() == binding_count_); uint32_t global_index = 0; binding_to_global_index_range_map_.reserve(binding_count_); // Vector order is finalized so create maps of bindings to descriptors and descriptors to indices for (uint32_t i = 0; i < binding_count_; ++i) { auto binding_num = bindings_[i].binding; auto final_index = global_index + bindings_[i].descriptorCount; binding_to_global_index_range_map_[binding_num] = IndexRange(global_index, final_index); if (final_index != global_index) { global_start_to_index_map_[global_index] = i; } global_index = final_index; } // Now create dyn offset array mapping for any dynamic descriptors uint32_t dyn_array_idx = 0; binding_to_dynamic_array_idx_map_.reserve(binding_to_dyn_count.size()); for (const auto &bc_pair : binding_to_dyn_count) { binding_to_dynamic_array_idx_map_[bc_pair.first] = dyn_array_idx; dyn_array_idx += bc_pair.second; } } size_t cvdescriptorset::DescriptorSetLayoutDef::hash() const { hash_util::HashCombiner hc; hc << flags_; hc.Combine(bindings_); return hc.Value(); } // // Return valid index or "end" i.e. binding_count_; // The asserts in "Get" are reduced to the set where no valid answer(like null or 0) could be given // Common code for all binding lookups. uint32_t cvdescriptorset::DescriptorSetLayoutDef::GetIndexFromBinding(uint32_t binding) const { const auto &bi_itr = binding_to_index_map_.find(binding); if (bi_itr != binding_to_index_map_.cend()) return bi_itr->second; return GetBindingCount(); } VkDescriptorSetLayoutBinding const *cvdescriptorset::DescriptorSetLayoutDef::GetDescriptorSetLayoutBindingPtrFromIndex( const uint32_t index) const { if (index >= bindings_.size()) return nullptr; return bindings_[index].ptr(); } // Return descriptorCount for given index, 0 if index is unavailable uint32_t cvdescriptorset::DescriptorSetLayoutDef::GetDescriptorCountFromIndex(const uint32_t index) const { if (index >= bindings_.size()) return 0; return bindings_[index].descriptorCount; } // For the given index, return descriptorType VkDescriptorType cvdescriptorset::DescriptorSetLayoutDef::GetTypeFromIndex(const uint32_t index) const { assert(index < bindings_.size()); if (index < bindings_.size()) return bindings_[index].descriptorType; return VK_DESCRIPTOR_TYPE_MAX_ENUM; } // For the given index, return stageFlags VkShaderStageFlags cvdescriptorset::DescriptorSetLayoutDef::GetStageFlagsFromIndex(const uint32_t index) const { assert(index < bindings_.size()); if (index < bindings_.size()) return bindings_[index].stageFlags; return VkShaderStageFlags(0); } // Return binding flags for given index, 0 if index is unavailable VkDescriptorBindingFlagsEXT cvdescriptorset::DescriptorSetLayoutDef::GetDescriptorBindingFlagsFromIndex( const uint32_t index) const { if (index >= binding_flags_.size()) return 0; return binding_flags_[index]; } // For the given global index, return index uint32_t cvdescriptorset::DescriptorSetLayoutDef::GetIndexFromGlobalIndex(const uint32_t global_index) const { auto start_it = global_start_to_index_map_.upper_bound(global_index); uint32_t index = binding_count_; assert(start_it != global_start_to_index_map_.cbegin()); if (start_it != global_start_to_index_map_.cbegin()) { --start_it; index = start_it->second; #ifndef NDEBUG const auto &range = GetGlobalIndexRangeFromBinding(bindings_[index].binding); assert(range.start <= global_index && global_index < range.end); #endif } return index; } // For the given binding, return the global index range // As start and end are often needed in pairs, get both with a single hash lookup. const cvdescriptorset::IndexRange &cvdescriptorset::DescriptorSetLayoutDef::GetGlobalIndexRangeFromBinding( const uint32_t binding) const { assert(binding_to_global_index_range_map_.count(binding)); // In error case max uint32_t so index is out of bounds to break ASAP const static IndexRange kInvalidRange = {0xFFFFFFFF, 0xFFFFFFFF}; const auto &range_it = binding_to_global_index_range_map_.find(binding); if (range_it != binding_to_global_index_range_map_.end()) { return range_it->second; } return kInvalidRange; } // For given binding, return ptr to ImmutableSampler array VkSampler const *cvdescriptorset::DescriptorSetLayoutDef::GetImmutableSamplerPtrFromBinding(const uint32_t binding) const { const auto &bi_itr = binding_to_index_map_.find(binding); if (bi_itr != binding_to_index_map_.end()) { return bindings_[bi_itr->second].pImmutableSamplers; } return nullptr; } // Move to next valid binding having a non-zero binding count uint32_t cvdescriptorset::DescriptorSetLayoutDef::GetNextValidBinding(const uint32_t binding) const { auto it = non_empty_bindings_.upper_bound(binding); assert(it != non_empty_bindings_.cend()); if (it != non_empty_bindings_.cend()) return *it; return GetMaxBinding() + 1; } // For given index, return ptr to ImmutableSampler array VkSampler const *cvdescriptorset::DescriptorSetLayoutDef::GetImmutableSamplerPtrFromIndex(const uint32_t index) const { if (index < bindings_.size()) { return bindings_[index].pImmutableSamplers; } return nullptr; } // If our layout is compatible with rh_ds_layout, return true, // else return false and fill in error_msg will description of what causes incompatibility bool cvdescriptorset::DescriptorSetLayout::IsCompatible(DescriptorSetLayout const *const rh_ds_layout, std::string *error_msg) const { // Trivial case if (layout_ == rh_ds_layout->GetDescriptorSetLayout()) return true; if (get_layout_def() == rh_ds_layout->get_layout_def()) return true; bool detailed_compat_check = get_layout_def()->IsCompatible(layout_, rh_ds_layout->GetDescriptorSetLayout(), rh_ds_layout->get_layout_def(), error_msg); // The detailed check should never tell us mismatching DSL are compatible assert(!detailed_compat_check); return detailed_compat_check; } // Do a detailed compatibility check of this def (referenced by ds_layout), vs. the rhs (layout and def) // Should only be called if trivial accept has failed, and in that context should return false. bool cvdescriptorset::DescriptorSetLayoutDef::IsCompatible(VkDescriptorSetLayout ds_layout, VkDescriptorSetLayout rh_ds_layout, DescriptorSetLayoutDef const *const rh_ds_layout_def, std::string *error_msg) const { if (descriptor_count_ != rh_ds_layout_def->descriptor_count_) { std::stringstream error_str; error_str << "DescriptorSetLayout " << ds_layout << " has " << descriptor_count_ << " descriptors, but DescriptorSetLayout " << rh_ds_layout << ", which comes from pipelineLayout, has " << rh_ds_layout_def->descriptor_count_ << " descriptors."; *error_msg = error_str.str(); return false; // trivial fail case } // Descriptor counts match so need to go through bindings one-by-one // and verify that type and stageFlags match for (auto binding : bindings_) { // TODO : Do we also need to check immutable samplers? // VkDescriptorSetLayoutBinding *rh_binding; if (binding.descriptorCount != rh_ds_layout_def->GetDescriptorCountFromBinding(binding.binding)) { std::stringstream error_str; error_str << "Binding " << binding.binding << " for DescriptorSetLayout " << ds_layout << " has a descriptorCount of " << binding.descriptorCount << " but binding " << binding.binding << " for DescriptorSetLayout " << rh_ds_layout << ", which comes from pipelineLayout, has a descriptorCount of " << rh_ds_layout_def->GetDescriptorCountFromBinding(binding.binding); *error_msg = error_str.str(); return false; } else if (binding.descriptorType != rh_ds_layout_def->GetTypeFromBinding(binding.binding)) { std::stringstream error_str; error_str << "Binding " << binding.binding << " for DescriptorSetLayout " << ds_layout << " is type '" << string_VkDescriptorType(binding.descriptorType) << "' but binding " << binding.binding << " for DescriptorSetLayout " << rh_ds_layout << ", which comes from pipelineLayout, is type '" << string_VkDescriptorType(rh_ds_layout_def->GetTypeFromBinding(binding.binding)) << "'"; *error_msg = error_str.str(); return false; } else if (binding.stageFlags != rh_ds_layout_def->GetStageFlagsFromBinding(binding.binding)) { std::stringstream error_str; error_str << "Binding " << binding.binding << " for DescriptorSetLayout " << ds_layout << " has stageFlags " << binding.stageFlags << " but binding " << binding.binding << " for DescriptorSetLayout " << rh_ds_layout << ", which comes from pipelineLayout, has stageFlags " << rh_ds_layout_def->GetStageFlagsFromBinding(binding.binding); *error_msg = error_str.str(); return false; } } return true; } bool cvdescriptorset::DescriptorSetLayoutDef::IsNextBindingConsistent(const uint32_t binding) const { if (!binding_to_index_map_.count(binding + 1)) return false; auto const &bi_itr = binding_to_index_map_.find(binding); if (bi_itr != binding_to_index_map_.end()) { const auto &next_bi_itr = binding_to_index_map_.find(binding + 1); if (next_bi_itr != binding_to_index_map_.end()) { auto type = bindings_[bi_itr->second].descriptorType; auto stage_flags = bindings_[bi_itr->second].stageFlags; auto immut_samp = bindings_[bi_itr->second].pImmutableSamplers ? true : false; auto flags = binding_flags_[bi_itr->second]; if ((type != bindings_[next_bi_itr->second].descriptorType) || (stage_flags != bindings_[next_bi_itr->second].stageFlags) || (immut_samp != (bindings_[next_bi_itr->second].pImmutableSamplers ? true : false)) || (flags != binding_flags_[next_bi_itr->second])) { return false; } return true; } } return false; } // Starting at offset descriptor of given binding, parse over update_count // descriptor updates and verify that for any binding boundaries that are crossed, the next binding(s) are all consistent // Consistency means that their type, stage flags, and whether or not they use immutable samplers matches // If so, return true. If not, fill in error_msg and return false bool cvdescriptorset::DescriptorSetLayoutDef::VerifyUpdateConsistency(uint32_t current_binding, uint32_t offset, uint32_t update_count, const char *type, const VkDescriptorSet set, std::string *error_msg) const { // Verify consecutive bindings match (if needed) auto orig_binding = current_binding; // Track count of descriptors in the current_bindings that are remaining to be updated auto binding_remaining = GetDescriptorCountFromBinding(current_binding); // First, it's legal to offset beyond your own binding so handle that case // Really this is just searching for the binding in which the update begins and adjusting offset accordingly while (offset >= binding_remaining) { // Advance to next binding, decrement offset by binding size offset -= binding_remaining; binding_remaining = GetDescriptorCountFromBinding(++current_binding); } binding_remaining -= offset; while (update_count > binding_remaining) { // While our updates overstep current binding // Verify next consecutive binding matches type, stage flags & immutable sampler use if (!IsNextBindingConsistent(current_binding++)) { std::stringstream error_str; error_str << "Attempting " << type << " descriptor set " << set << " binding #" << orig_binding << " with #" << update_count << " descriptors being updated but this update oversteps the bounds of this binding and the next binding is " "not consistent with current binding so this update is invalid."; *error_msg = error_str.str(); return false; } // For sake of this check consider the bindings updated and grab count for next binding update_count -= binding_remaining; binding_remaining = GetDescriptorCountFromBinding(current_binding); } return true; } // The DescriptorSetLayout stores the per handle data for a descriptor set layout, and references the common defintion for the // handle invariant portion cvdescriptorset::DescriptorSetLayout::DescriptorSetLayout(const VkDescriptorSetLayoutCreateInfo *p_create_info, const VkDescriptorSetLayout layout) : layout_(layout), layout_destroyed_(false), layout_id_(get_canonical_id(p_create_info)) {} // Validate descriptor set layout create info bool cvdescriptorset::DescriptorSetLayout::ValidateCreateInfo( const debug_report_data *report_data, const VkDescriptorSetLayoutCreateInfo *create_info, const bool push_descriptor_ext, const uint32_t max_push_descriptors, const bool descriptor_indexing_ext, const VkPhysicalDeviceDescriptorIndexingFeaturesEXT *descriptor_indexing_features) { bool skip = false; std::unordered_set<uint32_t> bindings; uint64_t total_descriptors = 0; const auto *flags_create_info = lvl_find_in_chain<VkDescriptorSetLayoutBindingFlagsCreateInfoEXT>(create_info->pNext); const bool push_descriptor_set = !!(create_info->flags & VK_DESCRIPTOR_SET_LAYOUT_CREATE_PUSH_DESCRIPTOR_BIT_KHR); if (push_descriptor_set && !push_descriptor_ext) { skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, DRAWSTATE_EXTENSION_NOT_ENABLED, "Attempted to use %s in %s but its required extension %s has not been enabled.\n", "VK_DESCRIPTOR_SET_LAYOUT_CREATE_PUSH_DESCRIPTOR_BIT_KHR", "VkDescriptorSetLayoutCreateInfo::flags", VK_KHR_PUSH_DESCRIPTOR_EXTENSION_NAME); } const bool update_after_bind_set = !!(create_info->flags & VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT_EXT); if (update_after_bind_set && !descriptor_indexing_ext) { skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, DRAWSTATE_EXTENSION_NOT_ENABLED, "Attemped to use %s in %s but its required extension %s has not been enabled.\n", "VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT_EXT", "VkDescriptorSetLayoutCreateInfo::flags", VK_EXT_DESCRIPTOR_INDEXING_EXTENSION_NAME); } auto valid_type = [push_descriptor_set](const VkDescriptorType type) { return !push_descriptor_set || ((type != VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC) && (type != VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC)); }; uint32_t max_binding = 0; for (uint32_t i = 0; i < create_info->bindingCount; ++i) { const auto &binding_info = create_info->pBindings[i]; max_binding = std::max(max_binding, binding_info.binding); if (!bindings.insert(binding_info.binding).second) { skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkDescriptorSetLayoutCreateInfo-binding-00279", "duplicated binding number in VkDescriptorSetLayoutBinding."); } if (!valid_type(binding_info.descriptorType)) { skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkDescriptorSetLayoutCreateInfo-flags-00280", "invalid type %s ,for push descriptors in VkDescriptorSetLayoutBinding entry %" PRIu32 ".", string_VkDescriptorType(binding_info.descriptorType), i); } total_descriptors += binding_info.descriptorCount; } if (flags_create_info) { if (flags_create_info->bindingCount != 0 && flags_create_info->bindingCount != create_info->bindingCount) { skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkDescriptorSetLayoutBindingFlagsCreateInfoEXT-bindingCount-03002", "VkDescriptorSetLayoutCreateInfo::bindingCount (%d) != " "VkDescriptorSetLayoutBindingFlagsCreateInfoEXT::bindingCount (%d)", create_info->bindingCount, flags_create_info->bindingCount); } if (flags_create_info->bindingCount == create_info->bindingCount) { for (uint32_t i = 0; i < create_info->bindingCount; ++i) { const auto &binding_info = create_info->pBindings[i]; if (flags_create_info->pBindingFlags[i] & VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT_EXT) { if (!update_after_bind_set) { skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkDescriptorSetLayoutCreateInfo-flags-03000", "Invalid flags for VkDescriptorSetLayoutBinding entry %" PRIu32, i); } if (binding_info.descriptorType == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER && !descriptor_indexing_features->descriptorBindingUniformBufferUpdateAfterBind) { skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkDescriptorSetLayoutBindingFlagsCreateInfoEXT-" "descriptorBindingUniformBufferUpdateAfterBind-03005", "Invalid flags for VkDescriptorSetLayoutBinding entry %" PRIu32, i); } if ((binding_info.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER || binding_info.descriptorType == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER || binding_info.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE) && !descriptor_indexing_features->descriptorBindingSampledImageUpdateAfterBind) { skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkDescriptorSetLayoutBindingFlagsCreateInfoEXT-" "descriptorBindingSampledImageUpdateAfterBind-03006", "Invalid flags for VkDescriptorSetLayoutBinding entry %" PRIu32, i); } if (binding_info.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE && !descriptor_indexing_features->descriptorBindingStorageImageUpdateAfterBind) { skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkDescriptorSetLayoutBindingFlagsCreateInfoEXT-" "descriptorBindingStorageImageUpdateAfterBind-03007", "Invalid flags for VkDescriptorSetLayoutBinding entry %" PRIu32, i); } if (binding_info.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER && !descriptor_indexing_features->descriptorBindingStorageBufferUpdateAfterBind) { skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkDescriptorSetLayoutBindingFlagsCreateInfoEXT-" "descriptorBindingStorageBufferUpdateAfterBind-03008", "Invalid flags for VkDescriptorSetLayoutBinding entry %" PRIu32, i); } if (binding_info.descriptorType == VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER && !descriptor_indexing_features->descriptorBindingUniformTexelBufferUpdateAfterBind) { skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkDescriptorSetLayoutBindingFlagsCreateInfoEXT-" "descriptorBindingUniformTexelBufferUpdateAfterBind-03009", "Invalid flags for VkDescriptorSetLayoutBinding entry %" PRIu32, i); } if (binding_info.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER && !descriptor_indexing_features->descriptorBindingStorageTexelBufferUpdateAfterBind) { skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkDescriptorSetLayoutBindingFlagsCreateInfoEXT-" "descriptorBindingStorageTexelBufferUpdateAfterBind-03010", "Invalid flags for VkDescriptorSetLayoutBinding entry %" PRIu32, i); } if ((binding_info.descriptorType == VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT || binding_info.descriptorType == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC || binding_info.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC)) { skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkDescriptorSetLayoutBindingFlagsCreateInfoEXT-None-03011", "Invalid flags for VkDescriptorSetLayoutBinding entry %" PRIu32, i); } } if (flags_create_info->pBindingFlags[i] & VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT_EXT) { if (!descriptor_indexing_features->descriptorBindingUpdateUnusedWhilePending) { skip |= log_msg( report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkDescriptorSetLayoutBindingFlagsCreateInfoEXT-descriptorBindingUpdateUnusedWhilePending-03012", "Invalid flags for VkDescriptorSetLayoutBinding entry %" PRIu32, i); } } if (flags_create_info->pBindingFlags[i] & VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT_EXT) { if (!descriptor_indexing_features->descriptorBindingPartiallyBound) { skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkDescriptorSetLayoutBindingFlagsCreateInfoEXT-descriptorBindingPartiallyBound-03013", "Invalid flags for VkDescriptorSetLayoutBinding entry %" PRIu32, i); } } if (flags_create_info->pBindingFlags[i] & VK_DESCRIPTOR_BINDING_VARIABLE_DESCRIPTOR_COUNT_BIT_EXT) { if (binding_info.binding != max_binding) { skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkDescriptorSetLayoutBindingFlagsCreateInfoEXT-pBindingFlags-03004", "Invalid flags for VkDescriptorSetLayoutBinding entry %" PRIu32, i); } if (!descriptor_indexing_features->descriptorBindingVariableDescriptorCount) { skip |= log_msg( report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkDescriptorSetLayoutBindingFlagsCreateInfoEXT-descriptorBindingVariableDescriptorCount-03014", "Invalid flags for VkDescriptorSetLayoutBinding entry %" PRIu32, i); } if ((binding_info.descriptorType == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC || binding_info.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC)) { skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkDescriptorSetLayoutBindingFlagsCreateInfoEXT-pBindingFlags-03015", "Invalid flags for VkDescriptorSetLayoutBinding entry %" PRIu32, i); } } if (push_descriptor_set && (flags_create_info->pBindingFlags[i] & (VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT_EXT | VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT_EXT | VK_DESCRIPTOR_BINDING_VARIABLE_DESCRIPTOR_COUNT_BIT_EXT))) { skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkDescriptorSetLayoutBindingFlagsCreateInfoEXT-flags-03003", "Invalid flags for VkDescriptorSetLayoutBinding entry %" PRIu32, i); } } } } if ((push_descriptor_set) && (total_descriptors > max_push_descriptors)) { const char *undefined = push_descriptor_ext ? "" : " -- undefined"; skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkDescriptorSetLayoutCreateInfo-flags-00281", "for push descriptor, total descriptor count in layout (%" PRIu64 ") must not be greater than VkPhysicalDevicePushDescriptorPropertiesKHR::maxPushDescriptors (%" PRIu32 "%s).", total_descriptors, max_push_descriptors, undefined); } return skip; } cvdescriptorset::AllocateDescriptorSetsData::AllocateDescriptorSetsData(uint32_t count) : required_descriptors_by_type{}, layout_nodes(count, nullptr) {} cvdescriptorset::DescriptorSet::DescriptorSet(const VkDescriptorSet set, const VkDescriptorPool pool, const std::shared_ptr<DescriptorSetLayout const> &layout, uint32_t variable_count, layer_data *dev_data) : some_update_(false), set_(set), pool_state_(nullptr), p_layout_(layout), device_data_(dev_data), limits_(GetPhysDevProperties(dev_data)->properties.limits), variable_count_(variable_count) { pool_state_ = GetDescriptorPoolState(dev_data, pool); // Foreach binding, create default descriptors of given type descriptors_.reserve(p_layout_->GetTotalDescriptorCount()); for (uint32_t i = 0; i < p_layout_->GetBindingCount(); ++i) { auto type = p_layout_->GetTypeFromIndex(i); switch (type) { case VK_DESCRIPTOR_TYPE_SAMPLER: { auto immut_sampler = p_layout_->GetImmutableSamplerPtrFromIndex(i); for (uint32_t di = 0; di < p_layout_->GetDescriptorCountFromIndex(i); ++di) { if (immut_sampler) { descriptors_.emplace_back(new SamplerDescriptor(immut_sampler + di)); some_update_ = true; // Immutable samplers are updated at creation } else descriptors_.emplace_back(new SamplerDescriptor(nullptr)); } break; } case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER: { auto immut = p_layout_->GetImmutableSamplerPtrFromIndex(i); for (uint32_t di = 0; di < p_layout_->GetDescriptorCountFromIndex(i); ++di) { if (immut) { descriptors_.emplace_back(new ImageSamplerDescriptor(immut + di)); some_update_ = true; // Immutable samplers are updated at creation } else descriptors_.emplace_back(new ImageSamplerDescriptor(nullptr)); } break; } // ImageDescriptors case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE: case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT: case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE: for (uint32_t di = 0; di < p_layout_->GetDescriptorCountFromIndex(i); ++di) descriptors_.emplace_back(new ImageDescriptor(type)); break; case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER: case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER: for (uint32_t di = 0; di < p_layout_->GetDescriptorCountFromIndex(i); ++di) descriptors_.emplace_back(new TexelDescriptor(type)); break; case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER: case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC: case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER: case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC: for (uint32_t di = 0; di < p_layout_->GetDescriptorCountFromIndex(i); ++di) descriptors_.emplace_back(new BufferDescriptor(type)); break; default: assert(0); // Bad descriptor type specified break; } } } cvdescriptorset::DescriptorSet::~DescriptorSet() { InvalidateBoundCmdBuffers(); } static std::string string_descriptor_req_view_type(descriptor_req req) { std::string result(""); for (unsigned i = 0; i <= VK_IMAGE_VIEW_TYPE_END_RANGE; i++) { if (req & (1 << i)) { if (result.size()) result += ", "; result += string_VkImageViewType(VkImageViewType(i)); } } if (!result.size()) result = "(none)"; return result; } // Is this sets underlying layout compatible with passed in layout according to "Pipeline Layout Compatibility" in spec? bool cvdescriptorset::DescriptorSet::IsCompatible(DescriptorSetLayout const *const layout, std::string *error) const { return layout->IsCompatible(p_layout_.get(), error); } // Validate that the state of this set is appropriate for the given bindings and dynamic_offsets at Draw time // This includes validating that all descriptors in the given bindings are updated, // that any update buffers are valid, and that any dynamic offsets are within the bounds of their buffers. // Return true if state is acceptable, or false and write an error message into error string bool cvdescriptorset::DescriptorSet::ValidateDrawState(const std::map<uint32_t, descriptor_req> &bindings, const std::vector<uint32_t> &dynamic_offsets, GLOBAL_CB_NODE *cb_node, const char *caller, std::string *error) const { for (auto binding_pair : bindings) { auto binding = binding_pair.first; if (!p_layout_->HasBinding(binding)) { std::stringstream error_str; error_str << "Attempting to validate DrawState for binding #" << binding << " which is an invalid binding for this descriptor set."; *error = error_str.str(); return false; } IndexRange index_range = p_layout_->GetGlobalIndexRangeFromBinding(binding); auto array_idx = 0; // Track array idx if we're dealing with array descriptors if (IsVariableDescriptorCount(binding)) { // Only validate the first N descriptors if it uses variable_count index_range.end = index_range.start + GetVariableDescriptorCount(); } for (uint32_t i = index_range.start; i < index_range.end; ++i, ++array_idx) { if (p_layout_->GetDescriptorBindingFlagsFromBinding(binding) & VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT_EXT) { // Can't validate the descriptor because it may not have been updated, // or the view could have been destroyed continue; } else if (!descriptors_[i]->updated) { std::stringstream error_str; error_str << "Descriptor in binding #" << binding << " at global descriptor index " << i << " is being used in draw but has not been updated."; *error = error_str.str(); return false; } else { auto descriptor_class = descriptors_[i]->GetClass(); if (descriptor_class == GeneralBuffer) { // Verify that buffers are valid auto buffer = static_cast<BufferDescriptor *>(descriptors_[i].get())->GetBuffer(); auto buffer_node = GetBufferState(device_data_, buffer); if (!buffer_node) { std::stringstream error_str; error_str << "Descriptor in binding #" << binding << " at global descriptor index " << i << " references invalid buffer " << buffer << "."; *error = error_str.str(); return false; } else if (!buffer_node->sparse) { for (auto mem_binding : buffer_node->GetBoundMemory()) { if (!GetMemObjInfo(device_data_, mem_binding)) { std::stringstream error_str; error_str << "Descriptor in binding #" << binding << " at global descriptor index " << i << " uses buffer " << buffer << " that references invalid memory " << mem_binding << "."; *error = error_str.str(); return false; } } } if (descriptors_[i]->IsDynamic()) { // Validate that dynamic offsets are within the buffer auto buffer_size = buffer_node->createInfo.size; auto range = static_cast<BufferDescriptor *>(descriptors_[i].get())->GetRange(); auto desc_offset = static_cast<BufferDescriptor *>(descriptors_[i].get())->GetOffset(); auto dyn_offset = dynamic_offsets[GetDynamicOffsetIndexFromBinding(binding) + array_idx]; if (VK_WHOLE_SIZE == range) { if ((dyn_offset + desc_offset) > buffer_size) { std::stringstream error_str; error_str << "Dynamic descriptor in binding #" << binding << " at global descriptor index " << i << " uses buffer " << buffer << " with update range of VK_WHOLE_SIZE has dynamic offset " << dyn_offset << " combined with offset " << desc_offset << " that oversteps the buffer size of " << buffer_size << "."; *error = error_str.str(); return false; } } else { if ((dyn_offset + desc_offset + range) > buffer_size) { std::stringstream error_str; error_str << "Dynamic descriptor in binding #" << binding << " at global descriptor index " << i << " uses buffer " << buffer << " with dynamic offset " << dyn_offset << " combined with offset " << desc_offset << " and range " << range << " that oversteps the buffer size of " << buffer_size << "."; *error = error_str.str(); return false; } } } } else if (descriptor_class == ImageSampler || descriptor_class == Image) { VkImageView image_view; VkImageLayout image_layout; if (descriptor_class == ImageSampler) { image_view = static_cast<ImageSamplerDescriptor *>(descriptors_[i].get())->GetImageView(); image_layout = static_cast<ImageSamplerDescriptor *>(descriptors_[i].get())->GetImageLayout(); } else { image_view = static_cast<ImageDescriptor *>(descriptors_[i].get())->GetImageView(); image_layout = static_cast<ImageDescriptor *>(descriptors_[i].get())->GetImageLayout(); } auto reqs = binding_pair.second; auto image_view_state = GetImageViewState(device_data_, image_view); if (nullptr == image_view_state) { // Image view must have been destroyed since initial update. Could potentially flag the descriptor // as "invalid" (updated = false) at DestroyImageView() time and detect this error at bind time std::stringstream error_str; error_str << "Descriptor in binding #" << binding << " at global descriptor index " << i << " is using imageView " << image_view << " that has been destroyed."; *error = error_str.str(); return false; } auto image_view_ci = image_view_state->create_info; if ((reqs & DESCRIPTOR_REQ_ALL_VIEW_TYPE_BITS) && (~reqs & (1 << image_view_ci.viewType))) { // bad view type std::stringstream error_str; error_str << "Descriptor in binding #" << binding << " at global descriptor index " << i << " requires an image view of type " << string_descriptor_req_view_type(reqs) << " but got " << string_VkImageViewType(image_view_ci.viewType) << "."; *error = error_str.str(); return false; } auto image_node = GetImageState(device_data_, image_view_ci.image); assert(image_node); // Verify Image Layout // Copy first mip level into sub_layers and loop over each mip level to verify layout VkImageSubresourceLayers sub_layers; sub_layers.aspectMask = image_view_ci.subresourceRange.aspectMask; sub_layers.baseArrayLayer = image_view_ci.subresourceRange.baseArrayLayer; sub_layers.layerCount = image_view_ci.subresourceRange.layerCount; bool hit_error = false; for (auto cur_level = image_view_ci.subresourceRange.baseMipLevel; cur_level < image_view_ci.subresourceRange.levelCount; ++cur_level) { sub_layers.mipLevel = cur_level; VerifyImageLayout(device_data_, cb_node, image_node, sub_layers, image_layout, VK_IMAGE_LAYOUT_UNDEFINED, caller, "VUID-VkDescriptorImageInfo-imageLayout-00344", &hit_error); if (hit_error) { *error = "Image layout specified at vkUpdateDescriptorSets() time doesn't match actual image layout at time " "descriptor is used. See previous error callback for specific details."; return false; } } // Verify Sample counts if ((reqs & DESCRIPTOR_REQ_SINGLE_SAMPLE) && image_node->createInfo.samples != VK_SAMPLE_COUNT_1_BIT) { std::stringstream error_str; error_str << "Descriptor in binding #" << binding << " at global descriptor index " << i << " requires bound image to have VK_SAMPLE_COUNT_1_BIT but got " << string_VkSampleCountFlagBits(image_node->createInfo.samples) << "."; *error = error_str.str(); return false; } if ((reqs & DESCRIPTOR_REQ_MULTI_SAMPLE) && image_node->createInfo.samples == VK_SAMPLE_COUNT_1_BIT) { std::stringstream error_str; error_str << "Descriptor in binding #" << binding << " at global descriptor index " << i << " requires bound image to have multiple samples, but got VK_SAMPLE_COUNT_1_BIT."; *error = error_str.str(); return false; } } if (descriptor_class == ImageSampler || descriptor_class == PlainSampler) { // Verify Sampler still valid VkSampler sampler; if (descriptor_class == ImageSampler) { sampler = static_cast<ImageSamplerDescriptor *>(descriptors_[i].get())->GetSampler(); } else { sampler = static_cast<SamplerDescriptor *>(descriptors_[i].get())->GetSampler(); } if (!ValidateSampler(sampler, device_data_)) { std::stringstream error_str; error_str << "Descriptor in binding #" << binding << " at global descriptor index " << i << " is using sampler " << sampler << " that has been destroyed."; *error = error_str.str(); return false; } } } } } return true; } // For given bindings, place any update buffers or images into the passed-in unordered_sets uint32_t cvdescriptorset::DescriptorSet::GetStorageUpdates(const std::map<uint32_t, descriptor_req> &bindings, std::unordered_set<VkBuffer> *buffer_set, std::unordered_set<VkImageView> *image_set) const { auto num_updates = 0; for (auto binding_pair : bindings) { auto binding = binding_pair.first; // If a binding doesn't exist, skip it if (!p_layout_->HasBinding(binding)) { continue; } uint32_t start_idx = p_layout_->GetGlobalIndexRangeFromBinding(binding).start; if (descriptors_[start_idx]->IsStorage()) { if (Image == descriptors_[start_idx]->descriptor_class) { for (uint32_t i = 0; i < p_layout_->GetDescriptorCountFromBinding(binding); ++i) { if (descriptors_[start_idx + i]->updated) { image_set->insert(static_cast<ImageDescriptor *>(descriptors_[start_idx + i].get())->GetImageView()); num_updates++; } } } else if (TexelBuffer == descriptors_[start_idx]->descriptor_class) { for (uint32_t i = 0; i < p_layout_->GetDescriptorCountFromBinding(binding); ++i) { if (descriptors_[start_idx + i]->updated) { auto bufferview = static_cast<TexelDescriptor *>(descriptors_[start_idx + i].get())->GetBufferView(); auto bv_state = GetBufferViewState(device_data_, bufferview); if (bv_state) { buffer_set->insert(bv_state->create_info.buffer); num_updates++; } } } } else if (GeneralBuffer == descriptors_[start_idx]->descriptor_class) { for (uint32_t i = 0; i < p_layout_->GetDescriptorCountFromBinding(binding); ++i) { if (descriptors_[start_idx + i]->updated) { buffer_set->insert(static_cast<BufferDescriptor *>(descriptors_[start_idx + i].get())->GetBuffer()); num_updates++; } } } } } return num_updates; } // Set is being deleted or updates so invalidate all bound cmd buffers void cvdescriptorset::DescriptorSet::InvalidateBoundCmdBuffers() { core_validation::invalidateCommandBuffers(device_data_, cb_bindings, {HandleToUint64(set_), kVulkanObjectTypeDescriptorSet}); } // Perform write update in given update struct void cvdescriptorset::DescriptorSet::PerformWriteUpdate(const VkWriteDescriptorSet *update) { // Perform update on a per-binding basis as consecutive updates roll over to next binding auto descriptors_remaining = update->descriptorCount; auto binding_being_updated = update->dstBinding; auto offset = update->dstArrayElement; uint32_t update_index = 0; while (descriptors_remaining) { uint32_t update_count = std::min(descriptors_remaining, GetDescriptorCountFromBinding(binding_being_updated)); auto global_idx = p_layout_->GetGlobalIndexRangeFromBinding(binding_being_updated).start + offset; // Loop over the updates for a single binding at a time for (uint32_t di = 0; di < update_count; ++di, ++update_index) { descriptors_[global_idx + di]->WriteUpdate(update, update_index); } // Roll over to next binding in case of consecutive update descriptors_remaining -= update_count; offset = 0; binding_being_updated++; } if (update->descriptorCount) some_update_ = true; if (!(p_layout_->GetDescriptorBindingFlagsFromBinding(update->dstBinding) & (VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT_EXT | VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT_EXT))) { InvalidateBoundCmdBuffers(); } } // Validate Copy update bool cvdescriptorset::DescriptorSet::ValidateCopyUpdate(const debug_report_data *report_data, const VkCopyDescriptorSet *update, const DescriptorSet *src_set, std::string *error_code, std::string *error_msg) { // Verify dst layout still valid if (p_layout_->IsDestroyed()) { *error_code = "VUID-VkCopyDescriptorSet-dstSet-parameter"; string_sprintf(error_msg, "Cannot call vkUpdateDescriptorSets() to perform copy update on descriptor set dstSet 0x%" PRIxLEAST64 " created with destroyed VkDescriptorSetLayout 0x%" PRIxLEAST64, HandleToUint64(set_), HandleToUint64(p_layout_->GetDescriptorSetLayout())); return false; } // Verify src layout still valid if (src_set->p_layout_->IsDestroyed()) { *error_code = "VUID-VkCopyDescriptorSet-srcSet-parameter"; string_sprintf( error_msg, "Cannot call vkUpdateDescriptorSets() to perform copy update of dstSet 0x%" PRIxLEAST64 " from descriptor set srcSet 0x%" PRIxLEAST64 " created with destroyed VkDescriptorSetLayout 0x%" PRIxLEAST64, HandleToUint64(set_), HandleToUint64(src_set->set_), HandleToUint64(src_set->p_layout_->GetDescriptorSetLayout())); return false; } if (!p_layout_->HasBinding(update->dstBinding)) { *error_code = "VUID-VkCopyDescriptorSet-dstBinding-00347"; std::stringstream error_str; error_str << "DescriptorSet " << set_ << " does not have copy update dest binding of " << update->dstBinding; *error_msg = error_str.str(); return false; } if (!src_set->HasBinding(update->srcBinding)) { *error_code = "VUID-VkCopyDescriptorSet-srcBinding-00345"; std::stringstream error_str; error_str << "DescriptorSet " << set_ << " does not have copy update src binding of " << update->srcBinding; *error_msg = error_str.str(); return false; } // Verify idle ds if (in_use.load() && !(p_layout_->GetDescriptorBindingFlagsFromBinding(update->dstBinding) & (VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT_EXT | VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT_EXT))) { // TODO : Re-using Free Idle error code, need copy update idle error code *error_code = "VUID-vkFreeDescriptorSets-pDescriptorSets-00309"; std::stringstream error_str; error_str << "Cannot call vkUpdateDescriptorSets() to perform copy update on descriptor set " << set_ << " that is in use by a command buffer"; *error_msg = error_str.str(); return false; } // src & dst set bindings are valid // Check bounds of src & dst auto src_start_idx = src_set->GetGlobalIndexRangeFromBinding(update->srcBinding).start + update->srcArrayElement; if ((src_start_idx + update->descriptorCount) > src_set->GetTotalDescriptorCount()) { // SRC update out of bounds *error_code = "VUID-VkCopyDescriptorSet-srcArrayElement-00346"; std::stringstream error_str; error_str << "Attempting copy update from descriptorSet " << update->srcSet << " binding#" << update->srcBinding << " with offset index of " << src_set->GetGlobalIndexRangeFromBinding(update->srcBinding).start << " plus update array offset of " << update->srcArrayElement << " and update of " << update->descriptorCount << " descriptors oversteps total number of descriptors in set: " << src_set->GetTotalDescriptorCount(); *error_msg = error_str.str(); return false; } auto dst_start_idx = p_layout_->GetGlobalIndexRangeFromBinding(update->dstBinding).start + update->dstArrayElement; if ((dst_start_idx + update->descriptorCount) > p_layout_->GetTotalDescriptorCount()) { // DST update out of bounds *error_code = "VUID-VkCopyDescriptorSet-dstArrayElement-00348"; std::stringstream error_str; error_str << "Attempting copy update to descriptorSet " << set_ << " binding#" << update->dstBinding << " with offset index of " << p_layout_->GetGlobalIndexRangeFromBinding(update->dstBinding).start << " plus update array offset of " << update->dstArrayElement << " and update of " << update->descriptorCount << " descriptors oversteps total number of descriptors in set: " << p_layout_->GetTotalDescriptorCount(); *error_msg = error_str.str(); return false; } // Check that types match // TODO : Base default error case going from here is "VUID-VkAcquireNextImageInfoKHR-semaphore-parameter"2ba which covers all // consistency issues, need more fine-grained error codes *error_code = "VUID-VkCopyDescriptorSet-srcSet-00349"; auto src_type = src_set->GetTypeFromBinding(update->srcBinding); auto dst_type = p_layout_->GetTypeFromBinding(update->dstBinding); if (src_type != dst_type) { std::stringstream error_str; error_str << "Attempting copy update to descriptorSet " << set_ << " binding #" << update->dstBinding << " with type " << string_VkDescriptorType(dst_type) << " from descriptorSet " << src_set->GetSet() << " binding #" << update->srcBinding << " with type " << string_VkDescriptorType(src_type) << ". Types do not match"; *error_msg = error_str.str(); return false; } // Verify consistency of src & dst bindings if update crosses binding boundaries if ((!src_set->GetLayout()->VerifyUpdateConsistency(update->srcBinding, update->srcArrayElement, update->descriptorCount, "copy update from", src_set->GetSet(), error_msg)) || (!p_layout_->VerifyUpdateConsistency(update->dstBinding, update->dstArrayElement, update->descriptorCount, "copy update to", set_, error_msg))) { return false; } if ((src_set->GetLayout()->GetCreateFlags() & VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT_EXT) && !(GetLayout()->GetCreateFlags() & VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT_EXT)) { *error_code = "VUID-VkCopyDescriptorSet-srcSet-01918"; std::stringstream error_str; error_str << "If pname:srcSet's (" << update->srcSet << ") layout was created with the " "ename:VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT_EXT flag " "set, then pname:dstSet's (" << update->dstSet << ") layout must: also have been created with the " "ename:VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT_EXT flag set"; *error_msg = error_str.str(); return false; } if (!(src_set->GetLayout()->GetCreateFlags() & VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT_EXT) && (GetLayout()->GetCreateFlags() & VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT_EXT)) { *error_code = "VUID-VkCopyDescriptorSet-srcSet-01919"; std::stringstream error_str; error_str << "If pname:srcSet's (" << update->srcSet << ") layout was created without the " "ename:VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT_EXT flag " "set, then pname:dstSet's (" << update->dstSet << ") layout must: also have been created without the " "ename:VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT_EXT flag set"; *error_msg = error_str.str(); return false; } if ((src_set->GetPoolState()->createInfo.flags & VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT_EXT) && !(GetPoolState()->createInfo.flags & VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT_EXT)) { *error_code = "VUID-VkCopyDescriptorSet-srcSet-01920"; std::stringstream error_str; error_str << "If the descriptor pool from which pname:srcSet (" << update->srcSet << ") was allocated was created " "with the ename:VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT_EXT flag " "set, then the descriptor pool from which pname:dstSet (" << update->dstSet << ") was allocated must: " "also have been created with the ename:VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT_EXT flag set"; *error_msg = error_str.str(); return false; } if (!(src_set->GetPoolState()->createInfo.flags & VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT_EXT) && (GetPoolState()->createInfo.flags & VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT_EXT)) { *error_code = "VUID-VkCopyDescriptorSet-srcSet-01921"; std::stringstream error_str; error_str << "If the descriptor pool from which pname:srcSet (" << update->srcSet << ") was allocated was created " "without the ename:VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT_EXT flag " "set, then the descriptor pool from which pname:dstSet (" << update->dstSet << ") was allocated must: " "also have been created without the ename:VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT_EXT flag set"; *error_msg = error_str.str(); return false; } // Update parameters all look good and descriptor updated so verify update contents if (!VerifyCopyUpdateContents(update, src_set, src_type, src_start_idx, error_code, error_msg)) return false; // All checks passed so update is good return true; } // Perform Copy update void cvdescriptorset::DescriptorSet::PerformCopyUpdate(const VkCopyDescriptorSet *update, const DescriptorSet *src_set) { auto src_start_idx = src_set->GetGlobalIndexRangeFromBinding(update->srcBinding).start + update->srcArrayElement; auto dst_start_idx = p_layout_->GetGlobalIndexRangeFromBinding(update->dstBinding).start + update->dstArrayElement; // Update parameters all look good so perform update for (uint32_t di = 0; di < update->descriptorCount; ++di) { auto src = src_set->descriptors_[src_start_idx + di].get(); auto dst = descriptors_[dst_start_idx + di].get(); if (src->updated) { dst->CopyUpdate(src); some_update_ = true; } else { dst->updated = false; } } if (!(p_layout_->GetDescriptorBindingFlagsFromBinding(update->dstBinding) & (VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT_EXT | VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT_EXT))) { InvalidateBoundCmdBuffers(); } } // Bind cb_node to this set and this set to cb_node. // Prereq: This should be called for a set that has been confirmed to be active for the given cb_node, meaning it's going // to be used in a draw by the given cb_node void cvdescriptorset::DescriptorSet::BindCommandBuffer(GLOBAL_CB_NODE *cb_node, const std::map<uint32_t, descriptor_req> &binding_req_map) { // bind cb to this descriptor set cb_bindings.insert(cb_node); // Add bindings for descriptor set, the set's pool, and individual objects in the set cb_node->object_bindings.insert({HandleToUint64(set_), kVulkanObjectTypeDescriptorSet}); pool_state_->cb_bindings.insert(cb_node); cb_node->object_bindings.insert({HandleToUint64(pool_state_->pool), kVulkanObjectTypeDescriptorPool}); // For the active slots, use set# to look up descriptorSet from boundDescriptorSets, and bind all of that descriptor set's // resources for (auto binding_req_pair : binding_req_map) { auto binding = binding_req_pair.first; auto range = p_layout_->GetGlobalIndexRangeFromBinding(binding); for (uint32_t i = range.start; i < range.end; ++i) { descriptors_[i]->BindCommandBuffer(device_data_, cb_node); } } } void cvdescriptorset::DescriptorSet::FilterAndTrackOneBindingReq(const BindingReqMap::value_type &binding_req_pair, const BindingReqMap &in_req, BindingReqMap *out_req, TrackedBindings *bindings) { assert(out_req); assert(bindings); const auto binding = binding_req_pair.first; // Use insert and look at the boolean ("was inserted") in the returned pair to see if this is a new set member. // Saves one hash lookup vs. find ... compare w/ end ... insert. const auto it_bool_pair = bindings->insert(binding); if (it_bool_pair.second) { out_req->emplace(binding_req_pair); } } void cvdescriptorset::DescriptorSet::FilterAndTrackOneBindingReq(const BindingReqMap::value_type &binding_req_pair, const BindingReqMap &in_req, BindingReqMap *out_req, TrackedBindings *bindings, uint32_t limit) { if (bindings->size() < limit) FilterAndTrackOneBindingReq(binding_req_pair, in_req, out_req, bindings); } void cvdescriptorset::DescriptorSet::FilterAndTrackBindingReqs(GLOBAL_CB_NODE *cb_state, const BindingReqMap &in_req, BindingReqMap *out_req) { TrackedBindings &bound = cached_validation_[cb_state].command_binding_and_usage; if (bound.size() == GetBindingCount()) { return; // All bindings are bound, out req is empty } for (const auto &binding_req_pair : in_req) { const auto binding = binding_req_pair.first; // If a binding doesn't exist, or has already been bound, skip it if (p_layout_->HasBinding(binding)) { FilterAndTrackOneBindingReq(binding_req_pair, in_req, out_req, &bound); } } } void cvdescriptorset::DescriptorSet::FilterAndTrackBindingReqs(GLOBAL_CB_NODE *cb_state, PIPELINE_STATE *pipeline, const BindingReqMap &in_req, BindingReqMap *out_req) { auto &validated = cached_validation_[cb_state]; auto &image_sample_val = validated.image_samplers[pipeline]; auto *const dynamic_buffers = &validated.dynamic_buffers; auto *const non_dynamic_buffers = &validated.non_dynamic_buffers; const auto &stats = p_layout_->GetBindingTypeStats(); for (const auto &binding_req_pair : in_req) { auto binding = binding_req_pair.first; VkDescriptorSetLayoutBinding const *layout_binding = p_layout_->GetDescriptorSetLayoutBindingPtrFromBinding(binding); if (!layout_binding) { continue; } // Caching criteria differs per type. // If image_layout have changed , the image descriptors need to be validated against them. if ((layout_binding->descriptorType == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC) || (layout_binding->descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC)) { FilterAndTrackOneBindingReq(binding_req_pair, in_req, out_req, dynamic_buffers, stats.dynamic_buffer_count); } else if ((layout_binding->descriptorType == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER) || (layout_binding->descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER)) { FilterAndTrackOneBindingReq(binding_req_pair, in_req, out_req, non_dynamic_buffers, stats.non_dynamic_buffer_count); } else { // This is rather crude, as the changed layouts may not impact the bound descriptors, // but the simple "versioning" is a simple "dirt" test. auto &version = image_sample_val[binding]; // Take advantage of default construtor zero initialzing new entries if (version != cb_state->image_layout_change_count) { version = cb_state->image_layout_change_count; out_req->emplace(binding_req_pair); } } } } cvdescriptorset::SamplerDescriptor::SamplerDescriptor(const VkSampler *immut) : sampler_(VK_NULL_HANDLE), immutable_(false) { updated = false; descriptor_class = PlainSampler; if (immut) { sampler_ = *immut; immutable_ = true; updated = true; } } // Validate given sampler. Currently this only checks to make sure it exists in the samplerMap bool cvdescriptorset::ValidateSampler(const VkSampler sampler, const layer_data *dev_data) { return (GetSamplerState(dev_data, sampler) != nullptr); } bool cvdescriptorset::ValidateImageUpdate(VkImageView image_view, VkImageLayout image_layout, VkDescriptorType type, const layer_data *dev_data, std::string *error_code, std::string *error_msg) { // TODO : Defaulting to 00943 for all cases here. Need to create new error codes for various cases. *error_code = "VUID-VkWriteDescriptorSet-descriptorType-00326"; auto iv_state = GetImageViewState(dev_data, image_view); if (!iv_state) { std::stringstream error_str; error_str << "Invalid VkImageView: " << image_view; *error_msg = error_str.str(); return false; } // Note that when an imageview is created, we validated that memory is bound so no need to re-check here // Validate that imageLayout is compatible with aspect_mask and image format // and validate that image usage bits are correct for given usage VkImageAspectFlags aspect_mask = iv_state->create_info.subresourceRange.aspectMask; VkImage image = iv_state->create_info.image; VkFormat format = VK_FORMAT_MAX_ENUM; VkImageUsageFlags usage = 0; auto image_node = GetImageState(dev_data, image); if (image_node) { format = image_node->createInfo.format; usage = image_node->createInfo.usage; // Validate that memory is bound to image // TODO: This should have its own valid usage id apart from 2524 which is from CreateImageView case. The only // the error here occurs is if memory bound to a created imageView has been freed. if (ValidateMemoryIsBoundToImage(dev_data, image_node, "vkUpdateDescriptorSets()", "VUID-VkImageViewCreateInfo-image-01020")) { *error_code = "VUID-VkImageViewCreateInfo-image-01020"; *error_msg = "No memory bound to image."; return false; } // KHR_maintenance1 allows rendering into 2D or 2DArray views which slice a 3D image, // but not binding them to descriptor sets. if (image_node->createInfo.imageType == VK_IMAGE_TYPE_3D && (iv_state->create_info.viewType == VK_IMAGE_VIEW_TYPE_2D || iv_state->create_info.viewType == VK_IMAGE_VIEW_TYPE_2D_ARRAY)) { *error_code = "VUID-VkDescriptorImageInfo-imageView-00343"; *error_msg = "ImageView must not be a 2D or 2DArray view of a 3D image"; return false; } } // First validate that format and layout are compatible if (format == VK_FORMAT_MAX_ENUM) { std::stringstream error_str; error_str << "Invalid image (" << image << ") in imageView (" << image_view << ")."; *error_msg = error_str.str(); return false; } // TODO : The various image aspect and format checks here are based on general spec language in 11.5 Image Views section under // vkCreateImageView(). What's the best way to create unique id for these cases? bool ds = FormatIsDepthOrStencil(format); switch (image_layout) { case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL: // Only Color bit must be set if ((aspect_mask & VK_IMAGE_ASPECT_COLOR_BIT) != VK_IMAGE_ASPECT_COLOR_BIT) { std::stringstream error_str; error_str << "ImageView (" << image_view << ") uses layout VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL but does not have VK_IMAGE_ASPECT_COLOR_BIT set."; *error_msg = error_str.str(); return false; } // format must NOT be DS if (ds) { std::stringstream error_str; error_str << "ImageView (" << image_view << ") uses layout VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL but the image format is " << string_VkFormat(format) << " which is not a color format."; *error_msg = error_str.str(); return false; } break; case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL: case VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL: // Depth or stencil bit must be set, but both must NOT be set if (aspect_mask & VK_IMAGE_ASPECT_DEPTH_BIT) { if (aspect_mask & VK_IMAGE_ASPECT_STENCIL_BIT) { // both must NOT be set std::stringstream error_str; error_str << "ImageView (" << image_view << ") has both STENCIL and DEPTH aspects set"; *error_msg = error_str.str(); return false; } } else if (!(aspect_mask & VK_IMAGE_ASPECT_STENCIL_BIT)) { // Neither were set std::stringstream error_str; error_str << "ImageView (" << image_view << ") has layout " << string_VkImageLayout(image_layout) << " but does not have STENCIL or DEPTH aspects set"; *error_msg = error_str.str(); return false; } // format must be DS if (!ds) { std::stringstream error_str; error_str << "ImageView (" << image_view << ") has layout " << string_VkImageLayout(image_layout) << " but the image format is " << string_VkFormat(format) << " which is not a depth/stencil format."; *error_msg = error_str.str(); return false; } break; default: // For other layouts if the source is depth/stencil image, both aspect bits must not be set if (ds) { if (aspect_mask & VK_IMAGE_ASPECT_DEPTH_BIT) { if (aspect_mask & VK_IMAGE_ASPECT_STENCIL_BIT) { // both must NOT be set std::stringstream error_str; error_str << "ImageView (" << image_view << ") has layout " << string_VkImageLayout(image_layout) << " and is using depth/stencil image of format " << string_VkFormat(format) << " but it has both STENCIL and DEPTH aspects set, which is illegal. When using a depth/stencil " "image in a descriptor set, please only set either VK_IMAGE_ASPECT_DEPTH_BIT or " "VK_IMAGE_ASPECT_STENCIL_BIT depending on whether it will be used for depth reads or stencil " "reads respectively."; *error_msg = error_str.str(); return false; } } } break; } // Now validate that usage flags are correctly set for given type of update // As we're switching per-type, if any type has specific layout requirements, check those here as well // TODO : The various image usage bit requirements are in general spec language for VkImageUsageFlags bit block in 11.3 Images // under vkCreateImage() // TODO : Need to also validate case "VUID-VkWriteDescriptorSet-descriptorType-00336" where STORAGE_IMAGE & INPUT_ATTACH types // must have been created with identify swizzle std::string error_usage_bit; switch (type) { case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE: case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER: { if (!(usage & VK_IMAGE_USAGE_SAMPLED_BIT)) { error_usage_bit = "VK_IMAGE_USAGE_SAMPLED_BIT"; } break; } case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE: { if (!(usage & VK_IMAGE_USAGE_STORAGE_BIT)) { error_usage_bit = "VK_IMAGE_USAGE_STORAGE_BIT"; } else if (VK_IMAGE_LAYOUT_GENERAL != image_layout) { std::stringstream error_str; // TODO : Need to create custom enum error codes for these cases if (image_node->shared_presentable) { if (VK_IMAGE_LAYOUT_SHARED_PRESENT_KHR != image_layout) { error_str << "ImageView (" << image_view << ") of VK_DESCRIPTOR_TYPE_STORAGE_IMAGE type with a front-buffered image is being updated with " "layout " << string_VkImageLayout(image_layout) << " but according to spec section 13.1 Descriptor Types, 'Front-buffered images that report " "support for VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT must be in the " "VK_IMAGE_LAYOUT_SHARED_PRESENT_KHR layout.'"; *error_msg = error_str.str(); return false; } } else if (VK_IMAGE_LAYOUT_GENERAL != image_layout) { error_str << "ImageView (" << image_view << ") of VK_DESCRIPTOR_TYPE_STORAGE_IMAGE type is being updated with layout " << string_VkImageLayout(image_layout) << " but according to spec section 13.1 Descriptor Types, 'Load and store operations on storage " "images can only be done on images in VK_IMAGE_LAYOUT_GENERAL layout.'"; *error_msg = error_str.str(); return false; } } break; } case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT: { if (!(usage & VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT)) { error_usage_bit = "VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT"; } break; } default: break; } if (!error_usage_bit.empty()) { std::stringstream error_str; error_str << "ImageView (" << image_view << ") with usage mask 0x" << usage << " being used for a descriptor update of type " << string_VkDescriptorType(type) << " does not have " << error_usage_bit << " set."; *error_msg = error_str.str(); return false; } return true; } void cvdescriptorset::SamplerDescriptor::WriteUpdate(const VkWriteDescriptorSet *update, const uint32_t index) { if (!immutable_) { sampler_ = update->pImageInfo[index].sampler; } updated = true; } void cvdescriptorset::SamplerDescriptor::CopyUpdate(const Descriptor *src) { if (!immutable_) { auto update_sampler = static_cast<const SamplerDescriptor *>(src)->sampler_; sampler_ = update_sampler; } updated = true; } void cvdescriptorset::SamplerDescriptor::BindCommandBuffer(const layer_data *dev_data, GLOBAL_CB_NODE *cb_node) { if (!immutable_) { auto sampler_state = GetSamplerState(dev_data, sampler_); if (sampler_state) core_validation::AddCommandBufferBindingSampler(cb_node, sampler_state); } } cvdescriptorset::ImageSamplerDescriptor::ImageSamplerDescriptor(const VkSampler *immut) : sampler_(VK_NULL_HANDLE), immutable_(false), image_view_(VK_NULL_HANDLE), image_layout_(VK_IMAGE_LAYOUT_UNDEFINED) { updated = false; descriptor_class = ImageSampler; if (immut) { sampler_ = *immut; immutable_ = true; } } void cvdescriptorset::ImageSamplerDescriptor::WriteUpdate(const VkWriteDescriptorSet *update, const uint32_t index) { updated = true; const auto &image_info = update->pImageInfo[index]; if (!immutable_) { sampler_ = image_info.sampler; } image_view_ = image_info.imageView; image_layout_ = image_info.imageLayout; } void cvdescriptorset::ImageSamplerDescriptor::CopyUpdate(const Descriptor *src) { if (!immutable_) { auto update_sampler = static_cast<const ImageSamplerDescriptor *>(src)->sampler_; sampler_ = update_sampler; } auto image_view = static_cast<const ImageSamplerDescriptor *>(src)->image_view_; auto image_layout = static_cast<const ImageSamplerDescriptor *>(src)->image_layout_; updated = true; image_view_ = image_view; image_layout_ = image_layout; } void cvdescriptorset::ImageSamplerDescriptor::BindCommandBuffer(const layer_data *dev_data, GLOBAL_CB_NODE *cb_node) { // First add binding for any non-immutable sampler if (!immutable_) { auto sampler_state = GetSamplerState(dev_data, sampler_); if (sampler_state) core_validation::AddCommandBufferBindingSampler(cb_node, sampler_state); } // Add binding for image auto iv_state = GetImageViewState(dev_data, image_view_); if (iv_state) { core_validation::AddCommandBufferBindingImageView(dev_data, cb_node, iv_state); } } cvdescriptorset::ImageDescriptor::ImageDescriptor(const VkDescriptorType type) : storage_(false), image_view_(VK_NULL_HANDLE), image_layout_(VK_IMAGE_LAYOUT_UNDEFINED) { updated = false; descriptor_class = Image; if (VK_DESCRIPTOR_TYPE_STORAGE_IMAGE == type) storage_ = true; } void cvdescriptorset::ImageDescriptor::WriteUpdate(const VkWriteDescriptorSet *update, const uint32_t index) { updated = true; const auto &image_info = update->pImageInfo[index]; image_view_ = image_info.imageView; image_layout_ = image_info.imageLayout; } void cvdescriptorset::ImageDescriptor::CopyUpdate(const Descriptor *src) { auto image_view = static_cast<const ImageDescriptor *>(src)->image_view_; auto image_layout = static_cast<const ImageDescriptor *>(src)->image_layout_; updated = true; image_view_ = image_view; image_layout_ = image_layout; } void cvdescriptorset::ImageDescriptor::BindCommandBuffer(const layer_data *dev_data, GLOBAL_CB_NODE *cb_node) { // Add binding for image auto iv_state = GetImageViewState(dev_data, image_view_); if (iv_state) { core_validation::AddCommandBufferBindingImageView(dev_data, cb_node, iv_state); } } cvdescriptorset::BufferDescriptor::BufferDescriptor(const VkDescriptorType type) : storage_(false), dynamic_(false), buffer_(VK_NULL_HANDLE), offset_(0), range_(0) { updated = false; descriptor_class = GeneralBuffer; if (VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC == type) { dynamic_ = true; } else if (VK_DESCRIPTOR_TYPE_STORAGE_BUFFER == type) { storage_ = true; } else if (VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC == type) { dynamic_ = true; storage_ = true; } } void cvdescriptorset::BufferDescriptor::WriteUpdate(const VkWriteDescriptorSet *update, const uint32_t index) { updated = true; const auto &buffer_info = update->pBufferInfo[index]; buffer_ = buffer_info.buffer; offset_ = buffer_info.offset; range_ = buffer_info.range; } void cvdescriptorset::BufferDescriptor::CopyUpdate(const Descriptor *src) { auto buff_desc = static_cast<const BufferDescriptor *>(src); updated = true; buffer_ = buff_desc->buffer_; offset_ = buff_desc->offset_; range_ = buff_desc->range_; } void cvdescriptorset::BufferDescriptor::BindCommandBuffer(const layer_data *dev_data, GLOBAL_CB_NODE *cb_node) { auto buffer_node = GetBufferState(dev_data, buffer_); if (buffer_node) core_validation::AddCommandBufferBindingBuffer(dev_data, cb_node, buffer_node); } cvdescriptorset::TexelDescriptor::TexelDescriptor(const VkDescriptorType type) : buffer_view_(VK_NULL_HANDLE), storage_(false) { updated = false; descriptor_class = TexelBuffer; if (VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER == type) storage_ = true; } void cvdescriptorset::TexelDescriptor::WriteUpdate(const VkWriteDescriptorSet *update, const uint32_t index) { updated = true; buffer_view_ = update->pTexelBufferView[index]; } void cvdescriptorset::TexelDescriptor::CopyUpdate(const Descriptor *src) { updated = true; buffer_view_ = static_cast<const TexelDescriptor *>(src)->buffer_view_; } void cvdescriptorset::TexelDescriptor::BindCommandBuffer(const layer_data *dev_data, GLOBAL_CB_NODE *cb_node) { auto bv_state = GetBufferViewState(dev_data, buffer_view_); if (bv_state) { core_validation::AddCommandBufferBindingBufferView(dev_data, cb_node, bv_state); } } // This is a helper function that iterates over a set of Write and Copy updates, pulls the DescriptorSet* for updated // sets, and then calls their respective Validate[Write|Copy]Update functions. // If the update hits an issue for which the callback returns "true", meaning that the call down the chain should // be skipped, then true is returned. // If there is no issue with the update, then false is returned. bool cvdescriptorset::ValidateUpdateDescriptorSets(const debug_report_data *report_data, const layer_data *dev_data, uint32_t write_count, const VkWriteDescriptorSet *p_wds, uint32_t copy_count, const VkCopyDescriptorSet *p_cds) { bool skip = false; // Validate Write updates for (uint32_t i = 0; i < write_count; i++) { auto dest_set = p_wds[i].dstSet; auto set_node = core_validation::GetSetNode(dev_data, dest_set); if (!set_node) { skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT, HandleToUint64(dest_set), DRAWSTATE_INVALID_DESCRIPTOR_SET, "Cannot call vkUpdateDescriptorSets() on descriptor set 0x%" PRIxLEAST64 " that has not been allocated.", HandleToUint64(dest_set)); } else { std::string error_code; std::string error_str; if (!set_node->ValidateWriteUpdate(report_data, &p_wds[i], &error_code, &error_str)) { skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT, HandleToUint64(dest_set), error_code, "vkUpdateDescriptorSets() failed write update validation for Descriptor Set 0x%" PRIx64 " with error: %s.", HandleToUint64(dest_set), error_str.c_str()); } } } // Now validate copy updates for (uint32_t i = 0; i < copy_count; ++i) { auto dst_set = p_cds[i].dstSet; auto src_set = p_cds[i].srcSet; auto src_node = core_validation::GetSetNode(dev_data, src_set); auto dst_node = core_validation::GetSetNode(dev_data, dst_set); // Object_tracker verifies that src & dest descriptor set are valid assert(src_node); assert(dst_node); std::string error_code; std::string error_str; if (!dst_node->ValidateCopyUpdate(report_data, &p_cds[i], src_node, &error_code, &error_str)) { skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT, HandleToUint64(dst_set), error_code, "vkUpdateDescriptorSets() failed copy update from Descriptor Set 0x%" PRIx64 " to Descriptor Set 0x%" PRIx64 " with error: %s.", HandleToUint64(src_set), HandleToUint64(dst_set), error_str.c_str()); } } return skip; } // This is a helper function that iterates over a set of Write and Copy updates, pulls the DescriptorSet* for updated // sets, and then calls their respective Perform[Write|Copy]Update functions. // Prerequisite : ValidateUpdateDescriptorSets() should be called and return "false" prior to calling PerformUpdateDescriptorSets() // with the same set of updates. // This is split from the validate code to allow validation prior to calling down the chain, and then update after // calling down the chain. void cvdescriptorset::PerformUpdateDescriptorSets(const layer_data *dev_data, uint32_t write_count, const VkWriteDescriptorSet *p_wds, uint32_t copy_count, const VkCopyDescriptorSet *p_cds) { // Write updates first uint32_t i = 0; for (i = 0; i < write_count; ++i) { auto dest_set = p_wds[i].dstSet; auto set_node = core_validation::GetSetNode(dev_data, dest_set); if (set_node) { set_node->PerformWriteUpdate(&p_wds[i]); } } // Now copy updates for (i = 0; i < copy_count; ++i) { auto dst_set = p_cds[i].dstSet; auto src_set = p_cds[i].srcSet; auto src_node = core_validation::GetSetNode(dev_data, src_set); auto dst_node = core_validation::GetSetNode(dev_data, dst_set); if (src_node && dst_node) { dst_node->PerformCopyUpdate(&p_cds[i], src_node); } } } // This helper function carries out the state updates for descriptor updates peformed via update templates. It basically collects // data and leverages the PerformUpdateDescriptor helper functions to do this. void cvdescriptorset::PerformUpdateDescriptorSetsWithTemplateKHR(layer_data *device_data, VkDescriptorSet descriptorSet, std::unique_ptr<TEMPLATE_STATE> const &template_state, const void *pData) { auto const &create_info = template_state->create_info; // Create a vector of write structs std::vector<VkWriteDescriptorSet> desc_writes; auto layout_obj = GetDescriptorSetLayout(device_data, create_info.descriptorSetLayout); // Create a WriteDescriptorSet struct for each template update entry for (uint32_t i = 0; i < create_info.descriptorUpdateEntryCount; i++) { auto binding_count = layout_obj->GetDescriptorCountFromBinding(create_info.pDescriptorUpdateEntries[i].dstBinding); auto binding_being_updated = create_info.pDescriptorUpdateEntries[i].dstBinding; auto dst_array_element = create_info.pDescriptorUpdateEntries[i].dstArrayElement; desc_writes.reserve(desc_writes.size() + create_info.pDescriptorUpdateEntries[i].descriptorCount); for (uint32_t j = 0; j < create_info.pDescriptorUpdateEntries[i].descriptorCount; j++) { desc_writes.emplace_back(); auto &write_entry = desc_writes.back(); size_t offset = create_info.pDescriptorUpdateEntries[i].offset + j * create_info.pDescriptorUpdateEntries[i].stride; char *update_entry = (char *)(pData) + offset; if (dst_array_element >= binding_count) { dst_array_element = 0; binding_being_updated = layout_obj->GetNextValidBinding(binding_being_updated); } write_entry.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; write_entry.pNext = NULL; write_entry.dstSet = descriptorSet; write_entry.dstBinding = binding_being_updated; write_entry.dstArrayElement = dst_array_element; write_entry.descriptorCount = 1; write_entry.descriptorType = create_info.pDescriptorUpdateEntries[i].descriptorType; switch (create_info.pDescriptorUpdateEntries[i].descriptorType) { case VK_DESCRIPTOR_TYPE_SAMPLER: case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER: case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE: case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE: case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT: write_entry.pImageInfo = reinterpret_cast<VkDescriptorImageInfo *>(update_entry); break; case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER: case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER: case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC: case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC: write_entry.pBufferInfo = reinterpret_cast<VkDescriptorBufferInfo *>(update_entry); break; case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER: case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER: write_entry.pTexelBufferView = reinterpret_cast<VkBufferView *>(update_entry); break; default: assert(0); break; } dst_array_element++; } } PerformUpdateDescriptorSets(device_data, static_cast<uint32_t>(desc_writes.size()), desc_writes.data(), 0, NULL); } // Validate the state for a given write update but don't actually perform the update // If an error would occur for this update, return false and fill in details in error_msg string bool cvdescriptorset::DescriptorSet::ValidateWriteUpdate(const debug_report_data *report_data, const VkWriteDescriptorSet *update, std::string *error_code, std::string *error_msg) { // Verify dst layout still valid if (p_layout_->IsDestroyed()) { *error_code = "VUID-VkWriteDescriptorSet-dstSet-00320"; string_sprintf(error_msg, "Cannot call vkUpdateDescriptorSets() to perform write update on descriptor set 0x%" PRIxLEAST64 " created with destroyed VkDescriptorSetLayout 0x%" PRIxLEAST64, HandleToUint64(set_), HandleToUint64(p_layout_->GetDescriptorSetLayout())); return false; } // Verify dst binding exists if (!p_layout_->HasBinding(update->dstBinding)) { *error_code = "VUID-VkWriteDescriptorSet-dstBinding-00315"; std::stringstream error_str; error_str << "DescriptorSet " << set_ << " does not have binding " << update->dstBinding; *error_msg = error_str.str(); return false; } else { // Make sure binding isn't empty if (0 == p_layout_->GetDescriptorCountFromBinding(update->dstBinding)) { *error_code = "VUID-VkWriteDescriptorSet-dstBinding-00316"; std::stringstream error_str; error_str << "DescriptorSet " << set_ << " cannot updated binding " << update->dstBinding << " that has 0 descriptors"; *error_msg = error_str.str(); return false; } } // Verify idle ds if (in_use.load() && !(p_layout_->GetDescriptorBindingFlagsFromBinding(update->dstBinding) & (VK_DESCRIPTOR_BINDING_UPDATE_UNUSED_WHILE_PENDING_BIT_EXT | VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT_EXT))) { // TODO : Re-using Free Idle error code, need write update idle error code *error_code = "VUID-vkFreeDescriptorSets-pDescriptorSets-00309"; std::stringstream error_str; error_str << "Cannot call vkUpdateDescriptorSets() to perform write update on descriptor set " << set_ << " that is in use by a command buffer"; *error_msg = error_str.str(); return false; } // We know that binding is valid, verify update and do update on each descriptor auto start_idx = p_layout_->GetGlobalIndexRangeFromBinding(update->dstBinding).start + update->dstArrayElement; auto type = p_layout_->GetTypeFromBinding(update->dstBinding); if (type != update->descriptorType) { *error_code = "VUID-VkWriteDescriptorSet-descriptorType-00319"; std::stringstream error_str; error_str << "Attempting write update to descriptor set " << set_ << " binding #" << update->dstBinding << " with type " << string_VkDescriptorType(type) << " but update type is " << string_VkDescriptorType(update->descriptorType); *error_msg = error_str.str(); return false; } if (update->descriptorCount > (descriptors_.size() - start_idx)) { *error_code = "VUID-VkWriteDescriptorSet-dstArrayElement-00321"; std::stringstream error_str; error_str << "Attempting write update to descriptor set " << set_ << " binding #" << update->dstBinding << " with " << descriptors_.size() - start_idx << " descriptors in that binding and all successive bindings of the set, but update of " << update->descriptorCount << " descriptors combined with update array element offset of " << update->dstArrayElement << " oversteps the available number of consecutive descriptors"; *error_msg = error_str.str(); return false; } // Verify consecutive bindings match (if needed) if (!p_layout_->VerifyUpdateConsistency(update->dstBinding, update->dstArrayElement, update->descriptorCount, "write update to", set_, error_msg)) { // TODO : Should break out "consecutive binding updates" language into valid usage statements *error_code = "VUID-VkWriteDescriptorSet-dstArrayElement-00321"; return false; } // Update is within bounds and consistent so last step is to validate update contents if (!VerifyWriteUpdateContents(update, start_idx, error_code, error_msg)) { std::stringstream error_str; error_str << "Write update to descriptor in set " << set_ << " binding #" << update->dstBinding << " failed with error message: " << error_msg->c_str(); *error_msg = error_str.str(); return false; } // All checks passed, update is clean return true; } // For the given buffer, verify that its creation parameters are appropriate for the given type // If there's an error, update the error_msg string with details and return false, else return true bool cvdescriptorset::DescriptorSet::ValidateBufferUsage(BUFFER_STATE const *buffer_node, VkDescriptorType type, std::string *error_code, std::string *error_msg) const { // Verify that usage bits set correctly for given type auto usage = buffer_node->createInfo.usage; std::string error_usage_bit; switch (type) { case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER: if (!(usage & VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT)) { *error_code = "VUID-VkWriteDescriptorSet-descriptorType-00334"; error_usage_bit = "VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT"; } break; case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER: if (!(usage & VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT)) { *error_code = "VUID-VkWriteDescriptorSet-descriptorType-00335"; error_usage_bit = "VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT"; } break; case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER: case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC: if (!(usage & VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT)) { *error_code = "VUID-VkWriteDescriptorSet-descriptorType-00330"; error_usage_bit = "VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT"; } break; case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER: case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC: if (!(usage & VK_BUFFER_USAGE_STORAGE_BUFFER_BIT)) { *error_code = "VUID-VkWriteDescriptorSet-descriptorType-00331"; error_usage_bit = "VK_BUFFER_USAGE_STORAGE_BUFFER_BIT"; } break; default: break; } if (!error_usage_bit.empty()) { std::stringstream error_str; error_str << "Buffer (" << buffer_node->buffer << ") with usage mask 0x" << usage << " being used for a descriptor update of type " << string_VkDescriptorType(type) << " does not have " << error_usage_bit << " set."; *error_msg = error_str.str(); return false; } return true; } // For buffer descriptor updates, verify the buffer usage and VkDescriptorBufferInfo struct which includes: // 1. buffer is valid // 2. buffer was created with correct usage flags // 3. offset is less than buffer size // 4. range is either VK_WHOLE_SIZE or falls in (0, (buffer size - offset)] // 5. range and offset are within the device's limits // If there's an error, update the error_msg string with details and return false, else return true bool cvdescriptorset::DescriptorSet::ValidateBufferUpdate(VkDescriptorBufferInfo const *buffer_info, VkDescriptorType type, std::string *error_code, std::string *error_msg) const { // First make sure that buffer is valid auto buffer_node = GetBufferState(device_data_, buffer_info->buffer); // Any invalid buffer should already be caught by object_tracker assert(buffer_node); if (ValidateMemoryIsBoundToBuffer(device_data_, buffer_node, "vkUpdateDescriptorSets()", "VUID-VkWriteDescriptorSet-descriptorType-00329")) { *error_code = "VUID-VkWriteDescriptorSet-descriptorType-00329"; *error_msg = "No memory bound to buffer."; return false; } // Verify usage bits if (!ValidateBufferUsage(buffer_node, type, error_code, error_msg)) { // error_msg will have been updated by ValidateBufferUsage() return false; } // offset must be less than buffer size if (buffer_info->offset >= buffer_node->createInfo.size) { *error_code = "VUID-VkDescriptorBufferInfo-offset-00340"; std::stringstream error_str; error_str << "VkDescriptorBufferInfo offset of " << buffer_info->offset << " is greater than or equal to buffer " << buffer_node->buffer << " size of " << buffer_node->createInfo.size; *error_msg = error_str.str(); return false; } if (buffer_info->range != VK_WHOLE_SIZE) { // Range must be VK_WHOLE_SIZE or > 0 if (!buffer_info->range) { *error_code = "VUID-VkDescriptorBufferInfo-range-00341"; std::stringstream error_str; error_str << "VkDescriptorBufferInfo range is not VK_WHOLE_SIZE and is zero, which is not allowed."; *error_msg = error_str.str(); return false; } // Range must be VK_WHOLE_SIZE or <= (buffer size - offset) if (buffer_info->range > (buffer_node->createInfo.size - buffer_info->offset)) { *error_code = "VUID-VkDescriptorBufferInfo-range-00342"; std::stringstream error_str; error_str << "VkDescriptorBufferInfo range is " << buffer_info->range << " which is greater than buffer size (" << buffer_node->createInfo.size << ") minus requested offset of " << buffer_info->offset; *error_msg = error_str.str(); return false; } } // Check buffer update sizes against device limits if (VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER == type || VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC == type) { auto max_ub_range = limits_.maxUniformBufferRange; // TODO : If range is WHOLE_SIZE, need to make sure underlying buffer size doesn't exceed device max if (buffer_info->range != VK_WHOLE_SIZE && buffer_info->range > max_ub_range) { *error_code = "VUID-VkWriteDescriptorSet-descriptorType-00332"; std::stringstream error_str; error_str << "VkDescriptorBufferInfo range is " << buffer_info->range << " which is greater than this device's maxUniformBufferRange (" << max_ub_range << ")"; *error_msg = error_str.str(); return false; } } else if (VK_DESCRIPTOR_TYPE_STORAGE_BUFFER == type || VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC == type) { auto max_sb_range = limits_.maxStorageBufferRange; // TODO : If range is WHOLE_SIZE, need to make sure underlying buffer size doesn't exceed device max if (buffer_info->range != VK_WHOLE_SIZE && buffer_info->range > max_sb_range) { *error_code = "VUID-VkWriteDescriptorSet-descriptorType-00333"; std::stringstream error_str; error_str << "VkDescriptorBufferInfo range is " << buffer_info->range << " which is greater than this device's maxStorageBufferRange (" << max_sb_range << ")"; *error_msg = error_str.str(); return false; } } return true; } // Verify that the contents of the update are ok, but don't perform actual update bool cvdescriptorset::DescriptorSet::VerifyWriteUpdateContents(const VkWriteDescriptorSet *update, const uint32_t index, std::string *error_code, std::string *error_msg) const { switch (update->descriptorType) { case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER: { for (uint32_t di = 0; di < update->descriptorCount; ++di) { // Validate image auto image_view = update->pImageInfo[di].imageView; auto image_layout = update->pImageInfo[di].imageLayout; if (!ValidateImageUpdate(image_view, image_layout, update->descriptorType, device_data_, error_code, error_msg)) { std::stringstream error_str; error_str << "Attempted write update to combined image sampler descriptor failed due to: " << error_msg->c_str(); *error_msg = error_str.str(); return false; } } } // fall through case VK_DESCRIPTOR_TYPE_SAMPLER: { for (uint32_t di = 0; di < update->descriptorCount; ++di) { if (!descriptors_[index + di].get()->IsImmutableSampler()) { if (!ValidateSampler(update->pImageInfo[di].sampler, device_data_)) { *error_code = "VUID-VkWriteDescriptorSet-descriptorType-00325"; std::stringstream error_str; error_str << "Attempted write update to sampler descriptor with invalid sampler: " << update->pImageInfo[di].sampler << "."; *error_msg = error_str.str(); return false; } } else { // TODO : Warn here } } break; } case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE: case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT: case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE: { for (uint32_t di = 0; di < update->descriptorCount; ++di) { auto image_view = update->pImageInfo[di].imageView; auto image_layout = update->pImageInfo[di].imageLayout; if (!ValidateImageUpdate(image_view, image_layout, update->descriptorType, device_data_, error_code, error_msg)) { std::stringstream error_str; error_str << "Attempted write update to image descriptor failed due to: " << error_msg->c_str(); *error_msg = error_str.str(); return false; } } break; } case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER: case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER: { for (uint32_t di = 0; di < update->descriptorCount; ++di) { auto buffer_view = update->pTexelBufferView[di]; auto bv_state = GetBufferViewState(device_data_, buffer_view); if (!bv_state) { *error_code = "VUID-VkWriteDescriptorSet-descriptorType-00323"; std::stringstream error_str; error_str << "Attempted write update to texel buffer descriptor with invalid buffer view: " << buffer_view; *error_msg = error_str.str(); return false; } auto buffer = bv_state->create_info.buffer; auto buffer_state = GetBufferState(device_data_, buffer); // Verify that buffer underlying the view hasn't been destroyed prematurely if (!buffer_state) { *error_code = "VUID-VkWriteDescriptorSet-descriptorType-00323"; std::stringstream error_str; error_str << "Attempted write update to texel buffer descriptor failed because underlying buffer (" << buffer << ") has been destroyed: " << error_msg->c_str(); *error_msg = error_str.str(); return false; } else if (!ValidateBufferUsage(buffer_state, update->descriptorType, error_code, error_msg)) { std::stringstream error_str; error_str << "Attempted write update to texel buffer descriptor failed due to: " << error_msg->c_str(); *error_msg = error_str.str(); return false; } } break; } case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER: case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC: case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER: case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC: { for (uint32_t di = 0; di < update->descriptorCount; ++di) { if (!ValidateBufferUpdate(update->pBufferInfo + di, update->descriptorType, error_code, error_msg)) { std::stringstream error_str; error_str << "Attempted write update to buffer descriptor failed due to: " << error_msg->c_str(); *error_msg = error_str.str(); return false; } } break; } default: assert(0); // We've already verified update type so should never get here break; } // All checks passed so update contents are good return true; } // Verify that the contents of the update are ok, but don't perform actual update bool cvdescriptorset::DescriptorSet::VerifyCopyUpdateContents(const VkCopyDescriptorSet *update, const DescriptorSet *src_set, VkDescriptorType type, uint32_t index, std::string *error_code, std::string *error_msg) const { // Note : Repurposing some Write update error codes here as specific details aren't called out for copy updates like they are // for write updates switch (src_set->descriptors_[index]->descriptor_class) { case PlainSampler: { for (uint32_t di = 0; di < update->descriptorCount; ++di) { const auto src_desc = src_set->descriptors_[index + di].get(); if (!src_desc->updated) continue; if (!src_desc->IsImmutableSampler()) { auto update_sampler = static_cast<SamplerDescriptor *>(src_desc)->GetSampler(); if (!ValidateSampler(update_sampler, device_data_)) { *error_code = "VUID-VkWriteDescriptorSet-descriptorType-00325"; std::stringstream error_str; error_str << "Attempted copy update to sampler descriptor with invalid sampler: " << update_sampler << "."; *error_msg = error_str.str(); return false; } } else { // TODO : Warn here } } break; } case ImageSampler: { for (uint32_t di = 0; di < update->descriptorCount; ++di) { const auto src_desc = src_set->descriptors_[index + di].get(); if (!src_desc->updated) continue; auto img_samp_desc = static_cast<const ImageSamplerDescriptor *>(src_desc); // First validate sampler if (!img_samp_desc->IsImmutableSampler()) { auto update_sampler = img_samp_desc->GetSampler(); if (!ValidateSampler(update_sampler, device_data_)) { *error_code = "VUID-VkWriteDescriptorSet-descriptorType-00325"; std::stringstream error_str; error_str << "Attempted copy update to sampler descriptor with invalid sampler: " << update_sampler << "."; *error_msg = error_str.str(); return false; } } else { // TODO : Warn here } // Validate image auto image_view = img_samp_desc->GetImageView(); auto image_layout = img_samp_desc->GetImageLayout(); if (!ValidateImageUpdate(image_view, image_layout, type, device_data_, error_code, error_msg)) { std::stringstream error_str; error_str << "Attempted copy update to combined image sampler descriptor failed due to: " << error_msg->c_str(); *error_msg = error_str.str(); return false; } } break; } case Image: { for (uint32_t di = 0; di < update->descriptorCount; ++di) { const auto src_desc = src_set->descriptors_[index + di].get(); if (!src_desc->updated) continue; auto img_desc = static_cast<const ImageDescriptor *>(src_desc); auto image_view = img_desc->GetImageView(); auto image_layout = img_desc->GetImageLayout(); if (!ValidateImageUpdate(image_view, image_layout, type, device_data_, error_code, error_msg)) { std::stringstream error_str; error_str << "Attempted copy update to image descriptor failed due to: " << error_msg->c_str(); *error_msg = error_str.str(); return false; } } break; } case TexelBuffer: { for (uint32_t di = 0; di < update->descriptorCount; ++di) { const auto src_desc = src_set->descriptors_[index + di].get(); if (!src_desc->updated) continue; auto buffer_view = static_cast<TexelDescriptor *>(src_desc)->GetBufferView(); auto bv_state = GetBufferViewState(device_data_, buffer_view); if (!bv_state) { *error_code = "VUID-VkWriteDescriptorSet-descriptorType-00323"; std::stringstream error_str; error_str << "Attempted copy update to texel buffer descriptor with invalid buffer view: " << buffer_view; *error_msg = error_str.str(); return false; } auto buffer = bv_state->create_info.buffer; if (!ValidateBufferUsage(GetBufferState(device_data_, buffer), type, error_code, error_msg)) { std::stringstream error_str; error_str << "Attempted copy update to texel buffer descriptor failed due to: " << error_msg->c_str(); *error_msg = error_str.str(); return false; } } break; } case GeneralBuffer: { for (uint32_t di = 0; di < update->descriptorCount; ++di) { const auto src_desc = src_set->descriptors_[index + di].get(); if (!src_desc->updated) continue; auto buffer = static_cast<BufferDescriptor *>(src_desc)->GetBuffer(); if (!ValidateBufferUsage(GetBufferState(device_data_, buffer), type, error_code, error_msg)) { std::stringstream error_str; error_str << "Attempted copy update to buffer descriptor failed due to: " << error_msg->c_str(); *error_msg = error_str.str(); return false; } } break; } default: assert(0); // We've already verified update type so should never get here break; } // All checks passed so update contents are good return true; } // Update the common AllocateDescriptorSetsData void cvdescriptorset::UpdateAllocateDescriptorSetsData(const layer_data *dev_data, const VkDescriptorSetAllocateInfo *p_alloc_info, AllocateDescriptorSetsData *ds_data) { for (uint32_t i = 0; i < p_alloc_info->descriptorSetCount; i++) { auto layout = GetDescriptorSetLayout(dev_data, p_alloc_info->pSetLayouts[i]); if (layout) { ds_data->layout_nodes[i] = layout; // Count total descriptors required per type for (uint32_t j = 0; j < layout->GetBindingCount(); ++j) { const auto &binding_layout = layout->GetDescriptorSetLayoutBindingPtrFromIndex(j); uint32_t typeIndex = static_cast<uint32_t>(binding_layout->descriptorType); ds_data->required_descriptors_by_type[typeIndex] += binding_layout->descriptorCount; } } // Any unknown layouts will be flagged as errors during ValidateAllocateDescriptorSets() call } } // Verify that the state at allocate time is correct, but don't actually allocate the sets yet bool cvdescriptorset::ValidateAllocateDescriptorSets(const core_validation::layer_data *dev_data, const VkDescriptorSetAllocateInfo *p_alloc_info, const AllocateDescriptorSetsData *ds_data) { bool skip = false; auto report_data = core_validation::GetReportData(dev_data); auto pool_state = GetDescriptorPoolState(dev_data, p_alloc_info->descriptorPool); for (uint32_t i = 0; i < p_alloc_info->descriptorSetCount; i++) { auto layout = GetDescriptorSetLayout(dev_data, p_alloc_info->pSetLayouts[i]); if (layout) { // nullptr layout indicates no valid layout handle for this device, validated/logged in object_tracker if (layout->GetCreateFlags() & VK_DESCRIPTOR_SET_LAYOUT_CREATE_PUSH_DESCRIPTOR_BIT_KHR) { skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT_EXT, HandleToUint64(p_alloc_info->pSetLayouts[i]), "VUID-VkDescriptorSetAllocateInfo-pSetLayouts-00308", "Layout 0x%" PRIxLEAST64 " specified at pSetLayouts[%" PRIu32 "] in vkAllocateDescriptorSets() was created with invalid flag %s set.", HandleToUint64(p_alloc_info->pSetLayouts[i]), i, "VK_DESCRIPTOR_SET_LAYOUT_CREATE_PUSH_DESCRIPTOR_BIT_KHR"); } if (layout->GetCreateFlags() & VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT_EXT && !(pool_state->createInfo.flags & VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT_EXT)) { skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT_EXT, 0, "VUID-VkDescriptorSetAllocateInfo-pSetLayouts-03044", "Descriptor set layout create flags and pool create flags mismatch for index (%d)", i); } } } if (!GetDeviceExtensions(dev_data)->vk_khr_maintenance1) { // Track number of descriptorSets allowable in this pool if (pool_state->availableSets < p_alloc_info->descriptorSetCount) { skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_POOL_EXT, HandleToUint64(pool_state->pool), "VUID-VkDescriptorSetAllocateInfo-descriptorSetCount-00306", "Unable to allocate %u descriptorSets from pool 0x%" PRIxLEAST64 ". This pool only has %d descriptorSets remaining.", p_alloc_info->descriptorSetCount, HandleToUint64(pool_state->pool), pool_state->availableSets); } // Determine whether descriptor counts are satisfiable for (uint32_t i = 0; i < VK_DESCRIPTOR_TYPE_RANGE_SIZE; i++) { if (ds_data->required_descriptors_by_type[i] > pool_state->availableDescriptorTypeCount[i]) { skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_POOL_EXT, HandleToUint64(pool_state->pool), "VUID-VkDescriptorSetAllocateInfo-descriptorPool-00307", "Unable to allocate %u descriptors of type %s from pool 0x%" PRIxLEAST64 ". This pool only has %d descriptors of this type remaining.", ds_data->required_descriptors_by_type[i], string_VkDescriptorType(VkDescriptorType(i)), HandleToUint64(pool_state->pool), pool_state->availableDescriptorTypeCount[i]); } } } const auto *count_allocate_info = lvl_find_in_chain<VkDescriptorSetVariableDescriptorCountAllocateInfoEXT>(p_alloc_info->pNext); if (count_allocate_info) { if (count_allocate_info->descriptorSetCount != 0 && count_allocate_info->descriptorSetCount != p_alloc_info->descriptorSetCount) { skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT_EXT, 0, "VUID-VkDescriptorSetVariableDescriptorCountAllocateInfoEXT-descriptorSetCount-03045", "VkDescriptorSetAllocateInfo::descriptorSetCount (%d) != " "VkDescriptorSetVariableDescriptorCountAllocateInfoEXT::descriptorSetCount (%d)", p_alloc_info->descriptorSetCount, count_allocate_info->descriptorSetCount); } if (count_allocate_info->descriptorSetCount == p_alloc_info->descriptorSetCount) { for (uint32_t i = 0; i < p_alloc_info->descriptorSetCount; i++) { auto layout = GetDescriptorSetLayout(dev_data, p_alloc_info->pSetLayouts[i]); if (count_allocate_info->pDescriptorCounts[i] > layout->GetDescriptorCountFromBinding(layout->GetMaxBinding())) { skip |= log_msg( report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_LAYOUT_EXT, 0, "VUID-VkDescriptorSetVariableDescriptorCountAllocateInfoEXT-pSetLayouts-03046", "pDescriptorCounts[%d] = (%d), binding's descriptorCount = (%d)", i, count_allocate_info->pDescriptorCounts[i], layout->GetDescriptorCountFromBinding(layout->GetMaxBinding())); } } } } return skip; } // Decrement allocated sets from the pool and insert new sets into set_map void cvdescriptorset::PerformAllocateDescriptorSets(const VkDescriptorSetAllocateInfo *p_alloc_info, const VkDescriptorSet *descriptor_sets, const AllocateDescriptorSetsData *ds_data, std::unordered_map<VkDescriptorPool, DESCRIPTOR_POOL_STATE *> *pool_map, std::unordered_map<VkDescriptorSet, cvdescriptorset::DescriptorSet *> *set_map, layer_data *dev_data) { auto pool_state = (*pool_map)[p_alloc_info->descriptorPool]; // Account for sets and individual descriptors allocated from pool pool_state->availableSets -= p_alloc_info->descriptorSetCount; for (uint32_t i = 0; i < VK_DESCRIPTOR_TYPE_RANGE_SIZE; i++) { pool_state->availableDescriptorTypeCount[i] -= ds_data->required_descriptors_by_type[i]; } const auto *variable_count_info = lvl_find_in_chain<VkDescriptorSetVariableDescriptorCountAllocateInfoEXT>(p_alloc_info->pNext); bool variable_count_valid = variable_count_info && variable_count_info->descriptorSetCount == p_alloc_info->descriptorSetCount; // Create tracking object for each descriptor set; insert into global map and the pool's set. for (uint32_t i = 0; i < p_alloc_info->descriptorSetCount; i++) { uint32_t variable_count = variable_count_valid ? variable_count_info->pDescriptorCounts[i] : 0; auto new_ds = new cvdescriptorset::DescriptorSet(descriptor_sets[i], p_alloc_info->descriptorPool, ds_data->layout_nodes[i], variable_count, dev_data); pool_state->sets.insert(new_ds); new_ds->in_use.store(0); (*set_map)[descriptor_sets[i]] = new_ds; } } cvdescriptorset::PrefilterBindRequestMap::PrefilterBindRequestMap(cvdescriptorset::DescriptorSet &ds, const BindingReqMap &in_map, GLOBAL_CB_NODE *cb_state) : filtered_map_(), orig_map_(in_map) { if (ds.GetTotalDescriptorCount() > kManyDescriptors_) { filtered_map_.reset(new std::map<uint32_t, descriptor_req>()); ds.FilterAndTrackBindingReqs(cb_state, orig_map_, filtered_map_.get()); } } cvdescriptorset::PrefilterBindRequestMap::PrefilterBindRequestMap(cvdescriptorset::DescriptorSet &ds, const BindingReqMap &in_map, GLOBAL_CB_NODE *cb_state, PIPELINE_STATE *pipeline) : filtered_map_(), orig_map_(in_map) { if (ds.GetTotalDescriptorCount() > kManyDescriptors_) { filtered_map_.reset(new std::map<uint32_t, descriptor_req>()); ds.FilterAndTrackBindingReqs(cb_state, pipeline, orig_map_, filtered_map_.get()); } }
1
8,161
It looks like this error_code field is used to return a string to the caller, not just a const input string to be consumed as in the rest of this PR? If so, my personal preference would be to leave it as a std::string* instead of a reference; I don't know offhand what the VL coding style dictates.
KhronosGroup-Vulkan-ValidationLayers
cpp
@@ -66,6 +66,11 @@ std::string MetaUtils::partVal(const std::vector<nebula::cpp2::HostAddr>& hosts) return val; } +std::string MetaUtils::partPrefix() { + static const std::string prefix = kPartsTable; + return prefix; +} + std::string MetaUtils::partPrefix(GraphSpaceID spaceId) { std::string prefix; static constexpr size_t tableLen = ::strlen(kPartsTable);
1
/* Copyright (c) 2018 - present, VE Software Inc. All rights reserved * * This source code is licensed under Apache 2.0 License * (found in the LICENSE.Apache file in the root directory) */ #include "meta/MetaUtils.h" #include <string.h> namespace nebula { namespace meta { const char kSpacesTable[] = "__spaces__"; const char kPartsTable[] = "__parts__"; const char kHostsTable[] = "__hosts__"; std::string MetaUtils::spaceKey(GraphSpaceID spaceId) { std::string key; static const size_t prefixLen = ::strlen(kSpacesTable); key.reserve(prefixLen + sizeof(spaceId)); key.append(kSpacesTable, prefixLen); key.append(reinterpret_cast<const char*>(&spaceId), sizeof(spaceId)); return key; } std::string MetaUtils::spaceVal(int32_t partsNum, int32_t replicaFactor, const std::string& name) { std::string val; val.reserve(sizeof(partsNum) + sizeof(replicaFactor) + name.size()); val.append(reinterpret_cast<const char*>(&partsNum), sizeof(partsNum)); val.append(reinterpret_cast<const char*>(&replicaFactor), sizeof(replicaFactor)); val.append(name); return val; } const std::string& MetaUtils::spacePrefix() { static const std::string prefix = kSpacesTable; return prefix; } GraphSpaceID MetaUtils::spaceId(folly::StringPiece rawKey) { static const size_t prefixLen = ::strlen(kSpacesTable); return *reinterpret_cast<const GraphSpaceID*>(rawKey.data() + prefixLen); } folly::StringPiece MetaUtils::spaceName(folly::StringPiece rawVal) { return rawVal.subpiece(sizeof(int32_t)*2); } std::string MetaUtils::partKey(GraphSpaceID spaceId, PartitionID partId) { std::string key; static constexpr size_t tableLen = ::strlen(kPartsTable); key.reserve(tableLen + sizeof(GraphSpaceID) + sizeof(PartitionID)); key.append(kPartsTable, tableLen); key.append(reinterpret_cast<const char*>(&spaceId), sizeof(GraphSpaceID)); key.append(reinterpret_cast<const char*>(&partId), sizeof(PartitionID)); return key; } std::string MetaUtils::partVal(const std::vector<nebula::cpp2::HostAddr>& hosts) { std::string val; val.reserve(hosts.size() * sizeof(int32_t) * 2); for (auto& h : hosts) { val.append(reinterpret_cast<const char*>(&h.ip), sizeof(h.ip)); val.append(reinterpret_cast<const char*>(&h.port), sizeof(h.port)); } return val; } std::string MetaUtils::partPrefix(GraphSpaceID spaceId) { std::string prefix; static constexpr size_t tableLen = ::strlen(kPartsTable); prefix.reserve(tableLen + sizeof(GraphSpaceID)); prefix.append(kPartsTable, tableLen); prefix.append(reinterpret_cast<const char*>(&spaceId), sizeof(GraphSpaceID)); return prefix; } std::vector<nebula::cpp2::HostAddr> MetaUtils::parsePartVal(folly::StringPiece val) { std::vector<nebula::cpp2::HostAddr> hosts; static const size_t unitSize = sizeof(int32_t) * 2; auto hostsNum = val.size() / unitSize; hosts.reserve(hostsNum); VLOG(3) << "Total size:" << val.size() << ", host size:" << unitSize << ", host num:" << hostsNum; for (decltype(hostsNum) i = 0; i < hostsNum; i++) { nebula::cpp2::HostAddr h; h.set_ip(*reinterpret_cast<const int32_t*>(val.data() + i * unitSize)); h.set_port(*reinterpret_cast<const int32_t*>(val.data() + i * unitSize + sizeof(int32_t))); hosts.emplace_back(std::move(h)); } return hosts; } std::string MetaUtils::hostKey(IPv4 ip, Port port) { std::string key; static constexpr size_t tableLen = ::strlen(kHostsTable); key.reserve(tableLen + sizeof(IPv4) + sizeof(Port)); key.append(kHostsTable, tableLen); key.append(reinterpret_cast<const char*>(&ip), sizeof(ip)); key.append(reinterpret_cast<const char*>(&port), sizeof(port)); return key; } std::string MetaUtils::hostVal() { return ""; } const std::string& MetaUtils::hostPrefix() { static const std::string prefix = kHostsTable; return prefix; } nebula::cpp2::HostAddr MetaUtils::parseHostKey(folly::StringPiece key) { nebula::cpp2::HostAddr host; static constexpr size_t tableLen = ::strlen(kHostsTable); memcpy(&host, key.data() + tableLen, sizeof(host)); return host; } std::string MetaUtils::schemaEdgeKey(EdgeType edgeType, int32_t version) { UNUSED(edgeType); UNUSED(version); return ""; } std::string MetaUtils::schemaEdgeVal(nebula::cpp2::Schema schema) { UNUSED(schema); return ""; } std::string MetaUtils::schemaTagKey(TagID tagId, int32_t version) { UNUSED(tagId); UNUSED(version); return ""; } std::string MetaUtils::schemaTagVal(nebula::cpp2::Schema schema) { UNUSED(schema); return ""; } } // namespace meta } // namespace nebula
1
15,632
If return by value, then why bother to make it `static`?
vesoft-inc-nebula
cpp
@@ -369,8 +369,11 @@ def nop(): @cmdutils.register() @cmdutils.argument('win_id', win_id=True) -def version(win_id): +def version(win_id, paste=False): """Show version information.""" tabbed_browser = objreg.get('tabbed-browser', scope='window', window=win_id) tabbed_browser.openurl(QUrl('qute://version'), newtab=True) + + if paste: + utils.pastebin_version()
1
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et: # Copyright 2014-2017 Florian Bruhin (The Compiler) <[email protected]> # # This file is part of qutebrowser. # # qutebrowser is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # qutebrowser is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with qutebrowser. If not, see <http://www.gnu.org/licenses/>. """Misc. utility commands exposed to the user.""" import functools import os import signal import traceback try: import hunter except ImportError: hunter = None import sip from PyQt5.QtCore import QUrl # so it's available for :debug-pyeval from PyQt5.QtWidgets import QApplication # pylint: disable=unused-import from qutebrowser.browser import qutescheme from qutebrowser.utils import log, objreg, usertypes, message, debug, utils from qutebrowser.commands import cmdutils, runners, cmdexc from qutebrowser.config import config, configdata from qutebrowser.misc import consolewidget @cmdutils.register(maxsplit=1, no_cmd_split=True, no_replace_variables=True) @cmdutils.argument('win_id', win_id=True) def later(ms: int, command, win_id): """Execute a command after some time. Args: ms: How many milliseconds to wait. command: The command to run, with optional args. """ if ms < 0: raise cmdexc.CommandError("I can't run something in the past!") commandrunner = runners.CommandRunner(win_id) app = objreg.get('app') timer = usertypes.Timer(name='later', parent=app) try: timer.setSingleShot(True) try: timer.setInterval(ms) except OverflowError: raise cmdexc.CommandError("Numeric argument is too large for " "internal int representation.") timer.timeout.connect( functools.partial(commandrunner.run_safely, command)) timer.timeout.connect(timer.deleteLater) timer.start() except: timer.deleteLater() raise @cmdutils.register(maxsplit=1, no_cmd_split=True, no_replace_variables=True) @cmdutils.argument('win_id', win_id=True) def repeat(times: int, command, win_id): """Repeat a given command. Args: times: How many times to repeat. command: The command to run, with optional args. """ if times < 0: raise cmdexc.CommandError("A negative count doesn't make sense.") commandrunner = runners.CommandRunner(win_id) for _ in range(times): commandrunner.run_safely(command) @cmdutils.register(maxsplit=1, no_cmd_split=True, no_replace_variables=True) @cmdutils.argument('win_id', win_id=True) @cmdutils.argument('count', count=True) def run_with_count(count_arg: int, command, win_id, count=1): """Run a command with the given count. If run_with_count itself is run with a count, it multiplies count_arg. Args: count_arg: The count to pass to the command. command: The command to run, with optional args. count: The count that run_with_count itself received. """ runners.CommandRunner(win_id).run(command, count_arg * count) @cmdutils.register() def message_error(text): """Show an error message in the statusbar. Args: text: The text to show. """ message.error(text) @cmdutils.register() @cmdutils.argument('count', count=True) def message_info(text, count=1): """Show an info message in the statusbar. Args: text: The text to show. count: How many times to show the message """ for _ in range(count): message.info(text) @cmdutils.register() def message_warning(text): """Show a warning message in the statusbar. Args: text: The text to show. """ message.warning(text) @cmdutils.register() def clear_messages(): """Clear all message notifications.""" message.global_bridge.clear_messages.emit() @cmdutils.register(debug=True) @cmdutils.argument('typ', choices=['exception', 'segfault']) def debug_crash(typ='exception'): """Crash for debugging purposes. Args: typ: either 'exception' or 'segfault'. """ if typ == 'segfault': os.kill(os.getpid(), signal.SIGSEGV) raise Exception("Segfault failed (wat.)") else: raise Exception("Forced crash") @cmdutils.register(debug=True) def debug_all_objects(): """Print a list of all objects to the debug log.""" s = debug.get_all_objects() log.misc.debug(s) @cmdutils.register(debug=True) def debug_cache_stats(): """Print LRU cache stats.""" prefix_info = configdata.is_valid_prefix.cache_info() # pylint: disable=protected-access render_stylesheet_info = config._render_stylesheet.cache_info() # pylint: enable=protected-access history_info = None try: from PyQt5.QtWebKit import QWebHistoryInterface interface = QWebHistoryInterface.defaultInterface() if interface is not None: history_info = interface.historyContains.cache_info() except ImportError: pass tabbed_browser = objreg.get('tabbed-browser', scope='window', window='last-focused') # pylint: disable=protected-access tab_bar = tabbed_browser.tabBar() tabbed_browser_info = tab_bar._minimum_tab_size_hint_helper.cache_info() # pylint: enable=protected-access log.misc.debug('is_valid_prefix: {}'.format(prefix_info)) log.misc.debug('_render_stylesheet: {}'.format(render_stylesheet_info)) log.misc.debug('history: {}'.format(history_info)) log.misc.debug('tab width cache: {}'.format(tabbed_browser_info)) @cmdutils.register(debug=True) def debug_console(): """Show the debugging console.""" try: con_widget = objreg.get('debug-console') except KeyError: log.misc.debug('initializing debug console') con_widget = consolewidget.ConsoleWidget() objreg.register('debug-console', con_widget) if con_widget.isVisible(): log.misc.debug('hiding debug console') con_widget.hide() else: log.misc.debug('showing debug console') con_widget.show() @cmdutils.register(debug=True, maxsplit=0, no_cmd_split=True) def debug_trace(expr=""): """Trace executed code via hunter. Args: expr: What to trace, passed to hunter. """ if hunter is None: raise cmdexc.CommandError("You need to install 'hunter' to use this " "command!") try: eval('hunter.trace({})'.format(expr)) except Exception as e: raise cmdexc.CommandError("{}: {}".format(e.__class__.__name__, e)) @cmdutils.register(maxsplit=0, debug=True, no_cmd_split=True) def debug_pyeval(s, file=False, quiet=False): """Evaluate a python string and display the results as a web page. Args: s: The string to evaluate. file: Interpret s as a path to file, also implies --quiet. quiet: Don't show the output in a new tab. """ if file: quiet = True path = os.path.expanduser(s) try: with open(path, 'r', encoding='utf-8') as f: s = f.read() except OSError as e: raise cmdexc.CommandError(str(e)) try: exec(s) out = "No error" except Exception: out = traceback.format_exc() else: try: r = eval(s) out = repr(r) except Exception: out = traceback.format_exc() qutescheme.pyeval_output = out if quiet: log.misc.debug("pyeval output: {}".format(out)) else: tabbed_browser = objreg.get('tabbed-browser', scope='window', window='last-focused') tabbed_browser.openurl(QUrl('qute://pyeval'), newtab=True) @cmdutils.register(debug=True) def debug_set_fake_clipboard(s=None): """Put data into the fake clipboard and enable logging, used for tests. Args: s: The text to put into the fake clipboard, or unset to enable logging. """ if s is None: utils.log_clipboard = True else: utils.fake_clipboard = s @cmdutils.register() @cmdutils.argument('win_id', win_id=True) @cmdutils.argument('count', count=True) def repeat_command(win_id, count=None): """Repeat the last executed command. Args: count: Which count to pass the command. """ mode_manager = objreg.get('mode-manager', scope='window', window=win_id) if mode_manager.mode not in runners.last_command: raise cmdexc.CommandError("You didn't do anything yet.") cmd = runners.last_command[mode_manager.mode] commandrunner = runners.CommandRunner(win_id) commandrunner.run(cmd[0], count if count is not None else cmd[1]) @cmdutils.register(debug=True, name='debug-log-capacity') def log_capacity(capacity: int): """Change the number of log lines to be stored in RAM. Args: capacity: Number of lines for the log. """ if capacity < 0: raise cmdexc.CommandError("Can't set a negative log capacity!") else: log.ram_handler.change_log_capacity(capacity) @cmdutils.register(debug=True) @cmdutils.argument('level', choices=sorted( (level.lower() for level in log.LOG_LEVELS), key=lambda e: log.LOG_LEVELS[e.upper()])) def debug_log_level(level: str): """Change the log level for console logging. Args: level: The log level to set. """ log.change_console_formatter(log.LOG_LEVELS[level.upper()]) log.console_handler.setLevel(log.LOG_LEVELS[level.upper()]) @cmdutils.register(debug=True) def debug_log_filter(filters: str): """Change the log filter for console logging. Args: filters: A comma separated list of logger names. Can also be "none" to clear any existing filters. """ if log.console_filter is None: raise cmdexc.CommandError("No log.console_filter. Not attached " "to a console?") if filters.strip().lower() == 'none': log.console_filter.names = None return if not set(filters.split(',')).issubset(log.LOGGER_NAMES): raise cmdexc.CommandError("filters: Invalid value {} - expected one " "of: {}".format(filters, ', '.join(log.LOGGER_NAMES))) log.console_filter.names = filters.split(',') @cmdutils.register() @cmdutils.argument('current_win_id', win_id=True) def window_only(current_win_id): """Close all windows except for the current one.""" for win_id, window in objreg.window_registry.items(): # We could be in the middle of destroying a window here if sip.isdeleted(window): continue if win_id != current_win_id: window.close() @cmdutils.register() def nop(): """Do nothing.""" return @cmdutils.register() @cmdutils.argument('win_id', win_id=True) def version(win_id): """Show version information.""" tabbed_browser = objreg.get('tabbed-browser', scope='window', window=win_id) tabbed_browser.openurl(QUrl('qute://version'), newtab=True)
1
20,442
You'll need to add docs for the argument, see e.g. the `debug_log_filter` docstring above.
qutebrowser-qutebrowser
py
@@ -30,6 +30,7 @@ import ( "go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/sdk/instrumentation" "go.opentelemetry.io/otel/sdk/resource" + sdktrace "go.opentelemetry.io/otel/sdk/trace" tracesdk "go.opentelemetry.io/otel/sdk/trace" "go.opentelemetry.io/otel/semconv" "go.opentelemetry.io/otel/trace"
1
// Copyright The OpenTelemetry Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package zipkin import ( "fmt" "net" "strconv" "testing" "time" "github.com/google/go-cmp/cmp" zkmodel "github.com/openzipkin/zipkin-go/model" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/sdk/instrumentation" "go.opentelemetry.io/otel/sdk/resource" tracesdk "go.opentelemetry.io/otel/sdk/trace" "go.opentelemetry.io/otel/semconv" "go.opentelemetry.io/otel/trace" ) func TestModelConversion(t *testing.T) { resource := resource.NewWithAttributes( semconv.ServiceNameKey.String("model-test"), ) inputBatch := []*tracesdk.SpanSnapshot{ // typical span data { SpanContext: trace.NewSpanContext(trace.SpanContextConfig{ TraceID: trace.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, SpanID: trace.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8}, }), Parent: trace.NewSpanContext(trace.SpanContextConfig{ TraceID: trace.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, SpanID: trace.SpanID{0x3F, 0x3E, 0x3D, 0x3C, 0x3B, 0x3A, 0x39, 0x38}, }), SpanKind: trace.SpanKindServer, Name: "foo", StartTime: time.Date(2020, time.March, 11, 19, 24, 0, 0, time.UTC), EndTime: time.Date(2020, time.March, 11, 19, 25, 0, 0, time.UTC), Attributes: []attribute.KeyValue{ attribute.Int64("attr1", 42), attribute.String("attr2", "bar"), attribute.Array("attr3", []int{0, 1, 2}), }, MessageEvents: []tracesdk.Event{ { Time: time.Date(2020, time.March, 11, 19, 24, 30, 0, time.UTC), Name: "ev1", Attributes: []attribute.KeyValue{ attribute.Int64("eventattr1", 123), }, }, { Time: time.Date(2020, time.March, 11, 19, 24, 45, 0, time.UTC), Name: "ev2", Attributes: nil, }, }, StatusCode: codes.Error, StatusMessage: "404, file not found", Resource: resource, }, // span data with no parent (same as typical, but has // invalid parent) { SpanContext: trace.NewSpanContext(trace.SpanContextConfig{ TraceID: trace.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, SpanID: trace.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8}, }), SpanKind: trace.SpanKindServer, Name: "foo", StartTime: time.Date(2020, time.March, 11, 19, 24, 0, 0, time.UTC), EndTime: time.Date(2020, time.March, 11, 19, 25, 0, 0, time.UTC), Attributes: []attribute.KeyValue{ attribute.Int64("attr1", 42), attribute.String("attr2", "bar"), }, MessageEvents: []tracesdk.Event{ { Time: time.Date(2020, time.March, 11, 19, 24, 30, 0, time.UTC), Name: "ev1", Attributes: []attribute.KeyValue{ attribute.Int64("eventattr1", 123), }, }, { Time: time.Date(2020, time.March, 11, 19, 24, 45, 0, time.UTC), Name: "ev2", Attributes: nil, }, }, StatusCode: codes.Error, StatusMessage: "404, file not found", Resource: resource, }, // span data of unspecified kind { SpanContext: trace.NewSpanContext(trace.SpanContextConfig{ TraceID: trace.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, SpanID: trace.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8}, }), Parent: trace.NewSpanContext(trace.SpanContextConfig{ TraceID: trace.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, SpanID: trace.SpanID{0x3F, 0x3E, 0x3D, 0x3C, 0x3B, 0x3A, 0x39, 0x38}, }), SpanKind: trace.SpanKindUnspecified, Name: "foo", StartTime: time.Date(2020, time.March, 11, 19, 24, 0, 0, time.UTC), EndTime: time.Date(2020, time.March, 11, 19, 25, 0, 0, time.UTC), Attributes: []attribute.KeyValue{ attribute.Int64("attr1", 42), attribute.String("attr2", "bar"), }, MessageEvents: []tracesdk.Event{ { Time: time.Date(2020, time.March, 11, 19, 24, 30, 0, time.UTC), Name: "ev1", Attributes: []attribute.KeyValue{ attribute.Int64("eventattr1", 123), }, }, { Time: time.Date(2020, time.March, 11, 19, 24, 45, 0, time.UTC), Name: "ev2", Attributes: nil, }, }, StatusCode: codes.Error, StatusMessage: "404, file not found", Resource: resource, }, // span data of internal kind { SpanContext: trace.NewSpanContext(trace.SpanContextConfig{ TraceID: trace.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, SpanID: trace.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8}, }), Parent: trace.NewSpanContext(trace.SpanContextConfig{ TraceID: trace.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, SpanID: trace.SpanID{0x3F, 0x3E, 0x3D, 0x3C, 0x3B, 0x3A, 0x39, 0x38}, }), SpanKind: trace.SpanKindInternal, Name: "foo", StartTime: time.Date(2020, time.March, 11, 19, 24, 0, 0, time.UTC), EndTime: time.Date(2020, time.March, 11, 19, 25, 0, 0, time.UTC), Attributes: []attribute.KeyValue{ attribute.Int64("attr1", 42), attribute.String("attr2", "bar"), }, MessageEvents: []tracesdk.Event{ { Time: time.Date(2020, time.March, 11, 19, 24, 30, 0, time.UTC), Name: "ev1", Attributes: []attribute.KeyValue{ attribute.Int64("eventattr1", 123), }, }, { Time: time.Date(2020, time.March, 11, 19, 24, 45, 0, time.UTC), Name: "ev2", Attributes: nil, }, }, StatusCode: codes.Error, StatusMessage: "404, file not found", Resource: resource, }, // span data of client kind { SpanContext: trace.NewSpanContext(trace.SpanContextConfig{ TraceID: trace.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, SpanID: trace.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8}, }), Parent: trace.NewSpanContext(trace.SpanContextConfig{ TraceID: trace.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, SpanID: trace.SpanID{0x3F, 0x3E, 0x3D, 0x3C, 0x3B, 0x3A, 0x39, 0x38}, }), SpanKind: trace.SpanKindClient, Name: "foo", StartTime: time.Date(2020, time.March, 11, 19, 24, 0, 0, time.UTC), EndTime: time.Date(2020, time.March, 11, 19, 25, 0, 0, time.UTC), Attributes: []attribute.KeyValue{ attribute.Int64("attr1", 42), attribute.String("attr2", "bar"), attribute.String("peer.hostname", "test-peer-hostname"), attribute.String("net.peer.ip", "1.2.3.4"), attribute.Int64("net.peer.port", 9876), }, MessageEvents: []tracesdk.Event{ { Time: time.Date(2020, time.March, 11, 19, 24, 30, 0, time.UTC), Name: "ev1", Attributes: []attribute.KeyValue{ attribute.Int64("eventattr1", 123), }, }, { Time: time.Date(2020, time.March, 11, 19, 24, 45, 0, time.UTC), Name: "ev2", Attributes: nil, }, }, StatusCode: codes.Error, StatusMessage: "404, file not found", Resource: resource, }, // span data of producer kind { SpanContext: trace.NewSpanContext(trace.SpanContextConfig{ TraceID: trace.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, SpanID: trace.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8}, }), Parent: trace.NewSpanContext(trace.SpanContextConfig{ TraceID: trace.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, SpanID: trace.SpanID{0x3F, 0x3E, 0x3D, 0x3C, 0x3B, 0x3A, 0x39, 0x38}, }), SpanKind: trace.SpanKindProducer, Name: "foo", StartTime: time.Date(2020, time.March, 11, 19, 24, 0, 0, time.UTC), EndTime: time.Date(2020, time.March, 11, 19, 25, 0, 0, time.UTC), Attributes: []attribute.KeyValue{ attribute.Int64("attr1", 42), attribute.String("attr2", "bar"), }, MessageEvents: []tracesdk.Event{ { Time: time.Date(2020, time.March, 11, 19, 24, 30, 0, time.UTC), Name: "ev1", Attributes: []attribute.KeyValue{ attribute.Int64("eventattr1", 123), }, }, { Time: time.Date(2020, time.March, 11, 19, 24, 45, 0, time.UTC), Name: "ev2", Attributes: nil, }, }, StatusCode: codes.Error, StatusMessage: "404, file not found", Resource: resource, }, // span data of consumer kind { SpanContext: trace.NewSpanContext(trace.SpanContextConfig{ TraceID: trace.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, SpanID: trace.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8}, }), Parent: trace.NewSpanContext(trace.SpanContextConfig{ TraceID: trace.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, SpanID: trace.SpanID{0x3F, 0x3E, 0x3D, 0x3C, 0x3B, 0x3A, 0x39, 0x38}, }), SpanKind: trace.SpanKindConsumer, Name: "foo", StartTime: time.Date(2020, time.March, 11, 19, 24, 0, 0, time.UTC), EndTime: time.Date(2020, time.March, 11, 19, 25, 0, 0, time.UTC), Attributes: []attribute.KeyValue{ attribute.Int64("attr1", 42), attribute.String("attr2", "bar"), }, MessageEvents: []tracesdk.Event{ { Time: time.Date(2020, time.March, 11, 19, 24, 30, 0, time.UTC), Name: "ev1", Attributes: []attribute.KeyValue{ attribute.Int64("eventattr1", 123), }, }, { Time: time.Date(2020, time.March, 11, 19, 24, 45, 0, time.UTC), Name: "ev2", Attributes: nil, }, }, StatusCode: codes.Error, StatusMessage: "404, file not found", Resource: resource, }, // span data with no events { SpanContext: trace.NewSpanContext(trace.SpanContextConfig{ TraceID: trace.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, SpanID: trace.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8}, }), Parent: trace.NewSpanContext(trace.SpanContextConfig{ TraceID: trace.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, SpanID: trace.SpanID{0x3F, 0x3E, 0x3D, 0x3C, 0x3B, 0x3A, 0x39, 0x38}, }), SpanKind: trace.SpanKindServer, Name: "foo", StartTime: time.Date(2020, time.March, 11, 19, 24, 0, 0, time.UTC), EndTime: time.Date(2020, time.March, 11, 19, 25, 0, 0, time.UTC), Attributes: []attribute.KeyValue{ attribute.Int64("attr1", 42), attribute.String("attr2", "bar"), }, MessageEvents: nil, StatusCode: codes.Error, StatusMessage: "404, file not found", Resource: resource, }, // span data with an "error" attribute set to "false" { SpanContext: trace.NewSpanContext(trace.SpanContextConfig{ TraceID: trace.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, SpanID: trace.SpanID{0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA, 0xF9, 0xF8}, }), Parent: trace.NewSpanContext(trace.SpanContextConfig{ TraceID: trace.TraceID{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}, SpanID: trace.SpanID{0x3F, 0x3E, 0x3D, 0x3C, 0x3B, 0x3A, 0x39, 0x38}, }), SpanKind: trace.SpanKindServer, Name: "foo", StartTime: time.Date(2020, time.March, 11, 19, 24, 0, 0, time.UTC), EndTime: time.Date(2020, time.March, 11, 19, 25, 0, 0, time.UTC), Attributes: []attribute.KeyValue{ attribute.String("error", "false"), }, MessageEvents: []tracesdk.Event{ { Time: time.Date(2020, time.March, 11, 19, 24, 30, 0, time.UTC), Name: "ev1", Attributes: []attribute.KeyValue{ attribute.Int64("eventattr1", 123), }, }, { Time: time.Date(2020, time.March, 11, 19, 24, 45, 0, time.UTC), Name: "ev2", Attributes: nil, }, }, StatusCode: codes.Unset, Resource: resource, }, } expectedOutputBatch := []zkmodel.SpanModel{ // model for typical span data { SpanContext: zkmodel.SpanContext{ TraceID: zkmodel.TraceID{ High: 0x001020304050607, Low: 0x8090a0b0c0d0e0f, }, ID: zkmodel.ID(0xfffefdfcfbfaf9f8), ParentID: zkmodelIDPtr(0x3f3e3d3c3b3a3938), Debug: false, Sampled: nil, Err: nil, }, Name: "foo", Kind: "SERVER", Timestamp: time.Date(2020, time.March, 11, 19, 24, 0, 0, time.UTC), Duration: time.Minute, Shared: false, LocalEndpoint: &zkmodel.Endpoint{ ServiceName: "model-test", }, RemoteEndpoint: nil, Annotations: []zkmodel.Annotation{ { Timestamp: time.Date(2020, time.March, 11, 19, 24, 30, 0, time.UTC), Value: `ev1: {"eventattr1":123}`, }, { Timestamp: time.Date(2020, time.March, 11, 19, 24, 45, 0, time.UTC), Value: "ev2", }, }, Tags: map[string]string{ "attr1": "42", "attr2": "bar", "attr3": "[0,1,2]", "otel.status_code": "Error", "error": "404, file not found", }, }, // model for span data with no parent { SpanContext: zkmodel.SpanContext{ TraceID: zkmodel.TraceID{ High: 0x001020304050607, Low: 0x8090a0b0c0d0e0f, }, ID: zkmodel.ID(0xfffefdfcfbfaf9f8), ParentID: nil, Debug: false, Sampled: nil, Err: nil, }, Name: "foo", Kind: "SERVER", Timestamp: time.Date(2020, time.March, 11, 19, 24, 0, 0, time.UTC), Duration: time.Minute, Shared: false, LocalEndpoint: &zkmodel.Endpoint{ ServiceName: "model-test", }, RemoteEndpoint: nil, Annotations: []zkmodel.Annotation{ { Timestamp: time.Date(2020, time.March, 11, 19, 24, 30, 0, time.UTC), Value: `ev1: {"eventattr1":123}`, }, { Timestamp: time.Date(2020, time.March, 11, 19, 24, 45, 0, time.UTC), Value: "ev2", }, }, Tags: map[string]string{ "attr1": "42", "attr2": "bar", "otel.status_code": "Error", "error": "404, file not found", }, }, // model for span data of unspecified kind { SpanContext: zkmodel.SpanContext{ TraceID: zkmodel.TraceID{ High: 0x001020304050607, Low: 0x8090a0b0c0d0e0f, }, ID: zkmodel.ID(0xfffefdfcfbfaf9f8), ParentID: zkmodelIDPtr(0x3f3e3d3c3b3a3938), Debug: false, Sampled: nil, Err: nil, }, Name: "foo", Kind: "", Timestamp: time.Date(2020, time.March, 11, 19, 24, 0, 0, time.UTC), Duration: time.Minute, Shared: false, LocalEndpoint: &zkmodel.Endpoint{ ServiceName: "model-test", }, RemoteEndpoint: nil, Annotations: []zkmodel.Annotation{ { Timestamp: time.Date(2020, time.March, 11, 19, 24, 30, 0, time.UTC), Value: `ev1: {"eventattr1":123}`, }, { Timestamp: time.Date(2020, time.March, 11, 19, 24, 45, 0, time.UTC), Value: "ev2", }, }, Tags: map[string]string{ "attr1": "42", "attr2": "bar", "otel.status_code": "Error", "error": "404, file not found", }, }, // model for span data of internal kind { SpanContext: zkmodel.SpanContext{ TraceID: zkmodel.TraceID{ High: 0x001020304050607, Low: 0x8090a0b0c0d0e0f, }, ID: zkmodel.ID(0xfffefdfcfbfaf9f8), ParentID: zkmodelIDPtr(0x3f3e3d3c3b3a3938), Debug: false, Sampled: nil, Err: nil, }, Name: "foo", Kind: "", Timestamp: time.Date(2020, time.March, 11, 19, 24, 0, 0, time.UTC), Duration: time.Minute, Shared: false, LocalEndpoint: &zkmodel.Endpoint{ ServiceName: "model-test", }, RemoteEndpoint: nil, Annotations: []zkmodel.Annotation{ { Timestamp: time.Date(2020, time.March, 11, 19, 24, 30, 0, time.UTC), Value: `ev1: {"eventattr1":123}`, }, { Timestamp: time.Date(2020, time.March, 11, 19, 24, 45, 0, time.UTC), Value: "ev2", }, }, Tags: map[string]string{ "attr1": "42", "attr2": "bar", "otel.status_code": "Error", "error": "404, file not found", }, }, // model for span data of client kind { SpanContext: zkmodel.SpanContext{ TraceID: zkmodel.TraceID{ High: 0x001020304050607, Low: 0x8090a0b0c0d0e0f, }, ID: zkmodel.ID(0xfffefdfcfbfaf9f8), ParentID: zkmodelIDPtr(0x3f3e3d3c3b3a3938), Debug: false, Sampled: nil, Err: nil, }, Name: "foo", Kind: "CLIENT", Timestamp: time.Date(2020, time.March, 11, 19, 24, 0, 0, time.UTC), Duration: time.Minute, Shared: false, LocalEndpoint: &zkmodel.Endpoint{ ServiceName: "model-test", }, RemoteEndpoint: &zkmodel.Endpoint{ IPv4: net.ParseIP("1.2.3.4"), Port: 9876, }, Annotations: []zkmodel.Annotation{ { Timestamp: time.Date(2020, time.March, 11, 19, 24, 30, 0, time.UTC), Value: `ev1: {"eventattr1":123}`, }, { Timestamp: time.Date(2020, time.March, 11, 19, 24, 45, 0, time.UTC), Value: "ev2", }, }, Tags: map[string]string{ "attr1": "42", "attr2": "bar", "net.peer.ip": "1.2.3.4", "net.peer.port": "9876", "peer.hostname": "test-peer-hostname", "otel.status_code": "Error", "error": "404, file not found", }, }, // model for span data of producer kind { SpanContext: zkmodel.SpanContext{ TraceID: zkmodel.TraceID{ High: 0x001020304050607, Low: 0x8090a0b0c0d0e0f, }, ID: zkmodel.ID(0xfffefdfcfbfaf9f8), ParentID: zkmodelIDPtr(0x3f3e3d3c3b3a3938), Debug: false, Sampled: nil, Err: nil, }, Name: "foo", Kind: "PRODUCER", Timestamp: time.Date(2020, time.March, 11, 19, 24, 0, 0, time.UTC), Duration: time.Minute, Shared: false, LocalEndpoint: &zkmodel.Endpoint{ ServiceName: "model-test", }, RemoteEndpoint: nil, Annotations: []zkmodel.Annotation{ { Timestamp: time.Date(2020, time.March, 11, 19, 24, 30, 0, time.UTC), Value: `ev1: {"eventattr1":123}`, }, { Timestamp: time.Date(2020, time.March, 11, 19, 24, 45, 0, time.UTC), Value: "ev2", }, }, Tags: map[string]string{ "attr1": "42", "attr2": "bar", "otel.status_code": "Error", "error": "404, file not found", }, }, // model for span data of consumer kind { SpanContext: zkmodel.SpanContext{ TraceID: zkmodel.TraceID{ High: 0x001020304050607, Low: 0x8090a0b0c0d0e0f, }, ID: zkmodel.ID(0xfffefdfcfbfaf9f8), ParentID: zkmodelIDPtr(0x3f3e3d3c3b3a3938), Debug: false, Sampled: nil, Err: nil, }, Name: "foo", Kind: "CONSUMER", Timestamp: time.Date(2020, time.March, 11, 19, 24, 0, 0, time.UTC), Duration: time.Minute, Shared: false, LocalEndpoint: &zkmodel.Endpoint{ ServiceName: "model-test", }, RemoteEndpoint: nil, Annotations: []zkmodel.Annotation{ { Timestamp: time.Date(2020, time.March, 11, 19, 24, 30, 0, time.UTC), Value: `ev1: {"eventattr1":123}`, }, { Timestamp: time.Date(2020, time.March, 11, 19, 24, 45, 0, time.UTC), Value: "ev2", }, }, Tags: map[string]string{ "attr1": "42", "attr2": "bar", "otel.status_code": "Error", "error": "404, file not found", }, }, // model for span data with no events { SpanContext: zkmodel.SpanContext{ TraceID: zkmodel.TraceID{ High: 0x001020304050607, Low: 0x8090a0b0c0d0e0f, }, ID: zkmodel.ID(0xfffefdfcfbfaf9f8), ParentID: zkmodelIDPtr(0x3f3e3d3c3b3a3938), Debug: false, Sampled: nil, Err: nil, }, Name: "foo", Kind: "SERVER", Timestamp: time.Date(2020, time.March, 11, 19, 24, 0, 0, time.UTC), Duration: time.Minute, Shared: false, LocalEndpoint: &zkmodel.Endpoint{ ServiceName: "model-test", }, RemoteEndpoint: nil, Annotations: nil, Tags: map[string]string{ "attr1": "42", "attr2": "bar", "otel.status_code": "Error", "error": "404, file not found", }, }, // model for span data with an "error" attribute set to "false" { SpanContext: zkmodel.SpanContext{ TraceID: zkmodel.TraceID{ High: 0x001020304050607, Low: 0x8090a0b0c0d0e0f, }, ID: zkmodel.ID(0xfffefdfcfbfaf9f8), ParentID: zkmodelIDPtr(0x3f3e3d3c3b3a3938), Debug: false, Sampled: nil, Err: nil, }, Name: "foo", Kind: "SERVER", Timestamp: time.Date(2020, time.March, 11, 19, 24, 0, 0, time.UTC), Duration: time.Minute, Shared: false, LocalEndpoint: &zkmodel.Endpoint{ ServiceName: "model-test", }, RemoteEndpoint: nil, Annotations: []zkmodel.Annotation{ { Timestamp: time.Date(2020, time.March, 11, 19, 24, 30, 0, time.UTC), Value: `ev1: {"eventattr1":123}`, }, { Timestamp: time.Date(2020, time.March, 11, 19, 24, 45, 0, time.UTC), Value: "ev2", }, }, Tags: nil, // should be omitted }, } gottenOutputBatch := toZipkinSpanModels(inputBatch) require.Equal(t, expectedOutputBatch, gottenOutputBatch) } func zkmodelIDPtr(n uint64) *zkmodel.ID { id := zkmodel.ID(n) return &id } func TestTagsTransformation(t *testing.T) { keyValue := "value" doubleValue := 123.456 uintValue := int64(123) statusMessage := "this is a problem" instrLibName := "instrumentation-library" instrLibVersion := "semver:1.0.0" tests := []struct { name string data *tracesdk.SpanSnapshot want map[string]string }{ { name: "attributes", data: &tracesdk.SpanSnapshot{ Attributes: []attribute.KeyValue{ attribute.String("key", keyValue), attribute.Float64("double", doubleValue), attribute.Int64("uint", uintValue), attribute.Bool("ok", true), }, }, want: map[string]string{ "double": fmt.Sprint(doubleValue), "key": keyValue, "ok": "true", "uint": strconv.FormatInt(uintValue, 10), }, }, { name: "no attributes", data: &tracesdk.SpanSnapshot{}, want: nil, }, { name: "omit-noerror", data: &tracesdk.SpanSnapshot{ Attributes: []attribute.KeyValue{ attribute.Bool("error", false), }, }, want: nil, }, { name: "statusCode", data: &tracesdk.SpanSnapshot{ Attributes: []attribute.KeyValue{ attribute.String("key", keyValue), attribute.Bool("error", true), }, StatusCode: codes.Error, StatusMessage: statusMessage, }, want: map[string]string{ "error": statusMessage, "key": keyValue, "otel.status_code": codes.Error.String(), }, }, { name: "instrLib-empty", data: &tracesdk.SpanSnapshot{ InstrumentationLibrary: instrumentation.Library{}, }, want: nil, }, { name: "instrLib-noversion", data: &tracesdk.SpanSnapshot{ Attributes: []attribute.KeyValue{}, InstrumentationLibrary: instrumentation.Library{ Name: instrLibName, }, }, want: map[string]string{ "otel.library.name": instrLibName, }, }, { name: "instrLib-with-version", data: &tracesdk.SpanSnapshot{ Attributes: []attribute.KeyValue{}, InstrumentationLibrary: instrumentation.Library{ Name: instrLibName, Version: instrLibVersion, }, }, want: map[string]string{ "otel.library.name": instrLibName, "otel.library.version": instrLibVersion, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got := toZipkinTags(tt.data) if diff := cmp.Diff(got, tt.want); diff != "" { t.Errorf("Diff%v", diff) } }) } } func TestRemoteEndpointTransformation(t *testing.T) { tests := []struct { name string data *tracesdk.SpanSnapshot want *zkmodel.Endpoint }{ { name: "nil-not-applicable", data: &tracesdk.SpanSnapshot{ SpanKind: trace.SpanKindClient, Attributes: []attribute.KeyValue{}, }, want: nil, }, { name: "nil-not-found", data: &tracesdk.SpanSnapshot{ SpanKind: trace.SpanKindConsumer, Attributes: []attribute.KeyValue{ attribute.String("attr", "test"), }, }, want: nil, }, { name: "peer-service-rank", data: &tracesdk.SpanSnapshot{ SpanKind: trace.SpanKindProducer, Attributes: []attribute.KeyValue{ semconv.PeerServiceKey.String("peer-service-test"), semconv.NetPeerNameKey.String("peer-name-test"), semconv.HTTPHostKey.String("http-host-test"), }, }, want: &zkmodel.Endpoint{ ServiceName: "peer-service-test", }, }, { name: "http-host-rank", data: &tracesdk.SpanSnapshot{ SpanKind: trace.SpanKindProducer, Attributes: []attribute.KeyValue{ semconv.HTTPHostKey.String("http-host-test"), semconv.DBNameKey.String("db-name-test"), }, }, want: &zkmodel.Endpoint{ ServiceName: "http-host-test", }, }, { name: "db-name-rank", data: &tracesdk.SpanSnapshot{ SpanKind: trace.SpanKindProducer, Attributes: []attribute.KeyValue{ attribute.String("foo", "bar"), semconv.DBNameKey.String("db-name-test"), }, }, want: &zkmodel.Endpoint{ ServiceName: "db-name-test", }, }, { name: "peer-hostname-rank", data: &tracesdk.SpanSnapshot{ SpanKind: trace.SpanKindProducer, Attributes: []attribute.KeyValue{ keyPeerHostname.String("peer-hostname-test"), keyPeerAddress.String("peer-address-test"), semconv.HTTPHostKey.String("http-host-test"), semconv.DBNameKey.String("http-host-test"), }, }, want: &zkmodel.Endpoint{ ServiceName: "peer-hostname-test", }, }, { name: "peer-address-rank", data: &tracesdk.SpanSnapshot{ SpanKind: trace.SpanKindProducer, Attributes: []attribute.KeyValue{ keyPeerAddress.String("peer-address-test"), semconv.HTTPHostKey.String("http-host-test"), semconv.DBNameKey.String("http-host-test"), }, }, want: &zkmodel.Endpoint{ ServiceName: "peer-address-test", }, }, { name: "net-peer-invalid-ip", data: &tracesdk.SpanSnapshot{ SpanKind: trace.SpanKindProducer, Attributes: []attribute.KeyValue{ semconv.NetPeerIPKey.String("INVALID"), }, }, want: nil, }, { name: "net-peer-ipv6-no-port", data: &tracesdk.SpanSnapshot{ SpanKind: trace.SpanKindProducer, Attributes: []attribute.KeyValue{ semconv.NetPeerIPKey.String("0:0:1:5ee:bad:c0de:0:0"), }, }, want: &zkmodel.Endpoint{ IPv6: net.ParseIP("0:0:1:5ee:bad:c0de:0:0"), }, }, { name: "net-peer-ipv4-port", data: &tracesdk.SpanSnapshot{ SpanKind: trace.SpanKindProducer, Attributes: []attribute.KeyValue{ semconv.NetPeerIPKey.String("1.2.3.4"), semconv.NetPeerPortKey.Int(9876), }, }, want: &zkmodel.Endpoint{ IPv4: net.ParseIP("1.2.3.4"), Port: 9876, }, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got := toZipkinRemoteEndpoint(tt.data) if diff := cmp.Diff(got, tt.want); diff != "" { t.Errorf("Diff%v", diff) } }) } } func TestServiceName(t *testing.T) { attrs := []attribute.KeyValue{} assert.Equal(t, defaultServiceName, getServiceName(attrs)) attrs = append(attrs, attribute.String("test_key", "test_value")) assert.Equal(t, defaultServiceName, getServiceName(attrs)) attrs = append(attrs, semconv.ServiceNameKey.String("my_service")) assert.Equal(t, "my_service", getServiceName(attrs)) }
1
15,224
`sdktrace` or `tracesdk`, pick one.
open-telemetry-opentelemetry-go
go
@@ -200,11 +200,7 @@ trait ContentMagicTrait } } - return [ - 'filename' => '', - 'alt' => '', - 'path' => '', - ]; + return []; } /**
1
<?php declare(strict_types=1); namespace Bolt\Entity; use Bolt\Entity\Field\Excerptable; use Bolt\Helpers\Excerpt; use Bolt\Repository\ContentRepository; use Doctrine\Common\Persistence\Mapping\ClassMetadata; use Doctrine\Common\Persistence\ObjectManager; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; use Symfony\Component\Serializer\Annotation\Groups; use Twig_Markup; trait ContentMagicTrait { /** * Set the "Magic properties for automagic population in the API. * * @todo to be removed with proper API implementation */ /** * @Groups("get_content") */ public $magicTitle; /** * @Groups("get_content") */ public $magicExcerpt; /** * @Groups("get_content") */ public $magicImage; /** * @Groups("get_content") */ public $magicLink; /** * @Groups("get_content") */ public $magicEditLink; /** @var ContentRepository */ private $repository; /** @var UrlGeneratorInterface */ private $urlGenerator; /** * Required by ObjectManagerAware interface */ public function injectObjectManager(ObjectManager $objectManager, ClassMetadata $classMetadata): void { $repository = $objectManager->getRepository(self::class); if ($repository instanceof ContentRepository) { $this->repository = $repository; } else { throw new \Exception('Invalid repository for Content'); } } private function getRepository(): ContentRepository { return $this->repository; } public function __toString(): string { return sprintf('Content # %d', $this->getId()); } /** * Magic getter for a record. Will return the field with $name, if it * exists or fall back to the `magicLink`, `magicExcerpt`, etc. methods * if it doesn't. * * - {{ record.title }} => Field named title, fall back to magic title * - {{ record.magic('title') }} => Magic title, no fallback * - {{ record.get('title') }} => Field named title, no fallback * * @return Field|mixed|null */ public function __call(string $name, array $arguments = []) { // Prefer a field with $name foreach ($this->fields as $field) { if ($field->getName() === $name) { return $field instanceof Excerptable ? new Twig_Markup($field, 'UTF-8') : $field; } } // Fall back to a `magicFoo` method return $this->magic($name, $arguments); } private function magic(string $name, array $arguments = []) { $magicName = 'magic' . ucfirst($name); if (method_exists($this, $magicName)) { return $this->{$magicName}(...$arguments); } throw new \RuntimeException(sprintf('Invalid field name or method call on %s: %s', self::class, $name)); } public function get(string $name): ?Field { foreach ($this->fields as $field) { if ($field->getName() === $name) { return $field; } } return null; } public function has(string $name): bool { foreach ($this->fields as $field) { if ($field->getName() === $name) { return true; } } return false; } public function setUrlGenerator(UrlGeneratorInterface $urlGenerator): void { $this->urlGenerator = $urlGenerator; } public function magicLink() { return $this->urlGenerator->generate('record', [ 'slugOrId' => $this->getSlug() ?: $this->getId(), 'contentTypeSlug' => $this->getDefinition()->get('singular_slug'), ]); } public function magicEditLink() { return $this->urlGenerator->generate('bolt_content_edit', ['id' => $this->getId()]); } public function magicTitleFields(): array { $definition = $this->getDefinition(); // First, see if we have a "title format" in the contenttype. if ($definition->has('title_format')) { return (array) $definition->get('title_format'); } // Alternatively, see if we have a field named 'title' or somesuch. $names = ['title', 'name', 'caption', 'subject']; // English $names = array_merge($names, ['titel', 'naam', 'kop', 'onderwerp']); // Dutch $names = array_merge($names, ['nom', 'sujet']); // French $names = array_merge($names, ['nombre', 'sujeto']); // Spanish foreach ($names as $name) { if ($this->get($name)) { return (array) $name; } } // Otherwise, grab the first field of type 'text', and assume that's the title. foreach ($this->getFields() as $field) { if ($field->getType() === 'text') { return [$field->getName()]; } } return []; } public function magicTitle(): string { $titleParts = []; foreach ($this->magicTitleFields() as $field) { $titleParts[] = $this->get($field); } return trim(implode(' ', $titleParts)); } public function magicImage(): array { foreach ($this->getFields() as $field) { if ($field->getDefinition()->get('type') === 'image') { return $field->getValue(); } } return [ 'filename' => '', 'alt' => '', 'path' => '', ]; } /** * @param string|array|null $focus */ public function magicExcerpt(int $length = 150, bool $includeTitle = true, $focus = null): Twig_Markup { $excerpter = new Excerpt($this); $excerpt = $excerpter->getExcerpt($length, $includeTitle, $focus); return new Twig_Markup($excerpt, 'utf-8'); } public function magicPrevious(string $byColumn = 'id', bool $sameContentType = true): ?Content { $byColumn = filter_var($byColumn, FILTER_SANITIZE_STRING); $repository = $this->getRepository(); $contentType = $sameContentType ? $this->getContentType() : null; return $repository->findAdjacentBy($byColumn, 'previous', $this->getId(), $contentType); } public function magicNext(string $byColumn = 'id', bool $sameContentType = true): ?Content { $byColumn = filter_var($byColumn, FILTER_SANITIZE_STRING); $repository = $this->getRepository(); $contentType = $sameContentType ? $this->getContentType() : null; return $repository->findAdjacentBy($byColumn, 'next', $this->getId(), $contentType); } }
1
10,874
can we return null instead?
bolt-core
php
@@ -179,6 +179,12 @@ void exit_event(void) bool success = dr_raw_tls_cfree(tls_offs, NUM_TLS_SLOTS); ASSERT(success); ASSERT(num_lea > 0); +#ifdef UNIX + /* i#2346: delay client threads termination on Windows. */ + dr_fprintf(STDERR, "process is exiting\n"); + dr_event_signal(child_continue); + dr_event_wait(child_dead); +#endif /* DR should have terminated the client thread for us */ dr_event_destroy(child_alive); dr_event_destroy(child_continue);
1
/* ********************************************************** * Copyright (c) 2011-2017 Google, Inc. All rights reserved. * Copyright (c) 2007-2010 VMware, Inc. All rights reserved. * **********************************************************/ /* * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of VMware, Inc. nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ #include "dr_api.h" #include "client_tools.h" #ifdef UNIX # include <sys/time.h> #endif #ifdef WINDOWS # define THREAD_ARG ((void *) dr_get_process_id()) #else /* thread actually has own pid so just using a constant to test arg passing */ # define THREAD_ARG ((void *)37) #endif /* Eventually this routine will test i/o by waiting on a file */ #define MINSERT instrlist_meta_preinsert static uint num_lea = 0; static reg_id_t tls_seg; static uint tls_offs; #define CANARY 0xbadcab42 #define NUM_TLS_SLOTS 4 #ifdef X64 # define ASM_XAX "rax" # define ASM_XDX "rdx" # define ASM_XBP "rbp" # define ASM_XSP "rsp" # define ASM_SEG "gs" #else # define ASM_XAX "eax" # define ASM_XDX "edx" # define ASM_XBP "ebp" # define ASM_XSP "esp" # define ASM_SEG "fs" #endif static void *child_alive; static void *child_continue; static void *child_dead; static bool nops_matched; #ifdef UNIX /* test PR 368737: add client timer support */ static void event_timer(void *drcontext, dr_mcontext_t *mcontext) { dr_fprintf(STDERR, "event_timer fired\n"); if (!dr_set_itimer(ITIMER_REAL, 0, event_timer)) dr_fprintf(STDERR, "unable to disable timer\n"); } #endif static void thread_func(void *arg) { /* FIXME: should really test corner cases: do raw system calls, etc. to * ensure we're treating it as a true native thread */ ASSERT(arg == THREAD_ARG); dr_fprintf(STDERR, "client thread is alive\n"); dr_event_signal(child_alive); #ifdef UNIX if (!dr_set_itimer(ITIMER_REAL, 10, event_timer)) dr_fprintf(STDERR, "unable to set timer callback\n"); dr_sleep(30); #endif dr_event_wait(child_continue); dr_fprintf(STDERR, "client thread is dying\n"); dr_event_signal(child_dead); } static void at_lea(uint opc, app_pc tag) { /* PR 223285: test (one side of) DR_ASSERT for something we know will succeed * (we don't want msgboxes in regressions) */ DR_ASSERT(opc == OP_lea); ASSERT((process_id_t)(ptr_uint_t) dr_get_tls_field(dr_get_current_drcontext()) == dr_get_process_id() + 1 /*we added 1 inline*/); dr_set_tls_field(dr_get_current_drcontext(), (void *)(ptr_uint_t) dr_get_process_id()); num_lea++; /* FIXME: should do some fp ops and really test the fp state preservation */ } static dr_emit_flags_t bb_event(void *drcontext, void *tag, instrlist_t *bb, bool for_trace, bool translating) { instr_t *instr, *next_instr; int num_nops = 0; bool in_nops = false; for (instr = instrlist_first(bb); instr != NULL; instr = next_instr) { next_instr = instr_get_next(instr); if (instr_get_opcode(instr) == OP_lea) { /* PR 200411: test inline tls access by adding 1 */ dr_save_reg(drcontext, bb, instr, REG_XAX, SPILL_SLOT_1); dr_insert_read_tls_field(drcontext, bb, instr, REG_XAX); instrlist_meta_preinsert(bb, instr, INSTR_CREATE_lea (drcontext, opnd_create_reg(REG_XAX), opnd_create_base_disp(REG_XAX, REG_NULL, 0, 1, OPSZ_lea))); dr_insert_write_tls_field(drcontext, bb, instr, REG_XAX); dr_restore_reg(drcontext, bb, instr, REG_XAX, SPILL_SLOT_1); dr_insert_clean_call(drcontext, bb, instr, at_lea, true/*save fp*/, 2, OPND_CREATE_INT32(instr_get_opcode(instr)), OPND_CREATE_INTPTR(tag)); } if (instr_get_opcode(instr) == OP_nop) { if (!in_nops) { in_nops = true; num_nops = 1; } else num_nops++; } else in_nops = false; } if (num_nops == 17 && !nops_matched) { /* PR 210591: test transparency by having client create a thread after * app has loaded a library and ensure its DllMain is not notified */ bool success; nops_matched = true; /* reset cond vars */ dr_event_reset(child_alive); dr_event_reset(child_continue); dr_event_reset(child_dead); dr_fprintf(STDERR, "PR 210591: testing client transparency\n"); success = dr_create_client_thread(thread_func, THREAD_ARG); ASSERT(success); dr_event_wait(child_alive); /* We leave the client thread alive until the app exits, to test i#1489 */ #ifdef UNIX dr_sleep(30); /* ensure we get an alarm */ #endif } return DR_EMIT_DEFAULT; } void exit_event(void) { bool success = dr_raw_tls_cfree(tls_offs, NUM_TLS_SLOTS); ASSERT(success); ASSERT(num_lea > 0); /* DR should have terminated the client thread for us */ dr_event_destroy(child_alive); dr_event_destroy(child_continue); dr_event_destroy(child_dead); } static bool str_eq(const char *s1, const char *s2) { if (s1 == NULL || s2 == NULL) return false; while (*s1 == *s2) { if (*s1 == '\0') return true; s1++; s2++; } return false; } static void thread_init_event(void *drcontext) { int i; dr_set_tls_field(drcontext, (void *)(ptr_uint_t) dr_get_process_id()); for (i = 0; i < NUM_TLS_SLOTS; i++) { int idx = tls_offs + i*sizeof(void*); ptr_uint_t val = (ptr_uint_t) (CANARY+i); #ifdef WINDOWS IF_X64_ELSE(__writegsqword,__writefsdword)(idx, val); #else asm("mov %0, %%"ASM_XAX: : "m"((val)) : ASM_XAX); asm("mov %0, %%edx" : : "m"((idx)) : ASM_XDX); asm("mov %%"ASM_XAX", %%"ASM_SEG":(%%"ASM_XDX")" : : : ASM_XAX, ASM_XDX); #endif } } static void thread_exit_event(void *drcontext) { int i; instrlist_t *ilist = instrlist_create(drcontext); dr_insert_read_raw_tls(drcontext, ilist, NULL, tls_seg, tls_offs, DR_REG_START_GPR); ASSERT(opnd_same(dr_raw_tls_opnd(drcontext, tls_seg, tls_offs), instr_get_src(instrlist_first(ilist), 0))); instrlist_clear_and_destroy(drcontext, ilist); for (i = 0; i < NUM_TLS_SLOTS; i++) { int idx = tls_offs + i*sizeof(void*); ptr_uint_t val; #ifdef WINDOWS val = IF_X64_ELSE(__readgsqword,__readfsdword)(idx); #else asm("mov %0, %%eax": : "m"((idx)) : ASM_XAX); asm("mov %%"ASM_SEG":(%%"ASM_XAX"), %%"ASM_XAX : : : ASM_XAX); asm("mov %%"ASM_XAX", %0" : "=m"((val)) : : ASM_XAX); #endif dr_fprintf(STDERR, "TLS slot %d is "PFX"\n", i, val); } } DR_EXPORT void dr_client_main(client_id_t id, int argc, const char *argv[]) { bool success; /* PR 216931: client options */ const char * ops = dr_get_options(id); dr_fprintf(STDERR, "PR 216931: client options are %s\n", ops); ASSERT(str_eq(ops, "-paramx -paramy")); ASSERT(argc == 3 && str_eq(argv[1], "-paramx") && str_eq(argv[2], "-paramy")); dr_register_bb_event(bb_event); dr_register_exit_event(exit_event); dr_register_thread_init_event(thread_init_event); dr_register_thread_exit_event(thread_exit_event); /* i#108: client raw TLS */ success = dr_raw_tls_calloc(&tls_seg, &tls_offs, NUM_TLS_SLOTS, 0); ASSERT(success); ASSERT(tls_seg == IF_X64_ELSE(SEG_GS, SEG_FS)); /* PR 219381: dr_get_application_name() and dr_get_process_id() */ #ifdef WINDOWS dr_fprintf(STDERR, "inside app %s\n", dr_get_application_name()); #else /* UNIX - append .exe so can use same expect file. */ dr_fprintf(STDERR, "inside app %s.exe\n", dr_get_application_name()); #endif { /* test PR 198871: client locks are all at same rank */ void *lock1 = dr_mutex_create(); void *lock2 = dr_mutex_create(); dr_mutex_lock(lock1); dr_mutex_lock(lock2); dr_fprintf(STDERR, "PR 198871 locking test..."); dr_mutex_unlock(lock2); dr_mutex_unlock(lock1); dr_mutex_destroy(lock1); dr_mutex_destroy(lock2); dr_fprintf(STDERR, "...passed\n"); } child_alive = dr_event_create(); child_continue = dr_event_create(); child_dead = dr_event_create(); /* PR 222812: start up and shut down a client thread */ success = dr_create_client_thread(thread_func, THREAD_ARG); ASSERT(success); dr_event_wait(child_alive); dr_event_signal(child_continue); dr_event_wait(child_dead); dr_fprintf(STDERR, "PR 222812: client thread test passed\n"); }
1
11,378
You mean XXX and "we should" or "NYI" or sthg. Maybe put it on the ifdef line.
DynamoRIO-dynamorio
c
@@ -25,3 +25,17 @@ func (w literalLoggable) GetValue(key string) string { return w.strings[key] } func (w literalLoggable) GetValueAsInt64Slice(key string) []int64 { return w.int64s[key] } func (w literalLoggable) ReadSerialPortLogs() []string { return w.serials } + +// SingleImageImportLoggable returns a Loggable that is pre-initialized with the metadata +// fields that are relevant when importing a single image file. +func SingleImageImportLoggable(fileFormat string, sourceSize, resultSize int64, serials []string) Loggable { + loggable := literalLoggable{ + strings: map[string]string{importFileFormat: fileFormat}, + int64s: map[string][]int64{ + sourceSizeGb: {sourceSize}, + targetSizeGb: {resultSize}, + }, + serials: serials, + } + return loggable +}
1
// Copyright 2020 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package service type literalLoggable struct { strings map[string]string int64s map[string][]int64 serials []string } func (w literalLoggable) GetValue(key string) string { return w.strings[key] } func (w literalLoggable) GetValueAsInt64Slice(key string) []int64 { return w.int64s[key] } func (w literalLoggable) ReadSerialPortLogs() []string { return w.serials }
1
10,980
minor: can be in-lined in return
GoogleCloudPlatform-compute-image-tools
go
@@ -14,7 +14,7 @@ module RSpec::Core::Formatters it "prints a message if provided, ignoring other data" do formatter.deprecation(:message => "this message", :deprecated => "x", :replacement => "y", :call_site => "z") deprecation_stream.rewind - expect(deprecation_stream.read).to eq "this message" + expect(deprecation_stream.read).to eq "this message\n" end it "includes the method" do
1
require 'spec_helper' require 'rspec/core/formatters/deprecation_formatter' require 'tempfile' module RSpec::Core::Formatters describe DeprecationFormatter do describe "#deprecation" do let(:formatter) { DeprecationFormatter.new(deprecation_stream, summary_stream) } let(:summary_stream) { StringIO.new } context "with a File deprecation_stream" do let(:deprecation_stream) { File.open("#{Dir.tmpdir}/deprecation_summary_example_output", "w+") } it "prints a message if provided, ignoring other data" do formatter.deprecation(:message => "this message", :deprecated => "x", :replacement => "y", :call_site => "z") deprecation_stream.rewind expect(deprecation_stream.read).to eq "this message" end it "includes the method" do formatter.deprecation(:deprecated => "i_am_deprecated") deprecation_stream.rewind expect(deprecation_stream.read).to match(/i_am_deprecated is deprecated/) end it "includes the replacement" do formatter.deprecation(:replacement => "use_me") deprecation_stream.rewind expect(deprecation_stream.read).to match(/Use use_me instead/) end it "includes the call site if provided" do formatter.deprecation(:call_site => "somewhere") deprecation_stream.rewind expect(deprecation_stream.read).to match(/Called from somewhere/) end end context "with an IO deprecation stream" do let(:deprecation_stream) { StringIO.new } it "prints nothing" do 5.times { formatter.deprecation(:deprecated => 'i_am_deprecated') } expect(deprecation_stream.string).to eq "" end end end describe "#deprecation_summary" do let(:formatter) { DeprecationFormatter.new(deprecation_stream, summary_stream) } let(:summary_stream) { StringIO.new } context "with a File deprecation_stream" do let(:deprecation_stream) { File.open("#{Dir.tmpdir}/deprecation_summary_example_output", "w") } it "prints a count of the deprecations" do formatter.deprecation(:deprecated => 'i_am_deprecated') formatter.deprecation_summary expect(summary_stream.string).to match(/1 deprecation logged to .*deprecation_summary_example_output/) end it "pluralizes the reported deprecation count for more than one deprecation" do formatter.deprecation(:deprecated => 'i_am_deprecated') formatter.deprecation(:deprecated => 'i_am_deprecated_also') formatter.deprecation_summary expect(summary_stream.string).to match(/2 deprecations/) end it "is not printed when there are no deprecations" do formatter.deprecation_summary expect(summary_stream.string).to eq "" end end context "with an IO deprecation_stream" do let(:deprecation_stream) { StringIO.new } it "limits the deprecation warnings after 3 calls" do 5.times { formatter.deprecation(:deprecated => 'i_am_deprecated') } formatter.deprecation_summary expected = <<-EOS.gsub(/^ {12}/, '') \nDeprecation Warnings: i_am_deprecated is deprecated. i_am_deprecated is deprecated. i_am_deprecated is deprecated. Too many uses of deprecated 'i_am_deprecated'. Set config.deprecation_stream to a File for full output. EOS expect(deprecation_stream.string).to eq expected end it "prints the true deprecation count to the summary_stream" do 5.times { formatter.deprecation(:deprecated => 'i_am_deprecated') } formatter.deprecation_summary expect(summary_stream.string).to match(/5 deprecation warnings total/) end end end end end
1
10,728
why the additional "\n"?
rspec-rspec-core
rb
@@ -183,7 +183,7 @@ func (s *streamTable) Do(f func(flux.ColReader) error) error { if err := f(s.first); err != nil { s.first.Release() s.first = nil - return nil + return err } s.first.Release() s.first = nil
1
package table import ( "context" "sync/atomic" "github.com/apache/arrow/go/arrow/array" "github.com/influxdata/flux" "github.com/influxdata/flux/arrow" "github.com/influxdata/flux/codes" "github.com/influxdata/flux/internal/errors" ) // SendFunc is used to send a flux.ColReader to a table stream so // it can be read by the table consumer. type SendFunc func(flux.ColReader) // StreamWriter is the input end of a stream. type StreamWriter struct { ctx context.Context key flux.GroupKey cols []flux.ColMeta ch chan<- streamBuffer } func (s *StreamWriter) Key() flux.GroupKey { return s.key } func (s *StreamWriter) Cols() []flux.ColMeta { return s.cols } // Write will write a new buffer to the stream using the given values. // The group key and columns will be used for the emitted column reader. func (s *StreamWriter) Write(vs []array.Interface) error { return s.write(vs, true) } // UnsafeWrite will write the new buffer to the stream without validating // that the resulting table is valid. This can be used to avoid the small // performance hit that comes from validating the resulting table. func (s *StreamWriter) UnsafeWrite(vs []array.Interface) error { return s.write(vs, false) } func (s *StreamWriter) write(vs []array.Interface, validate bool) error { cr := &arrow.TableBuffer{ GroupKey: s.key, Columns: s.cols, Values: vs, } if validate { if err := cr.Validate(); err != nil { cr.Release() return err } } return s.UnsafeWriteBuffer(cr) } // UnsafeWriteBuffer will emit the given column reader to the stream. // This does not validate that the column reader matches with the // stream schema. func (s *StreamWriter) UnsafeWriteBuffer(cr flux.ColReader) error { // Discard column readers with length zero. if cr.Len() == 0 { cr.Release() return nil } select { case s.ch <- streamBuffer{cr: cr}: return nil case <-s.ctx.Done(): // We could not send the column reader because this was cancelled. cr.Release() return s.ctx.Err() } } // Stream will call StreamWithContext with a background context. func Stream(key flux.GroupKey, cols []flux.ColMeta, f func(ctx context.Context, w *StreamWriter) error) (flux.Table, error) { return StreamWithContext(context.Background(), key, cols, f) } // StreamWithContext will create a table that streams column readers // through the flux.Table. This method will return only after // the function buffers the first column reader. // This first column reader is used to identify the group key // and columns for the entire table stream. // // Implementors using this *must* return at least one table. // If the function returns without returning at least one table, // then an error will be returned. If the first table that is returned // is empty, then this will return an empty table and further buffers // will not be used. func StreamWithContext(ctx context.Context, key flux.GroupKey, cols []flux.ColMeta, f func(ctx context.Context, w *StreamWriter) error) (flux.Table, error) { ctx, cancel := context.WithCancel(ctx) ch := make(chan streamBuffer) // Create the stream input. s := &StreamWriter{ ctx: ctx, key: key, cols: cols, ch: ch, } done := make(chan struct{}) go func() { defer close(done) defer close(ch) if err := f(ctx, s); err != nil && err != context.Canceled { ch <- streamBuffer{err: err} } }() select { case sp := <-ch: cr, err := sp.cr, sp.err if err != nil { cancel() return nil, err } // If no table was received, set empty to true. empty := cr == nil return &streamTable{ first: cr, key: key, cols: cols, cancel: cancel, ch: ch, done: done, empty: empty, }, nil case <-ctx.Done(): cancel() return nil, ctx.Err() } } // streamBuffer is a column reader or error sent // from the streaming function. type streamBuffer struct { cr flux.ColReader err error } // streamTable is an implementation of flux.Table // that will stream buffers from a column reader. type streamTable struct { used int32 first flux.ColReader key flux.GroupKey cols []flux.ColMeta cancel func() ch <-chan streamBuffer done <-chan struct{} empty bool } func (s *streamTable) Key() flux.GroupKey { return s.key } func (s *streamTable) Cols() []flux.ColMeta { return s.cols } func (s *streamTable) Do(f func(flux.ColReader) error) error { if !atomic.CompareAndSwapInt32(&s.used, 0, 1) { return errors.New(codes.Internal, "table already read") } // Ensure that we always call cancel to free any resources from // the context after we have completely read the channel. defer s.cancel() // If the table is empty, return immediately. // We already released the column reader. if s.empty { return nil } // Act on the first column reader that was read. if err := f(s.first); err != nil { s.first.Release() s.first = nil return nil } s.first.Release() s.first = nil for sp := range s.ch { cr, err := sp.cr, sp.err if err != nil { return err } if err := f(cr); err != nil { cr.Release() return err } cr.Release() } // Allow the stream function to exit. <-s.done return nil } func (s *streamTable) Done() { if atomic.CompareAndSwapInt32(&s.used, 0, 1) { if s.first != nil { s.first.Release() s.first = nil } s.cancel() } // Wait for the stream function to exit before we return. <-s.done } func (s *streamTable) Empty() bool { return s.empty } // IsDone is used to allow the tests to access internal parts // of the table structure for the table tests. // This method can only be used by asserting that it exists // through an anonymous interface. This should not be used // outside of testing code because there is no guarantee // on the safety of this method. func (s *streamTable) IsDone() bool { return s.empty || atomic.LoadInt32(&s.used) != 0 }
1
14,558
This seems to be a big omission. If the first buffer reports an error, stream seems to just discard it.
influxdata-flux
go
@@ -180,9 +180,7 @@ func MakeFull(log logging.Logger, rootDir string, cfg config.Local, phonebookDir return nil, err } - blockListeners := []ledger.BlockListener{ - node, - } + blockListeners := []ledger.BlockListener{} if node.config.EnableTopAccountsReporting { blockListeners = append(blockListeners, &accountListener)
1
// Copyright (C) 2019 Algorand, Inc. // This file is part of go-algorand // // go-algorand is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // go-algorand is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with go-algorand. If not, see <https://www.gnu.org/licenses/>. // Package node is the Algorand node itself, with functions exposed to the frontend package node import ( "context" "fmt" "io/ioutil" "os" "path/filepath" "time" "github.com/algorand/go-algorand/agreement" "github.com/algorand/go-algorand/agreement/gossip" "github.com/algorand/go-algorand/catchup" "github.com/algorand/go-algorand/config" "github.com/algorand/go-algorand/crypto" "github.com/algorand/go-algorand/data" "github.com/algorand/go-algorand/data/account" "github.com/algorand/go-algorand/data/basics" "github.com/algorand/go-algorand/data/bookkeeping" "github.com/algorand/go-algorand/data/pools" "github.com/algorand/go-algorand/data/transactions" "github.com/algorand/go-algorand/data/transactions/verify" "github.com/algorand/go-algorand/ledger" "github.com/algorand/go-algorand/logging" "github.com/algorand/go-algorand/network" "github.com/algorand/go-algorand/node/indexer" "github.com/algorand/go-algorand/protocol" "github.com/algorand/go-algorand/rpcs" "github.com/algorand/go-algorand/util/db" "github.com/algorand/go-algorand/util/execpool" "github.com/algorand/go-algorand/util/metrics" "github.com/algorand/go-algorand/util/timers" "github.com/algorand/go-deadlock" ) const participationKeyCheckSecs = 60 // StatusReport represents the current basic status of the node type StatusReport struct { LastRound basics.Round LastVersion protocol.ConsensusVersion NextVersion protocol.ConsensusVersion NextVersionRound basics.Round NextVersionSupported bool LastRoundTimestamp time.Time SynchronizingTime time.Duration CatchupTime time.Duration HasSyncedSinceStartup bool } // TimeSinceLastRound returns the time since the last block was approved (locally), or 0 if no blocks seen func (status StatusReport) TimeSinceLastRound() time.Duration { if status.LastRoundTimestamp.IsZero() { return time.Duration(0) } return time.Since(status.LastRoundTimestamp) } // AlgorandFullNode specifies and implements a full Algorand node. type AlgorandFullNode struct { nodeContextData mu deadlock.Mutex ctx context.Context cancelCtx context.CancelFunc config config.Local ledger *data.Ledger net network.GossipNode phonebook *network.ThreadsafePhonebook transactionPool *pools.TransactionPool txHandler *data.TxHandler accountManager *data.AccountManager feeTracker *pools.FeeTracker algorandService *agreement.Service syncer *catchup.Service indexer *indexer.Indexer rootDir string genesisID string genesisHash crypto.Digest log logging.Logger lastRoundTimestamp time.Time hasSyncedSinceStartup bool txPoolSyncer *rpcs.TxSyncer cryptoPool execpool.ExecutionPool lowPriorityCryptoVerificationPool execpool.BacklogPool highPriorityCryptoVerificationPool execpool.BacklogPool ledgerService *rpcs.LedgerService wsFetcherService *rpcs.WsFetcherService // to handle inbound gossip msgs for fetching over gossip oldKeyDeletionNotify chan struct{} } // TxnWithStatus represents information about a single transaction, // in particular, whether it has appeared in some block yet or not, // and whether it was kicked out of the txpool due to some error. type TxnWithStatus struct { Txn transactions.SignedTxn // Zero indicates no confirmation ConfirmedRound basics.Round // PoolError indicates that the transaction was kicked out of this // node's transaction pool (and specifies why that happened). An // empty string indicates the transaction wasn't kicked out of this // node's txpool due to an error. PoolError string // ApplyData is the transaction.ApplyData, if committed. ApplyData transactions.ApplyData } // MakeFull sets up an Algorand full node // (i.e., it returns a node that participates in consensus) func MakeFull(log logging.Logger, rootDir string, cfg config.Local, phonebookDir string, genesis bookkeeping.Genesis) (*AlgorandFullNode, error) { node := new(AlgorandFullNode) node.rootDir = rootDir node.config = cfg node.log = log.With("name", cfg.NetAddress) node.genesisID = genesis.ID() node.genesisHash = crypto.HashObj(genesis) node.phonebook = network.MakeThreadsafePhonebook() addrs, err := config.LoadPhonebook(phonebookDir) if err != nil { log.Debugf("Cannot load static phonebook: %v", err) } node.phonebook.ReplacePeerList(addrs) // tie network, block fetcher, and agreement services together p2pNode, err := network.NewWebsocketNetwork(node.log, node.config, node.phonebook, genesis.ID(), genesis.Network) if err != nil { log.Errorf("could not create websocket node: %v", err) return nil, err } p2pNode.SetPrioScheme(node) node.net = p2pNode node.accountManager = data.MakeAccountManager(log) accountListener := makeTopAccountListener(log) // load stored data genesisDir := filepath.Join(rootDir, genesis.ID()) ledgerPathnamePrefix := filepath.Join(genesisDir, config.LedgerFilenamePrefix) // create initial ledger, if it doesn't exist os.Mkdir(genesisDir, 0700) var genalloc data.GenesisBalances genalloc, err = bootstrapData(genesis, log) if err != nil { log.Errorf("Cannot load genesis allocation: %v", err) return nil, err } blockListeners := []ledger.BlockListener{ node, } if node.config.EnableTopAccountsReporting { blockListeners = append(blockListeners, &accountListener) } node.cryptoPool = execpool.MakePool(node) node.lowPriorityCryptoVerificationPool = execpool.MakeBacklog(node.cryptoPool, 2*node.cryptoPool.GetParallelism(), execpool.LowPriority, node) node.highPriorityCryptoVerificationPool = execpool.MakeBacklog(node.cryptoPool, 2*node.cryptoPool.GetParallelism(), execpool.HighPriority, node) node.ledger, err = data.LoadLedger(node.log, ledgerPathnamePrefix, false, genesis.Proto, genalloc, node.genesisID, node.genesisHash, blockListeners, cfg.Archival) if err != nil { log.Errorf("Cannot initialize ledger (%s): %v", ledgerPathnamePrefix, err) return nil, err } node.transactionPool = pools.MakeTransactionPool(node.ledger.Ledger, cfg) node.ledger.RegisterBlockListeners([]ledger.BlockListener{node.transactionPool}) node.txHandler = data.MakeTxHandler(node.transactionPool, node.ledger, node.net, node.genesisID, node.genesisHash, node.lowPriorityCryptoVerificationPool) node.feeTracker, err = pools.MakeFeeTracker() if err != nil { log.Error(err) return nil, err } // Indexer setup if cfg.IsIndexerActive && cfg.Archival { node.indexer, err = indexer.MakeIndexer(genesisDir, node.ledger, false) if err != nil { logging.Base().Errorf("failed to make indexer - %v", err) return nil, err } } node.ledgerService = rpcs.RegisterLedgerService(cfg, node.ledger, p2pNode, node.genesisID) node.wsFetcherService = rpcs.RegisterWsFetcherService(node.log, p2pNode) rpcs.RegisterTxService(node.transactionPool, p2pNode, node.genesisID, cfg.TxPoolSize, cfg.TxSyncServeResponseSize) crashPathname := filepath.Join(genesisDir, config.CrashFilename) crashAccess, err := db.MakeAccessor(crashPathname, false, false) if err != nil { log.Errorf("Cannot load crash data: %v", err) return nil, err } blockFactory := makeBlockFactory(node.ledger, node.transactionPool, node.config.EnableProcessBlockStats, node.highPriorityCryptoVerificationPool) blockValidator := blockValidatorImpl{l: node.ledger, tp: node.transactionPool, verificationPool: node.highPriorityCryptoVerificationPool} agreementLedger := agreementLedger{Ledger: node.ledger, ff: rpcs.MakeNetworkFetcherFactory(node.net, blockQueryPeerLimit, node.wsFetcherService), n: node.net} agreementParameters := agreement.Parameters{ Logger: log, Accessor: crashAccess, Clock: timers.MakeMonotonicClock(time.Now()), Local: node.config, Network: gossip.WrapNetwork(node.net), Ledger: agreementLedger, BlockFactory: blockFactory, BlockValidator: blockValidator, KeyManager: node.accountManager, RandomSource: node, BacklogPool: node.highPriorityCryptoVerificationPool, } node.algorandService = agreement.MakeService(agreementParameters) node.syncer = catchup.MakeService(node.log, node.config, p2pNode, node.ledger, node.wsFetcherService, blockAuthenticatorImpl{Ledger: node.ledger, AsyncVoteVerifier: agreement.MakeAsyncVoteVerifier(node.lowPriorityCryptoVerificationPool)}) node.txPoolSyncer = rpcs.MakeTxSyncer(node.transactionPool, node.net, node.txHandler.SolicitedTxHandler(), time.Duration(cfg.TxSyncIntervalSeconds)*time.Second, time.Duration(cfg.TxSyncTimeoutSeconds)*time.Second, cfg.TxSyncServeResponseSize) err = node.loadParticipationKeys() if err != nil { log.Errorf("Cannot load participation keys: %v", err) return nil, err } node.oldKeyDeletionNotify = make(chan struct{}, 1) return node, err } func bootstrapData(genesis bookkeeping.Genesis, log logging.Logger) (data.GenesisBalances, error) { genalloc := make(map[basics.Address]basics.AccountData) for _, entry := range genesis.Allocation { addr, err := basics.UnmarshalChecksumAddress(entry.Address) if err != nil { log.Errorf("Cannot parse genesis addr %s: %v", entry.Address, err) return data.GenesisBalances{}, err } _, present := genalloc[addr] if present { err = fmt.Errorf("repeated allocation to %s", entry.Address) log.Error(err) return data.GenesisBalances{}, err } genalloc[addr] = entry.State } feeSink, err := basics.UnmarshalChecksumAddress(genesis.FeeSink) if err != nil { log.Errorf("Cannot parse fee sink addr %s: %v", genesis.FeeSink, err) return data.GenesisBalances{}, err } rewardsPool, err := basics.UnmarshalChecksumAddress(genesis.RewardsPool) if err != nil { log.Errorf("Cannot parse rewards pool addr %s: %v", genesis.RewardsPool, err) return data.GenesisBalances{}, err } return data.MakeTimestampedGenesisBalances(genalloc, feeSink, rewardsPool, genesis.Timestamp), nil } // Config returns a copy of the node's Local configuration func (node *AlgorandFullNode) Config() config.Local { return node.config } // Start the node: connect to peers and run the agreement service while obtaining a lock. Doesn't wait for initial sync. func (node *AlgorandFullNode) Start() { node.mu.Lock() defer node.mu.Unlock() // start accepting connections node.net.Start() node.config.NetAddress, _ = node.net.Address() node.syncer.Start() node.algorandService.Start() node.txPoolSyncer.Start(node.syncer.InitialSyncDone) node.ledgerService.Start() node.txHandler.Start() // Set up a context we can use to cancel goroutines on Stop() ctx, cancel := context.WithCancel(context.Background()) node.ctx = ctx node.cancelCtx = cancel // start indexer if idx, err := node.Indexer(); err == nil { err := idx.Start() if err != nil { node.log.Errorf("indexer failed to start, turning it off - %v", err) node.config.IsIndexerActive = false } node.log.Info("Indexer was started successfully") } else { node.log.Infof("Indexer is not available - %v", err) } // Periodically check for new participation keys go node.checkForParticipationKeys() go node.txPoolGaugeThread() // Delete old participation keys go node.oldKeyDeletionThread() // TODO re-enable with configuration flag post V1 //go logging.UsageLogThread(node.ctx, node.log, 100*time.Millisecond, nil) } // ListeningAddress retrieves the node's current listening address, if any. // Returns true if currently listening, false otherwise. func (node *AlgorandFullNode) ListeningAddress() (string, bool) { node.mu.Lock() defer node.mu.Unlock() return node.net.Address() } // Stop stops running the node. Once a node is closed, it can never start again. func (node *AlgorandFullNode) Stop() { node.mu.Lock() defer node.mu.Unlock() node.net.ClearHandlers() node.txHandler.Stop() node.net.Stop() node.algorandService.Shutdown() node.syncer.Stop() node.txPoolSyncer.Stop() node.ledgerService.Stop() node.highPriorityCryptoVerificationPool.Shutdown() node.lowPriorityCryptoVerificationPool.Shutdown() node.cryptoPool.Shutdown() node.cancelCtx() if node.indexer != nil { node.indexer.Shutdown() } } // note: unlike the other two functions, this accepts a whole filename func (node *AlgorandFullNode) getExistingPartHandle(filename string) (db.Accessor, error) { filename = filepath.Join(node.rootDir, node.genesisID, filename) _, err := os.Stat(filename) if err == nil { return db.MakeErasableAccessor(filename) } return db.Accessor{}, err } // Ledger exposes the node's ledger handle to the algod API code func (node *AlgorandFullNode) Ledger() *data.Ledger { return node.ledger } // BroadcastSignedTxGroup broadcasts a transaction group that has already been signed. func (node *AlgorandFullNode) BroadcastSignedTxGroup(txgroup []transactions.SignedTxn) error { lastRound := node.ledger.Latest() b, err := node.ledger.BlockHdr(lastRound) if err != nil { node.log.Errorf("could not get block header from last round %v: %v", lastRound, err) } spec := transactions.SpecialAddresses{ FeeSink: b.FeeSink, RewardsPool: b.RewardsPool, } proto := config.Consensus[b.CurrentProtocol] for _, tx := range txgroup { err = verify.Txn(&tx, spec, proto) if err != nil { node.log.Warnf("malformed transaction: %v - transaction was %+v", err, tx) return err } } err = node.transactionPool.Remember(txgroup) if err != nil { node.log.Infof("rejected by local pool: %v - transaction group was %+v", err, txgroup) return err } var enc []byte var txids []transactions.Txid for _, tx := range txgroup { enc = append(enc, protocol.Encode(tx)...) txids = append(txids, tx.ID()) } err = node.net.Broadcast(context.TODO(), protocol.TxnTag, enc, true, nil) if err != nil { node.log.Infof("failure broadcasting transaction to network: %v - transaction group was %+v", err, txgroup) return err } node.log.Infof("Sent signed tx group with IDs %v", txids) return nil } // ListTxns returns SignedTxns associated with a specific account in a range of Rounds (inclusive). // TxnWithStatus returns the round in which a particular transaction appeared, // since that information is not part of the SignedTxn itself. func (node *AlgorandFullNode) ListTxns(addr basics.Address, minRound basics.Round, maxRound basics.Round) ([]TxnWithStatus, error) { result := make([]TxnWithStatus, 0) for r := minRound; r <= maxRound; r++ { h, err := node.ledger.AddressTxns(addr, r) if err != nil { return nil, err } for _, tx := range h { result = append(result, TxnWithStatus{ Txn: tx.SignedTxn, ConfirmedRound: r, ApplyData: tx.ApplyData, }) } } return result, nil } // GetTransaction looks for the required txID within with a specific account withing a range of rounds (inclusive) and // returns the SignedTxn and true iff it finds the transaction. func (node *AlgorandFullNode) GetTransaction(addr basics.Address, txID transactions.Txid, minRound basics.Round, maxRound basics.Round) (TxnWithStatus, bool) { // start with the most recent round, and work backwards: // this will abort early if it hits pruned rounds if maxRound < minRound { return TxnWithStatus{}, false } r := maxRound for { h, err := node.ledger.AddressTxns(addr, r) if err != nil { return TxnWithStatus{}, false } for _, tx := range h { if tx.ID() == txID { return TxnWithStatus{ Txn: tx.SignedTxn, ConfirmedRound: r, ApplyData: tx.ApplyData, }, true } } if r == minRound { break } r-- } return TxnWithStatus{}, false } // GetPendingTransaction looks for the required txID in the recent ledger // blocks, in the txpool, and in the txpool's status cache. It returns // the SignedTxn (with status information), and a bool to indicate if the // transaction was found. func (node *AlgorandFullNode) GetPendingTransaction(txID transactions.Txid) (res TxnWithStatus, found bool) { // We need to check both the pool and the ledger's blocks. // If the transaction is found in a committed block, that // takes precedence. But we check the pool first, because // otherwise there could be a race between the pool and the // ledger, where the block wasn't in the ledger at first, // but by the time we check the pool, it's not there either // because it committed. // The default return value is found=false, which is // appropriate if the transaction isn't found anywhere. // Check if it's in the pool or evicted from the pool. tx, txErr, found := node.transactionPool.Lookup(txID) if found { res = TxnWithStatus{ Txn: tx, ConfirmedRound: 0, PoolError: txErr, } found = true // Keep looking in the ledger.. } var maxLife basics.Round latest := node.ledger.Latest() proto, err := node.ledger.ConsensusParams(latest) if err == nil { maxLife = basics.Round(proto.MaxTxnLife) } else { node.log.Errorf("node.GetPendingTransaction: cannot get consensus params for latest round %v", latest) } maxRound := latest minRound := maxRound.SubSaturate(maxLife) for r := minRound; r <= maxRound; r++ { tx, found, err := node.ledger.LookupTxid(txID, r) if err != nil || !found { continue } return TxnWithStatus{ Txn: tx.SignedTxn, ConfirmedRound: r, ApplyData: tx.ApplyData, }, true } // Return whatever we found in the pool (if anything). return } // Status returns a StatusReport structure reporting our status as Active and with our ledger's LastRound func (node *AlgorandFullNode) Status() (s StatusReport, err error) { s.LastRound = node.ledger.Latest() b, err := node.ledger.BlockHdr(s.LastRound) if err != nil { return } node.mu.Lock() defer node.mu.Unlock() s.LastVersion = b.CurrentProtocol s.NextVersion, s.NextVersionRound, s.NextVersionSupported = b.NextVersionInfo() s.SynchronizingTime = node.syncer.SynchronizingTime() s.LastRoundTimestamp = node.lastRoundTimestamp s.CatchupTime = node.syncer.SynchronizingTime() s.HasSyncedSinceStartup = node.hasSyncedSinceStartup return } // GenesisID returns the ID of the genesis node. func (node *AlgorandFullNode) GenesisID() string { node.mu.Lock() defer node.mu.Unlock() return node.genesisID } // GenesisHash returns the hash of the genesis configuration. func (node *AlgorandFullNode) GenesisHash() crypto.Digest { node.mu.Lock() defer node.mu.Unlock() return node.genesisHash } // PoolStats returns a PoolStatus structure reporting stats about the transaction pool func (node *AlgorandFullNode) PoolStats() PoolStats { r := node.ledger.Latest() last, err := node.ledger.Block(r) if err != nil { node.log.Warnf("AlgorandFullNode: could not read ledger's last round: %v", err) return PoolStats{} } return PoolStats{ NumConfirmed: uint64(len(last.Payset)), NumOutstanding: uint64(node.transactionPool.PendingCount()), NumExpired: uint64(node.transactionPool.NumExpired(r)), } } // ExtendPeerList dynamically adds a peer to a node's peer list. func (node *AlgorandFullNode) ExtendPeerList(peers ...string) { node.phonebook.ExtendPeerList(peers) } // ReplacePeerList replaces the current peer list with a different one func (node *AlgorandFullNode) ReplacePeerList(peers ...string) { node.phonebook.ReplacePeerList(peers) } // SuggestedFee returns the suggested fee per byte recommended to ensure a new transaction is processed in a timely fashion. // Caller should set fee to max(MinTxnFee, SuggestedFee() * len(encoded SignedTxn)) func (node *AlgorandFullNode) SuggestedFee() basics.MicroAlgos { return node.feeTracker.EstimateFee() } // GetPendingTxnsFromPool returns a snapshot of every pending transactions from the node's transaction pool in a slice. // Transactions are sorted in decreasing order. If no transactions, returns an empty slice. func (node *AlgorandFullNode) GetPendingTxnsFromPool() ([]transactions.SignedTxn, error) { return bookkeeping.SignedTxnGroupsFlatten(node.transactionPool.Pending()), nil } // Reload participation keys from disk periodically func (node *AlgorandFullNode) checkForParticipationKeys() { ticker := time.NewTicker(participationKeyCheckSecs * time.Second) for { select { case <-ticker.C: node.loadParticipationKeys() case <-node.ctx.Done(): ticker.Stop() return } } } func (node *AlgorandFullNode) loadParticipationKeys() error { // Generate a list of all potential participation key files genesisDir := filepath.Join(node.rootDir, node.genesisID) files, err := ioutil.ReadDir(genesisDir) if err != nil { return fmt.Errorf("AlgorandFullNode.loadPartitipationKeys: could not read directory %v: %v", genesisDir, err) } // For each of these files for _, info := range files { // If it can't be a participation key database, skip it if !config.IsPartKeyFilename(info.Name()) { continue } filename := info.Name() // Fetch a handle to this database handle, err := node.getExistingPartHandle(filename) if err != nil { return fmt.Errorf("AlgorandFullNode.loadParticipationKeys: cannot load db %v: %v", filename, err) } // Fetch an account.Participation from the database part, err := account.RestoreParticipation(handle) if err != nil { handle.Close() if err == account.ErrUnsupportedSchema { node.log.Infof("Loaded participation keys from storage: %s %s", part.Address(), info.Name()) msg := fmt.Sprintf("loadParticipationKeys: not loading unsupported participation key: %v; renaming to *.old", info.Name()) fmt.Println(msg) node.log.Warn(msg) fullname := filepath.Join(genesisDir, info.Name()) os.Rename(fullname, filepath.Join(fullname, ".old")) } else { return fmt.Errorf("AlgorandFullNode.loadParticipationKeys: cannot load account at %v: %v", info.Name(), err) } } else { // Tell the AccountManager about the Participation (dupes don't matter) added := node.accountManager.AddParticipation(part) if added { node.log.Infof("Loaded participation keys from storage: %s %s", part.Address(), info.Name()) } else { part.Close() } } } return nil } func (node *AlgorandFullNode) txPoolGaugeThread() { txPoolGuage := metrics.MakeGauge(metrics.MetricName{Name: "algod_tx_pool_count", Description: "current number of available transactions in pool"}) ticker := time.NewTicker(10 * time.Second) defer ticker.Stop() for true { select { case <-ticker.C: txPoolGuage.Set(float64(node.transactionPool.PendingCount()), nil) case <-node.ctx.Done(): return } } } // IsArchival returns true the node is an archival node, false otherwise func (node *AlgorandFullNode) IsArchival() bool { return node.config.Archival } // OnNewBlock implements the BlockListener interface so we're notified after each block is written to the ledger func (node *AlgorandFullNode) OnNewBlock(block bookkeeping.Block) { node.mu.Lock() defer node.mu.Unlock() node.lastRoundTimestamp = time.Now() node.hasSyncedSinceStartup = true // Wake up oldKeyDeletionThread(), non-blocking. select { case node.oldKeyDeletionNotify <- struct{}{}: default: } // Update fee tracker node.feeTracker.ProcessBlock(block) } // oldKeyDeletionThread keeps deleting old participation keys. // It runs in a separate thread so that, during catchup, we // don't have to delete key for each block we received. func (node *AlgorandFullNode) oldKeyDeletionThread() { for { select { case <-node.ctx.Done(): return case <-node.oldKeyDeletionNotify: } r := node.ledger.Latest() // We need to find the consensus protocol used to agree on block r, // since that determines the params used for ephemeral keys in block // r. The params come from agreement.ParamsRound(r), which is r-2. hdr, err := node.ledger.BlockHdr(agreement.ParamsRound(r)) if err != nil { switch err.(type) { case ledger.ErrNoEntry: // No need to warn; expected during catchup. default: node.log.Warnf("Cannot look up block %d for deleting ephemeral keys: %v", agreement.ParamsRound(r), err) } } else { proto := config.Consensus[hdr.CurrentProtocol] node.mu.Lock() node.accountManager.DeleteOldKeys(r+1, proto) node.mu.Unlock() } } } // Uint64 implements the randomness by calling the crypto library. func (node *AlgorandFullNode) Uint64() uint64 { return crypto.RandUint64() } // Indexer returns a pointer to nodes indexer func (node *AlgorandFullNode) Indexer() (*indexer.Indexer, error) { if node.indexer != nil && node.config.IsIndexerActive { return node.indexer, nil } return nil, fmt.Errorf("indexer is not active") } // GetTransactionByID gets transaction by ID func (node *AlgorandFullNode) GetTransactionByID(txid transactions.Txid, rnd basics.Round) (TxnWithStatus, error) { stx, _, err := node.ledger.LookupTxid(txid, rnd) if err != nil { return TxnWithStatus{}, err } return TxnWithStatus{ Txn: stx.SignedTxn, ConfirmedRound: rnd, ApplyData: stx.ApplyData, }, nil }
1
36,643
Maybe move this one down too?
algorand-go-algorand
go
@@ -1,12 +1,12 @@ -using Datadog.Trace.Logging; +using Datadog.Trace.Logging; namespace Datadog.Trace { internal class AsyncLocalScopeManager { - private static ILog _log = LogProvider.For<AsyncLocalScopeManager>(); + private static readonly ILog _log = LogProvider.For<AsyncLocalScopeManager>(); - private AsyncLocalCompat<Scope> _currentSpan = new AsyncLocalCompat<Scope>(); + private readonly AsyncLocalCompat<Scope> _currentSpan = new AsyncLocalCompat<Scope>(); public Scope Active => _currentSpan.Get();
1
using Datadog.Trace.Logging; namespace Datadog.Trace { internal class AsyncLocalScopeManager { private static ILog _log = LogProvider.For<AsyncLocalScopeManager>(); private AsyncLocalCompat<Scope> _currentSpan = new AsyncLocalCompat<Scope>(); public Scope Active => _currentSpan.Get(); public Scope Activate(Span span, bool finishOnClose = true) { var current = _currentSpan.Get(); var scope = new Scope(current, span, this, finishOnClose); _currentSpan.Set(scope); return scope; } public void Close(Scope scope) { var current = _currentSpan.Get(); if (current == null) { _log.Error("Trying to close a null scope"); } if (current != scope) { _log.Warn("Current span doesn't match desactivated span"); } _currentSpan.Set(current.Parent); } } }
1
14,604
We do this in lots of places I'm starting to notice...typically you'd avoid taking concrete dependencies, but we also avoid package dependencies as well which makes sense (i.e. not using an IoC, etc.). Any reason we don't implement some form of poor-man's DI and/or a simple factory instead of new-ing things up everywhere. This may be a simple example (as I'm guessing this is likely the only place this is ever or ever will be used), but separating them doesn't take any more time/effort either really.
DataDog-dd-trace-dotnet
.cs
@@ -77,8 +77,13 @@ func Errf(format string, a ...interface{}) DError { } // wrapErrf returns a DError by keeping errors type and replacing original error message. -func wrapErrf(e DError, format string, a ...interface{}) DError { - return &dErrImpl{errs: []error{fmt.Errorf(format, a...)}, errsType: e.errorsType(), anonymizedErrs: []string{format}} +func wrapErrf(e DError, formatPrefix string, a ...interface{}) DError { + f := formatPrefix + strings.Join(e.AnonymizedErrs(), "; ") + return &dErrImpl{ + errs: []error{fmt.Errorf(fmt.Sprintf(formatPrefix, a...) + e.Error())}, + errsType: e.errorsType(), + anonymizedErrs: []string{f}, + } } // newErr returns a DError. newErr is used to wrap another error as a DError.
1
// Copyright 2017 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package daisy import ( "fmt" "strings" ) const ( untypedError = "" multiError = "MultiError" fileIOError = "FileIOError" resourceDNEError = "ResourceDoesNotExist" imageObsoleteDeletedError = "ImageObsoleteOrDeleted" apiError = "APIError" apiError404 = "APIError404" ) // DError is a Daisy external error type. // It has: // - optional error typing // - multiple error aggregation // - safe error messages in which privacy information is removed // // Default implementation: // The default DError implementation is flat, DError.add(anotherDErr) will merge the two dErrs // into a single, flat DError instead of making anotherDErr a child to DError. type DError interface { error // add shouldn't be called directly, instead call addErrs(DError, error). // This assists with nil dErrs. addErrs(nil, e) will return a new DError. add(error) etype() string errors() []error errorsType() []string AnonymizedErrs() []string CausedByErrType(t string) bool } // addErrs adds an error to a DError. // The DError can be nil. If both the DError and errors are nil, a nil DError is returned. // If DError is nil, but errors are not nil, a new DError is instantiated, the errors are added, // and the new DError is returned. // Any nil error in errs is disregarded. Therefore, `var e DError; e = addErrs(e, nil)` // preserves e's nil-ness. func addErrs(e DError, errs ...error) DError { for _, err := range errs { if err != nil { if e == nil { e = &dErrImpl{} } e.add(err) } } return e } // Errf returns a DError by constructing error message with given format. func Errf(format string, a ...interface{}) DError { return newErr(format, fmt.Errorf(format, a...)) } // wrapErrf returns a DError by keeping errors type and replacing original error message. func wrapErrf(e DError, format string, a ...interface{}) DError { return &dErrImpl{errs: []error{fmt.Errorf(format, a...)}, errsType: e.errorsType(), anonymizedErrs: []string{format}} } // newErr returns a DError. newErr is used to wrap another error as a DError. // If e is already a DError, e is copied and returned. // If e is a normal error, anonymizedErrMsg is used to hide privacy info. // If e is nil, nil is returned. func newErr(anonymizedErrMsg string, e error) DError { if e == nil { return nil } if dE, ok := e.(*dErrImpl); ok { return dE } return &dErrImpl{errs: []error{e}, errsType: []string{""}, anonymizedErrs: []string{anonymizedErrMsg}} } // ToDError returns a DError. ToDError is used to wrap another error as a DError. // If e is already a DError, e is copied and returned. // If e is a normal error, error message is reused as format. // If e is nil, nil is returned. func ToDError(e error) DError { if e == nil { return nil } if dE, ok := e.(*dErrImpl); ok { return dE } return &dErrImpl{errs: []error{e}, errsType: []string{""}, anonymizedErrs: []string{e.Error()}} } func typedErr(errType string, safeErrMsg string, e error) DError { if e == nil { return nil } safeErrMsg = fmt.Sprintf("%v: %v", errType, safeErrMsg) dE := newErr(safeErrMsg, e) dE.(*dErrImpl).errsType = []string{errType} return dE } func typedErrf(errType, format string, a ...interface{}) DError { return typedErr(errType, format, fmt.Errorf(format, a...)) } type dErrImpl struct { errs []error errsType []string anonymizedErrs []string } func (e *dErrImpl) add(err error) { if e2, ok := err.(*dErrImpl); ok { e.merge(e2) } else if !ok { // This is some other error type. Add it. e.errs = append(e.errs, err) e.errsType = append(e.errsType, "") } } func (e *dErrImpl) Error() string { if e.len() == 0 { return "" } if e.len() == 1 { errStr := e.errs[0].Error() if len(e.errsType) == 1 && e.errsType[0] != "" { return fmt.Sprintf("%s: %s", e.errsType[0], errStr) } return errStr } // Multiple error handling. pre := "* " lines := make([]string, e.len()) for i, err := range e.errs { lines[i] = pre + err.Error() } return "Multiple errors:\n" + strings.Join(lines, "\n") } func (e *dErrImpl) AnonymizedErrs() []string { return e.anonymizedErrs } func (e *dErrImpl) len() int { return len(e.errs) } func (e *dErrImpl) merge(e2 *dErrImpl) { if e2.len() > 0 { e.errs = append(e.errs, e2.errs...) e.errsType = append(e.errsType, e2.errsType...) e.anonymizedErrs = append(e.anonymizedErrs, e2.anonymizedErrs...) } } func (e *dErrImpl) etype() string { if e.len() > 1 { return multiError } else if e.len() == 1 && len(e.errsType) == 1 { return e.errsType[0] } else { return "" } } func (e *dErrImpl) errorsType() []string { return e.errsType } func (e *dErrImpl) errors() []error { return e.errs } func (e *dErrImpl) CausedByErrType(t string) bool { for _, et := range e.errsType { if et == t { return true } } return false }
1
10,134
What if formatPrefix doesn't include a space? Will the resulting error have e.Error() stuck at the end without any space?
GoogleCloudPlatform-compute-image-tools
go
@@ -2,6 +2,8 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +// Package pushsync provides the pushsync protocol +// implementation. package pushsync import (
1
// Copyright 2020 The Swarm Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package pushsync import ( "context" "errors" "fmt" "time" "github.com/ethersphere/bee/pkg/accounting" "github.com/ethersphere/bee/pkg/content" "github.com/ethersphere/bee/pkg/logging" "github.com/ethersphere/bee/pkg/p2p" "github.com/ethersphere/bee/pkg/p2p/protobuf" "github.com/ethersphere/bee/pkg/pushsync/pb" "github.com/ethersphere/bee/pkg/soc" "github.com/ethersphere/bee/pkg/storage" "github.com/ethersphere/bee/pkg/swarm" "github.com/ethersphere/bee/pkg/tags" "github.com/ethersphere/bee/pkg/topology" "github.com/ethersphere/bee/pkg/tracing" opentracing "github.com/opentracing/opentracing-go" ) const ( protocolName = "pushsync" protocolVersion = "1.0.0" streamName = "pushsync" ) const ( maxPeers = 5 ) type PushSyncer interface { PushChunkToClosest(ctx context.Context, ch swarm.Chunk) (*Receipt, error) } type Receipt struct { Address swarm.Address } type PushSync struct { streamer p2p.StreamerDisconnecter storer storage.Putter peerSuggester topology.ClosestPeerer tagger *tags.Tags unwrap func(swarm.Chunk) logger logging.Logger accounting accounting.Interface pricer accounting.Pricer metrics metrics tracer *tracing.Tracer } var timeToWaitForReceipt = 3 * time.Second // time to wait to get a receipt for a chunk func New(streamer p2p.StreamerDisconnecter, storer storage.Putter, closestPeerer topology.ClosestPeerer, tagger *tags.Tags, unwrap func(swarm.Chunk), logger logging.Logger, accounting accounting.Interface, pricer accounting.Pricer, tracer *tracing.Tracer) *PushSync { ps := &PushSync{ streamer: streamer, storer: storer, peerSuggester: closestPeerer, tagger: tagger, unwrap: unwrap, logger: logger, accounting: accounting, pricer: pricer, metrics: newMetrics(), tracer: tracer, } return ps } func (s *PushSync) Protocol() p2p.ProtocolSpec { return p2p.ProtocolSpec{ Name: protocolName, Version: protocolVersion, StreamSpecs: []p2p.StreamSpec{ { Name: streamName, Handler: s.handler, }, }, } } // handler handles chunk delivery from other node and forwards to its destination node. // If the current node is the destination, it stores in the local store and sends a receipt. func (ps *PushSync) handler(ctx context.Context, p p2p.Peer, stream p2p.Stream) (err error) { w, r := protobuf.NewWriterAndReader(stream) defer func() { if err != nil { ps.metrics.TotalErrors.Inc() _ = stream.Reset() } else { _ = stream.FullClose() } }() var ch pb.Delivery if err = r.ReadMsgWithContext(ctx, &ch); err != nil { return fmt.Errorf("pushsync read delivery: %w", err) } ps.metrics.TotalReceived.Inc() chunk := swarm.NewChunk(swarm.NewAddress(ch.Address), ch.Data) if content.Valid(chunk) { if ps.unwrap != nil { go ps.unwrap(chunk) } } else { if !soc.Valid(chunk) { return swarm.ErrInvalidChunk } } span, _, ctx := ps.tracer.StartSpanFromContext(ctx, "pushsync-handler", ps.logger, opentracing.Tag{Key: "address", Value: chunk.Address().String()}) defer span.Finish() // Select the closest peer to forward the chunk peer, err := ps.peerSuggester.ClosestPeer(chunk.Address()) if err != nil { // If i am the closest peer then store the chunk and send receipt if errors.Is(err, topology.ErrWantSelf) { return ps.handleDeliveryResponse(ctx, w, p, chunk) } return err } // This is a special situation in that the other peer thinks thats we are the closest node // and we think that the sending peer is the closest if p.Address.Equal(peer) { return ps.handleDeliveryResponse(ctx, w, p, chunk) } // compute the price we pay for this receipt and reserve it for the rest of this function receiptPrice := ps.pricer.PeerPrice(peer, chunk.Address()) err = ps.accounting.Reserve(ctx, peer, receiptPrice) if err != nil { return fmt.Errorf("reserve balance for peer %s: %w", peer.String(), err) } defer ps.accounting.Release(peer, receiptPrice) // Forward chunk to closest peer streamer, err := ps.streamer.NewStream(ctx, peer, nil, protocolName, protocolVersion, streamName) if err != nil { return fmt.Errorf("new stream peer %s: %w", peer.String(), err) } defer func() { if err != nil { _ = streamer.Reset() } else { go streamer.FullClose() } }() wc, rc := protobuf.NewWriterAndReader(streamer) if err := ps.sendChunkDelivery(ctx, wc, chunk); err != nil { return fmt.Errorf("forward chunk to peer %s: %w", peer.String(), err) } receipt, err := ps.receiveReceipt(ctx, rc) if err != nil { return fmt.Errorf("receive receipt from peer %s: %w", peer.String(), err) } // Check if the receipt is valid if !chunk.Address().Equal(swarm.NewAddress(receipt.Address)) { return fmt.Errorf("invalid receipt from peer %s", peer.String()) } err = ps.accounting.Credit(peer, receiptPrice) if err != nil { return err } // pass back the received receipt in the previously received stream err = ps.sendReceipt(ctx, w, &receipt) if err != nil { return fmt.Errorf("send receipt to peer %s: %w", peer.String(), err) } return ps.accounting.Debit(p.Address, ps.pricer.Price(chunk.Address())) } func (ps *PushSync) sendChunkDelivery(ctx context.Context, w protobuf.Writer, chunk swarm.Chunk) (err error) { ctx, cancel := context.WithTimeout(ctx, timeToWaitForReceipt) defer cancel() return w.WriteMsgWithContext(ctx, &pb.Delivery{ Address: chunk.Address().Bytes(), Data: chunk.Data(), }) } func (ps *PushSync) sendReceipt(ctx context.Context, w protobuf.Writer, receipt *pb.Receipt) (err error) { ctx, cancel := context.WithTimeout(ctx, timeToWaitForReceipt) defer cancel() if err := w.WriteMsgWithContext(ctx, receipt); err != nil { return err } return nil } func (ps *PushSync) receiveReceipt(ctx context.Context, r protobuf.Reader) (receipt pb.Receipt, err error) { ctx, cancel := context.WithTimeout(ctx, timeToWaitForReceipt) defer cancel() if err := r.ReadMsgWithContext(ctx, &receipt); err != nil { return receipt, err } return receipt, nil } // PushChunkToClosest sends chunk to the closest peer by opening a stream. It then waits for // a receipt from that peer and returns error or nil based on the receiving and // the validity of the receipt. func (ps *PushSync) PushChunkToClosest(ctx context.Context, ch swarm.Chunk) (*Receipt, error) { span, _, ctx := ps.tracer.StartSpanFromContext(ctx, "pushsync-push", ps.logger, opentracing.Tag{Key: "address", Value: ch.Address().String()}) defer span.Finish() var ( skipPeers []swarm.Address lastErr error ) deferFuncs := make([]func(), 0) defersFn := func() { if len(deferFuncs) > 0 { for _, deferFn := range deferFuncs { deferFn() } deferFuncs = deferFuncs[:0] } } defer defersFn() for i := 0; i < maxPeers; i++ { select { case <-ctx.Done(): return nil, ctx.Err() default: } defersFn() // find next closes peer peer, err := ps.peerSuggester.ClosestPeer(ch.Address(), skipPeers...) if err != nil { if errors.Is(err, topology.ErrNotFound) { // NOTE: needed for tests skipPeers = append(skipPeers, peer) continue } if errors.Is(err, topology.ErrWantSelf) { // this is to make sure that the sent number does not diverge from the synced counter t, err := ps.tagger.Get(ch.TagID()) if err == nil && t != nil { err = t.Inc(tags.StateSent) if err != nil { return nil, err } } // if you are the closest node return a receipt immediately return &Receipt{ Address: ch.Address(), }, nil } return nil, fmt.Errorf("closest peer: %w", err) } // save found peer (to be skipped if there is some error with him) skipPeers = append(skipPeers, peer) // compute the price we pay for this receipt and reserve it for the rest of this function receiptPrice := ps.pricer.PeerPrice(peer, ch.Address()) err = ps.accounting.Reserve(ctx, peer, receiptPrice) if err != nil { return nil, fmt.Errorf("reserve balance for peer %s: %w", peer.String(), err) } deferFuncs = append(deferFuncs, func() { ps.accounting.Release(peer, receiptPrice) }) streamer, err := ps.streamer.NewStream(ctx, peer, nil, protocolName, protocolVersion, streamName) if err != nil { ps.metrics.TotalErrors.Inc() lastErr = fmt.Errorf("new stream for peer %s: %w", peer.String(), err) ps.logger.Debugf("pushsync-push: %v", lastErr) continue } deferFuncs = append(deferFuncs, func() { go streamer.FullClose() }) w, r := protobuf.NewWriterAndReader(streamer) if err := ps.sendChunkDelivery(ctx, w, ch); err != nil { ps.metrics.TotalErrors.Inc() _ = streamer.Reset() lastErr = fmt.Errorf("chunk %s deliver to peer %s: %w", ch.Address().String(), peer.String(), err) ps.logger.Debugf("pushsync-push: %v", lastErr) continue } ps.metrics.TotalSent.Inc() // if you manage to get a tag, just increment the respective counter t, err := ps.tagger.Get(ch.TagID()) if err == nil && t != nil { err = t.Inc(tags.StateSent) if err != nil { return nil, err } } receipt, err := ps.receiveReceipt(ctx, r) if err != nil { ps.metrics.TotalErrors.Inc() _ = streamer.Reset() lastErr = fmt.Errorf("chunk %s receive receipt from peer %s: %w", ch.Address().String(), peer.String(), err) ps.logger.Debugf("pushsync-push: %v", lastErr) continue } // Check if the receipt is valid if !ch.Address().Equal(swarm.NewAddress(receipt.Address)) { _ = streamer.Reset() return nil, fmt.Errorf("invalid receipt. peer %s", peer.String()) } err = ps.accounting.Credit(peer, receiptPrice) if err != nil { return nil, err } rec := &Receipt{ Address: swarm.NewAddress(receipt.Address), } return rec, nil } ps.logger.Tracef("pushsync-push: failed to push chunk %s: reached max peers of %v", ch.Address(), maxPeers) if lastErr != nil { return nil, lastErr } return nil, topology.ErrNotFound } func (ps *PushSync) handleDeliveryResponse(ctx context.Context, w protobuf.Writer, p p2p.Peer, chunk swarm.Chunk) error { // Store the chunk in the local store _, err := ps.storer.Put(ctx, storage.ModePutSync, chunk) if err != nil { return fmt.Errorf("chunk store: %w", err) } // Send a receipt immediately once the storage of the chunk is successfully receipt := &pb.Receipt{Address: chunk.Address().Bytes()} err = ps.sendReceipt(ctx, w, receipt) if err != nil { return fmt.Errorf("send receipt to peer %s: %w", p.Address.String(), err) } err = ps.accounting.Debit(p.Address, ps.pricer.Price(chunk.Address())) if err != nil { return err } return nil }
1
13,698
that doesn't say a lot to me. Can you please be more specific on the function of pushsync?
ethersphere-bee
go
@@ -1602,6 +1602,15 @@ bool CoreChecks::ValidatePipelineUnlocked(const PIPELINE_STATE *pPipeline, uint3 } } } + if (subpass_desc->pDepthStencilAttachment->layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL) { + if (pPipeline->graphicsPipelineCI.pDepthStencilState->depthWriteEnable == VK_TRUE) { + skip |= LogError( + device, "VUID-VkGraphicsPipelineCreateInfo-subpass-04890", + "vkCreateGraphicsPipelines(): pCreateInfo[%" PRIu32 + "]: subpass uses read-only depth aspect layout, but pDepthStencilState->depthWriteEnable is VK_TRUE.", + pipelineIndex); + } + } } // If subpass uses color attachments, pColorBlendState must be valid pointer
1
/* Copyright (c) 2015-2021 The Khronos Group Inc. * Copyright (c) 2015-2021 Valve Corporation * Copyright (c) 2015-2021 LunarG, Inc. * Copyright (C) 2015-2021 Google Inc. * Modifications Copyright (C) 2020-2021 Advanced Micro Devices, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Author: Cody Northrop <[email protected]> * Author: Michael Lentine <[email protected]> * Author: Tobin Ehlis <[email protected]> * Author: Chia-I Wu <[email protected]> * Author: Chris Forbes <[email protected]> * Author: Mark Lobodzinski <[email protected]> * Author: Ian Elliott <[email protected]> * Author: Dave Houlton <[email protected]> * Author: Dustin Graves <[email protected]> * Author: Jeremy Hayes <[email protected]> * Author: Jon Ashburn <[email protected]> * Author: Karl Schultz <[email protected]> * Author: Mark Young <[email protected]> * Author: Mike Schuchardt <[email protected]> * Author: Mike Weiblen <[email protected]> * Author: Tony Barbour <[email protected]> * Author: John Zulauf <[email protected]> * Author: Shannon McPherson <[email protected]> * Author: Jeremy Kniager <[email protected]> * Author: Tobias Hector <[email protected]> * Author: Jeremy Gebben <[email protected]> */ #include <algorithm> #include <array> #include <assert.h> #include <cmath> #include <fstream> #include <iostream> #include <list> #include <map> #include <memory> #include <mutex> #include <set> #include <sstream> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <string> #include <valarray> #include "vk_loader_platform.h" #include "vk_enum_string_helper.h" #include "chassis.h" #include "convert_to_renderpass2.h" #include "core_validation.h" #include "buffer_validation.h" #include "shader_validation.h" #include "vk_layer_utils.h" #include "sync_utils.h" #include "sync_vuid_maps.h" // these templates are defined in buffer_validation.cpp so we need to pull in the explicit instantiations from there extern template void CoreChecks::TransitionImageLayouts(CMD_BUFFER_STATE *cb_state, uint32_t barrier_count, const VkImageMemoryBarrier *barrier); extern template void CoreChecks::TransitionImageLayouts(CMD_BUFFER_STATE *cb_state, uint32_t barrier_count, const VkImageMemoryBarrier2KHR *barrier); extern template bool CoreChecks::ValidateImageBarrierAttachment(const Location &loc, CMD_BUFFER_STATE const *cb_state, const FRAMEBUFFER_STATE *framebuffer, uint32_t active_subpass, const safe_VkSubpassDescription2 &sub_desc, const VkRenderPass rp_handle, const VkImageMemoryBarrier &img_barrier, const CMD_BUFFER_STATE *primary_cb_state) const; extern template bool CoreChecks::ValidateImageBarrierAttachment(const Location &loc, CMD_BUFFER_STATE const *cb_state, const FRAMEBUFFER_STATE *framebuffer, uint32_t active_subpass, const safe_VkSubpassDescription2 &sub_desc, const VkRenderPass rp_handle, const VkImageMemoryBarrier2KHR &img_barrier, const CMD_BUFFER_STATE *primary_cb_state) const; using std::max; using std::string; using std::stringstream; using std::unique_ptr; using std::vector; void CoreChecks::AddInitialLayoutintoImageLayoutMap(const IMAGE_STATE &image_state, GlobalImageLayoutMap &image_layout_map) { auto *range_map = GetLayoutRangeMap(image_layout_map, image_state); auto range_gen = subresource_adapter::RangeGenerator(image_state.subresource_encoder, image_state.full_range); for (; range_gen->non_empty(); ++range_gen) { range_map->insert(range_map->end(), std::make_pair(*range_gen, image_state.createInfo.initialLayout)); } } // Override base class, we have some extra work to do here void CoreChecks::InitDeviceValidationObject(bool add_obj, ValidationObject *inst_obj, ValidationObject *dev_obj) { if (add_obj) { ValidationStateTracker::InitDeviceValidationObject(add_obj, inst_obj, dev_obj); } } // For given mem object, verify that it is not null or UNBOUND, if it is, report error. Return skip value. template <typename T1> bool CoreChecks::VerifyBoundMemoryIsValid(const DEVICE_MEMORY_STATE *mem_state, const T1 object, const VulkanTypedHandle &typed_handle, const char *api_name, const char *error_code) const { return VerifyBoundMemoryIsValid<T1, SimpleErrorLocation>(mem_state, object, typed_handle, {api_name, error_code}); } template <typename T1, typename LocType> bool CoreChecks::VerifyBoundMemoryIsValid(const DEVICE_MEMORY_STATE *mem_state, const T1 object, const VulkanTypedHandle &typed_handle, const LocType &location) const { bool result = false; auto type_name = object_string[typed_handle.type]; if (!mem_state) { result |= LogError(object, location.Vuid(), "%s: %s used with no memory bound. Memory should be bound by calling vkBind%sMemory().", location.FuncName(), report_data->FormatHandle(typed_handle).c_str(), type_name + 2); } else if (mem_state->Destroyed()) { result |= LogError(object, location.Vuid(), "%s: %s used with no memory bound and previously bound memory was freed. Memory must not be freed " "prior to this operation.", location.FuncName(), report_data->FormatHandle(typed_handle).c_str()); } return result; } // Check to see if memory was ever bound to this image bool CoreChecks::ValidateMemoryIsBoundToImage(const IMAGE_STATE *image_state, const Location &loc) const { using LocationAdapter = core_error::LocationVuidAdapter<sync_vuid_maps::GetImageBarrierVUIDFunctor>; return ValidateMemoryIsBoundToImage<LocationAdapter>(image_state, LocationAdapter(loc, sync_vuid_maps::ImageError::kNoMemory)); } bool CoreChecks::ValidateMemoryIsBoundToImage(const IMAGE_STATE *image_state, const char *api_name, const char *error_code) const { return ValidateMemoryIsBoundToImage<SimpleErrorLocation>(image_state, SimpleErrorLocation(api_name, error_code)); } template <typename LocType> bool CoreChecks::ValidateMemoryIsBoundToImage(const IMAGE_STATE *image_state, const LocType &location) const { bool result = false; if (image_state->create_from_swapchain != VK_NULL_HANDLE) { if (!image_state->bind_swapchain) { LogObjectList objlist(image_state->image()); objlist.add(image_state->create_from_swapchain); result |= LogError( objlist, location.Vuid(), "%s: %s is created by %s, and the image should be bound by calling vkBindImageMemory2(), and the pNext chain " "includes VkBindImageMemorySwapchainInfoKHR.", location.FuncName(), report_data->FormatHandle(image_state->image()).c_str(), report_data->FormatHandle(image_state->create_from_swapchain).c_str()); } else if (image_state->create_from_swapchain != image_state->bind_swapchain->swapchain()) { LogObjectList objlist(image_state->image()); objlist.add(image_state->create_from_swapchain); objlist.add(image_state->bind_swapchain->Handle()); result |= LogError(objlist, location.Vuid(), "%s: %s is created by %s, but the image is bound by %s. The image should be created and bound by the same " "swapchain", location.FuncName(), report_data->FormatHandle(image_state->image()).c_str(), report_data->FormatHandle(image_state->create_from_swapchain).c_str(), report_data->FormatHandle(image_state->bind_swapchain->Handle()).c_str()); } } else if (image_state->IsExternalAHB()) { // TODO look into how to properly check for a valid bound memory for an external AHB } else if (0 == (static_cast<uint32_t>(image_state->createInfo.flags) & VK_IMAGE_CREATE_SPARSE_BINDING_BIT)) { result |= VerifyBoundMemoryIsValid(image_state->MemState(), image_state->image(), image_state->Handle(), location); } return result; } // Check to see if memory was bound to this buffer bool CoreChecks::ValidateMemoryIsBoundToBuffer(const BUFFER_STATE *buffer_state, const char *api_name, const char *error_code) const { bool result = false; if (0 == (static_cast<uint32_t>(buffer_state->createInfo.flags) & VK_BUFFER_CREATE_SPARSE_BINDING_BIT)) { result |= VerifyBoundMemoryIsValid(buffer_state->MemState(), buffer_state->buffer(), buffer_state->Handle(), api_name, error_code); } return result; } // Check to see if memory was bound to this acceleration structure bool CoreChecks::ValidateMemoryIsBoundToAccelerationStructure(const ACCELERATION_STRUCTURE_STATE *as_state, const char *api_name, const char *error_code) const { return VerifyBoundMemoryIsValid(as_state->MemState(), as_state->acceleration_structure(), as_state->Handle(), api_name, error_code); } // Check to see if memory was bound to this acceleration structure bool CoreChecks::ValidateMemoryIsBoundToAccelerationStructure(const ACCELERATION_STRUCTURE_STATE_KHR *as_state, const char *api_name, const char *error_code) const { return VerifyBoundMemoryIsValid(as_state->MemState(), as_state->acceleration_structure(), as_state->Handle(), api_name, error_code); } // Valid usage checks for a call to SetMemBinding(). // For NULL mem case, output warning // Make sure given object is in global object map // IF a previous binding existed, output validation error // Otherwise, add reference from objectInfo to memoryInfo // Add reference off of objInfo // TODO: We may need to refactor or pass in multiple valid usage statements to handle multiple valid usage conditions. bool CoreChecks::ValidateSetMemBinding(VkDeviceMemory mem, const VulkanTypedHandle &typed_handle, const char *apiName) const { bool skip = false; // It's an error to bind an object to NULL memory if (mem != VK_NULL_HANDLE) { const BINDABLE *mem_binding = ValidationStateTracker::GetObjectMemBinding(typed_handle); assert(mem_binding); if (mem_binding->sparse) { const char *error_code = nullptr; const char *handle_type = nullptr; if (typed_handle.type == kVulkanObjectTypeBuffer) { handle_type = "BUFFER"; if (strcmp(apiName, "vkBindBufferMemory()") == 0) { error_code = "VUID-vkBindBufferMemory-buffer-01030"; } else { error_code = "VUID-VkBindBufferMemoryInfo-buffer-01030"; } } else if (typed_handle.type == kVulkanObjectTypeImage) { handle_type = "IMAGE"; if (strcmp(apiName, "vkBindImageMemory()") == 0) { error_code = "VUID-vkBindImageMemory-image-01045"; } else { error_code = "VUID-VkBindImageMemoryInfo-image-01045"; } } else { // Unsupported object type assert(false); } LogObjectList objlist(mem); objlist.add(typed_handle); skip |= LogError(objlist, error_code, "In %s, attempting to bind %s to %s which was created with sparse memory flags " "(VK_%s_CREATE_SPARSE_*_BIT).", apiName, report_data->FormatHandle(mem).c_str(), report_data->FormatHandle(typed_handle).c_str(), handle_type); } const DEVICE_MEMORY_STATE *mem_info = ValidationStateTracker::GetDevMemState(mem); if (mem_info) { const DEVICE_MEMORY_STATE *prev_binding = mem_binding->MemState(); if (prev_binding) { if (!prev_binding->Destroyed()) { const char *error_code = nullptr; if (typed_handle.type == kVulkanObjectTypeBuffer) { if (strcmp(apiName, "vkBindBufferMemory()") == 0) { error_code = "VUID-vkBindBufferMemory-buffer-01029"; } else { error_code = "VUID-VkBindBufferMemoryInfo-buffer-01029"; } } else if (typed_handle.type == kVulkanObjectTypeImage) { if (strcmp(apiName, "vkBindImageMemory()") == 0) { error_code = "VUID-vkBindImageMemory-image-01044"; } else { error_code = "VUID-VkBindImageMemoryInfo-image-01044"; } } else { // Unsupported object type assert(false); } LogObjectList objlist(mem); objlist.add(typed_handle); objlist.add(prev_binding->mem()); skip |= LogError(objlist, error_code, "In %s, attempting to bind %s to %s which has already been bound to %s.", apiName, report_data->FormatHandle(mem).c_str(), report_data->FormatHandle(typed_handle).c_str(), report_data->FormatHandle(prev_binding->mem()).c_str()); } else { LogObjectList objlist(mem); objlist.add(typed_handle); skip |= LogError(objlist, kVUID_Core_MemTrack_RebindObject, "In %s, attempting to bind %s to %s which was previous bound to memory that has " "since been freed. Memory bindings are immutable in " "Vulkan so this attempt to bind to new memory is not allowed.", apiName, report_data->FormatHandle(mem).c_str(), report_data->FormatHandle(typed_handle).c_str()); } } } } return skip; } bool CoreChecks::ValidateDeviceQueueFamily(uint32_t queue_family, const char *cmd_name, const char *parameter_name, const char *error_code, bool optional = false) const { bool skip = false; if (!optional && queue_family == VK_QUEUE_FAMILY_IGNORED) { skip |= LogError(device, error_code, "%s: %s is VK_QUEUE_FAMILY_IGNORED, but it is required to provide a valid queue family index value.", cmd_name, parameter_name); } else if (queue_family_index_set.find(queue_family) == queue_family_index_set.end()) { skip |= LogError(device, error_code, "%s: %s (= %" PRIu32 ") is not one of the queue families given via VkDeviceQueueCreateInfo structures when the device was created.", cmd_name, parameter_name, queue_family); } return skip; } // Validate the specified queue families against the families supported by the physical device that owns this device bool CoreChecks::ValidatePhysicalDeviceQueueFamilies(uint32_t queue_family_count, const uint32_t *queue_families, const char *cmd_name, const char *array_parameter_name, const char *vuid) const { bool skip = false; if (queue_families) { layer_data::unordered_set<uint32_t> set; for (uint32_t i = 0; i < queue_family_count; ++i) { std::string parameter_name = std::string(array_parameter_name) + "[" + std::to_string(i) + "]"; if (set.count(queue_families[i])) { skip |= LogError(device, vuid, "%s: %s (=%" PRIu32 ") is not unique within %s array.", cmd_name, parameter_name.c_str(), queue_families[i], array_parameter_name); } else { set.insert(queue_families[i]); if (queue_families[i] == VK_QUEUE_FAMILY_IGNORED) { skip |= LogError( device, vuid, "%s: %s is VK_QUEUE_FAMILY_IGNORED, but it is required to provide a valid queue family index value.", cmd_name, parameter_name.c_str()); } else if (queue_families[i] >= physical_device_state->queue_family_known_count) { LogObjectList obj_list(physical_device); obj_list.add(device); skip |= LogError(obj_list, vuid, "%s: %s (= %" PRIu32 ") is not one of the queue families supported by the parent PhysicalDevice %s of this device %s.", cmd_name, parameter_name.c_str(), queue_families[i], report_data->FormatHandle(physical_device).c_str(), report_data->FormatHandle(device).c_str()); } } } } return skip; } // Check object status for selected flag state bool CoreChecks::ValidateStatus(const CMD_BUFFER_STATE *pNode, CBStatusFlags status_mask, const char *fail_msg, const char *msg_code) const { if (!(pNode->status & status_mask)) { return LogError(pNode->commandBuffer(), msg_code, "%s: %s.", report_data->FormatHandle(pNode->commandBuffer()).c_str(), fail_msg); } return false; } // Return true if for a given PSO, the given state enum is dynamic, else return false bool CoreChecks::IsDynamic(const PIPELINE_STATE *pPipeline, const VkDynamicState state) const { if (pPipeline && pPipeline->graphicsPipelineCI.pDynamicState) { for (uint32_t i = 0; i < pPipeline->graphicsPipelineCI.pDynamicState->dynamicStateCount; i++) { if (state == pPipeline->graphicsPipelineCI.pDynamicState->pDynamicStates[i]) return true; } } return false; } // Validate state stored as flags at time of draw call bool CoreChecks::ValidateDrawStateFlags(const CMD_BUFFER_STATE *pCB, const PIPELINE_STATE *pPipe, bool indexed, const char *msg_code) const { bool result = false; if (pPipe->topology_at_rasterizer == VK_PRIMITIVE_TOPOLOGY_LINE_LIST || pPipe->topology_at_rasterizer == VK_PRIMITIVE_TOPOLOGY_LINE_STRIP) { result |= ValidateStatus(pCB, CBSTATUS_LINE_WIDTH_SET, "Dynamic line width state not set for this command buffer", msg_code); } if (pPipe->graphicsPipelineCI.pRasterizationState && (pPipe->graphicsPipelineCI.pRasterizationState->depthBiasEnable == VK_TRUE)) { result |= ValidateStatus(pCB, CBSTATUS_DEPTH_BIAS_SET, "Dynamic depth bias state not set for this command buffer", msg_code); } if (pPipe->blendConstantsEnabled) { result |= ValidateStatus(pCB, CBSTATUS_BLEND_CONSTANTS_SET, "Dynamic blend constants state not set for this command buffer", msg_code); } if (pPipe->graphicsPipelineCI.pDepthStencilState && (pPipe->graphicsPipelineCI.pDepthStencilState->depthBoundsTestEnable == VK_TRUE)) { result |= ValidateStatus(pCB, CBSTATUS_DEPTH_BOUNDS_SET, "Dynamic depth bounds state not set for this command buffer", msg_code); } if (pPipe->graphicsPipelineCI.pDepthStencilState && (pPipe->graphicsPipelineCI.pDepthStencilState->stencilTestEnable == VK_TRUE)) { result |= ValidateStatus(pCB, CBSTATUS_STENCIL_READ_MASK_SET, "Dynamic stencil read mask state not set for this command buffer", msg_code); result |= ValidateStatus(pCB, CBSTATUS_STENCIL_WRITE_MASK_SET, "Dynamic stencil write mask state not set for this command buffer", msg_code); result |= ValidateStatus(pCB, CBSTATUS_STENCIL_REFERENCE_SET, "Dynamic stencil reference state not set for this command buffer", msg_code); } if (indexed) { result |= ValidateStatus(pCB, CBSTATUS_INDEX_BUFFER_BOUND, "Index buffer object not bound to this command buffer when Indexed Draw attempted", msg_code); } if (pPipe->topology_at_rasterizer == VK_PRIMITIVE_TOPOLOGY_LINE_LIST || pPipe->topology_at_rasterizer == VK_PRIMITIVE_TOPOLOGY_LINE_STRIP) { const auto *line_state = LvlFindInChain<VkPipelineRasterizationLineStateCreateInfoEXT>(pPipe->graphicsPipelineCI.pRasterizationState->pNext); if (line_state && line_state->stippledLineEnable) { result |= ValidateStatus(pCB, CBSTATUS_LINE_STIPPLE_SET, "Dynamic line stipple state not set for this command buffer", msg_code); } } return result; } bool CoreChecks::LogInvalidAttachmentMessage(const char *type1_string, const RENDER_PASS_STATE *rp1_state, const char *type2_string, const RENDER_PASS_STATE *rp2_state, uint32_t primary_attach, uint32_t secondary_attach, const char *msg, const char *caller, const char *error_code) const { LogObjectList objlist(rp1_state->renderPass()); objlist.add(rp2_state->renderPass()); return LogError(objlist, error_code, "%s: RenderPasses incompatible between %s w/ %s and %s w/ %s Attachment %u is not " "compatible with %u: %s.", caller, type1_string, report_data->FormatHandle(rp1_state->renderPass()).c_str(), type2_string, report_data->FormatHandle(rp2_state->renderPass()).c_str(), primary_attach, secondary_attach, msg); } bool CoreChecks::ValidateAttachmentCompatibility(const char *type1_string, const RENDER_PASS_STATE *rp1_state, const char *type2_string, const RENDER_PASS_STATE *rp2_state, uint32_t primary_attach, uint32_t secondary_attach, const char *caller, const char *error_code) const { bool skip = false; const auto &primary_pass_ci = rp1_state->createInfo; const auto &secondary_pass_ci = rp2_state->createInfo; if (primary_pass_ci.attachmentCount <= primary_attach) { primary_attach = VK_ATTACHMENT_UNUSED; } if (secondary_pass_ci.attachmentCount <= secondary_attach) { secondary_attach = VK_ATTACHMENT_UNUSED; } if (primary_attach == VK_ATTACHMENT_UNUSED && secondary_attach == VK_ATTACHMENT_UNUSED) { return skip; } if (primary_attach == VK_ATTACHMENT_UNUSED) { skip |= LogInvalidAttachmentMessage(type1_string, rp1_state, type2_string, rp2_state, primary_attach, secondary_attach, "The first is unused while the second is not.", caller, error_code); return skip; } if (secondary_attach == VK_ATTACHMENT_UNUSED) { skip |= LogInvalidAttachmentMessage(type1_string, rp1_state, type2_string, rp2_state, primary_attach, secondary_attach, "The second is unused while the first is not.", caller, error_code); return skip; } if (primary_pass_ci.pAttachments[primary_attach].format != secondary_pass_ci.pAttachments[secondary_attach].format) { skip |= LogInvalidAttachmentMessage(type1_string, rp1_state, type2_string, rp2_state, primary_attach, secondary_attach, "They have different formats.", caller, error_code); } if (primary_pass_ci.pAttachments[primary_attach].samples != secondary_pass_ci.pAttachments[secondary_attach].samples) { skip |= LogInvalidAttachmentMessage(type1_string, rp1_state, type2_string, rp2_state, primary_attach, secondary_attach, "They have different samples.", caller, error_code); } if (primary_pass_ci.pAttachments[primary_attach].flags != secondary_pass_ci.pAttachments[secondary_attach].flags) { skip |= LogInvalidAttachmentMessage(type1_string, rp1_state, type2_string, rp2_state, primary_attach, secondary_attach, "They have different flags.", caller, error_code); } return skip; } bool CoreChecks::ValidateSubpassCompatibility(const char *type1_string, const RENDER_PASS_STATE *rp1_state, const char *type2_string, const RENDER_PASS_STATE *rp2_state, const int subpass, const char *caller, const char *error_code) const { bool skip = false; const auto &primary_desc = rp1_state->createInfo.pSubpasses[subpass]; const auto &secondary_desc = rp2_state->createInfo.pSubpasses[subpass]; uint32_t max_input_attachment_count = std::max(primary_desc.inputAttachmentCount, secondary_desc.inputAttachmentCount); for (uint32_t i = 0; i < max_input_attachment_count; ++i) { uint32_t primary_input_attach = VK_ATTACHMENT_UNUSED, secondary_input_attach = VK_ATTACHMENT_UNUSED; if (i < primary_desc.inputAttachmentCount) { primary_input_attach = primary_desc.pInputAttachments[i].attachment; } if (i < secondary_desc.inputAttachmentCount) { secondary_input_attach = secondary_desc.pInputAttachments[i].attachment; } skip |= ValidateAttachmentCompatibility(type1_string, rp1_state, type2_string, rp2_state, primary_input_attach, secondary_input_attach, caller, error_code); } uint32_t max_color_attachment_count = std::max(primary_desc.colorAttachmentCount, secondary_desc.colorAttachmentCount); for (uint32_t i = 0; i < max_color_attachment_count; ++i) { uint32_t primary_color_attach = VK_ATTACHMENT_UNUSED, secondary_color_attach = VK_ATTACHMENT_UNUSED; if (i < primary_desc.colorAttachmentCount) { primary_color_attach = primary_desc.pColorAttachments[i].attachment; } if (i < secondary_desc.colorAttachmentCount) { secondary_color_attach = secondary_desc.pColorAttachments[i].attachment; } skip |= ValidateAttachmentCompatibility(type1_string, rp1_state, type2_string, rp2_state, primary_color_attach, secondary_color_attach, caller, error_code); if (rp1_state->createInfo.subpassCount > 1) { uint32_t primary_resolve_attach = VK_ATTACHMENT_UNUSED, secondary_resolve_attach = VK_ATTACHMENT_UNUSED; if (i < primary_desc.colorAttachmentCount && primary_desc.pResolveAttachments) { primary_resolve_attach = primary_desc.pResolveAttachments[i].attachment; } if (i < secondary_desc.colorAttachmentCount && secondary_desc.pResolveAttachments) { secondary_resolve_attach = secondary_desc.pResolveAttachments[i].attachment; } skip |= ValidateAttachmentCompatibility(type1_string, rp1_state, type2_string, rp2_state, primary_resolve_attach, secondary_resolve_attach, caller, error_code); } } uint32_t primary_depthstencil_attach = VK_ATTACHMENT_UNUSED, secondary_depthstencil_attach = VK_ATTACHMENT_UNUSED; if (primary_desc.pDepthStencilAttachment) { primary_depthstencil_attach = primary_desc.pDepthStencilAttachment[0].attachment; } if (secondary_desc.pDepthStencilAttachment) { secondary_depthstencil_attach = secondary_desc.pDepthStencilAttachment[0].attachment; } skip |= ValidateAttachmentCompatibility(type1_string, rp1_state, type2_string, rp2_state, primary_depthstencil_attach, secondary_depthstencil_attach, caller, error_code); // Both renderpasses must agree on Multiview usage if (primary_desc.viewMask && secondary_desc.viewMask) { if (primary_desc.viewMask != secondary_desc.viewMask) { std::stringstream ss; ss << "For subpass " << subpass << ", they have a different viewMask. The first has view mask " << primary_desc.viewMask << " while the second has view mask " << secondary_desc.viewMask << "."; skip |= LogInvalidPnextMessage(type1_string, rp1_state, type2_string, rp2_state, ss.str().c_str(), caller, error_code); } } else if (primary_desc.viewMask) { skip |= LogInvalidPnextMessage(type1_string, rp1_state, type2_string, rp2_state, "The first uses Multiview (has non-zero viewMasks) while the second one does not.", caller, error_code); } else if (secondary_desc.viewMask) { skip |= LogInvalidPnextMessage(type1_string, rp1_state, type2_string, rp2_state, "The second uses Multiview (has non-zero viewMasks) while the first one does not.", caller, error_code); } return skip; } bool CoreChecks::LogInvalidPnextMessage(const char *type1_string, const RENDER_PASS_STATE *rp1_state, const char *type2_string, const RENDER_PASS_STATE *rp2_state, const char *msg, const char *caller, const char *error_code) const { LogObjectList objlist(rp1_state->renderPass()); objlist.add(rp2_state->renderPass()); return LogError(objlist, error_code, "%s: RenderPasses incompatible between %s w/ %s and %s w/ %s: %s", caller, type1_string, report_data->FormatHandle(rp1_state->renderPass()).c_str(), type2_string, report_data->FormatHandle(rp2_state->renderPass()).c_str(), msg); } // Verify that given renderPass CreateInfo for primary and secondary command buffers are compatible. // This function deals directly with the CreateInfo, there are overloaded versions below that can take the renderPass handle and // will then feed into this function bool CoreChecks::ValidateRenderPassCompatibility(const char *type1_string, const RENDER_PASS_STATE *rp1_state, const char *type2_string, const RENDER_PASS_STATE *rp2_state, const char *caller, const char *error_code) const { bool skip = false; // createInfo flags must be identical for the renderpasses to be compatible. if (rp1_state->createInfo.flags != rp2_state->createInfo.flags) { LogObjectList objlist(rp1_state->renderPass()); objlist.add(rp2_state->renderPass()); skip |= LogError(objlist, error_code, "%s: RenderPasses incompatible between %s w/ %s with flags of %u and %s w/ " "%s with a flags of %u.", caller, type1_string, report_data->FormatHandle(rp1_state->renderPass()).c_str(), rp1_state->createInfo.flags, type2_string, report_data->FormatHandle(rp2_state->renderPass()).c_str(), rp2_state->createInfo.flags); } if (rp1_state->createInfo.subpassCount != rp2_state->createInfo.subpassCount) { LogObjectList objlist(rp1_state->renderPass()); objlist.add(rp2_state->renderPass()); skip |= LogError(objlist, error_code, "%s: RenderPasses incompatible between %s w/ %s with a subpassCount of %u and %s w/ " "%s with a subpassCount of %u.", caller, type1_string, report_data->FormatHandle(rp1_state->renderPass()).c_str(), rp1_state->createInfo.subpassCount, type2_string, report_data->FormatHandle(rp2_state->renderPass()).c_str(), rp2_state->createInfo.subpassCount); } else { for (uint32_t i = 0; i < rp1_state->createInfo.subpassCount; ++i) { skip |= ValidateSubpassCompatibility(type1_string, rp1_state, type2_string, rp2_state, i, caller, error_code); } } // Find an entry of the Fragment Density Map type in the pNext chain, if it exists const auto fdm1 = LvlFindInChain<VkRenderPassFragmentDensityMapCreateInfoEXT>(rp1_state->createInfo.pNext); const auto fdm2 = LvlFindInChain<VkRenderPassFragmentDensityMapCreateInfoEXT>(rp2_state->createInfo.pNext); // Both renderpasses must agree on usage of a Fragment Density Map type if (fdm1 && fdm2) { uint32_t primary_input_attach = fdm1->fragmentDensityMapAttachment.attachment; uint32_t secondary_input_attach = fdm2->fragmentDensityMapAttachment.attachment; skip |= ValidateAttachmentCompatibility(type1_string, rp1_state, type2_string, rp2_state, primary_input_attach, secondary_input_attach, caller, error_code); } else if (fdm1) { skip |= LogInvalidPnextMessage(type1_string, rp1_state, type2_string, rp2_state, "The first uses a Fragment Density Map while the second one does not.", caller, error_code); } else if (fdm2) { skip |= LogInvalidPnextMessage(type1_string, rp1_state, type2_string, rp2_state, "The second uses a Fragment Density Map while the first one does not.", caller, error_code); } return skip; } // For given pipeline, return number of MSAA samples, or one if MSAA disabled static VkSampleCountFlagBits GetNumSamples(PIPELINE_STATE const *pipe) { if (pipe->graphicsPipelineCI.pMultisampleState != NULL && VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO == pipe->graphicsPipelineCI.pMultisampleState->sType) { return pipe->graphicsPipelineCI.pMultisampleState->rasterizationSamples; } return VK_SAMPLE_COUNT_1_BIT; } static void ListBits(std::ostream &s, uint32_t bits) { for (int i = 0; i < 32 && bits; i++) { if (bits & (1 << i)) { s << i; bits &= ~(1 << i); if (bits) { s << ","; } } } } std::string DynamicStateString(CBStatusFlags input_value) { std::string ret; int index = 0; while (input_value) { if (input_value & 1) { if (!ret.empty()) ret.append("|"); ret.append(string_VkDynamicState(ConvertToDynamicState(static_cast<CBStatusFlagBits>(1 << index)))); } ++index; input_value >>= 1; } if (ret.empty()) ret.append(string_VkDynamicState(ConvertToDynamicState(static_cast<CBStatusFlagBits>(0)))); return ret; } // Validate draw-time state related to the PSO bool CoreChecks::ValidatePipelineDrawtimeState(const LAST_BOUND_STATE &state, const CMD_BUFFER_STATE *pCB, CMD_TYPE cmd_type, const PIPELINE_STATE *pPipeline, const char *caller) const { bool skip = false; const auto &current_vtx_bfr_binding_info = pCB->current_vertex_buffer_binding_info.vertex_buffer_bindings; const DrawDispatchVuid vuid = GetDrawDispatchVuid(cmd_type); // Verify vertex & index buffer for unprotected command buffer. // Because vertex & index buffer is read only, it doesn't need to care protected command buffer case. if (enabled_features.core11.protectedMemory == VK_TRUE) { for (const auto &buffer_binding : current_vtx_bfr_binding_info) { if (buffer_binding.buffer_state && !buffer_binding.buffer_state->Destroyed()) { skip |= ValidateProtectedBuffer(pCB, buffer_binding.buffer_state.get(), caller, vuid.unprotected_command_buffer, "Buffer is vertex buffer"); } } if (pCB->index_buffer_binding.buffer_state && !pCB->index_buffer_binding.buffer_state->Destroyed()) { skip |= ValidateProtectedBuffer(pCB, pCB->index_buffer_binding.buffer_state.get(), caller, vuid.unprotected_command_buffer, "Buffer is index buffer"); } } // Verify if using dynamic state setting commands that it doesn't set up in pipeline CBStatusFlags invalid_status = CBSTATUS_ALL_STATE_SET & ~(pCB->dynamic_status | pCB->static_status); if (invalid_status) { std::string dynamic_states = DynamicStateString(invalid_status); LogObjectList objlist(pCB->commandBuffer()); objlist.add(pPipeline->pipeline()); skip |= LogError(objlist, vuid.dynamic_state_setting_commands, "%s: %s doesn't set up %s, but it calls the related dynamic state setting commands", caller, report_data->FormatHandle(state.pipeline_state->pipeline()).c_str(), dynamic_states.c_str()); } // Verify vertex binding if (pPipeline->vertex_binding_descriptions_.size() > 0) { for (size_t i = 0; i < pPipeline->vertex_binding_descriptions_.size(); i++) { const auto vertex_binding = pPipeline->vertex_binding_descriptions_[i].binding; if (current_vtx_bfr_binding_info.size() < (vertex_binding + 1)) { skip |= LogError(pCB->commandBuffer(), vuid.vertex_binding, "%s: %s expects that this Command Buffer's vertex binding Index %u should be set via " "vkCmdBindVertexBuffers. This is because VkVertexInputBindingDescription struct at " "index " PRINTF_SIZE_T_SPECIFIER " of pVertexBindingDescriptions has a binding value of %u.", caller, report_data->FormatHandle(state.pipeline_state->pipeline()).c_str(), vertex_binding, i, vertex_binding); } else if ((current_vtx_bfr_binding_info[vertex_binding].buffer_state == nullptr) && !enabled_features.robustness2_features.nullDescriptor) { skip |= LogError(pCB->commandBuffer(), vuid.vertex_binding_null, "%s: Vertex binding %d must not be VK_NULL_HANDLE %s expects that this Command Buffer's vertex " "binding Index %u should be set via " "vkCmdBindVertexBuffers. This is because VkVertexInputBindingDescription struct at " "index " PRINTF_SIZE_T_SPECIFIER " of pVertexBindingDescriptions has a binding value of %u.", caller, vertex_binding, report_data->FormatHandle(state.pipeline_state->pipeline()).c_str(), vertex_binding, i, vertex_binding); } } // Verify vertex attribute address alignment for (size_t i = 0; i < pPipeline->vertex_attribute_descriptions_.size(); i++) { const auto &attribute_description = pPipeline->vertex_attribute_descriptions_[i]; const auto vertex_binding = attribute_description.binding; const auto attribute_offset = attribute_description.offset; const auto &vertex_binding_map_it = pPipeline->vertex_binding_to_index_map_.find(vertex_binding); if ((vertex_binding_map_it != pPipeline->vertex_binding_to_index_map_.cend()) && (vertex_binding < current_vtx_bfr_binding_info.size()) && ((current_vtx_bfr_binding_info[vertex_binding].buffer_state) || enabled_features.robustness2_features.nullDescriptor)) { auto vertex_buffer_stride = pPipeline->vertex_binding_descriptions_[vertex_binding_map_it->second].stride; if (IsDynamic(pPipeline, VK_DYNAMIC_STATE_VERTEX_INPUT_BINDING_STRIDE_EXT)) { vertex_buffer_stride = static_cast<uint32_t>(current_vtx_bfr_binding_info[vertex_binding].stride); uint32_t attribute_binding_extent = attribute_description.offset + FormatElementSize(attribute_description.format); if (vertex_buffer_stride < attribute_binding_extent) { skip |= LogError(pCB->commandBuffer(), "VUID-vkCmdBindVertexBuffers2EXT-pStrides-03363", "The pStrides[%u] (%u) parameter in the last call to vkCmdBindVertexBuffers2EXT is less than " "the extent of the binding for attribute %zu (%u).", vertex_binding, vertex_buffer_stride, i, attribute_binding_extent); } } const auto vertex_buffer_offset = current_vtx_bfr_binding_info[vertex_binding].offset; // Use 1 as vertex/instance index to use buffer stride as well const auto attrib_address = vertex_buffer_offset + vertex_buffer_stride + attribute_offset; VkDeviceSize vtx_attrib_req_alignment = pPipeline->vertex_attribute_alignments_[i]; if (SafeModulo(attrib_address, vtx_attrib_req_alignment) != 0) { LogObjectList objlist(current_vtx_bfr_binding_info[vertex_binding].buffer_state->buffer()); objlist.add(state.pipeline_state->pipeline()); skip |= LogError( objlist, vuid.vertex_binding_attribute, "%s: Invalid attribAddress alignment for vertex attribute " PRINTF_SIZE_T_SPECIFIER ", %s,from of %s and vertex %s.", caller, i, string_VkFormat(attribute_description.format), report_data->FormatHandle(state.pipeline_state->pipeline()).c_str(), report_data->FormatHandle(current_vtx_bfr_binding_info[vertex_binding].buffer_state->buffer()).c_str()); } } else { LogObjectList objlist(pCB->commandBuffer()); objlist.add(state.pipeline_state->pipeline()); skip |= LogError(objlist, vuid.vertex_binding_attribute, "%s: binding #%" PRIu32 " in pVertexAttributeDescriptions of %s is invalid in vkCmdBindVertexBuffers of %s.", caller, vertex_binding, report_data->FormatHandle(state.pipeline_state->pipeline()).c_str(), report_data->FormatHandle(pCB->commandBuffer()).c_str()); } } } // If Viewport or scissors are dynamic, verify that dynamic count matches PSO count. // Skip check if rasterization is disabled, if there is no viewport, or if viewport/scissors are being inherited. bool dyn_viewport = IsDynamic(pPipeline, VK_DYNAMIC_STATE_VIEWPORT); if ((!pPipeline->graphicsPipelineCI.pRasterizationState || (pPipeline->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable == VK_FALSE)) && pPipeline->graphicsPipelineCI.pViewportState && pCB->inheritedViewportDepths.size() == 0) { bool dyn_scissor = IsDynamic(pPipeline, VK_DYNAMIC_STATE_SCISSOR); // NB (akeley98): Current validation layers do not detect the error where vkCmdSetViewport (or scissor) was called, but // the dynamic state set is overwritten by binding a graphics pipeline with static viewport (scissor) state. // This condition be detected by checking trashedViewportMask & viewportMask (trashedScissorMask & scissorMask) is // nonzero in the range of bits needed by the pipeline. if (dyn_viewport) { const auto required_viewports_mask = (1 << pPipeline->graphicsPipelineCI.pViewportState->viewportCount) - 1; const auto missing_viewport_mask = ~pCB->viewportMask & required_viewports_mask; if (missing_viewport_mask) { std::stringstream ss; ss << caller << ": Dynamic viewport(s) "; ListBits(ss, missing_viewport_mask); ss << " are used by pipeline state object, but were not provided via calls to vkCmdSetViewport()."; skip |= LogError(device, vuid.dynamic_state, "%s", ss.str().c_str()); } } if (dyn_scissor) { const auto required_scissor_mask = (1 << pPipeline->graphicsPipelineCI.pViewportState->scissorCount) - 1; const auto missing_scissor_mask = ~pCB->scissorMask & required_scissor_mask; if (missing_scissor_mask) { std::stringstream ss; ss << caller << ": Dynamic scissor(s) "; ListBits(ss, missing_scissor_mask); ss << " are used by pipeline state object, but were not provided via calls to vkCmdSetScissor()."; skip |= LogError(device, vuid.dynamic_state, "%s", ss.str().c_str()); } } bool dyn_viewport_count = IsDynamic(pPipeline, VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT_EXT); bool dyn_scissor_count = IsDynamic(pPipeline, VK_DYNAMIC_STATE_SCISSOR_WITH_COUNT_EXT); // VUID {refpage}-viewportCount-03417 if (dyn_viewport_count && !dyn_scissor_count) { const auto required_viewport_mask = (1 << pPipeline->graphicsPipelineCI.pViewportState->scissorCount) - 1; const auto missing_viewport_mask = ~pCB->viewportWithCountMask & required_viewport_mask; if (missing_viewport_mask) { std::stringstream ss; ss << caller << ": Dynamic viewport with count "; ListBits(ss, missing_viewport_mask); ss << " are used by pipeline state object, but were not provided via calls to vkCmdSetViewportWithCountEXT()."; skip |= LogError(device, vuid.viewport_count, "%s", ss.str().c_str()); } } // VUID {refpage}-scissorCount-03418 if (dyn_scissor_count && !dyn_viewport_count) { const auto required_scissor_mask = (1 << pPipeline->graphicsPipelineCI.pViewportState->viewportCount) - 1; const auto missing_scissor_mask = ~pCB->scissorWithCountMask & required_scissor_mask; if (missing_scissor_mask) { std::stringstream ss; ss << caller << ": Dynamic scissor with count "; ListBits(ss, missing_scissor_mask); ss << " are used by pipeline state object, but were not provided via calls to vkCmdSetScissorWithCountEXT()."; skip |= LogError(device, vuid.scissor_count, "%s", ss.str().c_str()); } } // VUID {refpage}-viewportCount-03419 if (dyn_scissor_count && dyn_viewport_count) { if (pCB->viewportWithCountMask != pCB->scissorWithCountMask) { std::stringstream ss; ss << caller << ": Dynamic viewport and scissor with count "; ListBits(ss, pCB->viewportWithCountMask ^ pCB->scissorWithCountMask); ss << " are used by pipeline state object, but were not provided via matching calls to " "vkCmdSetViewportWithCountEXT and vkCmdSetScissorWithCountEXT()."; skip |= LogError(device, vuid.viewport_scissor_count, "%s", ss.str().c_str()); } } } // If inheriting viewports, verify that not using more than inherited. if (pCB->inheritedViewportDepths.size() != 0 && dyn_viewport) { uint32_t viewport_count = pPipeline->graphicsPipelineCI.pViewportState->viewportCount; uint32_t max_inherited = uint32_t(pCB->inheritedViewportDepths.size()); if (viewport_count > max_inherited) { skip |= LogError(device, vuid.dynamic_state, "Pipeline requires more viewports (%u) than inherited (viewportDepthCount=%u).", unsigned(viewport_count), unsigned(max_inherited)); } } // Verify that any MSAA request in PSO matches sample# in bound FB // Skip the check if rasterization is disabled. if (!pPipeline->graphicsPipelineCI.pRasterizationState || (pPipeline->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable == VK_FALSE)) { VkSampleCountFlagBits pso_num_samples = GetNumSamples(pPipeline); if (pCB->activeRenderPass) { const auto render_pass_info = pCB->activeRenderPass->createInfo.ptr(); const VkSubpassDescription2 *subpass_desc = &render_pass_info->pSubpasses[pCB->activeSubpass]; uint32_t i; unsigned subpass_num_samples = 0; for (i = 0; i < subpass_desc->colorAttachmentCount; i++) { const auto attachment = subpass_desc->pColorAttachments[i].attachment; if (attachment != VK_ATTACHMENT_UNUSED) { subpass_num_samples |= static_cast<unsigned>(render_pass_info->pAttachments[attachment].samples); } } if (subpass_desc->pDepthStencilAttachment && subpass_desc->pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED) { const auto attachment = subpass_desc->pDepthStencilAttachment->attachment; subpass_num_samples |= static_cast<unsigned>(render_pass_info->pAttachments[attachment].samples); } if (!(device_extensions.vk_amd_mixed_attachment_samples || device_extensions.vk_nv_framebuffer_mixed_samples) && ((subpass_num_samples & static_cast<unsigned>(pso_num_samples)) != subpass_num_samples)) { LogObjectList objlist(pPipeline->pipeline()); objlist.add(pCB->activeRenderPass->renderPass()); skip |= LogError(objlist, vuid.rasterization_samples, "%s: In %s the sample count is %s while the current %s has %s and they need to be the same.", caller, report_data->FormatHandle(pPipeline->pipeline()).c_str(), string_VkSampleCountFlagBits(pso_num_samples), report_data->FormatHandle(pCB->activeRenderPass->renderPass()).c_str(), string_VkSampleCountFlags(static_cast<VkSampleCountFlags>(subpass_num_samples)).c_str()); } } else { skip |= LogError(pPipeline->pipeline(), kVUID_Core_DrawState_NoActiveRenderpass, "%s: No active render pass found at draw-time in %s!", caller, report_data->FormatHandle(pPipeline->pipeline()).c_str()); } } // Verify that PSO creation renderPass is compatible with active renderPass if (pCB->activeRenderPass) { // TODO: AMD extension codes are included here, but actual function entrypoints are not yet intercepted if (pCB->activeRenderPass->renderPass() != pPipeline->rp_state->renderPass()) { // renderPass that PSO was created with must be compatible with active renderPass that PSO is being used with skip |= ValidateRenderPassCompatibility("active render pass", pCB->activeRenderPass.get(), "pipeline state object", pPipeline->rp_state.get(), caller, vuid.render_pass_compatible); } if (pPipeline->graphicsPipelineCI.subpass != pCB->activeSubpass) { skip |= LogError(pPipeline->pipeline(), vuid.subpass_index, "%s: Pipeline was built for subpass %u but used in subpass %u.", caller, pPipeline->graphicsPipelineCI.subpass, pCB->activeSubpass); } // Check if depth stencil attachment was created with sample location compatible bit if (pPipeline->sample_location_enabled == VK_TRUE) { const safe_VkAttachmentReference2 *ds_attachment = pCB->activeRenderPass->createInfo.pSubpasses[pCB->activeSubpass].pDepthStencilAttachment; const FRAMEBUFFER_STATE *fb_state = pCB->activeFramebuffer.get(); if ((ds_attachment != nullptr) && (fb_state != nullptr)) { const uint32_t attachment = ds_attachment->attachment; if (attachment != VK_ATTACHMENT_UNUSED) { const auto *imageview_state = pCB->GetActiveAttachmentImageViewState(attachment); if (imageview_state != nullptr) { const IMAGE_STATE *image_state = GetImageState(imageview_state->create_info.image); if (image_state != nullptr) { if ((image_state->createInfo.flags & VK_IMAGE_CREATE_SAMPLE_LOCATIONS_COMPATIBLE_DEPTH_BIT_EXT) == 0) { skip |= LogError(pPipeline->pipeline(), vuid.sample_location, "%s: sampleLocationsEnable is true for the pipeline, but the subpass (%u) depth " "stencil attachment's VkImage was not created with " "VK_IMAGE_CREATE_SAMPLE_LOCATIONS_COMPATIBLE_DEPTH_BIT_EXT.", caller, pCB->activeSubpass); } } } } } } } skip |= ValidateStatus(pCB, CBSTATUS_PATCH_CONTROL_POINTS_SET, "Dynamic patch control points not set for this command buffer", vuid.patch_control_points); skip |= ValidateStatus(pCB, CBSTATUS_RASTERIZER_DISCARD_ENABLE_SET, "Dynamic rasterizer discard enable not set for this command buffer", vuid.rasterizer_discard_enable); skip |= ValidateStatus(pCB, CBSTATUS_DEPTH_BIAS_ENABLE_SET, "Dynamic depth bias enable not set for this command buffer", vuid.depth_bias_enable); skip |= ValidateStatus(pCB, CBSTATUS_LOGIC_OP_SET, "Dynamic state logicOp not set for this command buffer", vuid.logic_op); skip |= ValidateStatus(pCB, CBSTATUS_PRIMITIVE_RESTART_ENABLE_SET, "Dynamic primitive restart enable not set for this command buffer", vuid.primitive_restart_enable); skip |= ValidateStatus(pCB, CBSTATUS_VERTEX_INPUT_BINDING_STRIDE_SET, "Dynamic vertex input binding stride not set for this command buffer", vuid.vertex_input_binding_stride); skip |= ValidateStatus(pCB, CBSTATUS_VERTEX_INPUT_SET, "Dynamic vertex input not set for this command buffer", vuid.vertex_input); // VUID {refpage}-primitiveTopology-03420 skip |= ValidateStatus(pCB, CBSTATUS_PRIMITIVE_TOPOLOGY_SET, "Dynamic primitive topology state not set for this command buffer", vuid.primitive_topology); if (IsDynamic(pPipeline, VK_DYNAMIC_STATE_PRIMITIVE_TOPOLOGY_EXT)) { bool compatible_topology = false; switch (pPipeline->graphicsPipelineCI.pInputAssemblyState->topology) { case VK_PRIMITIVE_TOPOLOGY_POINT_LIST: switch (pCB->primitiveTopology) { case VK_PRIMITIVE_TOPOLOGY_POINT_LIST: compatible_topology = true; break; default: break; } break; case VK_PRIMITIVE_TOPOLOGY_LINE_LIST: case VK_PRIMITIVE_TOPOLOGY_LINE_STRIP: case VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY: case VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY: switch (pCB->primitiveTopology) { case VK_PRIMITIVE_TOPOLOGY_LINE_LIST: case VK_PRIMITIVE_TOPOLOGY_LINE_STRIP: compatible_topology = true; break; default: break; } break; case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST: case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP: case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN: case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY: case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY: switch (pCB->primitiveTopology) { case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST: case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP: case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN: case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY: case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY: compatible_topology = true; break; default: break; } break; case VK_PRIMITIVE_TOPOLOGY_PATCH_LIST: switch (pCB->primitiveTopology) { case VK_PRIMITIVE_TOPOLOGY_PATCH_LIST: compatible_topology = true; break; default: break; } break; default: break; } if (!compatible_topology) { skip |= LogError(pPipeline->pipeline(), vuid.primitive_topology, "%s: the last primitive topology %s state set by vkCmdSetPrimitiveTopologyEXT is " "not compatible with the pipeline topology %s.", caller, string_VkPrimitiveTopology(pCB->primitiveTopology), string_VkPrimitiveTopology(pPipeline->graphicsPipelineCI.pInputAssemblyState->topology)); } } if (enabled_features.fragment_shading_rate_features.primitiveFragmentShadingRate) { skip |= ValidateGraphicsPipelineShaderDynamicState(pPipeline, pCB, caller, vuid); } return skip; } // For given cvdescriptorset::DescriptorSet, verify that its Set is compatible w/ the setLayout corresponding to // pipelineLayout[layoutIndex] static bool VerifySetLayoutCompatibility(const debug_report_data *report_data, const cvdescriptorset::DescriptorSet *descriptor_set, PIPELINE_LAYOUT_STATE const *pipeline_layout, const uint32_t layoutIndex, string &errorMsg) { auto num_sets = pipeline_layout->set_layouts.size(); if (layoutIndex >= num_sets) { stringstream error_str; error_str << report_data->FormatHandle(pipeline_layout->layout()) << ") only contains " << num_sets << " setLayouts corresponding to sets 0-" << num_sets - 1 << ", but you're attempting to bind set to index " << layoutIndex; errorMsg = error_str.str(); return false; } if (descriptor_set->IsPushDescriptor()) return true; auto layout_node = pipeline_layout->set_layouts[layoutIndex].get(); return cvdescriptorset::VerifySetLayoutCompatibility(report_data, layout_node, descriptor_set->GetLayout().get(), &errorMsg); } // Validate overall state at the time of a draw call bool CoreChecks::ValidateCmdBufDrawState(const CMD_BUFFER_STATE *cb_node, CMD_TYPE cmd_type, const bool indexed, const VkPipelineBindPoint bind_point, const char *function) const { const DrawDispatchVuid vuid = GetDrawDispatchVuid(cmd_type); const auto lv_bind_point = ConvertToLvlBindPoint(bind_point); const auto &state = cb_node->lastBound[lv_bind_point]; const auto *pipe = state.pipeline_state; if (nullptr == pipe) { return LogError(cb_node->commandBuffer(), vuid.pipeline_bound, "Must not call %s on this command buffer while there is no %s pipeline bound.", function, bind_point == VK_PIPELINE_BIND_POINT_RAY_TRACING_KHR ? "RayTracing" : bind_point == VK_PIPELINE_BIND_POINT_GRAPHICS ? "Graphics" : "Compute"); } bool result = false; if (VK_PIPELINE_BIND_POINT_GRAPHICS == bind_point) { // First check flag states result |= ValidateDrawStateFlags(cb_node, pipe, indexed, vuid.dynamic_state); if (cb_node->activeRenderPass && cb_node->activeFramebuffer) { // Verify attachments for unprotected/protected command buffer. if (enabled_features.core11.protectedMemory == VK_TRUE && cb_node->active_attachments) { uint32_t i = 0; for (const auto &view_state : *cb_node->active_attachments.get()) { const auto &subpass = cb_node->active_subpasses->at(i); if (subpass.used && view_state && !view_state->Destroyed()) { std::string image_desc = "Image is "; image_desc.append(string_VkImageUsageFlagBits(subpass.usage)); // Because inputAttachment is read only, it doesn't need to care protected command buffer case. // Some CMD_TYPE could not be protected. See VUID 02711. if (subpass.usage != VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT && vuid.protected_command_buffer != kVUIDUndefined) { result |= ValidateUnprotectedImage(cb_node, view_state->image_state.get(), function, vuid.protected_command_buffer, image_desc.c_str()); } result |= ValidateProtectedImage(cb_node, view_state->image_state.get(), function, vuid.unprotected_command_buffer, image_desc.c_str()); } ++i; } } } } // Now complete other state checks string error_string; auto const &pipeline_layout = pipe->pipeline_layout.get(); // Check if the current pipeline is compatible for the maximum used set with the bound sets. if (pipe->active_slots.size() > 0 && !CompatForSet(pipe->max_active_slot, state, pipeline_layout->compat_for_set)) { LogObjectList objlist(pipe->pipeline()); objlist.add(pipeline_layout->layout()); objlist.add(state.pipeline_layout); result |= LogError(objlist, vuid.compatible_pipeline, "%s(): %s defined with %s is not compatible for maximum set statically used %" PRIu32 " with bound descriptor sets, last bound with %s", CommandTypeString(cmd_type), report_data->FormatHandle(pipe->pipeline()).c_str(), report_data->FormatHandle(pipeline_layout->layout()).c_str(), pipe->max_active_slot, report_data->FormatHandle(state.pipeline_layout).c_str()); } for (const auto &set_binding_pair : pipe->active_slots) { uint32_t set_index = set_binding_pair.first; // If valid set is not bound throw an error if ((state.per_set.size() <= set_index) || (!state.per_set[set_index].bound_descriptor_set)) { result |= LogError(cb_node->commandBuffer(), kVUID_Core_DrawState_DescriptorSetNotBound, "%s(): %s uses set #%u but that set is not bound.", CommandTypeString(cmd_type), report_data->FormatHandle(pipe->pipeline()).c_str(), set_index); } else if (!VerifySetLayoutCompatibility(report_data, state.per_set[set_index].bound_descriptor_set, pipeline_layout, set_index, error_string)) { // Set is bound but not compatible w/ overlapping pipeline_layout from PSO VkDescriptorSet set_handle = state.per_set[set_index].bound_descriptor_set->GetSet(); LogObjectList objlist(set_handle); objlist.add(pipeline_layout->layout()); result |= LogError(objlist, kVUID_Core_DrawState_PipelineLayoutsIncompatible, "%s(): %s bound as set #%u is not compatible with overlapping %s due to: %s", CommandTypeString(cmd_type), report_data->FormatHandle(set_handle).c_str(), set_index, report_data->FormatHandle(pipeline_layout->layout()).c_str(), error_string.c_str()); } else { // Valid set is bound and layout compatible, validate that it's updated // Pull the set node const cvdescriptorset::DescriptorSet *descriptor_set = state.per_set[set_index].bound_descriptor_set; // Validate the draw-time state for this descriptor set std::string err_str; // For the "bindless" style resource usage with many descriptors, need to optimize command <-> descriptor // binding validation. Take the requested binding set and prefilter it to eliminate redundant validation checks. // Here, the currently bound pipeline determines whether an image validation check is redundant... // for images are the "req" portion of the binding_req is indirectly (but tightly) coupled to the pipeline. cvdescriptorset::PrefilterBindRequestMap reduced_map(*descriptor_set, set_binding_pair.second); const auto &binding_req_map = reduced_map.FilteredMap(*cb_node, *pipe); // We can skip validating the descriptor set if "nothing" has changed since the last validation. // Same set, no image layout changes, and same "pipeline state" (binding_req_map). If there are // any dynamic descriptors, always revalidate rather than caching the values. We currently only // apply this optimization if IsManyDescriptors is true, to avoid the overhead of copying the // binding_req_map which could potentially be expensive. bool descriptor_set_changed = !reduced_map.IsManyDescriptors() || // Revalidate each time if the set has dynamic offsets state.per_set[set_index].dynamicOffsets.size() > 0 || // Revalidate if descriptor set (or contents) has changed state.per_set[set_index].validated_set != descriptor_set || state.per_set[set_index].validated_set_change_count != descriptor_set->GetChangeCount() || (!disabled[image_layout_validation] && state.per_set[set_index].validated_set_image_layout_change_count != cb_node->image_layout_change_count); bool need_validate = descriptor_set_changed || // Revalidate if previous bindingReqMap doesn't include new bindingReqMap !std::includes(state.per_set[set_index].validated_set_binding_req_map.begin(), state.per_set[set_index].validated_set_binding_req_map.end(), binding_req_map.begin(), binding_req_map.end()); if (need_validate) { if (!descriptor_set_changed && reduced_map.IsManyDescriptors()) { // Only validate the bindings that haven't already been validated BindingReqMap delta_reqs; std::set_difference(binding_req_map.begin(), binding_req_map.end(), state.per_set[set_index].validated_set_binding_req_map.begin(), state.per_set[set_index].validated_set_binding_req_map.end(), layer_data::insert_iterator<BindingReqMap>(delta_reqs, delta_reqs.begin())); result |= ValidateDrawState(descriptor_set, delta_reqs, state.per_set[set_index].dynamicOffsets, cb_node, cb_node->active_attachments.get(), cb_node->active_subpasses.get(), function, vuid); } else { result |= ValidateDrawState(descriptor_set, binding_req_map, state.per_set[set_index].dynamicOffsets, cb_node, cb_node->active_attachments.get(), cb_node->active_subpasses.get(), function, vuid); } } } } // Check general pipeline state that needs to be validated at drawtime if (VK_PIPELINE_BIND_POINT_GRAPHICS == bind_point) { result |= ValidatePipelineDrawtimeState(state, cb_node, cmd_type, pipe, function); } // Verify if push constants have been set // NOTE: Currently not checking whether active push constants are compatible with the active pipeline, nor whether the // "life times" of push constants are correct. // Discussion on validity of these checks can be found at https://gitlab.khronos.org/vulkan/vulkan/-/issues/2602. if (!cb_node->push_constant_data_ranges || (pipeline_layout->push_constant_ranges == cb_node->push_constant_data_ranges)) { for (const auto &stage : pipe->stage_state) { const auto *entrypoint = stage.shader_state.get()->FindEntrypointStruct(stage.entry_point_name.c_str(), stage.stage_flag); if (!entrypoint || !entrypoint->push_constant_used_in_shader.IsUsed()) { continue; } // Edge case where if the shader is using push constants statically and there never was a vkCmdPushConstants if (!cb_node->push_constant_data_ranges) { LogObjectList objlist(cb_node->commandBuffer()); objlist.add(pipeline_layout->layout()); objlist.add(pipe->pipeline()); result |= LogError(objlist, vuid.push_constants_set, "%s(): Shader in %s uses push-constant statically but vkCmdPushConstants was not called yet for " "pipeline layout %s.", CommandTypeString(cmd_type), string_VkShaderStageFlags(stage.stage_flag).c_str(), report_data->FormatHandle(pipeline_layout->layout()).c_str()); } const auto it = cb_node->push_constant_data_update.find(stage.stage_flag); if (it == cb_node->push_constant_data_update.end()) { // This error has been printed in ValidatePushConstantUsage. break; } } } return result; } bool CoreChecks::ValidatePipelineLocked(std::vector<std::shared_ptr<PIPELINE_STATE>> const &pPipelines, int pipelineIndex) const { bool skip = false; const PIPELINE_STATE *pipeline = pPipelines[pipelineIndex].get(); // If create derivative bit is set, check that we've specified a base // pipeline correctly, and that the base pipeline was created to allow // derivatives. if (pipeline->graphicsPipelineCI.flags & VK_PIPELINE_CREATE_DERIVATIVE_BIT) { const PIPELINE_STATE *base_pipeline = nullptr; if (!((pipeline->graphicsPipelineCI.basePipelineHandle != VK_NULL_HANDLE) ^ (pipeline->graphicsPipelineCI.basePipelineIndex != -1))) { // TODO: This check is a superset of VUID-VkGraphicsPipelineCreateInfo-flags-00724 and // TODO: VUID-VkGraphicsPipelineCreateInfo-flags-00725 skip |= LogError(device, kVUID_Core_DrawState_InvalidPipelineCreateState, "Invalid Pipeline CreateInfo[%d]: exactly one of base pipeline index and handle must be specified", pipelineIndex); } else if (pipeline->graphicsPipelineCI.basePipelineIndex != -1) { if (pipeline->graphicsPipelineCI.basePipelineIndex >= pipelineIndex) { skip |= LogError(device, "VUID-vkCreateGraphicsPipelines-flags-00720", "Invalid Pipeline CreateInfo[%d]: base pipeline must occur earlier in array than derivative pipeline.", pipelineIndex); } else { base_pipeline = pPipelines[pipeline->graphicsPipelineCI.basePipelineIndex].get(); } } else if (pipeline->graphicsPipelineCI.basePipelineHandle != VK_NULL_HANDLE) { base_pipeline = GetPipelineState(pipeline->graphicsPipelineCI.basePipelineHandle); } if (base_pipeline && !(base_pipeline->graphicsPipelineCI.flags & VK_PIPELINE_CREATE_ALLOW_DERIVATIVES_BIT)) { skip |= LogError(device, "VUID-vkCreateGraphicsPipelines-flags-00721", "Invalid Pipeline CreateInfo[%d]: base pipeline does not allow derivatives.", pipelineIndex); } } // Check for portability errors if (ExtEnabled::kNotEnabled != device_extensions.vk_khr_portability_subset) { if ((VK_FALSE == enabled_features.portability_subset_features.triangleFans) && (VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN == pipeline->topology_at_rasterizer)) { skip |= LogError(device, "VUID-VkPipelineInputAssemblyStateCreateInfo-triangleFans-04452", "Invalid Pipeline CreateInfo[%d] (portability error): VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN is not supported", pipelineIndex); } // Validate vertex inputs for (const auto &desc : pipeline->vertex_binding_descriptions_) { const auto min_alignment = phys_dev_ext_props.portability_props.minVertexInputBindingStrideAlignment; if ((desc.stride < min_alignment) || (min_alignment == 0) || ((desc.stride % min_alignment) != 0)) { skip |= LogError( device, "VUID-VkVertexInputBindingDescription-stride-04456", "Invalid Pipeline CreateInfo[%d] (portability error): Vertex input stride must be at least as large as and a " "multiple of VkPhysicalDevicePortabilitySubsetPropertiesKHR::minVertexInputBindingStrideAlignment.", pipelineIndex); } } // Validate vertex attributes if (VK_FALSE == enabled_features.portability_subset_features.vertexAttributeAccessBeyondStride) { for (const auto &attrib : pipeline->vertex_attribute_descriptions_) { const auto vertex_binding_map_it = pipeline->vertex_binding_to_index_map_.find(attrib.binding); if (vertex_binding_map_it != pipeline->vertex_binding_to_index_map_.cend()) { const auto& desc = pipeline->vertex_binding_descriptions_[vertex_binding_map_it->second]; if ((attrib.offset + FormatElementSize(attrib.format)) > desc.stride) { skip |= LogError(device, "VUID-VkVertexInputAttributeDescription-vertexAttributeAccessBeyondStride-04457", "Invalid Pipeline CreateInfo[%d] (portability error): (attribute.offset + " "sizeof(vertex_description.format)) is larger than the vertex stride", pipelineIndex); } } } } // Validate polygon mode auto raster_state_ci = pipeline->graphicsPipelineCI.pRasterizationState; if ((VK_FALSE == enabled_features.portability_subset_features.pointPolygons) && raster_state_ci && (VK_FALSE == raster_state_ci->rasterizerDiscardEnable) && (VK_POLYGON_MODE_POINT == raster_state_ci->polygonMode)) { skip |= LogError(device, "VUID-VkPipelineRasterizationStateCreateInfo-pointPolygons-04458", "Invalid Pipeline CreateInfo[%d] (portability error): point polygons are not supported", pipelineIndex); } } return skip; } // UNLOCKED pipeline validation. DO NOT lookup objects in the CoreChecks->* maps in this function. bool CoreChecks::ValidatePipelineUnlocked(const PIPELINE_STATE *pPipeline, uint32_t pipelineIndex) const { bool skip = false; // Ensure the subpass index is valid. If not, then ValidateGraphicsPipelineShaderState // produces nonsense errors that confuse users. Other layers should already // emit errors for renderpass being invalid. auto subpass_desc = &pPipeline->rp_state->createInfo.pSubpasses[pPipeline->graphicsPipelineCI.subpass]; if (pPipeline->graphicsPipelineCI.subpass >= pPipeline->rp_state->createInfo.subpassCount) { skip |= LogError(device, "VUID-VkGraphicsPipelineCreateInfo-subpass-00759", "Invalid Pipeline CreateInfo[%u] State: Subpass index %u is out of range for this renderpass (0..%u).", pipelineIndex, pPipeline->graphicsPipelineCI.subpass, pPipeline->rp_state->createInfo.subpassCount - 1); subpass_desc = nullptr; } if (pPipeline->graphicsPipelineCI.pColorBlendState != NULL) { const safe_VkPipelineColorBlendStateCreateInfo *color_blend_state = pPipeline->graphicsPipelineCI.pColorBlendState; if (subpass_desc && color_blend_state->attachmentCount != subpass_desc->colorAttachmentCount) { skip |= LogError( device, "VUID-VkGraphicsPipelineCreateInfo-attachmentCount-00746", "vkCreateGraphicsPipelines() pCreateInfo[%u]: %s subpass %u has colorAttachmentCount of %u which doesn't " "match the pColorBlendState->attachmentCount of %u.", pipelineIndex, report_data->FormatHandle(pPipeline->rp_state->renderPass()).c_str(), pPipeline->graphicsPipelineCI.subpass, subpass_desc->colorAttachmentCount, color_blend_state->attachmentCount); } if (!enabled_features.core.independentBlend) { if (pPipeline->attachments.size() > 1) { const VkPipelineColorBlendAttachmentState *const attachments = &pPipeline->attachments[0]; for (size_t i = 1; i < pPipeline->attachments.size(); i++) { // Quoting the spec: "If [the independent blend] feature is not enabled, the VkPipelineColorBlendAttachmentState // settings for all color attachments must be identical." VkPipelineColorBlendAttachmentState contains // only attachment state, so memcmp is best suited for the comparison if (memcmp(static_cast<const void *>(attachments), static_cast<const void *>(&attachments[i]), sizeof(attachments[0]))) { skip |= LogError(device, "VUID-VkPipelineColorBlendStateCreateInfo-pAttachments-00605", "Invalid Pipeline CreateInfo[%u]: If independent blend feature not enabled, all elements of " "pAttachments must be identical.", pipelineIndex); break; } } } } if (!enabled_features.core.logicOp && (pPipeline->graphicsPipelineCI.pColorBlendState->logicOpEnable != VK_FALSE)) { skip |= LogError( device, "VUID-VkPipelineColorBlendStateCreateInfo-logicOpEnable-00606", "Invalid Pipeline CreateInfo[%u]: If logic operations feature not enabled, logicOpEnable must be VK_FALSE.", pipelineIndex); } for (size_t i = 0; i < pPipeline->attachments.size(); i++) { if ((pPipeline->attachments[i].srcColorBlendFactor == VK_BLEND_FACTOR_SRC1_COLOR) || (pPipeline->attachments[i].srcColorBlendFactor == VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR) || (pPipeline->attachments[i].srcColorBlendFactor == VK_BLEND_FACTOR_SRC1_ALPHA) || (pPipeline->attachments[i].srcColorBlendFactor == VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA)) { if (!enabled_features.core.dualSrcBlend) { skip |= LogError( device, "VUID-VkPipelineColorBlendAttachmentState-srcColorBlendFactor-00608", "vkCreateGraphicsPipelines(): pPipelines[%d].pColorBlendState.pAttachments[" PRINTF_SIZE_T_SPECIFIER "].srcColorBlendFactor uses a dual-source blend factor (%d), but this device feature is not " "enabled.", pipelineIndex, i, pPipeline->attachments[i].srcColorBlendFactor); } } if ((pPipeline->attachments[i].dstColorBlendFactor == VK_BLEND_FACTOR_SRC1_COLOR) || (pPipeline->attachments[i].dstColorBlendFactor == VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR) || (pPipeline->attachments[i].dstColorBlendFactor == VK_BLEND_FACTOR_SRC1_ALPHA) || (pPipeline->attachments[i].dstColorBlendFactor == VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA)) { if (!enabled_features.core.dualSrcBlend) { skip |= LogError( device, "VUID-VkPipelineColorBlendAttachmentState-dstColorBlendFactor-00609", "vkCreateGraphicsPipelines(): pPipelines[%d].pColorBlendState.pAttachments[" PRINTF_SIZE_T_SPECIFIER "].dstColorBlendFactor uses a dual-source blend factor (%d), but this device feature is not " "enabled.", pipelineIndex, i, pPipeline->attachments[i].dstColorBlendFactor); } } if ((pPipeline->attachments[i].srcAlphaBlendFactor == VK_BLEND_FACTOR_SRC1_COLOR) || (pPipeline->attachments[i].srcAlphaBlendFactor == VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR) || (pPipeline->attachments[i].srcAlphaBlendFactor == VK_BLEND_FACTOR_SRC1_ALPHA) || (pPipeline->attachments[i].srcAlphaBlendFactor == VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA)) { if (!enabled_features.core.dualSrcBlend) { skip |= LogError( device, "VUID-VkPipelineColorBlendAttachmentState-srcAlphaBlendFactor-00610", "vkCreateGraphicsPipelines(): pPipelines[%d].pColorBlendState.pAttachments[" PRINTF_SIZE_T_SPECIFIER "].srcAlphaBlendFactor uses a dual-source blend factor (%d), but this device feature is not " "enabled.", pipelineIndex, i, pPipeline->attachments[i].srcAlphaBlendFactor); } } if ((pPipeline->attachments[i].dstAlphaBlendFactor == VK_BLEND_FACTOR_SRC1_COLOR) || (pPipeline->attachments[i].dstAlphaBlendFactor == VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR) || (pPipeline->attachments[i].dstAlphaBlendFactor == VK_BLEND_FACTOR_SRC1_ALPHA) || (pPipeline->attachments[i].dstAlphaBlendFactor == VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA)) { if (!enabled_features.core.dualSrcBlend) { skip |= LogError( device, "VUID-VkPipelineColorBlendAttachmentState-dstAlphaBlendFactor-00611", "vkCreateGraphicsPipelines(): pPipelines[%d].pColorBlendState.pAttachments[" PRINTF_SIZE_T_SPECIFIER "].dstAlphaBlendFactor uses a dual-source blend factor (%d), but this device feature is not " "enabled.", pipelineIndex, i, pPipeline->attachments[i].dstAlphaBlendFactor); } } } } if (ValidateGraphicsPipelineShaderState(pPipeline)) { skip = true; } // Each shader's stage must be unique if (pPipeline->duplicate_shaders) { for (uint32_t stage = VK_SHADER_STAGE_VERTEX_BIT; stage & VK_SHADER_STAGE_ALL_GRAPHICS; stage <<= 1) { if (pPipeline->duplicate_shaders & stage) { skip |= LogError(device, "VUID-VkGraphicsPipelineCreateInfo-stage-00726", "Invalid Pipeline CreateInfo[%u] State: Multiple shaders provided for stage %s", pipelineIndex, string_VkShaderStageFlagBits(VkShaderStageFlagBits(stage))); } } } if (!enabled_features.core.geometryShader && (pPipeline->active_shaders & VK_SHADER_STAGE_GEOMETRY_BIT)) { skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-stage-00704", "Invalid Pipeline CreateInfo[%u] State: Geometry Shader not supported.", pipelineIndex); } if (!enabled_features.core.tessellationShader && (pPipeline->active_shaders & VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT || pPipeline->active_shaders & VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT)) { skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-stage-00705", "Invalid Pipeline CreateInfo[%u] State: Tessellation Shader not supported.", pipelineIndex); } if (device_extensions.vk_nv_mesh_shader) { // VS or mesh is required if (!(pPipeline->active_shaders & (VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_MESH_BIT_NV))) { skip |= LogError(device, "VUID-VkGraphicsPipelineCreateInfo-stage-02096", "Invalid Pipeline CreateInfo[%u] State: Vertex Shader or Mesh Shader required.", pipelineIndex); } // Can't mix mesh and VTG if ((pPipeline->active_shaders & (VK_SHADER_STAGE_MESH_BIT_NV | VK_SHADER_STAGE_TASK_BIT_NV)) && (pPipeline->active_shaders & (VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_GEOMETRY_BIT | VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT | VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT))) { skip |= LogError(device, "VUID-VkGraphicsPipelineCreateInfo-pStages-02095", "Invalid Pipeline CreateInfo[%u] State: Geometric shader stages must either be all mesh (mesh | task) " "or all VTG (vertex, tess control, tess eval, geom).", pipelineIndex); } } else { // VS is required if (!(pPipeline->active_shaders & VK_SHADER_STAGE_VERTEX_BIT)) { skip |= LogError(device, "VUID-VkGraphicsPipelineCreateInfo-stage-00727", "Invalid Pipeline CreateInfo[%u] State: Vertex Shader required.", pipelineIndex); } } if (!enabled_features.mesh_shader.meshShader && (pPipeline->active_shaders & VK_SHADER_STAGE_MESH_BIT_NV)) { skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-stage-02091", "Invalid Pipeline CreateInfo[%u] State: Mesh Shader not supported.", pipelineIndex); } if (!enabled_features.mesh_shader.taskShader && (pPipeline->active_shaders & VK_SHADER_STAGE_TASK_BIT_NV)) { skip |= LogError(device, "VUID-VkPipelineShaderStageCreateInfo-stage-02092", "Invalid Pipeline CreateInfo[%u] State: Task Shader not supported.", pipelineIndex); } // Either both or neither TC/TE shaders should be defined bool has_control = (pPipeline->active_shaders & VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT) != 0; bool has_eval = (pPipeline->active_shaders & VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT) != 0; if (has_control && !has_eval) { skip |= LogError(device, "VUID-VkGraphicsPipelineCreateInfo-pStages-00729", "Invalid Pipeline CreateInfo[%u] State: TE and TC shaders must be included or excluded as a pair.", pipelineIndex); } if (!has_control && has_eval) { skip |= LogError(device, "VUID-VkGraphicsPipelineCreateInfo-pStages-00730", "Invalid Pipeline CreateInfo[%u] State: TE and TC shaders must be included or excluded as a pair.", pipelineIndex); } // Compute shaders should be specified independent of Gfx shaders if (pPipeline->active_shaders & VK_SHADER_STAGE_COMPUTE_BIT) { skip |= LogError(device, "VUID-VkGraphicsPipelineCreateInfo-stage-00728", "Invalid Pipeline CreateInfo[%u] State: Do not specify Compute Shader for Gfx Pipeline.", pipelineIndex); } if ((pPipeline->active_shaders & VK_SHADER_STAGE_VERTEX_BIT) && !pPipeline->graphicsPipelineCI.pInputAssemblyState) { skip |= LogError(device, "VUID-VkGraphicsPipelineCreateInfo-pStages-02098", "Invalid Pipeline CreateInfo[%u] State: Missing pInputAssemblyState.", pipelineIndex); } // VK_PRIMITIVE_TOPOLOGY_PATCH_LIST primitive topology is only valid for tessellation pipelines. // Mismatching primitive topology and tessellation fails graphics pipeline creation. if (has_control && has_eval && (!pPipeline->graphicsPipelineCI.pInputAssemblyState || pPipeline->graphicsPipelineCI.pInputAssemblyState->topology != VK_PRIMITIVE_TOPOLOGY_PATCH_LIST)) { skip |= LogError(device, "VUID-VkGraphicsPipelineCreateInfo-pStages-00736", "Invalid Pipeline CreateInfo[%u] State: VK_PRIMITIVE_TOPOLOGY_PATCH_LIST must be set as IA topology for " "tessellation pipelines.", pipelineIndex); } if (pPipeline->graphicsPipelineCI.pInputAssemblyState) { if (pPipeline->graphicsPipelineCI.pInputAssemblyState->topology == VK_PRIMITIVE_TOPOLOGY_PATCH_LIST) { if (!has_control || !has_eval) { skip |= LogError( device, "VUID-VkGraphicsPipelineCreateInfo-topology-00737", "Invalid Pipeline CreateInfo[%u] State: VK_PRIMITIVE_TOPOLOGY_PATCH_LIST primitive topology is only valid " "for tessellation pipelines.", pipelineIndex); } } if ((pPipeline->graphicsPipelineCI.pInputAssemblyState->primitiveRestartEnable == VK_TRUE) && (pPipeline->graphicsPipelineCI.pInputAssemblyState->topology == VK_PRIMITIVE_TOPOLOGY_POINT_LIST || pPipeline->graphicsPipelineCI.pInputAssemblyState->topology == VK_PRIMITIVE_TOPOLOGY_LINE_LIST || pPipeline->graphicsPipelineCI.pInputAssemblyState->topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST || pPipeline->graphicsPipelineCI.pInputAssemblyState->topology == VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY || pPipeline->graphicsPipelineCI.pInputAssemblyState->topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY || pPipeline->graphicsPipelineCI.pInputAssemblyState->topology == VK_PRIMITIVE_TOPOLOGY_PATCH_LIST)) { skip |= LogError( device, "VUID-VkPipelineInputAssemblyStateCreateInfo-topology-00428", "vkCreateGraphicsPipelines() pCreateInfo[%u]: topology is %s and primitiveRestartEnable is VK_TRUE. It is invalid.", pipelineIndex, string_VkPrimitiveTopology(pPipeline->graphicsPipelineCI.pInputAssemblyState->topology)); } if ((enabled_features.core.geometryShader == VK_FALSE) && (pPipeline->graphicsPipelineCI.pInputAssemblyState->topology == VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY || pPipeline->graphicsPipelineCI.pInputAssemblyState->topology == VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY || pPipeline->graphicsPipelineCI.pInputAssemblyState->topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY || pPipeline->graphicsPipelineCI.pInputAssemblyState->topology == VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY)) { skip |= LogError(device, "VUID-VkPipelineInputAssemblyStateCreateInfo-topology-00429", "vkCreateGraphicsPipelines() pCreateInfo[%u]: topology is %s and geometry shaders feature is not enabled. " "It is invalid.", pipelineIndex, string_VkPrimitiveTopology(pPipeline->graphicsPipelineCI.pInputAssemblyState->topology)); } if ((enabled_features.core.tessellationShader == VK_FALSE) && (pPipeline->graphicsPipelineCI.pInputAssemblyState->topology == VK_PRIMITIVE_TOPOLOGY_PATCH_LIST)) { skip |= LogError(device, "VUID-VkPipelineInputAssemblyStateCreateInfo-topology-00430", "vkCreateGraphicsPipelines() pCreateInfo[%u]: topology is %s and tessellation shaders feature is not " "enabled. It is invalid.", pipelineIndex, string_VkPrimitiveTopology(pPipeline->graphicsPipelineCI.pInputAssemblyState->topology)); } } // If a rasterization state is provided... if (pPipeline->graphicsPipelineCI.pRasterizationState) { if ((pPipeline->graphicsPipelineCI.pRasterizationState->depthClampEnable == VK_TRUE) && (!enabled_features.core.depthClamp)) { skip |= LogError(device, "VUID-VkPipelineRasterizationStateCreateInfo-depthClampEnable-00782", "vkCreateGraphicsPipelines() pCreateInfo[%u]: the depthClamp device feature is disabled: the " "depthClampEnable member " "of the VkPipelineRasterizationStateCreateInfo structure must be set to VK_FALSE.", pipelineIndex); } if (!IsDynamic(pPipeline, VK_DYNAMIC_STATE_DEPTH_BIAS) && (pPipeline->graphicsPipelineCI.pRasterizationState->depthBiasClamp != 0.0) && (!enabled_features.core.depthBiasClamp)) { skip |= LogError(device, "VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-00754", "vkCreateGraphicsPipelines() pCreateInfo[%u]: the depthBiasClamp device feature is disabled: the " "depthBiasClamp member " "of the VkPipelineRasterizationStateCreateInfo structure must be set to 0.0 unless the " "VK_DYNAMIC_STATE_DEPTH_BIAS dynamic state is enabled", pipelineIndex); } // If rasterization is enabled... if (pPipeline->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable == VK_FALSE) { if ((pPipeline->graphicsPipelineCI.pMultisampleState->alphaToOneEnable == VK_TRUE) && (!enabled_features.core.alphaToOne)) { skip |= LogError( device, "VUID-VkPipelineMultisampleStateCreateInfo-alphaToOneEnable-00785", "vkCreateGraphicsPipelines() pCreateInfo[%u]: the alphaToOne device feature is disabled: the alphaToOneEnable " "member of the VkPipelineMultisampleStateCreateInfo structure must be set to VK_FALSE.", pipelineIndex); } // If subpass uses a depth/stencil attachment, pDepthStencilState must be a pointer to a valid structure if (subpass_desc && subpass_desc->pDepthStencilAttachment && subpass_desc->pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED) { if (!pPipeline->graphicsPipelineCI.pDepthStencilState) { skip |= LogError(device, "VUID-VkGraphicsPipelineCreateInfo-rasterizerDiscardEnable-00752", "Invalid Pipeline CreateInfo[%u] State: pDepthStencilState is NULL when rasterization is enabled " "and subpass uses a depth/stencil attachment.", pipelineIndex); } else if (pPipeline->graphicsPipelineCI.pDepthStencilState->depthBoundsTestEnable == VK_TRUE) { if (!enabled_features.core.depthBounds) { skip |= LogError(device, "VUID-VkPipelineDepthStencilStateCreateInfo-depthBoundsTestEnable-00598", "vkCreateGraphicsPipelines() pCreateInfo[%u]: the depthBounds device feature is disabled: the " "depthBoundsTestEnable member of the VkPipelineDepthStencilStateCreateInfo structure must be " "set to VK_FALSE.", pipelineIndex); } // The extension was not created with a feature bit whichs prevents displaying the 2 variations of the VUIDs if (!device_extensions.vk_ext_depth_range_unrestricted && !IsDynamic(pPipeline, VK_DYNAMIC_STATE_DEPTH_BOUNDS)) { const float minDepthBounds = pPipeline->graphicsPipelineCI.pDepthStencilState->minDepthBounds; const float maxDepthBounds = pPipeline->graphicsPipelineCI.pDepthStencilState->maxDepthBounds; // Also VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-00755 if (!(minDepthBounds >= 0.0) || !(minDepthBounds <= 1.0)) { skip |= LogError(device, "VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-02510", "vkCreateGraphicsPipelines() pCreateInfo[%u]: VK_EXT_depth_range_unrestricted extension " "is not enabled, VK_DYNAMIC_STATE_DEPTH_BOUNDS is not used, depthBoundsTestEnable is " "true, and pDepthStencilState::minDepthBounds (=%f) is not within the [0.0, 1.0] range.", pipelineIndex, minDepthBounds); } if (!(maxDepthBounds >= 0.0) || !(maxDepthBounds <= 1.0)) { skip |= LogError(device, "VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-02510", "vkCreateGraphicsPipelines() pCreateInfo[%u]: VK_EXT_depth_range_unrestricted extension " "is not enabled, VK_DYNAMIC_STATE_DEPTH_BOUNDS is not used, depthBoundsTestEnable is " "true, and pDepthStencilState::maxDepthBounds (=%f) is not within the [0.0, 1.0] range.", pipelineIndex, maxDepthBounds); } } } } // If subpass uses color attachments, pColorBlendState must be valid pointer if (subpass_desc) { uint32_t color_attachment_count = 0; for (uint32_t i = 0; i < subpass_desc->colorAttachmentCount; ++i) { if (subpass_desc->pColorAttachments[i].attachment != VK_ATTACHMENT_UNUSED) { ++color_attachment_count; } } if (color_attachment_count > 0 && pPipeline->graphicsPipelineCI.pColorBlendState == nullptr) { skip |= LogError( device, "VUID-VkGraphicsPipelineCreateInfo-rasterizerDiscardEnable-00753", "Invalid Pipeline CreateInfo[%u] State: pColorBlendState is NULL when rasterization is enabled and " "subpass uses color attachments.", pipelineIndex); } } } auto provoking_vertex_state_ci = lvl_find_in_chain<VkPipelineRasterizationProvokingVertexStateCreateInfoEXT>( pPipeline->graphicsPipelineCI.pRasterizationState->pNext); if (provoking_vertex_state_ci && provoking_vertex_state_ci->provokingVertexMode == VK_PROVOKING_VERTEX_MODE_LAST_VERTEX_EXT && !enabled_features.provoking_vertex_features.provokingVertexLast) { skip |= LogError( device, "VUID-VkPipelineRasterizationProvokingVertexStateCreateInfoEXT-provokingVertexMode-04883", "provokingVertexLast feature is not enabled."); } } if ((pPipeline->active_shaders & VK_SHADER_STAGE_VERTEX_BIT) && !pPipeline->graphicsPipelineCI.pVertexInputState) { skip |= LogError(device, "VUID-VkGraphicsPipelineCreateInfo-pStages-02097", "Invalid Pipeline CreateInfo[%u] State: Missing pVertexInputState.", pipelineIndex); } auto vi = pPipeline->graphicsPipelineCI.pVertexInputState; if (vi != NULL) { for (uint32_t j = 0; j < vi->vertexAttributeDescriptionCount; j++) { VkFormat format = vi->pVertexAttributeDescriptions[j].format; // Internal call to get format info. Still goes through layers, could potentially go directly to ICD. VkFormatProperties properties; DispatchGetPhysicalDeviceFormatProperties(physical_device, format, &properties); if ((properties.bufferFeatures & VK_FORMAT_FEATURE_VERTEX_BUFFER_BIT) == 0) { skip |= LogError(device, "VUID-VkVertexInputAttributeDescription-format-00623", "vkCreateGraphicsPipelines: pCreateInfo[%d].pVertexInputState->vertexAttributeDescriptions[%d].format " "(%s) is not a supported vertex buffer format.", pipelineIndex, j, string_VkFormat(format)); } } } if (subpass_desc && pPipeline->graphicsPipelineCI.pMultisampleState) { const safe_VkPipelineMultisampleStateCreateInfo *multisample_state = pPipeline->graphicsPipelineCI.pMultisampleState; auto accum_color_samples = [subpass_desc, pPipeline](uint32_t &samples) { for (uint32_t i = 0; i < subpass_desc->colorAttachmentCount; i++) { const auto attachment = subpass_desc->pColorAttachments[i].attachment; if (attachment != VK_ATTACHMENT_UNUSED) { samples |= static_cast<uint32_t>(pPipeline->rp_state->createInfo.pAttachments[attachment].samples); } } }; if (!(device_extensions.vk_amd_mixed_attachment_samples || device_extensions.vk_nv_framebuffer_mixed_samples)) { uint32_t raster_samples = static_cast<uint32_t>(GetNumSamples(pPipeline)); uint32_t subpass_num_samples = 0; accum_color_samples(subpass_num_samples); if (subpass_desc->pDepthStencilAttachment && subpass_desc->pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED) { const auto attachment = subpass_desc->pDepthStencilAttachment->attachment; subpass_num_samples |= static_cast<uint32_t>(pPipeline->rp_state->createInfo.pAttachments[attachment].samples); } // subpass_num_samples is 0 when the subpass has no attachments or if all attachments are VK_ATTACHMENT_UNUSED. // Only validate the value of subpass_num_samples if the subpass has attachments that are not VK_ATTACHMENT_UNUSED. if (subpass_num_samples && (!IsPowerOfTwo(subpass_num_samples) || (subpass_num_samples != raster_samples))) { skip |= LogError(device, "VUID-VkGraphicsPipelineCreateInfo-subpass-00757", "vkCreateGraphicsPipelines: pCreateInfo[%d].pMultisampleState->rasterizationSamples (%u) " "does not match the number of samples of the RenderPass color and/or depth attachment.", pipelineIndex, raster_samples); } } if (device_extensions.vk_amd_mixed_attachment_samples) { VkSampleCountFlagBits max_sample_count = static_cast<VkSampleCountFlagBits>(0); for (uint32_t i = 0; i < subpass_desc->colorAttachmentCount; ++i) { if (subpass_desc->pColorAttachments[i].attachment != VK_ATTACHMENT_UNUSED) { max_sample_count = std::max( max_sample_count, pPipeline->rp_state->createInfo.pAttachments[subpass_desc->pColorAttachments[i].attachment].samples); } } if (subpass_desc->pDepthStencilAttachment && subpass_desc->pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED) { max_sample_count = std::max( max_sample_count, pPipeline->rp_state->createInfo.pAttachments[subpass_desc->pDepthStencilAttachment->attachment].samples); } if ((pPipeline->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable == VK_FALSE) && (max_sample_count != static_cast<VkSampleCountFlagBits>(0)) && (multisample_state->rasterizationSamples != max_sample_count)) { skip |= LogError(device, "VUID-VkGraphicsPipelineCreateInfo-subpass-01505", "vkCreateGraphicsPipelines: pCreateInfo[%d].pMultisampleState->rasterizationSamples (%s) != max " "attachment samples (%s) used in subpass %u.", pipelineIndex, string_VkSampleCountFlagBits(multisample_state->rasterizationSamples), string_VkSampleCountFlagBits(max_sample_count), pPipeline->graphicsPipelineCI.subpass); } } if (device_extensions.vk_nv_framebuffer_mixed_samples) { uint32_t raster_samples = static_cast<uint32_t>(GetNumSamples(pPipeline)); uint32_t subpass_color_samples = 0; accum_color_samples(subpass_color_samples); if (subpass_desc->pDepthStencilAttachment && subpass_desc->pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED) { const auto attachment = subpass_desc->pDepthStencilAttachment->attachment; const uint32_t subpass_depth_samples = static_cast<uint32_t>(pPipeline->rp_state->createInfo.pAttachments[attachment].samples); if (pPipeline->graphicsPipelineCI.pDepthStencilState) { const bool ds_test_enabled = (pPipeline->graphicsPipelineCI.pDepthStencilState->depthTestEnable == VK_TRUE) || (pPipeline->graphicsPipelineCI.pDepthStencilState->depthBoundsTestEnable == VK_TRUE) || (pPipeline->graphicsPipelineCI.pDepthStencilState->stencilTestEnable == VK_TRUE); if (ds_test_enabled && (!IsPowerOfTwo(subpass_depth_samples) || (raster_samples != subpass_depth_samples))) { skip |= LogError(device, "VUID-VkGraphicsPipelineCreateInfo-subpass-01411", "vkCreateGraphicsPipelines: pCreateInfo[%d].pMultisampleState->rasterizationSamples (%u) " "does not match the number of samples of the RenderPass depth attachment (%u).", pipelineIndex, raster_samples, subpass_depth_samples); } } } if (IsPowerOfTwo(subpass_color_samples)) { if (raster_samples < subpass_color_samples) { skip |= LogError(device, "VUID-VkGraphicsPipelineCreateInfo-subpass-01412", "vkCreateGraphicsPipelines: pCreateInfo[%d].pMultisampleState->rasterizationSamples (%u) " "is not greater or equal to the number of samples of the RenderPass color attachment (%u).", pipelineIndex, raster_samples, subpass_color_samples); } if (multisample_state) { if ((raster_samples > subpass_color_samples) && (multisample_state->sampleShadingEnable == VK_TRUE)) { skip |= LogError(device, "VUID-VkPipelineMultisampleStateCreateInfo-rasterizationSamples-01415", "vkCreateGraphicsPipelines: pCreateInfo[%d].pMultisampleState->sampleShadingEnable must be " "VK_FALSE when " "pCreateInfo[%d].pMultisampleState->rasterizationSamples (%u) is greater than the number of " "samples of the " "subpass color attachment (%u).", pipelineIndex, pipelineIndex, raster_samples, subpass_color_samples); } const auto *coverage_modulation_state = LvlFindInChain<VkPipelineCoverageModulationStateCreateInfoNV>(multisample_state->pNext); if (coverage_modulation_state && (coverage_modulation_state->coverageModulationTableEnable == VK_TRUE)) { if (coverage_modulation_state->coverageModulationTableCount != (raster_samples / subpass_color_samples)) { skip |= LogError( device, "VUID-VkPipelineCoverageModulationStateCreateInfoNV-coverageModulationTableEnable-01405", "vkCreateGraphicsPipelines: pCreateInfos[%d] VkPipelineCoverageModulationStateCreateInfoNV " "coverageModulationTableCount of %u is invalid.", pipelineIndex, coverage_modulation_state->coverageModulationTableCount); } } } } } if (device_extensions.vk_nv_coverage_reduction_mode) { uint32_t raster_samples = static_cast<uint32_t>(GetNumSamples(pPipeline)); uint32_t subpass_color_samples = 0; uint32_t subpass_depth_samples = 0; accum_color_samples(subpass_color_samples); if (subpass_desc->pDepthStencilAttachment && subpass_desc->pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED) { const auto attachment = subpass_desc->pDepthStencilAttachment->attachment; subpass_depth_samples = static_cast<uint32_t>(pPipeline->rp_state->createInfo.pAttachments[attachment].samples); } if (multisample_state && IsPowerOfTwo(subpass_color_samples) && (subpass_depth_samples == 0 || IsPowerOfTwo(subpass_depth_samples))) { const auto *coverage_reduction_state = LvlFindInChain<VkPipelineCoverageReductionStateCreateInfoNV>(multisample_state->pNext); if (coverage_reduction_state) { const VkCoverageReductionModeNV coverage_reduction_mode = coverage_reduction_state->coverageReductionMode; uint32_t combination_count = 0; std::vector<VkFramebufferMixedSamplesCombinationNV> combinations; DispatchGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV(physical_device, &combination_count, nullptr); combinations.resize(combination_count); DispatchGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV(physical_device, &combination_count, &combinations[0]); bool combination_found = false; for (const auto &combination : combinations) { if (coverage_reduction_mode == combination.coverageReductionMode && raster_samples == combination.rasterizationSamples && subpass_depth_samples == combination.depthStencilSamples && subpass_color_samples == combination.colorSamples) { combination_found = true; break; } } if (!combination_found) { skip |= LogError(device, "VUID-VkGraphicsPipelineCreateInfo-coverageReductionMode-02722", "vkCreateGraphicsPipelines: pCreateInfos[%d] the specified combination of coverage " "reduction mode (%s), pMultisampleState->rasterizationSamples (%u), sample counts for " "the subpass color and depth/stencil attachments is not a valid combination returned by " "vkGetPhysicalDeviceSupportedFramebufferMixedSamplesCombinationsNV.", pipelineIndex, string_VkCoverageReductionModeNV(coverage_reduction_mode), raster_samples); } } } } if (device_extensions.vk_nv_fragment_coverage_to_color) { const auto coverage_to_color_state = LvlFindInChain<VkPipelineCoverageToColorStateCreateInfoNV>(multisample_state); if (coverage_to_color_state && coverage_to_color_state->coverageToColorEnable == VK_TRUE) { bool attachment_is_valid = false; std::string error_detail; if (coverage_to_color_state->coverageToColorLocation < subpass_desc->colorAttachmentCount) { const auto& color_attachment_ref = subpass_desc->pColorAttachments[coverage_to_color_state->coverageToColorLocation]; if (color_attachment_ref.attachment != VK_ATTACHMENT_UNUSED) { const auto& color_attachment = pPipeline->rp_state->createInfo.pAttachments[color_attachment_ref.attachment]; switch (color_attachment.format) { case VK_FORMAT_R8_UINT: case VK_FORMAT_R8_SINT: case VK_FORMAT_R16_UINT: case VK_FORMAT_R16_SINT: case VK_FORMAT_R32_UINT: case VK_FORMAT_R32_SINT: attachment_is_valid = true; break; default: std::ostringstream str; str << "references an attachment with an invalid format (" << string_VkFormat(color_attachment.format) << ")."; error_detail = str.str(); break; } } else { std::ostringstream str; str << "references an invalid attachment. The subpass pColorAttachments[" << coverage_to_color_state->coverageToColorLocation << "].attachment has the value VK_ATTACHMENT_UNUSED."; error_detail = str.str(); } } else { std::ostringstream str; str << "references an non-existing attachment since the subpass colorAttachmentCount is " << subpass_desc->colorAttachmentCount << "."; error_detail = str.str(); } if (!attachment_is_valid) { skip |= LogError(device, "VUID-VkPipelineCoverageToColorStateCreateInfoNV-coverageToColorEnable-01404", "vkCreateGraphicsPipelines: pCreateInfos[%" PRId32 "].pMultisampleState VkPipelineCoverageToColorStateCreateInfoNV " "coverageToColorLocation = %" PRIu32 " %s", pipelineIndex, coverage_to_color_state->coverageToColorLocation, error_detail.c_str()); } } } if (device_extensions.vk_ext_sample_locations) { const VkPipelineSampleLocationsStateCreateInfoEXT *sample_location_state = LvlFindInChain<VkPipelineSampleLocationsStateCreateInfoEXT>(multisample_state->pNext); if (sample_location_state != nullptr) { if ((sample_location_state->sampleLocationsEnable == VK_TRUE) && (IsDynamic(pPipeline, VK_DYNAMIC_STATE_SAMPLE_LOCATIONS_EXT) == false)) { const VkSampleLocationsInfoEXT sample_location_info = sample_location_state->sampleLocationsInfo; skip |= ValidateSampleLocationsInfo(&sample_location_info, "vkCreateGraphicsPipelines"); const VkExtent2D grid_size = sample_location_info.sampleLocationGridSize; auto multisample_prop = LvlInitStruct<VkMultisamplePropertiesEXT>(); DispatchGetPhysicalDeviceMultisamplePropertiesEXT(physical_device, multisample_state->rasterizationSamples, &multisample_prop); const VkExtent2D max_grid_size = multisample_prop.maxSampleLocationGridSize; // Note order or "divide" in "sampleLocationsInfo must evenly divide VkMultisamplePropertiesEXT" if (SafeModulo(max_grid_size.width, grid_size.width) != 0) { skip |= LogError( device, "VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-01521", "vkCreateGraphicsPipelines() pCreateInfo[%u]: Because there is no dynamic state for Sample Location " "and sampleLocationEnable is true, the " "VkPipelineSampleLocationsStateCreateInfoEXT::sampleLocationsInfo::sampleLocationGridSize.width (%u) " "must be evenly divided by VkMultisamplePropertiesEXT::sampleLocationGridSize.width (%u).", pipelineIndex, grid_size.width, max_grid_size.width); } if (SafeModulo(max_grid_size.height, grid_size.height) != 0) { skip |= LogError( device, "VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-01522", "vkCreateGraphicsPipelines() pCreateInfo[%u]: Because there is no dynamic state for Sample Location " "and sampleLocationEnable is true, the " "VkPipelineSampleLocationsStateCreateInfoEXT::sampleLocationsInfo::sampleLocationGridSize.height (%u) " "must be evenly divided by VkMultisamplePropertiesEXT::sampleLocationGridSize.height (%u).", pipelineIndex, grid_size.height, max_grid_size.height); } if (sample_location_info.sampleLocationsPerPixel != multisample_state->rasterizationSamples) { skip |= LogError( device, "VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-01523", "vkCreateGraphicsPipelines() pCreateInfo[%u]: Because there is no dynamic state for Sample Location " "and sampleLocationEnable is true, the " "VkPipelineSampleLocationsStateCreateInfoEXT::sampleLocationsInfo::sampleLocationsPerPixel (%s) must " "be the same as the VkPipelineMultisampleStateCreateInfo::rasterizationSamples (%s).", pipelineIndex, string_VkSampleCountFlagBits(sample_location_info.sampleLocationsPerPixel), string_VkSampleCountFlagBits(multisample_state->rasterizationSamples)); } } } } if (device_extensions.vk_qcom_render_pass_shader_resolve) { uint32_t raster_samples = static_cast<uint32_t>(GetNumSamples(pPipeline)); uint32_t subpass_input_attachment_samples = 0; for (uint32_t i = 0; i < subpass_desc->inputAttachmentCount; i++) { const auto attachment = subpass_desc->pInputAttachments[i].attachment; if (attachment != VK_ATTACHMENT_UNUSED) { subpass_input_attachment_samples |= static_cast<uint32_t>(pPipeline->rp_state->createInfo.pAttachments[attachment].samples); } } if ((subpass_desc->flags & VK_SUBPASS_DESCRIPTION_FRAGMENT_REGION_BIT_QCOM) != 0) { if (raster_samples != subpass_input_attachment_samples) { skip |= LogError(device, "VUID-VkGraphicsPipelineCreateInfo-rasterizationSamples-04899", "vkCreateGraphicsPipelines() pCreateInfo[%u]: The subpass includes " "VK_SUBPASS_DESCRIPTION_FRAGMENT_REGION_BIT_QCOM " "but the input attachment VkSampleCountFlagBits (%u) does not match the " "VkPipelineMultisampleStateCreateInfo::rasterizationSamples (%u) VkSampleCountFlagBits.", pipelineIndex, subpass_input_attachment_samples, multisample_state->rasterizationSamples); } if (multisample_state->sampleShadingEnable == VK_TRUE) { skip |= LogError(device, "VUID-VkGraphicsPipelineCreateInfo-sampleShadingEnable-04900", "vkCreateGraphicsPipelines() pCreateInfo[%u]: The subpass includes " "VK_SUBPASS_DESCRIPTION_FRAGMENT_REGION_BIT_QCOM " "which requires sample shading is disabled, but " "VkPipelineMultisampleStateCreateInfo::sampleShadingEnable is true. ", pipelineIndex); } } } } skip |= ValidatePipelineCacheControlFlags(pPipeline->graphicsPipelineCI.flags, pipelineIndex, "vkCreateGraphicsPipelines", "VUID-VkGraphicsPipelineCreateInfo-pipelineCreationCacheControl-02878"); // VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-03378 if (!enabled_features.extended_dynamic_state_features.extendedDynamicState && (IsDynamic(pPipeline, VK_DYNAMIC_STATE_CULL_MODE_EXT) || IsDynamic(pPipeline, VK_DYNAMIC_STATE_FRONT_FACE_EXT) || IsDynamic(pPipeline, VK_DYNAMIC_STATE_PRIMITIVE_TOPOLOGY_EXT) || IsDynamic(pPipeline, VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT_EXT) || IsDynamic(pPipeline, VK_DYNAMIC_STATE_SCISSOR_WITH_COUNT_EXT) || IsDynamic(pPipeline, VK_DYNAMIC_STATE_VERTEX_INPUT_BINDING_STRIDE_EXT) || IsDynamic(pPipeline, VK_DYNAMIC_STATE_DEPTH_TEST_ENABLE_EXT) || IsDynamic(pPipeline, VK_DYNAMIC_STATE_DEPTH_WRITE_ENABLE_EXT) || IsDynamic(pPipeline, VK_DYNAMIC_STATE_DEPTH_COMPARE_OP_EXT) || IsDynamic(pPipeline, VK_DYNAMIC_STATE_DEPTH_BOUNDS_TEST_ENABLE_EXT) || IsDynamic(pPipeline, VK_DYNAMIC_STATE_STENCIL_TEST_ENABLE_EXT) || IsDynamic(pPipeline, VK_DYNAMIC_STATE_STENCIL_OP_EXT))) { skip |= LogError(device, "VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-03378", "vkCreateGraphicsPipelines: Extended dynamic state used by the extendedDynamicState feature is not enabled"); } // VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-04868 if (!enabled_features.extended_dynamic_state2_features.extendedDynamicState2 && (IsDynamic(pPipeline, VK_DYNAMIC_STATE_RASTERIZER_DISCARD_ENABLE_EXT) || IsDynamic(pPipeline, VK_DYNAMIC_STATE_DEPTH_BIAS_ENABLE_EXT) || IsDynamic(pPipeline, VK_DYNAMIC_STATE_PRIMITIVE_RESTART_ENABLE_EXT))) { skip |= LogError(device, "VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-04868", "vkCreateGraphicsPipelines: Extended dynamic state used by the extendedDynamicState2 feature is not enabled"); } // VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-04869 if (!enabled_features.extended_dynamic_state2_features.extendedDynamicState2LogicOp && IsDynamic(pPipeline, VK_DYNAMIC_STATE_LOGIC_OP_EXT)) { skip |= LogError( device, "VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-04869", "vkCreateGraphicsPipelines: Extended dynamic state used by the extendedDynamicState2LogicOp feature is not enabled"); } // VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-04870 if (!enabled_features.extended_dynamic_state2_features.extendedDynamicState2PatchControlPoints && IsDynamic(pPipeline, VK_DYNAMIC_STATE_PATCH_CONTROL_POINTS_EXT)) { skip |= LogError(device, "VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-04870", "vkCreateGraphicsPipelines: Extended dynamic state used by the extendedDynamicState2PatchControlPoints " "feature is not enabled"); } const VkPipelineFragmentShadingRateStateCreateInfoKHR *fragment_shading_rate_state = LvlFindInChain<VkPipelineFragmentShadingRateStateCreateInfoKHR>(pPipeline->graphicsPipelineCI.pNext); if (fragment_shading_rate_state && !IsDynamic(pPipeline, VK_DYNAMIC_STATE_FRAGMENT_SHADING_RATE_KHR)) { const char *struct_name = "VkPipelineFragmentShadingRateStateCreateInfoKHR"; if (fragment_shading_rate_state->fragmentSize.width == 0) { skip |= LogError(device, "VUID-VkGraphicsPipelineCreateInfo-pDynamicState-04494", "vkCreateGraphicsPipelines: Fragment width of %u has been specified in %s.", fragment_shading_rate_state->fragmentSize.width, struct_name); } if (fragment_shading_rate_state->fragmentSize.height == 0) { skip |= LogError(device, "VUID-VkGraphicsPipelineCreateInfo-pDynamicState-04495", "vkCreateGraphicsPipelines: Fragment height of %u has been specified in %s.", fragment_shading_rate_state->fragmentSize.height, struct_name); } if (fragment_shading_rate_state->fragmentSize.width != 0 && !IsPowerOfTwo(fragment_shading_rate_state->fragmentSize.width)) { skip |= LogError(device, "VUID-VkGraphicsPipelineCreateInfo-pDynamicState-04496", "vkCreateGraphicsPipelines: Non-power-of-two fragment width of %u has been specified in %s.", fragment_shading_rate_state->fragmentSize.width, struct_name); } if (fragment_shading_rate_state->fragmentSize.height != 0 && !IsPowerOfTwo(fragment_shading_rate_state->fragmentSize.height)) { skip |= LogError(device, "VUID-VkGraphicsPipelineCreateInfo-pDynamicState-04497", "vkCreateGraphicsPipelines: Non-power-of-two fragment height of %u has been specified in %s.", fragment_shading_rate_state->fragmentSize.height, struct_name); } if (fragment_shading_rate_state->fragmentSize.width > 4) { skip |= LogError(device, "VUID-VkGraphicsPipelineCreateInfo-pDynamicState-04498", "vkCreateGraphicsPipelines: Fragment width of %u specified in %s is too large.", fragment_shading_rate_state->fragmentSize.width, struct_name); } if (fragment_shading_rate_state->fragmentSize.height > 4) { skip |= LogError(device, "VUID-VkGraphicsPipelineCreateInfo-pDynamicState-04499", "vkCreateGraphicsPipelines: Fragment height of %u specified in %s is too large", fragment_shading_rate_state->fragmentSize.height, struct_name); } if (!enabled_features.fragment_shading_rate_features.pipelineFragmentShadingRate && fragment_shading_rate_state->fragmentSize.width != 1) { skip |= LogError(device, "VUID-VkGraphicsPipelineCreateInfo-pDynamicState-04500", "vkCreateGraphicsPipelines: Pipeline fragment width of %u has been specified in %s, but " "pipelineFragmentShadingRate is not enabled", fragment_shading_rate_state->fragmentSize.width, struct_name); } if (!enabled_features.fragment_shading_rate_features.pipelineFragmentShadingRate && fragment_shading_rate_state->fragmentSize.height != 1) { skip |= LogError(device, "VUID-VkGraphicsPipelineCreateInfo-pDynamicState-04500", "vkCreateGraphicsPipelines: Pipeline fragment height of %u has been specified in %s, but " "pipelineFragmentShadingRate is not enabled", fragment_shading_rate_state->fragmentSize.height, struct_name); } if (!enabled_features.fragment_shading_rate_features.primitiveFragmentShadingRate && fragment_shading_rate_state->combinerOps[0] != VK_FRAGMENT_SHADING_RATE_COMBINER_OP_KEEP_KHR) { skip |= LogError(device, "VUID-VkGraphicsPipelineCreateInfo-pDynamicState-04501", "vkCreateGraphicsPipelines: First combiner operation of %s has been specified in %s, but " "primitiveFragmentShadingRate is not enabled", string_VkFragmentShadingRateCombinerOpKHR(fragment_shading_rate_state->combinerOps[0]), struct_name); } if (!enabled_features.fragment_shading_rate_features.attachmentFragmentShadingRate && fragment_shading_rate_state->combinerOps[1] != VK_FRAGMENT_SHADING_RATE_COMBINER_OP_KEEP_KHR) { skip |= LogError(device, "VUID-VkGraphicsPipelineCreateInfo-pDynamicState-04502", "vkCreateGraphicsPipelines: Second combiner operation of %s has been specified in %s, but " "attachmentFragmentShadingRate is not enabled", string_VkFragmentShadingRateCombinerOpKHR(fragment_shading_rate_state->combinerOps[1]), struct_name); } if (!phys_dev_ext_props.fragment_shading_rate_props.fragmentShadingRateNonTrivialCombinerOps && (fragment_shading_rate_state->combinerOps[0] != VK_FRAGMENT_SHADING_RATE_COMBINER_OP_KEEP_KHR && fragment_shading_rate_state->combinerOps[0] != VK_FRAGMENT_SHADING_RATE_COMBINER_OP_REPLACE_KHR)) { skip |= LogError(device, "VUID-VkGraphicsPipelineCreateInfo-fragmentShadingRateNonTrivialCombinerOps-04506", "vkCreateGraphicsPipelines: First combiner operation of %s has been specified in %s, but " "fragmentShadingRateNonTrivialCombinerOps is not supported", string_VkFragmentShadingRateCombinerOpKHR(fragment_shading_rate_state->combinerOps[0]), struct_name); } if (!phys_dev_ext_props.fragment_shading_rate_props.fragmentShadingRateNonTrivialCombinerOps && (fragment_shading_rate_state->combinerOps[1] != VK_FRAGMENT_SHADING_RATE_COMBINER_OP_KEEP_KHR && fragment_shading_rate_state->combinerOps[1] != VK_FRAGMENT_SHADING_RATE_COMBINER_OP_REPLACE_KHR)) { skip |= LogError(device, "VUID-VkGraphicsPipelineCreateInfo-fragmentShadingRateNonTrivialCombinerOps-04506", "vkCreateGraphicsPipelines: Second combiner operation of %s has been specified in %s, but " "fragmentShadingRateNonTrivialCombinerOps is not supported", string_VkFragmentShadingRateCombinerOpKHR(fragment_shading_rate_state->combinerOps[1]), struct_name); } } // VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-04807 if (!enabled_features.vertex_input_dynamic_state_features.vertexInputDynamicState && IsDynamic(pPipeline, VK_DYNAMIC_STATE_VERTEX_INPUT_EXT)) { skip |= LogError(device, "VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-04807", "The vertexInputDynamicState feature must be enabled to use the VK_DYNAMIC_STATE_VERTEX_INPUT_EXT dynamic state"); } if (!enabled_features.color_write_features.colorWriteEnable && IsDynamic(pPipeline, VK_DYNAMIC_STATE_COLOR_WRITE_ENABLE_EXT)) { skip |= LogError( device, "VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-04800", "The colorWriteEnable feature must be enabled to use the VK_DYNAMIC_STATE_COLOR_WRITE_ENABLE_EXT dynamic state"); } return skip; } // Block of code at start here specifically for managing/tracking DSs // Validate that given set is valid and that it's not being used by an in-flight CmdBuffer // func_str is the name of the calling function // Return false if no errors occur // Return true if validation error occurs and callback returns true (to skip upcoming API call down the chain) bool CoreChecks::ValidateIdleDescriptorSet(VkDescriptorSet set, const char *func_str) const { if (disabled[object_in_use]) return false; bool skip = false; auto set_node = setMap.find(set); if (set_node != setMap.end()) { // TODO : This covers various error cases so should pass error enum into this function and use passed in enum here if (set_node->second->InUse()) { skip |= LogError(set, "VUID-vkFreeDescriptorSets-pDescriptorSets-00309", "Cannot call %s() on %s that is in use by a command buffer.", func_str, report_data->FormatHandle(set).c_str()); } } return skip; } // If a renderpass is active, verify that the given command type is appropriate for current subpass state bool CoreChecks::ValidateCmdSubpassState(const CMD_BUFFER_STATE *pCB, const CMD_TYPE cmd_type) const { if (!pCB->activeRenderPass) return false; bool skip = false; if (pCB->activeSubpassContents == VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS && (cmd_type != CMD_EXECUTECOMMANDS && cmd_type != CMD_NEXTSUBPASS && cmd_type != CMD_ENDRENDERPASS && cmd_type != CMD_NEXTSUBPASS2 && cmd_type != CMD_ENDRENDERPASS2)) { skip |= LogError(pCB->commandBuffer(), kVUID_Core_DrawState_InvalidCommandBuffer, "Commands cannot be called in a subpass using secondary command buffers."); } else if (pCB->activeSubpassContents == VK_SUBPASS_CONTENTS_INLINE && cmd_type == CMD_EXECUTECOMMANDS) { skip |= LogError(pCB->commandBuffer(), kVUID_Core_DrawState_InvalidCommandBuffer, "vkCmdExecuteCommands() cannot be called in a subpass using inline commands."); } return skip; } bool CoreChecks::ValidateCmdQueueFlags(const CMD_BUFFER_STATE *cb_node, const char *caller_name, VkQueueFlags required_flags, const char *error_code) const { auto pool = cb_node->command_pool.get(); if (pool) { const uint32_t queue_family_index = pool->queueFamilyIndex; const VkQueueFlags queue_flags = GetPhysicalDeviceState()->queue_family_properties[queue_family_index].queueFlags; if (!(required_flags & queue_flags)) { string required_flags_string; for (auto flag : {VK_QUEUE_TRANSFER_BIT, VK_QUEUE_GRAPHICS_BIT, VK_QUEUE_COMPUTE_BIT, VK_QUEUE_SPARSE_BINDING_BIT, VK_QUEUE_PROTECTED_BIT}) { if (flag & required_flags) { if (required_flags_string.size()) { required_flags_string += " or "; } required_flags_string += string_VkQueueFlagBits(flag); } } return LogError(cb_node->commandBuffer(), error_code, "%s(): Called in command buffer %s which was allocated from the command pool %s which was created with " "queueFamilyIndex %u which doesn't contain the required %s capability flags.", caller_name, report_data->FormatHandle(cb_node->commandBuffer()).c_str(), report_data->FormatHandle(pool->commandPool()).c_str(), queue_family_index, required_flags_string.c_str()); } } return false; } bool CoreChecks::ValidateSampleLocationsInfo(const VkSampleLocationsInfoEXT *pSampleLocationsInfo, const char *apiName) const { bool skip = false; const VkSampleCountFlagBits sample_count = pSampleLocationsInfo->sampleLocationsPerPixel; const uint32_t sample_total_size = pSampleLocationsInfo->sampleLocationGridSize.width * pSampleLocationsInfo->sampleLocationGridSize.height * SampleCountSize(sample_count); if (pSampleLocationsInfo->sampleLocationsCount != sample_total_size) { skip |= LogError(device, "VUID-VkSampleLocationsInfoEXT-sampleLocationsCount-01527", "%s: VkSampleLocationsInfoEXT::sampleLocationsCount (%u) must equal grid width * grid height * pixel " "sample rate which currently is (%u * %u * %u).", apiName, pSampleLocationsInfo->sampleLocationsCount, pSampleLocationsInfo->sampleLocationGridSize.width, pSampleLocationsInfo->sampleLocationGridSize.height, SampleCountSize(sample_count)); } if ((phys_dev_ext_props.sample_locations_props.sampleLocationSampleCounts & sample_count) == 0) { skip |= LogError(device, "VUID-VkSampleLocationsInfoEXT-sampleLocationsPerPixel-01526", "%s: VkSampleLocationsInfoEXT::sampleLocationsPerPixel of %s is not supported by the device, please check " "VkPhysicalDeviceSampleLocationsPropertiesEXT::sampleLocationSampleCounts for valid sample counts.", apiName, string_VkSampleCountFlagBits(sample_count)); } return skip; } static char const *GetCauseStr(VulkanTypedHandle obj) { if (obj.type == kVulkanObjectTypeDescriptorSet) return "destroyed or updated"; if (obj.type == kVulkanObjectTypeCommandBuffer) return "destroyed or rerecorded"; return "destroyed"; } bool CoreChecks::ReportInvalidCommandBuffer(const CMD_BUFFER_STATE *cb_state, const char *call_source) const { bool skip = false; for (const auto& entry: cb_state->broken_bindings) { const auto& obj = entry.first; const char *cause_str = GetCauseStr(obj); string vuid; std::ostringstream str; str << kVUID_Core_DrawState_InvalidCommandBuffer << "-" << object_string[obj.type]; vuid = str.str(); auto objlist = entry.second; //intentional copy objlist.add(cb_state->commandBuffer()); skip |= LogError(objlist, vuid, "You are adding %s to %s that is invalid because bound %s was %s.", call_source, report_data->FormatHandle(cb_state->commandBuffer()).c_str(), report_data->FormatHandle(obj).c_str(), cause_str); } return skip; } bool CoreChecks::ValidateIndirectCmd(VkCommandBuffer command_buffer, VkBuffer buffer, CMD_TYPE cmd_type, const char *caller_name) const { bool skip = false; const DrawDispatchVuid vuid = GetDrawDispatchVuid(cmd_type); const CMD_BUFFER_STATE *cb_state = GetCBState(command_buffer); const BUFFER_STATE *buffer_state = GetBufferState(buffer); if ((cb_state != nullptr) && (buffer_state != nullptr)) { skip |= ValidateMemoryIsBoundToBuffer(buffer_state, caller_name, vuid.indirect_contiguous_memory); skip |= ValidateBufferUsageFlags(buffer_state, VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT, true, vuid.indirect_buffer_bit, caller_name, "VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT"); if (cb_state->unprotected == false) { skip |= LogError(cb_state->commandBuffer(), vuid.indirect_protected_cb, "%s: Indirect commands can't be used in protected command buffers.", caller_name); } } return skip; } template <typename T1> bool CoreChecks::ValidateDeviceMaskToPhysicalDeviceCount(uint32_t deviceMask, const T1 object, const char *VUID) const { bool skip = false; uint32_t count = 1 << physical_device_count; if (count <= deviceMask) { skip |= LogError(object, VUID, "deviceMask(0x%" PRIx32 ") is invalid. Physical device count is %" PRIu32 ".", deviceMask, physical_device_count); } return skip; } template <typename T1> bool CoreChecks::ValidateDeviceMaskToZero(uint32_t deviceMask, const T1 object, const char *VUID) const { bool skip = false; if (deviceMask == 0) { skip |= LogError(object, VUID, "deviceMask(0x%" PRIx32 ") must be non-zero.", deviceMask); } return skip; } template <typename T1> bool CoreChecks::ValidateDeviceMaskToCommandBuffer(const CMD_BUFFER_STATE *pCB, uint32_t deviceMask, const T1 object, const char *VUID) const { bool skip = false; if ((deviceMask & pCB->initial_device_mask) != deviceMask) { skip |= LogError(object, VUID, "deviceMask(0x%" PRIx32 ") is not a subset of %s initial device mask(0x%" PRIx32 ").", deviceMask, report_data->FormatHandle(pCB->commandBuffer()).c_str(), pCB->initial_device_mask); } return skip; } bool CoreChecks::ValidateDeviceMaskToRenderPass(const CMD_BUFFER_STATE *pCB, uint32_t deviceMask, const char *VUID) const { bool skip = false; if ((deviceMask & pCB->active_render_pass_device_mask) != deviceMask) { skip |= LogError(pCB->commandBuffer(), VUID, "deviceMask(0x%" PRIx32 ") is not a subset of %s device mask(0x%" PRIx32 ").", deviceMask, report_data->FormatHandle(pCB->activeRenderPass->renderPass()).c_str(), pCB->active_render_pass_device_mask); } return skip; } // Flags validation error if the associated call is made inside a render pass. The apiName routine should ONLY be called outside a // render pass. bool CoreChecks::InsideRenderPass(const CMD_BUFFER_STATE *pCB, const char *apiName, const char *msgCode) const { bool inside = false; if (pCB->activeRenderPass) { inside = LogError(pCB->commandBuffer(), msgCode, "%s: It is invalid to issue this call inside an active %s.", apiName, report_data->FormatHandle(pCB->activeRenderPass->renderPass()).c_str()); } return inside; } // Flags validation error if the associated call is made outside a render pass. The apiName // routine should ONLY be called inside a render pass. bool CoreChecks::OutsideRenderPass(const CMD_BUFFER_STATE *pCB, const char *apiName, const char *msgCode) const { bool outside = false; if (((pCB->createInfo.level == VK_COMMAND_BUFFER_LEVEL_PRIMARY) && (!pCB->activeRenderPass)) || ((pCB->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) && (!pCB->activeRenderPass) && !(pCB->beginInfo.flags & VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT))) { outside = LogError(pCB->commandBuffer(), msgCode, "%s: This call must be issued inside an active render pass.", apiName); } return outside; } bool CoreChecks::ValidateQueueFamilyIndex(const PHYSICAL_DEVICE_STATE *pd_state, uint32_t requested_queue_family, const char *err_code, const char *cmd_name, const char *queue_family_var_name) const { bool skip = false; if (requested_queue_family >= pd_state->queue_family_known_count) { const char *conditional_ext_cmd = instance_extensions.vk_khr_get_physical_device_properties2 ? " or vkGetPhysicalDeviceQueueFamilyProperties2[KHR]" : ""; skip |= LogError(pd_state->phys_device, err_code, "%s: %s (= %" PRIu32 ") is not less than any previously obtained pQueueFamilyPropertyCount from " "vkGetPhysicalDeviceQueueFamilyProperties%s (i.e. is not less than %s).", cmd_name, queue_family_var_name, requested_queue_family, conditional_ext_cmd, std::to_string(pd_state->queue_family_known_count).c_str()); } return skip; } // Verify VkDeviceQueueCreateInfos bool CoreChecks::ValidateDeviceQueueCreateInfos(const PHYSICAL_DEVICE_STATE *pd_state, uint32_t info_count, const VkDeviceQueueCreateInfo *infos) const { bool skip = false; const uint32_t not_used = std::numeric_limits<uint32_t>::max(); struct create_flags { // uint32_t is to represent the queue family index to allow for better error messages uint32_t unprocted_index; uint32_t protected_index; create_flags(uint32_t a, uint32_t b) : unprocted_index(a), protected_index(b) {} }; layer_data::unordered_map<uint32_t, create_flags> queue_family_map; for (uint32_t i = 0; i < info_count; ++i) { const auto requested_queue_family = infos[i].queueFamilyIndex; std::string queue_family_var_name = "pCreateInfo->pQueueCreateInfos[" + std::to_string(i) + "].queueFamilyIndex"; skip |= ValidateQueueFamilyIndex(pd_state, requested_queue_family, "VUID-VkDeviceQueueCreateInfo-queueFamilyIndex-00381", "vkCreateDevice", queue_family_var_name.c_str()); if (api_version == VK_API_VERSION_1_0) { // Vulkan 1.0 didn't have protected memory so always needed unique info create_flags flags = {requested_queue_family, not_used}; if (queue_family_map.emplace(requested_queue_family, flags).second == false) { skip |= LogError(pd_state->phys_device, "VUID-VkDeviceCreateInfo-queueFamilyIndex-00372", "CreateDevice(): %s (=%" PRIu32 ") is not unique and was also used in pCreateInfo->pQueueCreateInfos[%d].", queue_family_var_name.c_str(), requested_queue_family, queue_family_map.at(requested_queue_family).unprocted_index); } } else { // Vulkan 1.1 and up can have 2 queues be same family index if one is protected and one isn't auto it = queue_family_map.find(requested_queue_family); if (it == queue_family_map.end()) { // Add first time seeing queue family index and what the create flags were create_flags new_flags = {not_used, not_used}; if ((infos[i].flags & VK_DEVICE_QUEUE_CREATE_PROTECTED_BIT) != 0) { new_flags.protected_index = requested_queue_family; } else { new_flags.unprocted_index = requested_queue_family; } queue_family_map.emplace(requested_queue_family, new_flags); } else { // The queue family was seen, so now need to make sure the flags were different if ((infos[i].flags & VK_DEVICE_QUEUE_CREATE_PROTECTED_BIT) != 0) { if (it->second.protected_index != not_used) { skip |= LogError(pd_state->phys_device, "VUID-VkDeviceCreateInfo-queueFamilyIndex-02802", "CreateDevice(): %s (=%" PRIu32 ") is not unique and was also used in pCreateInfo->pQueueCreateInfos[%d] which both have " "VK_DEVICE_QUEUE_CREATE_PROTECTED_BIT.", queue_family_var_name.c_str(), requested_queue_family, queue_family_map.at(requested_queue_family).protected_index); } else { it->second.protected_index = requested_queue_family; } } else { if (it->second.unprocted_index != not_used) { skip |= LogError(pd_state->phys_device, "VUID-VkDeviceCreateInfo-queueFamilyIndex-02802", "CreateDevice(): %s (=%" PRIu32 ") is not unique and was also used in pCreateInfo->pQueueCreateInfos[%d].", queue_family_var_name.c_str(), requested_queue_family, queue_family_map.at(requested_queue_family).unprocted_index); } else { it->second.unprocted_index = requested_queue_family; } } } } // Verify that requested queue count of queue family is known to be valid at this point in time if (requested_queue_family < pd_state->queue_family_known_count) { const auto requested_queue_count = infos[i].queueCount; const bool queue_family_has_props = requested_queue_family < pd_state->queue_family_properties.size(); // spec guarantees at least one queue for each queue family const uint32_t available_queue_count = queue_family_has_props ? pd_state->queue_family_properties[requested_queue_family].queueCount : 1; const char *conditional_ext_cmd = instance_extensions.vk_khr_get_physical_device_properties2 ? " or vkGetPhysicalDeviceQueueFamilyProperties2[KHR]" : ""; if (requested_queue_count > available_queue_count) { const std::string count_note = queue_family_has_props ? "i.e. is not less than or equal to " + std::to_string(pd_state->queue_family_properties[requested_queue_family].queueCount) : "the pQueueFamilyProperties[" + std::to_string(requested_queue_family) + "] was never obtained"; skip |= LogError( pd_state->phys_device, "VUID-VkDeviceQueueCreateInfo-queueCount-00382", "vkCreateDevice: pCreateInfo->pQueueCreateInfos[%" PRIu32 "].queueCount (=%" PRIu32 ") is not less than or equal to available queue count for this pCreateInfo->pQueueCreateInfos[%" PRIu32 "].queueFamilyIndex} (=%" PRIu32 ") obtained previously from vkGetPhysicalDeviceQueueFamilyProperties%s (%s).", i, requested_queue_count, i, requested_queue_family, conditional_ext_cmd, count_note.c_str()); } } } return skip; } bool CoreChecks::PreCallValidateCreateDevice(VkPhysicalDevice gpu, const VkDeviceCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkDevice *pDevice) const { bool skip = false; auto pd_state = GetPhysicalDeviceState(gpu); // TODO: object_tracker should perhaps do this instead // and it does not seem to currently work anyway -- the loader just crashes before this point if (!pd_state) { skip |= LogError(device, kVUID_Core_DevLimit_MustQueryCount, "Invalid call to vkCreateDevice() w/o first calling vkEnumeratePhysicalDevices()."); } else { skip |= ValidateDeviceQueueCreateInfos(pd_state, pCreateInfo->queueCreateInfoCount, pCreateInfo->pQueueCreateInfos); const VkPhysicalDeviceFragmentShadingRateFeaturesKHR *fragment_shading_rate_features = LvlFindInChain<VkPhysicalDeviceFragmentShadingRateFeaturesKHR>(pCreateInfo->pNext); if (fragment_shading_rate_features) { const VkPhysicalDeviceShadingRateImageFeaturesNV *shading_rate_image_features = LvlFindInChain<VkPhysicalDeviceShadingRateImageFeaturesNV>(pCreateInfo->pNext); if (shading_rate_image_features && shading_rate_image_features->shadingRateImage) { if (fragment_shading_rate_features->pipelineFragmentShadingRate) { skip |= LogError( pd_state->phys_device, "VUID-VkDeviceCreateInfo-shadingRateImage-04478", "vkCreateDevice: Cannot enable shadingRateImage and pipelineFragmentShadingRate features simultaneously."); } if (fragment_shading_rate_features->primitiveFragmentShadingRate) { skip |= LogError( pd_state->phys_device, "VUID-VkDeviceCreateInfo-shadingRateImage-04479", "vkCreateDevice: Cannot enable shadingRateImage and primitiveFragmentShadingRate features simultaneously."); } if (fragment_shading_rate_features->attachmentFragmentShadingRate) { skip |= LogError(pd_state->phys_device, "VUID-VkDeviceCreateInfo-shadingRateImage-04480", "vkCreateDevice: Cannot enable shadingRateImage and attachmentFragmentShadingRate features " "simultaneously."); } } const VkPhysicalDeviceFragmentDensityMapFeaturesEXT *fragment_density_map_features = LvlFindInChain<VkPhysicalDeviceFragmentDensityMapFeaturesEXT>(pCreateInfo->pNext); if (fragment_density_map_features && fragment_density_map_features->fragmentDensityMap) { if (fragment_shading_rate_features->pipelineFragmentShadingRate) { skip |= LogError(pd_state->phys_device, "VUID-VkDeviceCreateInfo-fragmentDensityMap-04481", "vkCreateDevice: Cannot enable fragmentDensityMap and pipelineFragmentShadingRate features " "simultaneously."); } if (fragment_shading_rate_features->primitiveFragmentShadingRate) { skip |= LogError(pd_state->phys_device, "VUID-VkDeviceCreateInfo-fragmentDensityMap-04482", "vkCreateDevice: Cannot enable fragmentDensityMap and primitiveFragmentShadingRate features " "simultaneously."); } if (fragment_shading_rate_features->attachmentFragmentShadingRate) { skip |= LogError(pd_state->phys_device, "VUID-VkDeviceCreateInfo-fragmentDensityMap-04483", "vkCreateDevice: Cannot enable fragmentDensityMap and attachmentFragmentShadingRate features " "simultaneously."); } } } const auto *shader_image_atomic_int64_feature = LvlFindInChain<VkPhysicalDeviceShaderImageAtomicInt64FeaturesEXT>(pCreateInfo->pNext); if (shader_image_atomic_int64_feature) { if (shader_image_atomic_int64_feature->sparseImageInt64Atomics && !shader_image_atomic_int64_feature->shaderImageInt64Atomics) { skip |= LogError(pd_state->phys_device, "VUID-VkDeviceCreateInfo-None-04896", "vkCreateDevice: if shaderImageInt64Atomics feature is enabled then sparseImageInt64Atomics " "feature must also be enabled."); } } const auto *shader_atomic_float_feature = LvlFindInChain<VkPhysicalDeviceShaderAtomicFloatFeaturesEXT>(pCreateInfo->pNext); if (shader_atomic_float_feature) { if (shader_atomic_float_feature->sparseImageFloat32Atomics && !shader_atomic_float_feature->shaderImageFloat32Atomics) { skip |= LogError(pd_state->phys_device, "VUID-VkDeviceCreateInfo-None-04897", "vkCreateDevice: if sparseImageFloat32Atomics feature is enabled then shaderImageFloat32Atomics " "feature must also be enabled."); } if (shader_atomic_float_feature->sparseImageFloat32AtomicAdd && !shader_atomic_float_feature->shaderImageFloat32AtomicAdd) { skip |= LogError(pd_state->phys_device, "VUID-VkDeviceCreateInfo-None-04898", "vkCreateDevice: if sparseImageFloat32AtomicAdd feature is enabled then shaderImageFloat32AtomicAdd " "feature must also be enabled."); } } const auto *device_group_ci = LvlFindInChain<VkDeviceGroupDeviceCreateInfo>(pCreateInfo->pNext); if (device_group_ci) { for (uint32_t i = 0; i < device_group_ci->physicalDeviceCount - 1; ++i) { for (uint32_t j = i + 1; j < device_group_ci->physicalDeviceCount; ++j) { if (device_group_ci->pPhysicalDevices[i] == device_group_ci->pPhysicalDevices[j]) { skip |= LogError(pd_state->phys_device, "VUID-VkDeviceGroupDeviceCreateInfo-pPhysicalDevices-00375", "vkCreateDevice: VkDeviceGroupDeviceCreateInfo has a duplicated physical device " "in pPhysicalDevices [%" PRIu32 "] and [%" PRIu32 "].", i, j); } } } } } return skip; } void CoreChecks::PostCallRecordCreateDevice(VkPhysicalDevice gpu, const VkDeviceCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkDevice *pDevice, VkResult result) { // The state tracker sets up the device state StateTracker::PostCallRecordCreateDevice(gpu, pCreateInfo, pAllocator, pDevice, result); // Add the callback hooks for the functions that are either broadly or deeply used and that the ValidationStateTracker refactor // would be messier without. // TODO: Find a good way to do this hooklessly. ValidationObject *device_object = GetLayerDataPtr(get_dispatch_key(*pDevice), layer_data_map); ValidationObject *validation_data = GetValidationObject(device_object->object_dispatch, LayerObjectTypeCoreValidation); CoreChecks *core_checks = static_cast<CoreChecks *>(validation_data); core_checks->SetSetImageViewInitialLayoutCallback( [core_checks](CMD_BUFFER_STATE *cb_node, const IMAGE_VIEW_STATE &iv_state, VkImageLayout layout) -> void { core_checks->SetImageViewInitialLayout(cb_node, iv_state, layout); }); // Allocate shader validation cache if (!disabled[shader_validation_caching] && !disabled[shader_validation] && !core_checks->core_validation_cache) { std::string validation_cache_path; auto tmp_path = GetEnvironment("TMPDIR"); if (!tmp_path.size()) tmp_path = GetEnvironment("TMP"); if (!tmp_path.size()) tmp_path = GetEnvironment("TEMP"); if (!tmp_path.size()) tmp_path = "//tmp"; core_checks->validation_cache_path = tmp_path + "//shader_validation_cache.bin"; std::vector<char> validation_cache_data; std::ifstream read_file(core_checks->validation_cache_path.c_str(), std::ios::in | std::ios::binary); if (read_file) { std::copy(std::istreambuf_iterator<char>(read_file), {}, std::back_inserter(validation_cache_data)); read_file.close(); } else { LogInfo(core_checks->device, "VUID-NONE", "Cannot open shader validation cache at %s for reading (it may not exist yet)", core_checks->validation_cache_path.c_str()); } VkValidationCacheCreateInfoEXT cacheCreateInfo = {}; cacheCreateInfo.sType = VK_STRUCTURE_TYPE_VALIDATION_CACHE_CREATE_INFO_EXT; cacheCreateInfo.pNext = NULL; cacheCreateInfo.initialDataSize = validation_cache_data.size(); cacheCreateInfo.pInitialData = validation_cache_data.data(); cacheCreateInfo.flags = 0; CoreLayerCreateValidationCacheEXT(*pDevice, &cacheCreateInfo, nullptr, &core_checks->core_validation_cache); } } void CoreChecks::PreCallRecordDestroyDevice(VkDevice device, const VkAllocationCallbacks *pAllocator) { if (!device) return; imageLayoutMap.clear(); StateTracker::PreCallRecordDestroyDevice(device, pAllocator); if (core_validation_cache) { size_t validation_cache_size = 0; void *validation_cache_data = nullptr; CoreLayerGetValidationCacheDataEXT(device, core_validation_cache, &validation_cache_size, nullptr); validation_cache_data = (char *)malloc(sizeof(char) * validation_cache_size); if (!validation_cache_data) { LogInfo(device, "VUID-NONE", "Validation Cache Memory Error"); return; } VkResult result = CoreLayerGetValidationCacheDataEXT(device, core_validation_cache, &validation_cache_size, validation_cache_data); if (result != VK_SUCCESS) { LogInfo(device, "VUID-NONE", "Validation Cache Retrieval Error"); return; } FILE *write_file = fopen(validation_cache_path.c_str(), "wb"); if (write_file) { fwrite(validation_cache_data, sizeof(char), validation_cache_size, write_file); fclose(write_file); } else { LogInfo(device, "VUID-NONE", "Cannot open shader validation cache at %s for writing", validation_cache_path.c_str()); } free(validation_cache_data); CoreLayerDestroyValidationCacheEXT(device, core_validation_cache, NULL); } } bool CoreChecks::ValidateStageMaskHost(const Location &loc, VkPipelineStageFlags2KHR stageMask) const { bool skip = false; if ((stageMask & VK_PIPELINE_STAGE_HOST_BIT) != 0) { const auto &vuid = sync_vuid_maps::GetQueueSubmitVUID(loc, sync_vuid_maps::SubmitError::kHostStageMask); skip |= LogError( device, vuid, "%s stage mask must not include VK_PIPELINE_STAGE_HOST_BIT as the stage can't be invoked inside a command buffer.", loc.Message().c_str()); } return skip; } // Note: This function assumes that the global lock is held by the calling thread. // For the given queue, verify the queue state up to the given seq number. // Currently the only check is to make sure that if there are events to be waited on prior to // a QueryReset, make sure that all such events have been signalled. bool CoreChecks::VerifyQueueStateToSeq(const QUEUE_STATE *initial_queue, uint64_t initial_seq) const { bool skip = false; // sequence number we want to validate up to, per queue layer_data::unordered_map<const QUEUE_STATE *, uint64_t> target_seqs{{initial_queue, initial_seq}}; // sequence number we've completed validation for, per queue layer_data::unordered_map<const QUEUE_STATE *, uint64_t> done_seqs; std::vector<const QUEUE_STATE *> worklist{initial_queue}; while (worklist.size()) { auto queue = worklist.back(); worklist.pop_back(); auto target_seq = target_seqs[queue]; auto seq = std::max(done_seqs[queue], queue->seq); auto sub_it = queue->submissions.begin() + int(seq - queue->seq); // seq >= queue->seq for (; seq < target_seq; ++sub_it, ++seq) { for (auto &wait : sub_it->waitSemaphores) { auto other_queue = GetQueueState(wait.queue); if (other_queue == queue) continue; // semaphores /always/ point backwards, so no point here. auto other_target_seq = std::max(target_seqs[other_queue], wait.seq); auto other_done_seq = std::max(done_seqs[other_queue], other_queue->seq); // if this wait is for another queue, and covers new sequence // numbers beyond what we've already validated, mark the new // target seq and (possibly-re)add the queue to the worklist. if (other_done_seq < other_target_seq) { target_seqs[other_queue] = other_target_seq; worklist.push_back(other_queue); } } } // finally mark the point we've now validated this queue to. done_seqs[queue] = seq; } return skip; } // When the given fence is retired, verify outstanding queue operations through the point of the fence bool CoreChecks::VerifyQueueStateToFence(VkFence fence) const { auto fence_state = GetFenceState(fence); if (fence_state && fence_state->scope == kSyncScopeInternal && VK_NULL_HANDLE != fence_state->signaler.first) { return VerifyQueueStateToSeq(GetQueueState(fence_state->signaler.first), fence_state->signaler.second); } return false; } bool CoreChecks::ValidateCommandBufferSimultaneousUse(const Location &loc, const CMD_BUFFER_STATE *pCB, int current_submit_count) const { using sync_vuid_maps::GetQueueSubmitVUID; using sync_vuid_maps::SubmitError; bool skip = false; if ((pCB->InUse() || current_submit_count > 1) && !(pCB->beginInfo.flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT)) { const auto &vuid = sync_vuid_maps::GetQueueSubmitVUID(loc, SubmitError::kCmdNotSimultaneous); skip |= LogError(device, vuid, "%s %s is already in use and is not marked for simultaneous use.", loc.Message().c_str(), report_data->FormatHandle(pCB->commandBuffer()).c_str()); } return skip; } bool CoreChecks::ValidateCommandBufferState(const CMD_BUFFER_STATE *cb_state, const char *call_source, int current_submit_count, const char *vu_id) const { bool skip = false; if (disabled[command_buffer_state]) return skip; // Validate ONE_TIME_SUBMIT_BIT CB is not being submitted more than once if ((cb_state->beginInfo.flags & VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT) && (cb_state->submitCount + current_submit_count > 1)) { skip |= LogError(cb_state->commandBuffer(), kVUID_Core_DrawState_CommandBufferSingleSubmitViolation, "%s was begun w/ VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT set, but has been submitted 0x%" PRIxLEAST64 "times.", report_data->FormatHandle(cb_state->commandBuffer()).c_str(), cb_state->submitCount + current_submit_count); } // Validate that cmd buffers have been updated switch (cb_state->state) { case CB_INVALID_INCOMPLETE: case CB_INVALID_COMPLETE: skip |= ReportInvalidCommandBuffer(cb_state, call_source); break; case CB_NEW: skip |= LogError(cb_state->commandBuffer(), vu_id, "%s used in the call to %s is unrecorded and contains no commands.", report_data->FormatHandle(cb_state->commandBuffer()).c_str(), call_source); break; case CB_RECORDING: skip |= LogError(cb_state->commandBuffer(), kVUID_Core_DrawState_NoEndCommandBuffer, "You must call vkEndCommandBuffer() on %s before this call to %s!", report_data->FormatHandle(cb_state->commandBuffer()).c_str(), call_source); break; default: /* recorded */ break; } return skip; } // Check that the queue family index of 'queue' matches one of the entries in pQueueFamilyIndices bool CoreChecks::ValidImageBufferQueue(const CMD_BUFFER_STATE *cb_node, const VulkanTypedHandle &object, uint32_t queueFamilyIndex, uint32_t count, const uint32_t *indices) const { bool found = false; bool skip = false; for (uint32_t i = 0; i < count; i++) { if (indices[i] == queueFamilyIndex) { found = true; break; } } if (!found) { LogObjectList objlist(cb_node->commandBuffer()); objlist.add(object); skip = LogError(objlist, "VUID-vkQueueSubmit-pSubmits-04626", "vkQueueSubmit: %s contains %s which was not created allowing concurrent access to " "this queue family %d.", report_data->FormatHandle(cb_node->commandBuffer()).c_str(), report_data->FormatHandle(object).c_str(), queueFamilyIndex); } return skip; } // Validate that queueFamilyIndices of primary command buffers match this queue // Secondary command buffers were previously validated in vkCmdExecuteCommands(). bool CoreChecks::ValidateQueueFamilyIndices(const Location &loc, const CMD_BUFFER_STATE *pCB, VkQueue queue) const { using sync_vuid_maps::GetQueueSubmitVUID; using sync_vuid_maps::SubmitError; bool skip = false; auto pool = pCB->command_pool.get(); auto queue_state = GetQueueState(queue); if (pool && queue_state) { if (pool->queueFamilyIndex != queue_state->queueFamilyIndex) { LogObjectList objlist(pCB->commandBuffer()); objlist.add(queue); const auto &vuid = GetQueueSubmitVUID(loc, SubmitError::kCmdWrongQueueFamily); skip |= LogError(objlist, vuid, "%s Primary %s created in queue family %d is being submitted on %s " "from queue family %d.", loc.Message().c_str(), report_data->FormatHandle(pCB->commandBuffer()).c_str(), pool->queueFamilyIndex, report_data->FormatHandle(queue).c_str(), queue_state->queueFamilyIndex); } // Ensure that any bound images or buffers created with SHARING_MODE_CONCURRENT have access to the current queue family for (const auto &object : pCB->object_bindings) { if (object.type == kVulkanObjectTypeImage) { auto image_state = object.node ? (IMAGE_STATE *)object.node : GetImageState(object.Cast<VkImage>()); if (image_state && image_state->createInfo.sharingMode == VK_SHARING_MODE_CONCURRENT) { skip |= ValidImageBufferQueue(pCB, object, queue_state->queueFamilyIndex, image_state->createInfo.queueFamilyIndexCount, image_state->createInfo.pQueueFamilyIndices); } } else if (object.type == kVulkanObjectTypeBuffer) { auto buffer_state = object.node ? (BUFFER_STATE *)object.node : GetBufferState(object.Cast<VkBuffer>()); if (buffer_state && buffer_state->createInfo.sharingMode == VK_SHARING_MODE_CONCURRENT) { skip |= ValidImageBufferQueue(pCB, object, queue_state->queueFamilyIndex, buffer_state->createInfo.queueFamilyIndexCount, buffer_state->createInfo.pQueueFamilyIndices); } } } } return skip; } bool CoreChecks::ValidatePrimaryCommandBufferState( const Location &loc, const CMD_BUFFER_STATE *pCB, int current_submit_count, QFOTransferCBScoreboards<QFOImageTransferBarrier> *qfo_image_scoreboards, QFOTransferCBScoreboards<QFOBufferTransferBarrier> *qfo_buffer_scoreboards) const { using sync_vuid_maps::GetQueueSubmitVUID; using sync_vuid_maps::SubmitError; // Track in-use for resources off of primary and any secondary CBs bool skip = false; if (pCB->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) { const auto &vuid = GetQueueSubmitVUID(loc, SubmitError::kSecondaryCmdInSubmit); skip |= LogError(pCB->commandBuffer(), vuid, "%s Command buffer %s must be allocated with VK_COMMAND_BUFFER_LEVEL_PRIMARY.", loc.Message().c_str(), report_data->FormatHandle(pCB->commandBuffer()).c_str()); } else { for (const auto *sub_cb : pCB->linkedCommandBuffers) { skip |= ValidateQueuedQFOTransfers(sub_cb, qfo_image_scoreboards, qfo_buffer_scoreboards); // TODO: replace with InvalidateCommandBuffers() at recording. if ((sub_cb->primaryCommandBuffer != pCB->commandBuffer()) && !(sub_cb->beginInfo.flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT)) { LogObjectList objlist(device); objlist.add(pCB->commandBuffer()); objlist.add(sub_cb->commandBuffer()); objlist.add(sub_cb->primaryCommandBuffer); const auto &vuid = GetQueueSubmitVUID(loc, SubmitError::kSecondaryCmdNotSimultaneous); skip |= LogError(objlist, vuid, "%s %s was submitted with secondary %s but that buffer has subsequently been bound to " "primary %s and it does not have VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT set.", loc.Message().c_str(), report_data->FormatHandle(pCB->commandBuffer()).c_str(), report_data->FormatHandle(sub_cb->commandBuffer()).c_str(), report_data->FormatHandle(sub_cb->primaryCommandBuffer).c_str()); } } } // If USAGE_SIMULTANEOUS_USE_BIT not set then CB cannot already be executing on device skip |= ValidateCommandBufferSimultaneousUse(loc, pCB, current_submit_count); skip |= ValidateQueuedQFOTransfers(pCB, qfo_image_scoreboards, qfo_buffer_scoreboards); const char *vuid = loc.function == Func::vkQueueSubmit ? "VUID-vkQueueSubmit-pCommandBuffers-00072" : "VUID-vkQueueSubmit2KHR-commandBuffer-03876"; skip |= ValidateCommandBufferState(pCB, loc.StringFunc().c_str(), current_submit_count, vuid); return skip; } bool CoreChecks::ValidateFenceForSubmit(const FENCE_STATE *pFence, const char *inflight_vuid, const char *retired_vuid, const char *func_name) const { bool skip = false; if (pFence && pFence->scope == kSyncScopeInternal) { if (pFence->state == FENCE_INFLIGHT) { skip |= LogError(pFence->fence(), inflight_vuid, "%s: %s is already in use by another submission.", func_name, report_data->FormatHandle(pFence->fence()).c_str()); } else if (pFence->state == FENCE_RETIRED) { skip |= LogError(pFence->fence(), retired_vuid, "%s: %s submitted in SIGNALED state. Fences must be reset before being submitted", func_name, report_data->FormatHandle(pFence->fence()).c_str()); } } return skip; } void CoreChecks::PostCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo *pSubmits, VkFence fence, VkResult result) { StateTracker::PostCallRecordQueueSubmit(queue, submitCount, pSubmits, fence, result); if (result != VK_SUCCESS) return; // The triply nested for duplicates that in the StateTracker, but avoids the need for two additional callbacks. for (uint32_t submit_idx = 0; submit_idx < submitCount; submit_idx++) { const VkSubmitInfo *submit = &pSubmits[submit_idx]; for (uint32_t i = 0; i < submit->commandBufferCount; i++) { auto cb_node = GetCBState(submit->pCommandBuffers[i]); if (cb_node) { for (auto *secondary_cmd_buffer : cb_node->linkedCommandBuffers) { UpdateCmdBufImageLayouts(secondary_cmd_buffer); RecordQueuedQFOTransfers(secondary_cmd_buffer); } UpdateCmdBufImageLayouts(cb_node); RecordQueuedQFOTransfers(cb_node); } } } } void CoreChecks::PostCallRecordQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR *pSubmits, VkFence fence, VkResult result) { StateTracker::PostCallRecordQueueSubmit2KHR(queue, submitCount, pSubmits, fence, result); if (result != VK_SUCCESS) return; // The triply nested for duplicates that in the StateTracker, but avoids the need for two additional callbacks. for (uint32_t submit_idx = 0; submit_idx < submitCount; submit_idx++) { const VkSubmitInfo2KHR *submit = &pSubmits[submit_idx]; for (uint32_t i = 0; i < submit->commandBufferInfoCount; i++) { auto cb_node = GetCBState(submit->pCommandBufferInfos[i].commandBuffer); if (cb_node) { for (auto *secondaryCmdBuffer : cb_node->linkedCommandBuffers) { UpdateCmdBufImageLayouts(secondaryCmdBuffer); RecordQueuedQFOTransfers(secondaryCmdBuffer); } UpdateCmdBufImageLayouts(cb_node); RecordQueuedQFOTransfers(cb_node); } } } } bool CoreChecks::SemaphoreWasSignaled(VkSemaphore semaphore) const { for (auto &pair : queueMap) { const QUEUE_STATE &queue_state = pair.second; for (const auto &submission : queue_state.submissions) { for (const auto &signal_semaphore : submission.signalSemaphores) { if (signal_semaphore.semaphore == semaphore) { return true; } } } } return false; } struct SemaphoreSubmitState { const CoreChecks *core; VkQueueFlags queue_flags; layer_data::unordered_set<VkSemaphore> signaled_semaphores; layer_data::unordered_set<VkSemaphore> unsignaled_semaphores; layer_data::unordered_set<VkSemaphore> internal_semaphores; SemaphoreSubmitState(const CoreChecks *core_, VkQueueFlags queue_flags_) : core(core_), queue_flags(queue_flags_) {} bool ValidateWaitSemaphore(const core_error::Location &loc, VkQueue queue, VkSemaphore semaphore, uint64_t value, uint32_t device_Index) { using sync_vuid_maps::GetQueueSubmitVUID; using sync_vuid_maps::SubmitError; bool skip = false; LogObjectList objlist(semaphore); objlist.add(queue); const auto *pSemaphore = core->GetSemaphoreState(semaphore); if (pSemaphore && pSemaphore->type == VK_SEMAPHORE_TYPE_BINARY_KHR && (pSemaphore->scope == kSyncScopeInternal || internal_semaphores.count(semaphore))) { if (unsignaled_semaphores.count(semaphore) || (!(signaled_semaphores.count(semaphore)) && !(pSemaphore->signaled) && !core->SemaphoreWasSignaled(semaphore))) { auto error = core->device_extensions.vk_khr_timeline_semaphore ? SubmitError::kTimelineCannotBeSignalled : SubmitError::kBinaryCannotBeSignalled; const auto &vuid = GetQueueSubmitVUID(loc, error); skip |= core->LogError( objlist, pSemaphore->scope == kSyncScopeInternal ? vuid : kVUID_Core_DrawState_QueueForwardProgress, "%s Queue %s is waiting on semaphore (%s) that has no way to be signaled.", loc.Message().c_str(), core->report_data->FormatHandle(queue).c_str(), core->report_data->FormatHandle(semaphore).c_str()); } else { signaled_semaphores.erase(semaphore); unsignaled_semaphores.insert(semaphore); } } if (pSemaphore && pSemaphore->type == VK_SEMAPHORE_TYPE_BINARY_KHR && pSemaphore->scope == kSyncScopeExternalTemporary) { internal_semaphores.insert(semaphore); } if (pSemaphore && pSemaphore->type == VK_SEMAPHORE_TYPE_BINARY_KHR) { for (const auto &q : core->queueMap) { if (q.first != queue) { for (const auto &cb : q.second.submissions) { for (const auto &wait_semaphore : cb.waitSemaphores) { if (wait_semaphore.semaphore == semaphore) { const char *vuid = loc.function == core_error::Func::vkQueueSubmit ? "VUID-vkQueueSubmit-pWaitSemaphores-00068" : "VUID-vkQueueSubmit2KHR-semaphore-03871"; skip |= core->LogError(objlist, vuid, "%s Queue %s is already waiting on semaphore (%s).", loc.Message().c_str(), core->report_data->FormatHandle(q.first).c_str(), core->report_data->FormatHandle(semaphore).c_str()); } } } } } } return skip; } bool ValidateSignalSemaphore(const core_error::Location &loc, VkQueue queue, VkSemaphore semaphore, uint64_t value, uint32_t deviceIndex) { using sync_vuid_maps::GetQueueSubmitVUID; using sync_vuid_maps::SubmitError; bool skip = false; LogObjectList objlist(semaphore); objlist.add(queue); const auto *pSemaphore = core->GetSemaphoreState(semaphore); if (pSemaphore && pSemaphore->type == VK_SEMAPHORE_TYPE_TIMELINE_KHR && value <= pSemaphore->payload) { const auto &vuid = GetQueueSubmitVUID(loc, SubmitError::kTimelineSemSmallValue); skip |= core->LogError(objlist, vuid, "%s signal value (0x%" PRIx64 ") in %s must be greater than current timeline semaphore %s value (0x%" PRIx64 ")", loc.Message().c_str(), pSemaphore->payload, core->report_data->FormatHandle(queue).c_str(), core->report_data->FormatHandle(semaphore).c_str(), value); } if (pSemaphore && pSemaphore->type == VK_SEMAPHORE_TYPE_BINARY_KHR && (pSemaphore->scope == kSyncScopeInternal || internal_semaphores.count(semaphore))) { if (signaled_semaphores.count(semaphore) || (!(unsignaled_semaphores.count(semaphore)) && pSemaphore->signaled)) { objlist.add(pSemaphore->signaler.first); skip |= core->LogError(objlist, kVUID_Core_DrawState_QueueForwardProgress, "%s is signaling %s (%s) that was previously " "signaled by %s but has not since been waited on by any queue.", loc.Message().c_str(), core->report_data->FormatHandle(queue).c_str(), core->report_data->FormatHandle(semaphore).c_str(), core->report_data->FormatHandle(pSemaphore->signaler.first).c_str()); } else { unsignaled_semaphores.erase(semaphore); signaled_semaphores.insert(semaphore); } } return skip; } }; bool CoreChecks::ValidateSemaphoresForSubmit(SemaphoreSubmitState &state, VkQueue queue, const VkSubmitInfo *submit, const Location &outer_loc) const { bool skip = false; auto *timeline_semaphore_submit_info = LvlFindInChain<VkTimelineSemaphoreSubmitInfo>(submit->pNext); for (uint32_t i = 0; i < submit->waitSemaphoreCount; ++i) { uint64_t value = 0; uint32_t device_index = 0; // TODO: VkSemaphore semaphore = submit->pWaitSemaphores[i]; LogObjectList objlist(semaphore); objlist.add(queue); if (submit->pWaitDstStageMask) { auto loc = outer_loc.dot(Field::pWaitDstStageMask, i); skip |= ValidatePipelineStage(objlist, loc, state.queue_flags, submit->pWaitDstStageMask[i]); skip |= ValidateStageMaskHost(loc, submit->pWaitDstStageMask[i]); } const auto *semaphore_state = GetSemaphoreState(semaphore); if (!semaphore_state) { continue; } auto loc = outer_loc.dot(Field::pWaitSemaphores, i); if (semaphore_state->type == VK_SEMAPHORE_TYPE_TIMELINE) { if (timeline_semaphore_submit_info == nullptr) { skip |= LogError(semaphore, "VUID-VkSubmitInfo-pWaitSemaphores-03239", "%s (%s) is a timeline semaphore, but VkSubmitInfo does " "not include an instance of VkTimelineSemaphoreSubmitInfo", loc.Message().c_str(), report_data->FormatHandle(semaphore).c_str()); continue; } else if (submit->waitSemaphoreCount != timeline_semaphore_submit_info->waitSemaphoreValueCount) { skip |= LogError(semaphore, "VUID-VkSubmitInfo-pNext-03240", "%s (%s) is a timeline semaphore, it contains an " "instance of VkTimelineSemaphoreSubmitInfo, but waitSemaphoreValueCount (%u) is different than " "waitSemaphoreCount (%u)", loc.Message().c_str(), report_data->FormatHandle(semaphore).c_str(), timeline_semaphore_submit_info->waitSemaphoreValueCount, submit->waitSemaphoreCount); continue; } value = timeline_semaphore_submit_info->pWaitSemaphoreValues[i]; } skip |= state.ValidateWaitSemaphore(outer_loc.dot(Field::pWaitSemaphores, i), queue, semaphore, value, device_index); } for (uint32_t i = 0; i < submit->signalSemaphoreCount; ++i) { VkSemaphore semaphore = submit->pSignalSemaphores[i]; uint64_t value = 0; uint32_t device_index = 0; const auto *semaphore_state = GetSemaphoreState(semaphore); if (!semaphore_state) { continue; } auto loc = outer_loc.dot(Field::pSignalSemaphores, i); if (semaphore_state->type == VK_SEMAPHORE_TYPE_TIMELINE) { if (timeline_semaphore_submit_info == nullptr) { skip |= LogError(semaphore, "VUID-VkSubmitInfo-pWaitSemaphores-03239", "%s (%s) is a timeline semaphore, but VkSubmitInfo" "does not include an instance of VkTimelineSemaphoreSubmitInfo", loc.Message().c_str(), report_data->FormatHandle(semaphore).c_str()); continue; } else if (submit->signalSemaphoreCount != timeline_semaphore_submit_info->signalSemaphoreValueCount) { skip |= LogError(semaphore, "VUID-VkSubmitInfo-pNext-03241", "%s (%s) is a timeline semaphore, it contains an " "instance of VkTimelineSemaphoreSubmitInfo, but signalSemaphoreValueCount (%u) is different than " "signalSemaphoreCount (%u)", loc.Message().c_str(), report_data->FormatHandle(semaphore).c_str(), timeline_semaphore_submit_info->signalSemaphoreValueCount, submit->signalSemaphoreCount); continue; } value = timeline_semaphore_submit_info->pSignalSemaphoreValues[i]; } skip |= state.ValidateSignalSemaphore(loc, queue, semaphore, value, device_index); } return skip; } bool CoreChecks::ValidateSemaphoresForSubmit(SemaphoreSubmitState &state, VkQueue queue, const VkSubmitInfo2KHR *submit, const Location &outer_loc) const { bool skip = false; for (uint32_t i = 0; i < submit->waitSemaphoreInfoCount; ++i) { const auto &sem_info = submit->pWaitSemaphoreInfos[i]; Location loc = outer_loc.dot(Field::pWaitSemaphoreInfos, i); skip |= ValidatePipelineStage(LogObjectList(sem_info.semaphore), loc.dot(Field::stageMask), state.queue_flags, sem_info.stageMask); skip |= ValidateStageMaskHost(loc.dot(Field::stageMask), sem_info.stageMask); skip |= state.ValidateWaitSemaphore(loc, queue, sem_info.semaphore, sem_info.value, sem_info.deviceIndex); } for (uint32_t i = 0; i < submit->signalSemaphoreInfoCount; ++i) { const auto &sem_info = submit->pSignalSemaphoreInfos[i]; auto loc = outer_loc.dot(Field::pSignalSemaphoreInfos, i); skip |= ValidatePipelineStage(LogObjectList(sem_info.semaphore), loc.dot(Field::stageMask), state.queue_flags, sem_info.stageMask); skip |= ValidateStageMaskHost(loc.dot(Field::stageMask), sem_info.stageMask); skip |= state.ValidateSignalSemaphore(loc, queue, sem_info.semaphore, sem_info.value, sem_info.deviceIndex); } return skip; } bool CoreChecks::ValidateMaxTimelineSemaphoreValueDifference(const Location &loc, VkSemaphore semaphore, uint64_t value) const { using sync_vuid_maps::GetQueueSubmitVUID; using sync_vuid_maps::SubmitError; bool skip = false; const auto semaphore_state = GetSemaphoreState(semaphore); if (semaphore_state->type != VK_SEMAPHORE_TYPE_TIMELINE) return false; uint64_t diff = value > semaphore_state->payload ? value - semaphore_state->payload : semaphore_state->payload - value; if (diff > phys_dev_props_core12.maxTimelineSemaphoreValueDifference) { const auto &vuid = GetQueueSubmitVUID(loc, SubmitError::kTimelineSemMaxDiff); skip |= LogError(semaphore, vuid, "%s value exceeds limit regarding current semaphore %s payload", loc.Message().c_str(), report_data->FormatHandle(semaphore).c_str()); } for (auto &pair : queueMap) { const QUEUE_STATE &queue_state = pair.second; for (const auto &submission : queue_state.submissions) { for (const auto &signal_semaphore : submission.signalSemaphores) { if (signal_semaphore.semaphore == semaphore) { diff = value > signal_semaphore.payload ? value - signal_semaphore.payload : signal_semaphore.payload - value; if (diff > phys_dev_props_core12.maxTimelineSemaphoreValueDifference) { const auto &vuid = GetQueueSubmitVUID(loc, SubmitError::kTimelineSemMaxDiff); skip |= LogError(semaphore, vuid, "%s value exceeds limit regarding pending semaphore %s signal value", loc.Message().c_str(), report_data->FormatHandle(semaphore).c_str()); } } } for (const auto &wait_semaphore : submission.waitSemaphores) { if (wait_semaphore.semaphore == semaphore) { diff = value > wait_semaphore.payload ? value - wait_semaphore.payload : wait_semaphore.payload - value; if (diff > phys_dev_props_core12.maxTimelineSemaphoreValueDifference) { const auto &vuid = GetQueueSubmitVUID(loc, SubmitError::kTimelineSemMaxDiff); skip |= LogError(semaphore, vuid, "%s value exceeds limit regarding pending semaphore %s wait value", loc.Message().c_str(), report_data->FormatHandle(semaphore).c_str()); } } } } } return skip; } struct CommandBufferSubmitState { const CoreChecks *core; const QUEUE_STATE *queue_state; QFOTransferCBScoreboards<QFOImageTransferBarrier> qfo_image_scoreboards; QFOTransferCBScoreboards<QFOBufferTransferBarrier> qfo_buffer_scoreboards; vector<VkCommandBuffer> current_cmds; GlobalImageLayoutMap overlay_image_layout_map; QueryMap local_query_to_state_map; EventToStageMap local_event_to_stage_map; CommandBufferSubmitState(const CoreChecks *c, const char *func, const QUEUE_STATE *q) : core(c), queue_state(q) {} bool Validate(const core_error::Location &loc, VkCommandBuffer cmd, uint32_t perf_pass) { bool skip = false; const auto *cb_node = core->GetCBState(cmd); if (cb_node == nullptr) { return skip; } skip |= core->ValidateCmdBufImageLayouts(loc, cb_node, core->imageLayoutMap, overlay_image_layout_map); current_cmds.push_back(cmd); skip |= core->ValidatePrimaryCommandBufferState(loc, cb_node, static_cast<int>(std::count(current_cmds.begin(), current_cmds.end(), cmd)), &qfo_image_scoreboards, &qfo_buffer_scoreboards); skip |= core->ValidateQueueFamilyIndices(loc, cb_node, queue_state->queue); for (const auto &descriptor_set : cb_node->validate_descriptorsets_in_queuesubmit) { const cvdescriptorset::DescriptorSet *set_node = core->GetSetNode(descriptor_set.first); if (!set_node) { continue; } for (const auto &cmd_info : descriptor_set.second) { std::string function = loc.StringFunc(); function += ", "; function += cmd_info.function; for (const auto &binding_info : cmd_info.binding_infos) { std::string error; std::vector<uint32_t> dynamic_offsets; // dynamic data isn't allowed in UPDATE_AFTER_BIND, so dynamicOffsets is always empty. // This submit time not record time... const bool record_time_validate = false; layer_data::optional<layer_data::unordered_map<VkImageView, VkImageLayout>> checked_layouts; if (set_node->GetTotalDescriptorCount() > cvdescriptorset::PrefilterBindRequestMap::kManyDescriptors_) { checked_layouts.emplace(); } skip |= core->ValidateDescriptorSetBindingData( cb_node, set_node, dynamic_offsets, binding_info, cmd_info.framebuffer, cmd_info.attachments.get(), cmd_info.subpasses.get(), record_time_validate, function.c_str(), core->GetDrawDispatchVuid(cmd_info.cmd_type), checked_layouts); } } } // Potential early exit here as bad object state may crash in delayed function calls if (skip) { return true; } // Call submit-time functions to validate or update local mirrors of state (to preserve const-ness at validate time) for (auto &function : cb_node->queue_submit_functions) { skip |= function(core, queue_state); } for (auto &function : cb_node->eventUpdates) { skip |= function(core, /*do_validate*/ true, &local_event_to_stage_map); } VkQueryPool first_perf_query_pool = VK_NULL_HANDLE; for (auto &function : cb_node->queryUpdates) { skip |= function(core, /*do_validate*/ true, first_perf_query_pool, perf_pass, &local_query_to_state_map); } return skip; } }; bool CoreChecks::PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo *pSubmits, VkFence fence) const { const auto *fence_state = GetFenceState(fence); bool skip = ValidateFenceForSubmit(fence_state, "VUID-vkQueueSubmit-fence-00064", "VUID-vkQueueSubmit-fence-00063", "vkQueueSubmit()"); if (skip) { return true; } const auto queue_state = GetQueueState(queue); CommandBufferSubmitState cb_submit_state(this, "vkQueueSubmit()", queue_state); SemaphoreSubmitState sem_submit_state( this, GetPhysicalDeviceState()->queue_family_properties[queue_state->queueFamilyIndex].queueFlags); // Now verify each individual submit for (uint32_t submit_idx = 0; submit_idx < submitCount; submit_idx++) { const VkSubmitInfo *submit = &pSubmits[submit_idx]; const auto perf_submit = LvlFindInChain<VkPerformanceQuerySubmitInfoKHR>(submit->pNext); uint32_t perf_pass = perf_submit ? perf_submit->counterPassIndex : 0; Location loc(Func::vkQueueSubmit, Struct::VkSubmitInfo, Field::pSubmits, submit_idx); for (uint32_t i = 0; i < submit->commandBufferCount; i++) { skip |= cb_submit_state.Validate(loc.dot(Field::pCommandBuffers, i), submit->pCommandBuffers[i], perf_pass); } skip |= ValidateSemaphoresForSubmit(sem_submit_state, queue, submit, loc); auto chained_device_group_struct = LvlFindInChain<VkDeviceGroupSubmitInfo>(submit->pNext); if (chained_device_group_struct && chained_device_group_struct->commandBufferCount > 0) { for (uint32_t i = 0; i < chained_device_group_struct->commandBufferCount; ++i) { skip |= ValidateDeviceMaskToPhysicalDeviceCount(chained_device_group_struct->pCommandBufferDeviceMasks[i], queue, "VUID-VkDeviceGroupSubmitInfo-pCommandBufferDeviceMasks-00086"); } } auto protected_submit_info = LvlFindInChain<VkProtectedSubmitInfo>(submit->pNext); if (protected_submit_info) { const bool protected_submit = protected_submit_info->protectedSubmit == VK_TRUE; // Only check feature once for submit if ((protected_submit == true) && (enabled_features.core11.protectedMemory == VK_FALSE)) { skip |= LogError(queue, "VUID-VkProtectedSubmitInfo-protectedSubmit-01816", "vkQueueSubmit(): The protectedMemory device feature is disabled, can't submit a protected queue " "to %s pSubmits[%u]", report_data->FormatHandle(queue).c_str(), submit_idx); } // Make sure command buffers are all protected or unprotected for (uint32_t i = 0; i < submit->commandBufferCount; i++) { const CMD_BUFFER_STATE *cb_state = GetCBState(submit->pCommandBuffers[i]); if (cb_state != nullptr) { if ((cb_state->unprotected == true) && (protected_submit == true)) { LogObjectList objlist(cb_state->commandBuffer()); objlist.add(queue); skip |= LogError(objlist, "VUID-VkSubmitInfo-pNext-04148", "vkQueueSubmit(): command buffer %s is unprotected while queue %s pSubmits[%u] has " "VkProtectedSubmitInfo:protectedSubmit set to VK_TRUE", report_data->FormatHandle(cb_state->commandBuffer()).c_str(), report_data->FormatHandle(queue).c_str(), submit_idx); } if ((cb_state->unprotected == false) && (protected_submit == false)) { LogObjectList objlist(cb_state->commandBuffer()); objlist.add(queue); skip |= LogError(objlist, "VUID-VkSubmitInfo-pNext-04120", "vkQueueSubmit(): command buffer %s is protected while queue %s pSubmits[%u] has " "VkProtectedSubmitInfo:protectedSubmit set to VK_FALSE", report_data->FormatHandle(cb_state->commandBuffer()).c_str(), report_data->FormatHandle(queue).c_str(), submit_idx); } } } } } if (skip) return skip; // Now verify maxTimelineSemaphoreValueDifference for (uint32_t submit_idx = 0; submit_idx < submitCount; submit_idx++) { Location loc(Func::vkQueueSubmit, Struct::VkSubmitInfo, Field::pSubmits, submit_idx); const VkSubmitInfo *submit = &pSubmits[submit_idx]; auto *info = LvlFindInChain<VkTimelineSemaphoreSubmitInfo>(submit->pNext); if (info) { // If there are any timeline semaphores, this condition gets checked before the early return above if (info->waitSemaphoreValueCount) { for (uint32_t i = 0; i < submit->waitSemaphoreCount; ++i) { VkSemaphore semaphore = submit->pWaitSemaphores[i]; skip |= ValidateMaxTimelineSemaphoreValueDifference(loc.dot(Field::pWaitSemaphores, i), semaphore, info->pWaitSemaphoreValues[i]); } } // If there are any timeline semaphores, this condition gets checked before the early return above if (info->signalSemaphoreValueCount) { for (uint32_t i = 0; i < submit->signalSemaphoreCount; ++i) { VkSemaphore semaphore = submit->pSignalSemaphores[i]; skip |= ValidateMaxTimelineSemaphoreValueDifference(loc.dot(Field::pSignalSemaphores, i), semaphore, info->pSignalSemaphoreValues[i]); } } } } return skip; } bool CoreChecks::PreCallValidateQueueSubmit2KHR(VkQueue queue, uint32_t submitCount, const VkSubmitInfo2KHR *pSubmits, VkFence fence) const { const auto *pFence = GetFenceState(fence); bool skip = ValidateFenceForSubmit(pFence, "VUID-vkQueueSubmit2KHR-fence-04895", "VUID-vkQueueSubmit2KHR-fence-04894", "vkQueueSubmit2KHR()"); if (skip) { return true; } if (!enabled_features.synchronization2_features.synchronization2) { skip |= LogError(queue, "VUID-vkQueueSubmit2KHR-synchronization2-03866", "vkQueueSubmit2KHR(): Synchronization2 feature is not enabled"); } const auto queue_state = GetQueueState(queue); CommandBufferSubmitState cb_submit_state(this, "vkQueueSubmit2KHR()", queue_state); SemaphoreSubmitState sem_submit_state( this, GetPhysicalDeviceState()->queue_family_properties[queue_state->queueFamilyIndex].queueFlags); // Now verify each individual submit for (uint32_t submit_idx = 0; submit_idx < submitCount; submit_idx++) { const VkSubmitInfo2KHR *submit = &pSubmits[submit_idx]; const auto perf_submit = LvlFindInChain<VkPerformanceQuerySubmitInfoKHR>(submit->pNext); uint32_t perf_pass = perf_submit ? perf_submit->counterPassIndex : 0; Location loc(Func::vkQueueSubmit2KHR, Struct::VkSubmitInfo2KHR, Field::pSubmits, submit_idx); skip |= ValidateSemaphoresForSubmit(sem_submit_state, queue, submit, loc); bool protectedSubmit = (submit->flags & VK_SUBMIT_PROTECTED_BIT_KHR) != 0; // Only check feature once for submit if ((protectedSubmit == true) && (enabled_features.core11.protectedMemory == VK_FALSE)) { skip |= LogError(queue, "VUID-VkSubmitInfo2KHR-flags-03885", "vkQueueSubmit2KHR(): The protectedMemory device feature is disabled, can't submit a protected queue " "to %s pSubmits[%u]", report_data->FormatHandle(queue).c_str(), submit_idx); } for (uint32_t i = 0; i < submit->commandBufferInfoCount; i++) { auto info_loc = loc.dot(Field::pCommandBufferInfos, i); info_loc.structure = Struct::VkCommandBufferSubmitInfoKHR; skip |= cb_submit_state.Validate(info_loc.dot(Field::commandBuffer), submit->pCommandBufferInfos[i].commandBuffer, perf_pass); skip |= ValidateDeviceMaskToPhysicalDeviceCount(submit->pCommandBufferInfos[i].deviceMask, queue, "VUID-VkCommandBufferSubmitInfoKHR-deviceMask-03891"); // Make sure command buffers are all protected or unprotected const CMD_BUFFER_STATE *cb_state = GetCBState(submit->pCommandBufferInfos[i].commandBuffer); if (cb_state != nullptr) { if ((cb_state->unprotected == true) && (protectedSubmit == true)) { LogObjectList objlist(cb_state->commandBuffer()); objlist.add(queue); skip |= LogError(objlist, "VUID-VkSubmitInfo2KHR-flags-03886", "vkQueueSubmit2KHR(): command buffer %s is unprotected while queue %s pSubmits[%u] has " "VK_SUBMIT_PROTECTED_BIT_KHR set", report_data->FormatHandle(cb_state->commandBuffer()).c_str(), report_data->FormatHandle(queue).c_str(), submit_idx); } if ((cb_state->unprotected == false) && (protectedSubmit == false)) { LogObjectList objlist(cb_state->commandBuffer()); objlist.add(queue); skip |= LogError(objlist, "VUID-VkSubmitInfo2KHR-flags-03887", "vkQueueSubmit2KHR(): command buffer %s is protected while queue %s pSubmitInfos[%u] has " "VK_SUBMIT_PROTECTED_BIT_KHR not set", report_data->FormatHandle(cb_state->commandBuffer()).c_str(), report_data->FormatHandle(queue).c_str(), submit_idx); } } } } if (skip) return skip; // Now verify maxTimelineSemaphoreValueDifference for (uint32_t submit_idx = 0; submit_idx < submitCount; submit_idx++) { const VkSubmitInfo2KHR *submit = &pSubmits[submit_idx]; Location outer_loc(Func::vkQueueSubmit2KHR, Struct::VkSubmitInfo2KHR, Field::pSubmits, submit_idx); // If there are any timeline semaphores, this condition gets checked before the early return above for (uint32_t i = 0; i < submit->waitSemaphoreInfoCount; ++i) { const auto *sem_info = &submit->pWaitSemaphoreInfos[i]; auto loc = outer_loc.dot(Field::pWaitSemaphoreInfos, i); skip |= ValidateMaxTimelineSemaphoreValueDifference(loc.dot(Field::semaphore), sem_info->semaphore, sem_info->value); } // If there are any timeline semaphores, this condition gets checked before the early return above for (uint32_t i = 0; i < submit->signalSemaphoreInfoCount; ++i) { const auto *sem_info = &submit->pSignalSemaphoreInfos[i]; auto loc = outer_loc.dot(Field::pSignalSemaphoreInfos, i); skip |= ValidateMaxTimelineSemaphoreValueDifference(loc.dot(Field::semaphore), sem_info->semaphore, sem_info->value); } } return skip; } #ifdef AHB_VALIDATION_SUPPORT // Android-specific validation that uses types defined only on Android and only for NDK versions // that support the VK_ANDROID_external_memory_android_hardware_buffer extension. // This chunk could move into a seperate core_validation_android.cpp file... ? // clang-format off // Map external format and usage flags to/from equivalent Vulkan flags // (Tables as of v1.1.92) // AHardwareBuffer Format Vulkan Format // ====================== ============= // AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM VK_FORMAT_R8G8B8A8_UNORM // AHARDWAREBUFFER_FORMAT_R8G8B8X8_UNORM VK_FORMAT_R8G8B8A8_UNORM // AHARDWAREBUFFER_FORMAT_R8G8B8_UNORM VK_FORMAT_R8G8B8_UNORM // AHARDWAREBUFFER_FORMAT_R5G6B5_UNORM VK_FORMAT_R5G6B5_UNORM_PACK16 // AHARDWAREBUFFER_FORMAT_R16G16B16A16_FLOAT VK_FORMAT_R16G16B16A16_SFLOAT // AHARDWAREBUFFER_FORMAT_R10G10B10A2_UNORM VK_FORMAT_A2B10G10R10_UNORM_PACK32 // AHARDWAREBUFFER_FORMAT_D16_UNORM VK_FORMAT_D16_UNORM // AHARDWAREBUFFER_FORMAT_D24_UNORM VK_FORMAT_X8_D24_UNORM_PACK32 // AHARDWAREBUFFER_FORMAT_D24_UNORM_S8_UINT VK_FORMAT_D24_UNORM_S8_UINT // AHARDWAREBUFFER_FORMAT_D32_FLOAT VK_FORMAT_D32_SFLOAT // AHARDWAREBUFFER_FORMAT_D32_FLOAT_S8_UINT VK_FORMAT_D32_SFLOAT_S8_UINT // AHARDWAREBUFFER_FORMAT_S8_UINT VK_FORMAT_S8_UINT // The AHARDWAREBUFFER_FORMAT_* are an enum in the NDK headers, but get passed in to Vulkan // as uint32_t. Casting the enums here avoids scattering casts around in the code. std::map<uint32_t, VkFormat> ahb_format_map_a2v = { { (uint32_t)AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM }, { (uint32_t)AHARDWAREBUFFER_FORMAT_R8G8B8X8_UNORM, VK_FORMAT_R8G8B8A8_UNORM }, { (uint32_t)AHARDWAREBUFFER_FORMAT_R8G8B8_UNORM, VK_FORMAT_R8G8B8_UNORM }, { (uint32_t)AHARDWAREBUFFER_FORMAT_R5G6B5_UNORM, VK_FORMAT_R5G6B5_UNORM_PACK16 }, { (uint32_t)AHARDWAREBUFFER_FORMAT_R16G16B16A16_FLOAT, VK_FORMAT_R16G16B16A16_SFLOAT }, { (uint32_t)AHARDWAREBUFFER_FORMAT_R10G10B10A2_UNORM, VK_FORMAT_A2B10G10R10_UNORM_PACK32 }, { (uint32_t)AHARDWAREBUFFER_FORMAT_D16_UNORM, VK_FORMAT_D16_UNORM }, { (uint32_t)AHARDWAREBUFFER_FORMAT_D24_UNORM, VK_FORMAT_X8_D24_UNORM_PACK32 }, { (uint32_t)AHARDWAREBUFFER_FORMAT_D24_UNORM_S8_UINT, VK_FORMAT_D24_UNORM_S8_UINT }, { (uint32_t)AHARDWAREBUFFER_FORMAT_D32_FLOAT, VK_FORMAT_D32_SFLOAT }, { (uint32_t)AHARDWAREBUFFER_FORMAT_D32_FLOAT_S8_UINT, VK_FORMAT_D32_SFLOAT_S8_UINT }, { (uint32_t)AHARDWAREBUFFER_FORMAT_S8_UINT, VK_FORMAT_S8_UINT } }; // AHardwareBuffer Usage Vulkan Usage or Creation Flag (Intermixed - Aargh!) // ===================== =================================================== // None VK_IMAGE_USAGE_TRANSFER_SRC_BIT // None VK_IMAGE_USAGE_TRANSFER_DST_BIT // AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE VK_IMAGE_USAGE_SAMPLED_BIT // AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT // AHARDWAREBUFFER_USAGE_GPU_FRAMEBUFFER VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT // AHARDWAREBUFFER_USAGE_GPU_FRAMEBUFFER VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT // AHARDWAREBUFFER_USAGE_GPU_CUBE_MAP VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT // AHARDWAREBUFFER_USAGE_GPU_MIPMAP_COMPLETE None // AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT VK_IMAGE_CREATE_PROTECTED_BIT // None VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT // None VK_IMAGE_CREATE_EXTENDED_USAGE_BIT // Same casting rationale. De-mixing the table to prevent type confusion and aliasing std::map<uint64_t, VkImageUsageFlags> ahb_usage_map_a2v = { { (uint64_t)AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE, (VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT) }, { (uint64_t)AHARDWAREBUFFER_USAGE_GPU_FRAMEBUFFER, (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) }, { (uint64_t)AHARDWAREBUFFER_USAGE_GPU_MIPMAP_COMPLETE, 0 }, // No equivalent }; std::map<uint64_t, VkImageCreateFlags> ahb_create_map_a2v = { { (uint64_t)AHARDWAREBUFFER_USAGE_GPU_CUBE_MAP, VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT }, { (uint64_t)AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT, VK_IMAGE_CREATE_PROTECTED_BIT }, { (uint64_t)AHARDWAREBUFFER_USAGE_GPU_MIPMAP_COMPLETE, 0 }, // No equivalent }; std::map<VkImageUsageFlags, uint64_t> ahb_usage_map_v2a = { { VK_IMAGE_USAGE_SAMPLED_BIT, (uint64_t)AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE }, { VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT, (uint64_t)AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE }, { VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, (uint64_t)AHARDWAREBUFFER_USAGE_GPU_FRAMEBUFFER }, { VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, (uint64_t)AHARDWAREBUFFER_USAGE_GPU_FRAMEBUFFER }, }; std::map<VkImageCreateFlags, uint64_t> ahb_create_map_v2a = { { VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT, (uint64_t)AHARDWAREBUFFER_USAGE_GPU_CUBE_MAP }, { VK_IMAGE_CREATE_PROTECTED_BIT, (uint64_t)AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT }, }; // clang-format on // // AHB-extension new APIs // bool CoreChecks::PreCallValidateGetAndroidHardwareBufferPropertiesANDROID( VkDevice device, const struct AHardwareBuffer *buffer, VkAndroidHardwareBufferPropertiesANDROID *pProperties) const { bool skip = false; // buffer must be a valid Android hardware buffer object with at least one of the AHARDWAREBUFFER_USAGE_GPU_* usage flags. AHardwareBuffer_Desc ahb_desc; AHardwareBuffer_describe(buffer, &ahb_desc); uint32_t required_flags = AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE | AHARDWAREBUFFER_USAGE_GPU_FRAMEBUFFER | AHARDWAREBUFFER_USAGE_GPU_CUBE_MAP | AHARDWAREBUFFER_USAGE_GPU_MIPMAP_COMPLETE | AHARDWAREBUFFER_USAGE_GPU_DATA_BUFFER; if (0 == (ahb_desc.usage & required_flags)) { skip |= LogError(device, "VUID-vkGetAndroidHardwareBufferPropertiesANDROID-buffer-01884", "vkGetAndroidHardwareBufferPropertiesANDROID: The AHardwareBuffer's AHardwareBuffer_Desc.usage (0x%" PRIx64 ") does not have any AHARDWAREBUFFER_USAGE_GPU_* flags set.", ahb_desc.usage); } return skip; } bool CoreChecks::PreCallValidateGetMemoryAndroidHardwareBufferANDROID(VkDevice device, const VkMemoryGetAndroidHardwareBufferInfoANDROID *pInfo, struct AHardwareBuffer **pBuffer) const { bool skip = false; const DEVICE_MEMORY_STATE *mem_info = GetDevMemState(pInfo->memory); // VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID must have been included in // VkExportMemoryAllocateInfo::handleTypes when memory was created. if (!mem_info->IsExport() || (0 == (mem_info->export_handle_type_flags & VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID))) { skip |= LogError(device, "VUID-VkMemoryGetAndroidHardwareBufferInfoANDROID-handleTypes-01882", "vkGetMemoryAndroidHardwareBufferANDROID: %s was not allocated for export, or the " "export handleTypes (0x%" PRIx32 ") did not contain VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID.", report_data->FormatHandle(pInfo->memory).c_str(), mem_info->export_handle_type_flags); } // If the pNext chain of the VkMemoryAllocateInfo used to allocate memory included a VkMemoryDedicatedAllocateInfo // with non-NULL image member, then that image must already be bound to memory. if (mem_info->IsDedicatedImage()) { const auto image_state = GetImageState(mem_info->dedicated->handle.Cast<VkImage>()); if ((nullptr == image_state) || (0 == (image_state->GetBoundMemory().count(mem_info->mem())))) { LogObjectList objlist(device); objlist.add(pInfo->memory); objlist.add(mem_info->dedicated->handle); skip |= LogError(objlist, "VUID-VkMemoryGetAndroidHardwareBufferInfoANDROID-pNext-01883", "vkGetMemoryAndroidHardwareBufferANDROID: %s was allocated using a dedicated " "%s, but that image is not bound to the VkDeviceMemory object.", report_data->FormatHandle(pInfo->memory).c_str(), report_data->FormatHandle(mem_info->dedicated->handle).c_str()); } } return skip; } // // AHB-specific validation within non-AHB APIs // bool CoreChecks::ValidateAllocateMemoryANDROID(const VkMemoryAllocateInfo *alloc_info) const { bool skip = false; auto import_ahb_info = LvlFindInChain<VkImportAndroidHardwareBufferInfoANDROID>(alloc_info->pNext); auto exp_mem_alloc_info = LvlFindInChain<VkExportMemoryAllocateInfo>(alloc_info->pNext); auto mem_ded_alloc_info = LvlFindInChain<VkMemoryDedicatedAllocateInfo>(alloc_info->pNext); if ((import_ahb_info) && (NULL != import_ahb_info->buffer)) { // This is an import with handleType of VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID AHardwareBuffer_Desc ahb_desc = {}; AHardwareBuffer_describe(import_ahb_info->buffer, &ahb_desc); // Validate AHardwareBuffer_Desc::usage is a valid usage for imported AHB // // BLOB & GPU_DATA_BUFFER combo specifically allowed if ((AHARDWAREBUFFER_FORMAT_BLOB != ahb_desc.format) || (0 == (ahb_desc.usage & AHARDWAREBUFFER_USAGE_GPU_DATA_BUFFER))) { // Otherwise, must be a combination from the AHardwareBuffer Format and Usage Equivalence tables // Usage must have at least one bit from the table. It may have additional bits not in the table uint64_t ahb_equiv_usage_bits = AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE | AHARDWAREBUFFER_USAGE_GPU_FRAMEBUFFER | AHARDWAREBUFFER_USAGE_GPU_CUBE_MAP | AHARDWAREBUFFER_USAGE_GPU_MIPMAP_COMPLETE | AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT; if (0 == (ahb_desc.usage & ahb_equiv_usage_bits)) { skip |= LogError(device, "VUID-VkImportAndroidHardwareBufferInfoANDROID-buffer-01881", "vkAllocateMemory: The AHardwareBuffer_Desc's usage (0x%" PRIx64 ") is not compatible with Vulkan.", ahb_desc.usage); } } // Collect external buffer info auto pdebi = LvlInitStruct<VkPhysicalDeviceExternalBufferInfo>(); pdebi.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID; if (AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE & ahb_desc.usage) { pdebi.usage |= ahb_usage_map_a2v[AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE]; } if (AHARDWAREBUFFER_USAGE_GPU_FRAMEBUFFER & ahb_desc.usage) { pdebi.usage |= ahb_usage_map_a2v[AHARDWAREBUFFER_USAGE_GPU_FRAMEBUFFER]; } auto ext_buf_props = LvlInitStruct<VkExternalBufferProperties>(); DispatchGetPhysicalDeviceExternalBufferProperties(physical_device, &pdebi, &ext_buf_props); // If buffer is not NULL, Android hardware buffers must be supported for import, as reported by // VkExternalImageFormatProperties or VkExternalBufferProperties. if (0 == (ext_buf_props.externalMemoryProperties.externalMemoryFeatures & VK_EXTERNAL_MEMORY_FEATURE_IMPORTABLE_BIT)) { // Collect external format info auto pdeifi = LvlInitStruct<VkPhysicalDeviceExternalImageFormatInfo>(); pdeifi.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID; auto pdifi2 = LvlInitStruct<VkPhysicalDeviceImageFormatInfo2>(&pdeifi); if (0 < ahb_format_map_a2v.count(ahb_desc.format)) pdifi2.format = ahb_format_map_a2v[ahb_desc.format]; pdifi2.type = VK_IMAGE_TYPE_2D; // Seems likely pdifi2.tiling = VK_IMAGE_TILING_OPTIMAL; // Ditto if (AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE & ahb_desc.usage) { pdifi2.usage |= ahb_usage_map_a2v[AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE]; } if (AHARDWAREBUFFER_USAGE_GPU_FRAMEBUFFER & ahb_desc.usage) { pdifi2.usage |= ahb_usage_map_a2v[AHARDWAREBUFFER_USAGE_GPU_FRAMEBUFFER]; } if (AHARDWAREBUFFER_USAGE_GPU_CUBE_MAP & ahb_desc.usage) { pdifi2.flags |= ahb_create_map_a2v[AHARDWAREBUFFER_USAGE_GPU_CUBE_MAP]; } if (AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT & ahb_desc.usage) { pdifi2.flags |= ahb_create_map_a2v[AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT]; } auto ext_img_fmt_props = LvlInitStruct<VkExternalImageFormatProperties>(); auto ifp2 = LvlInitStruct<VkImageFormatProperties2>(&ext_img_fmt_props); VkResult fmt_lookup_result = DispatchGetPhysicalDeviceImageFormatProperties2(physical_device, &pdifi2, &ifp2); if ((VK_SUCCESS != fmt_lookup_result) || (0 == (ext_img_fmt_props.externalMemoryProperties.externalMemoryFeatures & VK_EXTERNAL_MEMORY_FEATURE_IMPORTABLE_BIT))) { skip |= LogError(device, "VUID-VkImportAndroidHardwareBufferInfoANDROID-buffer-01880", "vkAllocateMemory: Neither the VkExternalImageFormatProperties nor the VkExternalBufferProperties " "structs for the AHardwareBuffer include the VK_EXTERNAL_MEMORY_FEATURE_IMPORTABLE_BIT flag."); } } // Retrieve buffer and format properties of the provided AHardwareBuffer auto ahb_format_props = LvlInitStruct<VkAndroidHardwareBufferFormatPropertiesANDROID>(); auto ahb_props = LvlInitStruct<VkAndroidHardwareBufferPropertiesANDROID>(&ahb_format_props); DispatchGetAndroidHardwareBufferPropertiesANDROID(device, import_ahb_info->buffer, &ahb_props); // allocationSize must be the size returned by vkGetAndroidHardwareBufferPropertiesANDROID for the Android hardware buffer if (alloc_info->allocationSize != ahb_props.allocationSize) { skip |= LogError(device, "VUID-VkMemoryAllocateInfo-allocationSize-02383", "vkAllocateMemory: VkMemoryAllocateInfo struct with chained VkImportAndroidHardwareBufferInfoANDROID " "struct, allocationSize (%" PRId64 ") does not match the AHardwareBuffer's reported allocationSize (%" PRId64 ").", alloc_info->allocationSize, ahb_props.allocationSize); } // memoryTypeIndex must be one of those returned by vkGetAndroidHardwareBufferPropertiesANDROID for the AHardwareBuffer // Note: memoryTypeIndex is an index, memoryTypeBits is a bitmask uint32_t mem_type_bitmask = 1 << alloc_info->memoryTypeIndex; if (0 == (mem_type_bitmask & ahb_props.memoryTypeBits)) { skip |= LogError(device, "VUID-VkMemoryAllocateInfo-memoryTypeIndex-02385", "vkAllocateMemory: VkMemoryAllocateInfo struct with chained VkImportAndroidHardwareBufferInfoANDROID " "struct, memoryTypeIndex (%" PRId32 ") does not correspond to a bit set in AHardwareBuffer's reported " "memoryTypeBits bitmask (0x%" PRIx32 ").", alloc_info->memoryTypeIndex, ahb_props.memoryTypeBits); } // Checks for allocations without a dedicated allocation requirement if ((nullptr == mem_ded_alloc_info) || (VK_NULL_HANDLE == mem_ded_alloc_info->image)) { // the Android hardware buffer must have a format of AHARDWAREBUFFER_FORMAT_BLOB and a usage that includes // AHARDWAREBUFFER_USAGE_GPU_DATA_BUFFER if (((uint64_t)AHARDWAREBUFFER_FORMAT_BLOB != ahb_desc.format) || (0 == (ahb_desc.usage & AHARDWAREBUFFER_USAGE_GPU_DATA_BUFFER))) { skip |= LogError( device, "VUID-VkMemoryAllocateInfo-pNext-02384", "vkAllocateMemory: VkMemoryAllocateInfo struct with chained VkImportAndroidHardwareBufferInfoANDROID " "struct without a dedicated allocation requirement, while the AHardwareBuffer_Desc's format ( %u ) is not " "AHARDWAREBUFFER_FORMAT_BLOB or usage (0x%" PRIx64 ") does not include AHARDWAREBUFFER_USAGE_GPU_DATA_BUFFER.", ahb_desc.format, ahb_desc.usage); } } else { // Checks specific to import with a dedicated allocation requirement const VkImageCreateInfo *ici = &(GetImageState(mem_ded_alloc_info->image)->createInfo); // The Android hardware buffer's usage must include at least one of AHARDWAREBUFFER_USAGE_GPU_FRAMEBUFFER or // AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE if (0 == (ahb_desc.usage & (AHARDWAREBUFFER_USAGE_GPU_FRAMEBUFFER | AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE))) { skip |= LogError( device, "VUID-VkMemoryAllocateInfo-pNext-02386", "vkAllocateMemory: VkMemoryAllocateInfo struct with chained VkImportAndroidHardwareBufferInfoANDROID and a " "dedicated allocation requirement, while the AHardwareBuffer's usage (0x%" PRIx64 ") contains neither AHARDWAREBUFFER_USAGE_GPU_FRAMEBUFFER nor AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE.", ahb_desc.usage); } // the format of image must be VK_FORMAT_UNDEFINED or the format returned by // vkGetAndroidHardwareBufferPropertiesANDROID if ((ici->format != ahb_format_props.format) && (VK_FORMAT_UNDEFINED != ici->format)) { skip |= LogError(device, "VUID-VkMemoryAllocateInfo-pNext-02387", "vkAllocateMemory: VkMemoryAllocateInfo struct with chained " "VkImportAndroidHardwareBufferInfoANDROID, the dedicated allocation image's " "format (%s) is not VK_FORMAT_UNDEFINED and does not match the AHardwareBuffer's format (%s).", string_VkFormat(ici->format), string_VkFormat(ahb_format_props.format)); } // The width, height, and array layer dimensions of image and the Android hardwarebuffer must be identical if ((ici->extent.width != ahb_desc.width) || (ici->extent.height != ahb_desc.height) || (ici->arrayLayers != ahb_desc.layers)) { skip |= LogError(device, "VUID-VkMemoryAllocateInfo-pNext-02388", "vkAllocateMemory: VkMemoryAllocateInfo struct with chained " "VkImportAndroidHardwareBufferInfoANDROID, the dedicated allocation image's " "width, height, and arrayLayers (%" PRId32 " %" PRId32 " %" PRId32 ") do not match those of the AHardwareBuffer (%" PRId32 " %" PRId32 " %" PRId32 ").", ici->extent.width, ici->extent.height, ici->arrayLayers, ahb_desc.width, ahb_desc.height, ahb_desc.layers); } // If the Android hardware buffer's usage includes AHARDWAREBUFFER_USAGE_GPU_MIPMAP_COMPLETE, the image must // have either a full mipmap chain or exactly 1 mip level. // // NOTE! The language of this VUID contradicts the language in the spec (1.1.93), which says "The // AHARDWAREBUFFER_USAGE_GPU_MIPMAP_COMPLETE flag does not correspond to a Vulkan image usage or creation flag. Instead, // its presence indicates that the Android hardware buffer contains a complete mipmap chain, and its absence indicates // that the Android hardware buffer contains only a single mip level." // // TODO: This code implements the VUID's meaning, but it seems likely that the spec text is actually correct. // Clarification requested. if ((ahb_desc.usage & AHARDWAREBUFFER_USAGE_GPU_MIPMAP_COMPLETE) && (ici->mipLevels != 1) && (ici->mipLevels != FullMipChainLevels(ici->extent))) { skip |= LogError(device, "VUID-VkMemoryAllocateInfo-pNext-02389", "vkAllocateMemory: VkMemoryAllocateInfo struct with chained VkImportAndroidHardwareBufferInfoANDROID, " "usage includes AHARDWAREBUFFER_USAGE_GPU_MIPMAP_COMPLETE but mipLevels (%" PRId32 ") is neither 1 nor full mip " "chain levels (%" PRId32 ").", ici->mipLevels, FullMipChainLevels(ici->extent)); } // each bit set in the usage of image must be listed in AHardwareBuffer Usage Equivalence, and if there is a // corresponding AHARDWAREBUFFER_USAGE bit listed that bit must be included in the Android hardware buffer's // AHardwareBuffer_Desc::usage if (ici->usage & ~(VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) { skip |= LogError(device, "VUID-VkMemoryAllocateInfo-pNext-02390", "vkAllocateMemory: VkMemoryAllocateInfo struct with chained VkImportAndroidHardwareBufferInfoANDROID, " "dedicated image usage bits (0x%" PRIx32 ") include an issue not listed in the AHardwareBuffer Usage Equivalence table.", ici->usage); } std::vector<VkImageUsageFlags> usages = {VK_IMAGE_USAGE_SAMPLED_BIT, VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT}; for (VkImageUsageFlags ubit : usages) { if (ici->usage & ubit) { uint64_t ahb_usage = ahb_usage_map_v2a[ubit]; if (0 == (ahb_usage & ahb_desc.usage)) { skip |= LogError( device, "VUID-VkMemoryAllocateInfo-pNext-02390", "vkAllocateMemory: VkMemoryAllocateInfo struct with chained VkImportAndroidHardwareBufferInfoANDROID, " "The dedicated image usage bit %s equivalent is not in AHardwareBuffer_Desc.usage (0x%" PRIx64 ") ", string_VkImageUsageFlags(ubit).c_str(), ahb_desc.usage); } } } } } else { // Not an import if ((exp_mem_alloc_info) && (mem_ded_alloc_info) && (0 != (VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID & exp_mem_alloc_info->handleTypes)) && (VK_NULL_HANDLE != mem_ded_alloc_info->image)) { // This is an Android HW Buffer export if (0 != alloc_info->allocationSize) { skip |= LogError(device, "VUID-VkMemoryAllocateInfo-pNext-01874", "vkAllocateMemory: pNext chain indicates a dedicated Android Hardware Buffer export allocation, " "but allocationSize is non-zero."); } } else { if (0 == alloc_info->allocationSize) { skip |= LogError( device, "VUID-VkMemoryAllocateInfo-pNext-01874", "vkAllocateMemory: pNext chain does not indicate a dedicated export allocation, but allocationSize is 0."); }; } } return skip; } bool CoreChecks::ValidateGetImageMemoryRequirementsANDROID(const VkImage image, const char *func_name) const { bool skip = false; const IMAGE_STATE *image_state = GetImageState(image); if (image_state != nullptr) { if (image_state->IsExternalAHB() && (0 == image_state->GetBoundMemory().size())) { const char *vuid = strcmp(func_name, "vkGetImageMemoryRequirements()") == 0 ? "VUID-vkGetImageMemoryRequirements-image-04004" : "VUID-VkImageMemoryRequirementsInfo2-image-01897"; skip |= LogError(image, vuid, "%s: Attempt get image memory requirements for an image created with a " "VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID handleType, which has not yet been " "bound to memory.", func_name); } } return skip; } bool CoreChecks::ValidateGetPhysicalDeviceImageFormatProperties2ANDROID( const VkPhysicalDeviceImageFormatInfo2 *pImageFormatInfo, const VkImageFormatProperties2 *pImageFormatProperties) const { bool skip = false; const VkAndroidHardwareBufferUsageANDROID *ahb_usage = LvlFindInChain<VkAndroidHardwareBufferUsageANDROID>(pImageFormatProperties->pNext); if (nullptr != ahb_usage) { const VkPhysicalDeviceExternalImageFormatInfo *pdeifi = LvlFindInChain<VkPhysicalDeviceExternalImageFormatInfo>(pImageFormatInfo->pNext); if ((nullptr == pdeifi) || (VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID != pdeifi->handleType)) { skip |= LogError(device, "VUID-vkGetPhysicalDeviceImageFormatProperties2-pNext-01868", "vkGetPhysicalDeviceImageFormatProperties2: pImageFormatProperties includes a chained " "VkAndroidHardwareBufferUsageANDROID struct, but pImageFormatInfo does not include a chained " "VkPhysicalDeviceExternalImageFormatInfo struct with handleType " "VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID."); } } return skip; } bool CoreChecks::ValidateBufferImportedHandleANDROID(const char *func_name, VkExternalMemoryHandleTypeFlags handleType, VkDeviceMemory memory, VkBuffer buffer) const { bool skip = false; if ((handleType & VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID) == 0) { const char *vuid = (strcmp(func_name, "vkBindBufferMemory()") == 0) ? "VUID-vkBindBufferMemory-memory-02986" : "VUID-VkBindBufferMemoryInfo-memory-02986"; LogObjectList objlist(buffer); objlist.add(memory); skip |= LogError(objlist, vuid, "%s: The VkDeviceMemory (%s) was created with an AHB import operation which is not set " "VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID in the VkBuffer (%s) " "VkExternalMemoryBufferreateInfo::handleType (%s)", func_name, report_data->FormatHandle(memory).c_str(), report_data->FormatHandle(buffer).c_str(), string_VkExternalMemoryHandleTypeFlags(handleType).c_str()); } return skip; } bool CoreChecks::ValidateImageImportedHandleANDROID(const char *func_name, VkExternalMemoryHandleTypeFlags handleType, VkDeviceMemory memory, VkImage image) const { bool skip = false; if ((handleType & VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID) == 0) { const char *vuid = (strcmp(func_name, "vkBindImageMemory()") == 0) ? "VUID-vkBindImageMemory-memory-02990" : "VUID-VkBindImageMemoryInfo-memory-02990"; LogObjectList objlist(image); objlist.add(memory); skip |= LogError(objlist, vuid, "%s: The VkDeviceMemory (%s) was created with an AHB import operation which is not set " "VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID in the VkImage (%s) " "VkExternalMemoryImageCreateInfo::handleType (%s)", func_name, report_data->FormatHandle(memory).c_str(), report_data->FormatHandle(image).c_str(), string_VkExternalMemoryHandleTypeFlags(handleType).c_str()); } return skip; } #else // !AHB_VALIDATION_SUPPORT // Case building for Android without AHB Validation #ifdef VK_USE_PLATFORM_ANDROID_KHR bool CoreChecks::PreCallValidateGetAndroidHardwareBufferPropertiesANDROID( VkDevice device, const struct AHardwareBuffer *buffer, VkAndroidHardwareBufferPropertiesANDROID *pProperties) const { return false; } bool CoreChecks::PreCallValidateGetMemoryAndroidHardwareBufferANDROID(VkDevice device, const VkMemoryGetAndroidHardwareBufferInfoANDROID *pInfo, struct AHardwareBuffer **pBuffer) const { return false; } #endif // VK_USE_PLATFORM_ANDROID_KHR bool CoreChecks::ValidateAllocateMemoryANDROID(const VkMemoryAllocateInfo *alloc_info) const { return false; } bool CoreChecks::ValidateGetPhysicalDeviceImageFormatProperties2ANDROID( const VkPhysicalDeviceImageFormatInfo2 *pImageFormatInfo, const VkImageFormatProperties2 *pImageFormatProperties) const { return false; } bool CoreChecks::ValidateGetImageMemoryRequirementsANDROID(const VkImage image, const char *func_name) const { return false; } bool CoreChecks::ValidateBufferImportedHandleANDROID(const char *func_name, VkExternalMemoryHandleTypeFlags handleType, VkDeviceMemory memory, VkBuffer buffer) const { return false; } bool CoreChecks::ValidateImageImportedHandleANDROID(const char *func_name, VkExternalMemoryHandleTypeFlags handleType, VkDeviceMemory memory, VkImage image) const { return false; } #endif // AHB_VALIDATION_SUPPORT bool CoreChecks::PreCallValidateAllocateMemory(VkDevice device, const VkMemoryAllocateInfo *pAllocateInfo, const VkAllocationCallbacks *pAllocator, VkDeviceMemory *pMemory) const { bool skip = false; if (memObjMap.size() >= phys_dev_props.limits.maxMemoryAllocationCount) { skip |= LogError(device, "VUID-vkAllocateMemory-maxMemoryAllocationCount-04101", "vkAllocateMemory: Number of currently valid memory objects is not less than the maximum allowed (%u).", phys_dev_props.limits.maxMemoryAllocationCount); } if (device_extensions.vk_android_external_memory_android_hardware_buffer) { skip |= ValidateAllocateMemoryANDROID(pAllocateInfo); } else { if (0 == pAllocateInfo->allocationSize) { skip |= LogError(device, "VUID-VkMemoryAllocateInfo-allocationSize-00638", "vkAllocateMemory: allocationSize is 0."); }; } auto chained_flags_struct = LvlFindInChain<VkMemoryAllocateFlagsInfo>(pAllocateInfo->pNext); if (chained_flags_struct && chained_flags_struct->flags == VK_MEMORY_ALLOCATE_DEVICE_MASK_BIT) { skip |= ValidateDeviceMaskToPhysicalDeviceCount(chained_flags_struct->deviceMask, device, "VUID-VkMemoryAllocateFlagsInfo-deviceMask-00675"); skip |= ValidateDeviceMaskToZero(chained_flags_struct->deviceMask, device, "VUID-VkMemoryAllocateFlagsInfo-deviceMask-00676"); } if (pAllocateInfo->memoryTypeIndex >= phys_dev_mem_props.memoryTypeCount) { skip |= LogError(device, "VUID-vkAllocateMemory-pAllocateInfo-01714", "vkAllocateMemory: attempting to allocate memory type %u, which is not a valid index. Device only " "advertises %u memory types.", pAllocateInfo->memoryTypeIndex, phys_dev_mem_props.memoryTypeCount); } else { const VkMemoryType memory_type = phys_dev_mem_props.memoryTypes[pAllocateInfo->memoryTypeIndex]; if (pAllocateInfo->allocationSize > phys_dev_mem_props.memoryHeaps[memory_type.heapIndex].size) { skip |= LogError(device, "VUID-vkAllocateMemory-pAllocateInfo-01713", "vkAllocateMemory: attempting to allocate %" PRIu64 " bytes from heap %u," "but size of that heap is only %" PRIu64 " bytes.", pAllocateInfo->allocationSize, memory_type.heapIndex, phys_dev_mem_props.memoryHeaps[memory_type.heapIndex].size); } if (!enabled_features.device_coherent_memory_features.deviceCoherentMemory && ((memory_type.propertyFlags & VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD) != 0)) { skip |= LogError(device, "VUID-vkAllocateMemory-deviceCoherentMemory-02790", "vkAllocateMemory: attempting to allocate memory type %u, which includes the " "VK_MEMORY_PROPERTY_DEVICE_COHERENT_BIT_AMD memory property, but the deviceCoherentMemory feature " "is not enabled.", pAllocateInfo->memoryTypeIndex); } if ((enabled_features.core11.protectedMemory == VK_FALSE) && ((memory_type.propertyFlags & VK_MEMORY_PROPERTY_PROTECTED_BIT) != 0)) { skip |= LogError(device, "VUID-VkMemoryAllocateInfo-memoryTypeIndex-01872", "vkAllocateMemory(): attempting to allocate memory type %u, which includes the " "VK_MEMORY_PROPERTY_PROTECTED_BIT memory property, but the protectedMemory feature " "is not enabled.", pAllocateInfo->memoryTypeIndex); } } bool imported_ahb = false; #ifdef AHB_VALIDATION_SUPPORT // "memory is not an imported Android Hardware Buffer" refers to VkImportAndroidHardwareBufferInfoANDROID with a non-NULL // buffer value. Memory imported has another VUID to check size and allocationSize match up auto imported_ahb_info = LvlFindInChain<VkImportAndroidHardwareBufferInfoANDROID>(pAllocateInfo->pNext); if (imported_ahb_info != nullptr) { imported_ahb = imported_ahb_info->buffer != nullptr; } #endif // AHB_VALIDATION_SUPPORT auto dedicated_allocate_info = LvlFindInChain<VkMemoryDedicatedAllocateInfo>(pAllocateInfo->pNext); if (dedicated_allocate_info) { if ((dedicated_allocate_info->buffer != VK_NULL_HANDLE) && (dedicated_allocate_info->image != VK_NULL_HANDLE)) { skip |= LogError(device, "VUID-VkMemoryDedicatedAllocateInfo-image-01432", "vkAllocateMemory: Either buffer or image has to be VK_NULL_HANDLE in VkMemoryDedicatedAllocateInfo"); } else if (dedicated_allocate_info->image != VK_NULL_HANDLE) { // Dedicated VkImage const IMAGE_STATE *image_state = GetImageState(dedicated_allocate_info->image); if (image_state->disjoint == true) { skip |= LogError( device, "VUID-VkMemoryDedicatedAllocateInfo-image-01797", "vkAllocateMemory: VkImage %s can't be used in VkMemoryDedicatedAllocateInfo because it was created with " "VK_IMAGE_CREATE_DISJOINT_BIT", report_data->FormatHandle(dedicated_allocate_info->image).c_str()); } else { if ((pAllocateInfo->allocationSize != image_state->requirements[0].size) && (imported_ahb == false)) { const char *vuid = (device_extensions.vk_android_external_memory_android_hardware_buffer) ? "VUID-VkMemoryDedicatedAllocateInfo-image-02964" : "VUID-VkMemoryDedicatedAllocateInfo-image-01433"; skip |= LogError(device, vuid, "vkAllocateMemory: Allocation Size (%" PRIu64 ") needs to be equal to VkImage %s VkMemoryRequirements::size (%" PRIu64 ")", pAllocateInfo->allocationSize, report_data->FormatHandle(dedicated_allocate_info->image).c_str(), image_state->requirements[0].size); } if ((image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_BINDING_BIT) != 0) { skip |= LogError( device, "VUID-VkMemoryDedicatedAllocateInfo-image-01434", "vkAllocateMemory: VkImage %s can't be used in VkMemoryDedicatedAllocateInfo because it was created with " "VK_IMAGE_CREATE_SPARSE_BINDING_BIT", report_data->FormatHandle(dedicated_allocate_info->image).c_str()); } } } else if (dedicated_allocate_info->buffer != VK_NULL_HANDLE) { // Dedicated VkBuffer const BUFFER_STATE *buffer_state = GetBufferState(dedicated_allocate_info->buffer); if ((pAllocateInfo->allocationSize != buffer_state->requirements.size) && (imported_ahb == false)) { const char *vuid = (device_extensions.vk_android_external_memory_android_hardware_buffer) ? "VUID-VkMemoryDedicatedAllocateInfo-buffer-02965" : "VUID-VkMemoryDedicatedAllocateInfo-buffer-01435"; skip |= LogError( device, vuid, "vkAllocateMemory: Allocation Size (%" PRIu64 ") needs to be equal to VkBuffer %s VkMemoryRequirements::size (%" PRIu64 ")", pAllocateInfo->allocationSize, report_data->FormatHandle(dedicated_allocate_info->buffer).c_str(), buffer_state->requirements.size); } if ((buffer_state->createInfo.flags & VK_BUFFER_CREATE_SPARSE_BINDING_BIT) != 0) { skip |= LogError( device, "VUID-VkMemoryDedicatedAllocateInfo-buffer-01436", "vkAllocateMemory: VkBuffer %s can't be used in VkMemoryDedicatedAllocateInfo because it was created with " "VK_BUFFER_CREATE_SPARSE_BINDING_BIT", report_data->FormatHandle(dedicated_allocate_info->buffer).c_str()); } } } // TODO: VUIDs ending in 00643, 00644, 00646, 00647, 01742, 01743, 01745, 00645, 00648, 01744 return skip; } // For given obj node, if it is use, flag a validation error and return callback result, else return false bool CoreChecks::ValidateObjectNotInUse(const BASE_NODE *obj_node, const char *caller_name, const char *error_code) const { if (disabled[object_in_use]) return false; auto obj_struct = obj_node->Handle(); bool skip = false; if (obj_node->InUse()) { skip |= LogError(device, error_code, "Cannot call %s on %s that is currently in use by a command buffer.", caller_name, report_data->FormatHandle(obj_struct).c_str()); } return skip; } bool CoreChecks::PreCallValidateFreeMemory(VkDevice device, VkDeviceMemory mem, const VkAllocationCallbacks *pAllocator) const { const DEVICE_MEMORY_STATE *mem_info = GetDevMemState(mem); bool skip = false; if (mem_info) { skip |= ValidateObjectNotInUse(mem_info, "vkFreeMemory", "VUID-vkFreeMemory-memory-00677"); } return skip; } // Validate that given Map memory range is valid. This means that the memory should not already be mapped, // and that the size of the map range should be: // 1. Not zero // 2. Within the size of the memory allocation bool CoreChecks::ValidateMapMemRange(const DEVICE_MEMORY_STATE *mem_info, VkDeviceSize offset, VkDeviceSize size) const { bool skip = false; assert(mem_info); const auto mem = mem_info->mem(); if (size == 0) { skip = LogError(mem, "VUID-vkMapMemory-size-00680", "VkMapMemory: Attempting to map memory range of size zero"); } // It is an application error to call VkMapMemory on an object that is already mapped if (mem_info->mapped_range.size != 0) { skip = LogError(mem, "VUID-vkMapMemory-memory-00678", "VkMapMemory: Attempting to map memory on an already-mapped %s.", report_data->FormatHandle(mem).c_str()); } // Validate offset is not over allocaiton size if (offset >= mem_info->alloc_info.allocationSize) { skip = LogError(mem, "VUID-vkMapMemory-offset-00679", "VkMapMemory: Attempting to map memory with an offset of 0x%" PRIx64 " which is larger than the total array size 0x%" PRIx64, offset, mem_info->alloc_info.allocationSize); } // Validate that offset + size is within object's allocationSize if (size != VK_WHOLE_SIZE) { if ((offset + size) > mem_info->alloc_info.allocationSize) { skip = LogError(mem, "VUID-vkMapMemory-size-00681", "VkMapMemory: Mapping Memory from 0x%" PRIx64 " to 0x%" PRIx64 " oversteps total array size 0x%" PRIx64 ".", offset, size + offset, mem_info->alloc_info.allocationSize); } } return skip; } bool CoreChecks::PreCallValidateWaitForFences(VkDevice device, uint32_t fenceCount, const VkFence *pFences, VkBool32 waitAll, uint64_t timeout) const { // Verify fence status of submitted fences bool skip = false; for (uint32_t i = 0; i < fenceCount; i++) { skip |= VerifyQueueStateToFence(pFences[i]); } return skip; } bool CoreChecks::PreCallValidateGetDeviceQueue(VkDevice device, uint32_t queueFamilyIndex, uint32_t queueIndex, VkQueue *pQueue) const { bool skip = false; skip |= ValidateDeviceQueueFamily(queueFamilyIndex, "vkGetDeviceQueue", "queueFamilyIndex", "VUID-vkGetDeviceQueue-queueFamilyIndex-00384"); for (size_t i = 0; i < device_queue_info_list.size(); i++) { const auto device_queue_info = device_queue_info_list.at(i); if (device_queue_info.queue_family_index != queueFamilyIndex) { continue; } // flag must be zero if (device_queue_info.flags != 0) { skip |= LogError( device, "VUID-vkGetDeviceQueue-flags-01841", "vkGetDeviceQueue: queueIndex (=%" PRIu32 ") was created with a non-zero VkDeviceQueueCreateFlags in vkCreateDevice::pCreateInfo->pQueueCreateInfos[%" PRIu32 "]. Need to use vkGetDeviceQueue2 instead.", queueIndex, device_queue_info.index); } if (device_queue_info.queue_count <= queueIndex) { skip |= LogError(device, "VUID-vkGetDeviceQueue-queueIndex-00385", "vkGetDeviceQueue: queueIndex (=%" PRIu32 ") is not less than the number of queues requested from queueFamilyIndex (=%" PRIu32 ") when the device was created vkCreateDevice::pCreateInfo->pQueueCreateInfos[%" PRIu32 "] (i.e. is not less than %" PRIu32 ").", queueIndex, queueFamilyIndex, device_queue_info.index, device_queue_info.queue_count); } } return skip; } bool CoreChecks::PreCallValidateGetDeviceQueue2(VkDevice device, const VkDeviceQueueInfo2 *pQueueInfo, VkQueue *pQueue) const { bool skip = false; if (pQueueInfo) { const uint32_t queueFamilyIndex = pQueueInfo->queueFamilyIndex; const uint32_t queueIndex = pQueueInfo->queueIndex; const VkDeviceQueueCreateFlags flags = pQueueInfo->flags; skip |= ValidateDeviceQueueFamily(queueFamilyIndex, "vkGetDeviceQueue2", "pQueueInfo->queueFamilyIndex", "VUID-VkDeviceQueueInfo2-queueFamilyIndex-01842"); // ValidateDeviceQueueFamily() already checks if queueFamilyIndex but need to make sure flags match with it bool valid_flags = false; for (size_t i = 0; i < device_queue_info_list.size(); i++) { const auto device_queue_info = device_queue_info_list.at(i); // vkGetDeviceQueue2 only checks if both family index AND flags are same as device creation // this handle case where the same queueFamilyIndex is used with/without the protected flag if ((device_queue_info.queue_family_index != queueFamilyIndex) || (device_queue_info.flags != flags)) { continue; } valid_flags = true; if (device_queue_info.queue_count <= queueIndex) { skip |= LogError( device, "VUID-VkDeviceQueueInfo2-queueIndex-01843", "vkGetDeviceQueue2: queueIndex (=%" PRIu32 ") is not less than the number of queues requested from [queueFamilyIndex (=%" PRIu32 "), flags (%s)] combination when the device was created vkCreateDevice::pCreateInfo->pQueueCreateInfos[%" PRIu32 "] (i.e. is not less than %" PRIu32 ").", queueIndex, queueFamilyIndex, string_VkDeviceQueueCreateFlags(flags).c_str(), device_queue_info.index, device_queue_info.queue_count); } } // Don't double error message if already skipping from ValidateDeviceQueueFamily if (!valid_flags && !skip) { skip |= LogError(device, "UNASSIGNED-VkDeviceQueueInfo2", "vkGetDeviceQueue2: The combination of queueFamilyIndex (=%" PRIu32 ") and flags (%s) were never both set together in any element of " "vkCreateDevice::pCreateInfo->pQueueCreateInfos at device creation time.", queueFamilyIndex, string_VkDeviceQueueCreateFlags(flags).c_str()); } } return skip; } bool CoreChecks::PreCallValidateQueueWaitIdle(VkQueue queue) const { const QUEUE_STATE *queue_state = GetQueueState(queue); return VerifyQueueStateToSeq(queue_state, queue_state->seq + queue_state->submissions.size()); } bool CoreChecks::PreCallValidateDeviceWaitIdle(VkDevice device) const { bool skip = false; const auto &const_queue_map = queueMap; for (auto &queue : const_queue_map) { skip |= VerifyQueueStateToSeq(&queue.second, queue.second.seq + queue.second.submissions.size()); } return skip; } bool CoreChecks::PreCallValidateCreateSemaphore(VkDevice device, const VkSemaphoreCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkSemaphore *pSemaphore) const { bool skip = false; auto *sem_type_create_info = LvlFindInChain<VkSemaphoreTypeCreateInfo>(pCreateInfo->pNext); if (sem_type_create_info) { if (sem_type_create_info->semaphoreType == VK_SEMAPHORE_TYPE_TIMELINE && !enabled_features.core12.timelineSemaphore) { skip |= LogError(device, "VUID-VkSemaphoreTypeCreateInfo-timelineSemaphore-03252", "VkCreateSemaphore: timelineSemaphore feature is not enabled, can not create timeline semaphores"); } if (sem_type_create_info->semaphoreType == VK_SEMAPHORE_TYPE_BINARY && sem_type_create_info->initialValue != 0) { skip |= LogError(device, "VUID-VkSemaphoreTypeCreateInfo-semaphoreType-03279", "vkCreateSemaphore: if semaphoreType is VK_SEMAPHORE_TYPE_BINARY, initialValue must be zero"); } } return skip; } bool CoreChecks::PreCallValidateWaitSemaphores(VkDevice device, const VkSemaphoreWaitInfo *pWaitInfo, uint64_t timeout) const { return ValidateWaitSemaphores(device, pWaitInfo, timeout, "VkWaitSemaphores"); } bool CoreChecks::PreCallValidateWaitSemaphoresKHR(VkDevice device, const VkSemaphoreWaitInfo *pWaitInfo, uint64_t timeout) const { return ValidateWaitSemaphores(device, pWaitInfo, timeout, "VkWaitSemaphoresKHR"); } bool CoreChecks::ValidateWaitSemaphores(VkDevice device, const VkSemaphoreWaitInfo *pWaitInfo, uint64_t timeout, const char *apiName) const { bool skip = false; for (uint32_t i = 0; i < pWaitInfo->semaphoreCount; i++) { auto *semaphore_state = GetSemaphoreState(pWaitInfo->pSemaphores[i]); if (semaphore_state && semaphore_state->type != VK_SEMAPHORE_TYPE_TIMELINE) { skip |= LogError(pWaitInfo->pSemaphores[i], "VUID-VkSemaphoreWaitInfo-pSemaphores-03256", "%s(): all semaphores in pWaitInfo must be timeline semaphores, but %s is not", apiName, report_data->FormatHandle(pWaitInfo->pSemaphores[i]).c_str()); } } return skip; } bool CoreChecks::PreCallValidateDestroyFence(VkDevice device, VkFence fence, const VkAllocationCallbacks *pAllocator) const { const FENCE_STATE *fence_node = GetFenceState(fence); bool skip = false; if (fence_node) { if (fence_node->scope == kSyncScopeInternal && fence_node->state == FENCE_INFLIGHT) { skip |= LogError(fence, "VUID-vkDestroyFence-fence-01120", "%s is in use.", report_data->FormatHandle(fence).c_str()); } } return skip; } bool CoreChecks::PreCallValidateDestroySemaphore(VkDevice device, VkSemaphore semaphore, const VkAllocationCallbacks *pAllocator) const { const SEMAPHORE_STATE *sema_node = GetSemaphoreState(semaphore); bool skip = false; if (sema_node) { skip |= ValidateObjectNotInUse(sema_node, "vkDestroySemaphore", "VUID-vkDestroySemaphore-semaphore-01137"); } return skip; } bool CoreChecks::PreCallValidateDestroyEvent(VkDevice device, VkEvent event, const VkAllocationCallbacks *pAllocator) const { const EVENT_STATE *event_state = GetEventState(event); bool skip = false; if (event_state) { skip |= ValidateObjectNotInUse(event_state, "vkDestroyEvent", "VUID-vkDestroyEvent-event-01145"); } return skip; } bool CoreChecks::PreCallValidateDestroyQueryPool(VkDevice device, VkQueryPool queryPool, const VkAllocationCallbacks *pAllocator) const { if (disabled[query_validation]) return false; const QUERY_POOL_STATE *qp_state = GetQueryPoolState(queryPool); bool skip = false; if (qp_state) { skip |= ValidateObjectNotInUse(qp_state, "vkDestroyQueryPool", "VUID-vkDestroyQueryPool-queryPool-00793"); } return skip; } bool CoreChecks::ValidatePerformanceQueryResults(const char *cmd_name, const QUERY_POOL_STATE *query_pool_state, uint32_t firstQuery, uint32_t queryCount, VkQueryResultFlags flags) const { bool skip = false; if (flags & (VK_QUERY_RESULT_WITH_AVAILABILITY_BIT | VK_QUERY_RESULT_PARTIAL_BIT | VK_QUERY_RESULT_64_BIT)) { string invalid_flags_string; for (auto flag : {VK_QUERY_RESULT_WITH_AVAILABILITY_BIT, VK_QUERY_RESULT_PARTIAL_BIT, VK_QUERY_RESULT_64_BIT}) { if (flag & flags) { if (invalid_flags_string.size()) { invalid_flags_string += " and "; } invalid_flags_string += string_VkQueryResultFlagBits(flag); } } skip |= LogError(query_pool_state->pool(), strcmp(cmd_name, "vkGetQueryPoolResults") == 0 ? "VUID-vkGetQueryPoolResults-queryType-03230" : "VUID-vkCmdCopyQueryPoolResults-queryType-03233", "%s: QueryPool %s was created with a queryType of" "VK_QUERY_TYPE_PERFORMANCE_QUERY_KHR but flags contains %s.", cmd_name, report_data->FormatHandle(query_pool_state->pool()).c_str(), invalid_flags_string.c_str()); } for (uint32_t query_index = firstQuery; query_index < queryCount; query_index++) { uint32_t submitted = 0; for (uint32_t pass_index = 0; pass_index < query_pool_state->n_performance_passes; pass_index++) { QueryObject obj(QueryObject(query_pool_state->pool(), query_index), pass_index); auto query_pass_iter = queryToStateMap.find(obj); if (query_pass_iter != queryToStateMap.end() && query_pass_iter->second == QUERYSTATE_AVAILABLE) submitted++; } if (submitted < query_pool_state->n_performance_passes) { skip |= LogError(query_pool_state->pool(), "VUID-vkGetQueryPoolResults-queryType-03231", "%s: QueryPool %s has %u performance query passes, but the query has only been " "submitted for %u of the passes.", cmd_name, report_data->FormatHandle(query_pool_state->pool()).c_str(), query_pool_state->n_performance_passes, submitted); } } return skip; } bool CoreChecks::ValidateGetQueryPoolPerformanceResults(VkQueryPool queryPool, uint32_t firstQuery, uint32_t queryCount, void *pData, VkDeviceSize stride, VkQueryResultFlags flags, const char *apiName) const { bool skip = false; const auto query_pool_state = GetQueryPoolState(queryPool); if (!query_pool_state || query_pool_state->createInfo.queryType != VK_QUERY_TYPE_PERFORMANCE_QUERY_KHR) return skip; if (((((uintptr_t)pData) % sizeof(VkPerformanceCounterResultKHR)) != 0 || (stride % sizeof(VkPerformanceCounterResultKHR)) != 0)) { skip |= LogError(queryPool, "VUID-vkGetQueryPoolResults-queryType-03229", "%s(): QueryPool %s was created with a queryType of " "VK_QUERY_TYPE_PERFORMANCE_QUERY_KHR but pData & stride are not multiple of the " "size of VkPerformanceCounterResultKHR.", apiName, report_data->FormatHandle(queryPool).c_str()); } skip |= ValidatePerformanceQueryResults(apiName, query_pool_state, firstQuery, queryCount, flags); return skip; } bool CoreChecks::PreCallValidateGetQueryPoolResults(VkDevice device, VkQueryPool queryPool, uint32_t firstQuery, uint32_t queryCount, size_t dataSize, void *pData, VkDeviceSize stride, VkQueryResultFlags flags) const { if (disabled[query_validation]) return false; bool skip = false; skip |= ValidateQueryPoolStride("VUID-vkGetQueryPoolResults-flags-02827", "VUID-vkGetQueryPoolResults-flags-00815", stride, "dataSize", dataSize, flags); skip |= ValidateQueryPoolIndex(queryPool, firstQuery, queryCount, "vkGetQueryPoolResults()", "VUID-vkGetQueryPoolResults-firstQuery-00813", "VUID-vkGetQueryPoolResults-firstQuery-00816"); skip |= ValidateGetQueryPoolPerformanceResults(queryPool, firstQuery, queryCount, pData, stride, flags, "vkGetQueryPoolResults"); const auto query_pool_state = GetQueryPoolState(queryPool); if (query_pool_state) { if ((query_pool_state->createInfo.queryType == VK_QUERY_TYPE_TIMESTAMP) && (flags & VK_QUERY_RESULT_PARTIAL_BIT)) { skip |= LogError( queryPool, "VUID-vkGetQueryPoolResults-queryType-00818", "%s was created with a queryType of VK_QUERY_TYPE_TIMESTAMP but flags contains VK_QUERY_RESULT_PARTIAL_BIT.", report_data->FormatHandle(queryPool).c_str()); } if (!skip) { uint32_t query_avail_data = (flags & VK_QUERY_RESULT_WITH_AVAILABILITY_BIT) ? 1 : 0; uint32_t query_size_in_bytes = (flags & VK_QUERY_RESULT_64_BIT) ? sizeof(uint64_t) : sizeof(uint32_t); uint32_t query_items = 0; uint32_t query_size = 0; switch (query_pool_state->createInfo.queryType) { case VK_QUERY_TYPE_OCCLUSION: // Occlusion queries write one integer value - the number of samples passed. query_items = 1; query_size = query_size_in_bytes * (query_items + query_avail_data); break; case VK_QUERY_TYPE_PIPELINE_STATISTICS: // Pipeline statistics queries write one integer value for each bit that is enabled in the pipelineStatistics // when the pool is created { const int num_bits = sizeof(VkFlags) * CHAR_BIT; std::bitset<num_bits> pipe_stats_bits(query_pool_state->createInfo.pipelineStatistics); query_items = static_cast<uint32_t>(pipe_stats_bits.count()); query_size = query_size_in_bytes * (query_items + query_avail_data); } break; case VK_QUERY_TYPE_TIMESTAMP: // Timestamp queries write one integer query_items = 1; query_size = query_size_in_bytes * (query_items + query_avail_data); break; case VK_QUERY_TYPE_TRANSFORM_FEEDBACK_STREAM_EXT: // Transform feedback queries write two integers query_items = 2; query_size = query_size_in_bytes * (query_items + query_avail_data); break; case VK_QUERY_TYPE_PERFORMANCE_QUERY_KHR: // Performance queries store results in a tightly packed array of VkPerformanceCounterResultsKHR query_items = query_pool_state->perf_counter_index_count; query_size = sizeof(VkPerformanceCounterResultKHR) * query_items; if (query_size > stride) { skip |= LogError(queryPool, "VUID-vkGetQueryPoolResults-queryType-04519", "vkGetQueryPoolResults() on querypool %s specified stride %" PRIu64 " which must be at least counterIndexCount (%d) " "multiplied by sizeof(VkPerformanceCounterResultKHR) (%zu).", report_data->FormatHandle(queryPool).c_str(), stride, query_items, sizeof(VkPerformanceCounterResultKHR)); } break; // These cases intentionally fall through to the default case VK_QUERY_TYPE_ACCELERATION_STRUCTURE_COMPACTED_SIZE_KHR: // VK_QUERY_TYPE_ACCELERATION_STRUCTURE_COMPACTED_SIZE_NV case VK_QUERY_TYPE_ACCELERATION_STRUCTURE_SERIALIZATION_SIZE_KHR: case VK_QUERY_TYPE_PERFORMANCE_QUERY_INTEL: default: query_size = 0; break; } if (query_size && (((queryCount - 1) * stride + query_size) > dataSize)) { skip |= LogError(queryPool, "VUID-vkGetQueryPoolResults-dataSize-00817", "vkGetQueryPoolResults() on querypool %s specified dataSize %zu which is " "incompatible with the specified query type and options.", report_data->FormatHandle(queryPool).c_str(), dataSize); } } } return skip; } bool CoreChecks::ValidateInsertMemoryRange(const VulkanTypedHandle &typed_handle, const DEVICE_MEMORY_STATE *mem_info, VkDeviceSize memoryOffset, const char *api_name) const { bool skip = false; if (memoryOffset >= mem_info->alloc_info.allocationSize) { const char *error_code = nullptr; if (typed_handle.type == kVulkanObjectTypeBuffer) { if (strcmp(api_name, "vkBindBufferMemory()") == 0) { error_code = "VUID-vkBindBufferMemory-memoryOffset-01031"; } else { error_code = "VUID-VkBindBufferMemoryInfo-memoryOffset-01031"; } } else if (typed_handle.type == kVulkanObjectTypeImage) { if (strcmp(api_name, "vkBindImageMemory()") == 0) { error_code = "VUID-vkBindImageMemory-memoryOffset-01046"; } else { error_code = "VUID-VkBindImageMemoryInfo-memoryOffset-01046"; } } else if (typed_handle.type == kVulkanObjectTypeAccelerationStructureNV) { error_code = "VUID-VkBindAccelerationStructureMemoryInfoNV-memoryOffset-03621"; } else { // Unsupported object type assert(false); } LogObjectList objlist(mem_info->mem()); objlist.add(typed_handle); skip = LogError(objlist, error_code, "In %s, attempting to bind %s to %s, memoryOffset=0x%" PRIxLEAST64 " must be less than the memory allocation size 0x%" PRIxLEAST64 ".", api_name, report_data->FormatHandle(mem_info->mem()).c_str(), report_data->FormatHandle(typed_handle).c_str(), memoryOffset, mem_info->alloc_info.allocationSize); } return skip; } bool CoreChecks::ValidateInsertImageMemoryRange(VkImage image, const DEVICE_MEMORY_STATE *mem_info, VkDeviceSize mem_offset, const char *api_name) const { return ValidateInsertMemoryRange(VulkanTypedHandle(image, kVulkanObjectTypeImage), mem_info, mem_offset, api_name); } bool CoreChecks::ValidateInsertBufferMemoryRange(VkBuffer buffer, const DEVICE_MEMORY_STATE *mem_info, VkDeviceSize mem_offset, const char *api_name) const { return ValidateInsertMemoryRange(VulkanTypedHandle(buffer, kVulkanObjectTypeBuffer), mem_info, mem_offset, api_name); } bool CoreChecks::ValidateInsertAccelerationStructureMemoryRange(VkAccelerationStructureNV as, const DEVICE_MEMORY_STATE *mem_info, VkDeviceSize mem_offset, const char *api_name) const { return ValidateInsertMemoryRange(VulkanTypedHandle(as, kVulkanObjectTypeAccelerationStructureNV), mem_info, mem_offset, api_name); } bool CoreChecks::ValidateMemoryTypes(const DEVICE_MEMORY_STATE *mem_info, const uint32_t memory_type_bits, const char *funcName, const char *msgCode) const { bool skip = false; if (((1 << mem_info->alloc_info.memoryTypeIndex) & memory_type_bits) == 0) { skip = LogError(mem_info->mem(), msgCode, "%s(): MemoryRequirements->memoryTypeBits (0x%X) for this object type are not compatible with the memory " "type (0x%X) of %s.", funcName, memory_type_bits, mem_info->alloc_info.memoryTypeIndex, report_data->FormatHandle(mem_info->mem()).c_str()); } return skip; } bool CoreChecks::ValidateBindBufferMemory(VkBuffer buffer, VkDeviceMemory mem, VkDeviceSize memoryOffset, const char *api_name) const { const BUFFER_STATE *buffer_state = GetBufferState(buffer); bool bind_buffer_mem_2 = strcmp(api_name, "vkBindBufferMemory()") != 0; bool skip = false; if (buffer_state) { // Track objects tied to memory skip = ValidateSetMemBinding(mem, buffer_state->Handle(), api_name); const auto mem_info = GetDevMemState(mem); // Validate memory requirements alignment if (SafeModulo(memoryOffset, buffer_state->requirements.alignment) != 0) { const char *vuid = bind_buffer_mem_2 ? "VUID-VkBindBufferMemoryInfo-memoryOffset-01036" : "VUID-vkBindBufferMemory-memoryOffset-01036"; skip |= LogError(buffer, vuid, "%s: memoryOffset is 0x%" PRIxLEAST64 " but must be an integer multiple of the VkMemoryRequirements::alignment value 0x%" PRIxLEAST64 ", returned from a call to vkGetBufferMemoryRequirements with buffer.", api_name, memoryOffset, buffer_state->requirements.alignment); } if (mem_info) { // Validate bound memory range information skip |= ValidateInsertBufferMemoryRange(buffer, mem_info, memoryOffset, api_name); const char *mem_type_vuid = bind_buffer_mem_2 ? "VUID-VkBindBufferMemoryInfo-memory-01035" : "VUID-vkBindBufferMemory-memory-01035"; skip |= ValidateMemoryTypes(mem_info, buffer_state->requirements.memoryTypeBits, api_name, mem_type_vuid); // Validate memory requirements size if (buffer_state->requirements.size > (mem_info->alloc_info.allocationSize - memoryOffset)) { const char *vuid = bind_buffer_mem_2 ? "VUID-VkBindBufferMemoryInfo-size-01037" : "VUID-vkBindBufferMemory-size-01037"; skip |= LogError(buffer, vuid, "%s: memory size minus memoryOffset is 0x%" PRIxLEAST64 " but must be at least as large as VkMemoryRequirements::size value 0x%" PRIxLEAST64 ", returned from a call to vkGetBufferMemoryRequirements with buffer.", api_name, mem_info->alloc_info.allocationSize - memoryOffset, buffer_state->requirements.size); } // Validate dedicated allocation if (mem_info->IsDedicatedBuffer() && ((mem_info->dedicated->handle.Cast<VkBuffer>() != buffer) || (memoryOffset != 0))) { const char *vuid = bind_buffer_mem_2 ? "VUID-VkBindBufferMemoryInfo-memory-01508" : "VUID-vkBindBufferMemory-memory-01508"; LogObjectList objlist(buffer); objlist.add(mem); objlist.add(mem_info->dedicated->handle); skip |= LogError(objlist, vuid, "%s: for dedicated %s, VkMemoryDedicatedAllocateInfo::buffer %s must be equal " "to %s and memoryOffset 0x%" PRIxLEAST64 " must be zero.", api_name, report_data->FormatHandle(mem).c_str(), report_data->FormatHandle(mem_info->dedicated->handle).c_str(), report_data->FormatHandle(buffer).c_str(), memoryOffset); } auto chained_flags_struct = LvlFindInChain<VkMemoryAllocateFlagsInfo>(mem_info->alloc_info.pNext); if (enabled_features.core12.bufferDeviceAddress && (buffer_state->createInfo.usage & VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT) && (!chained_flags_struct || !(chained_flags_struct->flags & VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT))) { skip |= LogError(buffer, "VUID-vkBindBufferMemory-bufferDeviceAddress-03339", "%s: If buffer was created with the VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT bit set, " "memory must have been allocated with the VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT bit set.", api_name); } // Validate export memory handles if ((mem_info->export_handle_type_flags != 0) && ((mem_info->export_handle_type_flags & buffer_state->external_memory_handle) == 0)) { const char *vuid = bind_buffer_mem_2 ? "VUID-VkBindBufferMemoryInfo-memory-02726" : "VUID-vkBindBufferMemory-memory-02726"; LogObjectList objlist(buffer); objlist.add(mem); skip |= LogError(objlist, vuid, "%s: The VkDeviceMemory (%s) has an external handleType of %s which does not include at least one " "handle from VkBuffer (%s) handleType %s.", api_name, report_data->FormatHandle(mem).c_str(), string_VkExternalMemoryHandleTypeFlags(mem_info->export_handle_type_flags).c_str(), report_data->FormatHandle(buffer).c_str(), string_VkExternalMemoryHandleTypeFlags(buffer_state->external_memory_handle).c_str()); } // Validate import memory handles if (mem_info->IsImportAHB() == true) { skip |= ValidateBufferImportedHandleANDROID(api_name, buffer_state->external_memory_handle, mem, buffer); } else if (mem_info->IsImport() == true) { if ((mem_info->import_handle_type_flags & buffer_state->external_memory_handle) == 0) { const char *vuid = nullptr; if ((bind_buffer_mem_2) && (device_extensions.vk_android_external_memory_android_hardware_buffer)) { vuid = "VUID-VkBindBufferMemoryInfo-memory-02985"; } else if ((!bind_buffer_mem_2) && (device_extensions.vk_android_external_memory_android_hardware_buffer)) { vuid = "VUID-vkBindBufferMemory-memory-02985"; } else if ((bind_buffer_mem_2) && (!device_extensions.vk_android_external_memory_android_hardware_buffer)) { vuid = "VUID-VkBindBufferMemoryInfo-memory-02727"; } else if ((!bind_buffer_mem_2) && (!device_extensions.vk_android_external_memory_android_hardware_buffer)) { vuid = "VUID-vkBindBufferMemory-memory-02727"; } LogObjectList objlist(buffer); objlist.add(mem); skip |= LogError(objlist, vuid, "%s: The VkDeviceMemory (%s) was created with an import operation with handleType of %s which " "is not set in the VkBuffer (%s) VkExternalMemoryBufferCreateInfo::handleType (%s)", api_name, report_data->FormatHandle(mem).c_str(), string_VkExternalMemoryHandleTypeFlags(mem_info->import_handle_type_flags).c_str(), report_data->FormatHandle(buffer).c_str(), string_VkExternalMemoryHandleTypeFlags(buffer_state->external_memory_handle).c_str()); } } // Validate mix of protected buffer and memory if ((buffer_state->unprotected == false) && (mem_info->unprotected == true)) { const char *vuid = bind_buffer_mem_2 ? "VUID-VkBindBufferMemoryInfo-None-01898" : "VUID-vkBindBufferMemory-None-01898"; LogObjectList objlist(buffer); objlist.add(mem); skip |= LogError(objlist, vuid, "%s: The VkDeviceMemory (%s) was not created with protected memory but the VkBuffer (%s) was set " "to use protected memory.", api_name, report_data->FormatHandle(mem).c_str(), report_data->FormatHandle(buffer).c_str()); } else if ((buffer_state->unprotected == true) && (mem_info->unprotected == false)) { const char *vuid = bind_buffer_mem_2 ? "VUID-VkBindBufferMemoryInfo-None-01899" : "VUID-vkBindBufferMemory-None-01899"; LogObjectList objlist(buffer); objlist.add(mem); skip |= LogError(objlist, vuid, "%s: The VkDeviceMemory (%s) was created with protected memory but the VkBuffer (%s) was not set " "to use protected memory.", api_name, report_data->FormatHandle(mem).c_str(), report_data->FormatHandle(buffer).c_str()); } } } return skip; } bool CoreChecks::PreCallValidateBindBufferMemory(VkDevice device, VkBuffer buffer, VkDeviceMemory mem, VkDeviceSize memoryOffset) const { const char *api_name = "vkBindBufferMemory()"; return ValidateBindBufferMemory(buffer, mem, memoryOffset, api_name); } bool CoreChecks::PreCallValidateBindBufferMemory2(VkDevice device, uint32_t bindInfoCount, const VkBindBufferMemoryInfo *pBindInfos) const { char api_name[64]; bool skip = false; for (uint32_t i = 0; i < bindInfoCount; i++) { sprintf(api_name, "vkBindBufferMemory2() pBindInfos[%u]", i); skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, pBindInfos[i].memoryOffset, api_name); } return skip; } bool CoreChecks::PreCallValidateBindBufferMemory2KHR(VkDevice device, uint32_t bindInfoCount, const VkBindBufferMemoryInfo *pBindInfos) const { char api_name[64]; bool skip = false; for (uint32_t i = 0; i < bindInfoCount; i++) { sprintf(api_name, "vkBindBufferMemory2KHR() pBindInfos[%u]", i); skip |= ValidateBindBufferMemory(pBindInfos[i].buffer, pBindInfos[i].memory, pBindInfos[i].memoryOffset, api_name); } return skip; } bool CoreChecks::PreCallValidateGetImageMemoryRequirements(VkDevice device, VkImage image, VkMemoryRequirements *pMemoryRequirements) const { bool skip = false; if (device_extensions.vk_android_external_memory_android_hardware_buffer) { skip |= ValidateGetImageMemoryRequirementsANDROID(image, "vkGetImageMemoryRequirements()"); } const IMAGE_STATE *image_state = GetImageState(image); if (image_state) { // Checks for no disjoint bit if (image_state->disjoint == true) { skip |= LogError(image, "VUID-vkGetImageMemoryRequirements-image-01588", "vkGetImageMemoryRequirements(): %s must not have been created with the VK_IMAGE_CREATE_DISJOINT_BIT " "(need to use vkGetImageMemoryRequirements2).", report_data->FormatHandle(image).c_str()); } } return skip; } bool CoreChecks::ValidateGetImageMemoryRequirements2(const VkImageMemoryRequirementsInfo2 *pInfo, const char *func_name) const { bool skip = false; if (device_extensions.vk_android_external_memory_android_hardware_buffer) { skip |= ValidateGetImageMemoryRequirementsANDROID(pInfo->image, func_name); } const IMAGE_STATE *image_state = GetImageState(pInfo->image); const VkFormat image_format = image_state->createInfo.format; const VkImageTiling image_tiling = image_state->createInfo.tiling; const VkImagePlaneMemoryRequirementsInfo *image_plane_info = LvlFindInChain<VkImagePlaneMemoryRequirementsInfo>(pInfo->pNext); if ((FormatIsMultiplane(image_format)) && (image_state->disjoint == true) && (image_plane_info == nullptr)) { skip |= LogError(pInfo->image, "VUID-VkImageMemoryRequirementsInfo2-image-01589", "%s: %s image was created with a multi-planar format (%s) and " "VK_IMAGE_CREATE_DISJOINT_BIT, but the current pNext doesn't include a " "VkImagePlaneMemoryRequirementsInfo struct", func_name, report_data->FormatHandle(pInfo->image).c_str(), string_VkFormat(image_format)); } if ((image_state->disjoint == false) && (image_plane_info != nullptr)) { skip |= LogError(pInfo->image, "VUID-VkImageMemoryRequirementsInfo2-image-01590", "%s: %s image was not created with VK_IMAGE_CREATE_DISJOINT_BIT," "but the current pNext includes a VkImagePlaneMemoryRequirementsInfo struct", func_name, report_data->FormatHandle(pInfo->image).c_str()); } if ((FormatIsMultiplane(image_format) == false) && (image_tiling != VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT) && (image_plane_info != nullptr)) { const char *vuid = device_extensions.vk_ext_image_drm_format_modifier ? "VUID-VkImageMemoryRequirementsInfo2-image-02280" : "VUID-VkImageMemoryRequirementsInfo2-image-01591"; skip |= LogError(pInfo->image, vuid, "%s: %s image is a single-plane format (%s) and does not have tiling of " "VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT," "but the current pNext includes a VkImagePlaneMemoryRequirementsInfo struct", func_name, report_data->FormatHandle(pInfo->image).c_str(), string_VkFormat(image_format)); } if (image_plane_info != nullptr) { if ((image_tiling == VK_IMAGE_TILING_LINEAR) || (image_tiling == VK_IMAGE_TILING_OPTIMAL)) { // Make sure planeAspect is only a single, valid plane uint32_t planes = FormatPlaneCount(image_format); VkImageAspectFlags aspect = image_plane_info->planeAspect; if ((2 == planes) && (aspect != VK_IMAGE_ASPECT_PLANE_0_BIT) && (aspect != VK_IMAGE_ASPECT_PLANE_1_BIT)) { skip |= LogError( pInfo->image, "VUID-VkImagePlaneMemoryRequirementsInfo-planeAspect-02281", "%s: Image %s VkImagePlaneMemoryRequirementsInfo::planeAspect is %s but can only be VK_IMAGE_ASPECT_PLANE_0_BIT" "or VK_IMAGE_ASPECT_PLANE_1_BIT.", func_name, report_data->FormatHandle(image_state->image()).c_str(), string_VkImageAspectFlags(aspect).c_str()); } if ((3 == planes) && (aspect != VK_IMAGE_ASPECT_PLANE_0_BIT) && (aspect != VK_IMAGE_ASPECT_PLANE_1_BIT) && (aspect != VK_IMAGE_ASPECT_PLANE_2_BIT)) { skip |= LogError( pInfo->image, "VUID-VkImagePlaneMemoryRequirementsInfo-planeAspect-02281", "%s: Image %s VkImagePlaneMemoryRequirementsInfo::planeAspect is %s but can only be VK_IMAGE_ASPECT_PLANE_0_BIT" "or VK_IMAGE_ASPECT_PLANE_1_BIT or VK_IMAGE_ASPECT_PLANE_2_BIT.", func_name, report_data->FormatHandle(image_state->image()).c_str(), string_VkImageAspectFlags(aspect).c_str()); } } } return skip; } bool CoreChecks::PreCallValidateGetImageMemoryRequirements2(VkDevice device, const VkImageMemoryRequirementsInfo2 *pInfo, VkMemoryRequirements2 *pMemoryRequirements) const { return ValidateGetImageMemoryRequirements2(pInfo, "vkGetImageMemoryRequirements2()"); } bool CoreChecks::PreCallValidateGetImageMemoryRequirements2KHR(VkDevice device, const VkImageMemoryRequirementsInfo2 *pInfo, VkMemoryRequirements2 *pMemoryRequirements) const { return ValidateGetImageMemoryRequirements2(pInfo, "vkGetImageMemoryRequirements2KHR()"); } bool CoreChecks::PreCallValidateGetPhysicalDeviceImageFormatProperties2(VkPhysicalDevice physicalDevice, const VkPhysicalDeviceImageFormatInfo2 *pImageFormatInfo, VkImageFormatProperties2 *pImageFormatProperties) const { // Can't wrap AHB-specific validation in a device extension check here, but no harm bool skip = ValidateGetPhysicalDeviceImageFormatProperties2ANDROID(pImageFormatInfo, pImageFormatProperties); return skip; } bool CoreChecks::PreCallValidateGetPhysicalDeviceImageFormatProperties2KHR(VkPhysicalDevice physicalDevice, const VkPhysicalDeviceImageFormatInfo2 *pImageFormatInfo, VkImageFormatProperties2 *pImageFormatProperties) const { // Can't wrap AHB-specific validation in a device extension check here, but no harm bool skip = ValidateGetPhysicalDeviceImageFormatProperties2ANDROID(pImageFormatInfo, pImageFormatProperties); return skip; } bool CoreChecks::PreCallValidateDestroyPipeline(VkDevice device, VkPipeline pipeline, const VkAllocationCallbacks *pAllocator) const { const PIPELINE_STATE *pipeline_state = GetPipelineState(pipeline); bool skip = false; if (pipeline_state) { skip |= ValidateObjectNotInUse(pipeline_state, "vkDestroyPipeline", "VUID-vkDestroyPipeline-pipeline-00765"); } return skip; } bool CoreChecks::PreCallValidateDestroySampler(VkDevice device, VkSampler sampler, const VkAllocationCallbacks *pAllocator) const { const SAMPLER_STATE *sampler_state = GetSamplerState(sampler); bool skip = false; if (sampler_state) { skip |= ValidateObjectNotInUse(sampler_state, "vkDestroySampler", "VUID-vkDestroySampler-sampler-01082"); } return skip; } bool CoreChecks::PreCallValidateDestroyDescriptorPool(VkDevice device, VkDescriptorPool descriptorPool, const VkAllocationCallbacks *pAllocator) const { const DESCRIPTOR_POOL_STATE *desc_pool_state = GetDescriptorPoolState(descriptorPool); bool skip = false; if (desc_pool_state) { skip |= ValidateObjectNotInUse(desc_pool_state, "vkDestroyDescriptorPool", "VUID-vkDestroyDescriptorPool-descriptorPool-00303"); } return skip; } // Verify cmdBuffer in given cb_node is not in global in-flight set, and return skip result // If this is a secondary command buffer, then make sure its primary is also in-flight // If primary is not in-flight, then remove secondary from global in-flight set // This function is only valid at a point when cmdBuffer is being reset or freed bool CoreChecks::CheckCommandBufferInFlight(const CMD_BUFFER_STATE *cb_node, const char *action, const char *error_code) const { bool skip = false; if (cb_node->InUse()) { skip |= LogError(cb_node->commandBuffer(), error_code, "Attempt to %s %s which is in use.", action, report_data->FormatHandle(cb_node->commandBuffer()).c_str()); } return skip; } // Iterate over all cmdBuffers in given commandPool and verify that each is not in use bool CoreChecks::CheckCommandBuffersInFlight(const COMMAND_POOL_STATE *pPool, const char *action, const char *error_code) const { bool skip = false; for (auto cmd_buffer : pPool->commandBuffers) { skip |= CheckCommandBufferInFlight(GetCBState(cmd_buffer), action, error_code); } return skip; } bool CoreChecks::PreCallValidateFreeCommandBuffers(VkDevice device, VkCommandPool commandPool, uint32_t commandBufferCount, const VkCommandBuffer *pCommandBuffers) const { bool skip = false; for (uint32_t i = 0; i < commandBufferCount; i++) { const auto *cb_node = GetCBState(pCommandBuffers[i]); // Delete CB information structure, and remove from commandBufferMap if (cb_node) { skip |= CheckCommandBufferInFlight(cb_node, "free", "VUID-vkFreeCommandBuffers-pCommandBuffers-00047"); } } return skip; } bool CoreChecks::PreCallValidateCreateCommandPool(VkDevice device, const VkCommandPoolCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkCommandPool *pCommandPool) const { bool skip = false; skip |= ValidateDeviceQueueFamily(pCreateInfo->queueFamilyIndex, "vkCreateCommandPool", "pCreateInfo->queueFamilyIndex", "VUID-vkCreateCommandPool-queueFamilyIndex-01937"); if ((enabled_features.core11.protectedMemory == VK_FALSE) && ((pCreateInfo->flags & VK_COMMAND_POOL_CREATE_PROTECTED_BIT) != 0)) { skip |= LogError(device, "VUID-VkCommandPoolCreateInfo-flags-02860", "vkCreateCommandPool(): the protectedMemory device feature is disabled: CommandPools cannot be created " "with the VK_COMMAND_POOL_CREATE_PROTECTED_BIT set."); } return skip; } bool CoreChecks::PreCallValidateCreateQueryPool(VkDevice device, const VkQueryPoolCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkQueryPool *pQueryPool) const { if (disabled[query_validation]) return false; bool skip = false; if (pCreateInfo && pCreateInfo->queryType == VK_QUERY_TYPE_PIPELINE_STATISTICS) { if (!enabled_features.core.pipelineStatisticsQuery) { skip |= LogError(device, "VUID-VkQueryPoolCreateInfo-queryType-00791", "vkCreateQueryPool(): Query pool with type VK_QUERY_TYPE_PIPELINE_STATISTICS created on a device with " "VkDeviceCreateInfo.pEnabledFeatures.pipelineStatisticsQuery == VK_FALSE."); } } if (pCreateInfo && pCreateInfo->queryType == VK_QUERY_TYPE_PERFORMANCE_QUERY_KHR) { if (!enabled_features.performance_query_features.performanceCounterQueryPools) { skip |= LogError(device, "VUID-VkQueryPoolPerformanceCreateInfoKHR-performanceCounterQueryPools-03237", "vkCreateQueryPool(): Query pool with type VK_QUERY_TYPE_PERFORMANCE_QUERY_KHR created on a device with " "VkPhysicalDevicePerformanceQueryFeaturesKHR.performanceCounterQueryPools == VK_FALSE."); } auto perf_ci = LvlFindInChain<VkQueryPoolPerformanceCreateInfoKHR>(pCreateInfo->pNext); if (!perf_ci) { skip |= LogError( device, "VUID-VkQueryPoolCreateInfo-queryType-03222", "vkCreateQueryPool(): Query pool with type VK_QUERY_TYPE_PERFORMANCE_QUERY_KHR created but the pNext chain of " "pCreateInfo does not contain in instance of VkQueryPoolPerformanceCreateInfoKHR."); } else { const auto &perf_counter_iter = physical_device_state->perf_counters.find(perf_ci->queueFamilyIndex); if (perf_counter_iter == physical_device_state->perf_counters.end()) { skip |= LogError( device, "VUID-VkQueryPoolPerformanceCreateInfoKHR-queueFamilyIndex-03236", "vkCreateQueryPool(): VkQueryPerformanceCreateInfoKHR::queueFamilyIndex is not a valid queue family index."); } else { const QUEUE_FAMILY_PERF_COUNTERS *perf_counters = perf_counter_iter->second.get(); for (uint32_t idx = 0; idx < perf_ci->counterIndexCount; idx++) { if (perf_ci->pCounterIndices[idx] >= perf_counters->counters.size()) { skip |= LogError( device, "VUID-VkQueryPoolPerformanceCreateInfoKHR-pCounterIndices-03321", "vkCreateQueryPool(): VkQueryPerformanceCreateInfoKHR::pCounterIndices[%u] = %u is not a valid " "counter index.", idx, perf_ci->pCounterIndices[idx]); } } } } } return skip; } bool CoreChecks::PreCallValidateDestroyCommandPool(VkDevice device, VkCommandPool commandPool, const VkAllocationCallbacks *pAllocator) const { const COMMAND_POOL_STATE *cp_state = GetCommandPoolState(commandPool); bool skip = false; if (cp_state) { // Verify that command buffers in pool are complete (not in-flight) skip |= CheckCommandBuffersInFlight(cp_state, "destroy command pool with", "VUID-vkDestroyCommandPool-commandPool-00041"); } return skip; } bool CoreChecks::PreCallValidateResetCommandPool(VkDevice device, VkCommandPool commandPool, VkCommandPoolResetFlags flags) const { const auto *command_pool_state = GetCommandPoolState(commandPool); return CheckCommandBuffersInFlight(command_pool_state, "reset command pool with", "VUID-vkResetCommandPool-commandPool-00040"); } bool CoreChecks::PreCallValidateResetFences(VkDevice device, uint32_t fenceCount, const VkFence *pFences) const { bool skip = false; for (uint32_t i = 0; i < fenceCount; ++i) { const auto fence_state = GetFenceState(pFences[i]); if (fence_state && fence_state->scope == kSyncScopeInternal && fence_state->state == FENCE_INFLIGHT) { skip |= LogError(pFences[i], "VUID-vkResetFences-pFences-01123", "%s is in use.", report_data->FormatHandle(pFences[i]).c_str()); } } return skip; } bool CoreChecks::PreCallValidateDestroyFramebuffer(VkDevice device, VkFramebuffer framebuffer, const VkAllocationCallbacks *pAllocator) const { const FRAMEBUFFER_STATE *framebuffer_state = GetFramebufferState(framebuffer); bool skip = false; if (framebuffer_state) { skip |= ValidateObjectNotInUse(framebuffer_state, "vkDestroyFramebuffer", "VUID-vkDestroyFramebuffer-framebuffer-00892"); } return skip; } bool CoreChecks::PreCallValidateDestroyRenderPass(VkDevice device, VkRenderPass renderPass, const VkAllocationCallbacks *pAllocator) const { const RENDER_PASS_STATE *rp_state = GetRenderPassState(renderPass); bool skip = false; if (rp_state) { skip |= ValidateObjectNotInUse(rp_state, "vkDestroyRenderPass", "VUID-vkDestroyRenderPass-renderPass-00873"); } return skip; } // Access helper functions for external modules VkFormatProperties CoreChecks::GetPDFormatProperties(const VkFormat format) const { VkFormatProperties format_properties; DispatchGetPhysicalDeviceFormatProperties(physical_device, format, &format_properties); return format_properties; } bool CoreChecks::ValidatePipelineVertexDivisors(std::vector<std::shared_ptr<PIPELINE_STATE>> const &pipe_state_vec, const uint32_t count, const VkGraphicsPipelineCreateInfo *pipe_cis) const { bool skip = false; const VkPhysicalDeviceLimits *device_limits = &phys_dev_props.limits; for (uint32_t i = 0; i < count; i++) { auto pvids_ci = (pipe_cis[i].pVertexInputState) ? LvlFindInChain<VkPipelineVertexInputDivisorStateCreateInfoEXT>(pipe_cis[i].pVertexInputState->pNext) : nullptr; if (nullptr == pvids_ci) continue; const PIPELINE_STATE *pipe_state = pipe_state_vec[i].get(); for (uint32_t j = 0; j < pvids_ci->vertexBindingDivisorCount; j++) { const VkVertexInputBindingDivisorDescriptionEXT *vibdd = &(pvids_ci->pVertexBindingDivisors[j]); if (vibdd->binding >= device_limits->maxVertexInputBindings) { skip |= LogError( device, "VUID-VkVertexInputBindingDivisorDescriptionEXT-binding-01869", "vkCreateGraphicsPipelines(): Pipeline[%1u] with chained VkPipelineVertexInputDivisorStateCreateInfoEXT, " "pVertexBindingDivisors[%1u] binding index of (%1u) exceeds device maxVertexInputBindings (%1u).", i, j, vibdd->binding, device_limits->maxVertexInputBindings); } if (vibdd->divisor > phys_dev_ext_props.vtx_attrib_divisor_props.maxVertexAttribDivisor) { skip |= LogError( device, "VUID-VkVertexInputBindingDivisorDescriptionEXT-divisor-01870", "vkCreateGraphicsPipelines(): Pipeline[%1u] with chained VkPipelineVertexInputDivisorStateCreateInfoEXT, " "pVertexBindingDivisors[%1u] divisor of (%1u) exceeds extension maxVertexAttribDivisor (%1u).", i, j, vibdd->divisor, phys_dev_ext_props.vtx_attrib_divisor_props.maxVertexAttribDivisor); } if ((0 == vibdd->divisor) && !enabled_features.vtx_attrib_divisor_features.vertexAttributeInstanceRateZeroDivisor) { skip |= LogError( device, "VUID-VkVertexInputBindingDivisorDescriptionEXT-vertexAttributeInstanceRateZeroDivisor-02228", "vkCreateGraphicsPipelines(): Pipeline[%1u] with chained VkPipelineVertexInputDivisorStateCreateInfoEXT, " "pVertexBindingDivisors[%1u] divisor must not be 0 when vertexAttributeInstanceRateZeroDivisor feature is not " "enabled.", i, j); } if ((1 != vibdd->divisor) && !enabled_features.vtx_attrib_divisor_features.vertexAttributeInstanceRateDivisor) { skip |= LogError( device, "VUID-VkVertexInputBindingDivisorDescriptionEXT-vertexAttributeInstanceRateDivisor-02229", "vkCreateGraphicsPipelines(): Pipeline[%1u] with chained VkPipelineVertexInputDivisorStateCreateInfoEXT, " "pVertexBindingDivisors[%1u] divisor (%1u) must be 1 when vertexAttributeInstanceRateDivisor feature is not " "enabled.", i, j, vibdd->divisor); } // Find the corresponding binding description and validate input rate setting bool failed_01871 = true; for (size_t k = 0; k < pipe_state->vertex_binding_descriptions_.size(); k++) { if ((vibdd->binding == pipe_state->vertex_binding_descriptions_[k].binding) && (VK_VERTEX_INPUT_RATE_INSTANCE == pipe_state->vertex_binding_descriptions_[k].inputRate)) { failed_01871 = false; break; } } if (failed_01871) { // Description not found, or has incorrect inputRate value skip |= LogError( device, "VUID-VkVertexInputBindingDivisorDescriptionEXT-inputRate-01871", "vkCreateGraphicsPipelines(): Pipeline[%1u] with chained VkPipelineVertexInputDivisorStateCreateInfoEXT, " "pVertexBindingDivisors[%1u] specifies binding index (%1u), but that binding index's " "VkVertexInputBindingDescription.inputRate member is not VK_VERTEX_INPUT_RATE_INSTANCE.", i, j, vibdd->binding); } } } return skip; } bool CoreChecks::ValidatePipelineCacheControlFlags(VkPipelineCreateFlags flags, uint32_t index, const char *caller_name, const char *vuid) const { bool skip = false; if (enabled_features.pipeline_creation_cache_control_features.pipelineCreationCacheControl == VK_FALSE) { const VkPipelineCreateFlags invalid_flags = VK_PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT_EXT | VK_PIPELINE_CREATE_EARLY_RETURN_ON_FAILURE_BIT_EXT; if ((flags & invalid_flags) != 0) { skip |= LogError(device, vuid, "%s(): pipelineCreationCacheControl is turned off but pipeline[%u] has VkPipelineCreateFlags " "containing VK_PIPELINE_CREATE_FAIL_ON_PIPELINE_COMPILE_REQUIRED_BIT_EXT or " "VK_PIPELINE_CREATE_EARLY_RETURN_ON_FAILURE_BIT_EXT", caller_name, index); } } return skip; } bool CoreChecks::PreCallValidateCreatePipelineCache(VkDevice device, const VkPipelineCacheCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkPipelineCache *pPipelineCache) const { bool skip = false; if (enabled_features.pipeline_creation_cache_control_features.pipelineCreationCacheControl == VK_FALSE) { if ((pCreateInfo->flags & VK_PIPELINE_CACHE_CREATE_EXTERNALLY_SYNCHRONIZED_BIT_EXT) != 0) { skip |= LogError(device, "VUID-VkPipelineCacheCreateInfo-pipelineCreationCacheControl-02892", "vkCreatePipelineCache(): pipelineCreationCacheControl is turned off but pCreateInfo::flags contains " "VK_PIPELINE_CACHE_CREATE_EXTERNALLY_SYNCHRONIZED_BIT_EXT"); } } return skip; } bool CoreChecks::PreCallValidateCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t count, const VkGraphicsPipelineCreateInfo *pCreateInfos, const VkAllocationCallbacks *pAllocator, VkPipeline *pPipelines, void *cgpl_state_data) const { bool skip = StateTracker::PreCallValidateCreateGraphicsPipelines(device, pipelineCache, count, pCreateInfos, pAllocator, pPipelines, cgpl_state_data); create_graphics_pipeline_api_state *cgpl_state = reinterpret_cast<create_graphics_pipeline_api_state *>(cgpl_state_data); for (uint32_t i = 0; i < count; i++) { skip |= ValidatePipelineLocked(cgpl_state->pipe_state, i); } for (uint32_t i = 0; i < count; i++) { skip |= ValidatePipelineUnlocked(cgpl_state->pipe_state[i].get(), i); } if (device_extensions.vk_ext_vertex_attribute_divisor) { skip |= ValidatePipelineVertexDivisors(cgpl_state->pipe_state, count, pCreateInfos); } if (ExtEnabled::kNotEnabled != device_extensions.vk_khr_portability_subset) { for (uint32_t i = 0; i < count; ++i) { // Validate depth-stencil state auto raster_state_ci = pCreateInfos[i].pRasterizationState; if ((VK_FALSE == enabled_features.portability_subset_features.separateStencilMaskRef) && raster_state_ci && (VK_CULL_MODE_NONE == raster_state_ci->cullMode)) { auto depth_stencil_ci = pCreateInfos[i].pDepthStencilState; if (depth_stencil_ci && (VK_TRUE == depth_stencil_ci->stencilTestEnable) && (depth_stencil_ci->front.reference != depth_stencil_ci->back.reference)) { skip |= LogError(device, "VUID-VkPipelineDepthStencilStateCreateInfo-separateStencilMaskRef-04453", "Invalid Pipeline CreateInfo[%d] (portability error): VkStencilOpState::reference must be the " "same for front and back", i); } } // Validate color attachments uint32_t subpass = pCreateInfos[i].subpass; const auto *render_pass = GetRenderPassState(pCreateInfos[i].renderPass); bool ignore_color_blend_state = pCreateInfos[i].pRasterizationState->rasterizerDiscardEnable || render_pass->createInfo.pSubpasses[subpass].colorAttachmentCount == 0; if ((VK_FALSE == enabled_features.portability_subset_features.constantAlphaColorBlendFactors) && !ignore_color_blend_state) { auto color_blend_state = pCreateInfos[i].pColorBlendState; const auto attachments = color_blend_state->pAttachments; for (uint32_t color_attachment_index = 0; i < color_blend_state->attachmentCount; ++i) { if ((VK_BLEND_FACTOR_CONSTANT_ALPHA == attachments[color_attachment_index].srcColorBlendFactor) || (VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA == attachments[color_attachment_index].srcColorBlendFactor)) { skip |= LogError( device, "VUID-VkPipelineColorBlendAttachmentState-constantAlphaColorBlendFactors-04454", "Invalid Pipeline CreateInfo[%d] (portability error): srcColorBlendFactor for color attachment %d must " "not be VK_BLEND_FACTOR_CONSTANT_ALPHA or VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA", i, color_attachment_index); } if ((VK_BLEND_FACTOR_CONSTANT_ALPHA == attachments[color_attachment_index].dstColorBlendFactor) || (VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA == attachments[color_attachment_index].dstColorBlendFactor)) { skip |= LogError( device, "VUID-VkPipelineColorBlendAttachmentState-constantAlphaColorBlendFactors-04455", "Invalid Pipeline CreateInfo[%d] (portability error): dstColorBlendFactor for color attachment %d must " "not be VK_BLEND_FACTOR_CONSTANT_ALPHA or VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA", i, color_attachment_index); } } } } } return skip; } void CoreChecks::PostCallRecordCreateGraphicsPipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t count, const VkGraphicsPipelineCreateInfo *pCreateInfos, const VkAllocationCallbacks *pAllocator, VkPipeline *pPipelines, VkResult result, void *cgpl_state_data) { ValidationStateTracker::PostCallRecordCreateGraphicsPipelines(device, pipelineCache, count, pCreateInfos, pAllocator, pPipelines, result, cgpl_state_data); if (enabled_features.fragment_shading_rate_features.primitiveFragmentShadingRate) { for (uint32_t i = 0; i < count; i++) { PIPELINE_STATE *pipeline_state = GetPipelineState(pPipelines[i]); RecordGraphicsPipelineShaderDynamicState(pipeline_state); } } } bool CoreChecks::PreCallValidateCreateComputePipelines(VkDevice device, VkPipelineCache pipelineCache, uint32_t count, const VkComputePipelineCreateInfo *pCreateInfos, const VkAllocationCallbacks *pAllocator, VkPipeline *pPipelines, void *ccpl_state_data) const { bool skip = StateTracker::PreCallValidateCreateComputePipelines(device, pipelineCache, count, pCreateInfos, pAllocator, pPipelines, ccpl_state_data); auto *ccpl_state = reinterpret_cast<create_compute_pipeline_api_state *>(ccpl_state_data); for (uint32_t i = 0; i < count; i++) { // TODO: Add Compute Pipeline Verification skip |= ValidateComputePipelineShaderState(ccpl_state->pipe_state[i].get()); skip |= ValidatePipelineCacheControlFlags(pCreateInfos->flags, i, "vkCreateComputePipelines", "VUID-VkComputePipelineCreateInfo-pipelineCreationCacheControl-02875"); } return skip; } bool CoreChecks::PreCallValidateCreateRayTracingPipelinesNV(VkDevice device, VkPipelineCache pipelineCache, uint32_t count, const VkRayTracingPipelineCreateInfoNV *pCreateInfos, const VkAllocationCallbacks *pAllocator, VkPipeline *pPipelines, void *crtpl_state_data) const { bool skip = StateTracker::PreCallValidateCreateRayTracingPipelinesNV(device, pipelineCache, count, pCreateInfos, pAllocator, pPipelines, crtpl_state_data); auto *crtpl_state = reinterpret_cast<create_ray_tracing_pipeline_api_state *>(crtpl_state_data); for (uint32_t i = 0; i < count; i++) { PIPELINE_STATE *pipeline = crtpl_state->pipe_state[i].get(); if (pipeline->raytracingPipelineCI.flags & VK_PIPELINE_CREATE_DERIVATIVE_BIT) { const PIPELINE_STATE *base_pipeline = nullptr; if (pipeline->raytracingPipelineCI.basePipelineIndex != -1) { base_pipeline = crtpl_state->pipe_state[pipeline->raytracingPipelineCI.basePipelineIndex].get(); } else if (pipeline->raytracingPipelineCI.basePipelineHandle != VK_NULL_HANDLE) { base_pipeline = GetPipelineState(pipeline->raytracingPipelineCI.basePipelineHandle); } if (!base_pipeline || !(base_pipeline->getPipelineCreateFlags() & VK_PIPELINE_CREATE_ALLOW_DERIVATIVES_BIT)) { skip |= LogError( device, "VUID-vkCreateRayTracingPipelinesNV-flags-03416", "vkCreateRayTracingPipelinesNV: If the flags member of any element of pCreateInfos contains the " "VK_PIPELINE_CREATE_DERIVATIVE_BIT flag," "the base pipeline must have been created with the VK_PIPELINE_CREATE_ALLOW_DERIVATIVES_BIT flag set."); } } skip |= ValidateRayTracingPipeline(pipeline, pCreateInfos[i].flags, /*isKHR*/ false); skip |= ValidatePipelineCacheControlFlags(pCreateInfos[i].flags, i, "vkCreateRayTracingPipelinesNV", "VUID-VkRayTracingPipelineCreateInfoNV-pipelineCreationCacheControl-02905"); } return skip; } bool CoreChecks::PreCallValidateCreateRayTracingPipelinesKHR(VkDevice device, VkDeferredOperationKHR deferredOperation, VkPipelineCache pipelineCache, uint32_t count, const VkRayTracingPipelineCreateInfoKHR *pCreateInfos, const VkAllocationCallbacks *pAllocator, VkPipeline *pPipelines, void *crtpl_state_data) const { bool skip = StateTracker::PreCallValidateCreateRayTracingPipelinesKHR(device, deferredOperation, pipelineCache, count, pCreateInfos, pAllocator, pPipelines, crtpl_state_data); auto *crtpl_state = reinterpret_cast<create_ray_tracing_pipeline_khr_api_state *>(crtpl_state_data); for (uint32_t i = 0; i < count; i++) { PIPELINE_STATE *pipeline = crtpl_state->pipe_state[i].get(); if (pipeline->raytracingPipelineCI.flags & VK_PIPELINE_CREATE_DERIVATIVE_BIT) { const PIPELINE_STATE *base_pipeline = nullptr; if (pipeline->raytracingPipelineCI.basePipelineIndex != -1) { base_pipeline = crtpl_state->pipe_state[pipeline->raytracingPipelineCI.basePipelineIndex].get(); } else if (pipeline->raytracingPipelineCI.basePipelineHandle != VK_NULL_HANDLE) { base_pipeline = GetPipelineState(pipeline->raytracingPipelineCI.basePipelineHandle); } if (!base_pipeline || !(base_pipeline->getPipelineCreateFlags() & VK_PIPELINE_CREATE_ALLOW_DERIVATIVES_BIT)) { skip |= LogError( device, "VUID-vkCreateRayTracingPipelinesKHR-flags-03416", "vkCreateRayTracingPipelinesKHR: If the flags member of any element of pCreateInfos contains the " "VK_PIPELINE_CREATE_DERIVATIVE_BIT flag," "the base pipeline must have been created with the VK_PIPELINE_CREATE_ALLOW_DERIVATIVES_BIT flag set."); } } skip |= ValidateRayTracingPipeline(pipeline, pCreateInfos[i].flags, /*isKHR*/ true); skip |= ValidatePipelineCacheControlFlags(pCreateInfos[i].flags, i, "vkCreateRayTracingPipelinesKHR", "VUID-VkRayTracingPipelineCreateInfoKHR-pipelineCreationCacheControl-02905"); } return skip; } bool CoreChecks::PreCallValidateGetPipelineExecutablePropertiesKHR(VkDevice device, const VkPipelineInfoKHR *pPipelineInfo, uint32_t *pExecutableCount, VkPipelineExecutablePropertiesKHR *pProperties) const { bool skip = false; skip |= ValidatePipelineExecutableInfo(device, nullptr, "vkGetPipelineExecutablePropertiesKHR", "VUID-vkGetPipelineExecutablePropertiesKHR-pipelineExecutableInfo-03270"); return skip; } bool CoreChecks::ValidatePipelineExecutableInfo(VkDevice device, const VkPipelineExecutableInfoKHR *pExecutableInfo, const char *caller_name, const char *feature_vuid) const { bool skip = false; if (!enabled_features.pipeline_exe_props_features.pipelineExecutableInfo) { skip |= LogError(device, feature_vuid, "%s(): called when pipelineExecutableInfo feature is not enabled.", caller_name); } // vkGetPipelineExecutablePropertiesKHR will not have struct to validate further if (pExecutableInfo) { auto pi = LvlInitStruct<VkPipelineInfoKHR>(); pi.pipeline = pExecutableInfo->pipeline; // We could probably cache this instead of fetching it every time uint32_t executable_count = 0; DispatchGetPipelineExecutablePropertiesKHR(device, &pi, &executable_count, NULL); if (pExecutableInfo->executableIndex >= executable_count) { skip |= LogError( pExecutableInfo->pipeline, "VUID-VkPipelineExecutableInfoKHR-executableIndex-03275", "%s(): VkPipelineExecutableInfo::executableIndex (%1u) must be less than the number of executables associated with " "the pipeline (%1u) as returned by vkGetPipelineExecutablePropertiessKHR", caller_name, pExecutableInfo->executableIndex, executable_count); } } return skip; } bool CoreChecks::PreCallValidateGetPipelineExecutableStatisticsKHR(VkDevice device, const VkPipelineExecutableInfoKHR *pExecutableInfo, uint32_t *pStatisticCount, VkPipelineExecutableStatisticKHR *pStatistics) const { bool skip = false; skip |= ValidatePipelineExecutableInfo(device, pExecutableInfo, "vkGetPipelineExecutableStatisticsKHR", "VUID-vkGetPipelineExecutableStatisticsKHR-pipelineExecutableInfo-03272"); const PIPELINE_STATE *pipeline_state = GetPipelineState(pExecutableInfo->pipeline); if (!(pipeline_state->getPipelineCreateFlags() & VK_PIPELINE_CREATE_CAPTURE_STATISTICS_BIT_KHR)) { skip |= LogError(pExecutableInfo->pipeline, "VUID-vkGetPipelineExecutableStatisticsKHR-pipeline-03274", "vkGetPipelineExecutableStatisticsKHR called on a pipeline created without the " "VK_PIPELINE_CREATE_CAPTURE_STATISTICS_BIT_KHR flag set"); } return skip; } bool CoreChecks::PreCallValidateGetPipelineExecutableInternalRepresentationsKHR( VkDevice device, const VkPipelineExecutableInfoKHR *pExecutableInfo, uint32_t *pInternalRepresentationCount, VkPipelineExecutableInternalRepresentationKHR *pStatistics) const { bool skip = false; skip |= ValidatePipelineExecutableInfo(device, pExecutableInfo, "vkGetPipelineExecutableInternalRepresentationsKHR", "VUID-vkGetPipelineExecutableInternalRepresentationsKHR-pipelineExecutableInfo-03276"); const PIPELINE_STATE *pipeline_state = GetPipelineState(pExecutableInfo->pipeline); if (!(pipeline_state->getPipelineCreateFlags() & VK_PIPELINE_CREATE_CAPTURE_INTERNAL_REPRESENTATIONS_BIT_KHR)) { skip |= LogError(pExecutableInfo->pipeline, "VUID-vkGetPipelineExecutableInternalRepresentationsKHR-pipeline-03278", "vkGetPipelineExecutableInternalRepresentationsKHR called on a pipeline created without the " "VK_PIPELINE_CREATE_CAPTURE_INTERNAL_REPRESENTATIONS_BIT_KHR flag set"); } return skip; } bool CoreChecks::PreCallValidateCreateDescriptorSetLayout(VkDevice device, const VkDescriptorSetLayoutCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkDescriptorSetLayout *pSetLayout) const { return cvdescriptorset::ValidateDescriptorSetLayoutCreateInfo( this, pCreateInfo, IsExtEnabled(device_extensions.vk_khr_push_descriptor), phys_dev_ext_props.max_push_descriptors, IsExtEnabled(device_extensions.vk_ext_descriptor_indexing), &enabled_features.core12, &enabled_features.inline_uniform_block, &phys_dev_ext_props.inline_uniform_block_props, &device_extensions); } enum DSL_DESCRIPTOR_GROUPS { DSL_TYPE_SAMPLERS = 0, DSL_TYPE_UNIFORM_BUFFERS, DSL_TYPE_STORAGE_BUFFERS, DSL_TYPE_SAMPLED_IMAGES, DSL_TYPE_STORAGE_IMAGES, DSL_TYPE_INPUT_ATTACHMENTS, DSL_TYPE_INLINE_UNIFORM_BLOCK, DSL_NUM_DESCRIPTOR_GROUPS }; // Used by PreCallValidateCreatePipelineLayout. // Returns an array of size DSL_NUM_DESCRIPTOR_GROUPS of the maximum number of descriptors used in any single pipeline stage std::valarray<uint32_t> GetDescriptorCountMaxPerStage( const DeviceFeatures *enabled_features, const std::vector<std::shared_ptr<cvdescriptorset::DescriptorSetLayout const>> &set_layouts, bool skip_update_after_bind) { // Identify active pipeline stages std::vector<VkShaderStageFlags> stage_flags = {VK_SHADER_STAGE_VERTEX_BIT, VK_SHADER_STAGE_FRAGMENT_BIT, VK_SHADER_STAGE_COMPUTE_BIT}; if (enabled_features->core.geometryShader) { stage_flags.push_back(VK_SHADER_STAGE_GEOMETRY_BIT); } if (enabled_features->core.tessellationShader) { stage_flags.push_back(VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT); stage_flags.push_back(VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT); } // Allow iteration over enum values std::vector<DSL_DESCRIPTOR_GROUPS> dsl_groups = { DSL_TYPE_SAMPLERS, DSL_TYPE_UNIFORM_BUFFERS, DSL_TYPE_STORAGE_BUFFERS, DSL_TYPE_SAMPLED_IMAGES, DSL_TYPE_STORAGE_IMAGES, DSL_TYPE_INPUT_ATTACHMENTS, DSL_TYPE_INLINE_UNIFORM_BLOCK}; // Sum by layouts per stage, then pick max of stages per type std::valarray<uint32_t> max_sum(0U, DSL_NUM_DESCRIPTOR_GROUPS); // max descriptor sum among all pipeline stages for (auto stage : stage_flags) { std::valarray<uint32_t> stage_sum(0U, DSL_NUM_DESCRIPTOR_GROUPS); // per-stage sums for (const auto &dsl : set_layouts) { if (skip_update_after_bind && (dsl->GetCreateFlags() & VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT)) { continue; } for (uint32_t binding_idx = 0; binding_idx < dsl->GetBindingCount(); binding_idx++) { const VkDescriptorSetLayoutBinding *binding = dsl->GetDescriptorSetLayoutBindingPtrFromIndex(binding_idx); // Bindings with a descriptorCount of 0 are "reserved" and should be skipped if (0 != (stage & binding->stageFlags) && binding->descriptorCount > 0) { switch (binding->descriptorType) { case VK_DESCRIPTOR_TYPE_SAMPLER: stage_sum[DSL_TYPE_SAMPLERS] += binding->descriptorCount; break; case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER: case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC: stage_sum[DSL_TYPE_UNIFORM_BUFFERS] += binding->descriptorCount; break; case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER: case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC: stage_sum[DSL_TYPE_STORAGE_BUFFERS] += binding->descriptorCount; break; case VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE: case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER: stage_sum[DSL_TYPE_SAMPLED_IMAGES] += binding->descriptorCount; break; case VK_DESCRIPTOR_TYPE_STORAGE_IMAGE: case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER: stage_sum[DSL_TYPE_STORAGE_IMAGES] += binding->descriptorCount; break; case VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER: stage_sum[DSL_TYPE_SAMPLED_IMAGES] += binding->descriptorCount; stage_sum[DSL_TYPE_SAMPLERS] += binding->descriptorCount; break; case VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT: stage_sum[DSL_TYPE_INPUT_ATTACHMENTS] += binding->descriptorCount; break; case VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT: // count one block per binding. descriptorCount is number of bytes stage_sum[DSL_TYPE_INLINE_UNIFORM_BLOCK]++; break; default: break; } } } } for (auto type : dsl_groups) { max_sum[type] = std::max(stage_sum[type], max_sum[type]); } } return max_sum; } // Used by PreCallValidateCreatePipelineLayout. // Returns a map indexed by VK_DESCRIPTOR_TYPE_* enum of the summed descriptors by type. // Note: descriptors only count against the limit once even if used by multiple stages. std::map<uint32_t, uint32_t> GetDescriptorSum( const std::vector<std::shared_ptr<cvdescriptorset::DescriptorSetLayout const>> &set_layouts, bool skip_update_after_bind) { std::map<uint32_t, uint32_t> sum_by_type; for (const auto &dsl : set_layouts) { if (skip_update_after_bind && (dsl->GetCreateFlags() & VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT)) { continue; } for (uint32_t binding_idx = 0; binding_idx < dsl->GetBindingCount(); binding_idx++) { const VkDescriptorSetLayoutBinding *binding = dsl->GetDescriptorSetLayoutBindingPtrFromIndex(binding_idx); // Bindings with a descriptorCount of 0 are "reserved" and should be skipped if (binding->descriptorCount > 0) { if (binding->descriptorType == VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT) { // count one block per binding. descriptorCount is number of bytes sum_by_type[binding->descriptorType]++; } else { sum_by_type[binding->descriptorType] += binding->descriptorCount; } } } } return sum_by_type; } bool CoreChecks::PreCallValidateCreatePipelineLayout(VkDevice device, const VkPipelineLayoutCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkPipelineLayout *pPipelineLayout) const { bool skip = false; std::vector<std::shared_ptr<cvdescriptorset::DescriptorSetLayout const>> set_layouts(pCreateInfo->setLayoutCount, nullptr); unsigned int push_descriptor_set_count = 0; { for (uint32_t i = 0; i < pCreateInfo->setLayoutCount; ++i) { set_layouts[i] = GetDescriptorSetLayoutShared(pCreateInfo->pSetLayouts[i]); if (set_layouts[i]->IsPushDescriptor()) ++push_descriptor_set_count; } } if (push_descriptor_set_count > 1) { skip |= LogError(device, "VUID-VkPipelineLayoutCreateInfo-pSetLayouts-00293", "vkCreatePipelineLayout() Multiple push descriptor sets found."); } // Max descriptors by type, within a single pipeline stage std::valarray<uint32_t> max_descriptors_per_stage = GetDescriptorCountMaxPerStage(&enabled_features, set_layouts, true); // Samplers if (max_descriptors_per_stage[DSL_TYPE_SAMPLERS] > phys_dev_props.limits.maxPerStageDescriptorSamplers) { const char *vuid = (device_extensions.vk_ext_descriptor_indexing) ? "VUID-VkPipelineLayoutCreateInfo-descriptorType-03016" : "VUID-VkPipelineLayoutCreateInfo-pSetLayouts-00287"; skip |= LogError(device, vuid, "vkCreatePipelineLayout(): max per-stage sampler bindings count (%d) exceeds device " "maxPerStageDescriptorSamplers limit (%d).", max_descriptors_per_stage[DSL_TYPE_SAMPLERS], phys_dev_props.limits.maxPerStageDescriptorSamplers); } // Uniform buffers if (max_descriptors_per_stage[DSL_TYPE_UNIFORM_BUFFERS] > phys_dev_props.limits.maxPerStageDescriptorUniformBuffers) { const char *vuid = (device_extensions.vk_ext_descriptor_indexing) ? "VUID-VkPipelineLayoutCreateInfo-descriptorType-03017" : "VUID-VkPipelineLayoutCreateInfo-pSetLayouts-00288"; skip |= LogError(device, vuid, "vkCreatePipelineLayout(): max per-stage uniform buffer bindings count (%d) exceeds device " "maxPerStageDescriptorUniformBuffers limit (%d).", max_descriptors_per_stage[DSL_TYPE_UNIFORM_BUFFERS], phys_dev_props.limits.maxPerStageDescriptorUniformBuffers); } // Storage buffers if (max_descriptors_per_stage[DSL_TYPE_STORAGE_BUFFERS] > phys_dev_props.limits.maxPerStageDescriptorStorageBuffers) { const char *vuid = (device_extensions.vk_ext_descriptor_indexing) ? "VUID-VkPipelineLayoutCreateInfo-descriptorType-03018" : "VUID-VkPipelineLayoutCreateInfo-pSetLayouts-00289"; skip |= LogError(device, vuid, "vkCreatePipelineLayout(): max per-stage storage buffer bindings count (%d) exceeds device " "maxPerStageDescriptorStorageBuffers limit (%d).", max_descriptors_per_stage[DSL_TYPE_STORAGE_BUFFERS], phys_dev_props.limits.maxPerStageDescriptorStorageBuffers); } // Sampled images if (max_descriptors_per_stage[DSL_TYPE_SAMPLED_IMAGES] > phys_dev_props.limits.maxPerStageDescriptorSampledImages) { const char *vuid = (device_extensions.vk_ext_descriptor_indexing) ? "VUID-VkPipelineLayoutCreateInfo-descriptorType-03019" : "VUID-VkPipelineLayoutCreateInfo-pSetLayouts-00290"; skip |= LogError(device, vuid, "vkCreatePipelineLayout(): max per-stage sampled image bindings count (%d) exceeds device " "maxPerStageDescriptorSampledImages limit (%d).", max_descriptors_per_stage[DSL_TYPE_SAMPLED_IMAGES], phys_dev_props.limits.maxPerStageDescriptorSampledImages); } // Storage images if (max_descriptors_per_stage[DSL_TYPE_STORAGE_IMAGES] > phys_dev_props.limits.maxPerStageDescriptorStorageImages) { const char *vuid = (device_extensions.vk_ext_descriptor_indexing) ? "VUID-VkPipelineLayoutCreateInfo-descriptorType-03020" : "VUID-VkPipelineLayoutCreateInfo-pSetLayouts-00291"; skip |= LogError(device, vuid, "vkCreatePipelineLayout(): max per-stage storage image bindings count (%d) exceeds device " "maxPerStageDescriptorStorageImages limit (%d).", max_descriptors_per_stage[DSL_TYPE_STORAGE_IMAGES], phys_dev_props.limits.maxPerStageDescriptorStorageImages); } // Input attachments if (max_descriptors_per_stage[DSL_TYPE_INPUT_ATTACHMENTS] > phys_dev_props.limits.maxPerStageDescriptorInputAttachments) { const char *vuid = (device_extensions.vk_ext_descriptor_indexing) ? "VUID-VkPipelineLayoutCreateInfo-descriptorType-03021" : "VUID-VkPipelineLayoutCreateInfo-pSetLayouts-01676"; skip |= LogError(device, vuid, "vkCreatePipelineLayout(): max per-stage input attachment bindings count (%d) exceeds device " "maxPerStageDescriptorInputAttachments limit (%d).", max_descriptors_per_stage[DSL_TYPE_INPUT_ATTACHMENTS], phys_dev_props.limits.maxPerStageDescriptorInputAttachments); } // Inline uniform blocks if (max_descriptors_per_stage[DSL_TYPE_INLINE_UNIFORM_BLOCK] > phys_dev_ext_props.inline_uniform_block_props.maxPerStageDescriptorInlineUniformBlocks) { const char *vuid = (device_extensions.vk_ext_descriptor_indexing) ? "VUID-VkPipelineLayoutCreateInfo-descriptorType-02214" : "VUID-VkPipelineLayoutCreateInfo-descriptorType-02212"; skip |= LogError(device, vuid, "vkCreatePipelineLayout(): max per-stage inline uniform block bindings count (%d) exceeds device " "maxPerStageDescriptorInlineUniformBlocks limit (%d).", max_descriptors_per_stage[DSL_TYPE_INLINE_UNIFORM_BLOCK], phys_dev_ext_props.inline_uniform_block_props.maxPerStageDescriptorInlineUniformBlocks); } // Total descriptors by type // std::map<uint32_t, uint32_t> sum_all_stages = GetDescriptorSum(set_layouts, true); // Samplers uint32_t sum = sum_all_stages[VK_DESCRIPTOR_TYPE_SAMPLER] + sum_all_stages[VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER]; if (sum > phys_dev_props.limits.maxDescriptorSetSamplers) { const char *vuid = (device_extensions.vk_ext_descriptor_indexing) ? "VUID-VkPipelineLayoutCreateInfo-descriptorType-03028" : "VUID-VkPipelineLayoutCreateInfo-pSetLayouts-01677"; skip |= LogError(device, vuid, "vkCreatePipelineLayout(): sum of sampler bindings among all stages (%d) exceeds device " "maxDescriptorSetSamplers limit (%d).", sum, phys_dev_props.limits.maxDescriptorSetSamplers); } // Uniform buffers if (sum_all_stages[VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER] > phys_dev_props.limits.maxDescriptorSetUniformBuffers) { const char *vuid = (device_extensions.vk_ext_descriptor_indexing) ? "VUID-VkPipelineLayoutCreateInfo-descriptorType-03029" : "VUID-VkPipelineLayoutCreateInfo-pSetLayouts-01678"; skip |= LogError(device, vuid, "vkCreatePipelineLayout(): sum of uniform buffer bindings among all stages (%d) exceeds device " "maxDescriptorSetUniformBuffers limit (%d).", sum_all_stages[VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER], phys_dev_props.limits.maxDescriptorSetUniformBuffers); } // Dynamic uniform buffers if (sum_all_stages[VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC] > phys_dev_props.limits.maxDescriptorSetUniformBuffersDynamic) { const char *vuid = (device_extensions.vk_ext_descriptor_indexing) ? "VUID-VkPipelineLayoutCreateInfo-descriptorType-03030" : "VUID-VkPipelineLayoutCreateInfo-pSetLayouts-01679"; skip |= LogError(device, vuid, "vkCreatePipelineLayout(): sum of dynamic uniform buffer bindings among all stages (%d) exceeds device " "maxDescriptorSetUniformBuffersDynamic limit (%d).", sum_all_stages[VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC], phys_dev_props.limits.maxDescriptorSetUniformBuffersDynamic); } // Storage buffers if (sum_all_stages[VK_DESCRIPTOR_TYPE_STORAGE_BUFFER] > phys_dev_props.limits.maxDescriptorSetStorageBuffers) { const char *vuid = (device_extensions.vk_ext_descriptor_indexing) ? "VUID-VkPipelineLayoutCreateInfo-descriptorType-03031" : "VUID-VkPipelineLayoutCreateInfo-pSetLayouts-01680"; skip |= LogError(device, vuid, "vkCreatePipelineLayout(): sum of storage buffer bindings among all stages (%d) exceeds device " "maxDescriptorSetStorageBuffers limit (%d).", sum_all_stages[VK_DESCRIPTOR_TYPE_STORAGE_BUFFER], phys_dev_props.limits.maxDescriptorSetStorageBuffers); } // Dynamic storage buffers if (sum_all_stages[VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC] > phys_dev_props.limits.maxDescriptorSetStorageBuffersDynamic) { const char *vuid = (device_extensions.vk_ext_descriptor_indexing) ? "VUID-VkPipelineLayoutCreateInfo-descriptorType-03032" : "VUID-VkPipelineLayoutCreateInfo-pSetLayouts-01681"; skip |= LogError(device, vuid, "vkCreatePipelineLayout(): sum of dynamic storage buffer bindings among all stages (%d) exceeds device " "maxDescriptorSetStorageBuffersDynamic limit (%d).", sum_all_stages[VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC], phys_dev_props.limits.maxDescriptorSetStorageBuffersDynamic); } // Sampled images sum = sum_all_stages[VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE] + sum_all_stages[VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER] + sum_all_stages[VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER]; if (sum > phys_dev_props.limits.maxDescriptorSetSampledImages) { const char *vuid = (device_extensions.vk_ext_descriptor_indexing) ? "VUID-VkPipelineLayoutCreateInfo-descriptorType-03033" : "VUID-VkPipelineLayoutCreateInfo-pSetLayouts-01682"; skip |= LogError(device, vuid, "vkCreatePipelineLayout(): sum of sampled image bindings among all stages (%d) exceeds device " "maxDescriptorSetSampledImages limit (%d).", sum, phys_dev_props.limits.maxDescriptorSetSampledImages); } // Storage images sum = sum_all_stages[VK_DESCRIPTOR_TYPE_STORAGE_IMAGE] + sum_all_stages[VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER]; if (sum > phys_dev_props.limits.maxDescriptorSetStorageImages) { const char *vuid = (device_extensions.vk_ext_descriptor_indexing) ? "VUID-VkPipelineLayoutCreateInfo-descriptorType-03034" : "VUID-VkPipelineLayoutCreateInfo-pSetLayouts-01683"; skip |= LogError(device, vuid, "vkCreatePipelineLayout(): sum of storage image bindings among all stages (%d) exceeds device " "maxDescriptorSetStorageImages limit (%d).", sum, phys_dev_props.limits.maxDescriptorSetStorageImages); } // Input attachments if (sum_all_stages[VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT] > phys_dev_props.limits.maxDescriptorSetInputAttachments) { const char *vuid = (device_extensions.vk_ext_descriptor_indexing) ? "VUID-VkPipelineLayoutCreateInfo-descriptorType-03035" : "VUID-VkPipelineLayoutCreateInfo-pSetLayouts-01684"; skip |= LogError(device, vuid, "vkCreatePipelineLayout(): sum of input attachment bindings among all stages (%d) exceeds device " "maxDescriptorSetInputAttachments limit (%d).", sum_all_stages[VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT], phys_dev_props.limits.maxDescriptorSetInputAttachments); } // Inline uniform blocks if (sum_all_stages[VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT] > phys_dev_ext_props.inline_uniform_block_props.maxDescriptorSetInlineUniformBlocks) { const char *vuid = (device_extensions.vk_ext_descriptor_indexing) ? "VUID-VkPipelineLayoutCreateInfo-descriptorType-02216" : "VUID-VkPipelineLayoutCreateInfo-descriptorType-02213"; skip |= LogError(device, vuid, "vkCreatePipelineLayout(): sum of inline uniform block bindings among all stages (%d) exceeds device " "maxDescriptorSetInlineUniformBlocks limit (%d).", sum_all_stages[VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT], phys_dev_ext_props.inline_uniform_block_props.maxDescriptorSetInlineUniformBlocks); } if (device_extensions.vk_ext_descriptor_indexing) { // XXX TODO: replace with correct VU messages // Max descriptors by type, within a single pipeline stage std::valarray<uint32_t> max_descriptors_per_stage_update_after_bind = GetDescriptorCountMaxPerStage(&enabled_features, set_layouts, false); // Samplers if (max_descriptors_per_stage_update_after_bind[DSL_TYPE_SAMPLERS] > phys_dev_props_core12.maxPerStageDescriptorUpdateAfterBindSamplers) { skip |= LogError(device, "VUID-VkPipelineLayoutCreateInfo-descriptorType-03022", "vkCreatePipelineLayout(): max per-stage sampler bindings count (%d) exceeds device " "maxPerStageDescriptorUpdateAfterBindSamplers limit (%d).", max_descriptors_per_stage_update_after_bind[DSL_TYPE_SAMPLERS], phys_dev_props_core12.maxPerStageDescriptorUpdateAfterBindSamplers); } // Uniform buffers if (max_descriptors_per_stage_update_after_bind[DSL_TYPE_UNIFORM_BUFFERS] > phys_dev_props_core12.maxPerStageDescriptorUpdateAfterBindUniformBuffers) { skip |= LogError(device, "VUID-VkPipelineLayoutCreateInfo-descriptorType-03023", "vkCreatePipelineLayout(): max per-stage uniform buffer bindings count (%d) exceeds device " "maxPerStageDescriptorUpdateAfterBindUniformBuffers limit (%d).", max_descriptors_per_stage_update_after_bind[DSL_TYPE_UNIFORM_BUFFERS], phys_dev_props_core12.maxPerStageDescriptorUpdateAfterBindUniformBuffers); } // Storage buffers if (max_descriptors_per_stage_update_after_bind[DSL_TYPE_STORAGE_BUFFERS] > phys_dev_props_core12.maxPerStageDescriptorUpdateAfterBindStorageBuffers) { skip |= LogError(device, "VUID-VkPipelineLayoutCreateInfo-descriptorType-03024", "vkCreatePipelineLayout(): max per-stage storage buffer bindings count (%d) exceeds device " "maxPerStageDescriptorUpdateAfterBindStorageBuffers limit (%d).", max_descriptors_per_stage_update_after_bind[DSL_TYPE_STORAGE_BUFFERS], phys_dev_props_core12.maxPerStageDescriptorUpdateAfterBindStorageBuffers); } // Sampled images if (max_descriptors_per_stage_update_after_bind[DSL_TYPE_SAMPLED_IMAGES] > phys_dev_props_core12.maxPerStageDescriptorUpdateAfterBindSampledImages) { skip |= LogError(device, "VUID-VkPipelineLayoutCreateInfo-descriptorType-03025", "vkCreatePipelineLayout(): max per-stage sampled image bindings count (%d) exceeds device " "maxPerStageDescriptorUpdateAfterBindSampledImages limit (%d).", max_descriptors_per_stage_update_after_bind[DSL_TYPE_SAMPLED_IMAGES], phys_dev_props_core12.maxPerStageDescriptorUpdateAfterBindSampledImages); } // Storage images if (max_descriptors_per_stage_update_after_bind[DSL_TYPE_STORAGE_IMAGES] > phys_dev_props_core12.maxPerStageDescriptorUpdateAfterBindStorageImages) { skip |= LogError(device, "VUID-VkPipelineLayoutCreateInfo-descriptorType-03026", "vkCreatePipelineLayout(): max per-stage storage image bindings count (%d) exceeds device " "maxPerStageDescriptorUpdateAfterBindStorageImages limit (%d).", max_descriptors_per_stage_update_after_bind[DSL_TYPE_STORAGE_IMAGES], phys_dev_props_core12.maxPerStageDescriptorUpdateAfterBindStorageImages); } // Input attachments if (max_descriptors_per_stage_update_after_bind[DSL_TYPE_INPUT_ATTACHMENTS] > phys_dev_props_core12.maxPerStageDescriptorUpdateAfterBindInputAttachments) { skip |= LogError(device, "VUID-VkPipelineLayoutCreateInfo-descriptorType-03027", "vkCreatePipelineLayout(): max per-stage input attachment bindings count (%d) exceeds device " "maxPerStageDescriptorUpdateAfterBindInputAttachments limit (%d).", max_descriptors_per_stage_update_after_bind[DSL_TYPE_INPUT_ATTACHMENTS], phys_dev_props_core12.maxPerStageDescriptorUpdateAfterBindInputAttachments); } // Inline uniform blocks if (max_descriptors_per_stage_update_after_bind[DSL_TYPE_INLINE_UNIFORM_BLOCK] > phys_dev_ext_props.inline_uniform_block_props.maxPerStageDescriptorUpdateAfterBindInlineUniformBlocks) { skip |= LogError(device, "VUID-VkPipelineLayoutCreateInfo-descriptorType-02215", "vkCreatePipelineLayout(): max per-stage inline uniform block bindings count (%d) exceeds device " "maxPerStageDescriptorUpdateAfterBindInlineUniformBlocks limit (%d).", max_descriptors_per_stage_update_after_bind[DSL_TYPE_INLINE_UNIFORM_BLOCK], phys_dev_ext_props.inline_uniform_block_props.maxPerStageDescriptorUpdateAfterBindInlineUniformBlocks); } // Total descriptors by type, summed across all pipeline stages // std::map<uint32_t, uint32_t> sum_all_stages_update_after_bind = GetDescriptorSum(set_layouts, false); // Samplers sum = sum_all_stages_update_after_bind[VK_DESCRIPTOR_TYPE_SAMPLER] + sum_all_stages_update_after_bind[VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER]; if (sum > phys_dev_props_core12.maxDescriptorSetUpdateAfterBindSamplers) { skip |= LogError(device, "VUID-VkPipelineLayoutCreateInfo-pSetLayouts-03036", "vkCreatePipelineLayout(): sum of sampler bindings among all stages (%d) exceeds device " "maxDescriptorSetUpdateAfterBindSamplers limit (%d).", sum, phys_dev_props_core12.maxDescriptorSetUpdateAfterBindSamplers); } // Uniform buffers if (sum_all_stages_update_after_bind[VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER] > phys_dev_props_core12.maxDescriptorSetUpdateAfterBindUniformBuffers) { skip |= LogError(device, "VUID-VkPipelineLayoutCreateInfo-pSetLayouts-03037", "vkCreatePipelineLayout(): sum of uniform buffer bindings among all stages (%d) exceeds device " "maxDescriptorSetUpdateAfterBindUniformBuffers limit (%d).", sum_all_stages_update_after_bind[VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER], phys_dev_props_core12.maxDescriptorSetUpdateAfterBindUniformBuffers); } // Dynamic uniform buffers if (sum_all_stages_update_after_bind[VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC] > phys_dev_props_core12.maxDescriptorSetUpdateAfterBindUniformBuffersDynamic) { skip |= LogError(device, "VUID-VkPipelineLayoutCreateInfo-pSetLayouts-03038", "vkCreatePipelineLayout(): sum of dynamic uniform buffer bindings among all stages (%d) exceeds device " "maxDescriptorSetUpdateAfterBindUniformBuffersDynamic limit (%d).", sum_all_stages_update_after_bind[VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC], phys_dev_props_core12.maxDescriptorSetUpdateAfterBindUniformBuffersDynamic); } // Storage buffers if (sum_all_stages_update_after_bind[VK_DESCRIPTOR_TYPE_STORAGE_BUFFER] > phys_dev_props_core12.maxDescriptorSetUpdateAfterBindStorageBuffers) { skip |= LogError(device, "VUID-VkPipelineLayoutCreateInfo-pSetLayouts-03039", "vkCreatePipelineLayout(): sum of storage buffer bindings among all stages (%d) exceeds device " "maxDescriptorSetUpdateAfterBindStorageBuffers limit (%d).", sum_all_stages_update_after_bind[VK_DESCRIPTOR_TYPE_STORAGE_BUFFER], phys_dev_props_core12.maxDescriptorSetUpdateAfterBindStorageBuffers); } // Dynamic storage buffers if (sum_all_stages_update_after_bind[VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC] > phys_dev_props_core12.maxDescriptorSetUpdateAfterBindStorageBuffersDynamic) { skip |= LogError(device, "VUID-VkPipelineLayoutCreateInfo-pSetLayouts-03040", "vkCreatePipelineLayout(): sum of dynamic storage buffer bindings among all stages (%d) exceeds device " "maxDescriptorSetUpdateAfterBindStorageBuffersDynamic limit (%d).", sum_all_stages_update_after_bind[VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC], phys_dev_props_core12.maxDescriptorSetUpdateAfterBindStorageBuffersDynamic); } // Sampled images sum = sum_all_stages_update_after_bind[VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE] + sum_all_stages_update_after_bind[VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER] + sum_all_stages_update_after_bind[VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER]; if (sum > phys_dev_props_core12.maxDescriptorSetUpdateAfterBindSampledImages) { skip |= LogError(device, "VUID-VkPipelineLayoutCreateInfo-pSetLayouts-03041", "vkCreatePipelineLayout(): sum of sampled image bindings among all stages (%d) exceeds device " "maxDescriptorSetUpdateAfterBindSampledImages limit (%d).", sum, phys_dev_props_core12.maxDescriptorSetUpdateAfterBindSampledImages); } // Storage images sum = sum_all_stages_update_after_bind[VK_DESCRIPTOR_TYPE_STORAGE_IMAGE] + sum_all_stages_update_after_bind[VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER]; if (sum > phys_dev_props_core12.maxDescriptorSetUpdateAfterBindStorageImages) { skip |= LogError(device, "VUID-VkPipelineLayoutCreateInfo-pSetLayouts-03042", "vkCreatePipelineLayout(): sum of storage image bindings among all stages (%d) exceeds device " "maxDescriptorSetUpdateAfterBindStorageImages limit (%d).", sum, phys_dev_props_core12.maxDescriptorSetUpdateAfterBindStorageImages); } // Input attachments if (sum_all_stages_update_after_bind[VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT] > phys_dev_props_core12.maxDescriptorSetUpdateAfterBindInputAttachments) { skip |= LogError(device, "VUID-VkPipelineLayoutCreateInfo-pSetLayouts-03043", "vkCreatePipelineLayout(): sum of input attachment bindings among all stages (%d) exceeds device " "maxDescriptorSetUpdateAfterBindInputAttachments limit (%d).", sum_all_stages_update_after_bind[VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT], phys_dev_props_core12.maxDescriptorSetUpdateAfterBindInputAttachments); } // Inline uniform blocks if (sum_all_stages_update_after_bind[VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT] > phys_dev_ext_props.inline_uniform_block_props.maxDescriptorSetUpdateAfterBindInlineUniformBlocks) { skip |= LogError(device, "VUID-VkPipelineLayoutCreateInfo-descriptorType-02217", "vkCreatePipelineLayout(): sum of inline uniform block bindings among all stages (%d) exceeds device " "maxDescriptorSetUpdateAfterBindInlineUniformBlocks limit (%d).", sum_all_stages_update_after_bind[VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT], phys_dev_ext_props.inline_uniform_block_props.maxDescriptorSetUpdateAfterBindInlineUniformBlocks); } } if (device_extensions.vk_ext_fragment_density_map2) { uint32_t sum_subsampled_samplers = 0; for (const auto &dsl : set_layouts) { // find the number of subsampled samplers across all stages // NOTE: this does not use the GetDescriptorSum patter because it needs the GetSamplerState method if ((dsl->GetCreateFlags() & VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT)) { continue; } for (uint32_t binding_idx = 0; binding_idx < dsl->GetBindingCount(); binding_idx++) { const VkDescriptorSetLayoutBinding *binding = dsl->GetDescriptorSetLayoutBindingPtrFromIndex(binding_idx); // Bindings with a descriptorCount of 0 are "reserved" and should be skipped if (binding->descriptorCount > 0) { if (((binding->descriptorType == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER) || (binding->descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER)) && (binding->pImmutableSamplers != nullptr)) { for (uint32_t sampler_idx = 0; sampler_idx < binding->descriptorCount; sampler_idx++) { const SAMPLER_STATE *state = GetSamplerState(binding->pImmutableSamplers[sampler_idx]); if (state->createInfo.flags & (VK_SAMPLER_CREATE_SUBSAMPLED_BIT_EXT | VK_SAMPLER_CREATE_SUBSAMPLED_COARSE_RECONSTRUCTION_BIT_EXT)) { sum_subsampled_samplers++; } } } } } } if (sum_subsampled_samplers > phys_dev_ext_props.fragment_density_map2_props.maxDescriptorSetSubsampledSamplers) { skip |= LogError(device, "VUID-VkPipelineLayoutCreateInfo-pImmutableSamplers-03566", "vkCreatePipelineLayout(): sum of sampler bindings with flags containing " "VK_SAMPLER_CREATE_SUBSAMPLED_BIT_EXT or " "VK_SAMPLER_CREATE_SUBSAMPLED_COARSE_RECONSTRUCTION_BIT_EXT among all stages(% d) " "exceeds device maxDescriptorSetSubsampledSamplers limit (%d).", sum_subsampled_samplers, phys_dev_ext_props.fragment_density_map2_props.maxDescriptorSetSubsampledSamplers); } } return skip; } bool CoreChecks::PreCallValidateResetDescriptorPool(VkDevice device, VkDescriptorPool descriptorPool, VkDescriptorPoolResetFlags flags) const { // Make sure sets being destroyed are not currently in-use if (disabled[object_in_use]) return false; bool skip = false; const DESCRIPTOR_POOL_STATE *pool = GetDescriptorPoolState(descriptorPool); if (pool != nullptr) { for (auto *ds : pool->sets) { if (ds && ds->InUse()) { skip |= LogError(descriptorPool, "VUID-vkResetDescriptorPool-descriptorPool-00313", "It is invalid to call vkResetDescriptorPool() with descriptor sets in use by a command buffer."); if (skip) break; } } } return skip; } // Ensure the pool contains enough descriptors and descriptor sets to satisfy // an allocation request. Fills common_data with the total number of descriptors of each type required, // as well as DescriptorSetLayout ptrs used for later update. bool CoreChecks::PreCallValidateAllocateDescriptorSets(VkDevice device, const VkDescriptorSetAllocateInfo *pAllocateInfo, VkDescriptorSet *pDescriptorSets, void *ads_state_data) const { StateTracker::PreCallValidateAllocateDescriptorSets(device, pAllocateInfo, pDescriptorSets, ads_state_data); cvdescriptorset::AllocateDescriptorSetsData *ads_state = reinterpret_cast<cvdescriptorset::AllocateDescriptorSetsData *>(ads_state_data); // All state checks for AllocateDescriptorSets is done in single function return ValidateAllocateDescriptorSets(pAllocateInfo, ads_state); } bool CoreChecks::PreCallValidateFreeDescriptorSets(VkDevice device, VkDescriptorPool descriptorPool, uint32_t count, const VkDescriptorSet *pDescriptorSets) const { // Make sure that no sets being destroyed are in-flight bool skip = false; // First make sure sets being destroyed are not currently in-use for (uint32_t i = 0; i < count; ++i) { if (pDescriptorSets[i] != VK_NULL_HANDLE) { skip |= ValidateIdleDescriptorSet(pDescriptorSets[i], "vkFreeDescriptorSets"); } } const DESCRIPTOR_POOL_STATE *pool_state = GetDescriptorPoolState(descriptorPool); if (pool_state && !(VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT & pool_state->createInfo.flags)) { // Can't Free from a NON_FREE pool skip |= LogError(descriptorPool, "VUID-vkFreeDescriptorSets-descriptorPool-00312", "It is invalid to call vkFreeDescriptorSets() with a pool created without setting " "VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT."); } return skip; } bool CoreChecks::PreCallValidateUpdateDescriptorSets(VkDevice device, uint32_t descriptorWriteCount, const VkWriteDescriptorSet *pDescriptorWrites, uint32_t descriptorCopyCount, const VkCopyDescriptorSet *pDescriptorCopies) const { // First thing to do is perform map look-ups. // NOTE : UpdateDescriptorSets is somewhat unique in that it's operating on a number of DescriptorSets // so we can't just do a single map look-up up-front, but do them individually in functions below // Now make call(s) that validate state, but don't perform state updates in this function // Note, here DescriptorSets is unique in that we don't yet have an instance. Using a helper function in the // namespace which will parse params and make calls into specific class instances return ValidateUpdateDescriptorSets(descriptorWriteCount, pDescriptorWrites, descriptorCopyCount, pDescriptorCopies, "vkUpdateDescriptorSets()"); } bool CoreChecks::PreCallValidateBeginCommandBuffer(VkCommandBuffer commandBuffer, const VkCommandBufferBeginInfo *pBeginInfo) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); if (!cb_state) return false; bool skip = false; if (cb_state->InUse()) { skip |= LogError(commandBuffer, "VUID-vkBeginCommandBuffer-commandBuffer-00049", "Calling vkBeginCommandBuffer() on active %s before it has completed. You must check " "command buffer fence before this call.", report_data->FormatHandle(commandBuffer).c_str()); } if (cb_state->createInfo.level == VK_COMMAND_BUFFER_LEVEL_PRIMARY) { // Primary Command Buffer const VkCommandBufferUsageFlags invalid_usage = (VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT | VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT); if ((pBeginInfo->flags & invalid_usage) == invalid_usage) { skip |= LogError(commandBuffer, "VUID-vkBeginCommandBuffer-commandBuffer-02840", "vkBeginCommandBuffer(): Primary %s can't have both VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT and " "VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT set.", report_data->FormatHandle(commandBuffer).c_str()); } } else { // Secondary Command Buffer const VkCommandBufferInheritanceInfo *info = pBeginInfo->pInheritanceInfo; if (!info) { skip |= LogError(commandBuffer, "VUID-vkBeginCommandBuffer-commandBuffer-00051", "vkBeginCommandBuffer(): Secondary %s must have inheritance info.", report_data->FormatHandle(commandBuffer).c_str()); } else { if (pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT) { assert(info->renderPass); const auto *framebuffer = GetFramebufferState(info->framebuffer); if (framebuffer) { if (framebuffer->createInfo.renderPass != info->renderPass) { const auto *render_pass = GetRenderPassState(info->renderPass); // renderPass that framebuffer was created with must be compatible with local renderPass skip |= ValidateRenderPassCompatibility("framebuffer", framebuffer->rp_state.get(), "command buffer", render_pass, "vkBeginCommandBuffer()", "VUID-VkCommandBufferBeginInfo-flags-00055"); } } } if ((info->occlusionQueryEnable == VK_FALSE || enabled_features.core.occlusionQueryPrecise == VK_FALSE) && (info->queryFlags & VK_QUERY_CONTROL_PRECISE_BIT)) { skip |= LogError(commandBuffer, "VUID-vkBeginCommandBuffer-commandBuffer-00052", "vkBeginCommandBuffer(): Secondary %s must not have VK_QUERY_CONTROL_PRECISE_BIT if " "occulusionQuery is disabled or the device does not support precise occlusion queries.", report_data->FormatHandle(commandBuffer).c_str()); } auto p_inherited_viewport_scissor_info = LvlFindInChain<VkCommandBufferInheritanceViewportScissorInfoNV>(info->pNext); if (p_inherited_viewport_scissor_info != nullptr && p_inherited_viewport_scissor_info->viewportScissor2D) { if (!enabled_features.inherited_viewport_scissor_features.inheritedViewportScissor2D) { skip |= LogError(commandBuffer, "VUID-VkCommandBufferInheritanceViewportScissorInfoNV-viewportScissor2D-04782", "vkBeginCommandBuffer(): inheritedViewportScissor2D feature not enabled."); } if (!(pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT)) { skip |= LogError(commandBuffer, "VUID-VkCommandBufferInheritanceViewportScissorInfoNV-viewportScissor2D-04786", "vkBeginCommandBuffer(): Secondary %s must be recorded with the" "VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT if viewportScissor2D is VK_TRUE.", report_data->FormatHandle(commandBuffer).c_str()); } if (p_inherited_viewport_scissor_info->viewportDepthCount == 0) { skip |= LogError(commandBuffer, "VUID-VkCommandBufferInheritanceViewportScissorInfoNV-viewportScissor2D-04784", "vkBeginCommandBuffer(): " "If viewportScissor2D is VK_TRUE, then viewportDepthCount must be greater than 0."); } } } if (info && info->renderPass != VK_NULL_HANDLE) { const auto *render_pass = GetRenderPassState(info->renderPass); if (render_pass) { if (info->subpass >= render_pass->createInfo.subpassCount) { skip |= LogError(commandBuffer, "VUID-VkCommandBufferBeginInfo-flags-00054", "vkBeginCommandBuffer(): Secondary %s must have a subpass index (%d) that is " "less than the number of subpasses (%d).", report_data->FormatHandle(commandBuffer).c_str(), info->subpass, render_pass->createInfo.subpassCount); } } } } if (CB_RECORDING == cb_state->state) { skip |= LogError(commandBuffer, "VUID-vkBeginCommandBuffer-commandBuffer-00049", "vkBeginCommandBuffer(): Cannot call Begin on %s in the RECORDING state. Must first call " "vkEndCommandBuffer().", report_data->FormatHandle(commandBuffer).c_str()); } else if (CB_RECORDED == cb_state->state || CB_INVALID_COMPLETE == cb_state->state) { VkCommandPool cmd_pool = cb_state->createInfo.commandPool; const auto *pool = cb_state->command_pool.get(); if (!(VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT & pool->createFlags)) { LogObjectList objlist(commandBuffer); objlist.add(cmd_pool); skip |= LogError(objlist, "VUID-vkBeginCommandBuffer-commandBuffer-00050", "Call to vkBeginCommandBuffer() on %s attempts to implicitly reset cmdBuffer created from " "%s that does NOT have the VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT bit set.", report_data->FormatHandle(commandBuffer).c_str(), report_data->FormatHandle(cmd_pool).c_str()); } } auto chained_device_group_struct = LvlFindInChain<VkDeviceGroupCommandBufferBeginInfo>(pBeginInfo->pNext); if (chained_device_group_struct) { skip |= ValidateDeviceMaskToPhysicalDeviceCount(chained_device_group_struct->deviceMask, commandBuffer, "VUID-VkDeviceGroupCommandBufferBeginInfo-deviceMask-00106"); skip |= ValidateDeviceMaskToZero(chained_device_group_struct->deviceMask, commandBuffer, "VUID-VkDeviceGroupCommandBufferBeginInfo-deviceMask-00107"); } return skip; } bool CoreChecks::PreCallValidateEndCommandBuffer(VkCommandBuffer commandBuffer) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); if (!cb_state) return false; bool skip = false; if ((VK_COMMAND_BUFFER_LEVEL_PRIMARY == cb_state->createInfo.level) || !(cb_state->beginInfo.flags & VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT)) { // This needs spec clarification to update valid usage, see comments in PR: // https://github.com/KhronosGroup/Vulkan-ValidationLayers/issues/165 skip |= InsideRenderPass(cb_state, "vkEndCommandBuffer()", "VUID-vkEndCommandBuffer-commandBuffer-00060"); } if (cb_state->state == CB_INVALID_COMPLETE || cb_state->state == CB_INVALID_INCOMPLETE) { skip |= ReportInvalidCommandBuffer(cb_state, "vkEndCommandBuffer()"); } else if (CB_RECORDING != cb_state->state) { skip |= LogError( commandBuffer, "VUID-vkEndCommandBuffer-commandBuffer-00059", "vkEndCommandBuffer(): Cannot call End on %s when not in the RECORDING state. Must first call vkBeginCommandBuffer().", report_data->FormatHandle(commandBuffer).c_str()); } for (const auto &query : cb_state->activeQueries) { skip |= LogError(commandBuffer, "VUID-vkEndCommandBuffer-commandBuffer-00061", "vkEndCommandBuffer(): Ending command buffer with in progress query: %s, query %d.", report_data->FormatHandle(query.pool).c_str(), query.query); } return skip; } bool CoreChecks::PreCallValidateResetCommandBuffer(VkCommandBuffer commandBuffer, VkCommandBufferResetFlags flags) const { bool skip = false; const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); if (!cb_state) return false; VkCommandPool cmd_pool = cb_state->createInfo.commandPool; const auto *pool = cb_state->command_pool.get(); if (!(VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT & pool->createFlags)) { LogObjectList objlist(commandBuffer); objlist.add(cmd_pool); skip |= LogError(objlist, "VUID-vkResetCommandBuffer-commandBuffer-00046", "vkResetCommandBuffer(): Attempt to reset %s created from %s that does NOT have the " "VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT bit set.", report_data->FormatHandle(commandBuffer).c_str(), report_data->FormatHandle(cmd_pool).c_str()); } skip |= CheckCommandBufferInFlight(cb_state, "reset", "VUID-vkResetCommandBuffer-commandBuffer-00045"); return skip; } static const char *GetPipelineTypeName(VkPipelineBindPoint pipelineBindPoint) { switch (pipelineBindPoint) { case VK_PIPELINE_BIND_POINT_GRAPHICS: return "graphics"; case VK_PIPELINE_BIND_POINT_COMPUTE: return "compute"; case VK_PIPELINE_BIND_POINT_RAY_TRACING_KHR: return "ray-tracing"; default: return "unknown"; } } bool CoreChecks::ValidateGraphicsPipelineBindPoint(const CMD_BUFFER_STATE *cb_state, const PIPELINE_STATE *pipeline_state) const { bool skip = false; const FRAMEBUFFER_STATE *fb_state = cb_state->activeFramebuffer.get(); if (fb_state) { auto subpass_desc = &pipeline_state->rp_state->createInfo.pSubpasses[pipeline_state->graphicsPipelineCI.subpass]; for (size_t i = 0; i < pipeline_state->attachments.size() && i < subpass_desc->colorAttachmentCount; i++) { const auto attachment = subpass_desc->pColorAttachments[i].attachment; if (attachment == VK_ATTACHMENT_UNUSED) continue; const auto *imageview_state = cb_state->GetActiveAttachmentImageViewState(attachment); if (!imageview_state) continue; const IMAGE_STATE *image_state = GetImageState(imageview_state->create_info.image); if (!image_state) continue; const VkFormat format = pipeline_state->rp_state->createInfo.pAttachments[attachment].format; const VkFormatFeatureFlags format_features = GetPotentialFormatFeatures(format); if (pipeline_state->graphicsPipelineCI.pRasterizationState && !pipeline_state->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable && pipeline_state->attachments[i].blendEnable && !(format_features & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BLEND_BIT)) { skip |= LogError(device, "VUID-VkGraphicsPipelineCreateInfo-blendEnable-04717", "vkCreateGraphicsPipelines(): pipeline.pColorBlendState.pAttachments[" PRINTF_SIZE_T_SPECIFIER "].blendEnable is VK_TRUE but format %s associated with this attached image (%s) does " "not support VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BLEND_BIT.", i, report_data->FormatHandle(image_state->image()).c_str(), string_VkFormat(format)); } } } if (cb_state->inheritedViewportDepths.size() != 0) { bool dyn_viewport = IsDynamic(pipeline_state, VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT_EXT) || IsDynamic(pipeline_state, VK_DYNAMIC_STATE_VIEWPORT); bool dyn_scissor = IsDynamic(pipeline_state, VK_DYNAMIC_STATE_SCISSOR_WITH_COUNT_EXT) || IsDynamic(pipeline_state, VK_DYNAMIC_STATE_SCISSOR); if (!dyn_viewport || !dyn_scissor) { skip |= LogError(device, "VUID-vkCmdBindPipeline-commandBuffer-04808", "Graphics pipeline incompatible with viewport/scissor inheritance."); } } return skip; } bool CoreChecks::PreCallValidateCmdBindPipeline(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint, VkPipeline pipeline) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); bool skip = false; skip |= ValidateCmd(cb_state, CMD_BINDPIPELINE, "vkCmdBindPipeline()"); static const std::map<VkPipelineBindPoint, std::string> bindpoint_errors = { std::make_pair(VK_PIPELINE_BIND_POINT_GRAPHICS, "VUID-vkCmdBindPipeline-pipelineBindPoint-00777"), std::make_pair(VK_PIPELINE_BIND_POINT_COMPUTE, "VUID-vkCmdBindPipeline-pipelineBindPoint-00778"), std::make_pair(VK_PIPELINE_BIND_POINT_RAY_TRACING_KHR, "VUID-vkCmdBindPipeline-pipelineBindPoint-02391")}; skip |= ValidatePipelineBindPoint(cb_state, pipelineBindPoint, "vkCmdBindPipeline()", bindpoint_errors); const auto *pipeline_state = GetPipelineState(pipeline); assert(pipeline_state); const auto &pipeline_state_bind_point = pipeline_state->getPipelineType(); if (pipelineBindPoint != pipeline_state_bind_point) { if (pipelineBindPoint == VK_PIPELINE_BIND_POINT_GRAPHICS) { skip |= LogError(cb_state->commandBuffer(), "VUID-vkCmdBindPipeline-pipelineBindPoint-00779", "Cannot bind a pipeline of type %s to the graphics pipeline bind point", GetPipelineTypeName(pipeline_state_bind_point)); } else if (pipelineBindPoint == VK_PIPELINE_BIND_POINT_COMPUTE) { skip |= LogError(cb_state->commandBuffer(), "VUID-vkCmdBindPipeline-pipelineBindPoint-00780", "Cannot bind a pipeline of type %s to the compute pipeline bind point", GetPipelineTypeName(pipeline_state_bind_point)); } else if (pipelineBindPoint == VK_PIPELINE_BIND_POINT_RAY_TRACING_KHR) { skip |= LogError(cb_state->commandBuffer(), "VUID-vkCmdBindPipeline-pipelineBindPoint-02392", "Cannot bind a pipeline of type %s to the ray-tracing pipeline bind point", GetPipelineTypeName(pipeline_state_bind_point)); } } else { if (pipelineBindPoint == VK_PIPELINE_BIND_POINT_GRAPHICS) { skip |= ValidateGraphicsPipelineBindPoint(cb_state, pipeline_state); if (cb_state->activeRenderPass && phys_dev_ext_props.provoking_vertex_props.provokingVertexModePerPipeline == VK_FALSE) { const auto lvl_bind_point = ConvertToLvlBindPoint(pipelineBindPoint); const auto &last_bound_it = cb_state->lastBound[lvl_bind_point]; if (last_bound_it.pipeline_state) { auto last_bound_provoking_vertex_state_ci = LvlFindInChain<VkPipelineRasterizationProvokingVertexStateCreateInfoEXT>( last_bound_it.pipeline_state->graphicsPipelineCI.pRasterizationState->pNext); auto current_provoking_vertex_state_ci = LvlFindInChain<VkPipelineRasterizationProvokingVertexStateCreateInfoEXT>( pipeline_state->graphicsPipelineCI.pRasterizationState->pNext); if (last_bound_provoking_vertex_state_ci && !current_provoking_vertex_state_ci) { skip |= LogError(pipeline, "VUID-vkCmdBindPipeline-pipelineBindPoint-04881", "Previous %s's provokingVertexMode is %s, but %s doesn't chain " "VkPipelineRasterizationProvokingVertexStateCreateInfoEXT.", report_data->FormatHandle(last_bound_it.pipeline_state->pipeline()).c_str(), string_VkProvokingVertexModeEXT(last_bound_provoking_vertex_state_ci->provokingVertexMode), report_data->FormatHandle(pipeline).c_str()); } else if (!last_bound_provoking_vertex_state_ci && current_provoking_vertex_state_ci) { skip |= LogError(pipeline, "VUID-vkCmdBindPipeline-pipelineBindPoint-04881", " %s's provokingVertexMode is %s, but previous %s doesn't chain " "VkPipelineRasterizationProvokingVertexStateCreateInfoEXT.", report_data->FormatHandle(pipeline).c_str(), string_VkProvokingVertexModeEXT(current_provoking_vertex_state_ci->provokingVertexMode), report_data->FormatHandle(last_bound_it.pipeline_state->pipeline()).c_str()); } else if (last_bound_provoking_vertex_state_ci && current_provoking_vertex_state_ci && last_bound_provoking_vertex_state_ci->provokingVertexMode != current_provoking_vertex_state_ci->provokingVertexMode) { skip |= LogError(pipeline, "VUID-vkCmdBindPipeline-pipelineBindPoint-04881", "%s's provokingVertexMode is %s, but previous %s's provokingVertexMode is %s.", report_data->FormatHandle(pipeline).c_str(), string_VkProvokingVertexModeEXT(current_provoking_vertex_state_ci->provokingVertexMode), report_data->FormatHandle(last_bound_it.pipeline_state->pipeline()).c_str(), string_VkProvokingVertexModeEXT(last_bound_provoking_vertex_state_ci->provokingVertexMode)); } } } } } return skip; } bool CoreChecks::ForbidInheritedViewportScissor(VkCommandBuffer commandBuffer, const CMD_BUFFER_STATE *cb_state, const char* vuid, const char *cmdName) const { bool skip = false; if (cb_state->inheritedViewportDepths.size() != 0) { skip |= LogError( commandBuffer, vuid, "%s: commandBuffer must not have VkCommandBufferInheritanceViewportScissorInfoNV::viewportScissor2D enabled.", cmdName); } return skip; } bool CoreChecks::PreCallValidateCmdSetViewport(VkCommandBuffer commandBuffer, uint32_t firstViewport, uint32_t viewportCount, const VkViewport *pViewports) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); bool skip = false; skip |= ValidateCmd(cb_state, CMD_SETVIEWPORT, "vkCmdSetViewport()"); skip |= ForbidInheritedViewportScissor(commandBuffer, cb_state, "VUID-vkCmdSetViewport-commandBuffer-04821", "vkCmdSetViewport"); return skip; } bool CoreChecks::PreCallValidateCmdSetScissor(VkCommandBuffer commandBuffer, uint32_t firstScissor, uint32_t scissorCount, const VkRect2D *pScissors) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); bool skip = false; skip |= ValidateCmd(cb_state, CMD_SETSCISSOR, "vkCmdSetScissor()"); skip |= ForbidInheritedViewportScissor(commandBuffer, cb_state, "VUID-vkCmdSetScissor-viewportScissor2D-04789", "vkCmdSetScissor"); return skip; } bool CoreChecks::PreCallValidateCmdSetExclusiveScissorNV(VkCommandBuffer commandBuffer, uint32_t firstExclusiveScissor, uint32_t exclusiveScissorCount, const VkRect2D *pExclusiveScissors) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); bool skip = false; skip |= ValidateCmd(cb_state, CMD_SETEXCLUSIVESCISSORNV, "vkCmdSetExclusiveScissorNV()"); if (!enabled_features.exclusive_scissor.exclusiveScissor) { skip |= LogError(commandBuffer, "VUID-vkCmdSetExclusiveScissorNV-None-02031", "vkCmdSetExclusiveScissorNV: The exclusiveScissor feature is disabled."); } return skip; } bool CoreChecks::PreCallValidateCmdBindShadingRateImageNV(VkCommandBuffer commandBuffer, VkImageView imageView, VkImageLayout imageLayout) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); bool skip = false; skip |= ValidateCmd(cb_state, CMD_BINDSHADINGRATEIMAGENV, "vkCmdBindShadingRateImageNV()"); if (!enabled_features.shading_rate_image.shadingRateImage) { skip |= LogError(commandBuffer, "VUID-vkCmdBindShadingRateImageNV-None-02058", "vkCmdBindShadingRateImageNV: The shadingRateImage feature is disabled."); } if (imageView != VK_NULL_HANDLE) { const auto view_state = GetImageViewState(imageView); auto &ivci = view_state->create_info; if (!view_state || (ivci.viewType != VK_IMAGE_VIEW_TYPE_2D && ivci.viewType != VK_IMAGE_VIEW_TYPE_2D_ARRAY)) { skip |= LogError(imageView, "VUID-vkCmdBindShadingRateImageNV-imageView-02059", "vkCmdBindShadingRateImageNV: If imageView is not VK_NULL_HANDLE, it must be a valid " "VkImageView handle of type VK_IMAGE_VIEW_TYPE_2D or VK_IMAGE_VIEW_TYPE_2D_ARRAY."); } if (view_state && ivci.format != VK_FORMAT_R8_UINT) { skip |= LogError( imageView, "VUID-vkCmdBindShadingRateImageNV-imageView-02060", "vkCmdBindShadingRateImageNV: If imageView is not VK_NULL_HANDLE, it must have a format of VK_FORMAT_R8_UINT."); } const VkImageCreateInfo *ici = view_state ? &GetImageState(view_state->create_info.image)->createInfo : nullptr; if (ici && !(ici->usage & VK_IMAGE_USAGE_SHADING_RATE_IMAGE_BIT_NV)) { skip |= LogError(imageView, "VUID-vkCmdBindShadingRateImageNV-imageView-02061", "vkCmdBindShadingRateImageNV: If imageView is not VK_NULL_HANDLE, the image must have been " "created with VK_IMAGE_USAGE_SHADING_RATE_IMAGE_BIT_NV set."); } if (view_state) { const auto image_state = GetImageState(view_state->create_info.image); bool hit_error = false; // XXX TODO: While the VUID says "each subresource", only the base mip level is // actually used. Since we don't have an existing convenience function to iterate // over all mip levels, just don't bother with non-base levels. const VkImageSubresourceRange &range = view_state->normalized_subresource_range; VkImageSubresourceLayers subresource = {range.aspectMask, range.baseMipLevel, range.baseArrayLayer, range.layerCount}; if (image_state) { skip |= VerifyImageLayout(cb_state, image_state, subresource, imageLayout, VK_IMAGE_LAYOUT_SHADING_RATE_OPTIMAL_NV, "vkCmdCopyImage()", "VUID-vkCmdBindShadingRateImageNV-imageLayout-02063", "VUID-vkCmdBindShadingRateImageNV-imageView-02062", &hit_error); } } } return skip; } bool CoreChecks::PreCallValidateCmdSetViewportShadingRatePaletteNV(VkCommandBuffer commandBuffer, uint32_t firstViewport, uint32_t viewportCount, const VkShadingRatePaletteNV *pShadingRatePalettes) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); bool skip = false; skip |= ValidateCmd(cb_state, CMD_SETVIEWPORTSHADINGRATEPALETTENV, "vkCmdSetViewportShadingRatePaletteNV()"); if (!enabled_features.shading_rate_image.shadingRateImage) { skip |= LogError(commandBuffer, "VUID-vkCmdSetViewportShadingRatePaletteNV-None-02064", "vkCmdSetViewportShadingRatePaletteNV: The shadingRateImage feature is disabled."); } for (uint32_t i = 0; i < viewportCount; ++i) { auto *palette = &pShadingRatePalettes[i]; if (palette->shadingRatePaletteEntryCount == 0 || palette->shadingRatePaletteEntryCount > phys_dev_ext_props.shading_rate_image_props.shadingRatePaletteSize) { skip |= LogError( commandBuffer, "VUID-VkShadingRatePaletteNV-shadingRatePaletteEntryCount-02071", "vkCmdSetViewportShadingRatePaletteNV: shadingRatePaletteEntryCount must be between 1 and shadingRatePaletteSize."); } } return skip; } bool CoreChecks::ValidateGeometryTrianglesNV(const VkGeometryTrianglesNV &triangles, const char *func_name) const { bool skip = false; const BUFFER_STATE *vb_state = GetBufferState(triangles.vertexData); if (vb_state != nullptr && vb_state->createInfo.size <= triangles.vertexOffset) { skip |= LogError(device, "VUID-VkGeometryTrianglesNV-vertexOffset-02428", "%s", func_name); } const BUFFER_STATE *ib_state = GetBufferState(triangles.indexData); if (ib_state != nullptr && ib_state->createInfo.size <= triangles.indexOffset) { skip |= LogError(device, "VUID-VkGeometryTrianglesNV-indexOffset-02431", "%s", func_name); } const BUFFER_STATE *td_state = GetBufferState(triangles.transformData); if (td_state != nullptr && td_state->createInfo.size <= triangles.transformOffset) { skip |= LogError(device, "VUID-VkGeometryTrianglesNV-transformOffset-02437", "%s", func_name); } return skip; } bool CoreChecks::ValidateGeometryAABBNV(const VkGeometryAABBNV &aabbs, const char *func_name) const { bool skip = false; const BUFFER_STATE *aabb_state = GetBufferState(aabbs.aabbData); if (aabb_state != nullptr && aabb_state->createInfo.size > 0 && aabb_state->createInfo.size <= aabbs.offset) { skip |= LogError(device, "VUID-VkGeometryAABBNV-offset-02439", "%s", func_name); } return skip; } bool CoreChecks::ValidateGeometryNV(const VkGeometryNV &geometry, const char *func_name) const { bool skip = false; if (geometry.geometryType == VK_GEOMETRY_TYPE_TRIANGLES_NV) { skip = ValidateGeometryTrianglesNV(geometry.geometry.triangles, func_name); } else if (geometry.geometryType == VK_GEOMETRY_TYPE_AABBS_NV) { skip = ValidateGeometryAABBNV(geometry.geometry.aabbs, func_name); } return skip; } bool CoreChecks::PreCallValidateCreateAccelerationStructureNV(VkDevice device, const VkAccelerationStructureCreateInfoNV *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkAccelerationStructureNV *pAccelerationStructure) const { bool skip = false; if (pCreateInfo != nullptr && pCreateInfo->info.type == VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_NV) { for (uint32_t i = 0; i < pCreateInfo->info.geometryCount; i++) { skip |= ValidateGeometryNV(pCreateInfo->info.pGeometries[i], "vkCreateAccelerationStructureNV():"); } } return skip; } bool CoreChecks::PreCallValidateCreateAccelerationStructureKHR(VkDevice device, const VkAccelerationStructureCreateInfoKHR *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkAccelerationStructureKHR *pAccelerationStructure) const { bool skip = false; if (pCreateInfo) { const BUFFER_STATE *buffer_state = GetBufferState(pCreateInfo->buffer); if (buffer_state) { if (!(buffer_state->createInfo.usage & VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR)) { skip |= LogError(device, "VUID-VkAccelerationStructureCreateInfoKHR-buffer-03614", "VkAccelerationStructureCreateInfoKHR(): buffer must have been created with a usage value containing " "VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR."); } if (buffer_state->createInfo.flags & VK_BUFFER_CREATE_SPARSE_RESIDENCY_BIT) { skip |= LogError(device, "VUID-VkAccelerationStructureCreateInfoKHR-buffer-03615", "VkAccelerationStructureCreateInfoKHR(): buffer must not have been created with " "VK_BUFFER_CREATE_SPARSE_RESIDENCY_BIT."); } if (pCreateInfo->offset + pCreateInfo->size > buffer_state->createInfo.size) { skip |= LogError( device, "VUID-VkAccelerationStructureCreateInfoKHR-offset-03616", "VkAccelerationStructureCreateInfoKHR(): The sum of offset and size must be less than the size of buffer."); } } } return skip; } bool CoreChecks::ValidateBindAccelerationStructureMemory(VkDevice device, const VkBindAccelerationStructureMemoryInfoNV &info) const { bool skip = false; const ACCELERATION_STRUCTURE_STATE *as_state = GetAccelerationStructureStateNV(info.accelerationStructure); if (!as_state) { return skip; } if (!as_state->GetBoundMemory().empty()) { skip |= LogError(info.accelerationStructure, "VUID-VkBindAccelerationStructureMemoryInfoNV-accelerationStructure-03620", "vkBindAccelerationStructureMemoryNV(): accelerationStructure must not already be backed by a memory object."); } // Validate bound memory range information const auto mem_info = GetDevMemState(info.memory); if (mem_info) { skip |= ValidateInsertAccelerationStructureMemoryRange(info.accelerationStructure, mem_info, info.memoryOffset, "vkBindAccelerationStructureMemoryNV()"); skip |= ValidateMemoryTypes(mem_info, as_state->memory_requirements.memoryRequirements.memoryTypeBits, "vkBindAccelerationStructureMemoryNV()", "VUID-VkBindAccelerationStructureMemoryInfoNV-memory-03622"); } // Validate memory requirements alignment if (SafeModulo(info.memoryOffset, as_state->memory_requirements.memoryRequirements.alignment) != 0) { skip |= LogError(info.accelerationStructure, "VUID-VkBindAccelerationStructureMemoryInfoNV-memoryOffset-03623", "vkBindAccelerationStructureMemoryNV(): memoryOffset 0x%" PRIxLEAST64 " must be an integer multiple of the alignment 0x%" PRIxLEAST64 " member of the VkMemoryRequirements structure returned from " "a call to vkGetAccelerationStructureMemoryRequirementsNV with accelerationStructure and type of " "VK_ACCELERATION_STRUCTURE_MEMORY_REQUIREMENTS_TYPE_OBJECT_NV", info.memoryOffset, as_state->memory_requirements.memoryRequirements.alignment); } if (mem_info) { // Validate memory requirements size if (as_state->memory_requirements.memoryRequirements.size > (mem_info->alloc_info.allocationSize - info.memoryOffset)) { skip |= LogError(info.accelerationStructure, "VUID-VkBindAccelerationStructureMemoryInfoNV-size-03624", "vkBindAccelerationStructureMemoryNV(): The size 0x%" PRIxLEAST64 " member of the VkMemoryRequirements structure returned from a call to " "vkGetAccelerationStructureMemoryRequirementsNV with accelerationStructure and type of " "VK_ACCELERATION_STRUCTURE_MEMORY_REQUIREMENTS_TYPE_OBJECT_NV must be less than or equal to the size " "of memory minus memoryOffset 0x%" PRIxLEAST64 ".", as_state->memory_requirements.memoryRequirements.size, mem_info->alloc_info.allocationSize - info.memoryOffset); } } return skip; } bool CoreChecks::PreCallValidateBindAccelerationStructureMemoryNV(VkDevice device, uint32_t bindInfoCount, const VkBindAccelerationStructureMemoryInfoNV *pBindInfos) const { bool skip = false; for (uint32_t i = 0; i < bindInfoCount; i++) { skip |= ValidateBindAccelerationStructureMemory(device, pBindInfos[i]); } return skip; } bool CoreChecks::PreCallValidateGetAccelerationStructureHandleNV(VkDevice device, VkAccelerationStructureNV accelerationStructure, size_t dataSize, void *pData) const { bool skip = false; const ACCELERATION_STRUCTURE_STATE *as_state = GetAccelerationStructureStateNV(accelerationStructure); if (as_state != nullptr) { // TODO: update the fake VUID below once the real one is generated. skip = ValidateMemoryIsBoundToAccelerationStructure( as_state, "vkGetAccelerationStructureHandleNV", "UNASSIGNED-vkGetAccelerationStructureHandleNV-accelerationStructure-XXXX"); } return skip; } bool CoreChecks::PreCallValidateCmdBuildAccelerationStructuresKHR( VkCommandBuffer commandBuffer, uint32_t infoCount, const VkAccelerationStructureBuildGeometryInfoKHR *pInfos, const VkAccelerationStructureBuildRangeInfoKHR *const *ppBuildRangeInfos) const { bool skip = false; const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); skip |= ValidateCmd(cb_state, CMD_BUILDACCELERATIONSTRUCTURESKHR, "vkCmdBuildAccelerationStructuresKHR()"); if (pInfos != NULL) { for (uint32_t info_index = 0; info_index < infoCount; ++info_index) { const ACCELERATION_STRUCTURE_STATE_KHR *src_as_state = GetAccelerationStructureStateKHR(pInfos[info_index].srcAccelerationStructure); const ACCELERATION_STRUCTURE_STATE_KHR *dst_as_state = GetAccelerationStructureStateKHR(pInfos[info_index].dstAccelerationStructure); if (pInfos[info_index].mode == VK_BUILD_ACCELERATION_STRUCTURE_MODE_UPDATE_KHR) { if (src_as_state == nullptr || !src_as_state->built || !(src_as_state->build_info_khr.flags & VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_UPDATE_BIT_KHR)) { skip |= LogError(device, "VUID-vkCmdBuildAccelerationStructuresKHR-pInfos-03667", "vkCmdBuildAccelerationStructuresKHR(): For each element of pInfos, if its mode member is " "VK_BUILD_ACCELERATION_STRUCTURE_MODE_UPDATE_KHR, its srcAccelerationStructure member must " "have been built before with VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_UPDATE_BIT_KHR set in " "VkAccelerationStructureBuildGeometryInfoKHR::flags."); } if (pInfos[info_index].geometryCount != src_as_state->build_info_khr.geometryCount) { skip |= LogError(device, "VUID-vkCmdBuildAccelerationStructuresKHR-pInfos-03758", "vkCmdBuildAccelerationStructuresKHR(): For each element of pInfos, if its mode member is " "VK_BUILD_ACCELERATION_STRUCTURE_MODE_UPDATE_KHR," " its geometryCount member must have the same value which was specified when " "srcAccelerationStructure was last built."); } if (pInfos[info_index].flags != src_as_state->build_info_khr.flags) { skip |= LogError(device, "VUID-vkCmdBuildAccelerationStructuresKHR-pInfos-03759", "vkCmdBuildAccelerationStructuresKHR(): For each element of pInfos, if its mode member is" " VK_BUILD_ACCELERATION_STRUCTURE_MODE_UPDATE_KHR, its flags member must have the same value which" " was specified when srcAccelerationStructure was last built."); } if (pInfos[info_index].type != src_as_state->build_info_khr.type) { skip |= LogError(device, "VUID-vkCmdBuildAccelerationStructuresKHR-pInfos-03760", "vkCmdBuildAccelerationStructuresKHR(): For each element of pInfos, if its mode member is" " VK_BUILD_ACCELERATION_STRUCTURE_MODE_UPDATE_KHR, its type member must have the same value which" " was specified when srcAccelerationStructure was last built."); } } if (pInfos[info_index].type == VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR) { if (!dst_as_state || (dst_as_state && dst_as_state->create_infoKHR.type != VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR && dst_as_state->create_infoKHR.type != VK_ACCELERATION_STRUCTURE_TYPE_GENERIC_KHR)) { skip |= LogError(device, "VUID-vkCmdBuildAccelerationStructuresKHR-pInfos-03700", "vkCmdBuildAccelerationStructuresKHR(): For each element of pInfos, if its type member is " "VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR, its dstAccelerationStructure member must have " "been created with a value of VkAccelerationStructureCreateInfoKHR::type equal to either " "VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR or VK_ACCELERATION_STRUCTURE_TYPE_GENERIC_KHR."); } } if (pInfos[info_index].type == VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_KHR) { if (!dst_as_state || (dst_as_state && dst_as_state->create_infoKHR.type != VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_KHR && dst_as_state->create_infoKHR.type != VK_ACCELERATION_STRUCTURE_TYPE_GENERIC_KHR)) { skip |= LogError(device, "VUID-vkCmdBuildAccelerationStructuresKHR-pInfos-03699", "vkCmdBuildAccelerationStructuresKHR(): For each element of pInfos, if its type member is " "VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_KHR, its dstAccelerationStructure member must have been " "created with a value of VkAccelerationStructureCreateInfoKHR::type equal to either " "VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_KHR or VK_ACCELERATION_STRUCTURE_TYPE_GENERIC_KHR."); } } skip |= ValidateAccelerationBuffers(info_index, pInfos[info_index], "vkCmdBuildAccelerationStructuresKHR"); } } return skip; } bool CoreChecks::ValidateAccelerationBuffers(uint32_t info_index, const VkAccelerationStructureBuildGeometryInfoKHR &info, const char *func_name) const { bool skip = false; const auto geometry_count = info.geometryCount; const auto *p_geometries = info.pGeometries; const auto *const *const pp_geometries = info.ppGeometries; auto buffer_check = [this, info_index, func_name](uint32_t gi, const VkDeviceOrHostAddressConstKHR address, const char *field) -> bool { const auto itr = buffer_address_map_.find(address.deviceAddress); if (itr != buffer_address_map_.cend() && !(itr->second->createInfo.usage & VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR)) { LogObjectList objlist(device); objlist.add(itr->second->Handle()); return LogError(objlist, "VUID-vkCmdBuildAccelerationStructuresKHR-geometry-03673", "%s(): The buffer associated with pInfos[%" PRIu32 "].pGeometries[%" PRIu32 "].%s was not created with VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR.", func_name, info_index, gi, field); } return false; }; // Parameter validation has already checked VUID-VkAccelerationStructureBuildGeometryInfoKHR-pGeometries-03788 // !(pGeometries && ppGeometries) std::function<const VkAccelerationStructureGeometryKHR &(uint32_t)> geom_accessor; if (p_geometries) { geom_accessor = [p_geometries](uint32_t i) -> const VkAccelerationStructureGeometryKHR & { return p_geometries[i]; }; } else if (pp_geometries) { geom_accessor = [pp_geometries](uint32_t i) -> const VkAccelerationStructureGeometryKHR & { // pp_geometries[i] is assumed to be a valid pointer return *pp_geometries[i]; }; } if (geom_accessor) { for (uint32_t geom_index = 0; geom_index < geometry_count; ++geom_index) { const auto &geom_data = geom_accessor(geom_index); switch (geom_data.geometryType) { case VK_GEOMETRY_TYPE_TRIANGLES_KHR: // == VK_GEOMETRY_TYPE_TRIANGLES_NV skip |= buffer_check(geom_index, geom_data.geometry.triangles.vertexData, "geometry.triangles.vertexData"); skip |= buffer_check(geom_index, geom_data.geometry.triangles.indexData, "geometry.triangles.indexData"); skip |= buffer_check(geom_index, geom_data.geometry.triangles.transformData, "geometry.triangles.transformData"); break; case VK_GEOMETRY_TYPE_INSTANCES_KHR: skip |= buffer_check(geom_index, geom_data.geometry.instances.data, "geometry.instances.data"); break; case VK_GEOMETRY_TYPE_AABBS_KHR: // == VK_GEOMETRY_TYPE_AABBS_NV skip |= buffer_check(geom_index, geom_data.geometry.aabbs.data, "geometry.aabbs.data"); break; default: // no-op break; } } } return skip; } bool CoreChecks::PreCallValidateBuildAccelerationStructuresKHR( VkDevice device, VkDeferredOperationKHR deferredOperation, uint32_t infoCount, const VkAccelerationStructureBuildGeometryInfoKHR *pInfos, const VkAccelerationStructureBuildRangeInfoKHR *const *ppBuildRangeInfos) const { bool skip = false; for (uint32_t i = 0; i < infoCount; ++i) { const ACCELERATION_STRUCTURE_STATE_KHR *src_as_state = GetAccelerationStructureStateKHR(pInfos[i].srcAccelerationStructure); const ACCELERATION_STRUCTURE_STATE_KHR *dst_as_state = GetAccelerationStructureStateKHR(pInfos[i].dstAccelerationStructure); if (pInfos[i].mode == VK_BUILD_ACCELERATION_STRUCTURE_MODE_UPDATE_KHR) { if (src_as_state == nullptr || !src_as_state->built || !(src_as_state->build_info_khr.flags & VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_UPDATE_BIT_KHR)) { skip |= LogError(device, "VUID-vkBuildAccelerationStructuresKHR-pInfos-03667", "vkBuildAccelerationStructuresKHR(): For each element of pInfos, if its mode member is " "VK_BUILD_ACCELERATION_STRUCTURE_MODE_UPDATE_KHR, its srcAccelerationStructure member must have " "been built before with VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_UPDATE_BIT_KHR set in " "VkAccelerationStructureBuildGeometryInfoKHR::flags."); } if (pInfos[i].geometryCount != src_as_state->build_info_khr.geometryCount) { skip |= LogError(device, "VUID-vkBuildAccelerationStructuresKHR-pInfos-03758", "vkBuildAccelerationStructuresKHR(): For each element of pInfos, if its mode member is " "VK_BUILD_ACCELERATION_STRUCTURE_MODE_UPDATE_KHR," " its geometryCount member must have the same value which was specified when " "srcAccelerationStructure was last built."); } if (pInfos[i].flags != src_as_state->build_info_khr.flags) { skip |= LogError(device, "VUID-vkBuildAccelerationStructuresKHR-pInfos-03759", "vkBuildAccelerationStructuresKHR(): For each element of pInfos, if its mode member is" " VK_BUILD_ACCELERATION_STRUCTURE_MODE_UPDATE_KHR, its flags member must have the same value which" " was specified when srcAccelerationStructure was last built."); } if (pInfos[i].type != src_as_state->build_info_khr.type) { skip |= LogError(device, "VUID-vkBuildAccelerationStructuresKHR-pInfos-03760", "vkBuildAccelerationStructuresKHR(): For each element of pInfos, if its mode member is" " VK_BUILD_ACCELERATION_STRUCTURE_MODE_UPDATE_KHR, its type member must have the same value which" " was specified when srcAccelerationStructure was last built."); } } if (pInfos[i].type == VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR) { if (!dst_as_state || (dst_as_state && dst_as_state->create_infoKHR.type != VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR && dst_as_state->create_infoKHR.type != VK_ACCELERATION_STRUCTURE_TYPE_GENERIC_KHR)) { skip |= LogError(device, "VUID-vkBuildAccelerationStructuresKHR-pInfos-03700", "vkBuildAccelerationStructuresKHR(): For each element of pInfos, if its type member is " "VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR, its dstAccelerationStructure member must have " "been created with a value of VkAccelerationStructureCreateInfoKHR::type equal to either " "VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR or VK_ACCELERATION_STRUCTURE_TYPE_GENERIC_KHR."); } } if (pInfos[i].type == VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_KHR) { if (!dst_as_state || (dst_as_state && dst_as_state->create_infoKHR.type != VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_KHR && dst_as_state->create_infoKHR.type != VK_ACCELERATION_STRUCTURE_TYPE_GENERIC_KHR)) { skip |= LogError(device, "VUID-vkBuildAccelerationStructuresKHR-pInfos-03699", "vkBuildAccelerationStructuresKHR(): For each element of pInfos, if its type member is " "VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_KHR, its dstAccelerationStructure member must have been " "created with a value of VkAccelerationStructureCreateInfoKHR::type equal to either " "VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_KHR or VK_ACCELERATION_STRUCTURE_TYPE_GENERIC_KHR."); } } } return skip; } bool CoreChecks::PreCallValidateCmdBuildAccelerationStructureNV(VkCommandBuffer commandBuffer, const VkAccelerationStructureInfoNV *pInfo, VkBuffer instanceData, VkDeviceSize instanceOffset, VkBool32 update, VkAccelerationStructureNV dst, VkAccelerationStructureNV src, VkBuffer scratch, VkDeviceSize scratchOffset) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); bool skip = false; skip |= ValidateCmd(cb_state, CMD_BUILDACCELERATIONSTRUCTURENV, "vkCmdBuildAccelerationStructureNV()"); if (pInfo != nullptr && pInfo->type == VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_NV) { for (uint32_t i = 0; i < pInfo->geometryCount; i++) { skip |= ValidateGeometryNV(pInfo->pGeometries[i], "vkCmdBuildAccelerationStructureNV():"); } } if (pInfo != nullptr && pInfo->geometryCount > phys_dev_ext_props.ray_tracing_propsNV.maxGeometryCount) { skip |= LogError(commandBuffer, "VUID-vkCmdBuildAccelerationStructureNV-geometryCount-02241", "vkCmdBuildAccelerationStructureNV(): geometryCount [%d] must be less than or equal to " "VkPhysicalDeviceRayTracingPropertiesNV::maxGeometryCount.", pInfo->geometryCount); } const ACCELERATION_STRUCTURE_STATE *dst_as_state = GetAccelerationStructureStateNV(dst); const ACCELERATION_STRUCTURE_STATE *src_as_state = GetAccelerationStructureStateNV(src); const BUFFER_STATE *scratch_buffer_state = GetBufferState(scratch); if (dst_as_state != nullptr && pInfo != nullptr) { if (dst_as_state->create_infoNV.info.type != pInfo->type) { skip |= LogError(commandBuffer, "VUID-vkCmdBuildAccelerationStructureNV-dst-02488", "vkCmdBuildAccelerationStructureNV(): create info VkAccelerationStructureInfoNV::type" "[%s] must be identical to build info VkAccelerationStructureInfoNV::type [%s].", string_VkAccelerationStructureTypeNV(dst_as_state->create_infoNV.info.type), string_VkAccelerationStructureTypeNV(pInfo->type)); } if (dst_as_state->create_infoNV.info.flags != pInfo->flags) { skip |= LogError(commandBuffer, "VUID-vkCmdBuildAccelerationStructureNV-dst-02488", "vkCmdBuildAccelerationStructureNV(): create info VkAccelerationStructureInfoNV::flags" "[0x%X] must be identical to build info VkAccelerationStructureInfoNV::flags [0x%X].", dst_as_state->create_infoNV.info.flags, pInfo->flags); } if (dst_as_state->create_infoNV.info.instanceCount < pInfo->instanceCount) { skip |= LogError(commandBuffer, "VUID-vkCmdBuildAccelerationStructureNV-dst-02488", "vkCmdBuildAccelerationStructureNV(): create info VkAccelerationStructureInfoNV::instanceCount " "[%d] must be greater than or equal to build info VkAccelerationStructureInfoNV::instanceCount [%d].", dst_as_state->create_infoNV.info.instanceCount, pInfo->instanceCount); } if (dst_as_state->create_infoNV.info.geometryCount < pInfo->geometryCount) { skip |= LogError(commandBuffer, "VUID-vkCmdBuildAccelerationStructureNV-dst-02488", "vkCmdBuildAccelerationStructureNV(): create info VkAccelerationStructureInfoNV::geometryCount" "[%d] must be greater than or equal to build info VkAccelerationStructureInfoNV::geometryCount [%d].", dst_as_state->create_infoNV.info.geometryCount, pInfo->geometryCount); } else { for (uint32_t i = 0; i < pInfo->geometryCount; i++) { const VkGeometryDataNV &create_geometry_data = dst_as_state->create_infoNV.info.pGeometries[i].geometry; const VkGeometryDataNV &build_geometry_data = pInfo->pGeometries[i].geometry; if (create_geometry_data.triangles.vertexCount < build_geometry_data.triangles.vertexCount) { skip |= LogError( commandBuffer, "VUID-vkCmdBuildAccelerationStructureNV-dst-02488", "vkCmdBuildAccelerationStructureNV(): create info pGeometries[%d].geometry.triangles.vertexCount [%d]" "must be greater than or equal to build info pGeometries[%d].geometry.triangles.vertexCount [%d].", i, create_geometry_data.triangles.vertexCount, i, build_geometry_data.triangles.vertexCount); break; } if (create_geometry_data.triangles.indexCount < build_geometry_data.triangles.indexCount) { skip |= LogError( commandBuffer, "VUID-vkCmdBuildAccelerationStructureNV-dst-02488", "vkCmdBuildAccelerationStructureNV(): create info pGeometries[%d].geometry.triangles.indexCount [%d]" "must be greater than or equal to build info pGeometries[%d].geometry.triangles.indexCount [%d].", i, create_geometry_data.triangles.indexCount, i, build_geometry_data.triangles.indexCount); break; } if (create_geometry_data.aabbs.numAABBs < build_geometry_data.aabbs.numAABBs) { skip |= LogError(commandBuffer, "VUID-vkCmdBuildAccelerationStructureNV-dst-02488", "vkCmdBuildAccelerationStructureNV(): create info pGeometries[%d].geometry.aabbs.numAABBs [%d]" "must be greater than or equal to build info pGeometries[%d].geometry.aabbs.numAABBs [%d].", i, create_geometry_data.aabbs.numAABBs, i, build_geometry_data.aabbs.numAABBs); break; } } } } if (dst_as_state != nullptr) { skip |= ValidateMemoryIsBoundToAccelerationStructure( dst_as_state, "vkCmdBuildAccelerationStructureNV()", "UNASSIGNED-CoreValidation-DrawState-InvalidCommandBuffer-VkAccelerationStructureNV"); } if (update == VK_TRUE) { if (src == VK_NULL_HANDLE) { skip |= LogError(commandBuffer, "VUID-vkCmdBuildAccelerationStructureNV-update-02489", "vkCmdBuildAccelerationStructureNV(): If update is VK_TRUE, src must not be VK_NULL_HANDLE."); } else { if (src_as_state == nullptr || !src_as_state->built || !(src_as_state->build_info.flags & VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_UPDATE_BIT_NV)) { skip |= LogError(commandBuffer, "VUID-vkCmdBuildAccelerationStructureNV-update-02490", "vkCmdBuildAccelerationStructureNV(): If update is VK_TRUE, src must have been built before " "with VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_UPDATE_BIT_NV set in " "VkAccelerationStructureInfoNV::flags."); } } if (dst_as_state != nullptr && !dst_as_state->update_scratch_memory_requirements_checked) { skip |= LogWarning(dst, kVUID_Core_CmdBuildAccelNV_NoUpdateMemReqQuery, "vkCmdBuildAccelerationStructureNV(): Updating %s but vkGetAccelerationStructureMemoryRequirementsNV() " "has not been called for update scratch memory.", report_data->FormatHandle(dst_as_state->acceleration_structure()).c_str()); // Use requirements fetched at create time } if (scratch_buffer_state != nullptr && dst_as_state != nullptr && dst_as_state->update_scratch_memory_requirements.memoryRequirements.size > (scratch_buffer_state->createInfo.size - scratchOffset)) { skip |= LogError(commandBuffer, "VUID-vkCmdBuildAccelerationStructureNV-update-02492", "vkCmdBuildAccelerationStructureNV(): If update is VK_TRUE, The size member of the " "VkMemoryRequirements structure returned from a call to " "vkGetAccelerationStructureMemoryRequirementsNV with " "VkAccelerationStructureMemoryRequirementsInfoNV::accelerationStructure set to dst and " "VkAccelerationStructureMemoryRequirementsInfoNV::type set to " "VK_ACCELERATION_STRUCTURE_MEMORY_REQUIREMENTS_TYPE_UPDATE_SCRATCH_NV must be less than " "or equal to the size of scratch minus scratchOffset"); } } else { if (dst_as_state != nullptr && !dst_as_state->build_scratch_memory_requirements_checked) { skip |= LogWarning(dst, kVUID_Core_CmdBuildAccelNV_NoScratchMemReqQuery, "vkCmdBuildAccelerationStructureNV(): Assigning scratch buffer to %s but " "vkGetAccelerationStructureMemoryRequirementsNV() has not been called for scratch memory.", report_data->FormatHandle(dst_as_state->acceleration_structure()).c_str()); // Use requirements fetched at create time } if (scratch_buffer_state != nullptr && dst_as_state != nullptr && dst_as_state->build_scratch_memory_requirements.memoryRequirements.size > (scratch_buffer_state->createInfo.size - scratchOffset)) { skip |= LogError(commandBuffer, "VUID-vkCmdBuildAccelerationStructureNV-update-02491", "vkCmdBuildAccelerationStructureNV(): If update is VK_FALSE, The size member of the " "VkMemoryRequirements structure returned from a call to " "vkGetAccelerationStructureMemoryRequirementsNV with " "VkAccelerationStructureMemoryRequirementsInfoNV::accelerationStructure set to dst and " "VkAccelerationStructureMemoryRequirementsInfoNV::type set to " "VK_ACCELERATION_STRUCTURE_MEMORY_REQUIREMENTS_TYPE_BUILD_SCRATCH_NV must be less than " "or equal to the size of scratch minus scratchOffset"); } } if (instanceData != VK_NULL_HANDLE) { const auto buffer_state = GetBufferState(instanceData); if (buffer_state != nullptr) { skip |= ValidateBufferUsageFlags(buffer_state, VK_BUFFER_USAGE_RAY_TRACING_BIT_NV, true, "VUID-VkAccelerationStructureInfoNV-instanceData-02782", "vkCmdBuildAccelerationStructureNV()", "VK_BUFFER_USAGE_RAY_TRACING_BIT_NV"); } } if (scratch_buffer_state != nullptr) { skip |= ValidateBufferUsageFlags(scratch_buffer_state, VK_BUFFER_USAGE_RAY_TRACING_BIT_NV, true, "VUID-VkAccelerationStructureInfoNV-scratch-02781", "vkCmdBuildAccelerationStructureNV()", "VK_BUFFER_USAGE_RAY_TRACING_BIT_NV"); } return skip; } bool CoreChecks::PreCallValidateCmdCopyAccelerationStructureNV(VkCommandBuffer commandBuffer, VkAccelerationStructureNV dst, VkAccelerationStructureNV src, VkCopyAccelerationStructureModeNV mode) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); bool skip = false; skip |= ValidateCmd(cb_state, CMD_COPYACCELERATIONSTRUCTURENV, "vkCmdCopyAccelerationStructureNV()"); const ACCELERATION_STRUCTURE_STATE *dst_as_state = GetAccelerationStructureStateNV(dst); const ACCELERATION_STRUCTURE_STATE *src_as_state = GetAccelerationStructureStateNV(src); if (dst_as_state != nullptr) { skip |= ValidateMemoryIsBoundToAccelerationStructure( dst_as_state, "vkCmdBuildAccelerationStructureNV()", "UNASSIGNED-CoreValidation-DrawState-InvalidCommandBuffer-VkAccelerationStructureNV"); } if (mode == VK_COPY_ACCELERATION_STRUCTURE_MODE_COMPACT_NV) { if (src_as_state != nullptr && (!src_as_state->built || !(src_as_state->build_info.flags & VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_COMPACTION_BIT_NV))) { skip |= LogError(commandBuffer, "VUID-vkCmdCopyAccelerationStructureNV-src-03411", "vkCmdCopyAccelerationStructureNV(): src must have been built with " "VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_COMPACTION_BIT_NV if mode is " "VK_COPY_ACCELERATION_STRUCTURE_MODE_COMPACT_NV."); } } if (!(mode == VK_COPY_ACCELERATION_STRUCTURE_MODE_COMPACT_NV || mode == VK_COPY_ACCELERATION_STRUCTURE_MODE_CLONE_KHR)) { skip |= LogError(commandBuffer, "VUID-vkCmdCopyAccelerationStructureNV-mode-03410", "vkCmdCopyAccelerationStructureNV():mode must be VK_COPY_ACCELERATION_STRUCTURE_MODE_COMPACT_KHR" "or VK_COPY_ACCELERATION_STRUCTURE_MODE_CLONE_KHR."); } return skip; } bool CoreChecks::PreCallValidateDestroyAccelerationStructureNV(VkDevice device, VkAccelerationStructureNV accelerationStructure, const VkAllocationCallbacks *pAllocator) const { const ACCELERATION_STRUCTURE_STATE *as_state = GetAccelerationStructureStateNV(accelerationStructure); bool skip = false; if (as_state) { skip |= ValidateObjectNotInUse(as_state, "vkDestroyAccelerationStructureNV", "VUID-vkDestroyAccelerationStructureKHR-accelerationStructure-02442"); } return skip; } bool CoreChecks::PreCallValidateDestroyAccelerationStructureKHR(VkDevice device, VkAccelerationStructureKHR accelerationStructure, const VkAllocationCallbacks *pAllocator) const { const ACCELERATION_STRUCTURE_STATE_KHR *as_state = GetAccelerationStructureStateKHR(accelerationStructure); bool skip = false; if (as_state) { skip |= ValidateObjectNotInUse(as_state, "vkDestroyAccelerationStructureKHR", "VUID-vkDestroyAccelerationStructureKHR-accelerationStructure-02442"); } if (pAllocator && !as_state->allocator) { skip |= LogError(device, "VUID-vkDestroyAccelerationStructureKHR-accelerationStructure-02444", "vkDestroyAccelerationStructureKH:If no VkAllocationCallbacks were provided when accelerationStructure" "was created, pAllocator must be NULL."); } return skip; } bool CoreChecks::PreCallValidateCmdSetViewportWScalingNV(VkCommandBuffer commandBuffer, uint32_t firstViewport, uint32_t viewportCount, const VkViewportWScalingNV *pViewportWScalings) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); bool skip = false; skip |= ValidateCmd(cb_state, CMD_SETVIEWPORTWSCALINGNV, "vkCmdSetViewportWScalingNV()"); return skip; } bool CoreChecks::PreCallValidateCmdSetLineWidth(VkCommandBuffer commandBuffer, float lineWidth) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); bool skip = false; skip |= ValidateCmd(cb_state, CMD_SETLINEWIDTH, "vkCmdSetLineWidth()"); return skip; } bool CoreChecks::PreCallValidateCmdSetLineStippleEXT(VkCommandBuffer commandBuffer, uint32_t lineStippleFactor, uint16_t lineStipplePattern) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); bool skip = false; skip |= ValidateCmd(cb_state, CMD_SETLINESTIPPLEEXT, "vkCmdSetLineStippleEXT()"); return skip; } bool CoreChecks::PreCallValidateCmdSetDepthBias(VkCommandBuffer commandBuffer, float depthBiasConstantFactor, float depthBiasClamp, float depthBiasSlopeFactor) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); bool skip = false; skip |= ValidateCmd(cb_state, CMD_SETDEPTHBIAS, "vkCmdSetDepthBias()"); if ((depthBiasClamp != 0.0) && (!enabled_features.core.depthBiasClamp)) { skip |= LogError(commandBuffer, "VUID-vkCmdSetDepthBias-depthBiasClamp-00790", "vkCmdSetDepthBias(): the depthBiasClamp device feature is disabled: the depthBiasClamp parameter must " "be set to 0.0."); } return skip; } bool CoreChecks::PreCallValidateCmdSetBlendConstants(VkCommandBuffer commandBuffer, const float blendConstants[4]) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); bool skip = false; skip |= ValidateCmd(cb_state, CMD_SETBLENDCONSTANTS, "vkCmdSetBlendConstants()"); return skip; } bool CoreChecks::PreCallValidateCmdSetDepthBounds(VkCommandBuffer commandBuffer, float minDepthBounds, float maxDepthBounds) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); bool skip = false; skip |= ValidateCmd(cb_state, CMD_SETDEPTHBOUNDS, "vkCmdSetDepthBounds()"); // The extension was not created with a feature bit whichs prevents displaying the 2 variations of the VUIDs if (!device_extensions.vk_ext_depth_range_unrestricted) { if (!(minDepthBounds >= 0.0) || !(minDepthBounds <= 1.0)) { // Also VUID-vkCmdSetDepthBounds-minDepthBounds-00600 skip |= LogError(commandBuffer, "VUID-vkCmdSetDepthBounds-minDepthBounds-02508", "vkCmdSetDepthBounds(): VK_EXT_depth_range_unrestricted extension is not enabled and minDepthBounds " "(=%f) is not within the [0.0, 1.0] range.", minDepthBounds); } if (!(maxDepthBounds >= 0.0) || !(maxDepthBounds <= 1.0)) { // Also VUID-vkCmdSetDepthBounds-maxDepthBounds-00601 skip |= LogError(commandBuffer, "VUID-vkCmdSetDepthBounds-maxDepthBounds-02509", "vkCmdSetDepthBounds(): VK_EXT_depth_range_unrestricted extension is not enabled and maxDepthBounds " "(=%f) is not within the [0.0, 1.0] range.", maxDepthBounds); } } return skip; } bool CoreChecks::PreCallValidateCmdSetStencilCompareMask(VkCommandBuffer commandBuffer, VkStencilFaceFlags faceMask, uint32_t compareMask) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); bool skip = false; skip |= ValidateCmd(cb_state, CMD_SETSTENCILCOMPAREMASK, "vkCmdSetStencilCompareMask()"); return skip; } bool CoreChecks::PreCallValidateCmdSetStencilWriteMask(VkCommandBuffer commandBuffer, VkStencilFaceFlags faceMask, uint32_t writeMask) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); bool skip = false; skip |= ValidateCmd(cb_state, CMD_SETSTENCILWRITEMASK, "vkCmdSetStencilWriteMask()"); return skip; } bool CoreChecks::PreCallValidateCmdSetStencilReference(VkCommandBuffer commandBuffer, VkStencilFaceFlags faceMask, uint32_t reference) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); bool skip = false; skip |= ValidateCmd(cb_state, CMD_SETSTENCILREFERENCE, "vkCmdSetStencilReference()"); return skip; } bool CoreChecks::PreCallValidateCmdBindDescriptorSets(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint, VkPipelineLayout layout, uint32_t firstSet, uint32_t setCount, const VkDescriptorSet *pDescriptorSets, uint32_t dynamicOffsetCount, const uint32_t *pDynamicOffsets) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); bool skip = false; skip |= ValidateCmd(cb_state, CMD_BINDDESCRIPTORSETS, "vkCmdBindDescriptorSets()"); // Track total count of dynamic descriptor types to make sure we have an offset for each one uint32_t total_dynamic_descriptors = 0; string error_string = ""; const auto *pipeline_layout = GetPipelineLayout(layout); for (uint32_t set_idx = 0; set_idx < setCount; set_idx++) { const cvdescriptorset::DescriptorSet *descriptor_set = GetSetNode(pDescriptorSets[set_idx]); if (descriptor_set) { // Verify that set being bound is compatible with overlapping setLayout of pipelineLayout if (!VerifySetLayoutCompatibility(report_data, descriptor_set, pipeline_layout, set_idx + firstSet, error_string)) { skip |= LogError(pDescriptorSets[set_idx], "VUID-vkCmdBindDescriptorSets-pDescriptorSets-00358", "vkCmdBindDescriptorSets(): descriptorSet #%u being bound is not compatible with overlapping " "descriptorSetLayout at index %u of " "%s due to: %s.", set_idx, set_idx + firstSet, report_data->FormatHandle(layout).c_str(), error_string.c_str()); } auto set_dynamic_descriptor_count = descriptor_set->GetDynamicDescriptorCount(); if (set_dynamic_descriptor_count) { // First make sure we won't overstep bounds of pDynamicOffsets array if ((total_dynamic_descriptors + set_dynamic_descriptor_count) > dynamicOffsetCount) { // Test/report this here, such that we don't run past the end of pDynamicOffsets in the else clause skip |= LogError(pDescriptorSets[set_idx], "VUID-vkCmdBindDescriptorSets-dynamicOffsetCount-00359", "vkCmdBindDescriptorSets(): descriptorSet #%u (%s) requires %u dynamicOffsets, but only %u " "dynamicOffsets are left in " "pDynamicOffsets array. There must be one dynamic offset for each dynamic descriptor being bound.", set_idx, report_data->FormatHandle(pDescriptorSets[set_idx]).c_str(), descriptor_set->GetDynamicDescriptorCount(), (dynamicOffsetCount - total_dynamic_descriptors)); // Set the number found to the maximum to prevent duplicate messages, or subsquent descriptor sets from // testing against the "short tail" we're skipping below. total_dynamic_descriptors = dynamicOffsetCount; } else { // Validate dynamic offsets and Dynamic Offset Minimums // offset for all sets (pDynamicOffsets) uint32_t cur_dyn_offset = total_dynamic_descriptors; // offset into this descriptor set uint32_t set_dyn_offset = 0; const auto &dsl = descriptor_set->GetLayout(); const auto binding_count = dsl->GetBindingCount(); const auto &limits = phys_dev_props.limits; for (uint32_t i = 0; i < binding_count; i++) { const auto *binding = dsl->GetDescriptorSetLayoutBindingPtrFromIndex(i); // skip checking binding if not needed if (cvdescriptorset::IsDynamicDescriptor(binding->descriptorType) == false) { continue; } // If a descriptor set has only binding 0 and 2 the binding_index will be 0 and 2 const uint32_t binding_index = binding->binding; const uint32_t descriptorCount = binding->descriptorCount; // Need to loop through each descriptor count inside the binding // if descriptorCount is zero the binding with a dynamic descriptor type does not count for (uint32_t j = 0; j < descriptorCount; j++) { const uint32_t offset = pDynamicOffsets[cur_dyn_offset]; if (offset == 0) { // offset of zero is equivalent of not having the dynamic offset cur_dyn_offset++; set_dyn_offset++; continue; } // Validate alignment with limit if ((binding->descriptorType == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC) && (SafeModulo(offset, limits.minUniformBufferOffsetAlignment) != 0)) { skip |= LogError(commandBuffer, "VUID-vkCmdBindDescriptorSets-pDynamicOffsets-01971", "vkCmdBindDescriptorSets(): pDynamicOffsets[%u] is %u, but must be a multiple of " "device limit minUniformBufferOffsetAlignment 0x%" PRIxLEAST64 ".", cur_dyn_offset, offset, limits.minUniformBufferOffsetAlignment); } if ((binding->descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC) && (SafeModulo(offset, limits.minStorageBufferOffsetAlignment) != 0)) { skip |= LogError(commandBuffer, "VUID-vkCmdBindDescriptorSets-pDynamicOffsets-01972", "vkCmdBindDescriptorSets(): pDynamicOffsets[%u] is %u, but must be a multiple of " "device limit minStorageBufferOffsetAlignment 0x%" PRIxLEAST64 ".", cur_dyn_offset, offset, limits.minStorageBufferOffsetAlignment); } auto *descriptor = descriptor_set->GetDescriptorFromDynamicOffsetIndex(set_dyn_offset); assert(descriptor != nullptr); // Currently only GeneralBuffer are dynamic and need to be checked if (descriptor->GetClass() == cvdescriptorset::DescriptorClass::GeneralBuffer) { const auto *buffer_descriptor = static_cast<const cvdescriptorset::BufferDescriptor *>(descriptor); const VkDeviceSize bound_range = buffer_descriptor->GetRange(); const VkDeviceSize bound_offset = buffer_descriptor->GetOffset(); //NOTE: null / invalid buffers may show up here, errors are raised elsewhere for this. const BUFFER_STATE *buffer_state = buffer_descriptor->GetBufferState(); // Validate offset didn't go over buffer if ((bound_range == VK_WHOLE_SIZE) && (offset > 0)) { LogObjectList objlist(commandBuffer); objlist.add(pDescriptorSets[set_idx]); objlist.add(buffer_descriptor->GetBuffer()); skip |= LogError(objlist, "VUID-vkCmdBindDescriptorSets-pDescriptorSets-01979", "vkCmdBindDescriptorSets(): pDynamicOffsets[%u] is 0x%x, but must be zero since " "the buffer descriptor's range is VK_WHOLE_SIZE in descriptorSet #%u binding #%u " "descriptor[%u].", cur_dyn_offset, offset, set_idx, binding_index, j); } else if (buffer_state != nullptr && (bound_range != VK_WHOLE_SIZE) && ((offset + bound_range + bound_offset) > buffer_state->createInfo.size)) { LogObjectList objlist(commandBuffer); objlist.add(pDescriptorSets[set_idx]); objlist.add(buffer_descriptor->GetBuffer()); skip |= LogError(objlist, "VUID-vkCmdBindDescriptorSets-pDescriptorSets-01979", "vkCmdBindDescriptorSets(): pDynamicOffsets[%u] is 0x%x which when added to the " "buffer descriptor's range (0x%" PRIxLEAST64 ") is greater than the size of the buffer (0x%" PRIxLEAST64 ") in descriptorSet #%u binding #%u descriptor[%u].", cur_dyn_offset, offset, bound_range, buffer_state->createInfo.size, set_idx, binding_index, j); } } cur_dyn_offset++; set_dyn_offset++; } // descriptorCount loop } // bindingCount loop // Keep running total of dynamic descriptor count to verify at the end total_dynamic_descriptors += set_dynamic_descriptor_count; } } } else { skip |= LogError(pDescriptorSets[set_idx], "VUID-vkCmdBindDescriptorSets-pDescriptorSets-parameter", "vkCmdBindDescriptorSets(): Attempt to bind %s that doesn't exist!", report_data->FormatHandle(pDescriptorSets[set_idx]).c_str()); } } // dynamicOffsetCount must equal the total number of dynamic descriptors in the sets being bound if (total_dynamic_descriptors != dynamicOffsetCount) { skip |= LogError(cb_state->commandBuffer(), "VUID-vkCmdBindDescriptorSets-dynamicOffsetCount-00359", "vkCmdBindDescriptorSets(): Attempting to bind %u descriptorSets with %u dynamic descriptors, but " "dynamicOffsetCount is %u. It should " "exactly match the number of dynamic descriptors.", setCount, total_dynamic_descriptors, dynamicOffsetCount); } // firstSet and descriptorSetCount sum must be less than setLayoutCount if ((firstSet + setCount) > static_cast<uint32_t>(pipeline_layout->set_layouts.size())) { skip |= LogError(cb_state->commandBuffer(), "VUID-vkCmdBindDescriptorSets-firstSet-00360", "vkCmdBindDescriptorSets(): Sum of firstSet (%u) and descriptorSetCount (%u) is greater than " "VkPipelineLayoutCreateInfo::setLayoutCount " "(%zu) when pipeline layout was created", firstSet, setCount, pipeline_layout->set_layouts.size()); } static const std::map<VkPipelineBindPoint, std::string> bindpoint_errors = { std::make_pair(VK_PIPELINE_BIND_POINT_GRAPHICS, "VUID-vkCmdBindDescriptorSets-pipelineBindPoint-00361"), std::make_pair(VK_PIPELINE_BIND_POINT_COMPUTE, "VUID-vkCmdBindDescriptorSets-pipelineBindPoint-00361"), std::make_pair(VK_PIPELINE_BIND_POINT_RAY_TRACING_NV, "VUID-vkCmdBindDescriptorSets-pipelineBindPoint-00361")}; skip |= ValidatePipelineBindPoint(cb_state, pipelineBindPoint, "vkCmdBindPipeline()", bindpoint_errors); return skip; } // Validates that the supplied bind point is supported for the command buffer (vis. the command pool) // Takes array of error codes as some of the VUID's (e.g. vkCmdBindPipeline) are written per bindpoint // TODO add vkCmdBindPipeline bind_point validation using this call. bool CoreChecks::ValidatePipelineBindPoint(const CMD_BUFFER_STATE *cb_state, VkPipelineBindPoint bind_point, const char *func_name, const std::map<VkPipelineBindPoint, std::string> &bind_errors) const { bool skip = false; auto pool = cb_state->command_pool.get(); if (pool) { // The loss of a pool in a recording cmd is reported in DestroyCommandPool static const std::map<VkPipelineBindPoint, VkQueueFlags> flag_mask = { std::make_pair(VK_PIPELINE_BIND_POINT_GRAPHICS, static_cast<VkQueueFlags>(VK_QUEUE_GRAPHICS_BIT)), std::make_pair(VK_PIPELINE_BIND_POINT_COMPUTE, static_cast<VkQueueFlags>(VK_QUEUE_COMPUTE_BIT)), std::make_pair(VK_PIPELINE_BIND_POINT_RAY_TRACING_KHR, static_cast<VkQueueFlags>(VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT)), }; const auto &qfp = GetPhysicalDeviceState()->queue_family_properties[pool->queueFamilyIndex]; if (0 == (qfp.queueFlags & flag_mask.at(bind_point))) { const std::string &error = bind_errors.at(bind_point); LogObjectList objlist(cb_state->commandBuffer()); objlist.add(cb_state->createInfo.commandPool); skip |= LogError(objlist, error, "%s: %s was allocated from %s that does not support bindpoint %s.", func_name, report_data->FormatHandle(cb_state->commandBuffer()).c_str(), report_data->FormatHandle(cb_state->createInfo.commandPool).c_str(), string_VkPipelineBindPoint(bind_point)); } } return skip; } bool CoreChecks::PreCallValidateCmdPushDescriptorSetKHR(VkCommandBuffer commandBuffer, VkPipelineBindPoint pipelineBindPoint, VkPipelineLayout layout, uint32_t set, uint32_t descriptorWriteCount, const VkWriteDescriptorSet *pDescriptorWrites) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); const char *func_name = "vkCmdPushDescriptorSetKHR()"; bool skip = false; skip |= ValidateCmd(cb_state, CMD_PUSHDESCRIPTORSETKHR, func_name); static const std::map<VkPipelineBindPoint, std::string> bind_errors = { std::make_pair(VK_PIPELINE_BIND_POINT_GRAPHICS, "VUID-vkCmdPushDescriptorSetKHR-pipelineBindPoint-00363"), std::make_pair(VK_PIPELINE_BIND_POINT_COMPUTE, "VUID-vkCmdPushDescriptorSetKHR-pipelineBindPoint-00363"), std::make_pair(VK_PIPELINE_BIND_POINT_RAY_TRACING_KHR, "VUID-vkCmdPushDescriptorSetKHR-pipelineBindPoint-00363")}; skip |= ValidatePipelineBindPoint(cb_state, pipelineBindPoint, func_name, bind_errors); const auto layout_data = GetPipelineLayout(layout); // Validate the set index points to a push descriptor set and is in range if (layout_data) { const auto &set_layouts = layout_data->set_layouts; if (set < set_layouts.size()) { const auto &dsl = set_layouts[set]; if (dsl) { if (!dsl->IsPushDescriptor()) { skip = LogError(layout, "VUID-vkCmdPushDescriptorSetKHR-set-00365", "%s: Set index %" PRIu32 " does not match push descriptor set layout index for %s.", func_name, set, report_data->FormatHandle(layout).c_str()); } else { // Create an empty proxy in order to use the existing descriptor set update validation // TODO move the validation (like this) that doesn't need descriptor set state to the DSL object so we // don't have to do this. cvdescriptorset::DescriptorSet proxy_ds(VK_NULL_HANDLE, nullptr, dsl, 0, this); skip |= ValidatePushDescriptorsUpdate(&proxy_ds, descriptorWriteCount, pDescriptorWrites, func_name); } } } else { skip = LogError(layout, "VUID-vkCmdPushDescriptorSetKHR-set-00364", "%s: Set index %" PRIu32 " is outside of range for %s (set < %" PRIu32 ").", func_name, set, report_data->FormatHandle(layout).c_str(), static_cast<uint32_t>(set_layouts.size())); } } return skip; } bool CoreChecks::PreCallValidateCmdBindIndexBuffer(VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, VkIndexType indexType) const { const auto buffer_state = GetBufferState(buffer); const auto cb_node = GetCBState(commandBuffer); assert(buffer_state); assert(cb_node); bool skip = ValidateBufferUsageFlags(buffer_state, VK_BUFFER_USAGE_INDEX_BUFFER_BIT, true, "VUID-vkCmdBindIndexBuffer-buffer-00433", "vkCmdBindIndexBuffer()", "VK_BUFFER_USAGE_INDEX_BUFFER_BIT"); skip |= ValidateCmd(cb_node, CMD_BINDINDEXBUFFER, "vkCmdBindIndexBuffer()"); skip |= ValidateMemoryIsBoundToBuffer(buffer_state, "vkCmdBindIndexBuffer()", "VUID-vkCmdBindIndexBuffer-buffer-00434"); const auto offset_align = GetIndexAlignment(indexType); if (offset % offset_align) { skip |= LogError(commandBuffer, "VUID-vkCmdBindIndexBuffer-offset-00432", "vkCmdBindIndexBuffer() offset (0x%" PRIxLEAST64 ") does not fall on alignment (%s) boundary.", offset, string_VkIndexType(indexType)); } if (offset >= buffer_state->requirements.size) { skip |= LogError(commandBuffer, "VUID-vkCmdBindIndexBuffer-offset-00431", "vkCmdBindIndexBuffer() offset (0x%" PRIxLEAST64 ") is not less than the size (0x%" PRIxLEAST64 ") of buffer (%s).", offset, buffer_state->requirements.size, report_data->FormatHandle(buffer_state->buffer()).c_str()); } return skip; } bool CoreChecks::PreCallValidateCmdBindVertexBuffers(VkCommandBuffer commandBuffer, uint32_t firstBinding, uint32_t bindingCount, const VkBuffer *pBuffers, const VkDeviceSize *pOffsets) const { const auto cb_state = GetCBState(commandBuffer); assert(cb_state); bool skip = false; skip |= ValidateCmd(cb_state, CMD_BINDVERTEXBUFFERS, "vkCmdBindVertexBuffers()"); for (uint32_t i = 0; i < bindingCount; ++i) { const auto buffer_state = GetBufferState(pBuffers[i]); if (buffer_state) { skip |= ValidateBufferUsageFlags(buffer_state, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, true, "VUID-vkCmdBindVertexBuffers-pBuffers-00627", "vkCmdBindVertexBuffers()", "VK_BUFFER_USAGE_VERTEX_BUFFER_BIT"); skip |= ValidateMemoryIsBoundToBuffer(buffer_state, "vkCmdBindVertexBuffers()", "VUID-vkCmdBindVertexBuffers-pBuffers-00628"); if (pOffsets[i] >= buffer_state->createInfo.size) { skip |= LogError(buffer_state->buffer(), "VUID-vkCmdBindVertexBuffers-pOffsets-00626", "vkCmdBindVertexBuffers() offset (0x%" PRIxLEAST64 ") is beyond the end of the buffer.", pOffsets[i]); } } } return skip; } // Validate that an image's sampleCount matches the requirement for a specific API call bool CoreChecks::ValidateImageSampleCount(const IMAGE_STATE *image_state, VkSampleCountFlagBits sample_count, const char *location, const std::string &msgCode) const { bool skip = false; if (image_state->createInfo.samples != sample_count) { skip = LogError(image_state->image(), msgCode, "%s for %s was created with a sample count of %s but must be %s.", location, report_data->FormatHandle(image_state->image()).c_str(), string_VkSampleCountFlagBits(image_state->createInfo.samples), string_VkSampleCountFlagBits(sample_count)); } return skip; } bool CoreChecks::PreCallValidateCmdUpdateBuffer(VkCommandBuffer commandBuffer, VkBuffer dstBuffer, VkDeviceSize dstOffset, VkDeviceSize dataSize, const void *pData) const { const auto cb_state = GetCBState(commandBuffer); assert(cb_state); const auto dst_buffer_state = GetBufferState(dstBuffer); assert(dst_buffer_state); bool skip = false; skip |= ValidateMemoryIsBoundToBuffer(dst_buffer_state, "vkCmdUpdateBuffer()", "VUID-vkCmdUpdateBuffer-dstBuffer-00035"); // Validate that DST buffer has correct usage flags set skip |= ValidateBufferUsageFlags(dst_buffer_state, VK_BUFFER_USAGE_TRANSFER_DST_BIT, true, "VUID-vkCmdUpdateBuffer-dstBuffer-00034", "vkCmdUpdateBuffer()", "VK_BUFFER_USAGE_TRANSFER_DST_BIT"); skip |= ValidateCmd(cb_state, CMD_UPDATEBUFFER, "vkCmdUpdateBuffer()"); skip |= ValidateProtectedBuffer(cb_state, dst_buffer_state, "vkCmdUpdateBuffer()", "VUID-vkCmdUpdateBuffer-commandBuffer-01813"); skip |= ValidateUnprotectedBuffer(cb_state, dst_buffer_state, "vkCmdUpdateBuffer()", "VUID-vkCmdUpdateBuffer-commandBuffer-01814"); if (dstOffset >= dst_buffer_state->createInfo.size) { skip |= LogError( commandBuffer, "VUID-vkCmdUpdateBuffer-dstOffset-00032", "vkCmdUpdateBuffer() dstOffset (0x%" PRIxLEAST64 ") is not less than the size (0x%" PRIxLEAST64 ") of buffer (%s).", dstOffset, dst_buffer_state->createInfo.size, report_data->FormatHandle(dst_buffer_state->buffer()).c_str()); } else if (dataSize > dst_buffer_state->createInfo.size - dstOffset) { skip |= LogError(commandBuffer, "VUID-vkCmdUpdateBuffer-dataSize-00033", "vkCmdUpdateBuffer() dataSize (0x%" PRIxLEAST64 ") is not less than the size (0x%" PRIxLEAST64 ") of buffer (%s) minus dstOffset (0x%" PRIxLEAST64 ").", dataSize, dst_buffer_state->createInfo.size, report_data->FormatHandle(dst_buffer_state->buffer()).c_str(), dstOffset); } return skip; } bool CoreChecks::PreCallValidateCmdSetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); bool skip = false; skip |= ValidateCmd(cb_state, CMD_SETEVENT, "vkCmdSetEvent()"); Location loc(Func::vkCmdSetEvent, Field::stageMask); LogObjectList objects(commandBuffer); skip |= ValidatePipelineStage(objects, loc, cb_state->GetQueueFlags(), stageMask); skip |= ValidateStageMaskHost(loc, stageMask); return skip; } bool CoreChecks::PreCallValidateCmdSetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event, const VkDependencyInfoKHR *pDependencyInfo) const { const char *func = "vkCmdSetEvent2KHR()"; LogObjectList objects(commandBuffer); objects.add(event); const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); bool skip = false; skip |= ValidateCmd(cb_state, CMD_SETEVENT, func); Location loc(Func::vkCmdSetEvent2KHR, Field::pDependencyInfo); if (pDependencyInfo->dependencyFlags != 0) { skip |= LogError(objects, "VUID-vkCmdSetEvent2KHR-dependencyFlags-03825", "%s (%s) must be 0", loc.dot(Field::dependencyFlags).Message().c_str(), string_VkDependencyFlags(pDependencyInfo->dependencyFlags).c_str()); } skip |= ValidateDependencyInfo(objects, loc, cb_state, pDependencyInfo); return skip; } bool CoreChecks::PreCallValidateCmdResetEvent(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); LogObjectList objects(commandBuffer); Location loc(Func::vkCmdResetEvent, Field::stageMask); bool skip = false; skip |= ValidateCmd(cb_state, CMD_RESETEVENT, "vkCmdResetEvent()"); skip |= ValidatePipelineStage(objects, loc, cb_state->GetQueueFlags(), stageMask); skip |= ValidateStageMaskHost(loc, stageMask); return skip; } bool CoreChecks::PreCallValidateCmdResetEvent2KHR(VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags2KHR stageMask) const { const char *func = "vkCmdResetEvent2KHR()"; const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); LogObjectList objects(commandBuffer); Location loc(Func::vkCmdResetEvent2KHR, Field::stageMask); bool skip = false; skip |= ValidateCmd(cb_state, CMD_RESETEVENT, func); skip |= ValidatePipelineStage(objects, loc, cb_state->GetQueueFlags(), stageMask); skip |= ValidateStageMaskHost(loc, stageMask); return skip; } static bool HasNonFramebufferStagePipelineStageFlags(VkPipelineStageFlags2KHR inflags) { return (inflags & ~(VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT)) != 0; } // transient helper struct for checking parts of VUID 02285 struct RenderPassDepState { using Location = core_error::Location; using Func = core_error::Func; using Struct = core_error::Struct; using Field = core_error::Field; const CoreChecks *core; const std::string func_name; const std::string vuid; uint32_t active_subpass; const VkRenderPass rp_handle; const VkPipelineStageFlags2KHR disabled_features; const std::vector<uint32_t> &self_dependencies; const safe_VkSubpassDependency2 *dependencies; RenderPassDepState(const CoreChecks *c, const std::string &f, const std::string &v, uint32_t subpass, const VkRenderPass handle, const DeviceFeatures &features, const std::vector<uint32_t> &self_deps, const safe_VkSubpassDependency2 *deps) : core(c), func_name(f), vuid(v), active_subpass(subpass), rp_handle(handle), disabled_features(sync_utils::DisabledPipelineStages(features)), self_dependencies(self_deps), dependencies(deps) {} VkMemoryBarrier2KHR GetSubPassDepBarrier(const safe_VkSubpassDependency2 &dep) { VkMemoryBarrier2KHR result; const auto *barrier = LvlFindInChain<VkMemoryBarrier2KHR>(dep.pNext); if (barrier) { result = *barrier; } else { result.srcStageMask = dep.srcStageMask; result.dstStageMask = dep.dstStageMask; result.srcAccessMask = dep.srcAccessMask; result.dstAccessMask = dep.dstAccessMask; } return result; } bool ValidateStage(const Location &loc, VkPipelineStageFlags2KHR src_stage_mask, VkPipelineStageFlags2KHR dst_stage_mask) { // Look for matching mask in any self-dependency bool match = false; for (const auto self_dep_index : self_dependencies) { const auto sub_dep = GetSubPassDepBarrier(dependencies[self_dep_index]); auto sub_src_stage_mask = sync_utils::ExpandPipelineStages(sub_dep.srcStageMask, sync_utils::kAllQueueTypes, disabled_features); auto sub_dst_stage_mask = sync_utils::ExpandPipelineStages(sub_dep.dstStageMask, sync_utils::kAllQueueTypes, disabled_features); match = ((sub_src_stage_mask == VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) || (src_stage_mask == (sub_src_stage_mask & src_stage_mask))) && ((sub_dst_stage_mask == VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) || (dst_stage_mask == (sub_dst_stage_mask & dst_stage_mask))); if (match) break; } if (!match) { std::stringstream self_dep_ss; stream_join(self_dep_ss, ", ", self_dependencies); core->LogError(rp_handle, vuid, "%s (0x%" PRIx64 ") is not a subset of VkSubpassDependency srcAccessMask " "for any self-dependency of subpass %d of %s for which dstAccessMask is also a subset. " "Candidate VkSubpassDependency are pDependencies entries [%s].", loc.dot(Field::srcStageMask).Message().c_str(), src_stage_mask, active_subpass, core->report_data->FormatHandle(rp_handle).c_str(), self_dep_ss.str().c_str()); core->LogError(rp_handle, vuid, "%s (0x%" PRIx64 ") is not a subset of VkSubpassDependency dstAccessMask " "for any self-dependency of subpass %d of %s for which srcAccessMask is also a subset. " "Candidate VkSubpassDependency are pDependencies entries [%s].", loc.dot(Field::dstStageMask).Message().c_str(), dst_stage_mask, active_subpass, core->report_data->FormatHandle(rp_handle).c_str(), self_dep_ss.str().c_str()); } return !match; } bool ValidateAccess(const Location &loc, VkAccessFlags2KHR src_access_mask, VkAccessFlags2KHR dst_access_mask) { bool match = false; for (const auto self_dep_index : self_dependencies) { const auto sub_dep = GetSubPassDepBarrier(dependencies[self_dep_index]); match = (src_access_mask == (sub_dep.srcAccessMask & src_access_mask)) && (dst_access_mask == (sub_dep.dstAccessMask & dst_access_mask)); if (match) break; } if (!match) { std::stringstream self_dep_ss; stream_join(self_dep_ss, ", ", self_dependencies); core->LogError(rp_handle, vuid, "%s (0x%" PRIx64 ") is not a subset of VkSubpassDependency " "srcAccessMask of subpass %d of %s. Candidate VkSubpassDependency are pDependencies entries [%s].", loc.dot(Field::srcAccessMask).Message().c_str(), src_access_mask, active_subpass, core->report_data->FormatHandle(rp_handle).c_str(), self_dep_ss.str().c_str()); core->LogError(rp_handle, vuid, "%s (0x%" PRIx64 ") is not a subset of VkSubpassDependency " "dstAccessMask of subpass %d of %s. Candidate VkSubpassDependency are pDependencies entries [%s].", loc.dot(Field::dstAccessMask).Message().c_str(), dst_access_mask, active_subpass, core->report_data->FormatHandle(rp_handle).c_str(), self_dep_ss.str().c_str()); } return !match; } bool ValidateDependencyFlag(VkDependencyFlags dependency_flags) { bool match = false; for (const auto self_dep_index : self_dependencies) { const auto &sub_dep = dependencies[self_dep_index]; match = sub_dep.dependencyFlags == dependency_flags; if (match) break; } if (!match) { std::stringstream self_dep_ss; stream_join(self_dep_ss, ", ", self_dependencies); core->LogError(rp_handle, vuid, "%s: dependencyFlags param (0x%X) does not equal VkSubpassDependency dependencyFlags value for any " "self-dependency of subpass %d of %s. Candidate VkSubpassDependency are pDependencies entries [%s].", func_name.c_str(), dependency_flags, active_subpass, core->report_data->FormatHandle(rp_handle).c_str(), self_dep_ss.str().c_str()); } return !match; } }; // Validate VUs for Pipeline Barriers that are within a renderPass // Pre: cb_state->activeRenderPass must be a pointer to valid renderPass state bool CoreChecks::ValidateRenderPassPipelineBarriers(const Location &outer_loc, const CMD_BUFFER_STATE *cb_state, VkPipelineStageFlags src_stage_mask, VkPipelineStageFlags dst_stage_mask, VkDependencyFlags dependency_flags, uint32_t mem_barrier_count, const VkMemoryBarrier *mem_barriers, uint32_t buffer_mem_barrier_count, const VkBufferMemoryBarrier *buffer_mem_barriers, uint32_t image_mem_barrier_count, const VkImageMemoryBarrier *image_barriers) const { bool skip = false; const auto& rp_state = cb_state->activeRenderPass; RenderPassDepState state(this, outer_loc.StringFunc().c_str(), "VUID-vkCmdPipelineBarrier-pDependencies-02285", cb_state->activeSubpass, rp_state->renderPass(), enabled_features, rp_state->self_dependencies[cb_state->activeSubpass], rp_state->createInfo.pDependencies); if (state.self_dependencies.size() == 0) { skip |= LogError(state.rp_handle, "VUID-vkCmdPipelineBarrier-pDependencies-02285", "%s Barriers cannot be set during subpass %d of %s with no self-dependency specified.", outer_loc.Message().c_str(), state.active_subpass, report_data->FormatHandle(state.rp_handle).c_str()); return skip; } // Grab ref to current subpassDescription up-front for use below const auto &sub_desc = rp_state->createInfo.pSubpasses[state.active_subpass]; skip |= state.ValidateStage(outer_loc, src_stage_mask, dst_stage_mask); if (0 != buffer_mem_barrier_count) { skip |= LogError(state.rp_handle, "VUID-vkCmdPipelineBarrier-bufferMemoryBarrierCount-01178", "%s: bufferMemoryBarrierCount is non-zero (%d) for subpass %d of %s.", state.func_name.c_str(), buffer_mem_barrier_count, state.active_subpass, report_data->FormatHandle(rp_state->renderPass()).c_str()); } for (uint32_t i = 0; i < mem_barrier_count; ++i) { const auto &mem_barrier = mem_barriers[i]; Location loc(outer_loc.function, Struct::VkMemoryBarrier, Field::pMemoryBarriers, i); skip |= state.ValidateAccess(loc, mem_barrier.srcAccessMask, mem_barrier.dstAccessMask); } for (uint32_t i = 0; i < image_mem_barrier_count; ++i) { const auto &img_barrier = image_barriers[i]; Location loc(outer_loc.function, Struct::VkImageMemoryBarrier, Field::pImageMemoryBarriers, i); skip |= state.ValidateAccess(loc, img_barrier.srcAccessMask, img_barrier.dstAccessMask); if (VK_QUEUE_FAMILY_IGNORED != img_barrier.srcQueueFamilyIndex || VK_QUEUE_FAMILY_IGNORED != img_barrier.dstQueueFamilyIndex) { skip |= LogError(state.rp_handle, "VUID-vkCmdPipelineBarrier-srcQueueFamilyIndex-01182", "%s is %d and dstQueueFamilyIndex is %d but both must be VK_QUEUE_FAMILY_IGNORED.", loc.dot(Field::srcQueueFamilyIndex).Message().c_str(), img_barrier.srcQueueFamilyIndex, img_barrier.dstQueueFamilyIndex); } // Secondary CBs can have null framebuffer so record will queue up validation in that case 'til FB is known if (VK_NULL_HANDLE != cb_state->activeFramebuffer) { skip |= ValidateImageBarrierAttachment(loc, cb_state, cb_state->activeFramebuffer.get(), state.active_subpass, sub_desc, state.rp_handle, img_barrier); } } skip |= state.ValidateDependencyFlag(dependency_flags); return skip; } bool CoreChecks::ValidateRenderPassPipelineBarriers(const Location &outer_loc, const CMD_BUFFER_STATE *cb_state, const VkDependencyInfoKHR *dep_info) const { bool skip = false; const auto& rp_state = cb_state->activeRenderPass; RenderPassDepState state(this, outer_loc.StringFunc().c_str(), "VUID-vkCmdPipelineBarrier2KHR-pDependencies-02285", cb_state->activeSubpass, rp_state->renderPass(), enabled_features, rp_state->self_dependencies[cb_state->activeSubpass], rp_state->createInfo.pDependencies); if (state.self_dependencies.size() == 0) { skip |= LogError(state.rp_handle, state.vuid, "%s: Barriers cannot be set during subpass %d of %s with no self-dependency specified.", state.func_name.c_str(), state.active_subpass, report_data->FormatHandle(rp_state->renderPass()).c_str()); return skip; } // Grab ref to current subpassDescription up-front for use below const auto &sub_desc = rp_state->createInfo.pSubpasses[state.active_subpass]; for (uint32_t i = 0; i < dep_info->memoryBarrierCount; ++i) { const auto &mem_barrier = dep_info->pMemoryBarriers[i]; Location loc(outer_loc.function, Struct::VkMemoryBarrier2KHR, Field::pMemoryBarriers, i); skip |= state.ValidateStage(loc, mem_barrier.srcStageMask, mem_barrier.dstStageMask); skip |= state.ValidateAccess(loc, mem_barrier.srcAccessMask, mem_barrier.dstAccessMask); } if (0 != dep_info->bufferMemoryBarrierCount) { skip |= LogError(state.rp_handle, "VUID-vkCmdPipelineBarrier2KHR-bufferMemoryBarrierCount-01178", "%s: bufferMemoryBarrierCount is non-zero (%d) for subpass %d of %s.", state.func_name.c_str(), dep_info->bufferMemoryBarrierCount, state.active_subpass, report_data->FormatHandle(state.rp_handle).c_str()); } for (uint32_t i = 0; i < dep_info->imageMemoryBarrierCount; ++i) { const auto &img_barrier = dep_info->pImageMemoryBarriers[i]; Location loc(outer_loc.function, Struct::VkImageMemoryBarrier2KHR, Field::pImageMemoryBarriers, i); skip |= state.ValidateStage(loc, img_barrier.srcStageMask, img_barrier.dstStageMask); skip |= state.ValidateAccess(loc, img_barrier.srcAccessMask, img_barrier.dstAccessMask); if (VK_QUEUE_FAMILY_IGNORED != img_barrier.srcQueueFamilyIndex || VK_QUEUE_FAMILY_IGNORED != img_barrier.dstQueueFamilyIndex) { skip |= LogError(state.rp_handle, "VUID-vkCmdPipelineBarrier2KHR-srcQueueFamilyIndex-01182", "%s is %d and dstQueueFamilyIndex is %d but both must be VK_QUEUE_FAMILY_IGNORED.", loc.dot(Field::srcQueueFamilyIndex).Message().c_str(), img_barrier.srcQueueFamilyIndex, img_barrier.dstQueueFamilyIndex); } // Secondary CBs can have null framebuffer so record will queue up validation in that case 'til FB is known if (VK_NULL_HANDLE != cb_state->activeFramebuffer) { skip |= ValidateImageBarrierAttachment(loc, cb_state, cb_state->activeFramebuffer.get(), state.active_subpass, sub_desc, state.rp_handle, img_barrier); } } skip |= state.ValidateDependencyFlag(dep_info->dependencyFlags); return skip; } bool CoreChecks::ValidateStageMasksAgainstQueueCapabilities(const LogObjectList &objects, const Location &loc, VkQueueFlags queue_flags, VkPipelineStageFlags2KHR stage_mask) const { bool skip = false; // these are always allowed. stage_mask &= ~(VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR | VK_PIPELINE_STAGE_2_TOP_OF_PIPE_BIT_KHR | VK_PIPELINE_STAGE_2_BOTTOM_OF_PIPE_BIT_KHR | VK_PIPELINE_STAGE_2_HOST_BIT_KHR); if (stage_mask == 0) { return skip; } static const std::map<VkPipelineStageFlags2KHR, VkQueueFlags> metaFlags{ {VK_PIPELINE_STAGE_2_ALL_GRAPHICS_BIT_KHR, VK_QUEUE_GRAPHICS_BIT}, {VK_PIPELINE_STAGE_2_ALL_TRANSFER_BIT_KHR, VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT | VK_QUEUE_TRANSFER_BIT}, {VK_PIPELINE_STAGE_2_PRE_RASTERIZATION_SHADERS_BIT_KHR, VK_QUEUE_GRAPHICS_BIT}, {VK_PIPELINE_STAGE_2_VERTEX_INPUT_BIT_KHR, VK_QUEUE_GRAPHICS_BIT}, }; for (const auto &entry : metaFlags) { if (((entry.first & stage_mask) != 0) && ((entry.second & queue_flags) == 0)) { const auto& vuid = sync_vuid_maps::GetStageQueueCapVUID(loc, entry.first); skip |= LogError(objects, vuid, "%s flag %s is not compatible with the queue family properties (%s) of this command buffer.", loc.Message().c_str(), sync_utils::StringPipelineStageFlags(entry.first).c_str(), string_VkQueueFlags(queue_flags).c_str()); } stage_mask &= ~entry.first; } if (stage_mask == 0) { return skip; } auto supported_flags = sync_utils::ExpandPipelineStages(VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR, queue_flags); auto bad_flags = stage_mask & ~supported_flags; // Lookup each bit in the stagemask and check for overlap between its table bits and queue_flags for (size_t i = 0; i < sizeof(bad_flags) * 8; i++) { VkPipelineStageFlags2KHR bit = (1ULL << i) & bad_flags; if (bit) { const auto& vuid = sync_vuid_maps::GetStageQueueCapVUID(loc, bit); skip |= LogError( objects, vuid, "%s flag %s is not compatible with the queue family properties (%s) of this command buffer.", loc.Message().c_str(), sync_utils::StringPipelineStageFlags(bit).c_str(), string_VkQueueFlags(queue_flags).c_str()); } } return skip; } bool CoreChecks::ValidatePipelineStageFeatureEnables(const LogObjectList &objects, const Location &loc, VkPipelineStageFlags2KHR stage_mask) const { bool skip = false; if (!enabled_features.synchronization2_features.synchronization2 && stage_mask == 0) { const auto& vuid = sync_vuid_maps::GetBadFeatureVUID(loc, 0); std::stringstream msg; msg << loc.Message() << " must not be 0 unless synchronization2 is enabled."; skip |= LogError(objects, vuid, "%s", msg.str().c_str()); } auto disabled_stages = sync_utils::DisabledPipelineStages(enabled_features); auto bad_bits = stage_mask & disabled_stages; if (bad_bits == 0) { return skip; } for (size_t i = 0; i < sizeof(bad_bits) * 8; i++) { VkPipelineStageFlags2KHR bit = 1ULL << i; if (bit & bad_bits) { const auto& vuid = sync_vuid_maps::GetBadFeatureVUID(loc, bit); std::stringstream msg; msg << loc.Message() << " includes " << sync_utils::StringPipelineStageFlags(bit) << " when the device does not have " << sync_vuid_maps::kFeatureNameMap.at(bit) << " feature enabled."; skip |= LogError(objects, vuid, "%s", msg.str().c_str()); } } return skip; } bool CoreChecks::ValidatePipelineStage(const LogObjectList &objects, const Location &loc, VkQueueFlags queue_flags, VkPipelineStageFlags2KHR stage_mask) const { bool skip = false; skip |= ValidateStageMasksAgainstQueueCapabilities(objects, loc, queue_flags, stage_mask); skip |= ValidatePipelineStageFeatureEnables(objects, loc, stage_mask); return skip; } bool CoreChecks::ValidateAccessMask(const LogObjectList &objects, const Location &loc, VkQueueFlags queue_flags, VkAccessFlags2KHR access_mask, VkPipelineStageFlags2KHR stage_mask) const { bool skip = false; // Early out if all commands set if ((stage_mask & VK_PIPELINE_STAGE_2_ALL_COMMANDS_BIT_KHR) != 0) return skip; // or if only generic memory accesses are specified (or we got a 0 mask) access_mask &= ~(VK_ACCESS_2_MEMORY_READ_BIT_KHR | VK_ACCESS_2_MEMORY_WRITE_BIT_KHR); if (access_mask == 0) return skip; auto expanded_stages = sync_utils::ExpandPipelineStages(stage_mask, queue_flags); // TODO: auto valid_accesses = sync_utils::CompatibleAccessMask(expanded_stages); auto bad_accesses = (access_mask & ~valid_accesses); if (bad_accesses == 0) { return skip; } for (size_t i = 0; i < sizeof(bad_accesses) * 8; i++) { VkAccessFlags2KHR bit = (1ULL << i); if (bad_accesses & bit) { const auto& vuid = sync_vuid_maps::GetBadAccessFlagsVUID(loc, bit); std::stringstream msg; msg << loc.Message() << " bit " << sync_utils::StringAccessFlags(bit) << " is not supported by stage mask (" << sync_utils::StringPipelineStageFlags(stage_mask) << ")."; skip |= LogError(objects, vuid, "%s", msg.str().c_str()); } } return skip; } bool CoreChecks::ValidateEventStageMask(const ValidationStateTracker *state_data, const CMD_BUFFER_STATE *pCB, size_t eventCount, size_t firstEventIndex, VkPipelineStageFlags2KHR sourceStageMask, EventToStageMap *localEventToStageMap) { bool skip = false; VkPipelineStageFlags2KHR stage_mask = 0; const auto max_event = std::min((firstEventIndex + eventCount), pCB->events.size()); for (size_t event_index = firstEventIndex; event_index < max_event; ++event_index) { auto event = pCB->events[event_index]; auto event_data = localEventToStageMap->find(event); if (event_data != localEventToStageMap->end()) { stage_mask |= event_data->second; } else { auto global_event_data = state_data->GetEventState(event); if (!global_event_data) { skip |= state_data->LogError(event, kVUID_Core_DrawState_InvalidEvent, "%s cannot be waited on if it has never been set.", state_data->report_data->FormatHandle(event).c_str()); } else { stage_mask |= global_event_data->stageMask; } } } // TODO: Need to validate that host_bit is only set if set event is called // but set event can be called at any time. if (sourceStageMask != stage_mask && sourceStageMask != (stage_mask | VK_PIPELINE_STAGE_HOST_BIT)) { skip |= state_data->LogError( pCB->commandBuffer(), "VUID-vkCmdWaitEvents-srcStageMask-parameter", "Submitting cmdbuffer with call to VkCmdWaitEvents using srcStageMask 0x%" PRIx64 " which must be the bitwise OR of " "the stageMask parameters used in calls to vkCmdSetEvent and VK_PIPELINE_STAGE_HOST_BIT if used with " "vkSetEvent but instead is 0x%" PRIx64 ".", sourceStageMask, stage_mask); } return skip; } bool CoreChecks::PreCallValidateCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents, VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask, uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount, const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount, const VkImageMemoryBarrier *pImageMemoryBarriers) const { bool skip = false; const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); auto queue_flags = cb_state->GetQueueFlags(); LogObjectList objects(commandBuffer); Location loc(Func::vkCmdWaitEvents); skip |= ValidatePipelineStage(objects, loc.dot(Field::srcStageMask), queue_flags, srcStageMask); skip |= ValidatePipelineStage(objects, loc.dot(Field::dstStageMask), queue_flags, dstStageMask); skip |= ValidateCmd(cb_state, CMD_WAITEVENTS, "vkCmdWaitEvents()"); skip |= ValidateBarriers(loc.dot(Field::pDependencyInfo), cb_state, srcStageMask, dstStageMask, memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers); return skip; } bool CoreChecks::PreCallValidateCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents, const VkDependencyInfoKHR *pDependencyInfos) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); bool skip = false; if (!enabled_features.synchronization2_features.synchronization2) { skip |= LogError(commandBuffer, "VUID-vkCmdWaitEvents2KHR-synchronization2-03836", "vkCmdWaitEvents2KHR(): Synchronization2 feature is not enabled"); } for (uint32_t i = 0; (i < eventCount) && !skip; i++) { LogObjectList objects(commandBuffer); objects.add(pEvents[i]); Location loc(Func::vkCmdWaitEvents2KHR, Field::pDependencyInfos, i); if (pDependencyInfos[i].dependencyFlags != 0) { skip |= LogError(objects, "VUID-vkCmdWaitEvents2KHR-dependencyFlags-03844", "%s (%s) must be 0.", loc.dot(Field::dependencyFlags).Message().c_str(), string_VkDependencyFlags(pDependencyInfos[i].dependencyFlags).c_str()); } skip |= ValidateDependencyInfo(objects, loc, cb_state, &pDependencyInfos[i]); } skip |= ValidateCmd(cb_state, CMD_WAITEVENTS, "vkCmdWaitEvents()"); return skip; } void CoreChecks::PreCallRecordCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents, VkPipelineStageFlags sourceStageMask, VkPipelineStageFlags dstStageMask, uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount, const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount, const VkImageMemoryBarrier *pImageMemoryBarriers) { CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); // The StateTracker added will add to the events vector. auto first_event_index = cb_state->events.size(); StateTracker::PreCallRecordCmdWaitEvents(commandBuffer, eventCount, pEvents, sourceStageMask, dstStageMask, memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers); auto event_added_count = cb_state->events.size() - first_event_index; const CMD_BUFFER_STATE *cb_state_const = cb_state; cb_state->eventUpdates.emplace_back( [cb_state_const, event_added_count, first_event_index, sourceStageMask]( const ValidationStateTracker *device_data, bool do_validate, EventToStageMap *localEventToStageMap) { if (!do_validate) return false; return ValidateEventStageMask(device_data, cb_state_const, event_added_count, first_event_index, sourceStageMask, localEventToStageMap); }); TransitionImageLayouts(cb_state, imageMemoryBarrierCount, pImageMemoryBarriers); } void CoreChecks::PreCallRecordCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents, const VkDependencyInfoKHR *pDependencyInfos) { CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); // The StateTracker added will add to the events vector. auto first_event_index = cb_state->events.size(); StateTracker::PreCallRecordCmdWaitEvents2KHR(commandBuffer, eventCount, pEvents, pDependencyInfos); auto event_added_count = cb_state->events.size() - first_event_index; const CMD_BUFFER_STATE *cb_state_const = cb_state; for (uint32_t i = 0; i < eventCount; i++) { const auto &dep_info = pDependencyInfos[i]; auto stage_masks = sync_utils::GetGlobalStageMasks(dep_info); cb_state->eventUpdates.emplace_back( [cb_state_const, event_added_count, first_event_index, stage_masks]( const ValidationStateTracker *device_data, bool do_validate, EventToStageMap *localEventToStageMap) { if (!do_validate) return false; return ValidateEventStageMask(device_data, cb_state_const, event_added_count, first_event_index, stage_masks.src, localEventToStageMap); }); TransitionImageLayouts(cb_state, dep_info.imageMemoryBarrierCount, dep_info.pImageMemoryBarriers); } } void CoreChecks::PostCallRecordCmdWaitEvents(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents, VkPipelineStageFlags sourceStageMask, VkPipelineStageFlags dstStageMask, uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount, const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount, const VkImageMemoryBarrier *pImageMemoryBarriers) { CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); RecordBarriers(Func::vkCmdWaitEvents, cb_state, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers); } void CoreChecks::PostCallRecordCmdWaitEvents2KHR(VkCommandBuffer commandBuffer, uint32_t eventCount, const VkEvent *pEvents, const VkDependencyInfoKHR *pDependencyInfos) { CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); for (uint32_t i = 0; i < eventCount; i++) { const auto &dep_info = pDependencyInfos[i]; RecordBarriers(Func::vkCmdWaitEvents2KHR, cb_state, dep_info); } } bool CoreChecks::PreCallValidateCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags, uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount, const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount, const VkImageMemoryBarrier *pImageMemoryBarriers) const { bool skip = false; const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); LogObjectList objects(commandBuffer); auto queue_flags = cb_state->GetQueueFlags(); Location loc(Func::vkCmdPipelineBarrier); skip |= ValidatePipelineStage(objects, loc.dot(Field::srcStageMask), queue_flags, srcStageMask); skip |= ValidatePipelineStage(objects, loc.dot(Field::dstStageMask), queue_flags, dstStageMask); skip |= ValidateCmd(cb_state, CMD_PIPELINEBARRIER, "vkCmdPipelineBarrier()"); if (cb_state->activeRenderPass) { skip |= ValidateRenderPassPipelineBarriers(loc, cb_state, srcStageMask, dstStageMask, dependencyFlags, memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers); if (skip) return true; // Early return to avoid redundant errors from below calls } else { if (dependencyFlags & VK_DEPENDENCY_VIEW_LOCAL_BIT) { skip = LogError(objects, "VUID-vkCmdPipelineBarrier-dependencyFlags-01186", "%s VK_DEPENDENCY_VIEW_LOCAL_BIT must not be set outside of a render pass instance", loc.dot(Field::dependencyFlags).Message().c_str()); } } skip |= ValidateBarriers(loc, cb_state, srcStageMask, dstStageMask, memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers); return skip; } bool CoreChecks::PreCallValidateCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer, const VkDependencyInfoKHR *pDependencyInfo) const { bool skip = false; const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); LogObjectList objects(commandBuffer); Location loc(Func::vkCmdPipelineBarrier2KHR, Field::pDependencyInfo); skip |= ValidateCmd(cb_state, CMD_PIPELINEBARRIER, "vkCmdPipelineBarrier()"); if (cb_state->activeRenderPass) { skip |= ValidateRenderPassPipelineBarriers(loc, cb_state, pDependencyInfo); if (skip) return true; // Early return to avoid redundant errors from below calls } else { if (pDependencyInfo->dependencyFlags & VK_DEPENDENCY_VIEW_LOCAL_BIT) { skip = LogError(objects, "VUID-vkCmdPipelineBarrier2KHR-dependencyFlags-01186", "%s VK_DEPENDENCY_VIEW_LOCAL_BIT must not be set outside of a render pass instance", loc.dot(Field::dependencyFlags).Message().c_str()); } } skip |= ValidateDependencyInfo(objects, loc, cb_state, pDependencyInfo); return skip; } void CoreChecks::PreCallRecordCmdPipelineBarrier(VkCommandBuffer commandBuffer, VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags, uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount, const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount, const VkImageMemoryBarrier *pImageMemoryBarriers) { CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); RecordBarriers(Func::vkCmdPipelineBarrier, cb_state, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers); TransitionImageLayouts(cb_state, imageMemoryBarrierCount, pImageMemoryBarriers); StateTracker::PreCallRecordCmdPipelineBarrier(commandBuffer, srcStageMask, dstStageMask, dependencyFlags, memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers); } void CoreChecks::PreCallRecordCmdPipelineBarrier2KHR(VkCommandBuffer commandBuffer, const VkDependencyInfoKHR *pDependencyInfo) { CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); RecordBarriers(Func::vkCmdPipelineBarrier2KHR, cb_state, *pDependencyInfo); TransitionImageLayouts(cb_state, pDependencyInfo->imageMemoryBarrierCount, pDependencyInfo->pImageMemoryBarriers); StateTracker::PreCallRecordCmdPipelineBarrier2KHR(commandBuffer, pDependencyInfo); } bool CoreChecks::ValidateBeginQuery(const CMD_BUFFER_STATE *cb_state, const QueryObject &query_obj, VkFlags flags, uint32_t index, CMD_TYPE cmd, const char *cmd_name, const ValidateBeginQueryVuids *vuids) const { bool skip = false; const auto *query_pool_state = GetQueryPoolState(query_obj.pool); const auto &query_pool_ci = query_pool_state->createInfo; if (query_pool_ci.queryType == VK_QUERY_TYPE_TIMESTAMP) { skip |= LogError(cb_state->commandBuffer(), "VUID-vkCmdBeginQuery-queryType-02804", "%s: The querypool's query type must not be VK_QUERY_TYPE_TIMESTAMP.", cmd_name); } // Check for nested queries if (cb_state->activeQueries.size()) { for (const auto &a_query : cb_state->activeQueries) { auto active_query_pool_state = GetQueryPoolState(a_query.pool); if (active_query_pool_state->createInfo.queryType == query_pool_ci.queryType && a_query.index == index) { LogObjectList obj_list(cb_state->commandBuffer()); obj_list.add(query_obj.pool); obj_list.add(a_query.pool); skip |= LogError(obj_list, vuids->vuid_dup_query_type, "%s: Within the same command buffer %s, query %d from pool %s has same queryType as active query " "%d from pool %s.", cmd_name, report_data->FormatHandle(cb_state->commandBuffer()).c_str(), query_obj.index, report_data->FormatHandle(query_obj.pool).c_str(), a_query.index, report_data->FormatHandle(a_query.pool).c_str()); } } } // There are tighter queue constraints to test for certain query pools if (query_pool_ci.queryType == VK_QUERY_TYPE_TRANSFORM_FEEDBACK_STREAM_EXT) { skip |= ValidateCmdQueueFlags(cb_state, cmd_name, VK_QUEUE_GRAPHICS_BIT, vuids->vuid_queue_feedback); } if (query_pool_ci.queryType == VK_QUERY_TYPE_OCCLUSION) { skip |= ValidateCmdQueueFlags(cb_state, cmd_name, VK_QUEUE_GRAPHICS_BIT, vuids->vuid_queue_occlusion); } if (query_pool_ci.queryType == VK_QUERY_TYPE_PERFORMANCE_QUERY_KHR) { if (!cb_state->performance_lock_acquired) { skip |= LogError(cb_state->commandBuffer(), vuids->vuid_profile_lock, "%s: profiling lock must be held before vkBeginCommandBuffer is called on " "a command buffer where performance queries are recorded.", cmd_name); } if (query_pool_state->has_perf_scope_command_buffer && cb_state->commandCount > 0) { skip |= LogError(cb_state->commandBuffer(), vuids->vuid_scope_not_first, "%s: Query pool %s was created with a counter of scope " "VK_QUERY_SCOPE_COMMAND_BUFFER_KHR but %s is not the first recorded " "command in the command buffer.", cmd_name, report_data->FormatHandle(query_obj.pool).c_str(), cmd_name); } if (query_pool_state->has_perf_scope_render_pass && cb_state->activeRenderPass) { skip |= LogError(cb_state->commandBuffer(), vuids->vuid_scope_in_rp, "%s: Query pool %s was created with a counter of scope " "VK_QUERY_SCOPE_RENDER_PASS_KHR but %s is inside a render pass.", cmd_name, report_data->FormatHandle(query_obj.pool).c_str(), cmd_name); } } skip |= ValidateCmdQueueFlags(cb_state, cmd_name, VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT, vuids->vuid_queue_flags); if (flags & VK_QUERY_CONTROL_PRECISE_BIT) { if (!enabled_features.core.occlusionQueryPrecise) { skip |= LogError(cb_state->commandBuffer(), vuids->vuid_precise, "%s: VK_QUERY_CONTROL_PRECISE_BIT provided, but precise occlusion queries not enabled on the device.", cmd_name); } if (query_pool_ci.queryType != VK_QUERY_TYPE_OCCLUSION) { skip |= LogError(cb_state->commandBuffer(), vuids->vuid_precise, "%s: VK_QUERY_CONTROL_PRECISE_BIT provided, but pool query type is not VK_QUERY_TYPE_OCCLUSION", cmd_name); } } if (query_obj.query >= query_pool_ci.queryCount) { skip |= LogError(cb_state->commandBuffer(), vuids->vuid_query_count, "%s: Query index %" PRIu32 " must be less than query count %" PRIu32 " of %s.", cmd_name, query_obj.query, query_pool_ci.queryCount, report_data->FormatHandle(query_obj.pool).c_str()); } if (cb_state->unprotected == false) { skip |= LogError(cb_state->commandBuffer(), vuids->vuid_protected_cb, "%s: command can't be used in protected command buffers.", cmd_name); } skip |= ValidateCmd(cb_state, cmd, cmd_name); return skip; } bool CoreChecks::PreCallValidateCmdBeginQuery(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t slot, VkFlags flags) const { if (disabled[query_validation]) return false; const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); QueryObject query_obj(queryPool, slot); struct BeginQueryVuids : ValidateBeginQueryVuids { BeginQueryVuids() : ValidateBeginQueryVuids() { vuid_queue_flags = "VUID-vkCmdBeginQuery-commandBuffer-cmdpool"; vuid_queue_feedback = "VUID-vkCmdBeginQuery-queryType-02327"; vuid_queue_occlusion = "VUID-vkCmdBeginQuery-queryType-00803"; vuid_precise = "VUID-vkCmdBeginQuery-queryType-00800"; vuid_query_count = "VUID-vkCmdBeginQuery-query-00802"; vuid_profile_lock = "VUID-vkCmdBeginQuery-queryPool-03223"; vuid_scope_not_first = "VUID-vkCmdBeginQuery-queryPool-03224"; vuid_scope_in_rp = "VUID-vkCmdBeginQuery-queryPool-03225"; vuid_dup_query_type = "VUID-vkCmdBeginQuery-queryPool-01922"; vuid_protected_cb = "VUID-vkCmdBeginQuery-commandBuffer-01885"; } }; BeginQueryVuids vuids; return ValidateBeginQuery(cb_state, query_obj, flags, 0, CMD_BEGINQUERY, "vkCmdBeginQuery()", &vuids); } bool CoreChecks::VerifyQueryIsReset(const ValidationStateTracker *state_data, VkCommandBuffer commandBuffer, QueryObject query_obj, const char *func_name, VkQueryPool &firstPerfQueryPool, uint32_t perfPass, QueryMap *localQueryToStateMap) { bool skip = false; const auto *query_pool_state = state_data->GetQueryPoolState(query_obj.pool); const auto &query_pool_ci = query_pool_state->createInfo; QueryState state = state_data->GetQueryState(localQueryToStateMap, query_obj.pool, query_obj.query, perfPass); // If reset was in another command buffer, check the global map if (state == QUERYSTATE_UNKNOWN) { state = state_data->GetQueryState(&state_data->queryToStateMap, query_obj.pool, query_obj.query, perfPass); } // Performance queries have limitation upon when they can be // reset. if (query_pool_ci.queryType == VK_QUERY_TYPE_PERFORMANCE_QUERY_KHR && state == QUERYSTATE_UNKNOWN && perfPass >= query_pool_state->n_performance_passes) { // If the pass is invalid, assume RESET state, another error // will be raised in ValidatePerformanceQuery(). state = QUERYSTATE_RESET; } if (state != QUERYSTATE_RESET) { skip |= state_data->LogError(commandBuffer, kVUID_Core_DrawState_QueryNotReset, "%s: %s and query %" PRIu32 ": query not reset. " "After query pool creation, each query must be reset before it is used. " "Queries must also be reset between uses.", func_name, state_data->report_data->FormatHandle(query_obj.pool).c_str(), query_obj.query); } return skip; } bool CoreChecks::ValidatePerformanceQuery(const ValidationStateTracker *state_data, VkCommandBuffer commandBuffer, QueryObject query_obj, const char *func_name, VkQueryPool &firstPerfQueryPool, uint32_t perfPass, QueryMap *localQueryToStateMap) { const auto *query_pool_state = state_data->GetQueryPoolState(query_obj.pool); const auto &query_pool_ci = query_pool_state->createInfo; if (query_pool_ci.queryType != VK_QUERY_TYPE_PERFORMANCE_QUERY_KHR) return false; const CMD_BUFFER_STATE *cb_state = state_data->GetCBState(commandBuffer); bool skip = false; if (perfPass >= query_pool_state->n_performance_passes) { skip |= state_data->LogError(commandBuffer, "VUID-VkPerformanceQuerySubmitInfoKHR-counterPassIndex-03221", "Invalid counterPassIndex (%u, maximum allowed %u) value for query pool %s.", perfPass, query_pool_state->n_performance_passes, state_data->report_data->FormatHandle(query_obj.pool).c_str()); } if (!cb_state->performance_lock_acquired || cb_state->performance_lock_released) { skip |= state_data->LogError(commandBuffer, "VUID-vkQueueSubmit-pCommandBuffers-03220", "Commandbuffer %s was submitted and contains a performance query but the" "profiling lock was not held continuously throughout the recording of commands.", state_data->report_data->FormatHandle(commandBuffer).c_str()); } QueryState command_buffer_state = state_data->GetQueryState(localQueryToStateMap, query_obj.pool, query_obj.query, perfPass); if (command_buffer_state == QUERYSTATE_RESET) { skip |= state_data->LogError( commandBuffer, query_obj.indexed ? "VUID-vkCmdBeginQueryIndexedEXT-None-02863" : "VUID-vkCmdBeginQuery-None-02863", "VkQuery begin command recorded in a command buffer that, either directly or " "through secondary command buffers, also contains a vkCmdResetQueryPool command " "affecting the same query."); } if (firstPerfQueryPool != VK_NULL_HANDLE) { if (firstPerfQueryPool != query_obj.pool && !state_data->enabled_features.performance_query_features.performanceCounterMultipleQueryPools) { skip |= state_data->LogError( commandBuffer, query_obj.indexed ? "VUID-vkCmdBeginQueryIndexedEXT-queryPool-03226" : "VUID-vkCmdBeginQuery-queryPool-03226", "Commandbuffer %s contains more than one performance query pool but " "performanceCounterMultipleQueryPools is not enabled.", state_data->report_data->FormatHandle(commandBuffer).c_str()); } } else { firstPerfQueryPool = query_obj.pool; } return skip; } void CoreChecks::EnqueueVerifyBeginQuery(VkCommandBuffer command_buffer, const QueryObject &query_obj, const char *func_name) { CMD_BUFFER_STATE *cb_state = GetCBState(command_buffer); // Enqueue the submit time validation here, ahead of the submit time state update in the StateTracker's PostCallRecord cb_state->queryUpdates.emplace_back([command_buffer, query_obj, func_name](const ValidationStateTracker *device_data, bool do_validate, VkQueryPool &firstPerfQueryPool, uint32_t perfPass, QueryMap *localQueryToStateMap) { if (!do_validate) return false; bool skip = false; skip |= ValidatePerformanceQuery(device_data, command_buffer, query_obj, func_name, firstPerfQueryPool, perfPass, localQueryToStateMap); skip |= VerifyQueryIsReset(device_data, command_buffer, query_obj, func_name, firstPerfQueryPool, perfPass, localQueryToStateMap); return skip; }); } void CoreChecks::PreCallRecordCmdBeginQuery(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t slot, VkFlags flags) { if (disabled[query_validation]) return; QueryObject query_obj = {queryPool, slot}; EnqueueVerifyBeginQuery(commandBuffer, query_obj, "vkCmdBeginQuery()"); } void CoreChecks::EnqueueVerifyEndQuery(VkCommandBuffer command_buffer, const QueryObject &query_obj) { CMD_BUFFER_STATE *cb_state = GetCBState(command_buffer); // Enqueue the submit time validation here, ahead of the submit time state update in the StateTracker's PostCallRecord cb_state->queryUpdates.emplace_back([command_buffer, query_obj](const ValidationStateTracker *device_data, bool do_validate, VkQueryPool &firstPerfQueryPool, uint32_t perfPass, QueryMap *localQueryToStateMap) { if (!do_validate) return false; bool skip = false; const CMD_BUFFER_STATE *cb_state = device_data->GetCBState(command_buffer); const auto *query_pool_state = device_data->GetQueryPoolState(query_obj.pool); if (query_pool_state->has_perf_scope_command_buffer && (cb_state->commandCount - 1) != query_obj.endCommandIndex) { skip |= device_data->LogError(command_buffer, "VUID-vkCmdEndQuery-queryPool-03227", "vkCmdEndQuery: Query pool %s was created with a counter of scope" "VK_QUERY_SCOPE_COMMAND_BUFFER_KHR but the end of the query is not the last " "command in the command buffer %s.", device_data->report_data->FormatHandle(query_obj.pool).c_str(), device_data->report_data->FormatHandle(command_buffer).c_str()); } return skip; }); } bool CoreChecks::ValidateCmdEndQuery(const CMD_BUFFER_STATE *cb_state, const QueryObject &query_obj, uint32_t index, CMD_TYPE cmd, const char *cmd_name, const ValidateEndQueryVuids *vuids) const { bool skip = false; if (!cb_state->activeQueries.count(query_obj)) { skip |= LogError(cb_state->commandBuffer(), vuids->vuid_active_queries, "%s: Ending a query before it was started: %s, index %d.", cmd_name, report_data->FormatHandle(query_obj.pool).c_str(), query_obj.query); } const auto *query_pool_state = GetQueryPoolState(query_obj.pool); const auto &query_pool_ci = query_pool_state->createInfo; if (query_pool_ci.queryType == VK_QUERY_TYPE_PERFORMANCE_QUERY_KHR) { if (query_pool_state->has_perf_scope_render_pass && cb_state->activeRenderPass) { skip |= LogError(cb_state->commandBuffer(), "VUID-vkCmdEndQuery-queryPool-03228", "%s: Query pool %s was created with a counter of scope " "VK_QUERY_SCOPE_RENDER_PASS_KHR but %s is inside a render pass.", cmd_name, report_data->FormatHandle(query_obj.pool).c_str(), cmd_name); } } skip |= ValidateCmdQueueFlags(cb_state, cmd_name, VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT, vuids->vuid_queue_flags); skip |= ValidateCmd(cb_state, cmd, cmd_name); if (cb_state->unprotected == false) { skip |= LogError(cb_state->commandBuffer(), vuids->vuid_protected_cb, "%s: command can't be used in protected command buffers.", cmd_name); } return skip; } bool CoreChecks::PreCallValidateCmdEndQuery(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t slot) const { if (disabled[query_validation]) return false; bool skip = false; QueryObject query_obj = {queryPool, slot}; const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); const QUERY_POOL_STATE *query_pool_state = GetQueryPoolState(queryPool); if (query_pool_state) { const uint32_t available_query_count = query_pool_state->createInfo.queryCount; // Only continue validating if the slot is even within range if (slot >= available_query_count) { skip |= LogError(cb_state->commandBuffer(), "VUID-vkCmdEndQuery-query-00810", "vkCmdEndQuery(): query index (%u) is greater or equal to the queryPool size (%u).", slot, available_query_count); } else { struct EndQueryVuids : ValidateEndQueryVuids { EndQueryVuids() : ValidateEndQueryVuids() { vuid_queue_flags = "VUID-vkCmdEndQuery-commandBuffer-cmdpool"; vuid_active_queries = "VUID-vkCmdEndQuery-None-01923"; vuid_protected_cb = "VUID-vkCmdEndQuery-commandBuffer-01886"; } }; EndQueryVuids vuids; skip |= ValidateCmdEndQuery(cb_state, query_obj, 0, CMD_ENDQUERY, "vkCmdEndQuery()", &vuids); } } return skip; } void CoreChecks::PreCallRecordCmdEndQuery(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t slot) { if (disabled[query_validation]) return; const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); QueryObject query_obj = {queryPool, slot}; query_obj.endCommandIndex = cb_state->commandCount - 1; EnqueueVerifyEndQuery(commandBuffer, query_obj); } bool CoreChecks::ValidateQueryPoolIndex(VkQueryPool queryPool, uint32_t firstQuery, uint32_t queryCount, const char *func_name, const char *first_vuid, const char *sum_vuid) const { bool skip = false; const QUERY_POOL_STATE *query_pool_state = GetQueryPoolState(queryPool); if (query_pool_state) { const uint32_t available_query_count = query_pool_state->createInfo.queryCount; if (firstQuery >= available_query_count) { skip |= LogError(queryPool, first_vuid, "%s: In Query %s the firstQuery (%u) is greater or equal to the queryPool size (%u).", func_name, report_data->FormatHandle(queryPool).c_str(), firstQuery, available_query_count); } if ((firstQuery + queryCount) > available_query_count) { skip |= LogError(queryPool, sum_vuid, "%s: In Query %s the sum of firstQuery (%u) + queryCount (%u) is greater than the queryPool size (%u).", func_name, report_data->FormatHandle(queryPool).c_str(), firstQuery, queryCount, available_query_count); } } return skip; } bool CoreChecks::PreCallValidateCmdResetQueryPool(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t firstQuery, uint32_t queryCount) const { if (disabled[query_validation]) return false; const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); bool skip = false; skip |= ValidateCmd(cb_state, CMD_RESETQUERYPOOL, "VkCmdResetQueryPool()"); skip |= ValidateQueryPoolIndex(queryPool, firstQuery, queryCount, "VkCmdResetQueryPool()", "VUID-vkCmdResetQueryPool-firstQuery-00796", "VUID-vkCmdResetQueryPool-firstQuery-00797"); return skip; } static QueryResultType GetQueryResultType(QueryState state, VkQueryResultFlags flags) { switch (state) { case QUERYSTATE_UNKNOWN: return QUERYRESULT_UNKNOWN; case QUERYSTATE_RESET: case QUERYSTATE_RUNNING: if (flags & VK_QUERY_RESULT_WAIT_BIT) { return ((state == QUERYSTATE_RESET) ? QUERYRESULT_WAIT_ON_RESET : QUERYRESULT_WAIT_ON_RUNNING); } else if ((flags & VK_QUERY_RESULT_PARTIAL_BIT) || (flags & VK_QUERY_RESULT_WITH_AVAILABILITY_BIT)) { return QUERYRESULT_SOME_DATA; } else { return QUERYRESULT_NO_DATA; } case QUERYSTATE_ENDED: if ((flags & VK_QUERY_RESULT_WAIT_BIT) || (flags & VK_QUERY_RESULT_PARTIAL_BIT) || (flags & VK_QUERY_RESULT_WITH_AVAILABILITY_BIT)) { return QUERYRESULT_SOME_DATA; } else { return QUERYRESULT_UNKNOWN; } case QUERYSTATE_AVAILABLE: return QUERYRESULT_SOME_DATA; } assert(false); return QUERYRESULT_UNKNOWN; } bool CoreChecks::ValidateCopyQueryPoolResults(const ValidationStateTracker *state_data, VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t firstQuery, uint32_t queryCount, uint32_t perfPass, VkQueryResultFlags flags, QueryMap *localQueryToStateMap) { bool skip = false; for (uint32_t i = 0; i < queryCount; i++) { QueryState state = state_data->GetQueryState(localQueryToStateMap, queryPool, firstQuery + i, perfPass); QueryResultType result_type = GetQueryResultType(state, flags); if (result_type != QUERYRESULT_SOME_DATA && result_type != QUERYRESULT_UNKNOWN) { skip |= state_data->LogError( commandBuffer, kVUID_Core_DrawState_InvalidQuery, "vkCmdCopyQueryPoolResults(): Requesting a copy from query to buffer on %s query %" PRIu32 ": %s", state_data->report_data->FormatHandle(queryPool).c_str(), firstQuery + i, string_QueryResultType(result_type)); } } return skip; } bool CoreChecks::PreCallValidateCmdCopyQueryPoolResults(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t firstQuery, uint32_t queryCount, VkBuffer dstBuffer, VkDeviceSize dstOffset, VkDeviceSize stride, VkQueryResultFlags flags) const { if (disabled[query_validation]) return false; const auto cb_state = GetCBState(commandBuffer); const auto dst_buff_state = GetBufferState(dstBuffer); assert(cb_state); assert(dst_buff_state); bool skip = ValidateMemoryIsBoundToBuffer(dst_buff_state, "vkCmdCopyQueryPoolResults()", "VUID-vkCmdCopyQueryPoolResults-dstBuffer-00826"); skip |= ValidateQueryPoolStride("VUID-vkCmdCopyQueryPoolResults-flags-00822", "VUID-vkCmdCopyQueryPoolResults-flags-00823", stride, "dstOffset", dstOffset, flags); // Validate that DST buffer has correct usage flags set skip |= ValidateBufferUsageFlags(dst_buff_state, VK_BUFFER_USAGE_TRANSFER_DST_BIT, true, "VUID-vkCmdCopyQueryPoolResults-dstBuffer-00825", "vkCmdCopyQueryPoolResults()", "VK_BUFFER_USAGE_TRANSFER_DST_BIT"); skip |= ValidateCmd(cb_state, CMD_COPYQUERYPOOLRESULTS, "vkCmdCopyQueryPoolResults()"); skip |= ValidateQueryPoolIndex(queryPool, firstQuery, queryCount, "vkCmdCopyQueryPoolResults()", "VUID-vkCmdCopyQueryPoolResults-firstQuery-00820", "VUID-vkCmdCopyQueryPoolResults-firstQuery-00821"); if (dstOffset >= dst_buff_state->requirements.size) { skip |= LogError(commandBuffer, "VUID-vkCmdCopyQueryPoolResults-dstOffset-00819", "vkCmdCopyQueryPoolResults() dstOffset (0x%" PRIxLEAST64 ") is not less than the size (0x%" PRIxLEAST64 ") of buffer (%s).", dstOffset, dst_buff_state->requirements.size, report_data->FormatHandle(dst_buff_state->buffer()).c_str()); } else if (dstOffset + (queryCount * stride) > dst_buff_state->requirements.size) { skip |= LogError(commandBuffer, "VUID-vkCmdCopyQueryPoolResults-dstBuffer-00824", "vkCmdCopyQueryPoolResults() storage required (0x%" PRIxLEAST64 ") equal to dstOffset + (queryCount * stride) is greater than the size (0x%" PRIxLEAST64 ") of buffer (%s).", dstOffset + (queryCount * stride), dst_buff_state->requirements.size, report_data->FormatHandle(dst_buff_state->buffer()).c_str()); } auto query_pool_state_iter = queryPoolMap.find(queryPool); if (query_pool_state_iter != queryPoolMap.end()) { auto query_pool_state = query_pool_state_iter->second.get(); if (query_pool_state->createInfo.queryType == VK_QUERY_TYPE_PERFORMANCE_QUERY_KHR) { skip |= ValidatePerformanceQueryResults("vkCmdCopyQueryPoolResults", query_pool_state, firstQuery, queryCount, flags); if (!phys_dev_ext_props.performance_query_props.allowCommandBufferQueryCopies) { skip |= LogError(commandBuffer, "VUID-vkCmdCopyQueryPoolResults-queryType-03232", "vkCmdCopyQueryPoolResults called with query pool %s but " "VkPhysicalDevicePerformanceQueryPropertiesKHR::allowCommandBufferQueryCopies " "is not set.", report_data->FormatHandle(queryPool).c_str()); } } if ((query_pool_state->createInfo.queryType == VK_QUERY_TYPE_TIMESTAMP) && ((flags & VK_QUERY_RESULT_PARTIAL_BIT) != 0)) { skip |= LogError(commandBuffer, "VUID-vkCmdCopyQueryPoolResults-queryType-00827", "vkCmdCopyQueryPoolResults() query pool %s was created with VK_QUERY_TYPE_TIMESTAMP so flags must not " "contain VK_QUERY_RESULT_PARTIAL_BIT.", report_data->FormatHandle(queryPool).c_str()); } if (query_pool_state->createInfo.queryType == VK_QUERY_TYPE_PERFORMANCE_QUERY_INTEL) { skip |= LogError(queryPool, "VUID-vkCmdCopyQueryPoolResults-queryType-02734", "vkCmdCopyQueryPoolResults() called but QueryPool %s was created with queryType " "VK_QUERY_TYPE_PERFORMANCE_QUERY_INTEL.", report_data->FormatHandle(queryPool).c_str()); } } return skip; } void CoreChecks::PreCallRecordCmdCopyQueryPoolResults(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t firstQuery, uint32_t queryCount, VkBuffer dstBuffer, VkDeviceSize dstOffset, VkDeviceSize stride, VkQueryResultFlags flags) { if (disabled[query_validation]) return; auto cb_state = GetCBState(commandBuffer); cb_state->queryUpdates.emplace_back([commandBuffer, queryPool, firstQuery, queryCount, flags]( const ValidationStateTracker *device_data, bool do_validate, VkQueryPool &firstPerfQueryPool, uint32_t perfPass, QueryMap *localQueryToStateMap) { if (!do_validate) return false; return ValidateCopyQueryPoolResults(device_data, commandBuffer, queryPool, firstQuery, queryCount, perfPass, flags, localQueryToStateMap); }); } bool CoreChecks::PreCallValidateCmdPushConstants(VkCommandBuffer commandBuffer, VkPipelineLayout layout, VkShaderStageFlags stageFlags, uint32_t offset, uint32_t size, const void *pValues) const { bool skip = false; const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); skip |= ValidateCmd(cb_state, CMD_PUSHCONSTANTS, "vkCmdPushConstants()"); // Check if pipeline_layout VkPushConstantRange(s) overlapping offset, size have stageFlags set for each stage in the command // stageFlags argument, *and* that the command stageFlags argument has bits set for the stageFlags in each overlapping range. if (!skip) { const auto &ranges = *GetPipelineLayout(layout)->push_constant_ranges; VkShaderStageFlags found_stages = 0; for (const auto &range : ranges) { if ((offset >= range.offset) && (offset + size <= range.offset + range.size)) { VkShaderStageFlags matching_stages = range.stageFlags & stageFlags; if (matching_stages != range.stageFlags) { skip |= LogError(commandBuffer, "VUID-vkCmdPushConstants-offset-01796", "vkCmdPushConstants(): stageFlags (%s, offset (%" PRIu32 "), and size (%" PRIu32 "), must contain all stages in overlapping VkPushConstantRange stageFlags (%s), offset (%" PRIu32 "), and size (%" PRIu32 ") in %s.", string_VkShaderStageFlags(stageFlags).c_str(), offset, size, string_VkShaderStageFlags(range.stageFlags).c_str(), range.offset, range.size, report_data->FormatHandle(layout).c_str()); } // Accumulate all stages we've found found_stages = matching_stages | found_stages; } } if (found_stages != stageFlags) { uint32_t missing_stages = ~found_stages & stageFlags; skip |= LogError( commandBuffer, "VUID-vkCmdPushConstants-offset-01795", "vkCmdPushConstants(): %s, VkPushConstantRange in %s overlapping offset = %d and size = %d, do not contain %s.", string_VkShaderStageFlags(stageFlags).c_str(), report_data->FormatHandle(layout).c_str(), offset, size, string_VkShaderStageFlags(missing_stages).c_str()); } } return skip; } bool CoreChecks::PreCallValidateCmdWriteTimestamp(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage, VkQueryPool queryPool, uint32_t slot) const { if (disabled[query_validation]) return false; const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); bool skip = false; skip |= ValidateCmd(cb_state, CMD_WRITETIMESTAMP, "vkCmdWriteTimestamp()"); const QUERY_POOL_STATE *query_pool_state = GetQueryPoolState(queryPool); if ((query_pool_state != nullptr) && (query_pool_state->createInfo.queryType != VK_QUERY_TYPE_TIMESTAMP)) { skip |= LogError(cb_state->commandBuffer(), "VUID-vkCmdWriteTimestamp-queryPool-01416", "vkCmdWriteTimestamp(): Query Pool %s was not created with VK_QUERY_TYPE_TIMESTAMP.", report_data->FormatHandle(queryPool).c_str()); } const uint32_t timestamp_valid_bits = GetPhysicalDeviceState()->queue_family_properties[cb_state->command_pool->queueFamilyIndex].timestampValidBits; if (timestamp_valid_bits == 0) { skip |= LogError(cb_state->commandBuffer(), "VUID-vkCmdWriteTimestamp-timestampValidBits-00829", "vkCmdWriteTimestamp(): Query Pool %s has a timestampValidBits value of zero.", report_data->FormatHandle(queryPool).c_str()); } if ((query_pool_state != nullptr) && (slot >= query_pool_state->createInfo.queryCount)) { skip |= LogError(cb_state->commandBuffer(), "VUID-vkCmdWriteTimestamp-query-04904", "vkCmdWriteTimestamp(): query (%" PRIu32 ") is not lower than the number of queries (%" PRIu32 ") in Query pool %s.", slot, query_pool_state->createInfo.queryCount, report_data->FormatHandle(queryPool).c_str()); } return skip; } bool CoreChecks::PreCallValidateCmdWriteTimestamp2KHR(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR stage, VkQueryPool queryPool, uint32_t slot) const { if (disabled[query_validation]) return false; const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); bool skip = false; skip |= ValidateCmd(cb_state, CMD_WRITETIMESTAMP, "vkCmdWriteTimestamp2KHR()"); Location loc(Func::vkCmdWriteTimestamp2KHR, Field::stage); if ((stage & (stage - 1)) != 0) { skip |= LogError(cb_state->commandBuffer(), "VUID-vkCmdWriteTimestamp2KHR-stage-03859", "%s (%s) must only set a single pipeline stage.", loc.Message().c_str(), string_VkPipelineStageFlags2KHR(stage).c_str()); } skip |= ValidatePipelineStage(LogObjectList(cb_state->commandBuffer()), loc, cb_state->GetQueueFlags(), stage); loc.field = Field::queryPool; const QUERY_POOL_STATE *query_pool_state = GetQueryPoolState(queryPool); if ((query_pool_state != nullptr) && (query_pool_state->createInfo.queryType != VK_QUERY_TYPE_TIMESTAMP)) { skip |= LogError(cb_state->commandBuffer(), "VUID-vkCmdWriteTimestamp2KHR-queryPool-03861", "%s Query Pool %s was not created with VK_QUERY_TYPE_TIMESTAMP.", loc.Message().c_str(), report_data->FormatHandle(queryPool).c_str()); } const uint32_t timestampValidBits = GetPhysicalDeviceState()->queue_family_properties[cb_state->command_pool->queueFamilyIndex].timestampValidBits; if (timestampValidBits == 0) { skip |= LogError(cb_state->commandBuffer(), "VUID-vkCmdWriteTimestamp2KHR-timestampValidBits-03863", "%s Query Pool %s has a timestampValidBits value of zero.", loc.Message().c_str(), report_data->FormatHandle(queryPool).c_str()); } return skip; } void CoreChecks::PreCallRecordCmdWriteTimestamp(VkCommandBuffer commandBuffer, VkPipelineStageFlagBits pipelineStage, VkQueryPool queryPool, uint32_t slot) { if (disabled[query_validation]) return; // Enqueue the submit time validation check here, before the submit time state update in StateTracker::PostCall... CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); QueryObject query = {queryPool, slot}; const char *func_name = "vkCmdWriteTimestamp()"; cb_state->queryUpdates.emplace_back([commandBuffer, query, func_name](const ValidationStateTracker *device_data, bool do_validate, VkQueryPool &firstPerfQueryPool, uint32_t perfPass, QueryMap *localQueryToStateMap) { if (!do_validate) return false; return VerifyQueryIsReset(device_data, commandBuffer, query, func_name, firstPerfQueryPool, perfPass, localQueryToStateMap); }); } void CoreChecks::PreCallRecordCmdWriteTimestamp2KHR(VkCommandBuffer commandBuffer, VkPipelineStageFlags2KHR pipelineStage, VkQueryPool queryPool, uint32_t slot) { if (disabled[query_validation]) return; // Enqueue the submit time validation check here, before the submit time state update in StateTracker::PostCall... CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); QueryObject query = {queryPool, slot}; const char *func_name = "vkCmdWriteTimestamp()"; cb_state->queryUpdates.emplace_back([commandBuffer, query, func_name](const ValidationStateTracker *device_data, bool do_validate, VkQueryPool &firstPerfQueryPool, uint32_t perfPass, QueryMap *localQueryToStateMap) { if (!do_validate) return false; return VerifyQueryIsReset(device_data, commandBuffer, query, func_name, firstPerfQueryPool, perfPass, localQueryToStateMap); }); } void CoreChecks::PreCallRecordCmdWriteAccelerationStructuresPropertiesKHR(VkCommandBuffer commandBuffer, uint32_t accelerationStructureCount, const VkAccelerationStructureKHR *pAccelerationStructures, VkQueryType queryType, VkQueryPool queryPool, uint32_t firstQuery) { if (disabled[query_validation]) return; // Enqueue the submit time validation check here, before the submit time state update in StateTracker::PostCall... CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); const char *func_name = "vkCmdWriteAccelerationStructuresPropertiesKHR()"; cb_state->queryUpdates.emplace_back([accelerationStructureCount, commandBuffer, firstQuery, func_name, queryPool]( const ValidationStateTracker *device_data, bool do_validate, VkQueryPool &firstPerfQueryPool, uint32_t perfPass, QueryMap *localQueryToStateMap) { if (!do_validate) return false; bool skip = false; for (uint32_t i = 0; i < accelerationStructureCount; i++) { QueryObject query = {{queryPool, firstQuery + i}, perfPass}; skip |= VerifyQueryIsReset(device_data, commandBuffer, query, func_name, firstPerfQueryPool, perfPass, localQueryToStateMap); } return skip; }); } bool CoreChecks::MatchUsage(uint32_t count, const VkAttachmentReference2 *attachments, const VkFramebufferCreateInfo *fbci, VkImageUsageFlagBits usage_flag, const char *error_code) const { bool skip = false; if (attachments) { for (uint32_t attach = 0; attach < count; attach++) { if (attachments[attach].attachment != VK_ATTACHMENT_UNUSED) { // Attachment counts are verified elsewhere, but prevent an invalid access if (attachments[attach].attachment < fbci->attachmentCount) { if ((fbci->flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) == 0) { const VkImageView *image_view = &fbci->pAttachments[attachments[attach].attachment]; auto view_state = GetImageViewState(*image_view); if (view_state) { const VkImageCreateInfo *ici = &GetImageState(view_state->create_info.image)->createInfo; if (ici != nullptr) { auto creation_usage = ici->usage; const auto stencil_usage_info = LvlFindInChain<VkImageStencilUsageCreateInfo>(ici->pNext); if (stencil_usage_info) { creation_usage |= stencil_usage_info->stencilUsage; } if ((creation_usage & usage_flag) == 0) { skip |= LogError(device, error_code, "vkCreateFramebuffer: Framebuffer Attachment (%d) conflicts with the image's " "IMAGE_USAGE flags (%s).", attachments[attach].attachment, string_VkImageUsageFlagBits(usage_flag)); } } } } else { const VkFramebufferAttachmentsCreateInfo *fbaci = LvlFindInChain<VkFramebufferAttachmentsCreateInfo>(fbci->pNext); if (fbaci != nullptr && fbaci->pAttachmentImageInfos != nullptr && fbaci->attachmentImageInfoCount > attachments[attach].attachment) { uint32_t image_usage = fbaci->pAttachmentImageInfos[attachments[attach].attachment].usage; if ((image_usage & usage_flag) == 0) { skip |= LogError(device, error_code, "vkCreateFramebuffer: Framebuffer attachment info (%d) conflicts with the image's " "IMAGE_USAGE flags (%s).", attachments[attach].attachment, string_VkImageUsageFlagBits(usage_flag)); } } } } } } } return skip; } bool CoreChecks::ValidateFramebufferCreateInfo(const VkFramebufferCreateInfo *pCreateInfo) const { bool skip = false; const VkFramebufferAttachmentsCreateInfo *framebuffer_attachments_create_info = LvlFindInChain<VkFramebufferAttachmentsCreateInfo>(pCreateInfo->pNext); if ((pCreateInfo->flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) != 0) { if (!enabled_features.core12.imagelessFramebuffer) { skip |= LogError(device, "VUID-VkFramebufferCreateInfo-flags-03189", "vkCreateFramebuffer(): VkFramebufferCreateInfo flags includes VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT, " "but the imagelessFramebuffer feature is not enabled."); } if (framebuffer_attachments_create_info == nullptr) { skip |= LogError(device, "VUID-VkFramebufferCreateInfo-flags-03190", "vkCreateFramebuffer(): VkFramebufferCreateInfo flags includes VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT, " "but no instance of VkFramebufferAttachmentsCreateInfo is present in the pNext chain."); } else { if (framebuffer_attachments_create_info->attachmentImageInfoCount != 0 && framebuffer_attachments_create_info->attachmentImageInfoCount != pCreateInfo->attachmentCount) { skip |= LogError(device, "VUID-VkFramebufferCreateInfo-flags-03191", "vkCreateFramebuffer(): VkFramebufferCreateInfo attachmentCount is %u, but " "VkFramebufferAttachmentsCreateInfo attachmentImageInfoCount is %u.", pCreateInfo->attachmentCount, framebuffer_attachments_create_info->attachmentImageInfoCount); } } } if (framebuffer_attachments_create_info) { for (uint32_t i = 0; i < framebuffer_attachments_create_info->attachmentImageInfoCount; ++i) { if (framebuffer_attachments_create_info->pAttachmentImageInfos[i].pNext != nullptr) { skip |= LogError(device, "VUID-VkFramebufferAttachmentImageInfo-pNext-pNext", "vkCreateFramebuffer(): VkFramebufferAttachmentsCreateInfo[%" PRIu32 "].pNext is not NULL.", i); } } } auto rp_state = GetRenderPassState(pCreateInfo->renderPass); if (rp_state) { const VkRenderPassCreateInfo2 *rpci = rp_state->createInfo.ptr(); if (rpci->attachmentCount != pCreateInfo->attachmentCount) { skip |= LogError(pCreateInfo->renderPass, "VUID-VkFramebufferCreateInfo-attachmentCount-00876", "vkCreateFramebuffer(): VkFramebufferCreateInfo attachmentCount of %u does not match attachmentCount " "of %u of %s being used to create Framebuffer.", pCreateInfo->attachmentCount, rpci->attachmentCount, report_data->FormatHandle(pCreateInfo->renderPass).c_str()); } else { // attachmentCounts match, so make sure corresponding attachment details line up if ((pCreateInfo->flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) == 0) { const VkImageView *image_views = pCreateInfo->pAttachments; for (uint32_t i = 0; i < pCreateInfo->attachmentCount; ++i) { auto view_state = GetImageViewState(image_views[i]); if (view_state == nullptr) { skip |= LogError( image_views[i], "VUID-VkFramebufferCreateInfo-flags-02778", "vkCreateFramebuffer(): VkFramebufferCreateInfo attachment #%u is not a valid VkImageView.", i); } else { auto &ivci = view_state->create_info; auto &subresource_range = view_state->normalized_subresource_range; if (ivci.format != rpci->pAttachments[i].format) { skip |= LogError( pCreateInfo->renderPass, "VUID-VkFramebufferCreateInfo-pAttachments-00880", "vkCreateFramebuffer(): VkFramebufferCreateInfo attachment #%u has format of %s that does not " "match the format of %s used by the corresponding attachment for %s.", i, string_VkFormat(ivci.format), string_VkFormat(rpci->pAttachments[i].format), report_data->FormatHandle(pCreateInfo->renderPass).c_str()); } const VkImageCreateInfo *ici = &GetImageState(ivci.image)->createInfo; if (ici->samples != rpci->pAttachments[i].samples) { skip |= LogError(pCreateInfo->renderPass, "VUID-VkFramebufferCreateInfo-pAttachments-00881", "vkCreateFramebuffer(): VkFramebufferCreateInfo attachment #%u has %s samples that do not " "match the %s " "samples used by the corresponding attachment for %s.", i, string_VkSampleCountFlagBits(ici->samples), string_VkSampleCountFlagBits(rpci->pAttachments[i].samples), report_data->FormatHandle(pCreateInfo->renderPass).c_str()); } // Verify that image memory is valid auto image_data = GetImageState(ivci.image); skip |= ValidateMemoryIsBoundToImage(image_data, "vkCreateFramebuffer()", "UNASSIGNED-CoreValidation-BoundResourceFreedMemoryAccess"); // Verify that view only has a single mip level if (subresource_range.levelCount != 1) { skip |= LogError( device, "VUID-VkFramebufferCreateInfo-pAttachments-00883", "vkCreateFramebuffer(): VkFramebufferCreateInfo attachment #%u has mip levelCount of %u but " "only a single mip level (levelCount == 1) is allowed when creating a Framebuffer.", i, subresource_range.levelCount); } const uint32_t mip_level = subresource_range.baseMipLevel; uint32_t mip_width = max(1u, ici->extent.width >> mip_level); uint32_t mip_height = max(1u, ici->extent.height >> mip_level); bool used_as_input_color_resolve_depth_stencil_attachment = false; bool used_as_fragment_shading_rate_attachment = false; bool fsr_non_zero_viewmasks = false; for (uint32_t j = 0; j < rpci->subpassCount; ++j) { const VkSubpassDescription2 &subpass = rpci->pSubpasses[j]; uint32_t highest_view_bit = 0; for (uint32_t k = 0; k < 32; ++k) { if (((subpass.viewMask >> k) & 1) != 0) { highest_view_bit = k; } } for (uint32_t k = 0; k < rpci->pSubpasses[j].inputAttachmentCount; ++k) { if (subpass.pInputAttachments[k].attachment == i) { used_as_input_color_resolve_depth_stencil_attachment = true; break; } } for (uint32_t k = 0; k < rpci->pSubpasses[j].colorAttachmentCount; ++k) { if (subpass.pColorAttachments[k].attachment == i || (subpass.pResolveAttachments && subpass.pResolveAttachments[k].attachment == i)) { used_as_input_color_resolve_depth_stencil_attachment = true; break; } } if (subpass.pDepthStencilAttachment && subpass.pDepthStencilAttachment->attachment == i) { used_as_input_color_resolve_depth_stencil_attachment = true; } if (used_as_input_color_resolve_depth_stencil_attachment) { if (subresource_range.layerCount <= highest_view_bit) { skip |= LogError( device, "VUID-VkFramebufferCreateInfo-renderPass-04536", "vkCreateFramebuffer(): VkFramebufferCreateInfo attachment #%u has a layer count (%u) " "less than or equal to the highest bit in the view mask (%u) of subpass %u.", i, subresource_range.layerCount, highest_view_bit, j); } } if (enabled_features.fragment_shading_rate_features.attachmentFragmentShadingRate) { const VkFragmentShadingRateAttachmentInfoKHR *fsr_attachment; fsr_attachment = LvlFindInChain<VkFragmentShadingRateAttachmentInfoKHR>(subpass.pNext); if (fsr_attachment && fsr_attachment->pFragmentShadingRateAttachment && fsr_attachment->pFragmentShadingRateAttachment->attachment == i) { used_as_fragment_shading_rate_attachment = true; if ((mip_width * fsr_attachment->shadingRateAttachmentTexelSize.width) < pCreateInfo->width) { skip |= LogError(device, "VUID-VkFramebufferCreateInfo-flags-04539", "vkCreateFramebuffer(): VkFramebufferCreateInfo attachment #%u mip level " "%u is used as a " "fragment shading rate attachment in subpass %u, but the product of its " "width (%u) and the " "specified shading rate texel width (%u) are smaller than the " "corresponding framebuffer width (%u).", i, subresource_range.baseMipLevel, j, mip_width, fsr_attachment->shadingRateAttachmentTexelSize.width, pCreateInfo->width); } if ((mip_height * fsr_attachment->shadingRateAttachmentTexelSize.height) < pCreateInfo->height) { skip |= LogError(device, "VUID-VkFramebufferCreateInfo-flags-04540", "vkCreateFramebuffer(): VkFramebufferCreateInfo attachment #%u mip level %u " "is used as a " "fragment shading rate attachment in subpass %u, but the product of its " "height (%u) and the " "specified shading rate texel height (%u) are smaller than the corresponding " "framebuffer height (%u).", i, subresource_range.baseMipLevel, j, mip_height, fsr_attachment->shadingRateAttachmentTexelSize.height, pCreateInfo->height); } if (highest_view_bit != 0) { fsr_non_zero_viewmasks = true; } if (subresource_range.layerCount <= highest_view_bit) { skip |= LogError( device, "VUID-VkFramebufferCreateInfo-flags-04537", "vkCreateFramebuffer(): VkFramebufferCreateInfo attachment #%u has a layer count (%u) " "less than or equal to the highest bit in the view mask (%u) of subpass %u.", i, subresource_range.layerCount, highest_view_bit, j); } } } } if (enabled_features.fragment_density_map_features.fragmentDensityMap) { const VkRenderPassFragmentDensityMapCreateInfoEXT *fdm_attachment; fdm_attachment = LvlFindInChain<VkRenderPassFragmentDensityMapCreateInfoEXT>(rpci->pNext); if (fdm_attachment && fdm_attachment->fragmentDensityMapAttachment.attachment == i) { uint32_t ceiling_width = static_cast<uint32_t>(ceil( static_cast<float>(pCreateInfo->width) / std::max(static_cast<float>( phys_dev_ext_props.fragment_density_map_props.maxFragmentDensityTexelSize.width), 1.0f))); if (mip_width < ceiling_width) { skip |= LogError( device, "VUID-VkFramebufferCreateInfo-pAttachments-02555", "vkCreateFramebuffer(): VkFramebufferCreateInfo attachment #%u mip level %u has width " "smaller than the corresponding the ceiling of framebuffer width / " "maxFragmentDensityTexelSize.width " "Here are the respective dimensions for attachment #%u, the ceiling value:\n " "attachment #%u, framebuffer:\n" "width: %u, the ceiling value: %u\n", i, subresource_range.baseMipLevel, i, i, mip_width, ceiling_width); } uint32_t ceiling_height = static_cast<uint32_t>(ceil( static_cast<float>(pCreateInfo->height) / std::max(static_cast<float>( phys_dev_ext_props.fragment_density_map_props.maxFragmentDensityTexelSize.height), 1.0f))); if (mip_height < ceiling_height) { skip |= LogError( device, "VUID-VkFramebufferCreateInfo-pAttachments-02556", "vkCreateFramebuffer(): VkFramebufferCreateInfo attachment #%u mip level %u has height " "smaller than the corresponding the ceiling of framebuffer height / " "maxFragmentDensityTexelSize.height " "Here are the respective dimensions for attachment #%u, the ceiling value:\n " "attachment #%u, framebuffer:\n" "height: %u, the ceiling value: %u\n", i, subresource_range.baseMipLevel, i, i, mip_height, ceiling_height); } } } if (used_as_input_color_resolve_depth_stencil_attachment) { if (mip_width < pCreateInfo->width) { skip |= LogError(device, "VUID-VkFramebufferCreateInfo-flags-04533", "vkCreateFramebuffer(): VkFramebufferCreateInfo attachment #%u mip level %u has " "width (%u) smaller than the corresponding framebuffer width (%u).", i, mip_level, mip_width, pCreateInfo->width); } if (mip_height < pCreateInfo->height) { skip |= LogError(device, "VUID-VkFramebufferCreateInfo-flags-04534", "vkCreateFramebuffer(): VkFramebufferCreateInfo attachment #%u mip level %u has " "height (%u) smaller than the corresponding framebuffer height (%u).", i, mip_level, mip_height, pCreateInfo->height); } if (subresource_range.layerCount < pCreateInfo->layers) { skip |= LogError(device, "VUID-VkFramebufferCreateInfo-flags-04535", "vkCreateFramebuffer(): VkFramebufferCreateInfo attachment #%u has a layer count (%u) " "smaller than the corresponding framebuffer layer count (%u).", i, subresource_range.layerCount, pCreateInfo->layers); } } if (used_as_fragment_shading_rate_attachment && !fsr_non_zero_viewmasks) { if (subresource_range.layerCount != 1 && subresource_range.layerCount < pCreateInfo->layers) { skip |= LogError(device, "VUID-VkFramebufferCreateInfo-flags-04538", "vkCreateFramebuffer(): VkFramebufferCreateInfo attachment #%u has a layer count (%u) " "smaller than the corresponding framebuffer layer count (%u).", i, subresource_range.layerCount, pCreateInfo->layers); } } if (IsIdentitySwizzle(ivci.components) == false) { skip |= LogError( device, "VUID-VkFramebufferCreateInfo-pAttachments-00884", "vkCreateFramebuffer(): VkFramebufferCreateInfo attachment #%u has non-identy swizzle. All " "framebuffer attachments must have been created with the identity swizzle. Here are the actual " "swizzle values:\n" "r swizzle = %s\n" "g swizzle = %s\n" "b swizzle = %s\n" "a swizzle = %s\n", i, string_VkComponentSwizzle(ivci.components.r), string_VkComponentSwizzle(ivci.components.g), string_VkComponentSwizzle(ivci.components.b), string_VkComponentSwizzle(ivci.components.a)); } if ((ivci.viewType == VK_IMAGE_VIEW_TYPE_2D) || (ivci.viewType == VK_IMAGE_VIEW_TYPE_2D)) { const auto image_state = GetImageState(ivci.image); if (image_state->createInfo.imageType == VK_IMAGE_TYPE_3D) { if (FormatIsDepthOrStencil(ivci.format)) { LogObjectList objlist(device); objlist.add(ivci.image); skip |= LogError( objlist, "VUID-VkFramebufferCreateInfo-pAttachments-00891", "vkCreateFramebuffer(): VkFramebufferCreateInfo attachment #%u has an image view type of " "%s " "which was taken from image %s of type VK_IMAGE_TYPE_3D, but the image view format is a " "depth/stencil format %s", i, string_VkImageViewType(ivci.viewType), report_data->FormatHandle(ivci.image).c_str(), string_VkFormat(ivci.format)); } } } if (ivci.viewType == VK_IMAGE_VIEW_TYPE_3D) { LogObjectList objlist(device); objlist.add(image_views[i]); skip |= LogError(objlist, "VUID-VkFramebufferCreateInfo-flags-04113", "vkCreateFramebuffer(): VkFramebufferCreateInfo attachment #%u has an image view type " "of VK_IMAGE_VIEW_TYPE_3D", i); } } } } else if (framebuffer_attachments_create_info) { // VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT is set for (uint32_t i = 0; i < pCreateInfo->attachmentCount; ++i) { auto &aii = framebuffer_attachments_create_info->pAttachmentImageInfos[i]; bool format_found = false; for (uint32_t j = 0; j < aii.viewFormatCount; ++j) { if (aii.pViewFormats[j] == rpci->pAttachments[i].format) { format_found = true; } } if (!format_found) { skip |= LogError(pCreateInfo->renderPass, "VUID-VkFramebufferCreateInfo-flags-03205", "vkCreateFramebuffer(): VkFramebufferCreateInfo attachment info #%u does not include " "format %s used " "by the corresponding attachment for renderPass (%s).", i, string_VkFormat(rpci->pAttachments[i].format), report_data->FormatHandle(pCreateInfo->renderPass).c_str()); } bool used_as_input_color_resolve_depth_stencil_attachment = false; bool used_as_fragment_shading_rate_attachment = false; bool fsr_non_zero_viewmasks = false; for (uint32_t j = 0; j < rpci->subpassCount; ++j) { const VkSubpassDescription2 &subpass = rpci->pSubpasses[j]; uint32_t highest_view_bit = 0; for (int k = 0; k < 32; ++k) { if (((subpass.viewMask >> k) & 1) != 0) { highest_view_bit = k; } } for (uint32_t k = 0; k < rpci->pSubpasses[j].inputAttachmentCount; ++k) { if (subpass.pInputAttachments[k].attachment == i) { used_as_input_color_resolve_depth_stencil_attachment = true; break; } } for (uint32_t k = 0; k < rpci->pSubpasses[j].colorAttachmentCount; ++k) { if (subpass.pColorAttachments[k].attachment == i || (subpass.pResolveAttachments && subpass.pResolveAttachments[k].attachment == i)) { used_as_input_color_resolve_depth_stencil_attachment = true; break; } } if (subpass.pDepthStencilAttachment && subpass.pDepthStencilAttachment->attachment == i) { used_as_input_color_resolve_depth_stencil_attachment = true; } if (enabled_features.fragment_shading_rate_features.attachmentFragmentShadingRate) { const VkFragmentShadingRateAttachmentInfoKHR *fsr_attachment; fsr_attachment = LvlFindInChain<VkFragmentShadingRateAttachmentInfoKHR>(subpass.pNext); if (fsr_attachment && fsr_attachment->pFragmentShadingRateAttachment->attachment == i) { used_as_fragment_shading_rate_attachment = true; if ((aii.width * fsr_attachment->shadingRateAttachmentTexelSize.width) < pCreateInfo->width) { skip |= LogError( device, "VUID-VkFramebufferCreateInfo-flags-04543", "vkCreateFramebuffer(): VkFramebufferCreateInfo attachment #%u is used as a " "fragment shading rate attachment in subpass %u, but the product of its width (%u) and the " "specified shading rate texel width (%u) are smaller than the corresponding framebuffer " "width (%u).", i, j, aii.width, fsr_attachment->shadingRateAttachmentTexelSize.width, pCreateInfo->width); } if ((aii.height * fsr_attachment->shadingRateAttachmentTexelSize.height) < pCreateInfo->height) { skip |= LogError(device, "VUID-VkFramebufferCreateInfo-flags-04544", "vkCreateFramebuffer(): VkFramebufferCreateInfo attachment #%u is used as a " "fragment shading rate attachment in subpass %u, but the product of its " "height (%u) and the " "specified shading rate texel height (%u) are smaller than the corresponding " "framebuffer height (%u).", i, j, aii.height, fsr_attachment->shadingRateAttachmentTexelSize.height, pCreateInfo->height); } if (highest_view_bit != 0) { fsr_non_zero_viewmasks = true; } if (aii.layerCount != 1 && aii.layerCount <= highest_view_bit) { skip |= LogError( device, kVUIDUndefined, "vkCreateFramebuffer(): VkFramebufferCreateInfo attachment #%u has a layer count (%u) " "less than or equal to the highest bit in the view mask (%u) of subpass %u.", i, aii.layerCount, highest_view_bit, j); } } } } if (used_as_input_color_resolve_depth_stencil_attachment) { if (aii.width < pCreateInfo->width) { skip |= LogError( device, "VUID-VkFramebufferCreateInfo-flags-04541", "vkCreateFramebuffer(): VkFramebufferCreateInfo attachment info #%u has a width of only #%u, " "but framebuffer has a width of #%u.", i, aii.width, pCreateInfo->width); } if (aii.height < pCreateInfo->height) { skip |= LogError( device, "VUID-VkFramebufferCreateInfo-flags-04542", "vkCreateFramebuffer(): VkFramebufferCreateInfo attachment info #%u has a height of only #%u, " "but framebuffer has a height of #%u.", i, aii.height, pCreateInfo->height); } const char *mismatched_layers_no_multiview_vuid = device_extensions.vk_khr_multiview ? "VUID-VkFramebufferCreateInfo-renderPass-04546" : "VUID-VkFramebufferCreateInfo-flags-04547"; if ((rpci->subpassCount == 0) || (rpci->pSubpasses[0].viewMask == 0)) { if (aii.layerCount < pCreateInfo->layers) { skip |= LogError( device, mismatched_layers_no_multiview_vuid, "vkCreateFramebuffer(): VkFramebufferCreateInfo attachment info #%u has only #%u layers, " "but framebuffer has #%u layers.", i, aii.layerCount, pCreateInfo->layers); } } } if (used_as_fragment_shading_rate_attachment && !fsr_non_zero_viewmasks) { if (aii.layerCount != 1 && aii.layerCount < pCreateInfo->layers) { skip |= LogError(device, "VUID-VkFramebufferCreateInfo-flags-04545", "vkCreateFramebuffer(): VkFramebufferCreateInfo attachment #%u has a layer count (%u) " "smaller than the corresponding framebuffer layer count (%u).", i, aii.layerCount, pCreateInfo->layers); } } } // Validate image usage uint32_t attachment_index = VK_ATTACHMENT_UNUSED; for (uint32_t i = 0; i < rpci->subpassCount; ++i) { skip |= MatchUsage(rpci->pSubpasses[i].colorAttachmentCount, rpci->pSubpasses[i].pColorAttachments, pCreateInfo, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, "VUID-VkFramebufferCreateInfo-flags-03201"); skip |= MatchUsage(rpci->pSubpasses[i].colorAttachmentCount, rpci->pSubpasses[i].pResolveAttachments, pCreateInfo, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, "VUID-VkFramebufferCreateInfo-flags-03201"); skip |= MatchUsage(1, rpci->pSubpasses[i].pDepthStencilAttachment, pCreateInfo, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, "VUID-VkFramebufferCreateInfo-flags-03202"); skip |= MatchUsage(rpci->pSubpasses[i].inputAttachmentCount, rpci->pSubpasses[i].pInputAttachments, pCreateInfo, VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT, "VUID-VkFramebufferCreateInfo-flags-03204"); const VkSubpassDescriptionDepthStencilResolve *depth_stencil_resolve = LvlFindInChain<VkSubpassDescriptionDepthStencilResolve>(rpci->pSubpasses[i].pNext); if (device_extensions.vk_khr_depth_stencil_resolve && depth_stencil_resolve != nullptr) { skip |= MatchUsage(1, depth_stencil_resolve->pDepthStencilResolveAttachment, pCreateInfo, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, "VUID-VkFramebufferCreateInfo-flags-03203"); } const VkFragmentShadingRateAttachmentInfoKHR *fragment_shading_rate_attachment_info = LvlFindInChain<VkFragmentShadingRateAttachmentInfoKHR>(rpci->pSubpasses[i].pNext); if (enabled_features.fragment_shading_rate_features.attachmentFragmentShadingRate && fragment_shading_rate_attachment_info != nullptr) { skip |= MatchUsage(1, fragment_shading_rate_attachment_info->pFragmentShadingRateAttachment, pCreateInfo, VK_IMAGE_USAGE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR, "VUID-VkFramebufferCreateInfo-flags-04549"); } } if (device_extensions.vk_khr_multiview) { if ((rpci->subpassCount > 0) && (rpci->pSubpasses[0].viewMask != 0)) { for (uint32_t i = 0; i < rpci->subpassCount; ++i) { const VkSubpassDescriptionDepthStencilResolve *depth_stencil_resolve = LvlFindInChain<VkSubpassDescriptionDepthStencilResolve>(rpci->pSubpasses[i].pNext); uint32_t view_bits = rpci->pSubpasses[i].viewMask; uint32_t highest_view_bit = 0; for (int j = 0; j < 32; ++j) { if (((view_bits >> j) & 1) != 0) { highest_view_bit = j; } } for (uint32_t j = 0; j < rpci->pSubpasses[i].colorAttachmentCount; ++j) { attachment_index = rpci->pSubpasses[i].pColorAttachments[j].attachment; if (attachment_index != VK_ATTACHMENT_UNUSED) { uint32_t layer_count = framebuffer_attachments_create_info->pAttachmentImageInfos[attachment_index].layerCount; if (layer_count <= highest_view_bit) { skip |= LogError( pCreateInfo->renderPass, "VUID-VkFramebufferCreateInfo-renderPass-03198", "vkCreateFramebuffer(): VkFramebufferCreateInfo attachment info %u " "only specifies %u layers, but the view mask for subpass %u in renderPass (%s) " "includes layer %u, with that attachment specified as a color attachment %u.", attachment_index, layer_count, i, report_data->FormatHandle(pCreateInfo->renderPass).c_str(), highest_view_bit, j); } } if (rpci->pSubpasses[i].pResolveAttachments) { attachment_index = rpci->pSubpasses[i].pResolveAttachments[j].attachment; if (attachment_index != VK_ATTACHMENT_UNUSED) { uint32_t layer_count = framebuffer_attachments_create_info->pAttachmentImageInfos[attachment_index].layerCount; if (layer_count <= highest_view_bit) { skip |= LogError( pCreateInfo->renderPass, "VUID-VkFramebufferCreateInfo-renderPass-03198", "vkCreateFramebuffer(): VkFramebufferCreateInfo attachment info %u " "only specifies %u layers, but the view mask for subpass %u in renderPass (%s) " "includes layer %u, with that attachment specified as a resolve attachment %u.", attachment_index, layer_count, i, report_data->FormatHandle(pCreateInfo->renderPass).c_str(), highest_view_bit, j); } } } } for (uint32_t j = 0; j < rpci->pSubpasses[i].inputAttachmentCount; ++j) { attachment_index = rpci->pSubpasses[i].pInputAttachments[j].attachment; if (attachment_index != VK_ATTACHMENT_UNUSED) { uint32_t layer_count = framebuffer_attachments_create_info->pAttachmentImageInfos[attachment_index].layerCount; if (layer_count <= highest_view_bit) { skip |= LogError( pCreateInfo->renderPass, "VUID-VkFramebufferCreateInfo-renderPass-03198", "vkCreateFramebuffer(): VkFramebufferCreateInfo attachment info %u " "only specifies %u layers, but the view mask for subpass %u in renderPass (%s) " "includes layer %u, with that attachment specified as an input attachment %u.", attachment_index, layer_count, i, report_data->FormatHandle(pCreateInfo->renderPass).c_str(), highest_view_bit, j); } } } if (rpci->pSubpasses[i].pDepthStencilAttachment != nullptr) { attachment_index = rpci->pSubpasses[i].pDepthStencilAttachment->attachment; if (attachment_index != VK_ATTACHMENT_UNUSED) { uint32_t layer_count = framebuffer_attachments_create_info->pAttachmentImageInfos[attachment_index].layerCount; if (layer_count <= highest_view_bit) { skip |= LogError( pCreateInfo->renderPass, "VUID-VkFramebufferCreateInfo-renderPass-03198", "vkCreateFramebuffer(): VkFramebufferCreateInfo attachment info %u " "only specifies %u layers, but the view mask for subpass %u in renderPass (%s) " "includes layer %u, with that attachment specified as a depth/stencil attachment.", attachment_index, layer_count, i, report_data->FormatHandle(pCreateInfo->renderPass).c_str(), highest_view_bit); } } if (device_extensions.vk_khr_depth_stencil_resolve && depth_stencil_resolve != nullptr && depth_stencil_resolve->pDepthStencilResolveAttachment != nullptr) { attachment_index = depth_stencil_resolve->pDepthStencilResolveAttachment->attachment; if (attachment_index != VK_ATTACHMENT_UNUSED) { uint32_t layer_count = framebuffer_attachments_create_info->pAttachmentImageInfos[attachment_index].layerCount; if (layer_count <= highest_view_bit) { skip |= LogError( pCreateInfo->renderPass, "VUID-VkFramebufferCreateInfo-renderPass-03198", "vkCreateFramebuffer(): VkFramebufferCreateInfo attachment info %u " "only specifies %u layers, but the view mask for subpass %u in renderPass (%s) " "includes layer %u, with that attachment specified as a depth/stencil resolve " "attachment.", attachment_index, layer_count, i, report_data->FormatHandle(pCreateInfo->renderPass).c_str(), highest_view_bit); } } } } } } } } if ((pCreateInfo->flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) == 0) { // Verify correct attachment usage flags for (uint32_t subpass = 0; subpass < rpci->subpassCount; subpass++) { const VkSubpassDescription2 &subpass_description = rpci->pSubpasses[subpass]; // Verify input attachments: skip |= MatchUsage(subpass_description.inputAttachmentCount, subpass_description.pInputAttachments, pCreateInfo, VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT, "VUID-VkFramebufferCreateInfo-pAttachments-00879"); // Verify color attachments: skip |= MatchUsage(subpass_description.colorAttachmentCount, subpass_description.pColorAttachments, pCreateInfo, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, "VUID-VkFramebufferCreateInfo-pAttachments-00877"); // Verify depth/stencil attachments: skip |= MatchUsage(1, subpass_description.pDepthStencilAttachment, pCreateInfo, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, "VUID-VkFramebufferCreateInfo-pAttachments-02633"); // Verify depth/stecnil resolve if (device_extensions.vk_khr_depth_stencil_resolve) { const VkSubpassDescriptionDepthStencilResolve *ds_resolve = LvlFindInChain<VkSubpassDescriptionDepthStencilResolve>(subpass_description.pNext); if (ds_resolve) { skip |= MatchUsage(1, ds_resolve->pDepthStencilResolveAttachment, pCreateInfo, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, "VUID-VkFramebufferCreateInfo-pAttachments-02634"); } } // Verify fragment shading rate attachments if (enabled_features.fragment_shading_rate_features.attachmentFragmentShadingRate) { const VkFragmentShadingRateAttachmentInfoKHR *fragment_shading_rate_attachment_info = LvlFindInChain<VkFragmentShadingRateAttachmentInfoKHR>(subpass_description.pNext); if (fragment_shading_rate_attachment_info) { skip |= MatchUsage(1, fragment_shading_rate_attachment_info->pFragmentShadingRateAttachment, pCreateInfo, VK_IMAGE_USAGE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR, "VUID-VkFramebufferCreateInfo-flags-04548"); } } } } bool b_has_non_zero_view_masks = false; for (uint32_t i = 0; i < rpci->subpassCount; ++i) { if (rpci->pSubpasses[i].viewMask != 0) { b_has_non_zero_view_masks = true; break; } } if (b_has_non_zero_view_masks && pCreateInfo->layers != 1) { skip |= LogError(pCreateInfo->renderPass, "VUID-VkFramebufferCreateInfo-renderPass-02531", "vkCreateFramebuffer(): VkFramebufferCreateInfo has #%u layers but " "renderPass (%s) was specified with non-zero view masks\n", pCreateInfo->layers, report_data->FormatHandle(pCreateInfo->renderPass).c_str()); } } } // Verify FB dimensions are within physical device limits if (pCreateInfo->width > phys_dev_props.limits.maxFramebufferWidth) { skip |= LogError(device, "VUID-VkFramebufferCreateInfo-width-00886", "vkCreateFramebuffer(): Requested VkFramebufferCreateInfo width exceeds physical device limits. Requested " "width: %u, device max: %u\n", pCreateInfo->width, phys_dev_props.limits.maxFramebufferWidth); } if (pCreateInfo->height > phys_dev_props.limits.maxFramebufferHeight) { skip |= LogError(device, "VUID-VkFramebufferCreateInfo-height-00888", "vkCreateFramebuffer(): Requested VkFramebufferCreateInfo height exceeds physical device limits. Requested " "height: %u, device max: %u\n", pCreateInfo->height, phys_dev_props.limits.maxFramebufferHeight); } if (pCreateInfo->layers > phys_dev_props.limits.maxFramebufferLayers) { skip |= LogError(device, "VUID-VkFramebufferCreateInfo-layers-00890", "vkCreateFramebuffer(): Requested VkFramebufferCreateInfo layers exceeds physical device limits. Requested " "layers: %u, device max: %u\n", pCreateInfo->layers, phys_dev_props.limits.maxFramebufferLayers); } // Verify FB dimensions are greater than zero if (pCreateInfo->width <= 0) { skip |= LogError(device, "VUID-VkFramebufferCreateInfo-width-00885", "vkCreateFramebuffer(): Requested VkFramebufferCreateInfo width must be greater than zero."); } if (pCreateInfo->height <= 0) { skip |= LogError(device, "VUID-VkFramebufferCreateInfo-height-00887", "vkCreateFramebuffer(): Requested VkFramebufferCreateInfo height must be greater than zero."); } if (pCreateInfo->layers <= 0) { skip |= LogError(device, "VUID-VkFramebufferCreateInfo-layers-00889", "vkCreateFramebuffer(): Requested VkFramebufferCreateInfo layers must be greater than zero."); } return skip; } bool CoreChecks::PreCallValidateCreateFramebuffer(VkDevice device, const VkFramebufferCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkFramebuffer *pFramebuffer) const { // TODO : Verify that renderPass FB is created with is compatible with FB bool skip = false; skip |= ValidateFramebufferCreateInfo(pCreateInfo); return skip; } static bool FindDependency(const uint32_t index, const uint32_t dependent, const std::vector<DAGNode> &subpass_to_node, layer_data::unordered_set<uint32_t> &processed_nodes) { // If we have already checked this node we have not found a dependency path so return false. if (processed_nodes.count(index)) return false; processed_nodes.insert(index); const DAGNode &node = subpass_to_node[index]; // Look for a dependency path. If one exists return true else recurse on the previous nodes. if (std::find(node.prev.begin(), node.prev.end(), dependent) == node.prev.end()) { for (auto elem : node.prev) { if (FindDependency(elem, dependent, subpass_to_node, processed_nodes)) return true; } } else { return true; } return false; } bool CoreChecks::IsImageLayoutReadOnly(VkImageLayout layout) const { if ((layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL) || (layout == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL) || (layout == VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL) || (layout == VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL)) { return true; } return false; } bool CoreChecks::CheckDependencyExists(const VkRenderPass renderpass, const uint32_t subpass, const VkImageLayout layout, const std::vector<SubpassLayout> &dependent_subpasses, const std::vector<DAGNode> &subpass_to_node, bool &skip) const { bool result = true; bool b_image_layout_read_only = IsImageLayoutReadOnly(layout); // Loop through all subpasses that share the same attachment and make sure a dependency exists for (uint32_t k = 0; k < dependent_subpasses.size(); ++k) { const SubpassLayout &sp = dependent_subpasses[k]; if (subpass == sp.index) continue; if (b_image_layout_read_only && IsImageLayoutReadOnly(sp.layout)) continue; const DAGNode &node = subpass_to_node[subpass]; // Check for a specified dependency between the two nodes. If one exists we are done. auto prev_elem = std::find(node.prev.begin(), node.prev.end(), sp.index); auto next_elem = std::find(node.next.begin(), node.next.end(), sp.index); if (prev_elem == node.prev.end() && next_elem == node.next.end()) { // If no dependency exits an implicit dependency still might. If not, throw an error. layer_data::unordered_set<uint32_t> processed_nodes; if (!(FindDependency(subpass, sp.index, subpass_to_node, processed_nodes) || FindDependency(sp.index, subpass, subpass_to_node, processed_nodes))) { skip |= LogError(renderpass, kVUID_Core_DrawState_InvalidRenderpass, "A dependency between subpasses %d and %d must exist but one is not specified.", subpass, sp.index); result = false; } } } return result; } bool CoreChecks::CheckPreserved(const VkRenderPass renderpass, const VkRenderPassCreateInfo2 *pCreateInfo, const int index, const uint32_t attachment, const std::vector<DAGNode> &subpass_to_node, int depth, bool &skip) const { const DAGNode &node = subpass_to_node[index]; // If this node writes to the attachment return true as next nodes need to preserve the attachment. const VkSubpassDescription2 &subpass = pCreateInfo->pSubpasses[index]; for (uint32_t j = 0; j < subpass.colorAttachmentCount; ++j) { if (attachment == subpass.pColorAttachments[j].attachment) return true; } for (uint32_t j = 0; j < subpass.inputAttachmentCount; ++j) { if (attachment == subpass.pInputAttachments[j].attachment) return true; } if (subpass.pDepthStencilAttachment && subpass.pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED) { if (attachment == subpass.pDepthStencilAttachment->attachment) return true; } bool result = false; // Loop through previous nodes and see if any of them write to the attachment. for (auto elem : node.prev) { result |= CheckPreserved(renderpass, pCreateInfo, elem, attachment, subpass_to_node, depth + 1, skip); } // If the attachment was written to by a previous node than this node needs to preserve it. if (result && depth > 0) { bool has_preserved = false; for (uint32_t j = 0; j < subpass.preserveAttachmentCount; ++j) { if (subpass.pPreserveAttachments[j] == attachment) { has_preserved = true; break; } } if (!has_preserved) { skip |= LogError(renderpass, kVUID_Core_DrawState_InvalidRenderpass, "Attachment %d is used by a later subpass and must be preserved in subpass %d.", attachment, index); } } return result; } template <class T> bool IsRangeOverlapping(T offset1, T size1, T offset2, T size2) { return (((offset1 + size1) > offset2) && ((offset1 + size1) < (offset2 + size2))) || ((offset1 > offset2) && (offset1 < (offset2 + size2))); } bool IsRegionOverlapping(VkImageSubresourceRange range1, VkImageSubresourceRange range2) { return (IsRangeOverlapping(range1.baseMipLevel, range1.levelCount, range2.baseMipLevel, range2.levelCount) && IsRangeOverlapping(range1.baseArrayLayer, range1.layerCount, range2.baseArrayLayer, range2.layerCount)); } bool CoreChecks::ValidateDependencies(FRAMEBUFFER_STATE const *framebuffer, RENDER_PASS_STATE const *renderPass) const { bool skip = false; auto const framebuffer_info = framebuffer->createInfo.ptr(); auto const create_info = renderPass->createInfo.ptr(); auto const &subpass_to_node = renderPass->subpassToNode; struct Attachment { std::vector<SubpassLayout> outputs; std::vector<SubpassLayout> inputs; std::vector<uint32_t> overlapping; }; std::vector<Attachment> attachments(create_info->attachmentCount); if (!(framebuffer_info->flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT)) { // Find overlapping attachments for (uint32_t i = 0; i < create_info->attachmentCount; ++i) { for (uint32_t j = i + 1; j < create_info->attachmentCount; ++j) { VkImageView viewi = framebuffer_info->pAttachments[i]; VkImageView viewj = framebuffer_info->pAttachments[j]; if (viewi == viewj) { attachments[i].overlapping.emplace_back(j); attachments[j].overlapping.emplace_back(i); continue; } auto view_state_i = GetImageViewState(viewi); auto view_state_j = GetImageViewState(viewj); if (!view_state_i || !view_state_j) { continue; } auto view_ci_i = view_state_i->create_info; auto view_ci_j = view_state_j->create_info; if (view_ci_i.image == view_ci_j.image && IsRegionOverlapping(view_ci_i.subresourceRange, view_ci_j.subresourceRange)) { attachments[i].overlapping.emplace_back(j); attachments[j].overlapping.emplace_back(i); continue; } auto image_data_i = GetImageState(view_ci_i.image); auto image_data_j = GetImageState(view_ci_j.image); if (!image_data_i || !image_data_j) { continue; } const auto *binding_i = image_data_i->Binding(); const auto *binding_j = image_data_j->Binding(); if (binding_i && binding_j && binding_i->mem_state == binding_j->mem_state && IsRangeOverlapping(binding_i->offset, binding_i->size, binding_j->offset, binding_j->size)) { attachments[i].overlapping.emplace_back(j); attachments[j].overlapping.emplace_back(i); } } } } // Find for each attachment the subpasses that use them. layer_data::unordered_set<uint32_t> attachment_indices; for (uint32_t i = 0; i < create_info->subpassCount; ++i) { const VkSubpassDescription2 &subpass = create_info->pSubpasses[i]; attachment_indices.clear(); for (uint32_t j = 0; j < subpass.inputAttachmentCount; ++j) { uint32_t attachment = subpass.pInputAttachments[j].attachment; if (attachment == VK_ATTACHMENT_UNUSED) continue; SubpassLayout sp = {i, subpass.pInputAttachments[j].layout}; attachments[attachment].inputs.emplace_back(sp); for (auto overlapping_attachment : attachments[attachment].overlapping) { attachments[overlapping_attachment].inputs.emplace_back(sp); } } for (uint32_t j = 0; j < subpass.colorAttachmentCount; ++j) { uint32_t attachment = subpass.pColorAttachments[j].attachment; if (attachment == VK_ATTACHMENT_UNUSED) continue; SubpassLayout sp = {i, subpass.pColorAttachments[j].layout}; attachments[attachment].outputs.emplace_back(sp); for (auto overlapping_attachment : attachments[attachment].overlapping) { attachments[overlapping_attachment].outputs.emplace_back(sp); } attachment_indices.insert(attachment); } if (subpass.pDepthStencilAttachment && subpass.pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED) { uint32_t attachment = subpass.pDepthStencilAttachment->attachment; SubpassLayout sp = {i, subpass.pDepthStencilAttachment->layout}; attachments[attachment].outputs.emplace_back(sp); for (auto overlapping_attachment : attachments[attachment].overlapping) { attachments[overlapping_attachment].outputs.emplace_back(sp); } if (attachment_indices.count(attachment)) { skip |= LogError(renderPass->renderPass(), kVUID_Core_DrawState_InvalidRenderpass, "Cannot use same attachment (%u) as both color and depth output in same subpass (%u).", attachment, i); } } } // If there is a dependency needed make sure one exists for (uint32_t i = 0; i < create_info->subpassCount; ++i) { const VkSubpassDescription2 &subpass = create_info->pSubpasses[i]; // If the attachment is an input then all subpasses that output must have a dependency relationship for (uint32_t j = 0; j < subpass.inputAttachmentCount; ++j) { uint32_t attachment = subpass.pInputAttachments[j].attachment; if (attachment == VK_ATTACHMENT_UNUSED) continue; CheckDependencyExists(renderPass->renderPass(), i, subpass.pInputAttachments[j].layout, attachments[attachment].outputs, subpass_to_node, skip); } // If the attachment is an output then all subpasses that use the attachment must have a dependency relationship for (uint32_t j = 0; j < subpass.colorAttachmentCount; ++j) { uint32_t attachment = subpass.pColorAttachments[j].attachment; if (attachment == VK_ATTACHMENT_UNUSED) continue; CheckDependencyExists(renderPass->renderPass(), i, subpass.pColorAttachments[j].layout, attachments[attachment].outputs, subpass_to_node, skip); CheckDependencyExists(renderPass->renderPass(), i, subpass.pColorAttachments[j].layout, attachments[attachment].inputs, subpass_to_node, skip); } if (subpass.pDepthStencilAttachment && subpass.pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED) { const uint32_t &attachment = subpass.pDepthStencilAttachment->attachment; CheckDependencyExists(renderPass->renderPass(), i, subpass.pDepthStencilAttachment->layout, attachments[attachment].outputs, subpass_to_node, skip); CheckDependencyExists(renderPass->renderPass(), i, subpass.pDepthStencilAttachment->layout, attachments[attachment].inputs, subpass_to_node, skip); } } // Loop through implicit dependencies, if this pass reads make sure the attachment is preserved for all passes after it was // written. for (uint32_t i = 0; i < create_info->subpassCount; ++i) { const VkSubpassDescription2 &subpass = create_info->pSubpasses[i]; for (uint32_t j = 0; j < subpass.inputAttachmentCount; ++j) { CheckPreserved(renderPass->renderPass(), create_info, i, subpass.pInputAttachments[j].attachment, subpass_to_node, 0, skip); } } return skip; } bool CoreChecks::ValidateRenderPassDAG(RenderPassCreateVersion rp_version, const VkRenderPassCreateInfo2 *pCreateInfo) const { bool skip = false; const char *vuid; const bool use_rp2 = (rp_version == RENDER_PASS_VERSION_2); for (uint32_t i = 0; i < pCreateInfo->dependencyCount; ++i) { const VkSubpassDependency2 &dependency = pCreateInfo->pDependencies[i]; auto latest_src_stage = sync_utils::GetLogicallyLatestGraphicsPipelineStage(dependency.srcStageMask); auto earliest_dst_stage = sync_utils::GetLogicallyEarliestGraphicsPipelineStage(dependency.dstStageMask); // The first subpass here serves as a good proxy for "is multiview enabled" - since all view masks need to be non-zero if // any are, which enables multiview. if (use_rp2 && (dependency.dependencyFlags & VK_DEPENDENCY_VIEW_LOCAL_BIT) && (pCreateInfo->pSubpasses[0].viewMask == 0)) { skip |= LogError( device, "VUID-VkRenderPassCreateInfo2-viewMask-03059", "Dependency %u specifies the VK_DEPENDENCY_VIEW_LOCAL_BIT, but multiview is not enabled for this render pass.", i); } else if (use_rp2 && !(dependency.dependencyFlags & VK_DEPENDENCY_VIEW_LOCAL_BIT) && dependency.viewOffset != 0) { skip |= LogError(device, "VUID-VkSubpassDependency2-dependencyFlags-03092", "Dependency %u specifies the VK_DEPENDENCY_VIEW_LOCAL_BIT, but also specifies a view offset of %u.", i, dependency.viewOffset); } else if (dependency.srcSubpass == VK_SUBPASS_EXTERNAL || dependency.dstSubpass == VK_SUBPASS_EXTERNAL) { if (dependency.srcSubpass == dependency.dstSubpass) { vuid = use_rp2 ? "VUID-VkSubpassDependency2-srcSubpass-03085" : "VUID-VkSubpassDependency-srcSubpass-00865"; skip |= LogError(device, vuid, "The src and dst subpasses in dependency %u are both external.", i); } else if (dependency.dependencyFlags & VK_DEPENDENCY_VIEW_LOCAL_BIT) { if (dependency.srcSubpass == VK_SUBPASS_EXTERNAL) { vuid = "VUID-VkSubpassDependency-dependencyFlags-02520"; } else { // dependency.dstSubpass == VK_SUBPASS_EXTERNAL vuid = "VUID-VkSubpassDependency-dependencyFlags-02521"; } if (use_rp2) { // Create render pass 2 distinguishes between source and destination external dependencies. if (dependency.srcSubpass == VK_SUBPASS_EXTERNAL) { vuid = "VUID-VkSubpassDependency2-dependencyFlags-03090"; } else { vuid = "VUID-VkSubpassDependency2-dependencyFlags-03091"; } } skip |= LogError(device, vuid, "Dependency %u specifies an external dependency but also specifies VK_DEPENDENCY_VIEW_LOCAL_BIT.", i); } } else if (dependency.srcSubpass > dependency.dstSubpass) { vuid = use_rp2 ? "VUID-VkSubpassDependency2-srcSubpass-03084" : "VUID-VkSubpassDependency-srcSubpass-00864"; skip |= LogError(device, vuid, "Dependency %u specifies a dependency from a later subpass (%u) to an earlier subpass (%u), which is " "disallowed to prevent cyclic dependencies.", i, dependency.srcSubpass, dependency.dstSubpass); } else if (dependency.srcSubpass == dependency.dstSubpass) { if (dependency.viewOffset != 0) { vuid = use_rp2 ? "VUID-VkSubpassDependency2-viewOffset-02530" : "VUID-VkRenderPassCreateInfo-pNext-01930"; skip |= LogError(device, vuid, "Dependency %u specifies a self-dependency but has a non-zero view offset of %u", i, dependency.viewOffset); } else if ((dependency.dependencyFlags | VK_DEPENDENCY_VIEW_LOCAL_BIT) != dependency.dependencyFlags && pCreateInfo->pSubpasses[dependency.srcSubpass].viewMask > 1) { vuid = use_rp2 ? "VUID-VkRenderPassCreateInfo2-pDependencies-03060" : "VUID-VkSubpassDependency-srcSubpass-00872"; skip |= LogError(device, vuid, "Dependency %u specifies a self-dependency for subpass %u with a non-zero view mask, but does not " "specify VK_DEPENDENCY_VIEW_LOCAL_BIT.", i, dependency.srcSubpass); } else if ((HasNonFramebufferStagePipelineStageFlags(dependency.srcStageMask) || HasNonFramebufferStagePipelineStageFlags(dependency.dstStageMask)) && (sync_utils::GetGraphicsPipelineStageLogicalOrdinal(latest_src_stage) > sync_utils::GetGraphicsPipelineStageLogicalOrdinal(earliest_dst_stage))) { vuid = use_rp2 ? "VUID-VkSubpassDependency2-srcSubpass-03087" : "VUID-VkSubpassDependency-srcSubpass-00867"; skip |= LogError( device, vuid, "Dependency %u specifies a self-dependency from logically-later stage (%s) to a logically-earlier stage (%s).", i, sync_utils::StringPipelineStageFlags(latest_src_stage).c_str(), sync_utils::StringPipelineStageFlags(earliest_dst_stage).c_str()); } else if ((HasNonFramebufferStagePipelineStageFlags(dependency.srcStageMask) == false) && (HasNonFramebufferStagePipelineStageFlags(dependency.dstStageMask) == false) && ((dependency.dependencyFlags & VK_DEPENDENCY_BY_REGION_BIT) == 0)) { vuid = use_rp2 ? "VUID-VkSubpassDependency2-srcSubpass-02245" : "VUID-VkSubpassDependency-srcSubpass-02243"; skip |= LogError(device, vuid, "Dependency %u specifies a self-dependency for subpass %u with both stages including a " "framebuffer-space stage, but does not specify VK_DEPENDENCY_BY_REGION_BIT in dependencyFlags.", i, dependency.srcSubpass); } } else if ((dependency.srcSubpass < dependency.dstSubpass) && ((pCreateInfo->pSubpasses[dependency.srcSubpass].flags & VK_SUBPASS_DESCRIPTION_SHADER_RESOLVE_BIT_QCOM) != 0)) { vuid = use_rp2 ? "VUID-VkRenderPassCreateInfo2-flags-04909" : "VUID-VkSubpassDescription-flags-03343"; skip |= LogError(device, vuid, "Dependency %u specifies that subpass %u has a dependency on a later subpass" "and includes VK_SUBPASS_DESCRIPTION_SHADER_RESOLVE_BIT_QCOM subpass flags.", i, dependency.srcSubpass); } } return skip; } bool CoreChecks::ValidateAttachmentIndex(RenderPassCreateVersion rp_version, uint32_t attachment, uint32_t attachment_count, const char *error_type, const char *function_name) const { bool skip = false; const bool use_rp2 = (rp_version == RENDER_PASS_VERSION_2); assert(attachment != VK_ATTACHMENT_UNUSED); if (attachment >= attachment_count) { const char *vuid = use_rp2 ? "VUID-VkRenderPassCreateInfo2-attachment-03051" : "VUID-VkRenderPassCreateInfo-attachment-00834"; skip |= LogError(device, vuid, "%s: %s attachment %d must be less than the total number of attachments %d.", function_name, error_type, attachment, attachment_count); } return skip; } enum AttachmentType { ATTACHMENT_COLOR = 1, ATTACHMENT_DEPTH = 2, ATTACHMENT_INPUT = 4, ATTACHMENT_PRESERVE = 8, ATTACHMENT_RESOLVE = 16, }; char const *StringAttachmentType(uint8_t type) { switch (type) { case ATTACHMENT_COLOR: return "color"; case ATTACHMENT_DEPTH: return "depth"; case ATTACHMENT_INPUT: return "input"; case ATTACHMENT_PRESERVE: return "preserve"; case ATTACHMENT_RESOLVE: return "resolve"; default: return "(multiple)"; } } bool CoreChecks::AddAttachmentUse(RenderPassCreateVersion rp_version, uint32_t subpass, std::vector<uint8_t> &attachment_uses, std::vector<VkImageLayout> &attachment_layouts, uint32_t attachment, uint8_t new_use, VkImageLayout new_layout) const { if (attachment >= attachment_uses.size()) return false; /* out of range, but already reported */ bool skip = false; auto &uses = attachment_uses[attachment]; const bool use_rp2 = (rp_version == RENDER_PASS_VERSION_2); const char *vuid; const char *const function_name = use_rp2 ? "vkCreateRenderPass2()" : "vkCreateRenderPass()"; if (uses & new_use) { if (attachment_layouts[attachment] != new_layout) { vuid = use_rp2 ? "VUID-VkSubpassDescription2-layout-02528" : "VUID-VkSubpassDescription-layout-02519"; skip |= LogError(device, vuid, "%s: subpass %u already uses attachment %u with a different image layout (%s vs %s).", function_name, subpass, attachment, string_VkImageLayout(attachment_layouts[attachment]), string_VkImageLayout(new_layout)); } } else if (((new_use & ATTACHMENT_COLOR) && (uses & ATTACHMENT_DEPTH)) || ((uses & ATTACHMENT_COLOR) && (new_use & ATTACHMENT_DEPTH))) { vuid = use_rp2 ? "VUID-VkSubpassDescription2-pDepthStencilAttachment-04440" : "VUID-VkSubpassDescription-pDepthStencilAttachment-04438"; skip |= LogError(device, vuid, "%s: subpass %u uses attachment %u as both %s and %s attachment.", function_name, subpass, attachment, StringAttachmentType(uses), StringAttachmentType(new_use)); } else if ((uses && (new_use & ATTACHMENT_PRESERVE)) || (new_use && (uses & ATTACHMENT_PRESERVE))) { vuid = use_rp2 ? "VUID-VkSubpassDescription2-pPreserveAttachments-03074" : "VUID-VkSubpassDescription-pPreserveAttachments-00854"; skip |= LogError(device, vuid, "%s: subpass %u uses attachment %u as both %s and %s attachment.", function_name, subpass, attachment, StringAttachmentType(uses), StringAttachmentType(new_use)); } else { attachment_layouts[attachment] = new_layout; uses |= new_use; } return skip; } // Handles attachment references regardless of type (input, color, depth, etc) // Input attachments have extra VUs associated with them bool CoreChecks::ValidateAttachmentReference(RenderPassCreateVersion rp_version, VkAttachmentReference2 reference, const VkFormat attachment_format, bool input, const char *error_type, const char *function_name) const { bool skip = false; // Currently all VUs require attachment to not be UNUSED assert(reference.attachment != VK_ATTACHMENT_UNUSED); // currently VkAttachmentReference and VkAttachmentReference2 have no overlapping VUs if (rp_version == RENDER_PASS_VERSION_1) { switch (reference.layout) { case VK_IMAGE_LAYOUT_UNDEFINED: case VK_IMAGE_LAYOUT_PREINITIALIZED: case VK_IMAGE_LAYOUT_PRESENT_SRC_KHR: case VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL: case VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_OPTIMAL: case VK_IMAGE_LAYOUT_STENCIL_ATTACHMENT_OPTIMAL: case VK_IMAGE_LAYOUT_STENCIL_READ_ONLY_OPTIMAL: skip |= LogError(device, "VUID-VkAttachmentReference-layout-00857", "%s: Layout for %s is %s but must not be " "VK_IMAGE_LAYOUT_[UNDEFINED|PREINITIALIZED|PRESENT_SRC_KHR|DEPTH_ATTACHMENT_OPTIMAL|DEPTH_READ_" "ONLY_OPTIMAL|STENCIL_ATTACHMENT_OPTIMAL|STENCIL_READ_ONLY_OPTIMAL].", function_name, error_type, string_VkImageLayout(reference.layout)); break; default: break; } } else { const auto *attachment_reference_stencil_layout = LvlFindInChain<VkAttachmentReferenceStencilLayout>(reference.pNext); switch (reference.layout) { case VK_IMAGE_LAYOUT_UNDEFINED: case VK_IMAGE_LAYOUT_PREINITIALIZED: case VK_IMAGE_LAYOUT_PRESENT_SRC_KHR: skip |= LogError(device, "VUID-VkAttachmentReference2-layout-03077", "%s: Layout for %s is %s but must not be VK_IMAGE_LAYOUT_[UNDEFINED|PREINITIALIZED|PRESENT_SRC_KHR].", function_name, error_type, string_VkImageLayout(reference.layout)); break; // Only other layouts in VUs to be checked case VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL: case VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_OPTIMAL: case VK_IMAGE_LAYOUT_STENCIL_ATTACHMENT_OPTIMAL: case VK_IMAGE_LAYOUT_STENCIL_READ_ONLY_OPTIMAL: // First need to make sure feature bit is enabled and the format is actually a depth and/or stencil if (!enabled_features.core12.separateDepthStencilLayouts) { skip |= LogError(device, "VUID-VkAttachmentReference2-separateDepthStencilLayouts-03313", "%s: Layout for %s is %s but without separateDepthStencilLayouts enabled the layout must not " "be VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_OPTIMAL, " "VK_IMAGE_LAYOUT_STENCIL_ATTACHMENT_OPTIMAL, or VK_IMAGE_LAYOUT_STENCIL_READ_ONLY_OPTIMAL.", function_name, error_type, string_VkImageLayout(reference.layout)); } else if (!FormatIsDepthOrStencil(attachment_format)) { // using this over FormatIsColor() incase a multiplane and/or undef would sneak in // "color" format is still an ambiguous term in spec (internal issue #2484) skip |= LogError( device, "VUID-VkAttachmentReference2-attachment-04754", "%s: Layout for %s is %s but the attachment is a not a depth/stencil format (%s) so the layout must not " "be VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_OPTIMAL, " "VK_IMAGE_LAYOUT_STENCIL_ATTACHMENT_OPTIMAL, or VK_IMAGE_LAYOUT_STENCIL_READ_ONLY_OPTIMAL.", function_name, error_type, string_VkImageLayout(reference.layout), string_VkFormat(attachment_format)); } else { if ((reference.layout == VK_IMAGE_LAYOUT_STENCIL_ATTACHMENT_OPTIMAL) || (reference.layout == VK_IMAGE_LAYOUT_STENCIL_READ_ONLY_OPTIMAL)) { if (FormatIsDepthOnly(attachment_format)) { skip |= LogError( device, "VUID-VkAttachmentReference2-attachment-04756", "%s: Layout for %s is %s but the attachment is a depth-only format (%s) so the layout must not " "be VK_IMAGE_LAYOUT_STENCIL_ATTACHMENT_OPTIMAL or VK_IMAGE_LAYOUT_STENCIL_READ_ONLY_OPTIMAL.", function_name, error_type, string_VkImageLayout(reference.layout), string_VkFormat(attachment_format)); } } else { // DEPTH_ATTACHMENT_OPTIMAL || DEPTH_READ_ONLY_OPTIMAL if (FormatIsStencilOnly(attachment_format)) { skip |= LogError( device, "VUID-VkAttachmentReference2-attachment-04757", "%s: Layout for %s is %s but the attachment is a depth-only format (%s) so the layout must not " "be VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL or VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_OPTIMAL.", function_name, error_type, string_VkImageLayout(reference.layout), string_VkFormat(attachment_format)); } if (attachment_reference_stencil_layout) { // This check doesn't rely on the aspect mask value const VkImageLayout stencil_layout = attachment_reference_stencil_layout->stencilLayout; // clang-format off if (stencil_layout == VK_IMAGE_LAYOUT_UNDEFINED || stencil_layout == VK_IMAGE_LAYOUT_PREINITIALIZED || stencil_layout == VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL || stencil_layout == VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL || stencil_layout == VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_OPTIMAL || stencil_layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL || stencil_layout == VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL || stencil_layout == VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL || stencil_layout == VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL || stencil_layout == VK_IMAGE_LAYOUT_PRESENT_SRC_KHR) { skip |= LogError(device, "VUID-VkAttachmentReferenceStencilLayout-stencilLayout-03318", "%s: In %s with pNext chain instance VkAttachmentReferenceStencilLayout, " "the stencilLayout (%s) must not be " "VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_PREINITIALIZED, " "VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, " "VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL, " "VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_OPTIMAL, " "VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, " "VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL, " "VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL, " "VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL, or " "VK_IMAGE_LAYOUT_PRESENT_SRC_KHR.", function_name, error_type, string_VkImageLayout(stencil_layout)); } // clang-format on } else if (FormatIsDepthAndStencil(attachment_format)) { skip |= LogError( device, "VUID-VkAttachmentReference2-attachment-04755", "%s: Layout for %s is %s but the attachment is a depth and stencil format (%s) so if the layout is " "VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL or VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_OPTIMAL there needs " "to be a VkAttachmentReferenceStencilLayout in the pNext chain to set the seperate stencil layout " "because the separateDepthStencilLayouts feature is enabled.", function_name, error_type, string_VkImageLayout(reference.layout), string_VkFormat(attachment_format)); } } } break; default: break; } } return skip; } bool CoreChecks::ValidateRenderpassAttachmentUsage(RenderPassCreateVersion rp_version, const VkRenderPassCreateInfo2 *pCreateInfo, const char *function_name) const { bool skip = false; const bool use_rp2 = (rp_version == RENDER_PASS_VERSION_2); const char *vuid; for (uint32_t i = 0; i < pCreateInfo->attachmentCount; ++i) { VkFormat format = pCreateInfo->pAttachments[i].format; if (pCreateInfo->pAttachments[i].initialLayout == VK_IMAGE_LAYOUT_UNDEFINED) { if ((FormatIsColor(format) || FormatHasDepth(format)) && pCreateInfo->pAttachments[i].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD) { skip |= LogWarning(device, kVUID_Core_DrawState_InvalidRenderpass, "%s: Render pass pAttachment[%u] has loadOp == VK_ATTACHMENT_LOAD_OP_LOAD and initialLayout == " "VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you intended. Consider using " "VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the image truely is undefined at the start of the " "render pass.", function_name, i); } if (FormatHasStencil(format) && pCreateInfo->pAttachments[i].stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD) { skip |= LogWarning(device, kVUID_Core_DrawState_InvalidRenderpass, "%s: Render pass pAttachment[%u] has stencilLoadOp == VK_ATTACHMENT_LOAD_OP_LOAD and initialLayout " "== VK_IMAGE_LAYOUT_UNDEFINED. This is probably not what you intended. Consider using " "VK_ATTACHMENT_LOAD_OP_DONT_CARE instead if the image truely is undefined at the start of the " "render pass.", function_name, i); } } } // Track when we're observing the first use of an attachment std::vector<bool> attach_first_use(pCreateInfo->attachmentCount, true); for (uint32_t i = 0; i < pCreateInfo->subpassCount; ++i) { const VkSubpassDescription2 &subpass = pCreateInfo->pSubpasses[i]; std::vector<uint8_t> attachment_uses(pCreateInfo->attachmentCount); std::vector<VkImageLayout> attachment_layouts(pCreateInfo->attachmentCount); // Track if attachments are used as input as well as another type layer_data::unordered_set<uint32_t> input_attachments; if (subpass.pipelineBindPoint != VK_PIPELINE_BIND_POINT_GRAPHICS && subpass.pipelineBindPoint != VK_PIPELINE_BIND_POINT_SUBPASS_SHADING_HUAWEI) { vuid = use_rp2 ? "VUID-VkSubpassDescription2-pipelineBindPoint-04953" : "VUID-VkSubpassDescription-pipelineBindPoint-04952"; skip |= LogError(device, vuid, "%s: Pipeline bind point for pSubpasses[%d] must be VK_PIPELINE_BIND_POINT_GRAPHICS or " "VK_PIPELINE_BIND_POINT_SUBPASS_SHADING_HUAWEI.", function_name, i); } // Check input attachments first // - so we can detect first-use-as-input for VU #00349 // - if other color or depth/stencil is also input, it limits valid layouts for (uint32_t j = 0; j < subpass.inputAttachmentCount; ++j) { auto const &attachment_ref = subpass.pInputAttachments[j]; const uint32_t attachment_index = attachment_ref.attachment; const VkImageAspectFlags aspect_mask = attachment_ref.aspectMask; if (attachment_index != VK_ATTACHMENT_UNUSED) { input_attachments.insert(attachment_index); std::string error_type = "pSubpasses[" + std::to_string(i) + "].pInputAttachments[" + std::to_string(j) + "]"; skip |= ValidateAttachmentIndex(rp_version, attachment_index, pCreateInfo->attachmentCount, error_type.c_str(), function_name); if (aspect_mask & VK_IMAGE_ASPECT_METADATA_BIT) { vuid = use_rp2 ? "VUID-VkSubpassDescription2-attachment-02801" : "VUID-VkInputAttachmentAspectReference-aspectMask-01964"; skip |= LogError( device, vuid, "%s: Aspect mask for input attachment reference %d in subpass %d includes VK_IMAGE_ASPECT_METADATA_BIT.", function_name, j, i); } else if (aspect_mask & (VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT | VK_IMAGE_ASPECT_MEMORY_PLANE_1_BIT_EXT | VK_IMAGE_ASPECT_MEMORY_PLANE_2_BIT_EXT | VK_IMAGE_ASPECT_MEMORY_PLANE_3_BIT_EXT)) { vuid = use_rp2 ? "VUID-VkSubpassDescription2-attachment-04563" : "VUID-VkInputAttachmentAspectReference-aspectMask-02250"; skip |= LogError(device, vuid, "%s: Aspect mask for input attachment reference %d in subpass %d includes " "VK_IMAGE_ASPECT_MEMORY_PLANE_*_BIT_EXT bit.", function_name, j, i); } // safe to dereference pCreateInfo->pAttachments[] if (attachment_index < pCreateInfo->attachmentCount) { const VkFormat attachment_format = pCreateInfo->pAttachments[attachment_index].format; skip |= ValidateAttachmentReference(rp_version, attachment_ref, attachment_format, true, error_type.c_str(), function_name); skip |= AddAttachmentUse(rp_version, i, attachment_uses, attachment_layouts, attachment_index, ATTACHMENT_INPUT, attachment_ref.layout); vuid = use_rp2 ? "VUID-VkRenderPassCreateInfo2-attachment-02525" : "VUID-VkRenderPassCreateInfo-pNext-01963"; skip |= ValidateImageAspectMask(VK_NULL_HANDLE, attachment_format, aspect_mask, function_name, vuid); if (attach_first_use[attachment_index]) { skip |= ValidateLayoutVsAttachmentDescription(report_data, rp_version, subpass.pInputAttachments[j].layout, attachment_index, pCreateInfo->pAttachments[attachment_index]); bool used_as_depth = (subpass.pDepthStencilAttachment != NULL && subpass.pDepthStencilAttachment->attachment == attachment_index); bool used_as_color = false; for (uint32_t k = 0; !used_as_depth && !used_as_color && k < subpass.colorAttachmentCount; ++k) { used_as_color = (subpass.pColorAttachments[k].attachment == attachment_index); } if (!used_as_depth && !used_as_color && pCreateInfo->pAttachments[attachment_index].loadOp == VK_ATTACHMENT_LOAD_OP_CLEAR) { vuid = use_rp2 ? "VUID-VkSubpassDescription2-loadOp-03064" : "VUID-VkSubpassDescription-loadOp-00846"; skip |= LogError(device, vuid, "%s: attachment %u is first used as an input attachment in %s with loadOp set to " "VK_ATTACHMENT_LOAD_OP_CLEAR.", function_name, attachment_index, error_type.c_str()); } } attach_first_use[attachment_index] = false; const VkFormatFeatureFlags valid_flags = VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT | VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT; const VkFormatFeatureFlags format_features = GetPotentialFormatFeatures(attachment_format); if ((format_features & valid_flags) == 0) { vuid = use_rp2 ? "VUID-VkSubpassDescription2-pInputAttachments-02897" : "VUID-VkSubpassDescription-pInputAttachments-02647"; skip |= LogError(device, vuid, "%s: Input attachment %s format (%s) does not contain VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT " "| VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT.", function_name, error_type.c_str(), string_VkFormat(attachment_format)); } } if (rp_version == RENDER_PASS_VERSION_2) { // These are validated automatically as part of parameter validation for create renderpass 1 // as they are in a struct that only applies to input attachments - not so for v2. // Check for 0 if (aspect_mask == 0) { skip |= LogError(device, "VUID-VkSubpassDescription2-attachment-02800", "%s: Input attachment %s aspect mask must not be 0.", function_name, error_type.c_str()); } else { const VkImageAspectFlags valid_bits = (VK_IMAGE_ASPECT_COLOR_BIT | VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT | VK_IMAGE_ASPECT_METADATA_BIT | VK_IMAGE_ASPECT_PLANE_0_BIT | VK_IMAGE_ASPECT_PLANE_1_BIT | VK_IMAGE_ASPECT_PLANE_2_BIT | VK_IMAGE_ASPECT_MEMORY_PLANE_0_BIT_EXT | VK_IMAGE_ASPECT_MEMORY_PLANE_1_BIT_EXT | VK_IMAGE_ASPECT_MEMORY_PLANE_2_BIT_EXT | VK_IMAGE_ASPECT_MEMORY_PLANE_3_BIT_EXT); // Check for valid aspect mask bits if (aspect_mask & ~valid_bits) { skip |= LogError(device, "VUID-VkSubpassDescription2-attachment-02799", "%s: Input attachment %s aspect mask (0x%" PRIx32 ")is invalid.", function_name, error_type.c_str(), aspect_mask); } } } // Validate layout vuid = use_rp2 ? "VUID-VkSubpassDescription2-None-04439" : "VUID-VkSubpassDescription-None-04437"; switch (attachment_ref.layout) { case VK_IMAGE_LAYOUT_SHARED_PRESENT_KHR: case VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL: case VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL: case VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL: case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL: case VK_IMAGE_LAYOUT_GENERAL: case VK_IMAGE_LAYOUT_READ_ONLY_OPTIMAL_KHR: break; // valid layouts default: skip |= LogError(device, vuid, "%s: %s layout is %s but input attachments must be " "VK_IMAGE_LAYOUT_SHARED_PRESENT_KHR, " "VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL, " "VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL, " "VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL, " "VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL, or " "VK_IMAGE_LAYOUT_READ_ONLY_OPTIMAL_KHR", function_name, error_type.c_str(), string_VkImageLayout(attachment_ref.layout)); break; } } } for (uint32_t j = 0; j < subpass.preserveAttachmentCount; ++j) { std::string error_type = "pSubpasses[" + std::to_string(i) + "].pPreserveAttachments[" + std::to_string(j) + "]"; uint32_t attachment = subpass.pPreserveAttachments[j]; if (attachment == VK_ATTACHMENT_UNUSED) { vuid = use_rp2 ? "VUID-VkSubpassDescription2-attachment-03073" : "VUID-VkSubpassDescription-attachment-00853"; skip |= LogError(device, vuid, "%s: Preserve attachment (%d) must not be VK_ATTACHMENT_UNUSED.", function_name, j); } else { skip |= ValidateAttachmentIndex(rp_version, attachment, pCreateInfo->attachmentCount, error_type.c_str(), function_name); if (attachment < pCreateInfo->attachmentCount) { skip |= AddAttachmentUse(rp_version, i, attachment_uses, attachment_layouts, attachment, ATTACHMENT_PRESERVE, VkImageLayout(0) /* preserve doesn't have any layout */); } } } bool subpass_performs_resolve = false; for (uint32_t j = 0; j < subpass.colorAttachmentCount; ++j) { if (subpass.pResolveAttachments) { std::string error_type = "pSubpasses[" + std::to_string(i) + "].pResolveAttachments[" + std::to_string(j) + "]"; auto const &attachment_ref = subpass.pResolveAttachments[j]; if (attachment_ref.attachment != VK_ATTACHMENT_UNUSED) { skip |= ValidateAttachmentIndex(rp_version, attachment_ref.attachment, pCreateInfo->attachmentCount, error_type.c_str(), function_name); // safe to dereference pCreateInfo->pAttachments[] if (attachment_ref.attachment < pCreateInfo->attachmentCount) { const VkFormat attachment_format = pCreateInfo->pAttachments[attachment_ref.attachment].format; skip |= ValidateAttachmentReference(rp_version, attachment_ref, attachment_format, false, error_type.c_str(), function_name); skip |= AddAttachmentUse(rp_version, i, attachment_uses, attachment_layouts, attachment_ref.attachment, ATTACHMENT_RESOLVE, attachment_ref.layout); subpass_performs_resolve = true; if (pCreateInfo->pAttachments[attachment_ref.attachment].samples != VK_SAMPLE_COUNT_1_BIT) { vuid = use_rp2 ? "VUID-VkSubpassDescription2-pResolveAttachments-03067" : "VUID-VkSubpassDescription-pResolveAttachments-00849"; skip |= LogError( device, vuid, "%s: Subpass %u requests multisample resolve into attachment %u, which must " "have VK_SAMPLE_COUNT_1_BIT but has %s.", function_name, i, attachment_ref.attachment, string_VkSampleCountFlagBits(pCreateInfo->pAttachments[attachment_ref.attachment].samples)); } const VkFormatFeatureFlags format_features = GetPotentialFormatFeatures(attachment_format); if ((format_features & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT) == 0) { vuid = use_rp2 ? "VUID-VkSubpassDescription2-pResolveAttachments-02899" : "VUID-VkSubpassDescription-pResolveAttachments-02649"; skip |= LogError(device, vuid, "%s: Resolve attachment %s format (%s) does not contain " "VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT.", function_name, error_type.c_str(), string_VkFormat(attachment_format)); } // VK_QCOM_render_pass_shader_resolve check of resolve attachmnents if ((subpass.flags & VK_SUBPASS_DESCRIPTION_SHADER_RESOLVE_BIT_QCOM) != 0) { vuid = use_rp2 ? "VUID-VkRenderPassCreateInfo2-flags-04907" : "VUID-VkSubpassDescription-flags-03341"; skip |= LogError( device, vuid, "%s: Subpass %u enables shader resolve, which requires every element of pResolve attachments" " must be VK_ATTACHMENT_UNUSED, but element %u contains a reference to attachment %u instead.", function_name, i, j, attachment_ref.attachment); } } } } } if (subpass.pDepthStencilAttachment) { std::string error_type = "pSubpasses[" + std::to_string(i) + "].pDepthStencilAttachment"; const uint32_t attachment = subpass.pDepthStencilAttachment->attachment; const VkImageLayout image_layout = subpass.pDepthStencilAttachment->layout; if (attachment != VK_ATTACHMENT_UNUSED) { skip |= ValidateAttachmentIndex(rp_version, attachment, pCreateInfo->attachmentCount, error_type.c_str(), function_name); // safe to dereference pCreateInfo->pAttachments[] if (attachment < pCreateInfo->attachmentCount) { const VkFormat attachment_format = pCreateInfo->pAttachments[attachment].format; skip |= ValidateAttachmentReference(rp_version, *subpass.pDepthStencilAttachment, attachment_format, false, error_type.c_str(), function_name); skip |= AddAttachmentUse(rp_version, i, attachment_uses, attachment_layouts, attachment, ATTACHMENT_DEPTH, image_layout); if (attach_first_use[attachment]) { skip |= ValidateLayoutVsAttachmentDescription(report_data, rp_version, image_layout, attachment, pCreateInfo->pAttachments[attachment]); } attach_first_use[attachment] = false; const VkFormatFeatureFlags format_features = GetPotentialFormatFeatures(attachment_format); if ((format_features & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) == 0) { vuid = use_rp2 ? "VUID-VkSubpassDescription2-pDepthStencilAttachment-02900" : "VUID-VkSubpassDescription-pDepthStencilAttachment-02650"; skip |= LogError(device, vuid, "%s: Depth Stencil %s format (%s) does not contain " "VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT.", function_name, error_type.c_str(), string_VkFormat(attachment_format)); } } // Check for valid imageLayout vuid = use_rp2 ? "VUID-VkSubpassDescription2-None-04439" : "VUID-VkSubpassDescription-None-04437"; switch (image_layout) { case VK_IMAGE_LAYOUT_SHARED_PRESENT_KHR: case VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL: case VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL: case VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL: case VK_IMAGE_LAYOUT_GENERAL: break; // valid layouts case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL: case VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL: case VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_OPTIMAL: case VK_IMAGE_LAYOUT_STENCIL_ATTACHMENT_OPTIMAL: case VK_IMAGE_LAYOUT_STENCIL_READ_ONLY_OPTIMAL: case VK_IMAGE_LAYOUT_READ_ONLY_OPTIMAL_KHR: case VK_IMAGE_LAYOUT_ATTACHMENT_OPTIMAL_KHR: if (input_attachments.find(attachment) != input_attachments.end()) { skip |= LogError( device, vuid, "%s: %s is also an input attachment so the layout (%s) must not be " "VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL, " "VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_OPTIMAL, VK_IMAGE_LAYOUT_STENCIL_ATTACHMENT_OPTIMAL, " "VK_IMAGE_LAYOUT_STENCIL_READ_ONLY_OPTIMAL, VK_IMAGE_LAYOUT_READ_ONLY_OPTIMAL_KHR " "or VK_IMAGE_LAYOUT_ATTACHMENT_OPTIMAL_KHR.", function_name, error_type.c_str(), string_VkImageLayout(image_layout)); } break; default: skip |= LogError(device, vuid, "%s: %s layout is %s but depth/stencil attachments must be " "VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, " "VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_OPTIMAL, " "VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_OPTIMAL, " "VK_IMAGE_LAYOUT_STENCIL_ATTACHMENT_OPTIMAL, " "VK_IMAGE_LAYOUT_STENCIL_READ_ONLY_OPTIMAL, " "VK_IMAGE_LAYOUT_SHARED_PRESENT_KHR, " "VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL, " "VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL, " "VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL, " "VK_IMAGE_LAYOUT_GENERAL, " "VK_IMAGE_LAYOUT_READ_ONLY_OPTIMAL_KHR or" "VK_IMAGE_LAYOUT_ATTACHMENT_OPTIMAL_KHR.", function_name, error_type.c_str(), string_VkImageLayout(image_layout)); break; } } } uint32_t last_sample_count_attachment = VK_ATTACHMENT_UNUSED; for (uint32_t j = 0; j < subpass.colorAttachmentCount; ++j) { std::string error_type = "pSubpasses[" + std::to_string(i) + "].pColorAttachments[" + std::to_string(j) + "]"; auto const &attachment_ref = subpass.pColorAttachments[j]; const uint32_t attachment_index = attachment_ref.attachment; if (attachment_index != VK_ATTACHMENT_UNUSED) { skip |= ValidateAttachmentIndex(rp_version, attachment_index, pCreateInfo->attachmentCount, error_type.c_str(), function_name); // safe to dereference pCreateInfo->pAttachments[] if (attachment_index < pCreateInfo->attachmentCount) { const VkFormat attachment_format = pCreateInfo->pAttachments[attachment_index].format; skip |= ValidateAttachmentReference(rp_version, attachment_ref, attachment_format, false, error_type.c_str(), function_name); skip |= AddAttachmentUse(rp_version, i, attachment_uses, attachment_layouts, attachment_index, ATTACHMENT_COLOR, attachment_ref.layout); VkSampleCountFlagBits current_sample_count = pCreateInfo->pAttachments[attachment_index].samples; if (last_sample_count_attachment != VK_ATTACHMENT_UNUSED) { VkSampleCountFlagBits last_sample_count = pCreateInfo->pAttachments[subpass.pColorAttachments[last_sample_count_attachment].attachment].samples; if (current_sample_count != last_sample_count) { vuid = use_rp2 ? "VUID-VkSubpassDescription2-pColorAttachments-03069" : "VUID-VkSubpassDescription-pColorAttachments-01417"; skip |= LogError( device, vuid, "%s: Subpass %u attempts to render to color attachments with inconsistent sample counts." "Color attachment ref %u has sample count %s, whereas previous color attachment ref %u has " "sample count %s.", function_name, i, j, string_VkSampleCountFlagBits(current_sample_count), last_sample_count_attachment, string_VkSampleCountFlagBits(last_sample_count)); } } last_sample_count_attachment = j; if (subpass_performs_resolve && current_sample_count == VK_SAMPLE_COUNT_1_BIT) { vuid = use_rp2 ? "VUID-VkSubpassDescription2-pResolveAttachments-03066" : "VUID-VkSubpassDescription-pResolveAttachments-00848"; skip |= LogError(device, vuid, "%s: Subpass %u requests multisample resolve from attachment %u which has " "VK_SAMPLE_COUNT_1_BIT.", function_name, i, attachment_index); } if (subpass.pDepthStencilAttachment && subpass.pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED && subpass.pDepthStencilAttachment->attachment < pCreateInfo->attachmentCount) { const auto depth_stencil_sample_count = pCreateInfo->pAttachments[subpass.pDepthStencilAttachment->attachment].samples; if (device_extensions.vk_amd_mixed_attachment_samples) { if (current_sample_count > depth_stencil_sample_count) { vuid = use_rp2 ? "VUID-VkSubpassDescription2-pColorAttachments-03070" : "VUID-VkSubpassDescription-pColorAttachments-01506"; skip |= LogError(device, vuid, "%s: %s has %s which is larger than depth/stencil attachment %s.", function_name, error_type.c_str(), string_VkSampleCountFlagBits(current_sample_count), string_VkSampleCountFlagBits(depth_stencil_sample_count)); break; } } if (!device_extensions.vk_amd_mixed_attachment_samples && !device_extensions.vk_nv_framebuffer_mixed_samples && current_sample_count != depth_stencil_sample_count) { vuid = use_rp2 ? "VUID-VkSubpassDescription2-pDepthStencilAttachment-03071" : "VUID-VkSubpassDescription-pDepthStencilAttachment-01418"; skip |= LogError(device, vuid, "%s: Subpass %u attempts to render to use a depth/stencil attachment with sample " "count that differs " "from color attachment %u." "The depth attachment ref has sample count %s, whereas color attachment ref %u has " "sample count %s.", function_name, i, j, string_VkSampleCountFlagBits(depth_stencil_sample_count), j, string_VkSampleCountFlagBits(current_sample_count)); break; } } const VkFormatFeatureFlags format_features = GetPotentialFormatFeatures(attachment_format); if ((format_features & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT) == 0) { vuid = use_rp2 ? "VUID-VkSubpassDescription2-pColorAttachments-02898" : "VUID-VkSubpassDescription-pColorAttachments-02648"; skip |= LogError(device, vuid, "%s: Color attachment %s format (%s) does not contain " "VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT.", function_name, error_type.c_str(), string_VkFormat(attachment_format)); } if (attach_first_use[attachment_index]) { skip |= ValidateLayoutVsAttachmentDescription(report_data, rp_version, subpass.pColorAttachments[j].layout, attachment_index, pCreateInfo->pAttachments[attachment_index]); } attach_first_use[attachment_index] = false; } // Check for valid imageLayout vuid = use_rp2 ? "VUID-VkSubpassDescription2-None-04439" : "VUID-VkSubpassDescription-None-04437"; switch (attachment_ref.layout) { case VK_IMAGE_LAYOUT_SHARED_PRESENT_KHR: case VK_IMAGE_LAYOUT_GENERAL: break; // valid layouts case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL: case VK_IMAGE_LAYOUT_ATTACHMENT_OPTIMAL_KHR: if (input_attachments.find(attachment_index) != input_attachments.end()) { skip |= LogError(device, vuid, "%s: %s is also an input attachment so the layout (%s) must not be " "VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL or VK_IMAGE_LAYOUT_ATTACHMENT_OPTIMAL_KHR.", function_name, error_type.c_str(), string_VkImageLayout(attachment_ref.layout)); } break; default: skip |= LogError(device, vuid, "%s: %s layout is %s but color attachments must be " "VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, " "VK_IMAGE_LAYOUT_ATTACHMENT_OPTIMAL_KHR, " "VK_IMAGE_LAYOUT_SHARED_PRESENT_KHR or " "VK_IMAGE_LAYOUT_GENERAL.", function_name, error_type.c_str(), string_VkImageLayout(attachment_ref.layout)); break; } } if (subpass_performs_resolve && subpass.pResolveAttachments[j].attachment != VK_ATTACHMENT_UNUSED && subpass.pResolveAttachments[j].attachment < pCreateInfo->attachmentCount) { if (attachment_index == VK_ATTACHMENT_UNUSED) { vuid = use_rp2 ? "VUID-VkSubpassDescription2-pResolveAttachments-03065" : "VUID-VkSubpassDescription-pResolveAttachments-00847"; skip |= LogError(device, vuid, "%s: Subpass %u requests multisample resolve from attachment %u which has " "attachment=VK_ATTACHMENT_UNUSED.", function_name, i, attachment_index); } else { const auto &color_desc = pCreateInfo->pAttachments[attachment_index]; const auto &resolve_desc = pCreateInfo->pAttachments[subpass.pResolveAttachments[j].attachment]; if (color_desc.format != resolve_desc.format) { vuid = use_rp2 ? "VUID-VkSubpassDescription2-pResolveAttachments-03068" : "VUID-VkSubpassDescription-pResolveAttachments-00850"; skip |= LogError(device, vuid, "%s: %s resolves to an attachment with a " "different format. color format: %u, resolve format: %u.", function_name, error_type.c_str(), color_desc.format, resolve_desc.format); } } } } } return skip; } bool CoreChecks::ValidateCreateRenderPass(VkDevice device, RenderPassCreateVersion rp_version, const VkRenderPassCreateInfo2 *pCreateInfo, const char *function_name) const { bool skip = false; const bool use_rp2 = (rp_version == RENDER_PASS_VERSION_2); const char *vuid; skip |= ValidateRenderpassAttachmentUsage(rp_version, pCreateInfo, function_name); skip |= ValidateRenderPassDAG(rp_version, pCreateInfo); // Validate multiview correlation and view masks bool view_mask_zero = false; bool view_mask_non_zero = false; for (uint32_t i = 0; i < pCreateInfo->subpassCount; ++i) { const VkSubpassDescription2 &subpass = pCreateInfo->pSubpasses[i]; if (subpass.viewMask != 0) { view_mask_non_zero = true; } else { view_mask_zero = true; } if ((subpass.flags & VK_SUBPASS_DESCRIPTION_PER_VIEW_POSITION_X_ONLY_BIT_NVX) != 0 && (subpass.flags & VK_SUBPASS_DESCRIPTION_PER_VIEW_ATTRIBUTES_BIT_NVX) == 0) { vuid = use_rp2 ? "VUID-VkSubpassDescription2-flags-03076" : "VUID-VkSubpassDescription-flags-00856"; skip |= LogError(device, vuid, "%s: The flags parameter of subpass description %u includes " "VK_SUBPASS_DESCRIPTION_PER_VIEW_POSITION_X_ONLY_BIT_NVX but does not also include " "VK_SUBPASS_DESCRIPTION_PER_VIEW_ATTRIBUTES_BIT_NVX.", function_name, i); } } if (rp_version == RENDER_PASS_VERSION_2) { if (view_mask_non_zero && view_mask_zero) { skip |= LogError(device, "VUID-VkRenderPassCreateInfo2-viewMask-03058", "%s: Some view masks are non-zero whilst others are zero.", function_name); } if (view_mask_zero && pCreateInfo->correlatedViewMaskCount != 0) { skip |= LogError(device, "VUID-VkRenderPassCreateInfo2-viewMask-03057", "%s: Multiview is not enabled but correlation masks are still provided", function_name); } } uint32_t aggregated_cvms = 0; for (uint32_t i = 0; i < pCreateInfo->correlatedViewMaskCount; ++i) { if (aggregated_cvms & pCreateInfo->pCorrelatedViewMasks[i]) { vuid = use_rp2 ? "VUID-VkRenderPassCreateInfo2-pCorrelatedViewMasks-03056" : "VUID-VkRenderPassMultiviewCreateInfo-pCorrelationMasks-00841"; skip |= LogError(device, vuid, "%s: pCorrelatedViewMasks[%u] contains a previously appearing view bit.", function_name, i); } aggregated_cvms |= pCreateInfo->pCorrelatedViewMasks[i]; } LogObjectList objects(device); auto func_name = use_rp2 ? Func::vkCreateRenderPass2 : Func::vkCreateRenderPass; auto structure = use_rp2 ? Struct::VkSubpassDependency2 : Struct::VkSubpassDependency; for (uint32_t i = 0; i < pCreateInfo->dependencyCount; ++i) { auto const &dependency = pCreateInfo->pDependencies[i]; Location loc(func_name, structure, Field::pDependencies, i); skip |= ValidateSubpassDependency(objects, loc, dependency); } return skip; } bool CoreChecks::PreCallValidateCreateRenderPass(VkDevice device, const VkRenderPassCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkRenderPass *pRenderPass) const { bool skip = false; // Handle extension structs from KHR_multiview and KHR_maintenance2 that can only be validated for RP1 (indices out of bounds) const VkRenderPassMultiviewCreateInfo *multiview_info = LvlFindInChain<VkRenderPassMultiviewCreateInfo>(pCreateInfo->pNext); if (multiview_info) { if (multiview_info->subpassCount && multiview_info->subpassCount != pCreateInfo->subpassCount) { skip |= LogError(device, "VUID-VkRenderPassCreateInfo-pNext-01928", "vkCreateRenderPass(): Subpass count is %u but multiview info has a subpass count of %u.", pCreateInfo->subpassCount, multiview_info->subpassCount); } else if (multiview_info->dependencyCount && multiview_info->dependencyCount != pCreateInfo->dependencyCount) { skip |= LogError(device, "VUID-VkRenderPassCreateInfo-pNext-01929", "vkCreateRenderPass(): Dependency count is %u but multiview info has a dependency count of %u.", pCreateInfo->dependencyCount, multiview_info->dependencyCount); } bool all_zero = true; bool all_not_zero = true; for (uint32_t i = 0; i < multiview_info->subpassCount; ++i) { all_zero &= multiview_info->pViewMasks[i] == 0; all_not_zero &= !(multiview_info->pViewMasks[i] == 0); } if (!all_zero && !all_not_zero) { skip |= LogError( device, "VUID-VkRenderPassCreateInfo-pNext-02513", "vkCreateRenderPass(): elements of VkRenderPassMultiviewCreateInfo pViewMasks must all be either 0 or not 0."); } } const VkRenderPassInputAttachmentAspectCreateInfo *input_attachment_aspect_info = LvlFindInChain<VkRenderPassInputAttachmentAspectCreateInfo>(pCreateInfo->pNext); if (input_attachment_aspect_info) { for (uint32_t i = 0; i < input_attachment_aspect_info->aspectReferenceCount; ++i) { uint32_t subpass = input_attachment_aspect_info->pAspectReferences[i].subpass; uint32_t attachment = input_attachment_aspect_info->pAspectReferences[i].inputAttachmentIndex; if (subpass >= pCreateInfo->subpassCount) { skip |= LogError(device, "VUID-VkRenderPassCreateInfo-pNext-01926", "vkCreateRenderPass(): Subpass index %u specified by input attachment aspect info %u is greater " "than the subpass " "count of %u for this render pass.", subpass, i, pCreateInfo->subpassCount); } else if (pCreateInfo->pSubpasses && attachment >= pCreateInfo->pSubpasses[subpass].inputAttachmentCount) { skip |= LogError(device, "VUID-VkRenderPassCreateInfo-pNext-01927", "vkCreateRenderPass(): Input attachment index %u specified by input attachment aspect info %u is " "greater than the " "input attachment count of %u for this subpass.", attachment, i, pCreateInfo->pSubpasses[subpass].inputAttachmentCount); } } } const VkRenderPassFragmentDensityMapCreateInfoEXT *fragment_density_map_info = LvlFindInChain<VkRenderPassFragmentDensityMapCreateInfoEXT>(pCreateInfo->pNext); if (fragment_density_map_info) { if (fragment_density_map_info->fragmentDensityMapAttachment.attachment != VK_ATTACHMENT_UNUSED) { if (fragment_density_map_info->fragmentDensityMapAttachment.attachment >= pCreateInfo->attachmentCount) { skip |= LogError(device, "VUID-VkRenderPassFragmentDensityMapCreateInfoEXT-fragmentDensityMapAttachment-02547", "vkCreateRenderPass(): fragmentDensityMapAttachment %u must be less than attachmentCount %u of " "for this render pass.", fragment_density_map_info->fragmentDensityMapAttachment.attachment, pCreateInfo->attachmentCount); } else { if (!(fragment_density_map_info->fragmentDensityMapAttachment.layout == VK_IMAGE_LAYOUT_FRAGMENT_DENSITY_MAP_OPTIMAL_EXT || fragment_density_map_info->fragmentDensityMapAttachment.layout == VK_IMAGE_LAYOUT_GENERAL)) { skip |= LogError(device, "VUID-VkRenderPassFragmentDensityMapCreateInfoEXT-fragmentDensityMapAttachment-02549", "vkCreateRenderPass(): Layout of fragmentDensityMapAttachment %u' must be equal to " "VK_IMAGE_LAYOUT_FRAGMENT_DENSITY_MAP_OPTIMAL_EXT, or VK_IMAGE_LAYOUT_GENERAL.", fragment_density_map_info->fragmentDensityMapAttachment.attachment); } if (!(pCreateInfo->pAttachments[fragment_density_map_info->fragmentDensityMapAttachment.attachment].loadOp == VK_ATTACHMENT_LOAD_OP_LOAD || pCreateInfo->pAttachments[fragment_density_map_info->fragmentDensityMapAttachment.attachment].loadOp == VK_ATTACHMENT_LOAD_OP_DONT_CARE)) { skip |= LogError( device, "VUID-VkRenderPassFragmentDensityMapCreateInfoEXT-fragmentDensityMapAttachment-02550", "vkCreateRenderPass(): FragmentDensityMapAttachment %u' must reference an attachment with a loadOp " "equal to VK_ATTACHMENT_LOAD_OP_LOAD or VK_ATTACHMENT_LOAD_OP_DONT_CARE.", fragment_density_map_info->fragmentDensityMapAttachment.attachment); } if (pCreateInfo->pAttachments[fragment_density_map_info->fragmentDensityMapAttachment.attachment].storeOp != VK_ATTACHMENT_STORE_OP_DONT_CARE) { skip |= LogError( device, "VUID-VkRenderPassFragmentDensityMapCreateInfoEXT-fragmentDensityMapAttachment-02551", "vkCreateRenderPass(): FragmentDensityMapAttachment %u' must reference an attachment with a storeOp " "equal to VK_ATTACHMENT_STORE_OP_DONT_CARE.", fragment_density_map_info->fragmentDensityMapAttachment.attachment); } } } } if (!skip) { safe_VkRenderPassCreateInfo2 create_info_2; ConvertVkRenderPassCreateInfoToV2KHR(*pCreateInfo, &create_info_2); skip |= ValidateCreateRenderPass(device, RENDER_PASS_VERSION_1, create_info_2.ptr(), "vkCreateRenderPass()"); } return skip; } bool CoreChecks::ValidateDepthStencilResolve(const VkPhysicalDeviceVulkan12Properties &core12_props, const VkRenderPassCreateInfo2 *pCreateInfo, const char *function_name) const { bool skip = false; // If the pNext list of VkSubpassDescription2 includes a VkSubpassDescriptionDepthStencilResolve structure, // then that structure describes depth/stencil resolve operations for the subpass. for (uint32_t i = 0; i < pCreateInfo->subpassCount; i++) { const VkSubpassDescription2 &subpass = pCreateInfo->pSubpasses[i]; const auto *resolve = LvlFindInChain<VkSubpassDescriptionDepthStencilResolve>(subpass.pNext); if (resolve == nullptr) { continue; } const bool resolve_attachment_not_unused = (resolve->pDepthStencilResolveAttachment != nullptr && resolve->pDepthStencilResolveAttachment->attachment != VK_ATTACHMENT_UNUSED); const bool valid_resolve_attachment_index = (resolve_attachment_not_unused && resolve->pDepthStencilResolveAttachment->attachment < pCreateInfo->attachmentCount); const bool ds_attachment_not_unused = (subpass.pDepthStencilAttachment != nullptr && subpass.pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED); const bool valid_ds_attachment_index = (ds_attachment_not_unused && subpass.pDepthStencilAttachment->attachment < pCreateInfo->attachmentCount); if (resolve_attachment_not_unused && subpass.pDepthStencilAttachment != nullptr && subpass.pDepthStencilAttachment->attachment == VK_ATTACHMENT_UNUSED) { skip |= LogError(device, "VUID-VkSubpassDescriptionDepthStencilResolve-pDepthStencilResolveAttachment-03177", "%s: Subpass %u includes a VkSubpassDescriptionDepthStencilResolve " "structure with resolve attachment %u, but pDepthStencilAttachment=VK_ATTACHMENT_UNUSED.", function_name, i, resolve->pDepthStencilResolveAttachment->attachment); } if (resolve_attachment_not_unused && resolve->depthResolveMode == VK_RESOLVE_MODE_NONE && resolve->stencilResolveMode == VK_RESOLVE_MODE_NONE) { skip |= LogError(device, "VUID-VkSubpassDescriptionDepthStencilResolve-pDepthStencilResolveAttachment-03178", "%s: Subpass %u includes a VkSubpassDescriptionDepthStencilResolve " "structure with resolve attachment %u, but both depth and stencil resolve modes are " "VK_RESOLVE_MODE_NONE.", function_name, i, resolve->pDepthStencilResolveAttachment->attachment); } if (resolve_attachment_not_unused && valid_ds_attachment_index && pCreateInfo->pAttachments[subpass.pDepthStencilAttachment->attachment].samples == VK_SAMPLE_COUNT_1_BIT) { skip |= LogError( device, "VUID-VkSubpassDescriptionDepthStencilResolve-pDepthStencilResolveAttachment-03179", "%s: Subpass %u includes a VkSubpassDescriptionDepthStencilResolve " "structure with resolve attachment %u. However pDepthStencilAttachment has sample count=VK_SAMPLE_COUNT_1_BIT.", function_name, i, resolve->pDepthStencilResolveAttachment->attachment); } if (valid_resolve_attachment_index && pCreateInfo->pAttachments[resolve->pDepthStencilResolveAttachment->attachment].samples != VK_SAMPLE_COUNT_1_BIT) { skip |= LogError(device, "VUID-VkSubpassDescriptionDepthStencilResolve-pDepthStencilResolveAttachment-03180", "%s: Subpass %u includes a VkSubpassDescriptionDepthStencilResolve " "structure with resolve attachment %u which has sample count=VK_SAMPLE_COUNT_1_BIT.", function_name, i, resolve->pDepthStencilResolveAttachment->attachment); } VkFormat depth_stencil_attachment_format = (valid_ds_attachment_index ? pCreateInfo->pAttachments[subpass.pDepthStencilAttachment->attachment].format : VK_FORMAT_UNDEFINED); VkFormat depth_stencil_resolve_attachment_format = (valid_resolve_attachment_index ? pCreateInfo->pAttachments[resolve->pDepthStencilResolveAttachment->attachment].format : VK_FORMAT_UNDEFINED); if (valid_ds_attachment_index && valid_resolve_attachment_index) { const auto resolve_depth_size = FormatDepthSize(depth_stencil_resolve_attachment_format); const auto resolve_stencil_size = FormatStencilSize(depth_stencil_resolve_attachment_format); if (resolve_depth_size > 0 && ((FormatDepthSize(depth_stencil_attachment_format) != resolve_depth_size) || (FormatDepthNumericalType(depth_stencil_attachment_format) != FormatDepthNumericalType(depth_stencil_resolve_attachment_format)))) { skip |= LogError( device, "VUID-VkSubpassDescriptionDepthStencilResolve-pDepthStencilResolveAttachment-03181", "%s: Subpass %u includes a VkSubpassDescriptionDepthStencilResolve " "structure with resolve attachment %u which has a depth component (size %u). The depth component " "of pDepthStencilAttachment must have the same number of bits (currently %u) and the same numerical type.", function_name, i, resolve->pDepthStencilResolveAttachment->attachment, resolve_depth_size, FormatDepthSize(depth_stencil_attachment_format)); } if (resolve_stencil_size > 0 && ((FormatStencilSize(depth_stencil_attachment_format) != resolve_stencil_size) || (FormatStencilNumericalType(depth_stencil_attachment_format) != FormatStencilNumericalType(depth_stencil_resolve_attachment_format)))) { skip |= LogError( device, "VUID-VkSubpassDescriptionDepthStencilResolve-pDepthStencilResolveAttachment-03182", "%s: Subpass %u includes a VkSubpassDescriptionDepthStencilResolve " "structure with resolve attachment %u which has a stencil component (size %u). The stencil component " "of pDepthStencilAttachment must have the same number of bits (currently %u) and the same numerical type.", function_name, i, resolve->pDepthStencilResolveAttachment->attachment, resolve_stencil_size, FormatStencilSize(depth_stencil_attachment_format)); } } if (!(resolve->depthResolveMode == VK_RESOLVE_MODE_NONE || resolve->depthResolveMode & core12_props.supportedDepthResolveModes)) { skip |= LogError(device, "VUID-VkSubpassDescriptionDepthStencilResolve-depthResolveMode-03183", "%s: Subpass %u includes a VkSubpassDescriptionDepthStencilResolve " "structure with invalid depthResolveMode=%u.", function_name, i, resolve->depthResolveMode); } if (!(resolve->stencilResolveMode == VK_RESOLVE_MODE_NONE || resolve->stencilResolveMode & core12_props.supportedStencilResolveModes)) { skip |= LogError(device, "VUID-VkSubpassDescriptionDepthStencilResolve-stencilResolveMode-03184", "%s: Subpass %u includes a VkSubpassDescriptionDepthStencilResolve " "structure with invalid stencilResolveMode=%u.", function_name, i, resolve->stencilResolveMode); } if (valid_resolve_attachment_index && FormatIsDepthAndStencil(depth_stencil_resolve_attachment_format) && core12_props.independentResolve == VK_FALSE && core12_props.independentResolveNone == VK_FALSE && !(resolve->depthResolveMode == resolve->stencilResolveMode)) { skip |= LogError(device, "VUID-VkSubpassDescriptionDepthStencilResolve-pDepthStencilResolveAttachment-03185", "%s: Subpass %u includes a VkSubpassDescriptionDepthStencilResolve " "structure. The values of depthResolveMode (%u) and stencilResolveMode (%u) must be identical.", function_name, i, resolve->depthResolveMode, resolve->stencilResolveMode); } if (valid_resolve_attachment_index && FormatIsDepthAndStencil(depth_stencil_resolve_attachment_format) && core12_props.independentResolve == VK_FALSE && core12_props.independentResolveNone == VK_TRUE && !(resolve->depthResolveMode == resolve->stencilResolveMode || resolve->depthResolveMode == VK_RESOLVE_MODE_NONE || resolve->stencilResolveMode == VK_RESOLVE_MODE_NONE)) { skip |= LogError(device, "VUID-VkSubpassDescriptionDepthStencilResolve-pDepthStencilResolveAttachment-03186", "%s: Subpass %u includes a VkSubpassDescriptionDepthStencilResolve " "structure. The values of depthResolveMode (%u) and stencilResolveMode (%u) must be identical, or " "one of them must be %u.", function_name, i, resolve->depthResolveMode, resolve->stencilResolveMode, VK_RESOLVE_MODE_NONE); } // VK_QCOM_render_pass_shader_resolve check of depth/stencil attachmnent if (((subpass.flags & VK_SUBPASS_DESCRIPTION_SHADER_RESOLVE_BIT_QCOM) != 0) && (resolve_attachment_not_unused)) { skip |= LogError(device, "VUID-VkSubpassDescription-flags-03342", "%s: Subpass %u enables shader resolve, which requires the depth/stencil resolve attachment" " must be VK_ATTACHMENT_UNUSED, but a reference to attachment %u was found instead.", function_name, i, resolve->pDepthStencilResolveAttachment->attachment); } } return skip; } bool CoreChecks::ValidateCreateRenderPass2(VkDevice device, const VkRenderPassCreateInfo2 *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkRenderPass *pRenderPass, const char *function_name) const { bool skip = false; if (device_extensions.vk_khr_depth_stencil_resolve) { skip |= ValidateDepthStencilResolve(phys_dev_props_core12, pCreateInfo, function_name); } skip |= ValidateFragmentShadingRateAttachments(device, pCreateInfo); safe_VkRenderPassCreateInfo2 create_info_2(pCreateInfo); skip |= ValidateCreateRenderPass(device, RENDER_PASS_VERSION_2, create_info_2.ptr(), function_name); return skip; } bool CoreChecks::ValidateFragmentShadingRateAttachments(VkDevice device, const VkRenderPassCreateInfo2 *pCreateInfo) const { bool skip = false; if (enabled_features.fragment_shading_rate_features.attachmentFragmentShadingRate) { for (uint32_t attachment_description = 0; attachment_description < pCreateInfo->attachmentCount; ++attachment_description) { std::vector<uint32_t> used_as_fragment_shading_rate_attachment; // Prepass to find any use as a fragment shading rate attachment structures and validate them independently for (uint32_t subpass = 0; subpass < pCreateInfo->subpassCount; ++subpass) { const VkFragmentShadingRateAttachmentInfoKHR *fragment_shading_rate_attachment = LvlFindInChain<VkFragmentShadingRateAttachmentInfoKHR>(pCreateInfo->pSubpasses[subpass].pNext); if (fragment_shading_rate_attachment && fragment_shading_rate_attachment->pFragmentShadingRateAttachment) { const VkAttachmentReference2 &attachment_reference = *(fragment_shading_rate_attachment->pFragmentShadingRateAttachment); if (attachment_reference.attachment == attachment_description) { used_as_fragment_shading_rate_attachment.push_back(subpass); } if (((pCreateInfo->flags & VK_RENDER_PASS_CREATE_TRANSFORM_BIT_QCOM) != 0) && (attachment_reference.attachment != VK_ATTACHMENT_UNUSED)) { skip |= LogError(device, "VUID-VkRenderPassCreateInfo2-flags-04521", "vkCreateRenderPass2: Render pass includes VK_RENDER_PASS_CREATE_TRANSFORM_BIT_QCOM but " "a fragment shading rate attachment is specified in subpass %u.", subpass); } if (attachment_reference.attachment != VK_ATTACHMENT_UNUSED) { const VkFormatFeatureFlags potential_format_features = GetPotentialFormatFeatures(pCreateInfo->pAttachments[attachment_reference.attachment].format); if (!(potential_format_features & VK_FORMAT_FEATURE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR)) { skip |= LogError(device, "VUID-VkRenderPassCreateInfo2-pAttachments-04586", "vkCreateRenderPass2: Attachment description %u is used in subpass %u as a fragment " "shading rate attachment, but specifies format %s, which does not support " "VK_FORMAT_FEATURE_FRAGMENT_SHADING_RATE_ATTACHMENT_BIT_KHR.", attachment_reference.attachment, subpass, string_VkFormat(pCreateInfo->pAttachments[attachment_reference.attachment].format)); } if (attachment_reference.layout != VK_IMAGE_LAYOUT_GENERAL && attachment_reference.layout != VK_IMAGE_LAYOUT_FRAGMENT_SHADING_RATE_ATTACHMENT_OPTIMAL_KHR) { skip |= LogError( device, "VUID-VkFragmentShadingRateAttachmentInfoKHR-pFragmentShadingRateAttachment-04524", "vkCreateRenderPass2: Fragment shading rate attachment in subpass %u specifies a layout of %s.", subpass, string_VkImageLayout(attachment_reference.layout)); } if (!IsPowerOfTwo(fragment_shading_rate_attachment->shadingRateAttachmentTexelSize.width)) { skip |= LogError(device, "VUID-VkFragmentShadingRateAttachmentInfoKHR-pFragmentShadingRateAttachment-04525", "vkCreateRenderPass2: Fragment shading rate attachment in subpass %u has a " "non-power-of-two texel width of %u.", subpass, fragment_shading_rate_attachment->shadingRateAttachmentTexelSize.width); } if (fragment_shading_rate_attachment->shadingRateAttachmentTexelSize.width < phys_dev_ext_props.fragment_shading_rate_props.minFragmentShadingRateAttachmentTexelSize.width) { LogError( device, "VUID-VkFragmentShadingRateAttachmentInfoKHR-pFragmentShadingRateAttachment-04526", "vkCreateRenderPass2: Fragment shading rate attachment in subpass %u has a texel width of %u which " "is lower than the advertised minimum width %u.", subpass, fragment_shading_rate_attachment->shadingRateAttachmentTexelSize.width, phys_dev_ext_props.fragment_shading_rate_props.minFragmentShadingRateAttachmentTexelSize.width); } if (fragment_shading_rate_attachment->shadingRateAttachmentTexelSize.width > phys_dev_ext_props.fragment_shading_rate_props.maxFragmentShadingRateAttachmentTexelSize.width) { LogError( device, "VUID-VkFragmentShadingRateAttachmentInfoKHR-pFragmentShadingRateAttachment-04527", "vkCreateRenderPass2: Fragment shading rate attachment in subpass %u has a texel width of %u which " "is higher than the advertised maximum width %u.", subpass, fragment_shading_rate_attachment->shadingRateAttachmentTexelSize.width, phys_dev_ext_props.fragment_shading_rate_props.maxFragmentShadingRateAttachmentTexelSize.width); } if (!IsPowerOfTwo(fragment_shading_rate_attachment->shadingRateAttachmentTexelSize.height)) { skip |= LogError(device, "VUID-VkFragmentShadingRateAttachmentInfoKHR-pFragmentShadingRateAttachment-04528", "vkCreateRenderPass2: Fragment shading rate attachment in subpass %u has a " "non-power-of-two texel height of %u.", subpass, fragment_shading_rate_attachment->shadingRateAttachmentTexelSize.height); } if (fragment_shading_rate_attachment->shadingRateAttachmentTexelSize.height < phys_dev_ext_props.fragment_shading_rate_props.minFragmentShadingRateAttachmentTexelSize.height) { LogError( device, "VUID-VkFragmentShadingRateAttachmentInfoKHR-pFragmentShadingRateAttachment-04529", "vkCreateRenderPass2: Fragment shading rate attachment in subpass %u has a texel height of %u " "which is lower than the advertised minimum height %u.", subpass, fragment_shading_rate_attachment->shadingRateAttachmentTexelSize.height, phys_dev_ext_props.fragment_shading_rate_props.minFragmentShadingRateAttachmentTexelSize.height); } if (fragment_shading_rate_attachment->shadingRateAttachmentTexelSize.height > phys_dev_ext_props.fragment_shading_rate_props.maxFragmentShadingRateAttachmentTexelSize.height) { LogError( device, "VUID-VkFragmentShadingRateAttachmentInfoKHR-pFragmentShadingRateAttachment-04530", "vkCreateRenderPass2: Fragment shading rate attachment in subpass %u has a texel height of %u " "which is higher than the advertised maximum height %u.", subpass, fragment_shading_rate_attachment->shadingRateAttachmentTexelSize.height, phys_dev_ext_props.fragment_shading_rate_props.maxFragmentShadingRateAttachmentTexelSize.height); } uint32_t aspect_ratio = fragment_shading_rate_attachment->shadingRateAttachmentTexelSize.width / fragment_shading_rate_attachment->shadingRateAttachmentTexelSize.height; uint32_t inverse_aspect_ratio = fragment_shading_rate_attachment->shadingRateAttachmentTexelSize.height / fragment_shading_rate_attachment->shadingRateAttachmentTexelSize.width; if (aspect_ratio > phys_dev_ext_props.fragment_shading_rate_props.maxFragmentShadingRateAttachmentTexelSizeAspectRatio) { LogError( device, "VUID-VkFragmentShadingRateAttachmentInfoKHR-pFragmentShadingRateAttachment-04531", "vkCreateRenderPass2: Fragment shading rate attachment in subpass %u has a texel size of %u by %u, " "which has an aspect ratio %u, which is higher than the advertised maximum aspect ratio %u.", subpass, fragment_shading_rate_attachment->shadingRateAttachmentTexelSize.width, fragment_shading_rate_attachment->shadingRateAttachmentTexelSize.height, aspect_ratio, phys_dev_ext_props.fragment_shading_rate_props .maxFragmentShadingRateAttachmentTexelSizeAspectRatio); } if (inverse_aspect_ratio > phys_dev_ext_props.fragment_shading_rate_props.maxFragmentShadingRateAttachmentTexelSizeAspectRatio) { LogError( device, "VUID-VkFragmentShadingRateAttachmentInfoKHR-pFragmentShadingRateAttachment-04532", "vkCreateRenderPass2: Fragment shading rate attachment in subpass %u has a texel size of %u by %u, " "which has an inverse aspect ratio of %u, which is higher than the advertised maximum aspect ratio " "%u.", subpass, fragment_shading_rate_attachment->shadingRateAttachmentTexelSize.width, fragment_shading_rate_attachment->shadingRateAttachmentTexelSize.height, inverse_aspect_ratio, phys_dev_ext_props.fragment_shading_rate_props .maxFragmentShadingRateAttachmentTexelSizeAspectRatio); } } } } // Lambda function turning a vector of integers into a string auto vector_to_string = [&](std::vector<uint32_t> vector) { std::stringstream ss; size_t size = vector.size(); for (size_t i = 0; i < used_as_fragment_shading_rate_attachment.size(); i++) { if (size == 2 && i == 1) { ss << " and "; } else if (size > 2 && i == size - 2) { ss << ", and "; } else if (i != 0) { ss << ", "; } ss << vector[i]; } return ss.str(); }; // Search for other uses of the same attachment if (!used_as_fragment_shading_rate_attachment.empty()) { for (uint32_t subpass = 0; subpass < pCreateInfo->subpassCount; ++subpass) { const VkSubpassDescription2 &subpass_info = pCreateInfo->pSubpasses[subpass]; const VkSubpassDescriptionDepthStencilResolve *depth_stencil_resolve_attachment = LvlFindInChain<VkSubpassDescriptionDepthStencilResolve>(subpass_info.pNext); std::string fsr_attachment_subpasses_string = vector_to_string(used_as_fragment_shading_rate_attachment); for (uint32_t attachment = 0; attachment < subpass_info.colorAttachmentCount; ++attachment) { if (subpass_info.pColorAttachments[attachment].attachment == attachment_description) { skip |= LogError( device, "VUID-VkRenderPassCreateInfo2-pAttachments-04585", "vkCreateRenderPass2: Attachment description %u is used as a fragment shading rate attachment in " "subpass(es) %s but also as color attachment %u in subpass %u", attachment_description, fsr_attachment_subpasses_string.c_str(), attachment, subpass); } } for (uint32_t attachment = 0; attachment < subpass_info.colorAttachmentCount; ++attachment) { if (subpass_info.pResolveAttachments && subpass_info.pResolveAttachments[attachment].attachment == attachment_description) { skip |= LogError( device, "VUID-VkRenderPassCreateInfo2-pAttachments-04585", "vkCreateRenderPass2: Attachment description %u is used as a fragment shading rate attachment in " "subpass(es) %s but also as color resolve attachment %u in subpass %u", attachment_description, fsr_attachment_subpasses_string.c_str(), attachment, subpass); } } for (uint32_t attachment = 0; attachment < subpass_info.inputAttachmentCount; ++attachment) { if (subpass_info.pInputAttachments[attachment].attachment == attachment_description) { skip |= LogError( device, "VUID-VkRenderPassCreateInfo2-pAttachments-04585", "vkCreateRenderPass2: Attachment description %u is used as a fragment shading rate attachment in " "subpass(es) %s but also as input attachment %u in subpass %u", attachment_description, fsr_attachment_subpasses_string.c_str(), attachment, subpass); } } if (subpass_info.pDepthStencilAttachment) { if (subpass_info.pDepthStencilAttachment->attachment == attachment_description) { skip |= LogError( device, "VUID-VkRenderPassCreateInfo2-pAttachments-04585", "vkCreateRenderPass2: Attachment description %u is used as a fragment shading rate attachment in " "subpass(es) %s but also as the depth/stencil attachment in subpass %u", attachment_description, fsr_attachment_subpasses_string.c_str(), subpass); } } if (depth_stencil_resolve_attachment && depth_stencil_resolve_attachment->pDepthStencilResolveAttachment) { if (depth_stencil_resolve_attachment->pDepthStencilResolveAttachment->attachment == attachment_description) { skip |= LogError( device, "VUID-VkRenderPassCreateInfo2-pAttachments-04585", "vkCreateRenderPass2: Attachment description %u is used as a fragment shading rate attachment in " "subpass(es) %s but also as the depth/stencil resolve attachment in subpass %u", attachment_description, fsr_attachment_subpasses_string.c_str(), subpass); } } } } } } return skip; } bool CoreChecks::PreCallValidateCreateRenderPass2KHR(VkDevice device, const VkRenderPassCreateInfo2 *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkRenderPass *pRenderPass) const { return ValidateCreateRenderPass2(device, pCreateInfo, pAllocator, pRenderPass, "vkCreateRenderPass2KHR()"); } bool CoreChecks::PreCallValidateCreateRenderPass2(VkDevice device, const VkRenderPassCreateInfo2 *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkRenderPass *pRenderPass) const { return ValidateCreateRenderPass2(device, pCreateInfo, pAllocator, pRenderPass, "vkCreateRenderPass2()"); } bool CoreChecks::ValidatePrimaryCommandBuffer(const CMD_BUFFER_STATE *pCB, char const *cmd_name, const char *error_code) const { bool skip = false; if (pCB->createInfo.level != VK_COMMAND_BUFFER_LEVEL_PRIMARY) { skip |= LogError(pCB->commandBuffer(), error_code, "Cannot execute command %s on a secondary command buffer.", cmd_name); } return skip; } bool CoreChecks::VerifyRenderAreaBounds(const VkRenderPassBeginInfo *pRenderPassBegin, const char *func_name) const { bool skip = false; bool device_group = false; uint32_t device_group_area_count = 0; if (device_extensions.vk_khr_device_group) { device_group = true; const VkDeviceGroupRenderPassBeginInfo *device_group_render_pass_begin_info = LvlFindInChain<VkDeviceGroupRenderPassBeginInfo>(pRenderPassBegin->pNext); if (device_group_render_pass_begin_info) { device_group_area_count = device_group_render_pass_begin_info->deviceRenderAreaCount; } } if (device_group && device_group_area_count > 0) { return skip; } const safe_VkFramebufferCreateInfo *framebuffer_info = &GetFramebufferState(pRenderPassBegin->framebuffer)->createInfo; if (pRenderPassBegin->renderArea.offset.x < 0) { if (device_group) { skip |= LogError(pRenderPassBegin->renderPass, "VUID-VkRenderPassBeginInfo-pNext-02850", "%s: Cannot execute a render pass with renderArea not within the bound of the framebuffer and pNext " "of VkRenderPassBeginInfo does not contain VkDeviceGroupRenderPassBeginInfo or its " "deviceRenderAreaCount is 0, renderArea.offset.x is negative (%" PRIi32 ") .", func_name, pRenderPassBegin->renderArea.offset.x); } else { skip |= LogError(pRenderPassBegin->renderPass, "VUID-VkRenderPassBeginInfo-renderArea-02846", "%s: Cannot execute a render pass with renderArea not within the bound of the framebuffer, " "renderArea.offset.x is negative (%" PRIi32 ") .", func_name, pRenderPassBegin->renderArea.offset.x); } } if (pRenderPassBegin->renderArea.offset.y < 0) { if (device_group) { skip |= LogError(pRenderPassBegin->renderPass, "VUID-VkRenderPassBeginInfo-pNext-02851", "%s: Cannot execute a render pass with renderArea not within the bound of the framebuffer and pNext " "of VkRenderPassBeginInfo does not contain VkDeviceGroupRenderPassBeginInfo or its " "deviceRenderAreaCount is 0, renderArea.offset.y is negative (%" PRIi32 ") .", func_name, pRenderPassBegin->renderArea.offset.y); } else { skip |= LogError(pRenderPassBegin->renderPass, "VUID-VkRenderPassBeginInfo-renderArea-02847", "%s: Cannot execute a render pass with renderArea not within the bound of the framebuffer, " "renderArea.offset.y is negative (%" PRIi32 ") .", func_name, pRenderPassBegin->renderArea.offset.y); } } if ((pRenderPassBegin->renderArea.offset.x + pRenderPassBegin->renderArea.extent.width) > framebuffer_info->width) { if (device_group) { skip |= LogError(pRenderPassBegin->renderPass, "VUID-VkRenderPassBeginInfo-pNext-02852", "%s: Cannot execute a render pass with renderArea not within the bound of the framebuffer and pNext " "of VkRenderPassBeginInfo does not contain VkDeviceGroupRenderPassBeginInfo or its " "deviceRenderAreaCount is 0, renderArea.offset.x (%" PRIi32 ") + renderArea.extent.width (%" PRIi32 ") is greater than framebuffer width (%" PRIi32 ").", func_name, pRenderPassBegin->renderArea.offset.x, pRenderPassBegin->renderArea.extent.width, framebuffer_info->width); } else { skip |= LogError( pRenderPassBegin->renderPass, "VUID-VkRenderPassBeginInfo-renderArea-02848", "%s: Cannot execute a render pass with renderArea not within the bound of the framebuffer, renderArea.offset.x " "(%" PRIi32 ") + renderArea.extent.width (%" PRIi32 ") is greater than framebuffer width (%" PRIi32 ").", func_name, pRenderPassBegin->renderArea.offset.x, pRenderPassBegin->renderArea.extent.width, framebuffer_info->width); } } if ((pRenderPassBegin->renderArea.offset.y + pRenderPassBegin->renderArea.extent.height) > framebuffer_info->height) { if (device_group) { skip |= LogError(pRenderPassBegin->renderPass, "VUID-VkRenderPassBeginInfo-pNext-02853", "%s: Cannot execute a render pass with renderArea not within the bound of the framebuffer and pNext " "of VkRenderPassBeginInfo does not contain VkDeviceGroupRenderPassBeginInfo or its " "deviceRenderAreaCount is 0, renderArea.offset.y (%" PRIi32 ") + renderArea.extent.height (%" PRIi32 ") is greater than framebuffer height (%" PRIi32 ").", func_name, pRenderPassBegin->renderArea.offset.y, pRenderPassBegin->renderArea.extent.height, framebuffer_info->height); } else { skip |= LogError( pRenderPassBegin->renderPass, "VUID-VkRenderPassBeginInfo-renderArea-02849", "%s: Cannot execute a render pass with renderArea not within the bound of the framebuffer, renderArea.offset.y " "(%" PRIi32 ") + renderArea.extent.height (%" PRIi32 ") is greater than framebuffer height (%" PRIi32 ").", func_name, pRenderPassBegin->renderArea.offset.y, pRenderPassBegin->renderArea.extent.height, framebuffer_info->height); } } return skip; } bool CoreChecks::VerifyFramebufferAndRenderPassImageViews(const VkRenderPassBeginInfo *pRenderPassBeginInfo, const char *func_name) const { bool skip = false; const VkRenderPassAttachmentBeginInfo *render_pass_attachment_begin_info = LvlFindInChain<VkRenderPassAttachmentBeginInfo>(pRenderPassBeginInfo->pNext); if (render_pass_attachment_begin_info && render_pass_attachment_begin_info->attachmentCount != 0) { const safe_VkFramebufferCreateInfo *framebuffer_create_info = &GetFramebufferState(pRenderPassBeginInfo->framebuffer)->createInfo; const VkFramebufferAttachmentsCreateInfo *framebuffer_attachments_create_info = LvlFindInChain<VkFramebufferAttachmentsCreateInfo>(framebuffer_create_info->pNext); if ((framebuffer_create_info->flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT) == 0) { skip |= LogError(pRenderPassBeginInfo->renderPass, "VUID-VkRenderPassBeginInfo-framebuffer-03207", "%s: Image views specified at render pass begin, but framebuffer not created with " "VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT", func_name); } else if (framebuffer_attachments_create_info) { if (framebuffer_attachments_create_info->attachmentImageInfoCount != render_pass_attachment_begin_info->attachmentCount) { skip |= LogError(pRenderPassBeginInfo->renderPass, "VUID-VkRenderPassBeginInfo-framebuffer-03208", "%s: %u image views specified at render pass begin, but framebuffer " "created expecting %u attachments", func_name, render_pass_attachment_begin_info->attachmentCount, framebuffer_attachments_create_info->attachmentImageInfoCount); } else { const safe_VkRenderPassCreateInfo2 *render_pass_create_info = &GetRenderPassState(pRenderPassBeginInfo->renderPass)->createInfo; for (uint32_t i = 0; i < render_pass_attachment_begin_info->attachmentCount; ++i) { const auto image_view_state = GetImageViewState(render_pass_attachment_begin_info->pAttachments[i]); const VkImageViewCreateInfo *image_view_create_info = &image_view_state->create_info; const auto &subresource_range = image_view_state->normalized_subresource_range; const VkFramebufferAttachmentImageInfo *framebuffer_attachment_image_info = &framebuffer_attachments_create_info->pAttachmentImageInfos[i]; const VkImageCreateInfo *image_create_info = &GetImageState(image_view_create_info->image)->createInfo; if (framebuffer_attachment_image_info->flags != image_create_info->flags) { skip |= LogError(pRenderPassBeginInfo->renderPass, "VUID-VkRenderPassBeginInfo-framebuffer-03209", "%s: Image view #%u created from an image with flags set as 0x%X, " "but image info #%u used to create the framebuffer had flags set as 0x%X", func_name, i, image_create_info->flags, i, framebuffer_attachment_image_info->flags); } if (framebuffer_attachment_image_info->usage != image_view_state->inherited_usage) { // Give clearer message if this error is due to the "inherited" part or not if (image_create_info->usage == image_view_state->inherited_usage) { skip |= LogError(pRenderPassBeginInfo->renderPass, "VUID-VkRenderPassBeginInfo-framebuffer-04627", "%s: Image view #%u created from an image with usage set as 0x%X, " "but image info #%u used to create the framebuffer had usage set as 0x%X", func_name, i, image_create_info->usage, i, framebuffer_attachment_image_info->usage); } else { skip |= LogError(pRenderPassBeginInfo->renderPass, "VUID-VkRenderPassBeginInfo-framebuffer-04627", "%s: Image view #%u created from an image with usage set as 0x%X but using " "VkImageViewUsageCreateInfo the inherited usage is the subset 0x%X " "and the image info #%u used to create the framebuffer had usage set as 0x%X", func_name, i, image_create_info->usage, image_view_state->inherited_usage, i, framebuffer_attachment_image_info->usage); } } uint32_t view_width = image_create_info->extent.width >> subresource_range.baseMipLevel; if (framebuffer_attachment_image_info->width != view_width) { skip |= LogError(pRenderPassBeginInfo->renderPass, "VUID-VkRenderPassBeginInfo-framebuffer-03211", "%s: Image view #%u created from an image subresource with width set as %u, " "but image info #%u used to create the framebuffer had width set as %u", func_name, i, view_width, i, framebuffer_attachment_image_info->width); } uint32_t view_height = image_create_info->extent.height >> subresource_range.baseMipLevel; if (framebuffer_attachment_image_info->height != view_height) { skip |= LogError(pRenderPassBeginInfo->renderPass, "VUID-VkRenderPassBeginInfo-framebuffer-03212", "%s: Image view #%u created from an image subresource with height set as %u, " "but image info #%u used to create the framebuffer had height set as %u", func_name, i, view_height, i, framebuffer_attachment_image_info->height); } if (framebuffer_attachment_image_info->layerCount != subresource_range.layerCount) { skip |= LogError(pRenderPassBeginInfo->renderPass, "VUID-VkRenderPassBeginInfo-framebuffer-03213", "%s: Image view #%u created with a subresource range with a layerCount of %u, " "but image info #%u used to create the framebuffer had layerCount set as %u", func_name, i, subresource_range.layerCount, i, framebuffer_attachment_image_info->layerCount); } const VkImageFormatListCreateInfo *image_format_list_create_info = LvlFindInChain<VkImageFormatListCreateInfo>(image_create_info->pNext); if (image_format_list_create_info) { if (image_format_list_create_info->viewFormatCount != framebuffer_attachment_image_info->viewFormatCount) { skip |= LogError( pRenderPassBeginInfo->renderPass, "VUID-VkRenderPassBeginInfo-framebuffer-03214", "VkRenderPassBeginInfo: Image view #%u created with an image with a viewFormatCount of %u, " "but image info #%u used to create the framebuffer had viewFormatCount set as %u", i, image_format_list_create_info->viewFormatCount, i, framebuffer_attachment_image_info->viewFormatCount); } for (uint32_t j = 0; j < image_format_list_create_info->viewFormatCount; ++j) { bool format_found = false; for (uint32_t k = 0; k < framebuffer_attachment_image_info->viewFormatCount; ++k) { if (image_format_list_create_info->pViewFormats[j] == framebuffer_attachment_image_info->pViewFormats[k]) { format_found = true; } } if (!format_found) { skip |= LogError(pRenderPassBeginInfo->renderPass, "VUID-VkRenderPassBeginInfo-framebuffer-03215", "VkRenderPassBeginInfo: Image view #%u created with an image including the format " "%s in its view format list, " "but image info #%u used to create the framebuffer does not include this format", i, string_VkFormat(image_format_list_create_info->pViewFormats[j]), i); } } } if (render_pass_create_info->pAttachments[i].format != image_view_create_info->format) { skip |= LogError(pRenderPassBeginInfo->renderPass, "VUID-VkRenderPassBeginInfo-framebuffer-03216", "%s: Image view #%u created with a format of %s, " "but render pass attachment description #%u created with a format of %s", func_name, i, string_VkFormat(image_view_create_info->format), i, string_VkFormat(render_pass_create_info->pAttachments[i].format)); } if (render_pass_create_info->pAttachments[i].samples != image_create_info->samples) { skip |= LogError(pRenderPassBeginInfo->renderPass, "VUID-VkRenderPassBeginInfo-framebuffer-03217", "%s: Image view #%u created with an image with %s samples, " "but render pass attachment description #%u created with %s samples", func_name, i, string_VkSampleCountFlagBits(image_create_info->samples), i, string_VkSampleCountFlagBits(render_pass_create_info->pAttachments[i].samples)); } if (subresource_range.levelCount != 1) { skip |= LogError(render_pass_attachment_begin_info->pAttachments[i], "VUID-VkRenderPassAttachmentBeginInfo-pAttachments-03218", "%s: Image view #%u created with multiple (%u) mip levels.", func_name, i, subresource_range.levelCount); } if (IsIdentitySwizzle(image_view_create_info->components) == false) { skip |= LogError( render_pass_attachment_begin_info->pAttachments[i], "VUID-VkRenderPassAttachmentBeginInfo-pAttachments-03219", "%s: Image view #%u created with non-identity swizzle. All " "framebuffer attachments must have been created with the identity swizzle. Here are the actual " "swizzle values:\n" "r swizzle = %s\n" "g swizzle = %s\n" "b swizzle = %s\n" "a swizzle = %s\n", func_name, i, string_VkComponentSwizzle(image_view_create_info->components.r), string_VkComponentSwizzle(image_view_create_info->components.g), string_VkComponentSwizzle(image_view_create_info->components.b), string_VkComponentSwizzle(image_view_create_info->components.a)); } if (image_view_create_info->viewType == VK_IMAGE_VIEW_TYPE_3D) { skip |= LogError(render_pass_attachment_begin_info->pAttachments[i], "VUID-VkRenderPassAttachmentBeginInfo-pAttachments-04114", "%s: Image view #%u created with type VK_IMAGE_VIEW_TYPE_3D", func_name, i); } } } } } return skip; } // If this is a stencil format, make sure the stencil[Load|Store]Op flag is checked, while if it is a depth/color attachment the // [load|store]Op flag must be checked // TODO: The memory valid flag in DEVICE_MEMORY_STATE should probably be split to track the validity of stencil memory separately. template <typename T> static bool FormatSpecificLoadAndStoreOpSettings(VkFormat format, T color_depth_op, T stencil_op, T op) { if (color_depth_op != op && stencil_op != op) { return false; } bool check_color_depth_load_op = !FormatIsStencilOnly(format); bool check_stencil_load_op = FormatIsDepthAndStencil(format) || !check_color_depth_load_op; return ((check_color_depth_load_op && (color_depth_op == op)) || (check_stencil_load_op && (stencil_op == op))); } bool CoreChecks::ValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, RenderPassCreateVersion rp_version, const VkRenderPassBeginInfo *pRenderPassBegin) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); auto render_pass_state = pRenderPassBegin ? GetRenderPassState(pRenderPassBegin->renderPass) : nullptr; auto framebuffer = pRenderPassBegin ? GetFramebufferState(pRenderPassBegin->framebuffer) : nullptr; bool skip = false; const bool use_rp2 = (rp_version == RENDER_PASS_VERSION_2); const char *const function_name = use_rp2 ? "vkCmdBeginRenderPass2()" : "vkCmdBeginRenderPass()"; if (render_pass_state) { uint32_t clear_op_size = 0; // Make sure pClearValues is at least as large as last LOAD_OP_CLEAR // Handle extension struct from EXT_sample_locations const VkRenderPassSampleLocationsBeginInfoEXT *sample_locations_begin_info = LvlFindInChain<VkRenderPassSampleLocationsBeginInfoEXT>(pRenderPassBegin->pNext); if (sample_locations_begin_info) { for (uint32_t i = 0; i < sample_locations_begin_info->attachmentInitialSampleLocationsCount; ++i) { const VkAttachmentSampleLocationsEXT &sample_location = sample_locations_begin_info->pAttachmentInitialSampleLocations[i]; skip |= ValidateSampleLocationsInfo(&sample_location.sampleLocationsInfo, function_name); if (sample_location.attachmentIndex >= render_pass_state->createInfo.attachmentCount) { skip |= LogError(device, "VUID-VkAttachmentSampleLocationsEXT-attachmentIndex-01531", "%s: Attachment index %u specified by attachment sample locations %u is greater than the " "attachment count of %u for the render pass being begun.", function_name, sample_location.attachmentIndex, i, render_pass_state->createInfo.attachmentCount); } } for (uint32_t i = 0; i < sample_locations_begin_info->postSubpassSampleLocationsCount; ++i) { const VkSubpassSampleLocationsEXT &sample_location = sample_locations_begin_info->pPostSubpassSampleLocations[i]; skip |= ValidateSampleLocationsInfo(&sample_location.sampleLocationsInfo, function_name); if (sample_location.subpassIndex >= render_pass_state->createInfo.subpassCount) { skip |= LogError(device, "VUID-VkSubpassSampleLocationsEXT-subpassIndex-01532", "%s: Subpass index %u specified by subpass sample locations %u is greater than the subpass count " "of %u for the render pass being begun.", function_name, sample_location.subpassIndex, i, render_pass_state->createInfo.subpassCount); } } } for (uint32_t i = 0; i < render_pass_state->createInfo.attachmentCount; ++i) { auto attachment = &render_pass_state->createInfo.pAttachments[i]; if (FormatSpecificLoadAndStoreOpSettings(attachment->format, attachment->loadOp, attachment->stencilLoadOp, VK_ATTACHMENT_LOAD_OP_CLEAR)) { clear_op_size = static_cast<uint32_t>(i) + 1; if (FormatHasDepth(attachment->format)) { skip |= ValidateClearDepthStencilValue(commandBuffer, pRenderPassBegin->pClearValues[i].depthStencil, function_name); } } } if (clear_op_size > pRenderPassBegin->clearValueCount) { skip |= LogError(render_pass_state->renderPass(), "VUID-VkRenderPassBeginInfo-clearValueCount-00902", "In %s the VkRenderPassBeginInfo struct has a clearValueCount of %u but there " "must be at least %u entries in pClearValues array to account for the highest index attachment in " "%s that uses VK_ATTACHMENT_LOAD_OP_CLEAR is %u. Note that the pClearValues array is indexed by " "attachment number so even if some pClearValues entries between 0 and %u correspond to attachments " "that aren't cleared they will be ignored.", function_name, pRenderPassBegin->clearValueCount, clear_op_size, report_data->FormatHandle(render_pass_state->renderPass()).c_str(), clear_op_size, clear_op_size - 1); } skip |= VerifyFramebufferAndRenderPassImageViews(pRenderPassBegin, function_name); skip |= VerifyRenderAreaBounds(pRenderPassBegin, function_name); skip |= VerifyFramebufferAndRenderPassLayouts(rp_version, cb_state, pRenderPassBegin, GetFramebufferState(pRenderPassBegin->framebuffer)); if (framebuffer->rp_state->renderPass() != render_pass_state->renderPass()) { skip |= ValidateRenderPassCompatibility("render pass", render_pass_state, "framebuffer", framebuffer->rp_state.get(), function_name, "VUID-VkRenderPassBeginInfo-renderPass-00904"); } skip |= ValidateDependencies(framebuffer, render_pass_state); const CMD_TYPE cmd_type = use_rp2 ? CMD_BEGINRENDERPASS2 : CMD_BEGINRENDERPASS; skip |= ValidateCmd(cb_state, cmd_type, function_name); } auto chained_device_group_struct = LvlFindInChain<VkDeviceGroupRenderPassBeginInfo>(pRenderPassBegin->pNext); if (chained_device_group_struct) { skip |= ValidateDeviceMaskToPhysicalDeviceCount(chained_device_group_struct->deviceMask, pRenderPassBegin->renderPass, "VUID-VkDeviceGroupRenderPassBeginInfo-deviceMask-00905"); skip |= ValidateDeviceMaskToZero(chained_device_group_struct->deviceMask, pRenderPassBegin->renderPass, "VUID-VkDeviceGroupRenderPassBeginInfo-deviceMask-00906"); skip |= ValidateDeviceMaskToCommandBuffer(cb_state, chained_device_group_struct->deviceMask, pRenderPassBegin->renderPass, "VUID-VkDeviceGroupRenderPassBeginInfo-deviceMask-00907"); if (chained_device_group_struct->deviceRenderAreaCount != 0 && chained_device_group_struct->deviceRenderAreaCount != physical_device_count) { skip |= LogError(pRenderPassBegin->renderPass, "VUID-VkDeviceGroupRenderPassBeginInfo-deviceRenderAreaCount-00908", "%s: deviceRenderAreaCount[%" PRIu32 "] is invaild. Physical device count is %" PRIu32 ".", function_name, chained_device_group_struct->deviceRenderAreaCount, physical_device_count); } } return skip; } bool CoreChecks::PreCallValidateCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin, VkSubpassContents contents) const { bool skip = ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_1, pRenderPassBegin); return skip; } bool CoreChecks::PreCallValidateCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin, const VkSubpassBeginInfo *pSubpassBeginInfo) const { bool skip = ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin); return skip; } bool CoreChecks::PreCallValidateCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin, const VkSubpassBeginInfo *pSubpassBeginInfo) const { bool skip = ValidateCmdBeginRenderPass(commandBuffer, RENDER_PASS_VERSION_2, pRenderPassBegin); return skip; } void CoreChecks::RecordCmdBeginRenderPassLayouts(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin, const VkSubpassContents contents) { CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); auto render_pass_state = pRenderPassBegin ? GetRenderPassState(pRenderPassBegin->renderPass) : nullptr; auto framebuffer = pRenderPassBegin ? GetFramebufferState(pRenderPassBegin->framebuffer) : nullptr; if (render_pass_state) { // transition attachments to the correct layouts for beginning of renderPass and first subpass TransitionBeginRenderPassLayouts(cb_state, render_pass_state, framebuffer); } } void CoreChecks::PreCallRecordCmdBeginRenderPass(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin, VkSubpassContents contents) { StateTracker::PreCallRecordCmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents); RecordCmdBeginRenderPassLayouts(commandBuffer, pRenderPassBegin, contents); } void CoreChecks::PreCallRecordCmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin, const VkSubpassBeginInfo *pSubpassBeginInfo) { StateTracker::PreCallRecordCmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo); RecordCmdBeginRenderPassLayouts(commandBuffer, pRenderPassBegin, pSubpassBeginInfo->contents); } void CoreChecks::PreCallRecordCmdBeginRenderPass2(VkCommandBuffer commandBuffer, const VkRenderPassBeginInfo *pRenderPassBegin, const VkSubpassBeginInfo *pSubpassBeginInfo) { StateTracker::PreCallRecordCmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo); RecordCmdBeginRenderPassLayouts(commandBuffer, pRenderPassBegin, pSubpassBeginInfo->contents); } bool CoreChecks::ValidateCmdNextSubpass(RenderPassCreateVersion rp_version, VkCommandBuffer commandBuffer) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); bool skip = false; const bool use_rp2 = (rp_version == RENDER_PASS_VERSION_2); const char *vuid; const char *const function_name = use_rp2 ? "vkCmdNextSubpass2()" : "vkCmdNextSubpass()"; const CMD_TYPE cmd_type = use_rp2 ? CMD_NEXTSUBPASS2 : CMD_NEXTSUBPASS; skip |= ValidateCmd(cb_state, cmd_type, function_name); auto subpass_count = cb_state->activeRenderPass->createInfo.subpassCount; if (cb_state->activeSubpass == subpass_count - 1) { vuid = use_rp2 ? "VUID-vkCmdNextSubpass2-None-03102" : "VUID-vkCmdNextSubpass-None-00909"; skip |= LogError(commandBuffer, vuid, "%s: Attempted to advance beyond final subpass.", function_name); } return skip; } bool CoreChecks::PreCallValidateCmdNextSubpass(VkCommandBuffer commandBuffer, VkSubpassContents contents) const { return ValidateCmdNextSubpass(RENDER_PASS_VERSION_1, commandBuffer); } bool CoreChecks::PreCallValidateCmdNextSubpass2KHR(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo, const VkSubpassEndInfo *pSubpassEndInfo) const { return ValidateCmdNextSubpass(RENDER_PASS_VERSION_2, commandBuffer); } bool CoreChecks::PreCallValidateCmdNextSubpass2(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo, const VkSubpassEndInfo *pSubpassEndInfo) const { return ValidateCmdNextSubpass(RENDER_PASS_VERSION_2, commandBuffer); } void CoreChecks::RecordCmdNextSubpassLayouts(VkCommandBuffer commandBuffer, VkSubpassContents contents) { CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); TransitionSubpassLayouts(cb_state, cb_state->activeRenderPass.get(), cb_state->activeSubpass, Get<FRAMEBUFFER_STATE>(cb_state->activeRenderPassBeginInfo.framebuffer)); } void CoreChecks::PostCallRecordCmdNextSubpass(VkCommandBuffer commandBuffer, VkSubpassContents contents) { StateTracker::PostCallRecordCmdNextSubpass(commandBuffer, contents); RecordCmdNextSubpassLayouts(commandBuffer, contents); } void CoreChecks::PostCallRecordCmdNextSubpass2KHR(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo, const VkSubpassEndInfo *pSubpassEndInfo) { StateTracker::PostCallRecordCmdNextSubpass2KHR(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo); RecordCmdNextSubpassLayouts(commandBuffer, pSubpassBeginInfo->contents); } void CoreChecks::PostCallRecordCmdNextSubpass2(VkCommandBuffer commandBuffer, const VkSubpassBeginInfo *pSubpassBeginInfo, const VkSubpassEndInfo *pSubpassEndInfo) { StateTracker::PostCallRecordCmdNextSubpass2(commandBuffer, pSubpassBeginInfo, pSubpassEndInfo); RecordCmdNextSubpassLayouts(commandBuffer, pSubpassBeginInfo->contents); } bool CoreChecks::ValidateCmdEndRenderPass(RenderPassCreateVersion rp_version, VkCommandBuffer commandBuffer) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); bool skip = false; const bool use_rp2 = (rp_version == RENDER_PASS_VERSION_2); const char *vuid; const char *const function_name = use_rp2 ? "vkCmdEndRenderPass2KHR()" : "vkCmdEndRenderPass()"; RENDER_PASS_STATE *rp_state = cb_state->activeRenderPass.get(); if (rp_state) { if (cb_state->activeSubpass != rp_state->createInfo.subpassCount - 1) { vuid = use_rp2 ? "VUID-vkCmdEndRenderPass2-None-03103" : "VUID-vkCmdEndRenderPass-None-00910"; skip |= LogError(commandBuffer, vuid, "%s: Called before reaching final subpass.", function_name); } } const CMD_TYPE cmd_type = use_rp2 ? CMD_ENDRENDERPASS2 : CMD_ENDRENDERPASS; skip |= ValidateCmd(cb_state, cmd_type, function_name); return skip; } bool CoreChecks::PreCallValidateCmdEndRenderPass(VkCommandBuffer commandBuffer) const { bool skip = ValidateCmdEndRenderPass(RENDER_PASS_VERSION_1, commandBuffer); return skip; } bool CoreChecks::PreCallValidateCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) const { bool skip = ValidateCmdEndRenderPass(RENDER_PASS_VERSION_2, commandBuffer); return skip; } bool CoreChecks::PreCallValidateCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) const { bool skip = ValidateCmdEndRenderPass(RENDER_PASS_VERSION_2, commandBuffer); return skip; } void CoreChecks::RecordCmdEndRenderPassLayouts(VkCommandBuffer commandBuffer) { CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); TransitionFinalSubpassLayouts(cb_state, cb_state->activeRenderPassBeginInfo.ptr(), cb_state->activeFramebuffer.get()); } void CoreChecks::PostCallRecordCmdEndRenderPass(VkCommandBuffer commandBuffer) { // Record the end at the CoreLevel to ensure StateTracker cleanup doesn't step on anything we need. RecordCmdEndRenderPassLayouts(commandBuffer); StateTracker::PostCallRecordCmdEndRenderPass(commandBuffer); } void CoreChecks::PostCallRecordCmdEndRenderPass2KHR(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) { // Record the end at the CoreLevel to ensure StateTracker cleanup doesn't step on anything we need. RecordCmdEndRenderPassLayouts(commandBuffer); StateTracker::PostCallRecordCmdEndRenderPass2KHR(commandBuffer, pSubpassEndInfo); } void CoreChecks::PostCallRecordCmdEndRenderPass2(VkCommandBuffer commandBuffer, const VkSubpassEndInfo *pSubpassEndInfo) { RecordCmdEndRenderPassLayouts(commandBuffer); StateTracker::PostCallRecordCmdEndRenderPass2(commandBuffer, pSubpassEndInfo); } bool CoreChecks::ValidateFramebuffer(VkCommandBuffer primaryBuffer, const CMD_BUFFER_STATE *pCB, VkCommandBuffer secondaryBuffer, const CMD_BUFFER_STATE *pSubCB, const char *caller) const { bool skip = false; if (!pSubCB->beginInfo.pInheritanceInfo) { return skip; } VkFramebuffer primary_fb = pCB->activeFramebuffer ? pCB->activeFramebuffer->framebuffer() : VK_NULL_HANDLE; VkFramebuffer secondary_fb = pSubCB->beginInfo.pInheritanceInfo->framebuffer; if (secondary_fb != VK_NULL_HANDLE) { if (primary_fb != secondary_fb) { LogObjectList objlist(primaryBuffer); objlist.add(secondaryBuffer); objlist.add(secondary_fb); objlist.add(primary_fb); skip |= LogError(objlist, "VUID-vkCmdExecuteCommands-pCommandBuffers-00099", "vkCmdExecuteCommands() called w/ invalid secondary %s which has a %s" " that is not the same as the primary command buffer's current active %s.", report_data->FormatHandle(secondaryBuffer).c_str(), report_data->FormatHandle(secondary_fb).c_str(), report_data->FormatHandle(primary_fb).c_str()); } auto fb = GetFramebufferState(secondary_fb); if (!fb) { LogObjectList objlist(primaryBuffer); objlist.add(secondaryBuffer); objlist.add(secondary_fb); skip |= LogError(objlist, kVUID_Core_DrawState_InvalidSecondaryCommandBuffer, "vkCmdExecuteCommands() called w/ invalid %s which has invalid %s.", report_data->FormatHandle(secondaryBuffer).c_str(), report_data->FormatHandle(secondary_fb).c_str()); return skip; } } return skip; } bool CoreChecks::ValidateSecondaryCommandBufferState(const CMD_BUFFER_STATE *pCB, const CMD_BUFFER_STATE *pSubCB) const { bool skip = false; layer_data::unordered_set<int> active_types; if (!disabled[query_validation]) { for (const auto &query_object : pCB->activeQueries) { auto query_pool_state = GetQueryPoolState(query_object.pool); if (query_pool_state) { if (query_pool_state->createInfo.queryType == VK_QUERY_TYPE_PIPELINE_STATISTICS && pSubCB->beginInfo.pInheritanceInfo) { VkQueryPipelineStatisticFlags cmd_buf_statistics = pSubCB->beginInfo.pInheritanceInfo->pipelineStatistics; if ((cmd_buf_statistics & query_pool_state->createInfo.pipelineStatistics) != cmd_buf_statistics) { LogObjectList objlist(pCB->commandBuffer()); objlist.add(query_object.pool); skip |= LogError( objlist, "VUID-vkCmdExecuteCommands-commandBuffer-00104", "vkCmdExecuteCommands() called w/ invalid %s which has invalid active %s" ". Pipeline statistics is being queried so the command buffer must have all bits set on the queryPool.", report_data->FormatHandle(pCB->commandBuffer()).c_str(), report_data->FormatHandle(query_object.pool).c_str()); } } active_types.insert(query_pool_state->createInfo.queryType); } } for (const auto &query_object : pSubCB->startedQueries) { auto query_pool_state = GetQueryPoolState(query_object.pool); if (query_pool_state && active_types.count(query_pool_state->createInfo.queryType)) { LogObjectList objlist(pCB->commandBuffer()); objlist.add(query_object.pool); skip |= LogError(objlist, kVUID_Core_DrawState_InvalidSecondaryCommandBuffer, "vkCmdExecuteCommands() called w/ invalid %s which has invalid active %s" " of type %d but a query of that type has been started on secondary %s.", report_data->FormatHandle(pCB->commandBuffer()).c_str(), report_data->FormatHandle(query_object.pool).c_str(), query_pool_state->createInfo.queryType, report_data->FormatHandle(pSubCB->commandBuffer()).c_str()); } } } auto primary_pool = pCB->command_pool.get(); auto secondary_pool = pSubCB->command_pool.get(); if (primary_pool && secondary_pool && (primary_pool->queueFamilyIndex != secondary_pool->queueFamilyIndex)) { LogObjectList objlist(pSubCB->commandBuffer()); objlist.add(pCB->commandBuffer()); skip |= LogError(objlist, "VUID-vkCmdExecuteCommands-pCommandBuffers-00094", "vkCmdExecuteCommands(): Primary %s created in queue family %d has secondary " "%s created in queue family %d.", report_data->FormatHandle(pCB->commandBuffer()).c_str(), primary_pool->queueFamilyIndex, report_data->FormatHandle(pSubCB->commandBuffer()).c_str(), secondary_pool->queueFamilyIndex); } return skip; } // Object that simulates the inherited viewport/scissor state as the device executes the called secondary command buffers. // Visit the calling primary command buffer first, then the called secondaries in order. // Contact David Zhao Akeley <[email protected]> for clarifications and bug fixes. class CoreChecks::ViewportScissorInheritanceTracker { static_assert(4 == sizeof(CMD_BUFFER_STATE::viewportMask), "Adjust max_viewports to match viewportMask bit width"); static constexpr uint32_t kMaxViewports = 32, kNotTrashed = uint32_t(-2), kTrashedByPrimary = uint32_t(-1); const ValidationObject &validation_; const CMD_BUFFER_STATE *primary_state_ = nullptr; uint32_t viewport_mask_; uint32_t scissor_mask_; uint32_t viewport_trashed_by_[kMaxViewports]; // filled in VisitPrimary. uint32_t scissor_trashed_by_[kMaxViewports]; VkViewport viewports_to_inherit_[kMaxViewports]; uint32_t viewport_count_to_inherit_; // 0 if viewport count (EXT state) has never been defined (but not trashed) uint32_t scissor_count_to_inherit_; // 0 if scissor count (EXT state) has never been defined (but not trashed) uint32_t viewport_count_trashed_by_; uint32_t scissor_count_trashed_by_; public: ViewportScissorInheritanceTracker(const ValidationObject &validation) : validation_(validation) {} bool VisitPrimary(const CMD_BUFFER_STATE *primary_state) { assert(!primary_state_); primary_state_ = primary_state; viewport_mask_ = primary_state->viewportMask | primary_state->viewportWithCountMask; scissor_mask_ = primary_state->scissorMask | primary_state->scissorWithCountMask; for (uint32_t n = 0; n < kMaxViewports; ++n) { uint32_t bit = uint32_t(1) << n; viewport_trashed_by_[n] = primary_state->trashedViewportMask & bit ? kTrashedByPrimary : kNotTrashed; scissor_trashed_by_[n] = primary_state->trashedScissorMask & bit ? kTrashedByPrimary : kNotTrashed; if (viewport_mask_ & bit) { viewports_to_inherit_[n] = primary_state->dynamicViewports[n]; } } viewport_count_to_inherit_ = primary_state->viewportWithCountCount; scissor_count_to_inherit_ = primary_state->scissorWithCountCount; viewport_count_trashed_by_ = primary_state->trashedViewportCount ? kTrashedByPrimary : kNotTrashed; scissor_count_trashed_by_ = primary_state->trashedScissorCount ? kTrashedByPrimary : kNotTrashed; return false; } bool VisitSecondary(uint32_t cmd_buffer_idx, const CMD_BUFFER_STATE *secondary_state) { bool skip = false; if (secondary_state->inheritedViewportDepths.empty()) { skip |= VisitSecondaryNoInheritance(cmd_buffer_idx, secondary_state); } else { skip |= VisitSecondaryInheritance(cmd_buffer_idx, secondary_state); } // See note at end of VisitSecondaryNoInheritance. if (secondary_state->trashedViewportCount) { viewport_count_trashed_by_ = cmd_buffer_idx; } if (secondary_state->trashedScissorCount) { scissor_count_trashed_by_ = cmd_buffer_idx; } return skip; } private: // Track state inheritance as specified by VK_NV_inherited_scissor_viewport, including states // overwritten to undefined value by bound pipelines with non-dynamic state. bool VisitSecondaryNoInheritance(uint32_t cmd_buffer_idx, const CMD_BUFFER_STATE *secondary_state) { viewport_mask_ |= secondary_state->viewportMask | secondary_state->viewportWithCountMask; scissor_mask_ |= secondary_state->scissorMask | secondary_state->scissorWithCountMask; for (uint32_t n = 0; n < kMaxViewports; ++n) { uint32_t bit = uint32_t(1) << n; if ((secondary_state->viewportMask | secondary_state->viewportWithCountMask) & bit) { viewports_to_inherit_[n] = secondary_state->dynamicViewports[n]; viewport_trashed_by_[n] = kNotTrashed; } if ((secondary_state->scissorMask | secondary_state->scissorWithCountMask) & bit) { scissor_trashed_by_[n] = kNotTrashed; } if (secondary_state->viewportWithCountCount != 0) { viewport_count_to_inherit_ = secondary_state->viewportWithCountCount; viewport_count_trashed_by_ = kNotTrashed; } if (secondary_state->scissorWithCountCount != 0) { scissor_count_to_inherit_ = secondary_state->scissorWithCountCount; scissor_count_trashed_by_ = kNotTrashed; } // Order of above vs below matters here. if (secondary_state->trashedViewportMask & bit) { viewport_trashed_by_[n] = cmd_buffer_idx; } if (secondary_state->trashedScissorMask & bit) { scissor_trashed_by_[n] = cmd_buffer_idx; } // Check trashing dynamic viewport/scissor count in VisitSecondary (at end) as even secondary command buffers enabling // viewport/scissor state inheritance may define this state statically in bound graphics pipelines. } return false; } // Validate needed inherited state as specified by VK_NV_inherited_scissor_viewport. bool VisitSecondaryInheritance(uint32_t cmd_buffer_idx, const CMD_BUFFER_STATE *secondary_state) { bool skip = false; uint32_t check_viewport_count = 0, check_scissor_count = 0; // Common code for reporting missing inherited state (for a myriad of reasons). auto check_missing_inherit = [&](uint32_t was_ever_defined, uint32_t trashed_by, VkDynamicState state, uint32_t index = 0, uint32_t static_use_count = 0, const VkViewport *inherited_viewport = nullptr, const VkViewport *expected_viewport_depth = nullptr) { if (was_ever_defined && trashed_by == kNotTrashed) { if (state != VK_DYNAMIC_STATE_VIEWPORT) return false; assert(inherited_viewport != nullptr && expected_viewport_depth != nullptr); if (inherited_viewport->minDepth != expected_viewport_depth->minDepth || inherited_viewport->maxDepth != expected_viewport_depth->maxDepth) { return validation_.LogError( primary_state_->commandBuffer(), "VUID-vkCmdDraw-commandBuffer-02701", "vkCmdExecuteCommands(): Draw commands in pCommandBuffers[%u] (%s) consume inherited viewport %u %s" "but this state was not inherited as its depth range [%f, %f] does not match " "pViewportDepths[%u] = [%f, %f]", unsigned(cmd_buffer_idx), validation_.report_data->FormatHandle(secondary_state->commandBuffer()).c_str(), unsigned(index), index >= static_use_count ? "(with count) " : "", inherited_viewport->minDepth, inherited_viewport->maxDepth, unsigned(cmd_buffer_idx), expected_viewport_depth->minDepth, expected_viewport_depth->maxDepth); // akeley98 note: This VUID is not ideal; however, there isn't a more relevant VUID as // it isn't illegal in itself to have mismatched inherited viewport depths. // The error only occurs upon attempting to consume the viewport. } else { return false; } } const char *state_name; bool format_index = false; switch (state) { case VK_DYNAMIC_STATE_SCISSOR: state_name = "scissor"; format_index = true; break; case VK_DYNAMIC_STATE_VIEWPORT: state_name = "viewport"; format_index = true; break; case VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT_EXT: state_name = "dynamic viewport count"; break; case VK_DYNAMIC_STATE_SCISSOR_WITH_COUNT_EXT: state_name = "dynamic scissor count"; break; default: assert(0); state_name = "<unknown state, report bug>"; break; } std::stringstream ss; ss << "vkCmdExecuteCommands(): Draw commands in pCommandBuffers[" << cmd_buffer_idx << "] (" << validation_.report_data->FormatHandle(secondary_state->commandBuffer()).c_str() << ") consume inherited " << state_name << " "; if (format_index) { if (index >= static_use_count) { ss << "(with count) "; } ss << index << " "; } ss << "but this state "; if (!was_ever_defined) { ss << "was never defined."; } else if (trashed_by == kTrashedByPrimary) { ss << "was left undefined after vkCmdExecuteCommands or vkCmdBindPipeline (with non-dynamic state) in " "the calling primary command buffer."; } else { ss << "was left undefined after vkCmdBindPipeline (with non-dynamic state) in pCommandBuffers[" << trashed_by << "]."; } return validation_.LogError(primary_state_->commandBuffer(), "VUID-vkCmdDraw-commandBuffer-02701", "%s", ss.str().c_str()); }; // Check if secondary command buffer uses viewport/scissor-with-count state, and validate this state if so. if (secondary_state->usedDynamicViewportCount) { if (viewport_count_to_inherit_ == 0 || viewport_count_trashed_by_ != kNotTrashed) { skip |= check_missing_inherit(viewport_count_to_inherit_, viewport_count_trashed_by_, VK_DYNAMIC_STATE_VIEWPORT_WITH_COUNT_EXT); } else { check_viewport_count = viewport_count_to_inherit_; } } if (secondary_state->usedDynamicScissorCount) { if (scissor_count_to_inherit_ == 0 || scissor_count_trashed_by_ != kNotTrashed) { skip |= check_missing_inherit(scissor_count_to_inherit_, scissor_count_trashed_by_, VK_DYNAMIC_STATE_SCISSOR_WITH_COUNT_EXT); } else { check_scissor_count = scissor_count_to_inherit_; } } // Check the maximum of (viewports used by pipelines with static viewport count, "" dynamic viewport count) // but limit to length of inheritedViewportDepths array and uint32_t bit width (validation layer limit). check_viewport_count = std::min(std::min(kMaxViewports, uint32_t(secondary_state->inheritedViewportDepths.size())), std::max(check_viewport_count, secondary_state->usedViewportScissorCount)); check_scissor_count = std::min(kMaxViewports, std::max(check_scissor_count, secondary_state->usedViewportScissorCount)); if (secondary_state->usedDynamicViewportCount && viewport_count_to_inherit_ > secondary_state->inheritedViewportDepths.size()) { skip |= validation_.LogError( primary_state_->commandBuffer(), "VUID-vkCmdDraw-commandBuffer-02701", "vkCmdExecuteCommands(): " "Draw commands in pCommandBuffers[%u] (%s) consume inherited dynamic viewport with count state " "but the dynamic viewport count (%u) exceeds the inheritance limit (viewportDepthCount=%u).", unsigned(cmd_buffer_idx), validation_.report_data->FormatHandle(secondary_state->commandBuffer()).c_str(), unsigned(viewport_count_to_inherit_), unsigned(secondary_state->inheritedViewportDepths.size())); } for (uint32_t n = 0; n < check_viewport_count; ++n) { skip |= check_missing_inherit(viewport_mask_ & uint32_t(1) << n, viewport_trashed_by_[n], VK_DYNAMIC_STATE_VIEWPORT, n, secondary_state->usedViewportScissorCount, &viewports_to_inherit_[n], &secondary_state->inheritedViewportDepths[n]); } for (uint32_t n = 0; n < check_scissor_count; ++n) { skip |= check_missing_inherit(scissor_mask_ & uint32_t(1) << n, scissor_trashed_by_[n], VK_DYNAMIC_STATE_SCISSOR, n, secondary_state->usedViewportScissorCount); } return skip; } }; constexpr uint32_t CoreChecks::ViewportScissorInheritanceTracker::kMaxViewports; constexpr uint32_t CoreChecks::ViewportScissorInheritanceTracker::kNotTrashed; constexpr uint32_t CoreChecks::ViewportScissorInheritanceTracker::kTrashedByPrimary; bool CoreChecks::PreCallValidateCmdExecuteCommands(VkCommandBuffer commandBuffer, uint32_t commandBuffersCount, const VkCommandBuffer *pCommandBuffers) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); bool skip = false; const CMD_BUFFER_STATE *sub_cb_state = NULL; layer_data::unordered_set<const CMD_BUFFER_STATE *> linked_command_buffers; ViewportScissorInheritanceTracker viewport_scissor_inheritance{*this}; if (enabled_features.inherited_viewport_scissor_features.inheritedViewportScissor2D) { skip |= viewport_scissor_inheritance.VisitPrimary(cb_state); } bool active_occlusion_query = false; for (const auto& active_query : cb_state->activeQueries) { const auto query_pool_state = Get<QUERY_POOL_STATE>(active_query.pool); if (query_pool_state->createInfo.queryType == VK_QUERY_TYPE_OCCLUSION) { active_occlusion_query = true; break; } } for (uint32_t i = 0; i < commandBuffersCount; i++) { sub_cb_state = GetCBState(pCommandBuffers[i]); assert(sub_cb_state); if (enabled_features.inherited_viewport_scissor_features.inheritedViewportScissor2D) { skip |= viewport_scissor_inheritance.VisitSecondary(i, sub_cb_state); } if (VK_COMMAND_BUFFER_LEVEL_PRIMARY == sub_cb_state->createInfo.level) { skip |= LogError(pCommandBuffers[i], "VUID-vkCmdExecuteCommands-pCommandBuffers-00088", "vkCmdExecuteCommands() called w/ Primary %s in element %u of pCommandBuffers array. All " "cmd buffers in pCommandBuffers array must be secondary.", report_data->FormatHandle(pCommandBuffers[i]).c_str(), i); } else if (VK_COMMAND_BUFFER_LEVEL_SECONDARY == sub_cb_state->createInfo.level) { if (sub_cb_state->beginInfo.pInheritanceInfo != nullptr) { const auto secondary_rp_state = GetRenderPassState(sub_cb_state->beginInfo.pInheritanceInfo->renderPass); if (cb_state->activeRenderPass && !(sub_cb_state->beginInfo.flags & VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT)) { LogObjectList objlist(pCommandBuffers[i]); objlist.add(cb_state->activeRenderPass->renderPass()); skip |= LogError(objlist, "VUID-vkCmdExecuteCommands-pCommandBuffers-00096", "vkCmdExecuteCommands(): Secondary %s is executed within a %s " "instance scope, but the Secondary Command Buffer does not have the " "VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT set in VkCommandBufferBeginInfo::flags when " "the vkBeginCommandBuffer() was called.", report_data->FormatHandle(pCommandBuffers[i]).c_str(), report_data->FormatHandle(cb_state->activeRenderPass->renderPass()).c_str()); } else if (!cb_state->activeRenderPass && (sub_cb_state->beginInfo.flags & VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT)) { skip |= LogError(pCommandBuffers[i], "VUID-vkCmdExecuteCommands-pCommandBuffers-00100", "vkCmdExecuteCommands(): Secondary %s is executed outside a render pass " "instance scope, but the Secondary Command Buffer does have the " "VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT set in VkCommandBufferBeginInfo::flags when " "the vkBeginCommandBuffer() was called.", report_data->FormatHandle(pCommandBuffers[i]).c_str()); } else if (cb_state->activeRenderPass && (sub_cb_state->beginInfo.flags & VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT)) { // Make sure render pass is compatible with parent command buffer pass if has continue if (cb_state->activeRenderPass->renderPass() != secondary_rp_state->renderPass()) { skip |= ValidateRenderPassCompatibility( "primary command buffer", cb_state->activeRenderPass.get(), "secondary command buffer", secondary_rp_state, "vkCmdExecuteCommands()", "VUID-vkCmdExecuteCommands-pInheritanceInfo-00098"); } // If framebuffer for secondary CB is not NULL, then it must match active FB from primaryCB skip |= ValidateFramebuffer(commandBuffer, cb_state, pCommandBuffers[i], sub_cb_state, "vkCmdExecuteCommands()"); if (!sub_cb_state->cmd_execute_commands_functions.empty()) { // Inherit primary's activeFramebuffer and while running validate functions for (auto &function : sub_cb_state->cmd_execute_commands_functions) { skip |= function(cb_state, cb_state->activeFramebuffer.get()); } } } } } // TODO(mlentine): Move more logic into this method skip |= ValidateSecondaryCommandBufferState(cb_state, sub_cb_state); skip |= ValidateCommandBufferState(sub_cb_state, "vkCmdExecuteCommands()", 0, "VUID-vkCmdExecuteCommands-pCommandBuffers-00089"); if (!(sub_cb_state->beginInfo.flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT)) { if (sub_cb_state->InUse()) { skip |= LogError( cb_state->commandBuffer(), "VUID-vkCmdExecuteCommands-pCommandBuffers-00091", "vkCmdExecuteCommands(): Cannot execute pending %s without VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT set.", report_data->FormatHandle(sub_cb_state->commandBuffer()).c_str()); } // We use an const_cast, because one cannot query a container keyed on a non-const pointer using a const pointer if (cb_state->linkedCommandBuffers.count(const_cast<CMD_BUFFER_STATE *>(sub_cb_state))) { LogObjectList objlist(cb_state->commandBuffer()); objlist.add(sub_cb_state->commandBuffer()); skip |= LogError(objlist, "VUID-vkCmdExecuteCommands-pCommandBuffers-00092", "vkCmdExecuteCommands(): Cannot execute %s without VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT " "set if previously executed in %s", report_data->FormatHandle(sub_cb_state->commandBuffer()).c_str(), report_data->FormatHandle(cb_state->commandBuffer()).c_str()); } const auto insert_pair = linked_command_buffers.insert(sub_cb_state); if (!insert_pair.second) { skip |= LogError(cb_state->commandBuffer(), "VUID-vkCmdExecuteCommands-pCommandBuffers-00093", "vkCmdExecuteCommands(): Cannot duplicate %s in pCommandBuffers without " "VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT set.", report_data->FormatHandle(cb_state->commandBuffer()).c_str()); } if (cb_state->beginInfo.flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT) { // Warn that non-simultaneous secondary cmd buffer renders primary non-simultaneous LogObjectList objlist(pCommandBuffers[i]); objlist.add(cb_state->commandBuffer()); skip |= LogWarning(objlist, kVUID_Core_DrawState_InvalidCommandBufferSimultaneousUse, "vkCmdExecuteCommands(): Secondary %s does not have " "VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT set and will cause primary " "%s to be treated as if it does not have " "VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT set, even though it does.", report_data->FormatHandle(pCommandBuffers[i]).c_str(), report_data->FormatHandle(cb_state->commandBuffer()).c_str()); } } if (!cb_state->activeQueries.empty() && !enabled_features.core.inheritedQueries) { skip |= LogError(pCommandBuffers[i], "VUID-vkCmdExecuteCommands-commandBuffer-00101", "vkCmdExecuteCommands(): Secondary %s cannot be submitted with a query in flight and " "inherited queries not supported on this device.", report_data->FormatHandle(pCommandBuffers[i]).c_str()); } // Validate initial layout uses vs. the primary cmd buffer state // Novel Valid usage: "UNASSIGNED-vkCmdExecuteCommands-commandBuffer-00001" // initial layout usage of secondary command buffers resources must match parent command buffer const auto *const_cb_state = static_cast<const CMD_BUFFER_STATE *>(cb_state); for (const auto &sub_layout_map_entry : sub_cb_state->image_layout_map) { const auto image = sub_layout_map_entry.first; const auto *image_state = GetImageState(image); if (!image_state) continue; // Can't set layouts of a dead image const auto *cb_subres_map = const_cb_state->GetImageSubresourceLayoutMap(image); // Const getter can be null in which case we have nothing to check against for this image... if (!cb_subres_map) continue; const auto *sub_cb_subres_map = &sub_layout_map_entry.second; // Validate the initial_uses, that they match the current state of the primary cb, or absent a current state, // that the match any initial_layout. for (const auto &subres_layout : *sub_cb_subres_map) { const auto &sub_layout = subres_layout.initial_layout; const auto &subresource = subres_layout.subresource; if (VK_IMAGE_LAYOUT_UNDEFINED == sub_layout) continue; // secondary doesn't care about current or initial // Look up the layout to compared to the intial layout of the sub command buffer (current else initial) const auto *cb_layouts = cb_subres_map->GetSubresourceLayouts(subresource); auto cb_layout = cb_layouts ? cb_layouts->current_layout : kInvalidLayout; const char *layout_type = "current"; if (cb_layout == kInvalidLayout) { cb_layout = cb_layouts ? cb_layouts->initial_layout : kInvalidLayout; layout_type = "initial"; } if ((cb_layout != kInvalidLayout) && (cb_layout != sub_layout)) { skip |= LogError(pCommandBuffers[i], "UNASSIGNED-vkCmdExecuteCommands-commandBuffer-00001", "%s: Executed secondary command buffer using %s (subresource: aspectMask 0x%X array layer %u, " "mip level %u) which expects layout %s--instead, image %s layout is %s.", "vkCmdExecuteCommands():", report_data->FormatHandle(image).c_str(), subresource.aspectMask, subresource.arrayLayer, subresource.mipLevel, string_VkImageLayout(sub_layout), layout_type, string_VkImageLayout(cb_layout)); } } } // All commands buffers involved must be protected or unprotected if ((cb_state->unprotected == false) && (sub_cb_state->unprotected == true)) { LogObjectList objlist(cb_state->commandBuffer()); objlist.add(sub_cb_state->commandBuffer()); skip |= LogError( objlist, "VUID-vkCmdExecuteCommands-commandBuffer-01820", "vkCmdExecuteCommands(): command buffer %s is protected while secondary command buffer %s is a unprotected", report_data->FormatHandle(cb_state->commandBuffer()).c_str(), report_data->FormatHandle(sub_cb_state->commandBuffer()).c_str()); } else if ((cb_state->unprotected == true) && (sub_cb_state->unprotected == false)) { LogObjectList objlist(cb_state->commandBuffer()); objlist.add(sub_cb_state->commandBuffer()); skip |= LogError( objlist, "VUID-vkCmdExecuteCommands-commandBuffer-01821", "vkCmdExecuteCommands(): command buffer %s is unprotected while secondary command buffer %s is a protected", report_data->FormatHandle(cb_state->commandBuffer()).c_str(), report_data->FormatHandle(sub_cb_state->commandBuffer()).c_str()); } if (active_occlusion_query && sub_cb_state->inheritanceInfo.occlusionQueryEnable != VK_TRUE) { skip |= LogError(pCommandBuffers[i], "VUID-vkCmdExecuteCommands-commandBuffer-00102", "vkCmdExecuteCommands(): command buffer %s has an active occlusion query, but secondary command " "buffer %s was recorded with VkCommandBufferInheritanceInfo::occlusionQueryEnable set to VK_FALSE", report_data->FormatHandle(cb_state->commandBuffer()).c_str(), report_data->FormatHandle(sub_cb_state->commandBuffer()).c_str()); } } skip |= ValidateCmd(cb_state, CMD_EXECUTECOMMANDS, "vkCmdExecuteCommands()"); return skip; } bool CoreChecks::PreCallValidateMapMemory(VkDevice device, VkDeviceMemory mem, VkDeviceSize offset, VkDeviceSize size, VkFlags flags, void **ppData) const { bool skip = false; const DEVICE_MEMORY_STATE *mem_info = GetDevMemState(mem); if (mem_info) { if ((phys_dev_mem_props.memoryTypes[mem_info->alloc_info.memoryTypeIndex].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) == 0) { skip = LogError(mem, "VUID-vkMapMemory-memory-00682", "Mapping Memory without VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT set: %s.", report_data->FormatHandle(mem).c_str()); } if (mem_info->multi_instance) { skip = LogError(mem, "VUID-vkMapMemory-memory-00683", "Memory (%s) must not have been allocated with multiple instances -- either by supplying a deviceMask " "with more than one bit set, or by allocation from a heap with the MULTI_INSTANCE heap flag set.", report_data->FormatHandle(mem).c_str()); } skip |= ValidateMapMemRange(mem_info, offset, size); } return skip; } bool CoreChecks::PreCallValidateUnmapMemory(VkDevice device, VkDeviceMemory mem) const { bool skip = false; const auto mem_info = GetDevMemState(mem); if (mem_info && !mem_info->mapped_range.size) { // Valid Usage: memory must currently be mapped skip |= LogError(mem, "VUID-vkUnmapMemory-memory-00689", "Unmapping Memory without memory being mapped: %s.", report_data->FormatHandle(mem).c_str()); } return skip; } bool CoreChecks::ValidateMemoryIsMapped(const char *funcName, uint32_t memRangeCount, const VkMappedMemoryRange *pMemRanges) const { bool skip = false; for (uint32_t i = 0; i < memRangeCount; ++i) { auto mem_info = GetDevMemState(pMemRanges[i].memory); if (mem_info) { // Makes sure the memory is already mapped if (mem_info->mapped_range.size == 0) { skip = LogError(pMemRanges[i].memory, "VUID-VkMappedMemoryRange-memory-00684", "%s: Attempting to use memory (%s) that is not currently host mapped.", funcName, report_data->FormatHandle(pMemRanges[i].memory).c_str()); } if (pMemRanges[i].size == VK_WHOLE_SIZE) { if (mem_info->mapped_range.offset > pMemRanges[i].offset) { skip |= LogError(pMemRanges[i].memory, "VUID-VkMappedMemoryRange-size-00686", "%s: Flush/Invalidate offset (" PRINTF_SIZE_T_SPECIFIER ") is less than Memory Object's offset (" PRINTF_SIZE_T_SPECIFIER ").", funcName, static_cast<size_t>(pMemRanges[i].offset), static_cast<size_t>(mem_info->mapped_range.offset)); } } else { const uint64_t data_end = (mem_info->mapped_range.size == VK_WHOLE_SIZE) ? mem_info->alloc_info.allocationSize : (mem_info->mapped_range.offset + mem_info->mapped_range.size); if ((mem_info->mapped_range.offset > pMemRanges[i].offset) || (data_end < (pMemRanges[i].offset + pMemRanges[i].size))) { skip |= LogError(pMemRanges[i].memory, "VUID-VkMappedMemoryRange-size-00685", "%s: Flush/Invalidate size or offset (" PRINTF_SIZE_T_SPECIFIER ", " PRINTF_SIZE_T_SPECIFIER ") exceed the Memory Object's upper-bound (" PRINTF_SIZE_T_SPECIFIER ").", funcName, static_cast<size_t>(pMemRanges[i].offset + pMemRanges[i].size), static_cast<size_t>(pMemRanges[i].offset), static_cast<size_t>(data_end)); } } } } return skip; } bool CoreChecks::ValidateMappedMemoryRangeDeviceLimits(const char *func_name, uint32_t mem_range_count, const VkMappedMemoryRange *mem_ranges) const { bool skip = false; for (uint32_t i = 0; i < mem_range_count; ++i) { const uint64_t atom_size = phys_dev_props.limits.nonCoherentAtomSize; const VkDeviceSize offset = mem_ranges[i].offset; const VkDeviceSize size = mem_ranges[i].size; if (SafeModulo(offset, atom_size) != 0) { skip |= LogError(mem_ranges->memory, "VUID-VkMappedMemoryRange-offset-00687", "%s: Offset in pMemRanges[%d] is 0x%" PRIxLEAST64 ", which is not a multiple of VkPhysicalDeviceLimits::nonCoherentAtomSize (0x%" PRIxLEAST64 ").", func_name, i, offset, atom_size); } auto mem_info = GetDevMemState(mem_ranges[i].memory); if (mem_info) { const auto allocation_size = mem_info->alloc_info.allocationSize; if (size == VK_WHOLE_SIZE) { const auto mapping_offset = mem_info->mapped_range.offset; const auto mapping_size = mem_info->mapped_range.size; const auto mapping_end = ((mapping_size == VK_WHOLE_SIZE) ? allocation_size : mapping_offset + mapping_size); if (SafeModulo(mapping_end, atom_size) != 0 && mapping_end != allocation_size) { skip |= LogError(mem_ranges->memory, "VUID-VkMappedMemoryRange-size-01389", "%s: Size in pMemRanges[%d] is VK_WHOLE_SIZE and the mapping end (0x%" PRIxLEAST64 " = 0x%" PRIxLEAST64 " + 0x%" PRIxLEAST64 ") not a multiple of VkPhysicalDeviceLimits::nonCoherentAtomSize (0x%" PRIxLEAST64 ") and not equal to the end of the memory object (0x%" PRIxLEAST64 ").", func_name, i, mapping_end, mapping_offset, mapping_size, atom_size, allocation_size); } } else { const auto range_end = size + offset; if (range_end != allocation_size && SafeModulo(size, atom_size) != 0) { skip |= LogError(mem_ranges->memory, "VUID-VkMappedMemoryRange-size-01390", "%s: Size in pMemRanges[%d] is 0x%" PRIxLEAST64 ", which is not a multiple of VkPhysicalDeviceLimits::nonCoherentAtomSize (0x%" PRIxLEAST64 ") and offset + size (0x%" PRIxLEAST64 " + 0x%" PRIxLEAST64 " = 0x%" PRIxLEAST64 ") not equal to the memory size (0x%" PRIxLEAST64 ").", func_name, i, size, atom_size, offset, size, range_end, allocation_size); } } } } return skip; } bool CoreChecks::PreCallValidateFlushMappedMemoryRanges(VkDevice device, uint32_t memRangeCount, const VkMappedMemoryRange *pMemRanges) const { bool skip = false; skip |= ValidateMappedMemoryRangeDeviceLimits("vkFlushMappedMemoryRanges", memRangeCount, pMemRanges); skip |= ValidateMemoryIsMapped("vkFlushMappedMemoryRanges", memRangeCount, pMemRanges); return skip; } bool CoreChecks::PreCallValidateInvalidateMappedMemoryRanges(VkDevice device, uint32_t memRangeCount, const VkMappedMemoryRange *pMemRanges) const { bool skip = false; skip |= ValidateMappedMemoryRangeDeviceLimits("vkInvalidateMappedMemoryRanges", memRangeCount, pMemRanges); skip |= ValidateMemoryIsMapped("vkInvalidateMappedMemoryRanges", memRangeCount, pMemRanges); return skip; } bool CoreChecks::PreCallValidateGetDeviceMemoryCommitment(VkDevice device, VkDeviceMemory mem, VkDeviceSize *pCommittedMem) const { bool skip = false; const auto mem_info = GetDevMemState(mem); if (mem_info) { if ((phys_dev_mem_props.memoryTypes[mem_info->alloc_info.memoryTypeIndex].propertyFlags & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) == 0) { skip = LogError(mem, "VUID-vkGetDeviceMemoryCommitment-memory-00690", "vkGetDeviceMemoryCommitment(): Querying commitment for memory without " "VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT set: %s.", report_data->FormatHandle(mem).c_str()); } } return skip; } bool CoreChecks::ValidateBindImageMemory(uint32_t bindInfoCount, const VkBindImageMemoryInfo *pBindInfos, const char *api_name) const { bool skip = false; bool bind_image_mem_2 = strcmp(api_name, "vkBindImageMemory()") != 0; char error_prefix[128]; strcpy(error_prefix, api_name); // Track all image sub resources if they are bound for bind_image_mem_2 // uint32_t[3] is which index in pBindInfos for max 3 planes // Non disjoint images act as a single plane layer_data::unordered_map<VkImage, std::array<uint32_t, 3>> resources_bound; for (uint32_t i = 0; i < bindInfoCount; i++) { if (bind_image_mem_2 == true) { sprintf(error_prefix, "%s pBindInfos[%u]", api_name, i); } const VkBindImageMemoryInfo &bind_info = pBindInfos[i]; const IMAGE_STATE *image_state = GetImageState(bind_info.image); if (image_state) { // Track objects tied to memory skip |= ValidateSetMemBinding(bind_info.memory, image_state->Handle(), error_prefix); const auto plane_info = LvlFindInChain<VkBindImagePlaneMemoryInfo>(bind_info.pNext); const auto mem_info = GetDevMemState(bind_info.memory); // Need extra check for disjoint flag incase called without bindImage2 and don't want false positive errors // no 'else' case as if that happens another VUID is already being triggered for it being invalid if ((plane_info == nullptr) && (image_state->disjoint == false)) { // Check non-disjoint images VkMemoryRequirements // All validation using the image_state->requirements for external AHB is check in android only section if (image_state->IsExternalAHB() == false) { const VkMemoryRequirements &mem_req = image_state->requirements[0]; // Validate memory requirements alignment if (SafeModulo(bind_info.memoryOffset, mem_req.alignment) != 0) { const char *validation_error; if (bind_image_mem_2 == false) { validation_error = "VUID-vkBindImageMemory-memoryOffset-01048"; } else if (device_extensions.vk_khr_sampler_ycbcr_conversion) { validation_error = "VUID-VkBindImageMemoryInfo-pNext-01616"; } else { validation_error = "VUID-VkBindImageMemoryInfo-memoryOffset-01613"; } skip |= LogError(bind_info.image, validation_error, "%s: memoryOffset is 0x%" PRIxLEAST64 " but must be an integer multiple of the VkMemoryRequirements::alignment value 0x%" PRIxLEAST64 ", returned from a call to vkGetImageMemoryRequirements with image.", error_prefix, bind_info.memoryOffset, mem_req.alignment); } if (mem_info) { safe_VkMemoryAllocateInfo alloc_info = mem_info->alloc_info; // Validate memory requirements size if (mem_req.size > alloc_info.allocationSize - bind_info.memoryOffset) { const char *validation_error; if (bind_image_mem_2 == false) { validation_error = "VUID-vkBindImageMemory-size-01049"; } else if (device_extensions.vk_khr_sampler_ycbcr_conversion) { validation_error = "VUID-VkBindImageMemoryInfo-pNext-01617"; } else { validation_error = "VUID-VkBindImageMemoryInfo-memory-01614"; } skip |= LogError(bind_info.image, validation_error, "%s: memory size minus memoryOffset is 0x%" PRIxLEAST64 " but must be at least as large as VkMemoryRequirements::size value 0x%" PRIxLEAST64 ", returned from a call to vkGetImageMemoryRequirements with image.", error_prefix, alloc_info.allocationSize - bind_info.memoryOffset, mem_req.size); } // Validate memory type used { const char *validation_error; if (bind_image_mem_2 == false) { validation_error = "VUID-vkBindImageMemory-memory-01047"; } else if (device_extensions.vk_khr_sampler_ycbcr_conversion) { validation_error = "VUID-VkBindImageMemoryInfo-pNext-01615"; } else { validation_error = "VUID-VkBindImageMemoryInfo-memory-01612"; } skip |= ValidateMemoryTypes(mem_info, mem_req.memoryTypeBits, error_prefix, validation_error); } } } if (bind_image_mem_2 == true) { // since its a non-disjoint image, finding VkImage in map is a duplicate auto it = resources_bound.find(image_state->image()); if (it == resources_bound.end()) { std::array<uint32_t, 3> bound_index = {i, UINT32_MAX, UINT32_MAX}; resources_bound.emplace(image_state->image(), bound_index); } else { skip |= LogError( bind_info.image, "VUID-vkBindImageMemory2-pBindInfos-04006", "%s: The same non-disjoint image resource is being bound twice at pBindInfos[%d] and pBindInfos[%d]", error_prefix, it->second[0], i); } } } else if ((plane_info != nullptr) && (image_state->disjoint == true)) { // Check disjoint images VkMemoryRequirements for given plane int plane = 0; // All validation using the image_state->plane*_requirements for external AHB is check in android only section if (image_state->IsExternalAHB() == false) { const VkImageAspectFlagBits aspect = plane_info->planeAspect; switch (aspect) { case VK_IMAGE_ASPECT_PLANE_0_BIT: plane = 0; break; case VK_IMAGE_ASPECT_PLANE_1_BIT: plane = 1; break; case VK_IMAGE_ASPECT_PLANE_2_BIT: plane = 2; break; default: assert(false); // parameter validation should have caught this break; } const VkMemoryRequirements &disjoint_mem_req = image_state->requirements[plane]; // Validate memory requirements alignment if (SafeModulo(bind_info.memoryOffset, disjoint_mem_req.alignment) != 0) { skip |= LogError( bind_info.image, "VUID-VkBindImageMemoryInfo-pNext-01620", "%s: memoryOffset is 0x%" PRIxLEAST64 " but must be an integer multiple of the VkMemoryRequirements::alignment value 0x%" PRIxLEAST64 ", returned from a call to vkGetImageMemoryRequirements2 with disjoint image for aspect plane %s.", error_prefix, bind_info.memoryOffset, disjoint_mem_req.alignment, string_VkImageAspectFlagBits(aspect)); } if (mem_info) { safe_VkMemoryAllocateInfo alloc_info = mem_info->alloc_info; // Validate memory requirements size if (disjoint_mem_req.size > alloc_info.allocationSize - bind_info.memoryOffset) { skip |= LogError( bind_info.image, "VUID-VkBindImageMemoryInfo-pNext-01621", "%s: memory size minus memoryOffset is 0x%" PRIxLEAST64 " but must be at least as large as VkMemoryRequirements::size value 0x%" PRIxLEAST64 ", returned from a call to vkGetImageMemoryRequirements with disjoint image for aspect plane %s.", error_prefix, alloc_info.allocationSize - bind_info.memoryOffset, disjoint_mem_req.size, string_VkImageAspectFlagBits(aspect)); } // Validate memory type used { skip |= ValidateMemoryTypes(mem_info, disjoint_mem_req.memoryTypeBits, error_prefix, "VUID-VkBindImageMemoryInfo-pNext-01619"); } } } auto it = resources_bound.find(image_state->image()); if (it == resources_bound.end()) { std::array<uint32_t, 3> bound_index = {UINT32_MAX, UINT32_MAX, UINT32_MAX}; bound_index[plane] = i; resources_bound.emplace(image_state->image(), bound_index); } else { if (it->second[plane] == UINT32_MAX) { it->second[plane] = i; } else { skip |= LogError(bind_info.image, "VUID-vkBindImageMemory2-pBindInfos-04006", "%s: The same disjoint image sub-resource for plane %d is being bound twice at " "pBindInfos[%d] and pBindInfos[%d]", error_prefix, plane, it->second[plane], i); } } } if (mem_info) { // Validate bound memory range information // if memory is exported to an AHB then the mem_info->allocationSize must be zero and this check is not needed if ((mem_info->IsExport() == false) || ((mem_info->export_handle_type_flags & VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID) == 0)) { skip |= ValidateInsertImageMemoryRange(bind_info.image, mem_info, bind_info.memoryOffset, error_prefix); } // Validate dedicated allocation if (mem_info->IsDedicatedImage()) { if (enabled_features.dedicated_allocation_image_aliasing_features.dedicatedAllocationImageAliasing) { const auto current_image_state = GetImageState(bind_info.image); if ((bind_info.memoryOffset != 0) || !current_image_state || !current_image_state->IsCreateInfoDedicatedAllocationImageAliasingCompatible( mem_info->dedicated->create_info.image)) { const char *validation_error; if (bind_image_mem_2 == false) { validation_error = "VUID-vkBindImageMemory-memory-02629"; } else { validation_error = "VUID-VkBindImageMemoryInfo-memory-02629"; } LogObjectList objlist(bind_info.image); objlist.add(bind_info.memory); objlist.add(mem_info->dedicated->handle); skip |= LogError( objlist, validation_error, "%s: for dedicated memory allocation %s, VkMemoryDedicatedAllocateInfo:: %s must compatible " "with %s and memoryOffset 0x%" PRIxLEAST64 " must be zero.", error_prefix, report_data->FormatHandle(bind_info.memory).c_str(), report_data->FormatHandle(mem_info->dedicated->handle).c_str(), report_data->FormatHandle(bind_info.image).c_str(), bind_info.memoryOffset); } } else { if ((bind_info.memoryOffset != 0) || (mem_info->dedicated->handle.Cast<VkImage>() != bind_info.image)) { const char *validation_error; if (bind_image_mem_2 == false) { validation_error = "VUID-vkBindImageMemory-memory-01509"; } else { validation_error = "VUID-VkBindImageMemoryInfo-memory-01509"; } LogObjectList objlist(bind_info.image); objlist.add(bind_info.memory); objlist.add(mem_info->dedicated->handle); skip |= LogError(objlist, validation_error, "%s: for dedicated memory allocation %s, VkMemoryDedicatedAllocateInfo:: %s must be equal " "to %s and memoryOffset 0x%" PRIxLEAST64 " must be zero.", error_prefix, report_data->FormatHandle(bind_info.memory).c_str(), report_data->FormatHandle(mem_info->dedicated->handle).c_str(), report_data->FormatHandle(bind_info.image).c_str(), bind_info.memoryOffset); } } } // Validate export memory handles if ((mem_info->export_handle_type_flags != 0) && ((mem_info->export_handle_type_flags & image_state->external_memory_handle) == 0)) { const char *vuid = bind_image_mem_2 ? "VUID-VkBindImageMemoryInfo-memory-02728" : "VUID-vkBindImageMemory-memory-02728"; LogObjectList objlist(bind_info.image); objlist.add(bind_info.memory); skip |= LogError(objlist, vuid, "%s: The VkDeviceMemory (%s) has an external handleType of %s which does not include at least " "one handle from VkImage (%s) handleType %s.", error_prefix, report_data->FormatHandle(bind_info.memory).c_str(), string_VkExternalMemoryHandleTypeFlags(mem_info->export_handle_type_flags).c_str(), report_data->FormatHandle(bind_info.image).c_str(), string_VkExternalMemoryHandleTypeFlags(image_state->external_memory_handle).c_str()); } // Validate import memory handles if (mem_info->IsImportAHB() == true) { skip |= ValidateImageImportedHandleANDROID(api_name, image_state->external_memory_handle, bind_info.memory, bind_info.image); } else if (mem_info->IsImport() == true) { if ((mem_info->import_handle_type_flags & image_state->external_memory_handle) == 0) { const char *vuid = nullptr; if ((bind_image_mem_2) && (device_extensions.vk_android_external_memory_android_hardware_buffer)) { vuid = "VUID-VkBindImageMemoryInfo-memory-02989"; } else if ((!bind_image_mem_2) && (device_extensions.vk_android_external_memory_android_hardware_buffer)) { vuid = "VUID-vkBindImageMemory-memory-02989"; } else if ((bind_image_mem_2) && (!device_extensions.vk_android_external_memory_android_hardware_buffer)) { vuid = "VUID-VkBindImageMemoryInfo-memory-02729"; } else if ((!bind_image_mem_2) && (!device_extensions.vk_android_external_memory_android_hardware_buffer)) { vuid = "VUID-vkBindImageMemory-memory-02729"; } LogObjectList objlist(bind_info.image); objlist.add(bind_info.memory); skip |= LogError(objlist, vuid, "%s: The VkDeviceMemory (%s) was created with an import operation with handleType of %s " "which is not set in the VkImage (%s) VkExternalMemoryImageCreateInfo::handleType (%s)", api_name, report_data->FormatHandle(bind_info.memory).c_str(), string_VkExternalMemoryHandleTypeFlags(mem_info->import_handle_type_flags).c_str(), report_data->FormatHandle(bind_info.image).c_str(), string_VkExternalMemoryHandleTypeFlags(image_state->external_memory_handle).c_str()); } } // Validate mix of protected buffer and memory if ((image_state->unprotected == false) && (mem_info->unprotected == true)) { const char *vuid = bind_image_mem_2 ? "VUID-VkBindImageMemoryInfo-None-01901" : "VUID-vkBindImageMemory-None-01901"; LogObjectList objlist(bind_info.image); objlist.add(bind_info.memory); skip |= LogError(objlist, vuid, "%s: The VkDeviceMemory (%s) was not created with protected memory but the VkImage (%s) was " "set to use protected memory.", api_name, report_data->FormatHandle(bind_info.memory).c_str(), report_data->FormatHandle(bind_info.image).c_str()); } else if ((image_state->unprotected == true) && (mem_info->unprotected == false)) { const char *vuid = bind_image_mem_2 ? "VUID-VkBindImageMemoryInfo-None-01902" : "VUID-vkBindImageMemory-None-01902"; LogObjectList objlist(bind_info.image); objlist.add(bind_info.memory); skip |= LogError(objlist, vuid, "%s: The VkDeviceMemory (%s) was created with protected memory but the VkImage (%s) was not " "set to use protected memory.", api_name, report_data->FormatHandle(bind_info.memory).c_str(), report_data->FormatHandle(bind_info.image).c_str()); } } const auto swapchain_info = LvlFindInChain<VkBindImageMemorySwapchainInfoKHR>(bind_info.pNext); if (swapchain_info) { if (bind_info.memory != VK_NULL_HANDLE) { skip |= LogError(bind_info.image, "VUID-VkBindImageMemoryInfo-pNext-01631", "%s: %s is not VK_NULL_HANDLE.", error_prefix, report_data->FormatHandle(bind_info.memory).c_str()); } if (image_state->create_from_swapchain != swapchain_info->swapchain) { LogObjectList objlist(image_state->image()); objlist.add(image_state->create_from_swapchain); objlist.add(swapchain_info->swapchain); skip |= LogError( objlist, kVUID_Core_BindImageMemory_Swapchain, "%s: %s is created by %s, but the image is bound by %s. The image should be created and bound by the same " "swapchain", error_prefix, report_data->FormatHandle(image_state->image()).c_str(), report_data->FormatHandle(image_state->create_from_swapchain).c_str(), report_data->FormatHandle(swapchain_info->swapchain).c_str()); } const auto swapchain_state = GetSwapchainState(swapchain_info->swapchain); if (swapchain_state && swapchain_state->images.size() <= swapchain_info->imageIndex) { skip |= LogError(bind_info.image, "VUID-VkBindImageMemorySwapchainInfoKHR-imageIndex-01644", "%s: imageIndex (%i) is out of bounds of %s images (size: %i)", error_prefix, swapchain_info->imageIndex, report_data->FormatHandle(swapchain_info->swapchain).c_str(), static_cast<int>(swapchain_state->images.size())); } } else { if (image_state->create_from_swapchain) { skip |= LogError(bind_info.image, "VUID-VkBindImageMemoryInfo-image-01630", "%s: pNext of VkBindImageMemoryInfo doesn't include VkBindImageMemorySwapchainInfoKHR.", error_prefix); } if (!mem_info) { skip |= LogError(bind_info.image, "VUID-VkBindImageMemoryInfo-pNext-01632", "%s: %s is invalid.", error_prefix, report_data->FormatHandle(bind_info.memory).c_str()); } } const auto bind_image_memory_device_group_info = LvlFindInChain<VkBindImageMemoryDeviceGroupInfo>(bind_info.pNext); if (bind_image_memory_device_group_info && bind_image_memory_device_group_info->splitInstanceBindRegionCount != 0) { if (!(image_state->createInfo.flags & VK_IMAGE_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT)) { skip |= LogError(bind_info.image, "VUID-VkBindImageMemoryInfo-pNext-01627", "%s: pNext of VkBindImageMemoryInfo contains VkBindImageMemoryDeviceGroupInfo with " "splitInstanceBindRegionCount (%" PRIi32 ") not equal to 0 and %s is not created with " "VK_IMAGE_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT.", error_prefix, bind_image_memory_device_group_info->splitInstanceBindRegionCount, report_data->FormatHandle(image_state->image()).c_str()); } } if (plane_info) { // Checks for disjoint bit in image if (image_state->disjoint == false) { skip |= LogError( bind_info.image, "VUID-VkBindImageMemoryInfo-pNext-01618", "%s: pNext of VkBindImageMemoryInfo contains VkBindImagePlaneMemoryInfo and %s is not created with " "VK_IMAGE_CREATE_DISJOINT_BIT.", error_prefix, report_data->FormatHandle(image_state->image()).c_str()); } // Make sure planeAspect is only a single, valid plane uint32_t planes = FormatPlaneCount(image_state->createInfo.format); VkImageAspectFlags aspect = plane_info->planeAspect; if ((2 == planes) && (aspect != VK_IMAGE_ASPECT_PLANE_0_BIT) && (aspect != VK_IMAGE_ASPECT_PLANE_1_BIT)) { skip |= LogError( bind_info.image, "VUID-VkBindImagePlaneMemoryInfo-planeAspect-02283", "%s: Image %s VkBindImagePlaneMemoryInfo::planeAspect is %s but can only be VK_IMAGE_ASPECT_PLANE_0_BIT" "or VK_IMAGE_ASPECT_PLANE_1_BIT.", error_prefix, report_data->FormatHandle(image_state->image()).c_str(), string_VkImageAspectFlags(aspect).c_str()); } if ((3 == planes) && (aspect != VK_IMAGE_ASPECT_PLANE_0_BIT) && (aspect != VK_IMAGE_ASPECT_PLANE_1_BIT) && (aspect != VK_IMAGE_ASPECT_PLANE_2_BIT)) { skip |= LogError( bind_info.image, "VUID-VkBindImagePlaneMemoryInfo-planeAspect-02283", "%s: Image %s VkBindImagePlaneMemoryInfo::planeAspect is %s but can only be VK_IMAGE_ASPECT_PLANE_0_BIT" "or VK_IMAGE_ASPECT_PLANE_1_BIT or VK_IMAGE_ASPECT_PLANE_2_BIT.", error_prefix, report_data->FormatHandle(image_state->image()).c_str(), string_VkImageAspectFlags(aspect).c_str()); } } } const auto bind_image_memory_device_group = LvlFindInChain<VkBindImageMemoryDeviceGroupInfo>(bind_info.pNext); if (bind_image_memory_device_group) { if (bind_image_memory_device_group->deviceIndexCount > 0 && bind_image_memory_device_group->splitInstanceBindRegionCount > 0) { skip |= LogError(bind_info.image, "VUID-VkBindImageMemoryDeviceGroupInfo-deviceIndexCount-01633", "%s: VkBindImageMemoryDeviceGroupInfo in pNext of pBindInfos[%" PRIu32 "] has both deviceIndexCount and splitInstanceBindRegionCount greater than 0.", error_prefix, i); } } } // Check to make sure all disjoint planes were bound for (auto &resource : resources_bound) { const IMAGE_STATE *image_state = GetImageState(resource.first); if (image_state->disjoint == true) { uint32_t total_planes = FormatPlaneCount(image_state->createInfo.format); for (uint32_t i = 0; i < total_planes; i++) { if (resource.second[i] == UINT32_MAX) { skip |= LogError(resource.first, "VUID-vkBindImageMemory2-pBindInfos-02858", "%s: Plane %u of the disjoint image was not bound. All %d planes need to bound individually " "in separate pBindInfos in a single call.", api_name, i, total_planes); } } } } return skip; } bool CoreChecks::PreCallValidateBindImageMemory(VkDevice device, VkImage image, VkDeviceMemory mem, VkDeviceSize memoryOffset) const { bool skip = false; const IMAGE_STATE *image_state = GetImageState(image); if (image_state) { // Checks for no disjoint bit if (image_state->disjoint == true) { skip |= LogError(image, "VUID-vkBindImageMemory-image-01608", "%s must not have been created with the VK_IMAGE_CREATE_DISJOINT_BIT (need to use vkBindImageMemory2).", report_data->FormatHandle(image).c_str()); } } auto bind_info = LvlInitStruct<VkBindImageMemoryInfo>(); bind_info.image = image; bind_info.memory = mem; bind_info.memoryOffset = memoryOffset; skip |= ValidateBindImageMemory(1, &bind_info, "vkBindImageMemory()"); return skip; } bool CoreChecks::PreCallValidateBindImageMemory2(VkDevice device, uint32_t bindInfoCount, const VkBindImageMemoryInfo *pBindInfos) const { return ValidateBindImageMemory(bindInfoCount, pBindInfos, "vkBindImageMemory2()"); } bool CoreChecks::PreCallValidateBindImageMemory2KHR(VkDevice device, uint32_t bindInfoCount, const VkBindImageMemoryInfo *pBindInfos) const { return ValidateBindImageMemory(bindInfoCount, pBindInfos, "vkBindImageMemory2KHR()"); } bool CoreChecks::PreCallValidateSetEvent(VkDevice device, VkEvent event) const { bool skip = false; const auto event_state = GetEventState(event); if (event_state) { if (event_state->write_in_use) { skip |= LogError(event, kVUID_Core_DrawState_QueueForwardProgress, "vkSetEvent(): %s that is already in use by a command buffer.", report_data->FormatHandle(event).c_str()); } if (event_state->flags & VK_EVENT_CREATE_DEVICE_ONLY_BIT_KHR) { skip |= LogError(event, "VUID-vkSetEvent-event-03941", "vkSetEvent(): %s was created with VK_EVENT_CREATE_DEVICE_ONLY_BIT_KHR.", report_data->FormatHandle(event).c_str()); } } return skip; } bool CoreChecks::PreCallValidateResetEvent(VkDevice device, VkEvent event) const { bool skip = false; const auto event_state = GetEventState(event); if (event_state) { if (event_state->flags & VK_EVENT_CREATE_DEVICE_ONLY_BIT_KHR) { skip |= LogError(event, "VUID-vkResetEvent-event-03823", "vkResetEvent(): %s was created with VK_EVENT_CREATE_DEVICE_ONLY_BIT_KHR.", report_data->FormatHandle(event).c_str()); } } return skip; } bool CoreChecks::PreCallValidateGetEventStatus(VkDevice device, VkEvent event) const { bool skip = false; const auto event_state = GetEventState(event); if (event_state) { if (event_state->flags & VK_EVENT_CREATE_DEVICE_ONLY_BIT_KHR) { skip |= LogError(event, "VUID-vkGetEventStatus-event-03940", "vkGetEventStatus(): %s was created with VK_EVENT_CREATE_DEVICE_ONLY_BIT_KHR.", report_data->FormatHandle(event).c_str()); } } return skip; } bool CoreChecks::PreCallValidateQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo *pBindInfo, VkFence fence) const { const auto queue_data = GetQueueState(queue); const auto fence_state = GetFenceState(fence); bool skip = ValidateFenceForSubmit(fence_state, "VUID-vkQueueBindSparse-fence-01114", "VUID-vkQueueBindSparse-fence-01113", "VkQueueBindSparse()"); if (skip) { return true; } const auto queue_flags = GetPhysicalDeviceState()->queue_family_properties[queue_data->queueFamilyIndex].queueFlags; if (!(queue_flags & VK_QUEUE_SPARSE_BINDING_BIT)) { skip |= LogError(queue, "VUID-vkQueueBindSparse-queuetype", "vkQueueBindSparse(): a non-memory-management capable queue -- VK_QUEUE_SPARSE_BINDING_BIT not set."); } layer_data::unordered_set<VkSemaphore> signaled_semaphores; layer_data::unordered_set<VkSemaphore> unsignaled_semaphores; layer_data::unordered_set<VkSemaphore> internal_semaphores; auto *vuid_error = device_extensions.vk_khr_timeline_semaphore ? "VUID-vkQueueBindSparse-pWaitSemaphores-03245" : kVUID_Core_DrawState_QueueForwardProgress; for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; ++bind_idx) { const VkBindSparseInfo &bind_info = pBindInfo[bind_idx]; auto timeline_semaphore_submit_info = LvlFindInChain<VkTimelineSemaphoreSubmitInfo>(pBindInfo->pNext); std::vector<SEMAPHORE_WAIT> semaphore_waits; std::vector<VkSemaphore> semaphore_signals; for (uint32_t i = 0; i < bind_info.waitSemaphoreCount; ++i) { VkSemaphore semaphore = bind_info.pWaitSemaphores[i]; const auto semaphore_state = GetSemaphoreState(semaphore); if (semaphore_state && semaphore_state->type == VK_SEMAPHORE_TYPE_TIMELINE && !timeline_semaphore_submit_info) { skip |= LogError(semaphore, "VUID-VkBindSparseInfo-pWaitSemaphores-03246", "VkQueueBindSparse: pBindInfo[%u].pWaitSemaphores[%u] (%s) is a timeline semaphore, but " "pBindInfo[%u] does not include an instance of VkTimelineSemaphoreSubmitInfo", bind_idx, i, report_data->FormatHandle(semaphore).c_str(), bind_idx); } if (semaphore_state && semaphore_state->type == VK_SEMAPHORE_TYPE_TIMELINE && timeline_semaphore_submit_info && bind_info.waitSemaphoreCount != timeline_semaphore_submit_info->waitSemaphoreValueCount) { skip |= LogError(semaphore, "VUID-VkBindSparseInfo-pNext-03247", "VkQueueBindSparse: pBindInfo[%u].pWaitSemaphores[%u] (%s) is a timeline semaphore, it contains " "an instance of VkTimelineSemaphoreSubmitInfo, but waitSemaphoreValueCount (%u) is different " "than pBindInfo[%u].waitSemaphoreCount (%u)", bind_idx, i, report_data->FormatHandle(semaphore).c_str(), timeline_semaphore_submit_info->waitSemaphoreValueCount, bind_idx, bind_info.waitSemaphoreCount); } if (semaphore_state && semaphore_state->type == VK_SEMAPHORE_TYPE_BINARY && (semaphore_state->scope == kSyncScopeInternal || internal_semaphores.count(semaphore))) { if (unsignaled_semaphores.count(semaphore) || (!(signaled_semaphores.count(semaphore)) && !(semaphore_state->signaled) && !SemaphoreWasSignaled(semaphore))) { LogObjectList objlist(semaphore); objlist.add(queue); skip |= LogError( objlist, semaphore_state->scope == kSyncScopeInternal ? vuid_error : kVUID_Core_DrawState_QueueForwardProgress, "vkQueueBindSparse(): Queue %s is waiting on pBindInfo[%u].pWaitSemaphores[%u] (%s) that has no way to be " "signaled.", report_data->FormatHandle(queue).c_str(), bind_idx, i, report_data->FormatHandle(semaphore).c_str()); } else { signaled_semaphores.erase(semaphore); unsignaled_semaphores.insert(semaphore); } } if (semaphore_state && semaphore_state->type == VK_SEMAPHORE_TYPE_BINARY && semaphore_state->scope == kSyncScopeExternalTemporary) { internal_semaphores.insert(semaphore); } } for (uint32_t i = 0; i < bind_info.signalSemaphoreCount; ++i) { VkSemaphore semaphore = bind_info.pSignalSemaphores[i]; const auto semaphore_state = GetSemaphoreState(semaphore); if (semaphore_state && semaphore_state->type == VK_SEMAPHORE_TYPE_TIMELINE && !timeline_semaphore_submit_info) { skip |= LogError(semaphore, "VUID-VkBindSparseInfo-pWaitSemaphores-03246", "VkQueueBindSparse: pBindInfo[%u].pSignalSemaphores[%u] (%s) is a timeline semaphore, but " "pBindInfo[%u] does not include an instance of VkTimelineSemaphoreSubmitInfo", bind_idx, i, report_data->FormatHandle(semaphore).c_str(), bind_idx); } if (semaphore_state && semaphore_state->type == VK_SEMAPHORE_TYPE_TIMELINE && timeline_semaphore_submit_info && timeline_semaphore_submit_info->pSignalSemaphoreValues[i] <= semaphore_state->payload) { LogObjectList objlist(semaphore); objlist.add(queue); skip |= LogError(objlist, "VUID-VkBindSparseInfo-pSignalSemaphores-03249", "VkQueueBindSparse: signal value (0x%" PRIx64 ") in %s must be greater than current timeline semaphore %s value (0x%" PRIx64 ") in pBindInfo[%u].pSignalSemaphores[%u]", semaphore_state->payload, report_data->FormatHandle(queue).c_str(), report_data->FormatHandle(semaphore).c_str(), timeline_semaphore_submit_info->pSignalSemaphoreValues[i], bind_idx, i); } if (semaphore_state && semaphore_state->type == VK_SEMAPHORE_TYPE_TIMELINE && timeline_semaphore_submit_info && bind_info.signalSemaphoreCount != timeline_semaphore_submit_info->signalSemaphoreValueCount) { skip |= LogError(semaphore, "VUID-VkBindSparseInfo-pNext-03248", "VkQueueBindSparse: pBindInfo[%u].pSignalSemaphores[%u] (%s) is a timeline semaphore, it contains " "an instance of VkTimelineSemaphoreSubmitInfo, but signalSemaphoreValueCount (%u) is different " "than pBindInfo[%u].signalSemaphoreCount (%u)", bind_idx, i, report_data->FormatHandle(semaphore).c_str(), timeline_semaphore_submit_info->signalSemaphoreValueCount, bind_idx, bind_info.signalSemaphoreCount); } if (semaphore_state && semaphore_state->type == VK_SEMAPHORE_TYPE_BINARY && semaphore_state->scope == kSyncScopeInternal) { if (signaled_semaphores.count(semaphore) || (!(unsignaled_semaphores.count(semaphore)) && semaphore_state->signaled)) { LogObjectList objlist(semaphore); objlist.add(queue); objlist.add(semaphore_state->signaler.first); skip |= LogError(objlist, kVUID_Core_DrawState_QueueForwardProgress, "vkQueueBindSparse(): %s is signaling pBindInfo[%u].pSignalSemaphores[%u] (%s) that was " "previously signaled by %s but has not since been waited on by any queue.", report_data->FormatHandle(queue).c_str(), bind_idx, i, report_data->FormatHandle(semaphore).c_str(), report_data->FormatHandle(semaphore_state->signaler.first).c_str()); } else { unsignaled_semaphores.erase(semaphore); signaled_semaphores.insert(semaphore); } } } for (uint32_t image_idx = 0; image_idx < bind_info.imageBindCount; ++image_idx) { const VkSparseImageMemoryBindInfo &image_bind = bind_info.pImageBinds[image_idx]; const auto image_state = GetImageState(image_bind.image); if (image_state && !(image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT)) { skip |= LogError(image_bind.image, "VUID-VkSparseImageMemoryBindInfo-image-02901", "vkQueueBindSparse(): pBindInfo[%u].pImageBinds[%u]: image must have been created with " "VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT set", bind_idx, image_idx); } for (uint32_t image_bind_idx = 0; image_bind_idx < image_bind.bindCount; ++image_bind_idx) { const VkSparseImageMemoryBind &memory_bind = image_bind.pBinds[image_bind_idx]; const auto *mem_info = Get<DEVICE_MEMORY_STATE>(memory_bind.memory); if (mem_info) { if (memory_bind.memoryOffset >= mem_info->alloc_info.allocationSize) { skip |= LogError( image_bind.image, "VUID-VkSparseMemoryBind-memoryOffset-01101", "vkQueueBindSparse(): pBindInfo[%u].pImageBinds[%u]: memoryOffset is not less than the size of memory", bind_idx, image_idx); } } } } } if (skip) return skip; // Now verify maxTimelineSemaphoreValueDifference for (uint32_t bind_idx = 0; bind_idx < bindInfoCount; ++bind_idx) { Location outer_loc(Func::vkQueueBindSparse, Struct::VkBindSparseInfo); const VkBindSparseInfo *bind_info = &pBindInfo[bind_idx]; auto *info = LvlFindInChain<VkTimelineSemaphoreSubmitInfo>(bind_info->pNext); if (info) { // If there are any timeline semaphores, this condition gets checked before the early return above if (info->waitSemaphoreValueCount) { for (uint32_t i = 0; i < bind_info->waitSemaphoreCount; ++i) { auto loc = outer_loc.dot(Field::pWaitSemaphoreValues, i); VkSemaphore semaphore = bind_info->pWaitSemaphores[i]; skip |= ValidateMaxTimelineSemaphoreValueDifference(loc, semaphore, info->pWaitSemaphoreValues[i]); } } // If there are any timeline semaphores, this condition gets checked before the early return above if (info->signalSemaphoreValueCount) { for (uint32_t i = 0; i < bind_info->signalSemaphoreCount; ++i) { auto loc = outer_loc.dot(Field::pSignalSemaphoreValues, i); VkSemaphore semaphore = bind_info->pSignalSemaphores[i]; skip |= ValidateMaxTimelineSemaphoreValueDifference(loc, semaphore, info->pSignalSemaphoreValues[i]); } } } } return skip; } bool CoreChecks::ValidateSignalSemaphore(VkDevice device, const VkSemaphoreSignalInfo *pSignalInfo, const char *api_name) const { bool skip = false; const auto semaphore_state = GetSemaphoreState(pSignalInfo->semaphore); if (semaphore_state && semaphore_state->type != VK_SEMAPHORE_TYPE_TIMELINE) { skip |= LogError(pSignalInfo->semaphore, "VUID-VkSemaphoreSignalInfo-semaphore-03257", "%s(): semaphore %s must be of VK_SEMAPHORE_TYPE_TIMELINE type", api_name, report_data->FormatHandle(pSignalInfo->semaphore).c_str()); return skip; } if (semaphore_state && semaphore_state->payload >= pSignalInfo->value) { skip |= LogError(pSignalInfo->semaphore, "VUID-VkSemaphoreSignalInfo-value-03258", "%s(): value must be greater than current semaphore %s value", api_name, report_data->FormatHandle(pSignalInfo->semaphore).c_str()); } for (auto &pair : queueMap) { const QUEUE_STATE &queue_state = pair.second; for (const auto &submission : queue_state.submissions) { for (const auto &signal_semaphore : submission.signalSemaphores) { if (signal_semaphore.semaphore == pSignalInfo->semaphore && pSignalInfo->value >= signal_semaphore.payload) { skip |= LogError(pSignalInfo->semaphore, "VUID-VkSemaphoreSignalInfo-value-03259", "%s(): value must be greater than value of pending signal operation " "for semaphore %s", api_name, report_data->FormatHandle(pSignalInfo->semaphore).c_str()); } } } } if (!skip) { Location loc(Func::vkSignalSemaphore, Struct::VkSemaphoreSignalInfo, Field::value); skip |= ValidateMaxTimelineSemaphoreValueDifference(loc, pSignalInfo->semaphore, pSignalInfo->value); } return skip; } bool CoreChecks::PreCallValidateSignalSemaphore(VkDevice device, const VkSemaphoreSignalInfo *pSignalInfo) const { return ValidateSignalSemaphore(device, pSignalInfo, "vkSignalSemaphore"); } bool CoreChecks::PreCallValidateSignalSemaphoreKHR(VkDevice device, const VkSemaphoreSignalInfo *pSignalInfo) const { return ValidateSignalSemaphore(device, pSignalInfo, "vkSignalSemaphoreKHR"); } bool CoreChecks::ValidateImportSemaphore(VkSemaphore semaphore, const char *caller_name) const { bool skip = false; const SEMAPHORE_STATE *sema_node = GetSemaphoreState(semaphore); if (sema_node) { skip |= ValidateObjectNotInUse(sema_node, caller_name, kVUIDUndefined); } return skip; } #ifdef VK_USE_PLATFORM_WIN32_KHR bool CoreChecks::PreCallValidateImportSemaphoreWin32HandleKHR( VkDevice device, const VkImportSemaphoreWin32HandleInfoKHR *pImportSemaphoreWin32HandleInfo) const { return ValidateImportSemaphore(pImportSemaphoreWin32HandleInfo->semaphore, "vkImportSemaphoreWin32HandleKHR"); } #endif // VK_USE_PLATFORM_WIN32_KHR bool CoreChecks::PreCallValidateImportSemaphoreFdKHR(VkDevice device, const VkImportSemaphoreFdInfoKHR *pImportSemaphoreFdInfo) const { return ValidateImportSemaphore(pImportSemaphoreFdInfo->semaphore, "vkImportSemaphoreFdKHR"); } bool CoreChecks::ValidateImportFence(VkFence fence, const char *vuid, const char *caller_name) const { const FENCE_STATE *fence_node = GetFenceState(fence); bool skip = false; if (fence_node && fence_node->scope == kSyncScopeInternal && fence_node->state == FENCE_INFLIGHT) { skip |= LogError(fence, vuid, "%s: Fence %s that is currently in use.", caller_name, report_data->FormatHandle(fence).c_str()); } return skip; } #ifdef VK_USE_PLATFORM_WIN32_KHR bool CoreChecks::PreCallValidateImportFenceWin32HandleKHR( VkDevice device, const VkImportFenceWin32HandleInfoKHR *pImportFenceWin32HandleInfo) const { return ValidateImportFence(pImportFenceWin32HandleInfo->fence, "VUID-vkImportFenceWin32HandleKHR-fence-04448", "vkImportFenceWin32HandleKHR()"); } #endif // VK_USE_PLATFORM_WIN32_KHR bool CoreChecks::PreCallValidateImportFenceFdKHR(VkDevice device, const VkImportFenceFdInfoKHR *pImportFenceFdInfo) const { return ValidateImportFence(pImportFenceFdInfo->fence, "VUID-vkImportFenceFdKHR-fence-01463", "vkImportFenceFdKHR()"); } static VkImageCreateInfo GetSwapchainImpliedImageCreateInfo(VkSwapchainCreateInfoKHR const *pCreateInfo) { auto result = LvlInitStruct<VkImageCreateInfo>(); if (pCreateInfo->flags & VK_SWAPCHAIN_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT_KHR) { result.flags |= VK_IMAGE_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT; } if (pCreateInfo->flags & VK_SWAPCHAIN_CREATE_PROTECTED_BIT_KHR) result.flags |= VK_IMAGE_CREATE_PROTECTED_BIT; if (pCreateInfo->flags & VK_SWAPCHAIN_CREATE_MUTABLE_FORMAT_BIT_KHR) { result.flags |= VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT | VK_IMAGE_CREATE_EXTENDED_USAGE_BIT; } result.imageType = VK_IMAGE_TYPE_2D; result.format = pCreateInfo->imageFormat; result.extent.width = pCreateInfo->imageExtent.width; result.extent.height = pCreateInfo->imageExtent.height; result.extent.depth = 1; result.mipLevels = 1; result.arrayLayers = pCreateInfo->imageArrayLayers; result.samples = VK_SAMPLE_COUNT_1_BIT; result.tiling = VK_IMAGE_TILING_OPTIMAL; result.usage = pCreateInfo->imageUsage; result.sharingMode = pCreateInfo->imageSharingMode; result.queueFamilyIndexCount = pCreateInfo->queueFamilyIndexCount; result.pQueueFamilyIndices = pCreateInfo->pQueueFamilyIndices; result.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; return result; } bool CoreChecks::ValidateCreateSwapchain(const char *func_name, VkSwapchainCreateInfoKHR const *pCreateInfo, const SURFACE_STATE *surface_state, const SWAPCHAIN_NODE *old_swapchain_state) const { // All physical devices and queue families are required to be able to present to any native window on Android; require the // application to have established support on any other platform. if (!instance_extensions.vk_khr_android_surface) { auto support_predicate = [this](decltype(surface_state->gpu_queue_support)::value_type qs) -> bool { // TODO: should restrict search only to queue families of VkDeviceQueueCreateInfos, not whole phys. device return (qs.first.gpu == physical_device) && qs.second; }; const auto &support = surface_state->gpu_queue_support; bool is_supported = std::any_of(support.begin(), support.end(), support_predicate); if (!is_supported) { if (LogError( device, "VUID-VkSwapchainCreateInfoKHR-surface-01270", "%s: pCreateInfo->surface is not known at this time to be supported for presentation by this device. The " "vkGetPhysicalDeviceSurfaceSupportKHR() must be called beforehand, and it must return VK_TRUE support with " "this surface for at least one queue family of this device.", func_name)) { return true; } } } if (old_swapchain_state) { if (old_swapchain_state->createInfo.surface != pCreateInfo->surface) { if (LogError(pCreateInfo->oldSwapchain, "VUID-VkSwapchainCreateInfoKHR-oldSwapchain-01933", "%s: pCreateInfo->oldSwapchain's surface is not pCreateInfo->surface", func_name)) { return true; } } if (old_swapchain_state->retired) { if (LogError(pCreateInfo->oldSwapchain, "VUID-VkSwapchainCreateInfoKHR-oldSwapchain-01933", "%s: pCreateInfo->oldSwapchain is retired", func_name)) { return true; } } } if ((pCreateInfo->imageExtent.width == 0) || (pCreateInfo->imageExtent.height == 0)) { if (LogError(device, "VUID-VkSwapchainCreateInfoKHR-imageExtent-01689", "%s: pCreateInfo->imageExtent = (%d, %d) which is illegal.", func_name, pCreateInfo->imageExtent.width, pCreateInfo->imageExtent.height)) { return true; } } auto physical_device_state = GetPhysicalDeviceState(); bool skip = false; VkSurfaceTransformFlagBitsKHR current_transform = physical_device_state->surfaceCapabilities.currentTransform; if ((pCreateInfo->preTransform & current_transform) != pCreateInfo->preTransform) { skip |= LogPerformanceWarning(physical_device, kVUID_Core_Swapchain_PreTransform, "%s: pCreateInfo->preTransform (%s) doesn't match the currentTransform (%s) returned by " "vkGetPhysicalDeviceSurfaceCapabilitiesKHR, the presentation engine will transform the image " "content as part of the presentation operation.", func_name, string_VkSurfaceTransformFlagBitsKHR(pCreateInfo->preTransform), string_VkSurfaceTransformFlagBitsKHR(current_transform)); } const VkPresentModeKHR present_mode = pCreateInfo->presentMode; const bool shared_present_mode = (VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR == present_mode || VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR == present_mode); VkSurfaceCapabilitiesKHR capabilities{}; DispatchGetPhysicalDeviceSurfaceCapabilitiesKHR(physical_device_state->phys_device, pCreateInfo->surface, &capabilities); // Validate pCreateInfo->minImageCount against VkSurfaceCapabilitiesKHR::{min|max}ImageCount: // Shared Present Mode must have a minImageCount of 1 if ((pCreateInfo->minImageCount < capabilities.minImageCount) && !shared_present_mode) { const char *vuid = (device_extensions.vk_khr_shared_presentable_image) ? "VUID-VkSwapchainCreateInfoKHR-presentMode-02839" : "VUID-VkSwapchainCreateInfoKHR-minImageCount-01271"; if (LogError(device, vuid, "%s called with minImageCount = %d, which is outside the bounds returned by " "vkGetPhysicalDeviceSurfaceCapabilitiesKHR() (i.e. minImageCount = %d, maxImageCount = %d).", func_name, pCreateInfo->minImageCount, capabilities.minImageCount, capabilities.maxImageCount)) { return true; } } if ((capabilities.maxImageCount > 0) && (pCreateInfo->minImageCount > capabilities.maxImageCount)) { if (LogError(device, "VUID-VkSwapchainCreateInfoKHR-minImageCount-01272", "%s called with minImageCount = %d, which is outside the bounds returned by " "vkGetPhysicalDeviceSurfaceCapabilitiesKHR() (i.e. minImageCount = %d, maxImageCount = %d).", func_name, pCreateInfo->minImageCount, capabilities.minImageCount, capabilities.maxImageCount)) { return true; } } // Validate pCreateInfo->imageExtent against VkSurfaceCapabilitiesKHR::{current|min|max}ImageExtent: if ((pCreateInfo->imageExtent.width < capabilities.minImageExtent.width) || (pCreateInfo->imageExtent.width > capabilities.maxImageExtent.width) || (pCreateInfo->imageExtent.height < capabilities.minImageExtent.height) || (pCreateInfo->imageExtent.height > capabilities.maxImageExtent.height)) { if (LogError(device, "VUID-VkSwapchainCreateInfoKHR-imageExtent-01274", "%s called with imageExtent = (%d,%d), which is outside the bounds returned by " "vkGetPhysicalDeviceSurfaceCapabilitiesKHR(): currentExtent = (%d,%d), minImageExtent = (%d,%d), " "maxImageExtent = (%d,%d).", func_name, pCreateInfo->imageExtent.width, pCreateInfo->imageExtent.height, capabilities.currentExtent.width, capabilities.currentExtent.height, capabilities.minImageExtent.width, capabilities.minImageExtent.height, capabilities.maxImageExtent.width, capabilities.maxImageExtent.height)) { return true; } } // pCreateInfo->preTransform should have exactly one bit set, and that bit must also be set in // VkSurfaceCapabilitiesKHR::supportedTransforms. if (!pCreateInfo->preTransform || (pCreateInfo->preTransform & (pCreateInfo->preTransform - 1)) || !(pCreateInfo->preTransform & capabilities.supportedTransforms)) { // This is an error situation; one for which we'd like to give the developer a helpful, multi-line error message. Build // it up a little at a time, and then log it: std::string error_string = ""; char str[1024]; // Here's the first part of the message: sprintf(str, "%s called with a non-supported pCreateInfo->preTransform (i.e. %s). Supported values are:\n", func_name, string_VkSurfaceTransformFlagBitsKHR(pCreateInfo->preTransform)); error_string += str; for (int i = 0; i < 32; i++) { // Build up the rest of the message: if ((1 << i) & capabilities.supportedTransforms) { const char *new_str = string_VkSurfaceTransformFlagBitsKHR(static_cast<VkSurfaceTransformFlagBitsKHR>(1 << i)); sprintf(str, " %s\n", new_str); error_string += str; } } // Log the message that we've built up: if (LogError(device, "VUID-VkSwapchainCreateInfoKHR-preTransform-01279", "%s.", error_string.c_str())) return true; } // pCreateInfo->compositeAlpha should have exactly one bit set, and that bit must also be set in // VkSurfaceCapabilitiesKHR::supportedCompositeAlpha if (!pCreateInfo->compositeAlpha || (pCreateInfo->compositeAlpha & (pCreateInfo->compositeAlpha - 1)) || !((pCreateInfo->compositeAlpha) & capabilities.supportedCompositeAlpha)) { // This is an error situation; one for which we'd like to give the developer a helpful, multi-line error message. Build // it up a little at a time, and then log it: std::string error_string = ""; char str[1024]; // Here's the first part of the message: sprintf(str, "%s called with a non-supported pCreateInfo->compositeAlpha (i.e. %s). Supported values are:\n", func_name, string_VkCompositeAlphaFlagBitsKHR(pCreateInfo->compositeAlpha)); error_string += str; for (int i = 0; i < 32; i++) { // Build up the rest of the message: if ((1 << i) & capabilities.supportedCompositeAlpha) { const char *new_str = string_VkCompositeAlphaFlagBitsKHR(static_cast<VkCompositeAlphaFlagBitsKHR>(1 << i)); sprintf(str, " %s\n", new_str); error_string += str; } } // Log the message that we've built up: if (LogError(device, "VUID-VkSwapchainCreateInfoKHR-compositeAlpha-01280", "%s.", error_string.c_str())) return true; } // Validate pCreateInfo->imageArrayLayers against VkSurfaceCapabilitiesKHR::maxImageArrayLayers: if (pCreateInfo->imageArrayLayers > capabilities.maxImageArrayLayers) { if (LogError(device, "VUID-VkSwapchainCreateInfoKHR-imageArrayLayers-01275", "%s called with a non-supported imageArrayLayers (i.e. %d). Maximum value is %d.", func_name, pCreateInfo->imageArrayLayers, capabilities.maxImageArrayLayers)) { return true; } } const VkImageUsageFlags image_usage = pCreateInfo->imageUsage; // Validate pCreateInfo->imageUsage against VkSurfaceCapabilitiesKHR::supportedUsageFlags: // Shared Present Mode uses different set of capabilities to check imageUsage support if ((image_usage != (image_usage & capabilities.supportedUsageFlags)) && !shared_present_mode) { const char *vuid = (device_extensions.vk_khr_shared_presentable_image) ? "VUID-VkSwapchainCreateInfoKHR-presentMode-01427" : "VUID-VkSwapchainCreateInfoKHR-imageUsage-01276"; if (LogError(device, vuid, "%s called with a non-supported pCreateInfo->imageUsage (i.e. 0x%08x). Supported flag bits are 0x%08x.", func_name, image_usage, capabilities.supportedUsageFlags)) { return true; } } if (device_extensions.vk_khr_surface_protected_capabilities && (pCreateInfo->flags & VK_SWAPCHAIN_CREATE_PROTECTED_BIT_KHR)) { VkPhysicalDeviceSurfaceInfo2KHR surface_info = {VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SURFACE_INFO_2_KHR}; surface_info.surface = pCreateInfo->surface; VkSurfaceProtectedCapabilitiesKHR surface_protected_capabilities = {VK_STRUCTURE_TYPE_SURFACE_PROTECTED_CAPABILITIES_KHR}; VkSurfaceCapabilities2KHR surface_capabilities = {VK_STRUCTURE_TYPE_SURFACE_CAPABILITIES_2_KHR}; surface_capabilities.pNext = &surface_protected_capabilities; DispatchGetPhysicalDeviceSurfaceCapabilities2KHR(physical_device_state->phys_device, &surface_info, &surface_capabilities); if (!surface_protected_capabilities.supportsProtected) { if (LogError(device, "VUID-VkSwapchainCreateInfoKHR-flags-03187", "%s: pCreateInfo->flags contains VK_SWAPCHAIN_CREATE_PROTECTED_BIT_KHR but the surface " "capabilities does not have VkSurfaceProtectedCapabilitiesKHR.supportsProtected set to VK_TRUE.", func_name)) { return true; } } } std::vector<VkSurfaceFormatKHR> surface_formats; const auto *surface_formats_ref = &surface_formats; // Validate pCreateInfo values with the results of vkGetPhysicalDeviceSurfaceFormatsKHR(): if (physical_device_state->surface_formats.empty()) { uint32_t surface_format_count = 0; DispatchGetPhysicalDeviceSurfaceFormatsKHR(physical_device, pCreateInfo->surface, &surface_format_count, nullptr); surface_formats.resize(surface_format_count); DispatchGetPhysicalDeviceSurfaceFormatsKHR(physical_device, pCreateInfo->surface, &surface_format_count, &surface_formats[0]); } else { surface_formats_ref = &physical_device_state->surface_formats; } { // Validate pCreateInfo->imageFormat against VkSurfaceFormatKHR::format: bool found_format = false; bool found_color_space = false; bool found_match = false; for (const auto &format : *surface_formats_ref) { if (pCreateInfo->imageFormat == format.format) { // Validate pCreateInfo->imageColorSpace against VkSurfaceFormatKHR::colorSpace: found_format = true; if (pCreateInfo->imageColorSpace == format.colorSpace) { found_match = true; break; } } else { if (pCreateInfo->imageColorSpace == format.colorSpace) { found_color_space = true; } } } if (!found_match) { if (!found_format) { if (LogError(device, "VUID-VkSwapchainCreateInfoKHR-imageFormat-01273", "%s called with a non-supported pCreateInfo->imageFormat (%s).", func_name, string_VkFormat(pCreateInfo->imageFormat))) { return true; } } if (!found_color_space) { if (LogError(device, "VUID-VkSwapchainCreateInfoKHR-imageFormat-01273", "%s called with a non-supported pCreateInfo->imageColorSpace (%s).", func_name, string_VkColorSpaceKHR(pCreateInfo->imageColorSpace))) { return true; } } } } std::vector<VkPresentModeKHR> present_modes; const auto *present_modes_ref = &present_modes; // Validate pCreateInfo values with the results of vkGetPhysicalDeviceSurfacePresentModesKHR(): if (physical_device_state->present_modes.empty()) { uint32_t present_mode_count = 0; DispatchGetPhysicalDeviceSurfacePresentModesKHR(physical_device_state->phys_device, pCreateInfo->surface, &present_mode_count, nullptr); present_modes.resize(present_mode_count); DispatchGetPhysicalDeviceSurfacePresentModesKHR(physical_device_state->phys_device, pCreateInfo->surface, &present_mode_count, &present_modes[0]); } else { present_modes_ref = &physical_device_state->present_modes; } // Validate pCreateInfo->presentMode against vkGetPhysicalDeviceSurfacePresentModesKHR(): bool found_match = std::find(present_modes_ref->begin(), present_modes_ref->end(), present_mode) != present_modes_ref->end(); if (!found_match) { if (LogError(device, "VUID-VkSwapchainCreateInfoKHR-presentMode-01281", "%s called with a non-supported presentMode (i.e. %s).", func_name, string_VkPresentModeKHR(present_mode))) { return true; } } // Validate state for shared presentable case if (shared_present_mode) { if (!device_extensions.vk_khr_shared_presentable_image) { if (LogError( device, kVUID_Core_DrawState_ExtensionNotEnabled, "%s called with presentMode %s which requires the VK_KHR_shared_presentable_image extension, which has not " "been enabled.", func_name, string_VkPresentModeKHR(present_mode))) { return true; } } else if (pCreateInfo->minImageCount != 1) { if (LogError( device, "VUID-VkSwapchainCreateInfoKHR-minImageCount-01383", "%s called with presentMode %s, but minImageCount value is %d. For shared presentable image, minImageCount " "must be 1.", func_name, string_VkPresentModeKHR(present_mode), pCreateInfo->minImageCount)) { return true; } } VkSharedPresentSurfaceCapabilitiesKHR shared_present_capabilities = LvlInitStruct<VkSharedPresentSurfaceCapabilitiesKHR>(); VkSurfaceCapabilities2KHR capabilities2 = LvlInitStruct<VkSurfaceCapabilities2KHR>(&shared_present_capabilities); VkPhysicalDeviceSurfaceInfo2KHR surface_info = LvlInitStruct<VkPhysicalDeviceSurfaceInfo2KHR>(); surface_info.surface = pCreateInfo->surface; DispatchGetPhysicalDeviceSurfaceCapabilities2KHR(physical_device_state->phys_device, &surface_info, &capabilities2); if (image_usage != (image_usage & shared_present_capabilities.sharedPresentSupportedUsageFlags)) { if (LogError(device, "VUID-VkSwapchainCreateInfoKHR-imageUsage-01384", "%s called with a non-supported pCreateInfo->imageUsage (i.e. 0x%08x). Supported flag bits for %s " "present mode are 0x%08x.", func_name, image_usage, string_VkPresentModeKHR(pCreateInfo->presentMode), shared_present_capabilities.sharedPresentSupportedUsageFlags)) { return true; } } } if ((pCreateInfo->imageSharingMode == VK_SHARING_MODE_CONCURRENT) && pCreateInfo->pQueueFamilyIndices) { bool skip1 = ValidatePhysicalDeviceQueueFamilies(pCreateInfo->queueFamilyIndexCount, pCreateInfo->pQueueFamilyIndices, "vkCreateBuffer", "pCreateInfo->pQueueFamilyIndices", "VUID-VkSwapchainCreateInfoKHR-imageSharingMode-01428"); if (skip1) return true; } // Validate pCreateInfo->imageUsage against GetPhysicalDeviceFormatProperties const VkFormatProperties format_properties = GetPDFormatProperties(pCreateInfo->imageFormat); const VkFormatFeatureFlags tiling_features = format_properties.optimalTilingFeatures; if (tiling_features == 0) { if (LogError(device, "VUID-VkSwapchainCreateInfoKHR-imageFormat-01778", "%s: pCreateInfo->imageFormat %s with tiling VK_IMAGE_TILING_OPTIMAL has no supported format features on this " "physical device.", func_name, string_VkFormat(pCreateInfo->imageFormat))) { return true; } } else if ((image_usage & VK_IMAGE_USAGE_SAMPLED_BIT) && !(tiling_features & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT)) { if (LogError(device, "VUID-VkSwapchainCreateInfoKHR-imageFormat-01778", "%s: pCreateInfo->imageFormat %s with tiling VK_IMAGE_TILING_OPTIMAL does not support usage that includes " "VK_IMAGE_USAGE_SAMPLED_BIT.", func_name, string_VkFormat(pCreateInfo->imageFormat))) { return true; } } else if ((image_usage & VK_IMAGE_USAGE_STORAGE_BIT) && !(tiling_features & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT)) { if (LogError(device, "VUID-VkSwapchainCreateInfoKHR-imageFormat-01778", "%s: pCreateInfo->imageFormat %s with tiling VK_IMAGE_TILING_OPTIMAL does not support usage that includes " "VK_IMAGE_USAGE_STORAGE_BIT.", func_name, string_VkFormat(pCreateInfo->imageFormat))) { return true; } } else if ((image_usage & VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) && !(tiling_features & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT)) { if (LogError(device, "VUID-VkSwapchainCreateInfoKHR-imageFormat-01778", "%s: pCreateInfo->imageFormat %s with tiling VK_IMAGE_TILING_OPTIMAL does not support usage that includes " "VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT.", func_name, string_VkFormat(pCreateInfo->imageFormat))) { return true; } } else if ((image_usage & VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) && !(tiling_features & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT)) { if (LogError(device, "VUID-VkSwapchainCreateInfoKHR-imageFormat-01778", "%s: pCreateInfo->imageFormat %s with tiling VK_IMAGE_TILING_OPTIMAL does not support usage that includes " "VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT.", func_name, string_VkFormat(pCreateInfo->imageFormat))) { return true; } } else if ((image_usage & VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT) && !(tiling_features & (VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT | VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT))) { if (LogError(device, "VUID-VkSwapchainCreateInfoKHR-imageFormat-01778", "%s: pCreateInfo->imageFormat %s with tiling VK_IMAGE_TILING_OPTIMAL does not support usage that includes " "VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT or VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT.", func_name, string_VkFormat(pCreateInfo->imageFormat))) { return true; } } const VkImageCreateInfo image_create_info = GetSwapchainImpliedImageCreateInfo(pCreateInfo); VkImageFormatProperties image_properties = {}; const VkResult image_properties_result = DispatchGetPhysicalDeviceImageFormatProperties( physical_device, image_create_info.format, image_create_info.imageType, image_create_info.tiling, image_create_info.usage, image_create_info.flags, &image_properties); if (image_properties_result != VK_SUCCESS) { if (LogError(device, "VUID-VkSwapchainCreateInfoKHR-imageFormat-01778", "vkGetPhysicalDeviceImageFormatProperties() unexpectedly failed, " "when called for %s validation with following params: " "format: %s, imageType: %s, " "tiling: %s, usage: %s, " "flags: %s.", func_name, string_VkFormat(image_create_info.format), string_VkImageType(image_create_info.imageType), string_VkImageTiling(image_create_info.tiling), string_VkImageUsageFlags(image_create_info.usage).c_str(), string_VkImageCreateFlags(image_create_info.flags).c_str())) { return true; } } // Validate pCreateInfo->imageArrayLayers against VkImageFormatProperties::maxArrayLayers if (pCreateInfo->imageArrayLayers > image_properties.maxArrayLayers) { if (LogError(device, "VUID-VkSwapchainCreateInfoKHR-imageFormat-01778", "%s called with a non-supported imageArrayLayers (i.e. %d). " "Maximum value returned by vkGetPhysicalDeviceImageFormatProperties() is %d " "for imageFormat %s with tiling VK_IMAGE_TILING_OPTIMAL", func_name, pCreateInfo->imageArrayLayers, image_properties.maxArrayLayers, string_VkFormat(pCreateInfo->imageFormat))) { return true; } } // Validate pCreateInfo->imageExtent against VkImageFormatProperties::maxExtent if ((pCreateInfo->imageExtent.width > image_properties.maxExtent.width) || (pCreateInfo->imageExtent.height > image_properties.maxExtent.height)) { if (LogError(device, "VUID-VkSwapchainCreateInfoKHR-imageFormat-01778", "%s called with imageExtent = (%d,%d), which is bigger than max extent (%d,%d)" "returned by vkGetPhysicalDeviceImageFormatProperties(): " "for imageFormat %s with tiling VK_IMAGE_TILING_OPTIMAL", func_name, pCreateInfo->imageExtent.width, pCreateInfo->imageExtent.height, image_properties.maxExtent.width, image_properties.maxExtent.height, string_VkFormat(pCreateInfo->imageFormat))) { return true; } } if ((pCreateInfo->flags & VK_SWAPCHAIN_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT_KHR) && device_group_create_info.physicalDeviceCount == 1) { if (LogError(device, "VUID-VkSwapchainCreateInfoKHR-physicalDeviceCount-01429", "%s called with flags containing VK_SWAPCHAIN_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT_KHR" "but logical device was created with VkDeviceGroupDeviceCreateInfo::physicalDeviceCount equal to 1", func_name)) { return true; } } return skip; } bool CoreChecks::PreCallValidateCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkSwapchainKHR *pSwapchain) const { const auto surface_state = GetSurfaceState(pCreateInfo->surface); const auto old_swapchain_state = GetSwapchainState(pCreateInfo->oldSwapchain); return ValidateCreateSwapchain("vkCreateSwapchainKHR()", pCreateInfo, surface_state, old_swapchain_state); } void CoreChecks::PreCallRecordDestroySwapchainKHR(VkDevice device, VkSwapchainKHR swapchain, const VkAllocationCallbacks *pAllocator) { if (swapchain) { auto swapchain_data = GetSwapchainState(swapchain); if (swapchain_data) { for (const auto &swapchain_image : swapchain_data->images) { if (!swapchain_image.image_state) continue; imageLayoutMap.erase(swapchain_image.image_state->image()); qfo_release_image_barrier_map.erase(swapchain_image.image_state->image()); } } } StateTracker::PreCallRecordDestroySwapchainKHR(device, swapchain, pAllocator); } void CoreChecks::PostCallRecordGetSwapchainImagesKHR(VkDevice device, VkSwapchainKHR swapchain, uint32_t *pSwapchainImageCount, VkImage *pSwapchainImages, VkResult result) { // This function will run twice. The first is to get pSwapchainImageCount. The second is to get pSwapchainImages. // The first time in StateTracker::PostCallRecordGetSwapchainImagesKHR only generates the container's size. // The second time in StateTracker::PostCallRecordGetSwapchainImagesKHR will create VKImage and IMAGE_STATE. // So GlobalImageLayoutMap saving new IMAGE_STATEs has to run in the second time. // pSwapchainImages is not nullptr and it needs to wait until StateTracker::PostCallRecordGetSwapchainImagesKHR. uint32_t new_swapchain_image_index = 0; if (((result == VK_SUCCESS) || (result == VK_INCOMPLETE)) && pSwapchainImages) { auto swapchain_state = GetSwapchainState(swapchain); const auto image_vector_size = swapchain_state->images.size(); for (; new_swapchain_image_index < *pSwapchainImageCount; ++new_swapchain_image_index) { if ((new_swapchain_image_index >= image_vector_size) || !swapchain_state->images[new_swapchain_image_index].image_state) { break; }; } } StateTracker::PostCallRecordGetSwapchainImagesKHR(device, swapchain, pSwapchainImageCount, pSwapchainImages, result); if (((result == VK_SUCCESS) || (result == VK_INCOMPLETE)) && pSwapchainImages) { for (; new_swapchain_image_index < *pSwapchainImageCount; ++new_swapchain_image_index) { auto image_state = Get<IMAGE_STATE>(pSwapchainImages[new_swapchain_image_index]); AddInitialLayoutintoImageLayoutMap(*image_state, imageLayoutMap); } } } bool CoreChecks::PreCallValidateQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR *pPresentInfo) const { bool skip = false; const auto queue_state = GetQueueState(queue); for (uint32_t i = 0; i < pPresentInfo->waitSemaphoreCount; ++i) { const auto semaphore_state = GetSemaphoreState(pPresentInfo->pWaitSemaphores[i]); if (semaphore_state && semaphore_state->type != VK_SEMAPHORE_TYPE_BINARY) { skip |= LogError(pPresentInfo->pWaitSemaphores[i], "VUID-vkQueuePresentKHR-pWaitSemaphores-03267", "vkQueuePresentKHR: pWaitSemaphores[%u] (%s) is not a VK_SEMAPHORE_TYPE_BINARY", i, report_data->FormatHandle(pPresentInfo->pWaitSemaphores[i]).c_str()); } if (semaphore_state && !semaphore_state->signaled && !SemaphoreWasSignaled(pPresentInfo->pWaitSemaphores[i])) { LogObjectList objlist(queue); objlist.add(pPresentInfo->pWaitSemaphores[i]); skip |= LogError(objlist, "VUID-vkQueuePresentKHR-pWaitSemaphores-03268", "vkQueuePresentKHR: Queue %s is waiting on pWaitSemaphores[%u] (%s) that has no way to be signaled.", report_data->FormatHandle(queue).c_str(), i, report_data->FormatHandle(pPresentInfo->pWaitSemaphores[i]).c_str()); } } for (uint32_t i = 0; i < pPresentInfo->swapchainCount; ++i) { const auto swapchain_data = GetSwapchainState(pPresentInfo->pSwapchains[i]); if (swapchain_data) { // VU currently is 2-in-1, covers being a valid index and valid layout const char *validation_error = (device_extensions.vk_khr_shared_presentable_image) ? "VUID-VkPresentInfoKHR-pImageIndices-01430" : "VUID-VkPresentInfoKHR-pImageIndices-01296"; // Check if index is even possible to be acquired to give better error message if (pPresentInfo->pImageIndices[i] >= swapchain_data->images.size()) { skip |= LogError( pPresentInfo->pSwapchains[i], validation_error, "vkQueuePresentKHR: pSwapchains[%u] image index is too large (%u). There are only %u images in this swapchain.", i, pPresentInfo->pImageIndices[i], static_cast<uint32_t>(swapchain_data->images.size())); } else { const auto *image_state = swapchain_data->images[pPresentInfo->pImageIndices[i]].image_state; assert(image_state); if (!image_state->acquired) { skip |= LogError(pPresentInfo->pSwapchains[i], validation_error, "vkQueuePresentKHR: pSwapchains[%u] image index %u has not been acquired.", i, pPresentInfo->pImageIndices[i]); } vector<VkImageLayout> layouts; if (FindLayouts(*image_state, layouts)) { for (auto layout : layouts) { if ((layout != VK_IMAGE_LAYOUT_PRESENT_SRC_KHR) && (!device_extensions.vk_khr_shared_presentable_image || (layout != VK_IMAGE_LAYOUT_SHARED_PRESENT_KHR))) { skip |= LogError(queue, validation_error, "vkQueuePresentKHR(): pSwapchains[%u] images passed to present must be in layout " "VK_IMAGE_LAYOUT_PRESENT_SRC_KHR or " "VK_IMAGE_LAYOUT_SHARED_PRESENT_KHR but is in %s.", i, string_VkImageLayout(layout)); } } } } // All physical devices and queue families are required to be able to present to any native window on Android; require // the application to have established support on any other platform. if (!instance_extensions.vk_khr_android_surface) { const auto surface_state = GetSurfaceState(swapchain_data->createInfo.surface); auto support_it = surface_state->gpu_queue_support.find({physical_device, queue_state->queueFamilyIndex}); if (support_it == surface_state->gpu_queue_support.end()) { skip |= LogError( pPresentInfo->pSwapchains[i], kVUID_Core_DrawState_SwapchainUnsupportedQueue, "vkQueuePresentKHR: Presenting pSwapchains[%u] image without calling vkGetPhysicalDeviceSurfaceSupportKHR", i); } else if (!support_it->second) { skip |= LogError( pPresentInfo->pSwapchains[i], "VUID-vkQueuePresentKHR-pSwapchains-01292", "vkQueuePresentKHR: Presenting pSwapchains[%u] image on queue that cannot present to this surface.", i); } } } } if (pPresentInfo->pNext) { // Verify ext struct const auto *present_regions = LvlFindInChain<VkPresentRegionsKHR>(pPresentInfo->pNext); if (present_regions) { for (uint32_t i = 0; i < present_regions->swapchainCount; ++i) { const auto swapchain_data = GetSwapchainState(pPresentInfo->pSwapchains[i]); assert(swapchain_data); VkPresentRegionKHR region = present_regions->pRegions[i]; for (uint32_t j = 0; j < region.rectangleCount; ++j) { VkRectLayerKHR rect = region.pRectangles[j]; // Swap offsets and extents for 90 or 270 degree preTransform rotation if (swapchain_data->createInfo.preTransform & (VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR | VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR | VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR | VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR)) { std::swap(rect.offset.x, rect.offset.y); std::swap(rect.extent.width, rect.extent.height); } if ((rect.offset.x + rect.extent.width) > swapchain_data->createInfo.imageExtent.width) { skip |= LogError(pPresentInfo->pSwapchains[i], "VUID-VkRectLayerKHR-offset-04864", "vkQueuePresentKHR(): For VkPresentRegionKHR down pNext chain, pRegion[%i].pRectangles[%i], " "the sum of offset.x (%i) and extent.width (%i) after applying preTransform (%s) is greater " "than the corresponding swapchain's imageExtent.width (%i).", i, j, rect.offset.x, rect.extent.width, string_VkSurfaceTransformFlagBitsKHR(swapchain_data->createInfo.preTransform), swapchain_data->createInfo.imageExtent.width); } if ((rect.offset.y + rect.extent.height) > swapchain_data->createInfo.imageExtent.height) { skip |= LogError(pPresentInfo->pSwapchains[i], "VUID-VkRectLayerKHR-offset-04864", "vkQueuePresentKHR(): For VkPresentRegionKHR down pNext chain, pRegion[%i].pRectangles[%i], " "the sum of offset.y (%i) and extent.height (%i) after applying preTransform (%s) is greater " "than the corresponding swapchain's imageExtent.height (%i).", i, j, rect.offset.y, rect.extent.height, string_VkSurfaceTransformFlagBitsKHR(swapchain_data->createInfo.preTransform), swapchain_data->createInfo.imageExtent.height); } if (rect.layer > swapchain_data->createInfo.imageArrayLayers) { skip |= LogError( pPresentInfo->pSwapchains[i], "VUID-VkRectLayerKHR-layer-01262", "vkQueuePresentKHR(): For VkPresentRegionKHR down pNext chain, pRegion[%i].pRectangles[%i], the layer " "(%i) is greater than the corresponding swapchain's imageArrayLayers (%i).", i, j, rect.layer, swapchain_data->createInfo.imageArrayLayers); } } } } const auto *present_times_info = LvlFindInChain<VkPresentTimesInfoGOOGLE>(pPresentInfo->pNext); if (present_times_info) { if (pPresentInfo->swapchainCount != present_times_info->swapchainCount) { skip |= LogError(pPresentInfo->pSwapchains[0], "VUID-VkPresentTimesInfoGOOGLE-swapchainCount-01247", "vkQueuePresentKHR(): VkPresentTimesInfoGOOGLE.swapchainCount is %i but pPresentInfo->swapchainCount " "is %i. For VkPresentTimesInfoGOOGLE down pNext chain of VkPresentInfoKHR, " "VkPresentTimesInfoGOOGLE.swapchainCount must equal VkPresentInfoKHR.swapchainCount.", present_times_info->swapchainCount, pPresentInfo->swapchainCount); } } } return skip; } bool CoreChecks::PreCallValidateCreateSharedSwapchainsKHR(VkDevice device, uint32_t swapchainCount, const VkSwapchainCreateInfoKHR *pCreateInfos, const VkAllocationCallbacks *pAllocator, VkSwapchainKHR *pSwapchains) const { bool skip = false; if (pCreateInfos) { for (uint32_t i = 0; i < swapchainCount; i++) { const auto surface_state = GetSurfaceState(pCreateInfos[i].surface); const auto old_swapchain_state = GetSwapchainState(pCreateInfos[i].oldSwapchain); std::stringstream func_name; func_name << "vkCreateSharedSwapchainsKHR[" << swapchainCount << "]()"; skip |= ValidateCreateSwapchain(func_name.str().c_str(), &pCreateInfos[i], surface_state, old_swapchain_state); } } return skip; } bool CoreChecks::ValidateAcquireNextImage(VkDevice device, const CommandVersion cmd_version, VkSwapchainKHR swapchain, uint64_t timeout, VkSemaphore semaphore, VkFence fence, uint32_t *pImageIndex, const char *func_name, const char *semaphore_type_vuid) const { bool skip = false; auto semaphore_state = GetSemaphoreState(semaphore); if (semaphore_state && semaphore_state->type != VK_SEMAPHORE_TYPE_BINARY) { skip |= LogError(semaphore, semaphore_type_vuid, "%s: %s is not a VK_SEMAPHORE_TYPE_BINARY", func_name, report_data->FormatHandle(semaphore).c_str()); } if (semaphore_state && semaphore_state->scope == kSyncScopeInternal && semaphore_state->signaled) { skip |= LogError(semaphore, "VUID-vkAcquireNextImageKHR-semaphore-01286", "%s: Semaphore must not be currently signaled or in a wait state.", func_name); } auto fence_state = GetFenceState(fence); if (fence_state) { skip |= ValidateFenceForSubmit(fence_state, "VUID-vkAcquireNextImageKHR-fence-01287", "VUID-vkAcquireNextImageKHR-fence-01287", "vkAcquireNextImageKHR()"); } const auto swapchain_data = GetSwapchainState(swapchain); if (swapchain_data) { if (swapchain_data->retired) { skip |= LogError(swapchain, "VUID-vkAcquireNextImageKHR-swapchain-01285", "%s: This swapchain has been retired. The application can still present any images it " "has acquired, but cannot acquire any more.", func_name); } auto physical_device_state = GetPhysicalDeviceState(); // TODO: this is technically wrong on many levels, but requires massive cleanup if (physical_device_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHR_called) { const uint32_t acquired_images = static_cast<uint32_t>( std::count_if(swapchain_data->images.begin(), swapchain_data->images.end(), [](const SWAPCHAIN_IMAGE &image) { return (image.image_state && image.image_state->acquired); })); const uint32_t swapchain_image_count = static_cast<uint32_t>(swapchain_data->images.size()); const auto min_image_count = physical_device_state->surfaceCapabilities.minImageCount; const bool too_many_already_acquired = acquired_images > swapchain_image_count - min_image_count; if (timeout == UINT64_MAX && too_many_already_acquired) { const char *vuid = "INVALID-vuid"; if (cmd_version == CMD_VERSION_1) { vuid = "VUID-vkAcquireNextImageKHR-swapchain-01802"; } else if (cmd_version == CMD_VERSION_2) { vuid = "VUID-vkAcquireNextImage2KHR-swapchain-01803"; } else { assert(false); } const uint32_t acquirable = swapchain_image_count - min_image_count + 1; skip |= LogError(swapchain, vuid, "%s: Application has already previously acquired %" PRIu32 " image%s from swapchain. Only %" PRIu32 " %s available to be acquired using a timeout of UINT64_MAX (given the swapchain has %" PRIu32 ", and VkSurfaceCapabilitiesKHR::minImageCount is %" PRIu32 ").", func_name, acquired_images, acquired_images > 1 ? "s" : "", acquirable, acquirable > 1 ? "are" : "is", swapchain_image_count, min_image_count); } } } return skip; } bool CoreChecks::PreCallValidateAcquireNextImageKHR(VkDevice device, VkSwapchainKHR swapchain, uint64_t timeout, VkSemaphore semaphore, VkFence fence, uint32_t *pImageIndex) const { return ValidateAcquireNextImage(device, CMD_VERSION_1, swapchain, timeout, semaphore, fence, pImageIndex, "vkAcquireNextImageKHR", "VUID-vkAcquireNextImageKHR-semaphore-03265"); } bool CoreChecks::PreCallValidateAcquireNextImage2KHR(VkDevice device, const VkAcquireNextImageInfoKHR *pAcquireInfo, uint32_t *pImageIndex) const { bool skip = false; skip |= ValidateDeviceMaskToPhysicalDeviceCount(pAcquireInfo->deviceMask, pAcquireInfo->swapchain, "VUID-VkAcquireNextImageInfoKHR-deviceMask-01290"); skip |= ValidateDeviceMaskToZero(pAcquireInfo->deviceMask, pAcquireInfo->swapchain, "VUID-VkAcquireNextImageInfoKHR-deviceMask-01291"); skip |= ValidateAcquireNextImage(device, CMD_VERSION_2, pAcquireInfo->swapchain, pAcquireInfo->timeout, pAcquireInfo->semaphore, pAcquireInfo->fence, pImageIndex, "vkAcquireNextImage2KHR", "VUID-VkAcquireNextImageInfoKHR-semaphore-03266"); return skip; } bool CoreChecks::PreCallValidateDestroySurfaceKHR(VkInstance instance, VkSurfaceKHR surface, const VkAllocationCallbacks *pAllocator) const { const auto surface_state = GetSurfaceState(surface); bool skip = false; if ((surface_state) && (surface_state->swapchain)) { skip |= LogError(instance, "VUID-vkDestroySurfaceKHR-surface-01266", "vkDestroySurfaceKHR() called before its associated VkSwapchainKHR was destroyed."); } return skip; } #ifdef VK_USE_PLATFORM_WAYLAND_KHR bool CoreChecks::PreCallValidateGetPhysicalDeviceWaylandPresentationSupportKHR(VkPhysicalDevice physicalDevice, uint32_t queueFamilyIndex, struct wl_display *display) const { const auto pd_state = GetPhysicalDeviceState(physicalDevice); return ValidateQueueFamilyIndex(pd_state, queueFamilyIndex, "VUID-vkGetPhysicalDeviceWaylandPresentationSupportKHR-queueFamilyIndex-01306", "vkGetPhysicalDeviceWaylandPresentationSupportKHR", "queueFamilyIndex"); } #endif // VK_USE_PLATFORM_WAYLAND_KHR #ifdef VK_USE_PLATFORM_WIN32_KHR bool CoreChecks::PreCallValidateGetPhysicalDeviceWin32PresentationSupportKHR(VkPhysicalDevice physicalDevice, uint32_t queueFamilyIndex) const { const auto pd_state = GetPhysicalDeviceState(physicalDevice); return ValidateQueueFamilyIndex(pd_state, queueFamilyIndex, "VUID-vkGetPhysicalDeviceWin32PresentationSupportKHR-queueFamilyIndex-01309", "vkGetPhysicalDeviceWin32PresentationSupportKHR", "queueFamilyIndex"); } #endif // VK_USE_PLATFORM_WIN32_KHR #ifdef VK_USE_PLATFORM_XCB_KHR bool CoreChecks::PreCallValidateGetPhysicalDeviceXcbPresentationSupportKHR(VkPhysicalDevice physicalDevice, uint32_t queueFamilyIndex, xcb_connection_t *connection, xcb_visualid_t visual_id) const { const auto pd_state = GetPhysicalDeviceState(physicalDevice); return ValidateQueueFamilyIndex(pd_state, queueFamilyIndex, "VUID-vkGetPhysicalDeviceXcbPresentationSupportKHR-queueFamilyIndex-01312", "vkGetPhysicalDeviceXcbPresentationSupportKHR", "queueFamilyIndex"); } #endif // VK_USE_PLATFORM_XCB_KHR #ifdef VK_USE_PLATFORM_XLIB_KHR bool CoreChecks::PreCallValidateGetPhysicalDeviceXlibPresentationSupportKHR(VkPhysicalDevice physicalDevice, uint32_t queueFamilyIndex, Display *dpy, VisualID visualID) const { const auto pd_state = GetPhysicalDeviceState(physicalDevice); return ValidateQueueFamilyIndex(pd_state, queueFamilyIndex, "VUID-vkGetPhysicalDeviceXlibPresentationSupportKHR-queueFamilyIndex-01315", "vkGetPhysicalDeviceXlibPresentationSupportKHR", "queueFamilyIndex"); } #endif // VK_USE_PLATFORM_XLIB_KHR bool CoreChecks::PreCallValidateGetPhysicalDeviceSurfaceSupportKHR(VkPhysicalDevice physicalDevice, uint32_t queueFamilyIndex, VkSurfaceKHR surface, VkBool32 *pSupported) const { const auto physical_device_state = GetPhysicalDeviceState(physicalDevice); return ValidateQueueFamilyIndex(physical_device_state, queueFamilyIndex, "VUID-vkGetPhysicalDeviceSurfaceSupportKHR-queueFamilyIndex-01269", "vkGetPhysicalDeviceSurfaceSupportKHR", "queueFamilyIndex"); } bool CoreChecks::ValidateDescriptorUpdateTemplate(const char *func_name, const VkDescriptorUpdateTemplateCreateInfo *pCreateInfo) const { bool skip = false; const auto layout = GetDescriptorSetLayoutShared(pCreateInfo->descriptorSetLayout); if (VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_DESCRIPTOR_SET == pCreateInfo->templateType && !layout) { skip |= LogError(pCreateInfo->descriptorSetLayout, "VUID-VkDescriptorUpdateTemplateCreateInfo-templateType-00350", "%s: Invalid pCreateInfo->descriptorSetLayout (%s)", func_name, report_data->FormatHandle(pCreateInfo->descriptorSetLayout).c_str()); } else if (VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_PUSH_DESCRIPTORS_KHR == pCreateInfo->templateType) { auto bind_point = pCreateInfo->pipelineBindPoint; bool valid_bp = (bind_point == VK_PIPELINE_BIND_POINT_GRAPHICS) || (bind_point == VK_PIPELINE_BIND_POINT_COMPUTE) || (bind_point == VK_PIPELINE_BIND_POINT_RAY_TRACING_KHR); if (!valid_bp) { skip |= LogError(device, "VUID-VkDescriptorUpdateTemplateCreateInfo-templateType-00351", "%s: Invalid pCreateInfo->pipelineBindPoint (%" PRIu32 ").", func_name, static_cast<uint32_t>(bind_point)); } const auto pipeline_layout = GetPipelineLayout(pCreateInfo->pipelineLayout); if (!pipeline_layout) { skip |= LogError(pCreateInfo->pipelineLayout, "VUID-VkDescriptorUpdateTemplateCreateInfo-templateType-00352", "%s: Invalid pCreateInfo->pipelineLayout (%s)", func_name, report_data->FormatHandle(pCreateInfo->pipelineLayout).c_str()); } else { const uint32_t pd_set = pCreateInfo->set; if ((pd_set >= pipeline_layout->set_layouts.size()) || !pipeline_layout->set_layouts[pd_set] || !pipeline_layout->set_layouts[pd_set]->IsPushDescriptor()) { skip |= LogError(pCreateInfo->pipelineLayout, "VUID-VkDescriptorUpdateTemplateCreateInfo-templateType-00353", "%s: pCreateInfo->set (%" PRIu32 ") does not refer to the push descriptor set layout for pCreateInfo->pipelineLayout (%s).", func_name, pd_set, report_data->FormatHandle(pCreateInfo->pipelineLayout).c_str()); } } } return skip; } bool CoreChecks::PreCallValidateCreateDescriptorUpdateTemplate(VkDevice device, const VkDescriptorUpdateTemplateCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkDescriptorUpdateTemplate *pDescriptorUpdateTemplate) const { bool skip = ValidateDescriptorUpdateTemplate("vkCreateDescriptorUpdateTemplate()", pCreateInfo); return skip; } bool CoreChecks::PreCallValidateCreateDescriptorUpdateTemplateKHR(VkDevice device, const VkDescriptorUpdateTemplateCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkDescriptorUpdateTemplate *pDescriptorUpdateTemplate) const { bool skip = ValidateDescriptorUpdateTemplate("vkCreateDescriptorUpdateTemplateKHR()", pCreateInfo); return skip; } bool CoreChecks::ValidateUpdateDescriptorSetWithTemplate(VkDescriptorSet descriptorSet, VkDescriptorUpdateTemplate descriptorUpdateTemplate, const void *pData) const { bool skip = false; auto const template_map_entry = desc_template_map.find(descriptorUpdateTemplate); if ((template_map_entry == desc_template_map.end()) || (template_map_entry->second.get() == nullptr)) { // Object tracker will report errors for invalid descriptorUpdateTemplate values, avoiding a crash in release builds // but retaining the assert as template support is new enough to want to investigate these in debug builds. assert(0); } else { const TEMPLATE_STATE *template_state = template_map_entry->second.get(); // TODO: Validate template push descriptor updates if (template_state->create_info.templateType == VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_DESCRIPTOR_SET) { skip = ValidateUpdateDescriptorSetsWithTemplateKHR(descriptorSet, template_state, pData); } } return skip; } bool CoreChecks::PreCallValidateUpdateDescriptorSetWithTemplate(VkDevice device, VkDescriptorSet descriptorSet, VkDescriptorUpdateTemplate descriptorUpdateTemplate, const void *pData) const { return ValidateUpdateDescriptorSetWithTemplate(descriptorSet, descriptorUpdateTemplate, pData); } bool CoreChecks::PreCallValidateUpdateDescriptorSetWithTemplateKHR(VkDevice device, VkDescriptorSet descriptorSet, VkDescriptorUpdateTemplate descriptorUpdateTemplate, const void *pData) const { return ValidateUpdateDescriptorSetWithTemplate(descriptorSet, descriptorUpdateTemplate, pData); } bool CoreChecks::PreCallValidateCmdPushDescriptorSetWithTemplateKHR(VkCommandBuffer commandBuffer, VkDescriptorUpdateTemplate descriptorUpdateTemplate, VkPipelineLayout layout, uint32_t set, const void *pData) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); const char *const func_name = "vkPushDescriptorSetWithTemplateKHR()"; bool skip = false; skip |= ValidateCmd(cb_state, CMD_PUSHDESCRIPTORSETWITHTEMPLATEKHR, func_name); const auto layout_data = GetPipelineLayout(layout); const auto dsl = layout_data ? layout_data->GetDsl(set) : nullptr; // Validate the set index points to a push descriptor set and is in range if (dsl) { if (!dsl->IsPushDescriptor()) { skip = LogError(layout, "VUID-vkCmdPushDescriptorSetKHR-set-00365", "%s: Set index %" PRIu32 " does not match push descriptor set layout index for %s.", func_name, set, report_data->FormatHandle(layout).c_str()); } } else if (layout_data && (set >= layout_data->set_layouts.size())) { skip = LogError(layout, "VUID-vkCmdPushDescriptorSetKHR-set-00364", "%s: Set index %" PRIu32 " is outside of range for %s (set < %" PRIu32 ").", func_name, set, report_data->FormatHandle(layout).c_str(), static_cast<uint32_t>(layout_data->set_layouts.size())); } const auto template_state = GetDescriptorTemplateState(descriptorUpdateTemplate); if (template_state) { const auto &template_ci = template_state->create_info; static const std::map<VkPipelineBindPoint, std::string> bind_errors = { std::make_pair(VK_PIPELINE_BIND_POINT_GRAPHICS, "VUID-vkCmdPushDescriptorSetWithTemplateKHR-commandBuffer-00366"), std::make_pair(VK_PIPELINE_BIND_POINT_COMPUTE, "VUID-vkCmdPushDescriptorSetWithTemplateKHR-commandBuffer-00366"), std::make_pair(VK_PIPELINE_BIND_POINT_RAY_TRACING_KHR, "VUID-vkCmdPushDescriptorSetWithTemplateKHR-commandBuffer-00366")}; skip |= ValidatePipelineBindPoint(cb_state, template_ci.pipelineBindPoint, func_name, bind_errors); if (template_ci.templateType != VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_PUSH_DESCRIPTORS_KHR) { skip |= LogError(cb_state->commandBuffer(), kVUID_Core_PushDescriptorUpdate_TemplateType, "%s: descriptorUpdateTemplate %s was not created with flag " "VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_PUSH_DESCRIPTORS_KHR.", func_name, report_data->FormatHandle(descriptorUpdateTemplate).c_str()); } if (template_ci.set != set) { skip |= LogError(cb_state->commandBuffer(), kVUID_Core_PushDescriptorUpdate_Template_SetMismatched, "%s: descriptorUpdateTemplate %s created with set %" PRIu32 " does not match command parameter set %" PRIu32 ".", func_name, report_data->FormatHandle(descriptorUpdateTemplate).c_str(), template_ci.set, set); } if (!CompatForSet(set, layout_data, GetPipelineLayout(template_ci.pipelineLayout))) { LogObjectList objlist(cb_state->commandBuffer()); objlist.add(descriptorUpdateTemplate); objlist.add(template_ci.pipelineLayout); objlist.add(layout); skip |= LogError(objlist, kVUID_Core_PushDescriptorUpdate_Template_LayoutMismatched, "%s: descriptorUpdateTemplate %s created with %s is incompatible with command parameter " "%s for set %" PRIu32, func_name, report_data->FormatHandle(descriptorUpdateTemplate).c_str(), report_data->FormatHandle(template_ci.pipelineLayout).c_str(), report_data->FormatHandle(layout).c_str(), set); } } if (dsl && template_state) { // Create an empty proxy in order to use the existing descriptor set update validation cvdescriptorset::DescriptorSet proxy_ds(VK_NULL_HANDLE, nullptr, dsl, 0, this); // Decode the template into a set of write updates cvdescriptorset::DecodedTemplateUpdate decoded_template(this, VK_NULL_HANDLE, template_state, pData, dsl->GetDescriptorSetLayout()); // Validate the decoded update against the proxy_ds skip |= ValidatePushDescriptorsUpdate(&proxy_ds, static_cast<uint32_t>(decoded_template.desc_writes.size()), decoded_template.desc_writes.data(), func_name); } return skip; } bool CoreChecks::ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(VkPhysicalDevice physicalDevice, uint32_t planeIndex, const char *api_name) const { bool skip = false; const auto physical_device_state = GetPhysicalDeviceState(physicalDevice); if (physical_device_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHR_called) { if (planeIndex >= physical_device_state->display_plane_property_count) { skip |= LogError(physicalDevice, "VUID-vkGetDisplayPlaneSupportedDisplaysKHR-planeIndex-01249", "%s(): planeIndex (%u) must be in the range [0, %d] that was returned by " "vkGetPhysicalDeviceDisplayPlanePropertiesKHR " "or vkGetPhysicalDeviceDisplayPlaneProperties2KHR. Do you have the plane index hardcoded?", api_name, planeIndex, physical_device_state->display_plane_property_count - 1); } } return skip; } bool CoreChecks::PreCallValidateGetDisplayPlaneSupportedDisplaysKHR(VkPhysicalDevice physicalDevice, uint32_t planeIndex, uint32_t *pDisplayCount, VkDisplayKHR *pDisplays) const { bool skip = false; skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, planeIndex, "vkGetDisplayPlaneSupportedDisplaysKHR"); return skip; } bool CoreChecks::PreCallValidateGetDisplayPlaneCapabilitiesKHR(VkPhysicalDevice physicalDevice, VkDisplayModeKHR mode, uint32_t planeIndex, VkDisplayPlaneCapabilitiesKHR *pCapabilities) const { bool skip = false; skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, planeIndex, "vkGetDisplayPlaneCapabilitiesKHR"); return skip; } bool CoreChecks::PreCallValidateGetDisplayPlaneCapabilities2KHR(VkPhysicalDevice physicalDevice, const VkDisplayPlaneInfo2KHR *pDisplayPlaneInfo, VkDisplayPlaneCapabilities2KHR *pCapabilities) const { bool skip = false; skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(physicalDevice, pDisplayPlaneInfo->planeIndex, "vkGetDisplayPlaneCapabilities2KHR"); return skip; } bool CoreChecks::PreCallValidateCreateDisplayPlaneSurfaceKHR(VkInstance instance, const VkDisplaySurfaceCreateInfoKHR *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkSurfaceKHR *pSurface) const { bool skip = false; const VkDisplayModeKHR display_mode = pCreateInfo->displayMode; const uint32_t plane_index = pCreateInfo->planeIndex; if (pCreateInfo->alphaMode == VK_DISPLAY_PLANE_ALPHA_GLOBAL_BIT_KHR) { const float global_alpha = pCreateInfo->globalAlpha; if ((global_alpha > 1.0f) || (global_alpha < 0.0f)) { skip |= LogError( display_mode, "VUID-VkDisplaySurfaceCreateInfoKHR-alphaMode-01254", "vkCreateDisplayPlaneSurfaceKHR(): alphaMode is VK_DISPLAY_PLANE_ALPHA_GLOBAL_BIT_KHR but globalAlpha is %f.", global_alpha); } } const DISPLAY_MODE_STATE *dm_state = GetDisplayModeState(display_mode); if (dm_state != nullptr) { // Get physical device from VkDisplayModeKHR state tracking const VkPhysicalDevice physical_device = dm_state->physical_device; const auto physical_device_state = GetPhysicalDeviceState(physical_device); VkPhysicalDeviceProperties device_properties = {}; DispatchGetPhysicalDeviceProperties(physical_device, &device_properties); const uint32_t width = pCreateInfo->imageExtent.width; const uint32_t height = pCreateInfo->imageExtent.height; if (width >= device_properties.limits.maxImageDimension2D) { skip |= LogError(display_mode, "VUID-VkDisplaySurfaceCreateInfoKHR-width-01256", "vkCreateDisplayPlaneSurfaceKHR(): width (%" PRIu32 ") exceeds device limit maxImageDimension2D (%" PRIu32 ").", width, device_properties.limits.maxImageDimension2D); } if (height >= device_properties.limits.maxImageDimension2D) { skip |= LogError(display_mode, "VUID-VkDisplaySurfaceCreateInfoKHR-width-01256", "vkCreateDisplayPlaneSurfaceKHR(): height (%" PRIu32 ") exceeds device limit maxImageDimension2D (%" PRIu32 ").", height, device_properties.limits.maxImageDimension2D); } if (physical_device_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHR_called) { if (plane_index >= physical_device_state->display_plane_property_count) { skip |= LogError(display_mode, "VUID-VkDisplaySurfaceCreateInfoKHR-planeIndex-01252", "vkCreateDisplayPlaneSurfaceKHR(): planeIndex (%u) must be in the range [0, %d] that was returned by " "vkGetPhysicalDeviceDisplayPlanePropertiesKHR " "or vkGetPhysicalDeviceDisplayPlaneProperties2KHR. Do you have the plane index hardcoded?", plane_index, physical_device_state->display_plane_property_count - 1); } else { // call here once we know the plane index used is a valid plane index VkDisplayPlaneCapabilitiesKHR plane_capabilities; DispatchGetDisplayPlaneCapabilitiesKHR(physical_device, display_mode, plane_index, &plane_capabilities); if ((pCreateInfo->alphaMode & plane_capabilities.supportedAlpha) == 0) { skip |= LogError(display_mode, "VUID-VkDisplaySurfaceCreateInfoKHR-alphaMode-01255", "vkCreateDisplayPlaneSurfaceKHR(): alphaMode is %s but planeIndex %u supportedAlpha (0x%x) " "does not support the mode.", string_VkDisplayPlaneAlphaFlagBitsKHR(pCreateInfo->alphaMode), plane_index, plane_capabilities.supportedAlpha); } } } } return skip; } bool CoreChecks::PreCallValidateCmdDebugMarkerBeginEXT(VkCommandBuffer commandBuffer, const VkDebugMarkerMarkerInfoEXT *pMarkerInfo) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); return ValidateCmd(cb_state, CMD_DEBUGMARKERBEGINEXT, "vkCmdDebugMarkerBeginEXT()"); } bool CoreChecks::PreCallValidateCmdDebugMarkerEndEXT(VkCommandBuffer commandBuffer) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); return ValidateCmd(cb_state, CMD_DEBUGMARKERENDEXT, "vkCmdDebugMarkerEndEXT()"); } bool CoreChecks::PreCallValidateCmdBeginQueryIndexedEXT(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t query, VkQueryControlFlags flags, uint32_t index) const { if (disabled[query_validation]) return false; const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); QueryObject query_obj(queryPool, query, index); const char *cmd_name = "vkCmdBeginQueryIndexedEXT()"; struct BeginQueryIndexedVuids : ValidateBeginQueryVuids { BeginQueryIndexedVuids() : ValidateBeginQueryVuids() { vuid_queue_flags = "VUID-vkCmdBeginQueryIndexedEXT-commandBuffer-cmdpool"; vuid_queue_feedback = "VUID-vkCmdBeginQueryIndexedEXT-queryType-02338"; vuid_queue_occlusion = "VUID-vkCmdBeginQueryIndexedEXT-queryType-00803"; vuid_precise = "VUID-vkCmdBeginQueryIndexedEXT-queryType-00800"; vuid_query_count = "VUID-vkCmdBeginQueryIndexedEXT-query-00802"; vuid_profile_lock = "VUID-vkCmdBeginQueryIndexedEXT-queryPool-03223"; vuid_scope_not_first = "VUID-vkCmdBeginQueryIndexedEXT-queryPool-03224"; vuid_scope_in_rp = "VUID-vkCmdBeginQueryIndexedEXT-queryPool-03225"; vuid_dup_query_type = "VUID-vkCmdBeginQueryIndexedEXT-queryPool-04753"; vuid_protected_cb = "VUID-vkCmdBeginQueryIndexedEXT-commandBuffer-01885"; } }; BeginQueryIndexedVuids vuids; bool skip = ValidateBeginQuery(cb_state, query_obj, flags, index, CMD_BEGINQUERYINDEXEDEXT, cmd_name, &vuids); // Extension specific VU's const auto &query_pool_ci = GetQueryPoolState(query_obj.pool)->createInfo; if (query_pool_ci.queryType == VK_QUERY_TYPE_TRANSFORM_FEEDBACK_STREAM_EXT) { if (device_extensions.vk_ext_transform_feedback && (index >= phys_dev_ext_props.transform_feedback_props.maxTransformFeedbackStreams)) { skip |= LogError( cb_state->commandBuffer(), "VUID-vkCmdBeginQueryIndexedEXT-queryType-02339", "%s: index %" PRIu32 " must be less than VkPhysicalDeviceTransformFeedbackPropertiesEXT::maxTransformFeedbackStreams %" PRIu32 ".", cmd_name, index, phys_dev_ext_props.transform_feedback_props.maxTransformFeedbackStreams); } } else if (index != 0) { skip |= LogError(cb_state->commandBuffer(), "VUID-vkCmdBeginQueryIndexedEXT-queryType-02340", "%s: index %" PRIu32 " must be zero if %s was not created with type VK_QUERY_TYPE_TRANSFORM_FEEDBACK_STREAM_EXT.", cmd_name, index, report_data->FormatHandle(queryPool).c_str()); } return skip; } void CoreChecks::PreCallRecordCmdBeginQueryIndexedEXT(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t query, VkQueryControlFlags flags, uint32_t index) { if (disabled[query_validation]) return; QueryObject query_obj = {queryPool, query, index}; EnqueueVerifyBeginQuery(commandBuffer, query_obj, "vkCmdBeginQueryIndexedEXT()"); } void CoreChecks::PreCallRecordCmdEndQueryIndexedEXT(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t query, uint32_t index) { if (disabled[query_validation]) return; const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); QueryObject query_obj = {queryPool, query, index}; query_obj.endCommandIndex = cb_state->commandCount - 1; EnqueueVerifyEndQuery(commandBuffer, query_obj); } bool CoreChecks::PreCallValidateCmdEndQueryIndexedEXT(VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t query, uint32_t index) const { if (disabled[query_validation]) return false; QueryObject query_obj = {queryPool, query, index}; const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); struct EndQueryIndexedVuids : ValidateEndQueryVuids { EndQueryIndexedVuids() : ValidateEndQueryVuids() { vuid_queue_flags = "VUID-vkCmdEndQueryIndexedEXT-commandBuffer-cmdpool"; vuid_active_queries = "VUID-vkCmdEndQueryIndexedEXT-None-02342"; vuid_protected_cb = "VUID-vkCmdEndQueryIndexedEXT-commandBuffer-02344"; } }; EndQueryIndexedVuids vuids; return ValidateCmdEndQuery(cb_state, query_obj, index, CMD_ENDQUERYINDEXEDEXT, "vkCmdEndQueryIndexedEXT()", &vuids); } bool CoreChecks::PreCallValidateCmdSetDiscardRectangleEXT(VkCommandBuffer commandBuffer, uint32_t firstDiscardRectangle, uint32_t discardRectangleCount, const VkRect2D *pDiscardRectangles) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); bool skip = false; // Minimal validation for command buffer state skip |= ValidateCmd(cb_state, CMD_SETDISCARDRECTANGLEEXT, "vkCmdSetDiscardRectangleEXT()"); skip |= ForbidInheritedViewportScissor(commandBuffer, cb_state, "VUID-vkCmdSetDiscardRectangleEXT-viewportScissor2D-04788", "vkCmdSetDiscardRectangleEXT"); if (firstDiscardRectangle + discardRectangleCount > phys_dev_ext_props.discard_rectangle_props.maxDiscardRectangles) { skip |= LogError(cb_state->commandBuffer(), "VUID-vkCmdSetDiscardRectangleEXT-firstDiscardRectangle-00585", "vkCmdSetDiscardRectangleEXT(): firstDiscardRectangle (%" PRIu32 ") + discardRectangleCount (%" PRIu32 ") is not less than VkPhysicalDeviceDiscardRectanglePropertiesEXT::maxDiscardRectangles (%" PRIu32 ".", firstDiscardRectangle, discardRectangleCount, phys_dev_ext_props.discard_rectangle_props.maxDiscardRectangles); } return skip; } bool CoreChecks::PreCallValidateCmdSetSampleLocationsEXT(VkCommandBuffer commandBuffer, const VkSampleLocationsInfoEXT *pSampleLocationsInfo) const { bool skip = false; const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); // Minimal validation for command buffer state skip |= ValidateCmd(cb_state, CMD_SETSAMPLELOCATIONSEXT, "vkCmdSetSampleLocationsEXT()"); skip |= ValidateSampleLocationsInfo(pSampleLocationsInfo, "vkCmdSetSampleLocationsEXT"); const auto lv_bind_point = ConvertToLvlBindPoint(VK_PIPELINE_BIND_POINT_GRAPHICS); const auto *pipe = cb_state->lastBound[lv_bind_point].pipeline_state; if (pipe != nullptr) { // Check same error with different log messages const safe_VkPipelineMultisampleStateCreateInfo *multisample_state = pipe->graphicsPipelineCI.pMultisampleState; if (multisample_state == nullptr) { skip |= LogError(cb_state->commandBuffer(), "VUID-vkCmdSetSampleLocationsEXT-sampleLocationsPerPixel-01529", "vkCmdSetSampleLocationsEXT(): pSampleLocationsInfo->sampleLocationsPerPixel must be equal to " "rasterizationSamples, but the bound graphics pipeline was created without a multisample state"); } else if (multisample_state->rasterizationSamples != pSampleLocationsInfo->sampleLocationsPerPixel) { skip |= LogError(cb_state->commandBuffer(), "VUID-vkCmdSetSampleLocationsEXT-sampleLocationsPerPixel-01529", "vkCmdSetSampleLocationsEXT(): pSampleLocationsInfo->sampleLocationsPerPixel (%s) is not equal to " "the last bound pipeline's rasterizationSamples (%s)", string_VkSampleCountFlagBits(pSampleLocationsInfo->sampleLocationsPerPixel), string_VkSampleCountFlagBits(multisample_state->rasterizationSamples)); } } return skip; } bool CoreChecks::ValidateCreateSamplerYcbcrConversion(const char *func_name, const VkSamplerYcbcrConversionCreateInfo *create_info) const { bool skip = false; const VkFormat conversion_format = create_info->format; // Need to check for external format conversion first as it allows for non-UNORM format bool external_format = false; #ifdef VK_USE_PLATFORM_ANDROID_KHR const VkExternalFormatANDROID *ext_format_android = LvlFindInChain<VkExternalFormatANDROID>(create_info->pNext); if ((nullptr != ext_format_android) && (0 != ext_format_android->externalFormat)) { external_format = true; if (VK_FORMAT_UNDEFINED != create_info->format) { return LogError(device, "VUID-VkSamplerYcbcrConversionCreateInfo-format-01904", "%s: CreateInfo format is not VK_FORMAT_UNDEFINED while " "there is a chained VkExternalFormatANDROID struct with a non-zero externalFormat.", func_name); } } #endif // VK_USE_PLATFORM_ANDROID_KHR if ((external_format == false) && (FormatIsUNorm(conversion_format) == false)) { const char *vuid = (device_extensions.vk_android_external_memory_android_hardware_buffer) ? "VUID-VkSamplerYcbcrConversionCreateInfo-format-04061" : "VUID-VkSamplerYcbcrConversionCreateInfo-format-04060"; skip |= LogError(device, vuid, "%s: CreateInfo format (%s) is not an UNORM format and there is no external format conversion being created.", func_name, string_VkFormat(conversion_format)); } // Gets VkFormatFeatureFlags according to Sampler Ycbcr Conversion Format Features // (vkspec.html#potential-format-features) VkFormatFeatureFlags format_features = VK_FORMAT_FEATURE_FLAG_BITS_MAX_ENUM; if (conversion_format == VK_FORMAT_UNDEFINED) { #ifdef VK_USE_PLATFORM_ANDROID_KHR // only check for external format inside VK_FORMAT_UNDEFINED check to prevent unnecessary extra errors from no format // features being supported if (external_format == true) { auto it = ahb_ext_formats_map.find(ext_format_android->externalFormat); if (it != ahb_ext_formats_map.end()) { format_features = it->second; } } #endif // VK_USE_PLATFORM_ANDROID_KHR } else { format_features = GetPotentialFormatFeatures(conversion_format); } // Check all VUID that are based off of VkFormatFeatureFlags // These can't be in StatelessValidation due to needing possible External AHB state for feature support if (((format_features & VK_FORMAT_FEATURE_MIDPOINT_CHROMA_SAMPLES_BIT) == 0) && ((format_features & VK_FORMAT_FEATURE_COSITED_CHROMA_SAMPLES_BIT) == 0)) { skip |= LogError(device, "VUID-VkSamplerYcbcrConversionCreateInfo-format-01650", "%s: Format %s does not support either VK_FORMAT_FEATURE_MIDPOINT_CHROMA_SAMPLES_BIT or " "VK_FORMAT_FEATURE_COSITED_CHROMA_SAMPLES_BIT", func_name, string_VkFormat(conversion_format)); } if ((format_features & VK_FORMAT_FEATURE_COSITED_CHROMA_SAMPLES_BIT) == 0) { if (FormatIsXChromaSubsampled(conversion_format) && create_info->xChromaOffset == VK_CHROMA_LOCATION_COSITED_EVEN) { skip |= LogError(device, "VUID-VkSamplerYcbcrConversionCreateInfo-xChromaOffset-01651", "%s: Format %s does not support VK_FORMAT_FEATURE_COSITED_CHROMA_SAMPLES_BIT so xChromaOffset can't " "be VK_CHROMA_LOCATION_COSITED_EVEN", func_name, string_VkFormat(conversion_format)); } if (FormatIsYChromaSubsampled(conversion_format) && create_info->yChromaOffset == VK_CHROMA_LOCATION_COSITED_EVEN) { skip |= LogError(device, "VUID-VkSamplerYcbcrConversionCreateInfo-xChromaOffset-01651", "%s: Format %s does not support VK_FORMAT_FEATURE_COSITED_CHROMA_SAMPLES_BIT so yChromaOffset can't " "be VK_CHROMA_LOCATION_COSITED_EVEN", func_name, string_VkFormat(conversion_format)); } } if ((format_features & VK_FORMAT_FEATURE_MIDPOINT_CHROMA_SAMPLES_BIT) == 0) { if (FormatIsXChromaSubsampled(conversion_format) && create_info->xChromaOffset == VK_CHROMA_LOCATION_MIDPOINT) { skip |= LogError(device, "VUID-VkSamplerYcbcrConversionCreateInfo-xChromaOffset-01652", "%s: Format %s does not support VK_FORMAT_FEATURE_MIDPOINT_CHROMA_SAMPLES_BIT so xChromaOffset can't " "be VK_CHROMA_LOCATION_MIDPOINT", func_name, string_VkFormat(conversion_format)); } if (FormatIsYChromaSubsampled(conversion_format) && create_info->yChromaOffset == VK_CHROMA_LOCATION_MIDPOINT) { skip |= LogError(device, "VUID-VkSamplerYcbcrConversionCreateInfo-xChromaOffset-01652", "%s: Format %s does not support VK_FORMAT_FEATURE_MIDPOINT_CHROMA_SAMPLES_BIT so yChromaOffset can't " "be VK_CHROMA_LOCATION_MIDPOINT", func_name, string_VkFormat(conversion_format)); } } if (((format_features & VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_CHROMA_RECONSTRUCTION_EXPLICIT_FORCEABLE_BIT) == 0) && (create_info->forceExplicitReconstruction == VK_TRUE)) { skip |= LogError(device, "VUID-VkSamplerYcbcrConversionCreateInfo-forceExplicitReconstruction-01656", "%s: Format %s does not support " "VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_CHROMA_RECONSTRUCTION_EXPLICIT_FORCEABLE_BIT so " "forceExplicitReconstruction must be VK_FALSE", func_name, string_VkFormat(conversion_format)); } if (((format_features & VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_LINEAR_FILTER_BIT) == 0) && (create_info->chromaFilter == VK_FILTER_LINEAR)) { skip |= LogError(device, "VUID-VkSamplerYcbcrConversionCreateInfo-chromaFilter-01657", "%s: Format %s does not support VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_LINEAR_FILTER_BIT so " "chromaFilter must not be VK_FILTER_LINEAR", func_name, string_VkFormat(conversion_format)); } return skip; } bool CoreChecks::PreCallValidateCreateSamplerYcbcrConversion(VkDevice device, const VkSamplerYcbcrConversionCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkSamplerYcbcrConversion *pYcbcrConversion) const { return ValidateCreateSamplerYcbcrConversion("vkCreateSamplerYcbcrConversion()", pCreateInfo); } bool CoreChecks::PreCallValidateCreateSamplerYcbcrConversionKHR(VkDevice device, const VkSamplerYcbcrConversionCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkSamplerYcbcrConversion *pYcbcrConversion) const { return ValidateCreateSamplerYcbcrConversion("vkCreateSamplerYcbcrConversionKHR()", pCreateInfo); } bool CoreChecks::PreCallValidateCreateSampler(VkDevice device, const VkSamplerCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkSampler *pSampler) const { bool skip = false; if (samplerMap.size() >= phys_dev_props.limits.maxSamplerAllocationCount) { skip |= LogError( device, "VUID-vkCreateSampler-maxSamplerAllocationCount-04110", "vkCreateSampler(): Number of currently valid sampler objects (%zu) is not less than the maximum allowed (%u).", samplerMap.size(), phys_dev_props.limits.maxSamplerAllocationCount); } if (enabled_features.core11.samplerYcbcrConversion == VK_TRUE) { const VkSamplerYcbcrConversionInfo *conversion_info = LvlFindInChain<VkSamplerYcbcrConversionInfo>(pCreateInfo->pNext); if (conversion_info != nullptr) { const VkSamplerYcbcrConversion sampler_ycbcr_conversion = conversion_info->conversion; const SAMPLER_YCBCR_CONVERSION_STATE *ycbcr_state = GetSamplerYcbcrConversionState(sampler_ycbcr_conversion); if ((ycbcr_state->format_features & VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_SEPARATE_RECONSTRUCTION_FILTER_BIT) == 0) { const VkFilter chroma_filter = ycbcr_state->chromaFilter; if (pCreateInfo->minFilter != chroma_filter) { skip |= LogError( device, "VUID-VkSamplerCreateInfo-minFilter-01645", "VkCreateSampler: VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_SEPARATE_RECONSTRUCTION_FILTER_BIT is " "not supported for SamplerYcbcrConversion's (%s) format %s so minFilter (%s) needs to be equal to " "chromaFilter (%s)", report_data->FormatHandle(sampler_ycbcr_conversion).c_str(), string_VkFormat(ycbcr_state->format), string_VkFilter(pCreateInfo->minFilter), string_VkFilter(chroma_filter)); } if (pCreateInfo->magFilter != chroma_filter) { skip |= LogError( device, "VUID-VkSamplerCreateInfo-minFilter-01645", "VkCreateSampler: VK_FORMAT_FEATURE_SAMPLED_IMAGE_YCBCR_CONVERSION_SEPARATE_RECONSTRUCTION_FILTER_BIT is " "not supported for SamplerYcbcrConversion's (%s) format %s so minFilter (%s) needs to be equal to " "chromaFilter (%s)", report_data->FormatHandle(sampler_ycbcr_conversion).c_str(), string_VkFormat(ycbcr_state->format), string_VkFilter(pCreateInfo->minFilter), string_VkFilter(chroma_filter)); } } // At this point there is a known sampler YCbCr conversion enabled const auto *sampler_reduction = LvlFindInChain<VkSamplerReductionModeCreateInfo>(pCreateInfo->pNext); if (sampler_reduction != nullptr) { if (sampler_reduction->reductionMode != VK_SAMPLER_REDUCTION_MODE_WEIGHTED_AVERAGE) { skip |= LogError(device, "VUID-VkSamplerCreateInfo-None-01647", "A sampler YCbCr Conversion is being used creating this sampler so the sampler reduction mode " "must be VK_SAMPLER_REDUCTION_MODE_WEIGHTED_AVERAGE."); } } } } if (pCreateInfo->borderColor == VK_BORDER_COLOR_INT_CUSTOM_EXT || pCreateInfo->borderColor == VK_BORDER_COLOR_FLOAT_CUSTOM_EXT) { if (!enabled_features.custom_border_color_features.customBorderColors) { skip |= LogError(device, "VUID-VkSamplerCreateInfo-customBorderColors-04085", "vkCreateSampler(): A custom border color was specified without enabling the custom border color feature"); } auto custom_create_info = LvlFindInChain<VkSamplerCustomBorderColorCreateInfoEXT>(pCreateInfo->pNext); if (custom_create_info) { if (custom_create_info->format == VK_FORMAT_UNDEFINED && !enabled_features.custom_border_color_features.customBorderColorWithoutFormat) { skip |= LogError(device, "VUID-VkSamplerCustomBorderColorCreateInfoEXT-format-04014", "vkCreateSampler(): A custom border color was specified as VK_FORMAT_UNDEFINED without the " "customBorderColorWithoutFormat feature being enabled"); } } if (custom_border_color_sampler_count >= phys_dev_ext_props.custom_border_color_props.maxCustomBorderColorSamplers) { skip |= LogError(device, "VUID-VkSamplerCreateInfo-None-04012", "vkCreateSampler(): Creating a sampler with a custom border color will exceed the " "maxCustomBorderColorSamplers limit of %d", phys_dev_ext_props.custom_border_color_props.maxCustomBorderColorSamplers); } } if (ExtEnabled::kNotEnabled != device_extensions.vk_khr_portability_subset) { if ((VK_FALSE == enabled_features.portability_subset_features.samplerMipLodBias) && pCreateInfo->mipLodBias != 0) { skip |= LogError(device, "VUID-VkSamplerCreateInfo-samplerMipLodBias-04467", "vkCreateSampler (portability error): mip LOD bias not supported."); } } // If any of addressModeU, addressModeV or addressModeW are VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE, the // VK_KHR_sampler_mirror_clamp_to_edge extension or promoted feature must be enabled if ((device_extensions.vk_khr_sampler_mirror_clamp_to_edge != kEnabledByCreateinfo) && (enabled_features.core12.samplerMirrorClampToEdge == VK_FALSE)) { // Use 'else' because getting 3 large error messages is redundant and assume developer, if set all 3, will notice and fix // all at once if (pCreateInfo->addressModeU == VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE) { skip |= LogError(device, "VUID-VkSamplerCreateInfo-addressModeU-01079", "vkCreateSampler(): addressModeU is set to VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE but the " "VK_KHR_sampler_mirror_clamp_to_edge extension or samplerMirrorClampToEdge feature has not been enabled."); } else if (pCreateInfo->addressModeV == VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE) { skip |= LogError(device, "VUID-VkSamplerCreateInfo-addressModeU-01079", "vkCreateSampler(): addressModeV is set to VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE but the " "VK_KHR_sampler_mirror_clamp_to_edge extension or samplerMirrorClampToEdge feature has not been enabled."); } else if (pCreateInfo->addressModeW == VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE) { skip |= LogError(device, "VUID-VkSamplerCreateInfo-addressModeU-01079", "vkCreateSampler(): addressModeW is set to VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE but the " "VK_KHR_sampler_mirror_clamp_to_edge extension or samplerMirrorClampToEdge feature has not been enabled."); } } return skip; } bool CoreChecks::ValidateGetBufferDeviceAddress(VkDevice device, const VkBufferDeviceAddressInfo *pInfo, const char *apiName) const { bool skip = false; if (!enabled_features.core12.bufferDeviceAddress && !enabled_features.buffer_device_address_ext.bufferDeviceAddress) { skip |= LogError(pInfo->buffer, "VUID-vkGetBufferDeviceAddress-bufferDeviceAddress-03324", "%s: The bufferDeviceAddress feature must: be enabled.", apiName); } if (physical_device_count > 1 && !enabled_features.core12.bufferDeviceAddressMultiDevice && !enabled_features.buffer_device_address_ext.bufferDeviceAddressMultiDevice) { skip |= LogError(pInfo->buffer, "VUID-vkGetBufferDeviceAddress-device-03325", "%s: If device was created with multiple physical devices, then the " "bufferDeviceAddressMultiDevice feature must: be enabled.", apiName); } const auto buffer_state = GetBufferState(pInfo->buffer); if (buffer_state) { if (!(buffer_state->createInfo.flags & VK_BUFFER_CREATE_DEVICE_ADDRESS_CAPTURE_REPLAY_BIT)) { skip |= ValidateMemoryIsBoundToBuffer(buffer_state, apiName, "VUID-VkBufferDeviceAddressInfo-buffer-02600"); } skip |= ValidateBufferUsageFlags(buffer_state, VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, true, "VUID-VkBufferDeviceAddressInfo-buffer-02601", apiName, "VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT"); } return skip; } bool CoreChecks::PreCallValidateGetBufferDeviceAddressEXT(VkDevice device, const VkBufferDeviceAddressInfo *pInfo) const { return ValidateGetBufferDeviceAddress(device, static_cast<const VkBufferDeviceAddressInfo *>(pInfo), "vkGetBufferDeviceAddressEXT"); } bool CoreChecks::PreCallValidateGetBufferDeviceAddressKHR(VkDevice device, const VkBufferDeviceAddressInfo *pInfo) const { return ValidateGetBufferDeviceAddress(device, static_cast<const VkBufferDeviceAddressInfo *>(pInfo), "vkGetBufferDeviceAddressKHR"); } bool CoreChecks::PreCallValidateGetBufferDeviceAddress(VkDevice device, const VkBufferDeviceAddressInfo *pInfo) const { return ValidateGetBufferDeviceAddress(device, static_cast<const VkBufferDeviceAddressInfo *>(pInfo), "vkGetBufferDeviceAddress"); } bool CoreChecks::ValidateGetBufferOpaqueCaptureAddress(VkDevice device, const VkBufferDeviceAddressInfo *pInfo, const char *apiName) const { bool skip = false; if (!enabled_features.core12.bufferDeviceAddress) { skip |= LogError(pInfo->buffer, "VUID-vkGetBufferOpaqueCaptureAddress-None-03326", "%s(): The bufferDeviceAddress feature must: be enabled.", apiName); } if (physical_device_count > 1 && !enabled_features.core12.bufferDeviceAddressMultiDevice) { skip |= LogError(pInfo->buffer, "VUID-vkGetBufferOpaqueCaptureAddress-device-03327", "%s(): If device was created with multiple physical devices, then the " "bufferDeviceAddressMultiDevice feature must: be enabled.", apiName); } return skip; } bool CoreChecks::PreCallValidateGetBufferOpaqueCaptureAddressKHR(VkDevice device, const VkBufferDeviceAddressInfo *pInfo) const { return ValidateGetBufferOpaqueCaptureAddress(device, static_cast<const VkBufferDeviceAddressInfo *>(pInfo), "vkGetBufferOpaqueCaptureAddressKHR"); } bool CoreChecks::PreCallValidateGetBufferOpaqueCaptureAddress(VkDevice device, const VkBufferDeviceAddressInfo *pInfo) const { return ValidateGetBufferOpaqueCaptureAddress(device, static_cast<const VkBufferDeviceAddressInfo *>(pInfo), "vkGetBufferOpaqueCaptureAddress"); } bool CoreChecks::ValidateGetDeviceMemoryOpaqueCaptureAddress(VkDevice device, const VkDeviceMemoryOpaqueCaptureAddressInfo *pInfo, const char *apiName) const { bool skip = false; if (!enabled_features.core12.bufferDeviceAddress) { skip |= LogError(pInfo->memory, "VUID-vkGetDeviceMemoryOpaqueCaptureAddress-None-03334", "%s(): The bufferDeviceAddress feature must: be enabled.", apiName); } if (physical_device_count > 1 && !enabled_features.core12.bufferDeviceAddressMultiDevice) { skip |= LogError(pInfo->memory, "VUID-vkGetDeviceMemoryOpaqueCaptureAddress-device-03335", "%s(): If device was created with multiple physical devices, then the " "bufferDeviceAddressMultiDevice feature must: be enabled.", apiName); } const DEVICE_MEMORY_STATE *mem_info = GetDevMemState(pInfo->memory); if (mem_info) { auto chained_flags_struct = LvlFindInChain<VkMemoryAllocateFlagsInfo>(mem_info->alloc_info.pNext); if (!chained_flags_struct || !(chained_flags_struct->flags & VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT)) { skip |= LogError(pInfo->memory, "VUID-VkDeviceMemoryOpaqueCaptureAddressInfo-memory-03336", "%s(): memory must have been allocated with VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT.", apiName); } } return skip; } bool CoreChecks::PreCallValidateGetDeviceMemoryOpaqueCaptureAddressKHR(VkDevice device, const VkDeviceMemoryOpaqueCaptureAddressInfo *pInfo) const { return ValidateGetDeviceMemoryOpaqueCaptureAddress(device, static_cast<const VkDeviceMemoryOpaqueCaptureAddressInfo *>(pInfo), "vkGetDeviceMemoryOpaqueCaptureAddressKHR"); } bool CoreChecks::PreCallValidateGetDeviceMemoryOpaqueCaptureAddress(VkDevice device, const VkDeviceMemoryOpaqueCaptureAddressInfo *pInfo) const { return ValidateGetDeviceMemoryOpaqueCaptureAddress(device, static_cast<const VkDeviceMemoryOpaqueCaptureAddressInfo *>(pInfo), "vkGetDeviceMemoryOpaqueCaptureAddress"); } bool CoreChecks::ValidateQueryRange(VkDevice device, VkQueryPool queryPool, uint32_t totalCount, uint32_t firstQuery, uint32_t queryCount, const char *vuid_badfirst, const char *vuid_badrange, const char *apiName) const { bool skip = false; if (firstQuery >= totalCount) { skip |= LogError(device, vuid_badfirst, "%s(): firstQuery (%" PRIu32 ") greater than or equal to query pool count (%" PRIu32 ") for %s", apiName, firstQuery, totalCount, report_data->FormatHandle(queryPool).c_str()); } if ((firstQuery + queryCount) > totalCount) { skip |= LogError(device, vuid_badrange, "%s(): Query range [%" PRIu32 ", %" PRIu32 ") goes beyond query pool count (%" PRIu32 ") for %s", apiName, firstQuery, firstQuery + queryCount, totalCount, report_data->FormatHandle(queryPool).c_str()); } return skip; } bool CoreChecks::ValidateResetQueryPool(VkDevice device, VkQueryPool queryPool, uint32_t firstQuery, uint32_t queryCount, const char *apiName) const { if (disabled[query_validation]) return false; bool skip = false; if (!enabled_features.core12.hostQueryReset) { skip |= LogError(device, "VUID-vkResetQueryPool-None-02665", "%s(): Host query reset not enabled for device", apiName); } const auto query_pool_state = GetQueryPoolState(queryPool); if (query_pool_state) { skip |= ValidateQueryRange(device, queryPool, query_pool_state->createInfo.queryCount, firstQuery, queryCount, "VUID-vkResetQueryPool-firstQuery-02666", "VUID-vkResetQueryPool-firstQuery-02667", apiName); } return skip; } bool CoreChecks::PreCallValidateResetQueryPoolEXT(VkDevice device, VkQueryPool queryPool, uint32_t firstQuery, uint32_t queryCount) const { return ValidateResetQueryPool(device, queryPool, firstQuery, queryCount, "vkResetQueryPoolEXT"); } bool CoreChecks::PreCallValidateResetQueryPool(VkDevice device, VkQueryPool queryPool, uint32_t firstQuery, uint32_t queryCount) const { return ValidateResetQueryPool(device, queryPool, firstQuery, queryCount, "vkResetQueryPool"); } VkResult CoreChecks::CoreLayerCreateValidationCacheEXT(VkDevice device, const VkValidationCacheCreateInfoEXT *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkValidationCacheEXT *pValidationCache) { *pValidationCache = ValidationCache::Create(pCreateInfo); return *pValidationCache ? VK_SUCCESS : VK_ERROR_INITIALIZATION_FAILED; } void CoreChecks::CoreLayerDestroyValidationCacheEXT(VkDevice device, VkValidationCacheEXT validationCache, const VkAllocationCallbacks *pAllocator) { delete CastFromHandle<ValidationCache *>(validationCache); } VkResult CoreChecks::CoreLayerGetValidationCacheDataEXT(VkDevice device, VkValidationCacheEXT validationCache, size_t *pDataSize, void *pData) { size_t in_size = *pDataSize; CastFromHandle<ValidationCache *>(validationCache)->Write(pDataSize, pData); return (pData && *pDataSize != in_size) ? VK_INCOMPLETE : VK_SUCCESS; } VkResult CoreChecks::CoreLayerMergeValidationCachesEXT(VkDevice device, VkValidationCacheEXT dstCache, uint32_t srcCacheCount, const VkValidationCacheEXT *pSrcCaches) { bool skip = false; auto dst = CastFromHandle<ValidationCache *>(dstCache); VkResult result = VK_SUCCESS; for (uint32_t i = 0; i < srcCacheCount; i++) { auto src = CastFromHandle<const ValidationCache *>(pSrcCaches[i]); if (src == dst) { skip |= LogError(device, "VUID-vkMergeValidationCachesEXT-dstCache-01536", "vkMergeValidationCachesEXT: dstCache (0x%" PRIx64 ") must not appear in pSrcCaches array.", HandleToUint64(dstCache)); result = VK_ERROR_VALIDATION_FAILED_EXT; } if (!skip) { dst->Merge(src); } } return result; } bool CoreChecks::ValidateCmdSetDeviceMask(VkCommandBuffer commandBuffer, uint32_t deviceMask, const char *func_name) const { bool skip = false; const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); skip |= ValidateCmd(cb_state, CMD_SETDEVICEMASK, func_name); skip |= ValidateDeviceMaskToPhysicalDeviceCount(deviceMask, commandBuffer, "VUID-vkCmdSetDeviceMask-deviceMask-00108"); skip |= ValidateDeviceMaskToZero(deviceMask, commandBuffer, "VUID-vkCmdSetDeviceMask-deviceMask-00109"); skip |= ValidateDeviceMaskToCommandBuffer(cb_state, deviceMask, commandBuffer, "VUID-vkCmdSetDeviceMask-deviceMask-00110"); if (cb_state->activeRenderPass) { skip |= ValidateDeviceMaskToRenderPass(cb_state, deviceMask, "VUID-vkCmdSetDeviceMask-deviceMask-00111"); } return skip; } bool CoreChecks::PreCallValidateCmdSetDeviceMask(VkCommandBuffer commandBuffer, uint32_t deviceMask) const { return ValidateCmdSetDeviceMask(commandBuffer, deviceMask, "vkSetDeviceMask()"); } bool CoreChecks::PreCallValidateCmdSetDeviceMaskKHR(VkCommandBuffer commandBuffer, uint32_t deviceMask) const { return ValidateCmdSetDeviceMask(commandBuffer, deviceMask, "vkSetDeviceMaskKHR()"); } bool CoreChecks::ValidateGetSemaphoreCounterValue(VkDevice device, VkSemaphore semaphore, uint64_t *pValue, const char *apiName) const { bool skip = false; const auto *semaphore_state = GetSemaphoreState(semaphore); if (semaphore_state && semaphore_state->type != VK_SEMAPHORE_TYPE_TIMELINE) { skip |= LogError(semaphore, "VUID-vkGetSemaphoreCounterValue-semaphore-03255", "%s(): semaphore %s must be of VK_SEMAPHORE_TYPE_TIMELINE type", apiName, report_data->FormatHandle(semaphore).c_str()); } return skip; } bool CoreChecks::PreCallValidateGetSemaphoreCounterValueKHR(VkDevice device, VkSemaphore semaphore, uint64_t *pValue) const { return ValidateGetSemaphoreCounterValue(device, semaphore, pValue, "vkGetSemaphoreCounterValueKHR"); } bool CoreChecks::PreCallValidateGetSemaphoreCounterValue(VkDevice device, VkSemaphore semaphore, uint64_t *pValue) const { return ValidateGetSemaphoreCounterValue(device, semaphore, pValue, "vkGetSemaphoreCounterValue"); } bool CoreChecks::ValidateQueryPoolStride(const std::string &vuid_not_64, const std::string &vuid_64, const VkDeviceSize stride, const char *parameter_name, const uint64_t parameter_value, const VkQueryResultFlags flags) const { bool skip = false; if (flags & VK_QUERY_RESULT_64_BIT) { static const int condition_multiples = 0b0111; if ((stride & condition_multiples) || (parameter_value & condition_multiples)) { skip |= LogError(device, vuid_64, "stride %" PRIx64 " or %s %" PRIx64 " is invalid.", stride, parameter_name, parameter_value); } } else { static const int condition_multiples = 0b0011; if ((stride & condition_multiples) || (parameter_value & condition_multiples)) { skip |= LogError(device, vuid_not_64, "stride %" PRIx64 " or %s %" PRIx64 " is invalid.", stride, parameter_name, parameter_value); } } return skip; } bool CoreChecks::ValidateCmdDrawStrideWithStruct(VkCommandBuffer commandBuffer, const std::string &vuid, const uint32_t stride, const char *struct_name, const uint32_t struct_size) const { bool skip = false; static const int condition_multiples = 0b0011; if ((stride & condition_multiples) || (stride < struct_size)) { skip |= LogError(commandBuffer, vuid, "stride %d is invalid or less than sizeof(%s) %d.", stride, struct_name, struct_size); } return skip; } bool CoreChecks::ValidateCmdDrawStrideWithBuffer(VkCommandBuffer commandBuffer, const std::string &vuid, const uint32_t stride, const char *struct_name, const uint32_t struct_size, const uint32_t drawCount, const VkDeviceSize offset, const BUFFER_STATE *buffer_state) const { bool skip = false; uint64_t validation_value = stride * (drawCount - 1) + offset + struct_size; if (validation_value > buffer_state->createInfo.size) { skip |= LogError(commandBuffer, vuid, "stride[%d] * (drawCount[%d] - 1) + offset[%" PRIx64 "] + sizeof(%s)[%d] = %" PRIx64 " is greater than the size[%" PRIx64 "] of %s.", stride, drawCount, offset, struct_name, struct_size, validation_value, buffer_state->createInfo.size, report_data->FormatHandle(buffer_state->buffer()).c_str()); } return skip; } bool CoreChecks::PreCallValidateReleaseProfilingLockKHR(VkDevice device) const { bool skip = false; if (!performance_lock_acquired) { skip |= LogError(device, "VUID-vkReleaseProfilingLockKHR-device-03235", "vkReleaseProfilingLockKHR(): The profiling lock of device must have been held via a previous successful " "call to vkAcquireProfilingLockKHR."); } return skip; } bool CoreChecks::PreCallValidateCmdSetCheckpointNV(VkCommandBuffer commandBuffer, const void *pCheckpointMarker) const { { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); bool skip = false; skip |= ValidateCmd(cb_state, CMD_SETCHECKPOINTNV, "vkCmdSetCheckpointNV()"); return skip; } } bool CoreChecks::PreCallValidateWriteAccelerationStructuresPropertiesKHR(VkDevice device, uint32_t accelerationStructureCount, const VkAccelerationStructureKHR *pAccelerationStructures, VkQueryType queryType, size_t dataSize, void *pData, size_t stride) const { bool skip = false; for (uint32_t i = 0; i < accelerationStructureCount; ++i) { const ACCELERATION_STRUCTURE_STATE_KHR *as_state = GetAccelerationStructureStateKHR(pAccelerationStructures[i]); const auto &as_info = as_state->build_info_khr; if (queryType == VK_QUERY_TYPE_ACCELERATION_STRUCTURE_COMPACTED_SIZE_KHR) { if (!(as_info.flags & VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_COMPACTION_BIT_KHR)) { skip |= LogError(device, "VUID-vkWriteAccelerationStructuresPropertiesKHR-accelerationStructures-03431", "vkWriteAccelerationStructuresPropertiesKHR: All acceleration structures (%s) in " "pAccelerationStructures must have been built with" "VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_COMPACTION_BIT_KHR if queryType is " "VK_QUERY_TYPE_ACCELERATION_STRUCTURE_COMPACTED_SIZE_KHR.", report_data->FormatHandle(as_state->acceleration_structure()).c_str()); } } } return skip; } bool CoreChecks::PreCallValidateCmdWriteAccelerationStructuresPropertiesKHR( VkCommandBuffer commandBuffer, uint32_t accelerationStructureCount, const VkAccelerationStructureKHR *pAccelerationStructures, VkQueryType queryType, VkQueryPool queryPool, uint32_t firstQuery) const { bool skip = false; const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); skip |= ValidateCmd(cb_state, CMD_WRITEACCELERATIONSTRUCTURESPROPERTIESKHR, "vkCmdWriteAccelerationStructuresPropertiesKHR()"); const auto *query_pool_state = GetQueryPoolState(queryPool); const auto &query_pool_ci = query_pool_state->createInfo; if (query_pool_ci.queryType != queryType) { skip |= LogError( device, "VUID-vkCmdWriteAccelerationStructuresPropertiesKHR-queryPool-02493", "vkCmdWriteAccelerationStructuresPropertiesKHR: queryPool must have been created with a queryType matching queryType."); } for (uint32_t i = 0; i < accelerationStructureCount; ++i) { if (queryType == VK_QUERY_TYPE_ACCELERATION_STRUCTURE_COMPACTED_SIZE_KHR) { const ACCELERATION_STRUCTURE_STATE_KHR *as_state = GetAccelerationStructureStateKHR(pAccelerationStructures[i]); if (!(as_state->build_info_khr.flags & VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_COMPACTION_BIT_KHR)) { skip |= LogError( device, "VUID-vkCmdWriteAccelerationStructuresPropertiesKHR-accelerationStructures-03431", "vkCmdWriteAccelerationStructuresPropertiesKHR: All acceleration structures in pAccelerationStructures " "must have been built with VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_COMPACTION_BIT_KHR if queryType is " "VK_QUERY_TYPE_ACCELERATION_STRUCTURE_COMPACTED_SIZE_KHR."); } } } return skip; } bool CoreChecks::PreCallValidateCmdWriteAccelerationStructuresPropertiesNV(VkCommandBuffer commandBuffer, uint32_t accelerationStructureCount, const VkAccelerationStructureNV *pAccelerationStructures, VkQueryType queryType, VkQueryPool queryPool, uint32_t firstQuery) const { bool skip = false; const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); skip |= ValidateCmd(cb_state, CMD_WRITEACCELERATIONSTRUCTURESPROPERTIESNV, "vkCmdWriteAccelerationStructuresPropertiesNV()"); const auto *query_pool_state = GetQueryPoolState(queryPool); const auto &query_pool_ci = query_pool_state->createInfo; if (query_pool_ci.queryType != queryType) { skip |= LogError( device, "VUID-vkCmdWriteAccelerationStructuresPropertiesNV-queryPool-03755", "vkCmdWriteAccelerationStructuresPropertiesNV: queryPool must have been created with a queryType matching queryType."); } for (uint32_t i = 0; i < accelerationStructureCount; ++i) { if (queryType == VK_QUERY_TYPE_ACCELERATION_STRUCTURE_COMPACTED_SIZE_NV) { const ACCELERATION_STRUCTURE_STATE *as_state = GetAccelerationStructureStateNV(pAccelerationStructures[i]); if (!(as_state->build_info.flags & VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_COMPACTION_BIT_KHR)) { skip |= LogError(device, "VUID-vkCmdWriteAccelerationStructuresPropertiesNV-accelerationStructures-03431", "vkCmdWriteAccelerationStructuresPropertiesNV: All acceleration structures in pAccelerationStructures " "must have been built with VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_COMPACTION_BIT_KHR if queryType is " "VK_QUERY_TYPE_ACCELERATION_STRUCTURE_COMPACTED_SIZE_NV."); } } } return skip; } uint32_t CoreChecks::CalcTotalShaderGroupCount(const PIPELINE_STATE *pipelineState) const { uint32_t total = pipelineState->raytracingPipelineCI.groupCount; if (pipelineState->raytracingPipelineCI.pLibraryInfo) { for (uint32_t i = 0; i < pipelineState->raytracingPipelineCI.pLibraryInfo->libraryCount; ++i) { const PIPELINE_STATE *library_pipeline_state = GetPipelineState(pipelineState->raytracingPipelineCI.pLibraryInfo->pLibraries[i]); total += CalcTotalShaderGroupCount(library_pipeline_state); } } return total; } bool CoreChecks::PreCallValidateGetRayTracingShaderGroupHandlesKHR(VkDevice device, VkPipeline pipeline, uint32_t firstGroup, uint32_t groupCount, size_t dataSize, void *pData) const { bool skip = false; const PIPELINE_STATE *pipeline_state = GetPipelineState(pipeline); if (pipeline_state->getPipelineCreateFlags() & VK_PIPELINE_CREATE_LIBRARY_BIT_KHR) { skip |= LogError( device, "VUID-vkGetRayTracingShaderGroupHandlesKHR-pipeline-03482", "vkGetRayTracingShaderGroupHandlesKHR: pipeline must have not been created with VK_PIPELINE_CREATE_LIBRARY_BIT_KHR."); } if (dataSize < (phys_dev_ext_props.ray_tracing_propsKHR.shaderGroupHandleSize * groupCount)) { skip |= LogError(device, "VUID-vkGetRayTracingShaderGroupHandlesKHR-dataSize-02420", "vkGetRayTracingShaderGroupHandlesKHR: dataSize (%zu) must be at least " "VkPhysicalDeviceRayTracingPipelinePropertiesKHR::shaderGroupHandleSize * groupCount.", dataSize); } uint32_t total_group_count = CalcTotalShaderGroupCount(pipeline_state); if (firstGroup >= total_group_count) { skip |= LogError(device, "VUID-vkGetRayTracingShaderGroupHandlesKHR-firstGroup-04050", "vkGetRayTracingShaderGroupHandlesKHR: firstGroup must be less than the number of shader groups in pipeline."); } if ((firstGroup + groupCount) > total_group_count) { skip |= LogError( device, "VUID-vkGetRayTracingShaderGroupHandlesKHR-firstGroup-02419", "vkGetRayTracingShaderGroupHandlesKHR: The sum of firstGroup and groupCount must be less than or equal the number " "of shader groups in pipeline."); } return skip; } bool CoreChecks::PreCallValidateGetRayTracingCaptureReplayShaderGroupHandlesKHR(VkDevice device, VkPipeline pipeline, uint32_t firstGroup, uint32_t groupCount, size_t dataSize, void *pData) const { bool skip = false; if (dataSize < (phys_dev_ext_props.ray_tracing_propsKHR.shaderGroupHandleCaptureReplaySize * groupCount)) { skip |= LogError(device, "VUID-vkGetRayTracingCaptureReplayShaderGroupHandlesKHR-dataSize-03484", "vkGetRayTracingCaptureReplayShaderGroupHandlesKHR: dataSize (%zu) must be at least " "VkPhysicalDeviceRayTracingPipelinePropertiesKHR::shaderGroupHandleCaptureReplaySize * groupCount.", dataSize); } const PIPELINE_STATE *pipeline_state = GetPipelineState(pipeline); if (!pipeline_state) { return skip; } if (firstGroup >= pipeline_state->raytracingPipelineCI.groupCount) { skip |= LogError(device, "VUID-vkGetRayTracingCaptureReplayShaderGroupHandlesKHR-firstGroup-04051", "vkGetRayTracingCaptureReplayShaderGroupHandlesKHR: firstGroup must be less than the number of shader " "groups in pipeline."); } if ((firstGroup + groupCount) > pipeline_state->raytracingPipelineCI.groupCount) { skip |= LogError(device, "VUID-vkGetRayTracingCaptureReplayShaderGroupHandlesKHR-firstGroup-03483", "vkGetRayTracingCaptureReplayShaderGroupHandlesKHR: The sum of firstGroup and groupCount must be less " "than or equal to the number of shader groups in pipeline."); } if (!(pipeline_state->raytracingPipelineCI.flags & VK_PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR)) { skip |= LogError(device, "VUID-vkGetRayTracingCaptureReplayShaderGroupHandlesKHR-pipeline-03607", "pipeline must have been created with a flags that included " "VK_PIPELINE_CREATE_RAY_TRACING_SHADER_GROUP_HANDLE_CAPTURE_REPLAY_BIT_KHR."); } return skip; } bool CoreChecks::PreCallValidateCmdBuildAccelerationStructuresIndirectKHR(VkCommandBuffer commandBuffer, uint32_t infoCount, const VkAccelerationStructureBuildGeometryInfoKHR *pInfos, const VkDeviceAddress *pIndirectDeviceAddresses, const uint32_t *pIndirectStrides, const uint32_t *const *ppMaxPrimitiveCounts) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); bool skip = false; skip |= ValidateCmd(cb_state, CMD_BUILDACCELERATIONSTRUCTURESINDIRECTKHR, "vkCmdBuildAccelerationStructuresIndirectKHR()"); for (uint32_t i = 0; i < infoCount; ++i) { const ACCELERATION_STRUCTURE_STATE_KHR *src_as_state = GetAccelerationStructureStateKHR(pInfos[i].srcAccelerationStructure); const ACCELERATION_STRUCTURE_STATE_KHR *dst_as_state = GetAccelerationStructureStateKHR(pInfos[i].dstAccelerationStructure); if (pInfos[i].mode == VK_BUILD_ACCELERATION_STRUCTURE_MODE_UPDATE_KHR) { if (src_as_state == nullptr || !src_as_state->built || !(src_as_state->build_info_khr.flags & VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_UPDATE_BIT_KHR)) { skip |= LogError(device, "VUID-vkCmdBuildAccelerationStructuresIndirectKHR-pInfos-03667", "vkCmdBuildAccelerationStructuresIndirectKHR(): For each element of pInfos, if its mode member is " "VK_BUILD_ACCELERATION_STRUCTURE_MODE_UPDATE_KHR, its srcAccelerationStructure member must have " "been built before with VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_UPDATE_BIT_KHR set in " "VkAccelerationStructureBuildGeometryInfoKHR::flags."); } if (pInfos[i].geometryCount != src_as_state->build_info_khr.geometryCount) { skip |= LogError(device, "VUID-vkCmdBuildAccelerationStructuresIndirectKHR-pInfos-03758", "vkCmdBuildAccelerationStructuresIndirectKHR(): For each element of pInfos, if its mode member is " "VK_BUILD_ACCELERATION_STRUCTURE_MODE_UPDATE_KHR," " its geometryCount member must have the same value which was specified when " "srcAccelerationStructure was last built."); } if (pInfos[i].flags != src_as_state->build_info_khr.flags) { skip |= LogError(device, "VUID-vkCmdBuildAccelerationStructuresIndirectKHR-pInfos-03759", "vkCmdBuildAccelerationStructuresIndirectKHR(): For each element of pInfos, if its mode member is" " VK_BUILD_ACCELERATION_STRUCTURE_MODE_UPDATE_KHR, its flags member must have the same value which" " was specified when srcAccelerationStructure was last built."); } if (pInfos[i].type != src_as_state->build_info_khr.type) { skip |= LogError(device, "VUID-vkCmdBuildAccelerationStructuresIndirectKHR-pInfos-03760", "vkCmdBuildAccelerationStructuresIndirectKHR(): For each element of pInfos, if its mode member is" " VK_BUILD_ACCELERATION_STRUCTURE_MODE_UPDATE_KHR, its type member must have the same value which" " was specified when srcAccelerationStructure was last built."); } } if (pInfos[i].type == VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR) { if (!dst_as_state || (dst_as_state && dst_as_state->create_infoKHR.type != VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR && dst_as_state->create_infoKHR.type != VK_ACCELERATION_STRUCTURE_TYPE_GENERIC_KHR)) { skip |= LogError(device, "VUID-vkCmdBuildAccelerationStructuresIndirectKHR-pInfos-03700", "vkCmdBuildAccelerationStructuresIndirectKHR(): For each element of pInfos, if its type member is " "VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR, its dstAccelerationStructure member must have " "been created with a value of VkAccelerationStructureCreateInfoKHR::type equal to either " "VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_KHR or VK_ACCELERATION_STRUCTURE_TYPE_GENERIC_KHR."); } } if (pInfos[i].type == VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_KHR) { if (!dst_as_state || (dst_as_state && dst_as_state->create_infoKHR.type != VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_KHR && dst_as_state->create_infoKHR.type != VK_ACCELERATION_STRUCTURE_TYPE_GENERIC_KHR)) { skip |= LogError(device, "VUID-vkCmdBuildAccelerationStructuresIndirectKHR-pInfos-03699", "vkCmdBuildAccelerationStructuresIndirectKHR():For each element of pInfos, if its type member is " "VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_KHR, its dstAccelerationStructure member must have been " "created with a value of VkAccelerationStructureCreateInfoKHR::type equal to either " "VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_KHR or VK_ACCELERATION_STRUCTURE_TYPE_GENERIC_KHR."); } } } return skip; } bool CoreChecks::ValidateCopyAccelerationStructureInfoKHR(const VkCopyAccelerationStructureInfoKHR *pInfo, const char *api_name) const { bool skip = false; if (pInfo->mode == VK_COPY_ACCELERATION_STRUCTURE_MODE_COMPACT_KHR) { const ACCELERATION_STRUCTURE_STATE_KHR *src_as_state = GetAccelerationStructureStateKHR(pInfo->src); if (!(src_as_state->build_info_khr.flags & VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_COMPACTION_BIT_KHR)) { skip |= LogError(device, "VUID-VkCopyAccelerationStructureInfoKHR-src-03411", "(%s): src must have been built with VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_COMPACTION_BIT_KHR" "if mode is VK_COPY_ACCELERATION_STRUCTURE_MODE_COMPACT_KHR.", api_name); } } return skip; } bool CoreChecks::PreCallValidateCmdCopyAccelerationStructureKHR(VkCommandBuffer commandBuffer, const VkCopyAccelerationStructureInfoKHR *pInfo) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); ValidateCmd(cb_state, CMD_COPYACCELERATIONSTRUCTUREKHR, "vkCmdCopyAccelerationStructureKHR()"); ValidateCopyAccelerationStructureInfoKHR(pInfo, "vkCmdCopyAccelerationStructureKHR"); return false; } bool CoreChecks::PreCallValidateCopyAccelerationStructureKHR(VkDevice device, VkDeferredOperationKHR deferredOperation, const VkCopyAccelerationStructureInfoKHR *pInfo) const { bool skip = false; skip |= ValidateCopyAccelerationStructureInfoKHR(pInfo, "vkCopyAccelerationStructureKHR"); return skip; } bool CoreChecks::PreCallValidateCmdCopyAccelerationStructureToMemoryKHR( VkCommandBuffer commandBuffer, const VkCopyAccelerationStructureToMemoryInfoKHR *pInfo) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); bool skip = false; skip |= ValidateCmd(cb_state, CMD_COPYACCELERATIONSTRUCTURETOMEMORYKHR, "vkCmdCopyAccelerationStructureToMemoryKHR()"); const auto *accel_state = GetAccelerationStructureStateKHR(pInfo->src); if (accel_state) { const auto *buffer_state = GetBufferState(accel_state->create_infoKHR.buffer); skip |= ValidateMemoryIsBoundToBuffer(buffer_state, "vkCmdCopyAccelerationStructureToMemoryKHR", "VUID-vkCmdCopyAccelerationStructureToMemoryKHR-None-03559"); } return skip; } bool CoreChecks::PreCallValidateCmdCopyMemoryToAccelerationStructureKHR( VkCommandBuffer commandBuffer, const VkCopyMemoryToAccelerationStructureInfoKHR *pInfo) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); bool skip = false; skip |= ValidateCmd(cb_state, CMD_COPYMEMORYTOACCELERATIONSTRUCTUREKHR, "vkCmdCopyMemoryToAccelerationStructureKHR()"); return skip; } bool CoreChecks::PreCallValidateCmdBindTransformFeedbackBuffersEXT(VkCommandBuffer commandBuffer, uint32_t firstBinding, uint32_t bindingCount, const VkBuffer *pBuffers, const VkDeviceSize *pOffsets, const VkDeviceSize *pSizes) const { bool skip = false; char const *const cmd_name = "CmdBindTransformFeedbackBuffersEXT"; if (!enabled_features.transform_feedback_features.transformFeedback) { skip |= LogError(commandBuffer, "VUID-vkCmdBindTransformFeedbackBuffersEXT-transformFeedback-02355", "%s: transformFeedback feature is not enabled.", cmd_name); } { auto const cb_state = GetCBState(commandBuffer); if (cb_state->transform_feedback_active) { skip |= LogError(commandBuffer, "VUID-vkCmdBindTransformFeedbackBuffersEXT-None-02365", "%s: transform feedback is active.", cmd_name); } } for (uint32_t i = 0; i < bindingCount; ++i) { auto const buffer_state = GetBufferState(pBuffers[i]); assert(buffer_state != nullptr); if (pOffsets[i] >= buffer_state->createInfo.size) { skip |= LogError(buffer_state->buffer(), "VUID-vkCmdBindTransformFeedbackBuffersEXT-pOffsets-02358", "%s: pOffset[%" PRIu32 "](0x%" PRIxLEAST64 ") is greater than or equal to the size of pBuffers[%" PRIu32 "](0x%" PRIxLEAST64 ").", cmd_name, i, pOffsets[i], i, buffer_state->createInfo.size); } if ((buffer_state->createInfo.usage & VK_BUFFER_USAGE_TRANSFORM_FEEDBACK_BUFFER_BIT_EXT) == 0) { skip |= LogError(buffer_state->buffer(), "VUID-vkCmdBindTransformFeedbackBuffersEXT-pBuffers-02360", "%s: pBuffers[%" PRIu32 "] (%s)" " was not created with the VK_BUFFER_USAGE_TRANSFORM_FEEDBACK_BUFFER_BIT_EXT flag.", cmd_name, i, report_data->FormatHandle(pBuffers[i]).c_str()); } // pSizes is optional and may be nullptr. Also might be VK_WHOLE_SIZE which VU don't apply if ((pSizes != nullptr) && (pSizes[i] != VK_WHOLE_SIZE)) { // only report one to prevent redundant error if the size is larger since adding offset will be as well if (pSizes[i] > buffer_state->createInfo.size) { skip |= LogError(buffer_state->buffer(), "VUID-vkCmdBindTransformFeedbackBuffersEXT-pSizes-02362", "%s: pSizes[%" PRIu32 "](0x%" PRIxLEAST64 ") is greater than the size of pBuffers[%" PRIu32 "](0x%" PRIxLEAST64 ").", cmd_name, i, pSizes[i], i, buffer_state->createInfo.size); } else if (pOffsets[i] + pSizes[i] > buffer_state->createInfo.size) { skip |= LogError(buffer_state->buffer(), "VUID-vkCmdBindTransformFeedbackBuffersEXT-pOffsets-02363", "%s: The sum of pOffsets[%" PRIu32 "](Ox%" PRIxLEAST64 ") and pSizes[%" PRIu32 "](0x%" PRIxLEAST64 ") is greater than the size of pBuffers[%" PRIu32 "](0x%" PRIxLEAST64 ").", cmd_name, i, pOffsets[i], i, pSizes[i], i, buffer_state->createInfo.size); } } skip |= ValidateMemoryIsBoundToBuffer(buffer_state, cmd_name, "VUID-vkCmdBindTransformFeedbackBuffersEXT-pBuffers-02364"); } return skip; } bool CoreChecks::PreCallValidateCmdBeginTransformFeedbackEXT(VkCommandBuffer commandBuffer, uint32_t firstCounterBuffer, uint32_t counterBufferCount, const VkBuffer *pCounterBuffers, const VkDeviceSize *pCounterBufferOffsets) const { bool skip = false; char const *const cmd_name = "CmdBeginTransformFeedbackEXT"; if (!enabled_features.transform_feedback_features.transformFeedback) { skip |= LogError(commandBuffer, "VUID-vkCmdBeginTransformFeedbackEXT-transformFeedback-02366", "%s: transformFeedback feature is not enabled.", cmd_name); } { auto const cb_state = GetCBState(commandBuffer); if (cb_state->transform_feedback_active) { skip |= LogError(commandBuffer, "VUID-vkCmdBeginTransformFeedbackEXT-None-02367", "%s: transform feedback is active.", cmd_name); } } // pCounterBuffers and pCounterBufferOffsets are optional and may be nullptr. Additionaly, pCounterBufferOffsets must be nullptr // if pCounterBuffers is nullptr. if (pCounterBuffers == nullptr) { if (pCounterBufferOffsets != nullptr) { skip |= LogError(commandBuffer, "VUID-vkCmdBeginTransformFeedbackEXT-pCounterBuffer-02371", "%s: pCounterBuffers is NULL and pCounterBufferOffsets is not NULL.", cmd_name); } } else { for (uint32_t i = 0; i < counterBufferCount; ++i) { if (pCounterBuffers[i] != VK_NULL_HANDLE) { auto const buffer_state = GetBufferState(pCounterBuffers[i]); assert(buffer_state != nullptr); if (pCounterBufferOffsets != nullptr && pCounterBufferOffsets[i] + 4 > buffer_state->createInfo.size) { skip |= LogError(buffer_state->buffer(), "VUID-vkCmdBeginTransformFeedbackEXT-pCounterBufferOffsets-02370", "%s: pCounterBuffers[%" PRIu32 "](%s) is not large enough to hold 4 bytes at pCounterBufferOffsets[%" PRIu32 "](0x%" PRIx64 ").", cmd_name, i, report_data->FormatHandle(pCounterBuffers[i]).c_str(), i, pCounterBufferOffsets[i]); } if ((buffer_state->createInfo.usage & VK_BUFFER_USAGE_TRANSFORM_FEEDBACK_COUNTER_BUFFER_BIT_EXT) == 0) { skip |= LogError(buffer_state->buffer(), "VUID-vkCmdBeginTransformFeedbackEXT-pCounterBuffers-02372", "%s: pCounterBuffers[%" PRIu32 "] (%s) was not created with the VK_BUFFER_USAGE_TRANSFORM_FEEDBACK_COUNTER_BUFFER_BIT_EXT flag.", cmd_name, i, report_data->FormatHandle(pCounterBuffers[i]).c_str()); } } } } return skip; } bool CoreChecks::PreCallValidateCmdEndTransformFeedbackEXT(VkCommandBuffer commandBuffer, uint32_t firstCounterBuffer, uint32_t counterBufferCount, const VkBuffer *pCounterBuffers, const VkDeviceSize *pCounterBufferOffsets) const { bool skip = false; char const *const cmd_name = "CmdEndTransformFeedbackEXT"; if (!enabled_features.transform_feedback_features.transformFeedback) { skip |= LogError(commandBuffer, "VUID-vkCmdEndTransformFeedbackEXT-transformFeedback-02374", "%s: transformFeedback feature is not enabled.", cmd_name); } { auto const cb_state = GetCBState(commandBuffer); if (!cb_state->transform_feedback_active) { skip |= LogError(commandBuffer, "VUID-vkCmdEndTransformFeedbackEXT-None-02375", "%s: transform feedback is not active.", cmd_name); } } // pCounterBuffers and pCounterBufferOffsets are optional and may be nullptr. Additionaly, pCounterBufferOffsets must be nullptr // if pCounterBuffers is nullptr. if (pCounterBuffers == nullptr) { if (pCounterBufferOffsets != nullptr) { skip |= LogError(commandBuffer, "VUID-vkCmdEndTransformFeedbackEXT-pCounterBuffer-02379", "%s: pCounterBuffers is NULL and pCounterBufferOffsets is not NULL.", cmd_name); } } else { for (uint32_t i = 0; i < counterBufferCount; ++i) { if (pCounterBuffers[i] != VK_NULL_HANDLE) { auto const buffer_state = GetBufferState(pCounterBuffers[i]); assert(buffer_state != nullptr); if (pCounterBufferOffsets != nullptr && pCounterBufferOffsets[i] + 4 > buffer_state->createInfo.size) { skip |= LogError(buffer_state->buffer(), "VUID-vkCmdEndTransformFeedbackEXT-pCounterBufferOffsets-02378", "%s: pCounterBuffers[%" PRIu32 "](%s) is not large enough to hold 4 bytes at pCounterBufferOffsets[%" PRIu32 "](0x%" PRIx64 ").", cmd_name, i, report_data->FormatHandle(pCounterBuffers[i]).c_str(), i, pCounterBufferOffsets[i]); } if ((buffer_state->createInfo.usage & VK_BUFFER_USAGE_TRANSFORM_FEEDBACK_COUNTER_BUFFER_BIT_EXT) == 0) { skip |= LogError(buffer_state->buffer(), "VUID-vkCmdEndTransformFeedbackEXT-pCounterBuffers-02380", "%s: pCounterBuffers[%" PRIu32 "] (%s) was not created with the VK_BUFFER_USAGE_TRANSFORM_FEEDBACK_COUNTER_BUFFER_BIT_EXT flag.", cmd_name, i, report_data->FormatHandle(pCounterBuffers[i]).c_str()); } } } } return skip; } bool CoreChecks::PreCallValidateCmdSetLogicOpEXT(VkCommandBuffer commandBuffer, VkLogicOp logicOp) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); bool skip = false; skip |= ValidateCmd(cb_state, CMD_SETLOGICOPEXT, "vkCmdSetLogicOpEXT()"); if (!enabled_features.extended_dynamic_state2_features.extendedDynamicState2LogicOp) { skip |= LogError(commandBuffer, "VUID-vkCmdSetLogicOpEXT-None-04867", "vkCmdSetLogicOpEXT: extendedDynamicState feature is not enabled."); } return skip; } bool CoreChecks::PreCallValidateCmdSetPatchControlPointsEXT(VkCommandBuffer commandBuffer, uint32_t patchControlPoints) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); bool skip = false; skip |= ValidateCmd(cb_state, CMD_SETPATCHCONTROLPOINTSEXT, "vkCmdSetPatchControlPointsEXT()"); if (!enabled_features.extended_dynamic_state2_features.extendedDynamicState2PatchControlPoints) { skip |= LogError(commandBuffer, "VUID-vkCmdSetPatchControlPointsEXT-None-04873", "vkCmdSetPatchControlPointsEXT: extendedDynamicState feature is not enabled."); } if (patchControlPoints > phys_dev_props.limits.maxTessellationPatchSize) { skip |= LogError(commandBuffer, "VUID-vkCmdSetPatchControlPointsEXT-patchControlPoints-04874", "vkCmdSetPatchControlPointsEXT: The value of patchControlPoints must be less than " "VkPhysicalDeviceLimits::maxTessellationPatchSize"); } return skip; } bool CoreChecks::PreCallValidateCmdSetRasterizerDiscardEnableEXT(VkCommandBuffer commandBuffer, VkBool32 rasterizerDiscardEnable) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); bool skip = false; skip |= ValidateCmd(cb_state, CMD_SETRASTERIZERDISCARDENABLEEXT, "vkCmdSetRasterizerDiscardEnableEXT()"); if (!enabled_features.extended_dynamic_state2_features.extendedDynamicState2) { skip |= LogError(commandBuffer, "VUID-vkCmdSetRasterizerDiscardEnableEXT-None-04871", "vkCmdSetRasterizerDiscardEnableEXT: extendedDynamicState feature is not enabled."); } return skip; } bool CoreChecks::PreCallValidateCmdSetDepthBiasEnableEXT(VkCommandBuffer commandBuffer, VkBool32 depthBiasEnable) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); bool skip = false; skip |= ValidateCmd(cb_state, CMD_SETDEPTHBIASENABLEEXT, "vkCmdSetDepthBiasEnableEXT()"); if (!enabled_features.extended_dynamic_state2_features.extendedDynamicState2) { skip |= LogError(commandBuffer, "VUID-vkCmdSetDepthBiasEnableEXT-None-04872", "vkCmdSetDepthBiasEnableEXT: extendedDynamicState feature is not enabled."); } return skip; } bool CoreChecks::PreCallValidateCmdSetPrimitiveRestartEnableEXT(VkCommandBuffer commandBuffer, VkBool32 primitiveRestartEnable) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); bool skip = false; skip |= ValidateCmd(cb_state, CMD_SETPRIMITIVERESTARTENABLEEXT, "vkCmdSetPrimitiveRestartEnableEXT()"); if (!enabled_features.extended_dynamic_state2_features.extendedDynamicState2) { skip |= LogError(commandBuffer, "VUID-vkCmdSetPrimitiveRestartEnableEXT-None-04866", "vkCmdSetPrimitiveRestartEnableEXT: extendedDynamicState feature is not enabled."); } return skip; } bool CoreChecks::PreCallValidateCmdSetCullModeEXT(VkCommandBuffer commandBuffer, VkCullModeFlags cullMode) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); bool skip = false; skip |= ValidateCmd(cb_state, CMD_SETCULLMODEEXT, "vkCmdSetCullModeEXT()"); if (!enabled_features.extended_dynamic_state_features.extendedDynamicState) { skip |= LogError(commandBuffer, "VUID-vkCmdSetCullModeEXT-None-03384", "vkCmdSetCullModeEXT: extendedDynamicState feature is not enabled."); } return skip; } bool CoreChecks::PreCallValidateCmdSetFrontFaceEXT(VkCommandBuffer commandBuffer, VkFrontFace frontFace) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); bool skip = false; skip |= ValidateCmd(cb_state, CMD_SETFRONTFACEEXT, "vkCmdSetFrontFaceEXT()"); if (!enabled_features.extended_dynamic_state_features.extendedDynamicState) { skip |= LogError(commandBuffer, "VUID-vkCmdSetFrontFaceEXT-None-03383", "vkCmdSetFrontFaceEXT: extendedDynamicState feature is not enabled."); } return skip; } bool CoreChecks::PreCallValidateCmdSetPrimitiveTopologyEXT(VkCommandBuffer commandBuffer, VkPrimitiveTopology primitiveTopology) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); bool skip = false; skip |= ValidateCmd(cb_state, CMD_SETPRIMITIVETOPOLOGYEXT, "vkCmdSetPrimitiveTopologyEXT()"); if (!enabled_features.extended_dynamic_state_features.extendedDynamicState) { skip |= LogError(commandBuffer, "VUID-vkCmdSetPrimitiveTopologyEXT-None-03347", "vkCmdSetPrimitiveTopologyEXT: extendedDynamicState feature is not enabled."); } return skip; } bool CoreChecks::PreCallValidateCmdSetViewportWithCountEXT(VkCommandBuffer commandBuffer, uint32_t viewportCount, const VkViewport *pViewports) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); bool skip = false; skip |= ValidateCmd(cb_state, CMD_SETVIEWPORTWITHCOUNTEXT, "vkCmdSetViewportWithCountEXT()"); if (!enabled_features.extended_dynamic_state_features.extendedDynamicState) { skip |= LogError(commandBuffer, "VUID-vkCmdSetViewportWithCountEXT-None-03393", "vkCmdSetViewportWithCountEXT: extendedDynamicState feature is not enabled."); } skip |= ForbidInheritedViewportScissor(commandBuffer, cb_state, "VUID-vkCmdSetViewportWithCountEXT-commandBuffer-04819", "vkCmdSetViewportWithCountEXT"); return skip; } bool CoreChecks::PreCallValidateCmdSetScissorWithCountEXT(VkCommandBuffer commandBuffer, uint32_t scissorCount, const VkRect2D *pScissors) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); bool skip = false; skip |= ValidateCmd(cb_state, CMD_SETSCISSORWITHCOUNTEXT, "vkCmdSetScissorWithCountEXT()"); if (!enabled_features.extended_dynamic_state_features.extendedDynamicState) { skip |= LogError(commandBuffer, "VUID-vkCmdSetScissorWithCountEXT-None-03396", "vkCmdSetScissorWithCountEXT: extendedDynamicState feature is not enabled."); } skip |= ForbidInheritedViewportScissor(commandBuffer, cb_state, "VUID-vkCmdSetScissorWithCountEXT-commandBuffer-04820", "vkCmdSetScissorWithCountEXT"); return skip; } bool CoreChecks::PreCallValidateCmdBindVertexBuffers2EXT(VkCommandBuffer commandBuffer, uint32_t firstBinding, uint32_t bindingCount, const VkBuffer *pBuffers, const VkDeviceSize *pOffsets, const VkDeviceSize *pSizes, const VkDeviceSize *pStrides) const { const auto cb_state = GetCBState(commandBuffer); assert(cb_state); bool skip = false; skip |= ValidateCmd(cb_state, CMD_BINDVERTEXBUFFERS2EXT, "vkCmdBindVertexBuffers2EXT()"); for (uint32_t i = 0; i < bindingCount; ++i) { const auto buffer_state = GetBufferState(pBuffers[i]); if (buffer_state) { skip |= ValidateBufferUsageFlags(buffer_state, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, true, "VUID-vkCmdBindVertexBuffers2EXT-pBuffers-03359", "vkCmdBindVertexBuffers2EXT()", "VK_BUFFER_USAGE_VERTEX_BUFFER_BIT"); skip |= ValidateMemoryIsBoundToBuffer(buffer_state, "vkCmdBindVertexBuffers2EXT()", "VUID-vkCmdBindVertexBuffers2EXT-pBuffers-03360"); if (pOffsets[i] >= buffer_state->createInfo.size) { skip |= LogError(buffer_state->buffer(), "VUID-vkCmdBindVertexBuffers2EXT-pOffsets-03357", "vkCmdBindVertexBuffers2EXT() offset (0x%" PRIxLEAST64 ") is beyond the end of the buffer.", pOffsets[i]); } if (pSizes && pOffsets[i] + pSizes[i] > buffer_state->createInfo.size) { skip |= LogError(buffer_state->buffer(), "VUID-vkCmdBindVertexBuffers2EXT-pSizes-03358", "vkCmdBindVertexBuffers2EXT() size (0x%" PRIxLEAST64 ") is beyond the end of the buffer.", pSizes[i]); } } } return skip; } bool CoreChecks::PreCallValidateCmdSetDepthTestEnableEXT(VkCommandBuffer commandBuffer, VkBool32 depthTestEnable) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); bool skip = false; skip |= ValidateCmd(cb_state, CMD_SETDEPTHTESTENABLEEXT, "vkCmdSetDepthTestEnableEXT()"); if (!enabled_features.extended_dynamic_state_features.extendedDynamicState) { skip |= LogError(commandBuffer, "VUID-vkCmdSetDepthTestEnableEXT-None-03352", "vkCmdSetDepthTestEnableEXT: extendedDynamicState feature is not enabled."); } return skip; } bool CoreChecks::PreCallValidateCmdSetDepthWriteEnableEXT(VkCommandBuffer commandBuffer, VkBool32 depthWriteEnable) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); bool skip = false; skip |= ValidateCmd(cb_state, CMD_SETDEPTHWRITEENABLEEXT, "vkCmdSetDepthWriteEnableEXT()"); if (!enabled_features.extended_dynamic_state_features.extendedDynamicState) { skip |= LogError(commandBuffer, "VUID-vkCmdSetDepthWriteEnableEXT-None-03354", "vkCmdSetDepthWriteEnableEXT: extendedDynamicState feature is not enabled."); } return skip; } bool CoreChecks::PreCallValidateCmdSetDepthCompareOpEXT(VkCommandBuffer commandBuffer, VkCompareOp depthCompareOp) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); bool skip = false; skip |= ValidateCmd(cb_state, CMD_SETDEPTHCOMPAREOPEXT, "vkCmdSetDepthCompareOpEXT()"); if (!enabled_features.extended_dynamic_state_features.extendedDynamicState) { skip |= LogError(commandBuffer, "VUID-vkCmdSetDepthCompareOpEXT-None-03353", "vkCmdSetDepthCompareOpEXT: extendedDynamicState feature is not enabled."); } return skip; } bool CoreChecks::PreCallValidateCmdSetDepthBoundsTestEnableEXT(VkCommandBuffer commandBuffer, VkBool32 depthBoundsTestEnable) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); bool skip = false; skip |= ValidateCmd(cb_state, CMD_SETDEPTHBOUNDSTESTENABLEEXT, "vkCmdSetDepthBoundsTestEnableEXT()"); if (!enabled_features.extended_dynamic_state_features.extendedDynamicState) { skip |= LogError(commandBuffer, "VUID-vkCmdSetDepthBoundsTestEnableEXT-None-03349", "vkCmdSetDepthBoundsTestEnableEXT: extendedDynamicState feature is not enabled."); } return skip; } bool CoreChecks::PreCallValidateCmdSetStencilTestEnableEXT(VkCommandBuffer commandBuffer, VkBool32 stencilTestEnable) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); bool skip = false; skip |= ValidateCmd(cb_state, CMD_SETSTENCILTESTENABLEEXT, "vkCmdSetStencilTestEnableEXT()"); if (!enabled_features.extended_dynamic_state_features.extendedDynamicState) { skip |= LogError(commandBuffer, "VUID-vkCmdSetStencilTestEnableEXT-None-03350", "vkCmdSetStencilTestEnableEXT: extendedDynamicState feature is not enabled."); } return skip; } bool CoreChecks::PreCallValidateCmdSetStencilOpEXT(VkCommandBuffer commandBuffer, VkStencilFaceFlags faceMask, VkStencilOp failOp, VkStencilOp passOp, VkStencilOp depthFailOp, VkCompareOp compareOp) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); bool skip = false; skip |= ValidateCmd(cb_state, CMD_SETSTENCILOPEXT, "vkCmdSetStencilOpEXT()"); if (!enabled_features.extended_dynamic_state_features.extendedDynamicState) { skip |= LogError(commandBuffer, "VUID-vkCmdSetStencilOpEXT-None-03351", "vkCmdSetStencilOpEXT: extendedDynamicState feature is not enabled."); } return skip; } bool CoreChecks::PreCallValidateCreateEvent(VkDevice device, const VkEventCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkEvent *pEvent) const { bool skip = false; if (device_extensions.vk_khr_portability_subset != ExtEnabled::kNotEnabled) { if (VK_FALSE == enabled_features.portability_subset_features.events) { skip |= LogError(device, "VUID-vkCreateEvent-events-04468", "vkCreateEvent: events are not supported via VK_KHR_portability_subset"); } } return skip; } bool CoreChecks::PreCallValidateCmdSetRayTracingPipelineStackSizeKHR(VkCommandBuffer commandBuffer, uint32_t pipelineStackSize) const { bool skip = false; const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); skip |= ValidateCmd(cb_state, CMD_SETRAYTRACINGPIPELINESTACKSIZEKHR, "vkCmdSetRayTracingPipelineStackSizeKHR()"); return skip; } bool CoreChecks::PreCallValidateGetRayTracingShaderGroupStackSizeKHR(VkDevice device, VkPipeline pipeline, uint32_t group, VkShaderGroupShaderKHR groupShader) const { bool skip = false; const PIPELINE_STATE *pipeline_state = GetPipelineState(pipeline); if (group >= pipeline_state->raytracingPipelineCI.groupCount) { skip |= LogError(device, "VUID-vkGetRayTracingShaderGroupStackSizeKHR-group-03608", "vkGetRayTracingShaderGroupStackSizeKHR: The value of group must be less than the number of shader groups " "in pipeline."); } return skip; } bool CoreChecks::PreCallValidateCmdSetFragmentShadingRateKHR(VkCommandBuffer commandBuffer, const VkExtent2D *pFragmentSize, const VkFragmentShadingRateCombinerOpKHR combinerOps[2]) const { const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); assert(cb_state); const char *cmd_name = "vkCmdSetFragmentShadingRateKHR()"; bool skip = false; skip |= ValidateCmd(cb_state, CMD_SETFRAGMENTSHADINGRATEKHR, cmd_name); if (!enabled_features.fragment_shading_rate_features.pipelineFragmentShadingRate && !enabled_features.fragment_shading_rate_features.primitiveFragmentShadingRate && !enabled_features.fragment_shading_rate_features.attachmentFragmentShadingRate) { skip |= LogError( cb_state->commandBuffer(), "VUID-vkCmdSetFragmentShadingRateKHR-pipelineFragmentShadingRate-04509", "vkCmdSetFragmentShadingRateKHR: Application called %s, but no fragment shading rate features have been enabled.", cmd_name); } if (!enabled_features.fragment_shading_rate_features.pipelineFragmentShadingRate && pFragmentSize->width != 1) { skip |= LogError(cb_state->commandBuffer(), "VUID-vkCmdSetFragmentShadingRateKHR-pipelineFragmentShadingRate-04507", "vkCmdSetFragmentShadingRateKHR: Pipeline fragment width of %u has been specified in %s, but " "pipelineFragmentShadingRate is not enabled", pFragmentSize->width, cmd_name); } if (!enabled_features.fragment_shading_rate_features.pipelineFragmentShadingRate && pFragmentSize->height != 1) { skip |= LogError(cb_state->commandBuffer(), "VUID-vkCmdSetFragmentShadingRateKHR-pipelineFragmentShadingRate-04508", "vkCmdSetFragmentShadingRateKHR: Pipeline fragment height of %u has been specified in %s, but " "pipelineFragmentShadingRate is not enabled", pFragmentSize->height, cmd_name); } if (!enabled_features.fragment_shading_rate_features.primitiveFragmentShadingRate && combinerOps[0] != VK_FRAGMENT_SHADING_RATE_COMBINER_OP_KEEP_KHR) { skip |= LogError(cb_state->commandBuffer(), "VUID-vkCmdSetFragmentShadingRateKHR-primitiveFragmentShadingRate-04510", "vkCmdSetFragmentShadingRateKHR: First combiner operation of %s has been specified in %s, but " "primitiveFragmentShadingRate is not enabled", string_VkFragmentShadingRateCombinerOpKHR(combinerOps[0]), cmd_name); } if (!enabled_features.fragment_shading_rate_features.attachmentFragmentShadingRate && combinerOps[1] != VK_FRAGMENT_SHADING_RATE_COMBINER_OP_KEEP_KHR) { skip |= LogError(cb_state->commandBuffer(), "VUID-vkCmdSetFragmentShadingRateKHR-attachmentFragmentShadingRate-04511", "vkCmdSetFragmentShadingRateKHR: Second combiner operation of %s has been specified in %s, but " "attachmentFragmentShadingRate is not enabled", string_VkFragmentShadingRateCombinerOpKHR(combinerOps[1]), cmd_name); } if (!phys_dev_ext_props.fragment_shading_rate_props.fragmentShadingRateNonTrivialCombinerOps && (combinerOps[0] != VK_FRAGMENT_SHADING_RATE_COMBINER_OP_KEEP_KHR && combinerOps[0] != VK_FRAGMENT_SHADING_RATE_COMBINER_OP_REPLACE_KHR)) { skip |= LogError(cb_state->commandBuffer(), "VUID-vkCmdSetFragmentShadingRateKHR-fragmentSizeNonTrivialCombinerOps-04512", "vkCmdSetFragmentShadingRateKHR: First combiner operation of %s has been specified in %s, but " "fragmentShadingRateNonTrivialCombinerOps is " "not supported", string_VkFragmentShadingRateCombinerOpKHR(combinerOps[0]), cmd_name); } if (!phys_dev_ext_props.fragment_shading_rate_props.fragmentShadingRateNonTrivialCombinerOps && (combinerOps[1] != VK_FRAGMENT_SHADING_RATE_COMBINER_OP_KEEP_KHR && combinerOps[1] != VK_FRAGMENT_SHADING_RATE_COMBINER_OP_REPLACE_KHR)) { skip |= LogError(cb_state->commandBuffer(), "VUID-vkCmdSetFragmentShadingRateKHR-fragmentSizeNonTrivialCombinerOps-04512", "vkCmdSetFragmentShadingRateKHR: Second combiner operation of %s has been specified in %s, but " "fragmentShadingRateNonTrivialCombinerOps " "is not supported", string_VkFragmentShadingRateCombinerOpKHR(combinerOps[1]), cmd_name); } if (pFragmentSize->width == 0) { skip |= LogError(cb_state->commandBuffer(), "VUID-vkCmdSetFragmentShadingRateKHR-pFragmentSize-04513", "vkCmdSetFragmentShadingRateKHR: Fragment width of %u has been specified in %s.", pFragmentSize->width, cmd_name); } if (pFragmentSize->height == 0) { skip |= LogError(cb_state->commandBuffer(), "VUID-vkCmdSetFragmentShadingRateKHR-pFragmentSize-04514", "vkCmdSetFragmentShadingRateKHR: Fragment height of %u has been specified in %s.", pFragmentSize->height, cmd_name); } if (pFragmentSize->width != 0 && !IsPowerOfTwo(pFragmentSize->width)) { skip |= LogError(cb_state->commandBuffer(), "VUID-vkCmdSetFragmentShadingRateKHR-pFragmentSize-04515", "vkCmdSetFragmentShadingRateKHR: Non-power-of-two fragment width of %u has been specified in %s.", pFragmentSize->width, cmd_name); } if (pFragmentSize->height != 0 && !IsPowerOfTwo(pFragmentSize->height)) { skip |= LogError(cb_state->commandBuffer(), "VUID-vkCmdSetFragmentShadingRateKHR-pFragmentSize-04516", "vkCmdSetFragmentShadingRateKHR: Non-power-of-two fragment height of %u has been specified in %s.", pFragmentSize->height, cmd_name); } if (pFragmentSize->width > 4) { skip |= LogError(cb_state->commandBuffer(), "VUID-vkCmdSetFragmentShadingRateKHR-pFragmentSize-04517", "vkCmdSetFragmentShadingRateKHR: Fragment width of %u specified in %s is too large.", pFragmentSize->width, cmd_name); } if (pFragmentSize->height > 4) { skip |= LogError(cb_state->commandBuffer(), "VUID-vkCmdSetFragmentShadingRateKHR-pFragmentSize-04518", "vkCmdSetFragmentShadingRateKHR: Fragment height of %u specified in %s is too large", pFragmentSize->height, cmd_name); } return skip; } bool CoreChecks::PreCallValidateCmdSetColorWriteEnableEXT(VkCommandBuffer commandBuffer, uint32_t attachmentCount, const VkBool32 *pColorWriteEnables) const { bool skip = false; const CMD_BUFFER_STATE *cb_state = GetCBState(commandBuffer); if (!enabled_features.color_write_features.colorWriteEnable) { skip |= LogError(commandBuffer, "VUID-vkCmdSetColorWriteEnableEXT-None-04803", "vkCmdSetColorWriteEnableEXT: color write is not enabled."); } auto graphics_pipeline = cb_state->GetCurrentPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS); if (graphics_pipeline) { uint32_t pipeline_attachment_count = graphics_pipeline->graphicsPipelineCI.pColorBlendState->attachmentCount; if (attachmentCount != pipeline_attachment_count) { skip |= LogError( commandBuffer, "VUID-vkCmdSetColorWriteEnableEXT-attachmentCount-04804", "vkCmdSetColorWriteEnableEXT: attachment count (%" PRIu32 ") is not equal to currenly bound pipelines VkPipelineColorBlendStateCreateInfo::attachmentCount (%" PRIu32 ").", attachmentCount, pipeline_attachment_count); } } return skip; }
1
18,845
> subpass uses a depth/stencil attachment in renderPass with a read-only layout for the depth aspect Assume - VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL - VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_OPTIMAL count as well seems there is a `NormalizeDepthImageLayout` for this
KhronosGroup-Vulkan-ValidationLayers
cpp
@@ -49,14 +49,14 @@ export function registerDefaults( widgetsAPI ) { widgetsAPI.registerWidgetArea( AREA_DASHBOARD_ALL_TRAFFIC, { title: __( 'All Traffic', 'google-site-kit' ), subtitle: __( 'How people found your site.', 'google-site-kit' ), - style: WIDGET_AREA_STYLES.COMPOSITE, + style: WIDGET_AREA_STYLES.BOXES, priority: 1, }, CONTEXT_DASHBOARD ); widgetsAPI.registerWidgetArea( AREA_DASHBOARD_SEARCH_FUNNEL, { title: __( 'Search Funnel', 'google-site-kit' ), subtitle: __( 'How your site appeared in Search results and how many visitors you got from Search.', 'google-site-kit' ), - style: WIDGET_AREA_STYLES.COMPOSITE, + style: WIDGET_AREA_STYLES.BOXES, priority: 2, }, CONTEXT_DASHBOARD );
1
/** * Widgets API defaults * * Site Kit by Google, Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * WordPress dependencies */ import { __ } from '@wordpress/i18n'; /** * Internal dependencies */ import { CONTEXT_DASHBOARD, CONTEXT_PAGE_DASHBOARD } from './default-contexts'; import { AREA_DASHBOARD_ALL_TRAFFIC, AREA_DASHBOARD_SEARCH_FUNNEL, AREA_DASHBOARD_POPULARITY, AREA_DASHBOARD_SPEED, AREA_DASHBOARD_EARNINGS, AREA_PAGE_DASHBOARD_SEARCH_FUNNEL, AREA_PAGE_DASHBOARD_ALL_TRAFFIC, AREA_PAGE_DASHBOARD_TOP_QUERIES, AREA_PAGE_DASHBOARD_SPEED, } from './default-areas'; import { WIDGET_AREA_STYLES } from './datastore/constants'; /** * Defines default widget areas for a given context. * * @since 1.12.0 * * @param {Object} widgetsAPI Widgets API. */ export function registerDefaults( widgetsAPI ) { widgetsAPI.registerWidgetArea( AREA_DASHBOARD_ALL_TRAFFIC, { title: __( 'All Traffic', 'google-site-kit' ), subtitle: __( 'How people found your site.', 'google-site-kit' ), style: WIDGET_AREA_STYLES.COMPOSITE, priority: 1, }, CONTEXT_DASHBOARD ); widgetsAPI.registerWidgetArea( AREA_DASHBOARD_SEARCH_FUNNEL, { title: __( 'Search Funnel', 'google-site-kit' ), subtitle: __( 'How your site appeared in Search results and how many visitors you got from Search.', 'google-site-kit' ), style: WIDGET_AREA_STYLES.COMPOSITE, priority: 2, }, CONTEXT_DASHBOARD ); widgetsAPI.registerWidgetArea( AREA_DASHBOARD_POPULARITY, { title: __( 'Popularity', 'google-site-kit' ), subtitle: __( 'Your most popular pages and how people found them from Search.', 'google-site-kit' ), style: WIDGET_AREA_STYLES.BOXES, priority: 3, }, CONTEXT_DASHBOARD ); widgetsAPI.registerWidgetArea( AREA_DASHBOARD_SPEED, { title: __( 'Page Speed and Experience', 'google-site-kit' ), subtitle: __( 'How fast your home page loads, how quickly people can interact with your content, and how stable your content is.', 'google-site-kit' ), style: WIDGET_AREA_STYLES.BOXES, priority: 4, }, CONTEXT_DASHBOARD ); widgetsAPI.registerWidgetArea( AREA_DASHBOARD_EARNINGS, { title: __( 'Earnings', 'google-site-kit' ), subtitle: __( 'How much you’re earning from your content through AdSense.', 'google-site-kit' ), style: WIDGET_AREA_STYLES.BOXES, priority: 5, }, CONTEXT_DASHBOARD ); widgetsAPI.registerWidgetArea( AREA_PAGE_DASHBOARD_SEARCH_FUNNEL, { title: __( 'Search Funnel', 'google-site-kit' ), subtitle: __( 'How your site appeared in Search results and how many visitors you got from Search.', 'google-site-kit' ), style: WIDGET_AREA_STYLES.COMPOSITE, priority: 1, }, CONTEXT_PAGE_DASHBOARD ); widgetsAPI.registerWidgetArea( AREA_PAGE_DASHBOARD_ALL_TRAFFIC, { title: __( 'All Traffic', 'google-site-kit' ), subtitle: __( 'How people found your page.', 'google-site-kit' ), style: WIDGET_AREA_STYLES.COMPOSITE, priority: 2, }, CONTEXT_PAGE_DASHBOARD ); widgetsAPI.registerWidgetArea( AREA_PAGE_DASHBOARD_TOP_QUERIES, { title: __( 'Top Queries', 'google-site-kit' ), subtitle: __( 'What people searched for to find your page.', 'google-site-kit' ), style: WIDGET_AREA_STYLES.BOXES, priority: 3, }, CONTEXT_PAGE_DASHBOARD ); widgetsAPI.registerWidgetArea( AREA_PAGE_DASHBOARD_SPEED, { title: __( 'Page Speed and Experience', 'google-site-kit' ), subtitle: __( 'How fast your page loads, how quickly people can interact with your content, and how stable your content is.', 'google-site-kit' ), style: WIDGET_AREA_STYLES.BOXES, priority: 4, }, CONTEXT_PAGE_DASHBOARD ); }
1
31,614
This shouldn't be altered, you probably meant to update `AREA_PAGE_DASHBOARD_ALL_TRAFFIC` further below :)
google-site-kit-wp
js
@@ -882,7 +882,7 @@ class CmdDockerClient(ContainerClient): if mount_volumes: cmd += [ volume - for host_path, docker_path in mount_volumes + for host_path, docker_path in dict(mount_volumes).items() for volume in ["-v", f"{host_path}:{docker_path}"] ] if interactive:
1
import dataclasses import io import json import logging import os import queue import re import shlex import socket import subprocess import tarfile import tempfile import threading from abc import ABCMeta, abstractmethod from enum import Enum, unique from pathlib import Path from typing import Dict, List, Optional, Tuple, Union import docker from docker import DockerClient from docker.errors import APIError, ContainerError, DockerException, ImageNotFound, NotFound from docker.models.containers import Container from docker.utils.socket import STDERR, STDOUT, frames_iter from localstack import config from localstack.utils.common import ( TMP_FILES, HashableList, rm_rf, safe_run, save_file, short_uid, start_worker_thread, to_bytes, ) from localstack.utils.run import to_str LOG = logging.getLogger(__name__) SDK_ISDIR = 1 << 31 @unique class DockerContainerStatus(Enum): DOWN = -1 NON_EXISTENT = 0 UP = 1 class ContainerException(Exception): def __init__(self, message=None, stdout=None, stderr=None) -> None: self.message = message or "Error during the communication with the docker daemon" self.stdout = stdout self.stderr = stderr class NoSuchObject(ContainerException): def __init__(self, object_id: str, message=None, stdout=None, stderr=None) -> None: message = message or f"Docker object {object_id} not found" super().__init__(message, stdout, stderr) self.object_id = object_id class NoSuchContainer(ContainerException): def __init__(self, container_name_or_id: str, message=None, stdout=None, stderr=None) -> None: message = message or f"Docker container {container_name_or_id} not found" super().__init__(message, stdout, stderr) self.container_name_or_id = container_name_or_id class NoSuchImage(ContainerException): def __init__(self, image_name: str, message=None, stdout=None, stderr=None) -> None: message = message or f"Docker image {image_name} not found" super().__init__(message, stdout, stderr) self.image_name = image_name class NoSuchNetwork(ContainerException): def __init__(self, network_name: str, message=None, stdout=None, stderr=None) -> None: message = message or f"Docker network {network_name} not found" super().__init__(message, stdout, stderr) self.network_name = network_name class PortMappings(object): """Maps source to target port ranges for Docker port mappings.""" def __init__(self, bind_host=None): self.bind_host = bind_host if bind_host else "" self.mappings = {} def add(self, port, mapped=None, protocol="tcp"): mapped = mapped or port if isinstance(port, list): for i in range(port[1] - port[0] + 1): if isinstance(mapped, list): self.add(port[0] + i, mapped[0] + i) else: self.add(port[0] + i, mapped) return if port is None or int(port) <= 0: raise Exception("Unable to add mapping for invalid port: %s" % port) if self.contains(port): return bisected_host_port = None for from_range, to_range in self.mappings.items(): if not self.in_expanded_range(port, from_range): continue if not self.in_expanded_range(mapped, to_range): continue from_range_len = from_range[1] - from_range[0] to_range_len = to_range[1] - to_range[0] is_uniform = from_range_len == to_range_len if is_uniform: self.expand_range(port, from_range) self.expand_range(mapped, to_range) else: if not self.in_range(mapped, to_range): continue # extending a 1 to 1 mapping to be many to 1 elif from_range_len == 1: self.expand_range(port, from_range) # splitting a uniform mapping else: bisected_port_index = mapped - to_range[0] bisected_host_port = from_range[0] + bisected_port_index self.bisect_range(mapped, to_range) self.bisect_range(bisected_host_port, from_range) break return protocol = str(protocol or "tcp").lower() if bisected_host_port is None: port_range = [port, port, protocol] elif bisected_host_port < port: port_range = [bisected_host_port, port, protocol] else: port_range = [port, bisected_host_port, protocol] self.mappings[HashableList(port_range)] = [mapped, mapped] def to_str(self) -> str: bind_address = f"{self.bind_host}:" if self.bind_host else "" def entry(k, v): protocol = "/%s" % k[2] if k[2] != "tcp" else "" if k[0] == k[1] and v[0] == v[1]: return "-p %s%s:%s%s" % (bind_address, k[0], v[0], protocol) if k[0] != k[1] and v[0] == v[1]: return "-p %s%s-%s:%s%s" % (bind_address, k[0], k[1], v[0], protocol) return "-p %s%s-%s:%s-%s%s" % (bind_address, k[0], k[1], v[0], v[1], protocol) return " ".join([entry(k, v) for k, v in self.mappings.items()]) def to_list(self) -> List[str]: # TODO test bind_address = f"{self.bind_host}:" if self.bind_host else "" def entry(k, v): protocol = "/%s" % k[2] if k[2] != "tcp" else "" if k[0] == k[1] and v[0] == v[1]: return ["-p", f"{bind_address}{k[0]}:{v[0]}{protocol}"] return ["-p", f"{bind_address}{k[0]}-{k[1]}:{v[0]}-{v[1]}{protocol}"] return [item for k, v in self.mappings.items() for item in entry(k, v)] def to_dict(self) -> Dict[str, Union[Tuple[str, Union[int, List[int]]], int]]: bind_address = self.bind_host or "" def entry(k, v): protocol = "/%s" % k[2] if k[0] != k[1] and v[0] == v[1]: container_port = v[0] host_ports = list(range(k[0], k[1] + 1)) return [ ( f"{container_port}{protocol}", (bind_address, host_ports) if bind_address else host_ports, ) ] return [ ( f"{container_port}{protocol}", (bind_address, host_port) if bind_address else host_port, ) for container_port, host_port in zip(range(v[0], v[1] + 1), range(k[0], k[1] + 1)) ] items = [item for k, v in self.mappings.items() for item in entry(k, v)] return dict(items) def contains(self, port): for from_range, to_range in self.mappings.items(): if self.in_range(port, from_range): return True def in_range(self, port, range): return port >= range[0] and port <= range[1] def in_expanded_range(self, port, range): return port >= range[0] - 1 and port <= range[1] + 1 def expand_range(self, port, range): if self.in_range(port, range): return if port == range[0] - 1: range[0] = port elif port == range[1] + 1: range[1] = port else: raise Exception("Unable to add port %s to existing range %s" % (port, range)) """Bisect a port range, at the provided port This is needed in some cases when adding a non-uniform host to port mapping adjacent to an existing port range """ def bisect_range(self, port, range): if not self.in_range(port, range): return if port == range[0]: range[0] = port + 1 else: range[1] = port - 1 SimpleVolumeBind = Tuple[str, str] """Type alias for a simple version of VolumeBind""" @dataclasses.dataclass class VolumeBind: """Represents a --volume argument run/create command. When using VolumeBind to bind-mount a file or directory that does not yet exist on the Docker host, -v creates the endpoint for you. It is always created as a directory. """ host_dir: str container_dir: str options: Optional[List[str]] = None def to_str(self) -> str: args = list() if self.host_dir: args.append(self.host_dir) if not self.container_dir: raise ValueError("no container dir specified") args.append(self.container_dir) if self.options: args.append(self.options) return ":".join(args) class VolumeMappings: mappings: List[Union[SimpleVolumeBind, VolumeBind]] def __init__(self, mappings: List[Union[SimpleVolumeBind, VolumeBind]] = None): self.mappings = mappings if mappings is not None else list() def add(self, mapping: Union[SimpleVolumeBind, VolumeBind]): self.append(mapping) def append( self, mapping: Union[ SimpleVolumeBind, VolumeBind, ], ): self.mappings.append(mapping) def __iter__(self): return self.mappings.__iter__() class ContainerClient(metaclass=ABCMeta): STOP_TIMEOUT = 0 @abstractmethod def get_container_status(self, container_name: str) -> DockerContainerStatus: """Returns the status of the container with the given name""" pass @abstractmethod def get_network(self, container_name: str) -> str: """Returns the network mode of the container with the given name""" pass @abstractmethod def stop_container(self, container_name: str, timeout: int = None): """Stops container with given name :param container_name: Container identifier (name or id) of the container to be stopped :param timeout: Timeout after which SIGKILL is sent to the container. If not specified, defaults to `STOP_TIMEOUT` """ pass @abstractmethod def remove_container(self, container_name: str, force=True, check_existence=False) -> None: """Removes container with given name""" pass @abstractmethod def list_containers(self, filter: Union[List[str], str, None] = None, all=True) -> List[dict]: """List all containers matching the given filters :return: A list of dicts with keys id, image, name, labels, status """ pass def get_running_container_names(self) -> List[str]: """Returns a list of the names of all running containers""" result = self.list_containers(all=False) result = list(map(lambda container: container["name"], result)) return result def is_container_running(self, container_name: str) -> bool: """Checks whether a container with a given name is currently running""" return container_name in self.get_running_container_names() @abstractmethod def copy_into_container( self, container_name: str, local_path: str, container_path: str ) -> None: """Copy contents of the given local path into the container""" pass @abstractmethod def copy_from_container( self, container_name: str, local_path: str, container_path: str ) -> None: """Copy contents of the given container to the host""" pass @abstractmethod def pull_image(self, docker_image: str) -> None: """Pulls a image with a given name from a docker registry""" pass @abstractmethod def get_docker_image_names(self, strip_latest=True, include_tags=True) -> List[str]: """ Get all names of docker images available to the container engine :param strip_latest: return images both with and without :latest tag :param include_tags: Include tags of the images in the names :return: List of image names """ pass @abstractmethod def get_container_logs(self, container_name_or_id: str, safe=False) -> str: """Get all logs of a given container""" pass @abstractmethod def inspect_container(self, container_name_or_id: str) -> Dict[str, Union[Dict, str]]: """Get detailed attributes of an container. :return: Dict containing docker attributes as returned by the daemon """ pass @abstractmethod def inspect_image(self, image_name: str) -> Dict[str, Union[Dict, str]]: """Get detailed attributes of an image. :return: Dict containing docker attributes as returned by the daemon """ pass @abstractmethod def inspect_network(self, network_name: str) -> Dict[str, Union[Dict, str]]: """Get detailed attributes of an network. :return: Dict containing docker attributes as returned by the daemon """ pass def get_container_name(self, container_id: str) -> str: """Get the name of a container by a given identifier""" return self.inspect_container(container_id)["Name"].lstrip("/") def get_container_id(self, container_name: str) -> str: """Get the id of a container by a given name""" return self.inspect_container(container_name)["Id"] @abstractmethod def get_container_ip(self, container_name_or_id: str) -> str: """Get the IP address of a given container If container has multiple networks, it will return the IP of the first """ pass def get_image_cmd(self, docker_image: str) -> str: """Get the command for the given image""" cmd_list = self.inspect_image(docker_image)["Config"]["Cmd"] or [] return " ".join(cmd_list) def get_image_entrypoint(self, docker_image: str) -> str: """Get the entry point for the given image""" LOG.debug("Getting the entrypoint for image: %s", docker_image) entrypoint_list = self.inspect_image(docker_image)["Config"]["Entrypoint"] or [] return " ".join(entrypoint_list) @abstractmethod def has_docker(self) -> bool: """Check if system has docker available""" pass @abstractmethod def create_container( self, image_name: str, *, name: Optional[str] = None, entrypoint: Optional[str] = None, remove: bool = False, interactive: bool = False, tty: bool = False, detach: bool = False, command: Optional[Union[List[str], str]] = None, mount_volumes: Optional[List[SimpleVolumeBind]] = None, ports: Optional[PortMappings] = None, env_vars: Optional[Dict[str, str]] = None, user: Optional[str] = None, cap_add: Optional[str] = None, network: Optional[str] = None, dns: Optional[str] = None, additional_flags: Optional[str] = None, workdir: Optional[str] = None, ) -> str: """Creates a container with the given image :return: Container ID """ pass @abstractmethod def run_container( self, image_name: str, stdin: bytes = None, *, name: Optional[str] = None, entrypoint: Optional[str] = None, remove: bool = False, interactive: bool = False, tty: bool = False, detach: bool = False, command: Optional[Union[List[str], str]] = None, mount_volumes: Optional[List[SimpleVolumeBind]] = None, ports: Optional[PortMappings] = None, env_vars: Optional[Dict[str, str]] = None, user: Optional[str] = None, cap_add: Optional[str] = None, network: Optional[str] = None, dns: Optional[str] = None, additional_flags: Optional[str] = None, workdir: Optional[str] = None, ) -> Tuple[bytes, bytes]: """Creates and runs a given docker container :return: A tuple (stdout, stderr) """ pass @abstractmethod def exec_in_container( self, container_name_or_id: str, command: Union[List[str], str], interactive: bool = False, detach: bool = False, env_vars: Optional[Dict[str, Optional[str]]] = None, stdin: Optional[bytes] = None, user: Optional[str] = None, ) -> Tuple[bytes, bytes]: """Execute a given command in a container :return: A tuple (stdout, stderr) """ pass @abstractmethod def start_container( self, container_name_or_id: str, stdin: bytes = None, interactive: bool = False, attach: bool = False, flags: Optional[str] = None, ) -> Tuple[bytes, bytes]: """Start a given, already created container :return: A tuple (stdout, stderr) if attach or interactive is set, otherwise a tuple (b"container_name_or_id", b"") """ pass class CmdDockerClient(ContainerClient): """Class for managing docker containers using the command line executable""" default_run_outfile: Optional[str] = None def _docker_cmd(self) -> List[str]: """Return the string to be used for running Docker commands.""" return config.DOCKER_CMD.split() def get_container_status(self, container_name: str) -> DockerContainerStatus: cmd = self._docker_cmd() cmd += [ "ps", "-a", "--filter", f"name={container_name}", "--format", "{{ .Status }} - {{ .Names }}", ] cmd_result = safe_run(cmd) # filter empty / invalid lines from docker ps output cmd_result = next((line for line in cmd_result.splitlines() if container_name in line), "") container_status = cmd_result.strip().lower() if len(container_status) == 0: return DockerContainerStatus.NON_EXISTENT elif container_status.startswith("up "): return DockerContainerStatus.UP else: return DockerContainerStatus.DOWN def get_network(self, container_name: str) -> str: LOG.debug("Getting container network: %s", container_name) cmd = self._docker_cmd() cmd += [ "inspect", container_name, "--format", "{{ .HostConfig.NetworkMode }}", ] try: cmd_result = safe_run(cmd) except subprocess.CalledProcessError as e: if "No such container" in to_str(e.stdout): raise NoSuchContainer(container_name, stdout=e.stdout, stderr=e.stderr) else: raise ContainerException( "Docker process returned with errorcode %s" % e.returncode, e.stdout, e.stderr ) container_network = cmd_result.strip() return container_network def stop_container(self, container_name: str, timeout: int = None) -> None: if timeout is None: timeout = self.STOP_TIMEOUT cmd = self._docker_cmd() cmd += ["stop", "--time", str(timeout), container_name] LOG.debug("Stopping container with cmd %s", cmd) try: safe_run(cmd) except subprocess.CalledProcessError as e: if "No such container" in to_str(e.stdout): raise NoSuchContainer(container_name, stdout=e.stdout, stderr=e.stderr) else: raise ContainerException( "Docker process returned with errorcode %s" % e.returncode, e.stdout, e.stderr ) def remove_container(self, container_name: str, force=True, check_existence=False) -> None: if check_existence and container_name not in self.get_running_container_names(): return cmd = self._docker_cmd() + ["rm"] if force: cmd.append("-f") cmd.append(container_name) LOG.debug("Removing container with cmd %s", cmd) try: safe_run(cmd) except subprocess.CalledProcessError as e: if "No such container" in to_str(e.stdout): raise NoSuchContainer(container_name, stdout=e.stdout, stderr=e.stderr) else: raise ContainerException( "Docker process returned with errorcode %s" % e.returncode, e.stdout, e.stderr ) def list_containers(self, filter: Union[List[str], str, None] = None, all=True) -> List[dict]: filter = [filter] if isinstance(filter, str) else filter cmd = self._docker_cmd() cmd.append("ps") if all: cmd.append("-a") options = [] if filter: options += [y for filter_item in filter for y in ["--filter", filter_item]] cmd += options cmd.append("--format") cmd.append( '{"id":"{{ .ID }}","image":"{{ .Image }}","name":"{{ .Names }}",' '"labels":"{{ .Labels }}","status":"{{ .State }}"}' ) try: cmd_result = safe_run(cmd).strip() except subprocess.CalledProcessError as e: raise ContainerException( "Docker process returned with errorcode %s" % e.returncode, e.stdout, e.stderr ) container_list = [] if cmd_result: container_list = [json.loads(line) for line in cmd_result.splitlines()] return container_list def copy_into_container( self, container_name: str, local_path: str, container_path: str ) -> None: cmd = self._docker_cmd() cmd += ["cp", local_path, f"{container_name}:{container_path}"] LOG.debug("Copying into container with cmd: %s", cmd) try: safe_run(cmd) except subprocess.CalledProcessError as e: if "No such container" in to_str(e.stdout): raise NoSuchContainer(container_name) raise ContainerException( "Docker process returned with errorcode %s" % e.returncode, e.stdout, e.stderr ) def copy_from_container( self, container_name: str, local_path: str, container_path: str ) -> None: cmd = self._docker_cmd() cmd += ["cp", f"{container_name}:{container_path}", local_path] LOG.debug("Copying from container with cmd: %s", cmd) try: safe_run(cmd) except subprocess.CalledProcessError as e: if "No such container" in to_str(e.stdout): raise NoSuchContainer(container_name) raise ContainerException( "Docker process returned with errorcode %s" % e.returncode, e.stdout, e.stderr ) def pull_image(self, docker_image: str) -> None: cmd = self._docker_cmd() cmd += ["pull", docker_image] LOG.debug("Pulling image with cmd: %s", cmd) try: safe_run(cmd) except subprocess.CalledProcessError as e: if "pull access denied" in to_str(e.stdout): raise NoSuchImage(docker_image) raise ContainerException( "Docker process returned with errorcode %s" % e.returncode, e.stdout, e.stderr ) def get_docker_image_names(self, strip_latest=True, include_tags=True): format_string = "{{.Repository}}:{{.Tag}}" if include_tags else "{{.Repository}}" cmd = self._docker_cmd() cmd += ["images", "--format", format_string] try: output = safe_run(cmd) image_names = output.splitlines() if strip_latest: Util.append_without_latest(image_names) return image_names except Exception as e: LOG.info('Unable to list Docker images via "%s": %s' % (cmd, e)) return [] def get_container_logs(self, container_name_or_id: str, safe=False) -> str: cmd = self._docker_cmd() cmd += ["logs", container_name_or_id] try: return safe_run(cmd) except subprocess.CalledProcessError as e: if safe: return "" if "No such container" in to_str(e.stdout): raise NoSuchContainer(container_name_or_id, stdout=e.stdout, stderr=e.stderr) else: raise ContainerException( "Docker process returned with errorcode %s" % e.returncode, e.stdout, e.stderr ) def _inspect_object(self, object_name_or_id: str) -> Dict[str, Union[Dict, str]]: cmd = self._docker_cmd() cmd += ["inspect", "--format", "{{json .}}", object_name_or_id] try: cmd_result = safe_run(cmd) except subprocess.CalledProcessError as e: if "No such object" in to_str(e.stdout): raise NoSuchObject(object_name_or_id, stdout=e.stdout, stderr=e.stderr) else: raise ContainerException( "Docker process returned with errorcode %s" % e.returncode, e.stdout, e.stderr ) image_data = json.loads(cmd_result.strip()) return image_data def inspect_container(self, container_name_or_id: str) -> Dict[str, Union[Dict, str]]: try: return self._inspect_object(container_name_or_id) except NoSuchObject as e: raise NoSuchContainer(container_name_or_id=e.object_id) def inspect_image(self, image_name: str) -> Dict[str, Union[Dict, str]]: try: return self._inspect_object(image_name) except NoSuchObject as e: raise NoSuchImage(image_name=e.object_id) def inspect_network(self, network_name: str) -> Dict[str, Union[Dict, str]]: try: return self._inspect_object(network_name) except NoSuchObject as e: raise NoSuchNetwork(network_name=e.object_id) def get_container_ip(self, container_name_or_id: str) -> str: cmd = self._docker_cmd() cmd += [ "inspect", "--format", "{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}", container_name_or_id, ] try: return safe_run(cmd).strip() except subprocess.CalledProcessError as e: if "No such object" in to_str(e.stdout): raise NoSuchContainer(container_name_or_id, stdout=e.stdout, stderr=e.stderr) else: raise ContainerException( "Docker process returned with errorcode %s" % e.returncode, e.stdout, e.stderr ) def has_docker(self) -> bool: try: safe_run(self._docker_cmd() + ["ps"]) return True except subprocess.CalledProcessError: return False def create_container(self, image_name: str, **kwargs) -> str: cmd, env_file = self._build_run_create_cmd("create", image_name, **kwargs) LOG.debug("Create container with cmd: %s", cmd) try: container_id = safe_run(cmd) # Note: strip off Docker warning messages like "DNS setting (--dns=127.0.0.1) may fail in containers" container_id = container_id.strip().split("\n")[-1] return container_id.strip() except subprocess.CalledProcessError as e: if "Unable to find image" in to_str(e.stdout): raise NoSuchImage(image_name, stdout=e.stdout, stderr=e.stderr) raise ContainerException( "Docker process returned with errorcode %s" % e.returncode, e.stdout, e.stderr ) finally: Util.rm_env_vars_file(env_file) def run_container(self, image_name: str, stdin=None, **kwargs) -> Tuple[bytes, bytes]: cmd, env_file = self._build_run_create_cmd("run", image_name, **kwargs) LOG.debug("Run container with cmd: %s", cmd) result = self._run_async_cmd(cmd, stdin, kwargs.get("name") or "", image_name) Util.rm_env_vars_file(env_file) return result def exec_in_container( self, container_name_or_id: str, command: Union[List[str], str], interactive=False, detach=False, env_vars: Optional[Dict[str, Optional[str]]] = None, stdin: Optional[bytes] = None, user: Optional[str] = None, ) -> Tuple[bytes, bytes]: env_file = None cmd = self._docker_cmd() cmd.append("exec") if interactive: cmd.append("--interactive") if detach: cmd.append("--detach") if user: cmd += ["--user", user] if env_vars: env_flag, env_file = Util.create_env_vars_file_flag(env_vars) cmd += env_flag cmd.append(container_name_or_id) cmd += command if isinstance(command, List) else [command] LOG.debug("Execute in container cmd: %s", cmd) result = self._run_async_cmd(cmd, stdin, container_name_or_id) Util.rm_env_vars_file(env_file) return result def start_container( self, container_name_or_id: str, stdin=None, interactive: bool = False, attach: bool = False, flags: Optional[str] = None, ) -> Tuple[bytes, bytes]: cmd = self._docker_cmd() + ["start"] if flags: cmd.append(flags) if interactive: cmd.append("--interactive") if attach: cmd.append("--attach") cmd.append(container_name_or_id) LOG.debug("Start container with cmd: %s", cmd) return self._run_async_cmd(cmd, stdin, container_name_or_id) def _run_async_cmd( self, cmd: List[str], stdin: bytes, container_name: str, image_name=None ) -> Tuple[bytes, bytes]: kwargs = { "inherit_env": True, "asynchronous": True, "stderr": subprocess.PIPE, "outfile": self.default_run_outfile or subprocess.PIPE, } if stdin: kwargs["stdin"] = True try: process = safe_run(cmd, **kwargs) stdout, stderr = process.communicate(input=stdin) if process.returncode != 0: raise subprocess.CalledProcessError( process.returncode, cmd, stdout, stderr, ) else: return stdout, stderr except subprocess.CalledProcessError as e: stderr_str = to_str(e.stderr) if "Unable to find image" in stderr_str: raise NoSuchImage(image_name or "", stdout=e.stdout, stderr=e.stderr) if "No such container" in stderr_str: raise NoSuchContainer(container_name, stdout=e.stdout, stderr=e.stderr) raise ContainerException( "Docker process returned with errorcode %s" % e.returncode, e.stdout, e.stderr ) def _build_run_create_cmd( self, action: str, image_name: str, *, name: Optional[str] = None, entrypoint: Optional[str] = None, remove: bool = False, interactive: bool = False, tty: bool = False, detach: bool = False, command: Optional[Union[List[str], str]] = None, mount_volumes: Optional[List[SimpleVolumeBind]] = None, ports: Optional[PortMappings] = None, env_vars: Optional[Dict[str, str]] = None, user: Optional[str] = None, cap_add: Optional[str] = None, network: Optional[str] = None, dns: Optional[str] = None, additional_flags: Optional[str] = None, workdir: Optional[str] = None, ) -> Tuple[List[str], str]: env_file = None cmd = self._docker_cmd() + [action] if remove: cmd.append("--rm") if name: cmd += ["--name", name] if entrypoint is not None: # empty string entrypoint can be intentional cmd += ["--entrypoint", entrypoint] if mount_volumes: cmd += [ volume for host_path, docker_path in mount_volumes for volume in ["-v", f"{host_path}:{docker_path}"] ] if interactive: cmd.append("--interactive") if tty: cmd.append("--tty") if detach: cmd.append("--detach") if ports: cmd += ports.to_list() if env_vars: env_flags, env_file = Util.create_env_vars_file_flag(env_vars) cmd += env_flags if user: cmd += ["--user", user] if cap_add: cmd += ["--cap-add", cap_add] if network: cmd += ["--network", network] if dns: cmd += ["--dns", dns] if workdir: cmd += ["--workdir", workdir] if additional_flags: cmd += shlex.split(additional_flags) cmd.append(image_name) if command: cmd += command if isinstance(command, List) else [command] return cmd, env_file class Util: MAX_ENV_ARGS_LENGTH = 20000 @staticmethod def format_env_vars(key: str, value: Optional[str]): if value is None: return key return f"{key}={value}" @classmethod def create_env_vars_file_flag(cls, env_vars: Dict) -> Tuple[List[str], Optional[str]]: if not env_vars: return [], None result = [] env_vars = dict(env_vars) env_file = None if len(str(env_vars)) > cls.MAX_ENV_ARGS_LENGTH: # default ARG_MAX=131072 in Docker - let's create an env var file if the string becomes too long... env_file = cls.mountable_tmp_file() env_content = "" for name, value in dict(env_vars).items(): if len(value) > cls.MAX_ENV_ARGS_LENGTH: # each line in the env file has a max size as well (error "bufio.Scanner: token too long") continue env_vars.pop(name) value = value.replace("\n", "\\") env_content += f"{cls.format_env_vars(name, value)}\n" save_file(env_file, env_content) result += ["--env-file", env_file] env_vars_res = [ item for k, v in env_vars.items() for item in ["-e", cls.format_env_vars(k, v)] ] result += env_vars_res return result, env_file @staticmethod def rm_env_vars_file(env_vars_file) -> None: if env_vars_file: return rm_rf(env_vars_file) @staticmethod def mountable_tmp_file(): f = os.path.join(config.dirs.tmp, short_uid()) TMP_FILES.append(f) return f @staticmethod def append_without_latest(image_names): suffix = ":latest" for image in list(image_names): if image.endswith(suffix): image_names.append(image[: -len(suffix)]) @staticmethod def tar_path(path, target_path, is_dir: bool): f = tempfile.NamedTemporaryFile() with tarfile.open(mode="w", fileobj=f) as t: abs_path = os.path.abspath(path) arcname = ( os.path.basename(path) if is_dir else (os.path.basename(target_path) or os.path.basename(path)) ) t.add(abs_path, arcname=arcname) f.seek(0) return f @staticmethod def untar_to_path(tardata, target_path): target_path = Path(target_path) with tarfile.open(mode="r", fileobj=io.BytesIO(b"".join(b for b in tardata))) as t: if target_path.is_dir(): t.extractall(path=target_path) else: member = t.next() if member: member.name = target_path.name t.extract(member, target_path.parent) else: LOG.debug("File to copy empty, ignoring...") @staticmethod def parse_additional_flags( additional_flags: str, env_vars: Dict[str, str] = None, ports: PortMappings = None, mounts: List[SimpleVolumeBind] = None, network: Optional[str] = None, ) -> Tuple[ Dict[str, str], PortMappings, List[SimpleVolumeBind], Optional[Dict[str, str]], Optional[str], ]: """Parses environment, volume and port flags passed as string :param additional_flags: String which contains the flag definitions :param env_vars: Dict with env vars. Will be modified in place. :param ports: PortMapping object. Will be modified in place. :param mounts: List of mount tuples (host_path, container_path). Will be modified in place. :param network: Existing network name (optional). Warning will be printed if network is overwritten in flags. :return: A tuple containing the env_vars, ports, mount, extra_hosts and network objects. Will return new objects if respective parameters were None and additional flags contained a flag for that object, the same which are passed otherwise. """ cur_state = None extra_hosts = None # TODO Use argparse to simplify this logic for flag in shlex.split(additional_flags): if not cur_state: if flag in ["-v", "--volume"]: cur_state = "volume" elif flag in ["-p", "--publish"]: cur_state = "port" elif flag in ["-e", "--env"]: cur_state = "env" elif flag == "--add-host": cur_state = "add-host" elif flag == "--network": cur_state = "set-network" else: raise NotImplementedError( f"Flag {flag} is currently not supported by this Docker client." ) else: if cur_state == "volume": mounts = mounts if mounts is not None else [] match = re.match( r"(?P<host>[\w\s\\\/:\-.]+?):(?P<container>[\w\s\/\-.]+)(?::(?P<arg>ro|rw|z|Z))?", flag, ) if not match: LOG.warning("Unable to parse volume mount Docker flags: %s", flag) continue host_path = match.group("host") container_path = match.group("container") rw_args = match.group("arg") if rw_args: LOG.info("Volume options like :ro or :rw are currently ignored.") mounts.append((host_path, container_path)) elif cur_state == "port": port_split = flag.split(":") protocol = "tcp" if len(port_split) == 2: host_port, container_port = port_split elif len(port_split) == 3: LOG.warning( "Host part of port mappings are ignored currently in additional flags" ) _, host_port, container_port = port_split else: raise ValueError("Invalid port string provided: %s", flag) host_port_split = host_port.split("-") if len(host_port_split) == 2: host_port = [int(host_port_split[0]), int(host_port_split[1])] elif len(host_port_split) == 1: host_port = int(host_port) else: raise ValueError("Invalid port string provided: %s", flag) if "/" in container_port: container_port, protocol = container_port.split("/") ports = ports if ports is not None else PortMappings() ports.add(host_port, int(container_port), protocol) elif cur_state == "env": lhs, _, rhs = flag.partition("=") env_vars = env_vars if env_vars is not None else {} env_vars[lhs] = rhs elif cur_state == "add-host": extra_hosts = extra_hosts if extra_hosts is not None else {} hosts_split = flag.split(":") extra_hosts[hosts_split[0]] = hosts_split[1] elif cur_state == "set-network": if network: LOG.warning( "Overwriting Docker container network '%s' with new value '%s'", network, flag, ) network = flag cur_state = None return env_vars, ports, mounts, extra_hosts, network @staticmethod def convert_mount_list_to_dict( mount_volumes: List[SimpleVolumeBind], ) -> Dict[str, Dict[str, str]]: """Converts a List of (host_path, container_path) tuples to a Dict suitable as volume argument for docker sdk""" return dict( map( lambda paths: (str(paths[0]), {"bind": paths[1], "mode": "rw"}), mount_volumes, ) ) class SdkDockerClient(ContainerClient): """Class for managing docker using the python docker sdk""" docker_client: Optional[DockerClient] def __init__(self): try: self.docker_client = docker.from_env() logging.getLogger("urllib3").setLevel(logging.INFO) except DockerException: self.docker_client = None def client(self): if self.docker_client: return self.docker_client else: raise ContainerException("Docker not available") def _read_from_sock(self, sock: socket, tty: bool): """Reads multiplexed messages from a socket returned by attach_socket. Uses the protocol specified here: https://docs.docker.com/engine/api/v1.41/#operation/ContainerAttach """ stdout = b"" stderr = b"" for frame_type, frame_data in frames_iter(sock, tty): if frame_type == STDOUT: stdout += frame_data elif frame_type == STDERR: stderr += frame_data else: raise ContainerException("Invalid frame type when reading from socket") return stdout, stderr def _container_path_info(self, container: Container, container_path: str): """ Get information about a path in the given container :param container: Container to be inspected :param container_path: Path in container :return: Tuple (path_exists, path_is_directory) """ # Docker CLI copy uses go FileMode to determine if target is a dict or not # https://github.com/docker/cli/blob/e3dfc2426e51776a3263cab67fbba753dd3adaa9/cli/command/container/cp.go#L260 # The isDir Bit is the most significant bit in the 32bit struct: # https://golang.org/src/os/types.go?s=2650:2683 stats = {} try: _, stats = container.get_archive(container_path) target_exists = True except APIError: target_exists = False target_is_dir = target_exists and bool(stats["mode"] & SDK_ISDIR) return target_exists, target_is_dir def get_container_status(self, container_name: str) -> DockerContainerStatus: # LOG.debug("Getting container status for container: %s", container_name) # too verbose try: container = self.client().containers.get(container_name) if container.status == "running": return DockerContainerStatus.UP else: return DockerContainerStatus.DOWN except NotFound: return DockerContainerStatus.NON_EXISTENT except APIError: raise ContainerException() def get_network(self, container_name: str) -> str: LOG.debug("Getting network type for container: %s", container_name) try: container = self.client().containers.get(container_name) return container.attrs["HostConfig"]["NetworkMode"] except NotFound: raise NoSuchContainer(container_name) except APIError: raise ContainerException() def stop_container(self, container_name: str, timeout: int = None) -> None: if timeout is None: timeout = self.STOP_TIMEOUT LOG.debug("Stopping container: %s", container_name) try: container = self.client().containers.get(container_name) container.stop(timeout=timeout) except NotFound: raise NoSuchContainer(container_name) except APIError: raise ContainerException() def remove_container(self, container_name: str, force=True, check_existence=False) -> None: LOG.debug("Removing container: %s", container_name) if check_existence and container_name not in self.get_running_container_names(): LOG.debug("Aborting removing due to check_existence check") return try: container = self.client().containers.get(container_name) container.remove(force=force) except NotFound: if not force: raise NoSuchContainer(container_name) except APIError: raise ContainerException() def list_containers(self, filter: Union[List[str], str, None] = None, all=True) -> List[dict]: if filter: filter = [filter] if isinstance(filter, str) else filter filter = dict([f.split("=", 1) for f in filter]) LOG.debug("Listing containers with filters: %s", filter) try: container_list = self.client().containers.list(filters=filter, all=all) return list( map( lambda container: { "id": container.id, "image": container.image, "name": container.name, "status": container.status, "labels": container.labels, }, container_list, ) ) except APIError: raise ContainerException() def copy_into_container( self, container_name: str, local_path: str, container_path: str ) -> None: # TODO behave like https://docs.docker.com/engine/reference/commandline/cp/ LOG.debug("Copying file %s into %s:%s", local_path, container_name, container_path) try: container = self.client().containers.get(container_name) target_exists, target_isdir = self._container_path_info(container, container_path) target_path = container_path if target_isdir else os.path.dirname(container_path) with Util.tar_path(local_path, container_path, is_dir=target_isdir) as tar: container.put_archive(target_path, tar) except NotFound: raise NoSuchContainer(container_name) except APIError: raise ContainerException() def copy_from_container( self, container_name: str, local_path: str, container_path: str, ) -> None: LOG.debug("Copying file from %s:%s to %s", container_name, container_path, local_path) try: container = self.client().containers.get(container_name) bits, _ = container.get_archive(container_path) Util.untar_to_path(bits, local_path) except NotFound: raise NoSuchContainer(container_name) except APIError: raise ContainerException() def pull_image(self, docker_image: str) -> None: LOG.debug("Pulling image: %s", docker_image) # some path in the docker image string indicates a custom repository try: LOG.debug("Repository: %s", docker_image) self.client().images.pull(docker_image) except ImageNotFound: raise NoSuchImage(docker_image) except APIError: raise ContainerException() def get_docker_image_names(self, strip_latest=True, include_tags=True): try: images = self.client().images.list() image_names = [tag for image in images for tag in image.tags if image.tags] if not include_tags: image_names = list(map(lambda image_name: image_name.split(":")[0], image_names)) if strip_latest: Util.append_without_latest(image_names) return image_names except APIError: raise ContainerException() def get_container_logs(self, container_name_or_id: str, safe=False) -> str: try: container = self.client().containers.get(container_name_or_id) return to_str(container.logs()) except NotFound: if safe: return "" raise NoSuchContainer(container_name_or_id) except APIError: if safe: return "" raise ContainerException() def inspect_container(self, container_name_or_id: str) -> Dict[str, Union[Dict, str]]: try: return self.client().containers.get(container_name_or_id).attrs except NotFound: raise NoSuchContainer(container_name_or_id) except APIError: raise ContainerException() def inspect_image(self, image_name: str) -> Dict[str, Union[Dict, str]]: try: return self.client().images.get(image_name).attrs except NotFound: raise NoSuchImage(image_name) except APIError: raise ContainerException() def inspect_network(self, network_name: str) -> Dict[str, Union[Dict, str]]: try: return self.client().networks.get(network_name).attrs except NotFound: raise NoSuchNetwork(network_name) except APIError: raise ContainerException() def get_container_ip(self, container_name_or_id: str) -> str: networks = self.inspect_container(container_name_or_id)["NetworkSettings"]["Networks"] network_names = list(networks) if len(network_names) > 1: LOG.info("Container has more than one assigned network. Picking the first one...") return networks[network_names[0]]["IPAddress"] def has_docker(self) -> bool: try: if not self.docker_client: return False self.client().ping() return True except APIError: return False def start_container( self, container_name_or_id: str, stdin=None, interactive: bool = False, attach: bool = False, flags: Optional[str] = None, ) -> Tuple[bytes, bytes]: LOG.debug("Starting container %s", container_name_or_id) try: container = self.client().containers.get(container_name_or_id) stdout = to_bytes(container_name_or_id) stderr = b"" if interactive or attach: params = {"stdout": 1, "stderr": 1, "stream": 1} if interactive: params["stdin"] = 1 sock = container.attach_socket(params=params) sock = sock._sock if hasattr(sock, "_sock") else sock result_queue = queue.Queue() thread_started = threading.Event() start_waiting = threading.Event() # Note: We need to be careful about potential race conditions here - .wait() should happen right # after .start(). Hence starting a thread and asynchronously waiting for the container exit code def wait_for_result(*_): _exit_code = -1 try: thread_started.set() start_waiting.wait() _exit_code = container.wait()["StatusCode"] except APIError as e: _exit_code = 1 raise ContainerException(str(e)) finally: result_queue.put(_exit_code) # start listener thread start_worker_thread(wait_for_result) thread_started.wait() # start container container.start() # start awaiting container result start_waiting.set() # handle container input/output with sock: try: if stdin: sock.sendall(to_bytes(stdin)) sock.shutdown(socket.SHUT_WR) stdout, stderr = self._read_from_sock(sock, False) except socket.timeout: LOG.debug( f"Socket timeout when talking to the I/O streams of Docker container '{container_name_or_id}'" ) # get container exit code exit_code = result_queue.get() if exit_code: raise ContainerException( "Docker container returned with exit code %s" % exit_code, stdout=stdout, stderr=stderr, ) else: container.start() return stdout, stderr except NotFound: raise NoSuchContainer(container_name_or_id) except APIError: raise ContainerException() def create_container( self, image_name: str, *, name: Optional[str] = None, entrypoint: Optional[str] = None, remove: bool = False, interactive: bool = False, tty: bool = False, detach: bool = False, command: Optional[Union[List[str], str]] = None, mount_volumes: Optional[List[SimpleVolumeBind]] = None, ports: Optional[PortMappings] = None, env_vars: Optional[Dict[str, str]] = None, user: Optional[str] = None, cap_add: Optional[str] = None, network: Optional[str] = None, dns: Optional[str] = None, additional_flags: Optional[str] = None, workdir: Optional[str] = None, ) -> str: LOG.debug( "Creating container with image %s, command '%s', entrypoint '%s', volumes %s, env vars %s", image_name, command, entrypoint, mount_volumes, env_vars, ) extra_hosts = None if additional_flags: env_vars, ports, mount_volumes, extra_hosts, network = Util.parse_additional_flags( additional_flags, env_vars, ports, mount_volumes, network ) try: kwargs = {} if cap_add: kwargs["cap_add"] = [cap_add] if dns: kwargs["dns"] = [dns] if ports: kwargs["ports"] = ports.to_dict() if workdir: kwargs["working_dir"] = workdir mounts = None if mount_volumes: mounts = Util.convert_mount_list_to_dict(mount_volumes) def create_container(): return self.client().containers.create( image=image_name, command=command, auto_remove=remove, name=name, stdin_open=interactive, tty=tty, entrypoint=entrypoint, environment=env_vars, detach=detach, user=user, network=network, volumes=mounts, extra_hosts=extra_hosts, **kwargs, ) try: container = create_container() except ImageNotFound: self.pull_image(image_name) container = create_container() return container.id except ImageNotFound: raise NoSuchImage(image_name) except APIError: raise ContainerException() def run_container( self, image_name: str, stdin=None, *, name: Optional[str] = None, entrypoint: Optional[str] = None, remove: bool = False, interactive: bool = False, tty: bool = False, detach: bool = False, command: Optional[Union[List[str], str]] = None, mount_volumes: Optional[List[SimpleVolumeBind]] = None, ports: Optional[PortMappings] = None, env_vars: Optional[Dict[str, str]] = None, user: Optional[str] = None, cap_add: Optional[str] = None, network: Optional[str] = None, dns: Optional[str] = None, additional_flags: Optional[str] = None, workdir: Optional[str] = None, ) -> Tuple[bytes, bytes]: LOG.debug("Running container with image: %s", image_name) container = None try: container = self.create_container( image_name, name=name, entrypoint=entrypoint, interactive=interactive, tty=tty, detach=detach, remove=remove and detach, command=command, mount_volumes=mount_volumes, ports=ports, env_vars=env_vars, user=user, cap_add=cap_add, network=network, dns=dns, additional_flags=additional_flags, workdir=workdir, ) result = self.start_container( container_name_or_id=container, stdin=stdin, interactive=interactive, attach=not detach, ) finally: if remove and container and not detach: self.remove_container(container) return result def exec_in_container( self, container_name_or_id: str, command: Union[List[str], str], interactive=False, detach=False, env_vars: Optional[Dict[str, Optional[str]]] = None, stdin: Optional[bytes] = None, user: Optional[str] = None, ) -> Tuple[bytes, bytes]: LOG.debug("Executing command in container %s: %s", container_name_or_id, command) try: container: Container = self.client().containers.get(container_name_or_id) result = container.exec_run( cmd=command, environment=env_vars, user=user, detach=detach, stdin=interactive and bool(stdin), socket=interactive and bool(stdin), stdout=True, stderr=True, demux=True, ) tty = False if interactive and stdin: # result is a socket sock = result[1] sock = sock._sock if hasattr(sock, "_sock") else sock with sock: try: sock.sendall(stdin) sock.shutdown(socket.SHUT_WR) stdout, stderr = self._read_from_sock(sock, tty) return stdout, stderr except socket.timeout: pass else: if detach: return b"", b"" return_code = result[0] if isinstance(result[1], bytes): stdout = result[1] stderr = b"" else: stdout, stderr = result[1] if return_code != 0: raise ContainerException( "Exec command returned with exit code %s" % return_code, stdout, stderr ) return stdout, stderr except ContainerError: raise NoSuchContainer(container_name_or_id) except APIError: raise ContainerException() DOCKER_CLIENT: ContainerClient = ( CmdDockerClient() if config.LEGACY_DOCKER_CLIENT else SdkDockerClient() )
1
13,993
what does this change do exactly?
localstack-localstack
py
@@ -48,7 +48,8 @@ type networkImpl struct { proposalCh chan agreement.Message bundleCh chan agreement.Message - net network.GossipNode + net network.GossipNode + backgroundCtx context.Context } // WrapNetwork adapts a network.GossipNode into an agreement.Network.
1
// Copyright (C) 2019 Algorand, Inc. // This file is part of go-algorand // // go-algorand is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // go-algorand is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with go-algorand. If not, see <https://www.gnu.org/licenses/>. // Package gossip adapts the interface of network.GossipNode to // agreement.Network. package gossip import ( "context" "time" "github.com/algorand/go-algorand/agreement" "github.com/algorand/go-algorand/logging" "github.com/algorand/go-algorand/network" "github.com/algorand/go-algorand/protocol" "github.com/algorand/go-algorand/util/metrics" ) var ( voteBufferSize = 10000 proposalBufferSize = 14 bundleBufferSize = 7 ) var messagesHandled = metrics.MakeCounter(metrics.AgreementMessagesHandled) var messagesDropped = metrics.MakeCounter(metrics.AgreementMessagesDropped) type messageMetadata struct { raw network.IncomingMessage } // networkImpl wraps network.GossipNode to provide a compatible interface with agreement. type networkImpl struct { voteCh chan agreement.Message proposalCh chan agreement.Message bundleCh chan agreement.Message net network.GossipNode } // WrapNetwork adapts a network.GossipNode into an agreement.Network. func WrapNetwork(net network.GossipNode) agreement.Network { i := new(networkImpl) i.voteCh = make(chan agreement.Message, voteBufferSize) i.proposalCh = make(chan agreement.Message, proposalBufferSize) i.bundleCh = make(chan agreement.Message, bundleBufferSize) i.net = net handlers := []network.TaggedMessageHandler{ {Tag: protocol.AgreementVoteTag, MessageHandler: network.HandlerFunc(i.processVoteMessage)}, {Tag: protocol.ProposalPayloadTag, MessageHandler: network.HandlerFunc(i.processProposalMessage)}, {Tag: protocol.VoteBundleTag, MessageHandler: network.HandlerFunc(i.processBundleMessage)}, } net.RegisterHandlers(handlers) return i } func messageMetadataFromHandle(h agreement.MessageHandle) *messageMetadata { if msg, isMsg := h.(*messageMetadata); isMsg { return msg } return nil } func (i *networkImpl) processVoteMessage(raw network.IncomingMessage) network.OutgoingMessage { return i.processMessage(raw, i.voteCh) } func (i *networkImpl) processProposalMessage(raw network.IncomingMessage) network.OutgoingMessage { return i.processMessage(raw, i.proposalCh) } func (i *networkImpl) processBundleMessage(raw network.IncomingMessage) network.OutgoingMessage { return i.processMessage(raw, i.bundleCh) } // i.e. process<Type>Message func (i *networkImpl) processMessage(raw network.IncomingMessage, submit chan<- agreement.Message) network.OutgoingMessage { metadata := &messageMetadata{raw: raw} select { case submit <- agreement.Message{MessageHandle: agreement.MessageHandle(metadata), Data: raw.Data}: // It would be slightly better to measure at de-queue // time, but that happens in many places in code and // this is much easier. messagesHandled.Inc(nil) default: messagesDropped.Inc(nil) } // Immediately ignore everything here, sometimes Relay/Broadcast/Disconnect later based on API handles saved from IncomingMessage return network.OutgoingMessage{Action: network.Ignore} } func (i *networkImpl) Messages(t protocol.Tag) <-chan agreement.Message { switch t { case protocol.AgreementVoteTag: return i.voteCh case protocol.ProposalPayloadTag: return i.proposalCh case protocol.VoteBundleTag: return i.bundleCh default: logging.Base().Panicf("bad tag! %v", t) return nil } } func (i *networkImpl) Broadcast(t protocol.Tag, data []byte) { err := i.net.Broadcast(context.Background(), t, data, false, nil) if err != nil { logging.Base().Infof("agreement: could not broadcast message with tag %v: %v", t, err) } } func (i *networkImpl) Relay(h agreement.MessageHandle, t protocol.Tag, data []byte) { metadata := messageMetadataFromHandle(h) if metadata == nil { // synthentic loopback err := i.net.Broadcast(context.Background(), t, data, false, nil) if err != nil { logging.Base().Infof("agreement: could not (pseudo)relay message with tag %v: %v", t, err) } } else { err := i.net.Relay(context.Background(), t, data, false, metadata.raw.Sender) if err != nil { logging.Base().Infof("agreement: could not relay message from %v with tag %v: %v", metadata.raw.Sender, t, err) } } } func (i *networkImpl) Disconnect(h agreement.MessageHandle) { metadata := messageMetadataFromHandle(h) if metadata == nil { // synthentic loopback // TODO warn return } i.net.Disconnect(metadata.raw.Sender) } // broadcastTimeout is currently only used by test code. // In test code we want to queue up a bunch of outbound packets and then see that they got through, so we need to wait at least a little bit for them to all go out. // Normal agreement state machine code uses GossipNode.Broadcast non-blocking and may drop outbound packets. func (i *networkImpl) broadcastTimeout(t protocol.Tag, data []byte, timeout time.Duration) error { ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() return i.net.Broadcast(ctx, t, data, true, nil) }
1
35,533
What's the purpose of this `backgroundCtx` field?
algorand-go-algorand
go
@@ -42,7 +42,11 @@ import ( // Trie cache generation limit after which to evict trie nodes from memory. var MaxTrieCacheGen = uint32(1024 * 1024) -const IncarnationLength = 8 +const ( + IncarnationLength = 8 + FirstContractIncarnation = 1 + AccountIncarnation = 0 +) type StateReader interface { ReadAccountData(address common.Address) (*accounts.Account, error)
1
// Copyright 2019 The go-ethereum Authors // This file is part of the go-ethereum library. // // The go-ethereum library is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // The go-ethereum library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. package state import ( "bytes" "context" "encoding/binary" "fmt" "github.com/ledgerwatch/turbo-geth/common/debug" "io" "runtime" "sort" "sync" "sync/atomic" "unsafe" lru "github.com/hashicorp/golang-lru" "github.com/ledgerwatch/turbo-geth/common" "github.com/ledgerwatch/turbo-geth/common/dbutils" "github.com/ledgerwatch/turbo-geth/core/types/accounts" "github.com/ledgerwatch/turbo-geth/ethdb" "github.com/ledgerwatch/turbo-geth/log" "github.com/ledgerwatch/turbo-geth/trie" ) // Trie cache generation limit after which to evict trie nodes from memory. var MaxTrieCacheGen = uint32(1024 * 1024) const IncarnationLength = 8 type StateReader interface { ReadAccountData(address common.Address) (*accounts.Account, error) ReadAccountStorage(address common.Address, incarnation uint64, key *common.Hash) ([]byte, error) ReadAccountCode(address common.Address, codeHash common.Hash) ([]byte, error) ReadAccountCodeSize(address common.Address, codeHash common.Hash) (int, error) } type StateWriter interface { UpdateAccountData(ctx context.Context, address common.Address, original, account *accounts.Account) error UpdateAccountCode(addrHash common.Hash, incarnation uint64, codeHash common.Hash, code []byte) error DeleteAccount(ctx context.Context, address common.Address, original *accounts.Account) error WriteAccountStorage(ctx context.Context, address common.Address, incarnation uint64, key, original, value *common.Hash) error CreateContract(address common.Address) error } type NoopWriter struct { } func NewNoopWriter() *NoopWriter { return &NoopWriter{} } func (nw *NoopWriter) UpdateAccountData(_ context.Context, address common.Address, original, account *accounts.Account) error { return nil } func (nw *NoopWriter) DeleteAccount(_ context.Context, address common.Address, original *accounts.Account) error { return nil } func (nw *NoopWriter) UpdateAccountCode(addrHash common.Hash, incarnation uint64, codeHash common.Hash, code []byte) error { return nil } func (nw *NoopWriter) WriteAccountStorage(_ context.Context, address common.Address, incarnation uint64, key, original, value *common.Hash) error { return nil } func (nw *NoopWriter) CreateContract(address common.Address) error { return nil } // Structure holding updates, deletes, and reads registered within one change period // A change period can be transaction within a block, or a block within group of blocks type Buffer struct { storageUpdates map[common.Hash]map[common.Hash][]byte storageReads map[common.Hash]map[common.Hash]struct{} accountUpdates map[common.Hash]*accounts.Account accountReads map[common.Hash]struct{} deleted map[common.Hash]struct{} created map[common.Hash]struct{} } // Prepares buffer for work or clears previous data func (b *Buffer) initialise() { b.storageUpdates = make(map[common.Hash]map[common.Hash][]byte) b.storageReads = make(map[common.Hash]map[common.Hash]struct{}) b.accountUpdates = make(map[common.Hash]*accounts.Account) b.accountReads = make(map[common.Hash]struct{}) b.deleted = make(map[common.Hash]struct{}) b.created = make(map[common.Hash]struct{}) } // Replaces account pointer with pointers to the copies func (b *Buffer) detachAccounts() { for addrHash, account := range b.accountUpdates { if account != nil { b.accountUpdates[addrHash] = account.SelfCopy() } } } // Merges the content of another buffer into this one func (b *Buffer) merge(other *Buffer) { for addrHash, om := range other.storageUpdates { m, ok := b.storageUpdates[addrHash] if !ok { m = make(map[common.Hash][]byte) b.storageUpdates[addrHash] = m } for keyHash, v := range om { m[keyHash] = v } } for addrHash, om := range other.storageReads { m, ok := b.storageReads[addrHash] if !ok { m = make(map[common.Hash]struct{}) b.storageReads[addrHash] = m } for keyHash := range om { m[keyHash] = struct{}{} } } for addrHash, account := range other.accountUpdates { b.accountUpdates[addrHash] = account } for addrHash := range other.accountReads { b.accountReads[addrHash] = struct{}{} } for addrHash := range other.deleted { b.deleted[addrHash] = struct{}{} } for addrHash := range other.created { b.created[addrHash] = struct{}{} } } // TrieDbState implements StateReader by wrapping a trie and a database, where trie acts as a cache for the database type TrieDbState struct { t *trie.Trie tMu *sync.Mutex db ethdb.Database blockNr uint64 buffers []*Buffer aggregateBuffer *Buffer // Merge of all buffers currentBuffer *Buffer codeCache *lru.Cache codeSizeCache *lru.Cache historical bool noHistory bool resolveReads bool savePreimages bool pg *trie.ProofGenerator tp *trie.TriePruning } var ( trieObj = make(map[uint64]uintptr) trieObjMu sync.RWMutex ) func getTrieDBState(db ethdb.Database) *TrieDbState { if db == nil { return nil } trieObjMu.RLock() tr, ok := trieObj[db.ID()] trieObjMu.RUnlock() if !ok { return nil } return (*TrieDbState)(unsafe.Pointer(tr)) } func setTrieDBState(tds *TrieDbState, id uint64) { if tds == nil { return } ptr := unsafe.Pointer(tds) trieObjMu.Lock() trieObj[id] = uintptr(ptr) trieObjMu.Unlock() } func NewTrieDbState(root common.Hash, db ethdb.Database, blockNr uint64) (*TrieDbState, error) { tds, err := newTrieDbState(root, db, blockNr) if err != nil { return nil, err } setTrieDBState(tds, db.ID()) return tds, nil } func newTrieDbState(root common.Hash, db ethdb.Database, blockNr uint64) (*TrieDbState, error) { csc, err := lru.New(100000) if err != nil { return nil, err } cc, err := lru.New(10000) if err != nil { return nil, err } t := trie.New(root) tp := trie.NewTriePruning(blockNr) tds := &TrieDbState{ t: t, tMu: new(sync.Mutex), db: db, blockNr: blockNr, codeCache: cc, codeSizeCache: csc, pg: trie.NewProofGenerator(), tp: tp, savePreimages: true, } t.SetTouchFunc(func(hex []byte, del bool) { tp.Touch(hex, del) }) return tds, nil } func GetTrieDbState(root common.Hash, db ethdb.Database, blockNr uint64) (*TrieDbState, error) { if tr := getTrieDBState(db); tr != nil { if tr.getBlockNr() == blockNr && tr.LastRoot() == root { return tr, nil } } return newTrieDbState(root, db, blockNr) } func (tds *TrieDbState) EnablePreimages(ep bool) { tds.savePreimages = ep } func (tds *TrieDbState) SetHistorical(h bool) { tds.historical = h } func (tds *TrieDbState) SetResolveReads(rr bool) { tds.resolveReads = rr } func (tds *TrieDbState) SetNoHistory(nh bool) { tds.noHistory = nh } func (tds *TrieDbState) Copy() *TrieDbState { tds.tMu.Lock() tcopy := *tds.t tds.tMu.Unlock() n := tds.getBlockNr() tp := trie.NewTriePruning(n) cpy := TrieDbState{ t: &tcopy, tMu: new(sync.Mutex), db: tds.db, blockNr: n, tp: tp, } return &cpy } func (tds *TrieDbState) Database() ethdb.Database { return tds.db } func (tds *TrieDbState) Trie() *trie.Trie { return tds.t } func (tds *TrieDbState) StartNewBuffer() { if tds.currentBuffer != nil { if tds.aggregateBuffer == nil { tds.aggregateBuffer = &Buffer{} tds.aggregateBuffer.initialise() } tds.aggregateBuffer.merge(tds.currentBuffer) tds.currentBuffer.detachAccounts() } tds.currentBuffer = &Buffer{} tds.currentBuffer.initialise() tds.buffers = append(tds.buffers, tds.currentBuffer) } func (tds *TrieDbState) WithNewBuffer() *TrieDbState { aggregateBuffer := &Buffer{} aggregateBuffer.initialise() currentBuffer := &Buffer{} currentBuffer.initialise() buffers := []*Buffer{currentBuffer} tds.tMu.Lock() t := &TrieDbState{ t: tds.t, tMu: tds.tMu, db: tds.db, blockNr: tds.getBlockNr(), buffers: buffers, aggregateBuffer: aggregateBuffer, currentBuffer: currentBuffer, codeCache: tds.codeCache, codeSizeCache: tds.codeSizeCache, historical: tds.historical, noHistory: tds.noHistory, resolveReads: tds.resolveReads, pg: tds.pg, tp: tds.tp, } tds.tMu.Unlock() return t } func (tds *TrieDbState) LastRoot() common.Hash { tds.tMu.Lock() defer tds.tMu.Unlock() return tds.t.Hash() } // ComputeTrieRoots is a combination of `ResolveStateTrie` and `UpdateStateTrie` // DESCRIBED: docs/programmers_guide/guide.md#organising-ethereum-state-into-a-merkle-tree func (tds *TrieDbState) ComputeTrieRoots() ([]common.Hash, error) { if err := tds.ResolveStateTrie(); err != nil { return nil, err } return tds.UpdateStateTrie() } // UpdateStateTrie assumes that the state trie is already fully resolved, i.e. any operations // will find necessary data inside the trie. func (tds *TrieDbState) UpdateStateTrie() ([]common.Hash, error) { tds.tMu.Lock() defer tds.tMu.Unlock() roots, err := tds.updateTrieRoots(true) tds.clearUpdates() return roots, err } func (tds *TrieDbState) PrintTrie(w io.Writer) { tds.tMu.Lock() defer tds.tMu.Unlock() tds.t.Print(w) fmt.Fprintln(w, "") //nolint } // Builds a map where for each address (of a smart contract) there is // a sorted list of all key hashes that were touched within the // period for which we are aggregating updates func (tds *TrieDbState) buildStorageTouches(withReads bool, withValues bool) (common.StorageKeys, [][]byte) { storageTouches := common.StorageKeys{} var values [][]byte for addrHash, m := range tds.aggregateBuffer.storageUpdates { if withValues { if _, ok := tds.aggregateBuffer.deleted[addrHash]; ok { continue } } for keyHash := range m { var storageKey common.StorageKey copy(storageKey[:], addrHash[:]) copy(storageKey[common.HashLength:], keyHash[:]) storageTouches = append(storageTouches, storageKey) } } if withReads { for addrHash, m := range tds.aggregateBuffer.storageReads { mWrite := tds.aggregateBuffer.storageUpdates[addrHash] for keyHash := range m { if mWrite != nil { if _, ok := mWrite[keyHash]; ok { // Avoid repeating the same storage keys if they are both read and updated continue } } var storageKey common.StorageKey copy(storageKey[:], addrHash[:]) copy(storageKey[common.HashLength:], keyHash[:]) storageTouches = append(storageTouches, storageKey) } } } sort.Sort(storageTouches) if withValues { // We assume that if withValues == true, then withReads == false var addrHash common.Hash var keyHash common.Hash for _, storageKey := range storageTouches { copy(addrHash[:], storageKey[:]) copy(keyHash[:], storageKey[common.HashLength:]) values = append(values, tds.aggregateBuffer.storageUpdates[addrHash][keyHash]) } } return storageTouches, values } // Expands the storage tries (by loading data from the database) if it is required // for accessing storage slots containing in the storageTouches map func (tds *TrieDbState) resolveStorageTouches(storageTouches common.StorageKeys) error { var resolver *trie.Resolver for _, storageKey := range storageTouches { if need, req := tds.t.NeedResolution(storageKey[:common.HashLength], storageKey[:]); need { if resolver == nil { resolver = trie.NewResolver(0, false, tds.blockNr) resolver.SetHistorical(tds.historical) } resolver.AddRequest(req) } } if resolver != nil { if err := resolver.ResolveWithDb(tds.db, tds.blockNr); err != nil { return err } } return nil } // Populate pending block proof so that it will be sufficient for accessing all storage slots in storageTouches func (tds *TrieDbState) populateStorageBlockProof(storageTouches common.StorageKeys) error { //nolint for _, storageKey := range storageTouches { tds.pg.AddStorageTouch(storageKey[:]) } return nil } // Builds a sorted list of all address hashes that were touched within the // period for which we are aggregating updates func (tds *TrieDbState) buildAccountTouches(withReads bool, withValues bool) (common.Hashes, []*accounts.Account) { accountTouches := common.Hashes{} var aValues []*accounts.Account for addrHash, aValue := range tds.aggregateBuffer.accountUpdates { if aValue != nil { if _, ok := tds.aggregateBuffer.deleted[addrHash]; ok { accountTouches = append(accountTouches, addrHash) } } accountTouches = append(accountTouches, addrHash) } if withReads { for addrHash := range tds.aggregateBuffer.accountReads { if _, ok := tds.aggregateBuffer.accountUpdates[addrHash]; !ok { accountTouches = append(accountTouches, addrHash) } } } sort.Sort(accountTouches) if withValues { // We assume that if withValues == true, then withReads == false aValues = make([]*accounts.Account, len(accountTouches)) for i, addrHash := range accountTouches { if i < len(accountTouches)-1 && addrHash == accountTouches[i+1] { aValues[i] = nil // Entry that would wipe out existing storage } else { a := tds.aggregateBuffer.accountUpdates[addrHash] if a != nil { if _, ok := tds.aggregateBuffer.storageUpdates[addrHash]; ok { var ac accounts.Account ac.Copy(a) ac.Root = trie.EmptyRoot a = &ac } } aValues[i] = a } } } return accountTouches, aValues } // Expands the accounts trie (by loading data from the database) if it is required // for accessing accounts whose addresses are contained in the accountTouches func (tds *TrieDbState) resolveAccountTouches(accountTouches common.Hashes) error { var resolver *trie.Resolver for _, addrHash := range accountTouches { if need, req := tds.t.NeedResolution(nil, addrHash[:]); need { if resolver == nil { resolver = trie.NewResolver(0, true, tds.blockNr) resolver.SetHistorical(tds.historical) } resolver.AddRequest(req) } } if resolver != nil { if err := resolver.ResolveWithDb(tds.db, tds.blockNr); err != nil { return err } resolver = nil } return nil } func (tds *TrieDbState) populateAccountBlockProof(accountTouches common.Hashes) { for _, addrHash := range accountTouches { a := addrHash tds.pg.AddTouch(a[:]) } } // ExtractTouches returns two lists of keys - for accounts and storage items correspondingly // Each list is the collection of keys that have been "touched" (inserted, updated, or simply accessed) // since the last invocation of `ExtractTouches`. func (tds *TrieDbState) ExtractTouches() (accountTouches [][]byte, storageTouches [][]byte) { return tds.pg.ExtractTouches() } // ResolveStateTrie resolves parts of the state trie that would be necessary for any updates // (and reads, if `resolveReads` is set). func (tds *TrieDbState) ResolveStateTrie() error { // Aggregating the current buffer, if any if tds.currentBuffer != nil { if tds.aggregateBuffer == nil { tds.aggregateBuffer = &Buffer{} tds.aggregateBuffer.initialise() } tds.aggregateBuffer.merge(tds.currentBuffer) } if tds.aggregateBuffer == nil { return nil } tds.tMu.Lock() defer tds.tMu.Unlock() // Prepare (resolve) storage tries so that actual modifications can proceed without database access storageTouches, _ := tds.buildStorageTouches(tds.resolveReads, false) // Prepare (resolve) accounts trie so that actual modifications can proceed without database access accountTouches, _ := tds.buildAccountTouches(tds.resolveReads, false) if err := tds.resolveAccountTouches(accountTouches); err != nil { return err } if tds.resolveReads { tds.populateAccountBlockProof(accountTouches) } if err := tds.resolveStorageTouches(storageTouches); err != nil { return err } if tds.resolveReads { if err := tds.populateStorageBlockProof(storageTouches); err != nil { return err } } return nil } // CalcTrieRoots calculates trie roots without modifying the state trie func (tds *TrieDbState) CalcTrieRoots(trace bool) (common.Hash, error) { tds.tMu.Lock() defer tds.tMu.Unlock() // Retrive the list of inserted/updated/deleted storage items (keys and values) storageKeys, sValues := tds.buildStorageTouches(false, true) if trace { fmt.Printf("len(storageKeys)=%d, len(sValues)=%d\n", len(storageKeys), len(sValues)) } // Retrive the list of inserted/updated/deleted accounts (keys and values) accountKeys, aValues := tds.buildAccountTouches(false, true) if trace { fmt.Printf("len(accountKeys)=%d, len(aValues)=%d\n", len(accountKeys), len(aValues)) } return trie.HashWithModifications(tds.t, accountKeys, aValues, storageKeys, sValues, common.HashLength, trace) } // forward is `true` if the function is used to progress the state forward (by adding blocks) // forward is `false` if the function is used to rewind the state (for reorgs, for example) func (tds *TrieDbState) updateTrieRoots(forward bool) ([]common.Hash, error) { accountUpdates := tds.aggregateBuffer.accountUpdates // Perform actual updates on the tries, and compute one trie root per buffer // These roots can be used to populate receipt.PostState on pre-Byzantium roots := make([]common.Hash, len(tds.buffers)) // The following map is to prevent repeated clearouts of the storage alreadyCreated := make(map[common.Hash]struct{}) for i, b := range tds.buffers { // New contracts are being created at these addresses. Therefore, we need to clear the storage items // that might be remaining in the trie and figure out the next incarnations for addrHash := range b.created { // Prevent repeated storage clearouts if _, ok := alreadyCreated[addrHash]; ok { continue } alreadyCreated[addrHash] = struct{}{} if account, ok := b.accountUpdates[addrHash]; ok && account != nil { b.accountUpdates[addrHash].Root = trie.EmptyRoot } if account, ok := tds.aggregateBuffer.accountUpdates[addrHash]; ok && account != nil { tds.aggregateBuffer.accountUpdates[addrHash].Root = trie.EmptyRoot } // The only difference between Delete and DeleteSubtree is that Delete would delete accountNode too, // wherewas DeleteSubtree will keep the accountNode, but will make the storage sub-trie empty tds.t.DeleteSubtree(addrHash[:], tds.blockNr) } for addrHash, account := range b.accountUpdates { if account != nil { //fmt.Println("b.accountUpdates",addrHash.String(), account.Incarnation) tds.t.UpdateAccount(addrHash[:], account) } else { tds.t.Delete(addrHash[:], tds.blockNr) } } for addrHash, m := range b.storageUpdates { for keyHash, v := range m { cKey := dbutils.GenerateCompositeTrieKey(addrHash, keyHash) if len(v) > 0 { //fmt.Printf("Update storage trie addrHash %x, keyHash %x: %x\n", addrHash, keyHash, v) if forward { tds.t.Update(cKey, v, tds.blockNr) } else { // If rewinding, it might not be possible to execute storage item update. // If we rewind from the state where a contract does not exist anymore (it was self-destructed) // to the point where it existed (with storage), then rewinding to the point of existence // will not bring back the full storage trie. Instead there will be one hashNode. // So we probe for this situation first if _, ok := tds.t.Get(cKey); ok { tds.t.Update(cKey, v, tds.blockNr) } } } else { //fmt.Printf("Delete storage trie addrHash %x, keyHash %x\n", addrHash, keyHash) if forward { tds.t.Delete(cKey, tds.blockNr) } else { // If rewinding, it might not be possible to execute storage item update. // If we rewind from the state where a contract does not exist anymore (it was self-destructed) // to the point where it existed (with storage), then rewinding to the point of existence // will not bring back the full storage trie. Instead there will be one hashNode. // So we probe for this situation first if _, ok := tds.t.Get(cKey); ok { tds.t.Delete(cKey, tds.blockNr) } } } } if forward || debug.IsThinHistory() { if account, ok := b.accountUpdates[addrHash]; ok && account != nil { ok, root := tds.t.DeepHash(addrHash[:]) if ok { account.Root = root //fmt.Printf("(b)Set %x root for addrHash %x\n", root, addrHash) } else { //fmt.Printf("(b)Set empty root for addrHash %x\n", addrHash) account.Root = trie.EmptyRoot } } if account, ok := accountUpdates[addrHash]; ok && account != nil { ok, root := tds.t.DeepHash(addrHash[:]) if ok { account.Root = root //fmt.Printf("Set %x root for addrHash %x\n", root, addrHash) } else { //fmt.Printf("Set empty root for addrHash %x\n", addrHash) account.Root = trie.EmptyRoot } } } else { // Simply comparing the correctness of the storageRoot computations if account, ok := b.accountUpdates[addrHash]; ok && account != nil { ok, h := tds.t.DeepHash(addrHash[:]) if !ok { h = trie.EmptyRoot } if account.Root != h { return nil, fmt.Errorf("mismatched storage root for %x: expected %x, got %x", addrHash, account.Root, h) } } if account, ok := accountUpdates[addrHash]; ok && account != nil { ok, h := tds.t.DeepHash(addrHash[:]) if !ok { h = trie.EmptyRoot } if account.Root != h { return nil, fmt.Errorf("mismatched storage root for %x: expected %x, got %x", addrHash, account.Root, h) } } } } // For the contracts that got deleted for addrHash := range b.deleted { if _, ok := b.created[addrHash]; ok { // In some rather artificial circumstances, an account can be recreated after having been self-destructed // in the same block. It can only happen when contract is introduced in the genesis state with nonce 0 // rather than created by a transaction (in that case, its starting nonce is 1). The self-destructed // contract actually gets removed from the state only at the end of the block, so if its nonce is not 0, // it will prevent any re-creation within the same block. However, if the contract is introduced in // the genesis state, its nonce is 0, and that means it can be self-destructed, and then re-created, // all in the same block. In such cases, we must preserve storage modifications happening after the // self-destruction continue } if account, ok := b.accountUpdates[addrHash]; ok && account != nil { //fmt.Printf("(b)Set empty root for addrHash %x due to deleted\n", addrHash) account.Root = trie.EmptyRoot } if account, ok := accountUpdates[addrHash]; ok && account != nil { //fmt.Printf("Set empty root for addrHash %x due to deleted\n", addrHash) account.Root = trie.EmptyRoot } tds.t.DeleteSubtree(addrHash[:], tds.blockNr) } roots[i] = tds.t.Hash() } return roots, nil } func (tds *TrieDbState) clearUpdates() { tds.buffers = nil tds.currentBuffer = nil tds.aggregateBuffer = nil } func (tds *TrieDbState) Rebuild() error { tds.tMu.Lock() defer tds.tMu.Unlock() err := tds.t.Rebuild(tds.db, tds.blockNr) if err != nil { return err } var m runtime.MemStats runtime.ReadMemStats(&m) log.Info("Memory after rebuild", "nodes", tds.tp.NodeCount(), "alloc", int(m.Alloc/1024), "sys", int(m.Sys/1024), "numGC", int(m.NumGC)) return nil } func (tds *TrieDbState) SetBlockNr(blockNr uint64) { tds.setBlockNr(blockNr) tds.tp.SetBlockNr(blockNr) } func (tds *TrieDbState) GetBlockNr() uint64 { return tds.getBlockNr() } func (tds *TrieDbState) UnwindTo(blockNr uint64) error { tds.StartNewBuffer() b := tds.currentBuffer if err := tds.db.RewindData(tds.blockNr, blockNr, func(bucket, key, value []byte) error { //fmt.Printf("bucket: %x, key: %x, value: %x\n", bucket, key, value) if bytes.Equal(bucket, dbutils.AccountsHistoryBucket) { var addrHash common.Hash copy(addrHash[:], key) if len(value) > 0 { var acc accounts.Account if err := acc.DecodeForStorage(value); err != nil { return err } b.accountUpdates[addrHash] = &acc if err := tds.db.Put(dbutils.AccountsBucket, addrHash[:], value); err != nil { return err } } else { b.accountUpdates[addrHash] = nil if err := tds.db.Delete(dbutils.AccountsBucket, addrHash[:]); err != nil { return err } } } else if bytes.Equal(bucket, dbutils.StorageHistoryBucket) { var addrHash common.Hash copy(addrHash[:], key[:common.HashLength]) var keyHash common.Hash copy(keyHash[:], key[common.HashLength+IncarnationLength:]) m, ok := b.storageUpdates[addrHash] if !ok { m = make(map[common.Hash][]byte) b.storageUpdates[addrHash] = m } if len(value) > 0 { m[keyHash] = value if err := tds.db.Put(dbutils.StorageBucket, key[:common.HashLength+IncarnationLength+common.HashLength], value); err != nil { return err } } else { m[keyHash] = nil if err := tds.db.Delete(dbutils.StorageBucket, key[:common.HashLength+IncarnationLength+common.HashLength]); err != nil { return err } } } return nil }); err != nil { return err } if err := tds.ResolveStateTrie(); err != nil { return err } tds.tMu.Lock() defer tds.tMu.Unlock() if _, err := tds.updateTrieRoots(false); err != nil { return err } for i := tds.blockNr; i > blockNr; i-- { if err := tds.db.DeleteTimestamp(i); err != nil { return err } } tds.clearUpdates() tds.setBlockNr(blockNr) return nil } func (tds *TrieDbState) readAccountDataByHash(addrHash common.Hash) (*accounts.Account, error) { if acc, ok := tds.GetAccount(addrHash); ok { return acc, nil } // Not present in the trie, try the database var err error var enc []byte if tds.historical { enc, err = tds.db.GetAsOf(dbutils.AccountsBucket, dbutils.AccountsHistoryBucket, addrHash[:], tds.blockNr+1) if err != nil { enc = nil } } else { enc, err = tds.db.Get(dbutils.AccountsBucket, addrHash[:]) if err != nil { enc = nil } } if len(enc) == 0 { return nil, nil } var a accounts.Account if err := a.DecodeForStorage(enc); err != nil { return nil, err } if tds.historical && debug.IsThinHistory() { codeHash, err := tds.db.Get(dbutils.ContractCodeBucket, dbutils.GenerateStoragePrefix(addrHash, a.Incarnation)) if err == nil { a.CodeHash = common.BytesToHash(codeHash) } else { log.Error("Get code hash is incorrect", "err", err) } } return &a, nil } func (tds *TrieDbState) GetAccount(addrHash common.Hash) (*accounts.Account, bool) { tds.tMu.Lock() defer tds.tMu.Unlock() acc, ok := tds.t.GetAccount(addrHash[:]) return acc, ok } func (tds *TrieDbState) ReadAccountData(address common.Address) (*accounts.Account, error) { addrHash, err := common.HashData(address[:]) if err != nil { return nil, err } if tds.resolveReads { if _, ok := tds.currentBuffer.accountUpdates[addrHash]; !ok { tds.currentBuffer.accountReads[addrHash] = struct{}{} } } return tds.readAccountDataByHash(addrHash) } func (tds *TrieDbState) savePreimage(save bool, hash, preimage []byte) error { if !save || !tds.savePreimages { return nil } // Following check is to minimise the overwriting the same value of preimage // in the database, which would cause extra write churn if p, _ := tds.db.Get(dbutils.PreimagePrefix, hash); p != nil { return nil } return tds.db.Put(dbutils.PreimagePrefix, hash, preimage) } func (tds *TrieDbState) HashAddress(address common.Address, save bool) (common.Hash, error) { addrHash, err := common.HashData(address[:]) if err != nil { return common.Hash{}, err } return addrHash, tds.savePreimage(save, addrHash[:], address[:]) } func (tds *TrieDbState) HashKey(key *common.Hash, save bool) (common.Hash, error) { keyHash, err := common.HashData(key[:]) if err != nil { return common.Hash{}, err } return keyHash, tds.savePreimage(save, keyHash[:], key[:]) } func (tds *TrieDbState) GetKey(shaKey []byte) []byte { key, _ := tds.db.Get(dbutils.PreimagePrefix, shaKey) return key } func (tds *TrieDbState) ReadAccountStorage(address common.Address, incarnation uint64, key *common.Hash) ([]byte, error) { addrHash, err := tds.HashAddress(address, false /*save*/) if err != nil { return nil, err } if tds.currentBuffer != nil { if _, ok := tds.currentBuffer.deleted[addrHash]; ok { return nil, nil } } if tds.aggregateBuffer != nil { if _, ok := tds.aggregateBuffer.deleted[addrHash]; ok { return nil, nil } } seckey, err := tds.HashKey(key, false /*save*/) if err != nil { return nil, err } if tds.resolveReads { var addReadRecord = false if mWrite, ok := tds.currentBuffer.storageUpdates[addrHash]; ok { if _, ok1 := mWrite[seckey]; !ok1 { addReadRecord = true } } else { addReadRecord = true } if addReadRecord { m, ok := tds.currentBuffer.storageReads[addrHash] if !ok { m = make(map[common.Hash]struct{}) tds.currentBuffer.storageReads[addrHash] = m } m[seckey] = struct{}{} } } tds.tMu.Lock() enc, ok := tds.t.Get(dbutils.GenerateCompositeTrieKey(addrHash, seckey)) defer tds.tMu.Unlock() if !ok { // Not present in the trie, try database if tds.historical { enc, err = tds.db.GetAsOf(dbutils.StorageBucket, dbutils.StorageHistoryBucket, dbutils.GenerateCompositeStorageKey(addrHash, incarnation, seckey), tds.blockNr) if err != nil { enc = nil } } else { enc, err = tds.db.Get(dbutils.StorageBucket, dbutils.GenerateCompositeStorageKey(addrHash, incarnation, seckey)) if err != nil { enc = nil } } } return enc, nil } func (tds *TrieDbState) ReadAccountCode(address common.Address, codeHash common.Hash) (code []byte, err error) { if bytes.Equal(codeHash[:], emptyCodeHash) { return nil, nil } if cached, ok := tds.codeCache.Get(codeHash); ok { code, err = cached.([]byte), nil } else { code, err = tds.db.Get(dbutils.CodeBucket, codeHash[:]) if err == nil { tds.codeSizeCache.Add(codeHash, len(code)) tds.codeCache.Add(codeHash, code) } } if tds.resolveReads { addrHash, err1 := common.HashData(address[:]) if err1 != nil { return nil, err } if _, ok := tds.currentBuffer.accountUpdates[addrHash]; !ok { tds.currentBuffer.accountReads[addrHash] = struct{}{} } tds.pg.ReadCode(codeHash, code) } return code, err } func (tds *TrieDbState) ReadAccountCodeSize(address common.Address, codeHash common.Hash) (codeSize int, err error) { var code []byte if cached, ok := tds.codeSizeCache.Get(codeHash); ok { codeSize, err = cached.(int), nil if tds.resolveReads { if cachedCode, ok := tds.codeCache.Get(codeHash); ok { code, err = cachedCode.([]byte), nil } else { code, err = tds.ReadAccountCode(address, codeHash) if err != nil { return 0, err } } } } else { code, err = tds.ReadAccountCode(address, codeHash) if err != nil { return 0, err } codeSize = len(code) } if tds.resolveReads { addrHash, err1 := common.HashData(address[:]) if err1 != nil { return 0, err } if _, ok := tds.currentBuffer.accountUpdates[addrHash]; !ok { tds.currentBuffer.accountReads[addrHash] = struct{}{} } tds.pg.ReadCode(codeHash, code) } return codeSize, nil } // nextIncarnation determines what should be the next incarnation of an account (i.e. how many time it has existed before at this address) func (tds *TrieDbState) nextIncarnation(addrHash common.Hash) (uint64, error) { var found bool var incarnationBytes [IncarnationLength]byte if tds.historical { // We reserve ethdb.MaxTimestampLength (8) at the end of the key to accomodate any possible timestamp // (timestamp's encoding may have variable length) startkey := make([]byte, common.HashLength+IncarnationLength+common.HashLength+ethdb.MaxTimestampLength) var fixedbits uint = 8 * common.HashLength copy(startkey, addrHash[:]) if err := tds.db.WalkAsOf(dbutils.StorageBucket, dbutils.StorageHistoryBucket, startkey, fixedbits, tds.blockNr, func(k, _ []byte) (bool, error) { copy(incarnationBytes[:], k[common.HashLength:]) found = true return false, nil }); err != nil { return 0, err } } else { startkey := make([]byte, common.HashLength+IncarnationLength+common.HashLength) var fixedbits uint = 8 * common.HashLength copy(startkey, addrHash[:]) if err := tds.db.Walk(dbutils.StorageBucket, startkey, fixedbits, func(k, v []byte) (bool, error) { copy(incarnationBytes[:], k[common.HashLength:]) found = true return false, nil }); err != nil { return 0, err } } if found { return (^uint64(0) ^ binary.BigEndian.Uint64(incarnationBytes[:])) + 1, nil } return 1, nil } var prevMemStats runtime.MemStats type TrieStateWriter struct { tds *TrieDbState } func (tds *TrieDbState) PruneTries(print bool) { tds.tMu.Lock() defer tds.tMu.Unlock() if print { prunableNodes := tds.t.CountPrunableNodes() fmt.Printf("[Before] Actual prunable nodes: %d, accounted: %d\n", prunableNodes, tds.tp.NodeCount()) } tds.tp.PruneTo(tds.t, int(MaxTrieCacheGen)) if print { prunableNodes := tds.t.CountPrunableNodes() fmt.Printf("[After] Actual prunable nodes: %d, accounted: %d\n", prunableNodes, tds.tp.NodeCount()) } var m runtime.MemStats runtime.ReadMemStats(&m) log.Info("Memory", "nodes", tds.tp.NodeCount(), "alloc", int(m.Alloc/1024), "sys", int(m.Sys/1024), "numGC", int(m.NumGC)) if print { fmt.Printf("Pruning done. Nodes: %d, alloc: %d, sys: %d, numGC: %d\n", tds.tp.NodeCount(), int(m.Alloc/1024), int(m.Sys/1024), int(m.NumGC)) } } func (tds *TrieDbState) TrieStateWriter() *TrieStateWriter { return &TrieStateWriter{tds: tds} } func (tds *TrieDbState) DbStateWriter() *DbStateWriter { return &DbStateWriter{tds: tds} } func accountsEqual(a1, a2 *accounts.Account) bool { if a1.Nonce != a2.Nonce { return false } if !a1.Initialised { if a2.Initialised { return false } } else if !a2.Initialised { return false } else if a1.Balance.Cmp(&a2.Balance) != 0 { return false } if a1.Root != a2.Root { return false } if a1.CodeHash == (common.Hash{}) { if a2.CodeHash != (common.Hash{}) { return false } } else if a2.CodeHash == (common.Hash{}) { return false } else if a1.CodeHash != a2.CodeHash { return false } return true } func (tsw *TrieStateWriter) UpdateAccountData(_ context.Context, address common.Address, original, account *accounts.Account) error { addrHash, err := tsw.tds.HashAddress(address, false /*save*/) if err != nil { return err } tsw.tds.currentBuffer.accountUpdates[addrHash] = account return nil } func (tsw *TrieStateWriter) DeleteAccount(_ context.Context, address common.Address, original *accounts.Account) error { addrHash, err := tsw.tds.HashAddress(address, false /*save*/) if err != err { return err } tsw.tds.currentBuffer.accountUpdates[addrHash] = nil delete(tsw.tds.currentBuffer.storageUpdates, addrHash) tsw.tds.currentBuffer.deleted[addrHash] = struct{}{} return nil } func (tsw *TrieStateWriter) UpdateAccountCode(addrHash common.Hash, incarnation uint64, codeHash common.Hash, code []byte) error { if tsw.tds.resolveReads { tsw.tds.pg.CreateCode(codeHash, code) } return nil } func (tsw *TrieStateWriter) WriteAccountStorage(_ context.Context, address common.Address, incarnation uint64, key, original, value *common.Hash) error { addrHash, err := tsw.tds.HashAddress(address, false /*save*/) if err != nil { return err } v := bytes.TrimLeft(value[:], "\x00") m, ok := tsw.tds.currentBuffer.storageUpdates[addrHash] if !ok { m = make(map[common.Hash][]byte) tsw.tds.currentBuffer.storageUpdates[addrHash] = m } seckey, err := tsw.tds.HashKey(key, false /*save*/) if err != nil { return err } if len(v) > 0 { m[seckey] = v } else { m[seckey] = nil } //fmt.Printf("WriteAccountStorage %x %x: %x, buffer %d\n", addrHash, seckey, value, len(tsw.tds.buffers)) return nil } // ExtractWitness produces block witness for the block just been processed, in a serialised form func (tds *TrieDbState) ExtractWitness(trace bool, bin bool) ([]byte, *BlockWitnessStats, error) { bwb := trie.NewBlockWitnessBuilder(trace) var rs *trie.ResolveSet if bin { rs = trie.NewBinaryResolveSet(0) } else { rs = trie.NewResolveSet(0) } touches, storageTouches := tds.pg.ExtractTouches() for _, touch := range touches { rs.AddKey(touch) } for _, touch := range storageTouches { rs.AddKey(touch) } codeMap := tds.pg.ExtractCodeMap() err := tds.makeBlockWitness(bwb, rs, codeMap, bin) if err != nil { return nil, nil, err } var b bytes.Buffer stats, err := bwb.WriteTo(&b) if err != nil { return nil, nil, err } return b.Bytes(), NewBlockWitnessStats(tds.blockNr, uint64(b.Len()), stats), nil } func (tds *TrieDbState) makeBlockWitness(bwb *trie.BlockWitnessBuilder, rs *trie.ResolveSet, codeMap map[common.Hash][]byte, bin bool) error { tds.tMu.Lock() defer tds.tMu.Unlock() if bin { if err := bwb.MakeBlockWitnessBin(trie.HexToBin(tds.t), rs, codeMap); err != nil { return err } } else { if err := bwb.MakeBlockWitness(tds.t, rs, codeMap); err != nil { return err } } return nil } func (tsw *TrieStateWriter) CreateContract(address common.Address) error { addrHash, err := tsw.tds.HashAddress(address, true /*save*/) if err != nil { return err } tsw.tds.currentBuffer.created[addrHash] = struct{}{} incarnation, err := tsw.tds.nextIncarnation(addrHash) if err != nil { return err } if account, ok := tsw.tds.currentBuffer.accountUpdates[addrHash]; ok && account != nil { account.SetIncarnation(incarnation) } return nil } func (tds *TrieDbState) TriePruningDebugDump() string { return tds.tp.DebugDump() } func (tds *TrieDbState) getBlockNr() uint64 { return atomic.LoadUint64(&tds.blockNr) } func (tds *TrieDbState) setBlockNr(n uint64) { atomic.StoreUint64(&tds.blockNr, n) }
1
21,300
non contract incarnation
ledgerwatch-erigon
go
@@ -108,10 +108,7 @@ class ErrorHandler(object): message = value["value"] if not isinstance(message, basestring): value = message - try: - message = message['message'] - except TypeError: - message = None + message = message.get('message', None) else: message = value.get('message', None) except ValueError:
1
# Licensed to the Software Freedom Conservancy (SFC) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The SFC licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from selenium.common.exceptions import (ElementNotInteractableException, ElementNotSelectableException, ElementNotVisibleException, ErrorInResponseException, InvalidElementStateException, InvalidSelectorException, ImeNotAvailableException, ImeActivationFailedException, MoveTargetOutOfBoundsException, NoSuchElementException, NoSuchFrameException, NoSuchWindowException, NoAlertPresentException, StaleElementReferenceException, TimeoutException, UnexpectedAlertPresentException, WebDriverException) try: basestring except NameError: # Python 3.x basestring = str class ErrorCode(object): """ Error codes defined in the WebDriver wire protocol. """ # Keep in sync with org.openqa.selenium.remote.ErrorCodes and errorcodes.h SUCCESS = 0 NO_SUCH_ELEMENT = [7, 'no such element'] NO_SUCH_FRAME = [8, 'no such frame'] UNKNOWN_COMMAND = [9, 'unknown command'] STALE_ELEMENT_REFERENCE = [10, 'stale element reference'] ELEMENT_NOT_VISIBLE = [11, 'element not visible'] INVALID_ELEMENT_STATE = [12, 'invalid element state'] UNKNOWN_ERROR = [13, 'unknown error'] ELEMENT_NOT_INTERACTABLE = ["element not interactable"] ELEMENT_IS_NOT_SELECTABLE = [15, 'element not selectable'] JAVASCRIPT_ERROR = [17, 'javascript error'] XPATH_LOOKUP_ERROR = [19, 'invalid selector'] TIMEOUT = [21, 'timeout'] NO_SUCH_WINDOW = [23, 'no such window'] INVALID_COOKIE_DOMAIN = [24, 'invalid cookie domain'] UNABLE_TO_SET_COOKIE = [25, 'unable to set cookie'] UNEXPECTED_ALERT_OPEN = [26, 'unexpected alert open'] NO_ALERT_OPEN = [27, 'no such alert'] SCRIPT_TIMEOUT = [28, 'script timeout'] INVALID_ELEMENT_COORDINATES = [29, 'invalid element coordinates'] IME_NOT_AVAILABLE = [30, 'ime not available'] IME_ENGINE_ACTIVATION_FAILED = [31, 'ime engine activation failed'] INVALID_SELECTOR = [32, 'invalid selector'] MOVE_TARGET_OUT_OF_BOUNDS = [34, 'move target out of bounds'] INVALID_XPATH_SELECTOR = [51, 'invalid selector'] INVALID_XPATH_SELECTOR_RETURN_TYPER = [52, 'invalid selector'] METHOD_NOT_ALLOWED = [405, 'unsupported operation'] class ErrorHandler(object): """ Handles errors returned by the WebDriver server. """ def check_response(self, response): """ Checks that a JSON response from the WebDriver does not have an error. :Args: - response - The JSON response from the WebDriver server as a dictionary object. :Raises: If the response contains an error message. """ status = response.get('status', None) if status is None or status == ErrorCode.SUCCESS: return value = None message = response.get("message", "") screen = response.get("screen", "") stacktrace = None if isinstance(status, int): value_json = response.get('value', None) if value_json and isinstance(value_json, basestring): import json try: value = json.loads(value_json) if len(value.keys()) == 1: value = value['value'] status = value.get('error', None) if status is None: status = value["status"] message = value["value"] if not isinstance(message, basestring): value = message try: message = message['message'] except TypeError: message = None else: message = value.get('message', None) except ValueError: pass exception_class = ErrorInResponseException if status in ErrorCode.NO_SUCH_ELEMENT: exception_class = NoSuchElementException elif status in ErrorCode.NO_SUCH_FRAME: exception_class = NoSuchFrameException elif status in ErrorCode.NO_SUCH_WINDOW: exception_class = NoSuchWindowException elif status in ErrorCode.STALE_ELEMENT_REFERENCE: exception_class = StaleElementReferenceException elif status in ErrorCode.ELEMENT_NOT_VISIBLE: exception_class = ElementNotVisibleException elif status in ErrorCode.INVALID_ELEMENT_STATE: exception_class = InvalidElementStateException elif status in ErrorCode.INVALID_SELECTOR \ or status in ErrorCode.INVALID_XPATH_SELECTOR \ or status in ErrorCode.INVALID_XPATH_SELECTOR_RETURN_TYPER: exception_class = InvalidSelectorException elif status in ErrorCode.ELEMENT_IS_NOT_SELECTABLE: exception_class = ElementNotSelectableException elif status in ErrorCode.ELEMENT_NOT_INTERACTABLE: exception_class = ElementNotInteractableException elif status in ErrorCode.INVALID_COOKIE_DOMAIN: exception_class = WebDriverException elif status in ErrorCode.UNABLE_TO_SET_COOKIE: exception_class = WebDriverException elif status in ErrorCode.TIMEOUT: exception_class = TimeoutException elif status in ErrorCode.SCRIPT_TIMEOUT: exception_class = TimeoutException elif status in ErrorCode.UNKNOWN_ERROR: exception_class = WebDriverException elif status in ErrorCode.UNEXPECTED_ALERT_OPEN: exception_class = UnexpectedAlertPresentException elif status in ErrorCode.NO_ALERT_OPEN: exception_class = NoAlertPresentException elif status in ErrorCode.IME_NOT_AVAILABLE: exception_class = ImeNotAvailableException elif status in ErrorCode.IME_ENGINE_ACTIVATION_FAILED: exception_class = ImeActivationFailedException elif status in ErrorCode.MOVE_TARGET_OUT_OF_BOUNDS: exception_class = MoveTargetOutOfBoundsException else: exception_class = WebDriverException if value == '' or value is None: value = response['value'] if isinstance(value, basestring): if exception_class == ErrorInResponseException: raise exception_class(response, value) raise exception_class(value) if message == "" and 'message' in value: message = value['message'] screen = None if 'screen' in value: screen = value['screen'] stacktrace = None if 'stackTrace' in value and value['stackTrace']: stacktrace = [] try: for frame in value['stackTrace']: line = self._value_or_default(frame, 'lineNumber', '') file = self._value_or_default(frame, 'fileName', '<anonymous>') if line: file = "%s:%s" % (file, line) meth = self._value_or_default(frame, 'methodName', '<anonymous>') if 'className' in frame: meth = "%s.%s" % (frame['className'], meth) msg = " at %s (%s)" msg = msg % (meth, file) stacktrace.append(msg) except TypeError: pass if exception_class == ErrorInResponseException: raise exception_class(response, message) elif exception_class == UnexpectedAlertPresentException and 'alert' in value: raise exception_class(message, screen, stacktrace, value['alert'].get('text')) raise exception_class(message, screen, stacktrace) def _value_or_default(self, obj, key, default): return obj[key] if key in obj else default
1
14,481
I would recommend to leave out `None` because None is already the default.
SeleniumHQ-selenium
java
@@ -90,11 +90,11 @@ func (h *Handler) handleNewStream(s net.Stream) { switch err := h.processHelloMessage(from, &hello); err { case ErrBadGenesis: - log.Warningf("genesis cid: %s does not match: %s, disconnecting from peer: %s", &hello.GenesisHash, h.genesis, from) + log.Debugf("genesis cid: %s does not match: %s, disconnecting from peer: %s", &hello.GenesisHash, h.genesis, from) s.Conn().Close() // nolint: errcheck return case ErrWrongVersion: - log.Warningf("code not at same version: peer has version %s, daemon has version %s, disconnecting from peer: %s", hello.CommitSha, h.commitSha, from) + log.Debugf("code not at same version: peer has version %s, daemon has version %s, disconnecting from peer: %s", hello.CommitSha, h.commitSha, from) s.Conn().Close() // nolint: errcheck return case nil: // ok, noop
1
package hello import ( "context" "fmt" "time" cid "github.com/ipfs/go-cid" cbor "github.com/ipfs/go-ipld-cbor" logging "github.com/ipfs/go-log" host "github.com/libp2p/go-libp2p-host" net "github.com/libp2p/go-libp2p-net" peer "github.com/libp2p/go-libp2p-peer" ma "github.com/multiformats/go-multiaddr" cbu "github.com/filecoin-project/go-filecoin/cborutil" "github.com/filecoin-project/go-filecoin/types" ) func init() { cbor.RegisterCborType(Message{}) } // Protocol is the libp2p protocol identifier for the hello protocol. const protocol = "/fil/hello/1.0.0" var log = logging.Logger("/fil/hello") // Message is the data structure of a single message in the hello protocol. type Message struct { HeaviestTipSetCids []cid.Cid HeaviestTipSetHeight uint64 GenesisHash cid.Cid CommitSha string } type syncCallback func(from peer.ID, cids []cid.Cid, height uint64) type getTipSetFunc func() (*types.TipSet, error) // Handler implements the 'Hello' protocol handler. Upon connecting to a new // node, we send them a message containing some information about the state of // our chain, and receive the same information from them. This is used to // initiate a chainsync and detect connections to forks. type Handler struct { host host.Host genesis cid.Cid // chainSyncCB is called when new peers tell us about their chain chainSyncCB syncCallback // is used to retrieve the current heaviest tipset // for filling out our hello messages. getHeaviestTipSet getTipSetFunc net string commitSha string } // New creates a new instance of the hello protocol and registers it to // the given host, with the provided callbacks. func New(h host.Host, gen cid.Cid, syncCallback syncCallback, getHeaviestTipSet getTipSetFunc, net string, commitSha string) *Handler { hello := &Handler{ host: h, genesis: gen, chainSyncCB: syncCallback, getHeaviestTipSet: getHeaviestTipSet, net: net, commitSha: commitSha, } h.SetStreamHandler(protocol, hello.handleNewStream) // register for connection notifications h.Network().Notify((*helloNotify)(hello)) return hello } func (h *Handler) handleNewStream(s net.Stream) { defer s.Close() // nolint: errcheck from := s.Conn().RemotePeer() var hello Message if err := cbu.NewMsgReader(s).ReadMsg(&hello); err != nil { log.Warningf("bad hello message from peer %s: %s", from, err) return } switch err := h.processHelloMessage(from, &hello); err { case ErrBadGenesis: log.Warningf("genesis cid: %s does not match: %s, disconnecting from peer: %s", &hello.GenesisHash, h.genesis, from) s.Conn().Close() // nolint: errcheck return case ErrWrongVersion: log.Warningf("code not at same version: peer has version %s, daemon has version %s, disconnecting from peer: %s", hello.CommitSha, h.commitSha, from) s.Conn().Close() // nolint: errcheck return case nil: // ok, noop default: log.Error(err) } } // ErrBadGenesis is the error returned when a mismatch in genesis blocks happens. var ErrBadGenesis = fmt.Errorf("bad genesis block") // ErrWrongVersion is the error returned when a mismatch in the code version happens. var ErrWrongVersion = fmt.Errorf("code version mismatch") func (h *Handler) processHelloMessage(from peer.ID, msg *Message) error { if !msg.GenesisHash.Equals(h.genesis) { return ErrBadGenesis } if (h.net == "devnet-test" || h.net == "devnet-user") && msg.CommitSha != h.commitSha { return ErrWrongVersion } h.chainSyncCB(from, msg.HeaviestTipSetCids, msg.HeaviestTipSetHeight) return nil } func (h *Handler) getOurHelloMessage() *Message { heaviest, err := h.getHeaviestTipSet() if err != nil { panic("cannot fetch chain head") } height, err := heaviest.Height() if err != nil { panic("somehow heaviest tipset is empty") } return &Message{ GenesisHash: h.genesis, HeaviestTipSetCids: heaviest.ToSortedCidSet().ToSlice(), HeaviestTipSetHeight: height, CommitSha: h.commitSha, } } func (h *Handler) sayHello(ctx context.Context, p peer.ID) error { s, err := h.host.NewStream(ctx, p, protocol) if err != nil { return err } defer s.Close() // nolint: errcheck msg := h.getOurHelloMessage() return cbu.NewMsgWriter(s).WriteMsg(&msg) } // New peer connection notifications type helloNotify Handler func (hn *helloNotify) hello() *Handler { return (*Handler)(hn) } const helloTimeout = time.Second * 10 func (hn *helloNotify) Connected(n net.Network, c net.Conn) { go func() { ctx, cancel := context.WithTimeout(context.Background(), helloTimeout) defer cancel() p := c.RemotePeer() if err := hn.hello().sayHello(ctx, p); err != nil { log.Warningf("failed to send hello handshake to peer %s: %s", p, err) } }() } func (hn *helloNotify) Listen(n net.Network, a ma.Multiaddr) {} func (hn *helloNotify) ListenClose(n net.Network, a ma.Multiaddr) {} func (hn *helloNotify) Disconnected(n net.Network, c net.Conn) {} func (hn *helloNotify) OpenedStream(n net.Network, s net.Stream) {} func (hn *helloNotify) ClosedStream(n net.Network, s net.Stream) {}
1
18,915
Should the "bad hello message" case above also disconnect?
filecoin-project-venus
go
@@ -18,6 +18,9 @@ public abstract class InsulinOrefBasePlugin implements PluginBase, InsulinInterf public static double MIN_DIA = 5; + protected static boolean fragmentEnabled = false; + protected static boolean fragmentVisible = false; + long lastWarned = 0; @Override
1
package info.nightscout.androidaps.plugins.InsulinOrefCurves; import info.nightscout.androidaps.Constants; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import info.nightscout.androidaps.data.Iob; import info.nightscout.androidaps.db.Treatment; import info.nightscout.androidaps.interfaces.InsulinInterface; import info.nightscout.androidaps.interfaces.PluginBase; import info.nightscout.androidaps.plugins.Overview.Notification; import info.nightscout.androidaps.plugins.Overview.events.EventNewNotification; /** * Created by adrian on 13.08.2017. */ public abstract class InsulinOrefBasePlugin implements PluginBase, InsulinInterface { public static double MIN_DIA = 5; long lastWarned = 0; @Override public int getType() { return INSULIN; } @Override public String getNameShort() { return MainApp.sResources.getString(R.string.insulin_shortname); } @Override public boolean canBeHidden(int type) { return true; } @Override public boolean hasFragment() { return true; } @Override public boolean showInList(int type) { return true; } @Override public double getDia() { double dia = getUserDefinedDia(); if(dia >= MIN_DIA){ return dia; } else { if((System.currentTimeMillis() - lastWarned) > 60*1000) { lastWarned = System.currentTimeMillis(); Notification notification = new Notification(Notification.SHORT_DIA, String.format(MainApp.sResources.getString(R.string.dia_too_short), dia, MIN_DIA), Notification.URGENT); MainApp.bus().post(new EventNewNotification(notification)); } return MIN_DIA; } } public double getUserDefinedDia() { return MainApp.getConfigBuilder().getProfile() != null ? MainApp.getConfigBuilder().getProfile().getDia() : Constants.defaultDIA; } @Override public Iob iobCalcForTreatment(Treatment treatment, long time, Double dia) { Iob result = new Iob(); int peak = getPeak(); if (treatment.insulin != 0d) { long bolusTime = treatment.date; double t = (time - bolusTime) / 1000d / 60d; double td = getDia()*60; //getDIA() always > 5 double tp = peak; // force the IOB to 0 if over DIA hours have passed if (t < td) { double tau = tp * (1 - tp / td) / (1 - 2 * tp / td); double a = 2 * tau / td; double S = 1 / (1 - a + (1 + a) * Math.exp(-td / tau)); result.activityContrib = treatment.insulin * (S / Math.pow(tau, 2)) * t * (1 - t / td) * Math.exp(-t / tau); result.iobContrib = treatment.insulin * (1 - S * (1 - a) * ((Math.pow(t, 2) / (tau * td * (1 - a)) - t / tau - 1) * Math.exp(-t / tau) + 1)); } } return result; } @Override public String getComment() { String comment = commentStandardText(); double userDia = getUserDefinedDia(); if(userDia < MIN_DIA){ comment += "\n" + String.format(MainApp.sResources.getString(R.string.dia_too_short), userDia, MIN_DIA); } return comment; } abstract int getPeak(); abstract String commentStandardText(); }
1
29,535
Shouldn't this be in the child and not in the base plugin? Wouldn't having it here enable all derived plugins at once?
MilosKozak-AndroidAPS
java
@@ -226,6 +226,11 @@ FILTERING (options[:full_description] ||= []) << Regexp.compile(Regexp.escape(o)) end + parser.on('-E', '--example-matches STRING', "Run examples whose full nested names match REGEX (may be", + " used more than once)") do |o| + (options[:full_description] ||= []) << Regexp.compile(o) + end + parser.on('-t', '--tag TAG[:VALUE]', 'Run examples with the specified tag, or exclude examples', 'by adding ~ before the tag.',
1
# http://www.ruby-doc.org/stdlib/libdoc/optparse/rdoc/classes/OptionParser.html require 'optparse' module RSpec::Core # @private class Parser def self.parse(args, source=nil) new(args).parse(source) end attr_reader :original_args def initialize(original_args) @original_args = original_args end def parse(source=nil) return { :files_or_directories_to_run => [] } if original_args.empty? args = original_args.dup options = args.delete('--tty') ? { :tty => true } : {} begin parser(options).parse!(args) rescue OptionParser::InvalidOption => e failure = e.message failure << " (defined in #{source})" if source abort "#{failure}\n\nPlease use --help for a listing of valid options" end options[:files_or_directories_to_run] = args options end private # rubocop:disable MethodLength # rubocop:disable Metrics/AbcSize # rubocop:disable CyclomaticComplexity # rubocop:disable PerceivedComplexity def parser(options) OptionParser.new do |parser| parser.summary_width = 34 parser.banner = "Usage: rspec [options] [files or directories]\n\n" parser.on('-I PATH', 'Specify PATH to add to $LOAD_PATH (may be used more than once).') do |dirs| options[:libs] ||= [] options[:libs].concat(dirs.split(File::PATH_SEPARATOR)) end parser.on('-r', '--require PATH', 'Require a file.') do |path| options[:requires] ||= [] options[:requires] << path end parser.on('-O', '--options PATH', 'Specify the path to a custom options file.') do |path| options[:custom_options_file] = path end parser.on('--order TYPE[:SEED]', 'Run examples by the specified order type.', ' [defined] examples and groups are run in the order they are defined', ' [rand] randomize the order of groups and examples', ' [random] alias for rand', ' [random:SEED] e.g. --order random:123') do |o| options[:order] = o end parser.on('--seed SEED', Integer, 'Equivalent of --order rand:SEED.') do |seed| options[:order] = "rand:#{seed}" end parser.on('--bisect[=verbose]', 'Repeatedly runs the suite in order to isolate the failures to the ', ' smallest reproducible case.') do |argument| options[:bisect] = argument || true options[:runner] = RSpec::Core::Invocations::Bisect.new end parser.on('--[no-]fail-fast[=COUNT]', 'Abort the run after a certain number of failures (1 by default).') do |argument| if argument == true value = 1 elsif argument == false || argument == 0 value = false else begin value = Integer(argument) rescue ArgumentError RSpec.warning "Expected an integer value for `--fail-fast`, got: #{argument.inspect}", :call_site => nil end end set_fail_fast(options, value) end parser.on('--failure-exit-code CODE', Integer, 'Override the exit code used when there are failing specs.') do |code| options[:failure_exit_code] = code end parser.on('-X', '--[no-]drb', 'Run examples via DRb.') do |use_drb| options[:drb] = use_drb options[:runner] = RSpec::Core::Invocations::DRbWithFallback.new if use_drb end parser.on('--drb-port PORT', 'Port to connect to the DRb server.') do |o| options[:drb_port] = o.to_i end parser.separator("\n **** Output ****\n\n") parser.on('-f', '--format FORMATTER', 'Choose a formatter.', ' [p]rogress (default - dots)', ' [d]ocumentation (group and example names)', ' [h]tml', ' [j]son', ' custom formatter class name') do |o| options[:formatters] ||= [] options[:formatters] << [o] end parser.on('-o', '--out FILE', 'Write output to a file instead of $stdout. This option applies', ' to the previously specified --format, or the default format', ' if no format is specified.' ) do |o| options[:formatters] ||= [['progress']] options[:formatters].last << o end parser.on('--deprecation-out FILE', 'Write deprecation warnings to a file instead of $stderr.') do |file| options[:deprecation_stream] = file end parser.on('-b', '--backtrace', 'Enable full backtrace.') do |_o| options[:full_backtrace] = true end parser.on('-c', '--color', '--colour', '') do |_o| # flag will be excluded from `--help` output because it is deprecated options[:color] = true options[:color_mode] = :automatic end parser.on('--force-color', '--force-colour', 'Force the output to be in color, even if the output is not a TTY') do |_o| if options[:color_mode] == :off abort "Please only use one of `--force-color` and `--no-color`" end options[:color_mode] = :on end parser.on('--no-color', '--no-colour', 'Force the output to not be in color, even if the output is a TTY') do |_o| if options[:color_mode] == :on abort "Please only use one of --force-color and --no-color" end options[:color_mode] = :off end parser.on('-p', '--[no-]profile [COUNT]', 'Enable profiling of examples and list the slowest examples (default: 10).') do |argument| options[:profile_examples] = if argument.nil? true elsif argument == false false else begin Integer(argument) rescue ArgumentError RSpec.warning "Non integer specified as profile count, separate " \ "your path from options with -- e.g. " \ "`rspec --profile -- #{argument}`", :call_site => nil true end end end parser.on('--dry-run', 'Print the formatter output of your suite without', ' running any examples or hooks') do |_o| options[:dry_run] = true end parser.on('-w', '--warnings', 'Enable ruby warnings') do $VERBOSE = true end parser.separator <<-FILTERING **** Filtering/tags **** In addition to the following options for selecting specific files, groups, or examples, you can select individual examples by appending the line number(s) to the filename: rspec path/to/a_spec.rb:37:87 You can also pass example ids enclosed in square brackets: rspec path/to/a_spec.rb[1:5,1:6] # run the 5th and 6th examples/groups defined in the 1st group FILTERING parser.on('--only-failures', "Filter to just the examples that failed the last time they ran.") do configure_only_failures(options) end parser.on("-n", "--next-failure", "Apply `--only-failures` and abort after one failure.", " (Equivalent to `--only-failures --fail-fast --order defined`)") do configure_only_failures(options) set_fail_fast(options, 1) options[:order] ||= 'defined' end parser.on('-P', '--pattern PATTERN', 'Load files matching pattern (default: "spec/**/*_spec.rb").') do |o| if options[:pattern] options[:pattern] += ',' + o else options[:pattern] = o end end parser.on('--exclude-pattern PATTERN', 'Load files except those matching pattern. Opposite effect of --pattern.') do |o| options[:exclude_pattern] = o end parser.on('-e', '--example STRING', "Run examples whose full nested names include STRING (may be", " used more than once)") do |o| (options[:full_description] ||= []) << Regexp.compile(Regexp.escape(o)) end parser.on('-t', '--tag TAG[:VALUE]', 'Run examples with the specified tag, or exclude examples', 'by adding ~ before the tag.', ' - e.g. ~slow', ' - TAG is always converted to a symbol') do |tag| filter_type = tag =~ /^~/ ? :exclusion_filter : :inclusion_filter name, value = tag.gsub(/^(~@|~|@)/, '').split(':', 2) name = name.to_sym parsed_value = case value when nil then true # The default value for tags is true when 'true' then true when 'false' then false when 'nil' then nil when /^:/ then value[1..-1].to_sym when /^\d+$/ then Integer(value) when /^\d+.\d+$/ then Float(value) else value end add_tag_filter(options, filter_type, name, parsed_value) end parser.on('--default-path PATH', 'Set the default path where RSpec looks for examples (can', ' be a path to a file or a directory).') do |path| options[:default_path] = path end parser.separator("\n **** Utility ****\n\n") parser.on('--init', 'Initialize your project with RSpec.') do |_cmd| options[:runner] = RSpec::Core::Invocations::InitializeProject.new end parser.on('-v', '--version', 'Display the version.') do options[:runner] = RSpec::Core::Invocations::PrintVersion.new end # These options would otherwise be confusing to users, so we forcibly # prevent them from executing. # # * --I is too similar to -I. # * -d was a shorthand for --debugger, which is removed, but now would # trigger --default-path. invalid_options = %w[-d --I] hidden_options = invalid_options + %w[-c] parser.on_tail('-h', '--help', "You're looking at it.") do options[:runner] = RSpec::Core::Invocations::PrintHelp.new(parser, hidden_options) end # This prevents usage of the invalid_options. invalid_options.each do |option| parser.on(option) do raise OptionParser::InvalidOption.new end end end end # rubocop:enable Metrics/AbcSize # rubocop:enable MethodLength # rubocop:enable CyclomaticComplexity # rubocop:enable PerceivedComplexity def add_tag_filter(options, filter_type, tag_name, value=true) (options[filter_type] ||= {})[tag_name] = value end def set_fail_fast(options, value) options[:fail_fast] = value end def configure_only_failures(options) options[:only_failures] = true add_tag_filter(options, :inclusion_filter, :last_run_status, 'failed') end end end
1
17,155
Should probably say REGEX or PATTERN rather than string.
rspec-rspec-core
rb
@@ -179,14 +179,14 @@ func TestHandler(t *testing.T) { name: "an event with a very large payload", method: "POST", path: "/ns1/broker1", - event: createTestEventWithPayloadSize("test-event", 110000000), + event: createTestEventWithPayloadSize("test-event", 10000001), // 10Mb + extra byte wantCode: nethttp.StatusRequestEntityTooLarge, }, { name: "malicious requests or requests with unknown Content-Length and a very large payload", method: "POST", path: "/ns1/broker1", - event: createTestEventWithPayloadSize("test-event", 110000000), + event: createTestEventWithPayloadSize("test-event", 10000001), // 10Mb + extra byte contentLength: ptr.Int64(-1), wantCode: nethttp.StatusRequestEntityTooLarge, },
1
/* Copyright 2020 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package ingress import ( "bytes" "context" "encoding/json" "fmt" nethttp "net/http" "net/http/httptest" "testing" "time" "math/rand" "cloud.google.com/go/pubsub" "cloud.google.com/go/pubsub/pstest" cepubsub "github.com/cloudevents/sdk-go/protocol/pubsub/v2" cev2 "github.com/cloudevents/sdk-go/v2" cloudevents "github.com/cloudevents/sdk-go/v2" "github.com/cloudevents/sdk-go/v2/binding" cecontext "github.com/cloudevents/sdk-go/v2/context" "github.com/cloudevents/sdk-go/v2/extensions" "github.com/cloudevents/sdk-go/v2/protocol" "github.com/cloudevents/sdk-go/v2/protocol/http" "github.com/google/knative-gcp/pkg/broker/config" "github.com/google/knative-gcp/pkg/broker/config/memory" "github.com/google/knative-gcp/pkg/metrics" reportertest "github.com/google/knative-gcp/pkg/metrics/testing" kgcptesting "github.com/google/knative-gcp/pkg/testing" "go.uber.org/zap" "go.uber.org/zap/zaptest" "google.golang.org/api/option" "google.golang.org/api/support/bundler" "google.golang.org/grpc" "k8s.io/apimachinery/pkg/types" "knative.dev/eventing/pkg/kncloudevents" "knative.dev/pkg/logging" logtest "knative.dev/pkg/logging/testing" "knative.dev/pkg/metrics/metricskey" "knative.dev/pkg/metrics/metricstest" "knative.dev/pkg/ptr" _ "knative.dev/pkg/metrics/testing" ) const ( projectID = "testproject" topicID = "topic1" subscriptionID = "subscription1" traceID = "4bf92f3577b34da6a3ce929d0e0e4736" eventType = "google.cloud.scheduler.job.v1.executed" pod = "testpod" container = "testcontainer" ) var brokerConfig = &config.TargetsConfig{ Brokers: map[string]*config.Broker{ "ns1/broker1": { Id: "b-uid-1", Name: "broker1", Namespace: "ns1", DecoupleQueue: &config.Queue{Topic: topicID, State: config.State_READY}, }, "ns2/broker2": { Id: "b-uid-2", Name: "broker2", Namespace: "ns2", DecoupleQueue: nil, }, "ns3/broker3": { Id: "b-uid-3", Name: "broker3", Namespace: "ns3", DecoupleQueue: &config.Queue{Topic: ""}, }, "ns4/broker4": { Id: "b-uid-4", Name: "broker4", Namespace: "ns4", DecoupleQueue: &config.Queue{Topic: "topic4", State: config.State_UNKNOWN}, }, }, } type eventAssertion func(*testing.T, *cloudevents.Event) type testCase struct { name string // in happy case, path should match the /<ns>/<broker> in the brokerConfig. path string event *cloudevents.Event // If method is empty, POST will be used as default. method string // body and header can be specified if the client is making raw HTTP request instead of via cloudevents. body map[string]string header nethttp.Header wantCode int wantMetricTags map[string]string wantEventCount int64 // additional assertions on the output event. eventAssertions []eventAssertion decouple DecoupleSink contentLength *int64 } type fakeOverloadedDecoupleSink struct{} func (m *fakeOverloadedDecoupleSink) Send(ctx context.Context, broker types.NamespacedName, event cev2.Event) protocol.Result { return bundler.ErrOverflow } func TestHandler(t *testing.T) { tests := []testCase{ { name: "health check", path: "/healthz", method: nethttp.MethodGet, wantCode: nethttp.StatusOK, }, { name: "happy case", path: "/ns1/broker1", event: createTestEvent("test-event"), wantCode: nethttp.StatusAccepted, wantEventCount: 1, wantMetricTags: map[string]string{ metricskey.LabelEventType: eventType, metricskey.LabelResponseCode: "202", metricskey.LabelResponseCodeClass: "2xx", metricskey.PodName: pod, metricskey.ContainerName: container, }, eventAssertions: []eventAssertion{assertExtensionsExist(EventArrivalTime)}, }, { name: "trace context", path: "/ns1/broker1", event: createTestEvent("test-event"), wantCode: nethttp.StatusAccepted, header: nethttp.Header{ "Traceparent": {fmt.Sprintf("00-%s-00f067aa0ba902b7-01", traceID)}, }, wantEventCount: 1, wantMetricTags: map[string]string{ metricskey.LabelEventType: eventType, metricskey.LabelResponseCode: "202", metricskey.LabelResponseCodeClass: "2xx", metricskey.PodName: pod, metricskey.ContainerName: container, }, eventAssertions: []eventAssertion{assertExtensionsExist(EventArrivalTime), assertTraceID(traceID)}, }, { name: "valid event but unsupported http method", method: "PUT", path: "/ns1/broker1", event: createTestEvent("test-event"), wantCode: nethttp.StatusMethodNotAllowed, }, { name: "an event with a very large payload", method: "POST", path: "/ns1/broker1", event: createTestEventWithPayloadSize("test-event", 110000000), wantCode: nethttp.StatusRequestEntityTooLarge, }, { name: "malicious requests or requests with unknown Content-Length and a very large payload", method: "POST", path: "/ns1/broker1", event: createTestEventWithPayloadSize("test-event", 110000000), contentLength: ptr.Int64(-1), wantCode: nethttp.StatusRequestEntityTooLarge, }, { name: "malformed path", path: "/ns1/broker1/and/something/else", event: createTestEvent("test-event"), wantCode: nethttp.StatusNotFound, }, { name: "request is not an event", path: "/ns1/broker1", wantCode: nethttp.StatusBadRequest, header: nethttp.Header{}, }, { name: "wrong path - broker doesn't exist in given namespace", path: "/ns1/broker-not-exist", event: createTestEvent("test-event"), wantCode: nethttp.StatusNotFound, wantEventCount: 1, wantMetricTags: map[string]string{ metricskey.LabelEventType: eventType, metricskey.LabelResponseCode: "404", metricskey.LabelResponseCodeClass: "4xx", metricskey.PodName: pod, metricskey.ContainerName: container, }, }, { name: "wrong path - namespace doesn't exist", path: "/ns-not-exist/broker1", event: createTestEvent("test-event"), wantCode: nethttp.StatusNotFound, wantEventCount: 1, wantMetricTags: map[string]string{ metricskey.LabelEventType: eventType, metricskey.LabelResponseCode: "404", metricskey.LabelResponseCodeClass: "4xx", metricskey.PodName: pod, metricskey.ContainerName: container, }, }, { name: "decouple queue not ready", path: "/ns4/broker4", event: createTestEvent("test-event"), wantCode: nethttp.StatusServiceUnavailable, wantEventCount: 1, wantMetricTags: map[string]string{ metricskey.LabelEventType: eventType, metricskey.LabelResponseCode: "503", metricskey.LabelResponseCodeClass: "5xx", metricskey.PodName: pod, metricskey.ContainerName: container, }, }, { name: "broker queue is nil", path: "/ns2/broker2", event: createTestEvent("test-event"), wantCode: nethttp.StatusInternalServerError, wantEventCount: 1, wantMetricTags: map[string]string{ metricskey.LabelEventType: eventType, metricskey.LabelResponseCode: "500", metricskey.LabelResponseCodeClass: "5xx", metricskey.PodName: pod, metricskey.ContainerName: container, }, }, { name: "broker queue topic is empty", path: "/ns3/broker3", event: createTestEvent("test-event"), wantCode: nethttp.StatusInternalServerError, wantEventCount: 1, wantMetricTags: map[string]string{ metricskey.LabelEventType: eventType, metricskey.LabelResponseCode: "500", metricskey.LabelResponseCodeClass: "5xx", metricskey.PodName: pod, metricskey.ContainerName: container, }, }, { name: "pubsub overloaded", path: "/ns1/broker1", event: createTestEvent("test-event"), wantCode: nethttp.StatusTooManyRequests, wantEventCount: 1, wantMetricTags: map[string]string{ metricskey.LabelEventType: eventType, metricskey.LabelResponseCode: "429", metricskey.LabelResponseCodeClass: "4xx", metricskey.PodName: pod, metricskey.ContainerName: container, }, decouple: &fakeOverloadedDecoupleSink{}, }, } client := nethttp.Client{} defer client.CloseIdleConnections() for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { reportertest.ResetIngressMetrics() ctx := logging.WithLogger(context.Background(), logtest.TestLogger(t)) ctx, cancel := context.WithTimeout(ctx, 3*time.Second) defer cancel() psSrv := pstest.NewServer() defer psSrv.Close() decouple := tc.decouple if decouple == nil { decouple = NewMultiTopicDecoupleSink(ctx, memory.NewTargets(brokerConfig), createPubsubClient(ctx, t, psSrv), pubsub.DefaultPublishSettings) } url := createAndStartIngress(ctx, t, psSrv, decouple) rec := setupTestReceiver(ctx, t, psSrv) req := createRequest(tc, url) if tc.contentLength != nil { req.ContentLength = *tc.contentLength } res, err := client.Do(req) if err != nil { t.Fatalf("Unexpected error from http client: %v", err) } if res.StatusCode != tc.wantCode { t.Errorf("StatusCode mismatch. got: %v, want: %v", res.StatusCode, tc.wantCode) } verifyMetrics(t, tc) // If event is accepted, check that it's stored in the decouple sink. if res.StatusCode == nethttp.StatusAccepted { m, err := rec.Receive(ctx) if err != nil { t.Fatal(err) } savedToSink, err := binding.ToEvent(ctx, m) if err != nil { t.Fatal(err) } // Retrieve the event from the decouple sink. if tc.event.ID() != savedToSink.ID() { t.Errorf("Event ID mismatch. got: %v, want: %v", savedToSink.ID(), tc.event.ID()) } if savedToSink.Time().IsZero() { t.Errorf("Saved event should be decorated with timestamp, got zero.") } for _, assertion := range tc.eventAssertions { assertion(t, savedToSink) } } select { case <-ctx.Done(): t.Fatalf("test cancelled or timed out: %v", ctx.Err()) default: } }) } } func BenchmarkIngressHandler(b *testing.B) { for _, eventSize := range kgcptesting.BenchmarkEventSizes { b.Run(fmt.Sprintf("%d bytes", eventSize), func(b *testing.B) { runIngressHandlerBenchmark(b, eventSize) }) } } func runIngressHandlerBenchmark(b *testing.B, eventSize int) { reportertest.ResetIngressMetrics() ctx := logging.WithLogger(context.Background(), zaptest.NewLogger(b, zaptest.WrapOptions(zap.AddCaller()), zaptest.Level(zap.WarnLevel), ).Sugar()) psSrv := pstest.NewServer() defer psSrv.Close() psClient := createPubsubClient(ctx, b, psSrv) decouple := NewMultiTopicDecoupleSink(ctx, memory.NewTargets(brokerConfig), psClient, pubsub.DefaultPublishSettings) statsReporter, err := metrics.NewIngressReporter(metrics.PodName(pod), metrics.ContainerName(container)) if err != nil { b.Fatal(err) } h := NewHandler(ctx, nil, decouple, statsReporter) if _, err := psClient.CreateTopic(ctx, topicID); err != nil { b.Fatal(err) } message := binding.ToMessage(kgcptesting.NewTestEvent(b, eventSize)) // Set parallelism to 32 so that the benchmark is not limited by the Pub/Sub publish latency // over gRPC. b.SetParallelism(32) b.ResetTimer() b.RunParallel(func(pb *testing.PB) { for pb.Next() { req := httptest.NewRequest("POST", "/ns1/broker1", nil) http.WriteRequest(ctx, message, req) w := httptest.NewRecorder() h.ServeHTTP(w, req) if res := w.Result(); w.Result().StatusCode != nethttp.StatusAccepted { b.Errorf("Unexpected HTTP status code %v", res.StatusCode) } } }) } func createPubsubClient(ctx context.Context, t testing.TB, psSrv *pstest.Server) *pubsub.Client { conn, err := grpc.Dial(psSrv.Addr, grpc.WithInsecure()) if err != nil { t.Fatal(err) } t.Cleanup(func() { conn.Close() }) psClient, err := pubsub.NewClient(ctx, projectID, option.WithGRPCConn(conn)) if err != nil { t.Fatal(err) } return psClient } func setupTestReceiver(ctx context.Context, t testing.TB, psSrv *pstest.Server) *cepubsub.Protocol { ps := createPubsubClient(ctx, t, psSrv) topic, err := ps.CreateTopic(ctx, topicID) if err != nil { t.Fatal(err) } _, err = ps.CreateSubscription(ctx, subscriptionID, pubsub.SubscriptionConfig{Topic: topic}) if err != nil { t.Fatal(err) } p, err := cepubsub.New(ctx, cepubsub.WithClient(ps), cepubsub.WithSubscriptionAndTopicID(subscriptionID, topicID), cepubsub.WithReceiveSettings(&pubsub.DefaultReceiveSettings), ) if err != nil { t.Fatal(err) } go p.OpenInbound(cecontext.WithLogger(ctx, logtest.TestLogger(t))) return p } // createAndStartIngress creates an ingress and calls its Start() method in a goroutine. func createAndStartIngress(ctx context.Context, t testing.TB, psSrv *pstest.Server, decouple DecoupleSink) string { receiver := &testHttpMessageReceiver{urlCh: make(chan string)} statsReporter, err := metrics.NewIngressReporter(metrics.PodName(pod), metrics.ContainerName(container)) if err != nil { t.Fatal(err) } h := NewHandler(ctx, receiver, decouple, statsReporter) errCh := make(chan error, 1) go func() { errCh <- h.Start(ctx) }() select { case err := <-errCh: t.Fatalf("Failed to start ingress: %v", err) case url := <-h.httpReceiver.(*testHttpMessageReceiver).urlCh: return url } return "" } func createTestEvent(id string) *cloudevents.Event { event := cloudevents.NewEvent() event.SetID(id) event.SetSource("test-source") event.SetType(eventType) return &event } func createTestEventWithPayloadSize(id string, payloadSizeBytes int) *cloudevents.Event { testEvent := createTestEvent(id) payload := make([]byte, payloadSizeBytes) rand.Read(payload) testEvent.SetData("application/octet-stream", payload) return testEvent } // createRequest creates an http request from the test case. If event is specified, it converts the event to a request. func createRequest(tc testCase, url string) *nethttp.Request { method := "POST" if tc.method != "" { method = tc.method } body, _ := json.Marshal(tc.body) request, _ := nethttp.NewRequest(method, url+tc.path, bytes.NewBuffer(body)) if tc.header != nil { request.Header = tc.header } if tc.event != nil { message := binding.ToMessage(tc.event) defer message.Finish(nil) http.WriteRequest(context.Background(), message, request) } return request } // verifyMetrics verifies broker metrics are properly recorded (or not recorded) func verifyMetrics(t *testing.T, tc testCase) { if tc.wantEventCount == 0 { metricstest.CheckStatsNotReported(t, "event_count") } else { metricstest.CheckStatsReported(t, "event_count") metricstest.CheckCountData(t, "event_count", tc.wantMetricTags, tc.wantEventCount) } } func assertTraceID(id string) eventAssertion { return func(t *testing.T, e *cloudevents.Event) { t.Helper() dt, ok := extensions.GetDistributedTracingExtension(*e) if !ok { t.Errorf("event missing distributed tracing extensions: %v", e) return } sc, err := dt.ToSpanContext() if err != nil { t.Error(err) return } if sc.TraceID.String() != id { t.Errorf("unexpected trace ID: got %q, want %q", sc.TraceID, id) } } } func assertExtensionsExist(extensions ...string) eventAssertion { return func(t *testing.T, e *cloudevents.Event) { for _, extension := range extensions { if _, ok := e.Extensions()[extension]; !ok { t.Errorf("Extension %v doesn't exist.", extension) } } } } // testHttpMessageReceiver implements HttpMessageReceiver. When created, it creates an httptest.Server, // which starts a server with any available port. type testHttpMessageReceiver struct { // once the server is started, the server's url is sent to this channel. urlCh chan string } func (recv *testHttpMessageReceiver) StartListen(ctx context.Context, handler nethttp.Handler) error { // NewServer creates a new server and starts it. It is non-blocking. server := httptest.NewServer(kncloudevents.CreateHandler(handler)) defer server.Close() recv.urlCh <- server.URL select { case <-ctx.Done(): server.Close() } return nil }
1
18,310
I felt we don't need to set it that strict, like if somehow pubsub happens to allow extra 20 bytes for metadata, this test won't work. We would suggest to use 11MB instead.
google-knative-gcp
go
@@ -34,7 +34,7 @@ class AutocompleteTypeConfigurator implements TypeConfiguratorInterface } // by default, allow to autocomplete multiple values for OneToMany and ManyToMany associations - if (!isset($options['multiple']) && $metadata['associationType'] & ClassMetadata::TO_MANY) { + if (!isset($options['multiple']) && isset($metadata['associationType']) && $metadata['associationType'] & ClassMetadata::TO_MANY) { $options['multiple'] = true; }
1
<?php /* * This file is part of the EasyAdminBundle. * * (c) Javier Eguiluz <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace EasyCorp\Bundle\EasyAdminBundle\Form\Type\Configurator; use Doctrine\ORM\Mapping\ClassMetadata; use Symfony\Component\Form\FormConfigInterface; /** * This configurator is applied to any form field of type 'easyadmin_autocomplete' * and is used to configure the class of the autocompleted entity. * * @author Javier Eguiluz <[email protected]> * @author Yonel Ceruto <[email protected]> */ class AutocompleteTypeConfigurator implements TypeConfiguratorInterface { /** * {@inheritdoc} */ public function configure($name, array $options, array $metadata, FormConfigInterface $parentConfig) { // by default, guess the mandatory 'class' option from the Doctrine metadata if (!isset($options['class']) && isset($metadata['targetEntity'])) { $options['class'] = $metadata['targetEntity']; } // by default, allow to autocomplete multiple values for OneToMany and ManyToMany associations if (!isset($options['multiple']) && $metadata['associationType'] & ClassMetadata::TO_MANY) { $options['multiple'] = true; } if (null !== $metadata['label'] && !isset($options['label'])) { $options['label'] = $metadata['label']; } return $options; } /** * {@inheritdoc} */ public function supports($type, array $options, array $metadata) { $supportedTypes = array( 'easyadmin_autocomplete', 'JavierEguiluz\Bundle\EasyAdminBundle\Form\Type\EasyAdminAutocompleteType', ); return in_array($type, $supportedTypes, true); } } class_alias('EasyCorp\Bundle\EasyAdminBundle\Form\Type\Configurator\AutocompleteTypeConfigurator', 'JavierEguiluz\Bundle\EasyAdminBundle\Form\Type\Configurator\AutocompleteTypeConfigurator', false);
1
11,141
In theory `isset($metadata['associationType'])` is `false` if the linked field is not an association field, isn't?
EasyCorp-EasyAdminBundle
php
@@ -84,7 +84,7 @@ Doorkeeper.configure do # # If not specified, Doorkeeper enables all the four grant flows. # - # grant_flows %w(authorization_code implicit password client_credentials) + grant_flows %w(authorization_code implicit password client_credentials) # Under some circumstances you might want to have applications auto-approved, # so that the user skips the authorization step.
1
Doorkeeper.configure do # Change the ORM that doorkeeper will use. # Currently supported options are :active_record, :mongoid2, :mongoid3, # :mongoid4, :mongo_mapper orm :active_record # This block will be called to check whether the resource owner is authenticated or not. resource_owner_authenticator do if request.env[:clearance].current_user request.env[:clearance].current_user else session[:return_to] = request.fullpath redirect_to(sign_in_url) end end resource_owner_from_credentials do |routes| User.authenticate(params[:username], params[:password]) end # If you want to restrict access to the web interface for adding oauth authorized applications, you need to declare the block below. admin_authenticator do user = request.env[:clearance].current_user user && user.admin? or redirect_to(sign_in_url) end # Authorization Code expiration time (default 10 minutes). # authorization_code_expires_in 10.minutes # Access token expiration time (default 2 hours). # If you want to disable expiration, set this to nil. access_token_expires_in nil # Reuse access token for the same resource owner within an application (disabled by default) # Rationale: https://github.com/doorkeeper-gem/doorkeeper/issues/383 # reuse_access_token # Issue access tokens with refresh token (disabled by default) # use_refresh_token # Provide support for an owner to be assigned to each registered application (disabled by default) # Optional parameter :confirmation => true (default false) if you want to enforce ownership of # a registered application # Note: you must also run the rails g doorkeeper:application_owner generator to provide the necessary support # enable_application_owner :confirmation => false # Define access token scopes for your provider # For more information go to # https://github.com/doorkeeper-gem/doorkeeper/wiki/Using-Scopes # default_scopes :public # optional_scopes :write, :update # Change the way client credentials are retrieved from the request object. # By default it retrieves first from the `HTTP_AUTHORIZATION` header, then # falls back to the `:client_id` and `:client_secret` params from the `params` object. # Check out the wiki for more information on customization # client_credentials :from_basic, :from_params # Change the way access token is authenticated from the request object. # By default it retrieves first from the `HTTP_AUTHORIZATION` header, then # falls back to the `:access_token` or `:bearer_token` params from the `params` object. # Check out the wiki for more information on customization # access_token_methods :from_bearer_authorization, :from_access_token_param, :from_bearer_param # Change the native redirect uri for client apps # When clients register with the following redirect uri, they won't be redirected to any server and the authorization code will be displayed within the provider # The value can be any string. Use nil to disable this feature. When disabled, clients must provide a valid URL # (Similar behaviour: https://developers.google.com/accounts/docs/OAuth2InstalledApp#choosingredirecturi) # # native_redirect_uri 'urn:ietf:wg:oauth:2.0:oob' # Forces the usage of the HTTPS protocol in non-native redirect uris (enabled # by default in non-development environments). OAuth2 delegates security in # communication to the HTTPS protocol so it is wise to keep this enabled. force_ssl_in_redirect_uri Rails.env.production? # Specify what grant flows are enabled in array of Strings. The valid # strings and the flows they enable are: # # "authorization_code" => Authorization Code Grant Flow # "implicit" => Implicit Grant Flow # "password" => Resource Owner Password Credentials Grant Flow # "client_credentials" => Client Credentials Grant Flow # # If not specified, Doorkeeper enables all the four grant flows. # # grant_flows %w(authorization_code implicit password client_credentials) # Under some circumstances you might want to have applications auto-approved, # so that the user skips the authorization step. # For example if dealing with trusted a application. skip_authorization do |resource_owner, client| true end # WWW-Authenticate Realm (default "Doorkeeper"). # realm "Doorkeeper" # Allow dynamic query parameters (disabled by default) # Some applications require dynamic query parameters on their request_uri # set to true if you want this to be allowed # wildcard_redirect_uri false end
1
16,074
@tute the only thing I needed to enable this like as `password` is not in default flow anymore I think.
thoughtbot-upcase
rb
@@ -52,7 +52,8 @@ class IamPolicyTest(ForsetiTestCase): 'serviceAccount:[email protected]', 'user:[email protected]', 'allUsers', - 'user:anything' + 'user:anything', + 'allAuthenticatedUsers' ] # Test IamPolicyMember
1
# Copyright 2017 The Forseti Security Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Test the IamPolicy.""" import unittest from tests.unittest_utils import ForsetiTestCase from google.cloud.forseti.common.gcp_type.errors import InvalidIamAuditConfigError from google.cloud.forseti.common.gcp_type.errors import InvalidIamPolicyBindingError from google.cloud.forseti.common.gcp_type.errors import InvalidIamPolicyMemberError from google.cloud.forseti.common.gcp_type.iam_policy import IamAuditConfig from google.cloud.forseti.common.gcp_type.iam_policy import IamPolicy from google.cloud.forseti.common.gcp_type.iam_policy import IamPolicyBinding from google.cloud.forseti.common.gcp_type.iam_policy import IamPolicyMember def _get_member_list(members): return [':'.join(filter((lambda x: x is not None), [member.type, member.name])) for member in members] class IamPolicyTest(ForsetiTestCase): """Test IAM Policy class.""" def setUp(self): self.members = [ 'user:[email protected]', 'group:[email protected]', 'serviceAccount:[email protected]', 'allUsers', 'allAuthenticatedUsers', 'user:*@company.com', 'serviceAccount:*@*.gserviceaccount.com', 'user:*' ] self.test_members = [ 'user:[email protected]', 'serviceAccount:[email protected]', 'user:[email protected]', 'allUsers', 'user:anything' ] # Test IamPolicyMember def test_member_create_from_is_correct(self): """Test that IamPolicyMember creation is correct.""" iam_member1 = IamPolicyMember.create_from(self.members[0]) self.assertEqual('user', iam_member1.type) self.assertEqual('[email protected]', iam_member1.name) self.assertEqual('^test\-user\@company\.com$', iam_member1.name_pattern.pattern) iam_member2 = IamPolicyMember.create_from(self.members[3]) self.assertEqual('allUsers', iam_member2.type) self.assertIsNone(iam_member2.name) self.assertIsNone(iam_member2.name_pattern) def test_member_match_works(self): """Test the member match against wildcard and non-wildcard members.""" iam_policy_members = [ IamPolicyMember.create_from(self.members[0]), # specific user IamPolicyMember.create_from(self.members[3]), # allUsers IamPolicyMember.create_from(self.members[5]), # *@company.com IamPolicyMember.create_from(self.members[6]), # *@*.gserviceaccount IamPolicyMember.create_from(self.members[7]), # user:* ] self.assertTrue(iam_policy_members[0].matches(self.test_members[0])) # test globs/allUsers self.assertTrue(iam_policy_members[1].matches(self.members[3])) self.assertTrue(iam_policy_members[1].matches(self.test_members[3])) self.assertTrue(iam_policy_members[2].matches(self.test_members[0])) self.assertTrue(iam_policy_members[3].matches(self.test_members[1])) self.assertTrue(iam_policy_members[4].matches(self.test_members[2])) self.assertTrue(iam_policy_members[4].matches(self.test_members[4])) # test non matches self.assertFalse(iam_policy_members[0].matches( 'user:[email protected]')) self.assertFalse(iam_policy_members[2].matches( 'user:[email protected]')) self.assertFalse(iam_policy_members[2].matches( 'user:[email protected]')) self.assertFalse(iam_policy_members[2].matches( 'user:[email protected]')) self.assertFalse(iam_policy_members[3].matches( 'serviceAccount:[email protected]')) self.assertFalse(iam_policy_members[3].matches( 'serviceAccount:[email protected]')) def test_member_invalid_type_raises(self): """Test that invalid member type raises exception.""" with self.assertRaises(InvalidIamPolicyMemberError): iam_member = IamPolicyMember('fake_type') # Test IamPolicyBinding def test_binding_create_from_is_correct(self): """Test that the IamPolicyBinding create is correct.""" # test role, members, role name pattern binding = { 'role': 'roles/viewer', 'members': self.test_members } iam_binding = IamPolicyBinding.create_from(binding) self.assertEqual(binding['role'], iam_binding.role_name) self.assertEqual(binding['members'], _get_member_list(iam_binding.members)) self.assertEqual('^roles\/viewer$', iam_binding.role_pattern.pattern) # test roles glob binding2 = { 'role': 'roles/*', 'members': self.test_members } iam_binding2 = IamPolicyBinding.create_from(binding2) self.assertEqual('^roles\/.+?$', iam_binding2.role_pattern.pattern) def test_binding_missing_role_raises(self): """Test that a binding with no role raises an exception.""" with self.assertRaises(InvalidIamPolicyBindingError): IamPolicyBinding(None, ['*']) def test_binding_missing_members_raises(self): """Test that a binding with no members raises an exception.""" with self.assertRaises(InvalidIamPolicyBindingError): IamPolicyBinding('roles/fake', []) def test_binding_merge_members_other_type_different_raises(self): """Test that merging raises exception if `other`is not of same type.""" with self.assertRaises(InvalidIamPolicyBindingError): binding = { 'role': 'roles/viewer', 'members': [ 'user:[email protected]', 'serviceAccount:[email protected]', ] } iam_binding = IamPolicyBinding.create_from(binding) iam_binding.merge_members([1, 2, 4]) def test_binding_merge_members_same_role_and_members(self): binding = { 'role': 'roles/viewer', 'members': [ 'user:[email protected]', 'serviceAccount:[email protected]', ] } iam_binding1 = IamPolicyBinding.create_from(binding) iam_binding2 = IamPolicyBinding.create_from(binding) iam_binding1.merge_members(iam_binding2) self.assertEqual(iam_binding1, iam_binding2) def test_binding_merge_members_same_role_different_members(self): binding1 = { 'role': 'roles/viewer', 'members': [ 'user:[email protected]', 'serviceAccount:[email protected]', ] } binding2 = { 'role': 'roles/viewer', 'members': [ 'user:[email protected]', ] } expected_binding = { 'role': 'roles/viewer', 'members': [ 'user:[email protected]', 'serviceAccount:[email protected]', 'user:[email protected]', ] } iam_binding1 = IamPolicyBinding.create_from(binding1) iam_binding2 = IamPolicyBinding.create_from(binding2) iam_binding1.merge_members(iam_binding2) expected_binding = IamPolicyBinding.create_from(expected_binding) self.assertEqual(expected_binding, iam_binding1) def test_binding_merge_members_same_role_mixed_members(self): binding1 = { 'role': 'roles/viewer', 'members': [ 'user:[email protected]', 'serviceAccount:[email protected]', ] } binding2 = { 'role': 'roles/viewer', 'members': [ 'user:[email protected]', 'serviceAccount:[email protected]', ] } expected_binding = { 'role': 'roles/viewer', 'members': [ 'user:[email protected]', 'serviceAccount:[email protected]', 'user:[email protected]', ] } iam_binding1 = IamPolicyBinding.create_from(binding1) iam_binding2 = IamPolicyBinding.create_from(binding2) iam_binding1.merge_members(iam_binding2) expected_binding = IamPolicyBinding.create_from(expected_binding) self.assertEqual(expected_binding, iam_binding1) def test_binding_merge_members_different_role(self): """Original binding remains same if other's role is different.""" binding1 = { 'role': 'roles/owner', 'members': [ 'user:[email protected]', 'serviceAccount:[email protected]', ] } binding2 = { 'role': 'roles/viewer', 'members': [ 'user:[email protected]', ] } expected_binding = { 'role': 'roles/owner', 'members': [ 'user:[email protected]', 'serviceAccount:[email protected]', ] } iam_binding1 = IamPolicyBinding.create_from(binding1) iam_binding2 = IamPolicyBinding.create_from(binding2) iam_binding1.merge_members(iam_binding2) expected_binding = IamPolicyBinding.create_from(expected_binding) self.assertEqual(expected_binding, iam_binding1) # Test IamPolicy def test_policy_create_from_is_correct(self): """Test IamPolicy creation.""" policy_json = { 'bindings': [ { 'role': 'roles/editor', 'members': ['user:[email protected]'] }, { 'role': 'roles/viewer', 'members': ['user:[email protected]', 'group:[email protected]'] }, ] } iam_policy = IamPolicy.create_from(policy_json) actual_roles = [b.role_name for b in iam_policy.bindings] actual_members = [_get_member_list(b.members) for b in iam_policy.bindings] actual_audit_configs = iam_policy.audit_configs expected_roles = ['roles/editor', 'roles/viewer'] expected_members = [['user:[email protected]'], ['user:[email protected]', 'group:[email protected]']] self.assertEqual(expected_roles, actual_roles) self.assertEqual(expected_members, actual_members) self.assertIsNone(actual_audit_configs) def test_policy_create_from_with_audit_configs(self): """Test IamPolicy creation with auditConfigs.""" policy_json = { 'bindings': [ { 'role': 'roles/editor', 'members': ['user:[email protected]'] }, ], 'auditConfigs': [ { 'service': 'allServices', 'auditLogConfigs': [ { 'logType': 'ADMIN_READ', } ] }, { 'service': 'storage.googleapis.com', 'auditLogConfigs': [ { 'logType': 'DATA_READ', }, { 'logType': 'DATA_WRITE', 'exemptedMembers': [ 'user:[email protected]', 'user:[email protected]' ] } ] } ] } iam_policy = IamPolicy.create_from(policy_json) actual_roles = [b.role_name for b in iam_policy.bindings] actual_members = [_get_member_list(b.members) for b in iam_policy.bindings] actual_audit_configs = iam_policy.audit_configs.service_configs expected_roles = ['roles/editor'] expected_members = [['user:[email protected]']] expected_audit_configs = { 'allServices': { 'ADMIN_READ': set(), }, 'storage.googleapis.com': { 'DATA_READ': set(), 'DATA_WRITE': set(['user:[email protected]', 'user:[email protected]']), }, } self.assertEqual(expected_roles, actual_roles) self.assertEqual(expected_members, actual_members) self.assertEqual(expected_audit_configs, actual_audit_configs) def test_empty_policy_has_zero_length_bindings(self): """Test that an empty policy has no bindings.""" empty_policy = IamPolicy() self.assertTrue(empty_policy.is_empty()) self.assertEqual(False, bool(empty_policy.bindings)) def test_member_create_from_domain_is_correct(self): member = IamPolicyMember.create_from('domain:xyz.edu') self.assertEqual('domain', member.type) self.assertEqual('xyz.edu', member.name) self.assertEqual('^xyz\\.edu$', member.name_pattern.pattern) def test_is_matching_domain_success(self): member = IamPolicyMember.create_from('domain:xyz.edu') other = IamPolicyMember.create_from('user:[email protected]') self.assertTrue(member._is_matching_domain(other)) def test_is_matching_domain_fail_wrong_domain(self): member = IamPolicyMember.create_from('domain:xyz.edu') other = IamPolicyMember.create_from('user:[email protected]') self.assertFalse(member._is_matching_domain(other)) def test_is_matching_domain_fail_wrong_type(self): member = IamPolicyMember.create_from('group:xyz.edu') other = IamPolicyMember.create_from('user:[email protected]') self.assertFalse(member._is_matching_domain(other)) def test_is_matching_domain_fail_invalid_email(self): member = IamPolicyMember.create_from('domain:xyz.edu') other = IamPolicyMember.create_from('user:u AT xyz DOT edu') self.assertFalse(member._is_matching_domain(other)) # Test IamAuditConfig def test_audit_config_create_from_is_correct(self): audit_configs_json = [ { 'service': 'allServices', 'auditLogConfigs': [ { 'logType': 'DATA_READ', } ] }, { 'service': 'storage.googleapis.com', 'auditLogConfigs': [ { 'logType': 'DATA_READ', }, { 'logType': 'DATA_WRITE', 'exemptedMembers': [ 'user:[email protected]', 'user:[email protected]' ] } ] } ] audit_config = IamAuditConfig.create_from(audit_configs_json) expected_service_configs = { 'allServices': { 'DATA_READ': set(), }, 'storage.googleapis.com': { 'DATA_READ': set(), 'DATA_WRITE': set(['user:[email protected]', 'user:[email protected]']), }, } expected_audit_config = IamAuditConfig(expected_service_configs) self.assertEqual(expected_service_configs, audit_config.service_configs) self.assertEqual(expected_audit_config, audit_config) def test_audit_config_create_from_bad_config(self): # Log configs without a service service name. audit_configs_json = [ { 'auditLogConfigs': [ { 'logType': 'DATA_READ', } ] }, ] with self.assertRaises(InvalidIamAuditConfigError): audit_config = IamAuditConfig.create_from(audit_configs_json) def test_audit_config_merge_succeeds(self): configs1 = { 'allServices': { 'ADMIN_READ': set(['user:[email protected]', 'user:[email protected]']), 'DATA_READ': set(), }, 'storage.googleapis.com': { 'DATA_READ': set(), 'DATA_WRITE': set(['user:[email protected]', 'user:[email protected]']), }, } configs2 = { 'allServices': { 'ADMIN_READ': set(['user:[email protected]', 'user:[email protected]']), 'DATA_WRITE': set(), }, 'cloudsql.googleapis.com': { 'DATA_READ': set(), 'DATA_WRITE': set(['user:[email protected]', 'user:[email protected]']), }, } expected_configs = { 'allServices': { 'ADMIN_READ': set([ 'user:[email protected]', 'user:[email protected]', 'user:[email protected]' ]), 'DATA_READ': set(), 'DATA_WRITE': set(), }, 'cloudsql.googleapis.com': { 'DATA_READ': set(), 'DATA_WRITE': set(['user:[email protected]', 'user:[email protected]']), }, 'storage.googleapis.com': { 'DATA_READ': set(), 'DATA_WRITE': set(['user:[email protected]', 'user:[email protected]']), }, } audit_config1 = IamAuditConfig(configs1) audit_config2 = IamAuditConfig(configs2) expected_audit_config = IamAuditConfig(expected_configs) audit_config1.merge_configs(audit_config2) # Modify audit_config2 to make sure merge used a deep copy. audit_config2.service_configs['cloudsql.googleapis.com'][ 'DATA_READ'].add('user:[email protected]') self.assertEqual(expected_audit_config, audit_config1) if __name__ == '__main__': unittest.main()
1
31,650
nit: to be consistent with `self.members`, please move this up one line, so that it's closer to `allUsers`? You will need to update your test reference.
forseti-security-forseti-security
py
@@ -4,6 +4,7 @@ const config = require('./config') const fs = require('fs-extra') const runGClient = (args, options = {}) => { + if (options.verbose) args.push('--verbose') options.cwd = options.cwd || config.rootDir options = mergeWithDefault(options) options.env.GCLIENT_FILE = config.gClientFile
1
const path = require('path') const spawnSync = require('child_process').spawnSync const config = require('./config') const fs = require('fs-extra') const runGClient = (args, options = {}) => { options.cwd = options.cwd || config.rootDir options = mergeWithDefault(options) options.env.GCLIENT_FILE = config.gClientFile util.run('gclient', args, options) } const mergeWithDefault = (options) => { return Object.assign({}, config.defaultOptions, options) } const util = { run: (cmd, args = [], options = {}) => { console.log(cmd, args.join(' ')) const continueOnFail = options.continueOnFail delete options.continueOnFail const prog = spawnSync(cmd, args, options) if (prog.status !== 0) { if (!continueOnFail) { console.log(prog.stdout && prog.stdout.toString()) console.error(prog.stderr && prog.stderr.toString()) process.exit(1) } } return prog }, buildGClientConfig: () => { function replacer(key, value) { return value; } let solutions = config.projectNames.filter((projectName) => config.projects[projectName].ref).map((projectName) => { let project = config.projects[projectName] return { managed: "%False%", name: project.gclientName, url: project.url, custom_deps: project.custom_deps } }) const out = 'solutions = ' + JSON.stringify(solutions, replacer, 2) .replace(/"%None%"/g, "None") .replace(/"%False%"/g, "False") fs.writeFileSync(config.defaultGClientFile, out) }, updateBranding: () => { console.log('update branding...') const chromeComponentsDir = path.join(config.srcDir, 'components') const chromeAppDir = path.join(config.srcDir, 'chrome', 'app') const braveAppDir = path.join(config.projects['brave-core'].dir, 'app') fs.copySync(path.join(braveAppDir, 'brave_strings.grd'), path.join(chromeAppDir, 'brave_strings.grd')) fs.copySync(path.join(braveAppDir, 'settings_brave_strings.grdp'), path.join(chromeAppDir, 'settings_brave_strings.grdp')) fs.copySync(path.join(braveAppDir, 'components_brave_strings.grd'), path.join(config.srcDir, 'components', 'components_brave_strings.grd')) fs.copySync(path.join(braveAppDir, 'theme', 'brave'), path.join(chromeAppDir, 'theme', 'brave')) fs.copySync(path.join(braveAppDir, 'theme', 'default_100_percent', 'brave'), path.join(chromeAppDir, 'theme', 'default_100_percent', 'brave')) fs.copySync(path.join(braveAppDir, 'theme', 'default_200_percent', 'brave'), path.join(chromeAppDir, 'theme', 'default_200_percent', 'brave')) fs.copySync(path.join(braveAppDir, 'vector_icons', 'brave'), path.join(chromeAppDir, 'vector_icons', 'brave')) // Copy XTB files for app/brave_strings.grd => chromium_strings.grd fs.copySync(path.join(braveAppDir, 'resources'), path.join(chromeAppDir, 'resources')) // Copy XTB files for brave/app/components_brave_strings.grd => components/components_chromium_strings.grd fs.copySync(path.join(braveAppDir, 'strings'), path.join(chromeComponentsDir, 'strings')) }, buildMuon: (options = config.defaultOptions) => { console.log('building brave...') const args = util.buildArgsToString(config.buildArgs()) util.run('gn', ['gen', config.outputDir, '--args="' + args + '"'], options) util.run('ninja', ['-C', config.outputDir, 'brave'], options) }, submoduleSync: (options = { cwd: config.rootDir }) => { options = mergeWithDefault(options) util.run('git', ['submodule', 'sync'], options) util.run('git', ['submodule', 'update', '--init', '--recursive'], options) util.run('git', ['clean', '-fxd'], Object.assign(options, {cwd: config.depotToolsDir})) util.run('git', ['reset', '--hard', 'HEAD'], Object.assign(options, {cwd: config.depotToolsDir})) }, gclientSync: (options = {}) => { runGClient(['sync', '--force', '--nohooks', '--with_branch_heads'], options) }, gclientRunhooks: (options = {}) => { runGClient(['runhooks'], options) }, fetch: (options = {}) => { options = mergeWithDefault(options) util.run('git', ['fetch', '--all', '--tags'], options) }, setVersion: (version, options = {}) => { util.run('git', ['clean', '-f'], options) util.run('git', ['reset', '--hard', version], options) }, setDepVersion: (dir, version) => { const options = { cwd: dir } util.fetch(options) util.setVersion(version, options) }, buildArgsToString: (buildArgs) => { let args = '' for (let arg in buildArgs) { let val = buildArgs[arg] if (typeof val === 'string') { val = '"' + val + '"' } else { val = JSON.stringify(val) } args += arg + '=' + val + ' ' } return args.replace(/"/g,'\\"') } } module.exports = util
1
5,297
we might as well just access `config.gClientVerbose` directly here. If any other options are passed to `gclientSync` or `gclientRunhooks` then the verbose option will be lost the way it's used now
brave-brave-browser
js
@@ -353,6 +353,7 @@ return [ 'log' => [ 'menu_label' => 'Log settings', 'menu_description' => 'Specify which areas should use logging.', + 'logging' => 'Logging', 'log_events' => 'Log system events', 'log_events_comment' => 'Browser requests that may require attention, such as 404 errors.', 'log_requests' => 'Log bad requests',
1
<?php return [ 'app' => [ 'name' => 'OctoberCMS', 'tagline' => 'Getting back to basics' ], 'locale' => [ 'be' => 'Беларуская', 'bg' => 'Български', 'cs' => 'Čeština', 'da' => 'Dansk', 'en' => 'English (United States)', 'en-au' => 'English (Australia)', 'en-ca' => 'English (Canada)', 'en-gb' => 'English (United Kingdom)', 'de' => 'Deutsche', 'el' => 'Ελληνικά', 'es' => 'Español', 'es-ar' => 'Español (Argentina)', 'fa' => 'فارسی', 'fr' => 'Français', 'fr-ca' => 'Français (Canada)', 'hu' => 'Magyar', 'id' => 'Bahasa Indonesia', 'it' => 'Italiano', 'ja' => '日本語', 'lv' => 'Latvijas', 'nb-no' => 'Norsk (Bokmål)', 'nl' => 'Nederlands', 'pl' => 'Polskie', 'pt-br' => 'Português (Brasil)', 'ro' => 'Română', 'ru' => 'Русский', 'sv' => 'Svenska', 'sk' => 'Slovenský', 'tr' => 'Türk', 'zh-cn' => '简体中文', 'zh-tw' => '繁體中文' ], 'directory' => [ 'create_fail' => 'Cannot create directory: :name' ], 'file' => [ 'create_fail' => 'Cannot create file: :name' ], 'combiner' => [ 'not_found' => "The combiner file ':name' is not found." ], 'system' => [ 'name' => 'System', 'menu_label' => 'System', 'categories' => [ 'cms' => 'CMS', 'misc' => 'Misc', 'logs' => 'Logs', 'mail' => 'Mail', 'shop' => 'Shop', 'team' => 'Team', 'users' => 'Users', 'system' => 'System', 'social' => 'Social', 'events' => 'Events', 'customers' => 'Customers', 'my_settings' => 'My Settings' ] ], 'theme' => [ 'label' => 'Theme', 'unnamed' => 'Unnamed theme', 'name' => [ 'label' => 'Theme Name', 'help' => 'Name the theme by its unique code. For example, RainLab.Vanilla' ], ], 'themes' => [ 'install' => 'Install themes', 'search' => 'search themes to install...', 'installed' => 'Installed themes', 'no_themes' => 'There are no themes installed from the marketplace.', 'recommended' => 'Recommended', 'remove_confirm' => 'Are you sure you want to remove this theme?' ], 'plugin' => [ 'label' => 'Plugin', 'unnamed' => 'Unnamed plugin', 'name' => [ 'label' => 'Plugin Name', 'help' => 'Name the plugin by its unique code. For example, RainLab.Blog' ] ], 'plugins' => [ 'manage' => 'Manage plugins', 'enable_or_disable' => 'Enable or disable', 'enable_or_disable_title' => 'Enable or Disable Plugins', 'install' => 'Install plugins', 'install_products' => 'Install products', 'search' => 'search plugins to install...', 'installed' => 'Installed plugins', 'no_plugins' => 'There are no plugins installed from the marketplace.', 'recommended' => 'Recommended', 'remove' => 'Remove', 'refresh' => 'Refresh', 'disabled_label' => 'Disabled', 'disabled_help' => 'Plugins that are disabled are ignored by the application.', 'frozen_label' => 'Freeze updates', 'frozen_help' => 'Plugins that are frozen will be ignored by the update process.', 'selected_amount' => 'Plugins selected: :amount', 'remove_confirm' => 'Are you sure you want to remove this plugin?', 'remove_success' => 'Successfully removed those plugins from the system.', 'refresh_confirm' => 'Are you sure?', 'refresh_success' => 'Successfully refreshed those plugins in the system.', 'disable_confirm' => 'Are you sure?', 'disable_success' => 'Successfully disabled those plugins.', 'enable_success' => 'Successfully enabled those plugins.', 'unknown_plugin' => 'Plugin has been removed from the file system.' ], 'project' => [ 'name' => 'Project', 'owner_label' => 'Owner', 'attach' => 'Attach Project', 'detach' => 'Detach Project', 'none' => 'None', 'id' => [ 'label' => 'Project ID', 'help' => 'How to find your Project ID', 'missing' => 'Please specify a Project ID to use.' ], 'detach_confirm' => 'Are you sure you want to detach this project?', 'unbind_success' => 'Project has been detached.' ], 'settings' => [ 'menu_label' => 'Settings', 'not_found' => 'Unable to find the specified settings.', 'missing_model' => 'The settings page is missing a Model definition.', 'update_success' => ':name settings updated', 'return' => 'Return to system settings', 'search' => 'Search' ], 'mail' => [ 'log_file' => 'Log file', 'menu_label' => 'Mail configuration', 'menu_description' => 'Manage email configuration.', 'general' => 'General', 'method' => 'Mail method', 'sender_name' => 'Sender name', 'sender_email' => 'Sender email', 'php_mail' => 'PHP mail', 'smtp' => 'SMTP', 'smtp_address' => 'SMTP address', 'smtp_authorization' => 'SMTP authorization required', 'smtp_authorization_comment' => 'Use this checkbox if your SMTP server requires authorization.', 'smtp_username' => 'Username', 'smtp_password' => 'Password', 'smtp_port' => 'SMTP port', 'smtp_ssl' => 'SSL connection required', 'smtp_encryption' => 'SMTP encryption protocol', 'smtp_encryption_none' => 'No encryption', 'smtp_encryption_tls' => 'TLS', 'smtp_encryption_ssl' => 'SSL', 'sendmail' => 'Sendmail', 'sendmail_path' => 'Sendmail path', 'sendmail_path_comment' => 'Please specify the path of the sendmail program.', 'mailgun' => 'Mailgun', 'mailgun_domain' => 'Mailgun domain', 'mailgun_domain_comment' => 'Please specify the Mailgun domain name.', 'mailgun_secret' => 'Mailgun secret', 'mailgun_secret_comment' => 'Enter your Mailgun API key.', 'mandrill' => 'Mandrill', 'mandrill_secret' => 'Mandrill secret', 'mandrill_secret_comment' => 'Enter your Mandrill API key.', 'ses' => 'SES', 'ses_key' => 'SES key', 'ses_key_comment' => 'Enter your SES API key', 'ses_secret' => 'SES secret', 'ses_secret_comment' => 'Enter your SES API secret key', 'ses_region' => 'SES region', 'ses_region_comment' => 'Enter your SES region (e.g. us-east-1)', 'drivers_hint_header' => 'Drivers not installed', 'drivers_hint_content' => 'This mail method requires the plugin ":plugin" be installed before you can send mail.' ], 'mail_templates' => [ 'menu_label' => 'Mail templates', 'menu_description' => 'Modify the mail templates that are sent to users and administrators, manage email layouts.', 'new_template' => 'New Template', 'new_layout' => 'New Layout', 'template' => 'Template', 'templates' => 'Templates', 'menu_layouts_label' => 'Mail Layouts', 'layout' => 'Layout', 'layouts' => 'Layouts', 'no_layout' => '-- No layout --', 'name' => 'Name', 'name_comment' => 'Unique name used to refer to this template', 'code' => 'Code', 'code_comment' => 'Unique code used to refer to this template', 'subject' => 'Subject', 'subject_comment' => 'Email message subject', 'description' => 'Description', 'content_html' => 'HTML', 'content_css' => 'CSS', 'content_text' => 'Plaintext', 'test_send' => 'Send test message', 'test_success' => 'Test message sent.', 'test_confirm' => 'Send test message to :email. Continue?', 'creating' => 'Creating Template...', 'creating_layout' => 'Creating Layout...', 'saving' => 'Saving Template...', 'saving_layout' => 'Saving Layout...', 'delete_confirm' => 'Delete this template?', 'delete_layout_confirm' => 'Delete this layout?', 'deleting' => 'Deleting Template...', 'deleting_layout' => 'Deleting Layout...', 'sending' => 'Sending test message...', 'return' => 'Return to template list' ], 'install' => [ 'project_label' => 'Attach to Project', 'plugin_label' => 'Install Plugin', 'theme_label' => 'Install Theme', 'missing_plugin_name' => 'Please specify a Plugin name to install.', 'missing_theme_name' => 'Please specify a Theme name to install.', 'install_completing' => 'Finishing installation process', 'install_success' => 'Plugin installed successfully' ], 'updates' => [ 'title' => 'Manage Updates', 'name' => 'Software update', 'menu_label' => 'Updates & Plugins', 'menu_description' => 'Update the system, manage and install plugins and themes.', 'return_link' => 'Return to system updates', 'check_label' => 'Check for updates', 'retry_label' => 'Try again', 'plugin_name' => 'Name', 'plugin_code' => 'Code', 'plugin_description' => 'Description', 'plugin_version' => 'Version', 'plugin_author' => 'Author', 'plugin_not_found' => 'Plugin not found', 'core_current_build' => 'Current build', 'core_build' => 'Build :build', 'core_build_help' => 'Latest build is available.', 'core_downloading' => 'Downloading application files', 'core_extracting' => 'Unpacking application files', 'plugins' => 'Plugins', 'themes' => 'Themes', 'disabled' => 'Disabled', 'plugin_downloading' => 'Downloading plugin: :name', 'plugin_extracting' => 'Unpacking plugin: :name', 'plugin_version_none' => 'New plugin', 'plugin_current_version' => 'Current version', 'theme_new_install' => 'New theme installation.', 'theme_downloading' => 'Downloading theme: :name', 'theme_extracting' => 'Unpacking theme: :name', 'update_label' => 'Update software', 'update_completing' => 'Finishing update process', 'update_loading' => 'Loading available updates...', 'update_success' => 'Update process complete', 'update_failed_label' => 'Update failed', 'force_label' => 'Force update', 'found' => [ 'label' => 'Found new updates!', 'help' => 'Click Update software to begin the update process.' ], 'none' => [ 'label' => 'No updates', 'help' => 'No new updates were found.' ], 'important_action' => [ 'empty' => 'Select action', 'confirm' => 'Confirm update', 'skip' => 'Skip this plugin (once only)', 'ignore' => 'Skip this plugin (always)' ], 'important_action_required' => 'Action required', 'important_view_guide' => 'View upgrade guide', 'important_alert_text' => 'Some updates need your attention.', 'details_title' => 'Plugin details', 'details_view_homepage' => 'View homepage', 'details_readme' => 'Documentation', 'details_readme_missing' => 'There is no documentation provided.', 'details_changelog' => 'Changelog', 'details_changelog_missing' => 'There is no changelog provided.', 'details_upgrades' => 'Upgrade Guide', 'details_upgrades_missing' => 'There are no upgrade instructions provided.', 'details_licence' => 'Licence', 'details_licence_missing' => 'There is no licence provided.', 'details_current_version' => 'Current version', 'details_author' => 'Author' ], 'server' => [ 'connect_error' => 'Error connecting to the server.', 'response_not_found' => 'The update server could not be found.', 'response_invalid' => 'Invalid response from the server.', 'response_empty' => 'Empty response from the server.', 'file_error' => 'Server failed to deliver the package.', 'file_corrupt' => 'File from server is corrupt.' ], 'behavior' => [ 'missing_property' => 'Class :class must define property $:property used by :behavior behavior.' ], 'config' => [ 'not_found' => 'Unable to find configuration file :file defined for :location.', 'required' => "Configuration used in :location must supply a value ':property'." ], 'zip' => [ 'extract_failed' => "Unable to extract core file ':file'." ], 'event_log' => [ 'hint' => 'This log displays a list of potential errors that occur in the application, such as exceptions and debugging information.', 'menu_label' => 'Event log', 'menu_description' => 'View system log messages with their recorded time and details.', 'empty_link' => 'Empty event log', 'empty_loading' => 'Emptying event log...', 'empty_success' => 'Event log emptied', 'return_link' => 'Return to event log', 'id' => 'ID', 'id_label' => 'Event ID', 'created_at' => 'Date & Time', 'message' => 'Message', 'level' => 'Level', 'preview_title' => 'Event' ], 'request_log' => [ 'hint' => 'This log displays a list of browser requests that may require attention. For example, if a visitor opens a CMS page that cannot be found, a record is created with the status code 404.', 'menu_label' => 'Request log', 'menu_description' => 'View bad or redirected requests, such as Page not found (404).', 'empty_link' => 'Empty request log', 'empty_loading' => 'Emptying request log...', 'empty_success' => 'Request log emptied', 'return_link' => 'Return to request log', 'id' => 'ID', 'id_label' => 'Log ID', 'count' => 'Counter', 'referer' => 'Referers', 'url' => 'URL', 'status_code' => 'Status', 'preview_title' => 'Request' ], 'permissions' => [ 'name' => 'System', 'manage_system_settings' => 'Manage system settings', 'manage_software_updates' => 'Manage software updates', 'access_logs' => 'View system logs', 'manage_mail_templates' => 'Manage mail templates', 'manage_mail_settings' => 'Manage mail settings', 'manage_other_administrators' => 'Manage other administrators', 'manage_preferences' => 'Manage backend preferences', 'manage_editor' => 'Manage code editor preferences', 'view_the_dashboard' => 'View the dashboard', 'manage_branding' => 'Customize the back-end' ], 'log' => [ 'menu_label' => 'Log settings', 'menu_description' => 'Specify which areas should use logging.', 'log_events' => 'Log system events', 'log_events_comment' => 'Browser requests that may require attention, such as 404 errors.', 'log_requests' => 'Log bad requests', 'log_requests_comment' => 'When a change is made to the theme using the back-end.', 'log_theme' => 'Log theme changes', 'log_theme_comment' => 'Store system events in the database in addition to the file-based log.', ] ];
1
11,923
Change the key to `default_tab` instead and I'll merge this
octobercms-october
php
@@ -387,8 +387,11 @@ module OrgAdmin end end end - else - # If no funder was selected retrieve the Org's templates + end + + # If the no funder was specified OR the funder matches the org + if funder_id.blank? || funder_id == org_id + # Retrieve the Org's templates templates << Template.organisationally_visible.valid.where(published: true, org_id: org_id, customization_of: nil).to_a end
1
module OrgAdmin class TemplatesController < ApplicationController include Paginable include TemplateFilter after_action :verify_authorized # GET /org_admin/templates # ----------------------------------------------------- def index authorize Template # Apply scoping all_templates_hash = apply_scoping(params[:scope] || 'all', false, true) own_hash = apply_scoping(params[:scope] || 'all', false, false) customizable_hash = apply_scoping(params[:scope] || 'all', true, false) # Apply pagination all_templates_hash[:templates] = all_templates_hash[:templates].page(1) own_hash[:templates] = own_hash[:templates].page(1) customizable_hash[:templates] = customizable_hash[:templates].page(1) # Gather up all of the publication dates for the live versions of each template. published = get_publication_dates(all_templates_hash[:scopes][:dmptemplate_ids]) render 'index', locals: { all_templates: all_templates_hash[:templates], customizable_templates: customizable_hash[:templates], own_templates: own_hash[:templates], customized_templates: customizable_hash[:customizations], published: published, current_org: current_user.org, orgs: Org.all, current_tab: params[:r] || 'all-templates', scopes: { all: all_templates_hash[:scopes], orgs: own_hash[:scopes], funders: customizable_hash[:scopes] } } end # GET /org_admin/templates/new # ----------------------------------------------------- def new authorize Template @current_tab = params[:r] || 'all-templates' end # POST /org_admin/templates # ----------------------------------------------------- def create authorize Template # creates a new template with version 0 and new dmptemplate_id @template = Template.new(params[:template]) @template.org_id = current_user.org.id @template.description = params['template-desc'] @template.links = (params["template-links"].present? ? JSON.parse(params["template-links"]) : {"funder": [], "sample_plan": []}) if @template.save redirect_to edit_org_admin_template_path(@template), notice: success_message(_('template'), _('created')) else @hash = @template.to_hash flash[:alert] = failed_create_error(@template, _('template')) render action: "new" end end # GET /org_admin/templates/:id/edit # ----------------------------------------------------- def edit @template = Template.includes(:org, phases: [sections: [questions: [:question_options, :question_format, :annotations]]]).find(params[:id]) authorize @template @current = Template.current(@template.dmptemplate_id) if @template == @current if @template.published? new_version = @template.get_new_version if !new_version.nil? redirect_to(action: 'edit', id: new_version.id) return else flash[:alert] = _('Unable to create a new version of this template. You are currently working with a published copy.') end end else flash[:notice] = _('You are viewing a historical version of this template. You will not be able to make changes.') end # once the correct template has been generated, we convert it to hash @template_hash = @template.to_hash @current_tab = params[:r] || 'all-templates' render('container', locals: { partial_path: 'edit', template: @template, current: @current, template_hash: @template_hash, current_tab: @current_tab }) end # PUT /org_admin/templates/:id (AJAXable) # ----------------------------------------------------- def update @template = Template.find(params[:id]) authorize @template # NOTE if non-authorized error is raised, it performs a redirect to root_path and no JSON output is generated current = Template.current(@template.dmptemplate_id) # Only allow the current version to be updated if current != @template render(status: :forbidden, json: { msg: _('You can not edit a historical version of this template.')}) else template_links = nil begin template_links = JSON.parse(params["template-links"]) if params["template-links"].present? rescue JSON::ParserError render(status: :bad_request, json: { msg: _('Error parsing links for a template') }) return end # TODO dirty check at template model instead of here for reusability, i.e. method dirty? passing a template object if @template.description != params["template-desc"] || @template.title != params[:template][:title] || @template.links != template_links @template.dirty = true end @template.description = params["template-desc"] @template.links = template_links if template_links.present? # If the visibility checkbox is not checked and the user's org is a funder set the visibility to public # otherwise default it to organisationally_visible if current_user.org.funder? && params[:template_visibility].nil? @template.visibility = Template.visibilities[:publicly_visible] else @template.visibility = Template.visibilities[:organisationally_visible] end if @template.update_attributes(params[:template]) render(status: :ok, json: { msg: success_message(_('template'), _('saved'))}) else # Note failed_update_error may return HTML tags (e.g. <br/>) and therefore the client should parse them accordingly render(status: :bad_request, json: { msg: failed_update_error(@template, _('template'))}) end end end # DELETE /org_admin/templates/:id # ----------------------------------------------------- def destroy @template = Template.find(params[:id]) current_tab = params[:r] || 'all-templates' authorize @template if @template.plans.length <= 0 current = Template.current(@template.dmptemplate_id) # Only allow the current version to be destroyed if current == @template if @template.destroy flash[:notice] = success_message(_('template'), _('removed')) redirect_to org_admin_templates_path(r: current_tab) else @hash = @template.to_hash flash[:alert] = failed_destroy_error(@template, _('template')) redirect_to org_admin_templates_path(r: current_tab) end else flash[:alert] = _('You cannot delete historical versions of this template.') redirect_to org_admin_templates_path(r: current_tab) end else flash[:alert] = _('You cannot delete a template that has been used to create plans.') redirect_to org_admin_templates_path(r: current_tab) end end # GET /org_admin/templates/:id/history # ----------------------------------------------------- def history @template = Template.find(params[:id]) authorize @template @templates = Template.where(dmptemplate_id: @template.dmptemplate_id).order(version: :desc) @current = Template.current(@template.dmptemplate_id) @current_tab = params[:r] || 'all-templates' end # GET /org_admin/templates/:id/customize # ----------------------------------------------------- def customize @template = Template.find(params[:id]) @current_tab = params[:r] || 'all-templates' authorize @template customisation = Template.deep_copy(@template) customisation.org = current_user.org customisation.version = 0 customisation.customization_of = @template.dmptemplate_id customisation.dmptemplate_id = loop do random = rand 2147483647 break random unless Template.exists?(dmptemplate_id: random) end customisation.dirty = true customisation.save customisation.phases.includes(:sections, :questions).each do |phase| phase.modifiable = false phase.save! phase.sections.each do |section| section.modifiable = false section.save! section.questions.each do |question| question.modifiable = false question.save! end end end redirect_to edit_org_admin_template_path(customisation, r: 'funder-templates') end # GET /org_admin/templates/:id/transfer_customization # the funder template's id is passed through here # ----------------------------------------------------- def transfer_customization @template = Template.includes(:org).find(params[:id]) @current_tab = params[:r] || 'all-templates' authorize @template new_customization = Template.deep_copy(@template) new_customization.org_id = current_user.org_id new_customization.published = false new_customization.customization_of = @template.dmptemplate_id new_customization.dirty = true new_customization.phases.includes(sections: :questions).each do |phase| phase.modifiable = false phase.save phase.sections.each do |section| section.modifiable = false section.save section.questions.each do |question| question.modifiable = false question.save end end end customizations = Template.includes(:org, phases:[sections: [questions: :annotations]]).where(org_id: current_user.org_id, customization_of: @template.dmptemplate_id).order(version: :desc) # existing version to port over max_version = customizations.first new_customization.dmptemplate_id = max_version.dmptemplate_id new_customization.version = max_version.version + 1 # here we rip the customizations out of the old template # First, we find any customzed phases or sections max_version.phases.each do |phase| # check if the phase was added as a customization if phase.modifiable # deep copy the phase and add it to the template phase_copy = Phase.deep_copy(phase) phase_copy.number = new_customization.phases.length + 1 phase_copy.template_id = new_customization.id phase_copy.save! else # iterate over the sections to see if any of them are customizations phase.sections.each do |section| if section.modifiable # this is a custom section section_copy = Section.deep_copy(section) customization_phase = new_customization.phases.includes(:sections).where(number: phase.number).first section_copy.phase_id = customization_phase.id # custom sections get added to the end section_copy.number = customization_phase.sections.length + 1 # section from phase with corresponding number in the main_template section_copy.save! else # not a customized section, iterate over questions customization_phase = new_customization.phases.includes(sections: [questions: :annotations]).where(number: phase.number).first customization_section = customization_phase.sections.where(number: section.number).first section.questions.each do |question| # find corresponding question in new template customization_question = customization_section.questions.where(number: question.number).first # apply annotations question.annotations.where(org_id: current_user.org_id).each do |annotation| annotation_copy = Annotation.deep_copy(annotation) annotation_copy.question_id = customization_question.id annotation_copy.save! end end end end end end new_customization.save redirect_to edit_org_admin_template_path(new_customization, r: 'funder-templates') end # PUT /org_admin/templates/:id/copy (AJAX) # ----------------------------------------------------- def copy @template = Template.find(params[:id]) current_tab = params[:r] || 'all-templates' authorize @template new_copy = Template.deep_copy(@template) new_copy.title = "Copy of " + @template.title new_copy.version = 0 new_copy.published = false new_copy.dmptemplate_id = loop do random = rand 2147483647 break random unless Template.exists?(dmptemplate_id: random) end if new_copy.save flash[:notice] = 'Template was successfully copied.' redirect_to edit_org_admin_template_path(id: new_copy.id, edit: true, r: 'organisation-templates'), notice: _('Information was successfully created.') else flash[:alert] = failed_create_error(new_copy, _('template')) end end # GET /org_admin/templates/:id/publish (AJAX) TODO convert to PUT verb # ----------------------------------------------------- def publish template = Template.find(params[:id]) authorize template current = Template.current(template.dmptemplate_id) # Only allow the current version to be updated if current != template redirect_to org_admin_templates_path, alert: _('You can not publish a historical version of this template.') else # Unpublish the older published version if there is one live = Template.live(template.dmptemplate_id) if !live.nil? and self != live live.published = false live.save! end # Set the dirty flag to false template.dirty = false template.published = true template.save flash[:notice] = _('Your template has been published and is now available to users.') redirect_to "#{org_admin_templates_path}#{template.customization_of.present? ? '#funder-templates' : '#organisation-templates'}" end end # GET /org_admin/templates/:id/unpublish (AJAX) TODO convert to PUT verb # ----------------------------------------------------- def unpublish template = Template.find(params[:id]) authorize template if template.nil? flash[:alert] = _('That template is not currently published.') else template.published = false template.save flash[:notice] = _('Your template is no longer published. Users will not be able to create new DMPs for this template until you re-publish it') end redirect_to "#{org_admin_templates_path}#{template.customization_of.present? ? '#funder-templates' : '#organisation-templates'}" end # PUT /org_admin/template_options (AJAX) # Collect all of the templates available for the org+funder combination # -------------------------------------------------------------------------- def template_options() org_id = (plan_params[:org_id] == '-1' ? '' : plan_params[:org_id]) funder_id = (plan_params[:funder_id] == '-1' ? '' : plan_params[:funder_id]) authorize Template.new templates = [] if org_id.present? || funder_id.present? unless funder_id.blank? # Load the funder's template(s) templates = Template.valid.publicly_visible.where(published: true, org_id: funder_id).to_a unless org_id.blank? # Swap out any organisational cusotmizations of a funder template templates.each do |tmplt| customization = Template.valid.find_by(published: true, org_id: org_id, customization_of: tmplt.dmptemplate_id) if customization.present? && tmplt.created_at < customization.created_at templates.delete(tmplt) templates << customization end end end else # If no funder was selected retrieve the Org's templates templates << Template.organisationally_visible.valid.where(published: true, org_id: org_id, customization_of: nil).to_a end templates = templates.flatten.uniq end # If no templates were available use the default template if templates.empty? templates << Template.where(is_default: true, published: true).first end templates = (templates.count > 0 ? templates.sort{|x,y| x.title <=> y.title} : []) render json: {"templates": templates.collect{|t| {id: t.id, title: t.title} }}.to_json end # ====================================================== private def plan_params params.require(:plan).permit(:org_id, :funder_id) end end end
1
17,393
we still can end up passing a blank org_id to the scope method if for any reason the params is not present...
DMPRoadmap-roadmap
rb
@@ -236,7 +236,9 @@ public class SaxonXPathRuleQuery extends AbstractXPathRuleQuery { */ if (value == null) { return UntypedAtomicValue.ZERO_LENGTH_UNTYPED; - + } else if (value instanceof Enum) { + // enums use their toString + return new StringValue(value.toString()); } else if (value instanceof String) { return new StringValue((String) value); } else if (value instanceof Boolean) {
1
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.rule.xpath; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import net.sourceforge.pmd.RuleContext; import net.sourceforge.pmd.lang.ast.Node; import net.sourceforge.pmd.lang.ast.xpath.saxon.DocumentNode; import net.sourceforge.pmd.lang.ast.xpath.saxon.ElementNode; import net.sourceforge.pmd.lang.xpath.Initializer; import net.sourceforge.pmd.properties.PropertyDescriptor; import net.sf.saxon.om.Item; import net.sf.saxon.om.ValueRepresentation; import net.sf.saxon.sxpath.AbstractStaticContext; import net.sf.saxon.sxpath.IndependentContext; import net.sf.saxon.sxpath.XPathDynamicContext; import net.sf.saxon.sxpath.XPathEvaluator; import net.sf.saxon.sxpath.XPathExpression; import net.sf.saxon.sxpath.XPathStaticContext; import net.sf.saxon.sxpath.XPathVariable; import net.sf.saxon.trans.XPathException; import net.sf.saxon.value.AtomicValue; import net.sf.saxon.value.BigIntegerValue; import net.sf.saxon.value.BooleanValue; import net.sf.saxon.value.DoubleValue; import net.sf.saxon.value.EmptySequence; import net.sf.saxon.value.FloatValue; import net.sf.saxon.value.Int64Value; import net.sf.saxon.value.SequenceExtent; import net.sf.saxon.value.StringValue; import net.sf.saxon.value.UntypedAtomicValue; /** * This is a Saxon based XPathRule query. */ public class SaxonXPathRuleQuery extends AbstractXPathRuleQuery { private static final int MAX_CACHE_SIZE = 20; private static final Map<Node, DocumentNode> CACHE = new LinkedHashMap<Node, DocumentNode>(MAX_CACHE_SIZE) { private static final long serialVersionUID = -7653916493967142443L; @Override protected boolean removeEldestEntry(final Map.Entry<Node, DocumentNode> eldest) { return size() > MAX_CACHE_SIZE; } }; /** * Representation of an XPath query, created at {@link #initializeXPathExpression()} using {@link #xpath}. */ private XPathExpression xpathExpression; /** * Holds the static context later used to match the variables in the dynamic context in * {@link #createDynamicContext(ElementNode)}. Created at {@link #initializeXPathExpression()} * using the properties descriptors in {@link #properties}. */ private List<XPathVariable> xpathVariables; @Override public boolean isSupportedVersion(String version) { return XPATH_1_0_COMPATIBILITY.equals(version) || XPATH_2_0.equals(version); } @Override @SuppressWarnings("unchecked") public List<Node> evaluate(final Node node, final RuleContext data) { initializeXPathExpression(); try { final DocumentNode documentNode = getDocumentNodeForRootNode(node); // Map AST Node -> Saxon Node final ElementNode rootElementNode = documentNode.nodeToElementNode.get(node); final XPathDynamicContext xpathDynamicContext = createDynamicContext(rootElementNode); final List<ElementNode> nodes = xpathExpression.evaluate(xpathDynamicContext); /* Map List of Saxon Nodes -> List of AST Nodes, which were detected to match the XPath expression (i.e. violation found) */ final List<Node> results = new ArrayList<>(); for (final ElementNode elementNode : nodes) { results.add((Node) elementNode.getUnderlyingNode()); } return results; } catch (final XPathException e) { throw new RuntimeException(super.xpath + " had problem: " + e.getMessage(), e); } } /** * Attempt to create a dynamic context on which to evaluate the {@link #xpathExpression}. * * @param elementNode the node on which to create the context; generally this node is the root node of the Saxon * Tree * @return the dynamic context on which to run the query * @throws XPathException if the supplied value does not conform to the required type of the * variable, when setting up the dynamic context; or if the supplied value contains a node that does not belong to * this Configuration (or another Configuration that shares the same namePool) */ private XPathDynamicContext createDynamicContext(final ElementNode elementNode) throws XPathException { final XPathDynamicContext dynamicContext = xpathExpression.createDynamicContext(elementNode); // Set variable values on the dynamic context for (final XPathVariable xpathVariable : xpathVariables) { final String variableName = xpathVariable.getVariableQName().getLocalName(); for (final Map.Entry<PropertyDescriptor<?>, Object> entry : super.properties.entrySet()) { if (variableName.equals(entry.getKey().name())) { final ValueRepresentation valueRepresentation = getRepresentation(entry.getKey(), entry.getValue()); dynamicContext.setVariable(xpathVariable, valueRepresentation); } } } return dynamicContext; } private ValueRepresentation getRepresentation(final PropertyDescriptor<?> descriptor, final Object value) { if (descriptor.isMultiValue()) { final List<?> val = (List<?>) value; if (val.isEmpty()) { return EmptySequence.getInstance(); } final Item[] converted = new Item[val.size()]; for (int i = 0; i < val.size(); i++) { converted[i] = getAtomicRepresentation(val.get(i)); } return new SequenceExtent(converted); } else { return getAtomicRepresentation(value); } } /** * Gets the DocumentNode representation for the whole AST in which the node is, that is, if the node is not the root * of the AST, then the AST is traversed all the way up until the root node is found. If the DocumentNode was * cached because this method was previously called, then a new DocumentNode will not be instanced. * * @param node the node from which the root node will be looked for. * @return the DocumentNode representing the whole AST */ private DocumentNode getDocumentNodeForRootNode(final Node node) { final Node root = getRootNode(node); DocumentNode documentNode; synchronized (CACHE) { documentNode = CACHE.get(root); if (documentNode == null) { documentNode = new DocumentNode(root); CACHE.put(root, documentNode); } } return documentNode; } /** * Traverse the AST until the root node is found. * * @param node the node from where to start traversing the tree * @return the root node */ private Node getRootNode(final Node node) { Node root = node; while (root.jjtGetParent() != null) { root = root.jjtGetParent(); } return root; } /** * Initialize the {@link #xpathExpression} and the {@link #xpathVariables}. */ private void initializeXPathExpression() { if (xpathExpression != null) { return; } try { final XPathEvaluator xpathEvaluator = new XPathEvaluator(); final XPathStaticContext xpathStaticContext = xpathEvaluator.getStaticContext(); // Enable XPath 1.0 compatibility if (XPATH_1_0_COMPATIBILITY.equals(version)) { ((AbstractStaticContext) xpathStaticContext).setBackwardsCompatibilityMode(true); } // Register PMD functions Initializer.initialize((IndependentContext) xpathStaticContext); /* Create XPathVariables for later use. It is a Saxon quirk that XPathVariables must be defined on the static context, and reused later to associate an actual value on the dynamic context creation, in createDynamicContext(ElementNode). */ xpathVariables = new ArrayList<>(); for (final PropertyDescriptor<?> propertyDescriptor : super.properties.keySet()) { final String name = propertyDescriptor.name(); if (!"xpath".equals(name)) { final XPathVariable xpathVariable = xpathStaticContext.declareVariable(null, name); xpathVariables.add(xpathVariable); } } // TODO Come up with a way to make use of RuleChain. I had hacked up // an approach which used Jaxen's stuff, but that only works for // 1.0 compatibility mode. Rather do it right instead of kludging. xpathExpression = xpathEvaluator.createExpression(super.xpath); } catch (final XPathException e) { throw new RuntimeException(e); } } /** * Gets the Saxon representation of the parameter, if its type corresponds * to an XPath 2.0 atomic datatype. * * @param value The value to convert * * @return The converted AtomicValue */ public static AtomicValue getAtomicRepresentation(final Object value) { /* FUTURE When supported, we should consider refactor this implementation to use Pattern Matching (see http://openjdk.java.net/jeps/305) so that it looks clearer. */ if (value == null) { return UntypedAtomicValue.ZERO_LENGTH_UNTYPED; } else if (value instanceof String) { return new StringValue((String) value); } else if (value instanceof Boolean) { return BooleanValue.get((Boolean) value); } else if (value instanceof Integer) { return Int64Value.makeIntegerValue((Integer) value); } else if (value instanceof Long) { return new BigIntegerValue((Long) value); } else if (value instanceof Double) { return new DoubleValue((Double) value); } else if (value instanceof Character) { return new StringValue(value.toString()); } else if (value instanceof Float) { return new FloatValue((Float) value); } else if (value instanceof Pattern) { return new StringValue(String.valueOf(value)); } else { // We could maybe use UntypedAtomicValue throw new RuntimeException("Unable to create ValueRepresentation for value of type: " + value.getClass()); } } }
1
15,237
I think yes, this makes sense to expose this. +1
pmd-pmd
java
@@ -33,7 +33,7 @@ metadata: - name: StorageType value: "hostpath" - name: BasePath - value: "/var/openebs/local" + value: {{env "OPENEBS_IO_LOCALPV_HOSTPATH_DIR" | default "/var/openebs/local"}} provisioner: openebs.io/local volumeBindingMode: WaitForFirstConsumer reclaimPolicy: Delete
1
/* Copyright 2019 The OpenEBS Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package v1alpha1 const localPVSCYamls = ` --- apiVersion: storage.k8s.io/v1 kind: StorageClass metadata: name: openebs-hostpath annotations: #Define a new CAS Type called "local" #which indicates that Data is stored #directly onto hostpath. The hostpath can be: #- device (as block or mounted path) #- hostpath (sub directory on OS or mounted path) openebs.io/cas-type: local cas.openebs.io/config: | - name: StorageType value: "hostpath" - name: BasePath value: "/var/openebs/local" provisioner: openebs.io/local volumeBindingMode: WaitForFirstConsumer reclaimPolicy: Delete --- apiVersion: storage.k8s.io/v1 kind: StorageClass metadata: name: openebs-device annotations: #Define a new CAS Type called "local" #which indicates that Data is stored #directly onto hostpath. The hostpath can be: #- device (as block or mounted path) #- hostpath (sub directory on OS or mounted path) openebs.io/cas-type: local cas.openebs.io/config: | - name: StorageType value: "device" provisioner: openebs.io/local volumeBindingMode: WaitForFirstConsumer reclaimPolicy: Delete --- ` // LocalPVArtifacts returns the default Local PV storage // class related artifacts corresponding to latest version func LocalPVArtifacts() (list artifactList) { list.Items = append(list.Items, ParseArtifactListFromMultipleYamlsIf(localPVSCs{}, IsDefaultStorageConfigEnabled)...) return } type localPVSCs struct{} // FetchYamls returns all the yamls related to local pv storage classes // in a string format // // NOTE: // This is an implementation of MultiYamlFetcher func (j localPVSCs) FetchYamls() string { return localPVSCYamls }
1
17,335
let us put the sample yaml snippet i.e. maya api server deployment that makes use of this env & value
openebs-maya
go
@@ -117,12 +117,12 @@ public class ITRabbitMQCollector { /** Guards against errors that leak from storage, such as InvalidQueryException */ @Test - public void skipsOnSpanConsumerException() throws Exception { + public void skipsOnSpanConsumerException() { // TODO: reimplement } @Test - public void messagesDistributedAcrossMultipleThreadsSuccessfully() throws Exception { + public void messagesDistributedAcrossMultipleThreadsSuccessfully() { // TODO: reimplement } }
1
/* * Copyright 2015-2018 The OpenZipkin Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package zipkin2.collector.rabbitmq; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeoutException; import org.junit.After; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import zipkin2.Span; import zipkin2.codec.SpanBytesEncoder; import static org.assertj.core.api.Java6Assertions.assertThat; import static zipkin2.TestObjects.LOTS_OF_SPANS; import static zipkin2.collector.rabbitmq.RabbitMQCollector.builder; public class ITRabbitMQCollector { List<Span> spans = Arrays.asList(LOTS_OF_SPANS[0], LOTS_OF_SPANS[1]); @ClassRule public static RabbitMQCollectorRule rabbit = new RabbitMQCollectorRule("rabbitmq:3.6-alpine"); @After public void clear() { rabbit.metrics.clear(); rabbit.storage.clear(); } @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void checkPasses() { assertThat(rabbit.collector.check().ok()).isTrue(); } @Test public void startFailsWithInvalidRabbitMqServer() throws Exception { // we can be pretty certain RabbitMQ isn't running on localhost port 80 String notRabbitMqAddress = "localhost:80"; try (RabbitMQCollector collector = builder().addresses(Collections.singletonList(notRabbitMqAddress)).build()) { thrown.expect(IllegalStateException.class); thrown.expectMessage("Unable to establish connection to RabbitMQ server"); collector.start(); } } /** Ensures list encoding works: a json encoded list of spans */ @Test public void messageWithMultipleSpans_json() throws Exception { byte[] message = SpanBytesEncoder.JSON_V1.encodeList(spans); rabbit.publish(message); Thread.sleep(1000); assertThat(rabbit.storage.acceptedSpanCount()).isEqualTo(spans.size()); assertThat(rabbit.rabbitmqMetrics.messages()).isEqualTo(1); assertThat(rabbit.rabbitmqMetrics.bytes()).isEqualTo(message.length); assertThat(rabbit.rabbitmqMetrics.spans()).isEqualTo(spans.size()); } /** Ensures list encoding works: a version 2 json list of spans */ @Test public void messageWithMultipleSpans_json2() throws Exception { messageWithMultipleSpans(SpanBytesEncoder.JSON_V2); } /** Ensures list encoding works: proto3 ListOfSpans */ @Test public void messageWithMultipleSpans_proto3() throws Exception { messageWithMultipleSpans(SpanBytesEncoder.PROTO3); } void messageWithMultipleSpans(SpanBytesEncoder encoder) throws IOException, TimeoutException, InterruptedException { byte[] message = encoder.encodeList(spans); rabbit.publish(message); Thread.sleep(1000); assertThat(rabbit.storage.acceptedSpanCount()).isEqualTo(spans.size()); assertThat(rabbit.rabbitmqMetrics.messages()).isEqualTo(1); assertThat(rabbit.rabbitmqMetrics.bytes()).isEqualTo(message.length); assertThat(rabbit.rabbitmqMetrics.spans()).isEqualTo(spans.size()); } /** Ensures malformed spans don't hang the collector */ @Test public void skipsMalformedData() throws Exception { rabbit.publish(SpanBytesEncoder.JSON_V2.encodeList(spans)); rabbit.publish(new byte[0]); rabbit.publish("[\"='".getBytes()); // screwed up json rabbit.publish("malformed".getBytes()); rabbit.publish(SpanBytesEncoder.JSON_V2.encodeList(spans)); Thread.sleep(1000); assertThat(rabbit.rabbitmqMetrics.messages()).isEqualTo(5); assertThat(rabbit.rabbitmqMetrics.messagesDropped()).isEqualTo(3); } /** Guards against errors that leak from storage, such as InvalidQueryException */ @Test public void skipsOnSpanConsumerException() throws Exception { // TODO: reimplement } @Test public void messagesDistributedAcrossMultipleThreadsSuccessfully() throws Exception { // TODO: reimplement } }
1
13,530
What changed to cause this?
openzipkin-zipkin
java
@@ -81,6 +81,8 @@ func waitForBalanceState(t *testing.T, processor *PromiseProcessor, expectedStat type fakeStorage struct{} -func (fs fakeStorage) Store(issuer string, data interface{}) error { return nil } -func (fs fakeStorage) Delete(issuer string, data interface{}) error { return nil } -func (fs fakeStorage) Close() error { return nil } +func (fs fakeStorage) Store(issuer string, data interface{}) error { return nil } +func (fs fakeStorage) Delete(issuer string, data interface{}) error { return nil } +func (fs fakeStorage) Close() error { return nil } +func (fs fakeStorage) StoreSession(bucketName string, key string, value interface{}) error { return nil } +func (fs fakeStorage) GetAll(issuer string, data interface{}) error { return nil }
1
/* * Copyright (C) 2018 The "MysteriumNetwork/node" Authors. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package noop import ( "testing" "time" "github.com/mysteriumnetwork/node/core/promise" "github.com/mysteriumnetwork/node/money" "github.com/mysteriumnetwork/node/session" "github.com/stretchr/testify/assert" ) var _ session.PromiseProcessor = &PromiseProcessor{} func TestPromiseProcessor_Start_SendsBalanceMessages(t *testing.T) { dialog := &fakeDialog{} processor := &PromiseProcessor{ dialog: dialog, balanceInterval: time.Millisecond, storage: fakeStorage{}, } err := processor.Start(proposal) defer processor.Stop() assert.NoError(t, err) waitForBalanceState(t, processor, balanceNotifying) lastMessage, err := dialog.waitSendMessage() assert.NoError(t, err) assert.Exactly( t, promise.BalanceMessage{1, true, money.NewMoney(10, money.CURRENCY_MYST)}, lastMessage, ) } func TestPromiseProcessor_Stop_StopsBalanceMessages(t *testing.T) { dialog := &fakeDialog{} processor := &PromiseProcessor{ dialog: dialog, balanceInterval: time.Millisecond, storage: fakeStorage{}, } err := processor.Start(proposal) assert.NoError(t, err) waitForBalanceState(t, processor, balanceNotifying) err = processor.Stop() assert.NoError(t, err) waitForBalanceState(t, processor, balanceStopped) } func waitForBalanceState(t *testing.T, processor *PromiseProcessor, expectedState balanceState) { for i := 0; i < 10; i++ { if processor.getBalanceState() == expectedState { return } time.Sleep(time.Millisecond) } assert.Fail(t, "State expected to be ", string(expectedState)) } type fakeStorage struct{} func (fs fakeStorage) Store(issuer string, data interface{}) error { return nil } func (fs fakeStorage) Delete(issuer string, data interface{}) error { return nil } func (fs fakeStorage) Close() error { return nil }
1
12,437
Repeating big interface in many places shows smtg is wrong with design
mysteriumnetwork-node
go
@@ -0,0 +1,15 @@ +class Accounts::ChartsController < AccountsController + include SetAccountByAccountId + + before_action :redirect_if_disabled + + # NOTE: Replaces accounts#commits_history + def commits_by_project + render json: Chart.new(@account).commits_by_project + end + + # NOTE: Replaces accounts#language_experience + def commits_by_language + render json: Chart.new(@account).commits_by_language(params[:scope]) + end +end
1
1
7,082
Inheriting from `AccountsController` to get access to the `redirect_if_disabled` filter.
blackducksoftware-ohloh-ui
rb
@@ -1,14 +1,15 @@ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -# SPDX - License - Identifier: Apache - 2.0 +# SPDX-License-Identifier: Apache-2.0 + +# Purpose +# This code demonstrates how to copy an object from one Amazon Simple Storage Solution (Amazon S3) bucket to another. # snippet-start:[s3.ruby.copy_object_between_buckets.rb] require 'aws-sdk-s3' -# Copies an object from one Amazon S3 bucket to another. -# # Prerequisites: # -# - Two S3 buckets (a source bucket and a target bucket). +# - Two Amazon S3 buckets (a source bucket and a target bucket). # - An object in the source bucket to be copied. # # @param s3_client [Aws::S3::Client] An initialized Amazon S3 client.
1
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX - License - Identifier: Apache - 2.0 # snippet-start:[s3.ruby.copy_object_between_buckets.rb] require 'aws-sdk-s3' # Copies an object from one Amazon S3 bucket to another. # # Prerequisites: # # - Two S3 buckets (a source bucket and a target bucket). # - An object in the source bucket to be copied. # # @param s3_client [Aws::S3::Client] An initialized Amazon S3 client. # @param source_bucket_name [String] The source bucket's name. # @param source_key [String] The name of the object # in the source bucket to be copied. # @param target_bucket_name [String] The target bucket's name. # @param target_key [String] The name of the copied object. # @return [Boolean] true if the object was copied; otherwise, false. # @example # s3_client = Aws::S3::Client.new(region: 'us-east-1') # exit 1 unless object_copied?( # s3_client, # 'doc-example-bucket1', # 'my-source-file.txt', # 'doc-example-bucket2', # 'my-target-file.txt' # ) def object_copied?( s3_client, source_bucket_name, source_key, target_bucket_name, target_key) return true if s3_client.copy_object( bucket: target_bucket_name, copy_source: source_bucket_name + '/' + source_key, key: target_key ) rescue StandardError => e puts "Error while copying object: #{e.message}" end # snippet-end:[s3.ruby.copy_object_between_buckets.rb] # Full example call: def run_me source_bucket_name = 'doc-example-bucket1' source_key = 'my-source-file.txt' target_bucket_name = 'doc-example-bucket2' target_key = 'my-target-file.txt' region = 'us-east-1' s3_client = Aws::S3::Client.new(region: region) puts "Copying object '#{source_key}' from bucket '#{source_bucket_name}' " \ "to bucket '#{target_bucket_name}'..." if object_copied?( s3_client, source_bucket_name, source_key, target_bucket_name, target_key) puts 'The object was copied.' else puts 'The object was not copied. Stopping program.' exit 1 end end run_me if $PROGRAM_NAME == __FILE__
1
20,517
Simple Storage **Service**
awsdocs-aws-doc-sdk-examples
rb
@@ -0,0 +1 @@ +public class A { public int FUNC() { Class<?> cls = null; if(cls == null) return 0; else { B.FUNC3(cls); return 1;} } public void FUNC2(Class<?> arg) { return; }}class B {public static void FUNC3(Class<?> arg) { return; }}
1
1
12,604
Enter at the end of the file! :-D (and at the end of lines ;-) )
javaparser-javaparser
java
@@ -0,0 +1,9 @@ +class RenameScheduledForCancellation < ActiveRecord::Migration + def change + rename_column( + :subscriptions, + :scheduled_for_cancellation_on, + :scheduled_for_deactivation_on, + ) + end +end
1
1
15,524
Put a comma after the last parameter of a multiline method call.
thoughtbot-upcase
rb
@@ -88,7 +88,17 @@ func removeYields(plan *PlanSpec) (*PlanSpec, error) { } newRoot := root.Predecessors()[0] - newRoot.RemoveSuccessor(root) + newSucc := make([]PlanNode, 0, len(newRoot.Successors())) + + for _, succ := range newRoot.Successors() { + newSucc = append(newSucc, succ) + if succ == root { + continue + } + } + + newRoot.ClearSuccessors() + newRoot.AddSuccessors(newSucc...) plan.Replace(root, newRoot) plan.Results[name] = newRoot continue
1
package plan import ( "errors" "fmt" "math" ) // PhysicalPlanner performs transforms a logical plan to a physical plan, // by applying any registered physical rules. type PhysicalPlanner interface { Plan(lplan *PlanSpec) (*PlanSpec, error) } // NewPhysicalPlanner creates a new physical plan with the specified options. // The new plan will be configured to apply any physical rules that have been registered. func NewPhysicalPlanner(options ...PhysicalOption) PhysicalPlanner { pp := &physicalPlanner{ heuristicPlanner: newHeuristicPlanner(), defaultMemoryLimit: math.MaxInt64, } rules := make([]Rule, len(ruleNameToPhysicalRule)) i := 0 for _, v := range ruleNameToPhysicalRule { rules[i] = v i++ } pp.addRules(rules) // Options may add or remove rules, so process them after we've // added registered rules. for _, opt := range options { opt.apply(pp) } return pp } func (pp *physicalPlanner) Plan(spec *PlanSpec) (*PlanSpec, error) { transformedSpec, err := pp.heuristicPlanner.Plan(spec) if err != nil { return nil, err } // Convert yields into result list // TODO: Implement this via a transformation rule final, err := removeYields(transformedSpec) if err != nil { return nil, err } // Compute time bounds for nodes in the plan if err := final.BottomUpWalk(ComputeBounds); err != nil { return nil, err } // Update memory quota if final.Resources.MemoryBytesQuota == 0 { final.Resources.MemoryBytesQuota = pp.defaultMemoryLimit } // Update concurrency quota if final.Resources.ConcurrencyQuota == 0 { final.Resources.ConcurrencyQuota = len(spec.Results) } return final, nil } // TODO: This procedure should be encapsulated in a yield rewrite rule func removeYields(plan *PlanSpec) (*PlanSpec, error) { for root := range plan.Roots { name := DefaultYieldName if yield, ok := root.ProcedureSpec().(YieldProcedureSpec); ok { name = yield.YieldName() if len(root.Predecessors()) != 1 { return nil, errors.New("yield must have exactly one predecessor") } if _, ok := plan.Results[name]; ok { return nil, fmt.Errorf("found duplicate yield name %q", name) } newRoot := root.Predecessors()[0] newRoot.RemoveSuccessor(root) plan.Replace(root, newRoot) plan.Results[name] = newRoot continue } if _, ok := plan.Results[name]; ok { return nil, fmt.Errorf("found duplicate yield name %q", name) } plan.Results[name] = root } return plan, nil } type physicalPlanner struct { *heuristicPlanner defaultMemoryLimit int64 } // PhysicalOption is an option to configure the behavior of the physical plan. type PhysicalOption interface { apply(*physicalPlanner) } type physicalOption func(*physicalPlanner) func (opt physicalOption) apply(p *physicalPlanner) { opt(p) } // WithDefaultMemoryLimit sets the default memory limit for plans generated by the plan. // If the query spec explicitly sets a memory limit, that limit is used instead of the default. func WithDefaultMemoryLimit(memBytes int64) PhysicalOption { return physicalOption(func(p *physicalPlanner) { p.defaultMemoryLimit = memBytes }) } // PhysicalProcedureSpec is similar to its logical counterpart but must provide a method to determine cost. type PhysicalProcedureSpec interface { Kind() ProcedureKind Copy() ProcedureSpec Cost(inStats []Statistics) (cost Cost, outStats Statistics) } // PhysicalPlanNode represents a physical operation in a plan. type PhysicalPlanNode struct { edges bounds id NodeID Spec PhysicalProcedureSpec // The attributes required from inputs to this node RequiredAttrs []PhysicalAttributes // The attributes provided to consumers of this node's output OutputAttrs PhysicalAttributes } // ID returns a human-readable id for this plan node. func (ppn *PhysicalPlanNode) ID() NodeID { return ppn.id } // ProcedureSpec returns the procedure spec for this plan node. func (ppn *PhysicalPlanNode) ProcedureSpec() ProcedureSpec { return ppn.Spec } // Kind returns the procedure kind for this plan node. func (ppn *PhysicalPlanNode) Kind() ProcedureKind { return ppn.Spec.Kind() } func (ppn *PhysicalPlanNode) ShallowCopy() PlanNode { newNode := new(PhysicalPlanNode) newNode.edges = ppn.edges.shallowCopy() newNode.id = ppn.id + "_copy" // TODO: the type assertion below... is it needed? newNode.Spec = ppn.Spec.Copy().(PhysicalProcedureSpec) return newNode } // Cost provides the self-cost (i.e., does not include the cost of its predecessors) for // this plan node. Caller must provide statistics of predecessors to this node. func (ppn *PhysicalPlanNode) Cost(inStats []Statistics) (cost Cost, outStats Statistics) { return ppn.Spec.Cost(inStats) } // PhysicalAttributes encapsulates sny physical attributes of the result produced // by a physical plan node, such as collation, etc. type PhysicalAttributes struct { } // CreatePhysicalNode creates a single physical plan node from a procedure spec. // The newly created physical node has no incoming or outgoing edges. func CreatePhysicalNode(id NodeID, spec PhysicalProcedureSpec) *PhysicalPlanNode { return &PhysicalPlanNode{ id: id, Spec: spec, } }
1
8,648
Don't you want to place this check before you add `succ` to `newSucc`?
influxdata-flux
go
@@ -1,18 +1,6 @@ package com.fsck.k9.fragment; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.concurrent.Future; - import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context;
1
package com.fsck.k9.fragment; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.EnumMap; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.Future; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.database.Cursor; import android.graphics.Rect; import android.net.Uri; import android.os.Bundle; import android.os.Parcelable; import androidx.fragment.app.DialogFragment; import androidx.fragment.app.Fragment; import androidx.loader.app.LoaderManager; import androidx.loader.app.LoaderManager.LoaderCallbacks; import androidx.loader.content.CursorLoader; import androidx.loader.content.Loader; import androidx.localbroadcastmanager.content.LocalBroadcastManager; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.view.ActionMode; import android.text.TextUtils; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.fsck.k9.Account; import com.fsck.k9.Account.SortType; import com.fsck.k9.DI; import com.fsck.k9.K9; import com.fsck.k9.Preferences; import com.fsck.k9.activity.ActivityListener; import com.fsck.k9.activity.ChooseFolder; import com.fsck.k9.activity.FolderInfoHolder; import com.fsck.k9.activity.misc.ContactPicture; import com.fsck.k9.contacts.ContactPictureLoader; import com.fsck.k9.cache.EmailProviderCache; import com.fsck.k9.controller.MessageReference; import com.fsck.k9.controller.MessagingController; import com.fsck.k9.core.BuildConfig; import com.fsck.k9.ui.R; import com.fsck.k9.fragment.ConfirmationDialogFragment.ConfirmationDialogFragmentListener; import com.fsck.k9.fragment.MessageListFragmentComparators.ArrivalComparator; import com.fsck.k9.fragment.MessageListFragmentComparators.AttachmentComparator; import com.fsck.k9.fragment.MessageListFragmentComparators.ComparatorChain; import com.fsck.k9.fragment.MessageListFragmentComparators.DateComparator; import com.fsck.k9.fragment.MessageListFragmentComparators.FlaggedComparator; import com.fsck.k9.fragment.MessageListFragmentComparators.ReverseComparator; import com.fsck.k9.fragment.MessageListFragmentComparators.ReverseIdComparator; import com.fsck.k9.fragment.MessageListFragmentComparators.SenderComparator; import com.fsck.k9.fragment.MessageListFragmentComparators.SubjectComparator; import com.fsck.k9.fragment.MessageListFragmentComparators.UnreadComparator; import com.fsck.k9.helper.MergeCursorWithUniqueId; import com.fsck.k9.helper.MessageHelper; import com.fsck.k9.helper.Utility; import com.fsck.k9.mail.Flag; import com.fsck.k9.mail.Folder; import com.fsck.k9.mail.MessagingException; import com.fsck.k9.mailstore.LocalFolder; import com.fsck.k9.preferences.StorageEditor; import com.fsck.k9.provider.EmailProvider; import com.fsck.k9.provider.EmailProvider.MessageColumns; import com.fsck.k9.provider.EmailProvider.SpecialColumns; import com.fsck.k9.search.ConditionsTreeNode; import com.fsck.k9.search.LocalSearch; import com.fsck.k9.search.SearchSpecification; import com.fsck.k9.search.SearchSpecification.SearchCondition; import com.fsck.k9.search.SearchSpecification.SearchField; import com.fsck.k9.search.SqlQueryBuilder; import timber.log.Timber; import static com.fsck.k9.fragment.MLFProjectionInfo.ACCOUNT_UUID_COLUMN; import static com.fsck.k9.fragment.MLFProjectionInfo.FLAGGED_COLUMN; import static com.fsck.k9.fragment.MLFProjectionInfo.FOLDER_SERVER_ID_COLUMN; import static com.fsck.k9.fragment.MLFProjectionInfo.ID_COLUMN; import static com.fsck.k9.fragment.MLFProjectionInfo.PROJECTION; import static com.fsck.k9.fragment.MLFProjectionInfo.READ_COLUMN; import static com.fsck.k9.fragment.MLFProjectionInfo.SUBJECT_COLUMN; import static com.fsck.k9.fragment.MLFProjectionInfo.THREADED_PROJECTION; import static com.fsck.k9.fragment.MLFProjectionInfo.THREAD_COUNT_COLUMN; import static com.fsck.k9.fragment.MLFProjectionInfo.THREAD_ROOT_COLUMN; import static com.fsck.k9.fragment.MLFProjectionInfo.UID_COLUMN; public class MessageListFragment extends Fragment implements OnItemClickListener, ConfirmationDialogFragmentListener, LoaderCallbacks<Cursor> { public static MessageListFragment newInstance( LocalSearch search, boolean isThreadDisplay, boolean threadedList) { MessageListFragment fragment = new MessageListFragment(); Bundle args = new Bundle(); args.putParcelable(ARG_SEARCH, search); args.putBoolean(ARG_IS_THREAD_DISPLAY, isThreadDisplay); args.putBoolean(ARG_THREADED_LIST, threadedList); fragment.setArguments(args); return fragment; } private static final int ACTIVITY_CHOOSE_FOLDER_MOVE = 1; private static final int ACTIVITY_CHOOSE_FOLDER_COPY = 2; private static final String ARG_SEARCH = "searchObject"; private static final String ARG_THREADED_LIST = "showingThreadedList"; private static final String ARG_IS_THREAD_DISPLAY = "isThreadedDisplay"; private static final String STATE_SELECTED_MESSAGES = "selectedMessages"; private static final String STATE_ACTIVE_MESSAGE = "activeMessage"; private static final String STATE_REMOTE_SEARCH_PERFORMED = "remoteSearchPerformed"; private static final String STATE_MESSAGE_LIST = "listState"; /** * Maps a {@link SortType} to a {@link Comparator} implementation. */ private static final Map<SortType, Comparator<Cursor>> SORT_COMPARATORS; static { // fill the mapping at class time loading final Map<SortType, Comparator<Cursor>> map = new EnumMap<>(SortType.class); map.put(SortType.SORT_ATTACHMENT, new AttachmentComparator()); map.put(SortType.SORT_DATE, new DateComparator()); map.put(SortType.SORT_ARRIVAL, new ArrivalComparator()); map.put(SortType.SORT_FLAGGED, new FlaggedComparator()); map.put(SortType.SORT_SUBJECT, new SubjectComparator()); map.put(SortType.SORT_SENDER, new SenderComparator()); map.put(SortType.SORT_UNREAD, new UnreadComparator()); // make it immutable to prevent accidental alteration (content is immutable already) SORT_COMPARATORS = Collections.unmodifiableMap(map); } private final SortTypeToastProvider sortTypeToastProvider = DI.get(SortTypeToastProvider.class); ListView listView; private SwipeRefreshLayout swipeRefreshLayout; Parcelable savedListState; int previewLines = 0; private MessageListAdapter adapter; private View footerView; private FolderInfoHolder currentFolder; private LayoutInflater layoutInflater; private MessagingController messagingController; private Account account; private String[] accountUuids; private Cursor[] cursors; private boolean[] cursorValid; int uniqueIdColumn; /** * Stores the server ID of the folder that we want to open as soon as possible after load. */ private String folderServerId; private boolean remoteSearchPerformed = false; private Future<?> remoteSearchFuture = null; private List<String> extraSearchResults; private String title; private LocalSearch search = null; private boolean singleAccountMode; private boolean singleFolderMode; private boolean allAccounts; private final MessageListHandler handler = new MessageListHandler(this); private SortType sortType = SortType.SORT_DATE; private boolean sortAscending = true; private boolean sortDateAscending = false; boolean senderAboveSubject = false; boolean checkboxes = true; boolean stars = true; private int selectedCount = 0; Set<Long> selected = new HashSet<>(); private ActionMode actionMode; private Boolean hasConnectivity; /** * Relevant messages for the current context when we have to remember the chosen messages * between user interactions (e.g. selecting a folder for move operation). */ private List<MessageReference> activeMessages; /* package visibility for faster inner class access */ MessageHelper messageHelper; private final ActionModeCallback actionModeCallback = new ActionModeCallback(); MessageListFragmentListener fragmentListener; boolean showingThreadedList; private boolean isThreadDisplay; private Context context; private final ActivityListener activityListener = new MessageListActivityListener(); private Preferences preferences; private boolean loaderJustInitialized; MessageReference activeMessage; /** * {@code true} after {@link #onCreate(Bundle)} was executed. Used in {@link #updateTitle()} to * make sure we don't access member variables before initialization is complete. */ private boolean initialized = false; ContactPictureLoader contactsPictureLoader; private LocalBroadcastManager localBroadcastManager; private BroadcastReceiver cacheBroadcastReceiver; private IntentFilter cacheIntentFilter; /** * Stores the unique ID of the message the context menu was opened for. * * We have to save this because the message list might change between the time the menu was * opened and when the user clicks on a menu item. When this happens the 'adapter position' that * is accessible via the {@code ContextMenu} object might correspond to another list item and we * would end up using/modifying the wrong message. * * The value of this field is {@code 0} when no context menu is currently open. */ private long contextMenuUniqueId = 0; /** * @return The comparator to use to display messages in an ordered * fashion. Never {@code null}. */ private Comparator<Cursor> getComparator() { final List<Comparator<Cursor>> chain = new ArrayList<>(3 /* we add 3 comparators at most */); // Add the specified comparator final Comparator<Cursor> comparator = SORT_COMPARATORS.get(sortType); if (sortAscending) { chain.add(comparator); } else { chain.add(new ReverseComparator<>(comparator)); } // Add the date comparator if not already specified if (sortType != SortType.SORT_DATE && sortType != SortType.SORT_ARRIVAL) { final Comparator<Cursor> dateComparator = SORT_COMPARATORS.get(SortType.SORT_DATE); if (sortDateAscending) { chain.add(dateComparator); } else { chain.add(new ReverseComparator<>(dateComparator)); } } // Add the id comparator chain.add(new ReverseIdComparator()); // Build the comparator chain return new ComparatorChain<>(chain); } void folderLoading(String folder, boolean loading) { if (currentFolder != null && currentFolder.serverId.equals(folder)) { currentFolder.loading = loading; } updateMoreMessagesOfCurrentFolder(); updateFooterView(); } public void updateTitle() { if (!initialized) { return; } setWindowTitle(); if (!search.isManualSearch()) { setWindowProgress(); } } private void setWindowProgress() { int level = Window.PROGRESS_END; if (currentFolder != null && currentFolder.loading && activityListener.getFolderTotal() > 0) { int divisor = activityListener.getFolderTotal(); if (divisor != 0) { level = (Window.PROGRESS_END / divisor) * (activityListener.getFolderCompleted()) ; if (level > Window.PROGRESS_END) { level = Window.PROGRESS_END; } } } fragmentListener.setMessageListProgress(level); } private void setWindowTitle() { // regular folder content display if (!isManualSearch() && singleFolderMode) { fragmentListener.setMessageListTitle(currentFolder.displayName); } else { // query result display. This may be for a search folder as opposed to a user-initiated search. if (title != null) { // This was a search folder; the search folder has overridden our title. fragmentListener.setMessageListTitle(title); } else { // This is a search result; set it to the default search result line. fragmentListener.setMessageListTitle(getString(R.string.search_results)); } } } void progress(final boolean progress) { fragmentListener.enableActionBarProgress(progress); if (swipeRefreshLayout != null && !progress) { swipeRefreshLayout.setRefreshing(false); } } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (view == footerView) { if (currentFolder != null && !search.isManualSearch() && currentFolder.moreMessages) { messagingController.loadMoreMessages(account, folderServerId, null); } else if (currentFolder != null && isRemoteSearch() && extraSearchResults != null && extraSearchResults.size() > 0) { int numResults = extraSearchResults.size(); int limit = account.getRemoteSearchNumResults(); List<String> toProcess = extraSearchResults; if (limit > 0 && numResults > limit) { toProcess = toProcess.subList(0, limit); extraSearchResults = extraSearchResults.subList(limit, extraSearchResults.size()); } else { extraSearchResults = null; updateFooter(null); } messagingController.loadSearchResults(account, currentFolder.serverId, toProcess, activityListener); } return; } Cursor cursor = (Cursor) parent.getItemAtPosition(position); if (cursor == null) { return; } if (selectedCount > 0) { toggleMessageSelect(position); } else { if (showingThreadedList && cursor.getInt(THREAD_COUNT_COLUMN) > 1) { Account account = getAccountFromCursor(cursor); String folderServerId = cursor.getString(FOLDER_SERVER_ID_COLUMN); // If threading is enabled and this item represents a thread, display the thread contents. long rootId = cursor.getLong(THREAD_ROOT_COLUMN); fragmentListener.showThread(account, folderServerId, rootId); } else { // This item represents a message; just display the message. openMessageAtPosition(listViewToAdapterPosition(position)); } } } @Override public void onAttach(Activity activity) { super.onAttach(activity); context = activity.getApplicationContext(); try { fragmentListener = (MessageListFragmentListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.getClass() + " must implement MessageListFragmentListener"); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Context appContext = getActivity().getApplicationContext(); preferences = Preferences.getPreferences(appContext); messagingController = MessagingController.getInstance(getActivity().getApplication()); previewLines = K9.getMessageListPreviewLines(); checkboxes = K9.isShowMessageListCheckboxes(); stars = K9.isShowMessageListStars(); if (K9.isShowContactPicture()) { contactsPictureLoader = ContactPicture.getContactPictureLoader(); } restoreInstanceState(savedInstanceState); decodeArguments(); createCacheBroadcastReceiver(appContext); initialized = true; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { layoutInflater = inflater; View view = inflater.inflate(R.layout.message_list_fragment, container, false); initializePullToRefresh(view); initializeLayout(); listView.setVerticalFadingEdgeEnabled(false); return view; } @Override public void onDestroyView() { savedListState = listView.onSaveInstanceState(); super.onDestroyView(); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); messageHelper = MessageHelper.getInstance(getActivity()); initializeMessageList(); // This needs to be done before initializing the cursor loader below initializeSortSettings(); loaderJustInitialized = true; LoaderManager loaderManager = getLoaderManager(); int len = accountUuids.length; cursors = new Cursor[len]; cursorValid = new boolean[len]; for (int i = 0; i < len; i++) { loaderManager.initLoader(i, null, this); cursorValid[i] = false; } } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); saveSelectedMessages(outState); saveListState(outState); outState.putBoolean(STATE_REMOTE_SEARCH_PERFORMED, remoteSearchPerformed); if (activeMessage != null) { outState.putString(STATE_ACTIVE_MESSAGE, activeMessage.toIdentityString()); } } /** * Restore the state of a previous {@link MessageListFragment} instance. * * @see #onSaveInstanceState(Bundle) */ private void restoreInstanceState(Bundle savedInstanceState) { if (savedInstanceState == null) { return; } restoreSelectedMessages(savedInstanceState); remoteSearchPerformed = savedInstanceState.getBoolean(STATE_REMOTE_SEARCH_PERFORMED); savedListState = savedInstanceState.getParcelable(STATE_MESSAGE_LIST); String messageReferenceString = savedInstanceState.getString(STATE_ACTIVE_MESSAGE); activeMessage = MessageReference.parse(messageReferenceString); } /** * Write the unique IDs of selected messages to a {@link Bundle}. */ private void saveSelectedMessages(Bundle outState) { long[] selected = new long[this.selected.size()]; int i = 0; for (Long id : this.selected) { selected[i++] = id; } outState.putLongArray(STATE_SELECTED_MESSAGES, selected); } /** * Restore selected messages from a {@link Bundle}. */ private void restoreSelectedMessages(Bundle savedInstanceState) { long[] selected = savedInstanceState.getLongArray(STATE_SELECTED_MESSAGES); if (selected != null) { for (long id : selected) { this.selected.add(id); } } } private void saveListState(Bundle outState) { if (savedListState != null) { // The previously saved state was never restored, so just use that. outState.putParcelable(STATE_MESSAGE_LIST, savedListState); } else if (listView != null) { outState.putParcelable(STATE_MESSAGE_LIST, listView.onSaveInstanceState()); } } private void initializeSortSettings() { if (singleAccountMode) { sortType = account.getSortType(); sortAscending = account.isSortAscending(sortType); sortDateAscending = account.isSortAscending(SortType.SORT_DATE); } else { sortType = K9.getSortType(); sortAscending = K9.isSortAscending(sortType); sortDateAscending = K9.isSortAscending(SortType.SORT_DATE); } } private void decodeArguments() { Bundle args = getArguments(); showingThreadedList = args.getBoolean(ARG_THREADED_LIST, false); isThreadDisplay = args.getBoolean(ARG_IS_THREAD_DISPLAY, false); search = args.getParcelable(ARG_SEARCH); title = search.getName(); String[] accountUuids = search.getAccountUuids(); singleAccountMode = false; if (accountUuids.length == 1 && !search.searchAllAccounts()) { singleAccountMode = true; account = preferences.getAccount(accountUuids[0]); } singleFolderMode = false; if (singleAccountMode && (search.getFolderServerIds().size() == 1)) { singleFolderMode = true; folderServerId = search.getFolderServerIds().get(0); currentFolder = getFolderInfoHolder(folderServerId, account); } allAccounts = false; if (singleAccountMode) { this.accountUuids = new String[] { account.getUuid() }; } else { if (accountUuids.length == 1 && accountUuids[0].equals(SearchSpecification.ALL_ACCOUNTS)) { allAccounts = true; List<Account> accounts = preferences.getAccounts(); this.accountUuids = new String[accounts.size()]; for (int i = 0, len = accounts.size(); i < len; i++) { this.accountUuids[i] = accounts.get(i).getUuid(); } if (this.accountUuids.length == 1) { singleAccountMode = true; account = accounts.get(0); } } else { this.accountUuids = accountUuids; } } } private void initializeMessageList() { adapter = new MessageListAdapter(this); if (folderServerId != null) { currentFolder = getFolderInfoHolder(folderServerId, account); } if (singleFolderMode) { listView.addFooterView(getFooterView(listView)); updateFooterView(); } listView.setAdapter(adapter); } private void createCacheBroadcastReceiver(Context appContext) { localBroadcastManager = LocalBroadcastManager.getInstance(appContext); cacheBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { adapter.notifyDataSetChanged(); } }; cacheIntentFilter = new IntentFilter(EmailProviderCache.ACTION_CACHE_UPDATED); } private FolderInfoHolder getFolderInfoHolder(String folderServerId, Account account) { try { LocalFolder localFolder = MlfUtils.getOpenFolder(folderServerId, account); return new FolderInfoHolder(localFolder, account); } catch (MessagingException e) { throw new RuntimeException(e); } } @Override public void onPause() { super.onPause(); localBroadcastManager.unregisterReceiver(cacheBroadcastReceiver); activityListener.onPause(getActivity()); messagingController.removeListener(activityListener); } /** * On resume we refresh messages for the folder that is currently open. * This guarantees that things like unread message count and read status * are updated. */ @Override public void onResume() { super.onResume(); senderAboveSubject = K9.isMessageListSenderAboveSubject(); if (!loaderJustInitialized) { restartLoader(); } else { loaderJustInitialized = false; } // Check if we have connectivity. Cache the value. if (hasConnectivity == null) { hasConnectivity = Utility.hasConnectivity(getActivity().getApplication()); } localBroadcastManager.registerReceiver(cacheBroadcastReceiver, cacheIntentFilter); activityListener.onResume(getActivity()); messagingController.addListener(activityListener); //Cancel pending new mail notifications when we open an account List<Account> accountsWithNotification; Account account = this.account; if (account != null) { accountsWithNotification = Collections.singletonList(account); } else { accountsWithNotification = preferences.getAccounts(); } for (Account accountWithNotification : accountsWithNotification) { messagingController.cancelNotificationsForAccount(accountWithNotification); } if (this.account != null && folderServerId != null && !search.isManualSearch()) { messagingController.getFolderUnreadMessageCount(this.account, folderServerId, activityListener); } updateTitle(); } private void restartLoader() { if (cursorValid == null) { return; } // Refresh the message list LoaderManager loaderManager = getLoaderManager(); for (int i = 0; i < accountUuids.length; i++) { loaderManager.restartLoader(i, null, this); cursorValid[i] = false; } } private void initializePullToRefresh(View layout) { swipeRefreshLayout = layout.findViewById(R.id.swiperefresh); listView = layout.findViewById(R.id.message_list); if (isRemoteSearchAllowed()) { swipeRefreshLayout.setOnRefreshListener( new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { onRemoteSearchRequested(); } } ); } else if (isCheckMailSupported()) { swipeRefreshLayout.setOnRefreshListener( new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { checkMail(); } } ); } // Disable pull-to-refresh until the message list has been loaded swipeRefreshLayout.setEnabled(false); } private void initializeLayout() { listView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); listView.setLongClickable(true); listView.setFastScrollEnabled(true); listView.setScrollingCacheEnabled(false); listView.setOnItemClickListener(this); registerForContextMenu(listView); } public void onCompose() { if (!singleAccountMode) { /* * If we have a query string, we don't have an account to let * compose start the default action. */ fragmentListener.onCompose(null); } else { fragmentListener.onCompose(account); } } private void onReply(MessageReference messageReference) { fragmentListener.onReply(messageReference); } private void onReplyAll(MessageReference messageReference) { fragmentListener.onReplyAll(messageReference); } private void onForward(MessageReference messageReference) { fragmentListener.onForward(messageReference); } public void onForwardAsAttachment(MessageReference messageReference) { fragmentListener.onForwardAsAttachment(messageReference); } private void onResendMessage(MessageReference messageReference) { fragmentListener.onResendMessage(messageReference); } public void changeSort(SortType sortType) { Boolean sortAscending = (this.sortType == sortType) ? !this.sortAscending : null; changeSort(sortType, sortAscending); } /** * User has requested a remote search. Setup the bundle and start the intent. */ private void onRemoteSearchRequested() { String searchAccount; String searchFolder; searchAccount = account.getUuid(); searchFolder = currentFolder.serverId; String queryString = search.getRemoteSearchArguments(); remoteSearchPerformed = true; remoteSearchFuture = messagingController.searchRemoteMessages(searchAccount, searchFolder, queryString, null, null, activityListener); swipeRefreshLayout.setEnabled(false); fragmentListener.remoteSearchStarted(); } /** * Change the sort type and sort order used for the message list. * * @param sortType * Specifies which field to use for sorting the message list. * @param sortAscending * Specifies the sort order. If this argument is {@code null} the default search order * for the sort type is used. */ // FIXME: Don't save the changes in the UI thread private void changeSort(SortType sortType, Boolean sortAscending) { this.sortType = sortType; Account account = this.account; if (account != null) { account.setSortType(this.sortType); if (sortAscending == null) { this.sortAscending = account.isSortAscending(this.sortType); } else { this.sortAscending = sortAscending; } account.setSortAscending(this.sortType, this.sortAscending); sortDateAscending = account.isSortAscending(SortType.SORT_DATE); Preferences.getPreferences(getContext()).saveAccount(account); } else { K9.setSortType(this.sortType); if (sortAscending == null) { this.sortAscending = K9.isSortAscending(this.sortType); } else { this.sortAscending = sortAscending; } K9.setSortAscending(this.sortType, this.sortAscending); sortDateAscending = K9.isSortAscending(SortType.SORT_DATE); StorageEditor editor = preferences.createStorageEditor(); K9.save(editor); editor.commit(); } reSort(); } private void reSort() { int toastString = sortTypeToastProvider.getToast(sortType, sortAscending); Toast toast = Toast.makeText(getActivity(), toastString, Toast.LENGTH_SHORT); toast.show(); LoaderManager loaderManager = getLoaderManager(); for (int i = 0, len = accountUuids.length; i < len; i++) { loaderManager.restartLoader(i, null, this); } } public void onCycleSort() { SortType[] sorts = SortType.values(); int curIndex = 0; for (int i = 0; i < sorts.length; i++) { if (sorts[i] == sortType) { curIndex = i; break; } } curIndex++; if (curIndex == sorts.length) { curIndex = 0; } changeSort(sorts[curIndex]); } private void onDelete(MessageReference message) { onDelete(Collections.singletonList(message)); } private void onDelete(List<MessageReference> messages) { if (K9.isConfirmDelete()) { // remember the message selection for #onCreateDialog(int) activeMessages = messages; showDialog(R.id.dialog_confirm_delete); } else { onDeleteConfirmed(messages); } } private void onDeleteConfirmed(List<MessageReference> messages) { if (showingThreadedList) { messagingController.deleteThreads(messages); } else { messagingController.deleteMessages(messages, null); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode != Activity.RESULT_OK) { return; } switch (requestCode) { case ACTIVITY_CHOOSE_FOLDER_MOVE: case ACTIVITY_CHOOSE_FOLDER_COPY: { if (data == null) { return; } final String destFolder = data.getStringExtra(ChooseFolder.EXTRA_NEW_FOLDER); final List<MessageReference> messages = activeMessages; if (destFolder != null) { activeMessages = null; // don't need it any more if (messages.size() > 0) { MlfUtils.setLastSelectedFolder(preferences, messages, destFolder); } switch (requestCode) { case ACTIVITY_CHOOSE_FOLDER_MOVE: move(messages, destFolder); break; case ACTIVITY_CHOOSE_FOLDER_COPY: copy(messages, destFolder); break; } } break; } } } public void onExpunge() { if (currentFolder != null) { onExpunge(account, currentFolder.serverId); } } private void onExpunge(final Account account, String folderServerId) { messagingController.expunge(account, folderServerId); } public void onEmptyTrash() { if (isShowingTrashFolder()) { showDialog(R.id.dialog_confirm_empty_trash); } } public boolean isShowingTrashFolder() { return singleFolderMode && currentFolder != null && currentFolder.serverId.equals(account.getTrashFolder()); } private void showDialog(int dialogId) { DialogFragment fragment; if (dialogId == R.id.dialog_confirm_spam) { String title = getString(R.string.dialog_confirm_spam_title); int selectionSize = activeMessages.size(); String message = getResources().getQuantityString( R.plurals.dialog_confirm_spam_message, selectionSize, selectionSize); String confirmText = getString(R.string.dialog_confirm_spam_confirm_button); String cancelText = getString(R.string.dialog_confirm_spam_cancel_button); fragment = ConfirmationDialogFragment.newInstance(dialogId, title, message, confirmText, cancelText); } else if (dialogId == R.id.dialog_confirm_delete) { String title = getString(R.string.dialog_confirm_delete_title); int selectionSize = activeMessages.size(); String message = getResources().getQuantityString( R.plurals.dialog_confirm_delete_messages, selectionSize, selectionSize); String confirmText = getString(R.string.dialog_confirm_delete_confirm_button); String cancelText = getString(R.string.dialog_confirm_delete_cancel_button); fragment = ConfirmationDialogFragment.newInstance(dialogId, title, message, confirmText, cancelText); } else if (dialogId == R.id.dialog_confirm_mark_all_as_read) { String title = getString(R.string.dialog_confirm_mark_all_as_read_title); String message = getString(R.string.dialog_confirm_mark_all_as_read_message); String confirmText = getString(R.string.dialog_confirm_mark_all_as_read_confirm_button); String cancelText = getString(R.string.dialog_confirm_mark_all_as_read_cancel_button); fragment = ConfirmationDialogFragment.newInstance(dialogId, title, message, confirmText, cancelText); } else if (dialogId == R.id.dialog_confirm_empty_trash) { String title = getString(R.string.dialog_confirm_empty_trash_title); String message = getString(R.string.dialog_confirm_empty_trash_message); String confirmText = getString(R.string.dialog_confirm_delete_confirm_button); String cancelText = getString(R.string.dialog_confirm_delete_cancel_button); fragment = ConfirmationDialogFragment.newInstance(dialogId, title, message, confirmText, cancelText); } else { throw new RuntimeException("Called showDialog(int) with unknown dialog id."); } fragment.setTargetFragment(this, dialogId); fragment.show(getFragmentManager(), getDialogTag(dialogId)); } private String getDialogTag(int dialogId) { return "dialog-" + dialogId; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.set_sort_date) { changeSort(SortType.SORT_DATE); return true; } else if (id == R.id.set_sort_arrival) { changeSort(SortType.SORT_ARRIVAL); return true; } else if (id == R.id.set_sort_subject) { changeSort(SortType.SORT_SUBJECT); return true; } else if (id == R.id.set_sort_sender) { changeSort(SortType.SORT_SENDER); return true; } else if (id == R.id.set_sort_flag) { changeSort(SortType.SORT_FLAGGED); return true; } else if (id == R.id.set_sort_unread) { changeSort(SortType.SORT_UNREAD); return true; } else if (id == R.id.set_sort_attach) { changeSort(SortType.SORT_ATTACHMENT); return true; } else if (id == R.id.select_all) { selectAll(); return true; } if (!singleAccountMode) { // None of the options after this point are "safe" for search results //TODO: This is not true for "unread" and "starred" searches in regular folders return false; } if (id == R.id.send_messages) { onSendPendingMessages(); return true; } else if (id == R.id.expunge) { if (currentFolder != null) { onExpunge(account, currentFolder.serverId); } return true; } else { return super.onOptionsItemSelected(item); } } public void onSendPendingMessages() { messagingController.sendPendingMessages(account, null); } @Override public boolean onContextItemSelected(android.view.MenuItem item) { if (contextMenuUniqueId == 0) { return false; } int adapterPosition = getPositionForUniqueId(contextMenuUniqueId); if (adapterPosition == AdapterView.INVALID_POSITION) { return false; } int id = item.getItemId(); if (id == R.id.deselect || id == R.id.select) { toggleMessageSelectWithAdapterPosition(adapterPosition); } else if (id == R.id.reply) { onReply(getMessageAtPosition(adapterPosition)); } else if (id == R.id.reply_all) { onReplyAll(getMessageAtPosition(adapterPosition)); } else if (id == R.id.forward) { onForward(getMessageAtPosition(adapterPosition)); } else if (id == R.id.forward_as_attachment) { onForwardAsAttachment(getMessageAtPosition(adapterPosition)); } else if (id == R.id.send_again) { onResendMessage(getMessageAtPosition(adapterPosition)); selectedCount = 0; } else if (id == R.id.same_sender) { Cursor cursor = (Cursor) adapter.getItem(adapterPosition); String senderAddress = MlfUtils.getSenderAddressFromCursor(cursor); if (senderAddress != null) { fragmentListener.showMoreFromSameSender(senderAddress); } } else if (id == R.id.delete) { MessageReference message = getMessageAtPosition(adapterPosition); onDelete(message); } else if (id == R.id.mark_as_read) { setFlag(adapterPosition, Flag.SEEN, true); } else if (id == R.id.mark_as_unread) { setFlag(adapterPosition, Flag.SEEN, false); } else if (id == R.id.flag) { setFlag(adapterPosition, Flag.FLAGGED, true); } else if (id == R.id.unflag) { setFlag(adapterPosition, Flag.FLAGGED, false); } else if (id == R.id.archive) { // only if the account supports this onArchive(getMessageAtPosition(adapterPosition)); } else if (id == R.id.spam) { onSpam(getMessageAtPosition(adapterPosition)); } else if (id == R.id.move) { onMove(getMessageAtPosition(adapterPosition)); } else if (id == R.id.copy) { onCopy(getMessageAtPosition(adapterPosition)); } else if (id == R.id.debug_delete_locally) { // debug options onDebugClearLocally(getMessageAtPosition(adapterPosition)); } contextMenuUniqueId = 0; return true; } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; Cursor cursor = (Cursor) listView.getItemAtPosition(info.position); if (cursor == null) { return; } getActivity().getMenuInflater().inflate(R.menu.message_list_item_context, menu); menu.findItem(R.id.debug_delete_locally).setVisible(K9.DEVELOPER_MODE); contextMenuUniqueId = cursor.getLong(uniqueIdColumn); Account account = getAccountFromCursor(cursor); String subject = cursor.getString(SUBJECT_COLUMN); boolean read = (cursor.getInt(READ_COLUMN) == 1); boolean flagged = (cursor.getInt(FLAGGED_COLUMN) == 1); menu.setHeaderTitle(subject); if (selected.contains(contextMenuUniqueId)) { menu.findItem(R.id.select).setVisible(false); } else { menu.findItem(R.id.deselect).setVisible(false); } if (read) { menu.findItem(R.id.mark_as_read).setVisible(false); } else { menu.findItem(R.id.mark_as_unread).setVisible(false); } if (flagged) { menu.findItem(R.id.flag).setVisible(false); } else { menu.findItem(R.id.unflag).setVisible(false); } if (!messagingController.isCopyCapable(account)) { menu.findItem(R.id.copy).setVisible(false); } if (!messagingController.isMoveCapable(account)) { menu.findItem(R.id.move).setVisible(false); menu.findItem(R.id.archive).setVisible(false); menu.findItem(R.id.spam).setVisible(false); } if (!account.hasArchiveFolder()) { menu.findItem(R.id.archive).setVisible(false); } if (!account.hasSpamFolder()) { menu.findItem(R.id.spam).setVisible(false); } } public void onSwipeRightToLeft(final MotionEvent e1, final MotionEvent e2) { // Handle right-to-left as an un-select handleSwipe(e1, false); } public void onSwipeLeftToRight(final MotionEvent e1, final MotionEvent e2) { // Handle left-to-right as a select. handleSwipe(e1, true); } /** * Handle a select or unselect swipe event. * * @param downMotion * Event that started the swipe * @param selected * {@code true} if this was an attempt to select (i.e. left to right). */ private void handleSwipe(final MotionEvent downMotion, final boolean selected) { int x = (int) downMotion.getRawX(); int y = (int) downMotion.getRawY(); Rect headerRect = new Rect(); listView.getGlobalVisibleRect(headerRect); // Only handle swipes in the visible area of the message list if (headerRect.contains(x, y)) { int[] listPosition = new int[2]; listView.getLocationOnScreen(listPosition); int listX = x - listPosition[0]; int listY = y - listPosition[1]; int listViewPosition = listView.pointToPosition(listX, listY); toggleMessageSelect(listViewPosition); } } private int listViewToAdapterPosition(int position) { if (position >= 0 && position < adapter.getCount()) { return position; } return AdapterView.INVALID_POSITION; } private int adapterToListViewPosition(int position) { if (position >= 0 && position < adapter.getCount()) { return position; } return AdapterView.INVALID_POSITION; } class MessageListActivityListener extends ActivityListener { @Override public void remoteSearchFailed(String folderServerId, final String err) { handler.post(new Runnable() { @Override public void run() { Activity activity = getActivity(); if (activity != null) { Toast.makeText(activity, R.string.remote_search_error, Toast.LENGTH_LONG).show(); } } }); } @Override public void remoteSearchStarted(String folder) { handler.progress(true); handler.updateFooter(context.getString(R.string.remote_search_sending_query)); } @Override public void enableProgressIndicator(boolean enable) { handler.progress(enable); } @Override public void remoteSearchFinished(String folderServerId, int numResults, int maxResults, List<String> extraResults) { handler.progress(false); handler.remoteSearchFinished(); extraSearchResults = extraResults; if (extraResults != null && extraResults.size() > 0) { handler.updateFooter(String.format(context.getString(R.string.load_more_messages_fmt), maxResults)); } else { handler.updateFooter(null); } fragmentListener.setMessageListProgress(Window.PROGRESS_END); } @Override public void remoteSearchServerQueryComplete(String folderServerId, int numResults, int maxResults) { handler.progress(true); if (maxResults != 0 && numResults > maxResults) { handler.updateFooter(context.getResources().getQuantityString(R.plurals.remote_search_downloading_limited, maxResults, maxResults, numResults)); } else { handler.updateFooter(context.getResources().getQuantityString(R.plurals.remote_search_downloading, numResults, numResults)); } fragmentListener.setMessageListProgress(Window.PROGRESS_START); } @Override public void informUserOfStatus() { handler.refreshTitle(); } @Override public void synchronizeMailboxStarted(Account account, String folderServerId, String folderName) { if (updateForMe(account, folderServerId)) { handler.progress(true); handler.folderLoading(folderServerId, true); } super.synchronizeMailboxStarted(account, folderServerId, folderName); } @Override public void synchronizeMailboxFinished(Account account, String folderServerId, int totalMessagesInMailbox, int numNewMessages) { if (updateForMe(account, folderServerId)) { handler.progress(false); handler.folderLoading(folderServerId, false); } super.synchronizeMailboxFinished(account, folderServerId, totalMessagesInMailbox, numNewMessages); } @Override public void synchronizeMailboxFailed(Account account, String folderServerId, String message) { if (updateForMe(account, folderServerId)) { handler.progress(false); handler.folderLoading(folderServerId, false); } super.synchronizeMailboxFailed(account, folderServerId, message); } private boolean updateForMe(Account account, String folderServerId) { if (account == null || folderServerId == null) { return false; } if (!Utility.arrayContains(accountUuids, account.getUuid())) { return false; } List<String> folderServerIds = search.getFolderServerIds(); return (folderServerIds.isEmpty() || folderServerIds.contains(folderServerId)); } } private View getFooterView(ViewGroup parent) { if (footerView == null) { footerView = layoutInflater.inflate(R.layout.message_list_item_footer, parent, false); FooterViewHolder holder = new FooterViewHolder(); holder.main = footerView.findViewById(R.id.main_text); footerView.setTag(holder); } return footerView; } private void updateFooterView() { if (!search.isManualSearch() && currentFolder != null && account != null) { if (currentFolder.loading) { updateFooter(context.getString(R.string.status_loading_more)); } else if (!currentFolder.moreMessages) { updateFooter(null); } else { String message; if (!currentFolder.lastCheckFailed) { if (account.getDisplayCount() == 0) { message = context.getString(R.string.message_list_load_more_messages_action); } else { message = String.format(context.getString(R.string.load_more_messages_fmt), account.getDisplayCount()); } } else { message = context.getString(R.string.status_loading_more_failed); } updateFooter(message); } } else { updateFooter(null); } } public void updateFooter(final String text) { if (footerView == null) { return; } FooterViewHolder holder = (FooterViewHolder) footerView.getTag(); if (text != null) { holder.main.setText(text); holder.main.setVisibility(View.VISIBLE); } else { holder.main.setVisibility(View.GONE); } } static class FooterViewHolder { public TextView main; } /** * Set selection state for all messages. * * @param selected * If {@code true} all messages get selected. Otherwise, all messages get deselected and * action mode is finished. */ private void setSelectionState(boolean selected) { if (selected) { if (adapter.getCount() == 0) { // Nothing to do if there are no messages return; } selectedCount = 0; for (int i = 0, end = adapter.getCount(); i < end; i++) { Cursor cursor = (Cursor) adapter.getItem(i); long uniqueId = cursor.getLong(uniqueIdColumn); this.selected.add(uniqueId); if (showingThreadedList) { int threadCount = cursor.getInt(THREAD_COUNT_COLUMN); selectedCount += (threadCount > 1) ? threadCount : 1; } else { selectedCount++; } } if (actionMode == null) { startAndPrepareActionMode(); } computeBatchDirection(); updateActionModeTitle(); computeSelectAllVisibility(); } else { this.selected.clear(); selectedCount = 0; if (actionMode != null) { actionMode.finish(); actionMode = null; } } adapter.notifyDataSetChanged(); } private void toggleMessageSelect(int listViewPosition) { int adapterPosition = listViewToAdapterPosition(listViewPosition); if (adapterPosition == AdapterView.INVALID_POSITION) { return; } toggleMessageSelectWithAdapterPosition(adapterPosition); } void toggleMessageFlagWithAdapterPosition(int adapterPosition) { Cursor cursor = (Cursor) adapter.getItem(adapterPosition); boolean flagged = (cursor.getInt(FLAGGED_COLUMN) == 1); setFlag(adapterPosition,Flag.FLAGGED, !flagged); } void toggleMessageSelectWithAdapterPosition(int adapterPosition) { Cursor cursor = (Cursor) adapter.getItem(adapterPosition); long uniqueId = cursor.getLong(uniqueIdColumn); boolean selected = this.selected.contains(uniqueId); if (!selected) { this.selected.add(uniqueId); } else { this.selected.remove(uniqueId); } int selectedCountDelta = 1; if (showingThreadedList) { int threadCount = cursor.getInt(THREAD_COUNT_COLUMN); if (threadCount > 1) { selectedCountDelta = threadCount; } } if (actionMode != null) { if (selectedCount == selectedCountDelta && selected) { actionMode.finish(); actionMode = null; return; } } else { startAndPrepareActionMode(); } if (selected) { selectedCount -= selectedCountDelta; } else { selectedCount += selectedCountDelta; } computeBatchDirection(); updateActionModeTitle(); computeSelectAllVisibility(); adapter.notifyDataSetChanged(); } private void updateActionModeTitle() { actionMode.setTitle(String.format(getString(R.string.actionbar_selected), selectedCount)); } private void computeSelectAllVisibility() { actionModeCallback.showSelectAll(selected.size() != adapter.getCount()); } private void computeBatchDirection() { boolean isBatchFlag = false; boolean isBatchRead = false; for (int i = 0, end = adapter.getCount(); i < end; i++) { Cursor cursor = (Cursor) adapter.getItem(i); long uniqueId = cursor.getLong(uniqueIdColumn); if (selected.contains(uniqueId)) { boolean read = (cursor.getInt(READ_COLUMN) == 1); boolean flagged = (cursor.getInt(FLAGGED_COLUMN) == 1); if (!flagged) { isBatchFlag = true; } if (!read) { isBatchRead = true; } if (isBatchFlag && isBatchRead) { break; } } } actionModeCallback.showMarkAsRead(isBatchRead); actionModeCallback.showFlag(isBatchFlag); } private void setFlag(int adapterPosition, final Flag flag, final boolean newState) { if (adapterPosition == AdapterView.INVALID_POSITION) { return; } Cursor cursor = (Cursor) adapter.getItem(adapterPosition); Account account = preferences.getAccount(cursor.getString(ACCOUNT_UUID_COLUMN)); if (showingThreadedList && cursor.getInt(THREAD_COUNT_COLUMN) > 1) { long threadRootId = cursor.getLong(THREAD_ROOT_COLUMN); messagingController.setFlagForThreads(account, Collections.singletonList(threadRootId), flag, newState); } else { long id = cursor.getLong(ID_COLUMN); messagingController.setFlag(account, Collections.singletonList(id), flag, newState); } computeBatchDirection(); } private void setFlagForSelected(final Flag flag, final boolean newState) { if (selected.isEmpty()) { return; } Map<Account, List<Long>> messageMap = new HashMap<>(); Map<Account, List<Long>> threadMap = new HashMap<>(); Set<Account> accounts = new HashSet<>(); for (int position = 0, end = adapter.getCount(); position < end; position++) { Cursor cursor = (Cursor) adapter.getItem(position); long uniqueId = cursor.getLong(uniqueIdColumn); if (selected.contains(uniqueId)) { String uuid = cursor.getString(ACCOUNT_UUID_COLUMN); Account account = preferences.getAccount(uuid); accounts.add(account); if (showingThreadedList && cursor.getInt(THREAD_COUNT_COLUMN) > 1) { List<Long> threadRootIdList = threadMap.get(account); if (threadRootIdList == null) { threadRootIdList = new ArrayList<>(); threadMap.put(account, threadRootIdList); } threadRootIdList.add(cursor.getLong(THREAD_ROOT_COLUMN)); } else { List<Long> messageIdList = messageMap.get(account); if (messageIdList == null) { messageIdList = new ArrayList<>(); messageMap.put(account, messageIdList); } messageIdList.add(cursor.getLong(ID_COLUMN)); } } } for (Account account : accounts) { List<Long> messageIds = messageMap.get(account); List<Long> threadRootIds = threadMap.get(account); if (messageIds != null) { messagingController.setFlag(account, messageIds, flag, newState); } if (threadRootIds != null) { messagingController.setFlagForThreads(account, threadRootIds, flag, newState); } } computeBatchDirection(); } private void onMove(MessageReference message) { onMove(Collections.singletonList(message)); } /** * Display the message move activity. * * @param messages * Never {@code null}. */ private void onMove(List<MessageReference> messages) { if (!checkCopyOrMovePossible(messages, FolderOperation.MOVE)) { return; } String folderServerId; if (isThreadDisplay) { folderServerId = messages.get(0).getFolderServerId(); } else if (singleFolderMode) { folderServerId = currentFolder.folder.getServerId(); } else { folderServerId = null; } displayFolderChoice(ACTIVITY_CHOOSE_FOLDER_MOVE, folderServerId, messages.get(0).getAccountUuid(), null, messages); } private void onCopy(MessageReference message) { onCopy(Collections.singletonList(message)); } /** * Display the message copy activity. * * @param messages * Never {@code null}. */ private void onCopy(List<MessageReference> messages) { if (!checkCopyOrMovePossible(messages, FolderOperation.COPY)) { return; } String folderServerId; if (isThreadDisplay) { folderServerId = messages.get(0).getFolderServerId(); } else if (singleFolderMode) { folderServerId = currentFolder.folder.getServerId(); } else { folderServerId = null; } displayFolderChoice(ACTIVITY_CHOOSE_FOLDER_COPY, folderServerId, messages.get(0).getAccountUuid(), null, messages); } private void onDebugClearLocally(MessageReference message) { messagingController.debugClearMessagesLocally(Collections.singletonList(message)); } /** * Helper method to manage the invocation of {@link #startActivityForResult(Intent, int)} for a * folder operation ({@link ChooseFolder} activity), while saving a list of associated messages. * * @param requestCode * If {@code >= 0}, this code will be returned in {@code onActivityResult()} when the * activity exits. * * @see #startActivityForResult(Intent, int) */ private void displayFolderChoice(int requestCode, String sourceFolder, String accountUuid, String lastSelectedFolder, List<MessageReference> messages) { Intent intent = new Intent(getActivity(), ChooseFolder.class); intent.putExtra(ChooseFolder.EXTRA_ACCOUNT, accountUuid); intent.putExtra(ChooseFolder.EXTRA_SEL_FOLDER, lastSelectedFolder); if (sourceFolder == null) { intent.putExtra(ChooseFolder.EXTRA_SHOW_CURRENT, "yes"); } else { intent.putExtra(ChooseFolder.EXTRA_CUR_FOLDER, sourceFolder); } // remember the selected messages for #onActivityResult activeMessages = messages; startActivityForResult(intent, requestCode); } private void onArchive(MessageReference message) { onArchive(Collections.singletonList(message)); } private void onArchive(final List<MessageReference> messages) { Map<Account, List<MessageReference>> messagesByAccount = groupMessagesByAccount(messages); for (Entry<Account, List<MessageReference>> entry : messagesByAccount.entrySet()) { Account account = entry.getKey(); String archiveFolder = account.getArchiveFolder(); if (archiveFolder != null) { move(entry.getValue(), archiveFolder); } } } private Map<Account, List<MessageReference>> groupMessagesByAccount(final List<MessageReference> messages) { Map<Account, List<MessageReference>> messagesByAccount = new HashMap<>(); for (MessageReference message : messages) { Account account = preferences.getAccount(message.getAccountUuid()); List<MessageReference> msgList = messagesByAccount.get(account); if (msgList == null) { msgList = new ArrayList<>(); messagesByAccount.put(account, msgList); } msgList.add(message); } return messagesByAccount; } private void onSpam(MessageReference message) { onSpam(Collections.singletonList(message)); } /** * Move messages to the spam folder. * * @param messages * The messages to move to the spam folder. Never {@code null}. */ private void onSpam(List<MessageReference> messages) { if (K9.isConfirmSpam()) { // remember the message selection for #onCreateDialog(int) activeMessages = messages; showDialog(R.id.dialog_confirm_spam); } else { onSpamConfirmed(messages); } } private void onSpamConfirmed(List<MessageReference> messages) { Map<Account, List<MessageReference>> messagesByAccount = groupMessagesByAccount(messages); for (Entry<Account, List<MessageReference>> entry : messagesByAccount.entrySet()) { Account account = entry.getKey(); String spamFolder = account.getSpamFolder(); if (spamFolder != null) { move(entry.getValue(), spamFolder); } } } private enum FolderOperation { COPY, MOVE } /** * Display a Toast message if any message isn't synchronized * * @param messages * The messages to copy or move. Never {@code null}. * @param operation * The type of operation to perform. Never {@code null}. * * @return {@code true}, if operation is possible. */ private boolean checkCopyOrMovePossible(final List<MessageReference> messages, final FolderOperation operation) { if (messages.isEmpty()) { return false; } boolean first = true; for (MessageReference message : messages) { if (first) { first = false; Account account = preferences.getAccount(message.getAccountUuid()); if ((operation == FolderOperation.MOVE && !messagingController.isMoveCapable(account)) || (operation == FolderOperation.COPY && !messagingController.isCopyCapable(account))) { return false; } } // message check if ((operation == FolderOperation.MOVE && !messagingController.isMoveCapable(message)) || (operation == FolderOperation.COPY && !messagingController.isCopyCapable(message))) { final Toast toast = Toast.makeText(getActivity(), R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG); toast.show(); return false; } } return true; } /** * Copy the specified messages to the specified folder. * * @param messages * List of messages to copy. Never {@code null}. * @param destination * The name of the destination folder. Never {@code null}. */ private void copy(List<MessageReference> messages, final String destination) { copyOrMove(messages, destination, FolderOperation.COPY); } /** * Move the specified messages to the specified folder. * * @param messages * The list of messages to move. Never {@code null}. * @param destination * The name of the destination folder. Never {@code null}. */ private void move(List<MessageReference> messages, final String destination) { copyOrMove(messages, destination, FolderOperation.MOVE); } /** * The underlying implementation for {@link #copy(List, String)} and * {@link #move(List, String)}. This method was added mainly because those 2 * methods share common behavior. * * @param messages * The list of messages to copy or move. Never {@code null}. * @param destination * The name of the destination folder. Never {@code null}. * @param operation * Specifies what operation to perform. Never {@code null}. */ private void copyOrMove(List<MessageReference> messages, final String destination, final FolderOperation operation) { Map<String, List<MessageReference>> folderMap = new HashMap<>(); for (MessageReference message : messages) { if ((operation == FolderOperation.MOVE && !messagingController.isMoveCapable(message)) || (operation == FolderOperation.COPY && !messagingController.isCopyCapable(message))) { Toast.makeText(getActivity(), R.string.move_copy_cannot_copy_unsynced_message, Toast.LENGTH_LONG).show(); // XXX return meaningful error value? // message isn't synchronized return; } String folderServerId = message.getFolderServerId(); if (folderServerId.equals(destination)) { // Skip messages already in the destination folder continue; } List<MessageReference> outMessages = folderMap.get(folderServerId); if (outMessages == null) { outMessages = new ArrayList<>(); folderMap.put(folderServerId, outMessages); } outMessages.add(message); } for (Map.Entry<String, List<MessageReference>> entry : folderMap.entrySet()) { String folderServerId = entry.getKey(); List<MessageReference> outMessages = entry.getValue(); Account account = preferences.getAccount(outMessages.get(0).getAccountUuid()); if (operation == FolderOperation.MOVE) { if (showingThreadedList) { messagingController.moveMessagesInThread(account, folderServerId, outMessages, destination); } else { messagingController.moveMessages(account, folderServerId, outMessages, destination); } } else { if (showingThreadedList) { messagingController.copyMessagesInThread(account, folderServerId, outMessages, destination); } else { messagingController.copyMessages(account, folderServerId, outMessages, destination); } } } } class ActionModeCallback implements ActionMode.Callback { private MenuItem mSelectAll; private MenuItem mMarkAsRead; private MenuItem mMarkAsUnread; private MenuItem mFlag; private MenuItem mUnflag; @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { mSelectAll = menu.findItem(R.id.select_all); mMarkAsRead = menu.findItem(R.id.mark_as_read); mMarkAsUnread = menu.findItem(R.id.mark_as_unread); mFlag = menu.findItem(R.id.flag); mUnflag = menu.findItem(R.id.unflag); // we don't support cross account actions atm if (!singleAccountMode) { // show all menu.findItem(R.id.move).setVisible(true); menu.findItem(R.id.archive).setVisible(true); menu.findItem(R.id.spam).setVisible(true); menu.findItem(R.id.copy).setVisible(true); Set<String> accountUuids = getAccountUuidsForSelected(); for (String accountUuid : accountUuids) { Account account = preferences.getAccount(accountUuid); if (account != null) { setContextCapabilities(account, menu); } } } return true; } /** * Get the set of account UUIDs for the selected messages. */ private Set<String> getAccountUuidsForSelected() { int maxAccounts = accountUuids.length; Set<String> accountUuids = new HashSet<>(maxAccounts); for (int position = 0, end = adapter.getCount(); position < end; position++) { Cursor cursor = (Cursor) adapter.getItem(position); long uniqueId = cursor.getLong(uniqueIdColumn); if (selected.contains(uniqueId)) { String accountUuid = cursor.getString(ACCOUNT_UUID_COLUMN); accountUuids.add(accountUuid); if (accountUuids.size() == MessageListFragment.this.accountUuids.length) { break; } } } return accountUuids; } @Override public void onDestroyActionMode(ActionMode mode) { actionMode = null; mSelectAll = null; mMarkAsRead = null; mMarkAsUnread = null; mFlag = null; mUnflag = null; setSelectionState(false); } @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { MenuInflater inflater = mode.getMenuInflater(); inflater.inflate(R.menu.message_list_context, menu); // check capabilities setContextCapabilities(account, menu); return true; } /** * Disables menu options not supported by the account type or current "search view". * * @param account * The account to query for its capabilities. * @param menu * The menu to adapt. */ private void setContextCapabilities(Account account, Menu menu) { if (!singleAccountMode) { // We don't support cross-account copy/move operations right now menu.findItem(R.id.move).setVisible(false); menu.findItem(R.id.copy).setVisible(false); //TODO: we could support the archive and spam operations if all selected messages // belong to non-POP3 accounts menu.findItem(R.id.archive).setVisible(false); menu.findItem(R.id.spam).setVisible(false); } else { // hide unsupported if (!messagingController.isCopyCapable(account)) { menu.findItem(R.id.copy).setVisible(false); } if (!messagingController.isMoveCapable(account)) { menu.findItem(R.id.move).setVisible(false); menu.findItem(R.id.archive).setVisible(false); menu.findItem(R.id.spam).setVisible(false); } if (!account.hasArchiveFolder()) { menu.findItem(R.id.archive).setVisible(false); } if (!account.hasSpamFolder()) { menu.findItem(R.id.spam).setVisible(false); } } } public void showSelectAll(boolean show) { if (actionMode != null) { mSelectAll.setVisible(show); } } public void showMarkAsRead(boolean show) { if (actionMode != null) { mMarkAsRead.setVisible(show); mMarkAsUnread.setVisible(!show); } } public void showFlag(boolean show) { if (actionMode != null) { mFlag.setVisible(show); mUnflag.setVisible(!show); } } @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { /* * In the following we assume that we can't move or copy * mails to the same folder. Also that spam isn't available if we are * in the spam folder,same for archive. * * This is the case currently so safe assumption. */ int id = item.getItemId(); if (id == R.id.delete) { List<MessageReference> messages = getCheckedMessages(); onDelete(messages); selectedCount = 0; } else if (id == R.id.mark_as_read) { setFlagForSelected(Flag.SEEN, true); } else if (id == R.id.mark_as_unread) { setFlagForSelected(Flag.SEEN, false); } else if (id == R.id.flag) { setFlagForSelected(Flag.FLAGGED, true); } else if (id == R.id.unflag) { setFlagForSelected(Flag.FLAGGED, false); } else if (id == R.id.select_all) { selectAll(); } else if (id == R.id.archive) { // only if the account supports this onArchive(getCheckedMessages()); selectedCount = 0; } else if (id == R.id.spam) { onSpam(getCheckedMessages()); selectedCount = 0; } else if (id == R.id.move) { onMove(getCheckedMessages()); selectedCount = 0; } else if (id == R.id.copy) { onCopy(getCheckedMessages()); selectedCount = 0; } if (selectedCount == 0) { actionMode.finish(); } return true; } } @Override public void doPositiveClick(int dialogId) { if (dialogId == R.id.dialog_confirm_spam) { onSpamConfirmed(activeMessages); // No further need for this reference activeMessages = null; } else if (dialogId == R.id.dialog_confirm_delete) { onDeleteConfirmed(activeMessages); activeMessage = null; } else if (dialogId == R.id.dialog_confirm_mark_all_as_read) { markAllAsRead(); } else if (dialogId == R.id.dialog_confirm_empty_trash) { messagingController.emptyTrash(account, null); } } @Override public void doNegativeClick(int dialogId) { if (dialogId == R.id.dialog_confirm_spam || dialogId == R.id.dialog_confirm_delete) { // No further need for this reference activeMessages = null; } } @Override public void dialogCancelled(int dialogId) { doNegativeClick(dialogId); } public void checkMail() { if (isSingleAccountMode() && isSingleFolderMode()) { messagingController.synchronizeMailbox(account, folderServerId, activityListener, null); messagingController.sendPendingMessages(account, activityListener); } else if (allAccounts) { messagingController.checkMail(context, null, true, true, activityListener); } else { for (String accountUuid : accountUuids) { Account account = preferences.getAccount(accountUuid); messagingController.checkMail(context, account, true, true, activityListener); } } } /** * We need to do some special clean up when leaving a remote search result screen. If no * remote search is in progress, this method does nothing special. */ @Override public void onStop() { // If we represent a remote search, then kill that before going back. if (isRemoteSearch() && remoteSearchFuture != null) { try { Timber.i("Remote search in progress, attempting to abort..."); // Canceling the future stops any message fetches in progress. final boolean cancelSuccess = remoteSearchFuture.cancel(true); // mayInterruptIfRunning = true if (!cancelSuccess) { Timber.e("Could not cancel remote search future."); } // Closing the folder will kill off the connection if we're mid-search. final Account searchAccount = account; final Folder remoteFolder = currentFolder.folder; remoteFolder.close(); // Send a remoteSearchFinished() message for good measure. activityListener .remoteSearchFinished(currentFolder.serverId, 0, searchAccount.getRemoteSearchNumResults(), null); } catch (Exception e) { // Since the user is going back, log and squash any exceptions. Timber.e(e, "Could not abort remote search before going back"); } } // Workaround for Android bug https://issuetracker.google.com/issues/37008170 if (swipeRefreshLayout != null) { swipeRefreshLayout.setRefreshing(false); swipeRefreshLayout.destroyDrawingCache(); swipeRefreshLayout.clearAnimation(); } super.onStop(); } public void selectAll() { setSelectionState(true); } public void onMoveUp() { int currentPosition = listView.getSelectedItemPosition(); if (currentPosition == AdapterView.INVALID_POSITION || listView.isInTouchMode()) { currentPosition = listView.getFirstVisiblePosition(); } if (currentPosition > 0) { listView.setSelection(currentPosition - 1); } } public void onMoveDown() { int currentPosition = listView.getSelectedItemPosition(); if (currentPosition == AdapterView.INVALID_POSITION || listView.isInTouchMode()) { currentPosition = listView.getFirstVisiblePosition(); } if (currentPosition < listView.getCount()) { listView.setSelection(currentPosition + 1); } } public boolean openPrevious(MessageReference messageReference) { int position = getPosition(messageReference); if (position <= 0) { return false; } openMessageAtPosition(position - 1); return true; } public boolean openNext(MessageReference messageReference) { int position = getPosition(messageReference); if (position < 0 || position == adapter.getCount() - 1) { return false; } openMessageAtPosition(position + 1); return true; } public boolean isFirst(MessageReference messageReference) { return adapter.isEmpty() || messageReference.equals(getReferenceForPosition(0)); } public boolean isLast(MessageReference messageReference) { return adapter.isEmpty() || messageReference.equals(getReferenceForPosition(adapter.getCount() - 1)); } private MessageReference getReferenceForPosition(int position) { Cursor cursor = (Cursor) adapter.getItem(position); String accountUuid = cursor.getString(ACCOUNT_UUID_COLUMN); String folderServerId = cursor.getString(FOLDER_SERVER_ID_COLUMN); String messageUid = cursor.getString(UID_COLUMN); return new MessageReference(accountUuid, folderServerId, messageUid, null); } private void openMessageAtPosition(int position) { // Scroll message into view if necessary int listViewPosition = adapterToListViewPosition(position); if (listViewPosition != AdapterView.INVALID_POSITION && (listViewPosition < listView.getFirstVisiblePosition() || listViewPosition > listView.getLastVisiblePosition())) { listView.setSelection(listViewPosition); } MessageReference ref = getReferenceForPosition(position); // For some reason the listView.setSelection() above won't do anything when we call // onOpenMessage() (and consequently adapter.notifyDataSetChanged()) right away. So we // defer the call using MessageListHandler. handler.openMessage(ref); } private int getPosition(MessageReference messageReference) { for (int i = 0, len = adapter.getCount(); i < len; i++) { Cursor cursor = (Cursor) adapter.getItem(i); String accountUuid = cursor.getString(ACCOUNT_UUID_COLUMN); String folderServerId = cursor.getString(FOLDER_SERVER_ID_COLUMN); String uid = cursor.getString(UID_COLUMN); if (accountUuid.equals(messageReference.getAccountUuid()) && folderServerId.equals(messageReference.getFolderServerId()) && uid.equals(messageReference.getUid())) { return i; } } return -1; } public interface MessageListFragmentListener { void enableActionBarProgress(boolean enable); void setMessageListProgress(int level); void showThread(Account account, String folderServerId, long rootId); void showMoreFromSameSender(String senderAddress); void onResendMessage(MessageReference message); void onForward(MessageReference message); void onForwardAsAttachment(MessageReference message); void onReply(MessageReference message); void onReplyAll(MessageReference message); void openMessage(MessageReference messageReference); void setMessageListTitle(String title); void onCompose(Account account); boolean startSearch(Account account, String folderServerId); void remoteSearchStarted(); void goBack(); void updateMenu(); } public void onReverseSort() { changeSort(sortType); } private MessageReference getSelectedMessage() { int listViewPosition = listView.getSelectedItemPosition(); int adapterPosition = listViewToAdapterPosition(listViewPosition); return getMessageAtPosition(adapterPosition); } private int getAdapterPositionForSelectedMessage() { int listViewPosition = listView.getSelectedItemPosition(); return listViewToAdapterPosition(listViewPosition); } private int getPositionForUniqueId(long uniqueId) { for (int position = 0, end = adapter.getCount(); position < end; position++) { Cursor cursor = (Cursor) adapter.getItem(position); if (cursor.getLong(uniqueIdColumn) == uniqueId) { return position; } } return AdapterView.INVALID_POSITION; } private MessageReference getMessageAtPosition(int adapterPosition) { if (adapterPosition == AdapterView.INVALID_POSITION) { return null; } Cursor cursor = (Cursor) adapter.getItem(adapterPosition); String accountUuid = cursor.getString(ACCOUNT_UUID_COLUMN); String folderServerId = cursor.getString(FOLDER_SERVER_ID_COLUMN); String messageUid = cursor.getString(UID_COLUMN); return new MessageReference(accountUuid, folderServerId, messageUid, null); } private List<MessageReference> getCheckedMessages() { List<MessageReference> messages = new ArrayList<>(selected.size()); for (int position = 0, end = adapter.getCount(); position < end; position++) { Cursor cursor = (Cursor) adapter.getItem(position); long uniqueId = cursor.getLong(uniqueIdColumn); if (selected.contains(uniqueId)) { MessageReference message = getMessageAtPosition(position); if (message != null) { messages.add(message); } } } return messages; } public void onDelete() { MessageReference message = getSelectedMessage(); if (message != null) { onDelete(Collections.singletonList(message)); } } public void toggleMessageSelect() { toggleMessageSelect(listView.getSelectedItemPosition()); } public void onToggleFlagged() { onToggleFlag(Flag.FLAGGED, FLAGGED_COLUMN); } public void onToggleRead() { onToggleFlag(Flag.SEEN, READ_COLUMN); } private void onToggleFlag(Flag flag, int flagColumn) { int adapterPosition = getAdapterPositionForSelectedMessage(); if (adapterPosition == ListView.INVALID_POSITION) { return; } Cursor cursor = (Cursor) adapter.getItem(adapterPosition); boolean flagState = (cursor.getInt(flagColumn) == 1); setFlag(adapterPosition, flag, !flagState); } public void onMove() { MessageReference message = getSelectedMessage(); if (message != null) { onMove(message); } } public void onArchive() { MessageReference message = getSelectedMessage(); if (message != null) { onArchive(message); } } public void onCopy() { MessageReference message = getSelectedMessage(); if (message != null) { onCopy(message); } } public boolean isOutbox() { return (folderServerId != null && folderServerId.equals(account.getOutboxFolder())); } public boolean isRemoteFolder() { if (search.isManualSearch() || isOutbox()) { return false; } if (!messagingController.isMoveCapable(account)) { // For POP3 accounts only the Inbox is a remote folder. return (folderServerId != null && folderServerId.equals(account.getInboxFolder())); } return true; } public boolean isManualSearch() { return search.isManualSearch(); } public boolean isAccountExpungeCapable() { return account != null && messagingController.supportsExpunge(account); } public void onRemoteSearch() { // Remote search is useless without the network. if (hasConnectivity) { onRemoteSearchRequested(); } else { Toast.makeText(getActivity(), getText(R.string.remote_search_unavailable_no_network), Toast.LENGTH_SHORT).show(); } } public boolean isRemoteSearch() { return remoteSearchPerformed; } public boolean isRemoteSearchAllowed() { if (!search.isManualSearch() || remoteSearchPerformed || !singleFolderMode) { return false; } boolean allowRemoteSearch = false; final Account searchAccount = account; if (searchAccount != null) { allowRemoteSearch = searchAccount.isAllowRemoteSearch(); } return allowRemoteSearch; } public boolean onSearchRequested() { String folderServerId = (currentFolder != null) ? currentFolder.serverId : null; return fragmentListener.startSearch(account, folderServerId); } @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { String accountUuid = accountUuids[id]; Account account = preferences.getAccount(accountUuid); String threadId = getThreadId(search); Uri uri; String[] projection; boolean needConditions; if (threadId != null) { uri = Uri.withAppendedPath(EmailProvider.CONTENT_URI, "account/" + accountUuid + "/thread/" + threadId); projection = PROJECTION; needConditions = false; } else if (showingThreadedList) { uri = Uri.withAppendedPath(EmailProvider.CONTENT_URI, "account/" + accountUuid + "/messages/threaded"); projection = THREADED_PROJECTION; needConditions = true; } else { uri = Uri.withAppendedPath(EmailProvider.CONTENT_URI, "account/" + accountUuid + "/messages"); projection = PROJECTION; needConditions = true; } StringBuilder query = new StringBuilder(); List<String> queryArgs = new ArrayList<>(); if (needConditions) { boolean selectActive = activeMessage != null && activeMessage.getAccountUuid().equals(accountUuid); if (selectActive) { query.append("(" + MessageColumns.UID + " = ? AND " + SpecialColumns.FOLDER_SERVER_ID + " = ?) OR ("); queryArgs.add(activeMessage.getUid()); queryArgs.add(activeMessage.getFolderServerId()); } SqlQueryBuilder.buildWhereClause(account, search.getConditions(), query, queryArgs); if (selectActive) { query.append(')'); } } String selection = query.toString(); String[] selectionArgs = queryArgs.toArray(new String[0]); String sortOrder = buildSortOrder(); return new CursorLoader(getActivity(), uri, projection, selection, selectionArgs, sortOrder); } private String getThreadId(LocalSearch search) { for (ConditionsTreeNode node : search.getLeafSet()) { SearchCondition condition = node.mCondition; if (condition.field == SearchField.THREAD_ID) { return condition.value; } } return null; } private String buildSortOrder() { String sortColumn; switch (sortType) { case SORT_ARRIVAL: { sortColumn = MessageColumns.INTERNAL_DATE; break; } case SORT_ATTACHMENT: { sortColumn = "(" + MessageColumns.ATTACHMENT_COUNT + " < 1)"; break; } case SORT_FLAGGED: { sortColumn = "(" + MessageColumns.FLAGGED + " != 1)"; break; } case SORT_SENDER: { //FIXME sortColumn = MessageColumns.SENDER_LIST; break; } case SORT_SUBJECT: { sortColumn = MessageColumns.SUBJECT + " COLLATE NOCASE"; break; } case SORT_UNREAD: { sortColumn = MessageColumns.READ; break; } case SORT_DATE: default: { sortColumn = MessageColumns.DATE; } } String sortDirection = (sortAscending) ? " ASC" : " DESC"; String secondarySort; if (sortType == SortType.SORT_DATE || sortType == SortType.SORT_ARRIVAL) { secondarySort = ""; } else { secondarySort = MessageColumns.DATE + ((sortDateAscending) ? " ASC, " : " DESC, "); } return sortColumn + sortDirection + ", " + secondarySort + MessageColumns.ID + " DESC"; } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if (isThreadDisplay && data.getCount() == 0) { handler.goBack(); return; } swipeRefreshLayout.setRefreshing(false); swipeRefreshLayout.setEnabled(isPullToRefreshAllowed()); final int loaderId = loader.getId(); cursors[loaderId] = data; cursorValid[loaderId] = true; Cursor cursor; if (cursors.length > 1) { cursor = new MergeCursorWithUniqueId(cursors, getComparator()); uniqueIdColumn = cursor.getColumnIndex("_id"); } else { cursor = data; uniqueIdColumn = ID_COLUMN; } if (isThreadDisplay) { if (cursor.moveToFirst()) { title = cursor.getString(SUBJECT_COLUMN); if (!TextUtils.isEmpty(title)) { title = Utility.stripSubject(title); } if (TextUtils.isEmpty(title)) { title = getString(R.string.general_no_subject); } updateTitle(); } else { //TODO: empty thread view -> return to full message list } } cleanupSelected(cursor); updateContextMenu(cursor); adapter.swapCursor(cursor); resetActionMode(); computeBatchDirection(); if (isLoadFinished()) { if (savedListState != null) { handler.restoreListPosition(); } fragmentListener.updateMenu(); } } private void updateMoreMessagesOfCurrentFolder() { if (folderServerId != null) { try { LocalFolder folder = MlfUtils.getOpenFolder(folderServerId, account); currentFolder.setMoreMessagesFromFolder(folder); } catch (MessagingException e) { throw new RuntimeException(e); } } } public boolean isLoadFinished() { if (cursorValid == null) { return false; } for (boolean cursorValid : this.cursorValid) { if (!cursorValid) { return false; } } return true; } /** * Close the context menu when the message it was opened for is no longer in the message list. */ private void updateContextMenu(Cursor cursor) { if (contextMenuUniqueId == 0) { return; } for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { long uniqueId = cursor.getLong(uniqueIdColumn); if (uniqueId == contextMenuUniqueId) { return; } } contextMenuUniqueId = 0; Activity activity = getActivity(); if (activity != null) { activity.closeContextMenu(); } } private void cleanupSelected(Cursor cursor) { if (selected.isEmpty()) { return; } Set<Long> selected = new HashSet<>(); for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { long uniqueId = cursor.getLong(uniqueIdColumn); if (this.selected.contains(uniqueId)) { selected.add(uniqueId); } } this.selected = selected; } /** * Starts or finishes the action mode when necessary. */ private void resetActionMode() { if (selected.isEmpty()) { if (actionMode != null) { actionMode.finish(); } return; } if (actionMode == null) { startAndPrepareActionMode(); } recalculateSelectionCount(); updateActionModeTitle(); } private void startAndPrepareActionMode() { AppCompatActivity activity = (AppCompatActivity) requireActivity(); ActionMode actionMode = activity.startSupportActionMode(actionModeCallback); this.actionMode = actionMode; if (actionMode != null) { actionMode.invalidate(); } } /** * Recalculates the selection count. * * <p> * For non-threaded lists this is simply the number of visibly selected messages. If threaded * view is enabled this method counts the number of messages in the selected threads. * </p> */ private void recalculateSelectionCount() { if (!showingThreadedList) { selectedCount = selected.size(); return; } selectedCount = 0; for (int i = 0, end = adapter.getCount(); i < end; i++) { Cursor cursor = (Cursor) adapter.getItem(i); long uniqueId = cursor.getLong(uniqueIdColumn); if (selected.contains(uniqueId)) { int threadCount = cursor.getInt(THREAD_COUNT_COLUMN); selectedCount += (threadCount > 1) ? threadCount : 1; } } } @Override public void onLoaderReset(Loader<Cursor> loader) { selected.clear(); adapter.swapCursor(null); } Account getAccountFromCursor(Cursor cursor) { String accountUuid = cursor.getString(ACCOUNT_UUID_COLUMN); return preferences.getAccount(accountUuid); } void remoteSearchFinished() { remoteSearchFuture = null; } /** * Mark a message as 'active'. * * <p> * The active message is the one currently displayed in the message view portion of the split * view. * </p> * * @param messageReference * {@code null} to not mark any message as being 'active'. */ public void setActiveMessage(MessageReference messageReference) { activeMessage = messageReference; // Reload message list with modified query that always includes the active message if (isAdded()) { restartLoader(); } // Redraw list immediately if (adapter != null) { adapter.notifyDataSetChanged(); } } public boolean isSingleAccountMode() { return singleAccountMode; } public boolean isSingleFolderMode() { return singleFolderMode; } public boolean isInitialized() { return initialized; } public boolean isMarkAllAsReadSupported() { return (isSingleAccountMode() && isSingleFolderMode()); } public void confirmMarkAllAsRead() { if (K9.isConfirmMarkAllRead()) { showDialog(R.id.dialog_confirm_mark_all_as_read); } else { markAllAsRead(); } } private void markAllAsRead() { if (isMarkAllAsReadSupported()) { messagingController.markAllMessagesRead(account, folderServerId); } } public boolean isCheckMailSupported() { return (allAccounts || !isSingleAccountMode() || !isSingleFolderMode() || isRemoteFolder()); } private boolean isCheckMailAllowed() { return (!isManualSearch() && isCheckMailSupported()); } private boolean isPullToRefreshAllowed() { return (isRemoteSearchAllowed() || isCheckMailAllowed()); } LayoutInflater getK9LayoutInflater() { return layoutInflater; } public LocalSearch getLocalSearch() { return search; } }
1
17,705
Commit 676eeeab10884456a5f70ce708a8aa5116ecbaf7 contains a lot of unrelated code style changes. Please get rid of these.
k9mail-k-9
java
@@ -82,7 +82,10 @@ class BokehRenderer(Renderer): if bokeh_version < '0.12.6': raise RuntimeError('Bokeh png export only supported by versions >=0.12.6.') from bokeh.io import _get_screenshot_as_png - img = _get_screenshot_as_png(plot.state) + if bokeh_version > '0.12.6': + img = _get_screenshot_as_png(plot.state, None) + else: + img = _get_screenshot_as_png(plot.state) imgByteArr = BytesIO() img.save(imgByteArr, format='PNG') return imgByteArr.getvalue(), info
1
from io import BytesIO import logging import numpy as np import param from param.parameterized import bothmethod import bokeh.core from bokeh.application.handlers import FunctionHandler from bokeh.application import Application from bokeh.document import Document from bokeh.embed import notebook_div, autoload_server from bokeh.io import load_notebook, curdoc, show as bkshow from bokeh.models import Model from bokeh.resources import CDN, INLINE from bokeh.server.server import Server from ...core import Store, HoloMap from ..comms import JupyterComm, Comm from ..plot import Plot, GenericElementPlot from ..renderer import Renderer, MIME_TYPES from .widgets import BokehScrubberWidget, BokehSelectionWidget, BokehServerWidgets from .util import (compute_static_patch, serialize_json, attach_periodic, bokeh_version, compute_plot_size) class BokehRenderer(Renderer): backend = param.String(default='bokeh', doc="The backend name.") fig = param.ObjectSelector(default='auto', objects=['html', 'json', 'auto', 'png'], doc=""" Output render format for static figures. If None, no figure rendering will occur. """) holomap = param.ObjectSelector(default='auto', objects=['widgets', 'scrubber', 'server', None, 'auto'], doc=""" Output render multi-frame (typically animated) format. If None, no multi-frame rendering will occur.""") mode = param.ObjectSelector(default='default', objects=['default', 'server'], doc=""" Whether to render the object in regular or server mode. In server mode a bokeh Document will be returned which can be served as a bokeh server app. By default renders all output is rendered to HTML.""") # Defines the valid output formats for each mode. mode_formats = {'fig': {'default': ['html', 'json', 'auto', 'png'], 'server': ['html', 'json', 'auto']}, 'holomap': {'default': ['widgets', 'scrubber', 'auto', None], 'server': ['server', 'auto', None]}} webgl = param.Boolean(default=False, doc="""Whether to render plots with WebGL if bokeh version >=0.10""") widgets = {'scrubber': BokehScrubberWidget, 'widgets': BokehSelectionWidget, 'server': BokehServerWidgets} backend_dependencies = {'js': CDN.js_files if CDN.js_files else tuple(INLINE.js_raw), 'css': CDN.css_files if CDN.css_files else tuple(INLINE.css_raw)} comms = {'default': (JupyterComm, None), 'server': (Comm, None)} _loaded = False def __call__(self, obj, fmt=None, doc=None): """ Render the supplied HoloViews component using the appropriate backend. The output is not a file format but a suitable, in-memory byte stream together with any suitable metadata. """ plot, fmt = self._validate(obj, fmt) info = {'file-ext': fmt, 'mime_type': MIME_TYPES[fmt]} if self.mode == 'server': return self.server_doc(plot, doc), info elif isinstance(plot, tuple(self.widgets.values())): return plot(), info elif fmt == 'png': if bokeh_version < '0.12.6': raise RuntimeError('Bokeh png export only supported by versions >=0.12.6.') from bokeh.io import _get_screenshot_as_png img = _get_screenshot_as_png(plot.state) imgByteArr = BytesIO() img.save(imgByteArr, format='PNG') return imgByteArr.getvalue(), info elif fmt == 'html': html = self.figure_data(plot, doc=doc) html = "<div style='display: table; margin: 0 auto;'>%s</div>" % html return self._apply_post_render_hooks(html, obj, fmt), info elif fmt == 'json': return self.diff(plot), info @bothmethod def _save_prefix(self_or_cls, ext): "Hook to prefix content for instance JS when saving HTML" if ext == 'html': return '\n'.join(self_or_cls.html_assets()).encode('utf8') return @bothmethod def get_plot(self_or_cls, obj, doc=None, renderer=None): """ Given a HoloViews Viewable return a corresponding plot instance. Allows supplying a document attach the plot to, useful when combining the bokeh model with another plot. """ plot = super(BokehRenderer, self_or_cls).get_plot(obj, renderer) if doc is not None: plot.document = doc return plot @bothmethod def get_widget(self_or_cls, plot, widget_type, doc=None, **kwargs): if not isinstance(plot, Plot): plot = self_or_cls.get_plot(plot, doc) if self_or_cls.mode == 'server': return BokehServerWidgets(plot, renderer=self_or_cls.instance(), **kwargs) else: return super(BokehRenderer, self_or_cls).get_widget(plot, widget_type, **kwargs) @bothmethod def app(self_or_cls, plot, show=False, new_window=False): """ Creates a bokeh app from a HoloViews object or plot. By default simply attaches the plot to bokeh's curdoc and returns the Document, if show option is supplied creates an Application instance and displays it either in a browser window or inline if notebook extension has been loaded. Using the new_window option the app may be displayed in a new browser tab once the notebook extension has been loaded. """ renderer = self_or_cls.instance(mode='server') # If show=False and not in noteboook context return document if not show and not self_or_cls.notebook_context: doc, _ = renderer(plot) return doc def modify_doc(doc): renderer(plot, doc=doc) handler = FunctionHandler(modify_doc) app = Application(handler) if not show: # If not showing and in notebook context return app return app elif self_or_cls.notebook_context and not new_window: # If in notebook, show=True and no new window requested # display app inline return bkshow(app) # If app shown outside notebook or new_window requested # start server and open in new browser tab from tornado.ioloop import IOLoop loop = IOLoop.current() server = Server({'/': app}, port=0, loop=loop) def show_callback(): server.show('/') server.io_loop.add_callback(show_callback) server.start() try: loop.start() except RuntimeError: pass return server @bothmethod def server_doc(self_or_cls, obj, doc=None): """ Get a bokeh Document with the plot attached. May supply an existing doc, otherwise bokeh.io.curdoc() is used to attach the plot to the global document instance. """ if doc is None: doc = curdoc() if not isinstance(obj, (Plot, BokehServerWidgets)): renderer = self_or_cls.instance(mode='server') plot, _ = renderer._validate(obj, 'auto') else: plot = obj root = plot.state if isinstance(plot, BokehServerWidgets): plot = plot.plot plot.document = doc plot.traverse(lambda x: attach_periodic(x), [GenericElementPlot]) doc.add_root(root) return doc def figure_data(self, plot, fmt='html', doc=None, **kwargs): model = plot.state doc = Document() if doc is None else doc for m in model.references(): m._document = None doc.add_root(model) comm_id = plot.comm.id if plot.comm else None # Bokeh raises warnings about duplicate tools and empty subplots # but at the holoviews level these are not issues logger = logging.getLogger(bokeh.core.validation.check.__file__) logger.disabled = True try: div = notebook_div(model, comm_id) except: logger.disabled = False raise logger.disabled = False plot.document = doc return div def diff(self, plot, serialize=True): """ Returns a json diff required to update an existing plot with the latest plot data. """ plotobjects = [h for handles in plot.traverse(lambda x: x.current_handles, [lambda x: x._updated]) for h in handles] plot.traverse(lambda x: setattr(x, '_updated', False)) patch = compute_static_patch(plot.document, plotobjects) processed = self._apply_post_render_hooks(patch, plot, 'json') return serialize_json(processed) if serialize else processed @classmethod def plot_options(cls, obj, percent_size): """ Given a holoviews object and a percentage size, apply heuristics to compute a suitable figure size. For instance, scaling layouts and grids linearly can result in unwieldy figure sizes when there are a large number of elements. As ad hoc heuristics are used, this functionality is kept separate from the plotting classes themselves. Used by the IPython Notebook display hooks and the save utility. Note that this can be overridden explicitly per object using the fig_size and size plot options. """ factor = percent_size / 100.0 obj = obj.last if isinstance(obj, HoloMap) else obj plot = Store.registry[cls.backend].get(type(obj), None) if not hasattr(plot, 'width') or not hasattr(plot, 'height'): from .plot import BokehPlot plot = BokehPlot options = plot.lookup_options(obj, 'plot').options width = options.get('width', plot.width) * factor height = options.get('height', plot.height) * factor return dict(options, **{'width':int(width), 'height': int(height)}) @bothmethod def get_size(self_or_cls, plot): """ Return the display size associated with a plot before rendering to any particular format. Used to generate appropriate HTML display. Returns a tuple of (width, height) in pixels. """ if isinstance(plot, Plot): plot = plot.state elif not isinstance(plot, Model): raise ValueError('Can only compute sizes for HoloViews ' 'and bokeh plot objects.') return compute_plot_size(plot) @classmethod def load_nb(cls, inline=True): """ Loads the bokeh notebook resources. """ kwargs = {'notebook_type': 'jupyter'} if bokeh_version > '0.12.5' else {} load_notebook(hide_banner=True, resources=INLINE if inline else CDN, **kwargs) from bokeh.io import _state _state.output_notebook()
1
18,193
Well this sucks, I wish you'd mentioned you were using a private API, perhaps we could have made a public one with better guarantees before `0.12.6` was released.
holoviz-holoviews
py
@@ -69,17 +69,10 @@ func New(transport peer.Transport, opts ...ListOption) *List { &pendingHeap{}, plOpts..., ), - capacity: cfg.capacity, } } // List is a PeerList which rotates which peers are to be selected in a circle type List struct { *peerlist.List - capacity int -} - -// Capacity is the maximum number of peers the peer list will hold. -func (l *List) Capacity() int { - return l.capacity }
1
// Copyright (c) 2018 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package pendingheap import ( "go.uber.org/yarpc/api/peer" "go.uber.org/yarpc/peer/peerlist" ) type listConfig struct { capacity int shuffle bool } var defaultListConfig = listConfig{ capacity: 10, shuffle: true, } // ListOption customizes the behavior of a pending requests peer heap. type ListOption func(*listConfig) // Capacity specifies the default capacity of the underlying // data structures for this list. // // Defaults to 10. func Capacity(capacity int) ListOption { return func(c *listConfig) { c.capacity = capacity } } // New creates a new pending heap. func New(transport peer.Transport, opts ...ListOption) *List { cfg := defaultListConfig for _, o := range opts { o(&cfg) } plOpts := []peerlist.ListOption{ peerlist.Capacity(cfg.capacity), } if !cfg.shuffle { plOpts = append(plOpts, peerlist.NoShuffle()) } return &List{ List: peerlist.New( "fewest-pending-requests", transport, &pendingHeap{}, plOpts..., ), capacity: cfg.capacity, } } // List is a PeerList which rotates which peers are to be selected in a circle type List struct { *peerlist.List capacity int } // Capacity is the maximum number of peers the peer list will hold. func (l *List) Capacity() int { return l.capacity }
1
16,979
Consider instead moving this into an _test file so it's public but only usable in tests.
yarpc-yarpc-go
go
@@ -146,10 +146,10 @@ func (s *ec2Ops) waitAttachmentStatus( request := &ec2.DescribeVolumesInput{VolumeIds: []*string{&id}} actual := "" interval := 2 * time.Second - fmt.Printf("Waiting for state transition to %q", desired) + logrus.Infof("Waiting for state transition to %q", desired) var outVol *ec2.Volume - for elapsed, runs := 0*time.Second, 0; actual != desired && elapsed < timeout; elapsed += interval { + for elapsed, runs := 0*time.Second, 0; actual != desired && elapsed < timeout; elapsed, runs = elapsed+interval, runs+1 { awsVols, err := s.ec2.DescribeVolumes(request) if err != nil { return nil, err
1
package aws import ( "fmt" "os" "strings" "sync" "time" "github.com/Sirupsen/logrus" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/ec2" "github.com/aws/aws-sdk-go/service/opsworks" "github.com/libopenstorage/openstorage/pkg/storageops" "github.com/portworx/sched-ops/task" ) type ec2Ops struct { instance string ec2 *ec2.EC2 mutex sync.Mutex } // ErrAWSEnvNotAvailable is the error type when aws credentails are not set var ErrAWSEnvNotAvailable = fmt.Errorf("AWS credentials are not set in environment") // NewEnvClient creates a new AWS storage ops instance using environment vars func NewEnvClient() (storageops.Ops, error) { region := os.Getenv("AWS_REGION") if len(region) == 0 { return nil, ErrAWSEnvNotAvailable } instance := os.Getenv("AWS_INSTANCE_NAME") if len(instance) == 0 { return nil, ErrAWSEnvNotAvailable } if _, err := credentials.NewEnvCredentials().Get(); err != nil { return nil, ErrAWSEnvNotAvailable } ec2 := ec2.New( session.New( &aws.Config{ Region: &region, Credentials: credentials.NewEnvCredentials(), }, ), ) return NewEc2Storage(instance, ec2), nil } // NewEc2Storage creates a new aws storage ops instance func NewEc2Storage(instance string, ec2 *ec2.EC2) storageops.Ops { return &ec2Ops{ instance: instance, ec2: ec2, } } func (s *ec2Ops) filters( labels map[string]string, keys []string, ) []*ec2.Filter { if len(labels) == 0 { return nil } f := make([]*ec2.Filter, len(labels)+len(keys)) i := 0 for k, v := range labels { s := string("tag:") + k value := v f[i] = &ec2.Filter{Name: &s, Values: []*string{&value}} i++ } for _, k := range keys { s := string("tag-key:") + k f[i] = &ec2.Filter{Name: &s} i++ } return f } func (s *ec2Ops) tags(labels map[string]string) []*ec2.Tag { if len(labels) == 0 { return nil } t := make([]*ec2.Tag, len(labels)) i := 0 for k, v := range labels { key := k value := v t[i] = &ec2.Tag{Key: &key, Value: &value} i++ } return t } func (s *ec2Ops) waitStatus(id string, desired string) error { request := &ec2.DescribeVolumesInput{VolumeIds: []*string{&id}} actual := "" _, err := task.DoRetryWithTimeout( func() (interface{}, bool, error) { awsVols, err := s.ec2.DescribeVolumes(request) if err != nil { return nil, true, err } if len(awsVols.Volumes) != 1 { return nil, true, fmt.Errorf("expected one volume %v got %v", id, len(awsVols.Volumes)) } if awsVols.Volumes[0].State == nil { return nil, true, fmt.Errorf("Nil volume state for %v", id) } actual = *awsVols.Volumes[0].State if actual == desired { return nil, false, nil } return nil, true, fmt.Errorf( "Volume %v did not transition to %v current state %v", id, desired, actual) }, storageops.ProviderOpsTimeout, storageops.ProviderOpsRetryInterval) return err } func (s *ec2Ops) waitAttachmentStatus( volumeID string, desired string, timeout time.Duration, ) (*ec2.Volume, error) { id := volumeID request := &ec2.DescribeVolumesInput{VolumeIds: []*string{&id}} actual := "" interval := 2 * time.Second fmt.Printf("Waiting for state transition to %q", desired) var outVol *ec2.Volume for elapsed, runs := 0*time.Second, 0; actual != desired && elapsed < timeout; elapsed += interval { awsVols, err := s.ec2.DescribeVolumes(request) if err != nil { return nil, err } if len(awsVols.Volumes) != 1 { return nil, fmt.Errorf("expected one volume %v got %v", volumeID, len(awsVols.Volumes)) } outVol = awsVols.Volumes[0] awsAttachment := awsVols.Volumes[0].Attachments if awsAttachment == nil || len(awsAttachment) == 0 { // We have encountered scenarios where AWS returns a nil attachment state // for a volume transitioning from detaching -> attaching. actual = ec2.VolumeAttachmentStateDetached } else { actual = *awsAttachment[0].State } if actual == desired { break } time.Sleep(interval) if (runs % 10) == 0 { fmt.Print(".") } } fmt.Printf("\n") if actual != desired { return nil, fmt.Errorf("Volume %v failed to transition to %v current state %v", volumeID, desired, actual) } return outVol, nil } func (s *ec2Ops) Name() string { return "aws" } func (s *ec2Ops) ApplyTags(volumeID string, labels map[string]string) error { req := &ec2.CreateTagsInput{ Resources: []*string{&volumeID}, Tags: s.tags(labels), } _, err := s.ec2.CreateTags(req) return err } func (s *ec2Ops) RemoveTags(volumeID string, labels map[string]string) error { req := &ec2.DeleteTagsInput{ Resources: []*string{&volumeID}, Tags: s.tags(labels), } _, err := s.ec2.DeleteTags(req) return err } func (s *ec2Ops) matchTag(tag *ec2.Tag, match string) bool { return tag.Key != nil && tag.Value != nil && len(*tag.Key) != 0 && len(*tag.Value) != 0 && *tag.Key == match } func (s *ec2Ops) DeviceMappings() (map[string]string, error) { instance, err := s.describe() if err != nil { return nil, err } devPrefix := "/dev/sd" m := make(map[string]string) for _, d := range instance.BlockDeviceMappings { if d.DeviceName != nil && d.Ebs != nil && d.Ebs.VolumeId != nil { devName := *d.DeviceName // Skip the root device if devName == *instance.RootDeviceName { continue } // AWS EBS volumes get mapped from /dev/sdN -->/dev/xvdN if strings.HasPrefix(devName, devPrefix) { devName = "/dev/xvd" + devName[len(devPrefix):] } m[devName] = *d.Ebs.VolumeId } } return m, nil } // Describe current instance. func (s *ec2Ops) Describe() (interface{}, error) { return s.describe() } func (s *ec2Ops) describe() (*ec2.Instance, error) { request := &ec2.DescribeInstancesInput{ InstanceIds: []*string{&s.instance}, } out, err := s.ec2.DescribeInstances(request) if err != nil { return nil, err } if len(out.Reservations) != 1 { return nil, fmt.Errorf("DescribeInstances(%v) returned %v reservations, expect 1", s.instance, len(out.Reservations)) } if len(out.Reservations[0].Instances) != 1 { return nil, fmt.Errorf("DescribeInstances(%v) returned %v Reservations, expect 1", s.instance, len(out.Reservations[0].Instances)) } return out.Reservations[0].Instances[0], nil } func (s *ec2Ops) getPrefixFromRootDeviceName(rootDeviceName string) (string, error) { devPrefix := "/dev/sd" if !strings.HasPrefix(rootDeviceName, devPrefix) { devPrefix = "/dev/xvd" if !strings.HasPrefix(rootDeviceName, devPrefix) { return "", fmt.Errorf("unknown prefix type on root device: %s", rootDeviceName) } } return devPrefix, nil } func (s *ec2Ops) FreeDevices( blockDeviceMappings []interface{}, rootDeviceName string, ) ([]string, error) { initial := []byte("fghijklmnop") devPrefix := "/dev/sd" for _, d := range blockDeviceMappings { dev := d.(*ec2.InstanceBlockDeviceMapping) if dev.DeviceName == nil { return nil, fmt.Errorf("Nil device name") } devName := *dev.DeviceName if devName == rootDeviceName { continue } if !strings.HasPrefix(devName, devPrefix) { devPrefix = "/dev/xvd" if !strings.HasPrefix(devName, devPrefix) { return nil, fmt.Errorf("bad device name %q", devName) } } letter := devName[len(devPrefix):] // Reset devPrefix for next devices devPrefix = "/dev/sd" // AWS instances can have the following device names // /dev/xvd[b-c][a-z] if len(letter) == 1 { index := letter[0] - 'f' if index > ('p' - 'f') { continue } initial[index] = '0' } else if len(letter) == 2 { // We do not attach EBS volumes with "/dev/xvdc[a-z]" formats continue } else { return nil, fmt.Errorf("cannot parse device name %q", devName) } } // Set the prefix to the same one used as the root drive devPrefix, err := s.getPrefixFromRootDeviceName(rootDeviceName) if err != nil { return nil, err } free := make([]string, len(initial)) count := 0 for _, b := range initial { if b != '0' { free[count] = devPrefix + string(b) count++ } } if count == 0 { return nil, fmt.Errorf("No more free devices") } return free[:count], nil } func (s *ec2Ops) rollbackCreate(id string, createErr error) error { logrus.Warnf("Rollback create volume %v, Error %v", id, createErr) err := s.Delete(id) if err != nil { logrus.Warnf("Rollback failed volume %v, Error %v", id, err) } return createErr } func (s *ec2Ops) refreshVol(id *string) (*ec2.Volume, error) { vols, err := s.Inspect([]*string{id}) if err != nil { return nil, err } if len(vols) != 1 { return nil, fmt.Errorf("failed to get vol: %s."+ "Found: %d volumes on inspecting", *id, len(vols)) } resp, ok := vols[0].(*ec2.Volume) if !ok { return nil, storageops.NewStorageError(storageops.ErrVolInval, fmt.Sprintf("Invalid volume returned by inspect API for vol: %s", *id), "") } return resp, nil } func (s *ec2Ops) deleted(v *ec2.Volume) bool { return *v.State == ec2.VolumeStateDeleting || *v.State == ec2.VolumeStateDeleted } func (s *ec2Ops) available(v *ec2.Volume) bool { return *v.State == ec2.VolumeStateAvailable } func (s *ec2Ops) GetDeviceID(vol interface{}) (string, error) { if d, ok := vol.(*ec2.Volume); ok { return *d.VolumeId, nil } else if d, ok := vol.(*ec2.Snapshot); ok { return *d.SnapshotId, nil } else { return "", fmt.Errorf("invalid type: %v given to GetDeviceID", vol) } } func (s *ec2Ops) Inspect(volumeIds []*string) ([]interface{}, error) { req := &ec2.DescribeVolumesInput{VolumeIds: volumeIds} resp, err := s.ec2.DescribeVolumes(req) if err != nil { return nil, err } var awsVols = make([]interface{}, len(resp.Volumes)) for i, v := range resp.Volumes { awsVols[i] = v } return awsVols, nil } func (s *ec2Ops) Tags(volumeID string) (map[string]string, error) { vol, err := s.refreshVol(&volumeID) if err != nil { return nil, err } labels := make(map[string]string) for _, tag := range vol.Tags { labels[*tag.Key] = *tag.Value } return labels, nil } func (s *ec2Ops) Enumerate( volumeIds []*string, labels map[string]string, setIdentifier string, ) (map[string][]interface{}, error) { sets := make(map[string][]interface{}) // Enumerate all volumes that have same labels. f := s.filters(labels, nil) req := &ec2.DescribeVolumesInput{Filters: f, VolumeIds: volumeIds} awsVols, err := s.ec2.DescribeVolumes(req) if err != nil { return nil, err } // Volume sets are identified by volumes with the same setIdentifer. found := false for _, vol := range awsVols.Volumes { if s.deleted(vol) { continue } if len(setIdentifier) == 0 { storageops.AddElementToMap(sets, vol, storageops.SetIdentifierNone) } else { found = false for _, tag := range vol.Tags { if s.matchTag(tag, setIdentifier) { storageops.AddElementToMap(sets, vol, *tag.Value) found = true break } } if !found { storageops.AddElementToMap(sets, vol, storageops.SetIdentifierNone) } } } return sets, nil } func (s *ec2Ops) Create( v interface{}, labels map[string]string, ) (interface{}, error) { vol, ok := v.(*ec2.Volume) if !ok { return nil, storageops.NewStorageError(storageops.ErrVolInval, "Invalid volume template given", "") } req := &ec2.CreateVolumeInput{ AvailabilityZone: vol.AvailabilityZone, Encrypted: vol.Encrypted, KmsKeyId: vol.KmsKeyId, Size: vol.Size, VolumeType: vol.VolumeType, SnapshotId: vol.SnapshotId, } if *vol.VolumeType == opsworks.VolumeTypeIo1 { req.Iops = vol.Iops } resp, err := s.ec2.CreateVolume(req) if err != nil { return nil, err } if err = s.waitStatus( *resp.VolumeId, ec2.VolumeStateAvailable, ); err != nil { return nil, s.rollbackCreate(*resp.VolumeId, err) } if len(labels) > 0 { if err = s.ApplyTags(*resp.VolumeId, labels); err != nil { return nil, s.rollbackCreate(*resp.VolumeId, err) } } return s.refreshVol(resp.VolumeId) } func (s *ec2Ops) Delete(id string) error { req := &ec2.DeleteVolumeInput{VolumeId: &id} _, err := s.ec2.DeleteVolume(req) return err } func (s *ec2Ops) Attach(volumeID string) (string, error) { s.mutex.Lock() defer s.mutex.Unlock() self, err := s.describe() if err != nil { return "", err } var blockDeviceMappings = make([]interface{}, len(self.BlockDeviceMappings)) for i, b := range self.BlockDeviceMappings { blockDeviceMappings[i] = b } devices, err := s.FreeDevices(blockDeviceMappings, *self.RootDeviceName) if err != nil { return "", err } req := &ec2.AttachVolumeInput{ Device: &devices[0], InstanceId: &s.instance, VolumeId: &volumeID, } if _, err = s.ec2.AttachVolume(req); err != nil { return "", err } vol, err := s.waitAttachmentStatus( volumeID, ec2.VolumeAttachmentStateAttached, time.Minute, ) if err != nil { return "", err } return s.DevicePath(*vol.VolumeId) } func (s *ec2Ops) Detach(volumeID string) error { force := false req := &ec2.DetachVolumeInput{ InstanceId: &s.instance, VolumeId: &volumeID, Force: &force, } if _, err := s.ec2.DetachVolume(req); err != nil { return err } _, err := s.waitAttachmentStatus(volumeID, ec2.VolumeAttachmentStateDetached, time.Minute, ) return err } func (s *ec2Ops) Snapshot( volumeID string, readonly bool, ) (interface{}, error) { request := &ec2.CreateSnapshotInput{ VolumeId: &volumeID, } return s.ec2.CreateSnapshot(request) } func (s *ec2Ops) SnapshotDelete(snapID string) error { request := &ec2.DeleteSnapshotInput{ SnapshotId: &snapID, } _, err := s.ec2.DeleteSnapshot(request) return err } func (s *ec2Ops) DevicePath(volumeID string) (string, error) { vol, err := s.refreshVol(&volumeID) if err != nil { return "", err } if vol.Attachments == nil || len(vol.Attachments) == 0 { return "", storageops.NewStorageError(storageops.ErrVolDetached, "Volume is detached", *vol.VolumeId) } if vol.Attachments[0].InstanceId == nil { return "", storageops.NewStorageError(storageops.ErrVolInval, "Unable to determine volume instance attachment", "") } if s.instance != *vol.Attachments[0].InstanceId { return "", storageops.NewStorageError(storageops.ErrVolAttachedOnRemoteNode, fmt.Sprintf("Volume attached on %q current instance %q", *vol.Attachments[0].InstanceId, s.instance), *vol.Attachments[0].InstanceId) } if vol.Attachments[0].State == nil { return "", storageops.NewStorageError(storageops.ErrVolInval, "Unable to determine volume attachment state", "") } if *vol.Attachments[0].State != ec2.VolumeAttachmentStateAttached { return "", storageops.NewStorageError(storageops.ErrVolInval, fmt.Sprintf("Invalid state %q, volume is not attached", *vol.Attachments[0].State), "") } if vol.Attachments[0].Device == nil { return "", storageops.NewStorageError(storageops.ErrVolInval, "Unable to determine volume attachment path", "") } return *vol.Attachments[0].Device, nil }
1
6,545
Any reason why we want to remove this code ? It helps debugging AWS ebs attach issues. Ideally yes a library should have minimal logging, but there is no way we can track long running AWS attach calls.
libopenstorage-openstorage
go
@@ -87,9 +87,10 @@ func (fs *experimentStore) CreateExperiment(ctx context.Context, config *any.Any INSERT INTO experiment_run ( id, experiment_config_id, - execution_time, + execution_time, + scheduled_end_time, creation_time) - VALUES ($1, $2, tstzrange($3, $4, '[]'), NOW())` + VALUES ($1, $2, tstzrange($3, $4, '[]'), $4, NOW())` runId := id.NewID() _, err = fs.db.ExecContext(ctx, runSql, runId, configID, startTime, endTime)
1
package experimentstore import ( "bytes" "context" "database/sql" "errors" "strings" "time" "github.com/golang/protobuf/jsonpb" "github.com/golang/protobuf/ptypes" "github.com/golang/protobuf/ptypes/any" "github.com/golang/protobuf/ptypes/timestamp" "github.com/uber-go/tally" "go.uber.org/zap" experimentation "github.com/lyft/clutch/backend/api/chaos/experimentation/v1" "github.com/lyft/clutch/backend/id" "github.com/lyft/clutch/backend/service" pgservice "github.com/lyft/clutch/backend/service/db/postgres" ) const Name = "clutch.service.chaos.experimentation.store" // ExperimentStore stores experiment data type ExperimentStore interface { CreateExperiment(context.Context, *any.Any, *time.Time, *time.Time) (*experimentation.Experiment, error) StopExperiments(context.Context, []uint64) error GetExperiments(context.Context) ([]*experimentation.Experiment, error) GetExperimentRunDetails(ctx context.Context, id uint64) (*experimentation.ExperimentRunDetails, error) Close() } type experimentStore struct { db *sql.DB } // New returns a new NewExperimentStore instance. func New(_ *any.Any, _ *zap.Logger, _ tally.Scope) (service.Service, error) { p, ok := service.Registry[pgservice.Name] if !ok { return nil, errors.New("could not find database service") } client, ok := p.(pgservice.Client) if !ok { return nil, errors.New("experiment store wrong type") } return &experimentStore{ client.DB(), }, nil } func (fs *experimentStore) CreateExperiment(ctx context.Context, config *any.Any, startTime *time.Time, endTime *time.Time) (*experimentation.Experiment, error) { // This API call will eventually be broken into 2 separate calls: // 1) creating the config // 2) starting a new experiment with the config // All experiments are created in a single transaction tx, err := fs.db.Begin() if err != nil { return nil, err } if config == nil { return nil, errors.New("empty config") } // Step 1) create the config configID := id.NewID() configJson, err := marshalConfig(config) if err != nil { return nil, err } configSql := `INSERT INTO experiment_config (id, details) VALUES ($1, $2)` _, err = fs.db.ExecContext(ctx, configSql, configID, configJson) if err != nil { return nil, err } // Step 2) start a new experiment with the config runSql := ` INSERT INTO experiment_run ( id, experiment_config_id, execution_time, creation_time) VALUES ($1, $2, tstzrange($3, $4, '[]'), NOW())` runId := id.NewID() _, err = fs.db.ExecContext(ctx, runSql, runId, configID, startTime, endTime) if err != nil { return nil, err } err = tx.Commit() if err != nil { return nil, err } st, err := toProto(startTime) if err != nil { return nil, err } et, err := toProto(endTime) if err != nil { return nil, err } return &experimentation.Experiment{ // TODO(bgallagher) temporarily returning the experiment run ID. Eventually, the CreateExperiments function // will be split into CreateExperimentConfig and CreateExperimentRun in which case they will each return // their respective IDs Id: uint64(runId), Config: config, StartTime: st, EndTime: et, }, nil } func toProto(t *time.Time) (*timestamp.Timestamp, error) { if t == nil { return nil, nil } timestampProto, err := ptypes.TimestampProto(*t) if err != nil { return nil, err } return timestampProto, nil } func (fs *experimentStore) StopExperiments(ctx context.Context, ids []uint64) error { if len(ids) != 1 { // TODO: This API will be changed to take a single ID as a parameter return errors.New("A single ID must be provided") } sql := `UPDATE experiment_run SET execution_time = tstzrange(lower(execution_time), NOW(), '[]') WHERE id = $1 AND (upper(execution_time) IS NULL OR NOW() < upper(execution_time))` _, err := fs.db.ExecContext(ctx, sql, ids[0]) return err } // GetExperiments gets all experiments func (fs *experimentStore) GetExperiments(ctx context.Context) ([]*experimentation.Experiment, error) { sql := ` SELECT experiment_run.id, details FROM experiment_config, experiment_run WHERE experiment_config.id = experiment_run.experiment_config_id` rows, err := fs.db.QueryContext(ctx, sql) if err != nil { return nil, err } defer rows.Close() var experiments []*experimentation.Experiment for rows.Next() { var experiment experimentation.Experiment var details string err = rows.Scan(&experiment.Id, &details) if err != nil { return nil, err } anyConfig := &any.Any{} if nil != jsonpb.Unmarshal(strings.NewReader(details), anyConfig) { return nil, err } experiment.Config = anyConfig experiments = append(experiments, &experiment) } err = rows.Err() if err != nil { return nil, err } return experiments, nil } func (fs *experimentStore) GetExperimentRunDetails(ctx context.Context, id uint64) (*experimentation.ExperimentRunDetails, error) { sqlQuery := ` SELECT experiment_run.id, lower(execution_time), upper(execution_time), scheduled_end_time, creation_time, details FROM experiment_config, experiment_run WHERE experiment_run.id = $1 AND experiment_run.experiment_config_id = experiment_config.id` row := fs.db.QueryRowContext(ctx, sqlQuery, id) var fetchedID uint64 var startTime, endTime, scheduledEndTime sql.NullTime var creationTime time.Time var details string err := row.Scan(&fetchedID, &startTime, &endTime, &scheduledEndTime, &creationTime, &details) if err != nil { return nil, err } return NewRunDetails(fetchedID, startTime, endTime, scheduledEndTime, creationTime, details) } // Close closes all resources held. func (fs *experimentStore) Close() { fs.db.Close() } func marshalConfig(config *any.Any) (string, error) { marshaler := jsonpb.Marshaler{} buf := &bytes.Buffer{} err := marshaler.Marshal(buf, config) if err != nil { return "", err } return buf.String(), nil }
1
8,640
nit: indentation doesn't match (unfortunately i don't know of a way to automatically lint these sql statements with how we're using them currently)
lyft-clutch
go
@@ -231,6 +231,7 @@ module RSpec::Core return if @setup @setup_default.call + setup_profiler @setup = true end
1
module RSpec::Core # A reporter will send notifications to listeners, usually formatters for the # spec suite run. class Reporter # @private RSPEC_NOTIFICATIONS = Set.new( [ :close, :deprecation, :deprecation_summary, :dump_failures, :dump_pending, :dump_profile, :dump_summary, :example_failed, :example_group_finished, :example_group_started, :example_passed, :example_pending, :example_started, :message, :seed, :start, :start_dump, :stop, :example_finished ]) def initialize(configuration) @configuration = configuration @listeners = Hash.new { |h, k| h[k] = Set.new } @examples = [] @failed_examples = [] @pending_examples = [] @duration = @start = @load_time = nil @non_example_exception_count = 0 @setup_default = lambda {} @setup = false end # @private attr_reader :examples, :failed_examples, :pending_examples # @private def setup_profiler @profiler = Profiler.new register_listener @profiler, *Profiler::NOTIFICATIONS end # Registers a listener to a list of notifications. The reporter will send # notification of events to all registered listeners. # # @param listener [Object] An obect that wishes to be notified of reporter # events # @param notifications [Array] Array of symbols represents the events a # listener wishes to subscribe too def register_listener(listener, *notifications) notifications.each do |notification| @listeners[notification.to_sym] << listener end true end # @private def prepare_default(loader, output_stream, deprecation_stream) @setup_default = lambda do loader.setup_default output_stream, deprecation_stream end end # @private def registered_listeners(notification) @listeners[notification].to_a end # @overload report(count, &block) # @overload report(count, &block) # @param expected_example_count [Integer] the number of examples being run # @yield [Block] block yields itself for further reporting. # # Initializes the report run and yields itself for further reporting. The # block is required, so that the reporter can manage cleaning up after the # run. # # @example # # reporter.report(group.examples.size) do |r| # example_groups.map {|g| g.run(r) } # end # def report(expected_example_count) start(expected_example_count) begin yield self ensure finish end end # @private def start(expected_example_count, time=RSpec::Core::Time.now) @start = time @load_time = (@start - @configuration.start_time).to_f notify :seed, Notifications::SeedNotification.new(@configuration.seed, seed_used?) notify :start, Notifications::StartNotification.new(expected_example_count, @load_time) end # @param message [#to_s] A message object to send to formatters # # Send a custom message to supporting formatters. def message(message) notify :message, Notifications::MessageNotification.new(message) end # @param event [Symbol] Name of the custom event to trigger on formatters # @param options [Hash] Hash of arguments to provide via `CustomNotification` # # Publish a custom event to supporting registered formatters. # @see RSpec::Core::Notifications::CustomNotification def publish(event, options={}) if RSPEC_NOTIFICATIONS.include? event raise "RSpec::Core::Reporter#publish is intended for sending custom " \ "events not internal RSpec ones, please rename your custom event." end notify event, Notifications::CustomNotification.for(options) end # @private def example_group_started(group) notify :example_group_started, Notifications::GroupNotification.new(group) unless group.descendant_filtered_examples.empty? end # @private def example_group_finished(group) notify :example_group_finished, Notifications::GroupNotification.new(group) unless group.descendant_filtered_examples.empty? end # @private def example_started(example) @examples << example notify :example_started, Notifications::ExampleNotification.for(example) end # @private def example_finished(example) notify :example_finished, Notifications::ExampleNotification.for(example) end # @private def example_passed(example) notify :example_passed, Notifications::ExampleNotification.for(example) end # @private def example_failed(example) @failed_examples << example notify :example_failed, Notifications::ExampleNotification.for(example) end # @private def example_pending(example) @pending_examples << example notify :example_pending, Notifications::ExampleNotification.for(example) end # @private def deprecation(hash) notify :deprecation, Notifications::DeprecationNotification.from_hash(hash) end # @private # Provides a way to notify of an exception that is not tied to any # particular example (such as an exception encountered in a :suite hook). # Exceptions will be formatted the same way they normally are. def notify_non_example_exception(exception, context_description) @configuration.world.non_example_failure = true @non_example_exception_count += 1 example = Example.new(AnonymousExampleGroup, context_description, {}) presenter = Formatters::ExceptionPresenter.new(exception, example, :indentation => 0) message presenter.fully_formatted(nil) end # @private def finish close_after do stop notify :start_dump, Notifications::NullNotification notify :dump_pending, Notifications::ExamplesNotification.new(self) notify :dump_failures, Notifications::ExamplesNotification.new(self) notify :deprecation_summary, Notifications::NullNotification unless mute_profile_output? notify :dump_profile, Notifications::ProfileNotification.new(@duration, @examples, @configuration.profile_examples, @profiler.example_groups) end notify :dump_summary, Notifications::SummaryNotification.new(@duration, @examples, @failed_examples, @pending_examples, @load_time, @non_example_exception_count) notify :seed, Notifications::SeedNotification.new(@configuration.seed, seed_used?) end end # @private def close_after yield ensure close end # @private def stop @duration = (RSpec::Core::Time.now - @start).to_f if @start notify :stop, Notifications::ExamplesNotification.new(self) end # @private def notify(event, notification) ensure_listeners_ready registered_listeners(event).each do |formatter| formatter.__send__(event, notification) end end # @private def abort_with(msg, exit_status) message(msg) close exit!(exit_status) end # @private def fail_fast_limit_met? return false unless (fail_fast = @configuration.fail_fast) if fail_fast == true @failed_examples.any? else fail_fast <= @failed_examples.size end end private def ensure_listeners_ready return if @setup @setup_default.call @setup = true end def close notify :close, Notifications::NullNotification end def mute_profile_output? # Don't print out profiled info if there are failures and `--fail-fast` is # used, it just clutters the output. [email protected]_examples? || fail_fast_limit_met? end def seed_used? @configuration.seed && @configuration.seed_used? end end # @private # # Used in place of a {Reporter} for situations where we don't want reporting output. class NullReporter def self.method_missing(*) # ignore end private_class_method :method_missing end end
1
16,891
Should we remove the other `setup_profiler` call site and just let this be the one call site for it, since, AFAIK, the other one is no longer necessary with this? Also, can we make `setup_profiler` private?
rspec-rspec-core
rb
@@ -151,7 +151,6 @@ func BuildEnvShowCmd() *cobra.Command { GlobalOpts: NewGlobalOpts(), } cmd := &cobra.Command{ - Hidden: true, //TODO remove when ready for production! Use: "show", Short: "Shows info about a deployed environment.", Long: "Shows info about a deployed environment, including region, account ID, and services.",
1
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package cli import ( "fmt" "io" "github.com/aws/copilot-cli/internal/pkg/config" "github.com/aws/copilot-cli/internal/pkg/deploy" "github.com/aws/copilot-cli/internal/pkg/describe" "github.com/aws/copilot-cli/internal/pkg/term/color" "github.com/aws/copilot-cli/internal/pkg/term/log" "github.com/aws/copilot-cli/internal/pkg/term/selector" "github.com/spf13/cobra" ) const ( envShowAppNamePrompt = "Which application is the environment in?" envShowAppNameHelpPrompt = "An application is a collection of related services." envShowNamePrompt = "Which environment of %s would you like to show?" envShowHelpPrompt = "The detail of an environment will be shown (e.g., region, account ID, services)." ) type showEnvVars struct { *GlobalOpts shouldOutputJSON bool shouldOutputResources bool envName string } type showEnvOpts struct { showEnvVars w io.Writer store store describer envDescriber sel configSelector initEnvDescriber func() error } func newShowEnvOpts(vars showEnvVars) (*showEnvOpts, error) { configStore, err := config.NewStore() if err != nil { return nil, fmt.Errorf("connect to copilot config store: %w", err) } deployStore, err := deploy.NewStore(configStore) if err != nil { return nil, fmt.Errorf("connect to copilot deploy store: %w", err) } opts := &showEnvOpts{ showEnvVars: vars, store: configStore, w: log.OutputWriter, sel: selector.NewConfigSelect(vars.prompt, configStore), } opts.initEnvDescriber = func() error { d, err := describe.NewEnvDescriber(describe.NewEnvDescriberConfig{ App: opts.AppName(), Env: opts.envName, ConfigStore: configStore, DeployStore: deployStore, EnableResources: opts.shouldOutputResources, }) if err != nil { return fmt.Errorf("creating describer for environment %s in application %s: %w", opts.envName, opts.AppName(), err) } opts.describer = d return nil } return opts, nil } // Validate returns an error if the values provided by the user are invalid. func (o *showEnvOpts) Validate() error { if o.AppName() != "" { if _, err := o.store.GetApplication(o.AppName()); err != nil { return err } } if o.envName != "" { if _, err := o.store.GetEnvironment(o.AppName(), o.envName); err != nil { return err } } return nil } // Ask asks for fields that are required but not passed in. func (o *showEnvOpts) Ask() error { if err := o.askApp(); err != nil { return err } return o.askEnvName() } // Execute shows the environments through the prompt. func (o *showEnvOpts) Execute() error { if err := o.initEnvDescriber(); err != nil { return err } env, err := o.describer.Describe() if err != nil { return fmt.Errorf("describe environment %s: %w", o.envName, err) } if o.shouldOutputJSON { data, err := env.JSONString() if err != nil { return err } fmt.Fprintf(o.w, data) } else { fmt.Fprintf(o.w, env.HumanString()) } return nil } func (o *showEnvOpts) askApp() error { if o.AppName() != "" { return nil } app, err := o.sel.Application(envShowAppNamePrompt, envShowAppNameHelpPrompt) if err != nil { return fmt.Errorf("select application: %w", err) } o.appName = app return nil } func (o *showEnvOpts) askEnvName() error { //return if env name is set by flag if o.envName != "" { return nil } env, err := o.sel.Environment(fmt.Sprintf(envShowNamePrompt, color.HighlightUserInput(o.AppName())), envShowHelpPrompt, o.AppName()) if err != nil { return fmt.Errorf("select environment for application %s: %w", o.AppName(), err) } o.envName = env return nil } // BuildEnvShowCmd builds the command for showing environments in an application. func BuildEnvShowCmd() *cobra.Command { vars := showEnvVars{ GlobalOpts: NewGlobalOpts(), } cmd := &cobra.Command{ Hidden: true, //TODO remove when ready for production! Use: "show", Short: "Shows info about a deployed environment.", Long: "Shows info about a deployed environment, including region, account ID, and services.", Example: ` Shows info about the environment "test". /code $ copilot env show -n test`, RunE: runCmdE(func(cmd *cobra.Command, args []string) error { opts, err := newShowEnvOpts(vars) if err != nil { return err } if err := opts.Validate(); err != nil { return err } if err := opts.Ask(); err != nil { return err } return opts.Execute() }), } // The flags bound by viper are available to all sub-commands through viper.GetString({flagName}) cmd.Flags().StringVarP(&vars.envName, nameFlag, nameFlagShort, "", envFlagDescription) cmd.Flags().BoolVar(&vars.shouldOutputJSON, jsonFlag, false, jsonFlagDescription) cmd.Flags().BoolVar(&vars.shouldOutputResources, resourcesFlag, false, envResourcesFlagDescription) return cmd }
1
14,212
Are there any other templates where this command needs to be added, or were those issues specific to storage requiring us to enable a new command group?
aws-copilot-cli
go
@@ -1,18 +1,3 @@ // +build !linux !cgo !seccomp package patchbpf - -import ( - "errors" - - "github.com/opencontainers/runc/libcontainer/configs" - - libseccomp "github.com/seccomp/libseccomp-golang" -) - -func PatchAndLoad(config *configs.Seccomp, filter *libseccomp.ScmpFilter) error { - if config != nil { - return errors.New("cannot patch and load seccomp filter without runc seccomp support") - } - return nil -}
1
// +build !linux !cgo !seccomp package patchbpf import ( "errors" "github.com/opencontainers/runc/libcontainer/configs" libseccomp "github.com/seccomp/libseccomp-golang" ) func PatchAndLoad(config *configs.Seccomp, filter *libseccomp.ScmpFilter) error { if config != nil { return errors.New("cannot patch and load seccomp filter without runc seccomp support") } return nil }
1
22,359
perhaps file can be removed altogether (trying to avoid an empty package for these build tags)
opencontainers-runc
go
@@ -980,7 +980,7 @@ get_module_handle_64(const wchar_t *name) { /* Be careful: we can't directly de-ref any ptrs b/c they can be >4GB */ LDR_MODULE_64 mod; - if (!get_ldr_module_64(name, NULL, &mod)) + if (!get_ldr_module_64(name, 0, &mod)) return NULL; return mod.BaseAddress; }
1
/* ********************************************************** * Copyright (c) 2010-2017 Google, Inc. All rights reserved. * Copyright (c) 2008 VMware, Inc. All rights reserved. * **********************************************************/ /* * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of VMware, Inc. nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. */ /* * module_shared.c * Windows DLL routines that are shared between the core, preinject, and * drmarker-using code like libutil. * It's a pain to link module.c with non-core targets like preinject, * so we split these routines out here. * Note that NOT_DYNAMORIO_CORE_PROPER still links ntdll.c, while * NOT_DYNAMORIO_CORE (i.e., libutil) does not (since it is a pain * to link both ntdll.lib and a libc.lib). */ #include "configure.h" #if defined(NOT_DYNAMORIO_CORE) # define ASSERT(x) # define ASSERT_NOT_REACHED() # define ASSERT_NOT_IMPLEMENTED(x) # define DODEBUG(x) # define DOCHECK(n, x) # define DECLARE_NEVERPROT_VAR(var, ...) var = __VA_ARGS__; # define ALIGN_BACKWARD(x, alignment) (((ULONG_PTR)x) & (~((alignment)-1))) # define PAGE_SIZE 4096 #else /* we include globals.h mainly for ASSERT, even though we're * used by preinject. * preinject just defines its own internal_error! */ # include "../globals.h" # if !defined(NOT_DYNAMORIO_CORE_PROPER) # include "os_private.h" /* for is_readable_pe_base() */ # include "../module_shared.h" /* for is_in_code_section() */ # endif # ifdef CLIENT_INTERFACE # include "instrument.h" /* dr_lookup_module_by_name */ # endif #endif #include "ntdll.h" /* We have to hack away things we use here that won't work for non-core */ #if defined(NOT_DYNAMORIO_CORE_PROPER) || defined(NOT_DYNAMORIO_CORE) # undef strcasecmp # define strcasecmp _stricmp # define wcscasecmp _wcsicmp # undef TRY_EXCEPT_ALLOW_NO_DCONTEXT # define TRY_EXCEPT_ALLOW_NO_DCONTEXT(dc, try, except) try # undef ASSERT_OWN_NO_LOCKS # define ASSERT_OWN_NO_LOCKS() /* who cares if not the core */ # undef ASSERT_CURIOSITY # define ASSERT_CURIOSITY(x) /* who cares if not the core */ /* since not including os_shared.h (this is impl in ntdll.c): */ bool is_readable_without_exception(const byte *pc, size_t size); /* allow converting functions to and from data pointers */ # pragma warning(disable : 4055) # pragma warning(disable : 4054) # define convert_data_to_function(func) ((generic_func_t) (func)) # undef LOG /* remove preinject's LOG */ # define LOG(...) /* nothing */ #endif #if defined(CLIENT_INTERFACE) && !defined(NOT_DYNAMORIO_CORE) &&\ !defined(NOT_DYNAMORIO_CORE_PROPER) # include "instrument.h" typedef struct _pe_symbol_export_iterator_t { dr_symbol_export_t info; byte *mod_base; size_t mod_size; IMAGE_EXPORT_DIRECTORY *exports; size_t exports_size; PULONG functions; /* array of RVAs */ PUSHORT ordinals; PULONG fnames; /* array of RVAs */ uint idx; bool hasnext; /* set to false on error or end */ } pe_symbol_export_iterator_t; #endif /* This routine was moved here from os.c since we need it for * get_proc_address_64 (via get_module_exports_directory_*()) for preinject * and drmarker, neither of which link os.c. */ /* is_readable_without_exception checks to see that all bytes with addresses * from pc to pc+size-1 are readable and that reading from there won't * generate an exception. this is a stronger check than * !not_readable() below. * FIXME : beware of multi-thread races, just because this returns true, * doesn't mean another thread can't make the region unreadable between the * check here and the actual read later. See safe_read() as an alt. */ /* throw-away buffer */ DECLARE_NEVERPROT_VAR(static char is_readable_buf[4/*efficient read*/], {0}); bool is_readable_without_exception(const byte *pc, size_t size) { /* Case 7967: NtReadVirtualMemory is significantly faster than * NtQueryVirtualMemory (probably even for large regions where NtQuery can * walk by mbi.RegionSize but we have to walk by page size). We don't care * if multiple threads write into the buffer at once. Nearly all of our * calls ask about areas smaller than a page. */ byte *check_pc = (byte *) ALIGN_BACKWARD(pc, PAGE_SIZE); if (size > (size_t)((byte *)POINTER_MAX - pc)) size = (byte *)POINTER_MAX - pc; do { size_t bytes_read = 0; #if defined(NOT_DYNAMORIO_CORE) if (!ReadProcessMemory(NT_CURRENT_PROCESS, check_pc, is_readable_buf, sizeof(is_readable_buf), (SIZE_T*) &bytes_read) || bytes_read != sizeof(is_readable_buf)) { #else if (!nt_read_virtual_memory(NT_CURRENT_PROCESS, check_pc, is_readable_buf, sizeof(is_readable_buf), &bytes_read) || bytes_read != sizeof(is_readable_buf)) { #endif return false; } check_pc += PAGE_SIZE; } while (check_pc != 0/*overflow*/ && check_pc < pc+size); return true; } #if defined(WINDOWS) && !defined(NOT_DYNAMORIO_CORE) /* Image entry point is stored at, * PEB->DOS_HEADER->NT_HEADER->OptionalHeader.AddressOfEntryPoint */ void * get_remote_process_entry(HANDLE process_handle, OUT bool *x86_code) { PEB peb; LPVOID peb_base; IMAGE_DOS_HEADER *dos_ptr, dos; IMAGE_NT_HEADERS *nt_ptr, nt; bool res; size_t nbytes; peb_base = get_peb(process_handle); res = nt_read_virtual_memory(process_handle, (LPVOID)peb_base, &peb, sizeof(peb), &nbytes); if (!res || nbytes != sizeof(peb)) return NULL; dos_ptr = (IMAGE_DOS_HEADER *)peb.ImageBaseAddress; res = nt_read_virtual_memory(process_handle, (void*)dos_ptr, &dos, sizeof(dos), &nbytes); if (!res || nbytes != sizeof(dos)) return NULL; nt_ptr = (IMAGE_NT_HEADERS *)(((ptr_uint_t)dos_ptr) + dos.e_lfanew); res = nt_read_virtual_memory(process_handle, (void*)nt_ptr, &nt, sizeof(nt), &nbytes); if (!res || nbytes != sizeof(nt)) return NULL; *x86_code = nt.FileHeader.Machine == IMAGE_FILE_MACHINE_I386; return (void*)((byte*)dos_ptr + (size_t)nt.OptionalHeader.AddressOfEntryPoint); } #endif /* returns NULL if exports directory doesn't exist * if exports_size != NULL returns also exports section size * assumes base_addr is a safe is_readable_pe_base() * * NOTE - only verifies readability of the IMAGE_EXPORT_DIRECTORY, does not verify target * readability of any RVAs it contains (for that use get_module_exports_directory_check * or verify in the caller at usage). Xref case 9717. */ static IMAGE_EXPORT_DIRECTORY* get_module_exports_directory_common(app_pc base_addr, size_t *exports_size /* OPTIONAL OUT */ _IF_NOT_X64(bool ldr64)) { IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *) base_addr; IMAGE_NT_HEADERS *nt = (IMAGE_NT_HEADERS *) (base_addr + dos->e_lfanew); IMAGE_DATA_DIRECTORY *expdir; ASSERT(dos->e_magic == IMAGE_DOS_SIGNATURE); ASSERT(nt != NULL && nt->Signature == IMAGE_NT_SIGNATURE); #ifndef X64 if (ldr64) { expdir = ((IMAGE_OPTIONAL_HEADER64 *)&(nt->OptionalHeader))->DataDirectory + IMAGE_DIRECTORY_ENTRY_EXPORT; } else #endif expdir = OPT_HDR(nt, DataDirectory) + IMAGE_DIRECTORY_ENTRY_EXPORT; /* avoid preinject link issues: we don't have is_readable_pe_base */ #if !defined(NOT_DYNAMORIO_CORE_PROPER) && !defined(NOT_DYNAMORIO_CORE) /* callers should have done this in release builds */ ASSERT(is_readable_pe_base(base_addr)); #endif /* RVA conversions are trivial only for MEM_IMAGE */ DODEBUG({ MEMORY_BASIC_INFORMATION mbi; size_t len = query_virtual_memory(base_addr, &mbi, sizeof(mbi)); ASSERT(len == sizeof(mbi)); /* We do see MEM_MAPPED PE files: case 7947 */ if (mbi.Type != MEM_IMAGE) { LOG(THREAD_GET, LOG_SYMBOLS, 1, "get_module_exports_directory(base_addr="PFX"): !MEM_IMAGE\n", base_addr); ASSERT_CURIOSITY(expdir == NULL || expdir->Size == 0); } }); LOG(THREAD_GET, LOG_SYMBOLS, 5, "get_module_exports_directory(base_addr="PFX", expdir="PFX")\n", base_addr, expdir); if (expdir != NULL) { ULONG size = expdir->Size; ULONG exports_vaddr = expdir->VirtualAddress; LOG(THREAD_GET, LOG_SYMBOLS, 5, "get_module_exports_directory(base_addr="PFX") expdir="PFX " size=%d exports_vaddr=%d\n", base_addr, expdir, size, exports_vaddr); /* not all DLLs have exports - e.g. drpreinject.dll, or * shdoclc.dll in notepad help */ if (size > 0) { IMAGE_EXPORT_DIRECTORY *exports = (IMAGE_EXPORT_DIRECTORY *) (base_addr + exports_vaddr); ASSERT_CURIOSITY(size >= sizeof(IMAGE_EXPORT_DIRECTORY)); if (is_readable_without_exception((app_pc)exports, sizeof(IMAGE_EXPORT_DIRECTORY))) { if (exports_size != NULL) *exports_size = size; ASSERT_CURIOSITY(exports->Characteristics == 0); return exports; } else { ASSERT_CURIOSITY(false && "bad exports directory, partial map?" || EXEMPT_TEST("win32.partial_map.exe")); } } } else ASSERT_CURIOSITY(false && "no exports directory"); return NULL; } /* Same as get_module_exports_directory except also verifies that the functions (and, * if check_names, ordinals and fnames) arrays are readable. NOTE - does not verify that * the RVA names pointed to by fnames are themselves readable strings. */ static IMAGE_EXPORT_DIRECTORY* get_module_exports_directory_check_common(app_pc base_addr, size_t *exports_size /*OPTIONAL OUT*/, bool check_names _IF_NOT_X64(bool ldr64)) { IMAGE_EXPORT_DIRECTORY *exports = get_module_exports_directory_common (base_addr, exports_size _IF_NOT_X64(ldr64)); if (exports != NULL) { PULONG functions = (PULONG) (base_addr + exports->AddressOfFunctions); PUSHORT ordinals = (PUSHORT) (base_addr + exports->AddressOfNameOrdinals); PULONG fnames = (PULONG) (base_addr + exports->AddressOfNames); if (exports->NumberOfFunctions > 0) { if (!is_readable_without_exception((byte *)functions, exports->NumberOfFunctions * sizeof(*functions))) { ASSERT_CURIOSITY(false && "ill-formed exports directory, unreadable " "functions array, partial map?" || EXEMPT_TEST("win32.partial_map.exe")); return NULL; } } if (exports->NumberOfNames > 0 && check_names) { ASSERT_CURIOSITY(exports->NumberOfFunctions > 0 && "ill-formed exports directory"); if (!is_readable_without_exception((byte *)ordinals, exports->NumberOfNames * sizeof(*ordinals)) || !is_readable_without_exception((byte *)fnames, exports->NumberOfNames * sizeof(*fnames))) { ASSERT_CURIOSITY(false && "ill-formed exports directory, unreadable " "ordinal or names array, partial map?" || EXEMPT_TEST("win32.partial_map.exe")); return NULL; } } } return exports; } /* XXX - this walk is similar to that used in several other module.c * functions, we should look into sharing. Also, like almost all of the * module.c routines this could be racy with app memory deallocations. * XXX - We could also allow wildcards and, if desired, extend it to * return multiple matching addresses. */ /* Interface is similar to msdn GetProcAddress, takes in a module handle * (this is just the allocation base of the module) and either a name * or an ordinal and returns the address of the export with said name * or ordinal. Returns NULL on failure. * Only one of name and ordinal should be specified: the other should be * NULL (name) or UINT_MAX (ordinal). * NOTE - will return NULL for forwarded exports, exports pointing outside of * the module and for exports not in a code section (FIXME - is this the * behavior we want?). Name is case insensitive. */ static generic_func_t get_proc_address_common(module_base_t lib, const char *name, uint ordinal _IF_NOT_X64(bool ldr64), const char **forwarder OUT) { app_pc module_base; size_t exports_size; uint i; IMAGE_EXPORT_DIRECTORY *exports; PULONG functions; /* array of RVAs */ PUSHORT ordinals; PULONG fnames; /* array of RVAs */ uint ord = UINT_MAX; /* the ordinal to use */ app_pc func; /* avoid non-core issues: we don't have get_allocation_size or dcontexts */ #if !defined(NOT_DYNAMORIO_CORE_PROPER) && !defined(NOT_DYNAMORIO_CORE) size_t module_size; dcontext_t *dcontext = get_thread_private_dcontext(); #endif if (forwarder != NULL) *forwarder = NULL; ASSERT((name != NULL && *name != '\0' && ordinal == UINT_MAX) || (name == NULL && ordinal < UINT_MAX)); /* verify valid args */ if (lib == NULL || (ordinal == UINT_MAX && (name == NULL || *name == '\0'))) return NULL; /* avoid non-core issues: we don't have get_allocation_size or is_readable_pe_base */ #if !defined(NOT_DYNAMORIO_CORE_PROPER) && !defined(NOT_DYNAMORIO_CORE) /* FIXME - get_allocation_size and is_readable_pe_base are expensive * operations, we could put the onus on the caller to only pass in a * valid module_handle_t/pe_base and just assert instead if performance of * this routine becomes a concern, esp. since the caller has likely * already done it. */ module_size = get_allocation_size(lib, &module_base); if (!is_readable_pe_base(module_base)) return NULL; #else module_base = (app_pc) lib; #endif exports = get_module_exports_directory_check_common (module_base, &exports_size, true _IF_NOT_X64(ldr64)); if (exports == NULL || exports_size == 0 || exports->NumberOfNames == 0 || /* just extra sanity check */ exports->AddressOfNames == 0) return NULL; /* avoid preinject issues: doesn't have module_size */ #if !defined(NOT_DYNAMORIO_CORE_PROPER) && !defined(NOT_DYNAMORIO_CORE) /* sanity check */ ASSERT(exports->AddressOfFunctions < module_size && exports->AddressOfFunctions > 0 && exports->AddressOfNameOrdinals < module_size && exports->AddressOfNameOrdinals > 0 && exports->AddressOfNames < module_size && exports->AddressOfNames > 0); #endif functions = (PULONG)(module_base + exports->AddressOfFunctions); ordinals = (PUSHORT)(module_base + exports->AddressOfNameOrdinals); fnames = (PULONG)(module_base + exports->AddressOfNames); if (ordinal < UINT_MAX) { /* The functions array is indexed by the ordinal minus the base, to * support ordinals starting at 1 (i#1866). */ ord = ordinal - exports->Base; } else { /* FIXME - linear walk, if this routine becomes performance critical we * we should use a binary search. */ bool match = false; for (i = 0; i < exports->NumberOfNames; i++) { char *export_name = (char *)(module_base + fnames[i]); ASSERT_CURIOSITY((app_pc)export_name > module_base && /* sanity check */ (app_pc)export_name < module_base + module_size || EXEMPT_TEST("win32.partial_map.exe")); /* FIXME - xref case 9717, we haven't verified that export_name string is * safely readable (might not be the case for improperly formed or partially * mapped module) and the try will only protect us if we have a thread_private * dcontext. Could use is_string_readable_without_exception(), but that may be * too much of a perf hit for the no private dcontext case. */ TRY_EXCEPT_ALLOW_NO_DCONTEXT(dcontext, { match = (strcasecmp(name, export_name) == 0); }, { ASSERT_CURIOSITY_ONCE(false && "Exception during get_proc_address" || EXEMPT_TEST("win32.partial_map.exe")); }); if (match) { /* we have a match */ ord = ordinals[i]; break; } } if (!match) { /* export name wasn't found */ return NULL; } } /* note - function array is indexed by ordinal */ if (ord >= exports->NumberOfFunctions) { ASSERT_CURIOSITY(false && "invalid ordinal index"); return NULL; } func = (app_pc)(module_base + functions[ord]); if (func == module_base) { /* entries can be 0 when no code/data is exported for that * ordinal */ ASSERT_CURIOSITY(false && "get_proc_addr of name with empty export"); return NULL; } /* avoid non-core issues: we don't have module_size */ #if !defined(NOT_DYNAMORIO_CORE_PROPER) && !defined(NOT_DYNAMORIO_CORE) if (func < module_base || func >= module_base + module_size) { /* FIXME - export isn't in the module, should we still return * it? Will shimeng.dll or the like ever do this to replace * a function? For now we return NULL. Xref case 9717, can also * happen for a partial map in which case NULL is the right thing * to return. */ if (is_in_ntdll(func)) { /* i#: more recent loaders patch forwarded functions. * Since we don't make a private copy of user32.dll, we * hit this when a private lib imports from one of the * couple of user32 routines that forward to ntdll. */ return convert_data_to_function(func); } ASSERT_CURIOSITY(false && "get_proc_addr export location " "outside of module bounds" || EXEMPT_TEST("win32.partial_map.exe")); return NULL; } #endif if (func >= (app_pc)exports && func < (app_pc)exports + exports_size) { /* FIXME - is forwarded function, should we still return it * or return the target? Check - what does GetProcAddress do? * For now we return NULL. Looking up the target would require * a get_module_handle call which might not be safe here. * With current and planned usage we shouldn' be looking these * up anyways. */ if (forwarder != NULL) { /* func should point at something like "NTDLL.strlen" */ *forwarder = (const char *) func; return NULL; } else { ASSERT_NOT_IMPLEMENTED(false && "get_proc_addr export is forwarded"); return NULL; } } /* avoid non-core issues: we don't have is_in_code_section */ #if !defined(NOT_DYNAMORIO_CORE_PROPER) && !defined(NOT_DYNAMORIO_CORE) # ifndef CLIENT_INTERFACE /* CLIENT_INTERFACE uses a data export for versioning (PR 250952) */ /* FIXME - this check is also somewhat costly. */ if (!is_in_code_section(module_base, func, NULL, NULL)) { /* FIXME - export isn't in a code section. Prob. a data * export? For now we return NULL as all current users are * going to call or hook the returned value. */ ASSERT_CURIOSITY(false && "get_proc_addr export not in code section"); return NULL; } # endif #endif /* get around warnings converting app_pc to generic_func_t */ return convert_data_to_function(func); } IMAGE_EXPORT_DIRECTORY* get_module_exports_directory(app_pc base_addr, size_t *exports_size /* OPTIONAL OUT */) { return get_module_exports_directory_common (base_addr, exports_size _IF_NOT_X64(false)); } IMAGE_EXPORT_DIRECTORY* get_module_exports_directory_check(app_pc base_addr, size_t *exports_size /*OPTIONAL OUT*/, bool check_names) { return get_module_exports_directory_check_common (base_addr, exports_size, check_names _IF_NOT_X64(false)); } generic_func_t get_proc_address(module_base_t lib, const char *name) { return get_proc_address_common(lib, name, UINT_MAX _IF_NOT_X64(false), NULL); } #ifndef NOT_DYNAMORIO_CORE /* else need get_own_peb() alternate */ /* could be linked w/ non-core but only used by loader.c so far */ generic_func_t get_proc_address_ex(module_base_t lib, const char *name, const char **forwarder OUT) { return get_proc_address_common(lib, name, UINT_MAX _IF_NOT_X64(false), forwarder); } /* could be linked w/ non-core but only used by loader.c so far */ generic_func_t get_proc_address_by_ordinal(module_base_t lib, uint ordinal, const char **forwarder OUT) { return get_proc_address_common(lib, NULL, ordinal _IF_NOT_X64(false), forwarder); } #if defined(CLIENT_INTERFACE) && !defined(NOT_DYNAMORIO_CORE) &&\ !defined(NOT_DYNAMORIO_CORE_PROPER) generic_func_t get_proc_address_resolve_forward(module_base_t lib, const char *name) { /* We match GetProcAddress and follow forwarded exports (i#428). * Not doing this inside get_proc_address() b/c I'm not certain the core * never relies on the answer being inside the asked-about module. */ const char *forwarder, *forwfunc; char forwmodpath[MAXIMUM_PATH]; generic_func_t func = get_proc_address_ex(lib, name, &forwarder); module_data_t *forwmod; /* XXX: this is based on loader.c's privload_process_one_import(): should * try to share some of the code */ while (func == NULL && forwarder != NULL) { forwfunc = strchr(forwarder, '.') + 1; /* XXX: forwarder string constraints are not documented and * all I've seen look like this: "NTDLL.RtlAllocateHeap". * so I've never seen a full filename or path. * but there could still be extra dots somewhere: watch for them. */ if (forwfunc == (char *)(ptr_int_t)1 || strchr(forwfunc+1, '.') != NULL) { CLIENT_ASSERT(false, "unexpected forwarder string"); return NULL; } if (forwfunc - forwarder + strlen("dll") >= BUFFER_SIZE_ELEMENTS(forwmodpath)) { CLIENT_ASSERT(false, "import string too long"); LOG(GLOBAL, LOG_INTERP, 1, "%s: import string %s too long\n", __FUNCTION__, forwarder); return NULL; } snprintf(forwmodpath, forwfunc - forwarder, "%s", forwarder); snprintf(forwmodpath + (forwfunc - forwarder), strlen("dll"), "dll"); forwmodpath[forwfunc - 1/*'.'*/ - forwarder + strlen(".dll")] = '\0'; LOG(GLOBAL, LOG_INTERP, 3, "\tforwarder %s => %s %s\n", forwarder, forwmodpath, forwfunc); forwmod = dr_lookup_module_by_name(forwmodpath); if (forwmod == NULL) { LOG(GLOBAL, LOG_INTERP, 1, "%s: unable to load forwarder for %s\n" __FUNCTION__, forwarder); return NULL; } /* should be listed as import; don't want to inc ref count on each forw */ func = get_proc_address_ex(forwmod->start, forwfunc, &forwarder); dr_free_module_data(forwmod); } return func; } DR_API dr_symbol_export_iterator_t * dr_symbol_export_iterator_start(module_handle_t handle) { pe_symbol_export_iterator_t *iter; byte *base_check; iter = global_heap_alloc(sizeof(*iter) HEAPACCT(ACCT_CLIENT)); memset(iter, 0, sizeof(*iter)); iter->mod_base = (byte *) handle; iter->mod_size = get_allocation_size(iter->mod_base, &base_check); if (base_check != iter->mod_base || !is_readable_pe_base(base_check)) goto error; iter->exports = get_module_exports_directory_check_common (iter->mod_base, &iter->exports_size, true _IF_NOT_X64(false)); if (iter->exports == NULL || iter->exports_size == 0 || iter->exports->AddressOfNames >= iter->mod_size || iter->exports->AddressOfFunctions >= iter->mod_size || iter->exports->AddressOfNameOrdinals >= iter->mod_size) goto error; iter->functions = (PULONG)(iter->mod_base + iter->exports->AddressOfFunctions); iter->ordinals = (PUSHORT)(iter->mod_base + iter->exports->AddressOfNameOrdinals); iter->fnames = (PULONG)(iter->mod_base + iter->exports->AddressOfNames); iter->idx = 0; iter->hasnext = (iter->idx < iter->exports->NumberOfNames); return (dr_symbol_export_iterator_t *) iter; error: global_heap_free(iter, sizeof(*iter) HEAPACCT(ACCT_CLIENT)); return NULL; } DR_API bool dr_symbol_export_iterator_hasnext(dr_symbol_export_iterator_t *dr_iter) { pe_symbol_export_iterator_t *iter = (pe_symbol_export_iterator_t *) dr_iter; return (iter != NULL && iter->hasnext); } DR_API dr_symbol_export_t * dr_symbol_export_iterator_next(dr_symbol_export_iterator_t *dr_iter) { pe_symbol_export_iterator_t *iter = (pe_symbol_export_iterator_t *) dr_iter; dcontext_t *dcontext = get_thread_private_dcontext(); CLIENT_ASSERT(iter != NULL, "invalid parameter"); CLIENT_ASSERT(iter->hasnext, "dr_symbol_export_iterator_next: !hasnext"); CLIENT_ASSERT(iter->idx < iter->exports->NumberOfNames, "export iter internal error"); memset(&iter->info, 0, sizeof(iter->info)); iter->info.name = (char *)(iter->mod_base + iter->fnames[iter->idx]); if ((app_pc)iter->info.name < iter->mod_base || (app_pc)iter->info.name >= iter->mod_base + iter->mod_size) return NULL; iter->info.ordinal = iter->ordinals[iter->idx]; if (iter->info.ordinal >= iter->exports->NumberOfFunctions) return NULL; iter->info.addr = (app_pc)(iter->mod_base + iter->functions[iter->info.ordinal]); if (iter->info.addr == iter->mod_base) { /* see get_proc_address_ex: this means there's no export */ return NULL; } if (iter->info.addr < iter->mod_base || iter->info.addr >= iter->mod_base + iter->mod_size) { /* an already-patched forward -- we leave as is */ } else if (iter->info.addr >= (app_pc)iter->exports && iter->info.addr < (app_pc)iter->exports + iter->exports_size) { iter->info.forward = (const char *) iter->info.addr; iter->info.addr = NULL; } iter->info.is_code = true; iter->idx++; iter->hasnext = (iter->idx < iter->exports->NumberOfNames); return &iter->info; } DR_API void dr_symbol_export_iterator_stop(dr_symbol_export_iterator_t *dr_iter) { pe_symbol_export_iterator_t *iter = (pe_symbol_export_iterator_t *) dr_iter; if (iter == NULL) return; global_heap_free(iter, sizeof(*iter) HEAPACCT(ACCT_CLIENT)); } # endif /* CLIENT_INTERFACE */ /* returns NULL if no loader module is found * N.B.: walking loader data structures at random times is dangerous! See * get_ldr_module_by_pc in module.c for code to grab the ldr lock (which is * also unsafe). Here we presume that we already own the ldr lock and that * the ldr list is consistent, which should be the case for preinject (the only * user). FIXME stick this in module.c with get_ldr_module_by_pc, would need * to get module.c compiled into preinjector which is a significant hassle. */ LDR_MODULE * get_ldr_module_by_name(wchar_t *name) { PEB *peb = get_own_peb(); PEB_LDR_DATA *ldr = peb->LoaderData; LIST_ENTRY *e, *mark; LDR_MODULE *mod; uint traversed = 0; /* a simple infinite loop break out */ /* Now, you'd think these would actually be in memory order, but they * don't seem to be for me! */ mark = &ldr->InMemoryOrderModuleList; for (e = mark->Flink; e != mark; e = e->Flink) { mod = (LDR_MODULE *) ((char *)e - offsetof(LDR_MODULE, InMemoryOrderModuleList)); /* NOTE - for comparison we could use pe_name or mod->BaseDllName. * Our current usage is just to get user32.dll for which BaseDllName * is prob. better (can't rename user32, and a random dll could have * user32.dll as a pe_name). If wanted to be extra certain could * check FullDllName for %systemroot%/system32/user32.dll as that * should ensure uniqueness. */ ASSERT(mod->BaseDllName.Length <= mod->BaseDllName.MaximumLength && mod->BaseDllName.Buffer != NULL); if (wcscasecmp(name, mod->BaseDllName.Buffer) == 0) { return mod; } if (traversed++ > MAX_MODULE_LIST_INFINITE_LOOP_THRESHOLD) { /* Only caller (preinject) should hold the ldr lock and the ldr * state should be consistent so we don't expect to get stuck. */ ASSERT_NOT_REACHED(); /* TODO: In case we ever hit this we may want to retry the * traversal once more */ return NULL; } } return NULL; } bool ldr_module_statically_linked(LDR_MODULE *mod) { /* The ldr uses -1 as the load count for statically linked dlls * (signals to not bother to keep track of the load count/never * unload). It doesn't appear to ever use this value for non- * statically linked dlls (including user32.dll if late loaded). * * i#1522: However, on Win8, they renamed the LoadCount field to * ObsoleteLoadCount, and it seems that many statically linked dlls have * a positive value. There are 2 other fields: LDR_PROCESS_STATIC_IMPORT * in the Flags ("ProcessStaticImport" bitfield in PDB types), and * LoadReasonStaticDependency. Looking at real data, though, the fields * are very confusingly used, so for now we accept any of the 3. */ bool win8plus = false; # if defined(NOT_DYNAMORIO_CORE) || defined(NOT_DYNAMORIO_CORE_PROPER) PEB *peb = get_own_peb(); win8plus = ((peb->OSMajorVersion == 6 && peb->OSMinorVersion >= 2) || peb->OSMajorVersion > 6); # else win8plus = (get_os_version() >= WINDOWS_VERSION_8); # endif if (win8plus) { return (mod->LoadCount == -1 || TEST(LDR_PROCESS_STATIC_IMPORT, mod->Flags) || mod->LoadReason == LoadReasonStaticDependency || mod->LoadReason == LoadReasonStaticForwarderDependency); } else return (mod->LoadCount == -1); } #endif /* !NOT_DYNAMORIO_CORE */ /****************************************************************************/ #ifndef X64 /* PR 271719: Access x64 loader data from WOW64. * We duplicate a bunch of data structures and code here, but this is cleaner * than compiling the original code as x64 and hacking the build process to * get it linked: stick as char[] inside code section or something. */ typedef struct ALIGN_VAR(8) _LIST_ENTRY_64 { uint64 /* struct _LIST_ENTRY_64 * */ Flink; uint64 /* struct _LIST_ENTRY_64 * */ Blink; } LIST_ENTRY_64; /* UNICODE_STRING_64 is in ntdll.h */ /* module information filled by the loader */ typedef struct ALIGN_VAR(8) _PEB_LDR_DATA_64 { ULONG Length; BOOLEAN Initialized; PVOID SsHandle; uint SsHandle_hi; LIST_ENTRY_64 InLoadOrderModuleList; LIST_ENTRY_64 InMemoryOrderModuleList; LIST_ENTRY_64 InInitializationOrderModuleList; } PEB_LDR_DATA_64; /* Note that these lists are walked through corresponding LIST_ENTRY pointers * i.e., for InInit*Order*, Flink points 16 bytes into the LDR_MODULE structure */ typedef struct ALIGN_VAR(8) _LDR_MODULE_64 { LIST_ENTRY_64 InLoadOrderModuleList; LIST_ENTRY_64 InMemoryOrderModuleList; LIST_ENTRY_64 InInitializationOrderModuleList; uint64 BaseAddress; uint64 EntryPoint; ULONG SizeOfImage; int padding; UNICODE_STRING_64 FullDllName; UNICODE_STRING_64 BaseDllName; ULONG Flags; SHORT LoadCount; SHORT TlsIndex; LIST_ENTRY_64 HashTableEntry; /* see notes for LDR_MODULE */ ULONG TimeDateStamp; } LDR_MODULE_64; typedef void (*void_func_t) (); #define MAX_MODNAME_SIZE 128 #define MAX_FUNCNAME_SIZE 128 /* in arch/x86.asm */ extern int switch_modes_and_load(void *ntdll64_LdrLoadDll, UNICODE_STRING_64 *lib, HANDLE *result); /* in arch/x86.asm */ /* Switches from 32-bit mode to 64-bit mode and invokes func, passing * arg1, arg2, and arg3. Works fine when func takes fewer than 3 args * as well. */ extern int switch_modes_and_call(uint64 func, void *arg1, void *arg2, void *arg3); /* Here and not in ntdll.c b/c libutil targets link to this file but not * ntdll.c */ uint64 get_own_x64_peb(void) { /* __readgsqword is not supported for 32-bit */ /* We assume the x64 PEB is in the low 4GB (else we'll need syscall to * get its value). */ uint peb64, peb64_hi; if (!is_wow64_process(NT_CURRENT_PROCESS)) { ASSERT_NOT_REACHED(); return NULL; } __asm { mov eax, dword ptr gs:X64_PEB_TIB_OFFSET mov peb64, eax mov eax, dword ptr gs:(X64_PEB_TIB_OFFSET+4) mov peb64_hi, eax }; ASSERT(peb64_hi == 0); /* Though could we even read it if it were high? */ return (uint64) peb64; } #ifdef NOT_DYNAMORIO_CORE /* This is not in the headers exported to libutil */ process_id_t get_process_id(void); #endif static bool read64(uint64 addr, size_t sz, void *buf) { size_t got; HANDLE proc = NT_CURRENT_PROCESS; NTSTATUS res; /* On Win10, passing NT_CURRENT_PROCESS results in STATUS_INVALID_HANDLE * (pretty strange). */ #if !defined(NOT_DYNAMORIO_CORE) && !defined(NOT_DYNAMORIO_CORE_PROPER) if (get_os_version() >= WINDOWS_VERSION_10) proc = process_handle_from_id(get_process_id()); #else /* We don't have easy access to version info or PEB so we always use a real handle */ proc = OpenProcess(PROCESS_VM_READ|PROCESS_QUERY_INFORMATION, FALSE, GetCurrentProcessId()); #endif res = nt_wow64_read_virtual_memory64(proc, addr, buf, sz, &got); if (proc != NT_CURRENT_PROCESS) { #if !defined(NOT_DYNAMORIO_CORE) && !defined(NOT_DYNAMORIO_CORE_PROPER) close_handle(proc); #else CloseHandle(proc); #endif } return (NT_SUCCESS(res) && got == sz); } static uint64 get_ldr_data_64(void) { uint64 peb64 = get_own_x64_peb(); uint64 ldr64 = 0; if (!read64(peb64 + X64_LDR_PEB_OFFSET, sizeof(ldr64), &ldr64)) return 0; return ldr64; } /* Pass either name or base. * * XXX: this can be racy, accessing app loader data structs! Use with care. * Caller should synchronize w/ other threads, and avoid calling while app * holds the x64 loader lock. */ static bool get_ldr_module_64(const wchar_t *name, uint64 base, LDR_MODULE_64 *out) { /* Be careful: we can't directly de-ref any ptrs b/c they can be >4GB */ uint64 ldr_addr = get_ldr_data_64(); PEB_LDR_DATA_64 ldr; uint64 e_addr, mark_addr; LIST_ENTRY_64 e, mark; LDR_MODULE_64 mod; wchar_t local_buf[MAX_MODNAME_SIZE]; uint traversed = 0; /* a simple infinite loop break out */ if (ldr_addr == 0 || !read64(ldr_addr, sizeof(ldr), &ldr)) return false; /* Now, you'd think these would actually be in memory order, but they * don't seem to be for me! */ mark_addr = ldr_addr + offsetof(PEB_LDR_DATA_64, InMemoryOrderModuleList); if (!read64(mark_addr, sizeof(mark), &mark)) return false; for (e_addr = mark.Flink; e_addr != mark_addr; e_addr = e.Flink) { if (!read64(e_addr, sizeof(e), &e) || !read64(e_addr - offsetof(LDR_MODULE_64, InMemoryOrderModuleList), sizeof(mod), &mod)) return false; ASSERT(mod.BaseDllName.Length <= mod.BaseDllName.MaximumLength && mod.BaseDllName.u.Buffer64 != 0); if (name != NULL) { int len = MIN(mod.BaseDllName.Length, BUFFER_SIZE_BYTES(local_buf)); if (!read64(mod.BaseDllName.u.Buffer64, len, local_buf)) return false; if (len < BUFFER_SIZE_BYTES(local_buf)) local_buf[len/sizeof(wchar_t)] = L'\0'; else NULL_TERMINATE_BUFFER(local_buf); if (wcscasecmp(name, local_buf) == 0) { memcpy(out, &mod, sizeof(mod)); return true; } } else if (base != 0 && base == mod.BaseAddress) { memcpy(out, &mod, sizeof(mod)); return true; } if (traversed++ > MAX_MODULE_LIST_INFINITE_LOOP_THRESHOLD) { /* Only caller (preinject) should hold the ldr lock and the ldr * state should be consistent so we don't expect to get stuck. */ ASSERT_NOT_REACHED(); /* TODO: In case we ever hit this we may want to retry the * traversal once more */ return false; } } return false; } /* returns NULL if no loader module is found * N.B.: walking loader data structures at random times is dangerous! See * get_ldr_module_by_pc in module.c for code to grab the ldr lock (which is * also unsafe). Here we presume that we already own the ldr lock and that * the ldr list is consistent, which should be the case for preinject (the only * user). FIXME stick this in module.c with get_ldr_module_by_pc, would need * to get module.c compiled into preinjector which is a significant hassle. * * This is now used by more than just preinjector, and it's up to the caller * to synchronize and avoid calling while the app holds the x64 loader lock. */ uint64 get_module_handle_64(const wchar_t *name) { /* Be careful: we can't directly de-ref any ptrs b/c they can be >4GB */ LDR_MODULE_64 mod; if (!get_ldr_module_64(name, NULL, &mod)) return NULL; return mod.BaseAddress; } uint64 get_proc_address_64(uint64 lib, const char *name) { /* Because we have to handle 64-bit addresses, we can't share * get_proc_address_common(). We thus have a specialized routine here. * We ignore forwarders and ordinals. */ size_t exports_size; IMAGE_DOS_HEADER dos; IMAGE_NT_HEADERS64 nt; IMAGE_DATA_DIRECTORY *expdir; IMAGE_EXPORT_DIRECTORY exports; uint i; PULONG functions; /* array of RVAs */ PUSHORT ordinals; PULONG fnames; /* array of RVAs */ uint ord = UINT_MAX; /* the ordinal to use */ uint64 func = 0; char local_buf[MAX_FUNCNAME_SIZE]; if (!read64(lib, sizeof(dos), &dos) || !read64(lib + dos.e_lfanew, sizeof(nt), &nt)) return 0; ASSERT(dos.e_magic == IMAGE_DOS_SIGNATURE); ASSERT(nt.Signature == IMAGE_NT_SIGNATURE); expdir = &nt.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]; exports_size = expdir->Size; if (exports_size <= 0 || !read64(lib + expdir->VirtualAddress, MIN(exports_size, sizeof(exports)), &exports)) return 0; if (exports.NumberOfNames == 0 || exports.AddressOfNames == 0) return 0; #if defined(NOT_DYNAMORIO_CORE) || defined(NOT_DYNAMORIO_CORE_PROPER) functions = (PULONG) HeapAlloc(GetProcessHeap(), 0, exports.NumberOfFunctions * sizeof(ULONG)); ordinals = (PUSHORT) HeapAlloc(GetProcessHeap(), 0, exports.NumberOfNames * sizeof(USHORT)); fnames = (PULONG) HeapAlloc(GetProcessHeap(), 0, exports.NumberOfNames * sizeof(ULONG)); #else functions = (PULONG) global_heap_alloc(exports.NumberOfFunctions * sizeof(ULONG) HEAPACCT(ACCT_OTHER)); ordinals = (PUSHORT) global_heap_alloc(exports.NumberOfNames * sizeof(USHORT) HEAPACCT(ACCT_OTHER)); fnames = (PULONG) global_heap_alloc(exports.NumberOfNames * sizeof(ULONG) HEAPACCT(ACCT_OTHER)); #endif if (read64(lib + exports.AddressOfFunctions, exports.NumberOfFunctions * sizeof(ULONG), functions) && read64(lib + exports.AddressOfNameOrdinals, exports.NumberOfNames * sizeof(USHORT), ordinals) && read64(lib + exports.AddressOfNames, exports.NumberOfNames * sizeof(ULONG), fnames)) { bool match = false; for (i = 0; i < exports.NumberOfNames; i++) { if (!read64(lib + fnames[i], BUFFER_SIZE_BYTES(local_buf), local_buf)) break; NULL_TERMINATE_BUFFER(local_buf); if (strcasecmp(name, local_buf) == 0) { match = true; ord = ordinals[i]; break; } } if (match && ord < exports.NumberOfFunctions && functions[ord] != 0 && /* We don't support forwarded functions */ (functions[ord] < expdir->VirtualAddress || functions[ord] >= expdir->VirtualAddress + exports_size)) func = lib + functions[ord]; } #if defined(NOT_DYNAMORIO_CORE) || defined(NOT_DYNAMORIO_CORE_PROPER) HeapFree(GetProcessHeap(), 0, functions); HeapFree(GetProcessHeap(), 0, ordinals); HeapFree(GetProcessHeap(), 0, fnames); #else global_heap_free(functions, exports.NumberOfFunctions * sizeof(ULONG) HEAPACCT(ACCT_OTHER)); global_heap_free(ordinals, exports.NumberOfNames * sizeof(USHORT) HEAPACCT(ACCT_OTHER)); global_heap_free(fnames, exports.NumberOfNames * sizeof(ULONG) HEAPACCT(ACCT_OTHER)); #endif return func; } /* Excluding from libutil b/c it doesn't need it and it would be a pain * to switch _snwprintf, etc. to work w/ UNICODE. * Up to caller to synchronize and avoid interfering w/ app. */ # ifndef NOT_DYNAMORIO_CORE HANDLE load_library_64(const char *path) { uint64 ntdll64; HANDLE result; int success; byte *ntdll64_LoadLibrary; /* We hand-build our UNICODE_STRING_64 rather than jumping through * hoops to call ntdll64's RtlInitUnicodeString */ UNICODE_STRING_64 us; wchar_t wpath[MAXIMUM_PATH + 1]; _snwprintf(wpath, BUFFER_SIZE_ELEMENTS(wpath), L"%S", path); NULL_TERMINATE_BUFFER(wpath); ASSERT((wcslen(wpath) + 1) * sizeof(wchar_t) <= USHRT_MAX); us.Length = (USHORT) wcslen(wpath) * sizeof(wchar_t); /* If not >= 2 bytes larger then STATUS_INVALID_PARAMETER ((NTSTATUS)0xC000000DL) */ us.MaximumLength = (USHORT) (wcslen(wpath) + 1) * sizeof(wchar_t); us.u.b32.Buffer32 = wpath; us.u.b32.Buffer32_hi = 0; /* this is racy, but it's up to the caller to synchronize */ ntdll64 = get_module_handle_64(L"ntdll.dll"); /* XXX i#1633: this routine does not yet support ntdll64 > 4GB */ if (ntdll64 > UINT_MAX || ntdll64 == 0) return NULL; LOG(THREAD_GET, LOG_LOADER, 3, "Found ntdll64 at "UINT64_FORMAT_STRING" %s\n", ntdll64, path); /* There is no kernel32 so we use LdrLoadDll. * 32-bit GetProcAddress is doing some header checks and fails, * Our 32-bit get_proc_address does work though. */ ntdll64_LoadLibrary = (byte *)(uint) get_proc_address_64(ntdll64, "LdrLoadDll"); LOG(THREAD_GET, LOG_LOADER, 3, "Found ntdll64!LdrLoadDll at 0x%08x\n", ntdll64_LoadLibrary); if (ntdll64_LoadLibrary == NULL) return NULL; /* XXX: the WOW64 x64 loader refuses to load kernel32.dll via a name * check versus ntdll!Kernel32String (pre-Win7) or ntdll!LdrpKernel32DllName * (Win7). That's not an exported symbol so we can't robustly locate it * to work around it (in tests, disabling the check leads to successfully * loading kernel32, though its entry point fails on Vista+). */ success = switch_modes_and_load(ntdll64_LoadLibrary, &us, &result); LOG(THREAD_GET, LOG_LOADER, 3, "Loaded at 0x%08x with success 0x%08x\n", result, success); if (success >= 0) { /* preinject doesn't have get_os_version() but it only loads DR */ #if !defined(NOT_DYNAMORIO_CORE_PROPER) && !defined(NOT_DYNAMORIO_CORE) if (get_os_version() >= WINDOWS_VERSION_VISTA) { /* The WOW64 x64 loader on Vista+ does not seem to * call any entry points so we do so here. * * FIXME i#979: we should walk the Ldr list afterward to see what * dependent libs were loaded so we can call their entry points. * * FIXME i#979: we should check for the Ldr entry existing already to * avoid calling the entry point twice! */ LDR_MODULE_64 mod; dr_auxlib64_routine_ptr_t entry; DEBUG_DECLARE(bool ok = ) get_ldr_module_64(NULL, (uint64)result, &mod); ASSERT(ok); entry = (dr_auxlib64_routine_ptr_t) mod.EntryPoint; if (entry != NULL) { if (dr_invoke_x64_routine(entry, 3, result, DLL_PROCESS_ATTACH, NULL)) return result; else { LOG(THREAD_GET, LOG_LOADER, 1, "init routine for %s failed!\n", path); free_library_64(result); } } else return result; } else #endif return result; } return NULL; } bool free_library_64(HANDLE lib) { uint64 ntdll64_LdrUnloadDll; int res; uint64 ntdll64 = get_module_handle_64(L"ntdll.dll"); /* XXX i#1633: we don't yet support ntdll64 > 4GB (need to update code below) */ if (ntdll64 > UINT_MAX || ntdll64 == 0) return false; ntdll64_LdrUnloadDll = get_proc_address_64(ntdll64, "LdrUnloadDll"); res = switch_modes_and_call(ntdll64_LdrUnloadDll, (void *)lib, NULL, NULL); return (res >= 0); } # ifndef NOT_DYNAMORIO_CORE_PROPER bool thread_get_context_64(HANDLE thread, CONTEXT_64 *cxt64) { /* i#1035, DrMem i#1685: we could use a mode switch and then a raw 64-bit syscall, * which would be simpler than all this manipulating of PE structures beyond * our direct reach, but we need PE parsing for drmarker anyway and use the * same routines here. */ uint64 ntdll64_GetContextThread; NTSTATUS res; uint64 ntdll64= get_module_handle_64(L"ntdll.dll"); if (ntdll64 == 0) return false; ntdll64_GetContextThread = get_proc_address_64(ntdll64, "NtGetContextThread"); res = switch_modes_and_call(ntdll64_GetContextThread, thread, cxt64, NULL); return NT_SUCCESS(res); } bool thread_set_context_64(HANDLE thread, CONTEXT_64 *cxt64) { uint64 ntdll64_SetContextThread; NTSTATUS res; uint64 ntdll64= get_module_handle_64(L"ntdll.dll"); if (ntdll64 == 0) return false; ntdll64_SetContextThread = get_proc_address_64(ntdll64, "NtSetContextThread"); res = switch_modes_and_call(ntdll64_SetContextThread, thread, cxt64, NULL); return NT_SUCCESS(res); } # endif /* !NOT_DYNAMORIO_CORE_PROPER */ # endif /* !NOT_DYNAMORIO_CORE */ #endif /* !X64 */ /****************************************************************************/
1
12,673
NULL change, could you move that out too?
DynamoRIO-dynamorio
c
@@ -25,6 +25,10 @@ func formatKV(in []string) string { return columnize.Format(in, columnConf) } +func FormatList(in []string) string { + return formatList(in) +} + // formatList takes a set of strings and formats them into properly // aligned output, replacing any blank fields with a placeholder // for awk-ability.
1
package command import ( "bytes" "fmt" "io" "io/ioutil" "os" "strconv" "time" gg "github.com/hashicorp/go-getter" "github.com/hashicorp/nomad/api" "github.com/hashicorp/nomad/jobspec" "github.com/ryanuber/columnize" ) // formatKV takes a set of strings and formats them into properly // aligned k = v pairs using the columnize library. func formatKV(in []string) string { columnConf := columnize.DefaultConfig() columnConf.Empty = "<none>" columnConf.Glue = " = " return columnize.Format(in, columnConf) } // formatList takes a set of strings and formats them into properly // aligned output, replacing any blank fields with a placeholder // for awk-ability. func formatList(in []string) string { columnConf := columnize.DefaultConfig() columnConf.Empty = "<none>" return columnize.Format(in, columnConf) } // formatListWithSpaces takes a set of strings and formats them into properly // aligned output. It should be used sparingly since it doesn't replace empty // values and hence not awk/sed friendly func formatListWithSpaces(in []string) string { columnConf := columnize.DefaultConfig() return columnize.Format(in, columnConf) } // Limits the length of the string. func limit(s string, length int) string { if len(s) < length { return s } return s[:length] } // formatTime formats the time to string based on RFC822 func formatTime(t time.Time) string { return t.Format("01/02/06 15:04:05 MST") } // formatUnixNanoTime is a helper for formatting time for output. func formatUnixNanoTime(nano int64) string { t := time.Unix(0, nano) return formatTime(t) } // formatTimeDifference takes two times and determines their duration difference // truncating to a passed unit. // E.g. formatTimeDifference(first=1m22s33ms, second=1m28s55ms, time.Second) -> 6s func formatTimeDifference(first, second time.Time, d time.Duration) string { return second.Truncate(d).Sub(first.Truncate(d)).String() } // getLocalNodeID returns the node ID of the local Nomad Client and an error if // it couldn't be determined or the Agent is not running in Client mode. func getLocalNodeID(client *api.Client) (string, error) { info, err := client.Agent().Self() if err != nil { return "", fmt.Errorf("Error querying agent info: %s", err) } clientStats, ok := info.Stats["client"] if !ok { return "", fmt.Errorf("Nomad not running in client mode") } nodeID, ok := clientStats["node_id"] if !ok { return "", fmt.Errorf("Failed to determine node ID") } return nodeID, nil } // evalFailureStatus returns whether the evaluation has failures and a string to // display when presenting users with whether there are failures for the eval func evalFailureStatus(eval *api.Evaluation) (string, bool) { if eval == nil { return "", false } hasFailures := len(eval.FailedTGAllocs) != 0 text := strconv.FormatBool(hasFailures) if eval.Status == "blocked" { text = "N/A - In Progress" } return text, hasFailures } // LineLimitReader wraps another reader and provides `tail -n` like behavior. // LineLimitReader buffers up to the searchLimit and returns `-n` number of // lines. After those lines have been returned, LineLimitReader streams the // underlying ReadCloser type LineLimitReader struct { io.ReadCloser lines int searchLimit int timeLimit time.Duration lastRead time.Time buffer *bytes.Buffer bufFiled bool foundLines bool } // NewLineLimitReader takes the ReadCloser to wrap, the number of lines to find // searching backwards in the first searchLimit bytes. timeLimit can optionally // be specified by passing a non-zero duration. When set, the search for the // last n lines is aborted if no data has been read in the duration. This // can be used to flush what is had if no extra data is being received. When // used, the underlying reader must not block forever and must periodically // unblock even when no data has been read. func NewLineLimitReader(r io.ReadCloser, lines, searchLimit int, timeLimit time.Duration) *LineLimitReader { return &LineLimitReader{ ReadCloser: r, searchLimit: searchLimit, timeLimit: timeLimit, lines: lines, buffer: bytes.NewBuffer(make([]byte, 0, searchLimit)), } } func (l *LineLimitReader) Read(p []byte) (n int, err error) { // Fill up the buffer so we can find the correct number of lines. if !l.bufFiled { b := make([]byte, len(p)) n, err := l.ReadCloser.Read(b) if n > 0 { if _, err := l.buffer.Write(b[:n]); err != nil { return 0, err } } if err != nil { if err != io.EOF { return 0, err } l.bufFiled = true goto READ } if l.buffer.Len() >= l.searchLimit { l.bufFiled = true goto READ } if l.timeLimit.Nanoseconds() > 0 { if l.lastRead.IsZero() { l.lastRead = time.Now() return 0, nil } now := time.Now() if n == 0 { // We hit the limit if l.lastRead.Add(l.timeLimit).Before(now) { l.bufFiled = true goto READ } else { return 0, nil } } else { l.lastRead = now } } return 0, nil } READ: if l.bufFiled && l.buffer.Len() != 0 { b := l.buffer.Bytes() // Find the lines if !l.foundLines { found := 0 i := len(b) - 1 sep := byte('\n') lastIndex := len(b) - 1 for ; found < l.lines && i >= 0; i-- { if b[i] == sep { lastIndex = i // Skip the first one if i != len(b)-1 { found++ } } } // We found them all if found == l.lines { // Clear the buffer until the last index l.buffer.Next(lastIndex + 1) } l.foundLines = true } // Read from the buffer n := copy(p, l.buffer.Next(len(p))) return n, nil } // Just stream from the underlying reader now return l.ReadCloser.Read(p) } type JobGetter struct { // The fields below can be overwritten for tests testStdin io.Reader } // StructJob returns the Job struct from jobfile. func (j *JobGetter) ApiJob(jpath string) (*api.Job, error) { var jobfile io.Reader switch jpath { case "-": if j.testStdin != nil { jobfile = j.testStdin } else { jobfile = os.Stdin } default: if len(jpath) == 0 { return nil, fmt.Errorf("Error jobfile path has to be specified.") } job, err := ioutil.TempFile("", "jobfile") if err != nil { return nil, err } defer os.Remove(job.Name()) if err := job.Close(); err != nil { return nil, err } // Get the pwd pwd, err := os.Getwd() if err != nil { return nil, err } client := &gg.Client{ Src: jpath, Pwd: pwd, Dst: job.Name(), } if err := client.Get(); err != nil { return nil, fmt.Errorf("Error getting jobfile from %q: %v", jpath, err) } else { file, err := os.Open(job.Name()) defer file.Close() if err != nil { return nil, fmt.Errorf("Error opening file %q: %v", jpath, err) } jobfile = file } } // Parse the JobFile jobStruct, err := jobspec.Parse(jobfile) if err != nil { return nil, fmt.Errorf("Error parsing job file from %s: %v", jpath, err) } return jobStruct, nil }
1
6,729
A brief explanation about this func is required.
openebs-maya
go
@@ -32,6 +32,11 @@ class MergedCellsCollection { this.hot = plugin.hot; } + static IS_OVERLAPPING_WARNING(newMergedCell) { + return `The merged cell declared at [${newMergedCell.row}, ${newMergedCell.col}] overlaps with the other ` + + 'declared merged cell. The overlapping merged cell was not added to the table, please fix your setup.'; + } + /** * Get a merged cell from the container, based on the provided arguments. You can provide either the "starting coordinates" * of a merged cell, or any coordinates from the body of the merged cell.
1
import MergedCellCoords from './cellCoords'; import {CellCoords, CellRange} from '../../3rdparty/walkontable/src/index'; import {rangeEach} from '../../helpers/number'; import {arrayEach} from '../../helpers/array'; import {applySpanProperties} from './utils'; /** * Defines a container object for the merged cells. * * @class MergedCellsCollection * @plugin MergeCells */ class MergedCellsCollection { constructor(plugin) { /** * Reference to the Merge Cells plugin. * * @type {MergeCells} */ this.plugin = plugin; /** * Array of merged cells. * * @type {Array} */ this.mergedCells = []; /** * The Handsontable instance. * * @type {Handsontable} */ this.hot = plugin.hot; } /** * Get a merged cell from the container, based on the provided arguments. You can provide either the "starting coordinates" * of a merged cell, or any coordinates from the body of the merged cell. * * @param {Number} row Row index. * @param {Number} column Column index. * @returns {MergedCellCoords|Boolean} Returns a wanted merged cell on success and `false` on failure. */ get(row, column) { const mergedCells = this.mergedCells; let result = false; arrayEach(mergedCells, (mergedCell) => { if (mergedCell.row <= row && mergedCell.row + mergedCell.rowspan - 1 >= row && mergedCell.col <= column && mergedCell.col + mergedCell.colspan - 1 >= column) { result = mergedCell; return false; } return true; }); return result; } /** * Get a merged cell containing the provided range. * * @param {CellRange|Object} range The range to search merged cells for. * @return {MergedCellCoords|Boolean} */ getByRange(range) { const mergedCells = this.mergedCells; let result = false; arrayEach(mergedCells, (mergedCell) => { if (mergedCell.row <= range.from.row && mergedCell.row + mergedCell.rowspan - 1 >= range.to.row && mergedCell.col <= range.from.col && mergedCell.col + mergedCell.colspan - 1 >= range.to.col) { result = mergedCell; return result; } return true; }); return result; } /** * Get a merged cell contained in the provided range. * * @param {CellRange|Object} range The range to search merged cells in. * @param [countPartials=false] If set to `true`, all the merged cells overlapping the range will be taken into calculation. * @return {Array|Boolean} Array of found merged cells of `false` if none were found. */ getWithinRange(range, countPartials = false) { const mergedCells = this.mergedCells; const foundMergedCells = []; if (!range.includesRange) { let from = new CellCoords(range.from.row, range.from.col); let to = new CellCoords(range.to.row, range.to.col); range = new CellRange(from, from, to); } arrayEach(mergedCells, (mergedCell) => { let mergedCellTopLeft = new CellCoords(mergedCell.row, mergedCell.col); let mergedCellBottomRight = new CellCoords(mergedCell.row + mergedCell.rowspan - 1, mergedCell.col + mergedCell.colspan - 1); let mergedCellRange = new CellRange(mergedCellTopLeft, mergedCellTopLeft, mergedCellBottomRight); if (countPartials) { if (range.overlaps(mergedCellRange)) { foundMergedCells.push(mergedCell); } } else if (range.includesRange(mergedCellRange)) { foundMergedCells.push(mergedCell); } }); return foundMergedCells.length ? foundMergedCells : false; } /** * Add a merged cell to the container. * * @param {Object} mergedCellInfo The merged cell information object. Has to contain `row`, `col`, `colspan` and `rowspan` properties. * @return {MergedCellCoords|Boolean} Returns the new merged cell on success and `false` on failure. */ add(mergedCellInfo) { const mergedCells = this.mergedCells; const row = mergedCellInfo.row; const column = mergedCellInfo.col; const rowspan = mergedCellInfo.rowspan; const colspan = mergedCellInfo.colspan; const newMergedCell = new MergedCellCoords(row, column, rowspan, colspan); if (!this.get(row, column) && !this.isOverlapping(newMergedCell)) { if (this.hot) { newMergedCell.normalize(this.hot); } mergedCells.push(newMergedCell); return newMergedCell; } console.warn(`The declared merged cell at [${newMergedCell.row}, ${newMergedCell.col}] overlaps with the other declared merged cell. The overlapping merged cell was not added to the table, please fix your setup.`); return false; } /** * Remove a merged cell from the container. You can provide either the "starting coordinates" * of a merged cell, or any coordinates from the body of the merged cell. * * @param {Number} row Row index. * @param {Number} column Column index. * @return {MergedCellCoords|Boolean} Returns the removed merged cell on success and `false` on failure. */ remove(row, column) { const mergedCells = this.mergedCells; const wantedCollection = this.get(row, column); const wantedCollectionIndex = wantedCollection ? this.mergedCells.indexOf(wantedCollection) : null; if (wantedCollection && wantedCollectionIndex !== false) { mergedCells.splice(wantedCollectionIndex, 1); return wantedCollection; } return false; } /** * Clear all the merged cells. */ clear() { const mergedCells = this.mergedCells; const mergedCellParentsToClear = []; const hiddenCollectionElements = []; arrayEach(mergedCells, (mergedCell) => { mergedCellParentsToClear.push([this.hot.getCell(mergedCell.row, mergedCell.col), this.get(mergedCell.row, mergedCell.col), mergedCell.row, mergedCell.col]); }); this.mergedCells.length = 0; arrayEach(mergedCellParentsToClear, (mergedCell, i) => { rangeEach(0, mergedCell.rowspan - 1, (j) => { rangeEach(0, mergedCell.colspan - 1, (k) => { if (k !== 0 || j !== 0) { hiddenCollectionElements.push([this.hot.getCell(mergedCell.row + j, mergedCell.col + k), null, null, null]); } }); }); mergedCellParentsToClear[i][1] = null; }); arrayEach(mergedCellParentsToClear, (mergedCellParents) => { applySpanProperties(...mergedCellParents); }); arrayEach(hiddenCollectionElements, (hiddenCollectionElement) => { applySpanProperties(...hiddenCollectionElement); }); } /** * Check if the provided merged cell overlaps with the others in the container. * * @param {MergedCellCoords} mergedCell The merged cell to check against all others in the container. * @return {Boolean} `true` if the provided merged cell overlaps with the others, `false` otherwise. */ isOverlapping(mergedCell) { const mergedCellRange = new CellRange(null, new CellCoords(mergedCell.row, mergedCell.col), new CellCoords(mergedCell.row + mergedCell.rowspan - 1, mergedCell.col + mergedCell.colspan - 1)); let result = false; arrayEach(this.mergedCells, (col) => { let currentRange = new CellRange(null, new CellCoords(col.row, col.col), new CellCoords(col.row + col.rowspan - 1, col.col + col.colspan - 1)); if (currentRange.overlaps(mergedCellRange)) { result = true; return false; } return true; }); return result; } /** * Check whether the provided row/col coordinates direct to a merged parent. * * @param {Number} row Row index. * @param {Number} column Column index. * @return {Boolean} */ isMergedParent(row, column) { const mergedCells = this.mergedCells; let result = false; arrayEach(mergedCells, (mergedCell) => { if (mergedCell.row === row && mergedCell.col === column) { result = true; return false; } return true; }); return result; } /** * Shift the merged cell in the direction and by an offset defined in the arguments. * * @param {String} direction `right`, `left`, `up` or `down`. * @param {Number} index Index where the change, which caused the shifting took place. * @param {Number} count Number of rows/columns added/removed in the preceding action. */ shiftCollections(direction, index, count) { const shiftVector = [0, 0]; switch (direction) { case 'right': shiftVector[0] += count; break; case 'left': shiftVector[0] -= count; break; case 'down': shiftVector[1] += count; break; case 'up': shiftVector[1] -= count; break; default: } arrayEach(this.mergedCells, (currentMerge) => { currentMerge.shift(shiftVector, index); }); arrayEach(this.mergedCells, (currentMerge) => { if (currentMerge.removed) { this.mergedCells.splice(this.mergedCells.indexOf(currentMerge), 1); } }); } } export default MergedCellsCollection;
1
14,623
Could you add description for below static function?
handsontable-handsontable
js