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
@@ -109,9 +109,8 @@ function TransactionBuilder(opts) { this.lockTime = opts.lockTime || 0; this.spendUnconfirmed = opts.spendUnconfirmed || false; - if (opts.fee || opts.feeSat) { - this.givenFeeSat = opts.fee ? opts.fee * util.COIN : opts.feeSat; - } + this.givenFeeSat = typeof(opts.fee) !== 'undefined' ? opts.fee * util.COIN : opts.feeSat; + this.remainderOut = opts.remainderOut; this.signhash = opts.signhash || Transaction.SIGHASH_ALL;
1
// TransactionBuilder // ================== // // Creates a bitcore Transaction object // // // Synopsis // -------- // ``` // var tx = (new TransactionBuilder(opts)) // .setUnspent(utxos) // .setOutputs(outs) // .sign(keys) // .build(); // // // var builder = (new TransactionBuilder(opts)) // .setUnspent(spent) // .setOutputs(outs); // // // Uncomplete tx (no signed or partially signed) // var tx = builder.build(); // // ..later.. // // builder.sign(keys); // while ( builder.isFullySigned() ) { // // ... get new keys ... // // builder.sign(keys); // } // // var tx = builder.build(); // broadcast(tx.serialize()); // // //Serialize it and pass it around... // var string = JSON.stringify(builder.toObj()); // // then... // var builder = TransactionBuilder.fromObj(JSON.parse(str); // builder.sign(keys); // // Also // var builder2 = TransactionBuilder.fromObj(JSON.parse(str2); // builder2.merge(builder); // Will merge signatures for p2sh mulsig txs. // // // ``` // // // 'use strict'; var Address = require('./Address'); var Script = require('./Script'); var util = require('../util'); var bignum = require('bignum'); var buffertools = require('buffertools'); var networks = require('../networks'); var WalletKey = require('./WalletKey'); var PrivateKey = require('./PrivateKey'); var Key = require('./Key'); var log = require('../util/log'); var Transaction = require('./Transaction'); var FEE_PER_1000B_SAT = parseInt(0.0001 * util.COIN); var TOOBJ_VERSION = 1; // Methods // ------- // // TransactionBuilder // ------------------ // Creates a TransactionBuilder instance // `opts` // ``` // { // remainderOut: null, // fee: 0.001, // lockTime: null, // spendUnconfirmed: false, // signhash: SIGHASH_ALL // } // ``` // Amounts are in BTC. instead of fee and amount; feeSat and amountSat can be given, // repectively, to provide amounts in satoshis. // // If no remainderOut is given, and there are remainder coins, the // first IN out will be used to return the coins. remainderOut has the form: // ``` // remainderOut = { address: 1xxxxx} // ``` // or // ``` // remainderOut = { pubkeys: ['hex1','hex2',...} for multisig // ``` function TransactionBuilder(opts) { opts = opts || {}; this.vanilla = {}; this.vanilla.scriptSig = []; this.vanilla.opts = JSON.stringify(opts); // If any default opts is changed, TOOBJ_VERSION should be changed as // a caution measure. this.lockTime = opts.lockTime || 0; this.spendUnconfirmed = opts.spendUnconfirmed || false; if (opts.fee || opts.feeSat) { this.givenFeeSat = opts.fee ? opts.fee * util.COIN : opts.feeSat; } this.remainderOut = opts.remainderOut; this.signhash = opts.signhash || Transaction.SIGHASH_ALL; this.tx = {}; this.inputsSigned = 0; return this; } TransactionBuilder.FEE_PER_1000B_SAT = FEE_PER_1000B_SAT; TransactionBuilder._scriptForPubkeys = function(out) { var l = out.pubkeys.length; var pubKeyBuf = []; for (var i = 0; i < l; i++) { pubKeyBuf.push(new Buffer(out.pubkeys[i], 'hex')); } return Script.createMultisig(out.nreq, pubKeyBuf); }; TransactionBuilder._scriptForOut = function(out) { var ret; if (out.address) ret = new Address(out.address).getScriptPubKey(); else if (out.pubkeys || out.nreq || out.nreq > 1) ret = this._scriptForPubkeys(out); else throw new Error('unknown out type'); return ret; }; TransactionBuilder.infoForP2sh = function(opts, networkName) { var script = this._scriptForOut(opts); var hash = util.sha256ripe160(script.getBuffer()); var version = networkName === 'testnet' ? networks.testnet.P2SHVersion : networks.livenet.P2SHVersion; var addr = new Address(version, hash); var addrStr = addr.as('base58'); return { script: script, scriptBufHex: script.getBuffer().toString('hex'), hash: hash, address: addrStr, }; }; // setUnspent // ---------- // Sets the `unspent` available for the transaction. Some (or all) // of them to fullfil the transaction's outputs and fee. // The expected format is: // ``` // [{ // address: "mqSjTad2TKbPcKQ3Jq4kgCkKatyN44UMgZ", // txid: "2ac165fa7a3a2b535d106a0041c7568d03b531e58aeccdd3199d7289ab12cfc1", // scriptPubKey: "76a9146ce4e1163eb18939b1440c42844d5f0261c0338288ac", // vout: 1, // amount: 0.01, // confirmations: 3 // }, ... // ] // ``` // This is compatible con insight's utxo API. // That amount is in BTCs (as returned in insight and bitcoind). // amountSat (instead of amount) can be given to provide amount in satochis. TransactionBuilder.prototype.setUnspent = function(unspent) { this.vanilla.utxos = JSON.stringify(unspent); this.utxos = unspent; return this; }; TransactionBuilder.prototype._setInputMap = function() { var inputMap = []; var l = this.selectedUtxos.length; for (var i = 0; i < l; i++) { var utxo = this.selectedUtxos[i]; var scriptBuf = new Buffer(utxo.scriptPubKey, 'hex'); var scriptPubKey = new Script(scriptBuf); var scriptType = scriptPubKey.classify(); if (scriptType === Script.TX_UNKNOWN) throw new Error('Unknown scriptPubKey type at:' + i + ' Type:' + scriptPubKey.getRawOutType()); inputMap.push({ address: utxo.address, scriptPubKey: scriptPubKey, scriptType: scriptType, i: i, }); } this.inputMap = inputMap; return this; }; // getSelectedUnspent // ------------------ // // Returns the selected unspent outputs, to be used in the transaction. TransactionBuilder.prototype.getSelectedUnspent = function() { return this.selectedUtxos; }; /* _selectUnspent * TODO(?): sort sel (at the end) and check is some inputs can be avoided. * If the initial utxos are sorted, this step would be necesary only if * utxos were selected from different minConfirmationSteps. */ TransactionBuilder.prototype._selectUnspent = function(neededAmountSat) { if (!this.utxos || !this.utxos.length) throw new Error('unspent not set'); var minConfirmationSteps = [6, 1]; if (this.spendUnconfirmed) minConfirmationSteps.push(0); var sel = [], totalSat = bignum(0), fulfill = false, maxConfirmations = null, l = this.utxos.length; do { var minConfirmations = minConfirmationSteps.shift(); for (var i = 0; i < l; i++) { var u = this.utxos[i]; var c = u.confirmations || 0; if (c < minConfirmations || (maxConfirmations && c >= maxConfirmations)) continue; var sat = u.amountSat || util.parseValue(u.amount); totalSat = totalSat.add(sat); sel.push(u); if (totalSat.cmp(neededAmountSat) >= 0) { fulfill = true; break; } } maxConfirmations = minConfirmations; } while (!fulfill && minConfirmationSteps.length); if (!fulfill) throw new Error('not enough unspent tx outputs to fulfill totalNeededAmount [SAT]:' + neededAmountSat); this.selectedUtxos = sel; this._setInputMap(); return this; }; TransactionBuilder.prototype._setInputs = function(txobj) { var ins = this.selectedUtxos; var l = ins.length; var valueInSat = bignum(0); txobj.ins = []; for (var i = 0; i < l; i++) { valueInSat = valueInSat.add(util.parseValue(ins[i].amount)); var txin = {}; txin.s = util.EMPTY_BUFFER; txin.q = 0xffffffff; var hash = new Buffer(ins[i].txid, 'hex'); var hashReversed = buffertools.reverse(hash); var vout = parseInt(ins[i].vout); var voutBuf = new Buffer(4); voutBuf.writeUInt32LE(vout, 0); txin.o = Buffer.concat([hashReversed, voutBuf]); txobj.ins.push(txin); } this.valueInSat = valueInSat; return this; }; TransactionBuilder.prototype._setFee = function(feeSat) { if (typeof this.valueOutSat === 'undefined') throw new Error('valueOutSat undefined'); var valueOutSat = this.valueOutSat.add(feeSat); if (this.valueInSat.cmp(valueOutSat) < 0) { var inv = this.valueInSat.toString(); var ouv = valueOutSat.toString(); throw new Error('transaction input amount is less than outputs: ' + inv + ' < ' + ouv + ' [SAT]'); } this.feeSat = feeSat; return this; }; TransactionBuilder.prototype._setRemainder = function(txobj, remainderIndex) { if (typeof this.valueInSat === 'undefined' || typeof this.valueOutSat === 'undefined') throw new Error('valueInSat / valueOutSat undefined'); /* add remainder (without modifying outs[]) */ var remainderSat = this.valueInSat.sub(this.valueOutSat).sub(this.feeSat); var l = txobj.outs.length; this.remainderSat = bignum(0); /*remove old remainder? */ if (l > remainderIndex) { txobj.outs.pop(); } if (remainderSat.cmp(0) > 0) { var remainderOut = this.remainderOut || this.selectedUtxos[0]; var value = util.bigIntToValue(remainderSat); var script = TransactionBuilder._scriptForOut(remainderOut); var txout = { v: value, s: script.getBuffer(), }; txobj.outs.push(txout); this.remainderSat = remainderSat; } return this; }; TransactionBuilder.prototype._setFeeAndRemainder = function(txobj) { /* starting size estimation */ var size = 500, maxSizeK, remainderIndex = txobj.outs.length; do { /* based on https://en.bitcoin.it/wiki/Transaction_fees */ maxSizeK = parseInt(size / 1000) + 1; var feeSat = this.givenFeeSat ? this.givenFeeSat : maxSizeK * FEE_PER_1000B_SAT; var neededAmountSat = this.valueOutSat.add(feeSat); this._selectUnspent(neededAmountSat) ._setInputs(txobj) ._setFee(feeSat) ._setRemainder(txobj, remainderIndex); size = new Transaction(txobj).getSize(); } while (size > (maxSizeK + 1) * 1000); return this; }; // setOutputs // ---------- // Sets the outputs for the transaction. Format is: // ``` // an array of [{ // address: xx, // amount:0.001 // },...] // ``` // // Note that only some of this outputs will be selected // to create the transaction. The selected ones can be checked // after calling `setOutputs`, with `.getSelectedUnspent`. // amountSatStr could be used to pass in the amount in satoshis, as a string. // TransactionBuilder.prototype.setOutputs = function(outs) { this.vanilla.outs = JSON.stringify(outs); var valueOutSat = bignum(0); var txobj = {}; txobj.version = 1; txobj.lock_time = this.lockTime || 0; txobj.ins = []; txobj.outs = []; var l = outs.length; for (var i = 0; i < l; i++) { var amountSat = outs[i].amountSat || outs[i].amountSatStr ? bignum(outs[i].amountSatStr) : util.parseValue(outs[i].amount); var value = util.bigIntToValue(amountSat); var script = TransactionBuilder._scriptForOut(outs[i]); var txout = { v: value, s: script.getBuffer(), }; txobj.outs.push(txout); valueOutSat = valueOutSat.add(amountSat); } this.valueOutSat = valueOutSat; this._setFeeAndRemainder(txobj); this.tx = new Transaction(txobj); return this; }; TransactionBuilder._mapKeys = function(keys) { /* prepare keys */ var walletKeyMap = {}; var l = keys.length; var wk; for (var i = 0; i < l; i++) { var k = keys[i]; if (typeof k === 'string') { var pk = new PrivateKey(k); wk = new WalletKey({ network: pk.network() }); wk.fromObj({ priv: k }); } else if (k instanceof WalletKey) { wk = k; } else { throw new Error('argument must be an array of strings (WIF format) or WalletKey objects'); } var addr = wk.storeObj().addr; walletKeyMap[addr] = wk; } return walletKeyMap; }; TransactionBuilder._signHashAndVerify = function(wk, txSigHash) { var triesLeft = 10, sigRaw; do { sigRaw = wk.privKey.signSync(txSigHash); } while (wk.privKey.verifySignatureSync(txSigHash, sigRaw) === false && triesLeft--); if (triesLeft < 0) throw new Error('could not sign input: verification failed'); return sigRaw; }; TransactionBuilder.prototype._checkTx = function() { if (!this.tx || !this.tx.ins || !this.tx.ins.length || !this.tx.outs.length) throw new Error('tx is not defined'); }; TransactionBuilder.prototype._multiFindKey = function(walletKeyMap, pubKeyHash) { var wk; [networks.livenet, networks.testnet].forEach(function(n) { [n.addressVersion, n.P2SHVersion].forEach(function(v) { var a = new Address(v, pubKeyHash); if (!wk && walletKeyMap[a]) { wk = walletKeyMap[a]; } }); }); return wk; }; TransactionBuilder.prototype._findWalletKey = function(walletKeyMap, input) { var wk; if (input.address) { wk = walletKeyMap[input.address]; } else if (input.pubKeyHash) { wk = this._multiFindKey(walletKeyMap, input.pubKeyHash); } else if (input.pubKeyBuf) { var pubKeyHash = util.sha256ripe160(input.pubKeyBuf); wk = this._multiFindKey(walletKeyMap, pubKeyHash); } else { throw new Error('no infomation at input to find keys'); } return wk; }; TransactionBuilder.prototype._signPubKey = function(walletKeyMap, input, txSigHash) { if (this.tx.ins[input.i].s.length > 0) return {}; var wk = this._findWalletKey(walletKeyMap, input); if (!wk) return; var sigRaw = TransactionBuilder._signHashAndVerify(wk, txSigHash); var sigType = new Buffer(1); sigType[0] = this.signhash; var sig = Buffer.concat([sigRaw, sigType]); var scriptSig = new Script(); scriptSig.chunks.push(sig); scriptSig.updateBuffer(); return { inputFullySigned: true, signaturesAdded: 1, script: scriptSig.getBuffer() }; }; TransactionBuilder.prototype._signPubKeyHash = function(walletKeyMap, input, txSigHash) { if (this.tx.ins[input.i].s.length > 0) return {}; var wk = this._findWalletKey(walletKeyMap, input); if (!wk) return; var sigRaw = TransactionBuilder._signHashAndVerify(wk, txSigHash); var sigType = new Buffer(1); sigType[0] = this.signhash; var sig = Buffer.concat([sigRaw, sigType]); var scriptSig = new Script(); scriptSig.chunks.push(sig); scriptSig.chunks.push(wk.privKey.public); scriptSig.updateBuffer(); return { inputFullySigned: true, signaturesAdded: 1, script: scriptSig.getBuffer() }; }; /* FOR TESTING var _dumpChunks = function (scriptSig, label) { console.log('## DUMP: ' + label + ' ##'); for(var i=0; i<scriptSig.chunks.length; i++) { console.log('\tCHUNK ', i, Buffer.isBuffer(scriptSig.chunks[i]) ?scriptSig.chunks[i].toString('hex'):scriptSig.chunks[i] ); } }; */ TransactionBuilder.prototype._chunkSignedWithKey = function(scriptSig, txSigHash, publicKey) { var ret; var k = new Key(); k.public = publicKey; for (var i = 1; i <= scriptSig.countSignatures(); i++) { var chunk = scriptSig.chunks[i]; var sigRaw = new Buffer(chunk.slice(0, chunk.length - 1)); if (k.verifySignatureSync(txSigHash, sigRaw)) { ret = chunk; } } return ret; }; TransactionBuilder.prototype._getSignatureOrder = function(sigPrio, sigRaw, txSigHash, pubkeys) { var l = pubkeys.length; for (var j = 0; j < l; j++) { var k = new Key(); k.public = new Buffer(pubkeys[j], 'hex'); if (k.verifySignatureSync(txSigHash, sigRaw)) break; } return j; }; TransactionBuilder.prototype._getNewSignatureOrder = function(sigPrio, scriptSig, txSigHash, pubkeys) { var iPrio; for (var i = 1; i <= scriptSig.countSignatures(); i++) { var chunk = scriptSig.chunks[i]; var sigRaw = new Buffer(chunk.slice(0, chunk.length - 1)); iPrio = this._getSignatureOrder(sigPrio, sigRaw, txSigHash, pubkeys); if (sigPrio <= iPrio) break; } return (sigPrio === iPrio ? -1 : i - 1); }; TransactionBuilder.prototype._chunkIsEmpty = function(chunk) { return chunk === 0 || // when serializing and back, EMPTY_BUFFER becomes 0 buffertools.compare(chunk, util.EMPTY_BUFFER) === 0; }; TransactionBuilder.prototype._initMultiSig = function(script) { var wasUpdated = false; if (script.chunks[0] !== 0) { script.prependOp0(); wasUpdated = true; } return wasUpdated; }; TransactionBuilder.prototype._updateMultiSig = function(sigPrio, wk, scriptSig, txSigHash, pubkeys) { var wasUpdated = this._initMultiSig(scriptSig); if (this._chunkSignedWithKey(scriptSig, txSigHash, wk.privKey.public)) return null; // Create signature var sigRaw = TransactionBuilder._signHashAndVerify(wk, txSigHash); var sigType = new Buffer(1); sigType[0] = this.signhash; var sig = Buffer.concat([sigRaw, sigType]); // Add signature var order = this._getNewSignatureOrder(sigPrio, scriptSig, txSigHash, pubkeys); scriptSig.chunks.splice(order + 1, 0, sig); scriptSig.updateBuffer(); wasUpdated = true; return wasUpdated ? scriptSig : null; }; TransactionBuilder.prototype._signMultiSig = function(walletKeyMap, input, txSigHash) { var pubkeys = input.scriptPubKey.capture(), nreq = input.scriptPubKey.chunks[0] - 80, //see OP_2-OP_16 l = pubkeys.length, originalScriptBuf = this.tx.ins[input.i].s; var scriptSig = new Script(originalScriptBuf); var signaturesAdded = 0; for (var j = 0; j < l && scriptSig.countSignatures() < nreq; j++) { var wk = this._findWalletKey(walletKeyMap, { pubKeyBuf: pubkeys[j] }); if (!wk) continue; var newScriptSig = this._updateMultiSig(j, wk, scriptSig, txSigHash, pubkeys); if (newScriptSig) { scriptSig = newScriptSig; signaturesAdded++; } } var ret = { inputFullySigned: scriptSig.countSignatures() === nreq, signaturesAdded: signaturesAdded, script: scriptSig.getBuffer(), }; return ret; }; var fnToSign = {}; TransactionBuilder.prototype._scriptIsAppended = function(script, scriptToAddBuf) { var len = script.chunks.length; if (script.chunks[len - 1] === undefined) return false; if (typeof script.chunks[len - 1] === 'number') return false; if (buffertools.compare(script.chunks[len - 1], scriptToAddBuf) !== 0) return false; return true; }; TransactionBuilder.prototype._addScript = function(scriptBuf, scriptToAddBuf) { var s = new Script(scriptBuf); if (!this._scriptIsAppended(s, scriptToAddBuf)) { s.chunks.push(scriptToAddBuf); s.updateBuffer(); } return s.getBuffer(); }; TransactionBuilder.prototype._getInputForP2sh = function(script, index) { var scriptType = script.classify(); /* pubKeyHash is needed for TX_PUBKEYHASH and TX_PUBKEY to retrieve the keys. */ var pubKeyHash; switch (scriptType) { case Script.TX_PUBKEYHASH: pubKeyHash = script.captureOne(); break; case Script.TX_PUBKEY: var chunk = script.captureOne(); pubKeyHash = util.sha256ripe160(chunk); } return { i: index, pubKeyHash: pubKeyHash, scriptPubKey: script, scriptType: scriptType, isP2sh: true, }; }; TransactionBuilder.prototype._p2shInput = function(input) { if (!this.hashToScriptMap) throw new Error('hashToScriptMap not set'); var scriptHex = this.hashToScriptMap[input.address]; if (!scriptHex) return; var scriptBuf = new Buffer(scriptHex, 'hex'); var script = new Script(scriptBuf); var scriptType = script.classify(); if (!fnToSign[scriptType] || scriptType === Script.TX_SCRIPTHASH) throw new Error('dont know how to sign p2sh script type:' + script.getRawOutType()); return { input: this._getInputForP2sh(script, input.i), txSigHash: this.tx.hashForSignature(script, input.i, this.signhash), scriptType: script.classify(), scriptBuf: scriptBuf, }; }; TransactionBuilder.prototype._signScriptHash = function(walletKeyMap, input, txSigHash) { var p2sh = this._p2shInput(input); var ret = fnToSign[p2sh.scriptType].call(this, walletKeyMap, p2sh.input, p2sh.txSigHash); if (ret && ret.script && ret.signaturesAdded) { ret.script = this._addScript(ret.script, p2sh.scriptBuf); } return ret; }; fnToSign[Script.TX_PUBKEYHASH] = TransactionBuilder.prototype._signPubKeyHash; fnToSign[Script.TX_PUBKEY] = TransactionBuilder.prototype._signPubKey; fnToSign[Script.TX_MULTISIG] = TransactionBuilder.prototype._signMultiSig; fnToSign[Script.TX_SCRIPTHASH] = TransactionBuilder.prototype._signScriptHash; // sign // ---- // Signs a transaction. // `keys`: an array of strings representing private keys to sign the // transaction in WIF private key format OR bitcore's `WalletKey` objects // // If multiple keys are given, each will be tested against the transaction's // scriptPubKeys. Only the valid private keys will be used to sign. // This method is fully compatible with *multisig* transactions. // // `.isFullySigned` can be queried to check is the transactions have all the needed // signatures. // // TransactionBuilder.prototype.sign = function(keys) { if (!(keys instanceof Array)) throw new Error('parameter should be an array'); this._checkTx(); var tx = this.tx, ins = tx.ins, l = ins.length, walletKeyMap = TransactionBuilder._mapKeys(keys); for (var i = 0; i < l; i++) { var input = this.inputMap[i]; var txSigHash = this.tx.hashForSignature( input.scriptPubKey, i, this.signhash); var ret = fnToSign[input.scriptType].call(this, walletKeyMap, input, txSigHash); if (ret && ret.script) { this.vanilla.scriptSig[i] = ret.script.toString('hex'); tx.ins[i].s = ret.script; if (ret.inputFullySigned) this.inputsSigned++; } } return this; }; // setHashToScriptMap // ------------------ // Needed for setup Address to Script maps // for p2sh transactions. See `.infoForP2sh` // for generate the input for this call. // TransactionBuilder.prototype.setHashToScriptMap = function(hashToScriptMap) { this.vanilla.hashToScriptMap = JSON.stringify(hashToScriptMap); this.hashToScriptMap = hashToScriptMap; return this; }; // isFullySigned // ------------- // Checks if the transaction have all the necesary signatures. // TransactionBuilder.prototype.isFullySigned = function() { return this.inputsSigned === this.tx.ins.length; }; TransactionBuilder.prototype.build = function() { this._checkTx(); return this.tx; }; // toObj // ----- // Returns a plain Javascript object that contains // the full status of the TransactionBuilder instance, // suitable for serialization, storage and transmition. // See `.fromObj` // TransactionBuilder.prototype.toObj = function() { var ret = { version: TOOBJ_VERSION, outs: JSON.parse(this.vanilla.outs), utxos: JSON.parse(this.vanilla.utxos), opts: JSON.parse(this.vanilla.opts), scriptSig: this.vanilla.scriptSig, }; if (this.vanilla.hashToScriptMap) ret.hashToScriptMap = JSON.parse(this.vanilla.hashToScriptMap); return ret; }; TransactionBuilder.prototype._setScriptSig = function(inScriptSig) { this.vanilla.scriptSig = inScriptSig; for (var i in inScriptSig) { this.tx.ins[i].s = new Buffer(inScriptSig[i], 'hex'); var scriptSig = new Script(this.tx.ins[i].s); if (scriptSig.finishedMultiSig() !== false) this.inputsSigned++; } }; // fromObj // ------- // Returns a TransactionBuilder instance given // a plain Javascript object created previously // with `.toObj`. See `.toObj`. TransactionBuilder.fromObj = function(data) { if (data.version !== TOOBJ_VERSION) throw new Error('Incompatible version at TransactionBuilder fromObj'); var b = new TransactionBuilder(data.opts); if (data.utxos) { b.setUnspent(data.utxos); if (data.hashToScriptMap) b.setHashToScriptMap(data.hashToScriptMap); if (data.outs) { b.setOutputs(data.outs); if (data.scriptSig) { b._setScriptSig(data.scriptSig); } } } return b; }; TransactionBuilder.prototype._checkMergeability = function(b) { var toCompare = ['opts', 'hashToScriptMap', 'outs', 'uxtos']; for (var i in toCompare) { var k = toCompare[i]; if (JSON.stringify(this.vanilla[k]) !== JSON.stringify(b.vanilla[k])) throw new Error('cannot merge: incompatible builders:' + k) } }; // TODO this could be on Script class TransactionBuilder.prototype._mergeInputSigP2sh = function(input, s0, s1) { var p2sh = this._p2shInput(input); var redeemScript = new Script(p2sh.scriptBuf); var pubkeys = redeemScript.capture(); // Look for differences var s0keys = {}; var l = pubkeys.length; for (var j = 0; j < l; j++) { if (this._chunkSignedWithKey(s0, p2sh.txSigHash, pubkeys[j])) s0keys[pubkeys[j].toString('hex')] = 1; } var diff = []; for (var j = 0; j < l; j++) { var chunk = this._chunkSignedWithKey(s1, p2sh.txSigHash, pubkeys[j]); var pubHex = pubkeys[j].toString('hex'); if (chunk && !s0keys[pubHex]) { diff.push({ prio: j, chunk: chunk, pubHex: pubHex, }); } } // Add signatures for (var j in diff) { var newSig = diff[j]; var order = this._getNewSignatureOrder(newSig.prio, s0, p2sh.txSigHash, pubkeys); s0.chunks.splice(order + 1, 0, newSig.chunk); } s0.updateBuffer(); return s0.getBuffer(); }; // TODO: move this to script TransactionBuilder.prototype._getSighashType = function(sig) { return sig[sig.length - 1]; }; TransactionBuilder.prototype._checkSignHash = function(s1) { var l = s1.chunks.length - 1; for (var i = 0; i < l; i++) { if (i == 0 && s1.chunks[i] === 0) continue; if (this._getSighashType(s1.chunks[i]) !== this.signhash) throw new Error('signhash type mismatch at merge p2sh'); } }; // TODO this could be on Script class TransactionBuilder.prototype._mergeInputSig = function(index, s0buf, s1buf) { if (buffertools.compare(s0buf, s1buf) === 0) return s0buf; var s0 = new Script(s0buf); var s1 = new Script(s1buf); var l0 = s0.chunks.length; var l1 = s1.chunks.length; var s0map = {}; if (l0 && l1 && ((l0 < 2 && l1 > 2) || (l1 < 2 && l0 > 2))) throw new Error('TX sig types mismatch in merge'); if ((!l0 && !l1) || (l0 && !l1)) return s0buf; this._checkSignHash(s1); if ((!l0 && l1)) return s1buf; // Get the pubkeys var input = this.inputMap[index]; var type = input.scriptPubKey.classify(); //p2pubkey or p2pubkeyhash if (type === Script.TX_PUBKEYHASH || type === Script.TX_PUBKEY) { var s = new Script(s1buf); log.debug('Merging two signed inputs type:' + input.scriptPubKey.getRawOutType() + '. Signatures differs. Using the first version.'); return s0buf; } else if (type !== Script.TX_SCRIPTHASH) { // No support for normal multisig or strange txs. throw new Error('Script type:' + input.scriptPubKey.getRawOutType() + 'not supported at #merge'); } return this._mergeInputSigP2sh(input, s0, s1); }; // TODO this could be on Transaction class TransactionBuilder.prototype._mergeTx = function(tx) { var v0 = this.tx; var v1 = tx; var l = v0.ins.length; if (l !== v1.ins.length) throw new Error('TX in length mismatch in merge'); this.inputsSigned = 0; for (var i = 0; i < l; i++) { var i0 = v0.ins[i]; var i1 = v1.ins[i]; if (i0.q !== i1.q) throw new Error('TX sequence ins mismatch in merge. Input:', i); if (buffertools.compare(i0.o, i1.o) !== 0) throw new Error('TX .o in mismatch in merge. Input:', i); i0.s = this._mergeInputSig(i, i0.s, i1.s); this.vanilla.scriptSig[i] = i0.s.toString('hex'); if (v0.isInputComplete(i)) this.inputsSigned++; } }; // clone // ----- // Clone current TransactionBuilder, regenerate derived fields. // TransactionBuilder.prototype.clone = function() { return new TransactionBuilder.fromObj(this.toObj()); }; // merge // ----- // Merge to TransactionBuilder objects, merging inputs signatures. // This function supports multisig p2sh inputs. TransactionBuilder.prototype.merge = function(inB) { // var b = inB.clone(); this._checkMergeability(b); // Does this tX have any signature already? if (this.tx || b.tx) { if (this.tx.getNormalizedHash().toString('hex') !== b.tx.getNormalizedHash().toString('hex')) throw new Error('mismatch at TransactionBuilder NTXID'); this._mergeTx(b.tx); } }; module.exports = TransactionBuilder;
1
13,000
`typeof` is not a function - its an operator, and the standard way to use it is as `typeof foo !== ...` (i.e. no parenthesis). Also, I would personally use `opts.fee != null` instead (with a non-strict comparison, which also identifies `undefined` values because `null == undefined`).
bitpay-bitcore
js
@@ -855,6 +855,7 @@ class ReaderTest < Minitest::Test end test 'unreadable file referenced by include directive is replaced by warning' do + next if windows? # JRuby on Windows runs this even with the conditional on the block include_file = File.join DIRNAME, 'fixtures', 'chapter-a.adoc' FileUtils.chmod 0000, include_file input = <<~'EOS'
1
# frozen_string_literal: true require_relative 'test_helper' class ReaderTest < Minitest::Test DIRNAME = ASCIIDOCTOR_TEST_DIR SAMPLE_DATA = ['first line', 'second line', 'third line'] context 'Reader' do context 'Prepare lines' do test 'should prepare lines from Array data' do reader = Asciidoctor::Reader.new SAMPLE_DATA assert_equal SAMPLE_DATA, reader.lines end test 'should prepare lines from String data' do reader = Asciidoctor::Reader.new SAMPLE_DATA.join(Asciidoctor::LF) assert_equal SAMPLE_DATA, reader.lines end test 'should prepare lines from String data with trailing newline' do reader = Asciidoctor::Reader.new SAMPLE_DATA.join(Asciidoctor::LF) + Asciidoctor::LF assert_equal SAMPLE_DATA, reader.lines end test 'should remove UTF-8 BOM from first line of String data' do ['UTF-8', 'ASCII-8BIT'].each do |start_encoding| data = String.new %(\xef\xbb\xbf#{SAMPLE_DATA.join ::Asciidoctor::LF}), encoding: start_encoding reader = Asciidoctor::Reader.new data, nil, normalize: true assert_equal Encoding::UTF_8, reader.lines[0].encoding assert_equal 'f', reader.lines[0].chr assert_equal SAMPLE_DATA, reader.lines end end test 'should remove UTF-8 BOM from first line of Array data' do ['UTF-8', 'ASCII-8BIT'].each do |start_encoding| data = SAMPLE_DATA.drop 0 data[0] = String.new %(\xef\xbb\xbf#{data.first}), encoding: start_encoding reader = Asciidoctor::Reader.new data, nil, normalize: true assert_equal Encoding::UTF_8, reader.lines[0].encoding assert_equal 'f', reader.lines[0].chr assert_equal SAMPLE_DATA, reader.lines end end test 'should encode UTF-16LE string to UTF-8 when BOM is found' do ['UTF-8', 'ASCII-8BIT'].each do |start_encoding| data = "\ufeff#{SAMPLE_DATA.join ::Asciidoctor::LF}".encode('UTF-16LE').force_encoding(start_encoding) reader = Asciidoctor::Reader.new data, nil, normalize: true assert_equal Encoding::UTF_8, reader.lines[0].encoding assert_equal 'f', reader.lines[0].chr assert_equal SAMPLE_DATA, reader.lines end end test 'should encode UTF-16LE string array to UTF-8 when BOM is found' do ['UTF-8', 'ASCII-8BIT'].each do |start_encoding| # NOTE can't split a UTF-16LE string using .lines when encoding is set to UTF-8 data = SAMPLE_DATA.drop 0 data.unshift %(\ufeff#{data.shift}) data.each {|line| (line.encode 'UTF-16LE').force_encoding start_encoding } reader = Asciidoctor::Reader.new data, nil, normalize: true assert_equal Encoding::UTF_8, reader.lines[0].encoding assert_equal 'f', reader.lines[0].chr assert_equal SAMPLE_DATA, reader.lines end end test 'should encode UTF-16BE string to UTF-8 when BOM is found' do ['UTF-8', 'ASCII-8BIT'].each do |start_encoding| data = "\ufeff#{SAMPLE_DATA.join ::Asciidoctor::LF}".encode('UTF-16BE').force_encoding(start_encoding) reader = Asciidoctor::Reader.new data, nil, normalize: true assert_equal Encoding::UTF_8, reader.lines[0].encoding assert_equal 'f', reader.lines[0].chr assert_equal SAMPLE_DATA, reader.lines end end test 'should encode UTF-16BE string array to UTF-8 when BOM is found' do ['UTF-8', 'ASCII-8BIT'].each do |start_encoding| data = SAMPLE_DATA.drop 0 data.unshift %(\ufeff#{data.shift}) data = data.map {|line| (line.encode 'UTF-16BE').force_encoding start_encoding } reader = Asciidoctor::Reader.new data, nil, normalize: true assert_equal Encoding::UTF_8, reader.lines[0].encoding assert_equal 'f', reader.lines[0].chr assert_equal SAMPLE_DATA, reader.lines end end end context 'With empty data' do test 'has_more_lines? should return false with empty data' do refute Asciidoctor::Reader.new.has_more_lines? end test 'empty? should return true with empty data' do assert Asciidoctor::Reader.new.empty? assert Asciidoctor::Reader.new.eof? end test 'next_line_empty? should return true with empty data' do assert Asciidoctor::Reader.new.next_line_empty? end test 'peek_line should return nil with empty data' do assert_nil Asciidoctor::Reader.new.peek_line end test 'peek_lines should return empty Array with empty data' do assert_equal [], Asciidoctor::Reader.new.peek_lines(1) end test 'read_line should return nil with empty data' do assert_nil Asciidoctor::Reader.new.read_line #assert_nil Asciidoctor::Reader.new.get_line end test 'read_lines should return empty Array with empty data' do assert_equal [], Asciidoctor::Reader.new.read_lines #assert_equal [], Asciidoctor::Reader.new.get_lines end end context 'With data' do test 'has_more_lines? should return true if there are lines remaining' do reader = Asciidoctor::Reader.new SAMPLE_DATA assert reader.has_more_lines? end test 'empty? should return false if there are lines remaining' do reader = Asciidoctor::Reader.new SAMPLE_DATA refute reader.empty? refute reader.eof? end test 'next_line_empty? should return false if next line is not blank' do reader = Asciidoctor::Reader.new SAMPLE_DATA refute reader.next_line_empty? end test 'next_line_empty? should return true if next line is blank' do reader = Asciidoctor::Reader.new ['', 'second line'] assert reader.next_line_empty? end test 'peek_line should return next line if there are lines remaining' do reader = Asciidoctor::Reader.new SAMPLE_DATA assert_equal SAMPLE_DATA.first, reader.peek_line end test 'peek_line should not consume line or increment line number' do reader = Asciidoctor::Reader.new SAMPLE_DATA assert_equal SAMPLE_DATA.first, reader.peek_line assert_equal SAMPLE_DATA.first, reader.peek_line assert_equal 1, reader.lineno end test 'peek_line should return next lines if there are lines remaining' do reader = Asciidoctor::Reader.new SAMPLE_DATA assert_equal SAMPLE_DATA[0..1], reader.peek_lines(2) end test 'peek_lines should not consume lines or increment line number' do reader = Asciidoctor::Reader.new SAMPLE_DATA assert_equal SAMPLE_DATA[0..1], reader.peek_lines(2) assert_equal SAMPLE_DATA[0..1], reader.peek_lines(2) assert_equal 1, reader.lineno end test 'peek_lines should not increment line number if reader overruns buffer' do reader = Asciidoctor::Reader.new SAMPLE_DATA assert_equal SAMPLE_DATA, (reader.peek_lines SAMPLE_DATA.size * 2) assert_equal 1, reader.lineno end test 'peek_lines should peek all lines if no arguments are given' do reader = Asciidoctor::Reader.new SAMPLE_DATA assert_equal SAMPLE_DATA, reader.peek_lines assert_equal 1, reader.lineno end test 'peek_lines should not invert order of lines' do reader = Asciidoctor::Reader.new SAMPLE_DATA assert_equal SAMPLE_DATA, reader.lines reader.peek_lines 3 assert_equal SAMPLE_DATA, reader.lines end test 'read_line should return next line if there are lines remaining' do reader = Asciidoctor::Reader.new SAMPLE_DATA assert_equal SAMPLE_DATA.first, reader.read_line end test 'read_line should consume next line and increment line number' do reader = Asciidoctor::Reader.new SAMPLE_DATA assert_equal SAMPLE_DATA[0], reader.read_line assert_equal SAMPLE_DATA[1], reader.read_line assert_equal 3, reader.lineno end test 'advance should consume next line and return a Boolean indicating if a line was consumed' do reader = Asciidoctor::Reader.new SAMPLE_DATA assert reader.advance assert reader.advance assert reader.advance refute reader.advance end test 'read_lines should return all lines' do reader = Asciidoctor::Reader.new SAMPLE_DATA assert_equal SAMPLE_DATA, reader.read_lines end test 'read should return all lines joined as String' do reader = Asciidoctor::Reader.new SAMPLE_DATA assert_equal SAMPLE_DATA.join(::Asciidoctor::LF), reader.read end test 'has_more_lines? should return false after read_lines is invoked' do reader = Asciidoctor::Reader.new SAMPLE_DATA reader.read_lines refute reader.has_more_lines? end test 'unshift puts line onto Reader as next line to read' do reader = Asciidoctor::Reader.new SAMPLE_DATA, nil, normalize: true reader.unshift 'line zero' assert_equal 'line zero', reader.peek_line assert_equal 'line zero', reader.read_line assert_equal 1, reader.lineno end test 'terminate should consume all lines and update line number' do reader = Asciidoctor::Reader.new SAMPLE_DATA reader.terminate assert reader.eof? assert_equal 4, reader.lineno end test 'skip_blank_lines should skip blank lines' do reader = Asciidoctor::Reader.new ['', ''].concat(SAMPLE_DATA) reader.skip_blank_lines assert_equal SAMPLE_DATA.first, reader.peek_line end test 'lines should return remaining lines' do reader = Asciidoctor::Reader.new SAMPLE_DATA reader.read_line assert_equal SAMPLE_DATA[1..-1], reader.lines end test 'source_lines should return copy of original data Array' do reader = Asciidoctor::Reader.new SAMPLE_DATA reader.read_lines assert_equal SAMPLE_DATA, reader.source_lines end test 'source should return original data Array joined as String' do reader = Asciidoctor::Reader.new SAMPLE_DATA reader.read_lines assert_equal SAMPLE_DATA.join(::Asciidoctor::LF), reader.source end end context 'Line context' do test 'cursor.to_s should return file name and line number of current line' do reader = Asciidoctor::Reader.new SAMPLE_DATA, 'sample.adoc' reader.read_line assert_equal 'sample.adoc: line 2', reader.cursor.to_s end test 'line_info should return file name and line number of current line' do reader = Asciidoctor::Reader.new SAMPLE_DATA, 'sample.adoc' reader.read_line assert_equal 'sample.adoc: line 2', reader.line_info end test 'cursor_at_prev_line should return file name and line number of previous line read' do reader = Asciidoctor::Reader.new SAMPLE_DATA, 'sample.adoc' reader.read_line assert_equal 'sample.adoc: line 1', reader.cursor_at_prev_line.to_s end end context 'Read lines until' do test 'Read lines until until end' do lines = <<~'EOS'.lines This is one paragraph. This is another paragraph. EOS reader = Asciidoctor::Reader.new lines, nil, normalize: true result = reader.read_lines_until assert_equal 3, result.size assert_equal lines.map(&:chomp), result refute reader.has_more_lines? assert reader.eof? end test 'Read lines until until blank line' do lines = <<~'EOS'.lines This is one paragraph. This is another paragraph. EOS reader = Asciidoctor::Reader.new lines, nil, normalize: true result = reader.read_lines_until break_on_blank_lines: true assert_equal 1, result.size assert_equal lines.first.chomp, result.first assert_equal lines.last.chomp, reader.peek_line end test 'Read lines until until blank line preserving last line' do lines = <<~'EOS'.split ::Asciidoctor::LF This is one paragraph. This is another paragraph. EOS reader = Asciidoctor::Reader.new lines result = reader.read_lines_until break_on_blank_lines: true, preserve_last_line: true assert_equal 1, result.size assert_equal lines.first.chomp, result.first assert reader.next_line_empty? end test 'Read lines until until condition is true' do lines = <<~'EOS'.split ::Asciidoctor::LF -- This is one paragraph inside the block. This is another paragraph inside the block. -- This is a paragraph outside the block. EOS reader = Asciidoctor::Reader.new lines reader.read_line result = reader.read_lines_until {|line| line == '--' } assert_equal 3, result.size assert_equal lines[1, 3], result assert reader.next_line_empty? end test 'Read lines until until condition is true, taking last line' do lines = <<~'EOS'.split ::Asciidoctor::LF -- This is one paragraph inside the block. This is another paragraph inside the block. -- This is a paragraph outside the block. EOS reader = Asciidoctor::Reader.new lines reader.read_line result = reader.read_lines_until(read_last_line: true) {|line| line == '--' } assert_equal 4, result.size assert_equal lines[1, 4], result assert reader.next_line_empty? end test 'Read lines until until condition is true, taking and preserving last line' do lines = <<~'EOS'.split ::Asciidoctor::LF -- This is one paragraph inside the block. This is another paragraph inside the block. -- This is a paragraph outside the block. EOS reader = Asciidoctor::Reader.new lines reader.read_line result = reader.read_lines_until(read_last_line: true, preserve_last_line: true) {|line| line == '--' } assert_equal 4, result.size assert_equal lines[1, 4], result assert_equal '--', reader.peek_line end test 'read lines until terminator' do lines = <<~'EOS'.lines **** captured also captured **** not captured EOS expected = ['captured', '', 'also captured'] doc = empty_safe_document base_dir: DIRNAME reader = Asciidoctor::PreprocessorReader.new doc, lines, nil, normalize: true terminator = reader.read_line result = reader.read_lines_until terminator: terminator, skip_processing: true assert_equal expected, result refute reader.unterminated end test 'should flag reader as unterminated if reader reaches end of source without finding terminator' do lines = <<~'EOS'.lines **** captured also captured captured yet again EOS expected = lines[1..-1].map(&:chomp) using_memory_logger do |logger| doc = empty_safe_document base_dir: DIRNAME reader = Asciidoctor::PreprocessorReader.new doc, lines, nil, normalize: true terminator = reader.peek_line result = reader.read_lines_until terminator: terminator, skip_first_line: true, skip_processing: true assert_equal expected, result assert reader.unterminated assert_message logger, :WARN, '<stdin>: line 1: unterminated **** block', Hash end end end end context 'PreprocessorReader' do context 'Type hierarchy' do test 'PreprocessorReader should extend from Reader' do reader = empty_document.reader assert_kind_of Asciidoctor::PreprocessorReader, reader end test 'PreprocessorReader should invoke or emulate Reader initializer' do doc = Asciidoctor::Document.new SAMPLE_DATA reader = doc.reader assert_equal SAMPLE_DATA, reader.lines assert_equal 1, reader.lineno end end context 'Prepare lines' do test 'should prepare and normalize lines from Array data' do data = SAMPLE_DATA.drop 0 data.unshift '' data.push '' doc = Asciidoctor::Document.new data reader = doc.reader assert_equal SAMPLE_DATA, reader.lines end test 'should prepare and normalize lines from String data' do data = SAMPLE_DATA.drop 0 data.unshift ' ' data.push ' ' data_as_string = data * ::Asciidoctor::LF doc = Asciidoctor::Document.new data_as_string reader = doc.reader assert_equal SAMPLE_DATA, reader.lines end test 'should clean CRLF from end of lines' do input = <<~EOS source\r with\r CRLF\r line endings\r EOS [input, input.lines, input.split(::Asciidoctor::LF), input.split(::Asciidoctor::LF).join(::Asciidoctor::LF)].each do |lines| doc = Asciidoctor::Document.new lines reader = doc.reader reader.lines.each do |line| refute line.end_with?("\r"), "CRLF not properly cleaned for source lines: #{lines.inspect}" refute line.end_with?("\r\n"), "CRLF not properly cleaned for source lines: #{lines.inspect}" refute line.end_with?("\n"), "CRLF not properly cleaned for source lines: #{lines.inspect}" end end end test 'should not skip front matter by default' do input = <<~'EOS' --- layout: post title: Document Title author: username tags: [ first, second ] --- = Document Title Author Name preamble EOS doc = Asciidoctor::Document.new input reader = doc.reader refute doc.attributes.key?('front-matter') assert_equal '---', reader.peek_line end test 'should skip front matter if specified by skip-front-matter attribute' do front_matter = <<~'EOS'.chop layout: post title: Document Title author: username tags: [ first, second ] EOS input = <<~EOS --- #{front_matter} --- = Document Title Author Name preamble EOS doc = Asciidoctor::Document.new input, attributes: { 'skip-front-matter' => '' } reader = doc.reader assert_equal '= Document Title', reader.peek_line assert_equal front_matter, doc.attributes['front-matter'] end end context 'Include Stack' do test 'PreprocessorReader#push_include method should return reader' do reader = empty_document.reader append_lines = %w(one two three) result = reader.push_include append_lines, '<stdin>', '<stdin>' assert_equal reader, result end test 'PreprocessorReader#push_include method should put lines on top of stack' do lines = %w(a b c) doc = Asciidoctor::Document.new lines reader = doc.reader append_lines = %w(one two three) reader.push_include append_lines, '', '<stdin>' assert_equal 1, reader.include_stack.size assert_equal 'one', reader.read_line.rstrip end test 'PreprocessorReader#push_include method should gracefully handle file and path' do lines = %w(a b c) doc = Asciidoctor::Document.new lines reader = doc.reader append_lines = %w(one two three) reader.push_include append_lines assert_equal 1, reader.include_stack.size assert_equal 'one', reader.read_line.rstrip assert_nil reader.file assert_equal '<stdin>', reader.path end test 'PreprocessorReader#push_include method should set path from file automatically if not specified' do lines = %w(a b c) doc = Asciidoctor::Document.new lines reader = doc.reader append_lines = %w(one two three) reader.push_include append_lines, '/tmp/lines.adoc' assert_equal '/tmp/lines.adoc', reader.file assert_equal 'lines.adoc', reader.path assert doc.catalog[:includes]['lines'] end test 'PreprocessorReader#push_include method should accept file as a URI and compute dir and path' do file_uri = ::URI.parse 'http://example.com/docs/file.adoc' dir_uri = ::URI.parse 'http://example.com/docs' reader = empty_document.reader reader.push_include %w(one two three), file_uri assert_same file_uri, reader.file assert_equal dir_uri, reader.dir assert_equal 'file.adoc', reader.path end test 'PreprocessorReader#push_include method should accept file as a top-level URI and compute dir and path' do file_uri = ::URI.parse 'http://example.com/index.adoc' dir_uri = ::URI.parse 'http://example.com' reader = empty_document.reader reader.push_include %w(one two three), file_uri assert_same file_uri, reader.file assert_equal dir_uri, reader.dir assert_equal 'index.adoc', reader.path end test 'PreprocessorReader#push_include method should not fail if data is nil' do lines = %w(a b c) doc = Asciidoctor::Document.new lines reader = doc.reader reader.push_include nil, '', '<stdin>' assert_equal 0, reader.include_stack.size assert_equal 'a', reader.read_line.rstrip end test 'PreprocessorReader#push_include method should ignore dot in directory name when computing include path' do lines = %w(a b c) doc = Asciidoctor::Document.new lines reader = doc.reader append_lines = %w(one two three) reader.push_include append_lines, nil, 'include.d/data' assert_nil reader.file assert_equal 'include.d/data', reader.path assert doc.catalog[:includes]['include.d/data'] end end context 'Include Directive' do test 'include directive is disabled by default and becomes a link' do input = 'include::include-file.adoc[]' doc = Asciidoctor::Document.new input reader = doc.reader assert_equal 'link:include-file.adoc[]', reader.read_line end test 'include directive is enabled when safe mode is less than SECURE' do input = 'include::fixtures/include-file.adoc[]' doc = document_from_string input, safe: :safe, standalone: false, base_dir: DIRNAME output = doc.convert assert_match(/included content/, output) assert doc.catalog[:includes]['fixtures/include-file'] end test 'strips BOM from include file' do input = %(:showtitle:\ninclude::fixtures/file-with-utf8-bom.adoc[]) output = convert_string_to_embedded input, safe: :safe, base_dir: DIRNAME assert_css '.paragraph', output, 0 assert_css 'h1', output, 1 assert_match(/<h1>人<\/h1>/, output) end test 'should not track include in catalog for non-AsciiDoc include files' do input = <<~'EOS' ---- include::fixtures/circle.svg[] ---- EOS doc = document_from_string input, safe: :safe, standalone: false, base_dir: DIRNAME assert doc.catalog[:includes].empty? end test 'include directive should resolve file with spaces in name' do input = 'include::fixtures/include file.adoc[]' include_file = File.join DIRNAME, 'fixtures', 'include-file.adoc' include_file_with_sp = File.join DIRNAME, 'fixtures', 'include file.adoc' begin FileUtils.cp include_file, include_file_with_sp doc = document_from_string input, safe: :safe, standalone: false, base_dir: DIRNAME output = doc.convert assert_match(/included content/, output) ensure FileUtils.rm include_file_with_sp end end test 'include directive should resolve file with {sp} in name' do input = 'include::fixtures/include{sp}file.adoc[]' include_file = File.join DIRNAME, 'fixtures', 'include-file.adoc' include_file_with_sp = File.join DIRNAME, 'fixtures', 'include file.adoc' begin FileUtils.cp include_file, include_file_with_sp doc = document_from_string input, safe: :safe, standalone: false, base_dir: DIRNAME output = doc.convert assert_match(/included content/, output) ensure FileUtils.rm include_file_with_sp end end test 'include directive should resolve file relative to current include' do input = 'include::fixtures/parent-include.adoc[]' pseudo_docfile = File.join DIRNAME, 'include-master.adoc' fixtures_dir = File.join DIRNAME, 'fixtures' parent_include_docfile = File.join fixtures_dir, 'parent-include.adoc' child_include_docfile = File.join fixtures_dir, 'child-include.adoc' grandchild_include_docfile = File.join fixtures_dir, 'grandchild-include.adoc' doc = empty_safe_document base_dir: DIRNAME reader = Asciidoctor::PreprocessorReader.new doc, input, pseudo_docfile, normalize: true assert_equal pseudo_docfile, reader.file assert_equal DIRNAME, reader.dir assert_equal 'include-master.adoc', reader.path assert_equal 'first line of parent', reader.read_line assert_equal 'fixtures/parent-include.adoc: line 1', reader.cursor_at_prev_line.to_s assert_equal parent_include_docfile, reader.file assert_equal fixtures_dir, reader.dir assert_equal 'fixtures/parent-include.adoc', reader.path reader.skip_blank_lines assert_equal 'first line of child', reader.read_line assert_equal 'fixtures/child-include.adoc: line 1', reader.cursor_at_prev_line.to_s assert_equal child_include_docfile, reader.file assert_equal fixtures_dir, reader.dir assert_equal 'fixtures/child-include.adoc', reader.path reader.skip_blank_lines assert_equal 'first line of grandchild', reader.read_line assert_equal 'fixtures/grandchild-include.adoc: line 1', reader.cursor_at_prev_line.to_s assert_equal grandchild_include_docfile, reader.file assert_equal fixtures_dir, reader.dir assert_equal 'fixtures/grandchild-include.adoc', reader.path reader.skip_blank_lines assert_equal 'last line of grandchild', reader.read_line reader.skip_blank_lines assert_equal 'last line of child', reader.read_line reader.skip_blank_lines assert_equal 'last line of parent', reader.read_line assert_equal 'fixtures/parent-include.adoc: line 5', reader.cursor_at_prev_line.to_s assert_equal parent_include_docfile, reader.file assert_equal fixtures_dir, reader.dir assert_equal 'fixtures/parent-include.adoc', reader.path end test 'include directive should process lines when file extension of target is .asciidoc' do input = 'include::fixtures/include-alt-extension.asciidoc[]' doc = document_from_string input, safe: :safe, base_dir: DIRNAME assert_equal 3, doc.blocks.size assert_equal ['first line'], doc.blocks[0].lines assert_equal ['Asciidoctor!'], doc.blocks[1].lines assert_equal ['last line'], doc.blocks[2].lines end test 'should only strip trailing newlines, not trailing whitespace, if include file is not AsciiDoc' do input = <<~'EOS' .... include::fixtures/data.tsv[] .... EOS doc = document_from_string input, safe: :safe, base_dir: DIRNAME assert_equal 1, doc.blocks.size assert doc.blocks[0].lines[2].end_with? ?\t end test 'should fail to read include file if not UTF-8 encoded and encoding is not specified' do input = <<~'EOS' .... include::fixtures/iso-8859-1.txt[] .... EOS assert_raises StandardError, 'invalid byte sequence in UTF-8' do doc = document_from_string input, safe: :safe, base_dir: DIRNAME assert_equal 1, doc.blocks.size refute_equal ['Où est l\'hôpital ?'], doc.blocks[0].lines doc.convert end end test 'should ignore encoding attribute if value is not an valid encoding' do input = <<~'EOS' .... include::fixtures/encoding.adoc[tag=romé,encoding=iso-1000-1] .... EOS doc = document_from_string input, safe: :safe, base_dir: DIRNAME assert_equal 1, doc.blocks.size assert_equal doc.blocks[0].lines[0].encoding, Encoding::UTF_8 assert_equal ['Gregory Romé has written an AsciiDoc plugin for the Redmine project management application.'], doc.blocks[0].lines end test 'should use encoding specified by encoding attribute when reading include file' do input = <<~'EOS' .... include::fixtures/iso-8859-1.txt[encoding=iso-8859-1] .... EOS doc = document_from_string input, safe: :safe, base_dir: DIRNAME assert_equal 1, doc.blocks.size assert_equal doc.blocks[0].lines[0].encoding, Encoding::UTF_8 assert_equal ['Où est l\'hôpital ?'], doc.blocks[0].lines end test 'unresolved target referenced by include directive is skipped when optional option is set' do input = <<~'EOS' include::fixtures/{no-such-file}[opts=optional] trailing content EOS begin using_memory_logger do |logger| doc = document_from_string input, safe: :safe, base_dir: DIRNAME assert_equal 1, doc.blocks.size assert_equal ['trailing content'], doc.blocks[0].lines assert_message logger, :INFO, '~<stdin>: line 1: optional include dropped because include file not found', Hash end rescue flunk 'include directive should not raise exception on unresolved target' end end test 'missing file referenced by include directive is skipped when optional option is set' do input = <<~'EOS' include::fixtures/no-such-file.adoc[opts=optional] trailing content EOS begin using_memory_logger do |logger| doc = document_from_string input, safe: :safe, base_dir: DIRNAME assert_equal 1, doc.blocks.size assert_equal ['trailing content'], doc.blocks[0].lines assert_message logger, :INFO, '~<stdin>: line 1: optional include dropped because include file not found', Hash end rescue flunk 'include directive should not raise exception on missing file' end end test 'missing file referenced by include directive is replaced by warning' do input = <<~'EOS' include::fixtures/no-such-file.adoc[] trailing content EOS begin using_memory_logger do |logger| doc = document_from_string input, safe: :safe, base_dir: DIRNAME assert_equal 2, doc.blocks.size assert_equal ['Unresolved directive in <stdin> - include::fixtures/no-such-file.adoc[]'], doc.blocks[0].lines assert_equal ['trailing content'], doc.blocks[1].lines assert_message logger, :ERROR, '~<stdin>: line 1: include file not found', Hash end rescue flunk 'include directive should not raise exception on missing file' end end test 'unreadable file referenced by include directive is replaced by warning' do include_file = File.join DIRNAME, 'fixtures', 'chapter-a.adoc' FileUtils.chmod 0000, include_file input = <<~'EOS' include::fixtures/chapter-a.adoc[] trailing content EOS begin using_memory_logger do |logger| doc = document_from_string input, safe: :safe, base_dir: DIRNAME assert_equal 2, doc.blocks.size assert_equal ['Unresolved directive in <stdin> - include::fixtures/chapter-a.adoc[]'], doc.blocks[0].lines assert_equal ['trailing content'], doc.blocks[1].lines assert_message logger, :ERROR, '~<stdin>: line 1: include file not readable', Hash end rescue flunk 'include directive should not raise exception on missing file' ensure FileUtils.chmod 0644, include_file end end unless windows? # IMPORTANT this test needs to be run on Windows to verify proper behavior in Windows test 'can resolve include directive with absolute path' do include_path = ::File.join DIRNAME, 'fixtures', 'chapter-a.adoc' input = %(include::#{include_path}[]) result = document_from_string input, safe: :safe assert_equal 'Chapter A', result.doctitle result = document_from_string input, safe: :unsafe, base_dir: ::Dir.tmpdir assert_equal 'Chapter A', result.doctitle end test 'include directive can retrieve data from uri' do url = %(http://#{resolve_localhost}:9876/name/asciidoctor) input = <<~EOS .... include::#{url}[] .... EOS expect = /\{"name": "asciidoctor"\}/ output = using_test_webserver do convert_string_to_embedded input, safe: :safe, attributes: { 'allow-uri-read' => '' } end refute_nil output assert_match(expect, output) end test 'nested include directives are resolved relative to current file' do input = <<~'EOS' .... include::fixtures/outer-include.adoc[] .... EOS output = convert_string_to_embedded input, safe: :safe, base_dir: DIRNAME expected = <<~'EOS'.chop first line of outer first line of middle first line of inner last line of inner last line of middle last line of outer EOS assert_includes output, expected end test 'nested remote include directive is resolved relative to uri of current file' do url = %(http://#{resolve_localhost}:9876/fixtures/outer-include.adoc) input = <<~EOS .... include::#{url}[] .... EOS output = using_test_webserver do convert_string_to_embedded input, safe: :safe, attributes: { 'allow-uri-read' => '' } end expected = <<~'EOS'.chop first line of outer first line of middle first line of inner last line of inner last line of middle last line of outer EOS assert_includes output, expected end test 'nested remote include directive that cannot be resolved does not crash processor' do include_url = %(http://#{resolve_localhost}:9876/fixtures/file-with-missing-include.adoc) nested_include_url = 'no-such-file.adoc' input = <<~EOS .... include::#{include_url}[] .... EOS begin using_memory_logger do |logger| result = using_test_webserver do convert_string_to_embedded input, safe: :safe, attributes: { 'allow-uri-read' => '' } end assert_includes result, %(Unresolved directive in #{include_url} - include::#{nested_include_url}[]) assert_message logger, :ERROR, %(#{include_url}: line 1: include uri not readable: http://#{resolve_localhost}:9876/fixtures/#{nested_include_url}), Hash end rescue flunk 'include directive should not raise exception on missing file' end end test 'tag filtering is supported for remote includes' do url = %(http://#{resolve_localhost}:9876/fixtures/tagged-class.rb) input = <<~EOS [source,ruby] ---- include::#{url}[tag=init,indent=0] ---- EOS output = using_test_webserver do convert_string_to_embedded input, safe: :safe, attributes: { 'allow-uri-read' => '' } end # NOTE cannot use single-quoted heredoc because of https://github.com/jruby/jruby/issues/4260 expected = <<~EOS.chop <code class="language-ruby" data-lang="ruby">def initialize breed @breed = breed end</code> EOS assert_includes output, expected end test 'inaccessible uri referenced by include directive does not crash processor' do url = %(http://#{resolve_localhost}:9876/no_such_file) input = <<~EOS .... include::#{url}[] .... EOS begin using_memory_logger do |logger| output = using_test_webserver do convert_string_to_embedded input, safe: :safe, attributes: { 'allow-uri-read' => '' } end refute_nil output assert_match(/Unresolved directive/, output) assert_message logger, :ERROR, %(<stdin>: line 2: include uri not readable: #{url}), Hash end rescue flunk 'include directive should not raise exception on inaccessible uri' end end test 'include directive supports selecting lines by line number' do input = 'include::fixtures/include-file.adoc[lines=1;3..4;6..-1]' output = convert_string_to_embedded input, safe: :safe, base_dir: DIRNAME assert_match(/first line/, output) refute_match(/second line/, output) assert_match(/third line/, output) assert_match(/fourth line/, output) refute_match(/fifth line/, output) assert_match(/sixth line/, output) assert_match(/seventh line/, output) assert_match(/eighth line/, output) assert_match(/last line of included content/, output) end test 'include directive supports line ranges specified in quoted attribute value' do input = 'include::fixtures/include-file.adoc[lines="1, 3..4 , 6 .. -1"]' output = convert_string_to_embedded input, safe: :safe, base_dir: DIRNAME assert_match(/first line/, output) refute_match(/second line/, output) assert_match(/third line/, output) assert_match(/fourth line/, output) refute_match(/fifth line/, output) assert_match(/sixth line/, output) assert_match(/seventh line/, output) assert_match(/eighth line/, output) assert_match(/last line of included content/, output) end test 'include directive supports implicit endless range' do input = 'include::fixtures/include-file.adoc[lines=6..]' output = convert_string_to_embedded input, safe: :safe, base_dir: DIRNAME refute_match(/first line/, output) refute_match(/second line/, output) refute_match(/third line/, output) refute_match(/fourth line/, output) refute_match(/fifth line/, output) assert_match(/sixth line/, output) assert_match(/seventh line/, output) assert_match(/eighth line/, output) assert_match(/last line of included content/, output) end test 'include directive ignores empty lines attribute' do input = <<~'EOS' ++++ include::fixtures/include-file.adoc[lines=] ++++ EOS output = convert_string_to_embedded input, safe: :safe, base_dir: DIRNAME assert_includes output, 'first line of included content' assert_includes output, 'last line of included content' end test 'include directive ignores lines attribute with invalid range' do input = <<~'EOS' ++++ include::fixtures/include-file.adoc[lines=10..5] ++++ EOS output = convert_string_to_embedded input, safe: :safe, base_dir: DIRNAME assert_includes output, 'first line of included content' assert_includes output, 'last line of included content' end test 'include directive supports selecting lines by tag' do input = 'include::fixtures/include-file.adoc[tag=snippetA]' output = convert_string_to_embedded input, safe: :safe, base_dir: DIRNAME assert_match(/snippetA content/, output) refute_match(/snippetB content/, output) refute_match(/non-tagged content/, output) refute_match(/included content/, output) end test 'include directive supports selecting lines by tags' do input = 'include::fixtures/include-file.adoc[tags=snippetA;snippetB]' output = convert_string_to_embedded input, safe: :safe, base_dir: DIRNAME assert_match(/snippetA content/, output) assert_match(/snippetB content/, output) refute_match(/non-tagged content/, output) refute_match(/included content/, output) end test 'include directive supports selecting lines by tag in language that uses circumfix comments' do { 'include-file.xml' => '<snippet>content</snippet>', 'include-file.ml' => 'let s = SS.empty;;', 'include-file.jsx' => '<p>Welcome to the club.</p>', }.each do |filename, expect| input = <<~EOS [source,xml] ---- include::fixtures/#{filename}[tag=snippet,indent=0] ---- EOS doc = document_from_string input, safe: :safe, base_dir: DIRNAME assert_equal expect, doc.blocks[0].source end end test 'include directive supports selecting tagged lines in file that has CRLF line endings' do begin tmp_include = Tempfile.new %w(include- .adoc) tmp_include_dir, tmp_include_path = File.split tmp_include.path tmp_include.write %(do not include\r\ntag::include-me[]\r\nincluded line\r\nend::include-me[]\r\ndo not include\r\n) tmp_include.close input = %(include::#{tmp_include_path}[tag=include-me]) output = convert_string_to_embedded input, safe: :safe, base_dir: tmp_include_dir assert_includes output, 'included line' refute_includes output, 'do not include' ensure tmp_include.close! end end test 'include directive finds closing tag on last line of file without a trailing newline' do begin tmp_include = Tempfile.new %w(include- .adoc) tmp_include_dir, tmp_include_path = File.split tmp_include.path tmp_include.write %(line not included\ntag::include-me[]\nline included\nend::include-me[]) tmp_include.close input = %(include::#{tmp_include_path}[tag=include-me]) using_memory_logger do |logger| output = convert_string_to_embedded input, safe: :safe, base_dir: tmp_include_dir assert_empty logger.messages assert_includes output, 'line included' refute_includes output, 'line not included' end ensure tmp_include.close! end end test 'include directive does not select lines with tag directives within selected tag region' do input = <<~'EOS' ++++ include::fixtures/include-file.adoc[tags=snippet] ++++ EOS output = convert_string_to_embedded input, safe: :safe, base_dir: DIRNAME expected = <<~'EOS'.chop snippetA content non-tagged content snippetB content EOS assert_equal expected, output end test 'include directive skips lines marked with negated tags' do input = <<~'EOS' ---- include::fixtures/tagged-class-enclosed.rb[tags=all;!bark] ---- EOS output = convert_string_to_embedded input, safe: :safe, base_dir: DIRNAME # NOTE cannot use single-quoted heredoc because of https://github.com/jruby/jruby/issues/4260 expected = <<~EOS.chop class Dog def initialize breed @breed = breed end end EOS assert_includes output, expected end test 'include directive takes all lines without tag directives when value is double asterisk' do input = <<~'EOS' ---- include::fixtures/tagged-class.rb[tags=**] ---- EOS output = convert_string_to_embedded input, safe: :safe, base_dir: DIRNAME # NOTE cannot use single-quoted heredoc because of https://github.com/jruby/jruby/issues/4260 expected = <<~EOS.chop class Dog def initialize breed @breed = breed end def bark if @breed == 'beagle' 'woof woof woof woof woof' else 'woof woof' end end end EOS assert_includes output, expected end test 'include directive takes all lines except negated tags when value contains double asterisk' do input = <<~'EOS' ---- include::fixtures/tagged-class.rb[tags=**;!bark] ---- EOS output = convert_string_to_embedded input, safe: :safe, base_dir: DIRNAME # NOTE cannot use single-quoted heredoc because of https://github.com/jruby/jruby/issues/4260 expected = <<~EOS.chop class Dog def initialize breed @breed = breed end end EOS assert_includes output, expected end test 'include directive selects lines for all tags when value of tags attribute is wildcard' do input = <<~'EOS' ---- include::fixtures/tagged-class-enclosed.rb[tags=*] ---- EOS output = convert_string_to_embedded input, safe: :safe, base_dir: DIRNAME # NOTE cannot use single-quoted heredoc because of https://github.com/jruby/jruby/issues/4260 expected = <<~EOS.chop class Dog def initialize breed @breed = breed end def bark if @breed == 'beagle' 'woof woof woof woof woof' else 'woof woof' end end end EOS assert_includes output, expected end test 'include directive selects lines for all tags except exclusions when value of tags attribute is wildcard' do input = <<~'EOS' ---- include::fixtures/tagged-class-enclosed.rb[tags=*;!init] ---- EOS output = convert_string_to_embedded input, safe: :safe, base_dir: DIRNAME # NOTE cannot use single-quoted heredoc because of https://github.com/jruby/jruby/issues/4260 expected = <<~EOS.chop class Dog def bark if @breed == 'beagle' 'woof woof woof woof woof' else 'woof woof' end end end EOS assert_includes output, expected end test 'include directive skips lines all tagged lines when value of tags attribute is negated wildcard' do input = <<~'EOS' ---- include::fixtures/tagged-class.rb[tags=!*] ---- EOS output = convert_string_to_embedded input, safe: :safe, base_dir: DIRNAME expected = %(class Dog\nend) assert_includes output, expected end test 'include directive selects specified tagged lines and ignores the other tag directives' do input = <<~'EOS' [indent=0] ---- include::fixtures/tagged-class.rb[tags=bark;!bark-other] ---- EOS output = convert_string_to_embedded input, safe: :safe, base_dir: DIRNAME # NOTE cannot use single-quoted heredoc because of https://github.com/jruby/jruby/issues/4260 expected = <<~EOS.chop def bark if @breed == 'beagle' 'woof woof woof woof woof' end end EOS assert_includes output, expected end test 'should warn if specified tag is not found in include file' do input = 'include::fixtures/include-file.adoc[tag=no-such-tag]' using_memory_logger do |logger| convert_string_to_embedded input, safe: :safe, base_dir: DIRNAME assert_message logger, :WARN, %(~<stdin>: line 1: tag 'no-such-tag' not found in include file), Hash end end test 'should warn if specified tags are not found in include file' do input = <<~'EOS' ++++ include::fixtures/include-file.adoc[tags=no-such-tag-b;no-such-tag-a] ++++ EOS using_memory_logger do |logger| convert_string_to_embedded input, safe: :safe, base_dir: DIRNAME expected_tags = 'no-such-tag-b, no-such-tag-a' assert_message logger, :WARN, %(~<stdin>: line 2: tags '#{expected_tags}' not found in include file), Hash end end test 'should warn if specified tag in include file is not closed' do input = <<~'EOS' ++++ include::fixtures/unclosed-tag.adoc[tag=a] ++++ EOS using_memory_logger do |logger| result = convert_string_to_embedded input, safe: :safe, base_dir: DIRNAME assert_equal 'a', result assert_message logger, :WARN, %(~<stdin>: line 2: detected unclosed tag 'a' starting at line 2 of include file), Hash refute_nil logger.messages[0][:message][:include_location] end end test 'should warn if end tag in included file is mismatched' do input = <<~'EOS' ++++ include::fixtures/mismatched-end-tag.adoc[tags=a;b] ++++ EOS inc_path = File.join DIRNAME, 'fixtures/mismatched-end-tag.adoc' using_memory_logger do |logger| result = convert_string_to_embedded input, safe: :safe, base_dir: DIRNAME assert_equal %(a\nb), result assert_message logger, :WARN, %(<stdin>: line 2: mismatched end tag (expected 'b' but found 'a') at line 5 of include file: #{inc_path}), Hash refute_nil logger.messages[0][:message][:include_location] end end test 'should warn if unexpected end tag is found in included file' do input = <<~'EOS' ++++ include::fixtures/unexpected-end-tag.adoc[tags=a] ++++ EOS inc_path = File.join DIRNAME, 'fixtures/unexpected-end-tag.adoc' using_memory_logger do |logger| result = convert_string_to_embedded input, safe: :safe, base_dir: DIRNAME assert_equal 'a', result assert_message logger, :WARN, %(<stdin>: line 2: unexpected end tag 'a' at line 4 of include file: #{inc_path}), Hash refute_nil logger.messages[0][:message][:include_location] end end test 'include directive ignores tags attribute when empty' do ['tag', 'tags'].each do |attr_name| input = <<~EOS ++++ include::fixtures/include-file.xml[#{attr_name}=] ++++ EOS output = convert_string_to_embedded input, safe: :safe, base_dir: DIRNAME assert_match(/(?:tag|end)::/, output, 2) end end test 'lines attribute takes precedence over tags attribute in include directive' do input = 'include::fixtures/include-file.adoc[lines=1, tags=snippetA;snippetB]' output = convert_string_to_embedded input, safe: :safe, base_dir: DIRNAME assert_match(/first line of included content/, output) refute_match(/snippetA content/, output) refute_match(/snippetB content/, output) end test 'indent of included file can be reset to size of indent attribute' do input = <<~'EOS' [source, xml] ---- include::fixtures/basic-docinfo.xml[lines=2..3, indent=0] ---- EOS output = convert_string_to_embedded input, safe: :safe, base_dir: DIRNAME result = xmlnodes_at_xpath('//pre', output, 1).text assert_equal "<year>2013</year>\n<holder>Acme™, Inc.</holder>", result end test 'should substitute attribute references in attrlist' do input = <<~'EOS' :name-of-tag: snippetA include::fixtures/include-file.adoc[tag={name-of-tag}] EOS output = convert_string_to_embedded input, safe: :safe, base_dir: DIRNAME assert_match(/snippetA content/, output) refute_match(/snippetB content/, output) refute_match(/non-tagged content/, output) refute_match(/included content/, output) end test 'should fall back to built-in include directive behavior when not handled by include processor' do input = 'include::fixtures/include-file.adoc[]' include_processor = Class.new do def initialize document end def handles? target false end def process reader, target, attributes raise 'TestIncludeHandler should not have been invoked' end end document = empty_safe_document base_dir: DIRNAME reader = Asciidoctor::PreprocessorReader.new document, input, nil, normalize: true reader.instance_variable_set '@include_processors', [include_processor.new(document)] lines = reader.read_lines source = lines * ::Asciidoctor::LF assert_match(/included content/, source) end test 'leveloffset attribute entries should be added to content if leveloffset attribute is specified' do input = 'include::fixtures/master.adoc[]' expected = <<~'EOS'.split ::Asciidoctor::LF = Master Document preamble :leveloffset: +1 = Chapter A content :leveloffset!: EOS document = Asciidoctor.load input, safe: :safe, base_dir: DIRNAME, parse: false assert_equal expected, document.reader.read_lines end test 'attributes are substituted in target of include directive' do input = <<~'EOS' :fixturesdir: fixtures :ext: adoc include::{fixturesdir}/include-file.{ext}[] EOS doc = document_from_string input, safe: :safe, base_dir: DIRNAME output = doc.convert assert_match(/included content/, output) end test 'line is skipped by default if target of include directive resolves to empty' do input = 'include::{blank}[]' using_memory_logger do |logger| doc = empty_safe_document base_dir: DIRNAME reader = Asciidoctor::PreprocessorReader.new doc, input, nil, normalize: true line = reader.read_line assert_equal 'Unresolved directive in <stdin> - include::{blank}[]', line assert_message logger, :WARN, '<stdin>: line 1: include dropped because resolved target is blank: include::{blank}[]', Hash end end test 'include is dropped if target contains missing attribute and attribute-missing is drop-line' do input = 'include::{foodir}/include-file.adoc[]' using_memory_logger Logger::INFO do |logger| doc = empty_safe_document base_dir: DIRNAME, attributes: { 'attribute-missing' => 'drop-line' } reader = Asciidoctor::PreprocessorReader.new doc, input, nil, normalize: true line = reader.read_line assert_nil line assert_messages logger, [ [:INFO, 'dropping line containing reference to missing attribute: foodir'], [:INFO, '<stdin>: line 1: include dropped due to missing attribute: include::{foodir}/include-file.adoc[]', Hash], ] end end test 'line following dropped include is not dropped' do input = <<~'EOS' include::{foodir}/include-file.adoc[] yo EOS using_memory_logger do |logger| doc = empty_safe_document base_dir: DIRNAME, attributes: { 'attribute-missing' => 'warn' } reader = Asciidoctor::PreprocessorReader.new doc, input, nil, normalize: true line = reader.read_line assert_equal 'Unresolved directive in <stdin> - include::{foodir}/include-file.adoc[]', line line = reader.read_line assert_equal 'yo', line assert_messages logger, [ [:INFO, 'dropping line containing reference to missing attribute: foodir'], [:WARN, '<stdin>: line 1: include dropped due to missing attribute: include::{foodir}/include-file.adoc[]', Hash], ] end end test 'escaped include directive is left unprocessed' do input = <<~'EOS' \include::fixtures/include-file.adoc[] \escape preserved here EOS doc = empty_safe_document base_dir: DIRNAME reader = Asciidoctor::PreprocessorReader.new doc, input, nil, normalize: true # we should be able to peek it multiple times and still have the backslash preserved # this is the test for @unescape_next_line assert_equal 'include::fixtures/include-file.adoc[]', reader.peek_line assert_equal 'include::fixtures/include-file.adoc[]', reader.peek_line assert_equal 'include::fixtures/include-file.adoc[]', reader.read_line assert_equal '\\escape preserved here', reader.read_line end test 'include directive not at start of line is ignored' do input = ' include::include-file.adoc[]' para = block_from_string input assert_equal 1, para.lines.size # NOTE the space gets stripped because the line is treated as an inline literal assert_equal :literal, para.context assert_equal 'include::include-file.adoc[]', para.source end test 'include directive is disabled when max-include-depth attribute is 0' do input = 'include::include-file.adoc[]' para = block_from_string input, safe: :safe, attributes: { 'max-include-depth' => 0 } assert_equal 1, para.lines.size assert_equal 'include::include-file.adoc[]', para.source end test 'max-include-depth cannot be set by document' do input = <<~'EOS' :max-include-depth: 1 include::include-file.adoc[] EOS para = block_from_string input, safe: :safe, attributes: { 'max-include-depth' => 0 } assert_equal 1, para.lines.size assert_equal 'include::include-file.adoc[]', para.source end test 'include directive should be disabled if max include depth has been exceeded' do input = 'include::fixtures/parent-include.adoc[depth=1]' using_memory_logger do |logger| pseudo_docfile = File.join DIRNAME, 'include-master.adoc' doc = empty_safe_document base_dir: DIRNAME reader = Asciidoctor::PreprocessorReader.new doc, input, Asciidoctor::Reader::Cursor.new(pseudo_docfile), normalize: true lines = reader.readlines assert_includes lines, 'include::grandchild-include.adoc[]' assert_message logger, :ERROR, 'fixtures/child-include.adoc: line 3: maximum include depth of 1 exceeded', Hash end end test 'include directive should be disabled if max include depth set in nested context has been exceeded' do input = 'include::fixtures/parent-include-restricted.adoc[depth=3]' using_memory_logger do |logger| pseudo_docfile = File.join DIRNAME, 'include-master.adoc' doc = empty_safe_document base_dir: DIRNAME reader = Asciidoctor::PreprocessorReader.new doc, input, Asciidoctor::Reader::Cursor.new(pseudo_docfile), normalize: true lines = reader.readlines assert_includes lines, 'first line of child' assert_includes lines, 'include::grandchild-include.adoc[]' assert_message logger, :ERROR, 'fixtures/child-include.adoc: line 3: maximum include depth of 0 exceeded', Hash end end test 'read_lines_until should not process lines if process option is false' do lines = <<~'EOS'.lines //// include::fixtures/no-such-file.adoc[] //// EOS doc = empty_safe_document base_dir: DIRNAME reader = Asciidoctor::PreprocessorReader.new doc, lines, nil, normalize: true reader.read_line result = reader.read_lines_until(terminator: '////', skip_processing: true) assert_equal lines.map(&:chomp)[1..1], result end test 'skip_comment_lines should not process lines read' do lines = <<~'EOS'.lines //// include::fixtures/no-such-file.adoc[] //// EOS using_memory_logger do |logger| doc = empty_safe_document base_dir: DIRNAME reader = Asciidoctor::PreprocessorReader.new doc, lines, nil, normalize: true reader.skip_comment_lines assert reader.empty? assert logger.empty? end end end context 'Conditional Inclusions' do test 'process_line returns nil if cursor advanced' do input = <<~'EOS' ifdef::asciidoctor[] Asciidoctor! endif::asciidoctor[] EOS doc = Asciidoctor::Document.new input reader = doc.reader assert_nil reader.send :process_line, reader.lines.first end test 'peek_line advances cursor to next conditional line of content' do input = <<~'EOS' ifdef::asciidoctor[] Asciidoctor! endif::asciidoctor[] EOS doc = Asciidoctor::Document.new input reader = doc.reader assert_equal 1, reader.lineno assert_equal 'Asciidoctor!', reader.peek_line assert_equal 2, reader.lineno end test 'peek_lines should preprocess lines if direct is false' do input = <<~'EOS' The Asciidoctor ifdef::asciidoctor[is in.] EOS doc = Asciidoctor::Document.new input reader = doc.reader result = reader.peek_lines 2, false assert_equal ['The Asciidoctor', 'is in.'], result end test 'peek_lines should not preprocess lines if direct is true' do input = <<~'EOS' The Asciidoctor ifdef::asciidoctor[is in.] EOS doc = Asciidoctor::Document.new input reader = doc.reader result = reader.peek_lines 2, true assert_equal ['The Asciidoctor', 'ifdef::asciidoctor[is in.]'], result end test 'peek_lines should not prevent subsequent preprocessing of peeked lines' do input = <<~'EOS' The Asciidoctor ifdef::asciidoctor[is in.] EOS doc = Asciidoctor::Document.new input reader = doc.reader result = reader.peek_lines 2, true result = reader.peek_lines 2, false assert_equal ['The Asciidoctor', 'is in.'], result end test 'process_line returns line if cursor not advanced' do input = <<~'EOS' content ifdef::asciidoctor[] Asciidoctor! endif::asciidoctor[] EOS doc = Asciidoctor::Document.new input reader = doc.reader refute_nil reader.send :process_line, reader.lines.first end test 'peek_line does not advance cursor when on a regular content line' do input = <<~'EOS' content ifdef::asciidoctor[] Asciidoctor! endif::asciidoctor[] EOS doc = Asciidoctor::Document.new input reader = doc.reader assert_equal 1, reader.lineno assert_equal 'content', reader.peek_line assert_equal 1, reader.lineno end test 'peek_line returns nil if cursor advances past end of source' do input = <<~'EOS' ifdef::foobar[] swallowed content endif::foobar[] EOS doc = Asciidoctor::Document.new input reader = doc.reader assert_equal 1, reader.lineno assert_nil reader.peek_line assert_equal 4, reader.lineno end test 'ifdef with defined attribute includes content' do input = <<~'EOS' ifdef::holygrail[] There is a holy grail! endif::holygrail[] EOS doc = Asciidoctor::Document.new input, attributes: { 'holygrail' => '' } reader = doc.reader lines = [] while reader.has_more_lines? lines << reader.read_line end assert_equal 'There is a holy grail!', (lines * ::Asciidoctor::LF) end test 'ifdef with defined attribute includes text in brackets' do input = <<~'EOS' On our quest we go... ifdef::holygrail[There is a holy grail!] There was much rejoicing. EOS doc = Asciidoctor::Document.new input, attributes: { 'holygrail' => '' } reader = doc.reader lines = [] while reader.has_more_lines? lines << reader.read_line end assert_equal "On our quest we go...\nThere is a holy grail!\nThere was much rejoicing.", (lines * ::Asciidoctor::LF) end test 'ifdef with defined attribute processes include directive in brackets' do input = 'ifdef::asciidoctor-version[include::fixtures/include-file.adoc[tag=snippetA]]' doc = Asciidoctor::Document.new input, safe: :safe, base_dir: DIRNAME reader = doc.reader lines = [] while reader.has_more_lines? lines << reader.read_line end assert_equal 'snippetA content', lines[0] end test 'ifdef attribute name is not case sensitive' do input = <<~'EOS' ifdef::showScript[] The script is shown! endif::showScript[] EOS doc = Asciidoctor::Document.new input, attributes: { 'showscript' => '' } result = doc.reader.read assert_equal 'The script is shown!', result end test 'ifndef with defined attribute does not include text in brackets' do input = <<~'EOS' On our quest we go... ifndef::hardships[There is a holy grail!] There was no rejoicing. EOS doc = Asciidoctor::Document.new input, attributes: { 'hardships' => '' } reader = doc.reader lines = [] while reader.has_more_lines? lines << reader.read_line end assert_equal "On our quest we go...\nThere was no rejoicing.", (lines * ::Asciidoctor::LF) end test 'include with non-matching nested exclude' do input = <<~'EOS' ifdef::grail[] holy ifdef::swallow[] swallow endif::swallow[] grail endif::grail[] EOS doc = Asciidoctor::Document.new input, attributes: { 'grail' => '' } reader = doc.reader lines = [] while reader.has_more_lines? lines << reader.read_line end assert_equal "holy\ngrail", (lines * ::Asciidoctor::LF) end test 'nested excludes with same condition' do input = <<~'EOS' ifndef::grail[] ifndef::grail[] not here endif::grail[] endif::grail[] EOS doc = Asciidoctor::Document.new input, attributes: { 'grail' => '' } reader = doc.reader lines = [] while reader.has_more_lines? lines << reader.read_line end assert_equal '', (lines * ::Asciidoctor::LF) end test 'include with nested exclude of inverted condition' do input = <<~'EOS' ifdef::grail[] holy ifndef::grail[] not here endif::grail[] grail endif::grail[] EOS doc = Asciidoctor::Document.new input, attributes: { 'grail' => '' } reader = doc.reader lines = [] while reader.has_more_lines? lines << reader.read_line end assert_equal "holy\ngrail", (lines * ::Asciidoctor::LF) end test 'exclude with matching nested exclude' do input = <<~'EOS' poof ifdef::swallow[] no ifdef::swallow[] swallow endif::swallow[] here endif::swallow[] gone EOS doc = Asciidoctor::Document.new input, attributes: { 'grail' => '' } reader = doc.reader lines = [] while reader.has_more_lines? lines << reader.read_line end assert_equal "poof\ngone", (lines * ::Asciidoctor::LF) end test 'exclude with nested include using shorthand end' do input = <<~'EOS' poof ifndef::grail[] no grail ifndef::swallow[] or swallow endif::[] in here endif::[] gone EOS doc = Asciidoctor::Document.new input, attributes: { 'grail' => '' } reader = doc.reader lines = [] while reader.has_more_lines? lines << reader.read_line end assert_equal "poof\ngone", (lines * ::Asciidoctor::LF) end test 'ifdef with one alternative attribute set includes content' do input = <<~'EOS' ifdef::holygrail,swallow[] Our quest is complete! endif::holygrail,swallow[] EOS doc = Asciidoctor::Document.new input, attributes: { 'swallow' => '' } reader = doc.reader lines = [] while reader.has_more_lines? lines << reader.read_line end assert_equal 'Our quest is complete!', (lines * ::Asciidoctor::LF) end test 'ifdef with no alternative attributes set does not include content' do input = <<~'EOS' ifdef::holygrail,swallow[] Our quest is complete! endif::holygrail,swallow[] EOS doc = Asciidoctor::Document.new input reader = doc.reader lines = [] while reader.has_more_lines? lines << reader.read_line end assert_equal '', (lines * ::Asciidoctor::LF) end test 'ifdef with all required attributes set includes content' do input = <<~'EOS' ifdef::holygrail+swallow[] Our quest is complete! endif::holygrail+swallow[] EOS doc = Asciidoctor::Document.new input, attributes: { 'holygrail' => '', 'swallow' => '' } reader = doc.reader lines = [] while reader.has_more_lines? lines << reader.read_line end assert_equal 'Our quest is complete!', (lines * ::Asciidoctor::LF) end test 'ifdef with missing required attributes does not include content' do input = <<~'EOS' ifdef::holygrail+swallow[] Our quest is complete! endif::holygrail+swallow[] EOS doc = Asciidoctor::Document.new input, attributes: { 'holygrail' => '' } reader = doc.reader lines = [] while reader.has_more_lines? lines << reader.read_line end assert_equal '', (lines * ::Asciidoctor::LF) end test 'ifdef should permit leading, trailing, and repeat operators' do { 'asciidoctor,' => 'content', ',asciidoctor' => 'content', 'asciidoctor+' => '', '+asciidoctor' => '', 'asciidoctor,,asciidoctor-version' => 'content', 'asciidoctor++asciidoctor-version' => '', }.each do |condition, expected| input = <<~EOS ifdef::#{condition}[] content endif::[] EOS assert_equal expected, (document_from_string input, parse: false).reader.read end end test 'ifndef with undefined attribute includes block' do input = <<~'EOS' ifndef::holygrail[] Our quest continues to find the holy grail! endif::holygrail[] EOS doc = Asciidoctor::Document.new input reader = doc.reader lines = [] while reader.has_more_lines? lines << reader.read_line end assert_equal 'Our quest continues to find the holy grail!', (lines * ::Asciidoctor::LF) end test 'ifndef with one alternative attribute set does not include content' do input = <<~'EOS' ifndef::holygrail,swallow[] Our quest is complete! endif::holygrail,swallow[] EOS result = (Asciidoctor::Document.new input, attributes: { 'swallow' => '' }).reader.read assert_empty result end test 'ifndef with both alternative attributes set does not include content' do input = <<~'EOS' ifndef::holygrail,swallow[] Our quest is complete! endif::holygrail,swallow[] EOS result = (Asciidoctor::Document.new input, attributes: { 'swallow' => '', 'holygrail' => '' }).reader.read assert_empty result end test 'ifndef with no alternative attributes set includes content' do input = <<~'EOS' ifndef::holygrail,swallow[] Our quest is complete! endif::holygrail,swallow[] EOS result = (Asciidoctor::Document.new input).reader.read assert_equal 'Our quest is complete!', result end test 'ifndef with no required attributes set includes content' do input = <<~'EOS' ifndef::holygrail+swallow[] Our quest is complete! endif::holygrail+swallow[] EOS result = (Asciidoctor::Document.new input).reader.read assert_equal 'Our quest is complete!', result end test 'ifndef with all required attributes set does not include content' do input = <<~'EOS' ifndef::holygrail+swallow[] Our quest is complete! endif::holygrail+swallow[] EOS result = (Asciidoctor::Document.new input, attributes: { 'swallow' => '', 'holygrail' => '' }).reader.read assert_empty result end test 'ifndef with at least one required attributes set does not include content' do input = <<~'EOS' ifndef::holygrail+swallow[] Our quest is complete! endif::holygrail+swallow[] EOS result = (Asciidoctor::Document.new input, attributes: { 'swallow' => '' }).reader.read assert_equal 'Our quest is complete!', result end test 'should log warning if endif is unmatched' do input = <<~'EOS' Our quest is complete! endif::on-quest[] EOS using_memory_logger do |logger| result = (Asciidoctor::Document.new input, attributes: { 'on-quest' => '' }).reader.read assert_equal 'Our quest is complete!', result assert_message logger, :ERROR, '~<stdin>: line 2: unmatched preprocessor directive: endif::on-quest[]', Hash end end test 'should log warning if endif is mismatched' do input = <<~'EOS' ifdef::on-quest[] Our quest is complete! endif::on-journey[] EOS using_memory_logger do |logger| result = (Asciidoctor::Document.new input, attributes: { 'on-quest' => '' }).reader.read assert_equal 'Our quest is complete!', result assert_message logger, :ERROR, '~<stdin>: line 3: mismatched preprocessor directive: endif::on-journey[]', Hash end end test 'should log warning if endif contains text' do input = <<~'EOS' ifdef::on-quest[] Our quest is complete! endif::on-quest[complete!] EOS using_memory_logger do |logger| result = (Asciidoctor::Document.new input, attributes: { 'on-quest' => '' }).reader.read assert_equal 'Our quest is complete!', result assert_message logger, :ERROR, '~<stdin>: line 3: malformed preprocessor directive - text not permitted: endif::on-quest[complete!]', Hash end end test 'escaped ifdef is unescaped and ignored' do input = <<~'EOS' \ifdef::holygrail[] content \endif::holygrail[] EOS doc = Asciidoctor::Document.new input reader = doc.reader lines = [] while reader.has_more_lines? lines << reader.read_line end assert_equal "ifdef::holygrail[]\ncontent\nendif::holygrail[]", (lines * ::Asciidoctor::LF) end test 'ifeval comparing missing attribute to nil includes content' do input = <<~'EOS' ifeval::['{foo}' == ''] No foo for you! endif::[] EOS doc = Asciidoctor::Document.new input reader = doc.reader lines = [] while reader.has_more_lines? lines << reader.read_line end assert_equal 'No foo for you!', (lines * ::Asciidoctor::LF) end test 'ifeval comparing missing attribute to 0 drops content' do input = <<~'EOS' ifeval::[{leveloffset} == 0] I didn't make the cut! endif::[] EOS doc = Asciidoctor::Document.new input reader = doc.reader lines = [] while reader.has_more_lines? lines << reader.read_line end assert_equal '', (lines * ::Asciidoctor::LF) end test 'ifeval comparing double-quoted attribute to matching string includes content' do input = <<~'EOS' ifeval::["{gem}" == "asciidoctor"] Asciidoctor it is! endif::[] EOS doc = Asciidoctor::Document.new input, attributes: { 'gem' => 'asciidoctor' } reader = doc.reader lines = [] while reader.has_more_lines? lines << reader.read_line end assert_equal 'Asciidoctor it is!', (lines * ::Asciidoctor::LF) end test 'ifeval comparing single-quoted attribute to matching string includes content' do input = <<~'EOS' ifeval::['{gem}' == 'asciidoctor'] Asciidoctor it is! endif::[] EOS doc = Asciidoctor::Document.new input, attributes: { 'gem' => 'asciidoctor' } reader = doc.reader lines = [] while reader.has_more_lines? lines << reader.read_line end assert_equal 'Asciidoctor it is!', (lines * ::Asciidoctor::LF) end test 'ifeval comparing quoted attribute to non-matching string drops content' do input = <<~'EOS' ifeval::['{gem}' == 'asciidoctor'] Asciidoctor it is! endif::[] EOS doc = Asciidoctor::Document.new input, attributes: { 'gem' => 'tilt' } reader = doc.reader lines = [] while reader.has_more_lines? lines << reader.read_line end assert_equal '', (lines * ::Asciidoctor::LF) end test 'ifeval comparing attribute to lower version number includes content' do input = <<~'EOS' ifeval::['{asciidoctor-version}' >= '0.1.0'] That version will do! endif::[] EOS doc = Asciidoctor::Document.new input reader = doc.reader lines = [] while reader.has_more_lines? lines << reader.read_line end assert_equal 'That version will do!', (lines * ::Asciidoctor::LF) end test 'ifeval comparing attribute to self includes content' do input = <<~'EOS' ifeval::['{asciidoctor-version}' == '{asciidoctor-version}'] Of course it's the same! endif::[] EOS doc = Asciidoctor::Document.new input reader = doc.reader lines = [] while reader.has_more_lines? lines << reader.read_line end assert_equal 'Of course it\'s the same!', (lines * ::Asciidoctor::LF) end test 'ifeval arguments can be transposed' do input = <<~'EOS' ifeval::['0.1.0' <= '{asciidoctor-version}'] That version will do! endif::[] EOS doc = Asciidoctor::Document.new input reader = doc.reader lines = [] while reader.has_more_lines? lines << reader.read_line end assert_equal 'That version will do!', (lines * ::Asciidoctor::LF) end test 'ifeval matching numeric equality includes content' do input = <<~'EOS' ifeval::[{rings} == 1] One ring to rule them all! endif::[] EOS doc = Asciidoctor::Document.new input, attributes: { 'rings' => '1' } reader = doc.reader lines = [] while reader.has_more_lines? lines << reader.read_line end assert_equal 'One ring to rule them all!', (lines * ::Asciidoctor::LF) end test 'ifeval matching numeric inequality includes content' do input = <<~'EOS' ifeval::[{rings} != 0] One ring to rule them all! endif::[] EOS doc = Asciidoctor::Document.new input, attributes: { 'rings' => '1' } reader = doc.reader lines = [] while reader.has_more_lines? lines << reader.read_line end assert_equal 'One ring to rule them all!', (lines * ::Asciidoctor::LF) end test 'should warn if ifeval has target' do input = <<~'EOS' ifeval::target[1 == 1] content EOS using_memory_logger do |logger| doc = Asciidoctor::Document.new input reader = doc.reader lines = [] lines << reader.read_line while reader.has_more_lines? assert_equal 'content', (lines * ::Asciidoctor::LF) assert_message logger, :ERROR, '~<stdin>: line 1: malformed preprocessor directive - target not permitted: ifeval::target[1 == 1]', Hash end end test 'should warn if ifeval has invalid expression' do input = <<~'EOS' ifeval::[1 | 2] content EOS using_memory_logger do |logger| doc = Asciidoctor::Document.new input reader = doc.reader lines = [] lines << reader.read_line while reader.has_more_lines? assert_equal 'content', (lines * ::Asciidoctor::LF) assert_message logger, :ERROR, '~<stdin>: line 1: malformed preprocessor directive - invalid expression: ifeval::[1 | 2]', Hash end end test 'should warn if ifeval is missing expression' do input = <<~'EOS' ifeval::[] content EOS using_memory_logger do |logger| doc = Asciidoctor::Document.new input reader = doc.reader lines = [] lines << reader.read_line while reader.has_more_lines? assert_equal 'content', (lines * ::Asciidoctor::LF) assert_message logger, :ERROR, '~<stdin>: line 1: malformed preprocessor directive - missing expression: ifeval::[]', Hash end end test 'ifdef with no target is ignored' do input = <<~'EOS' ifdef::[] content EOS using_memory_logger do |logger| doc = Asciidoctor::Document.new input reader = doc.reader lines = [] lines << reader.read_line while reader.has_more_lines? assert_equal 'content', (lines * ::Asciidoctor::LF) assert_message logger, :ERROR, '~<stdin>: line 1: malformed preprocessor directive - missing target: ifdef::[]', Hash end end test 'should not warn if preprocessor directive is invalid if already skipping' do input = <<~'EOS' ifdef::attribute-not-set[] foo ifdef::[] bar endif::[] EOS using_memory_logger do |logger| result = (Asciidoctor::Document.new input).reader.read assert_empty result assert_empty logger end end end end end
1
6,840
Is there a reason why you're not using Rspec `skip`? It allows to specify message and makes it clearly visible in test results which tests were skipped.
asciidoctor-asciidoctor
rb
@@ -36,6 +36,10 @@ type ClusterSyncStatus struct { // Conditions is a list of conditions associated with syncing to the cluster. // +optional Conditions []ClusterSyncCondition `json:"conditions,omitempty"` + + // FirstSyncSetsSuccessTime is the time we first successfully applied all (selector)syncsets to a cluster. + // +optional + FirstSyncSetsSuccessTime *metav1.Time `json:"firstSyncSetsSuccessTime,omitempty"` } // SyncStatus is the status of applying a specific SyncSet or SelectorSyncSet to the cluster.
1
package v1alpha1 import ( corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) // +genclient // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // ClusterSync is the status of all of the SelectorSyncSets and SyncSets that apply to a ClusterDeployment. // +k8s:openapi-gen=true // +kubebuilder:subresource:status // +kubebuilder:resource:path=clustersyncs,shortName=csync,scope=Namespaced type ClusterSync struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` Spec ClusterSyncSpec `json:"spec,omitempty"` Status ClusterSyncStatus `json:"status,omitempty"` } // ClusterSyncSpec defines the desired state of ClusterSync type ClusterSyncSpec struct{} // ClusterSyncStatus defines the observed state of ClusterSync type ClusterSyncStatus struct { // SyncSets is the sync status of all of the SyncSets for the cluster. // +optional SyncSets []SyncStatus `json:"syncSets,omitempty"` // SelectorSyncSets is the sync status of all of the SelectorSyncSets for the cluster. // +optional SelectorSyncSets []SyncStatus `json:"selectorSyncSets,omitempty"` // Conditions is a list of conditions associated with syncing to the cluster. // +optional Conditions []ClusterSyncCondition `json:"conditions,omitempty"` } // SyncStatus is the status of applying a specific SyncSet or SelectorSyncSet to the cluster. type SyncStatus struct { // Name is the name of the SyncSet or SelectorSyncSet. Name string `json:"name"` // ObservedGeneration is the generation of the SyncSet or SelectorSyncSet that was last observed. ObservedGeneration int64 `json:"observedGeneration"` // ResourcesToDelete is the list of resources in the cluster that should be deleted when the SyncSet or SelectorSyncSet // is deleted or is no longer matched to the cluster. // +optional ResourcesToDelete []SyncResourceReference `json:"resourcesToDelete,omitempty"` // Result is the result of the last attempt to apply the SyncSet or SelectorSyncSet to the cluster. Result SyncSetResult `json:"result"` // FailureMessage is a message describing why the SyncSet or SelectorSyncSet could not be applied. This is only // set when Result is Failure. // +optional FailureMessage string `json:"failureMessage,omitempty"` // LastTransitionTime is the time when this status last changed. LastTransitionTime metav1.Time `json:"lastTransitionTime"` // FirstSuccessTime is the time when the SyncSet or SelectorSyncSet was first successfully applied to the cluster. // +optional FirstSuccessTime *metav1.Time `json:"firstSuccessTime,omitempty"` } // SyncResourceReference is a reference to a resource that is synced to a cluster via a SyncSet or SelectorSyncSet. type SyncResourceReference struct { // APIVersion is the Group and Version of the resource. APIVersion string `json:"apiVersion"` // Kind is the Kind of the resource. // +optional Kind string `json:"kind"` // Name is the name of the resource. Name string `json:"name"` // Namespace is the namespace of the resource. // +optional Namespace string `json:"namespace,omitempty"` } // SyncSetResult is the result of a sync attempt. // +kubebuilder:validation:Enum=Success;Failure type SyncSetResult string const ( // SuccessSyncSetResult is the result when the SyncSet or SelectorSyncSet was applied successfully to the cluster. SuccessSyncSetResult SyncSetResult = "Success" // FailureSyncSetResult is the result when there was an error when attempting to apply the SyncSet or SelectorSyncSet // to the cluster FailureSyncSetResult SyncSetResult = "Failure" ) // ClusterSyncCondition contains details for the current condition of a ClusterSync type ClusterSyncCondition struct { // Type is the type of the condition. Type ClusterSyncConditionType `json:"type"` // Status is the status of the condition. Status corev1.ConditionStatus `json:"status"` // LastProbeTime is the last time we probed the condition. // +optional LastProbeTime metav1.Time `json:"lastProbeTime,omitempty"` // LastTransitionTime is the last time the condition transitioned from one status to another. // +optional LastTransitionTime metav1.Time `json:"lastTransitionTime,omitempty"` // Reason is a unique, one-word, CamelCase reason for the condition's last transition. // +optional Reason string `json:"reason,omitempty"` // Message is a human-readable message indicating details about the last transition. // +optional Message string `json:"message,omitempty"` } // ClusterSyncConditionType is a valid value for ClusterSyncCondition.Type type ClusterSyncConditionType string const ( // ClusterSyncFailed is the type of condition used to indicate whether there are SyncSets or SelectorSyncSets which // have not been applied due to an error. ClusterSyncFailed ClusterSyncConditionType = "Failed" ) // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // ClusterSyncList contains a list of ClusterSync type ClusterSyncList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata,omitempty"` Items []ClusterSync `json:"items"` } func init() { SchemeBuilder.Register(&ClusterSync{}, &ClusterSyncList{}) }
1
14,635
how about "all matching SyncSets and SelectorSyncSets"
openshift-hive
go
@@ -331,7 +331,7 @@ void Storage::PopulateLayout(DataLayout &layout) // load geometries sizes { - io::FileReader reader(config.geometries_path, io::FileReader::HasNoFingerprint); + io::FileReader reader(config.geometries_path, io::FileReader::VerifyFingerprint); const auto number_of_geometries_indices = reader.ReadVectorSize<unsigned>(); layout.SetBlockSize<unsigned>(DataLayout::GEOMETRIES_INDEX, number_of_geometries_indices);
1
#include "storage/storage.hpp" #include "storage/io.hpp" #include "storage/shared_datatype.hpp" #include "storage/shared_memory.hpp" #include "storage/shared_memory_ownership.hpp" #include "storage/shared_monitor.hpp" #include "contractor/files.hpp" #include "contractor/query_graph.hpp" #include "customizer/edge_based_graph.hpp" #include "extractor/compressed_edge_container.hpp" #include "extractor/edge_based_edge.hpp" #include "extractor/files.hpp" #include "extractor/guidance/turn_instruction.hpp" #include "extractor/original_edge_data.hpp" #include "extractor/profile_properties.hpp" #include "extractor/query_node.hpp" #include "extractor/travel_mode.hpp" #include "partition/cell_storage.hpp" #include "partition/edge_based_graph_reader.hpp" #include "partition/files.hpp" #include "partition/multi_level_partition.hpp" #include "engine/datafacade/datafacade_base.hpp" #include "util/coordinate.hpp" #include "util/exception.hpp" #include "util/exception_utils.hpp" #include "util/fingerprint.hpp" #include "util/log.hpp" #include "util/packed_vector.hpp" #include "util/range_table.hpp" #include "util/static_graph.hpp" #include "util/static_rtree.hpp" #include "util/typedefs.hpp" #include "util/vector_view.hpp" #ifdef __linux__ #include <sys/mman.h> #endif #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/filesystem/path.hpp> #include <boost/interprocess/sync/file_lock.hpp> #include <boost/interprocess/sync/scoped_lock.hpp> #include <cstdint> #include <fstream> #include <iostream> #include <iterator> #include <new> #include <string> namespace osrm { namespace storage { using RTreeLeaf = engine::datafacade::BaseDataFacade::RTreeLeaf; using RTreeNode = util::StaticRTree<RTreeLeaf, storage::Ownership::View>::TreeNode; using QueryGraph = util::StaticGraph<contractor::QueryEdge::EdgeData>; using EdgeBasedGraph = util::StaticGraph<extractor::EdgeBasedEdge::EdgeData>; using Monitor = SharedMonitor<SharedDataTimestamp>; Storage::Storage(StorageConfig config_) : config(std::move(config_)) {} int Storage::Run(int max_wait) { BOOST_ASSERT_MSG(config.IsValid(), "Invalid storage config"); util::LogPolicy::GetInstance().Unmute(); boost::filesystem::path lock_path = boost::filesystem::temp_directory_path() / "osrm-datastore.lock"; if (!boost::filesystem::exists(lock_path)) { boost::filesystem::ofstream ofs(lock_path); } boost::interprocess::file_lock file_lock(lock_path.string().c_str()); boost::interprocess::scoped_lock<boost::interprocess::file_lock> datastore_lock( file_lock, boost::interprocess::defer_lock); if (!datastore_lock.try_lock()) { util::UnbufferedLog(logWARNING) << "Data update in progress, waiting until it finishes... "; datastore_lock.lock(); util::UnbufferedLog(logWARNING) << "ok."; } #ifdef __linux__ // try to disable swapping on Linux const bool lock_flags = MCL_CURRENT | MCL_FUTURE; if (-1 == mlockall(lock_flags)) { util::Log(logWARNING) << "Could not request RAM lock"; } #endif // Get the next region ID and time stamp without locking shared barriers. // Because of datastore_lock the only write operation can occur sequentially later. Monitor monitor(SharedDataTimestamp{REGION_NONE, 0}); auto in_use_region = monitor.data().region; auto next_timestamp = monitor.data().timestamp + 1; auto next_region = in_use_region == REGION_2 || in_use_region == REGION_NONE ? REGION_1 : REGION_2; // ensure that the shared memory region we want to write to is really removed // this is only needef for failure recovery because we actually wait for all clients // to detach at the end of the function if (storage::SharedMemory::RegionExists(next_region)) { util::Log(logWARNING) << "Old shared memory region " << regionToString(next_region) << " still exists."; util::UnbufferedLog() << "Retrying removal... "; storage::SharedMemory::Remove(next_region); util::UnbufferedLog() << "ok."; } util::Log() << "Loading data into " << regionToString(next_region); // Populate a memory layout into stack memory DataLayout layout; PopulateLayout(layout); // Allocate shared memory block auto regions_size = sizeof(layout) + layout.GetSizeOfLayout(); util::Log() << "Allocating shared memory of " << regions_size << " bytes"; auto data_memory = makeSharedMemory(next_region, regions_size); // Copy memory layout to shared memory and populate data char *shared_memory_ptr = static_cast<char *>(data_memory->Ptr()); memcpy(shared_memory_ptr, &layout, sizeof(layout)); PopulateData(layout, shared_memory_ptr + sizeof(layout)); { // Lock for write access shared region mutex boost::interprocess::scoped_lock<Monitor::mutex_type> lock(monitor.get_mutex(), boost::interprocess::defer_lock); if (max_wait >= 0) { if (!lock.timed_lock(boost::posix_time::microsec_clock::universal_time() + boost::posix_time::seconds(max_wait))) { util::Log(logWARNING) << "Could not aquire current region lock after " << max_wait << " seconds. Removing locked block and creating a new one. All currently " "attached processes will not receive notifications and must be restarted"; Monitor::remove(); in_use_region = REGION_NONE; monitor = Monitor(SharedDataTimestamp{REGION_NONE, 0}); } } else { lock.lock(); } // Update the current region ID and timestamp monitor.data().region = next_region; monitor.data().timestamp = next_timestamp; } util::Log() << "All data loaded. Notify all client about new data in " << regionToString(next_region) << " with timestamp " << next_timestamp; monitor.notify_all(); // SHMCTL(2): Mark the segment to be destroyed. The segment will actually be destroyed // only after the last process detaches it. if (in_use_region != REGION_NONE && storage::SharedMemory::RegionExists(in_use_region)) { util::UnbufferedLog() << "Marking old shared memory region " << regionToString(in_use_region) << " for removal... "; // aquire a handle for the old shared memory region before we mark it for deletion // we will need this to wait for all users to detach auto in_use_shared_memory = makeSharedMemory(in_use_region); storage::SharedMemory::Remove(in_use_region); util::UnbufferedLog() << "ok."; util::UnbufferedLog() << "Waiting for clients to detach... "; in_use_shared_memory->WaitForDetach(); util::UnbufferedLog() << " ok."; } util::Log() << "All clients switched."; return EXIT_SUCCESS; } /** * This function examines all our data files and figures out how much * memory needs to be allocated, and the position of each data structure * in that big block. It updates the fields in the DataLayout parameter. */ void Storage::PopulateLayout(DataLayout &layout) { { auto absolute_file_index_path = boost::filesystem::absolute(config.file_index_path); layout.SetBlockSize<char>(DataLayout::FILE_INDEX_PATH, absolute_file_index_path.string().length() + 1); } { util::Log() << "load names from: " << config.names_data_path; // number of entries in name index io::FileReader name_file(config.names_data_path, io::FileReader::HasNoFingerprint); layout.SetBlockSize<char>(DataLayout::NAME_CHAR_DATA, name_file.GetSize()); } { io::FileReader reader(config.turn_lane_description_path, io::FileReader::HasNoFingerprint); auto num_offsets = reader.ReadVectorSize<std::uint32_t>(); auto num_masks = reader.ReadVectorSize<extractor::guidance::TurnLaneType::Mask>(); layout.SetBlockSize<std::uint32_t>(DataLayout::LANE_DESCRIPTION_OFFSETS, num_offsets); layout.SetBlockSize<extractor::guidance::TurnLaneType::Mask>( DataLayout::LANE_DESCRIPTION_MASKS, num_masks); } // Loading information for original edges { io::FileReader edges_file(config.edges_data_path, io::FileReader::HasNoFingerprint); const auto number_of_original_edges = edges_file.ReadElementCount64(); // note: settings this all to the same size is correct, we extract them from the same struct layout.SetBlockSize<NodeID>(DataLayout::VIA_NODE_LIST, number_of_original_edges); layout.SetBlockSize<unsigned>(DataLayout::NAME_ID_LIST, number_of_original_edges); layout.SetBlockSize<extractor::TravelMode>(DataLayout::TRAVEL_MODE, number_of_original_edges); layout.SetBlockSize<util::guidance::TurnBearing>(DataLayout::PRE_TURN_BEARING, number_of_original_edges); layout.SetBlockSize<util::guidance::TurnBearing>(DataLayout::POST_TURN_BEARING, number_of_original_edges); layout.SetBlockSize<extractor::guidance::TurnInstruction>(DataLayout::TURN_INSTRUCTION, number_of_original_edges); layout.SetBlockSize<LaneDataID>(DataLayout::LANE_DATA_ID, number_of_original_edges); layout.SetBlockSize<EntryClassID>(DataLayout::ENTRY_CLASSID, number_of_original_edges); } if (boost::filesystem::exists(config.hsgr_data_path)) { io::FileReader reader(config.hsgr_data_path, io::FileReader::VerifyFingerprint); reader.Skip<std::uint32_t>(1); // checksum auto num_nodes = reader.ReadVectorSize<contractor::QueryGraph::NodeArrayEntry>(); auto num_edges = reader.ReadVectorSize<contractor::QueryGraph::EdgeArrayEntry>(); layout.SetBlockSize<unsigned>(DataLayout::HSGR_CHECKSUM, 1); layout.SetBlockSize<contractor::QueryGraph::NodeArrayEntry>(DataLayout::CH_GRAPH_NODE_LIST, num_nodes); layout.SetBlockSize<contractor::QueryGraph::EdgeArrayEntry>(DataLayout::CH_GRAPH_EDGE_LIST, num_edges); } else { layout.SetBlockSize<unsigned>(DataLayout::HSGR_CHECKSUM, 0); layout.SetBlockSize<contractor::QueryGraph::NodeArrayEntry>(DataLayout::CH_GRAPH_NODE_LIST, 0); layout.SetBlockSize<contractor::QueryGraph::EdgeArrayEntry>(DataLayout::CH_GRAPH_EDGE_LIST, 0); } // load rsearch tree size { io::FileReader tree_node_file(config.ram_index_path, io::FileReader::HasNoFingerprint); const auto tree_size = tree_node_file.ReadElementCount64(); layout.SetBlockSize<RTreeNode>(DataLayout::R_SEARCH_TREE, tree_size); } { layout.SetBlockSize<extractor::ProfileProperties>(DataLayout::PROPERTIES, 1); } // read timestampsize { io::FileReader timestamp_file(config.timestamp_path, io::FileReader::HasNoFingerprint); const auto timestamp_size = timestamp_file.Size(); layout.SetBlockSize<char>(DataLayout::TIMESTAMP, timestamp_size); } // load core marker size if (boost::filesystem::exists(config.core_data_path)) { io::FileReader core_marker_file(config.core_data_path, io::FileReader::HasNoFingerprint); const auto number_of_core_markers = core_marker_file.ReadElementCount32(); layout.SetBlockSize<unsigned>(DataLayout::CH_CORE_MARKER, number_of_core_markers); } else { layout.SetBlockSize<unsigned>(DataLayout::CH_CORE_MARKER, 0); } // load turn weight penalties { io::FileReader turn_weight_penalties_file(config.turn_weight_penalties_path, io::FileReader::HasNoFingerprint); const auto number_of_penalties = turn_weight_penalties_file.ReadElementCount64(); layout.SetBlockSize<TurnPenalty>(DataLayout::TURN_WEIGHT_PENALTIES, number_of_penalties); } // load turn duration penalties { io::FileReader turn_duration_penalties_file(config.turn_duration_penalties_path, io::FileReader::HasNoFingerprint); const auto number_of_penalties = turn_duration_penalties_file.ReadElementCount64(); layout.SetBlockSize<TurnPenalty>(DataLayout::TURN_DURATION_PENALTIES, number_of_penalties); } // load coordinate size { io::FileReader node_file(config.nodes_data_path, io::FileReader::VerifyFingerprint); const auto coordinate_list_size = node_file.ReadElementCount64(); layout.SetBlockSize<util::Coordinate>(DataLayout::COORDINATE_LIST, coordinate_list_size); // we'll read a list of OSM node IDs from the same data, so set the block size for the same // number of items: layout.SetBlockSize<std::uint64_t>( DataLayout::OSM_NODE_ID_LIST, util::PackedVectorView<OSMNodeID>::elements_to_blocks(coordinate_list_size)); } // load geometries sizes { io::FileReader reader(config.geometries_path, io::FileReader::HasNoFingerprint); const auto number_of_geometries_indices = reader.ReadVectorSize<unsigned>(); layout.SetBlockSize<unsigned>(DataLayout::GEOMETRIES_INDEX, number_of_geometries_indices); const auto number_of_compressed_geometries = reader.ReadVectorSize<NodeID>(); layout.SetBlockSize<NodeID>(DataLayout::GEOMETRIES_NODE_LIST, number_of_compressed_geometries); layout.SetBlockSize<EdgeWeight>(DataLayout::GEOMETRIES_FWD_WEIGHT_LIST, number_of_compressed_geometries); layout.SetBlockSize<EdgeWeight>(DataLayout::GEOMETRIES_REV_WEIGHT_LIST, number_of_compressed_geometries); layout.SetBlockSize<EdgeWeight>(DataLayout::GEOMETRIES_FWD_DURATION_LIST, number_of_compressed_geometries); layout.SetBlockSize<EdgeWeight>(DataLayout::GEOMETRIES_REV_DURATION_LIST, number_of_compressed_geometries); layout.SetBlockSize<DatasourceID>(DataLayout::DATASOURCES_LIST, number_of_compressed_geometries); } // Load datasource name sizes. { layout.SetBlockSize<extractor::Datasources>(DataLayout::DATASOURCES_NAMES, 1); } { io::FileReader intersection_file(config.intersection_class_path, io::FileReader::VerifyFingerprint); std::vector<BearingClassID> bearing_class_id_table; serialization::read(intersection_file, bearing_class_id_table); layout.SetBlockSize<BearingClassID>(DataLayout::BEARING_CLASSID, bearing_class_id_table.size()); const auto bearing_blocks = intersection_file.ReadElementCount32(); intersection_file.Skip<std::uint32_t>(1); // sum_lengths layout.SetBlockSize<unsigned>(DataLayout::BEARING_OFFSETS, bearing_blocks); layout.SetBlockSize<typename util::RangeTable<16, storage::Ownership::View>::BlockT>( DataLayout::BEARING_BLOCKS, bearing_blocks); // No need to read the data intersection_file.Skip<unsigned>(bearing_blocks); intersection_file.Skip<typename util::RangeTable<16, storage::Ownership::View>::BlockT>( bearing_blocks); const auto num_bearings = intersection_file.ReadElementCount64(); // Skip over the actual data intersection_file.Skip<DiscreteBearing>(num_bearings); layout.SetBlockSize<DiscreteBearing>(DataLayout::BEARING_VALUES, num_bearings); std::vector<util::guidance::EntryClass> entry_class_table; serialization::read(intersection_file, entry_class_table); layout.SetBlockSize<util::guidance::EntryClass>(DataLayout::ENTRY_CLASS, entry_class_table.size()); } { // Loading turn lane data io::FileReader lane_data_file(config.turn_lane_data_path, io::FileReader::HasNoFingerprint); const auto lane_tuple_count = lane_data_file.ReadElementCount64(); layout.SetBlockSize<util::guidance::LaneTupleIdPair>(DataLayout::TURN_LANE_DATA, lane_tuple_count); } { // Loading MLD Data if (boost::filesystem::exists(config.mld_partition_path)) { io::FileReader reader(config.mld_partition_path, io::FileReader::VerifyFingerprint); reader.Skip<partition::MultiLevelPartition::LevelData>(1); layout.SetBlockSize<partition::MultiLevelPartition::LevelData>( DataLayout::MLD_LEVEL_DATA, 1); const auto partition_entries_count = reader.ReadVectorSize<PartitionID>(); layout.SetBlockSize<PartitionID>(DataLayout::MLD_PARTITION, partition_entries_count); const auto children_entries_count = reader.ReadVectorSize<CellID>(); layout.SetBlockSize<CellID>(DataLayout::MLD_CELL_TO_CHILDREN, children_entries_count); } else { layout.SetBlockSize<partition::MultiLevelPartition::LevelData>( DataLayout::MLD_LEVEL_DATA, 0); layout.SetBlockSize<PartitionID>(DataLayout::MLD_PARTITION, 0); layout.SetBlockSize<CellID>(DataLayout::MLD_CELL_TO_CHILDREN, 0); } if (boost::filesystem::exists(config.mld_storage_path)) { io::FileReader reader(config.mld_storage_path, io::FileReader::VerifyFingerprint); const auto weights_count = reader.ReadVectorSize<EdgeWeight>(); layout.SetBlockSize<EdgeWeight>(DataLayout::MLD_CELL_WEIGHTS, weights_count); const auto source_node_count = reader.ReadVectorSize<NodeID>(); layout.SetBlockSize<NodeID>(DataLayout::MLD_CELL_SOURCE_BOUNDARY, source_node_count); const auto destination_node_count = reader.ReadVectorSize<NodeID>(); layout.SetBlockSize<NodeID>(DataLayout::MLD_CELL_DESTINATION_BOUNDARY, destination_node_count); const auto cell_count = reader.ReadVectorSize<partition::CellStorage::CellData>(); layout.SetBlockSize<partition::CellStorage::CellData>(DataLayout::MLD_CELLS, cell_count); const auto level_offsets_count = reader.ReadVectorSize<std::uint64_t>(); layout.SetBlockSize<std::uint64_t>(DataLayout::MLD_CELL_LEVEL_OFFSETS, level_offsets_count); } else { layout.SetBlockSize<char>(DataLayout::MLD_CELL_WEIGHTS, 0); layout.SetBlockSize<char>(DataLayout::MLD_CELL_SOURCE_BOUNDARY, 0); layout.SetBlockSize<char>(DataLayout::MLD_CELL_DESTINATION_BOUNDARY, 0); layout.SetBlockSize<char>(DataLayout::MLD_CELLS, 0); layout.SetBlockSize<char>(DataLayout::MLD_CELL_LEVEL_OFFSETS, 0); } if (boost::filesystem::exists(config.mld_graph_path)) { io::FileReader reader(config.mld_graph_path, io::FileReader::VerifyFingerprint); const auto num_nodes = reader.ReadVectorSize<customizer::MultiLevelEdgeBasedGraph::NodeArrayEntry>(); const auto num_edges = reader.ReadVectorSize<customizer::MultiLevelEdgeBasedGraph::EdgeArrayEntry>(); const auto num_node_offsets = reader.ReadVectorSize<customizer::MultiLevelEdgeBasedGraph::EdgeOffset>(); layout.SetBlockSize<customizer::MultiLevelEdgeBasedGraph::NodeArrayEntry>( DataLayout::MLD_GRAPH_NODE_LIST, num_nodes); layout.SetBlockSize<customizer::MultiLevelEdgeBasedGraph::EdgeArrayEntry>( DataLayout::MLD_GRAPH_EDGE_LIST, num_edges); layout.SetBlockSize<customizer::MultiLevelEdgeBasedGraph::EdgeOffset>( DataLayout::MLD_GRAPH_NODE_TO_OFFSET, num_node_offsets); } else { layout.SetBlockSize<customizer::MultiLevelEdgeBasedGraph::NodeArrayEntry>( DataLayout::MLD_GRAPH_NODE_LIST, 0); layout.SetBlockSize<customizer::MultiLevelEdgeBasedGraph::EdgeArrayEntry>( DataLayout::MLD_GRAPH_EDGE_LIST, 0); layout.SetBlockSize<customizer::MultiLevelEdgeBasedGraph::EdgeOffset>( DataLayout::MLD_GRAPH_NODE_TO_OFFSET, 0); } } } void Storage::PopulateData(const DataLayout &layout, char *memory_ptr) { BOOST_ASSERT(memory_ptr != nullptr); // read actual data into shared memory object // // Load the HSGR file if (boost::filesystem::exists(config.hsgr_data_path)) { auto graph_nodes_ptr = layout.GetBlockPtr<contractor::QueryGraphView::NodeArrayEntry, true>( memory_ptr, storage::DataLayout::CH_GRAPH_NODE_LIST); auto graph_edges_ptr = layout.GetBlockPtr<contractor::QueryGraphView::EdgeArrayEntry, true>( memory_ptr, storage::DataLayout::CH_GRAPH_EDGE_LIST); auto checksum = layout.GetBlockPtr<unsigned, true>(memory_ptr, DataLayout::HSGR_CHECKSUM); util::vector_view<contractor::QueryGraphView::NodeArrayEntry> node_list( graph_nodes_ptr, layout.num_entries[storage::DataLayout::CH_GRAPH_NODE_LIST]); util::vector_view<contractor::QueryGraphView::EdgeArrayEntry> edge_list( graph_edges_ptr, layout.num_entries[storage::DataLayout::CH_GRAPH_EDGE_LIST]); contractor::QueryGraphView graph_view(std::move(node_list), std::move(edge_list)); contractor::files::readGraph(config.hsgr_data_path, *checksum, graph_view); } else { layout.GetBlockPtr<unsigned, true>(memory_ptr, DataLayout::HSGR_CHECKSUM); layout.GetBlockPtr<contractor::QueryGraphView::NodeArrayEntry, true>( memory_ptr, DataLayout::CH_GRAPH_NODE_LIST); layout.GetBlockPtr<contractor::QueryGraphView::EdgeArrayEntry, true>( memory_ptr, DataLayout::CH_GRAPH_EDGE_LIST); } // store the filename of the on-disk portion of the RTree { const auto file_index_path_ptr = layout.GetBlockPtr<char, true>(memory_ptr, DataLayout::FILE_INDEX_PATH); // make sure we have 0 ending std::fill(file_index_path_ptr, file_index_path_ptr + layout.GetBlockSize(DataLayout::FILE_INDEX_PATH), 0); const auto absolute_file_index_path = boost::filesystem::absolute(config.file_index_path).string(); BOOST_ASSERT(static_cast<std::size_t>(layout.GetBlockSize(DataLayout::FILE_INDEX_PATH)) >= absolute_file_index_path.size()); std::copy( absolute_file_index_path.begin(), absolute_file_index_path.end(), file_index_path_ptr); } // Name data { io::FileReader name_file(config.names_data_path, io::FileReader::HasNoFingerprint); std::size_t name_file_size = name_file.GetSize(); BOOST_ASSERT(name_file_size == layout.GetBlockSize(DataLayout::NAME_CHAR_DATA)); const auto name_char_ptr = layout.GetBlockPtr<char, true>(memory_ptr, DataLayout::NAME_CHAR_DATA); name_file.ReadInto<char>(name_char_ptr, name_file_size); } // Turn lane data { io::FileReader lane_data_file(config.turn_lane_data_path, io::FileReader::HasNoFingerprint); const auto lane_tuple_count = lane_data_file.ReadElementCount64(); // Need to call GetBlockPtr -> it write the memory canary, even if no data needs to be // loaded. const auto turn_lane_data_ptr = layout.GetBlockPtr<util::guidance::LaneTupleIdPair, true>( memory_ptr, DataLayout::TURN_LANE_DATA); BOOST_ASSERT(lane_tuple_count * sizeof(util::guidance::LaneTupleIdPair) == layout.GetBlockSize(DataLayout::TURN_LANE_DATA)); lane_data_file.ReadInto(turn_lane_data_ptr, lane_tuple_count); } // Turn lane descriptions { auto offsets_ptr = layout.GetBlockPtr<std::uint32_t, true>( memory_ptr, storage::DataLayout::LANE_DESCRIPTION_OFFSETS); util::vector_view<std::uint32_t> offsets( offsets_ptr, layout.num_entries[storage::DataLayout::LANE_DESCRIPTION_OFFSETS]); auto masks_ptr = layout.GetBlockPtr<extractor::guidance::TurnLaneType::Mask, true>( memory_ptr, storage::DataLayout::LANE_DESCRIPTION_MASKS); util::vector_view<extractor::guidance::TurnLaneType::Mask> masks( masks_ptr, layout.num_entries[storage::DataLayout::LANE_DESCRIPTION_MASKS]); extractor::files::readTurnLaneDescriptions( config.turn_lane_description_path, offsets, masks); } // Load original edge data { auto via_geometry_list_ptr = layout.GetBlockPtr<GeometryID, true>(memory_ptr, storage::DataLayout::VIA_NODE_LIST); util::vector_view<GeometryID> geometry_ids( via_geometry_list_ptr, layout.num_entries[storage::DataLayout::VIA_NODE_LIST]); const auto travel_mode_list_ptr = layout.GetBlockPtr<extractor::TravelMode, true>( memory_ptr, storage::DataLayout::TRAVEL_MODE); util::vector_view<extractor::TravelMode> travel_modes( travel_mode_list_ptr, layout.num_entries[storage::DataLayout::TRAVEL_MODE]); const auto lane_data_id_ptr = layout.GetBlockPtr<LaneDataID, true>(memory_ptr, storage::DataLayout::LANE_DATA_ID); util::vector_view<LaneDataID> lane_data_ids( lane_data_id_ptr, layout.num_entries[storage::DataLayout::LANE_DATA_ID]); const auto turn_instruction_list_ptr = layout.GetBlockPtr<extractor::guidance::TurnInstruction, true>( memory_ptr, storage::DataLayout::TURN_INSTRUCTION); util::vector_view<extractor::guidance::TurnInstruction> turn_instructions( turn_instruction_list_ptr, layout.num_entries[storage::DataLayout::TURN_INSTRUCTION]); const auto name_id_list_ptr = layout.GetBlockPtr<NameID, true>(memory_ptr, storage::DataLayout::NAME_ID_LIST); util::vector_view<NameID> name_ids(name_id_list_ptr, layout.num_entries[storage::DataLayout::NAME_ID_LIST]); const auto entry_class_id_list_ptr = layout.GetBlockPtr<EntryClassID, true>(memory_ptr, storage::DataLayout::ENTRY_CLASSID); util::vector_view<EntryClassID> entry_class_ids( entry_class_id_list_ptr, layout.num_entries[storage::DataLayout::ENTRY_CLASSID]); const auto pre_turn_bearing_ptr = layout.GetBlockPtr<util::guidance::TurnBearing, true>( memory_ptr, storage::DataLayout::PRE_TURN_BEARING); util::vector_view<util::guidance::TurnBearing> pre_turn_bearings( pre_turn_bearing_ptr, layout.num_entries[storage::DataLayout::PRE_TURN_BEARING]); const auto post_turn_bearing_ptr = layout.GetBlockPtr<util::guidance::TurnBearing, true>( memory_ptr, storage::DataLayout::POST_TURN_BEARING); util::vector_view<util::guidance::TurnBearing> post_turn_bearings( post_turn_bearing_ptr, layout.num_entries[storage::DataLayout::POST_TURN_BEARING]); extractor::TurnDataView turn_data(std::move(geometry_ids), std::move(name_ids), std::move(turn_instructions), std::move(lane_data_ids), std::move(travel_modes), std::move(entry_class_ids), std::move(pre_turn_bearings), std::move(post_turn_bearings)); extractor::files::readTurnData(config.edges_data_path, turn_data); } // load compressed geometry { auto geometries_index_ptr = layout.GetBlockPtr<unsigned, true>(memory_ptr, storage::DataLayout::GEOMETRIES_INDEX); util::vector_view<unsigned> geometry_begin_indices( geometries_index_ptr, layout.num_entries[storage::DataLayout::GEOMETRIES_INDEX]); auto geometries_node_list_ptr = layout.GetBlockPtr<NodeID, true>(memory_ptr, storage::DataLayout::GEOMETRIES_NODE_LIST); util::vector_view<NodeID> geometry_node_list( geometries_node_list_ptr, layout.num_entries[storage::DataLayout::GEOMETRIES_NODE_LIST]); auto geometries_fwd_weight_list_ptr = layout.GetBlockPtr<EdgeWeight, true>( memory_ptr, storage::DataLayout::GEOMETRIES_FWD_WEIGHT_LIST); util::vector_view<EdgeWeight> geometry_fwd_weight_list( geometries_fwd_weight_list_ptr, layout.num_entries[storage::DataLayout::GEOMETRIES_FWD_WEIGHT_LIST]); auto geometries_rev_weight_list_ptr = layout.GetBlockPtr<EdgeWeight, true>( memory_ptr, storage::DataLayout::GEOMETRIES_REV_WEIGHT_LIST); util::vector_view<EdgeWeight> geometry_rev_weight_list( geometries_rev_weight_list_ptr, layout.num_entries[storage::DataLayout::GEOMETRIES_REV_WEIGHT_LIST]); auto geometries_fwd_duration_list_ptr = layout.GetBlockPtr<EdgeWeight, true>( memory_ptr, storage::DataLayout::GEOMETRIES_FWD_DURATION_LIST); util::vector_view<EdgeWeight> geometry_fwd_duration_list( geometries_fwd_duration_list_ptr, layout.num_entries[storage::DataLayout::GEOMETRIES_FWD_DURATION_LIST]); auto geometries_rev_duration_list_ptr = layout.GetBlockPtr<EdgeWeight, true>( memory_ptr, storage::DataLayout::GEOMETRIES_REV_DURATION_LIST); util::vector_view<EdgeWeight> geometry_rev_duration_list( geometries_rev_duration_list_ptr, layout.num_entries[storage::DataLayout::GEOMETRIES_REV_DURATION_LIST]); auto datasources_list_ptr = layout.GetBlockPtr<DatasourceID, true>( memory_ptr, storage::DataLayout::DATASOURCES_LIST); util::vector_view<DatasourceID> datasources_list( datasources_list_ptr, layout.num_entries[storage::DataLayout::DATASOURCES_LIST]); extractor::SegmentDataView segment_data{std::move(geometry_begin_indices), std::move(geometry_node_list), std::move(geometry_fwd_weight_list), std::move(geometry_rev_weight_list), std::move(geometry_fwd_duration_list), std::move(geometry_rev_duration_list), std::move(datasources_list)}; extractor::files::readSegmentData(config.geometries_path, segment_data); } { const auto datasources_names_ptr = layout.GetBlockPtr<extractor::Datasources, true>( memory_ptr, DataLayout::DATASOURCES_NAMES); extractor::files::readDatasources(config.datasource_names_path, *datasources_names_ptr); } // Loading list of coordinates { const auto coordinates_ptr = layout.GetBlockPtr<util::Coordinate, true>(memory_ptr, DataLayout::COORDINATE_LIST); const auto osmnodeid_ptr = layout.GetBlockPtr<std::uint64_t, true>(memory_ptr, DataLayout::OSM_NODE_ID_LIST); util::vector_view<util::Coordinate> coordinates( coordinates_ptr, layout.num_entries[DataLayout::COORDINATE_LIST]); util::PackedVectorView<OSMNodeID> osm_node_ids; osm_node_ids.reset(osmnodeid_ptr, layout.num_entries[DataLayout::OSM_NODE_ID_LIST]); extractor::files::readNodes(config.nodes_data_path, coordinates, osm_node_ids); } // load turn weight penalties { io::FileReader turn_weight_penalties_file(config.turn_weight_penalties_path, io::FileReader::HasNoFingerprint); const auto number_of_penalties = turn_weight_penalties_file.ReadElementCount64(); const auto turn_weight_penalties_ptr = layout.GetBlockPtr<TurnPenalty, true>(memory_ptr, DataLayout::TURN_WEIGHT_PENALTIES); turn_weight_penalties_file.ReadInto(turn_weight_penalties_ptr, number_of_penalties); } // load turn duration penalties { io::FileReader turn_duration_penalties_file(config.turn_duration_penalties_path, io::FileReader::HasNoFingerprint); const auto number_of_penalties = turn_duration_penalties_file.ReadElementCount64(); const auto turn_duration_penalties_ptr = layout.GetBlockPtr<TurnPenalty, true>(memory_ptr, DataLayout::TURN_DURATION_PENALTIES); turn_duration_penalties_file.ReadInto(turn_duration_penalties_ptr, number_of_penalties); } // store timestamp { io::FileReader timestamp_file(config.timestamp_path, io::FileReader::HasNoFingerprint); const auto timestamp_size = timestamp_file.Size(); const auto timestamp_ptr = layout.GetBlockPtr<char, true>(memory_ptr, DataLayout::TIMESTAMP); BOOST_ASSERT(timestamp_size == layout.num_entries[DataLayout::TIMESTAMP]); timestamp_file.ReadInto(timestamp_ptr, timestamp_size); } // store search tree portion of rtree { io::FileReader tree_node_file(config.ram_index_path, io::FileReader::HasNoFingerprint); // perform this read so that we're at the right stream position for the next // read. tree_node_file.Skip<std::uint64_t>(1); const auto rtree_ptr = layout.GetBlockPtr<RTreeNode, true>(memory_ptr, DataLayout::R_SEARCH_TREE); tree_node_file.ReadInto(rtree_ptr, layout.num_entries[DataLayout::R_SEARCH_TREE]); } if (boost::filesystem::exists(config.core_data_path)) { io::FileReader core_marker_file(config.core_data_path, io::FileReader::HasNoFingerprint); const auto number_of_core_markers = core_marker_file.ReadElementCount32(); // load core markers std::vector<char> unpacked_core_markers(number_of_core_markers); core_marker_file.ReadInto(unpacked_core_markers.data(), number_of_core_markers); const auto core_marker_ptr = layout.GetBlockPtr<unsigned, true>(memory_ptr, DataLayout::CH_CORE_MARKER); for (auto i = 0u; i < number_of_core_markers; ++i) { BOOST_ASSERT(unpacked_core_markers[i] == 0 || unpacked_core_markers[i] == 1); if (unpacked_core_markers[i] == 1) { const unsigned bucket = i / 32; const unsigned offset = i % 32; const unsigned value = [&] { unsigned return_value = 0; if (0 != offset) { return_value = core_marker_ptr[bucket]; } return return_value; }(); core_marker_ptr[bucket] = (value | (1u << offset)); } } } // load profile properties { io::FileReader profile_properties_file(config.properties_path, io::FileReader::HasNoFingerprint); const auto profile_properties_ptr = layout.GetBlockPtr<extractor::ProfileProperties, true>( memory_ptr, DataLayout::PROPERTIES); profile_properties_file.ReadInto(profile_properties_ptr, layout.num_entries[DataLayout::PROPERTIES]); } // Load intersection data { io::FileReader intersection_file(config.intersection_class_path, io::FileReader::VerifyFingerprint); std::vector<BearingClassID> bearing_class_id_table; serialization::read(intersection_file, bearing_class_id_table); const auto bearing_blocks = intersection_file.ReadElementCount32(); intersection_file.Skip<std::uint32_t>(1); // sum_lengths std::vector<unsigned> bearing_offsets_data(bearing_blocks); std::vector<typename util::RangeTable<16, storage::Ownership::View>::BlockT> bearing_blocks_data(bearing_blocks); intersection_file.ReadInto(bearing_offsets_data.data(), bearing_blocks); intersection_file.ReadInto(bearing_blocks_data.data(), bearing_blocks); const auto num_bearings = intersection_file.ReadElementCount64(); std::vector<DiscreteBearing> bearing_class_table(num_bearings); intersection_file.ReadInto(bearing_class_table.data(), num_bearings); std::vector<util::guidance::EntryClass> entry_class_table; serialization::read(intersection_file, entry_class_table); // load intersection classes if (!bearing_class_id_table.empty()) { const auto bearing_id_ptr = layout.GetBlockPtr<BearingClassID, true>(memory_ptr, DataLayout::BEARING_CLASSID); BOOST_ASSERT( static_cast<std::size_t>(layout.GetBlockSize(DataLayout::BEARING_CLASSID)) >= std::distance(bearing_class_id_table.begin(), bearing_class_id_table.end()) * sizeof(decltype(bearing_class_id_table)::value_type)); std::copy(bearing_class_id_table.begin(), bearing_class_id_table.end(), bearing_id_ptr); } if (layout.GetBlockSize(DataLayout::BEARING_OFFSETS) > 0) { const auto bearing_offsets_ptr = layout.GetBlockPtr<unsigned, true>(memory_ptr, DataLayout::BEARING_OFFSETS); BOOST_ASSERT( static_cast<std::size_t>(layout.GetBlockSize(DataLayout::BEARING_OFFSETS)) >= std::distance(bearing_offsets_data.begin(), bearing_offsets_data.end()) * sizeof(decltype(bearing_offsets_data)::value_type)); std::copy( bearing_offsets_data.begin(), bearing_offsets_data.end(), bearing_offsets_ptr); } if (layout.GetBlockSize(DataLayout::BEARING_BLOCKS) > 0) { const auto bearing_blocks_ptr = layout.GetBlockPtr<typename util::RangeTable<16, storage::Ownership::View>::BlockT, true>(memory_ptr, DataLayout::BEARING_BLOCKS); BOOST_ASSERT( static_cast<std::size_t>(layout.GetBlockSize(DataLayout::BEARING_BLOCKS)) >= std::distance(bearing_blocks_data.begin(), bearing_blocks_data.end()) * sizeof(decltype(bearing_blocks_data)::value_type)); std::copy(bearing_blocks_data.begin(), bearing_blocks_data.end(), bearing_blocks_ptr); } if (!bearing_class_table.empty()) { const auto bearing_class_ptr = layout.GetBlockPtr<DiscreteBearing, true>(memory_ptr, DataLayout::BEARING_VALUES); BOOST_ASSERT( static_cast<std::size_t>(layout.GetBlockSize(DataLayout::BEARING_VALUES)) >= std::distance(bearing_class_table.begin(), bearing_class_table.end()) * sizeof(decltype(bearing_class_table)::value_type)); std::copy(bearing_class_table.begin(), bearing_class_table.end(), bearing_class_ptr); } if (!entry_class_table.empty()) { const auto entry_class_ptr = layout.GetBlockPtr<util::guidance::EntryClass, true>( memory_ptr, DataLayout::ENTRY_CLASS); BOOST_ASSERT(static_cast<std::size_t>(layout.GetBlockSize(DataLayout::ENTRY_CLASS)) >= std::distance(entry_class_table.begin(), entry_class_table.end()) * sizeof(decltype(entry_class_table)::value_type)); std::copy(entry_class_table.begin(), entry_class_table.end(), entry_class_ptr); } } { // Loading MLD Data if (boost::filesystem::exists(config.mld_partition_path)) { BOOST_ASSERT(layout.GetBlockSize(storage::DataLayout::MLD_LEVEL_DATA) > 0); BOOST_ASSERT(layout.GetBlockSize(storage::DataLayout::MLD_CELL_TO_CHILDREN) > 0); BOOST_ASSERT(layout.GetBlockSize(storage::DataLayout::MLD_PARTITION) > 0); auto level_data = layout.GetBlockPtr<partition::MultiLevelPartitionView::LevelData, true>( memory_ptr, storage::DataLayout::MLD_LEVEL_DATA); auto mld_partition_ptr = layout.GetBlockPtr<PartitionID, true>( memory_ptr, storage::DataLayout::MLD_PARTITION); auto partition_entries_count = layout.GetBlockEntries(storage::DataLayout::MLD_PARTITION); util::vector_view<PartitionID> partition(mld_partition_ptr, partition_entries_count); auto mld_chilren_ptr = layout.GetBlockPtr<CellID, true>( memory_ptr, storage::DataLayout::MLD_CELL_TO_CHILDREN); auto children_entries_count = layout.GetBlockEntries(storage::DataLayout::MLD_CELL_TO_CHILDREN); util::vector_view<CellID> cell_to_children(mld_chilren_ptr, children_entries_count); partition::MultiLevelPartitionView mlp{ std::move(level_data), std::move(partition), std::move(cell_to_children)}; partition::files::readPartition(config.mld_partition_path, mlp); } if (boost::filesystem::exists(config.mld_storage_path)) { BOOST_ASSERT(layout.GetBlockSize(storage::DataLayout::MLD_CELLS) > 0); BOOST_ASSERT(layout.GetBlockSize(storage::DataLayout::MLD_CELL_LEVEL_OFFSETS) > 0); auto mld_cell_weights_ptr = layout.GetBlockPtr<EdgeWeight, true>( memory_ptr, storage::DataLayout::MLD_CELL_WEIGHTS); auto mld_source_boundary_ptr = layout.GetBlockPtr<NodeID, true>( memory_ptr, storage::DataLayout::MLD_CELL_SOURCE_BOUNDARY); auto mld_destination_boundary_ptr = layout.GetBlockPtr<NodeID, true>( memory_ptr, storage::DataLayout::MLD_CELL_DESTINATION_BOUNDARY); auto mld_cells_ptr = layout.GetBlockPtr<partition::CellStorageView::CellData, true>( memory_ptr, storage::DataLayout::MLD_CELLS); auto mld_cell_level_offsets_ptr = layout.GetBlockPtr<std::uint64_t, true>( memory_ptr, storage::DataLayout::MLD_CELL_LEVEL_OFFSETS); auto weight_entries_count = layout.GetBlockEntries(storage::DataLayout::MLD_CELL_WEIGHTS); auto source_boundary_entries_count = layout.GetBlockEntries(storage::DataLayout::MLD_CELL_SOURCE_BOUNDARY); auto destination_boundary_entries_count = layout.GetBlockEntries(storage::DataLayout::MLD_CELL_DESTINATION_BOUNDARY); auto cells_entries_counts = layout.GetBlockEntries(storage::DataLayout::MLD_CELLS); auto cell_level_offsets_entries_count = layout.GetBlockEntries(storage::DataLayout::MLD_CELL_LEVEL_OFFSETS); util::vector_view<EdgeWeight> weights(mld_cell_weights_ptr, weight_entries_count); util::vector_view<NodeID> source_boundary(mld_source_boundary_ptr, source_boundary_entries_count); util::vector_view<NodeID> destination_boundary(mld_destination_boundary_ptr, destination_boundary_entries_count); util::vector_view<partition::CellStorageView::CellData> cells(mld_cells_ptr, cells_entries_counts); util::vector_view<std::uint64_t> level_offsets(mld_cell_level_offsets_ptr, cell_level_offsets_entries_count); partition::CellStorageView storage{std::move(weights), std::move(source_boundary), std::move(destination_boundary), std::move(cells), std::move(level_offsets)}; partition::files::readCells(config.mld_storage_path, storage); } if (boost::filesystem::exists(config.mld_graph_path)) { auto graph_nodes_ptr = layout.GetBlockPtr<customizer::MultiLevelEdgeBasedGraphView::NodeArrayEntry, true>( memory_ptr, storage::DataLayout::MLD_GRAPH_NODE_LIST); auto graph_edges_ptr = layout.GetBlockPtr<customizer::MultiLevelEdgeBasedGraphView::EdgeArrayEntry, true>( memory_ptr, storage::DataLayout::MLD_GRAPH_EDGE_LIST); auto graph_node_to_offset_ptr = layout.GetBlockPtr<customizer::MultiLevelEdgeBasedGraphView::EdgeOffset, true>( memory_ptr, storage::DataLayout::MLD_GRAPH_NODE_TO_OFFSET); util::vector_view<customizer::MultiLevelEdgeBasedGraphView::NodeArrayEntry> node_list( graph_nodes_ptr, layout.num_entries[storage::DataLayout::MLD_GRAPH_NODE_LIST]); util::vector_view<customizer::MultiLevelEdgeBasedGraphView::EdgeArrayEntry> edge_list( graph_edges_ptr, layout.num_entries[storage::DataLayout::MLD_GRAPH_EDGE_LIST]); util::vector_view<customizer::MultiLevelEdgeBasedGraphView::EdgeOffset> node_to_offset( graph_node_to_offset_ptr, layout.num_entries[storage::DataLayout::MLD_GRAPH_NODE_TO_OFFSET]); customizer::MultiLevelEdgeBasedGraphView graph_view( std::move(node_list), std::move(edge_list), std::move(node_to_offset)); partition::files::readGraph(config.mld_graph_path, graph_view); } } } } }
1
21,183
What is the logic behind `ReadVectorSize` reading `CountElement64`, then skipping `T` (in this case `unsigned`)? Naming doesn't cover what's actually happening here. Ideally I'd also take this through a `files` layer, any input as to how?
Project-OSRM-osrm-backend
cpp
@@ -24,6 +24,7 @@ import org.apache.solr.common.params.CommonParams; import org.apache.solr.core.CoreContainer; import org.apache.solr.core.SolrCore; +import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
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.servlet; import org.apache.commons.io.IOUtils; import org.apache.commons.io.output.CloseShieldOutputStream; import org.apache.commons.lang3.StringUtils; import org.apache.commons.text.StringEscapeUtils; import org.apache.solr.common.params.CommonParams; import org.apache.solr.core.CoreContainer; import org.apache.solr.core.SolrCore; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.charset.StandardCharsets; /** * A simple servlet to load the Solr Admin UI * * @since solr 4.0 */ public final class LoadAdminUiServlet extends BaseSolrServlet { @Override public void doGet(HttpServletRequest _request, HttpServletResponse _response) throws IOException { HttpServletRequest request = SolrDispatchFilter.closeShield(_request, false); HttpServletResponse response = SolrDispatchFilter.closeShield(_response, false); response.addHeader("X-Frame-Options", "DENY"); // security: SOLR-7966 - avoid clickjacking for admin interface // This attribute is set by the SolrDispatchFilter String admin = request.getRequestURI().substring(request.getContextPath().length()); CoreContainer cores = (CoreContainer) request.getAttribute("org.apache.solr.CoreContainer"); InputStream in = getServletContext().getResourceAsStream(admin); Writer out = null; if(in != null && cores != null) { try { response.setCharacterEncoding("UTF-8"); response.setContentType("text/html"); // We have to close this to flush OutputStreamWriter buffer out = new OutputStreamWriter(new CloseShieldOutputStream(response.getOutputStream()), StandardCharsets.UTF_8); String html = IOUtils.toString(in, "UTF-8"); Package pack = SolrCore.class.getPackage(); String[] search = new String[] { "${contextPath}", "${adminPath}", "${version}" }; String[] replace = new String[] { StringEscapeUtils.escapeEcmaScript(request.getContextPath()), StringEscapeUtils.escapeEcmaScript(CommonParams.CORES_HANDLER_PATH), StringEscapeUtils.escapeEcmaScript(pack.getSpecificationVersion()) }; out.write( StringUtils.replaceEach(html, search, replace) ); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } else { response.sendError(404); } } }
1
33,527
This looks like an unused import to me?
apache-lucene-solr
java
@@ -231,13 +231,13 @@ func taskListInfoFromBlob(b []byte, proto string) (*sqlblobs.TaskListInfo, error return result, thriftRWDecode(b, proto, result) } -func transferTaskInfoToBlob(info *sqlblobs.TransferTaskInfo) (p.DataBlob, error) { - return thriftRWEncode(info) +func TransferTaskInfoToBlob(info *persistenceblobs.TransferTaskInfo) (p.DataBlob, error) { + return protoRWEncode(info) } -func transferTaskInfoFromBlob(b []byte, proto string) (*sqlblobs.TransferTaskInfo, error) { - result := &sqlblobs.TransferTaskInfo{} - return result, thriftRWDecode(b, proto, result) +func TransferTaskInfoFromBlob(b []byte, proto string) (*persistenceblobs.TransferTaskInfo, error) { + result := &persistenceblobs.TransferTaskInfo{} + return result, protoRWDecode(b, proto, result) } func TimerTaskInfoToBlob(info *persistenceblobs.TimerTaskInfo) (p.DataBlob, error) {
1
// Copyright (c) 2017 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 sql import ( "bytes" "fmt" "github.com/gogo/protobuf/types" "github.com/temporalio/temporal/.gen/proto/persistenceblobs" "go.uber.org/thriftrw/protocol" "go.uber.org/thriftrw/wire" "github.com/temporalio/temporal/.gen/go/sqlblobs" "github.com/temporalio/temporal/common" p "github.com/temporalio/temporal/common/persistence" ) // thriftRWType represents an thrift auto generated type type thriftRWType interface { ToWire() (wire.Value, error) FromWire(w wire.Value) error } type protoMarshal interface { Marshal() ([]byte, error) Unmarshal([]byte) error } func validateProto(p string, expected common.EncodingType) error { if common.EncodingType(p) != expected { return fmt.Errorf("invalid encoding type: %v", p) } return nil } func encodeErr(encoding common.EncodingType, err error) error { if err == nil { return nil } return fmt.Errorf("error serializing struct to blob using encoding - %v - : %v", encoding, err) } func decodeErr(encoding common.EncodingType, err error) error { if err == nil { return nil } return fmt.Errorf("error deserializing blob to blob using encoding - %v - : %v", encoding, err) } func protoRWEncode(m protoMarshal) (p.DataBlob, error) { blob := p.DataBlob{Encoding: common.EncodingTypeProto3} data, err := m.Marshal() if err != nil { return blob, encodeErr(common.EncodingTypeProto3, err) } blob.Data = data return blob, nil } func protoRWDecode(b []byte, proto string, result protoMarshal) error { if err := validateProto(proto, common.EncodingTypeProto3); err != nil { return err } return decodeErr(common.EncodingTypeThriftRW, result.Unmarshal(b)) } func thriftRWEncode(t thriftRWType) (p.DataBlob, error) { blob := p.DataBlob{Encoding: common.EncodingTypeThriftRW} value, err := t.ToWire() if err != nil { return blob, encodeErr(common.EncodingTypeThriftRW, err) } var b bytes.Buffer if err := protocol.Binary.Encode(value, &b); err != nil { return blob, encodeErr(common.EncodingTypeThriftRW, err) } blob.Data = b.Bytes() return blob, nil } func thriftRWDecode(b []byte, proto string, result thriftRWType) error { if err := validateProto(proto, common.EncodingTypeThriftRW); err != nil { return err } value, err := protocol.Binary.Decode(bytes.NewReader(b), wire.TStruct) if err != nil { return decodeErr(common.EncodingTypeThriftRW, err) } return decodeErr(common.EncodingTypeThriftRW, result.FromWire(value)) } func ShardInfoToBlob(info *persistenceblobs.ShardInfo) (p.DataBlob, error) { return protoRWEncode(info) } func ShardInfoFromBlob(b []byte, proto string, clusterName string) (*persistenceblobs.ShardInfo, error) { shardInfo := &persistenceblobs.ShardInfo{} err := protoRWDecode(b, proto, shardInfo) if err != nil { return nil, err } if len(shardInfo.GetClusterTransferAckLevel()) == 0 { shardInfo.ClusterTransferAckLevel = map[string]int64{ clusterName: shardInfo.GetTransferAckLevel(), } } if len(shardInfo.GetClusterTimerAckLevel()) == 0 { shardInfo.ClusterTimerAckLevel = map[string]*types.Timestamp{ clusterName: shardInfo.GetTimerAckLevel(), } } if shardInfo.GetClusterReplicationLevel() == nil { shardInfo.ClusterReplicationLevel = make(map[string]int64) } return shardInfo, nil } func domainInfoToBlob(info *sqlblobs.DomainInfo) (p.DataBlob, error) { return thriftRWEncode(info) } func domainInfoFromBlob(b []byte, proto string) (*sqlblobs.DomainInfo, error) { result := &sqlblobs.DomainInfo{} return result, thriftRWDecode(b, proto, result) } func historyTreeInfoToBlob(info *sqlblobs.HistoryTreeInfo) (p.DataBlob, error) { return thriftRWEncode(info) } func historyTreeInfoFromBlob(b []byte, proto string) (*sqlblobs.HistoryTreeInfo, error) { result := &sqlblobs.HistoryTreeInfo{} return result, thriftRWDecode(b, proto, result) } func workflowExecutionInfoToBlob(info *sqlblobs.WorkflowExecutionInfo) (p.DataBlob, error) { return thriftRWEncode(info) } func workflowExecutionInfoFromBlob(b []byte, proto string) (*sqlblobs.WorkflowExecutionInfo, error) { result := &sqlblobs.WorkflowExecutionInfo{} return result, thriftRWDecode(b, proto, result) } func activityInfoToBlob(info *sqlblobs.ActivityInfo) (p.DataBlob, error) { return thriftRWEncode(info) } func activityInfoFromBlob(b []byte, proto string) (*sqlblobs.ActivityInfo, error) { result := &sqlblobs.ActivityInfo{} return result, thriftRWDecode(b, proto, result) } func childExecutionInfoToBlob(info *sqlblobs.ChildExecutionInfo) (p.DataBlob, error) { return thriftRWEncode(info) } func childExecutionInfoFromBlob(b []byte, proto string) (*sqlblobs.ChildExecutionInfo, error) { result := &sqlblobs.ChildExecutionInfo{} return result, thriftRWDecode(b, proto, result) } func signalInfoToBlob(info *sqlblobs.SignalInfo) (p.DataBlob, error) { return thriftRWEncode(info) } func signalInfoFromBlob(b []byte, proto string) (*sqlblobs.SignalInfo, error) { result := &sqlblobs.SignalInfo{} return result, thriftRWDecode(b, proto, result) } func requestCancelInfoToBlob(info *sqlblobs.RequestCancelInfo) (p.DataBlob, error) { return thriftRWEncode(info) } func requestCancelInfoFromBlob(b []byte, proto string) (*sqlblobs.RequestCancelInfo, error) { result := &sqlblobs.RequestCancelInfo{} return result, thriftRWDecode(b, proto, result) } func timerInfoToBlob(info *sqlblobs.TimerInfo) (p.DataBlob, error) { return thriftRWEncode(info) } func timerInfoFromBlob(b []byte, proto string) (*sqlblobs.TimerInfo, error) { result := &sqlblobs.TimerInfo{} return result, thriftRWDecode(b, proto, result) } func taskInfoToBlob(info *sqlblobs.TaskInfo) (p.DataBlob, error) { return thriftRWEncode(info) } func taskInfoFromBlob(b []byte, proto string) (*sqlblobs.TaskInfo, error) { result := &sqlblobs.TaskInfo{} return result, thriftRWDecode(b, proto, result) } func taskListInfoToBlob(info *sqlblobs.TaskListInfo) (p.DataBlob, error) { return thriftRWEncode(info) } func taskListInfoFromBlob(b []byte, proto string) (*sqlblobs.TaskListInfo, error) { result := &sqlblobs.TaskListInfo{} return result, thriftRWDecode(b, proto, result) } func transferTaskInfoToBlob(info *sqlblobs.TransferTaskInfo) (p.DataBlob, error) { return thriftRWEncode(info) } func transferTaskInfoFromBlob(b []byte, proto string) (*sqlblobs.TransferTaskInfo, error) { result := &sqlblobs.TransferTaskInfo{} return result, thriftRWDecode(b, proto, result) } func TimerTaskInfoToBlob(info *persistenceblobs.TimerTaskInfo) (p.DataBlob, error) { return protoRWEncode(info) } func TimerTaskInfoFromBlob(b []byte, proto string) (*persistenceblobs.TimerTaskInfo, error) { result := &persistenceblobs.TimerTaskInfo{} return result, protoRWDecode(b, proto, result) } func ReplicationTaskInfoToBlob(info *persistenceblobs.ReplicationTaskInfo) (p.DataBlob, error) { return protoRWEncode(info) } func ReplicationTaskInfoFromBlob(b []byte, proto string) (*persistenceblobs.ReplicationTaskInfo, error) { result := &persistenceblobs.ReplicationTaskInfo{} return result, protoRWDecode(b, proto, result) }
1
9,295
`RW` means read/write. Why do we have it here, as part of a func name?
temporalio-temporal
go
@@ -61,7 +61,7 @@ class UnboundZmqEventBus implements EventBus { return thread; }); - LOG.info(String.format("Connecting to %s and %s", publishConnection, subscribeConnection)); + LOG.finest(String.format("Connecting to %s and %s", publishConnection, subscribeConnection)); sub = context.createSocket(SocketType.SUB); sub.connect(publishConnection);
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. package org.openqa.selenium.events.zeromq; import static java.nio.charset.StandardCharsets.UTF_8; import com.google.common.collect.EvictingQueue; import org.openqa.selenium.events.Event; import org.openqa.selenium.events.EventBus; import org.openqa.selenium.events.Type; import org.openqa.selenium.json.Json; import org.zeromq.SocketType; import org.zeromq.ZContext; import org.zeromq.ZMQ; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Queue; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Consumer; import java.util.logging.Logger; class UnboundZmqEventBus implements EventBus { private static final Logger LOG = Logger.getLogger(EventBus.class.getName()); private static final Json JSON = new Json(); private final ExecutorService executor; private final Map<Type, List<Consumer<Event>>> listeners = new ConcurrentHashMap<>(); private final Queue<UUID> recentMessages = EvictingQueue.create(128); private ZMQ.Socket pub; private ZMQ.Socket sub; UnboundZmqEventBus(ZContext context, String publishConnection, String subscribeConnection) { executor = Executors.newCachedThreadPool(r -> { Thread thread = new Thread(r); thread.setName("Event Bus"); thread.setDaemon(true); return thread; }); LOG.info(String.format("Connecting to %s and %s", publishConnection, subscribeConnection)); sub = context.createSocket(SocketType.SUB); sub.connect(publishConnection); sub.subscribe(new byte[0]); pub = context.createSocket(SocketType.PUB); pub.connect(subscribeConnection); ZMQ.Poller poller = context.createPoller(1); poller.register(sub, ZMQ.Poller.POLLIN); LOG.info("Sockets created"); AtomicBoolean pollingStarted = new AtomicBoolean(false); executor.submit(() -> { LOG.info("Bus started"); while (!Thread.currentThread().isInterrupted()) { try { poller.poll(150); pollingStarted.lazySet(true); if (poller.pollin(0)) { ZMQ.Socket socket = poller.getSocket(0); Type type = new Type(new String(socket.recv(ZMQ.DONTWAIT), UTF_8)); UUID id = UUID.fromString(new String(socket.recv(ZMQ.DONTWAIT), UTF_8)); String data = new String(socket.recv(ZMQ.DONTWAIT), UTF_8); Object converted = JSON.toType(data, Object.class); Event event = new Event(id, type, converted); if (recentMessages.contains(id)) { continue; } recentMessages.add(id); List<Consumer<Event>> typeListeners = listeners.get(type); if (typeListeners == null) { continue; } typeListeners.parallelStream().forEach(listener -> listener.accept(event)); } } catch (Throwable e) { if (e.getCause() != null && e.getCause() instanceof AssertionError) { // Do nothing. } else { throw e; } } } }); // Give ourselves up to a second to connect, using The World's Worst heuristic. If we don't // manage to connect, it's not the end of the world, as the socket we're connecting to may not // be up yet. while (!pollingStarted.get()) { try { Thread.sleep(100); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new RuntimeException(e); } } } @Override public void addListener(Type type, Consumer<Event> onType) { Objects.requireNonNull(type, "Event type must be set."); Objects.requireNonNull(onType, "Event listener must be set."); List<Consumer<Event>> typeListeners = listeners.computeIfAbsent(type, t -> new LinkedList<>()); typeListeners.add(onType); } @Override public void fire(Event event) { Objects.requireNonNull(event, "Event to send must be set."); pub.sendMore(event.getType().getName().getBytes(UTF_8)); pub.sendMore(event.getId().toString().getBytes(UTF_8)); pub.send(event.getRawData().getBytes(UTF_8)); } @Override public void close() { executor.shutdown(); if (sub != null) { sub.close(); } if (pub != null) { pub.close(); } } }
1
16,464
I'd keep this at `info` level...
SeleniumHQ-selenium
java
@@ -1051,7 +1051,11 @@ static ssize_t expect_preface(h2o_http2_conn_t *conn, const uint8_t *src, size_t } { /* send SETTINGS and connection-level WINDOW_UPDATE */ - h2o_iovec_t vec = h2o_buffer_reserve(&conn->_write.buf, SERVER_PREFACE.len); + h2o_iovec_t vec = h2o_buffer_try_reserve(&conn->_write.buf, SERVER_PREFACE.len); + if (vec.base == NULL) { + *err_desc = "failed to allocate memory"; + return H2O_HTTP2_ERROR_PROTOCOL_CLOSE_IMMEDIATELY; + } memcpy(vec.base, SERVER_PREFACE.base, SERVER_PREFACE.len); conn->_write.buf->size += SERVER_PREFACE.len; if (conn->http2_origin_frame) {
1
/* * Copyright (c) 2014-2016 DeNA Co., Ltd., Kazuho Oku, Fastly, 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. */ #include <inttypes.h> #include <stdio.h> #include <stdlib.h> #include "h2o.h" #include "h2o/hpack.h" #include "h2o/http1.h" #include "h2o/http2.h" #include "h2o/http2_internal.h" static const h2o_iovec_t CONNECTION_PREFACE = {H2O_STRLIT("PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n")}; #define LIT16(x) ((uint32_t)(x) >> 16) & 0xff, (x)&0xff #define LIT24(x) LIT16((x) >> 8), (x)&0xff #define LIT32(x) LIT24((x) >> 8), (x)&0xff #define LIT_FRAME_HEADER(size, type, flags, stream_id) LIT24(size), (type), (flags), LIT32(stream_id) static const uint8_t SERVER_PREFACE_BIN[] = { /* settings frame */ LIT_FRAME_HEADER(6, H2O_HTTP2_FRAME_TYPE_SETTINGS, 0, 0), LIT16(H2O_HTTP2_SETTINGS_MAX_CONCURRENT_STREAMS), LIT32(100), /* window_update frame */ LIT_FRAME_HEADER(4, H2O_HTTP2_FRAME_TYPE_WINDOW_UPDATE, 0, 0), LIT32(H2O_HTTP2_SETTINGS_HOST_CONNECTION_WINDOW_SIZE - H2O_HTTP2_SETTINGS_HOST_STREAM_INITIAL_WINDOW_SIZE)}; #undef LIT16 #undef LIT24 #undef LIT32 #undef LIT_FRAME_HEADER static const h2o_iovec_t SERVER_PREFACE = {(char *)SERVER_PREFACE_BIN, sizeof(SERVER_PREFACE_BIN)}; __thread h2o_buffer_prototype_t h2o_http2_wbuf_buffer_prototype = {{16}, {H2O_HTTP2_DEFAULT_OUTBUF_SIZE}}; static void update_stream_input_window(h2o_http2_conn_t *conn, h2o_http2_stream_t *stream, size_t bytes); static void initiate_graceful_shutdown(h2o_context_t *ctx); static int close_connection(h2o_http2_conn_t *conn); static ssize_t expect_default(h2o_http2_conn_t *conn, const uint8_t *src, size_t len, const char **err_desc); static void do_emit_writereq(h2o_http2_conn_t *conn); static void on_read(h2o_socket_t *sock, const char *err); static void push_path(h2o_req_t *src_req, const char *abspath, size_t abspath_len, int is_critical); static int foreach_request(h2o_context_t *ctx, int (*cb)(h2o_req_t *req, void *cbdata), void *cbdata); static void stream_send_error(h2o_http2_conn_t *conn, uint32_t stream_id, int errnum); const h2o_protocol_callbacks_t H2O_HTTP2_CALLBACKS = {initiate_graceful_shutdown, foreach_request}; static int is_idle_stream_id(h2o_http2_conn_t *conn, uint32_t stream_id) { return (h2o_http2_stream_is_push(stream_id) ? conn->push_stream_ids.max_open : conn->pull_stream_ids.max_open) < stream_id; } static void enqueue_goaway(h2o_http2_conn_t *conn, int errnum, h2o_iovec_t additional_data) { if (conn->state < H2O_HTTP2_CONN_STATE_IS_CLOSING) { /* http2 spec allows sending GOAWAY more than once (for one reason since errors may arise after sending the first one) */ h2o_http2_encode_goaway_frame(&conn->_write.buf, conn->pull_stream_ids.max_open, errnum, additional_data); h2o_http2_conn_request_write(conn); conn->state = H2O_HTTP2_CONN_STATE_HALF_CLOSED; } } static void graceful_shutdown_close_stragglers(h2o_timer_t *entry) { h2o_context_t *ctx = H2O_STRUCT_FROM_MEMBER(h2o_context_t, http2._graceful_shutdown_timeout, entry); h2o_linklist_t *node, *next; /* We've sent two GOAWAY frames, close the remaining connections */ for (node = ctx->http2._conns.next; node != &ctx->http2._conns; node = next) { h2o_http2_conn_t *conn = H2O_STRUCT_FROM_MEMBER(h2o_http2_conn_t, _conns, node); next = node->next; close_connection(conn); } } static void graceful_shutdown_resend_goaway(h2o_timer_t *entry) { h2o_context_t *ctx = H2O_STRUCT_FROM_MEMBER(h2o_context_t, http2._graceful_shutdown_timeout, entry); h2o_linklist_t *node; int do_close_stragglers = 0; for (node = ctx->http2._conns.next; node != &ctx->http2._conns; node = node->next) { h2o_http2_conn_t *conn = H2O_STRUCT_FROM_MEMBER(h2o_http2_conn_t, _conns, node); if (conn->state < H2O_HTTP2_CONN_STATE_HALF_CLOSED) { enqueue_goaway(conn, H2O_HTTP2_ERROR_NONE, (h2o_iovec_t){NULL}); do_close_stragglers = 1; } } /* After waiting a second, we still had active connections. If configured, wait one * final timeout before closing the connections */ if (do_close_stragglers && ctx->globalconf->http2.graceful_shutdown_timeout) { h2o_timer_unlink(&ctx->http2._graceful_shutdown_timeout); ctx->http2._graceful_shutdown_timeout.cb = graceful_shutdown_close_stragglers; h2o_timer_link(ctx->loop, ctx->globalconf->http2.graceful_shutdown_timeout, &ctx->http2._graceful_shutdown_timeout); } } static void initiate_graceful_shutdown(h2o_context_t *ctx) { /* draft-16 6.8 * A server that is attempting to gracefully shut down a connection SHOULD send an initial GOAWAY frame with the last stream * identifier set to 231-1 and a NO_ERROR code. This signals to the client that a shutdown is imminent and that no further * requests can be initiated. After waiting at least one round trip time, the server can send another GOAWAY frame with an * updated last stream identifier. This ensures that a connection can be cleanly shut down without losing requests. */ h2o_linklist_t *node; /* only doit once */ if (ctx->http2._graceful_shutdown_timeout.cb != NULL) return; ctx->http2._graceful_shutdown_timeout.cb = graceful_shutdown_resend_goaway; for (node = ctx->http2._conns.next; node != &ctx->http2._conns; node = node->next) { h2o_http2_conn_t *conn = H2O_STRUCT_FROM_MEMBER(h2o_http2_conn_t, _conns, node); if (conn->state < H2O_HTTP2_CONN_STATE_HALF_CLOSED) { h2o_http2_encode_goaway_frame(&conn->_write.buf, INT32_MAX, H2O_HTTP2_ERROR_NONE, (h2o_iovec_t){H2O_STRLIT("graceful shutdown")}); h2o_http2_conn_request_write(conn); } } h2o_timer_link(ctx->loop, 1000, &ctx->http2._graceful_shutdown_timeout); } static void on_idle_timeout(h2o_timer_t *entry) { h2o_http2_conn_t *conn = H2O_STRUCT_FROM_MEMBER(h2o_http2_conn_t, _timeout_entry, entry); enqueue_goaway(conn, H2O_HTTP2_ERROR_NONE, h2o_iovec_init(H2O_STRLIT("idle timeout"))); close_connection(conn); } static void update_idle_timeout(h2o_http2_conn_t *conn) { h2o_timer_unlink(&conn->_timeout_entry); /* always set idle timeout if TLS handshake is in progress */ if (conn->sock->ssl != NULL && h2o_socket_ssl_is_early_data(conn->sock)) goto SetTimeout; /* no need to set timeout if pending requests exist */ if (conn->num_streams.blocked_by_server != 0) return; /* no need to set timeout if write is in flight */ if (conn->_write.buf_in_flight != NULL) return; SetTimeout: conn->_timeout_entry.cb = on_idle_timeout; h2o_timer_link(conn->super.ctx->loop, conn->super.ctx->globalconf->http2.idle_timeout, &conn->_timeout_entry); } static int can_run_requests(h2o_http2_conn_t *conn) { return conn->num_streams.pull.half_closed + conn->num_streams.push.half_closed < conn->super.ctx->globalconf->http2.max_concurrent_requests_per_connection; } static void run_pending_requests(h2o_http2_conn_t *conn) { h2o_linklist_t *link, *lnext; int ran_one_request; do { ran_one_request = 0; for (link = conn->_pending_reqs.next; link != &conn->_pending_reqs && can_run_requests(conn); link = lnext) { /* fetch and detach a pending stream */ h2o_http2_stream_t *stream = H2O_STRUCT_FROM_MEMBER(h2o_http2_stream_t, _link, link); lnext = link->next; /* handle streaming request */ if (stream->req.proceed_req != NULL) { if (conn->num_streams._request_body_in_progress >= 1) continue; conn->num_streams._request_body_in_progress++; stream->_conn_stream_in_progress = 1; update_stream_input_window(conn, stream, conn->super.ctx->globalconf->http2.active_stream_window_size - H2O_HTTP2_SETTINGS_HOST_STREAM_INITIAL_WINDOW_SIZE); } else { if (stream->state < H2O_HTTP2_STREAM_STATE_SEND_HEADERS) { h2o_http2_stream_set_state(conn, stream, H2O_HTTP2_STREAM_STATE_REQ_PENDING); h2o_http2_stream_set_state(conn, stream, H2O_HTTP2_STREAM_STATE_SEND_HEADERS); } } h2o_linklist_unlink(&stream->_link); ran_one_request = 1; /* handle it */ if (!h2o_http2_stream_is_push(stream->stream_id) && conn->pull_stream_ids.max_processed < stream->stream_id) conn->pull_stream_ids.max_processed = stream->stream_id; h2o_process_request(&stream->req); } } while (ran_one_request && !h2o_linklist_is_empty(&conn->_pending_reqs)); } static int reset_stream_if_disregarded(h2o_http2_conn_t *conn, h2o_http2_stream_t *stream) { if (!h2o_http2_stream_is_push(stream->stream_id) && stream->stream_id > conn->pull_stream_ids.max_open) { /* this stream is opened after sending GOAWAY, so ignore it */ h2o_http2_stream_reset(conn, stream); return 1; } return 0; } static void execute_or_enqueue_request_core(h2o_http2_conn_t *conn, h2o_http2_stream_t *stream) { /* TODO schedule the pending reqs using the scheduler */ h2o_linklist_insert(&conn->_pending_reqs, &stream->_link); run_pending_requests(conn); update_idle_timeout(conn); } static void execute_or_enqueue_request(h2o_http2_conn_t *conn, h2o_http2_stream_t *stream) { assert(stream->state == H2O_HTTP2_STREAM_STATE_RECV_HEADERS || stream->state == H2O_HTTP2_STREAM_STATE_REQ_PENDING); if (reset_stream_if_disregarded(conn, stream)) return; h2o_http2_stream_set_state(conn, stream, H2O_HTTP2_STREAM_STATE_REQ_PENDING); if (!stream->blocked_by_server) h2o_http2_stream_set_blocked_by_server(conn, stream, 1); execute_or_enqueue_request_core(conn, stream); } void h2o_http2_conn_register_stream(h2o_http2_conn_t *conn, h2o_http2_stream_t *stream) { khiter_t iter; int r; iter = kh_put(h2o_http2_stream_t, conn->streams, stream->stream_id, &r); assert(iter != kh_end(conn->streams)); kh_val(conn->streams, iter) = stream; } static void preserve_stream_scheduler(h2o_http2_conn_t *conn, h2o_http2_stream_t *src) { assert(h2o_http2_scheduler_is_open(&src->_scheduler)); h2o_http2_stream_t **dst = conn->_recently_closed_streams.streams + conn->_recently_closed_streams.next_slot; if (++conn->_recently_closed_streams.next_slot == HTTP2_CLOSED_STREAM_PRIORITIES) conn->_recently_closed_streams.next_slot = 0; if (*dst != NULL) { assert(h2o_http2_scheduler_is_open(&(*dst)->_scheduler)); h2o_http2_scheduler_close(&(*dst)->_scheduler); } else { *dst = h2o_mem_alloc(offsetof(h2o_http2_stream_t, _scheduler) + sizeof((*dst)->_scheduler)); } (*dst)->stream_id = src->stream_id; h2o_http2_scheduler_relocate(&(*dst)->_scheduler, &src->_scheduler); h2o_http2_scheduler_deactivate(&(*dst)->_scheduler); } void h2o_http2_conn_unregister_stream(h2o_http2_conn_t *conn, h2o_http2_stream_t *stream) { preserve_stream_scheduler(conn, stream); khiter_t iter = kh_get(h2o_http2_stream_t, conn->streams, stream->stream_id); assert(iter != kh_end(conn->streams)); kh_del(h2o_http2_stream_t, conn->streams, iter); if (stream->_conn_stream_in_progress) { h2o_http2_conn_t *conn = (h2o_http2_conn_t *)stream->req.conn; stream->_conn_stream_in_progress = 0; conn->num_streams._request_body_in_progress--; } switch (stream->state) { case H2O_HTTP2_STREAM_STATE_RECV_BODY: if (h2o_linklist_is_linked(&stream->_link)) h2o_linklist_unlink(&stream->_link); /* fallthru */ case H2O_HTTP2_STREAM_STATE_IDLE: case H2O_HTTP2_STREAM_STATE_RECV_HEADERS: assert(!h2o_linklist_is_linked(&stream->_link)); break; case H2O_HTTP2_STREAM_STATE_REQ_PENDING: assert(h2o_linklist_is_linked(&stream->_link)); h2o_linklist_unlink(&stream->_link); break; case H2O_HTTP2_STREAM_STATE_SEND_HEADERS: case H2O_HTTP2_STREAM_STATE_SEND_BODY: case H2O_HTTP2_STREAM_STATE_SEND_BODY_IS_FINAL: case H2O_HTTP2_STREAM_STATE_END_STREAM: if (h2o_linklist_is_linked(&stream->_link)) h2o_linklist_unlink(&stream->_link); break; } if (stream->state != H2O_HTTP2_STREAM_STATE_END_STREAM) h2o_http2_stream_set_state(conn, stream, H2O_HTTP2_STREAM_STATE_END_STREAM); if (conn->state < H2O_HTTP2_CONN_STATE_IS_CLOSING) { run_pending_requests(conn); update_idle_timeout(conn); } } static void close_connection_now(h2o_http2_conn_t *conn) { h2o_http2_stream_t *stream; assert(!h2o_timer_is_linked(&conn->_write.timeout_entry)); kh_foreach_value(conn->streams, stream, { h2o_http2_stream_close(conn, stream); }); assert(conn->num_streams.pull.open == 0); assert(conn->num_streams.pull.half_closed == 0); assert(conn->num_streams.pull.send_body == 0); assert(conn->num_streams.push.half_closed == 0); assert(conn->num_streams.push.send_body == 0); assert(conn->num_streams.priority.open == 0); kh_destroy(h2o_http2_stream_t, conn->streams); assert(conn->_http1_req_input == NULL); h2o_hpack_dispose_header_table(&conn->_input_header_table); h2o_hpack_dispose_header_table(&conn->_output_header_table); assert(h2o_linklist_is_empty(&conn->_pending_reqs)); h2o_timer_unlink(&conn->_timeout_entry); h2o_buffer_dispose(&conn->_write.buf); if (conn->_write.buf_in_flight != NULL) h2o_buffer_dispose(&conn->_write.buf_in_flight); { size_t i; for (i = 0; i < sizeof(conn->_recently_closed_streams.streams) / sizeof(conn->_recently_closed_streams.streams[0]); ++i) { h2o_http2_stream_t *closed_stream = conn->_recently_closed_streams.streams[i]; if (closed_stream == NULL) break; assert(h2o_http2_scheduler_is_open(&closed_stream->_scheduler)); h2o_http2_scheduler_close(&closed_stream->_scheduler); free(closed_stream); } } h2o_http2_scheduler_dispose(&conn->scheduler); assert(h2o_linklist_is_empty(&conn->_write.streams_to_proceed)); assert(!h2o_timer_is_linked(&conn->_write.timeout_entry)); if (conn->_headers_unparsed != NULL) h2o_buffer_dispose(&conn->_headers_unparsed); if (conn->push_memo != NULL) h2o_cache_destroy(conn->push_memo); if (conn->casper != NULL) h2o_http2_casper_destroy(conn->casper); h2o_linklist_unlink(&conn->_conns); if (conn->sock != NULL) h2o_socket_close(conn->sock); free(conn); } int close_connection(h2o_http2_conn_t *conn) { conn->state = H2O_HTTP2_CONN_STATE_IS_CLOSING; if (conn->_write.buf_in_flight != NULL || h2o_timer_is_linked(&conn->_write.timeout_entry)) { /* there is a pending write, let on_write_complete actually close the connection */ } else { close_connection_now(conn); return -1; } return 0; } static void stream_send_error(h2o_http2_conn_t *conn, uint32_t stream_id, int errnum) { assert(stream_id != 0); assert(conn->state < H2O_HTTP2_CONN_STATE_IS_CLOSING); conn->super.ctx->http2.events.protocol_level_errors[-errnum]++; h2o_http2_encode_rst_stream_frame(&conn->_write.buf, stream_id, -errnum); h2o_http2_conn_request_write(conn); } static void request_gathered_write(h2o_http2_conn_t *conn) { assert(conn->state < H2O_HTTP2_CONN_STATE_IS_CLOSING); if (conn->sock->_cb.write == NULL && !h2o_timer_is_linked(&conn->_write.timeout_entry)) { h2o_timer_link(conn->super.ctx->loop, 0, &conn->_write.timeout_entry); } } static int update_stream_output_window(h2o_http2_stream_t *stream, ssize_t delta) { ssize_t cur = h2o_http2_window_get_avail(&stream->output_window); if (h2o_http2_window_update(&stream->output_window, delta) != 0) return -1; if (cur <= 0 && h2o_http2_window_get_avail(&stream->output_window) > 0 && (h2o_http2_stream_has_pending_data(stream) || stream->state == H2O_HTTP2_STREAM_STATE_SEND_BODY_IS_FINAL)) { assert(!h2o_linklist_is_linked(&stream->_link)); h2o_http2_scheduler_activate(&stream->_scheduler); } return 0; } static void handle_request_body_chunk(h2o_http2_conn_t *conn, h2o_http2_stream_t *stream, h2o_iovec_t payload, int is_end_stream) { stream->_req_body.bytes_received += payload.len; /* check size */ if (stream->_req_body.bytes_received > conn->super.ctx->globalconf->max_request_entity_size) { stream_send_error(conn, stream->stream_id, H2O_HTTP2_ERROR_REFUSED_STREAM); h2o_http2_stream_reset(conn, stream); return; } if (stream->req.content_length != SIZE_MAX) { size_t received = stream->_req_body.bytes_received, cl = stream->req.content_length; if (is_end_stream ? (received != cl) : (received > cl)) { stream_send_error(conn, stream->stream_id, H2O_HTTP2_ERROR_PROTOCOL); h2o_http2_stream_reset(conn, stream); return; } } /* update timer */ if (!stream->blocked_by_server) h2o_http2_stream_set_blocked_by_server(conn, stream, 1); /* handle input */ if (is_end_stream) { h2o_http2_stream_set_state(conn, stream, H2O_HTTP2_STREAM_STATE_REQ_PENDING); if (stream->req.proceed_req != NULL) h2o_http2_stream_set_state(conn, stream, H2O_HTTP2_STREAM_STATE_SEND_HEADERS); } if (stream->req.write_req.cb(stream->req.write_req.ctx, payload, is_end_stream) != 0) { stream_send_error(conn, stream->stream_id, H2O_HTTP2_ERROR_STREAM_CLOSED); h2o_http2_stream_reset(conn, stream); } } static int handle_incoming_request(h2o_http2_conn_t *conn, h2o_http2_stream_t *stream, const uint8_t *src, size_t len, const char **err_desc) { int ret, header_exists_map; assert(stream->state == H2O_HTTP2_STREAM_STATE_RECV_HEADERS); header_exists_map = 0; if ((ret = h2o_hpack_parse_request(&stream->req.pool, h2o_hpack_decode_header, &conn->_input_header_table, &stream->req.input.method, &stream->req.input.scheme, &stream->req.input.authority, &stream->req.input.path, &stream->req.headers, &header_exists_map, &stream->req.content_length, &stream->cache_digests, src, len, err_desc)) != 0) { /* all errors except invalid-header-char are connection errors */ if (ret != H2O_HTTP2_ERROR_INVALID_HEADER_CHAR) return ret; } /* handle stream-level errors */ #define EXPECTED_MAP \ (H2O_HPACK_PARSE_HEADERS_METHOD_EXISTS | H2O_HPACK_PARSE_HEADERS_PATH_EXISTS | H2O_HPACK_PARSE_HEADERS_SCHEME_EXISTS) if ((header_exists_map & EXPECTED_MAP) != EXPECTED_MAP) { ret = H2O_HTTP2_ERROR_PROTOCOL; goto SendRSTStream; } #undef EXPECTED_MAP if (conn->num_streams.pull.open > H2O_HTTP2_SETTINGS_HOST_MAX_CONCURRENT_STREAMS) { ret = H2O_HTTP2_ERROR_REFUSED_STREAM; goto SendRSTStream; } /* handle request to send response */ if (ret != 0) { assert(ret == H2O_HTTP2_ERROR_INVALID_HEADER_CHAR); /* fast forward the stream's state so that we can start sending the response */ h2o_http2_stream_set_state(conn, stream, H2O_HTTP2_STREAM_STATE_REQ_PENDING); h2o_http2_stream_set_state(conn, stream, H2O_HTTP2_STREAM_STATE_SEND_HEADERS); h2o_send_error_400(&stream->req, "Invalid Headers", *err_desc, 0); return 0; } if (stream->_req_body.body == NULL) { execute_or_enqueue_request(conn, stream); } else { h2o_http2_stream_set_state(conn, stream, H2O_HTTP2_STREAM_STATE_RECV_BODY); } return 0; SendRSTStream: stream_send_error(conn, stream->stream_id, ret); h2o_http2_stream_reset(conn, stream); return 0; } static int handle_trailing_headers(h2o_http2_conn_t *conn, h2o_http2_stream_t *stream, const uint8_t *src, size_t len, const char **err_desc) { size_t dummy_content_length; int ret; if ((ret = h2o_hpack_parse_request(&stream->req.pool, h2o_hpack_decode_header, &conn->_input_header_table, &stream->req.input.method, &stream->req.input.scheme, &stream->req.input.authority, &stream->req.input.path, &stream->req.headers, NULL, &dummy_content_length, NULL, src, len, err_desc)) != 0) return ret; handle_request_body_chunk(conn, stream, h2o_iovec_init(NULL, 0), 1); return 0; } static ssize_t expect_continuation_of_headers(h2o_http2_conn_t *conn, const uint8_t *src, size_t len, const char **err_desc) { h2o_http2_frame_t frame; ssize_t ret; h2o_http2_stream_t *stream; int hret; if ((ret = h2o_http2_decode_frame(&frame, src, len, H2O_HTTP2_SETTINGS_HOST_MAX_FRAME_SIZE, err_desc)) < 0) return ret; if (frame.type != H2O_HTTP2_FRAME_TYPE_CONTINUATION) { *err_desc = "expected CONTINUATION frame"; return H2O_HTTP2_ERROR_PROTOCOL; } if ((stream = h2o_http2_conn_get_stream(conn, frame.stream_id)) == NULL || !(stream->state == H2O_HTTP2_STREAM_STATE_RECV_HEADERS || stream->state == H2O_HTTP2_STREAM_STATE_RECV_BODY)) { *err_desc = "unexpected stream id in CONTINUATION frame"; return H2O_HTTP2_ERROR_PROTOCOL; } if (conn->_headers_unparsed->size + frame.length <= H2O_MAX_REQLEN) { h2o_buffer_reserve(&conn->_headers_unparsed, frame.length); memcpy(conn->_headers_unparsed->bytes + conn->_headers_unparsed->size, frame.payload, frame.length); conn->_headers_unparsed->size += frame.length; if ((frame.flags & H2O_HTTP2_FRAME_FLAG_END_HEADERS) != 0) { conn->_read_expect = expect_default; if (stream->state == H2O_HTTP2_STREAM_STATE_RECV_HEADERS) { hret = handle_incoming_request(conn, stream, (const uint8_t *)conn->_headers_unparsed->bytes, conn->_headers_unparsed->size, err_desc); } else { hret = handle_trailing_headers(conn, stream, (const uint8_t *)conn->_headers_unparsed->bytes, conn->_headers_unparsed->size, err_desc); } if (hret != 0) ret = hret; h2o_buffer_dispose(&conn->_headers_unparsed); conn->_headers_unparsed = NULL; } } else { /* request is too large (TODO log) */ stream_send_error(conn, stream->stream_id, H2O_HTTP2_ERROR_REFUSED_STREAM); h2o_http2_stream_reset(conn, stream); } return ret; } static void send_window_update(h2o_http2_conn_t *conn, uint32_t stream_id, h2o_http2_window_t *window, size_t delta) { assert(delta <= INT32_MAX); h2o_http2_encode_window_update_frame(&conn->_write.buf, stream_id, (int32_t)delta); h2o_http2_conn_request_write(conn); h2o_http2_window_update(window, delta); } void update_stream_input_window(h2o_http2_conn_t *conn, h2o_http2_stream_t *stream, size_t delta) { stream->input_window.bytes_unnotified += delta; if (stream->input_window.bytes_unnotified >= h2o_http2_window_get_avail(&stream->input_window.window)) { send_window_update(conn, stream->stream_id, &stream->input_window.window, stream->input_window.bytes_unnotified); stream->input_window.bytes_unnotified = 0; } } static void set_priority(h2o_http2_conn_t *conn, h2o_http2_stream_t *stream, const h2o_http2_priority_t *priority, int scheduler_is_open) { h2o_http2_scheduler_node_t *parent_sched = NULL; /* determine the parent */ if (priority->dependency != 0) { h2o_http2_stream_t *parent_stream = h2o_http2_conn_get_stream(conn, priority->dependency); if (parent_stream != NULL) { parent_sched = &parent_stream->_scheduler.node; } else { size_t i; for (i = 0; i < HTTP2_CLOSED_STREAM_PRIORITIES; i++) { if (conn->_recently_closed_streams.streams[i] && conn->_recently_closed_streams.streams[i]->stream_id == priority->dependency) { parent_sched = &conn->_recently_closed_streams.streams[i]->_scheduler.node; break; } } if (parent_sched == NULL) { /* A dependency on a stream that is not currently in the tree - such as a stream in the "idle" state - results in * that stream being given a default priority. (RFC 7540 5.3.1) It is possible for a stream to become closed while * prioritization information that creates a dependency on that stream is in transit. If a stream identified in a * dependency has no associated priority information, then the dependent stream is instead assigned a default * priority. (RFC 7540 5.3.4) */ parent_sched = &conn->scheduler; priority = &h2o_http2_default_priority; } } } else { parent_sched = &conn->scheduler; } /* setup the scheduler */ if (!scheduler_is_open) { h2o_http2_scheduler_open(&stream->_scheduler, parent_sched, priority->weight, priority->exclusive); } else { h2o_http2_scheduler_rebind(&stream->_scheduler, parent_sched, priority->weight, priority->exclusive); } } static void proceed_request(h2o_req_t *req, size_t written, int is_end_stream) { h2o_http2_stream_t *stream = H2O_STRUCT_FROM_MEMBER(h2o_http2_stream_t, req, req); h2o_http2_conn_t *conn = (h2o_http2_conn_t *)stream->req.conn; if (!is_end_stream) { assert(written != 0); update_stream_input_window(conn, stream, written); } if (stream->blocked_by_server && stream->state == H2O_HTTP2_STREAM_STATE_RECV_BODY && h2o_http2_window_get_avail(&stream->input_window.window) > 0) { h2o_http2_stream_set_blocked_by_server(conn, stream, 0); update_idle_timeout(conn); } } static int write_req_non_streaming(void *_req, h2o_iovec_t payload, int is_end_stream) { h2o_http2_stream_t *stream = H2O_STRUCT_FROM_MEMBER(h2o_http2_stream_t, req, _req); if (h2o_buffer_append(&stream->_req_body.body, payload.base, payload.len) == 0) return -1; proceed_request(&stream->req, payload.len, is_end_stream); if (is_end_stream) { stream->req.entity = h2o_iovec_init(stream->_req_body.body->bytes, stream->_req_body.body->size); execute_or_enqueue_request((h2o_http2_conn_t *)stream->req.conn, stream); } return 0; } static int write_req_streaming_pre_dispatch(void *_req, h2o_iovec_t payload, int is_end_stream) { h2o_http2_stream_t *stream = H2O_STRUCT_FROM_MEMBER(h2o_http2_stream_t, req, _req); if (h2o_buffer_append(&stream->_req_body.body, payload.base, payload.len) == 0) return -1; stream->req.entity = h2o_iovec_init(stream->_req_body.body->bytes, stream->_req_body.body->size); /* mark that we have seen eos */ if (is_end_stream) stream->req.proceed_req = NULL; return 0; } static int write_req_first(void *_req, h2o_iovec_t payload, int is_end_stream) { h2o_http2_stream_t *stream = H2O_STRUCT_FROM_MEMBER(h2o_http2_stream_t, req, _req); h2o_http2_conn_t *conn = (h2o_http2_conn_t *)stream->req.conn; h2o_handler_t *first_handler; /* if possible, switch to either streaming request body mode */ if (!is_end_stream && (first_handler = h2o_get_first_handler(&stream->req)) != NULL && first_handler->supports_request_streaming) { if (h2o_buffer_append(&stream->_req_body.body, payload.base, payload.len) == 0) return -1; stream->req.entity = h2o_iovec_init(stream->_req_body.body->bytes, stream->_req_body.body->size); stream->req.write_req.cb = write_req_streaming_pre_dispatch; stream->req.proceed_req = proceed_request; if (!reset_stream_if_disregarded(conn, stream)) execute_or_enqueue_request_core(conn, stream); return 0; } /* TODO elect input streams one by one for non-streaming case as well? */ update_stream_input_window(conn, stream, conn->super.ctx->globalconf->http2.active_stream_window_size - H2O_HTTP2_SETTINGS_HOST_STREAM_INITIAL_WINDOW_SIZE); stream->req.write_req.cb = write_req_non_streaming; return write_req_non_streaming(stream->req.write_req.ctx, payload, is_end_stream); } static int handle_data_frame(h2o_http2_conn_t *conn, h2o_http2_frame_t *frame, const char **err_desc) { h2o_http2_data_payload_t payload; h2o_http2_stream_t *stream; int ret; if ((ret = h2o_http2_decode_data_payload(&payload, frame, err_desc)) != 0) return ret; /* update connection-level window */ h2o_http2_window_consume_window(&conn->_input_window, frame->length); if (h2o_http2_window_get_avail(&conn->_input_window) <= H2O_HTTP2_SETTINGS_HOST_CONNECTION_WINDOW_SIZE / 2) send_window_update(conn, 0, &conn->_input_window, H2O_HTTP2_SETTINGS_HOST_CONNECTION_WINDOW_SIZE - h2o_http2_window_get_avail(&conn->_input_window)); /* check state */ if ((stream = h2o_http2_conn_get_stream(conn, frame->stream_id)) == NULL) { if (frame->stream_id <= conn->pull_stream_ids.max_open) { stream_send_error(conn, frame->stream_id, H2O_HTTP2_ERROR_STREAM_CLOSED); return 0; } else { *err_desc = "invalid DATA frame"; return H2O_HTTP2_ERROR_PROTOCOL; } } if (stream->state != H2O_HTTP2_STREAM_STATE_RECV_BODY) { stream_send_error(conn, frame->stream_id, H2O_HTTP2_ERROR_STREAM_CLOSED); h2o_http2_stream_reset(conn, stream); return 0; } /* update stream-level window (doing it here could end up in sending multiple WINDOW_UPDATE frames if the receive window is * fully-used, but no need to worry; in such case we'd be sending ACKs at a very fast rate anyways) */ h2o_http2_window_consume_window(&stream->input_window.window, frame->length); if (frame->length != payload.length) update_stream_input_window(conn, stream, frame->length - payload.length); /* actually handle the input */ if (payload.length != 0 || (frame->flags & H2O_HTTP2_FRAME_FLAG_END_STREAM) != 0) handle_request_body_chunk(conn, stream, h2o_iovec_init(payload.data, payload.length), (frame->flags & H2O_HTTP2_FRAME_FLAG_END_STREAM) != 0); return 0; } static int handle_headers_frame(h2o_http2_conn_t *conn, h2o_http2_frame_t *frame, const char **err_desc) { h2o_http2_headers_payload_t payload; h2o_http2_stream_t *stream; int ret; /* decode */ if ((ret = h2o_http2_decode_headers_payload(&payload, frame, err_desc)) != 0) return ret; if ((frame->stream_id & 1) == 0) { *err_desc = "invalid stream id in HEADERS frame"; return H2O_HTTP2_ERROR_PROTOCOL; } if (!(conn->pull_stream_ids.max_open < frame->stream_id)) { if ((stream = h2o_http2_conn_get_stream(conn, frame->stream_id)) != NULL && stream->state == H2O_HTTP2_STREAM_STATE_RECV_BODY) { /* is a trailer */ if ((frame->flags & H2O_HTTP2_FRAME_FLAG_END_STREAM) == 0) { *err_desc = "trailing HEADERS frame MUST have END_STREAM flag set"; return H2O_HTTP2_ERROR_PROTOCOL; } stream->req.entity = h2o_iovec_init(stream->_req_body.body->bytes, stream->_req_body.body->size); if ((frame->flags & H2O_HTTP2_FRAME_FLAG_END_HEADERS) == 0) goto PREPARE_FOR_CONTINUATION; return handle_trailing_headers(conn, stream, payload.headers, payload.headers_len, err_desc); } else { *err_desc = "invalid stream id in HEADERS frame"; return H2O_HTTP2_ERROR_STREAM_CLOSED; } } if (frame->stream_id == payload.priority.dependency) { *err_desc = "stream cannot depend on itself"; return H2O_HTTP2_ERROR_PROTOCOL; } /* open or determine the stream and prepare */ if ((stream = h2o_http2_conn_get_stream(conn, frame->stream_id)) != NULL) { if ((frame->flags & H2O_HTTP2_FRAME_FLAG_PRIORITY) != 0) { set_priority(conn, stream, &payload.priority, 1); stream->received_priority = payload.priority; } } else { stream = h2o_http2_stream_open(conn, frame->stream_id, NULL, &payload.priority); set_priority(conn, stream, &payload.priority, 0); } h2o_http2_stream_prepare_for_request(conn, stream); stream->req.write_req.cb = write_req_first; stream->req.write_req.ctx = &stream->req; /* setup container for request body if it is expected to arrive */ if ((frame->flags & H2O_HTTP2_FRAME_FLAG_END_STREAM) == 0) h2o_buffer_init(&stream->_req_body.body, &h2o_socket_buffer_prototype); if ((frame->flags & H2O_HTTP2_FRAME_FLAG_END_HEADERS) != 0) { /* request is complete, handle it */ return handle_incoming_request(conn, stream, payload.headers, payload.headers_len, err_desc); } PREPARE_FOR_CONTINUATION: /* request is not complete, store in buffer */ conn->_read_expect = expect_continuation_of_headers; h2o_buffer_init(&conn->_headers_unparsed, &h2o_socket_buffer_prototype); h2o_buffer_reserve(&conn->_headers_unparsed, payload.headers_len); memcpy(conn->_headers_unparsed->bytes, payload.headers, payload.headers_len); conn->_headers_unparsed->size = payload.headers_len; return 0; } static int handle_priority_frame(h2o_http2_conn_t *conn, h2o_http2_frame_t *frame, const char **err_desc) { h2o_http2_priority_t payload; h2o_http2_stream_t *stream; int ret; if ((ret = h2o_http2_decode_priority_payload(&payload, frame, err_desc)) != 0) return ret; if (frame->stream_id == payload.dependency) { *err_desc = "stream cannot depend on itself"; return H2O_HTTP2_ERROR_PROTOCOL; } if ((stream = h2o_http2_conn_get_stream(conn, frame->stream_id)) != NULL) { stream->received_priority = payload; /* ignore priority changes to pushed streams with weight=257, since that is where we are trying to be smarter than the web * browsers */ if (h2o_http2_scheduler_get_weight(&stream->_scheduler) != 257) set_priority(conn, stream, &payload, 1); } else { if (h2o_http2_stream_is_push(frame->stream_id)) { /* Ignore PRIORITY frames for closed or idle pushed streams */ return 0; } else { /* Ignore PRIORITY frames for closed pull streams */ if (frame->stream_id <= conn->pull_stream_ids.max_open) return 0; } if (conn->num_streams.priority.open >= conn->super.ctx->globalconf->http2.max_streams_for_priority) { *err_desc = "too many streams in idle/closed state"; /* RFC 7540 10.5: An endpoint MAY treat activity that is suspicious as a connection error (Section 5.4.1) of type * ENHANCE_YOUR_CALM. */ return H2O_HTTP2_ERROR_ENHANCE_YOUR_CALM; } stream = h2o_http2_stream_open(conn, frame->stream_id, NULL, &payload); set_priority(conn, stream, &payload, 0); } return 0; } static void resume_send(h2o_http2_conn_t *conn) { if (h2o_http2_conn_get_buffer_window(conn) <= 0) return; #if 0 /* TODO reenable this check for performance? */ if (conn->scheduler.list.size == 0) return; #endif request_gathered_write(conn); } static int handle_settings_frame(h2o_http2_conn_t *conn, h2o_http2_frame_t *frame, const char **err_desc) { if (frame->stream_id != 0) { *err_desc = "invalid stream id in SETTINGS frame"; return H2O_HTTP2_ERROR_PROTOCOL; } if ((frame->flags & H2O_HTTP2_FRAME_FLAG_ACK) != 0) { if (frame->length != 0) { *err_desc = "invalid SETTINGS frame (+ACK)"; return H2O_HTTP2_ERROR_FRAME_SIZE; } } else { uint32_t prev_initial_window_size = conn->peer_settings.initial_window_size; /* FIXME handle SETTINGS_HEADER_TABLE_SIZE */ int ret = h2o_http2_update_peer_settings(&conn->peer_settings, frame->payload, frame->length, err_desc); if (ret != 0) return ret; { /* schedule ack */ h2o_iovec_t header_buf = h2o_buffer_reserve(&conn->_write.buf, H2O_HTTP2_FRAME_HEADER_SIZE); h2o_http2_encode_frame_header((void *)header_buf.base, 0, H2O_HTTP2_FRAME_TYPE_SETTINGS, H2O_HTTP2_FRAME_FLAG_ACK, 0); conn->_write.buf->size += H2O_HTTP2_FRAME_HEADER_SIZE; h2o_http2_conn_request_write(conn); } /* apply the change to window size (to all the streams but not the connection, see 6.9.2 of draft-15) */ if (prev_initial_window_size != conn->peer_settings.initial_window_size) { ssize_t delta = (int32_t)conn->peer_settings.initial_window_size - (int32_t)prev_initial_window_size; h2o_http2_stream_t *stream; kh_foreach_value(conn->streams, stream, { update_stream_output_window(stream, delta); }); resume_send(conn); } } return 0; } static int handle_window_update_frame(h2o_http2_conn_t *conn, h2o_http2_frame_t *frame, const char **err_desc) { h2o_http2_window_update_payload_t payload; int ret, err_is_stream_level; if ((ret = h2o_http2_decode_window_update_payload(&payload, frame, err_desc, &err_is_stream_level)) != 0) { if (err_is_stream_level) { h2o_http2_stream_t *stream = h2o_http2_conn_get_stream(conn, frame->stream_id); if (stream != NULL) h2o_http2_stream_reset(conn, stream); stream_send_error(conn, frame->stream_id, ret); return 0; } else { return ret; } } if (frame->stream_id == 0) { if (h2o_http2_window_update(&conn->_write.window, payload.window_size_increment) != 0) { *err_desc = "flow control window overflow"; return H2O_HTTP2_ERROR_FLOW_CONTROL; } } else if (!is_idle_stream_id(conn, frame->stream_id)) { h2o_http2_stream_t *stream = h2o_http2_conn_get_stream(conn, frame->stream_id); if (stream != NULL) { if (update_stream_output_window(stream, payload.window_size_increment) != 0) { h2o_http2_stream_reset(conn, stream); stream_send_error(conn, frame->stream_id, H2O_HTTP2_ERROR_FLOW_CONTROL); return 0; } } } else { *err_desc = "invalid stream id in WINDOW_UPDATE frame"; return H2O_HTTP2_ERROR_PROTOCOL; } resume_send(conn); return 0; } static int handle_goaway_frame(h2o_http2_conn_t *conn, h2o_http2_frame_t *frame, const char **err_desc) { h2o_http2_goaway_payload_t payload; int ret; if ((ret = h2o_http2_decode_goaway_payload(&payload, frame, err_desc)) != 0) return ret; /* stop opening new push streams hereafter */ conn->push_stream_ids.max_open = 0x7ffffffe; return 0; } static int handle_ping_frame(h2o_http2_conn_t *conn, h2o_http2_frame_t *frame, const char **err_desc) { h2o_http2_ping_payload_t payload; int ret; if ((ret = h2o_http2_decode_ping_payload(&payload, frame, err_desc)) != 0) return ret; if ((frame->flags & H2O_HTTP2_FRAME_FLAG_ACK) == 0) { h2o_http2_encode_ping_frame(&conn->_write.buf, 1, payload.data); h2o_http2_conn_request_write(conn); } return 0; } static int handle_rst_stream_frame(h2o_http2_conn_t *conn, h2o_http2_frame_t *frame, const char **err_desc) { h2o_http2_rst_stream_payload_t payload; h2o_http2_stream_t *stream; int ret; if ((ret = h2o_http2_decode_rst_stream_payload(&payload, frame, err_desc)) != 0) return ret; if (is_idle_stream_id(conn, frame->stream_id)) { *err_desc = "unexpected stream id in RST_STREAM frame"; return H2O_HTTP2_ERROR_PROTOCOL; } stream = h2o_http2_conn_get_stream(conn, frame->stream_id); if (stream != NULL) { /* reset the stream */ h2o_http2_stream_reset(conn, stream); } /* TODO log */ return 0; } static int handle_push_promise_frame(h2o_http2_conn_t *conn, h2o_http2_frame_t *frame, const char **err_desc) { *err_desc = "received PUSH_PROMISE frame"; return H2O_HTTP2_ERROR_PROTOCOL; } static int handle_invalid_continuation_frame(h2o_http2_conn_t *conn, h2o_http2_frame_t *frame, const char **err_desc) { *err_desc = "received invalid CONTINUATION frame"; return H2O_HTTP2_ERROR_PROTOCOL; } ssize_t expect_default(h2o_http2_conn_t *conn, const uint8_t *src, size_t len, const char **err_desc) { h2o_http2_frame_t frame; ssize_t ret; static int (*FRAME_HANDLERS[])(h2o_http2_conn_t * conn, h2o_http2_frame_t * frame, const char **err_desc) = { handle_data_frame, /* DATA */ handle_headers_frame, /* HEADERS */ handle_priority_frame, /* PRIORITY */ handle_rst_stream_frame, /* RST_STREAM */ handle_settings_frame, /* SETTINGS */ handle_push_promise_frame, /* PUSH_PROMISE */ handle_ping_frame, /* PING */ handle_goaway_frame, /* GOAWAY */ handle_window_update_frame, /* WINDOW_UPDATE */ handle_invalid_continuation_frame /* CONTINUATION */ }; if ((ret = h2o_http2_decode_frame(&frame, src, len, H2O_HTTP2_SETTINGS_HOST_MAX_FRAME_SIZE, err_desc)) < 0) return ret; if (frame.type < sizeof(FRAME_HANDLERS) / sizeof(FRAME_HANDLERS[0])) { int hret = FRAME_HANDLERS[frame.type](conn, &frame, err_desc); if (hret != 0) ret = hret; } else { h2o_error_printf("skipping frame (type:%d)\n", frame.type); } return ret; } static ssize_t expect_preface(h2o_http2_conn_t *conn, const uint8_t *src, size_t len, const char **err_desc) { if (len < CONNECTION_PREFACE.len) { return H2O_HTTP2_ERROR_INCOMPLETE; } if (memcmp(src, CONNECTION_PREFACE.base, CONNECTION_PREFACE.len) != 0) { return H2O_HTTP2_ERROR_PROTOCOL_CLOSE_IMMEDIATELY; } { /* send SETTINGS and connection-level WINDOW_UPDATE */ h2o_iovec_t vec = h2o_buffer_reserve(&conn->_write.buf, SERVER_PREFACE.len); memcpy(vec.base, SERVER_PREFACE.base, SERVER_PREFACE.len); conn->_write.buf->size += SERVER_PREFACE.len; if (conn->http2_origin_frame) { /* write origin frame */ h2o_http2_encode_origin_frame(&conn->_write.buf, *conn->http2_origin_frame); } h2o_http2_conn_request_write(conn); } conn->_read_expect = expect_default; return CONNECTION_PREFACE.len; } static int parse_input(h2o_http2_conn_t *conn) { /* handle the input */ while (conn->state < H2O_HTTP2_CONN_STATE_IS_CLOSING && conn->sock->input->size != 0) { /* process a frame */ const char *err_desc = NULL; ssize_t ret = conn->_read_expect(conn, (uint8_t *)conn->sock->input->bytes, conn->sock->input->size, &err_desc); if (ret == H2O_HTTP2_ERROR_INCOMPLETE) { break; } else if (ret < 0) { if (ret != H2O_HTTP2_ERROR_PROTOCOL_CLOSE_IMMEDIATELY) { enqueue_goaway(conn, (int)ret, err_desc != NULL ? (h2o_iovec_t){(char *)err_desc, strlen(err_desc)} : (h2o_iovec_t){NULL}); } return close_connection(conn); } /* advance to the next frame */ h2o_buffer_consume(&conn->sock->input, ret); } return 0; } static void on_read(h2o_socket_t *sock, const char *err) { h2o_http2_conn_t *conn = sock->data; if (err != NULL) { conn->super.ctx->http2.events.read_closed++; h2o_socket_read_stop(conn->sock); close_connection(conn); return; } /* dispatch requests blocked by 425 when TLS handshake is complete */ if (!h2o_linklist_is_empty(&conn->early_data.blocked_streams)) { assert(conn->sock->ssl != NULL); if (!h2o_socket_ssl_is_early_data(conn->sock)) { while (conn->early_data.blocked_streams.next != &conn->early_data.blocked_streams) { h2o_http2_stream_t *stream = H2O_STRUCT_FROM_MEMBER(h2o_http2_stream_t, _link, conn->early_data.blocked_streams.next); h2o_linklist_unlink(&stream->_link); h2o_replay_request(&stream->req); } } } if (parse_input(conn) != 0) return; update_idle_timeout(conn); /* write immediately, if there is no write in flight and if pending write exists */ if (h2o_timer_is_linked(&conn->_write.timeout_entry)) { h2o_timer_unlink(&conn->_write.timeout_entry); do_emit_writereq(conn); } } static void on_upgrade_complete(void *_conn, h2o_socket_t *sock, size_t reqsize) { h2o_http2_conn_t *conn = _conn; if (sock == NULL) { close_connection(conn); return; } conn->sock = sock; sock->data = conn; conn->_http1_req_input = sock->input; h2o_buffer_init(&sock->input, &h2o_socket_buffer_prototype); /* setup inbound */ h2o_socket_read_start(conn->sock, on_read); /* handle the request */ execute_or_enqueue_request(conn, h2o_http2_conn_get_stream(conn, 1)); if (conn->_http1_req_input->size > reqsize) { size_t remaining_bytes = conn->_http1_req_input->size - reqsize; h2o_buffer_reserve(&sock->input, remaining_bytes); memcpy(sock->input->bytes, conn->_http1_req_input->bytes + reqsize, remaining_bytes); sock->input->size += remaining_bytes; on_read(conn->sock, NULL); } } void h2o_http2_conn_request_write(h2o_http2_conn_t *conn) { if (conn->state == H2O_HTTP2_CONN_STATE_IS_CLOSING) return; request_gathered_write(conn); } void h2o_http2_conn_register_for_proceed_callback(h2o_http2_conn_t *conn, h2o_http2_stream_t *stream) { h2o_http2_conn_request_write(conn); if (h2o_http2_stream_has_pending_data(stream) || stream->state >= H2O_HTTP2_STREAM_STATE_SEND_BODY_IS_FINAL) { if (h2o_http2_window_get_avail(&stream->output_window) > 0) { assert(!h2o_linklist_is_linked(&stream->_link)); h2o_http2_scheduler_activate(&stream->_scheduler); } } else { h2o_linklist_insert(&conn->_write.streams_to_proceed, &stream->_link); } } void h2o_http2_conn_register_for_replay(h2o_http2_conn_t *conn, h2o_http2_stream_t *stream) { if (conn->sock->ssl != NULL && h2o_socket_ssl_is_early_data(conn->sock)) { h2o_linklist_insert(&conn->early_data.blocked_streams, &stream->_link); } else { h2o_replay_request_deferred(&stream->req); } } static void on_notify_write(h2o_socket_t *sock, const char *err) { h2o_http2_conn_t *conn = sock->data; if (err != NULL) { close_connection_now(conn); return; } do_emit_writereq(conn); } static void on_write_complete(h2o_socket_t *sock, const char *err) { h2o_http2_conn_t *conn = sock->data; assert(conn->_write.buf_in_flight != NULL); /* close by error if necessary */ if (err != NULL) { conn->super.ctx->http2.events.write_closed++; close_connection_now(conn); return; } /* reset the other memory pool */ h2o_buffer_dispose(&conn->_write.buf_in_flight); assert(conn->_write.buf_in_flight == NULL); /* call the proceed callback of the streams that have been flushed (while unlinking them from the list) */ if (conn->state < H2O_HTTP2_CONN_STATE_IS_CLOSING) { while (!h2o_linklist_is_empty(&conn->_write.streams_to_proceed)) { h2o_http2_stream_t *stream = H2O_STRUCT_FROM_MEMBER(h2o_http2_stream_t, _link, conn->_write.streams_to_proceed.next); assert(!h2o_http2_stream_has_pending_data(stream)); h2o_linklist_unlink(&stream->_link); h2o_http2_stream_proceed(conn, stream); } } /* update the timeout now that the states have been updated */ update_idle_timeout(conn); /* cancel the write callback if scheduled (as the generator may have scheduled a write just before this function gets called) */ if (h2o_timer_is_linked(&conn->_write.timeout_entry)) h2o_timer_unlink(&conn->_write.timeout_entry); #if !H2O_USE_LIBUV if (conn->state == H2O_HTTP2_CONN_STATE_OPEN) { if (conn->_write.buf->size != 0 || h2o_http2_scheduler_is_active(&conn->scheduler)) h2o_socket_notify_write(sock, on_notify_write); return; } #endif /* write more, if possible */ do_emit_writereq(conn); } static int emit_writereq_of_openref(h2o_http2_scheduler_openref_t *ref, int *still_is_active, void *cb_arg) { h2o_http2_conn_t *conn = cb_arg; h2o_http2_stream_t *stream = H2O_STRUCT_FROM_MEMBER(h2o_http2_stream_t, _scheduler, ref); assert(h2o_http2_stream_has_pending_data(stream) || stream->state >= H2O_HTTP2_STREAM_STATE_SEND_BODY_IS_FINAL); *still_is_active = 0; h2o_http2_stream_send_pending_data(conn, stream); if (h2o_http2_stream_has_pending_data(stream) || stream->state == H2O_HTTP2_STREAM_STATE_SEND_BODY_IS_FINAL) { if (h2o_http2_window_get_avail(&stream->output_window) <= 0) { /* is blocked */ } else { *still_is_active = 1; } } else { if (stream->state == H2O_HTTP2_STREAM_STATE_END_STREAM && stream->req.send_server_timing) { h2o_header_t trailers[1]; size_t num_trailers = 0; h2o_iovec_t server_timing; if ((server_timing = h2o_build_server_timing_trailer(&stream->req, NULL, 0, NULL, 0)).len != 0) { static const h2o_iovec_t name = {H2O_STRLIT("server-timing")}; trailers[num_trailers++] = (h2o_header_t){(h2o_iovec_t *)&name, NULL, server_timing}; } h2o_hpack_flatten_trailers(&conn->_write.buf, &conn->_output_header_table, stream->stream_id, conn->peer_settings.max_frame_size, trailers, num_trailers); } h2o_linklist_insert(&conn->_write.streams_to_proceed, &stream->_link); } return h2o_http2_conn_get_buffer_window(conn) > 0 ? 0 : -1; } void do_emit_writereq(h2o_http2_conn_t *conn) { assert(conn->_write.buf_in_flight == NULL); /* push DATA frames */ if (conn->state < H2O_HTTP2_CONN_STATE_IS_CLOSING && h2o_http2_conn_get_buffer_window(conn) > 0) h2o_http2_scheduler_run(&conn->scheduler, emit_writereq_of_openref, conn); if (conn->_write.buf->size != 0) { /* write and wait for completion */ h2o_iovec_t buf = {conn->_write.buf->bytes, conn->_write.buf->size}; h2o_socket_write(conn->sock, &buf, 1, on_write_complete); conn->_write.buf_in_flight = conn->_write.buf; h2o_buffer_init(&conn->_write.buf, &h2o_http2_wbuf_buffer_prototype); update_idle_timeout(conn); } /* close the connection if necessary */ switch (conn->state) { case H2O_HTTP2_CONN_STATE_OPEN: break; case H2O_HTTP2_CONN_STATE_HALF_CLOSED: if (conn->num_streams.pull.open + conn->num_streams.push.open != 0) break; conn->state = H2O_HTTP2_CONN_STATE_IS_CLOSING; /* fall-thru */ case H2O_HTTP2_CONN_STATE_IS_CLOSING: close_connection_now(conn); break; } } static void emit_writereq(h2o_timer_t *entry) { h2o_http2_conn_t *conn = H2O_STRUCT_FROM_MEMBER(h2o_http2_conn_t, _write.timeout_entry, entry); do_emit_writereq(conn); } static socklen_t get_sockname(h2o_conn_t *_conn, struct sockaddr *sa) { h2o_http2_conn_t *conn = (void *)_conn; return h2o_socket_getsockname(conn->sock, sa); } static socklen_t get_peername(h2o_conn_t *_conn, struct sockaddr *sa) { h2o_http2_conn_t *conn = (void *)_conn; return h2o_socket_getpeername(conn->sock, sa); } static h2o_socket_t *get_socket(h2o_conn_t *_conn) { h2o_http2_conn_t *conn = (void *)_conn; return conn->sock; } #define DEFINE_TLS_LOGGER(name) \ static h2o_iovec_t log_##name(h2o_req_t *req) \ { \ h2o_http2_conn_t *conn = (void *)req->conn; \ return h2o_socket_log_ssl_##name(conn->sock, &req->pool); \ } DEFINE_TLS_LOGGER(protocol_version) DEFINE_TLS_LOGGER(session_reused) DEFINE_TLS_LOGGER(cipher) DEFINE_TLS_LOGGER(cipher_bits) DEFINE_TLS_LOGGER(session_id) #undef DEFINE_TLS_LOGGER static h2o_iovec_t log_stream_id(h2o_req_t *req) { h2o_http2_stream_t *stream = H2O_STRUCT_FROM_MEMBER(h2o_http2_stream_t, req, req); char *s = h2o_mem_alloc_pool(&stream->req.pool, *s, sizeof(H2O_UINT32_LONGEST_STR)); size_t len = (size_t)sprintf(s, "%" PRIu32, stream->stream_id); return h2o_iovec_init(s, len); } static h2o_iovec_t log_priority_received(h2o_req_t *req) { h2o_http2_stream_t *stream = H2O_STRUCT_FROM_MEMBER(h2o_http2_stream_t, req, req); char *s = h2o_mem_alloc_pool(&stream->req.pool, *s, sizeof("1:" H2O_UINT32_LONGEST_STR ":" H2O_UINT16_LONGEST_STR)); size_t len = (size_t)sprintf(s, "%c:%" PRIu32 ":%" PRIu16, stream->received_priority.exclusive ? '1' : '0', stream->received_priority.dependency, stream->received_priority.weight); return h2o_iovec_init(s, len); } static h2o_iovec_t log_priority_received_exclusive(h2o_req_t *req) { h2o_http2_stream_t *stream = H2O_STRUCT_FROM_MEMBER(h2o_http2_stream_t, req, req); return h2o_iovec_init(stream->received_priority.exclusive ? "1" : "0", 1); } static h2o_iovec_t log_priority_received_parent(h2o_req_t *req) { h2o_http2_stream_t *stream = H2O_STRUCT_FROM_MEMBER(h2o_http2_stream_t, req, req); char *s = h2o_mem_alloc_pool(&stream->req.pool, *s, sizeof(H2O_UINT32_LONGEST_STR)); size_t len = sprintf(s, "%" PRIu32, stream->received_priority.dependency); return h2o_iovec_init(s, len); } static h2o_iovec_t log_priority_received_weight(h2o_req_t *req) { h2o_http2_stream_t *stream = H2O_STRUCT_FROM_MEMBER(h2o_http2_stream_t, req, req); char *s = h2o_mem_alloc_pool(&stream->req.pool, *s, sizeof(H2O_UINT16_LONGEST_STR)); size_t len = sprintf(s, "%" PRIu16, stream->received_priority.weight); return h2o_iovec_init(s, len); } static uint32_t get_parent_stream_id(h2o_http2_conn_t *conn, h2o_http2_stream_t *stream) { h2o_http2_scheduler_node_t *parent_sched = h2o_http2_scheduler_get_parent(&stream->_scheduler); if (parent_sched == &conn->scheduler) { return 0; } else { h2o_http2_stream_t *parent_stream = H2O_STRUCT_FROM_MEMBER(h2o_http2_stream_t, _scheduler, parent_sched); return parent_stream->stream_id; } } static h2o_iovec_t log_priority_actual(h2o_req_t *req) { h2o_http2_conn_t *conn = (void *)req->conn; h2o_http2_stream_t *stream = H2O_STRUCT_FROM_MEMBER(h2o_http2_stream_t, req, req); char *s = h2o_mem_alloc_pool(&stream->req.pool, *s, sizeof(H2O_UINT32_LONGEST_STR ":" H2O_UINT16_LONGEST_STR)); size_t len = (size_t)sprintf(s, "%" PRIu32 ":%" PRIu16, get_parent_stream_id(conn, stream), h2o_http2_scheduler_get_weight(&stream->_scheduler)); return h2o_iovec_init(s, len); } static h2o_iovec_t log_priority_actual_parent(h2o_req_t *req) { h2o_http2_conn_t *conn = (void *)req->conn; h2o_http2_stream_t *stream = H2O_STRUCT_FROM_MEMBER(h2o_http2_stream_t, req, req); char *s = h2o_mem_alloc_pool(&stream->req.pool, *s, sizeof(H2O_UINT32_LONGEST_STR)); size_t len = (size_t)sprintf(s, "%" PRIu32, get_parent_stream_id(conn, stream)); return h2o_iovec_init(s, len); } static h2o_iovec_t log_priority_actual_weight(h2o_req_t *req) { h2o_http2_stream_t *stream = H2O_STRUCT_FROM_MEMBER(h2o_http2_stream_t, req, req); char *s = h2o_mem_alloc_pool(&stream->req.pool, *s, sizeof(H2O_UINT16_LONGEST_STR)); size_t len = (size_t)sprintf(s, "%" PRIu16, h2o_http2_scheduler_get_weight(&stream->_scheduler)); return h2o_iovec_init(s, len); } static h2o_http2_conn_t *create_conn(h2o_context_t *ctx, h2o_hostconf_t **hosts, h2o_socket_t *sock, struct timeval connected_at) { static const h2o_conn_callbacks_t callbacks = { get_sockname, /* stringify address */ get_peername, /* ditto */ push_path, /* HTTP2 push */ get_socket, /* get underlying socket */ h2o_http2_get_debug_state, /* get debug state */ {{ {log_protocol_version, log_session_reused, log_cipher, log_cipher_bits, log_session_id}, /* ssl */ {NULL}, /* http1 */ {log_stream_id, log_priority_received, log_priority_received_exclusive, log_priority_received_parent, log_priority_received_weight, log_priority_actual, log_priority_actual_parent, log_priority_actual_weight} /* http2 */ }} /* loggers */ }; h2o_http2_conn_t *conn = (void *)h2o_create_connection(sizeof(*conn), ctx, hosts, connected_at, &callbacks); memset((char *)conn + sizeof(conn->super), 0, sizeof(*conn) - sizeof(conn->super)); conn->sock = sock; conn->peer_settings = H2O_HTTP2_SETTINGS_DEFAULT; conn->streams = kh_init(h2o_http2_stream_t); h2o_http2_scheduler_init(&conn->scheduler); conn->state = H2O_HTTP2_CONN_STATE_OPEN; h2o_linklist_insert(&ctx->http2._conns, &conn->_conns); conn->_read_expect = expect_preface; conn->_input_header_table.hpack_capacity = conn->_input_header_table.hpack_max_capacity = H2O_HTTP2_SETTINGS_DEFAULT.header_table_size; h2o_http2_window_init(&conn->_input_window, H2O_HTTP2_SETTINGS_HOST_CONNECTION_WINDOW_SIZE); conn->_output_header_table.hpack_capacity = H2O_HTTP2_SETTINGS_DEFAULT.header_table_size; h2o_linklist_init_anchor(&conn->_pending_reqs); h2o_buffer_init(&conn->_write.buf, &h2o_http2_wbuf_buffer_prototype); h2o_linklist_init_anchor(&conn->_write.streams_to_proceed); conn->_write.timeout_entry.cb = emit_writereq; h2o_http2_window_init(&conn->_write.window, conn->peer_settings.initial_window_size); h2o_linklist_init_anchor(&conn->early_data.blocked_streams); return conn; } static int update_push_memo(h2o_http2_conn_t *conn, h2o_req_t *src_req, const char *abspath, size_t abspath_len) { if (conn->push_memo == NULL) conn->push_memo = h2o_cache_create(0, 1024, 1, NULL); /* uses the hash as the key */ h2o_cache_hashcode_t url_hash = h2o_cache_calchash(src_req->input.scheme->name.base, src_req->input.scheme->name.len) ^ h2o_cache_calchash(src_req->input.authority.base, src_req->input.authority.len) ^ h2o_cache_calchash(abspath, abspath_len); return h2o_cache_set(conn->push_memo, 0, h2o_iovec_init(&url_hash, sizeof(url_hash)), url_hash, h2o_iovec_init(NULL, 0)); } static void push_path(h2o_req_t *src_req, const char *abspath, size_t abspath_len, int is_critical) { h2o_http2_conn_t *conn = (void *)src_req->conn; h2o_http2_stream_t *src_stream = H2O_STRUCT_FROM_MEMBER(h2o_http2_stream_t, req, src_req); /* RFC 7540 8.2.1: PUSH_PROMISE frames can be sent by the server in response to any client-initiated stream */ if (h2o_http2_stream_is_push(src_stream->stream_id)) return; if (!src_stream->req.hostconf->http2.push_preload || !conn->peer_settings.enable_push || conn->num_streams.push.open >= conn->peer_settings.max_concurrent_streams) return; if (conn->state >= H2O_HTTP2_CONN_STATE_IS_CLOSING) return; if (conn->push_stream_ids.max_open >= 0x7ffffff0) return; if (!(h2o_linklist_is_empty(&conn->_pending_reqs) && can_run_requests(conn))) return; if (h2o_find_header(&src_stream->req.headers, H2O_TOKEN_X_FORWARDED_FOR, -1) != -1) return; if (src_stream->cache_digests != NULL) { h2o_iovec_t url = h2o_concat(&src_stream->req.pool, src_stream->req.input.scheme->name, h2o_iovec_init(H2O_STRLIT("://")), src_stream->req.input.authority, h2o_iovec_init(abspath, abspath_len)); if (h2o_cache_digests_lookup_by_url(src_stream->cache_digests, url.base, url.len) == H2O_CACHE_DIGESTS_STATE_FRESH) return; } /* delayed initialization of casper (cookie-based), that MAY be used together to cache-digests */ if (src_stream->req.hostconf->http2.casper.capacity_bits != 0) { if (!src_stream->pull.casper_is_ready) { src_stream->pull.casper_is_ready = 1; if (conn->casper == NULL) h2o_http2_conn_init_casper(conn, src_stream->req.hostconf->http2.casper.capacity_bits); ssize_t header_index; for (header_index = -1; (header_index = h2o_find_header(&src_stream->req.headers, H2O_TOKEN_COOKIE, header_index)) != -1;) { h2o_header_t *header = src_stream->req.headers.entries + header_index; h2o_http2_casper_consume_cookie(conn->casper, header->value.base, header->value.len); } } } /* update the push memo, and if it already pushed on the same connection, return */ if (update_push_memo(conn, &src_stream->req, abspath, abspath_len)) return; /* open the stream */ h2o_http2_stream_t *stream = h2o_http2_stream_open(conn, conn->push_stream_ids.max_open + 2, NULL, &h2o_http2_default_priority); stream->received_priority.dependency = src_stream->stream_id; stream->push.parent_stream_id = src_stream->stream_id; if (is_critical) { h2o_http2_scheduler_open(&stream->_scheduler, &conn->scheduler, 257, 0); } else { h2o_http2_scheduler_open(&stream->_scheduler, &src_stream->_scheduler.node, 16, 0); } h2o_http2_stream_prepare_for_request(conn, stream); /* setup request */ stream->req.input.method = (h2o_iovec_t){H2O_STRLIT("GET")}; stream->req.input.scheme = src_stream->req.input.scheme; stream->req.input.authority = h2o_strdup(&stream->req.pool, src_stream->req.input.authority.base, src_stream->req.input.authority.len); stream->req.input.path = h2o_strdup(&stream->req.pool, abspath, abspath_len); stream->req.version = 0x200; { /* copy headers that may affect the response (of a cacheable response) */ size_t i; for (i = 0; i != src_stream->req.headers.size; ++i) { h2o_header_t *src_header = src_stream->req.headers.entries + i; /* currently only predefined headers are copiable */ if (h2o_iovec_is_token(src_header->name)) { h2o_token_t *token = H2O_STRUCT_FROM_MEMBER(h2o_token_t, buf, src_header->name); if (token->flags.copy_for_push_request) h2o_add_header(&stream->req.pool, &stream->req.headers, token, NULL, h2o_strdup(&stream->req.pool, src_header->value.base, src_header->value.len).base, src_header->value.len); } } } execute_or_enqueue_request(conn, stream); /* send push-promise ASAP (before the parent stream gets closed), even if execute_or_enqueue_request did not trigger the * invocation of send_headers */ if (!stream->push.promise_sent && stream->state != H2O_HTTP2_STREAM_STATE_END_STREAM) h2o_http2_stream_send_push_promise(conn, stream); } static int foreach_request(h2o_context_t *ctx, int (*cb)(h2o_req_t *req, void *cbdata), void *cbdata) { h2o_linklist_t *node; for (node = ctx->http2._conns.next; node != &ctx->http2._conns; node = node->next) { h2o_http2_conn_t *conn = H2O_STRUCT_FROM_MEMBER(h2o_http2_conn_t, _conns, node); h2o_http2_stream_t *stream; kh_foreach_value(conn->streams, stream, { int ret = cb(&stream->req, cbdata); if (ret != 0) return ret; }); } return 0; } void h2o_http2_accept(h2o_accept_ctx_t *ctx, h2o_socket_t *sock, struct timeval connected_at) { h2o_http2_conn_t *conn = create_conn(ctx->ctx, ctx->hosts, sock, connected_at); conn->http2_origin_frame = ctx->http2_origin_frame; sock->data = conn; h2o_socket_read_start(conn->sock, on_read); update_idle_timeout(conn); if (sock->input->size != 0) on_read(sock, 0); } int h2o_http2_handle_upgrade(h2o_req_t *req, struct timeval connected_at) { h2o_http2_conn_t *http2conn = create_conn(req->conn->ctx, req->conn->hosts, NULL, connected_at); h2o_http2_stream_t *stream; ssize_t connection_index, settings_index; h2o_iovec_t settings_decoded; const char *err_desc; assert(req->version < 0x200); /* from HTTP/1.x */ /* check that "HTTP2-Settings" is declared in the connection header */ connection_index = h2o_find_header(&req->headers, H2O_TOKEN_CONNECTION, -1); assert(connection_index != -1); if (!h2o_contains_token(req->headers.entries[connection_index].value.base, req->headers.entries[connection_index].value.len, H2O_STRLIT("http2-settings"), ',')) { goto Error; } /* decode the settings */ if ((settings_index = h2o_find_header(&req->headers, H2O_TOKEN_HTTP2_SETTINGS, -1)) == -1) { goto Error; } if ((settings_decoded = h2o_decode_base64url(&req->pool, req->headers.entries[settings_index].value.base, req->headers.entries[settings_index].value.len)) .base == NULL) { goto Error; } if (h2o_http2_update_peer_settings(&http2conn->peer_settings, (uint8_t *)settings_decoded.base, settings_decoded.len, &err_desc) != 0) { goto Error; } /* open the stream, now that the function is guaranteed to succeed */ stream = h2o_http2_stream_open(http2conn, 1, req, &h2o_http2_default_priority); h2o_http2_scheduler_open(&stream->_scheduler, &http2conn->scheduler, h2o_http2_default_priority.weight, 0); h2o_http2_stream_prepare_for_request(http2conn, stream); /* send response */ req->res.status = 101; req->res.reason = "Switching Protocols"; h2o_add_header(&req->pool, &req->res.headers, H2O_TOKEN_UPGRADE, NULL, H2O_STRLIT("h2c")); h2o_http1_upgrade(req, (h2o_iovec_t *)&SERVER_PREFACE, 1, on_upgrade_complete, http2conn); return 0; Error: h2o_linklist_unlink(&http2conn->_conns); kh_destroy(h2o_http2_stream_t, http2conn->streams); free(http2conn); return -1; }
1
13,657
I think you missed this.
h2o-h2o
c
@@ -145,6 +145,13 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http return _requestStream.ReadAsync(buffer, offset, count, cancellationToken); } +#if NETCOREAPP2_1 + public override ValueTask<int> ReadAsync(Memory<byte> destination, CancellationToken cancellationToken = default) + { + return _requestStream.ReadAsync(destination, cancellationToken); + } +#endif + public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) { return _requestStream.CopyToAsync(destination, bufferSize, cancellationToken);
1
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.IO; using System.Threading; using System.Threading.Tasks; namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http { internal class HttpUpgradeStream : Stream { private readonly Stream _requestStream; private readonly Stream _responseStream; public HttpUpgradeStream(Stream requestStream, Stream responseStream) { _requestStream = requestStream; _responseStream = responseStream; } public override bool CanRead { get { return _requestStream.CanRead; } } public override bool CanSeek { get { return _requestStream.CanSeek; } } public override bool CanTimeout { get { return _responseStream.CanTimeout || _requestStream.CanTimeout; } } public override bool CanWrite { get { return _responseStream.CanWrite; } } public override long Length { get { return _requestStream.Length; } } public override long Position { get { return _requestStream.Position; } set { _requestStream.Position = value; } } public override int ReadTimeout { get { return _requestStream.ReadTimeout; } set { _requestStream.ReadTimeout = value; } } public override int WriteTimeout { get { return _responseStream.WriteTimeout; } set { _responseStream.WriteTimeout = value; } } protected override void Dispose(bool disposing) { if (disposing) { _requestStream.Dispose(); _responseStream.Dispose(); } } public override void Flush() { _responseStream.Flush(); } public override Task FlushAsync(CancellationToken cancellationToken) { return _responseStream.FlushAsync(cancellationToken); } public override void Close() { _requestStream.Close(); _responseStream.Close(); } public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { return _requestStream.BeginRead(buffer, offset, count, callback, state); } public override int EndRead(IAsyncResult asyncResult) { return _requestStream.EndRead(asyncResult); } public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { return _responseStream.BeginWrite(buffer, offset, count, callback, state); } public override void EndWrite(IAsyncResult asyncResult) { _responseStream.EndWrite(asyncResult); } public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { return _requestStream.ReadAsync(buffer, offset, count, cancellationToken); } public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) { return _requestStream.CopyToAsync(destination, bufferSize, cancellationToken); } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { return _responseStream.WriteAsync(buffer, offset, count, cancellationToken); } public override long Seek(long offset, SeekOrigin origin) { return _requestStream.Seek(offset, origin); } public override void SetLength(long value) { _requestStream.SetLength(value); } public override int Read(byte[] buffer, int offset, int count) { return _requestStream.Read(buffer, offset, count); } public override int ReadByte() { return _requestStream.ReadByte(); } public override void Write(byte[] buffer, int offset, int count) { _responseStream.Write(buffer, offset, count); } public override void WriteByte(byte value) { _responseStream.WriteByte(value); } } }
1
15,853
List all of the current TFMs so we know if this gets outdated. E.g. this breaks if we add 2.2.
aspnet-KestrelHttpServer
.cs
@@ -811,6 +811,12 @@ func (s *VolumeServer) mergeVolumeSpecs(vol *api.VolumeSpec, req *api.VolumeSpec spec.ExportSpec = vol.GetExportSpec() } + // Xattr + if req.GetXattr() >= 0 { + spec.Xattr = req.GetXattr() + } else { + spec.Xattr = vol.GetXattr() + } return spec }
1
/* Package sdk is the gRPC implementation of the SDK gRPC server 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 sdk import ( "context" "fmt" "time" "github.com/sirupsen/logrus" "github.com/libopenstorage/openstorage/api" "github.com/libopenstorage/openstorage/pkg/auth" "github.com/libopenstorage/openstorage/pkg/auth/secrets" policy "github.com/libopenstorage/openstorage/pkg/storagepolicy" "github.com/libopenstorage/openstorage/pkg/util" "github.com/libopenstorage/openstorage/volume" "github.com/portworx/kvdb" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) var ( // AdminOwnedLabelKeys is a set of labels that only the storage admin // can change. AdminOwnedLabelKeys = []string{ secrets.SecretNameKey, secrets.SecretNamespaceKey, api.KubernetesPvcNameKey, api.KubernetesPvcNamespaceKey, } ) // When create is called for an existing volume, this function is called to make sure // the SDK only returns that the volume is ready when the status is UP func (s *VolumeServer) waitForVolumeReady(ctx context.Context, id string) (*api.Volume, error) { var v *api.Volume minTimeout := 1 * time.Second maxTimeout := 60 * time.Minute defaultTimeout := 10 * time.Minute logrus.Infof("Waiting for volume %s to become available", id) e := util.WaitForWithContext( ctx, minTimeout, maxTimeout, defaultTimeout, // timeouts 250*time.Millisecond, // period func() (bool, error) { var err error // Get the latest status from the volume v, err = util.VolumeFromName(s.driver(ctx), id) if err != nil { return false, status.Errorf(codes.Internal, err.Error()) } // Check if the volume is ready if v.GetStatus() == api.VolumeStatus_VOLUME_STATUS_UP { return false, nil } // Continue waiting return true, nil }) return v, e } func (s *VolumeServer) waitForVolumeRemoved(ctx context.Context, id string) error { minTimeout := 1 * time.Second maxTimeout := 10 * time.Minute defaultTimeout := 5 * time.Minute logrus.Infof("Waiting for volume %s to be removed", id) return util.WaitForWithContext( ctx, minTimeout, maxTimeout, defaultTimeout, // timeouts 250*time.Millisecond, // period func() (bool, error) { // Get the latest status from the volume if _, err := util.VolumeFromName(s.driver(ctx), id); err != nil { // Removed return false, nil } // Continue waiting return true, nil }) } func (s *VolumeServer) create( ctx context.Context, locator *api.VolumeLocator, source *api.Source, spec *api.VolumeSpec, ) (string, error) { // Check if the volume has already been created or is in process of creation volName := locator.GetName() v, err := util.VolumeFromName(s.driver(ctx), volName) // If the volume is still there but it is being delete, then wait until it is removed if err == nil && v.GetState() == api.VolumeState_VOLUME_STATE_DELETED { if err = s.waitForVolumeRemoved(ctx, volName); err != nil { return "", status.Errorf(codes.Internal, "Volume with same name %s is in the process of being deleted. Timed out waiting for deletion to complete: %v", volName, err) } // If the volume is there but it is not being deleted then just return the current id } else if err == nil { // Check ownership if !v.IsPermitted(ctx, api.Ownership_Admin) { return "", status.Errorf(codes.PermissionDenied, "Volume %s already exists and is owned by another user", volName) } // Wait until ready v, err = s.waitForVolumeReady(ctx, volName) if err != nil { return "", status.Errorf(codes.Internal, "Timed out waiting for volume %s to be in ready state: %v", volName, err) } // Check the requested arguments match that of the existing volume if v.GetSpec().GetSize() != spec.GetSize() { return "", status.Errorf( codes.AlreadyExists, "Existing volume has a size of %v which differs from requested size of %v", v.GetSpec().GetSize(), spec.Size) } if v.GetSpec().GetShared() != spec.GetShared() { return "", status.Errorf( codes.AlreadyExists, "Existing volume has shared=%v while request is asking for shared=%v", v.GetSpec().GetShared(), spec.GetShared()) } if v.GetSource().GetParent() != source.GetParent() { return "", status.Error(codes.AlreadyExists, "Existing volume has conflicting parent value") } // Return information on existing volume return v.GetId(), nil } // Check if the caller is asking to create a snapshot or for a new volume var id string if len(source.GetParent()) != 0 { // Get parent volume information parent, err := util.VolumeFromName(s.driver(ctx), source.Parent) if err != nil { return "", status.Errorf( codes.NotFound, "unable to get parent volume information: %s", err.Error()) } // Check ownership // Snapshots just need read access if !parent.IsPermitted(ctx, api.Ownership_Read) { return "", status.Errorf(codes.PermissionDenied, "Access denied to volume %s", parent.GetId()) } // Create a snapshot from the parent id, err = s.driver(ctx).Snapshot(parent.GetId(), false, &api.VolumeLocator{ Name: volName, }, false) if err != nil { return "", status.Errorf( codes.Internal, "unable to create snapshot: %s", err.Error()) } // If this is a different owner, make adjust the clone to this owner clone, err := s.Inspect(ctx, &api.SdkVolumeInspectRequest{ VolumeId: id, }) if err != nil { return "", err } newOwnership, updateNeeded := clone.Volume.Spec.GetCloneCreatorOwnership(ctx) if updateNeeded { // Set no authentication so that we can override the ownership ctxNoAuth := context.Background() // New owner for the snapshot, let's make the change _, err := s.Update(ctxNoAuth, &api.SdkVolumeUpdateRequest{ VolumeId: id, Spec: &api.VolumeSpecUpdate{ Ownership: newOwnership, }, }) if err != nil { return "", err } } } else { // New volume, set ownership spec.Ownership = api.OwnershipSetUsernameFromContext(ctx, spec.Ownership) // Create the volume id, err = s.driver(ctx).Create(locator, source, spec) if err != nil { return "", status.Errorf( codes.Internal, "Failed to create volume: %v", err.Error()) } } return id, nil } // Create creates a new volume func (s *VolumeServer) Create( ctx context.Context, req *api.SdkVolumeCreateRequest, ) (*api.SdkVolumeCreateResponse, error) { if s.cluster() == nil || s.driver(ctx) == nil { return nil, status.Error(codes.Unavailable, "Resource has not been initialized") } if len(req.GetName()) == 0 { return nil, status.Error( codes.InvalidArgument, "Must supply a unique name") } else if req.GetSpec() == nil { return nil, status.Error( codes.InvalidArgument, "Must supply spec object") } locator := &api.VolumeLocator{ Name: req.GetName(), VolumeLabels: req.GetLabels(), } source := &api.Source{} // Validate/Update given spec according to default storage policy set // In case policy is not set, should fall back to default way // of creating volume spec, err := GetDefaultVolSpecs(ctx, req.GetSpec(), false) if err != nil { return nil, err } // Copy any labels from the spec to the locator locator = locator.MergeVolumeSpecLabels(spec) // Convert node IP to ID if necessary for API calls if err := s.updateReplicaSpecNodeIPstoIds(spec.GetReplicaSet()); err != nil { return nil, status.Errorf(codes.Internal, "Failed to get replicat set information: %v", err) } // Create volume id, err := s.create(ctx, locator, source, spec) if err != nil { return nil, err } return &api.SdkVolumeCreateResponse{ VolumeId: id, }, nil } // Clone creates a new volume from an existing volume func (s *VolumeServer) Clone( ctx context.Context, req *api.SdkVolumeCloneRequest, ) (*api.SdkVolumeCloneResponse, error) { if s.cluster() == nil || s.driver(ctx) == nil { return nil, status.Error(codes.Unavailable, "Resource has not been initialized") } if len(req.GetName()) == 0 { return nil, status.Error( codes.InvalidArgument, "Must supply a uniqe name") } else if len(req.GetParentId()) == 0 { return nil, status.Error( codes.InvalidArgument, "Must parent volume id") } locator := &api.VolumeLocator{ Name: req.GetName(), } source := &api.Source{ Parent: req.GetParentId(), } // Get spec. This also checks if the parend id exists. // This will also check for Ownership_Read access. parentVol, err := s.Inspect(ctx, &api.SdkVolumeInspectRequest{ VolumeId: req.GetParentId(), }) if err != nil { return nil, err } // Create the clone id, err := s.create(ctx, locator, source, parentVol.GetVolume().GetSpec()) if err != nil { return nil, err } return &api.SdkVolumeCloneResponse{ VolumeId: id, }, nil } // Delete deletes a volume func (s *VolumeServer) Delete( ctx context.Context, req *api.SdkVolumeDeleteRequest, ) (*api.SdkVolumeDeleteResponse, error) { if s.cluster() == nil || s.driver(ctx) == nil { return nil, status.Error(codes.Unavailable, "Resource has not been initialized") } if len(req.GetVolumeId()) == 0 { return nil, status.Error(codes.InvalidArgument, "Must supply volume id") } // If the volume is not found, return OK to be idempotent // This checks access rights also resp, err := s.Inspect(ctx, &api.SdkVolumeInspectRequest{ VolumeId: req.GetVolumeId(), }) if err != nil { if IsErrorNotFound(err) { return &api.SdkVolumeDeleteResponse{}, nil } return nil, err } vol := resp.GetVolume() // Only the owner or the admin can delete if !vol.IsPermitted(ctx, api.Ownership_Admin) { return nil, status.Errorf(codes.PermissionDenied, "Cannot delete volume %v", vol.GetId()) } // Delete the volume err = s.driver(ctx).Delete(req.GetVolumeId()) if err != nil { return nil, status.Errorf( codes.Internal, "Failed to delete volume %s: %v", req.GetVolumeId(), err.Error()) } return &api.SdkVolumeDeleteResponse{}, nil } // InspectWithFilters is a helper function returning information about volumes which match a filter func (s *VolumeServer) InspectWithFilters( ctx context.Context, req *api.SdkVolumeInspectWithFiltersRequest, ) (*api.SdkVolumeInspectWithFiltersResponse, error) { if s.cluster() == nil || s.driver(ctx) == nil { return nil, status.Error(codes.Unavailable, "Resource has not been initialized") } var locator *api.VolumeLocator if len(req.GetName()) != 0 || len(req.GetLabels()) != 0 || req.GetOwnership() != nil { locator = &api.VolumeLocator{ Name: req.GetName(), VolumeLabels: req.GetLabels(), Ownership: req.GetOwnership(), } } enumVols, err := s.driver(ctx).Enumerate(locator, nil) if err != nil { return nil, status.Errorf( codes.Internal, "Failed to enumerate volumes: %v", err.Error()) } vols := make([]*api.SdkVolumeInspectResponse, 0, len(enumVols)) for _, vol := range enumVols { // Check access if vol.IsPermitted(ctx, api.Ownership_Read) { // Check if the caller wants more information if req.GetOptions().GetDeep() { resp, err := s.Inspect(ctx, &api.SdkVolumeInspectRequest{ VolumeId: vol.GetId(), Options: req.GetOptions(), }) if IsErrorNotFound(err) { continue } else if err != nil { return nil, err } vols = append(vols, resp) } else { // Caller does not require a deep inspect // Add the object now vols = append(vols, &api.SdkVolumeInspectResponse{ Volume: vol, Name: vol.GetLocator().GetName(), Labels: vol.GetLocator().GetVolumeLabels(), }) } } } return &api.SdkVolumeInspectWithFiltersResponse{ Volumes: vols, }, nil } // Inspect returns information about a volume func (s *VolumeServer) Inspect( ctx context.Context, req *api.SdkVolumeInspectRequest, ) (*api.SdkVolumeInspectResponse, error) { if s.cluster() == nil || s.driver(ctx) == nil { return nil, status.Error(codes.Unavailable, "Resource has not been initialized") } if len(req.GetVolumeId()) == 0 { return nil, status.Error(codes.InvalidArgument, "Must supply volume id") } var v *api.Volume if !req.GetOptions().GetDeep() { vols, err := s.driver(ctx).Enumerate(&api.VolumeLocator{ VolumeIds: []string{req.GetVolumeId()}, }, nil) if err != nil { return nil, status.Errorf( codes.Internal, "Failed to inspect volume %s: %v", req.GetVolumeId(), err) } if len(vols) == 0 { return nil, status.Errorf( codes.NotFound, "Volume id %s not found", req.GetVolumeId()) } v = vols[0] } else { vols, err := s.driver(ctx).Inspect([]string{req.GetVolumeId()}) if err == kvdb.ErrNotFound || (err == nil && len(vols) == 0) { return nil, status.Errorf( codes.NotFound, "Volume id %s not found", req.GetVolumeId()) } else if err != nil { return nil, status.Errorf( codes.Internal, "Failed to inspect volume %s: %v", req.GetVolumeId(), err) } v = vols[0] } // Check ownership if !v.IsPermitted(ctx, api.Ownership_Read) { return nil, status.Errorf(codes.PermissionDenied, "Access denied to volume %s", v.GetId()) } return &api.SdkVolumeInspectResponse{ Volume: v, Name: v.GetLocator().GetName(), Labels: v.GetLocator().GetVolumeLabels(), }, nil } // Enumerate returns a list of volumes func (s *VolumeServer) Enumerate( ctx context.Context, req *api.SdkVolumeEnumerateRequest, ) (*api.SdkVolumeEnumerateResponse, error) { if s.cluster() == nil || s.driver(ctx) == nil { return nil, status.Error(codes.Unavailable, "Resource has not been initialized") } resp, err := s.EnumerateWithFilters( ctx, &api.SdkVolumeEnumerateWithFiltersRequest{}, ) if err != nil { return nil, err } return &api.SdkVolumeEnumerateResponse{ VolumeIds: resp.GetVolumeIds(), }, nil } // EnumerateWithFilters returns a list of volumes for the provided filters func (s *VolumeServer) EnumerateWithFilters( ctx context.Context, req *api.SdkVolumeEnumerateWithFiltersRequest, ) (*api.SdkVolumeEnumerateWithFiltersResponse, error) { if s.cluster() == nil || s.driver(ctx) == nil { return nil, status.Error(codes.Unavailable, "Resource has not been initialized") } var locator *api.VolumeLocator if len(req.GetName()) != 0 || len(req.GetLabels()) != 0 || req.GetOwnership() != nil { locator = &api.VolumeLocator{ Name: req.GetName(), VolumeLabels: req.GetLabels(), Ownership: req.GetOwnership(), } } vols, err := s.driver(ctx).Enumerate(locator, nil) if err != nil { return nil, status.Errorf( codes.Internal, "Failed to enumerate volumes: %v", err.Error()) } ids := make([]string, 0) for _, vol := range vols { // Check access if vol.IsPermitted(ctx, api.Ownership_Read) { ids = append(ids, vol.GetId()) } } return &api.SdkVolumeEnumerateWithFiltersResponse{ VolumeIds: ids, }, nil } // Update allows the caller to change values in the volume specification func (s *VolumeServer) Update( ctx context.Context, req *api.SdkVolumeUpdateRequest, ) (*api.SdkVolumeUpdateResponse, error) { if s.cluster() == nil || s.driver(ctx) == nil { return nil, status.Error(codes.Unavailable, "Resource has not been initialized") } if len(req.GetVolumeId()) == 0 { return nil, status.Error(codes.InvalidArgument, "Must supply volume id") } // Get current state // This checks for Read access in ownership resp, err := s.Inspect(ctx, &api.SdkVolumeInspectRequest{ VolumeId: req.GetVolumeId(), }) if err != nil { return nil, err } // Only the administrator can change admin-only labels if !api.IsAdminByContext(ctx) && req.GetLabels() != nil { for _, adminKey := range AdminOwnedLabelKeys { if _, ok := req.GetLabels()[adminKey]; ok { return nil, status.Errorf(codes.PermissionDenied, "Only the administrator can update label %s", adminKey) } } } // Check if the caller can update the volume if !resp.GetVolume().IsPermitted(ctx, api.Ownership_Write) { return nil, status.Errorf(codes.PermissionDenied, "Cannot update volume") } // Merge specs spec := s.mergeVolumeSpecs(resp.GetVolume().GetSpec(), req.GetSpec()) // Update Ownership... carefully // First point to the original ownership spec.Ownership = resp.GetVolume().GetSpec().GetOwnership() // Check if we have been provided an update to the ownership if req.GetSpec().GetOwnership() != nil { if spec.Ownership == nil { spec.Ownership = &api.Ownership{} } user, _ := auth.NewUserInfoFromContext(ctx) if err := spec.Ownership.Update(req.GetSpec().GetOwnership(), user); err != nil { return nil, err } } // Check if labels have been updated var locator *api.VolumeLocator if len(req.GetLabels()) != 0 { locator = &api.VolumeLocator{VolumeLabels: req.GetLabels()} } // Validate/Update given spec according to default storage policy set // to make sure if update does not violates default policy updatedSpec, err := GetDefaultVolSpecs(ctx, spec, true) if err != nil { return nil, err } // Send to driver if err := s.driver(ctx).Set(req.GetVolumeId(), locator, updatedSpec); err != nil { return nil, status.Errorf(codes.Internal, "Failed to update volume: %v", err) } return &api.SdkVolumeUpdateResponse{}, nil } // Stats returns volume statistics func (s *VolumeServer) Stats( ctx context.Context, req *api.SdkVolumeStatsRequest, ) (*api.SdkVolumeStatsResponse, error) { if s.cluster() == nil || s.driver(ctx) == nil { return nil, status.Error(codes.Unavailable, "Resource has not been initialized") } if len(req.GetVolumeId()) == 0 { return nil, status.Error(codes.InvalidArgument, "Must supply volume id") } // Get access rights if err := s.checkAccessForVolumeId(ctx, req.GetVolumeId(), api.Ownership_Read); err != nil { return nil, err } stats, err := s.driver(ctx).Stats(req.GetVolumeId(), !req.GetNotCumulative()) if err != nil { return nil, status.Errorf( codes.Internal, "Failed to obtain stats for volume %s: %v", req.GetVolumeId(), err.Error()) } return &api.SdkVolumeStatsResponse{ Stats: stats, }, nil } func (s *VolumeServer) CapacityUsage( ctx context.Context, req *api.SdkVolumeCapacityUsageRequest, ) (*api.SdkVolumeCapacityUsageResponse, error) { if len(req.GetVolumeId()) == 0 { return nil, status.Error(codes.InvalidArgument, "Must supply volume id") } // Get access rights if err := s.checkAccessForVolumeId(ctx, req.GetVolumeId(), api.Ownership_Read); err != nil { return nil, err } dResp, err := s.driver(ctx).CapacityUsage(req.GetVolumeId()) if err != nil { return nil, status.Errorf( codes.Internal, "Failed to obtain stats for volume %s: %v", req.GetVolumeId(), err.Error()) } resp := &api.SdkVolumeCapacityUsageResponse{} resp.CapacityUsageInfo = &api.CapacityUsageInfo{} resp.CapacityUsageInfo.ExclusiveBytes = dResp.CapacityUsageInfo.ExclusiveBytes resp.CapacityUsageInfo.SharedBytes = dResp.CapacityUsageInfo.SharedBytes resp.CapacityUsageInfo.TotalBytes = dResp.CapacityUsageInfo.TotalBytes if dResp.Error != nil { if dResp.Error == volume.ErrAborted { return resp, status.Errorf( codes.Aborted, "Failed to obtain stats for volume %s: %v", req.GetVolumeId(), volume.ErrAborted.Error()) } else if dResp.Error == volume.ErrNotSupported { return resp, status.Errorf( codes.Unimplemented, "Failed to obtain stats for volume %s: %v", req.GetVolumeId(), volume.ErrNotSupported.Error()) } } return resp, nil } func (s *VolumeServer) mergeVolumeSpecs(vol *api.VolumeSpec, req *api.VolumeSpecUpdate) *api.VolumeSpec { spec := &api.VolumeSpec{} spec.Shared = setSpecBool(vol.GetShared(), req.GetShared(), req.GetSharedOpt()) spec.Sharedv4 = setSpecBool(vol.GetSharedv4(), req.GetSharedv4(), req.GetSharedv4Opt()) spec.Sticky = setSpecBool(vol.GetSticky(), req.GetSticky(), req.GetStickyOpt()) spec.Journal = setSpecBool(vol.GetJournal(), req.GetJournal(), req.GetJournalOpt()) spec.Nodiscard = setSpecBool(vol.GetNodiscard(), req.GetNodiscard(), req.GetNodiscardOpt()) // fastpath extensions if req.GetFastpathOpt() != nil { spec.FpPreference = req.GetFastpath() } else { spec.FpPreference = vol.GetFpPreference() } if req.GetIoStrategy() != nil { spec.IoStrategy = req.GetIoStrategy() } else { spec.IoStrategy = vol.GetIoStrategy() } // Cos if req.GetCosOpt() != nil { spec.Cos = req.GetCos() } else { spec.Cos = vol.GetCos() } // Passphrase if req.GetPassphraseOpt() != nil { spec.Passphrase = req.GetPassphrase() } else { spec.Passphrase = vol.GetPassphrase() } // Snapshot schedule as a string if req.GetSnapshotScheduleOpt() != nil { spec.SnapshotSchedule = req.GetSnapshotSchedule() } else { spec.SnapshotSchedule = vol.GetSnapshotSchedule() } // Scale if req.GetScaleOpt() != nil { spec.Scale = req.GetScale() } else { spec.Scale = vol.GetScale() } // Snapshot Interval if req.GetSnapshotIntervalOpt() != nil { spec.SnapshotInterval = req.GetSnapshotInterval() } else { spec.SnapshotInterval = vol.GetSnapshotInterval() } // Io Profile if req.GetIoProfileOpt() != nil { spec.IoProfile = req.GetIoProfile() } else { spec.IoProfile = vol.GetIoProfile() } // GroupID if req.GetGroupOpt() != nil { spec.Group = req.GetGroup() } else { spec.Group = vol.GetGroup() } // Size if req.GetSizeOpt() != nil { spec.Size = req.GetSize() } else { spec.Size = vol.GetSize() } // ReplicaSet if req.GetReplicaSet() != nil { spec.ReplicaSet = req.GetReplicaSet() } else { spec.ReplicaSet = vol.GetReplicaSet() } // HA Level if req.GetHaLevelOpt() != nil { spec.HaLevel = req.GetHaLevel() } else { spec.HaLevel = vol.GetHaLevel() } // Queue depth if req.GetQueueDepthOpt() != nil { spec.QueueDepth = req.GetQueueDepth() } else { spec.QueueDepth = vol.GetQueueDepth() } // ExportSpec if req.GetExportSpec() != nil { spec.ExportSpec = req.GetExportSpec() } else { spec.ExportSpec = vol.GetExportSpec() } return spec } func (s *VolumeServer) nodeIPtoIds(nodes []string) ([]string, error) { nodeIds := make([]string, 0) for _, idIp := range nodes { if idIp != "" { id, err := s.cluster().GetNodeIdFromIp(idIp) if err != nil { return nodeIds, err } nodeIds = append(nodeIds, id) } } return nodeIds, nil } // Convert any replica set node values which are IPs to the corresponding Node ID. // Update the replica set node list. func (s *VolumeServer) updateReplicaSpecNodeIPstoIds(rspecRef *api.ReplicaSet) error { if rspecRef != nil && len(rspecRef.Nodes) > 0 { nodeIds, err := s.nodeIPtoIds(rspecRef.Nodes) if err != nil { return err } if len(nodeIds) > 0 { rspecRef.Nodes = nodeIds } } return nil } func setSpecBool(current, req bool, reqSet interface{}) bool { if reqSet != nil { return req } return current } // GetDefaultVolSpecs returns volume spec merged with default storage policy applied if any func GetDefaultVolSpecs( ctx context.Context, spec *api.VolumeSpec, isUpdate bool, ) (*api.VolumeSpec, error) { storPolicy, err := policy.Inst() if err != nil { return nil, status.Errorf(codes.Internal, "Unable to get storage policy instance %v", err) } var policy *api.SdkStoragePolicy // check if custom policy passed with volume if spec.GetStoragePolicy() != "" { inspReq := &api.SdkOpenStoragePolicyInspectRequest{ // name of storage policy specified in volSpecs Name: spec.GetStoragePolicy(), } // inspect will make sure user will atleast have read access customPolicy, customErr := storPolicy.Inspect(ctx, inspReq) if customErr != nil { return nil, customErr } policy = customPolicy.GetStoragePolicy() } else { // check if default storage policy is set defPolicy, err := storPolicy.DefaultInspect(context.Background(), &api.SdkOpenStoragePolicyDefaultInspectRequest{}) if err != nil { // err means there is policy stored, but we are not able to retrive it // hence we are not allowing volume create operation return nil, status.Errorf(codes.Internal, "Unable to get default policy details %v", err) } else if defPolicy.GetStoragePolicy() == nil { // no default storage policy found return spec, nil } policy = defPolicy.GetStoragePolicy() } // track volume created using storage policy spec.StoragePolicy = policy.GetName() // check if volume update request, if allowupdate is set // return spec received as it is if isUpdate && policy.GetAllowUpdate() { if !policy.IsPermitted(ctx, api.Ownership_Write) { return nil, status.Errorf(codes.PermissionDenied, "Cannot use storage policy %v", policy.GetName()) } return spec, nil } return mergeVolumeSpecsPolicy(spec, policy.GetPolicy(), policy.GetForce()) } func mergeVolumeSpecsPolicy(vol *api.VolumeSpec, req *api.VolumeSpecPolicy, isValidate bool) (*api.VolumeSpec, error) { errMsg := fmt.Errorf("Storage Policy Violation, valid specs are : %v", req.String()) spec := vol // Shared if req.GetSharedOpt() != nil { if isValidate && vol.GetShared() != req.GetShared() { return nil, errMsg } spec.Shared = req.GetShared() } //sharedv4 if req.GetSharedv4Opt() != nil { if isValidate && vol.GetSharedv4() != req.GetSharedv4() { return vol, errMsg } spec.Sharedv4 = req.GetSharedv4() } //sticky if req.GetStickyOpt() != nil { if isValidate && vol.GetSticky() != req.GetSticky() { return vol, errMsg } spec.Sticky = req.GetSticky() } //journal if req.GetJournalOpt() != nil { if isValidate && vol.GetJournal() != req.GetJournal() { return vol, errMsg } spec.Journal = req.GetJournal() } // encrypt if req.GetEncryptedOpt() != nil { if isValidate && vol.GetEncrypted() != req.GetEncrypted() { return vol, errMsg } spec.Encrypted = req.GetEncrypted() } // cos level if req.GetCosOpt() != nil { if isValidate && vol.GetCos() != req.GetCos() { return vol, errMsg } spec.Cos = req.GetCos() } // passphrase if req.GetPassphraseOpt() != nil { if isValidate && vol.GetPassphrase() != req.GetPassphrase() { return vol, errMsg } spec.Passphrase = req.GetPassphrase() } // IO profile if req.GetIoProfileOpt() != nil { if isValidate && req.GetIoProfile() != vol.GetIoProfile() { return vol, errMsg } spec.IoProfile = req.GetIoProfile() } // Group if req.GetGroupOpt() != nil { if isValidate && req.GetGroup() != vol.GetGroup() { return vol, errMsg } spec.Group = req.GetGroup() } // Replicaset if req.GetReplicaSet() != nil { if isValidate && req.GetReplicaSet() != vol.GetReplicaSet() { return vol, errMsg } spec.ReplicaSet = req.GetReplicaSet() } // QueueDepth if req.GetQueueDepthOpt() != nil { if isValidate && req.GetQueueDepth() != vol.GetQueueDepth() { return vol, errMsg } spec.QueueDepth = req.GetQueueDepth() } // SnapshotSchedule if req.GetSnapshotScheduleOpt() != nil { if isValidate && req.GetSnapshotSchedule() != vol.GetSnapshotSchedule() { return vol, errMsg } spec.SnapshotSchedule = req.GetSnapshotSchedule() } // aggr level if req.GetAggregationLevelOpt() != nil { if isValidate && req.GetAggregationLevel() != vol.GetAggregationLevel() { return vol, errMsg } spec.AggregationLevel = req.GetAggregationLevel() } // Size if req.GetSizeOpt() != nil { isCorrect := validateMinMaxParams(uint64(req.GetSize()), uint64(vol.Size), req.GetSizeOperator()) if !isCorrect { if isValidate { return vol, errMsg } spec.Size = req.GetSize() } } // HA Level if req.GetHaLevelOpt() != nil { isCorrect := validateMinMaxParams(uint64(req.GetHaLevel()), uint64(vol.HaLevel), req.GetHaLevelOperator()) if !isCorrect { if isValidate { return vol, errMsg } spec.HaLevel = req.GetHaLevel() } } // Scale if req.GetScaleOpt() != nil { isCorrect := validateMinMaxParams(uint64(req.GetScale()), uint64(vol.Scale), req.GetScaleOperator()) if !isCorrect { if isValidate { return vol, errMsg } spec.Scale = req.GetScale() } } // Snapshot Interval if req.GetSnapshotIntervalOpt() != nil { isCorrect := validateMinMaxParams(uint64(req.GetSnapshotInterval()), uint64(vol.SnapshotInterval), req.GetSnapshotIntervalOperator()) if !isCorrect { if isValidate { return vol, errMsg } spec.SnapshotInterval = req.GetSnapshotInterval() } } // Nodiscard if req.GetNodiscardOpt() != nil { if isValidate && vol.GetNodiscard() != req.GetNodiscard() { return vol, errMsg } spec.Nodiscard = req.GetNodiscard() } // IoStrategy if req.GetIoStrategy() != nil { if isValidate && vol.GetIoStrategy() != req.GetIoStrategy() { return vol, errMsg } spec.IoStrategy = req.GetIoStrategy() } // ExportSpec if req.GetExportSpec() != nil { if isValidate && vol.GetExportSpec() != req.GetExportSpec() { return vol, errMsg } if exportPolicy := vol.GetExportSpec(); exportPolicy == nil { spec.ExportSpec = req.GetExportSpec() } else { // If the spec has an ExportSpec then only modify the fields that came in // the request. reqExportSpec := req.GetExportSpec() if reqExportSpec.ExportProtocol != api.ExportProtocol_INVALID { spec.ExportSpec.ExportProtocol = reqExportSpec.ExportProtocol } if len(reqExportSpec.ExportOptions) != 0 { if reqExportSpec.ExportOptions == api.SpecExportOptionsEmpty { spec.ExportSpec.ExportOptions = "" } else { spec.ExportSpec.ExportOptions = reqExportSpec.ExportOptions } } } } logrus.Debugf("Updated VolumeSpecs %v", spec) return spec, nil } // VolumeCatalog returns a list of volumes for the provided filters func (s *VolumeServer) VolumeCatalog( ctx context.Context, req *api.SdkVolumeCatalogRequest, ) (*api.SdkVolumeCatalogResponse, error) { if s.cluster() == nil || s.driver(ctx) == nil { return nil, status.Error(codes.Unavailable, "Resource has not been initialized") } if len(req.GetVolumeId()) == 0 { return nil, status.Error(codes.Unavailable, "VolumeId not provided.") } catalog, err := s.driver(ctx).Catalog(req.GetVolumeId(), req.GetPath(), req.GetDepth()) if err != nil { return nil, status.Errorf( codes.Internal, "Failed to get the catalog: %v", err.Error()) } return &api.SdkVolumeCatalogResponse{ Catalog: &catalog, }, nil } func validateMinMaxParams(policy uint64, specified uint64, op api.VolumeSpecPolicy_PolicyOp) bool { switch op { case api.VolumeSpecPolicy_Maximum: if specified > policy { return false } case api.VolumeSpecPolicy_Minimum: if specified < policy { return false } default: if specified != policy { return false } } return true }
1
8,601
here, you want to use req.GetXattrOpt() referring to the in line 514 of api.proto. This will be nil if not provided. See the example above on line 801 on this file
libopenstorage-openstorage
go
@@ -952,7 +952,14 @@ public class LocalPSMP extends PlaybackServiceMediaPlayer { // Load next episode if previous episode was in the queue and if there // is an episode in the queue left. // Start playback immediately if continuous playback is enabled - nextMedia = callback.getNextInQueue(currentMedia); + + // Repeat episode implementation + if (UserPreferences.repeatEpisode() && !wasSkipped) { + nextMedia = currentMedia; + nextMedia.setPosition(0); + } else { + nextMedia = callback.getNextInQueue(currentMedia); + } boolean playNextEpisode = isPlaying && nextMedia != null &&
1
package de.danoeh.antennapod.core.service.playback; import android.app.UiModeManager; import android.content.Context; import android.content.res.Configuration; import android.media.AudioManager; import android.os.PowerManager; import androidx.annotation.NonNull; import android.telephony.TelephonyManager; import android.util.Log; import android.util.Pair; import android.view.SurfaceHolder; import androidx.media.AudioAttributesCompat; import androidx.media.AudioFocusRequestCompat; import androidx.media.AudioManagerCompat; import de.danoeh.antennapod.core.storage.DBReader; import org.antennapod.audio.MediaPlayer; import java.io.File; import java.io.IOException; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.ReentrantLock; import de.danoeh.antennapod.model.feed.FeedMedia; import de.danoeh.antennapod.model.feed.FeedPreferences; import de.danoeh.antennapod.model.playback.MediaType; import de.danoeh.antennapod.model.feed.VolumeAdaptionSetting; import de.danoeh.antennapod.core.feed.util.PlaybackSpeedUtils; import de.danoeh.antennapod.core.preferences.UserPreferences; import de.danoeh.antennapod.core.util.RewindAfterPauseUtils; import de.danoeh.antennapod.core.util.playback.AudioPlayer; import de.danoeh.antennapod.core.util.playback.IPlayer; import de.danoeh.antennapod.model.playback.Playable; import de.danoeh.antennapod.core.util.playback.PlaybackServiceStarter; import de.danoeh.antennapod.core.util.playback.VideoPlayer; /** * Manages the MediaPlayer object of the PlaybackService. */ public class LocalPSMP extends PlaybackServiceMediaPlayer { private static final String TAG = "LclPlaybackSvcMPlayer"; private final AudioManager audioManager; private volatile PlayerStatus statusBeforeSeeking; private volatile IPlayer mediaPlayer; private volatile Playable media; private volatile boolean stream; private volatile MediaType mediaType; private final AtomicBoolean startWhenPrepared; private volatile boolean pausedBecauseOfTransientAudiofocusLoss; private volatile Pair<Integer, Integer> videoSize; private final AudioFocusRequestCompat audioFocusRequest; /** * Some asynchronous calls might change the state of the MediaPlayer object. Therefore calls in other threads * have to wait until these operations have finished. */ private final PlayerLock playerLock; private final PlayerExecutor executor; private boolean useCallerThread = true; private CountDownLatch seekLatch; /** * All ExoPlayer methods must be executed on the same thread. * We use the main application thread. This class allows to * "fake" an executor that just calls the methods on the * calling thread instead of submitting to an executor. * Other players are still executed in a background thread. */ private class PlayerExecutor { private ThreadPoolExecutor threadPool; public Future<?> submit(Runnable r) { if (useCallerThread) { r.run(); return new FutureTask<Void>(() -> {}, null); } else { return threadPool.submit(r); } } public void shutdown() { threadPool.shutdown(); } } /** * All ExoPlayer methods must be executed on the same thread. * We use the main application thread. This class allows to * "fake" a lock that does nothing. A lock is not needed if * everything is called on the same thread. * Other players are still executed in a background thread and * therefore use a real lock. */ private class PlayerLock { private ReentrantLock lock = new ReentrantLock(); public void lock() { if (!useCallerThread) { lock.lock(); } } public boolean tryLock(int i, TimeUnit milliseconds) throws InterruptedException { if (!useCallerThread) { return lock.tryLock(i, milliseconds); } return true; } public boolean tryLock() { if (!useCallerThread) { return lock.tryLock(); } return true; } public void unlock() { if (!useCallerThread) { lock.unlock(); } } public boolean isHeldByCurrentThread() { if (!useCallerThread) { return lock.isHeldByCurrentThread(); } return true; } } public LocalPSMP(@NonNull Context context, @NonNull PSMPCallback callback) { super(context, callback); this.audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); this.playerLock = new PlayerLock(); this.startWhenPrepared = new AtomicBoolean(false); executor = new PlayerExecutor(); executor.threadPool = new ThreadPoolExecutor(1, 1, 5, TimeUnit.MINUTES, new LinkedBlockingDeque<>(), (r, executor) -> Log.d(TAG, "Rejected execution of runnable")); mediaPlayer = null; statusBeforeSeeking = null; pausedBecauseOfTransientAudiofocusLoss = false; mediaType = MediaType.UNKNOWN; videoSize = null; AudioAttributesCompat audioAttributes = new AudioAttributesCompat.Builder() .setUsage(AudioAttributesCompat.USAGE_MEDIA) .setContentType(AudioAttributesCompat.CONTENT_TYPE_SPEECH) .build(); audioFocusRequest = new AudioFocusRequestCompat.Builder(AudioManagerCompat.AUDIOFOCUS_GAIN) .setAudioAttributes(audioAttributes) .setOnAudioFocusChangeListener(audioFocusChangeListener) .setWillPauseWhenDucked(true) .build(); } /** * Starts or prepares playback of the specified Playable object. If another Playable object is already being played, the currently playing * episode will be stopped and replaced with the new Playable object. If the Playable object is already being played, the method will * not do anything. * Whether playback starts immediately depends on the given parameters. See below for more details. * <p/> * States: * During execution of the method, the object will be in the INITIALIZING state. The end state depends on the given parameters. * <p/> * If 'prepareImmediately' is set to true, the method will go into PREPARING state and after that into PREPARED state. If * 'startWhenPrepared' is set to true, the method will additionally go into PLAYING state. * <p/> * If an unexpected error occurs while loading the Playable's metadata or while setting the MediaPlayers data source, the object * will enter the ERROR state. * <p/> * This method is executed on an internal executor service. * * @param playable The Playable object that is supposed to be played. This parameter must not be null. * @param stream The type of playback. If false, the Playable object MUST provide access to a locally available file via * getLocalMediaUrl. If true, the Playable object MUST provide access to a resource that can be streamed by * the Android MediaPlayer via getStreamUrl. * @param startWhenPrepared Sets the 'startWhenPrepared' flag. This flag determines whether playback will start immediately after the * episode has been prepared for playback. Setting this flag to true does NOT mean that the episode will be prepared * for playback immediately (see 'prepareImmediately' parameter for more details) * @param prepareImmediately Set to true if the method should also prepare the episode for playback. */ @Override public void playMediaObject(@NonNull final Playable playable, final boolean stream, final boolean startWhenPrepared, final boolean prepareImmediately) { Log.d(TAG, "playMediaObject(...)"); useCallerThread = UserPreferences.useExoplayer(); executor.submit(() -> { playerLock.lock(); try { playMediaObject(playable, false, stream, startWhenPrepared, prepareImmediately); } catch (RuntimeException e) { e.printStackTrace(); throw e; } finally { playerLock.unlock(); } }); } /** * Internal implementation of playMediaObject. This method has an additional parameter that allows the caller to force a media player reset even if * the given playable parameter is the same object as the currently playing media. * <p/> * This method requires the playerLock and is executed on the caller's thread. * * @see #playMediaObject(Playable, boolean, boolean, boolean) */ private void playMediaObject(@NonNull final Playable playable, final boolean forceReset, final boolean stream, final boolean startWhenPrepared, final boolean prepareImmediately) { if (!playerLock.isHeldByCurrentThread()) { throw new IllegalStateException("method requires playerLock"); } if (media != null) { if (!forceReset && media.getIdentifier().equals(playable.getIdentifier()) && playerStatus == PlayerStatus.PLAYING) { // episode is already playing -> ignore method call Log.d(TAG, "Method call to playMediaObject was ignored: media file already playing."); return; } else { // stop playback of this episode if (playerStatus == PlayerStatus.PAUSED || playerStatus == PlayerStatus.PLAYING || playerStatus == PlayerStatus.PREPARED) { mediaPlayer.stop(); } // set temporarily to pause in order to update list with current position if (playerStatus == PlayerStatus.PLAYING) { callback.onPlaybackPause(media, getPosition()); } if (!media.getIdentifier().equals(playable.getIdentifier())) { final Playable oldMedia = media; executor.submit(() -> callback.onPostPlayback(oldMedia, false, false, true)); } setPlayerStatus(PlayerStatus.INDETERMINATE, null); } } this.media = playable; this.stream = stream; this.mediaType = media.getMediaType(); this.videoSize = null; createMediaPlayer(); LocalPSMP.this.startWhenPrepared.set(startWhenPrepared); setPlayerStatus(PlayerStatus.INITIALIZING, media); try { if (media instanceof FeedMedia && ((FeedMedia) media).getItem() == null) { ((FeedMedia) media).setItem(DBReader.getFeedItem(((FeedMedia) media).getItemId())); } callback.onMediaChanged(false); setPlaybackParams(PlaybackSpeedUtils.getCurrentPlaybackSpeed(media), UserPreferences.isSkipSilence()); if (stream) { if (playable instanceof FeedMedia) { FeedMedia feedMedia = (FeedMedia) playable; FeedPreferences preferences = feedMedia.getItem().getFeed().getPreferences(); mediaPlayer.setDataSource( media.getStreamUrl(), preferences.getUsername(), preferences.getPassword()); } else { mediaPlayer.setDataSource(media.getStreamUrl()); } } else if (media.getLocalMediaUrl() != null && new File(media.getLocalMediaUrl()).canRead()) { mediaPlayer.setDataSource(media.getLocalMediaUrl()); } else { throw new IOException("Unable to read local file " + media.getLocalMediaUrl()); } UiModeManager uiModeManager = (UiModeManager) context.getSystemService(Context.UI_MODE_SERVICE); if (uiModeManager.getCurrentModeType() != Configuration.UI_MODE_TYPE_CAR) { setPlayerStatus(PlayerStatus.INITIALIZED, media); } if (prepareImmediately) { setPlayerStatus(PlayerStatus.PREPARING, media); mediaPlayer.prepare(); onPrepared(startWhenPrepared); } } catch (IOException | IllegalStateException e) { e.printStackTrace(); setPlayerStatus(PlayerStatus.ERROR, null); } } /** * Resumes playback if the PSMP object is in PREPARED or PAUSED state. If the PSMP object is in an invalid state. * nothing will happen. * <p/> * This method is executed on an internal executor service. */ @Override public void resume() { executor.submit(() -> { playerLock.lock(); resumeSync(); playerLock.unlock(); }); } private void resumeSync() { if (playerStatus == PlayerStatus.PAUSED || playerStatus == PlayerStatus.PREPARED) { int focusGained = AudioManagerCompat.requestAudioFocus(audioManager, audioFocusRequest); if (focusGained == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { Log.d(TAG, "Audiofocus successfully requested"); Log.d(TAG, "Resuming/Starting playback"); acquireWifiLockIfNecessary(); setPlaybackParams(PlaybackSpeedUtils.getCurrentPlaybackSpeed(media), UserPreferences.isSkipSilence()); float leftVolume = UserPreferences.getLeftVolume(); float rightVolume = UserPreferences.getRightVolume(); setVolume(leftVolume, rightVolume); if (playerStatus == PlayerStatus.PREPARED && media.getPosition() > 0) { int newPosition = RewindAfterPauseUtils.calculatePositionWithRewind( media.getPosition(), media.getLastPlayedTime()); seekToSync(newPosition); } mediaPlayer.start(); setPlayerStatus(PlayerStatus.PLAYING, media); pausedBecauseOfTransientAudiofocusLoss = false; } else { Log.e(TAG, "Failed to request audio focus"); } } else { Log.d(TAG, "Call to resume() was ignored because current state of PSMP object is " + playerStatus); } } /** * Saves the current position and pauses playback. Note that, if audiofocus * is abandoned, the lockscreen controls will also disapear. * <p/> * This method is executed on an internal executor service. * * @param abandonFocus is true if the service should release audio focus * @param reinit is true if service should reinit after pausing if the media * file is being streamed */ @Override public void pause(final boolean abandonFocus, final boolean reinit) { executor.submit(() -> { playerLock.lock(); releaseWifiLockIfNecessary(); if (playerStatus == PlayerStatus.PLAYING) { Log.d(TAG, "Pausing playback."); mediaPlayer.pause(); setPlayerStatus(PlayerStatus.PAUSED, media, getPosition()); if (abandonFocus) { abandonAudioFocus(); pausedBecauseOfTransientAudiofocusLoss = false; } if (stream && reinit) { reinit(); } } else { Log.d(TAG, "Ignoring call to pause: Player is in " + playerStatus + " state"); } playerLock.unlock(); }); } private void abandonAudioFocus() { AudioManagerCompat.abandonAudioFocusRequest(audioManager, audioFocusRequest); } /** * Prepares media player for playback if the service is in the INITALIZED * state. * <p/> * This method is executed on an internal executor service. */ @Override public void prepare() { executor.submit(() -> { playerLock.lock(); if (playerStatus == PlayerStatus.INITIALIZED) { Log.d(TAG, "Preparing media player"); setPlayerStatus(PlayerStatus.PREPARING, media); try { mediaPlayer.prepare(); onPrepared(startWhenPrepared.get()); } catch (IOException e) { e.printStackTrace(); setPlayerStatus(PlayerStatus.ERROR, null); } } playerLock.unlock(); }); } /** * Called after media player has been prepared. This method is executed on the caller's thread. */ private void onPrepared(final boolean startWhenPrepared) { playerLock.lock(); if (playerStatus != PlayerStatus.PREPARING) { playerLock.unlock(); throw new IllegalStateException("Player is not in PREPARING state"); } Log.d(TAG, "Resource prepared"); if (mediaType == MediaType.VIDEO && mediaPlayer instanceof ExoPlayerWrapper) { ExoPlayerWrapper vp = (ExoPlayerWrapper) mediaPlayer; videoSize = new Pair<>(vp.getVideoWidth(), vp.getVideoHeight()); } else if(mediaType == MediaType.VIDEO && mediaPlayer instanceof VideoPlayer) { VideoPlayer vp = (VideoPlayer) mediaPlayer; videoSize = new Pair<>(vp.getVideoWidth(), vp.getVideoHeight()); } // TODO this call has no effect! if (media.getPosition() > 0) { seekToSync(media.getPosition()); } if (media.getDuration() <= 0) { Log.d(TAG, "Setting duration of media"); media.setDuration(mediaPlayer.getDuration()); } setPlayerStatus(PlayerStatus.PREPARED, media); if (startWhenPrepared) { resumeSync(); } playerLock.unlock(); } /** * Resets the media player and moves it into INITIALIZED state. * <p/> * This method is executed on an internal executor service. */ @Override public void reinit() { useCallerThread = UserPreferences.useExoplayer(); executor.submit(() -> { playerLock.lock(); Log.d(TAG, "reinit()"); releaseWifiLockIfNecessary(); if (media != null) { playMediaObject(media, true, stream, startWhenPrepared.get(), false); } else if (mediaPlayer != null) { mediaPlayer.reset(); } else { Log.d(TAG, "Call to reinit was ignored: media and mediaPlayer were null"); } playerLock.unlock(); }); } /** * Seeks to the specified position. If the PSMP object is in an invalid state, this method will do nothing. * * @param t The position to seek to in milliseconds. t < 0 will be interpreted as t = 0 * <p/> * This method is executed on the caller's thread. */ private void seekToSync(int t) { if (t < 0) { t = 0; } playerLock.lock(); if (playerStatus == PlayerStatus.PLAYING || playerStatus == PlayerStatus.PAUSED || playerStatus == PlayerStatus.PREPARED) { if(seekLatch != null && seekLatch.getCount() > 0) { try { seekLatch.await(3, TimeUnit.SECONDS); } catch (InterruptedException e) { Log.e(TAG, Log.getStackTraceString(e)); } } seekLatch = new CountDownLatch(1); statusBeforeSeeking = playerStatus; setPlayerStatus(PlayerStatus.SEEKING, media, getPosition()); mediaPlayer.seekTo(t); if (statusBeforeSeeking == PlayerStatus.PREPARED) { media.setPosition(t); } try { seekLatch.await(3, TimeUnit.SECONDS); } catch (InterruptedException e) { Log.e(TAG, Log.getStackTraceString(e)); } } else if (playerStatus == PlayerStatus.INITIALIZED) { media.setPosition(t); startWhenPrepared.set(false); prepare(); } playerLock.unlock(); } /** * Seeks to the specified position. If the PSMP object is in an invalid state, this method will do nothing. * Invalid time values (< 0) will be ignored. * <p/> * This method is executed on an internal executor service. */ @Override public void seekTo(final int t) { executor.submit(() -> seekToSync(t)); } /** * Seek a specific position from the current position * * @param d offset from current position (positive or negative) */ @Override public void seekDelta(final int d) { executor.submit(() -> { playerLock.lock(); int currentPosition = getPosition(); if (currentPosition != INVALID_TIME) { seekToSync(currentPosition + d); } else { Log.e(TAG, "getPosition() returned INVALID_TIME in seekDelta"); } playerLock.unlock(); }); } /** * Returns the duration of the current media object or INVALID_TIME if the duration could not be retrieved. */ @Override public int getDuration() { if (!playerLock.tryLock()) { return INVALID_TIME; } int retVal = INVALID_TIME; if (playerStatus == PlayerStatus.PLAYING || playerStatus == PlayerStatus.PAUSED || playerStatus == PlayerStatus.PREPARED) { retVal = mediaPlayer.getDuration(); } if (retVal <= 0 && media != null && media.getDuration() > 0) { retVal = media.getDuration(); } playerLock.unlock(); return retVal; } /** * Returns the position of the current media object or INVALID_TIME if the position could not be retrieved. */ @Override public int getPosition() { try { if (!playerLock.tryLock(50, TimeUnit.MILLISECONDS)) { return INVALID_TIME; } } catch (InterruptedException e) { return INVALID_TIME; } int retVal = INVALID_TIME; if (playerStatus.isAtLeast(PlayerStatus.PREPARED)) { retVal = mediaPlayer.getCurrentPosition(); } if (retVal <= 0 && media != null && media.getPosition() >= 0) { retVal = media.getPosition(); } playerLock.unlock(); return retVal; } @Override public boolean isStartWhenPrepared() { return startWhenPrepared.get(); } @Override public void setStartWhenPrepared(boolean startWhenPrepared) { this.startWhenPrepared.set(startWhenPrepared); } /** * Sets the playback speed. * This method is executed on the caller's thread. */ private void setSpeedSyncAndSkipSilence(float speed, boolean skipSilence) { playerLock.lock(); Log.d(TAG, "Playback speed was set to " + speed); callback.playbackSpeedChanged(speed); mediaPlayer.setPlaybackParams(speed, skipSilence); playerLock.unlock(); } /** * Sets the playback speed. * This method is executed on an internal executor service. */ @Override public void setPlaybackParams(final float speed, final boolean skipSilence) { executor.submit(() -> setSpeedSyncAndSkipSilence(speed, skipSilence)); } /** * Returns the current playback speed. If the playback speed could not be retrieved, 1 is returned. */ @Override public float getPlaybackSpeed() { if (!playerLock.tryLock()) { return 1; } float retVal = 1; if ((playerStatus == PlayerStatus.PLAYING || playerStatus == PlayerStatus.PAUSED || playerStatus == PlayerStatus.INITIALIZED || playerStatus == PlayerStatus.PREPARED)) { retVal = mediaPlayer.getCurrentSpeedMultiplier(); } playerLock.unlock(); return retVal; } /** * Sets the playback volume. * This method is executed on an internal executor service. */ @Override public void setVolume(final float volumeLeft, float volumeRight) { executor.submit(() -> setVolumeSync(volumeLeft, volumeRight)); } /** * Sets the playback volume. * This method is executed on the caller's thread. */ private void setVolumeSync(float volumeLeft, float volumeRight) { playerLock.lock(); Playable playable = getPlayable(); if (playable instanceof FeedMedia) { FeedMedia feedMedia = (FeedMedia) playable; FeedPreferences preferences = feedMedia.getItem().getFeed().getPreferences(); VolumeAdaptionSetting volumeAdaptionSetting = preferences.getVolumeAdaptionSetting(); float adaptionFactor = volumeAdaptionSetting.getAdaptionFactor(); volumeLeft *= adaptionFactor; volumeRight *= adaptionFactor; } mediaPlayer.setVolume(volumeLeft, volumeRight); Log.d(TAG, "Media player volume was set to " + volumeLeft + " " + volumeRight); playerLock.unlock(); } /** * Returns true if the mediaplayer can mix stereo down to mono */ @Override public boolean canDownmix() { boolean retVal = false; if (mediaPlayer != null && media != null && media.getMediaType() == MediaType.AUDIO) { retVal = mediaPlayer.canDownmix(); } return retVal; } @Override public void setDownmix(boolean enable) { playerLock.lock(); if (media != null && media.getMediaType() == MediaType.AUDIO) { mediaPlayer.setDownmix(enable); Log.d(TAG, "Media player downmix was set to " + enable); } playerLock.unlock(); } @Override public MediaType getCurrentMediaType() { return mediaType; } @Override public boolean isStreaming() { return stream; } /** * Releases internally used resources. This method should only be called when the object is not used anymore. */ @Override public void shutdown() { executor.shutdown(); if (mediaPlayer != null) { try { removeMediaPlayerErrorListener(); if (mediaPlayer.isPlaying()) { mediaPlayer.stop(); } } catch (Exception ignore) { } mediaPlayer.release(); } releaseWifiLockIfNecessary(); } private void removeMediaPlayerErrorListener() { if (mediaPlayer instanceof VideoPlayer) { VideoPlayer vp = (VideoPlayer) mediaPlayer; vp.setOnErrorListener((mp, what, extra) -> true); } else if (mediaPlayer instanceof AudioPlayer) { AudioPlayer ap = (AudioPlayer) mediaPlayer; ap.setOnErrorListener((mediaPlayer, i, i1) -> true); } else if (mediaPlayer instanceof ExoPlayerWrapper) { ExoPlayerWrapper ap = (ExoPlayerWrapper) mediaPlayer; ap.setOnErrorListener((mediaPlayer, i, i1) -> true); } } /** * Releases internally used resources. This method should only be called when the object is not used anymore. * This method is executed on an internal executor service. */ @Override public void shutdownQuietly() { executor.submit(this::shutdown); executor.shutdown(); } @Override public void setVideoSurface(final SurfaceHolder surface) { executor.submit(() -> { playerLock.lock(); if (mediaPlayer != null) { mediaPlayer.setDisplay(surface); } playerLock.unlock(); }); } @Override public void resetVideoSurface() { executor.submit(() -> { playerLock.lock(); if (mediaType == MediaType.VIDEO) { Log.d(TAG, "Resetting video surface"); mediaPlayer.setDisplay(null); reinit(); } else { Log.e(TAG, "Resetting video surface for media of Audio type"); } playerLock.unlock(); }); } /** * Return width and height of the currently playing video as a pair. * * @return Width and height as a Pair or null if the video size could not be determined. The method might still * return an invalid non-null value if the getVideoWidth() and getVideoHeight() methods of the media player return * invalid values. */ @Override public Pair<Integer, Integer> getVideoSize() { if (!playerLock.tryLock()) { // use cached value if lock can't be aquired return videoSize; } Pair<Integer, Integer> res; if (mediaPlayer == null || playerStatus == PlayerStatus.ERROR || mediaType != MediaType.VIDEO) { res = null; } else if (mediaPlayer instanceof ExoPlayerWrapper) { ExoPlayerWrapper vp = (ExoPlayerWrapper) mediaPlayer; videoSize = new Pair<>(vp.getVideoWidth(), vp.getVideoHeight()); res = videoSize; } else { VideoPlayer vp = (VideoPlayer) mediaPlayer; videoSize = new Pair<>(vp.getVideoWidth(), vp.getVideoHeight()); res = videoSize; } playerLock.unlock(); return res; } /** * Returns the current media, if you need the media and the player status together, you should * use getPSMPInfo() to make sure they're properly synchronized. Otherwise a race condition * could result in nonsensical results (like a status of PLAYING, but a null playable) * @return the current media. May be null */ @Override public Playable getPlayable() { return media; } @Override protected void setPlayable(Playable playable) { media = playable; } public List<String> getAudioTracks() { return mediaPlayer.getAudioTracks(); } public void setAudioTrack(int track) { mediaPlayer.setAudioTrack(track); } public int getSelectedAudioTrack() { return mediaPlayer.getSelectedAudioTrack(); } private void createMediaPlayer() { if (mediaPlayer != null) { mediaPlayer.release(); } if (media == null) { mediaPlayer = null; return; } if (UserPreferences.useExoplayer()) { mediaPlayer = new ExoPlayerWrapper(context); } else if (media.getMediaType() == MediaType.VIDEO) { mediaPlayer = new VideoPlayer(); } else { mediaPlayer = new AudioPlayer(context); } mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mediaPlayer.setWakeMode(context, PowerManager.PARTIAL_WAKE_LOCK); setMediaPlayerListeners(mediaPlayer); } private final AudioManager.OnAudioFocusChangeListener audioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() { @Override public void onAudioFocusChange(final int focusChange) { if (!PlaybackService.isRunning) { abandonAudioFocus(); Log.d(TAG, "onAudioFocusChange: PlaybackService is no longer running"); if (focusChange == AudioManager.AUDIOFOCUS_GAIN && pausedBecauseOfTransientAudiofocusLoss) { new PlaybackServiceStarter(context, getPlayable()) .startWhenPrepared(true) .streamIfLastWasStream() .callEvenIfRunning(false) .start(); } return; } executor.submit(() -> { playerLock.lock(); // If there is an incoming call, playback should be paused permanently TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); final int callState = (tm != null) ? tm.getCallState() : 0; Log.i(TAG, "Call state:" + callState); if (focusChange == AudioManager.AUDIOFOCUS_LOSS || (!UserPreferences.shouldResumeAfterCall() && callState != TelephonyManager.CALL_STATE_IDLE)) { Log.d(TAG, "Lost audio focus"); pause(true, false); callback.shouldStop(); } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) { Log.d(TAG, "Gained audio focus"); if (pausedBecauseOfTransientAudiofocusLoss) { // we paused => play now resume(); } else { // we ducked => raise audio level back setVolumeSync(UserPreferences.getLeftVolume(), UserPreferences.getRightVolume()); } } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) { if (playerStatus == PlayerStatus.PLAYING) { if (!UserPreferences.shouldPauseForFocusLoss()) { Log.d(TAG, "Lost audio focus temporarily. Ducking..."); final float DUCK_FACTOR = 0.25f; setVolumeSync(DUCK_FACTOR * UserPreferences.getLeftVolume(), DUCK_FACTOR * UserPreferences.getRightVolume()); pausedBecauseOfTransientAudiofocusLoss = false; } else { Log.d(TAG, "Lost audio focus temporarily. Could duck, but won't, pausing..."); pause(false, false); pausedBecauseOfTransientAudiofocusLoss = true; } } } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) { if (playerStatus == PlayerStatus.PLAYING) { Log.d(TAG, "Lost audio focus temporarily. Pausing..."); pause(false, false); pausedBecauseOfTransientAudiofocusLoss = true; } } playerLock.unlock(); }); } }; @Override protected Future<?> endPlayback(final boolean hasEnded, final boolean wasSkipped, final boolean shouldContinue, final boolean toStoppedState) { useCallerThread = UserPreferences.useExoplayer(); return executor.submit(() -> { playerLock.lock(); releaseWifiLockIfNecessary(); boolean isPlaying = playerStatus == PlayerStatus.PLAYING; // we're relying on the position stored in the Playable object for post-playback processing if (media != null) { int position = getPosition(); if (position >= 0) { media.setPosition(position); } } if (mediaPlayer != null) { mediaPlayer.reset(); } abandonAudioFocus(); final Playable currentMedia = media; Playable nextMedia = null; if (shouldContinue) { // Load next episode if previous episode was in the queue and if there // is an episode in the queue left. // Start playback immediately if continuous playback is enabled nextMedia = callback.getNextInQueue(currentMedia); boolean playNextEpisode = isPlaying && nextMedia != null && UserPreferences.isFollowQueue(); if (playNextEpisode) { Log.d(TAG, "Playback of next episode will start immediately."); } else if (nextMedia == null){ Log.d(TAG, "No more episodes available to play"); } else { Log.d(TAG, "Loading next episode, but not playing automatically."); } if (nextMedia != null) { callback.onPlaybackEnded(nextMedia.getMediaType(), !playNextEpisode); // setting media to null signals to playMediaObject() that we're taking care of post-playback processing media = null; playMediaObject(nextMedia, false, !nextMedia.localFileAvailable(), playNextEpisode, playNextEpisode); } } if (shouldContinue || toStoppedState) { if (nextMedia == null) { callback.onPlaybackEnded(null, true); stop(); } final boolean hasNext = nextMedia != null; executor.submit(() -> callback.onPostPlayback(currentMedia, hasEnded, wasSkipped, hasNext)); } else if (isPlaying) { callback.onPlaybackPause(currentMedia, currentMedia.getPosition()); } playerLock.unlock(); }); } /** * Moves the LocalPSMP into STOPPED state. This call is only valid if the player is currently in * INDETERMINATE state, for example after a call to endPlayback. * This method will only take care of changing the PlayerStatus of this object! Other tasks like * abandoning audio focus have to be done with other methods. */ private void stop() { executor.submit(() -> { playerLock.lock(); releaseWifiLockIfNecessary(); if (playerStatus == PlayerStatus.INDETERMINATE) { setPlayerStatus(PlayerStatus.STOPPED, null); } else { Log.d(TAG, "Ignored call to stop: Current player state is: " + playerStatus); } playerLock.unlock(); }); } @Override protected boolean shouldLockWifi(){ return stream; } private IPlayer setMediaPlayerListeners(IPlayer mp) { if (mp == null || media == null) { return mp; } if (mp instanceof VideoPlayer) { if (media.getMediaType() != MediaType.VIDEO) { Log.w(TAG, "video player, but media type is " + media.getMediaType()); } VideoPlayer vp = (VideoPlayer) mp; vp.setOnCompletionListener(videoCompletionListener); vp.setOnSeekCompleteListener(videoSeekCompleteListener); vp.setOnErrorListener(videoErrorListener); vp.setOnBufferingUpdateListener(videoBufferingUpdateListener); vp.setOnInfoListener(videoInfoListener); } else if (mp instanceof AudioPlayer) { if (media.getMediaType() != MediaType.AUDIO) { Log.w(TAG, "audio player, but media type is " + media.getMediaType()); } AudioPlayer ap = (AudioPlayer) mp; ap.setOnCompletionListener(audioCompletionListener); ap.setOnSeekCompleteListener(audioSeekCompleteListener); ap.setOnErrorListener(audioErrorListener); ap.setOnBufferingUpdateListener(audioBufferingUpdateListener); ap.setOnInfoListener(audioInfoListener); } else if (mp instanceof ExoPlayerWrapper) { ExoPlayerWrapper ap = (ExoPlayerWrapper) mp; ap.setOnCompletionListener(audioCompletionListener); ap.setOnSeekCompleteListener(audioSeekCompleteListener); ap.setOnBufferingUpdateListener(audioBufferingUpdateListener); ap.setOnErrorListener(audioErrorListener); ap.setOnInfoListener(audioInfoListener); } else { Log.w(TAG, "Unknown media player: " + mp); } return mp; } private final MediaPlayer.OnCompletionListener audioCompletionListener = mp -> genericOnCompletion(); private final android.media.MediaPlayer.OnCompletionListener videoCompletionListener = mp -> genericOnCompletion(); private void genericOnCompletion() { endPlayback(true, false, true, true); } private final MediaPlayer.OnBufferingUpdateListener audioBufferingUpdateListener = (mp, percent) -> genericOnBufferingUpdate(percent); private final android.media.MediaPlayer.OnBufferingUpdateListener videoBufferingUpdateListener = (mp, percent) -> genericOnBufferingUpdate(percent); private void genericOnBufferingUpdate(int percent) { callback.onBufferingUpdate(percent); } private final MediaPlayer.OnInfoListener audioInfoListener = (mp, what, extra) -> genericInfoListener(what); private final android.media.MediaPlayer.OnInfoListener videoInfoListener = (mp, what, extra) -> genericInfoListener(what); private boolean genericInfoListener(int what) { return callback.onMediaPlayerInfo(what, 0); } private final MediaPlayer.OnErrorListener audioErrorListener = (mp, what, extra) -> { if(mp != null && mp.canFallback()) { mp.fallback(); return true; } else { return genericOnError(mp, what, extra); } }; private final android.media.MediaPlayer.OnErrorListener videoErrorListener = this::genericOnError; private boolean genericOnError(Object inObj, int what, int extra) { return callback.onMediaPlayerError(inObj, what, extra); } private final MediaPlayer.OnSeekCompleteListener audioSeekCompleteListener = mp -> genericSeekCompleteListener(); private final android.media.MediaPlayer.OnSeekCompleteListener videoSeekCompleteListener = mp -> genericSeekCompleteListener(); private void genericSeekCompleteListener() { Log.d(TAG, "genericSeekCompleteListener"); if (seekLatch != null) { seekLatch.countDown(); } Runnable r = () -> { playerLock.lock(); if (playerStatus == PlayerStatus.PLAYING) { callback.onPlaybackStart(media, getPosition()); } if (playerStatus == PlayerStatus.SEEKING) { setPlayerStatus(statusBeforeSeeking, media, getPosition()); } playerLock.unlock(); }; if (useCallerThread) { r.run(); } else { executor.submit(r); } } }
1
20,661
I think this should be done outside LocalPSMP, but in `getNextInQueue`. The reason is that I want to reduce the dependence of the media players on the preferences and database. Also, it will then probably work on Chromecast.
AntennaPod-AntennaPod
java
@@ -143,7 +143,9 @@ struct _hiprtcProgram { { using namespace std; - name = hip_impl::demangle(name.c_str()); + char* demangled = hip_impl::demangle(name.c_str()); + name.assign(demangled == nullptr ? "" : demangled); + free(demangled); if (name.empty()) return name;
1
/* Copyright (c) 2015 - present Advanced Micro Devices, Inc. All rights reserved. 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. */ #include "../include/hip/hiprtc.h" #include "../include/hip/hcc_detail/code_object_bundle.hpp" #include "../include/hip/hcc_detail/elfio/elfio.hpp" #include "../include/hip/hcc_detail/program_state.hpp" #include "../lpl_ca/pstreams/pstream.h" #include <hsa/hsa.h> #include <cxxabi.h> #include <algorithm> #include <cassert> #include <cstdio> #include <cstdlib> #include <experimental/filesystem> #include <fstream> #include <future> #include <iterator> #include <memory> #include <mutex> #include <stdexcept> #include <string> #include <unordered_map> #include <utility> #include <vector> #include <iostream> const char* hiprtcGetErrorString(hiprtcResult x) { switch (x) { case HIPRTC_SUCCESS: return "HIPRTC_SUCCESS"; case HIPRTC_ERROR_OUT_OF_MEMORY: return "HIPRTC_ERROR_OUT_OF_MEMORY"; case HIPRTC_ERROR_PROGRAM_CREATION_FAILURE: return "HIPRTC_ERROR_PROGRAM_CREATION_FAILURE"; case HIPRTC_ERROR_INVALID_INPUT: return "HIPRTC_ERROR_INVALID_INPUT"; case HIPRTC_ERROR_INVALID_PROGRAM: return "HIPRTC_ERROR_INVALID_PROGRAM"; case HIPRTC_ERROR_INVALID_OPTION: return "HIPRTC_ERROR_INVALID_OPTION"; case HIPRTC_ERROR_COMPILATION: return "HIPRTC_ERROR_COMPILATION"; case HIPRTC_ERROR_BUILTIN_OPERATION_FAILURE: return "HIPRTC_ERROR_BUILTIN_OPERATION_FAILURE"; case HIPRTC_ERROR_NO_NAME_EXPRESSIONS_AFTER_COMPILATION: return "HIPRTC_ERROR_NO_NAME_EXPRESSIONS_AFTER_COMPILATION"; case HIPRTC_ERROR_NO_LOWERED_NAMES_BEFORE_COMPILATION: return "HIPRTC_ERROR_NO_LOWERED_NAMES_BEFORE_COMPILATION"; case HIPRTC_ERROR_NAME_EXPRESSION_NOT_VALID: return "HIPRTC_ERROR_NAME_EXPRESSION_NOT_VALID"; case HIPRTC_ERROR_INTERNAL_ERROR: return "HIPRTC_ERROR_INTERNAL_ERROR"; default: throw std::logic_error{"Invalid HIPRTC result."}; }; } namespace { struct Symbol { std::string name; ELFIO::Elf64_Addr value = 0; ELFIO::Elf_Xword size = 0; ELFIO::Elf_Half sect_idx = 0; std::uint8_t bind = 0; std::uint8_t type = 0; std::uint8_t other = 0; }; inline Symbol read_symbol(const ELFIO::symbol_section_accessor& section, unsigned int idx) { assert(idx < section.get_symbols_num()); Symbol r; section.get_symbol( idx, r.name, r.value, r.size, r.bind, r.type, r.sect_idx, r.other); return r; } } // Unnamed namespace. struct _hiprtcProgram { // DATA - STATICS static std::vector<std::unique_ptr<_hiprtcProgram>> programs; static std::mutex mtx; // DATA std::vector<std::pair<std::string, std::string>> headers; std::vector<std::pair<std::string, std::string>> names; std::vector<std::string> loweredNames; std::vector<char> elf; std::string source; std::string name; std::string log; bool compiled; // STATICS static hiprtcResult destroy(_hiprtcProgram* p) { using namespace std; lock_guard<mutex> lck{mtx}; const auto it{find_if(programs.cbegin(), programs.cend(), [=](const unique_ptr<_hiprtcProgram>& x) { return x.get() == p; })}; if (it == programs.cend()) return HIPRTC_ERROR_INVALID_PROGRAM; return HIPRTC_SUCCESS; } static std::string handleMangledName(std::string name) { using namespace std; name = hip_impl::demangle(name.c_str()); if (name.empty()) return name; if (name.find("void ") == 0) name.erase(0, strlen("void ")); auto dx{name.find_first_of("(<")}; if (dx == string::npos) return name; if (name[dx] == '<') { auto cnt{1u}; do { ++dx; cnt += (name[dx] == '<') ? 1 : ((name[dx] == '>') ? -1 : 0); } while (cnt); name.erase(++dx); } else name.erase(dx); return name; } static _hiprtcProgram* make(std::string s, std::string n, std::vector<std::pair<std::string, std::string>> h) { using namespace std; unique_ptr<_hiprtcProgram> tmp{new _hiprtcProgram{move(h), {}, {}, {}, move(s), move(n), {}, false}}; lock_guard<mutex> lck{mtx}; programs.push_back(move(tmp)); return programs.back().get(); } static bool isValid(_hiprtcProgram* p) noexcept { return std::find_if(programs.cbegin(), programs.cend(), [=](const std::unique_ptr<_hiprtcProgram>& x) { return x.get() == p; }) != programs.cend(); } // MANIPULATORS bool compile(const std::vector<std::string>& args, const std::experimental::filesystem::path& program_folder) { using namespace ELFIO; using namespace redi; using namespace std; ipstream compile{args.front(), args, pstreambuf::pstderr}; constexpr const auto tmp_size{1024u}; char tmp[tmp_size]{}; while (!compile.eof()) { log.append(tmp, tmp + compile.readsome(tmp, tmp_size)); } compile.close(); if (compile.rdbuf()->exited() && compile.rdbuf()->status() != EXIT_SUCCESS) return false; elfio reader; if (!reader.load(args.back())) return false; const auto it{find_if(reader.sections.begin(), reader.sections.end(), [](const section* x) { return x->get_name() == ".kernel"; })}; if (it == reader.sections.end()) return false; hip_impl::Bundled_code_header h{(*it)->get_data()}; if (bundles(h).empty()) return false; elf.assign(bundles(h).back().blob.cbegin(), bundles(h).back().blob.cend()); return true; } bool readLoweredNames() { using namespace ELFIO; using namespace hip_impl; using namespace std; if (names.empty()) return true; istringstream blob{string{elf.cbegin(), elf.cend()}}; elfio reader; if (!reader.load(blob)) return false; const auto it{find_if(reader.sections.begin(), reader.sections.end(), [](const section* x) { return x->get_type() == SHT_SYMTAB; })}; ELFIO::symbol_section_accessor symbols{reader, *it}; auto n{symbols.get_symbols_num()}; if (n < loweredNames.size()) return false; while (n--) { const auto tmp{read_symbol(symbols, n)}; auto it{find_if(names.cbegin(), names.cend(), [&](const pair<string, string>& x) { return x.second == tmp.name; })}; if (it == names.cend()) { const auto name{handleMangledName(tmp.name)}; if (name.empty()) continue; it = find_if(names.cbegin(), names.cend(), [&](const pair<string, string>& x) { return x.second == name; }); if (it == names.cend()) continue; } loweredNames[distance(names.cbegin(), it)] = tmp.name; } return true; } // ACCESSORS std::experimental::filesystem::path writeTemporaryFiles( const std::experimental::filesystem::path& programFolder) const { using namespace std; vector<future<void>> fut{headers.size()}; transform(headers.cbegin(), headers.cend(), begin(fut), [&](const pair<string, string>& x) { return async([&]() { ofstream h{programFolder / x.first}; h.write(x.second.data(), x.second.size()); }); }); auto tmp{(programFolder / name).replace_extension(".cpp")}; ofstream{tmp}.write(source.data(), source.size()); return tmp; } }; std::vector<std::unique_ptr<_hiprtcProgram>> _hiprtcProgram::programs{}; std::mutex _hiprtcProgram::mtx{}; namespace { inline bool isValidProgram(const hiprtcProgram p) { if (!p) return false; std::lock_guard<std::mutex> lck{_hiprtcProgram::mtx}; return _hiprtcProgram::isValid(p); } } // Unnamed namespace. hiprtcResult hiprtcAddNameExpression(hiprtcProgram p, const char* n) { if (!n) return HIPRTC_ERROR_INVALID_INPUT; if (!isValidProgram(p)) return HIPRTC_ERROR_INVALID_PROGRAM; if (p->compiled) return HIPRTC_ERROR_NO_NAME_EXPRESSIONS_AFTER_COMPILATION; const auto id{p->names.size()}; p->names.emplace_back(n, n); p->loweredNames.emplace_back(); if (p->names.back().second.back() == ')') { p->names.back().second.pop_back(); p->names.back().second.erase(0, p->names.back().second.find('(')); } if (p->names.back().second.front() == '&') { p->names.back().second.erase(0, 1); } const auto var{"__hiprtc_" + std::to_string(id)}; p->source.append("\nextern \"C\" constexpr auto " + var + " = " + n + ';'); return HIPRTC_SUCCESS; } namespace { class Unique_temporary_path { // DATA std::experimental::filesystem::path path_{}; public: // CREATORS Unique_temporary_path() : path_{std::tmpnam(nullptr)} { while (std::experimental::filesystem::exists(path_)) { path_ = std::tmpnam(nullptr); } } Unique_temporary_path(const std::string& extension) : Unique_temporary_path{} { path_.replace_extension(extension); } Unique_temporary_path(const Unique_temporary_path&) = default; Unique_temporary_path(Unique_temporary_path&&) = default; ~Unique_temporary_path() noexcept { std::experimental::filesystem::remove_all(path_); } // MANIPULATORS Unique_temporary_path& operator=( const Unique_temporary_path&) = default; Unique_temporary_path& operator=(Unique_temporary_path&&) = default; // ACCESSORS const std::experimental::filesystem::path& path() const noexcept { return path_; } }; } // Unnamed namespace. namespace hip_impl { inline std::string demangle(const char* x) { if (!x) return {}; int s{}; std::unique_ptr<char, decltype(std::free)*> tmp{ abi::__cxa_demangle(x, nullptr, nullptr, &s), std::free}; if (s != 0) return {}; return tmp.get(); } } // Namespace hip_impl. namespace { const std::string& defaultTarget() { using namespace std; static string r{"gfx900"}; static once_flag f{}; call_once(f, []() { static hsa_agent_t a{}; hsa_iterate_agents([](hsa_agent_t x, void*) { hsa_device_type_t t{}; hsa_agent_get_info(x, HSA_AGENT_INFO_DEVICE, &t); if (t != HSA_DEVICE_TYPE_GPU) return HSA_STATUS_SUCCESS; a = x; return HSA_STATUS_INFO_BREAK; }, nullptr); if (!a.handle) return; hsa_agent_iterate_isas(a, [](hsa_isa_t x, void*){ uint32_t n{}; hsa_isa_get_info_alt(x, HSA_ISA_INFO_NAME_LENGTH, &n); if (n == 0) return HSA_STATUS_SUCCESS; r.resize(n); hsa_isa_get_info_alt(x, HSA_ISA_INFO_NAME, &r[0]); r.erase(0, r.find("gfx")); return HSA_STATUS_INFO_BREAK; }, nullptr); }); return r; } inline void handleTarget(std::vector<std::string>& args) { using namespace std; bool hasTarget{false}; for (auto&& x : args) { const auto dx{x.find("--gpu-architecture")}; const auto dy{(dx == string::npos) ? x.find("-arch") : string::npos}; if (dx == dy) continue; x.replace(0, x.find('=', min(dx, dy)), "--amdgpu-target"); hasTarget = true; break; } if (!hasTarget) args.push_back("--amdgpu-target=" + defaultTarget()); } } // Unnamed namespace. hiprtcResult hiprtcCompileProgram(hiprtcProgram p, int n, const char** o) { using namespace std; if (n && !o) return HIPRTC_ERROR_INVALID_INPUT; if (!isValidProgram(p)) return HIPRTC_ERROR_INVALID_PROGRAM; if (p->compiled) return HIPRTC_ERROR_COMPILATION; static const string hipcc{ getenv("HIP_PATH") ? (getenv("HIP_PATH") + string{"/bin/hipcc"}) : "/opt/rocm/bin/hipcc"}; if (!experimental::filesystem::exists(hipcc)) { return HIPRTC_ERROR_INTERNAL_ERROR; } Unique_temporary_path tmp{}; experimental::filesystem::create_directory(tmp.path()); const auto src{p->writeTemporaryFiles(tmp.path())}; vector<string> args{hipcc, "-shared"}; if (n) args.insert(args.cend(), o, o + n); handleTarget(args); args.emplace_back(src); args.emplace_back("-o"); args.emplace_back(tmp.path() / "hiprtc.out"); if (!p->compile(args, tmp.path())) return HIPRTC_ERROR_INTERNAL_ERROR; if (!p->readLoweredNames()) return HIPRTC_ERROR_INTERNAL_ERROR; p->compiled = true; return HIPRTC_SUCCESS; } hiprtcResult hiprtcCreateProgram(hiprtcProgram* p, const char* src, const char* name, int n, const char** hdrs, const char** incs) { using namespace std; if (!p) return HIPRTC_ERROR_INVALID_PROGRAM; if (n < 0) return HIPRTC_ERROR_INVALID_INPUT; if (n && (!hdrs || !incs)) return HIPRTC_ERROR_INVALID_INPUT; vector<pair<string, string>> h; for (auto i = 0; i != n; ++i) h.emplace_back(incs[i], hdrs[i]); *p = _hiprtcProgram::make(src, name ? name : "default_name", move(h)); return HIPRTC_SUCCESS; } hiprtcResult hiprtcDestroyProgram(hiprtcProgram* p) { if (!p) return HIPRTC_SUCCESS; return _hiprtcProgram::destroy(*p); } hiprtcResult hiprtcGetLoweredName(hiprtcProgram p, const char* n, const char** ln) { using namespace std; if (!n || !ln) return HIPRTC_ERROR_INVALID_INPUT; if (!isValidProgram(p)) return HIPRTC_ERROR_INVALID_PROGRAM; if (!p->compiled) return HIPRTC_ERROR_NO_LOWERED_NAMES_BEFORE_COMPILATION; const auto it{find_if(p->names.cbegin(), p->names.cend(), [=](const pair<string, string>& x) { return x.first == n; })}; if (it == p->names.cend()) return HIPRTC_ERROR_NAME_EXPRESSION_NOT_VALID; *ln = p->loweredNames[distance(p->names.cbegin(), it)].c_str(); return HIPRTC_SUCCESS; } hiprtcResult hiprtcGetProgramLog(hiprtcProgram p, char* l) { if (!l) return HIPRTC_ERROR_INVALID_INPUT; if (!isValidProgram(p)) return HIPRTC_ERROR_INVALID_PROGRAM; if (!p->compiled) return HIPRTC_ERROR_INVALID_PROGRAM; l = std::copy_n(p->log.data(), p->log.size(), l); *l = '\0'; return HIPRTC_SUCCESS; } hiprtcResult hiprtcGetProgramLogSize(hiprtcProgram p, std::size_t* sz) { if (!sz) return HIPRTC_ERROR_INVALID_INPUT; if (!isValidProgram(p)) return HIPRTC_ERROR_INVALID_PROGRAM; if (!p->compiled) return HIPRTC_ERROR_INVALID_PROGRAM; *sz = p->log.empty() ? 0 : p->log.size() + 1; return HIPRTC_SUCCESS; } hiprtcResult hiprtcGetCode(hiprtcProgram p, char* c) { if (!c) return HIPRTC_ERROR_INVALID_INPUT; if (!isValidProgram(p)) return HIPRTC_ERROR_INVALID_PROGRAM; if (!p->compiled) return HIPRTC_ERROR_INVALID_PROGRAM; std::copy_n(p->elf.data(), p->elf.size(), c); return HIPRTC_SUCCESS; } hiprtcResult hiprtcGetCodeSize(hiprtcProgram p, std::size_t* sz) { if (!sz) return HIPRTC_ERROR_INVALID_INPUT; if (!isValidProgram(p)) return HIPRTC_ERROR_INVALID_PROGRAM; if (!p->compiled) return HIPRTC_ERROR_INVALID_PROGRAM; *sz = p->elf.size(); return HIPRTC_SUCCESS; }
1
8,690
Please remove it or remove all `std::` namespace prefixes.
ROCm-Developer-Tools-HIP
cpp
@@ -0,0 +1,17 @@ +// Copyright (C) 2019-2020 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 nodecontrol
1
1
40,520
wait! I'm confused - is that an empty file ?!
algorand-go-algorand
go
@@ -19,14 +19,14 @@ var phrasingElements = ['A', 'EM', 'STRONG', 'SMALL', 'MARK', 'ABBR', 'DFN', 'I' * @param {HTMLElement} element The HTMLElement * @return {HTMLElement} The label element, or null if none is found */ -function findLabel({ actualNode }) { +function findLabel(virtualNode) { let label; - if (actualNode.id) { + if (virtualNode.actualNode.id) { label = dom.findElmsInContext({ - elm: 'label', attr: 'for', value: actualNode.id, context: actualNode + elm: 'label', attr: 'for', value: virtualNode.actualNode.id, context: virtualNode.actualNode })[0]; } else { - label = dom.findUp(actualNode, 'label'); + label = dom.findUpVirtual(virtualNode, 'label'); } return axe.utils.getNodeFromTree(axe._tree[0], label); }
1
/* global text, dom, aria, axe */ /* jshint maxstatements: 27, maxcomplexity: 19 */ var defaultButtonValues = { submit: 'Submit', reset: 'Reset' }; var inputTypes = ['text', 'search', 'tel', 'url', 'email', 'date', 'time', 'number', 'range', 'color']; var phrasingElements = ['A', 'EM', 'STRONG', 'SMALL', 'MARK', 'ABBR', 'DFN', 'I', 'B', 'S', 'U', 'CODE', 'VAR', 'SAMP', 'KBD', 'SUP', 'SUB', 'Q', 'CITE', 'SPAN', 'BDO', 'BDI', 'BR', 'WBR', 'INS', 'DEL', 'IMG', 'EMBED', 'OBJECT', 'IFRAME', 'MAP', 'AREA', 'SCRIPT', 'NOSCRIPT', 'RUBY', 'VIDEO', 'AUDIO', 'INPUT', 'TEXTAREA', 'SELECT', 'BUTTON', 'LABEL', 'OUTPUT', 'DATALIST', 'KEYGEN', 'PROGRESS', 'COMMAND', 'CANVAS', 'TIME', 'METER']; /** * Find a non-ARIA label for an element * @private * @param {HTMLElement} element The HTMLElement * @return {HTMLElement} The label element, or null if none is found */ function findLabel({ actualNode }) { let label; if (actualNode.id) { label = dom.findElmsInContext({ elm: 'label', attr: 'for', value: actualNode.id, context: actualNode })[0]; } else { label = dom.findUp(actualNode, 'label'); } return axe.utils.getNodeFromTree(axe._tree[0], label); } function isButton({ actualNode }) { return ['button', 'reset', 'submit'].includes(actualNode.type.toLowerCase()); } function isInput({ actualNode }) { var nodeName = actualNode.nodeName.toUpperCase(); return (nodeName === 'TEXTAREA' || nodeName === 'SELECT') || (nodeName === 'INPUT' && actualNode.type.toLowerCase() !== 'hidden'); } function shouldCheckSubtree({ actualNode }) { return ['BUTTON', 'SUMMARY', 'A'].includes(actualNode.nodeName.toUpperCase()); } function shouldNeverCheckSubtree({ actualNode }) { return ['TABLE', 'FIGURE'].includes(actualNode.nodeName.toUpperCase()); } /** * Calculate value of a form element when treated as a value * @private * @param {HTMLElement} element The HTMLElement * @return {string} The calculated value */ function formValueText({ actualNode }) { const nodeName = actualNode.nodeName.toUpperCase(); if (nodeName === 'INPUT') { if (!actualNode.hasAttribute('type') || inputTypes.includes(actualNode.type.toLowerCase())) { return actualNode.value; } return ''; } if (nodeName === 'SELECT') { var opts = actualNode.options; if (opts && opts.length) { var returnText = ''; for (var i = 0; i < opts.length; i++) { if (opts[i].selected) { returnText += ' ' + opts[i].text; } } return text.sanitize(returnText); } return ''; } if (nodeName === 'TEXTAREA' && actualNode.value) { return actualNode.value; } return ''; } /** * Get the accessible text of first matching node * IMPORTANT: This method does not look at the composed tree * @private */ function checkDescendant({ actualNode }, nodeName) { var candidate = actualNode.querySelector(nodeName.toLowerCase()); if (candidate) { return text.accessibleText(candidate); } return ''; } /** * Determine whether an element can be an embedded control * @private * @param {HTMLElement} element The HTMLElement * @return {boolean} True if embedded control */ function isEmbeddedControl(elm) { if (!elm) { return false; } const { actualNode } = elm; switch (actualNode.nodeName.toUpperCase()) { case 'SELECT': case 'TEXTAREA': return true; case 'INPUT': return (!actualNode.hasAttribute('type') || inputTypes.includes(actualNode.getAttribute('type').toLowerCase())); default: return false; } } function shouldCheckAlt({ actualNode }) { const nodeName = actualNode.nodeName.toUpperCase(); return ['IMG', 'APPLET', 'AREA'].includes(nodeName) || (nodeName === 'INPUT' && actualNode.type.toLowerCase() === 'image'); } function nonEmptyText(t) { return !!text.sanitize(t); } /** * Finds virtual node and calls accessibleTextVirtual() * IMPORTANT: This method requires the composed tree at axe._tree * @method accessibleText * @memberof axe.commons.text * @instance * @param {HTMLElement} element The HTMLElement * @param {Boolean} inLabelledByContext True when in the context of resolving a labelledBy * @return {string} */ text.accessibleText = function accessibleText(element, inLabelledByContext) { let virtualNode = axe.utils.getNodeFromTree(axe._tree[0], element); // throws an exception on purpose if axe._tree not correct return axe.commons.text.accessibleTextVirtual(virtualNode, inLabelledByContext); }; /** * Determine the accessible text of an element, using logic from ARIA: * http://www.w3.org/TR/html-aam-1.0/ * http://www.w3.org/TR/wai-aria/roles#textalternativecomputation * @method accessibleTextVirtual * @memberof axe.commons.text * @instance * @param {VirtualNode} element Virtual Node to search * @param {Boolean} inLabelledByContext True when in the context of resolving a labelledBy * @return {string} */ text.accessibleTextVirtual = function accessibleTextVirtual(element, inLabelledByContext) { let accessibleNameComputation; const encounteredNodes = []; if (element instanceof Node) { element = axe.utils.getNodeFromTree(axe._tree[0], element); } function getInnerText (element, inLabelledByContext, inControlContext) { return element.children.reduce((returnText, child) => { const { actualNode } = child; if (actualNode.nodeType === 3) { returnText += actualNode.nodeValue; } else if (actualNode.nodeType === 1) { if (!phrasingElements.includes(actualNode.nodeName.toUpperCase())) { returnText += ' '; } returnText += accessibleNameComputation(child, inLabelledByContext, inControlContext); } return returnText; }, ''); } function getLayoutTableText (element) { // // check if layout table only has one cell if (!axe.commons.table.isDataTable(element.actualNode) && axe.commons.table.getAllCells(element.actualNode).length === 1) { return getInnerText(element, false, false).trim(); } return ''; } function checkNative (element, inLabelledByContext, inControlContext) { // jshint maxstatements:30, maxcomplexity: 20 let returnText = ''; const { actualNode } = element; const nodeName = actualNode.nodeName.toUpperCase(); if (shouldCheckSubtree(element)) { returnText = getInnerText(element, false, false) || ''; if (nonEmptyText(returnText)) { return returnText; } } if (nodeName === 'FIGURE') { returnText = checkDescendant(element, 'figcaption'); if (nonEmptyText(returnText)) { return returnText; } } if (nodeName === 'TABLE') { returnText = checkDescendant(element, 'caption'); if (nonEmptyText(returnText)) { return returnText; } returnText = (actualNode.getAttribute('title') || actualNode.getAttribute('summary') || getLayoutTableText(element) || ''); if (nonEmptyText(returnText)) { return returnText; } } if (shouldCheckAlt(element)) { return actualNode.getAttribute('alt') || ''; } if (isInput(element) && !inControlContext) { if (isButton(element)) { return actualNode.value || actualNode.title || defaultButtonValues[actualNode.type] || ''; } var labelElement = findLabel(element); if (labelElement) { return accessibleNameComputation(labelElement, inLabelledByContext, true); } } return ''; } function checkARIA (element, inLabelledByContext, inControlContext) { let returnText = ''; const { actualNode } = element; if (!inLabelledByContext && actualNode.hasAttribute('aria-labelledby')) { // Store the return text, if it's empty, fall back to aria-label returnText = text.sanitize(dom.idrefs(actualNode, 'aria-labelledby').map(label => { if (label !== null) {// handle unfound elements by dom.idref if (actualNode === label) { encounteredNodes.pop(); } //let element be encountered twice const vLabel = axe.utils.getNodeFromTree(axe._tree[0], label); return accessibleNameComputation(vLabel, true, actualNode !== label); } else { return ''; } }).join(' ')); } if (!returnText && !(inControlContext && isEmbeddedControl(element)) && actualNode.hasAttribute('aria-label')) { return text.sanitize(actualNode.getAttribute('aria-label')); } return returnText; } /** * Determine the accessible text of an element, using logic from ARIA: * http://www.w3.org/TR/accname-aam-1.1/#mapping_additional_nd_name * * @param {HTMLElement} element The HTMLElement * @param {Boolean} inLabelledByContext True when in the context of resolving a labelledBy * @param {Boolean} inControlContext True when in the context of textifying a widget * @return {string} */ accessibleNameComputation = function (element, inLabelledByContext, inControlContext) { let returnText; // If the node was already checked or is null, skip if (!element || encounteredNodes.includes(element)) { return ''; // if the node is invalid, throw } else if (element !== null && element.actualNode instanceof Node !== true) { throw new Error('Invalid argument. Virtual Node must be provided'); //Step 2a: Skip if the element is hidden, unless part of labelledby } else if(!inLabelledByContext && !dom.isVisible(element.actualNode, true)) { return ''; } encounteredNodes.push(element); var role = element.actualNode.getAttribute('role'); //Step 2b & 2c returnText = checkARIA(element, inLabelledByContext, inControlContext); if (nonEmptyText(returnText)) { return returnText; } //Step 2d - native attribute or elements returnText = checkNative(element, inLabelledByContext, inControlContext); if (nonEmptyText(returnText)) { return returnText; } //Step 2e if (inControlContext) { returnText = formValueText(element); if (nonEmptyText(returnText)) { return returnText; } } //Step 2f if (!shouldNeverCheckSubtree(element) && (!role || aria.getRolesWithNameFromContents().indexOf(role) !== -1)) { returnText = getInnerText(element, inLabelledByContext, inControlContext); if (nonEmptyText(returnText)) { return returnText; } } //Step 2g - if text node, return value (handled in getInnerText) //Step 2h if (element.actualNode.hasAttribute('title')) { return element.actualNode.getAttribute('title'); } return ''; }; return text.sanitize(accessibleNameComputation(element, inLabelledByContext)); };
1
12,041
These should all call `findUpVirtual`.
dequelabs-axe-core
js
@@ -105,7 +105,7 @@ class HierarchicHTTPRequest(HTTPRequest): file_dict["path"] = path mime = mimetypes.guess_type(file_dict["path"])[0] or "application/octet-stream" - file_dict.get('mime-type', mime) + file_dict["mime-type"] = mime self.content_encoding = self.config.get('content-encoding', None)
1
""" Copyright 2017 BlazeMeter 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. """ import mimetypes import re from bzt import TaurusConfigError, TaurusInternalException from bzt.utils import ensure_is_dict, dehumanize_time, get_full_path VARIABLE_PATTERN = re.compile("\${.+\}") def has_variable_pattern(val): return bool(VARIABLE_PATTERN.search(val)) class Request(object): NAME = "request" def __init__(self, config, scenario=None): self.config = config self.scenario = scenario def priority_option(self, name, default=None): val = self.config.get(name, None) if val is None: val = self.scenario.get(name, None) if val is None and default is not None: val = default return val class HTTPRequest(Request): NAME = "request" def __init__(self, config, scenario, engine): self.engine = engine self.log = self.engine.log.getChild(self.__class__.__name__) super(HTTPRequest, self).__init__(config, scenario) msg = "Option 'url' is mandatory for request but not found in %s" % config self.url = self.config.get("url", TaurusConfigError(msg)) self.label = self.config.get("label", self.url) self.method = self.config.get("method", "GET") # TODO: add method to join dicts/lists from scenario/request level? self.headers = self.config.get("headers", {}) self.keepalive = self.config.get('keepalive', None) self.timeout = self.config.get('timeout', None) self.think_time = self.config.get('think-time', None) self.follow_redirects = self.config.get('follow-redirects', None) self.body = self.__get_body() def __get_body(self): body = self.config.get('body', None) body_file = self.config.get('body-file', None) if body_file: if body: self.log.warning('body and body-file fields are found, only first will take effect') else: body_file_path = self.engine.find_file(body_file) with open(body_file_path) as fhd: body = fhd.read() return body class HierarchicHTTPRequest(HTTPRequest): def __init__(self, config, scenario, engine): super(HierarchicHTTPRequest, self).__init__(config, scenario, engine) self.upload_files = self.config.get("upload-files", []) method = self.config.get("method") if method == "PUT" and len(self.upload_files) > 1: self.upload_files = self.upload_files[:1] for file_dict in self.upload_files: param = file_dict.get("param", None) if method == "PUT": file_dict["param"] = "" if method == "POST" and not param: raise TaurusConfigError("Items from upload-files must specify parameter name") path_exc = TaurusConfigError("Items from upload-files must specify path to file") path = str(file_dict.get("path", path_exc)) if not has_variable_pattern(path): # exclude variables path = get_full_path(self.engine.find_file(path)) # prepare full path for jmx else: msg = "Path '%s' contains variable and can't be expanded. Don't use relative paths in 'upload-files'!" self.log.warning(msg % path) file_dict["path"] = path mime = mimetypes.guess_type(file_dict["path"])[0] or "application/octet-stream" file_dict.get('mime-type', mime) self.content_encoding = self.config.get('content-encoding', None) class IfBlock(Request): NAME = "if" def __init__(self, condition, then_clause, else_clause, config): super(IfBlock, self).__init__(config) self.condition = condition self.then_clause = then_clause self.else_clause = else_clause def __repr__(self): then_clause = [repr(req) for req in self.then_clause] else_clause = [repr(req) for req in self.else_clause] return "IfBlock(condition=%s, then=%s, else=%s)" % (self.condition, then_clause, else_clause) class LoopBlock(Request): NAME = "loop" def __init__(self, loops, requests, config): super(LoopBlock, self).__init__(config) self.loops = loops self.requests = requests def __repr__(self): requests = [repr(req) for req in self.requests] return "LoopBlock(loops=%s, requests=%s)" % (self.loops, requests) class WhileBlock(Request): NAME = "while" def __init__(self, condition, requests, config): super(WhileBlock, self).__init__(config) self.condition = condition self.requests = requests def __repr__(self): requests = [repr(req) for req in self.requests] return "WhileBlock(condition=%s, requests=%s)" % (self.condition, requests) class ForEachBlock(Request): NAME = "foreach" def __init__(self, input_var, loop_var, requests, config): super(ForEachBlock, self).__init__(config) self.input_var = input_var self.loop_var = loop_var self.requests = requests def __repr__(self): requests = [repr(req) for req in self.requests] fmt = "ForEachBlock(input=%s, loop_var=%s, requests=%s)" return fmt % (self.input_var, self.loop_var, requests) class TransactionBlock(Request): NAME = "transaction" def __init__(self, name, requests, config, scenario): super(TransactionBlock, self).__init__(config, scenario) self.name = name self.requests = requests def __repr__(self): requests = [repr(req) for req in self.requests] fmt = "TransactionBlock(name=%s, requests=%s)" return fmt % (self.name, requests) class IncludeScenarioBlock(Request): NAME = "include-scenario" def __init__(self, scenario_name, config): super(IncludeScenarioBlock, self).__init__(config) self.scenario_name = scenario_name def __repr__(self): return "IncludeScenarioBlock(scenario_name=%r)" % self.scenario_name class RequestsParser(object): def __init__(self, scenario, engine): self.engine = engine self.scenario = scenario def __parse_request(self, req): if 'if' in req: condition = req.get("if") # TODO: apply some checks to `condition`? then_clause = req.get("then", TaurusConfigError("'then' clause is mandatory for 'if' blocks")) then_requests = self.__parse_requests(then_clause) else_clause = req.get("else", []) else_requests = self.__parse_requests(else_clause) return IfBlock(condition, then_requests, else_requests, req) elif 'loop' in req: loops = req.get("loop") do_block = req.get("do", TaurusConfigError("'do' option is mandatory for 'loop' blocks")) do_requests = self.__parse_requests(do_block) return LoopBlock(loops, do_requests, req) elif 'while' in req: condition = req.get("while") do_block = req.get("do", TaurusConfigError("'do' option is mandatory for 'while' blocks")) do_requests = self.__parse_requests(do_block) return WhileBlock(condition, do_requests, req) elif 'foreach' in req: iteration_str = req.get("foreach") match = re.match(r'(.+) in (.+)', iteration_str) if not match: msg = "'foreach' value should be in format '<elementName> in <collection>' but '%s' found" raise TaurusConfigError(msg % iteration_str) loop_var, input_var = match.groups() do_block = req.get("do", TaurusConfigError("'do' field is mandatory for 'foreach' blocks")) do_requests = self.__parse_requests(do_block) return ForEachBlock(input_var, loop_var, do_requests, req) elif 'transaction' in req: name = req.get('transaction') do_block = req.get('do', TaurusConfigError("'do' field is mandatory for transaction blocks")) do_requests = self.__parse_requests(do_block) return TransactionBlock(name, do_requests, req, self.scenario) elif 'include-scenario' in req: name = req.get('include-scenario') return IncludeScenarioBlock(name, req) elif 'action' in req: action = req.get('action') if action not in ('pause', 'stop', 'stop-now', 'continue'): raise TaurusConfigError("Action should be either 'pause', 'stop', 'stop-now' or 'continue'") target = req.get('target', 'current-thread') if target not in ('current-thread', 'all-threads'): msg = "Target for action should be either 'current-thread' or 'all-threads' but '%s' found" raise TaurusConfigError(msg % target) duration = req.get('pause-duration', None) if duration is not None: duration = dehumanize_time(duration) return ActionBlock(action, target, duration, req) elif 'set-variables' in req: mapping = req.get('set-variables') return SetVariables(mapping, req) else: return HierarchicHTTPRequest(req, self.scenario, self.engine) def __parse_requests(self, raw_requests, require_url=True): requests = [] for key in range(len(raw_requests)): # pylint: disable=consider-using-enumerate req = ensure_is_dict(raw_requests, key, "url") if not require_url and "url" not in req: req["url"] = None requests.append(self.__parse_request(req)) return requests def extract_requests(self, require_url=True): requests = self.scenario.get("requests", []) return self.__parse_requests(requests, require_url=require_url) class ActionBlock(Request): def __init__(self, action, target, duration, config): super(ActionBlock, self).__init__(config) self.action = action self.target = target self.duration = duration class SetVariables(Request): def __init__(self, mapping, config): super(SetVariables, self).__init__(config) self.mapping = mapping class RequestVisitor(object): def __init__(self): self.path = [] def clear_path_cache(self): self.path = [] def record_path(self, path): self.path.append(path) def visit(self, node): class_name = node.__class__.__name__.lower() visitor = getattr(self, 'visit_' + class_name, None) if visitor is not None: return visitor(node) raise TaurusInternalException("Visitor for class %s not found" % class_name) class ResourceFilesCollector(RequestVisitor): def __init__(self, executor): """ :param executor: JMeterExecutor """ super(ResourceFilesCollector, self).__init__() self.executor = executor def visit_hierarchichttprequest(self, request): files = [] body_file = request.config.get('body-file') if body_file and not has_variable_pattern(body_file): files.append(body_file) uploads = request.config.get('upload-files', []) files.extend([x['path'] for x in uploads if not has_variable_pattern(x['path'])]) if 'jsr223' in request.config: jsrs = request.config.get('jsr223') if isinstance(jsrs, dict): jsrs = [jsrs] for jsr in jsrs: if 'script-file' in jsr: files.append(jsr.get('script-file')) return files def visit_ifblock(self, block): files = [] for request in block.then_clause: files.extend(self.visit(request)) for request in block.else_clause: files.extend(self.visit(request)) return files def visit_loopblock(self, block): files = [] for request in block.requests: files.extend(self.visit(request)) return files def visit_whileblock(self, block): files = [] for request in block.requests: files.extend(self.visit(request)) return files def visit_foreachblock(self, block): files = [] for request in block.requests: files.extend(self.visit(request)) return files def visit_transactionblock(self, block): files = [] for request in block.requests: files.extend(self.visit(request)) return files def visit_includescenarioblock(self, block): scenario_name = block.scenario_name if scenario_name in self.path: msg = "Mutual recursion detected in include-scenario blocks (scenario %s)" raise TaurusConfigError(msg % scenario_name) self.record_path(scenario_name) scenario = self.executor.get_scenario(name=block.scenario_name) return self.executor.res_files_from_scenario(scenario) def visit_actionblock(self, _): return [] def visit_setvariables(self, _): return []
1
14,724
This changes the behavior. Original behavior was "set if not set", while new is "just set".
Blazemeter-taurus
py
@@ -110,7 +110,7 @@ public final class DefaultBearerTokenResolver implements BearerTokenResolver { throw new OAuth2AuthenticationException(error); } - return matcher.group("token"); + return authorization.substring(7); } return null; }
1
/* * Copyright 2002-2020 the original author or 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 org.springframework.security.oauth2.server.resource.web; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import org.springframework.http.HttpHeaders; import org.springframework.security.oauth2.core.OAuth2AuthenticationException; import org.springframework.security.oauth2.server.resource.BearerTokenError; import org.springframework.util.StringUtils; import static org.springframework.security.oauth2.server.resource.BearerTokenErrors.invalidRequest; import static org.springframework.security.oauth2.server.resource.BearerTokenErrors.invalidToken; /** * The default {@link BearerTokenResolver} implementation based on RFC 6750. * * @author Vedran Pavic * @since 5.1 * @see <a href="https://tools.ietf.org/html/rfc6750#section-2" target="_blank">RFC 6750 Section 2: Authenticated Requests</a> */ public final class DefaultBearerTokenResolver implements BearerTokenResolver { private static final Pattern authorizationPattern = Pattern.compile( "^Bearer (?<token>[a-zA-Z0-9-._~+/]+)=*$", Pattern.CASE_INSENSITIVE); private boolean allowFormEncodedBodyParameter = false; private boolean allowUriQueryParameter = false; private String bearerTokenHeaderName = HttpHeaders.AUTHORIZATION; /** * {@inheritDoc} */ @Override public String resolve(HttpServletRequest request) { String authorizationHeaderToken = resolveFromAuthorizationHeader(request); String parameterToken = resolveFromRequestParameters(request); if (authorizationHeaderToken != null) { if (parameterToken != null) { BearerTokenError error = invalidRequest("Found multiple bearer tokens in the request"); throw new OAuth2AuthenticationException(error); } return authorizationHeaderToken; } else if (parameterToken != null && isParameterTokenSupportedForRequest(request)) { return parameterToken; } return null; } /** * Set if transport of access token using form-encoded body parameter is supported. Defaults to {@code false}. * @param allowFormEncodedBodyParameter if the form-encoded body parameter is supported */ public void setAllowFormEncodedBodyParameter(boolean allowFormEncodedBodyParameter) { this.allowFormEncodedBodyParameter = allowFormEncodedBodyParameter; } /** * Set if transport of access token using URI query parameter is supported. Defaults to {@code false}. * * The spec recommends against using this mechanism for sending bearer tokens, and even goes as far as * stating that it was only included for completeness. * * @param allowUriQueryParameter if the URI query parameter is supported */ public void setAllowUriQueryParameter(boolean allowUriQueryParameter) { this.allowUriQueryParameter = allowUriQueryParameter; } /** * Set this value to configure what header is checked when resolving a Bearer Token. * This value is defaulted to {@link HttpHeaders#AUTHORIZATION}. * * This allows other headers to be used as the Bearer Token source such as {@link HttpHeaders#PROXY_AUTHORIZATION} * * @param bearerTokenHeaderName the header to check when retrieving the Bearer Token. * @since 5.4 */ public void setBearerTokenHeaderName(String bearerTokenHeaderName) { this.bearerTokenHeaderName = bearerTokenHeaderName; } private String resolveFromAuthorizationHeader(HttpServletRequest request) { String authorization = request.getHeader(this.bearerTokenHeaderName); if (StringUtils.startsWithIgnoreCase(authorization, "bearer")) { Matcher matcher = authorizationPattern.matcher(authorization); if (!matcher.matches()) { BearerTokenError error = invalidToken("Bearer token is malformed"); throw new OAuth2AuthenticationException(error); } return matcher.group("token"); } return null; } private static String resolveFromRequestParameters(HttpServletRequest request) { String[] values = request.getParameterValues("access_token"); if (values == null || values.length == 0) { return null; } if (values.length == 1) { return values[0]; } BearerTokenError error = invalidRequest("Found multiple bearer tokens in the request"); throw new OAuth2AuthenticationException(error); } private boolean isParameterTokenSupportedForRequest(HttpServletRequest request) { return ((this.allowFormEncodedBodyParameter && "POST".equals(request.getMethod())) || (this.allowUriQueryParameter && "GET".equals(request.getMethod()))); } }
1
15,575
Let's keep using the regular expression to make sure that the token is well-formed. I think the regular expression should be altered instead of doing a substring.
spring-projects-spring-security
java
@@ -26,10 +26,10 @@ public final class Array<T> implements Kind1<Array<?>, T>, IndexedSeq<T>, Serial private static final Array<?> EMPTY = new Array<>(new Object[0]); - private final Object[] back; + private final Object[] delegate; - private Array(Object[] back) { - this.back = back; + private Array(Object[] delegate) { + this.delegate = delegate; } static <T> Array<T> wrap(Object[] array) {
1
/* / \____ _ _ ____ ______ / \ ____ __ _______ * / / \/ \ / \/ \ / /\__\/ // \/ \ // /\__\ JΛVΛSLΛNG * _/ / /\ \ \/ / /\ \\__\\ \ // /\ \ /\\/ \ /__\ \ Copyright 2014-2016 Javaslang, http://javaslang.io * /___/\_/ \_/\____/\_/ \_/\__\/__/\__\_/ \_// \__/\_____/ Licensed under the Apache License, Version 2.0 */ package javaslang.collection; import javaslang.*; import javaslang.collection.ArrayModule.Combinations; import javaslang.control.Option; import java.io.Serializable; import java.util.*; import java.util.function.*; import java.util.stream.Collector; /** * Array is a Traversable wrapper for {@code Object[]} containing elements of type {@code T}. * * @param <T> Component type * @author Ruslan Sennov, Daniel Dietrich * @since 2.0.0 */ public final class Array<T> implements Kind1<Array<?>, T>, IndexedSeq<T>, Serializable { private static final long serialVersionUID = 1L; private static final Array<?> EMPTY = new Array<>(new Object[0]); private final Object[] back; private Array(Object[] back) { this.back = back; } static <T> Array<T> wrap(Object[] array) { return array.length == 0 ? empty() : new Array<T>(array); } /** * 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.Array}. * * @param <T> Component type of the Array. * @return A {@link javaslang.collection.Array} Collector. */ public static <T> Collector<T, ArrayList<T>, Array<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>, Array<T>> finisher = Array::ofAll; return Collector.of(supplier, accumulator, combiner, finisher); } @SuppressWarnings("unchecked") public static <T> Array<T> empty() { return (Array<T>) EMPTY; } /** * Narrows a widened {@code Array<? extends T>} to {@code Array<T>} * by performing a type safe-cast. This is eligible because immutable/read-only * collections are covariant. * * @param array An {@code Array}. * @param <T> Component type of the {@code Array}. * @return the given {@code array} instance as narrowed type {@code Array<T>}. */ @SuppressWarnings("unchecked") public static <T> Array<T> narrow(Array<? extends T> array) { return (Array<T>) array; } /** * Returns a singleton {@code Array}, i.e. a {@code Array} of one element. * * @param element An element. * @param <T> The component type * @return A new Array instance containing the given element */ public static <T> Array<T> of(T element) { return wrap(new Object[] { element }); } /** * Creates a Array of the given elements. * * @param <T> Component type of the Array. * @param elements Zero or more elements. * @return A Array containing the given elements in the same order. * @throws NullPointerException if {@code elements} is null */ @SuppressWarnings("varargs") @SafeVarargs public static <T> Array<T> of(T... elements) { Objects.requireNonNull(elements, "elements is null"); return wrap(Arrays.copyOf(elements, elements.length)); } /** * Creates a Array of the given elements. * <p> * The resulting Array 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 Array. * @param elements An Iterable of elements. * @return A Array containing the given elements in the same order. * @throws NullPointerException if {@code elements} is null */ @SuppressWarnings("unchecked") public static <T> Array<T> ofAll(Iterable<? extends T> elements) { Objects.requireNonNull(elements, "elements is null"); return elements instanceof Array ? (Array<T>) elements : wrap(toArray(elements)); } /** * Creates a Array that contains the elements of the given {@link java.util.stream.Stream}. * * @param javaStream A {@link java.util.stream.Stream} * @param <T> Component type of the Stream. * @return A Array containing the given elements in the same order. */ public static <T> Array<T> ofAll(java.util.stream.Stream<? extends T> javaStream) { Objects.requireNonNull(javaStream, "javaStream is null"); return wrap(javaStream.toArray()); } /** * Creates a Array based on the elements of a boolean array. * * @param array a boolean array * @return A new Array of Boolean values */ public static Array<Boolean> ofAll(boolean[] array) { Objects.requireNonNull(array, "array is null"); return ofAll(Iterator.ofAll(array)); } /** * Creates a Array based on the elements of a byte array. * * @param array a byte array * @return A new Array of Byte values */ public static Array<Byte> ofAll(byte[] array) { Objects.requireNonNull(array, "array is null"); return ofAll(Iterator.ofAll(array)); } /** * Creates a Array based on the elements of a char array. * * @param array a char array * @return A new Array of Character values */ public static Array<Character> ofAll(char[] array) { Objects.requireNonNull(array, "array is null"); return ofAll(Iterator.ofAll(array)); } /** * Creates a Array based on the elements of a double array. * * @param array a double array * @return A new Array of Double values */ public static Array<Double> ofAll(double[] array) { Objects.requireNonNull(array, "array is null"); return ofAll(Iterator.ofAll(array)); } /** * Creates a Array based on the elements of a float array. * * @param array a float array * @return A new Array of Float values */ public static Array<Float> ofAll(float[] array) { Objects.requireNonNull(array, "array is null"); return ofAll(Iterator.ofAll(array)); } /** * Creates a Array based on the elements of an int array. * * @param array an int array * @return A new Array of Integer values */ public static Array<Integer> ofAll(int[] array) { Objects.requireNonNull(array, "array is null"); return ofAll(Iterator.ofAll(array)); } /** * Creates a Array based on the elements of a long array. * * @param array a long array * @return A new Array of Long values */ public static Array<Long> ofAll(long[] array) { Objects.requireNonNull(array, "array is null"); return ofAll(Iterator.ofAll(array)); } /** * Creates a Array based on the elements of a short array. * * @param array a short array * @return A new Array of Short values */ public static Array<Short> ofAll(short[] array) { Objects.requireNonNull(array, "array is null"); return ofAll(Iterator.ofAll(array)); } /** * Returns an Array containing {@code n} values of a given Function {@code f} * over a range of integer values from 0 to {@code n - 1}. * * @param <T> Component type of the Array * @param n The number of elements in the Array * @param f The Function computing element values * @return An Array consisting of elements {@code f(0),f(1), ..., f(n - 1)} * @throws NullPointerException if {@code f} is null */ public static <T> Array<T> tabulate(int n, Function<? super Integer, ? extends T> f) { Objects.requireNonNull(f, "f is null"); return Collections.tabulate(n, f, empty(), Array::of); } /** * Returns an Array containing {@code n} values supplied by a given Supplier {@code s}. * * @param <T> Component type of the Array * @param n The number of elements in the Array * @param s The Supplier computing element values * @return An Array of size {@code n}, where each element contains the result supplied by {@code s}. * @throws NullPointerException if {@code s} is null */ public static <T> Array<T> fill(int n, Supplier<? extends T> s) { Objects.requireNonNull(s, "s is null"); return Collections.fill(n, s, empty(), Array::of); } public static Array<Character> range(char from, char toExclusive) { return ofAll(Iterator.range(from, toExclusive)); } public static Array<Character> rangeBy(char from, char toExclusive, int step) { return ofAll(Iterator.rangeBy(from, toExclusive, step)); } @GwtIncompatible public static Array<Double> rangeBy(double from, double toExclusive, double step) { return ofAll(Iterator.rangeBy(from, toExclusive, step)); } /** * Creates a Array of int numbers starting from {@code from}, extending to {@code toExclusive - 1}. * <p> * Examples: * <pre> * <code> * Array.range(0, 0) // = Array() * Array.range(2, 0) // = Array() * Array.range(-2, 2) // = Array(-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} */ public static Array<Integer> range(int from, int toExclusive) { return ofAll(Iterator.range(from, toExclusive)); } /** * Creates a Array of int numbers starting from {@code from}, extending to {@code toExclusive - 1}, * with {@code step}. * <p> * Examples: * <pre> * <code> * Array.rangeBy(1, 3, 1) // = Array(1, 2) * Array.rangeBy(1, 4, 2) // = Array(1, 3) * Array.rangeBy(4, 1, -2) // = Array(4, 2) * Array.rangeBy(4, 1, 2) // = Array() * </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 */ public static Array<Integer> rangeBy(int from, int toExclusive, int step) { return ofAll(Iterator.rangeBy(from, toExclusive, step)); } /** * Creates a Array of long numbers starting from {@code from}, extending to {@code toExclusive - 1}. * <p> * Examples: * <pre> * <code> * Array.range(0L, 0L) // = Array() * Array.range(2L, 0L) // = Array() * Array.range(-2L, 2L) // = Array(-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} */ public static Array<Long> range(long from, long toExclusive) { return ofAll(Iterator.range(from, toExclusive)); } /** * Creates a Array of long numbers starting from {@code from}, extending to {@code toExclusive - 1}, * with {@code step}. * <p> * Examples: * <pre> * <code> * Array.rangeBy(1L, 3L, 1L) // = Array(1L, 2L) * Array.rangeBy(1L, 4L, 2L) // = Array(1L, 3L) * Array.rangeBy(4L, 1L, -2L) // = Array(4L, 2L) * Array.rangeBy(4L, 1L, 2L) // = Array() * </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 */ public static Array<Long> rangeBy(long from, long toExclusive, long step) { return ofAll(Iterator.rangeBy(from, toExclusive, step)); } public static Array<Character> rangeClosed(char from, char toInclusive) { return ofAll(Iterator.rangeClosed(from, toInclusive)); } public static Array<Character> rangeClosedBy(char from, char toInclusive, int step) { return ofAll(Iterator.rangeClosedBy(from, toInclusive, step)); } @GwtIncompatible public static Array<Double> rangeClosedBy(double from, double toInclusive, double step) { return ofAll(Iterator.rangeClosedBy(from, toInclusive, step)); } /** * Creates a Array of int numbers starting from {@code from}, extending to {@code toInclusive}. * <p> * Examples: * <pre> * <code> * Array.rangeClosed(0, 0) // = Array(0) * Array.rangeClosed(2, 0) // = Array() * Array.rangeClosed(-2, 2) // = Array(-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} */ public static Array<Integer> rangeClosed(int from, int toInclusive) { return ofAll(Iterator.rangeClosed(from, toInclusive)); } /** * Creates a Array of int numbers starting from {@code from}, extending to {@code toInclusive}, * with {@code step}. * <p> * Examples: * <pre> * <code> * Array.rangeClosedBy(1, 3, 1) // = Array(1, 2, 3) * Array.rangeClosedBy(1, 4, 2) // = Array(1, 3) * Array.rangeClosedBy(4, 1, -2) // = Array(4, 2) * Array.rangeClosedBy(4, 1, 2) // = Array() * </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 */ public static Array<Integer> rangeClosedBy(int from, int toInclusive, int step) { return ofAll(Iterator.rangeClosedBy(from, toInclusive, step)); } /** * Creates a Array of long numbers starting from {@code from}, extending to {@code toInclusive}. * <p> * Examples: * <pre> * <code> * Array.rangeClosed(0L, 0L) // = Array(0L) * Array.rangeClosed(2L, 0L) // = Array() * Array.rangeClosed(-2L, 2L) // = Array(-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} */ public static Array<Long> rangeClosed(long from, long toInclusive) { return ofAll(Iterator.rangeClosed(from, toInclusive)); } /** * Creates a Array of long numbers starting from {@code from}, extending to {@code toInclusive}, * with {@code step}. * <p> * Examples: * <pre> * <code> * Array.rangeClosedBy(1L, 3L, 1L) // = Array(1L, 2L, 3L) * Array.rangeClosedBy(1L, 4L, 2L) // = Array(1L, 3L) * Array.rangeClosedBy(4L, 1L, -2L) // = Array(4L, 2L) * Array.rangeClosedBy(4L, 1L, 2L) // = Array() * </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 */ public static Array<Long> rangeClosedBy(long from, long toInclusive, long step) { return ofAll(Iterator.rangeClosedBy(from, toInclusive, step)); } /** * Creates a Array from a seed value and a function. * The function takes the seed at first. * The function should return {@code None} when it's * done generating the Array, otherwise {@code Some} {@code Tuple} * of the element for the next call and the value to add to the * resulting Array. * <p> * Example: * <pre> * <code> * Array.unfoldRight(10, x -&gt; x == 0 * ? Option.none() * : Option.of(new Tuple2&lt;gt;(x, x-1))); * // Array(10, 9, 8, 7, 6, 5, 4, 3, 2, 1)) * </code> * </pre> * * @param seed the start value for the iteration * @param f the function to get the next step of the iteration * @return an Array with the values built up by the iteration * @throws IllegalArgumentException if {@code f} is null */ public static <T, U> Array<U> unfoldRight(T seed, Function<? super T, Option<Tuple2<? extends U, ? extends T>>> f) { return Iterator.unfoldRight(seed, f).toArray(); } /** * Creates an Array from a seed value and a function. * The function takes the seed at first. * The function should return {@code None} when it's * done generating the list, otherwise {@code Some} {@code Tuple} * of the value to add to the resulting list and * the element for the next call. * <p> * Example: * <pre> * <code> * Array.unfoldLeft(10, x -&gt; x == 0 * ? Option.none() * : Option.of(new Tuple2&lt;gt;(x-1, x))); * // Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) * </code> * </pre> * * @param seed the start value for the iteration * @param f the function to get the next step of the iteration * @return an Array with the values built up by the iteration * @throws IllegalArgumentException if {@code f} is null */ public static <T, U> Array<U> unfoldLeft(T seed, Function<? super T, Option<Tuple2<? extends T, ? extends U>>> f) { return Iterator.unfoldLeft(seed, f).toArray(); } /** * Creates an Array from a seed value and a function. * The function takes the seed at first. * The function should return {@code None} when it's * done generating the list, otherwise {@code Some} {@code Tuple} * of the value to add to the resulting list and * the element for the next call. * <p> * Example: * <pre> * <code> * Array.unfold(10, x -&gt; x == 0 * ? Option.none() * : Option.of(new Tuple2&lt;gt;(x-1, x))); * // Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)) * </code> * </pre> * * @param seed the start value for the iteration * @param f the function to get the next step of the iteration * @return an Array with the values built up by the iteration * @throws IllegalArgumentException if {@code f} is null */ public static <T> Array<T> unfold(T seed, Function<? super T, Option<Tuple2<? extends T, ? extends T>>> f) { return Iterator.unfold(seed, f).toArray(); } @Override public Array<T> append(T element) { final Object[] copy = Arrays.copyOf(back, back.length + 1); copy[back.length] = element; return wrap(copy); } @Override public Array<T> appendAll(Iterable<? extends T> elements) { Objects.requireNonNull(elements, "elements is null"); final Object[] source = toArray(elements); if (source.length == 0) { return this; } else { final Object[] arr = Arrays.copyOf(back, back.length + source.length); System.arraycopy(source, 0, arr, back.length, source.length); return wrap(arr); } } @Override public boolean hasDefiniteSize() { return true; } @Override public boolean isTraversableAgain() { return true; } @SuppressWarnings("unchecked") @Override public Iterator<T> iterator() { return new AbstractIterator<T>() { private int index = 0; @Override public boolean hasNext() { return index < back.length; } @Override public T getNext() { return (T) back[index++]; } }; } @Override public Array<Array<T>> combinations() { return rangeClosed(0, length()).map(this::combinations).flatMap(Function.identity()); } @Override public Array<Array<T>> combinations(int k) { return Combinations.apply(this, Math.max(k, 0)); } @Override public Iterator<Array<T>> crossProduct(int power) { return Collections.crossProduct(empty(), this, power); } @SuppressWarnings("unchecked") @Override public T get(int index) { if (index < 0 || index >= length()) { throw new IndexOutOfBoundsException("get(" + index + ")"); } return (T) back[index]; } @Override public Array<T> distinct() { return distinctBy(Function.identity()); } @Override public Array<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 public <U> Array<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 public Array<T> drop(int n) { if (n <= 0) { return this; } else if (n >= length()) { return empty(); } else { final Object[] arr = new Object[back.length - n]; System.arraycopy(back, n, arr, 0, arr.length); return wrap(arr); } } @Override public Array<T> dropRight(int n) { if (n <= 0) { return this; } else if (n >= length()) { return empty(); } else { return wrap(Arrays.copyOf(back, back.length - n)); } } @Override public Array<T> dropUntil(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); return dropWhile(predicate.negate()); } @Override public Array<T> dropWhile(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); for (int i = 0; i < length(); i++) { if (!predicate.test(get(i))) { return drop(i); } } return empty(); } @Override public Array<T> filter(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); final java.util.List<T> list = new ArrayList<>(); for (T t : this) { if (predicate.test(t)) { list.add(t); } } if (list.isEmpty()) { return empty(); } else if (list.size() == size()) { return this; } else { return wrap(list.toArray()); } } @Override public <U> Array<U> flatMap(Function<? super T, ? extends Iterable<? extends U>> mapper) { Objects.requireNonNull(mapper, "mapper is null"); if (isEmpty()) { return empty(); } else { final java.util.List<U> list = new ArrayList<>(); for (T t : this) { for (U u : mapper.apply(t)) { list.add(u); } } return wrap(toArray(list)); } } @Override public <C> Map<C, Array<T>> groupBy(Function<? super T, ? extends C> classifier) { return Collections.groupBy(this, classifier, Array::ofAll); } @Override public Iterator<Array<T>> grouped(int size) { return sliding(size, size); } @SuppressWarnings("unchecked") @Override public T head() { if (isEmpty()) { throw new NoSuchElementException("head on empty Array"); } else { return (T) back[0]; } } @Override public int indexOf(T element, int from) { for (int i = from; i < length(); i++) { if (Objects.equals(get(i), element)) { return i; } } return -1; } @Override public Array<T> init() { if (isEmpty()) { throw new UnsupportedOperationException("init of empty vector"); } return dropRight(1); } @Override public Option<Array<T>> initOption() { return isEmpty() ? Option.none() : Option.some(init()); } @Override public boolean isEmpty() { return back.length == 0; } private Object readResolve() { return isEmpty() ? EMPTY : this; } @Override public Array<T> insert(int index, T element) { if (index < 0) { throw new IndexOutOfBoundsException("insert(" + index + ", e)"); } else if (index > length()) { throw new IndexOutOfBoundsException("insert(" + index + ", e) on Vector of length " + length()); } final Object[] arr = new Object[back.length + 1]; System.arraycopy(back, 0, arr, 0, index); arr[index] = element; System.arraycopy(back, index, arr, index + 1, back.length - index); return wrap(arr); } @Override public Array<T> insertAll(int index, Iterable<? extends T> elements) { if (index < 0) { throw new IndexOutOfBoundsException("insert(" + index + ", e)"); } else if (index > length()) { throw new IndexOutOfBoundsException("insert(" + index + ", e) on Array of length " + length()); } final Object[] list = toArray(elements); if (list.length == 0) { return this; } else { final Object[] arr = new Object[back.length + list.length]; System.arraycopy(back, 0, arr, 0, index); System.arraycopy(list, 0, arr, index, list.length); System.arraycopy(back, index, arr, index + list.length, back.length - index); return wrap(arr); } } @Override public Array<T> intersperse(T element) { if (back.length <= 1) { return this; } else { final Object[] arr = new Object[back.length * 2 - 1]; for (int i = 0; i < back.length; i++) { arr[i * 2] = back[i]; if (i > 0) { arr[i * 2 - 1] = element; } } return wrap(arr); } } @Override public int lastIndexOf(T element, int end) { for (int i = Math.min(end, length() - 1); i >= 0; i--) { if (Objects.equals(get(i), element)) { return i; } } return -1; } @Override public int length() { return back.length; } @Override public <U> Array<U> map(Function<? super T, ? extends U> mapper) { Objects.requireNonNull(mapper, "mapper is null"); final Object[] arr = new Object[length()]; for (int i = 0; i < back.length; i++) { arr[i] = mapper.apply(get(i)); } return wrap(arr); } @Override public Array<T> padTo(int length, T element) { final int actualLength = length(); if (length <= actualLength) { return this; } else { return appendAll(Iterator.continually(element).take(length - actualLength)); } } @Override public Array<T> leftPadTo(int length, T element) { final int actualLength = length(); if (length <= actualLength) { return this; } else { return prependAll(Iterator.continually(element).take(length - actualLength)); } } @Override public Array<T> patch(int from, Iterable<? extends T> that, int replaced) { from = from < 0 ? 0 : from; replaced = replaced < 0 ? 0 : replaced; Array<T> result = take(from).appendAll(that); from += replaced; result = result.appendAll(drop(from)); return result; } @Override public Tuple2<Array<T>, Array<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(ofAll(left), ofAll(right)); } @Override public Array<T> peek(Consumer<? super T> action) { Objects.requireNonNull(action, "action is null"); if (!isEmpty()) { action.accept(head()); } return this; } @Override public Array<Array<T>> permutations() { if (isEmpty()) { return empty(); } else if (back.length == 1) { return of(this); } else { Array<Array<T>> results = empty(); for (T t : distinct()) { for (Array<T> ts : remove(t).permutations()) { results = results.append(of(t).appendAll(ts)); } } return results; } } @Override public Array<T> prepend(T element) { return insert(0, element); } @Override public Array<T> prependAll(Iterable<? extends T> elements) { return insertAll(0, elements); } @Override public Array<T> remove(T element) { int index = -1; for (int i = 0; i < length(); i++) { final T value = get(i); if (element.equals(value)) { index = i; break; } } if (index < 0) { return this; } else { return removeAt(index); } } @Override public Array<T> removeFirst(Predicate<T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); int found = -1; for (int i = 0; i < length(); i++) { final T value = get(i); if (predicate.test(value)) { found = i; break; } } if (found < 0) { return this; } else { return removeAt(found); } } @Override public Array<T> removeLast(Predicate<T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); int found = -1; for (int i = length() - 1; i >= 0; i--) { final T value = get(i); if (predicate.test(value)) { found = i; break; } } if (found < 0) { return this; } else { return removeAt(found); } } @Override public Array<T> removeAt(int index) { if (index < 0) { throw new IndexOutOfBoundsException("removeAt(" + index + ")"); } else if (index >= length()) { throw new IndexOutOfBoundsException("removeAt(" + index + ")"); } else { final Object[] arr = new Object[length() - 1]; System.arraycopy(back, 0, arr, 0, index); System.arraycopy(back, index + 1, arr, index, length() - index - 1); return wrap(arr); } } @Override public Array<T> removeAll(T element) { return Collections.removeAll(this, element); } @Override public Array<T> removeAll(Iterable<? extends T> elements) { return Collections.removeAll(this, elements); } @Override public Array<T> removeAll(Predicate<? super T> predicate) { return Collections.removeAll(this, predicate); } @Override public Array<T> replace(T currentElement, T newElement) { final Object[] arr = new Object[length()]; boolean found = false; for (int i = 0; i < length(); i++) { final T value = get(i); if (found) { arr[i] = back[i]; } else { if (currentElement.equals(value)) { arr[i] = newElement; found = true; } else { arr[i] = back[i]; } } } return found ? wrap(arr) : this; } @Override public Array<T> replaceAll(T currentElement, T newElement) { final Object[] arr = new Object[length()]; boolean changed = false; for (int i = 0; i < length(); i++) { final T value = get(i); if (currentElement.equals(value)) { arr[i] = newElement; changed = true; } else { arr[i] = back[i]; } } return changed ? wrap(arr) : this; } @Override public Array<T> retainAll(Iterable<? extends T> elements) { return Collections.retainAll(this, elements); } @Override public Array<T> reverse() { final Object[] arr = new Object[back.length]; for (int i = 0; i < back.length; i++) { arr[back.length - 1 - i] = back[i]; } return wrap(arr); } @Override public Array<T> scan(T zero, BiFunction<? super T, ? super T, ? extends T> operation) { return scanLeft(zero, operation); } @Override public <U> Array<U> scanLeft(U zero, BiFunction<? super U, ? super T, ? extends U> operation) { Objects.requireNonNull(operation, "operation is null"); return Collections.scanLeft(this, zero, operation, new java.util.ArrayList<>(), (c, u) -> { c.add(u); return c; }, Array::ofAll); } @Override public <U> Array<U> scanRight(U zero, BiFunction<? super T, ? super U, ? extends U> operation) { Objects.requireNonNull(operation, "operation is null"); return Collections.scanRight(this, zero, operation, List.empty(), List::prepend, Value::toArray); } @Override public Array<T> slice(int beginIndex, int endIndex) { if (beginIndex >= endIndex || beginIndex >= length() || isEmpty()) { return empty(); } if (beginIndex <= 0 && endIndex >= length()) { return this; } final int index = Math.max(beginIndex, 0); final int length = Math.min(endIndex, length()) - index; final Object[] arr = new Object[length]; System.arraycopy(back, index, arr, 0, length); return wrap(arr); } @Override public Iterator<Array<T>> sliding(int size) { return sliding(size, 1); } @Override public Iterator<Array<T>> sliding(int size, int step) { return iterator().sliding(size, step).map(Array::ofAll); } @Override public Array<T> sorted() { final Object[] arr = Arrays.copyOf(back, back.length); Arrays.sort(arr); return wrap(arr); } @SuppressWarnings("unchecked") @Override public Array<T> sorted(Comparator<? super T> comparator) { final Object[] arr = Arrays.copyOf(back, back.length); Arrays.sort(arr, (o1, o2) -> comparator.compare((T) o1, (T) o2)); return wrap(arr); } @Override public <U extends Comparable<? super U>> Array<T> sortBy(Function<? super T, ? extends U> mapper) { return sortBy(U::compareTo, mapper); } @Override public <U> Array<T> sortBy(Comparator<? super U> comparator, Function<? super T, ? extends U> mapper) { final Function<? super T, ? extends U> domain = Function1.of(mapper::apply).memoized(); return toJavaStream() .sorted((e1, e2) -> comparator.compare(domain.apply(e1), domain.apply(e2))) .collect(collector()); } @Override public Tuple2<Array<T>, Array<T>> splitAt(int n) { return Tuple.of(take(n), drop(n)); } @Override public Tuple2<Array<T>, Array<T>> splitAt(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); final Array<T> init = takeWhile(predicate.negate()); return Tuple.of(init, drop(init.length())); } @Override public Tuple2<Array<T>, Array<T>> splitAtInclusive(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); for (int i = 0; i < back.length; i++) { final T value = get(i); if (predicate.test(value)) { if (i == back.length - 1) { return Tuple.of(this, empty()); } else { return Tuple.of(take(i + 1), drop(i + 1)); } } } return Tuple.of(this, empty()); } @Override public Spliterator<T> spliterator() { return Spliterators.spliterator(iterator(), length(), Spliterator.ORDERED | Spliterator.IMMUTABLE); } @Override public Tuple2<Array<T>, Array<T>> span(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); return Tuple.of(takeWhile(predicate), dropWhile(predicate)); } @Override public Array<T> subSequence(int beginIndex) { if (beginIndex < 0) { throw new IndexOutOfBoundsException("subSequence(" + beginIndex + ")"); } else if (beginIndex > length()) { throw new IndexOutOfBoundsException("subSequence(" + beginIndex + ")"); } else { return drop(beginIndex); } } @Override public Array<T> subSequence(int beginIndex, int endIndex) { if (beginIndex < 0 || beginIndex > endIndex || endIndex > length()) { throw new IndexOutOfBoundsException("subSequence(" + beginIndex + ", " + endIndex + ") on List of length " + length()); } else if (beginIndex == endIndex) { return empty(); } else { final Object[] arr = new Object[endIndex - beginIndex]; System.arraycopy(back, beginIndex, arr, 0, arr.length); return wrap(arr); } } @Override public Array<T> tail() { if (isEmpty()) { throw new UnsupportedOperationException("tail() on empty Array"); } else { final Object[] arr = new Object[back.length - 1]; System.arraycopy(back, 1, arr, 0, arr.length); return wrap(arr); } } @Override public Option<Array<T>> tailOption() { return isEmpty() ? Option.none() : Option.some(tail()); } @Override public Array<T> take(int n) { if (n >= length()) { return this; } else if (n <= 0) { return empty(); } else { return wrap(Arrays.copyOf(back, n)); } } @Override public Array<T> takeRight(int n) { if (n >= length()) { return this; } else if (n <= 0) { return empty(); } else { final Object[] arr = new Object[n]; System.arraycopy(back, back.length - n, arr, 0, n); return wrap(arr); } } @Override public Array<T> takeUntil(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); return takeWhile(predicate.negate()); } @Override public Array<T> takeWhile(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); for (int i = 0; i < back.length; i++) { final T value = get(i); if (!predicate.test(value)) { return take(i); } } return this; } /** * Transforms this {@code Array}. * * @param f A transformation * @param <U> Type of transformation result * @return An instance of type {@code U} * @throws NullPointerException if {@code f} is null */ public <U> U transform(Function<? super Array<T>, ? extends U> f) { Objects.requireNonNull(f, "f is null"); return f.apply(this); } @Override public <U> Array<U> unit(Iterable<? extends U> iterable) { return ofAll(iterable); } @Override public <T1, T2> Tuple2<Array<T1>, Array<T2>> unzip( Function<? super T, Tuple2<? extends T1, ? extends T2>> unzipper) { Objects.requireNonNull(unzipper, "unzipper is null"); if (isEmpty()) { return Tuple.of(empty(), empty()); } else { final Object[] xs = new Object[back.length]; final Object[] ys = new Object[back.length]; for (int i = 0; i < back.length; i++) { final Tuple2<? extends T1, ? extends T2> t = unzipper.apply(get(i)); xs[i] = t._1; ys[i] = t._2; } return Tuple.of(wrap(xs), wrap(ys)); } } @Override public <T1, T2, T3> Tuple3<Array<T1>, Array<T2>, Array<T3>> unzip3(Function<? super T, Tuple3<? extends T1, ? extends T2, ? extends T3>> unzipper) { Objects.requireNonNull(unzipper, "unzipper is null"); if (isEmpty()) { return Tuple.of(empty(), empty(), empty()); } else { final Object[] xs = new Object[back.length]; final Object[] ys = new Object[back.length]; final Object[] zs = new Object[back.length]; for (int i = 0; i < back.length; i++) { final Tuple3<? extends T1, ? extends T2, ? extends T3> t = unzipper.apply(get(i)); xs[i] = t._1; ys[i] = t._2; zs[i] = t._3; } return Tuple.of(wrap(xs), wrap(ys), wrap(zs)); } } @Override public Array<T> update(int index, T element) { if (index < 0) { throw new IndexOutOfBoundsException("update(" + index + ")"); } else if (index >= length()) { throw new IndexOutOfBoundsException("update(" + index + ")"); } else { final Object[] arr = toArray(this); arr[index] = element; return wrap(arr); } } @Override public <U> Array<Tuple2<T, U>> zip(Iterable<? extends U> that) { return zipWith(that, Tuple::of); } @Override public <U, R> Array<R> zipWith(Iterable<? extends U> that, BiFunction<? super T, ? super U, ? extends R> mapper) { Objects.requireNonNull(that, "that is null"); Objects.requireNonNull(mapper, "mapper is null"); return ofAll(iterator().zipWith(that, mapper)); } @Override public <U> Array<Tuple2<T, U>> zipAll(Iterable<? extends U> that, T thisElem, U thatElem) { Objects.requireNonNull(that, "that is null"); return ofAll(iterator().zipAll(that, thisElem, thatElem)); } @Override public Array<Tuple2<T, Integer>> zipWithIndex() { return ofAll(iterator().zipWithIndex()); } @Override public <U> Array<U> zipWithIndex(BiFunction<? super T, ? super Integer, ? extends U> mapper) { Objects.requireNonNull(mapper, "mapper is null"); return ofAll(iterator().zipWithIndex(mapper)); } @Override public boolean equals(Object o) { if (o == this) { return true; } else if (o instanceof Array) { final Object[] arr1 = back; final Object[] arr2 = ((Array<?>) o).back; return Objects.deepEquals(arr1, arr2); } else { return false; } } @Override public int hashCode() { return Objects.hash(back); } @Override public String stringPrefix() { return "Array"; } @Override public String toString() { return mkString(stringPrefix() + "(", ", ", ")"); } private static <T> Object[] toArray(Iterable<T> elements) { if (elements instanceof java.util.List) { final java.util.List<T> list = (java.util.List<T>) elements; return list.toArray(); } else { final java.util.Iterator<? extends T> it = elements.iterator(); final java.util.List<T> list = new java.util.ArrayList<>(); while (it.hasNext()) { list.add(it.next()); } return list.toArray(); } } } interface ArrayModule { final class Combinations { static <T> Array<Array<T>> apply(Array<T> elements, int k) { if (k == 0) { return Array.of(Array.empty()); } else { return elements.zipWithIndex().flatMap( t -> apply(elements.drop(t._2 + 1), (k - 1)).map(c -> c.prepend(t._1)) ); } } } }
1
8,976
All the operations are delegated to this entity, hence the rename. `back` can have too many meanings.
vavr-io-vavr
java
@@ -561,16 +561,9 @@ module Beaker block_on host do |host| skip_msg = host.skip_set_env? - if skip_msg.nil? - env = construct_env(host, opts) - logger.debug("setting local environment on #{host.name}") - if host['platform'] =~ /windows/ and host.is_cygwin? - env['CYGWIN'] = 'nodosfilewarning' - end - host.ssh_permit_user_environment - host.ssh_set_user_environment(env) - else - logger.debug(skip_msg) + unless skip_msg.nil? + logger.debug( skip_msg ) + next end if skip_msg.nil?
1
require 'pathname' [ 'command', "dsl" ].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'] FREEBSD_PACKAGES = ['curl', 'perl5|perl'] OPENBSD_PACKAGES = ['curl'] ARCHLINUX_PACKAGES = ['curl', 'ntp'] WINDOWS_PACKAGES = ['curl'] PSWINDOWS_PACKAGES = [] SLES10_PACKAGES = ['curl'] SLES_PACKAGES = ['curl', 'ntp'] DEBIAN_PACKAGES = ['curl', 'ntpdate', 'lsb-release'] CUMULUS_PACKAGES = ['curl', 'ntpdate'] SOLARIS10_PACKAGES = ['CSWcurl', 'CSWntp'] SOLARIS11_PACKAGES = ['curl', 'ntp'] 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" ROOT_KEYS_SYNC_CMD_AIX = "curl --tlsv1 -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] ntp_server = opts[:ntp_server] ? opts[:ntp_server] : NTPSERVER 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:#{ntp_server} /syncfromflags:manual /update")) host.exec(Command.new("w32tm /resync")) logger.notify "NTP date succeeded on #{host}" else case when host['platform'] =~ /sles-/ ntp_command = "sntp #{ntp_server}" when host['platform'] =~ /cisco_nexus/ ntp_server = host.exec(Command.new("getent hosts #{NTPSERVER} | head -n1 |cut -d \" \" -f1"), :acceptable_exit_codes => [0]).stdout ntp_command = "sudo -E sh -c 'export DCOS_CONTEXT=2;/isan/bin/ntpdate -u -t 20 #{ntp_server}'" else ntp_command = "ntpdate -u -t 20 #{ntp_server}" end success=false try = 0 until try >= TRIES do try += 1 if host.exec(Command.new(ntp_command), :accept_all_exit_codes => true).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 nil 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, # {HostPrebuiltSteps::CUMULUS_PACKAGES} on cumulus platform hosts, # {HostPrebuiltSteps::WINDOWS_PACKAGES} on cygwin-installed windows platform hosts, # and {HostPrebuiltSteps::PSWINDOWS_PACKAGES} on non-cygwin windows platform hosts. # # @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] block_on host do |host| case when host['platform'] =~ /sles-10/ check_and_install_packages_if_needed(host, SLES10_PACKAGES) when host['platform'] =~ /sles-/ check_and_install_packages_if_needed(host, SLES_PACKAGES) when host['platform'] =~ /debian/ check_and_install_packages_if_needed(host, DEBIAN_PACKAGES) when host['platform'] =~ /cumulus/ check_and_install_packages_if_needed(host, CUMULUS_PACKAGES) when (host['platform'] =~ /windows/ and host.is_cygwin?) raise RuntimeError, "cygwin is not installed on #{host}" if !host.cygwin_installed? check_and_install_packages_if_needed(host, WINDOWS_PACKAGES) when (host['platform'] =~ /windows/ and not host.is_cygwin?) check_and_install_packages_if_needed(host, PSWINDOWS_PACKAGES) when host['platform'] =~ /freebsd/ check_and_install_packages_if_needed(host, FREEBSD_PACKAGES) when host['platform'] =~ /openbsd/ check_and_install_packages_if_needed(host, OPENBSD_PACKAGES) when host['platform'] =~ /solaris-10/ check_and_install_packages_if_needed(host, SOLARIS10_PACKAGES) when host['platform'] =~ /solaris-1[1-9]/ check_and_install_packages_if_needed(host, SOLARIS11_PACKAGES) when host['platform'] =~ /archlinux/ check_and_install_packages_if_needed(host, ARCHLINUX_PACKAGES) when host['platform'] !~ /debian|aix|solaris|windows|sles-|osx-|cumulus|f5-|netscaler|cisco_/ check_and_install_packages_if_needed(host, UNIX_PACKAGES) end end rescue => e report_and_raise(logger, e, "validate") end # Installs the given packages if they aren't already on a host # # @param [Host] host Host to act on # @param [Array<String>] package_list List of package names to install def check_and_install_packages_if_needed host, package_list package_list.each do |string| alternatives = string.split('|') next if alternatives.any? { |pkg| host.check_for_package pkg } install_one_of_packages host, alternatives end end # Installs one of alternative packages (first available) # # @param [Host] host Host to act on # @param [Array<String>] packages List of package names (alternatives). def install_one_of_packages host, packages error = nil packages.each do |pkg| begin return host.install_package pkg rescue Beaker::Host::CommandFailure => e error = e end end raise error 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'] =~ /solaris|eos/ host.exec(Command.new(ROOT_KEYS_SYNC_CMD % "bash"), :accept_all_exit_codes => true) elsif host['platform'] =~ /aix/ host.exec(Command.new(ROOT_KEYS_SYNC_CMD_AIX % "env PATH=/usr/gnu/bin:$PATH bash"), :accept_all_exit_codes => true) else host.exec(Command.new(ROOT_KEYS_SYNC_CMD % "env PATH=\"/usr/gnu/bin:$PATH\" bash"), :accept_all_exit_codes => true) end end rescue => e report_and_raise(logger, e, "sync_root_keys") end # Run 'apt-get update' on the provided host or hosts. # If the platform of the provided host is not ubuntu, debian or cumulus: 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|cumulus/ 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 # On ubuntu, debian, or cumulus host or hosts: alter apt configuration to use # the internal Puppet Labs proxy {HostPrebuiltSteps::APT_CFG} proxy. # On solaris-11 host or hosts: alter pkg to point to # the internal Puppet Labs proxy {HostPrebuiltSteps::IPS_PKG_REPO}. # # Do nothing for other 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 ) logger = opts[:logger] block_on host do |host| case when host['platform'] =~ /ubuntu|debian|cumulus/ 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|7)/. Do nothing on host or hosts of other platforms. # @param [Host, Array<Host>] host One or more hosts to act upon. Will use individual host epel_url, epel_arch # and epel_pkg before using defaults provided in opts. # @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 # @option opts [String] :epel_url Link to download from 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 el_based?(host) && ['5','6','7'].include?(host['platform'].version) result = host.exec(Command.new('rpm -qa | grep epel-release'), :acceptable_exit_codes => [0,1]) if result.exit_code == 1 url_base = opts[:epel_url] url_base = opts[:epel_url_archive] if host['platform'].version == '5' host.install_package_with_rpm("#{url_base}/epel-release-latest-#{host['platform'].version}.noarch.rpm", '--replacepkgs', { :package_proxy => opts[:package_proxy] }) #update /etc/yum.repos.d/epel.repo for new baseurl host.exec(Command.new("sed -i -e 's;#baseurl.*$;baseurl=#{Regexp.escape("#{url_base}/#{host['platform'].version}")}/\$basearch;' /etc/yum.repos.d/epel.repo")) #remove mirrorlist host.exec(Command.new("sed -i -e '/mirrorlist/d' /etc/yum.repos.d/epel.repo")) 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 if host['platform'] =~ /windows/ if host.is_cygwin? resolv_conf = host.exec(Command.new("cat /cygdrive/c/Windows/System32/drivers/etc/hosts")).stdout else resolv_conf = host.exec(Command.new('type C:\Windows\System32\drivers\etc\hosts')).stdout end else resolv_conf = host.exec(Command.new("cat /etc/resolv.conf")).stdout end resolv_conf.each_line { |line| if line =~ /^\s*domain\s+(\S+)/ domain = $1 elsif line =~ /^\s*search\s+(\S+)/ search = $1 end } return_value ||= domain return_value ||= search if return_value return_value.gsub(/\.$/, '') end 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) if host['platform'] =~ /freebsd/ host.echo_to_file(etc_hosts, '/etc/hosts') elsif ((host['platform'] =~ /windows/) and not host.is_cygwin?) host.exec(Command.new("echo '#{etc_hosts}' >> C:\\Windows\\System32\\drivers\\etc\\hosts")) else host.exec(Command.new("echo '#{etc_hosts}' >> /etc/hosts")) end # AIX must be configured to prefer local DNS over external if host['platform'] =~ /aix/ aix_netsvc = '/etc/netsvc.conf' aix_local_resolv = 'hosts = local, bind' unless host.exec(Command.new("grep '#{aix_local_resolv}' #{aix_netsvc}"), :accept_all_exit_codes => true).exit_code == 0 host.exec(Command.new("echo '#{aix_local_resolv}' >> #{aix_netsvc}")) end end 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/ and host.is_cygwin? host.exec(Command.new('cp -r .ssh /cygdrive/c/Users/Administrator/.')) host.exec(Command.new('chown -R Administrator /cygdrive/c/Users/Administrator/.ssh')) elsif host['platform'] =~ /windows/ and not host.is_cygwin? # from https://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/xcopy.mspx?mfr=true: # /i : If Source is a directory or contains wildcards and Destination # does not exist, xcopy assumes destination specifies a directory # name and creates a new directory. Then, xcopy copies all specified # files into the new directory. By default, xcopy prompts you to # specify whether Destination is a file or a directory. # # /y : Suppresses prompting to confirm that you want to overwrite an # existing destination file. host.exec(Command.new("if exist .ssh (xcopy .ssh C:\\Users\\Administrator\\.ssh /s /e /y /i)")) elsif host['platform'] =~ /osx/ host.exec(Command.new('sudo cp -r .ssh /var/root/.'), {:pty => true}) elsif host['platform'] =~ /freebsd/ host.exec(Command.new('sudo cp -r .ssh /root/.'), {:pty => true}) elsif host['platform'] =~ /openbsd/ host.exec(Command.new('sudo cp -r .ssh /root/.'), {:pty => true}) elsif host['platform'] =~ /solaris-10/ host.exec(Command.new('sudo cp -r .ssh /.'), {:pty => true}) elsif host['platform'] =~ /solaris-11/ host.exec(Command.new('sudo cp -r .ssh /root/.'), {:pty => true}) else host.exec(Command.new('sudo su -c "cp -r .ssh /root/."'), {:pty => true}) end if host.selinux_enabled? host.exec(Command.new('sudo fixfiles restore /root')) 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; in the instance where a provider sets # host['ip'] to an address which facilitates access to the host externally, but the actual host # addresses differ from this, we check first for the presence of a host['vm_ip'] key first, # and use that if present. # @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| ip = host['vm_ip'] || host['ip'].to_s hostname = host[:vmhostname] || host.name domain = get_domain_name(host) etc_hosts += "#{ip}\t#{hostname}.#{domain} #{hostname}\n" end hosts.each do |host| set_etc_hosts(host, etc_hosts) end end # Update /etc/hosts to make updates.puppetlabs.com (aka the dujour server) resolve to 127.0.01, # so that we don't pollute the server with test data. See SERVER-1000, BKR-182, BKR-237, DJ-10 # for additional details. def disable_updates hosts, opts logger = opts[:logger] hosts.each do |host| next if host['platform'] =~ /netscaler/ logger.notify "Disabling updates.puppetlabs.com by modifying hosts file to resolve updates to 127.0.0.1 on #{host}" set_etc_hosts(host, "127.0.0.1\tupdates.puppetlabs.com\n") end end # Update sshd_config on debian, ubuntu, centos, el, redhat, cumulus, 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 sshd_config to allow root login" if host['platform'] =~ /osx/ # If osx > 10.10 use '/private/etc/ssh/sshd_config', else use '/etc/sshd_config' ssh_config_file = '/private/etc/ssh/sshd_config' ssh_config_file = '/etc/sshd_config' if host['platform'] =~ /^osx-10\.(9|10)/i host.exec(Command.new("sudo sed -i '' 's/#PermitRootLogin no/PermitRootLogin Yes/g' #{ssh_config_file}")) host.exec(Command.new("sudo sed -i '' 's/#PermitRootLogin yes/PermitRootLogin Yes/g' #{ssh_config_file}")) elsif host['platform'] =~ /freebsd/ host.exec(Command.new("sudo sed -i -e 's/#PermitRootLogin no/PermitRootLogin yes/g' /etc/ssh/sshd_config"), {:pty => true} ) elsif host['platform'] =~ /openbsd/ host.exec(Command.new("sudo perl -pi -e 's/^PermitRootLogin no/PermitRootLogin yes/' /etc/ssh/sshd_config"), {:pty => true} ) elsif host['platform'] =~ /solaris-10/ host.exec(Command.new("sudo gsed -i -e 's/#PermitRootLogin no/PermitRootLogin yes/g' /etc/ssh/sshd_config"), {:pty => true} ) elsif host['platform'] =~ /solaris-11/ host.exec(Command.new("if grep \"root::::type=role\" /etc/user_attr; then sudo rolemod -K type=normal root; else echo \"root user already type=normal\"; fi"), {:pty => true} ) host.exec(Command.new("sudo gsed -i -e 's/PermitRootLogin no/PermitRootLogin yes/g' /etc/ssh/sshd_config"), {:pty => true} ) elsif host['platform'] =~ /f5/ #interacting with f5 should using tmsh logger.warn("Attempting to enable root login non-supported platform: #{host.name}: #{host['platform']}") elsif host.is_cygwin? host.exec(Command.new("sed -ri 's/^#?PermitRootLogin /PermitRootLogin yes/' /etc/sshd_config"), {:pty => true}) elsif host.is_powershell? logger.warn("Attempting to enable root login non-supported platform: #{host.name}: #{host['platform']}") else host.exec(Command.new("sudo su -c \"sed -ri 's/^#?PermitRootLogin no|^#?PermitRootLogin yes/PermitRootLogin yes/' /etc/ssh/sshd_config\""), {:pty => true}) end #restart sshd if host['platform'] =~ /debian|ubuntu|cumulus/ host.exec(Command.new("sudo su -c \"service ssh restart\""), {:pty => true}) elsif host['platform'] =~ /arch|centos-7|el-7|redhat-7|fedora-(1[4-9]|2[0-9])/ host.exec(Command.new("sudo -E systemctl restart sshd.service"), {:pty => true}) elsif host['platform'] =~ /centos|el-|redhat|fedora|eos/ host.exec(Command.new("sudo -E /sbin/service sshd reload"), {:pty => true}) elsif host['platform'] =~ /(free|open)bsd/ host.exec(Command.new("sudo /etc/rc.d/sshd restart")) elsif host['platform'] =~ /solaris/ host.exec(Command.new("sudo -E svcadm restart network/ssh"), {: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|eos/ @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|eos/ 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, ubuntu, and cumulus # 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/, /cumulus/ host.exec(Command.new("echo 'Acquire::http::Proxy \"#{opts[:package_proxy]}/\";' >> /etc/apt/apt.conf.d/10proxy")) when /^el-/, /centos/, /fedora/, /redhat/, /eos/ 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 # Merge the two provided hashes so that an array of values is created from collisions # @param [Hash] h1 The first hash # @param [Hash] h2 The second hash # @return [Hash] A merged hash with arrays of values where collisions between the two hashes occured. # @example # > h1 = {:PATH=>"/1st/path"} # > h2 = {:PATH=>"/2nd/path"} # > additive_hash_merge(h1, h2) # => {:PATH=>["/1st/path", "/2nd/path"]} def additive_hash_merge h1, h2 merged_hash = {} normalized_h2 = h2.inject({}) { |h, (k, v)| h[k.to_s.upcase] = v; h } h1.each_pair do |key, val| normalized_key = key.to_s.upcase if normalized_h2.has_key?(normalized_key) merged_hash[key] = [h1[key], normalized_h2[normalized_key]] merged_hash[key] = merged_hash[key].uniq #remove dupes end end merged_hash end # Create the hash of default environment from host (:host_env), global options hash (:host_env) and default PE/Foss puppet variables # @param [Host] host The host to construct the environment hash for, host specific environment should be in :host_env in a hash # @param [Hash] opts Hash of options, including optional global host_env to be applied to each provided host # @return [Hash] A hash of environment variables for provided host def construct_env host, opts env = additive_hash_merge(host[:host_env], opts[:host_env]) env.each_key do |key| separator = host['pathseparator'] if key == 'PATH' && (not host.is_powershell?) separator = ':' end env[key] = env[key].join(separator) end env end # Add a host specific set of env vars to each provided host's ~/.ssh/environment # @param [Host, Array<Host>] host One or more hosts to act upon # @param [Hash{Symbol=>String}] opts Options to alter execution. def set_env host, opts logger = opts[:logger] block_on host do |host| skip_msg = host.skip_set_env? if skip_msg.nil? env = construct_env(host, opts) logger.debug("setting local environment on #{host.name}") if host['platform'] =~ /windows/ and host.is_cygwin? env['CYGWIN'] = 'nodosfilewarning' end host.ssh_permit_user_environment host.ssh_set_user_environment(env) else logger.debug(skip_msg) end if skip_msg.nil? #close the host to re-establish the connection with the new sshd settings host.close # print out the working env if host.is_powershell? host.exec(Command.new("SET")) else host.exec(Command.new("cat #{host[:ssh_env_file]}")) end end end end private # A helper to tell whether a host is el-based # @param [Host] host the host to act upon # # @return [Boolean] if the host is el_based def el_based? host ['centos','redhat','scientific','el','oracle'].include?(host['platform'].variant) end end end
1
15,799
@trevor-vaughan it looks like the spec failures are caused by the fact that although it was a great idea to put the guard clause here first & get the error case out of the way, the main code path has been erased when I assume it should be just below the guard clause.
voxpupuli-beaker
rb
@@ -22,6 +22,7 @@ import ( "github.com/algorand/go-algorand/config" "github.com/algorand/go-algorand/data/basics" "github.com/algorand/go-algorand/logging" + "github.com/algorand/go-algorand/protocol" ) var filterTimeout = 2 * config.Protocol.SmallLambda
1
// Copyright (C) 2019-2020 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 agreement import ( "time" "github.com/algorand/go-algorand/config" "github.com/algorand/go-algorand/data/basics" "github.com/algorand/go-algorand/logging" ) var filterTimeout = 2 * config.Protocol.SmallLambda var deadlineTimeout = config.Protocol.BigLambda + config.Protocol.SmallLambda var partitionStep = next + 3 var recoveryExtraTimeout = config.Protocol.SmallLambda // FilterTimeout is the duration of the first agreement step. func FilterTimeout() time.Duration { return filterTimeout } // DeadlineTimeout is the duration of the second agreement step. func DeadlineTimeout() time.Duration { return deadlineTimeout } type ( // round denotes a single round of the agreement protocol round = basics.Round // step is a sequence number denoting distinct stages in Algorand step uint64 // period is used to track progress with a given round in the protocol period uint64 ) // Algorand 2.0 steps const ( propose step = iota soft cert next ) const ( late step = 253 + iota redo down ) func (s step) nextVoteRanges() (lower, upper time.Duration) { extra := recoveryExtraTimeout // eg 2500 ms lower = deadlineTimeout // eg 17500 ms (15000 + 2500) upper = lower + extra // eg 20000 ms for i := next; i < s; i++ { extra *= 2 lower = upper upper = lower + extra } // e.g. if s == 14 // extra = 2 ^ 8 * 2500ms = 256 * 2.5 = 512 + 128 = 640s return lower, upper } // ReachesQuorum compares the current weight to the thresholds appropriate for the step, // to determine if we've reached a quorum. func (s step) reachesQuorum(proto config.ConsensusParams, weight uint64) bool { switch s { case propose: logging.Base().Warn("Called Propose.ReachesQuorum") return false case soft: return weight >= proto.SoftCommitteeThreshold case cert: return weight >= proto.CertCommitteeThreshold case late: return weight >= proto.LateCommitteeThreshold case redo: return weight >= proto.RedoCommitteeThreshold case down: return weight >= proto.DownCommitteeThreshold default: return weight >= proto.NextCommitteeThreshold } } // threshold returns the threshold necessary for the given step. // Do not compare values to the output of this function directly; // instead, use s.reachesQuorum to avoid off-by-one errors. func (s step) threshold(proto config.ConsensusParams) uint64 { switch s { case propose: logging.Base().Warn("Called propose.threshold") return 0 case soft: return proto.SoftCommitteeThreshold case cert: return proto.CertCommitteeThreshold case late: return proto.LateCommitteeThreshold case redo: return proto.RedoCommitteeThreshold case down: return proto.DownCommitteeThreshold default: return proto.NextCommitteeThreshold } } // CommitteeSize returns the size of the committee required for the step func (s step) committeeSize(proto config.ConsensusParams) uint64 { switch s { case propose: return proto.NumProposers case soft: return proto.SoftCommitteeSize case cert: return proto.CertCommitteeSize case late: return proto.LateCommitteeSize case redo: return proto.RedoCommitteeSize case down: return proto.DownCommitteeSize default: return proto.NextCommitteeSize } }
1
39,895
Could you delete this constant?
algorand-go-algorand
go
@@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +using BenchmarkDotNet.Disassemblers; using BenchmarkDotNet.Exporters; using BenchmarkDotNet.Loggers; using BenchmarkDotNet.Parameters;
1
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using BenchmarkDotNet.Exporters; using BenchmarkDotNet.Loggers; using BenchmarkDotNet.Parameters; using BenchmarkDotNet.Reports; using BenchmarkDotNet.Running; using Reporting; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; namespace BenchmarkDotNet.Extensions { internal class PerfLabExporter : ExporterBase { protected override string FileExtension => "json"; protected override string FileCaption => "perf-lab-report"; public PerfLabExporter() { } public override void ExportToLog(Summary summary, ILogger logger) { var reporter = Reporter.CreateReporter(); if (!reporter.InLab) // not running in the perf lab return; foreach (var report in summary.Reports) { var test = new Test(); test.Name = FullNameProvider.GetBenchmarkName(report.BenchmarkCase); test.Categories = report.BenchmarkCase.Descriptor.Categories; var results = from result in report.AllMeasurements where result.IterationMode == Engines.IterationMode.Workload && result.IterationStage == Engines.IterationStage.Result orderby result.LaunchIndex, result.IterationIndex select new { result.Nanoseconds, result.Operations }; test.Counters.Add(new Counter { Name = "Duration of single invocation", TopCounter = true, DefaultCounter = true, HigherIsBetter = false, MetricName = "ns", Results = (from result in results select result.Nanoseconds / result.Operations).ToList() }); test.Counters.Add(new Counter { Name = "Duration", TopCounter = false, DefaultCounter = false, HigherIsBetter = false, MetricName = "ms", Results = (from result in results select result.Nanoseconds).ToList() }); test.Counters.Add(new Counter { Name = "Operations", TopCounter = false, DefaultCounter = false, HigherIsBetter = true, MetricName = "Count", Results = (from result in results select (double)result.Operations).ToList() }); foreach (var metric in report.Metrics.Keys) { var m = report.Metrics[metric]; test.Counters.Add(new Counter { Name = m.Descriptor.DisplayName, TopCounter = false, DefaultCounter = false, HigherIsBetter = m.Descriptor.TheGreaterTheBetter, MetricName = m.Descriptor.Unit, Results = new[] { m.Value } }); } reporter.AddTest(test); } logger.WriteLine(reporter.GetJson()); } } }
1
11,599
looks like this snuck in from your other change?
dotnet-performance
.cs
@@ -10,11 +10,6 @@ module Ncr BUILDING_NUMBERS = YAML.load_file("#{Rails.root}/config/data/ncr/building_numbers.yml") class WorkOrder < ActiveRecord::Base - NCR_BA61_TIER1_BUDGET_APPROVER_MAILBOX = ENV['NCR_BA61_TIER1_BUDGET_MAILBOX'] || '[email protected]' - NCR_BA61_TIER2_BUDGET_APPROVER_MAILBOX = ENV['NCR_BA61_TIER2_BUDGET_MAILBOX'] || '[email protected]' - NCR_BA80_BUDGET_APPROVER_MAILBOX = ENV['NCR_BA80_BUDGET_MAILBOX'] || '[email protected]' - OOL_BA80_BUDGET_APPROVER_MAILBOX = ENV['NCR_OOL_BA80_BUDGET_MAILBOX'] || '[email protected]' - # must define before include PurchaseCardMixin def self.purchase_amount_column_name :amount
1
require 'csv' module Ncr # Make sure all table names use 'ncr_XXX' def self.table_name_prefix 'ncr_' end EXPENSE_TYPES = %w(BA60 BA61 BA80) BUILDING_NUMBERS = YAML.load_file("#{Rails.root}/config/data/ncr/building_numbers.yml") class WorkOrder < ActiveRecord::Base NCR_BA61_TIER1_BUDGET_APPROVER_MAILBOX = ENV['NCR_BA61_TIER1_BUDGET_MAILBOX'] || '[email protected]' NCR_BA61_TIER2_BUDGET_APPROVER_MAILBOX = ENV['NCR_BA61_TIER2_BUDGET_MAILBOX'] || '[email protected]' NCR_BA80_BUDGET_APPROVER_MAILBOX = ENV['NCR_BA80_BUDGET_MAILBOX'] || '[email protected]' OOL_BA80_BUDGET_APPROVER_MAILBOX = ENV['NCR_OOL_BA80_BUDGET_MAILBOX'] || '[email protected]' # must define before include PurchaseCardMixin def self.purchase_amount_column_name :amount end include ValueHelper include ProposalDelegate include PurchaseCardMixin attr_accessor :approving_official_email # This is a hack to be able to attribute changes to the correct user. This attribute needs to be set explicitly, then the update comment will use them as the "commenter". Defaults to the requester. attr_accessor :modifier after_initialize :set_defaults before_validation :normalize_values before_update :record_changes validates :approving_official_email, presence: true validates_email_format_of :approving_official_email validates :amount, presence: true validates :cl_number, format: { with: /\ACL\d{7}\z/, message: "must start with 'CL', followed by seven numbers" }, allow_blank: true validates :expense_type, inclusion: {in: EXPENSE_TYPES}, presence: true validates :function_code, format: { with: /\APG[A-Z0-9]{3}\z/, message: "must start with 'PG', followed by three letters or numbers" }, allow_blank: true validates :project_title, presence: true validates :vendor, presence: true validates :building_number, presence: true validates :rwa_number, presence: true, if: :ba80? validates :rwa_number, format: { with: /\A[a-zA-Z][0-9]{7}\z/, message: "must be one letter followed by 7 numbers" }, allow_blank: true validates :soc_code, format: { with: /\A[A-Z0-9]{3}\z/, message: "must be three letters or numbers" }, allow_blank: true FISCAL_YEAR_START_MONTH = 10 # 1-based scope :for_fiscal_year, lambda { |year| start_time = Time.zone.local(year - 1, FISCAL_YEAR_START_MONTH, 1) end_time = start_time + 1.year where(created_at: start_time...end_time) } def set_defaults # not sure why the latter condition is necessary...was getting some weird errors from the tests without it. -AF 10/5/2015 if !self.approving_official_email && self.approvers.any? self.approving_official_email = self.approvers.first.try(:email_address) end end # For budget attributes, converts empty strings to `nil`, so that the request isn't shown as being modified when the fields appear in the edit form. def normalize_values if self.cl_number.present? self.cl_number = self.cl_number.upcase self.cl_number.prepend('CL') unless self.cl_number.start_with?('CL') else self.cl_number = nil end if self.function_code.present? self.function_code.upcase! self.function_code.prepend('PG') unless self.function_code.start_with?('PG') else self.function_code = nil end if self.soc_code.present? self.soc_code.upcase! else self.soc_code = nil end end def approver_email_frozen? approval = self.individual_approvals.first approval && !approval.actionable? end def approver_changed? self.approving_official && self.approving_official.email_address != approving_official_email end # Check the approvers, accounting for frozen approving official def approvers_emails emails = self.system_approver_emails if self.approver_email_frozen? emails.unshift(self.approving_official.email_address) else emails.unshift(self.approving_official_email) end emails end def setup_approvals_and_observers emails = self.approvers_emails if self.emergency emails.each{|e| self.add_observer(e)} # skip state machine self.proposal.update(status: 'approved') else original_approvers = self.proposal.individual_approvals.non_pending.map(&:user) self.force_approvers(emails) self.notify_removed_approvers(original_approvers) end end def approving_official self.approvers.first end def current_approver if pending? currently_awaiting_approvers.first elsif approving_official approving_official elsif emergency and approvers.empty? nil else User.for_email(self.system_approver_emails.first) end end def final_approver if !emergency and approvers.any? approvers.last end end def email_approvers Dispatcher.on_proposal_update(self.proposal, self.modifier) end # Ignore values in certain fields if they aren't relevant. May want to # split these into different models def self.relevant_fields(expense_type) fields = [:description, :amount, :expense_type, :vendor, :not_to_exceed, :building_number, :org_code, :direct_pay, :cl_number, :function_code, :soc_code] case expense_type when 'BA61' fields << :emergency when 'BA80' fields.concat([:rwa_number, :code]) end fields end def relevant_fields Ncr::WorkOrder.relevant_fields(self.expense_type) end # Methods for Client Data interface def fields_for_display attributes = self.relevant_fields attributes.map{|key| [WorkOrder.human_attribute_name(key), self[key]]} end # will return nil if the `org_code` is blank or not present in Organization list def organization # TODO reference by `code` rather than storing the whole thing code = (self.org_code || '').split(' ', 2)[0] Ncr::Organization.find(code) end def ba80? self.expense_type == 'BA80' end def total_price self.amount || 0.0 end # may be replaced with paper-trail or similar at some point def version self.updated_at.to_i end def name self.project_title end def system_approver_emails results = [] if %w(BA60 BA61).include?(self.expense_type) unless self.organization.try(:whsc?) results << self.class.ba61_tier1_budget_mailbox end results << self.class.ba61_tier2_budget_mailbox else # BA80 if self.organization.try(:ool?) results << self.class.ool_ba80_budget_mailbox else results << self.class.ba80_budget_mailbox end end results end def self.ba61_tier1_budget_mailbox NCR_BA61_TIER1_BUDGET_APPROVER_MAILBOX end def self.ba61_tier2_budget_mailbox NCR_BA61_TIER2_BUDGET_APPROVER_MAILBOX end def self.ba80_budget_mailbox NCR_BA80_BUDGET_APPROVER_MAILBOX end def self.ool_ba80_budget_mailbox OOL_BA80_BUDGET_APPROVER_MAILBOX end def org_id self.organization.try(:code) end def building_id regex = /\A(\w{8}) .*\z/ if self.building_number && regex.match(self.building_number) regex.match(self.building_number)[1] else self.building_number end end def as_json super.merge(org_id: self.org_id, building_id: self.building_id) end def public_identifier "FY" + fiscal_year.to_s.rjust(2, "0") + "-#{proposal.id}" end def fiscal_year year = self.created_at.nil? ? Time.zone.now.year : self.created_at.year month = self.created_at.nil? ? Time.zone.now.month : self.created_at.month if month >= 10 year += 1 end year % 100 # convert to two-digit end protected # TODO move to Proposal model def record_changes changed_attributes = self.changed_attributes.except(:updated_at) comment_texts = [] bullet = changed_attributes.length > 1 ? '- ' : '' changed_attributes.each do |key, value| former = property_to_s(self.send(key + "_was")) value = property_to_s(self[key]) property_name = WorkOrder.human_attribute_name(key) comment_texts << WorkOrder.update_comment_format(property_name, value, bullet, former) end if !comment_texts.empty? if self.approved? comment_texts << "_Modified post-approval_" end proposal.comments.create( comment_text: comment_texts.join("\n"), update_comment: true, user: self.modifier || self.requester ) end end def self.update_comment_format(key, value, bullet, former=nil) if !former || former.empty? from = "" else from = "from #{former} " end if value.empty? to = "*empty*" else to = value end "#{bullet}*#{key}* was changed " + from + "to #{to}" end # Generally shouldn't be called directly as it doesn't account for # emergencies, or notify removed approvers def force_approvers(emails) individuals = emails.map do |email| user = User.for_email(email) user.update!(client_slug: 'ncr') # Reuse existing approvals, if present self.proposal.existing_approval_for(user) || Approvals::Individual.new(user: user) end self.proposal.root_approval = Approvals::Serial.new(child_approvals: individuals) end def notify_removed_approvers(original_approvers) current_approvers = self.proposal.individual_approvals.non_pending.map(&:user) removed_approvers_to_notify = original_approvers - current_approvers Dispatcher.on_approver_removal(self.proposal, removed_approvers_to_notify) end end end
1
15,241
These env vars are not set in any CF environment, on purpose, because we are moving away from using env vars to store role-based information and instead using the database. So in a CF environment, the wrong emails get used (the defaults, rather than what is in the db).
18F-C2
rb
@@ -1,4 +1,4 @@ -<%# locals: { question, answer, readonly, locking } %> +<%# locals: { template, question, answer, readonly, locking } %> <!-- This partial creates a form for each type of question. The local variables are: plan, answer, question, readonly -->
1
<%# locals: { question, answer, readonly, locking } %> <!-- This partial creates a form for each type of question. The local variables are: plan, answer, question, readonly --> <!-- Question text --> <% q_format = question.question_format %> <% if q_format.rda_metadata? %> <p> <strong><%= raw question.text %></strong> </p> <% answer_hash = answer.answer_hash %> <div class="rda_metadata"><button class="remove-standard" style="display:none;"></button> <div class="selected_standards"><strong><%=_("Your Selected Standards:")%></strong></br><ul class="list bullet"></ul></div> <div class="rda_right" style="float:right;width:50%;margin-bottom:5px;display:none;"> OR Search:</br> <input type="text" data-provide="typeahead" class="standards-typeahead"></input></br> <button class="btn btn-primary select_standard_typeahead"><%=_("Add Standard")%></button> </div> <div class="subject"><%=_("Please select a subject")%></br> <select name="subject" class="form-control"></select> </div> <div class="sub-subject"><%=_("Please select a sub-subject")%></br> <select name="sub-subject" class="form-control"></select> </div> </br> <div class="suggested-answer-div"> <span class="suggested-answer-intro"> <strong><%=_("Browse Standards") %></strong> </span> <div class="browse-standards-border"> <p class="suggested-answer"> <strong><%=_("Please wait, Standards are loading")%></strong> </p> </div> <div> <a href="#" class="custom-standard"><strong>Standard not listed? Add your own.</strong></a> <div class="add-custom-standard" style="display:none;"> <input type="text" class="custom-standard-name"></input> <button class="btn btn-primary submit_custom_standard">Add Standard</button> </div> </div> </div> </div> <% end %> <%= form_for answer, url: {controller: :answers, action: :create_or_update}, html: {method: :post, 'data-autosave': question.id, class: 'form-answer' } do |f| %> <% if !readonly %> <%= f.hidden_field :plan_id %> <%= f.hidden_field :question_id %> <%= f.hidden_field :lock_version %> <% if q_format.rda_metadata? %> <%= hidden_field_tag :standards, answer_hash['standards'].to_json %> <% end %> <% end %> <fieldset <%= 'disabled' if readonly %>> <% if question.option_based? || question.question_format.rda_metadata? %> <%= render(partial: 'questions/new_edit_question_option_based', locals: { f: f, question: question, answer: answer }) %> <% elsif question.question_format.textfield?%> <%= render(partial: 'questions/new_edit_question_textfield', locals: { f: f, question: question, answer: answer }) %> <% elsif question.question_format.textarea? %> <%= render(partial: 'questions/new_edit_question_textarea', locals: { f: f, question: question, answer: answer, locking: locking }) %> <% end %> <%= f.button(_('Save'), class: "btn btn-default", type: "submit") %> </fieldset> <!--Example Answer area --> <% annotation = question.first_example_answer %> <% if annotation.present? && annotation.text.present? %> <div class="panel panel-default"> <span class="label label-default"> <%="#{annotation.org.abbreviation} "%> <%=_('example answer')%> </span> <div class="panel-body"> <%= raw annotation.text %> </div> </div> <% end %> <% end %>
1
17,505
this partial is used also for previewing a template, did you test if still works?
DMPRoadmap-roadmap
rb
@@ -22,6 +22,19 @@ import ( "github.com/spf13/cobra" ) +var ( + appInitAppTypePrompt = "Which type of " + color.Emphasize("infrastructure pattern") + " best represents your application?" + appInitAppTypeHelpPrompt = `Your application's architecture. Most applications need additional AWS resources to run. +To help setup the infrastructure resources, select what "kind" or "type" of application you want to build.` + + fmtAppInitAppNamePrompt = "What do you want to " + color.Emphasize("name") + " this %s?" + fmtAppInitAppNameHelpPrompt = `The name will uniquely identify this application within your %s project. +Deployed resources (such as your service, logs) will contain this app's name and be tagged with it.` + + fmtAppInitDockerfilePrompt = "Which Dockerfile would you like to use for %s app?" + appInitDockerfileHelpPrompt = "Dockerfile to use for building your application's container image." +) + const ( fmtAddAppToProjectStart = "Creating ECR repositories for application %s." fmtAddAppToProjectFailed = "Failed to create ECR repositories for application %s."
1
// Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package cli import ( "errors" "fmt" "os" "path/filepath" "github.com/aws/amazon-ecs-cli-v2/internal/pkg/archer" "github.com/aws/amazon-ecs-cli-v2/internal/pkg/aws/session" "github.com/aws/amazon-ecs-cli-v2/internal/pkg/deploy/cloudformation" "github.com/aws/amazon-ecs-cli-v2/internal/pkg/manifest" "github.com/aws/amazon-ecs-cli-v2/internal/pkg/store" "github.com/aws/amazon-ecs-cli-v2/internal/pkg/term/color" "github.com/aws/amazon-ecs-cli-v2/internal/pkg/term/log" termprogress "github.com/aws/amazon-ecs-cli-v2/internal/pkg/term/progress" "github.com/aws/amazon-ecs-cli-v2/internal/pkg/workspace" "github.com/spf13/afero" "github.com/spf13/cobra" ) const ( fmtAddAppToProjectStart = "Creating ECR repositories for application %s." fmtAddAppToProjectFailed = "Failed to create ECR repositories for application %s." fmtAddAppToProjectComplete = "Created ECR repositories for application %s." ) // InitAppOpts holds the configuration needed to create a new application. type InitAppOpts struct { // Fields with matching flags. AppType string AppName string DockerfilePath string // Interfaces to interact with dependencies. fs afero.Fs manifestWriter archer.ManifestIO appStore archer.ApplicationStore projGetter archer.ProjectGetter projDeployer projectDeployer prog progress // Outputs stored on successful actions. manifestPath string *GlobalOpts } // Ask prompts for fields that are required but not passed in. func (opts *InitAppOpts) Ask() error { if opts.AppType == "" { if err := opts.askAppType(); err != nil { return err } } if opts.AppName == "" { if err := opts.askAppName(); err != nil { return err } } if opts.DockerfilePath == "" { if err := opts.askDockerfile(); err != nil { return err } } return nil } // Validate returns an error if the flag values passed by the user are invalid. func (opts *InitAppOpts) Validate() error { if opts.AppType != "" { if err := validateApplicationType(opts.AppType); err != nil { return err } } if opts.AppName != "" { if err := validateApplicationName(opts.AppName); err != nil { return err } } if opts.DockerfilePath != "" { if _, err := opts.fs.Stat(opts.DockerfilePath); err != nil { return err } } if opts.ProjectName() == "" { return errNoProjectInWorkspace } return nil } // Execute writes the application's manifest file and stores the application in SSM. func (opts *InitAppOpts) Execute() error { if err := opts.ensureNoExistingApp(opts.ProjectName(), opts.AppName); err != nil { return err } manifestPath, err := opts.createManifest() if err != nil { return err } opts.manifestPath = manifestPath log.Infoln() log.Successf("Wrote the manifest for %s app at '%s'\n", color.HighlightUserInput(opts.AppName), color.HighlightResource(opts.manifestPath)) log.Infoln("Your manifest contains configurations like your container size and ports.") log.Infoln() proj, err := opts.projGetter.GetProject(opts.ProjectName()) if err != nil { return fmt.Errorf("get project %s: %w", opts.ProjectName(), err) } opts.prog.Start(fmt.Sprintf(fmtAddAppToProjectStart, opts.AppName)) if err := opts.projDeployer.AddAppToProject(proj, opts.AppName); err != nil { opts.prog.Stop(log.Serrorf(fmtAddAppToProjectFailed, opts.AppName)) return fmt.Errorf("add app %s to project %s: %w", opts.AppName, opts.ProjectName(), err) } opts.prog.Stop(log.Ssuccessf(fmtAddAppToProjectComplete, opts.AppName)) return opts.createAppInProject(opts.ProjectName()) } func (opts *InitAppOpts) createManifest() (string, error) { manifest, err := manifest.CreateApp(opts.AppName, opts.AppType, opts.DockerfilePath) if err != nil { return "", fmt.Errorf("generate a manifest: %w", err) } manifestBytes, err := manifest.Marshal() if err != nil { return "", fmt.Errorf("marshal manifest: %w", err) } filename := opts.manifestWriter.AppManifestFileName(opts.AppName) manifestPath, err := opts.manifestWriter.WriteFile(manifestBytes, filename) if err != nil { return "", fmt.Errorf("write manifest for app %s: %w", opts.AppName, err) } wkdir, err := os.Getwd() if err != nil { return "", fmt.Errorf("get working directory: %w", err) } relPath, err := filepath.Rel(wkdir, manifestPath) if err != nil { return "", fmt.Errorf("relative path of manifest file: %w", err) } return relPath, nil } func (opts *InitAppOpts) createAppInProject(projectName string) error { if err := opts.appStore.CreateApplication(&archer.Application{ Project: projectName, Name: opts.AppName, Type: opts.AppType, }); err != nil { return fmt.Errorf("saving application %s: %w", opts.AppName, err) } return nil } func (opts *InitAppOpts) askAppType() error { t, err := opts.prompt.SelectOne( "Which type of infrastructure pattern best represents your application?", `Your application's architecture. Most applications need additional AWS resources to run. To help setup the infrastructure resources, select what "kind" or "type" of application you want to build.`, manifest.AppTypes) if err != nil { return fmt.Errorf("failed to get type selection: %w", err) } opts.AppType = t return nil } func (opts *InitAppOpts) askAppName() error { name, err := opts.prompt.Get( fmt.Sprintf("What do you want to call this %s?", opts.AppType), fmt.Sprintf(`The name will uniquely identify this application within your %s project. Deployed resources (such as your service, logs) will contain this app's name and be tagged with it.`, opts.ProjectName()), validateApplicationName) if err != nil { return fmt.Errorf("failed to get application name: %w", err) } opts.AppName = name return nil } // askDockerfile prompts for the Dockerfile by looking at sub-directories with a Dockerfile. // If the user chooses to enter a custom path, then we prompt them for the path. func (opts *InitAppOpts) askDockerfile() error { // TODO https://github.com/aws/amazon-ecs-cli-v2/issues/206 dockerfiles, err := listDockerfiles(opts.fs, ".") if err != nil { return err } sel, err := opts.prompt.SelectOne( fmt.Sprintf("Which Dockerfile would you like to use for %s app?", opts.AppName), "Dockerfile to use for building your application's container image.", dockerfiles, ) if err != nil { return fmt.Errorf("failed to select Dockerfile: %w", err) } opts.DockerfilePath = sel return nil } func (opts *InitAppOpts) ensureNoExistingApp(projectName, appName string) error { _, err := opts.appStore.GetApplication(projectName, opts.AppName) // If the app doesn't exist - that's perfect, return no error. var existsErr *store.ErrNoSuchApplication if errors.As(err, &existsErr) { return nil } // If there's no error, that means we were able to fetch an existing app if err == nil { return fmt.Errorf("application %s already exists under project %s", appName, projectName) } // Otherwise, there was an error calling the store return fmt.Errorf("couldn't check if application %s exists in project %s: %w", appName, projectName, err) } // RecommendedActions returns follow-up actions the user can take after successfully executing the command. func (opts *InitAppOpts) RecommendedActions() []string { return []string{ fmt.Sprintf("Update your manifest %s to change the defaults.", color.HighlightResource(opts.manifestPath)), fmt.Sprintf("Run %s to deploy your application to a %s environment.", color.HighlightCode(fmt.Sprintf("ecs-preview app deploy --name %s --env %s", opts.AppName, defaultEnvironmentName)), defaultEnvironmentName), } } // BuildAppInitCmd build the command for creating a new application. func BuildAppInitCmd() *cobra.Command { opts := &InitAppOpts{ GlobalOpts: NewGlobalOpts(), } cmd := &cobra.Command{ Use: "init", Short: "Creates a new application in a project.", Long: `Creates a new application in a project. This command is also run as part of "ecs-preview init".`, Example: ` Create a "frontend" web application. /code $ ecs-preview app init --name frontend --app-type "Load Balanced Web App" --dockerfile ./frontend/Dockerfile`, PreRunE: runCmdE(func(cmd *cobra.Command, args []string) error { opts.fs = &afero.Afero{Fs: afero.NewOsFs()} store, err := store.New() if err != nil { return fmt.Errorf("couldn't connect to project datastore: %w", err) } opts.appStore = store opts.projGetter = store ws, err := workspace.New() if err != nil { return fmt.Errorf("workspace cannot be created: %w", err) } opts.manifestWriter = ws sess, err := session.Default() if err != nil { return err } opts.projDeployer = cloudformation.New(sess) opts.prog = termprogress.NewSpinner() return opts.Validate() }), RunE: runCmdE(func(cmd *cobra.Command, args []string) error { log.Warningln("It's best to run this command in the root of your workspace.") if err := opts.Ask(); err != nil { return err } if err := opts.Validate(); err != nil { // validate flags return err } return opts.Execute() }), PostRunE: func(cmd *cobra.Command, args []string) error { log.Infoln("Recommended follow-up actions:") for _, followup := range opts.RecommendedActions() { log.Infof("- %s\n", followup) } return nil }, } cmd.Flags().StringVarP(&opts.AppType, appTypeFlag, appTypeFlagShort, "" /* default */, appTypeFlagDescription) cmd.Flags().StringVarP(&opts.AppName, nameFlag, nameFlagShort, "" /* default */, appFlagDescription) cmd.Flags().StringVarP(&opts.DockerfilePath, dockerFileFlag, dockerFileFlagShort, "" /* default */, dockerFileFlagDescription) return cmd }
1
11,530
Would it be better to put like `Which Dockerfile would you like to use for %s?`
aws-copilot-cli
go
@@ -3636,8 +3636,8 @@ Model.hydrate = function(obj) { * @see response http://docs.mongodb.org/v2.6/reference/command/update/#output * @param {Object} filter * @param {Object} doc - * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) - * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) + * @param {Object} [options] optional see [`Query.prototype.setOptions()`](/api.html#query_Query-setOptions) + * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](/docs/guide.html#strict) * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document * @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern) * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server.
1
'use strict'; /*! * Module dependencies. */ const Aggregate = require('./aggregate'); const ChangeStream = require('./cursor/ChangeStream'); const Document = require('./document'); const DocumentNotFoundError = require('./error/notFound'); const DivergentArrayError = require('./error/divergentArray'); const EventEmitter = require('events').EventEmitter; const MongooseBuffer = require('./types/buffer'); const MongooseError = require('./error/index'); const OverwriteModelError = require('./error/overwriteModel'); const PromiseProvider = require('./promise_provider'); const Query = require('./query'); const RemoveOptions = require('./options/removeOptions'); const SaveOptions = require('./options/saveOptions'); const Schema = require('./schema'); const ServerSelectionError = require('./error/serverSelection'); const SkipPopulateValue = require('./helpers/populate/SkipPopulateValue'); const ValidationError = require('./error/validation'); const VersionError = require('./error/version'); const ParallelSaveError = require('./error/parallelSave'); const applyQueryMiddleware = require('./helpers/query/applyQueryMiddleware'); const applyHooks = require('./helpers/model/applyHooks'); const applyMethods = require('./helpers/model/applyMethods'); const applyStaticHooks = require('./helpers/model/applyStaticHooks'); const applyStatics = require('./helpers/model/applyStatics'); const applyWriteConcern = require('./helpers/schema/applyWriteConcern'); const assignVals = require('./helpers/populate/assignVals'); const castBulkWrite = require('./helpers/model/castBulkWrite'); const discriminator = require('./helpers/model/discriminator'); const each = require('./helpers/each'); const getDiscriminatorByValue = require('./helpers/discriminator/getDiscriminatorByValue'); const getModelsMapForPopulate = require('./helpers/populate/getModelsMapForPopulate'); const immediate = require('./helpers/immediate'); const internalToObjectOptions = require('./options').internalToObjectOptions; const isDefaultIdIndex = require('./helpers/indexes/isDefaultIdIndex'); const isPathSelectedInclusive = require('./helpers/projection/isPathSelectedInclusive'); const get = require('./helpers/get'); const leanPopulateMap = require('./helpers/populate/leanPopulateMap'); const modifiedPaths = require('./helpers/update/modifiedPaths'); const mpath = require('mpath'); const parallelLimit = require('./helpers/parallelLimit'); const promiseOrCallback = require('./helpers/promiseOrCallback'); const parseProjection = require('./helpers/projection/parseProjection'); const util = require('util'); const utils = require('./utils'); const VERSION_WHERE = 1; const VERSION_INC = 2; const VERSION_ALL = VERSION_WHERE | VERSION_INC; const arrayAtomicsSymbol = require('./helpers/symbols').arrayAtomicsSymbol; const modelCollectionSymbol = Symbol('mongoose#Model#collection'); const modelDbSymbol = Symbol('mongoose#Model#db'); const modelSymbol = require('./helpers/symbols').modelSymbol; const subclassedSymbol = Symbol('mongoose#Model#subclassed'); const saveToObjectOptions = Object.assign({}, internalToObjectOptions, { bson: true }); /** * A Model is a class that's your primary tool for interacting with MongoDB. * An instance of a Model is called a [Document](./api.html#Document). * * In Mongoose, the term "Model" refers to subclasses of the `mongoose.Model` * class. You should not use the `mongoose.Model` class directly. The * [`mongoose.model()`](./api.html#mongoose_Mongoose-model) and * [`connection.model()`](./api.html#connection_Connection-model) functions * create subclasses of `mongoose.Model` as shown below. * * ####Example: * * // `UserModel` is a "Model", a subclass of `mongoose.Model`. * const UserModel = mongoose.model('User', new Schema({ name: String })); * * // You can use a Model to create new documents using `new`: * const userDoc = new UserModel({ name: 'Foo' }); * await userDoc.save(); * * // You also use a model to create queries: * const userFromDb = await UserModel.findOne({ name: 'Foo' }); * * @param {Object} doc values for initial set * @param [fields] optional object containing the fields that were selected in the query which returned this document. You do **not** need to set this parameter to ensure Mongoose handles your [query projection](./api.html#query_Query-select). * @param {Boolean} [skipId=false] optional boolean. If true, mongoose doesn't add an `_id` field to the document. * @inherits Document http://mongoosejs.com/docs/api/document.html * @event `error`: If listening to this event, 'error' is emitted when a document was saved without passing a callback and an `error` occurred. If not listening, the event bubbles to the connection used to create this Model. * @event `index`: Emitted after `Model#ensureIndexes` completes. If an error occurred it is passed with the event. * @event `index-single-start`: Emitted when an individual index starts within `Model#ensureIndexes`. The fields and options being used to build the index are also passed with the event. * @event `index-single-done`: Emitted when an individual index finishes within `Model#ensureIndexes`. If an error occurred it is passed with the event. The fields, options, and index name are also passed. * @api public */ function Model(doc, fields, skipId) { if (fields instanceof Schema) { throw new TypeError('2nd argument to `Model` must be a POJO or string, ' + '**not** a schema. Make sure you\'re calling `mongoose.model()`, not ' + '`mongoose.Model()`.'); } Document.call(this, doc, fields, skipId); } /*! * Inherits from Document. * * All Model.prototype features are available on * top level (non-sub) documents. */ Model.prototype.__proto__ = Document.prototype; Model.prototype.$isMongooseModelPrototype = true; /** * Connection the model uses. * * @api public * @property db * @memberOf Model * @instance */ Model.prototype.db; /** * Collection the model uses. * * This property is read-only. Modifying this property is a no-op. * * @api public * @property collection * @memberOf Model * @instance */ Model.prototype.collection; /** * The name of the model * * @api public * @property modelName * @memberOf Model * @instance */ Model.prototype.modelName; /** * Additional properties to attach to the query when calling `save()` and * `isNew` is false. * * @api public * @property $where * @memberOf Model * @instance */ Model.prototype.$where; /** * If this is a discriminator model, `baseModelName` is the name of * the base model. * * @api public * @property baseModelName * @memberOf Model * @instance */ Model.prototype.baseModelName; /** * Event emitter that reports any errors that occurred. Useful for global error * handling. * * ####Example: * * MyModel.events.on('error', err => console.log(err.message)); * * // Prints a 'CastError' because of the above handler * await MyModel.findOne({ _id: 'notanid' }).catch(noop); * * @api public * @fires error whenever any query or model function errors * @memberOf Model * @static events */ Model.events; /*! * Compiled middleware for this model. Set in `applyHooks()`. * * @api private * @property _middleware * @memberOf Model * @static */ Model._middleware; /*! * ignore */ function _applyCustomWhere(doc, where) { if (doc.$where == null) { return; } const keys = Object.keys(doc.$where); const len = keys.length; for (let i = 0; i < len; ++i) { where[keys[i]] = doc.$where[keys[i]]; } } /*! * ignore */ Model.prototype.$__handleSave = function(options, callback) { const _this = this; let saveOptions = {}; if ('safe' in options) { _handleSafe(options); } applyWriteConcern(this.schema, options); if ('w' in options) { saveOptions.w = options.w; } if ('j' in options) { saveOptions.j = options.j; } if ('wtimeout' in options) { saveOptions.wtimeout = options.wtimeout; } if ('checkKeys' in options) { saveOptions.checkKeys = options.checkKeys; } const session = this.$session(); if (!saveOptions.hasOwnProperty('session')) { saveOptions.session = session; } if (Object.keys(saveOptions).length === 0) { saveOptions = null; } if (this.isNew) { // send entire doc const obj = this.toObject(saveToObjectOptions); if ((obj || {})._id === void 0) { // documents must have an _id else mongoose won't know // what to update later if more changes are made. the user // wouldn't know what _id was generated by mongodb either // nor would the ObjectId generated by mongodb necessarily // match the schema definition. setTimeout(function() { callback(new MongooseError('document must have an _id before saving')); }, 0); return; } this.$__version(true, obj); this[modelCollectionSymbol].insertOne(obj, saveOptions, function(err, ret) { if (err) { _setIsNew(_this, true); callback(err, null); return; } callback(null, ret); }); this.$__reset(); _setIsNew(this, false); // Make it possible to retry the insert this.$__.inserting = true; } else { // Make sure we don't treat it as a new object on error, // since it already exists this.$__.inserting = false; const delta = this.$__delta(); if (delta) { if (delta instanceof MongooseError) { callback(delta); return; } const where = this.$__where(delta[0]); if (where instanceof MongooseError) { callback(where); return; } _applyCustomWhere(this, where); this[modelCollectionSymbol].updateOne(where, delta[1], saveOptions, function(err, ret) { if (err) { callback(err); return; } ret.$where = where; callback(null, ret); }); } else { const optionsWithCustomValues = Object.assign({}, options, saveOptions); this.constructor.exists(this.$__where(), optionsWithCustomValues) .then((documentExists) => { if (!documentExists) throw new DocumentNotFoundError(this.$__where(), this.constructor.modelName); this.$__reset(); callback(); }) .catch(callback); return; } _setIsNew(this, false); } }; /*! * ignore */ Model.prototype.$__save = function(options, callback) { this.$__handleSave(options, (error, result) => { const hooks = this.schema.s.hooks; if (error) { return hooks.execPost('save:error', this, [this], { error: error }, (error) => { callback(error, this); }); } // store the modified paths before the document is reset const modifiedPaths = this.modifiedPaths(); this.$__reset(); let numAffected = 0; if (get(options, 'safe.w') !== 0 && get(options, 'w') !== 0) { // Skip checking if write succeeded if writeConcern is set to // unacknowledged writes, because otherwise `numAffected` will always be 0 if (result) { if (Array.isArray(result)) { numAffected = result.length; } else if (result.result && result.result.n !== undefined) { numAffected = result.result.n; } else if (result.result && result.result.nModified !== undefined) { numAffected = result.result.nModified; } else { numAffected = result; } } // was this an update that required a version bump? if (this.$__.version && !this.$__.inserting) { const doIncrement = VERSION_INC === (VERSION_INC & this.$__.version); this.$__.version = undefined; const key = this.schema.options.versionKey; const version = this.$__getValue(key) || 0; if (numAffected <= 0) { // the update failed. pass an error back const err = this.$__.$versionError || new VersionError(this, version, modifiedPaths); return callback(err); } // increment version if was successful if (doIncrement) { this.$__setValue(key, version + 1); } } if (result != null && numAffected <= 0) { error = new DocumentNotFoundError(result.$where, this.constructor.modelName, numAffected, result); return hooks.execPost('save:error', this, [this], { error: error }, (error) => { callback(error, this); }); } } this.$__.saving = undefined; this.emit('save', this, numAffected); this.constructor.emit('save', this, numAffected); callback(null, this); }); }; /*! * ignore */ function generateVersionError(doc, modifiedPaths) { const key = doc.schema.options.versionKey; if (!key) { return null; } const version = doc.$__getValue(key) || 0; return new VersionError(doc, version, modifiedPaths); } /** * Saves this document by inserting a new document into the database if [document.isNew](/docs/api.html#document_Document-isNew) is `true`, * or sends an [updateOne](/docs/api.html#document_Document-updateOne) operation **only** with the modifications to the database, it does not replace the whole document in the latter case. * * ####Example: * * product.sold = Date.now(); * product = await product.save(); * * If save is successful, the returned promise will fulfill with the document * saved. * * ####Example: * * const newProduct = await product.save(); * newProduct === product; // true * * @param {Object} [options] options optional options * @param {Session} [options.session=null] the [session](https://docs.mongodb.com/manual/reference/server-sessions/) associated with this save operation. If not specified, defaults to the [document's associated session](api.html#document_Document-$session). * @param {Object} [options.safe] (DEPRECATED) overrides [schema's safe option](http://mongoosejs.com//docs/guide.html#safe). Use the `w` option instead. * @param {Boolean} [options.validateBeforeSave] set to false to save without validating. * @param {Number|String} [options.w] set the [write concern](https://docs.mongodb.com/manual/reference/write-concern/#w-option). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern) * @param {Boolean} [options.j] set to true for MongoDB to wait until this `save()` has been [journaled before resolving the returned promise](https://docs.mongodb.com/manual/reference/write-concern/#j-option). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern) * @param {Number} [options.wtimeout] sets a [timeout for the write concern](https://docs.mongodb.com/manual/reference/write-concern/#wtimeout). Overrides the [schema-level `writeConcern` option](/docs/guide.html#writeConcern). * @param {Boolean} [options.checkKeys=true] the MongoDB driver prevents you from saving keys that start with '$' or contain '.' by default. Set this option to `false` to skip that check. See [restrictions on field names](https://docs.mongodb.com/manual/reference/limits/#Restrictions-on-Field-Names) * @param {Boolean} [options.timestamps=true] if `false` and [timestamps](./guide.html#timestamps) are enabled, skip timestamps for this `save()`. * @param {Function} [fn] optional callback * @throws {DocumentNotFoundError} if this [save updates an existing document](api.html#document_Document-isNew) but the document doesn't exist in the database. For example, you will get this error if the document is [deleted between when you retrieved the document and when you saved it](documents.html#updating). * @return {Promise|undefined} Returns undefined if used with callback or a Promise otherwise. * @api public * @see middleware http://mongoosejs.com/docs/middleware.html */ Model.prototype.save = function(options, fn) { let parallelSave; this.$op = 'save'; if (this.$__.saving) { parallelSave = new ParallelSaveError(this); } else { this.$__.saving = new ParallelSaveError(this); } if (typeof options === 'function') { fn = options; options = undefined; } options = new SaveOptions(options); if (options.hasOwnProperty('session')) { this.$session(options.session); } this.$__.$versionError = generateVersionError(this, this.modifiedPaths()); fn = this.constructor.$handleCallbackError(fn); return promiseOrCallback(fn, cb => { cb = this.constructor.$wrapCallback(cb); if (parallelSave) { this.$__handleReject(parallelSave); return cb(parallelSave); } this.$__.saveOptions = options; this.$__save(options, error => { this.$__.saving = undefined; delete this.$__.saveOptions; delete this.$__.$versionError; this.$op = null; if (error) { this.$__handleReject(error); return cb(error); } cb(null, this); }); }, this.constructor.events); }; /*! * Determines whether versioning should be skipped for the given path * * @param {Document} self * @param {String} path * @return {Boolean} true if versioning should be skipped for the given path */ function shouldSkipVersioning(self, path) { const skipVersioning = self.schema.options.skipVersioning; if (!skipVersioning) return false; // Remove any array indexes from the path path = path.replace(/\.\d+\./, '.'); return skipVersioning[path]; } /*! * Apply the operation to the delta (update) clause as * well as track versioning for our where clause. * * @param {Document} self * @param {Object} where * @param {Object} delta * @param {Object} data * @param {Mixed} val * @param {String} [operation] */ function operand(self, where, delta, data, val, op) { // delta op || (op = '$set'); if (!delta[op]) delta[op] = {}; delta[op][data.path] = val; // disabled versioning? if (self.schema.options.versionKey === false) return; // path excluded from versioning? if (shouldSkipVersioning(self, data.path)) return; // already marked for versioning? if (VERSION_ALL === (VERSION_ALL & self.$__.version)) return; switch (op) { case '$set': case '$unset': case '$pop': case '$pull': case '$pullAll': case '$push': case '$addToSet': break; default: // nothing to do return; } // ensure updates sent with positional notation are // editing the correct array element. // only increment the version if an array position changes. // modifying elements of an array is ok if position does not change. if (op === '$push' || op === '$addToSet' || op === '$pullAll' || op === '$pull') { self.$__.version = VERSION_INC; } else if (/^\$p/.test(op)) { // potentially changing array positions self.increment(); } else if (Array.isArray(val)) { // $set an array self.increment(); } else if (/\.\d+\.|\.\d+$/.test(data.path)) { // now handling $set, $unset // subpath of array self.$__.version = VERSION_WHERE; } } /*! * Compiles an update and where clause for a `val` with _atomics. * * @param {Document} self * @param {Object} where * @param {Object} delta * @param {Object} data * @param {Array} value */ function handleAtomics(self, where, delta, data, value) { if (delta.$set && delta.$set[data.path]) { // $set has precedence over other atomics return; } if (typeof value.$__getAtomics === 'function') { value.$__getAtomics().forEach(function(atomic) { const op = atomic[0]; const val = atomic[1]; operand(self, where, delta, data, val, op); }); return; } // legacy support for plugins const atomics = value[arrayAtomicsSymbol]; const ops = Object.keys(atomics); let i = ops.length; let val; let op; if (i === 0) { // $set if (utils.isMongooseObject(value)) { value = value.toObject({ depopulate: 1, _isNested: true }); } else if (value.valueOf) { value = value.valueOf(); } return operand(self, where, delta, data, value); } function iter(mem) { return utils.isMongooseObject(mem) ? mem.toObject({ depopulate: 1, _isNested: true }) : mem; } while (i--) { op = ops[i]; val = atomics[op]; if (utils.isMongooseObject(val)) { val = val.toObject({ depopulate: true, transform: false, _isNested: true }); } else if (Array.isArray(val)) { val = val.map(iter); } else if (val.valueOf) { val = val.valueOf(); } if (op === '$addToSet') { val = { $each: val }; } operand(self, where, delta, data, val, op); } } /** * Produces a special query document of the modified properties used in updates. * * @api private * @method $__delta * @memberOf Model * @instance */ Model.prototype.$__delta = function() { const dirty = this.$__dirty(); if (!dirty.length && VERSION_ALL !== this.$__.version) { return; } const where = {}; const delta = {}; const len = dirty.length; const divergent = []; let d = 0; where._id = this._doc._id; // If `_id` is an object, need to depopulate, but also need to be careful // because `_id` can technically be null (see gh-6406) if (get(where, '_id.$__', null) != null) { where._id = where._id.toObject({ transform: false, depopulate: true }); } for (; d < len; ++d) { const data = dirty[d]; let value = data.value; const match = checkDivergentArray(this, data.path, value); if (match) { divergent.push(match); continue; } const pop = this.populated(data.path, true); if (!pop && this.$__.selected) { // If any array was selected using an $elemMatch projection, we alter the path and where clause // NOTE: MongoDB only supports projected $elemMatch on top level array. const pathSplit = data.path.split('.'); const top = pathSplit[0]; if (this.$__.selected[top] && this.$__.selected[top].$elemMatch) { // If the selected array entry was modified if (pathSplit.length > 1 && pathSplit[1] == 0 && typeof where[top] === 'undefined') { where[top] = this.$__.selected[top]; pathSplit[1] = '$'; data.path = pathSplit.join('.'); } // if the selected array was modified in any other way throw an error else { divergent.push(data.path); continue; } } } if (divergent.length) continue; if (value === undefined) { operand(this, where, delta, data, 1, '$unset'); } else if (value === null) { operand(this, where, delta, data, null); } else if (value.isMongooseArray && value.$path() && value[arrayAtomicsSymbol]) { // arrays and other custom types (support plugins etc) handleAtomics(this, where, delta, data, value); } else if (value[MongooseBuffer.pathSymbol] && Buffer.isBuffer(value)) { // MongooseBuffer value = value.toObject(); operand(this, where, delta, data, value); } else { value = utils.clone(value, { depopulate: true, transform: false, virtuals: false, getters: false, _isNested: true }); operand(this, where, delta, data, value); } } if (divergent.length) { return new DivergentArrayError(divergent); } if (this.$__.version) { this.$__version(where, delta); } return [where, delta]; }; /*! * Determine if array was populated with some form of filter and is now * being updated in a manner which could overwrite data unintentionally. * * @see https://github.com/Automattic/mongoose/issues/1334 * @param {Document} doc * @param {String} path * @return {String|undefined} */ function checkDivergentArray(doc, path, array) { // see if we populated this path const pop = doc.populated(path, true); if (!pop && doc.$__.selected) { // If any array was selected using an $elemMatch projection, we deny the update. // NOTE: MongoDB only supports projected $elemMatch on top level array. const top = path.split('.')[0]; if (doc.$__.selected[top + '.$']) { return top; } } if (!(pop && array && array.isMongooseArray)) return; // If the array was populated using options that prevented all // documents from being returned (match, skip, limit) or they // deselected the _id field, $pop and $set of the array are // not safe operations. If _id was deselected, we do not know // how to remove elements. $pop will pop off the _id from the end // of the array in the db which is not guaranteed to be the // same as the last element we have here. $set of the entire array // would be similarily destructive as we never received all // elements of the array and potentially would overwrite data. const check = pop.options.match || pop.options.options && utils.object.hasOwnProperty(pop.options.options, 'limit') || // 0 is not permitted pop.options.options && pop.options.options.skip || // 0 is permitted pop.options.select && // deselected _id? (pop.options.select._id === 0 || /\s?-_id\s?/.test(pop.options.select)); if (check) { const atomics = array[arrayAtomicsSymbol]; if (Object.keys(atomics).length === 0 || atomics.$set || atomics.$pop) { return path; } } } /** * Appends versioning to the where and update clauses. * * @api private * @method $__version * @memberOf Model * @instance */ Model.prototype.$__version = function(where, delta) { const key = this.schema.options.versionKey; if (where === true) { // this is an insert if (key) this.$__setValue(key, delta[key] = 0); return; } // updates // only apply versioning if our versionKey was selected. else // there is no way to select the correct version. we could fail // fast here and force them to include the versionKey but // thats a bit intrusive. can we do this automatically? if (!this.isSelected(key)) { return; } // $push $addToSet don't need the where clause set if (VERSION_WHERE === (VERSION_WHERE & this.$__.version)) { const value = this.$__getValue(key); if (value != null) where[key] = value; } if (VERSION_INC === (VERSION_INC & this.$__.version)) { if (get(delta.$set, key, null) != null) { // Version key is getting set, means we'll increment the doc's version // after a successful save, so we should set the incremented version so // future saves don't fail (gh-5779) ++delta.$set[key]; } else { delta.$inc = delta.$inc || {}; delta.$inc[key] = 1; } } }; /** * Signal that we desire an increment of this documents version. * * ####Example: * * Model.findById(id, function (err, doc) { * doc.increment(); * doc.save(function (err) { .. }) * }) * * @see versionKeys http://mongoosejs.com/docs/guide.html#versionKey * @api public */ Model.prototype.increment = function increment() { this.$__.version = VERSION_ALL; return this; }; /** * Returns a query object * * @api private * @method $__where * @memberOf Model * @instance */ Model.prototype.$__where = function _where(where) { where || (where = {}); if (!where._id) { where._id = this._doc._id; } if (this._doc._id === void 0) { return new MongooseError('No _id found on document!'); } return where; }; /** * Removes this document from the db. * * ####Example: * product.remove(function (err, product) { * if (err) return handleError(err); * Product.findById(product._id, function (err, product) { * console.log(product) // null * }) * }) * * * As an extra measure of flow control, remove will return a Promise (bound to `fn` if passed) so it could be chained, or hooked to recieve errors * * ####Example: * product.remove().then(function (product) { * ... * }).catch(function (err) { * assert.ok(err) * }) * * @param {Object} [options] * @param {Session} [options.session=null] the [session](https://docs.mongodb.com/manual/reference/server-sessions/) associated with this operation. If not specified, defaults to the [document's associated session](api.html#document_Document-$session). * @param {function(err,product)} [fn] optional callback * @return {Promise} Promise * @api public */ Model.prototype.remove = function remove(options, fn) { if (typeof options === 'function') { fn = options; options = undefined; } options = new RemoveOptions(options); if (options.hasOwnProperty('session')) { this.$session(options.session); } this.$op = 'remove'; fn = this.constructor.$handleCallbackError(fn); return promiseOrCallback(fn, cb => { cb = this.constructor.$wrapCallback(cb); this.$__remove(options, (err, res) => { this.$op = null; cb(err, res); }); }, this.constructor.events); }; /** * Alias for remove */ Model.prototype.delete = Model.prototype.remove; /** * Removes this document from the db. Equivalent to `.remove()`. * * ####Example: * product = await product.deleteOne(); * await Product.findById(product._id); // null * * @param {function(err,product)} [fn] optional callback * @return {Promise} Promise * @api public */ Model.prototype.deleteOne = function deleteOne(options, fn) { if (typeof options === 'function') { fn = options; options = undefined; } if (!options) { options = {}; } fn = this.constructor.$handleCallbackError(fn); return promiseOrCallback(fn, cb => { cb = this.constructor.$wrapCallback(cb); this.$__deleteOne(options, cb); }, this.constructor.events); }; /*! * ignore */ Model.prototype.$__remove = function $__remove(options, cb) { if (this.$__.isDeleted) { return immediate(() => cb(null, this)); } const where = this.$__where(); if (where instanceof MongooseError) { return cb(where); } _applyCustomWhere(this, where); const session = this.$session(); if (!options.hasOwnProperty('session')) { options.session = session; } this[modelCollectionSymbol].deleteOne(where, options, err => { if (!err) { this.$__.isDeleted = true; this.emit('remove', this); this.constructor.emit('remove', this); return cb(null, this); } this.$__.isDeleted = false; cb(err); }); }; /*! * ignore */ Model.prototype.$__deleteOne = Model.prototype.$__remove; /** * Returns another Model instance. * * ####Example: * * var doc = new Tank; * doc.model('User').findById(id, callback); * * @param {String} name model name * @api public */ Model.prototype.model = function model(name) { return this[modelDbSymbol].model(name); }; /** * Returns true if at least one document exists in the database that matches * the given `filter`, and false otherwise. * * Under the hood, `MyModel.exists({ answer: 42 })` is equivalent to * `MyModel.findOne({ answer: 42 }).select({ _id: 1 }).lean().then(doc => !!doc)` * * ####Example: * await Character.deleteMany({}); * await Character.create({ name: 'Jean-Luc Picard' }); * * await Character.exists({ name: /picard/i }); // true * await Character.exists({ name: /riker/i }); // false * * This function triggers the following middleware. * * - `findOne()` * * @param {Object} filter * @param {Function} [callback] callback * @return {Promise} */ Model.exists = function exists(filter, options, callback) { _checkContext(this, 'exists'); if (typeof options === 'function') { callback = options; options = null; } const query = this.findOne(filter). select({ _id: 1 }). lean(). setOptions(options); if (typeof callback === 'function') { query.exec(function(err, doc) { if (err != null) { return callback(err); } callback(null, !!doc); }); return; } return query.then(doc => !!doc); }; /** * Adds a discriminator type. * * ####Example: * * function BaseSchema() { * Schema.apply(this, arguments); * * this.add({ * name: String, * createdAt: Date * }); * } * util.inherits(BaseSchema, Schema); * * var PersonSchema = new BaseSchema(); * var BossSchema = new BaseSchema({ department: String }); * * var Person = mongoose.model('Person', PersonSchema); * var Boss = Person.discriminator('Boss', BossSchema); * new Boss().__t; // "Boss". `__t` is the default `discriminatorKey` * * var employeeSchema = new Schema({ boss: ObjectId }); * var Employee = Person.discriminator('Employee', employeeSchema, 'staff'); * new Employee().__t; // "staff" because of 3rd argument above * * @param {String} name discriminator model name * @param {Schema} schema discriminator model schema * @param {String} [value] the string stored in the `discriminatorKey` property. If not specified, Mongoose uses the `name` parameter. * @return {Model} The newly created discriminator model * @api public */ Model.discriminator = function(name, schema, value) { let model; if (typeof name === 'function') { model = name; name = utils.getFunctionName(model); if (!(model.prototype instanceof Model)) { throw new MongooseError('The provided class ' + name + ' must extend Model'); } } _checkContext(this, 'discriminator'); if (utils.isObject(schema) && !schema.instanceOfSchema) { schema = new Schema(schema); } schema = discriminator(this, name, schema, value, true); if (this.db.models[name]) { throw new OverwriteModelError(name); } schema.$isRootDiscriminator = true; schema.$globalPluginsApplied = true; model = this.db.model(model || name, schema, this.collection.name); this.discriminators[name] = model; const d = this.discriminators[name]; d.prototype.__proto__ = this.prototype; Object.defineProperty(d, 'baseModelName', { value: this.modelName, configurable: true, writable: false }); // apply methods and statics applyMethods(d, schema); applyStatics(d, schema); if (this[subclassedSymbol] != null) { for (const submodel of this[subclassedSymbol]) { submodel.discriminators = submodel.discriminators || {}; submodel.discriminators[name] = model.__subclass(model.db, schema, submodel.collection.name); } } return d; }; /*! * Make sure `this` is a model */ function _checkContext(ctx, fnName) { // Check context, because it is easy to mistakenly type // `new Model.discriminator()` and get an incomprehensible error if (ctx == null || ctx === global) { throw new MongooseError('`Model.' + fnName + '()` cannot run without a ' + 'model as `this`. Make sure you are calling `MyModel.' + fnName + '()` ' + 'where `MyModel` is a Mongoose model.'); } else if (ctx[modelSymbol] == null) { throw new MongooseError('`Model.' + fnName + '()` cannot run without a ' + 'model as `this`. Make sure you are not calling ' + '`new Model.' + fnName + '()`'); } } // Model (class) features /*! * Give the constructor the ability to emit events. */ for (const i in EventEmitter.prototype) { Model[i] = EventEmitter.prototype[i]; } /** * This function is responsible for building [indexes](https://docs.mongodb.com/manual/indexes/), * unless [`autoIndex`](http://mongoosejs.com/docs/guide.html#autoIndex) is turned off. * * Mongoose calls this function automatically when a model is created using * [`mongoose.model()`](/docs/api.html#mongoose_Mongoose-model) or * [`connection.model()`](/docs/api.html#connection_Connection-model), so you * don't need to call it. This function is also idempotent, so you may call it * to get back a promise that will resolve when your indexes are finished * building as an alternative to [`MyModel.on('index')`](/docs/guide.html#indexes) * * ####Example: * * var eventSchema = new Schema({ thing: { type: 'string', unique: true }}) * // This calls `Event.init()` implicitly, so you don't need to call * // `Event.init()` on your own. * var Event = mongoose.model('Event', eventSchema); * * Event.init().then(function(Event) { * // You can also use `Event.on('index')` if you prefer event emitters * // over promises. * console.log('Indexes are done building!'); * }); * * @api public * @param {Function} [callback] * @returns {Promise} */ Model.init = function init(callback) { _checkContext(this, 'init'); this.schema.emit('init', this); if (this.$init != null) { if (callback) { this.$init.then(() => callback(), err => callback(err)); return null; } return this.$init; } const Promise = PromiseProvider.get(); const autoIndex = utils.getOption('autoIndex', this.schema.options, this.db.config, this.db.base.options); const autoCreate = this.schema.options.autoCreate == null ? this.db.config.autoCreate : this.schema.options.autoCreate; const _ensureIndexes = autoIndex ? cb => this.ensureIndexes({ _automatic: true }, cb) : cb => cb(); const _createCollection = autoCreate ? cb => this.createCollection({}, cb) : cb => cb(); this.$init = new Promise((resolve, reject) => { _createCollection(error => { if (error) { return reject(error); } _ensureIndexes(error => { if (error) { return reject(error); } resolve(this); }); }); }); if (callback) { this.$init.then(() => callback(), err => callback(err)); this.$caught = true; return null; } else { const _catch = this.$init.catch; const _this = this; this.$init.catch = function() { this.$caught = true; return _catch.apply(_this.$init, arguments); }; } return this.$init; }; /** * Create the collection for this model. By default, if no indexes are specified, * mongoose will not create the collection for the model until any documents are * created. Use this method to create the collection explicitly. * * Note 1: You may need to call this before starting a transaction * See https://docs.mongodb.com/manual/core/transactions/#transactions-and-operations * * Note 2: You don't have to call this if your schema contains index or unique field. * In that case, just use `Model.init()` * * ####Example: * * var userSchema = new Schema({ name: String }) * var User = mongoose.model('User', userSchema); * * User.createCollection().then(function(collection) { * console.log('Collection is created!'); * }); * * @api public * @param {Object} [options] see [MongoDB driver docs](http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#createCollection) * @param {Function} [callback] * @returns {Promise} */ Model.createCollection = function createCollection(options, callback) { _checkContext(this, 'createCollection'); if (typeof options === 'string') { throw new MongooseError('You can\'t specify a new collection name in Model.createCollection.' + 'This is not like Connection.createCollection. Only options are accepted here.'); } else if (typeof options === 'function') { callback = options; options = null; } const schemaCollation = get(this, 'schema.options.collation', null); if (schemaCollation != null) { options = Object.assign({ collation: schemaCollation }, options); } callback = this.$handleCallbackError(callback); return promiseOrCallback(callback, cb => { cb = this.$wrapCallback(cb); this.db.createCollection(this.collection.collectionName, options, utils.tick((error) => { if (error) { return cb(error); } this.collection = this.db.collection(this.collection.collectionName, options); cb(null, this.collection); })); }, this.events); }; /** * Makes the indexes in MongoDB match the indexes defined in this model's * schema. This function will drop any indexes that are not defined in * the model's schema except the `_id` index, and build any indexes that * are in your schema but not in MongoDB. * * See the [introductory blog post](http://thecodebarbarian.com/whats-new-in-mongoose-5-2-syncindexes) * for more information. * * ####Example: * * const schema = new Schema({ name: { type: String, unique: true } }); * const Customer = mongoose.model('Customer', schema); * await Customer.createIndex({ age: 1 }); // Index is not in schema * // Will drop the 'age' index and create an index on `name` * await Customer.syncIndexes(); * * @param {Object} [options] options to pass to `ensureIndexes()` * @param {Boolean} [options.background=null] if specified, overrides each index's `background` property * @param {Function} [callback] optional callback * @return {Promise|undefined} Returns `undefined` if callback is specified, returns a promise if no callback. * @api public */ Model.syncIndexes = function syncIndexes(options, callback) { _checkContext(this, 'syncIndexes'); callback = this.$handleCallbackError(callback); return promiseOrCallback(callback, cb => { cb = this.$wrapCallback(cb); this.createCollection(err => { if (err) { return cb(err); } this.cleanIndexes((err, dropped) => { if (err != null) { return cb(err); } this.createIndexes(options, err => { if (err != null) { return cb(err); } cb(null, dropped); }); }); }); }, this.events); }; /** * Deletes all indexes that aren't defined in this model's schema. Used by * `syncIndexes()`. * * The returned promise resolves to a list of the dropped indexes' names as an array * * @param {Function} [callback] optional callback * @return {Promise|undefined} Returns `undefined` if callback is specified, returns a promise if no callback. * @api public */ Model.cleanIndexes = function cleanIndexes(callback) { _checkContext(this, 'cleanIndexes'); callback = this.$handleCallbackError(callback); return promiseOrCallback(callback, cb => { const collection = this.collection; this.listIndexes((err, indexes) => { if (err != null) { return cb(err); } const schemaIndexes = this.schema.indexes(); const toDrop = []; for (const index of indexes) { let found = false; // Never try to drop `_id` index, MongoDB server doesn't allow it if (isDefaultIdIndex(index)) { continue; } for (const schemaIndex of schemaIndexes) { if (isIndexEqual(this, schemaIndex, index)) { found = true; } } if (!found) { toDrop.push(index.name); } } if (toDrop.length === 0) { return cb(null, []); } dropIndexes(toDrop, cb); }); function dropIndexes(toDrop, cb) { let remaining = toDrop.length; let error = false; toDrop.forEach(indexName => { collection.dropIndex(indexName, err => { if (err != null) { error = true; return cb(err); } if (!error) { --remaining || cb(null, toDrop); } }); }); } }); }; /*! * ignore */ function isIndexEqual(model, schemaIndex, dbIndex) { const key = schemaIndex[0]; const options = _decorateDiscriminatorIndexOptions(model, utils.clone(schemaIndex[1])); // If these options are different, need to rebuild the index const optionKeys = [ 'unique', 'partialFilterExpression', 'sparse', 'expireAfterSeconds', 'collation' ]; for (const key of optionKeys) { if (!(key in options) && !(key in dbIndex)) { continue; } if (!utils.deepEqual(options[key], dbIndex[key])) { return false; } } const schemaIndexKeys = Object.keys(key); const dbIndexKeys = Object.keys(dbIndex.key); if (schemaIndexKeys.length !== dbIndexKeys.length) { return false; } for (let i = 0; i < schemaIndexKeys.length; ++i) { if (schemaIndexKeys[i] !== dbIndexKeys[i]) { return false; } if (!utils.deepEqual(key[schemaIndexKeys[i]], dbIndex.key[dbIndexKeys[i]])) { return false; } } return true; } /** * Lists the indexes currently defined in MongoDB. This may or may not be * the same as the indexes defined in your schema depending on whether you * use the [`autoIndex` option](/docs/guide.html#autoIndex) and if you * build indexes manually. * * @param {Function} [cb] optional callback * @return {Promise|undefined} Returns `undefined` if callback is specified, returns a promise if no callback. * @api public */ Model.listIndexes = function init(callback) { _checkContext(this, 'listIndexes'); const _listIndexes = cb => { this.collection.listIndexes().toArray(cb); }; callback = this.$handleCallbackError(callback); return promiseOrCallback(callback, cb => { cb = this.$wrapCallback(cb); // Buffering if (this.collection.buffer) { this.collection.addQueue(_listIndexes, [cb]); } else { _listIndexes(cb); } }, this.events); }; /** * Sends `createIndex` commands to mongo for each index declared in the schema. * The `createIndex` commands are sent in series. * * ####Example: * * Event.ensureIndexes(function (err) { * if (err) return handleError(err); * }); * * After completion, an `index` event is emitted on this `Model` passing an error if one occurred. * * ####Example: * * var eventSchema = new Schema({ thing: { type: 'string', unique: true }}) * var Event = mongoose.model('Event', eventSchema); * * Event.on('index', function (err) { * if (err) console.error(err); // error occurred during index creation * }) * * _NOTE: It is not recommended that you run this in production. Index creation may impact database performance depending on your load. Use with caution._ * * @param {Object} [options] internal options * @param {Function} [cb] optional callback * @return {Promise} * @api public */ Model.ensureIndexes = function ensureIndexes(options, callback) { _checkContext(this, 'ensureIndexes'); if (typeof options === 'function') { callback = options; options = null; } callback = this.$handleCallbackError(callback); return promiseOrCallback(callback, cb => { cb = this.$wrapCallback(cb); _ensureIndexes(this, options || {}, error => { if (error) { return cb(error); } cb(null); }); }, this.events); }; /** * Similar to `ensureIndexes()`, except for it uses the [`createIndex`](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#createIndex) * function. * * @param {Object} [options] internal options * @param {Function} [cb] optional callback * @return {Promise} * @api public */ Model.createIndexes = function createIndexes(options, callback) { _checkContext(this, 'createIndexes'); if (typeof options === 'function') { callback = options; options = {}; } options = options || {}; options.createIndex = true; return this.ensureIndexes(options, callback); }; /*! * ignore */ function _ensureIndexes(model, options, callback) { const indexes = model.schema.indexes(); let indexError; options = options || {}; const done = function(err) { if (err && !model.$caught) { model.emit('error', err); } model.emit('index', err || indexError); callback && callback(err); }; for (const index of indexes) { if (isDefaultIdIndex(index)) { console.warn('mongoose: Cannot specify a custom index on `_id` for ' + 'model name "' + model.modelName + '", ' + 'MongoDB does not allow overwriting the default `_id` index. See ' + 'http://bit.ly/mongodb-id-index'); } } if (!indexes.length) { immediate(function() { done(); }); return; } // Indexes are created one-by-one to support how MongoDB < 2.4 deals // with background indexes. const indexSingleDone = function(err, fields, options, name) { model.emit('index-single-done', err, fields, options, name); }; const indexSingleStart = function(fields, options) { model.emit('index-single-start', fields, options); }; const baseSchema = model.schema._baseSchema; const baseSchemaIndexes = baseSchema ? baseSchema.indexes() : []; const create = function() { if (options._automatic) { if (model.schema.options.autoIndex === false || (model.schema.options.autoIndex == null && model.db.config.autoIndex === false)) { return done(); } } const index = indexes.shift(); if (!index) { return done(); } if (baseSchemaIndexes.find(i => utils.deepEqual(i, index))) { return create(); } const indexFields = utils.clone(index[0]); const indexOptions = utils.clone(index[1]); _decorateDiscriminatorIndexOptions(model, indexOptions); if ('safe' in options) { _handleSafe(options); } applyWriteConcern(model.schema, indexOptions); indexSingleStart(indexFields, options); let useCreateIndex = !!model.base.options.useCreateIndex; if ('useCreateIndex' in model.db.config) { useCreateIndex = !!model.db.config.useCreateIndex; } if ('createIndex' in options) { useCreateIndex = !!options.createIndex; } if ('background' in options) { indexOptions.background = options.background; } const methodName = useCreateIndex ? 'createIndex' : 'ensureIndex'; model.collection[methodName](indexFields, indexOptions, utils.tick(function(err, name) { indexSingleDone(err, indexFields, indexOptions, name); if (err) { if (!indexError) { indexError = err; } if (!model.$caught) { model.emit('error', err); } } create(); })); }; immediate(function() { // If buffering is off, do this manually. if (options._automatic && !model.collection.collection) { model.collection.addQueue(create, []); } else { create(); } }); } function _decorateDiscriminatorIndexOptions(model, indexOptions) { // If the model is a discriminator and it has a unique index, add a // partialFilterExpression by default so the unique index will only apply // to that discriminator. if (model.baseModelName != null && indexOptions.unique && !('partialFilterExpression' in indexOptions) && !('sparse' in indexOptions)) { const value = ( model.schema.discriminatorMapping && model.schema.discriminatorMapping.value ) || model.modelName; indexOptions.partialFilterExpression = { [model.schema.options.discriminatorKey]: value }; } return indexOptions; } const safeDeprecationWarning = 'Mongoose: the `safe` option for `save()` is ' + 'deprecated. Use the `w` option instead: http://bit.ly/mongoose-save'; const _handleSafe = util.deprecate(function _handleSafe(options) { if (options.safe) { if (typeof options.safe === 'boolean') { options.w = options.safe; delete options.safe; } if (typeof options.safe === 'object') { options.w = options.safe.w; options.j = options.safe.j; options.wtimeout = options.safe.wtimeout; delete options.safe; } } }, safeDeprecationWarning); /** * Schema the model uses. * * @property schema * @receiver Model * @api public * @memberOf Model */ Model.schema; /*! * Connection instance the model uses. * * @property db * @api public * @memberOf Model */ Model.db; /*! * Collection the model uses. * * @property collection * @api public * @memberOf Model */ Model.collection; /** * Base Mongoose instance the model uses. * * @property base * @api public * @memberOf Model */ Model.base; /** * Registered discriminators for this model. * * @property discriminators * @api public * @memberOf Model */ Model.discriminators; /** * Translate any aliases fields/conditions so the final query or document object is pure * * ####Example: * * Character * .find(Character.translateAliases({ * '名': 'Eddard Stark' // Alias for 'name' * }) * .exec(function(err, characters) {}) * * ####Note: * Only translate arguments of object type anything else is returned raw * * @param {Object} raw fields/conditions that may contain aliased keys * @return {Object} the translated 'pure' fields/conditions */ Model.translateAliases = function translateAliases(fields) { _checkContext(this, 'translateAliases'); const translate = (key, value) => { let alias; const translated = []; const fieldKeys = key.split('.'); let currentSchema = this.schema; for (const i in fieldKeys) { const name = fieldKeys[i]; if (currentSchema && currentSchema.aliases[name]) { alias = currentSchema.aliases[name]; // Alias found, translated.push(alias); } else { // Alias not found, so treat as un-aliased key translated.push(name); } // Check if aliased path is a schema if (currentSchema && currentSchema.paths[alias]) { currentSchema = currentSchema.paths[alias].schema; } else currentSchema = null; } const translatedKey = translated.join('.'); if (fields instanceof Map) fields.set(translatedKey, value); else fields[translatedKey] = value; if (translatedKey !== key) { // We'll be using the translated key instead if (fields instanceof Map) { // Delete from map fields.delete(key); } else { // Delete from object delete fields[key]; // We'll be using the translated key instead } } return fields; }; if (typeof fields === 'object') { // Fields is an object (query conditions or document fields) if (fields instanceof Map) { // A Map was supplied for (const field of new Map(fields)) { fields = translate(field[0], field[1]); } } else { // Infer a regular object was supplied for (const key of Object.keys(fields)) { fields = translate(key, fields[key]); if (key[0] === '$') { if (Array.isArray(fields[key])) { for (const i in fields[key]) { // Recursively translate nested queries fields[key][i] = this.translateAliases(fields[key][i]); } } } } } return fields; } else { // Don't know typeof fields return fields; } }; /** * Removes all documents that match `conditions` from the collection. * To remove just the first document that matches `conditions`, set the `single` * option to true. * * ####Example: * * const res = await Character.remove({ name: 'Eddard Stark' }); * res.deletedCount; // Number of documents removed * * ####Note: * * This method sends a remove command directly to MongoDB, no Mongoose documents * are involved. Because no Mongoose documents are involved, Mongoose does * not execute [document middleware](/docs/middleware.html#types-of-middleware). * * @param {Object} conditions * @param {Object} [options] * @param {Session} [options.session=null] the [session](https://docs.mongodb.com/manual/reference/server-sessions/) associated with this operation. * @param {Function} [callback] * @return {Query} * @api public */ Model.remove = function remove(conditions, options, callback) { _checkContext(this, 'remove'); if (typeof conditions === 'function') { callback = conditions; conditions = {}; options = null; } else if (typeof options === 'function') { callback = options; options = null; } // get the mongodb collection object const mq = new this.Query({}, {}, this, this.collection); mq.setOptions(options); callback = this.$handleCallbackError(callback); return mq.remove(conditions, callback); }; /** * Deletes the first document that matches `conditions` from the collection. * Behaves like `remove()`, but deletes at most one document regardless of the * `single` option. * * ####Example: * * Character.deleteOne({ name: 'Eddard Stark' }, function (err) {}); * * ####Note: * * Like `Model.remove()`, this function does **not** trigger `pre('remove')` or `post('remove')` hooks. * * @param {Object} conditions * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) * @param {Function} [callback] * @return {Query} * @api public */ Model.deleteOne = function deleteOne(conditions, options, callback) { _checkContext(this, 'deleteOne'); if (typeof conditions === 'function') { callback = conditions; conditions = {}; options = null; } else if (typeof options === 'function') { callback = options; options = null; } const mq = new this.Query({}, {}, this, this.collection); mq.setOptions(options); callback = this.$handleCallbackError(callback); return mq.deleteOne(conditions, callback); }; /** * Deletes all of the documents that match `conditions` from the collection. * Behaves like `remove()`, but deletes all documents that match `conditions` * regardless of the `single` option. * * ####Example: * * Character.deleteMany({ name: /Stark/, age: { $gte: 18 } }, function (err) {}); * * ####Note: * * Like `Model.remove()`, this function does **not** trigger `pre('remove')` or `post('remove')` hooks. * * @param {Object} conditions * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) * @param {Function} [callback] * @return {Query} * @api public */ Model.deleteMany = function deleteMany(conditions, options, callback) { _checkContext(this, 'deleteMany'); if (typeof conditions === 'function') { callback = conditions; conditions = {}; options = null; } else if (typeof options === 'function') { callback = options; options = null; } const mq = new this.Query({}, {}, this, this.collection); mq.setOptions(options); callback = this.$handleCallbackError(callback); return mq.deleteMany(conditions, callback); }; /** * Finds documents. * * The `filter` are cast to their respective SchemaTypes before the command is sent. * See our [query casting tutorial](/docs/tutorials/query_casting.html) for * more information on how Mongoose casts `filter`. * * ####Examples: * * // named john and at least 18 * MyModel.find({ name: 'john', age: { $gte: 18 }}); * * // executes, passing results to callback * MyModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) {}); * * // executes, name LIKE john and only selecting the "name" and "friends" fields * MyModel.find({ name: /john/i }, 'name friends', function (err, docs) { }) * * // passing options * MyModel.find({ name: /john/i }, null, { skip: 10 }) * * // passing options and executes * MyModel.find({ name: /john/i }, null, { skip: 10 }, function (err, docs) {}); * * // executing a query explicitly * var query = MyModel.find({ name: /john/i }, null, { skip: 10 }) * query.exec(function (err, docs) {}); * * // using the promise returned from executing a query * var query = MyModel.find({ name: /john/i }, null, { skip: 10 }); * var promise = query.exec(); * promise.addBack(function (err, docs) {}); * * @param {Object|ObjectId} filter * @param {Object|String} [projection] optional fields to return, see [`Query.prototype.select()`](http://mongoosejs.com/docs/api.html#query_Query-select) * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) * @param {Function} [callback] * @return {Query} * @see field selection #query_Query-select * @see query casting /docs/tutorials/query_casting.html * @api public */ Model.find = function find(conditions, projection, options, callback) { _checkContext(this, 'find'); if (typeof conditions === 'function') { callback = conditions; conditions = {}; projection = null; options = null; } else if (typeof projection === 'function') { callback = projection; projection = null; options = null; } else if (typeof options === 'function') { callback = options; options = null; } const mq = new this.Query({}, {}, this, this.collection); mq.select(projection); mq.setOptions(options); if (this.schema.discriminatorMapping && this.schema.discriminatorMapping.isRoot && mq.selectedInclusively()) { // Need to select discriminator key because original schema doesn't have it mq.select(this.schema.options.discriminatorKey); } callback = this.$handleCallbackError(callback); return mq.find(conditions, callback); }; /** * Finds a single document by its _id field. `findById(id)` is almost* * equivalent to `findOne({ _id: id })`. If you want to query by a document's * `_id`, use `findById()` instead of `findOne()`. * * The `id` is cast based on the Schema before sending the command. * * This function triggers the following middleware. * * - `findOne()` * * \* Except for how it treats `undefined`. If you use `findOne()`, you'll see * that `findOne(undefined)` and `findOne({ _id: undefined })` are equivalent * to `findOne({})` and return arbitrary documents. However, mongoose * translates `findById(undefined)` into `findOne({ _id: null })`. * * ####Example: * * // find adventure by id and execute * Adventure.findById(id, function (err, adventure) {}); * * // same as above * Adventure.findById(id).exec(callback); * * // select only the adventures name and length * Adventure.findById(id, 'name length', function (err, adventure) {}); * * // same as above * Adventure.findById(id, 'name length').exec(callback); * * // include all properties except for `length` * Adventure.findById(id, '-length').exec(function (err, adventure) {}); * * // passing options (in this case return the raw js objects, not mongoose documents by passing `lean` * Adventure.findById(id, 'name', { lean: true }, function (err, doc) {}); * * // same as above * Adventure.findById(id, 'name').lean().exec(function (err, doc) {}); * * @param {Any} id value of `_id` to query by * @param {Object|String} [projection] optional fields to return, see [`Query.prototype.select()`](#query_Query-select) * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) * @param {Function} [callback] * @return {Query} * @see field selection #query_Query-select * @see lean queries /docs/tutorials/lean.html * @see findById in Mongoose https://masteringjs.io/tutorials/mongoose/find-by-id * @api public */ Model.findById = function findById(id, projection, options, callback) { _checkContext(this, 'findById'); if (typeof id === 'undefined') { id = null; } callback = this.$handleCallbackError(callback); return this.findOne({ _id: id }, projection, options, callback); }; /** * Finds one document. * * The `conditions` are cast to their respective SchemaTypes before the command is sent. * * *Note:* `conditions` is optional, and if `conditions` is null or undefined, * mongoose will send an empty `findOne` command to MongoDB, which will return * an arbitrary document. If you're querying by `_id`, use `findById()` instead. * * ####Example: * * // find one iphone adventures - iphone adventures?? * Adventure.findOne({ type: 'iphone' }, function (err, adventure) {}); * * // same as above * Adventure.findOne({ type: 'iphone' }).exec(function (err, adventure) {}); * * // select only the adventures name * Adventure.findOne({ type: 'iphone' }, 'name', function (err, adventure) {}); * * // same as above * Adventure.findOne({ type: 'iphone' }, 'name').exec(function (err, adventure) {}); * * // specify options, in this case lean * Adventure.findOne({ type: 'iphone' }, 'name', { lean: true }, callback); * * // same as above * Adventure.findOne({ type: 'iphone' }, 'name', { lean: true }).exec(callback); * * // chaining findOne queries (same as above) * Adventure.findOne({ type: 'iphone' }).select('name').lean().exec(callback); * * @param {Object} [conditions] * @param {Object|String} [projection] optional fields to return, see [`Query.prototype.select()`](#query_Query-select) * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) * @param {Function} [callback] * @return {Query} * @see field selection #query_Query-select * @see lean queries /docs/tutorials/lean.html * @api public */ Model.findOne = function findOne(conditions, projection, options, callback) { _checkContext(this, 'findOne'); if (typeof options === 'function') { callback = options; options = null; } else if (typeof projection === 'function') { callback = projection; projection = null; options = null; } else if (typeof conditions === 'function') { callback = conditions; conditions = {}; projection = null; options = null; } const mq = new this.Query({}, {}, this, this.collection); mq.select(projection); mq.setOptions(options); if (this.schema.discriminatorMapping && this.schema.discriminatorMapping.isRoot && mq.selectedInclusively()) { mq.select(this.schema.options.discriminatorKey); } callback = this.$handleCallbackError(callback); return mq.findOne(conditions, callback); }; /** * Estimates the number of documents in the MongoDB collection. Faster than * using `countDocuments()` for large collections because * `estimatedDocumentCount()` uses collection metadata rather than scanning * the entire collection. * * ####Example: * * const numAdventures = Adventure.estimatedDocumentCount(); * * @param {Object} [options] * @param {Function} [callback] * @return {Query} * @api public */ Model.estimatedDocumentCount = function estimatedDocumentCount(options, callback) { _checkContext(this, 'estimatedDocumentCount'); const mq = new this.Query({}, {}, this, this.collection); callback = this.$handleCallbackError(callback); return mq.estimatedDocumentCount(options, callback); }; /** * Counts number of documents matching `filter` in a database collection. * * ####Example: * * Adventure.countDocuments({ type: 'jungle' }, function (err, count) { * console.log('there are %d jungle adventures', count); * }); * * If you want to count all documents in a large collection, * use the [`estimatedDocumentCount()` function](/docs/api.html#model_Model.estimatedDocumentCount) * instead. If you call `countDocuments({})`, MongoDB will always execute * a full collection scan and **not** use any indexes. * * The `countDocuments()` function is similar to `count()`, but there are a * [few operators that `countDocuments()` does not support](https://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#countDocuments). * Below are the operators that `count()` supports but `countDocuments()` does not, * and the suggested replacement: * * - `$where`: [`$expr`](https://docs.mongodb.com/manual/reference/operator/query/expr/) * - `$near`: [`$geoWithin`](https://docs.mongodb.com/manual/reference/operator/query/geoWithin/) with [`$center`](https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center) * - `$nearSphere`: [`$geoWithin`](https://docs.mongodb.com/manual/reference/operator/query/geoWithin/) with [`$centerSphere`](https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere) * * @param {Object} filter * @param {Function} [callback] * @return {Query} * @api public */ Model.countDocuments = function countDocuments(conditions, callback) { _checkContext(this, 'countDocuments'); if (typeof conditions === 'function') { callback = conditions; conditions = {}; } const mq = new this.Query({}, {}, this, this.collection); callback = this.$handleCallbackError(callback); return mq.countDocuments(conditions, callback); }; /** * Counts number of documents that match `filter` in a database collection. * * This method is deprecated. If you want to count the number of documents in * a collection, e.g. `count({})`, use the [`estimatedDocumentCount()` function](/docs/api.html#model_Model.estimatedDocumentCount) * instead. Otherwise, use the [`countDocuments()`](/docs/api.html#model_Model.countDocuments) function instead. * * ####Example: * * Adventure.count({ type: 'jungle' }, function (err, count) { * if (err) .. * console.log('there are %d jungle adventures', count); * }); * * @deprecated * @param {Object} filter * @param {Function} [callback] * @return {Query} * @api public */ Model.count = function count(conditions, callback) { _checkContext(this, 'count'); if (typeof conditions === 'function') { callback = conditions; conditions = {}; } const mq = new this.Query({}, {}, this, this.collection); callback = this.$handleCallbackError(callback); return mq.count(conditions, callback); }; /** * Creates a Query for a `distinct` operation. * * Passing a `callback` executes the query. * * ####Example * * Link.distinct('url', { clicks: {$gt: 100}}, function (err, result) { * if (err) return handleError(err); * * assert(Array.isArray(result)); * console.log('unique urls with more than 100 clicks', result); * }) * * var query = Link.distinct('url'); * query.exec(callback); * * @param {String} field * @param {Object} [conditions] optional * @param {Function} [callback] * @return {Query} * @api public */ Model.distinct = function distinct(field, conditions, callback) { _checkContext(this, 'distinct'); const mq = new this.Query({}, {}, this, this.collection); if (typeof conditions === 'function') { callback = conditions; conditions = {}; } callback = this.$handleCallbackError(callback); return mq.distinct(field, conditions, callback); }; /** * Creates a Query, applies the passed conditions, and returns the Query. * * For example, instead of writing: * * User.find({age: {$gte: 21, $lte: 65}}, callback); * * we can instead write: * * User.where('age').gte(21).lte(65).exec(callback); * * Since the Query class also supports `where` you can continue chaining * * User * .where('age').gte(21).lte(65) * .where('name', /^b/i) * ... etc * * @param {String} path * @param {Object} [val] optional value * @return {Query} * @api public */ Model.where = function where(path, val) { _checkContext(this, 'where'); void val; // eslint const mq = new this.Query({}, {}, this, this.collection).find({}); return mq.where.apply(mq, arguments); }; /** * Creates a `Query` and specifies a `$where` condition. * * Sometimes you need to query for things in mongodb using a JavaScript expression. You can do so via `find({ $where: javascript })`, or you can use the mongoose shortcut method $where via a Query chain or from your mongoose Model. * * Blog.$where('this.username.indexOf("val") !== -1').exec(function (err, docs) {}); * * @param {String|Function} argument is a javascript string or anonymous function * @method $where * @memberOf Model * @return {Query} * @see Query.$where #query_Query-%24where * @api public */ Model.$where = function $where() { _checkContext(this, '$where'); const mq = new this.Query({}, {}, this, this.collection).find({}); return mq.$where.apply(mq, arguments); }; /** * Issues a mongodb findAndModify update command. * * Finds a matching document, updates it according to the `update` arg, passing any `options`, and returns the found document (if any) to the callback. The query executes if `callback` is passed else a Query object is returned. * * ####Options: * * - `new`: bool - if true, return the modified document rather than the original. defaults to false (changed in 4.0) * - `upsert`: bool - creates the object if it doesn't exist. defaults to false. * - `fields`: {Object|String} - Field selection. Equivalent to `.select(fields).findOneAndUpdate()` * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0 * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update * - `runValidators`: if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema. * - `setDefaultsOnInsert`: if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/). * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) * - `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update * * ####Examples: * * A.findOneAndUpdate(conditions, update, options, callback) // executes * A.findOneAndUpdate(conditions, update, options) // returns Query * A.findOneAndUpdate(conditions, update, callback) // executes * A.findOneAndUpdate(conditions, update) // returns Query * A.findOneAndUpdate() // returns Query * * ####Note: * * All top level update keys which are not `atomic` operation names are treated as set operations: * * ####Example: * * var query = { name: 'borne' }; * Model.findOneAndUpdate(query, { name: 'jason bourne' }, options, callback) * * // is sent as * Model.findOneAndUpdate(query, { $set: { name: 'jason bourne' }}, options, callback) * * This helps prevent accidentally overwriting your document with `{ name: 'jason bourne' }`. * * ####Note: * * Values are cast to their appropriate types when using the findAndModify helpers. * However, the below are not executed by default. * * - defaults. Use the `setDefaultsOnInsert` option to override. * * `findAndModify` helpers support limited validation. You can * enable these by setting the `runValidators` options, * respectively. * * If you need full-fledged validation, use the traditional approach of first * retrieving the document. * * Model.findById(id, function (err, doc) { * if (err) .. * doc.name = 'jason bourne'; * doc.save(callback); * }); * * @param {Object} [conditions] * @param {Object} [update] * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) * @param {Boolean} [options.new=false] By default, `findOneAndUpdate()` returns the document as it was **before** `update` was applied. If you set `new: true`, `findOneAndUpdate()` will instead give you the object after `update` was applied. * @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](/docs/api.html#query_Query-lean) and [the Mongoose lean tutorial](/docs/tutorials/lean.html). * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server. * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set. * @param {Boolean} [options.returnOriginal=null] An alias for the `new` option. `returnOriginal: false` is equivalent to `new: true`. * @param {Boolean} [options.overwrite=false] By default, if you don't include any [update operators](https://docs.mongodb.com/manual/reference/operator/update/) in `update`, Mongoose will wrap `update` in `$set` for you. This prevents you from accidentally overwriting the document. This option tells Mongoose to skip adding `$set`. An alternative to this would be using [Model.findOneAndReplace(conditions, update, options, callback)](https://mongoosejs.com/docs/api/model.html#model_Model.findOneAndReplace). * @param {Function} [callback] * @return {Query} * @see Tutorial /docs/tutorials/findoneandupdate.html * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command * @api public */ Model.findOneAndUpdate = function(conditions, update, options, callback) { _checkContext(this, 'findOneAndUpdate'); if (typeof options === 'function') { callback = options; options = null; } else if (arguments.length === 1) { if (typeof conditions === 'function') { const msg = 'Model.findOneAndUpdate(): First argument must not be a function.\n\n' + ' ' + this.modelName + '.findOneAndUpdate(conditions, update, options, callback)\n' + ' ' + this.modelName + '.findOneAndUpdate(conditions, update, options)\n' + ' ' + this.modelName + '.findOneAndUpdate(conditions, update)\n' + ' ' + this.modelName + '.findOneAndUpdate(update)\n' + ' ' + this.modelName + '.findOneAndUpdate()\n'; throw new TypeError(msg); } update = conditions; conditions = undefined; } callback = this.$handleCallbackError(callback); let fields; if (options) { fields = options.fields || options.projection; } update = utils.clone(update, { depopulate: true, _isNested: true }); _decorateUpdateWithVersionKey(update, options, this.schema.options.versionKey); const mq = new this.Query({}, {}, this, this.collection); mq.select(fields); return mq.findOneAndUpdate(conditions, update, options, callback); }; /*! * Decorate the update with a version key, if necessary */ function _decorateUpdateWithVersionKey(update, options, versionKey) { if (!versionKey || !get(options, 'upsert', false)) { return; } const updatedPaths = modifiedPaths(update); if (!updatedPaths[versionKey]) { if (options.overwrite) { update[versionKey] = 0; } else { if (!update.$setOnInsert) { update.$setOnInsert = {}; } update.$setOnInsert[versionKey] = 0; } } } /** * Issues a mongodb findAndModify update command by a document's _id field. * `findByIdAndUpdate(id, ...)` is equivalent to `findOneAndUpdate({ _id: id }, ...)`. * * Finds a matching document, updates it according to the `update` arg, * passing any `options`, and returns the found document (if any) to the * callback. The query executes if `callback` is passed. * * This function triggers the following middleware. * * - `findOneAndUpdate()` * * ####Options: * * - `new`: bool - true to return the modified document rather than the original. defaults to false * - `upsert`: bool - creates the object if it doesn't exist. defaults to false. * - `runValidators`: if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema. * - `setDefaultsOnInsert`: if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/). * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update * - `select`: sets the document fields to return * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) * - `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update * * ####Examples: * * A.findByIdAndUpdate(id, update, options, callback) // executes * A.findByIdAndUpdate(id, update, options) // returns Query * A.findByIdAndUpdate(id, update, callback) // executes * A.findByIdAndUpdate(id, update) // returns Query * A.findByIdAndUpdate() // returns Query * * ####Note: * * All top level update keys which are not `atomic` operation names are treated as set operations: * * ####Example: * * Model.findByIdAndUpdate(id, { name: 'jason bourne' }, options, callback) * * // is sent as * Model.findByIdAndUpdate(id, { $set: { name: 'jason bourne' }}, options, callback) * * This helps prevent accidentally overwriting your document with `{ name: 'jason bourne' }`. * * ####Note: * * Values are cast to their appropriate types when using the findAndModify helpers. * However, the below are not executed by default. * * - defaults. Use the `setDefaultsOnInsert` option to override. * * `findAndModify` helpers support limited validation. You can * enable these by setting the `runValidators` options, * respectively. * * If you need full-fledged validation, use the traditional approach of first * retrieving the document. * * Model.findById(id, function (err, doc) { * if (err) .. * doc.name = 'jason bourne'; * doc.save(callback); * }); * * @param {Object|Number|String} id value of `_id` to query by * @param {Object} [update] * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) * @param {Boolean} [options.new=false] By default, `findOneAndUpdate()` returns the document as it was **before** `update` was applied. If you set `new: true`, `findOneAndUpdate()` will instead give you the object after `update` was applied. * @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](/docs/api.html#query_Query-lean) and [the Mongoose lean tutorial](/docs/tutorials/lean.html). * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server. * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set. * @param {Boolean} [options.returnOriginal=null] An alias for the `new` option. `returnOriginal: false` is equivalent to `new: true`. * @param {Boolean} [options.overwrite=false] By default, if you don't include any [update operators](https://docs.mongodb.com/manual/reference/operator/update/) in `update`, Mongoose will wrap `update` in `$set` for you. This prevents you from accidentally overwriting the document. This option tells Mongoose to skip adding `$set`. An alternative to this would be using [Model.findOneAndReplace({ _id: id }, update, options, callback)](https://mongoosejs.com/docs/api/model.html#model_Model.findOneAndReplace). * @param {Function} [callback] * @return {Query} * @see Model.findOneAndUpdate #model_Model.findOneAndUpdate * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command * @api public */ Model.findByIdAndUpdate = function(id, update, options, callback) { _checkContext(this, 'findByIdAndUpdate'); callback = this.$handleCallbackError(callback); if (arguments.length === 1) { if (typeof id === 'function') { const msg = 'Model.findByIdAndUpdate(): First argument must not be a function.\n\n' + ' ' + this.modelName + '.findByIdAndUpdate(id, callback)\n' + ' ' + this.modelName + '.findByIdAndUpdate(id)\n' + ' ' + this.modelName + '.findByIdAndUpdate()\n'; throw new TypeError(msg); } return this.findOneAndUpdate({ _id: id }, undefined); } // if a model is passed in instead of an id if (id instanceof Document) { id = id._id; } return this.findOneAndUpdate.call(this, { _id: id }, update, options, callback); }; /** * Issue a MongoDB `findOneAndDelete()` command. * * Finds a matching document, removes it, and passes the found document * (if any) to the callback. * * Executes the query if `callback` is passed. * * This function triggers the following middleware. * * - `findOneAndDelete()` * * This function differs slightly from `Model.findOneAndRemove()` in that * `findOneAndRemove()` becomes a [MongoDB `findAndModify()` command](https://docs.mongodb.com/manual/reference/method/db.collection.findAndModify/), * as opposed to a `findOneAndDelete()` command. For most mongoose use cases, * this distinction is purely pedantic. You should use `findOneAndDelete()` * unless you have a good reason not to. * * ####Options: * * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0 * - `select`: sets the document fields to return * - `projection`: like select, it determines which fields to return, ex. `{ projection: { _id: 0 } }` * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) * - `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update * * ####Examples: * * A.findOneAndDelete(conditions, options, callback) // executes * A.findOneAndDelete(conditions, options) // return Query * A.findOneAndDelete(conditions, callback) // executes * A.findOneAndDelete(conditions) // returns Query * A.findOneAndDelete() // returns Query * * Values are cast to their appropriate types when using the findAndModify helpers. * However, the below are not executed by default. * * - defaults. Use the `setDefaultsOnInsert` option to override. * * `findAndModify` helpers support limited validation. You can * enable these by setting the `runValidators` options, * respectively. * * If you need full-fledged validation, use the traditional approach of first * retrieving the document. * * Model.findById(id, function (err, doc) { * if (err) .. * doc.name = 'jason bourne'; * doc.save(callback); * }); * * @param {Object} conditions * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). * @param {Function} [callback] * @return {Query} * @api public */ Model.findOneAndDelete = function(conditions, options, callback) { _checkContext(this, 'findOneAndDelete'); if (arguments.length === 1 && typeof conditions === 'function') { const msg = 'Model.findOneAndDelete(): First argument must not be a function.\n\n' + ' ' + this.modelName + '.findOneAndDelete(conditions, callback)\n' + ' ' + this.modelName + '.findOneAndDelete(conditions)\n' + ' ' + this.modelName + '.findOneAndDelete()\n'; throw new TypeError(msg); } if (typeof options === 'function') { callback = options; options = undefined; } callback = this.$handleCallbackError(callback); let fields; if (options) { fields = options.select; options.select = undefined; } const mq = new this.Query({}, {}, this, this.collection); mq.select(fields); return mq.findOneAndDelete(conditions, options, callback); }; /** * Issue a MongoDB `findOneAndDelete()` command by a document's _id field. * In other words, `findByIdAndDelete(id)` is a shorthand for * `findOneAndDelete({ _id: id })`. * * This function triggers the following middleware. * * - `findOneAndDelete()` * * @param {Object|Number|String} id value of `_id` to query by * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) * @param {Function} [callback] * @return {Query} * @see Model.findOneAndRemove #model_Model.findOneAndRemove * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command */ Model.findByIdAndDelete = function(id, options, callback) { _checkContext(this, 'findByIdAndDelete'); if (arguments.length === 1 && typeof id === 'function') { const msg = 'Model.findByIdAndDelete(): First argument must not be a function.\n\n' + ' ' + this.modelName + '.findByIdAndDelete(id, callback)\n' + ' ' + this.modelName + '.findByIdAndDelete(id)\n' + ' ' + this.modelName + '.findByIdAndDelete()\n'; throw new TypeError(msg); } callback = this.$handleCallbackError(callback); return this.findOneAndDelete({ _id: id }, options, callback); }; /** * Issue a MongoDB `findOneAndReplace()` command. * * Finds a matching document, replaces it with the provided doc, and passes the * returned doc to the callback. * * Executes the query if `callback` is passed. * * This function triggers the following query middleware. * * - `findOneAndReplace()` * * ####Options: * * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0 * - `select`: sets the document fields to return * - `projection`: like select, it determines which fields to return, ex. `{ projection: { _id: 0 } }` * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) * - `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update * * ####Examples: * * A.findOneAndReplace(conditions, options, callback) // executes * A.findOneAndReplace(conditions, options) // return Query * A.findOneAndReplace(conditions, callback) // executes * A.findOneAndReplace(conditions) // returns Query * A.findOneAndReplace() // returns Query * * Values are cast to their appropriate types when using the findAndModify helpers. * However, the below are not executed by default. * * - defaults. Use the `setDefaultsOnInsert` option to override. * * @param {Object} filter Replace the first document that matches this filter * @param {Object} [replacement] Replace with this document * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) * @param {Boolean} [options.new=false] By default, `findOneAndUpdate()` returns the document as it was **before** `update` was applied. If you set `new: true`, `findOneAndUpdate()` will instead give you the object after `update` was applied. * @param {Object} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](/docs/api.html#query_Query-lean) and [the Mongoose lean tutorial](/docs/tutorials/lean.html). * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server. * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set. * @param {Boolean} [options.returnOriginal=null] An alias for the `new` option. `returnOriginal: false` is equivalent to `new: true`. * @param {Function} [callback] * @return {Query} * @api public */ Model.findOneAndReplace = function(filter, replacement, options, callback) { _checkContext(this, 'findOneAndReplace'); if (arguments.length === 1 && typeof filter === 'function') { const msg = 'Model.findOneAndReplace(): First argument must not be a function.\n\n' + ' ' + this.modelName + '.findOneAndReplace(conditions, callback)\n' + ' ' + this.modelName + '.findOneAndReplace(conditions)\n' + ' ' + this.modelName + '.findOneAndReplace()\n'; throw new TypeError(msg); } if (arguments.length === 3 && typeof options === 'function') { callback = options; options = replacement; replacement = void 0; } if (arguments.length === 2 && typeof replacement === 'function') { callback = replacement; replacement = void 0; options = void 0; } callback = this.$handleCallbackError(callback); let fields; if (options) { fields = options.select; options.select = undefined; } const mq = new this.Query({}, {}, this, this.collection); mq.select(fields); return mq.findOneAndReplace(filter, replacement, options, callback); }; /** * Issue a mongodb findAndModify remove command. * * Finds a matching document, removes it, passing the found document (if any) to the callback. * * Executes the query if `callback` is passed. * * This function triggers the following middleware. * * - `findOneAndRemove()` * * ####Options: * * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update * - `maxTimeMS`: puts a time limit on the query - requires mongodb >= 2.6.0 * - `select`: sets the document fields to return * - `projection`: like select, it determines which fields to return, ex. `{ projection: { _id: 0 } }` * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) * - `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update * * ####Examples: * * A.findOneAndRemove(conditions, options, callback) // executes * A.findOneAndRemove(conditions, options) // return Query * A.findOneAndRemove(conditions, callback) // executes * A.findOneAndRemove(conditions) // returns Query * A.findOneAndRemove() // returns Query * * Values are cast to their appropriate types when using the findAndModify helpers. * However, the below are not executed by default. * * - defaults. Use the `setDefaultsOnInsert` option to override. * * `findAndModify` helpers support limited validation. You can * enable these by setting the `runValidators` options, * respectively. * * If you need full-fledged validation, use the traditional approach of first * retrieving the document. * * Model.findById(id, function (err, doc) { * if (err) .. * doc.name = 'jason bourne'; * doc.save(callback); * }); * * @param {Object} conditions * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) * @param {Function} [callback] * @return {Query} * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command * @api public */ Model.findOneAndRemove = function(conditions, options, callback) { _checkContext(this, 'findOneAndRemove'); if (arguments.length === 1 && typeof conditions === 'function') { const msg = 'Model.findOneAndRemove(): First argument must not be a function.\n\n' + ' ' + this.modelName + '.findOneAndRemove(conditions, callback)\n' + ' ' + this.modelName + '.findOneAndRemove(conditions)\n' + ' ' + this.modelName + '.findOneAndRemove()\n'; throw new TypeError(msg); } if (typeof options === 'function') { callback = options; options = undefined; } callback = this.$handleCallbackError(callback); let fields; if (options) { fields = options.select; options.select = undefined; } const mq = new this.Query({}, {}, this, this.collection); mq.select(fields); return mq.findOneAndRemove(conditions, options, callback); }; /** * Issue a mongodb findAndModify remove command by a document's _id field. `findByIdAndRemove(id, ...)` is equivalent to `findOneAndRemove({ _id: id }, ...)`. * * Finds a matching document, removes it, passing the found document (if any) to the callback. * * Executes the query if `callback` is passed. * * This function triggers the following middleware. * * - `findOneAndRemove()` * * ####Options: * * - `sort`: if multiple docs are found by the conditions, sets the sort order to choose which doc to update * - `select`: sets the document fields to return * - `rawResult`: if true, returns the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.0/api/Collection.html#findAndModify) * - `strict`: overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) for this update * * ####Examples: * * A.findByIdAndRemove(id, options, callback) // executes * A.findByIdAndRemove(id, options) // return Query * A.findByIdAndRemove(id, callback) // executes * A.findByIdAndRemove(id) // returns Query * A.findByIdAndRemove() // returns Query * * @param {Object|Number|String} id value of `_id` to query by * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) * @param {ClientSession} [options.session=null] The session associated with this query. See [transactions docs](/docs/transactions.html). * @param {Function} [callback] * @return {Query} * @see Model.findOneAndRemove #model_Model.findOneAndRemove * @see mongodb http://www.mongodb.org/display/DOCS/findAndModify+Command */ Model.findByIdAndRemove = function(id, options, callback) { _checkContext(this, 'findByIdAndRemove'); if (arguments.length === 1 && typeof id === 'function') { const msg = 'Model.findByIdAndRemove(): First argument must not be a function.\n\n' + ' ' + this.modelName + '.findByIdAndRemove(id, callback)\n' + ' ' + this.modelName + '.findByIdAndRemove(id)\n' + ' ' + this.modelName + '.findByIdAndRemove()\n'; throw new TypeError(msg); } callback = this.$handleCallbackError(callback); return this.findOneAndRemove({ _id: id }, options, callback); }; /** * Shortcut for saving one or more documents to the database. * `MyModel.create(docs)` does `new MyModel(doc).save()` for every doc in * docs. * * This function triggers the following middleware. * * - `save()` * * ####Example: * * // pass a spread of docs and a callback * Candy.create({ type: 'jelly bean' }, { type: 'snickers' }, function (err, jellybean, snickers) { * if (err) // ... * }); * * // pass an array of docs * var array = [{ type: 'jelly bean' }, { type: 'snickers' }]; * Candy.create(array, function (err, candies) { * if (err) // ... * * var jellybean = candies[0]; * var snickers = candies[1]; * // ... * }); * * // callback is optional; use the returned promise if you like: * var promise = Candy.create({ type: 'jawbreaker' }); * promise.then(function (jawbreaker) { * // ... * }) * * @param {Array|Object} docs Documents to insert, as a spread or array * @param {Object} [options] Options passed down to `save()`. To specify `options`, `docs` **must** be an array, not a spread. * @param {Function} [callback] callback * @return {Promise} * @api public */ Model.create = function create(doc, options, callback) { _checkContext(this, 'create'); let args; let cb; const discriminatorKey = this.schema.options.discriminatorKey; if (Array.isArray(doc)) { args = doc; cb = typeof options === 'function' ? options : callback; options = options != null && typeof options === 'object' ? options : {}; } else { const last = arguments[arguments.length - 1]; options = {}; // Handle falsy callbacks re: #5061 if (typeof last === 'function' || !last) { cb = last; args = utils.args(arguments, 0, arguments.length - 1); } else { args = utils.args(arguments); } if (args.length === 2 && args[0] != null && args[1] != null && args[0].session == null && last.session != null && last.session.constructor.name === 'ClientSession' && !this.schema.path('session')) { // Probably means the user is running into the common mistake of trying // to use a spread to specify options, see gh-7535 console.warn('WARNING: to pass a `session` to `Model.create()` in ' + 'Mongoose, you **must** pass an array as the first argument. See: ' + 'https://mongoosejs.com/docs/api.html#model_Model.create'); } } return promiseOrCallback(cb, cb => { cb = this.$wrapCallback(cb); if (args.length === 0) { return cb(null); } const toExecute = []; let firstError; args.forEach(doc => { toExecute.push(callback => { const Model = this.discriminators && doc[discriminatorKey] != null ? this.discriminators[doc[discriminatorKey]] || getDiscriminatorByValue(this, doc[discriminatorKey]) : this; if (Model == null) { throw new MongooseError(`Discriminator "${doc[discriminatorKey]}" not ` + `found for model "${this.modelName}"`); } let toSave = doc; const callbackWrapper = (error, doc) => { if (error) { if (!firstError) { firstError = error; } return callback(null, { error: error }); } callback(null, { doc: doc }); }; if (!(toSave instanceof Model)) { try { toSave = new Model(toSave); } catch (error) { return callbackWrapper(error); } } toSave.save(options, callbackWrapper); }); }); let numFns = toExecute.length; if (numFns === 0) { return cb(null, []); } const _done = (error, res) => { const savedDocs = []; const len = res.length; for (let i = 0; i < len; ++i) { if (res[i].doc) { savedDocs.push(res[i].doc); } } if (firstError) { return cb(firstError, savedDocs); } if (doc instanceof Array) { cb(null, savedDocs); } else { cb.apply(this, [null].concat(savedDocs)); } }; const _res = []; toExecute.forEach((fn, i) => { fn((err, res) => { _res[i] = res; if (--numFns <= 0) { return _done(null, _res); } }); }); }, this.events); }; /** * _Requires a replica set running MongoDB >= 3.6.0._ Watches the * underlying collection for changes using * [MongoDB change streams](https://docs.mongodb.com/manual/changeStreams/). * * This function does **not** trigger any middleware. In particular, it * does **not** trigger aggregate middleware. * * The ChangeStream object is an event emitter that emits the following events: * * - 'change': A change occurred, see below example * - 'error': An unrecoverable error occurred. In particular, change streams currently error out if they lose connection to the replica set primary. Follow [this GitHub issue](https://github.com/Automattic/mongoose/issues/6799) for updates. * - 'end': Emitted if the underlying stream is closed * - 'close': Emitted if the underlying stream is closed * * ####Example: * * const doc = await Person.create({ name: 'Ned Stark' }); * const changeStream = Person.watch().on('change', change => console.log(change)); * // Will print from the above `console.log()`: * // { _id: { _data: ... }, * // operationType: 'delete', * // ns: { db: 'mydb', coll: 'Person' }, * // documentKey: { _id: 5a51b125c5500f5aa094c7bd } } * await doc.remove(); * * @param {Array} [pipeline] * @param {Object} [options] see the [mongodb driver options](http://mongodb.github.io/node-mongodb-native/3.0/api/Collection.html#watch) * @return {ChangeStream} mongoose-specific change stream wrapper, inherits from EventEmitter * @api public */ Model.watch = function(pipeline, options) { _checkContext(this, 'watch'); const changeStreamThunk = cb => { if (this.collection.buffer) { this.collection.addQueue(() => { if (this.closed) { return; } const driverChangeStream = this.collection.watch(pipeline, options); cb(null, driverChangeStream); }); } else { const driverChangeStream = this.collection.watch(pipeline, options); cb(null, driverChangeStream); } }; return new ChangeStream(changeStreamThunk, pipeline, options); }; /** * _Requires MongoDB >= 3.6.0._ Starts a [MongoDB session](https://docs.mongodb.com/manual/release-notes/3.6/#client-sessions) * for benefits like causal consistency, [retryable writes](https://docs.mongodb.com/manual/core/retryable-writes/), * and [transactions](http://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html). * * Calling `MyModel.startSession()` is equivalent to calling `MyModel.db.startSession()`. * * This function does not trigger any middleware. * * ####Example: * * const session = await Person.startSession(); * let doc = await Person.findOne({ name: 'Ned Stark' }, null, { session }); * await doc.remove(); * // `doc` will always be null, even if reading from a replica set * // secondary. Without causal consistency, it is possible to * // get a doc back from the below query if the query reads from a * // secondary that is experiencing replication lag. * doc = await Person.findOne({ name: 'Ned Stark' }, null, { session, readPreference: 'secondary' }); * * @param {Object} [options] see the [mongodb driver options](http://mongodb.github.io/node-mongodb-native/3.0/api/MongoClient.html#startSession) * @param {Boolean} [options.causalConsistency=true] set to false to disable causal consistency * @param {Function} [callback] * @return {Promise<ClientSession>} promise that resolves to a MongoDB driver `ClientSession` * @api public */ Model.startSession = function() { _checkContext(this, 'startSession'); return this.db.startSession.apply(this.db, arguments); }; /** * Shortcut for validating an array of documents and inserting them into * MongoDB if they're all valid. This function is faster than `.create()` * because it only sends one operation to the server, rather than one for each * document. * * Mongoose always validates each document **before** sending `insertMany` * to MongoDB. So if one document has a validation error, no documents will * be saved, unless you set * [the `ordered` option to false](https://docs.mongodb.com/manual/reference/method/db.collection.insertMany/#error-handling). * * This function does **not** trigger save middleware. * * This function triggers the following middleware. * * - `insertMany()` * * ####Example: * * var arr = [{ name: 'Star Wars' }, { name: 'The Empire Strikes Back' }]; * Movies.insertMany(arr, function(error, docs) {}); * * @param {Array|Object|*} doc(s) * @param {Object} [options] see the [mongodb driver options](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#insertMany) * @param {Boolean} [options.ordered = true] if true, will fail fast on the first error encountered. If false, will insert all the documents it can and report errors later. An `insertMany()` with `ordered = false` is called an "unordered" `insertMany()`. * @param {Boolean} [options.rawResult = false] if false, the returned promise resolves to the documents that passed mongoose document validation. If `true`, will return the [raw result from the MongoDB driver](http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~insertWriteOpCallback) with a `mongoose` property that contains `validationErrors` if this is an unordered `insertMany`. * @param {Boolean} [options.lean = false] if `true`, skips hydrating and validating the documents. This option is useful if you need the extra performance, but Mongoose won't validate the documents before inserting. * @param {Number} [options.limit = null] this limits the number of documents being processed (validation/casting) by mongoose in parallel, this does **NOT** send the documents in batches to MongoDB. Use this option if you're processing a large number of documents and your app is running out of memory. * @param {Function} [callback] callback * @return {Promise} resolving to the raw result from the MongoDB driver if `options.rawResult` was `true`, or the documents that passed validation, otherwise * @api public */ Model.insertMany = function(arr, options, callback) { _checkContext(this, 'insertMany'); if (typeof options === 'function') { callback = options; options = null; } return promiseOrCallback(callback, cb => { this.$__insertMany(arr, options, cb); }, this.events); }; /*! * ignore */ Model.$__insertMany = function(arr, options, callback) { const _this = this; if (typeof options === 'function') { callback = options; options = null; } if (callback) { callback = this.$handleCallbackError(callback); callback = this.$wrapCallback(callback); } callback = callback || utils.noop; options = options || {}; const limit = get(options, 'limit', 1000); const rawResult = get(options, 'rawResult', false); const ordered = get(options, 'ordered', true); const lean = get(options, 'lean', false); if (!Array.isArray(arr)) { arr = [arr]; } const validationErrors = []; const toExecute = arr.map(doc => callback => { if (!(doc instanceof _this)) { try { doc = new _this(doc); } catch (err) { return callback(err); } } if (options.session != null) { doc.$session(options.session); } // If option `lean` is set to true bypass validation if (lean) { // we have to execute callback at the nextTick to be compatible // with parallelLimit, as `results` variable has TDZ issue if we // execute the callback synchronously return process.nextTick(() => callback(null, doc)); } doc.validate({ __noPromise: true }, function(error) { if (error) { // Option `ordered` signals that insert should be continued after reaching // a failing insert. Therefore we delegate "null", meaning the validation // failed. It's up to the next function to filter out all failed models if (ordered === false) { validationErrors.push(error); return callback(null, null); } return callback(error); } callback(null, doc); }); }); parallelLimit(toExecute, limit, function(error, docs) { if (error) { callback(error, null); return; } // We filter all failed pre-validations by removing nulls const docAttributes = docs.filter(function(doc) { return doc != null; }); // Quickly escape while there aren't any valid docAttributes if (docAttributes.length < 1) { if (rawResult) { const res = { mongoose: { validationErrors: validationErrors } }; return callback(null, res); } callback(null, []); return; } const docObjects = docAttributes.map(function(doc) { if (doc.schema.options.versionKey) { doc[doc.schema.options.versionKey] = 0; } if (doc.initializeTimestamps) { return doc.initializeTimestamps().toObject(internalToObjectOptions); } return doc.toObject(internalToObjectOptions); }); _this.collection.insertMany(docObjects, options, function(error, res) { if (error) { callback(error, null); return; } for (const attribute of docAttributes) { attribute.$__reset(); _setIsNew(attribute, false); } if (rawResult) { if (ordered === false) { // Decorate with mongoose validation errors in case of unordered, // because then still do `insertMany()` res.mongoose = { validationErrors: validationErrors }; } return callback(null, res); } callback(null, docAttributes); }); }); }; /*! * ignore */ function _setIsNew(doc, val) { doc.isNew = val; doc.emit('isNew', val); doc.constructor.emit('isNew', val); const subdocs = doc.$__getAllSubdocs(); for (const subdoc of subdocs) { subdoc.isNew = val; } } /** * Sends multiple `insertOne`, `updateOne`, `updateMany`, `replaceOne`, * `deleteOne`, and/or `deleteMany` operations to the MongoDB server in one * command. This is faster than sending multiple independent operations (e.g. * if you use `create()`) because with `bulkWrite()` there is only one round * trip to MongoDB. * * Mongoose will perform casting on all operations you provide. * * This function does **not** trigger any middleware, neither `save()`, nor `update()`. * If you need to trigger * `save()` middleware for every document use [`create()`](http://mongoosejs.com/docs/api.html#model_Model.create) instead. * * ####Example: * * Character.bulkWrite([ * { * insertOne: { * document: { * name: 'Eddard Stark', * title: 'Warden of the North' * } * } * }, * { * updateOne: { * filter: { name: 'Eddard Stark' }, * // If you were using the MongoDB driver directly, you'd need to do * // `update: { $set: { title: ... } }` but mongoose adds $set for * // you. * update: { title: 'Hand of the King' } * } * }, * { * deleteOne: { * { * filter: { name: 'Eddard Stark' } * } * } * } * ]).then(res => { * // Prints "1 1 1" * console.log(res.insertedCount, res.modifiedCount, res.deletedCount); * }); * * The [supported operations](https://docs.mongodb.com/manual/reference/method/db.collection.bulkWrite/#db.collection.bulkWrite) are: * * - `insertOne` * - `updateOne` * - `updateMany` * - `deleteOne` * - `deleteMany` * - `replaceOne` * * @param {Array} ops * @param {Object} [ops.insertOne.document] The document to insert * @param {Object} [opts.updateOne.filter] Update the first document that matches this filter * @param {Object} [opts.updateOne.update] An object containing [update operators](https://docs.mongodb.com/manual/reference/operator/update/) * @param {Boolean} [opts.updateOne.upsert=false] If true, insert a doc if none match * @param {Boolean} [opts.updateOne.timestamps=true] If false, do not apply [timestamps](https://mongoosejs.com/docs/guide.html#timestamps) to the operation * @param {Object} [opts.updateOne.collation] The [MongoDB collation](https://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-34-collations) to use * @param {Array} [opts.updateOne.arrayFilters] The [array filters](https://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-36-array-filters.html) used in `update` * @param {Object} [opts.updateMany.filter] Update all the documents that match this filter * @param {Object} [opts.updateMany.update] An object containing [update operators](https://docs.mongodb.com/manual/reference/operator/update/) * @param {Boolean} [opts.updateMany.upsert=false] If true, insert a doc if no documents match `filter` * @param {Boolean} [opts.updateMany.timestamps=true] If false, do not apply [timestamps](https://mongoosejs.com/docs/guide.html#timestamps) to the operation * @param {Object} [opts.updateMany.collation] The [MongoDB collation](https://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-34-collations) to use * @param {Array} [opts.updateMany.arrayFilters] The [array filters](https://thecodebarbarian.com/a-nodejs-perspective-on-mongodb-36-array-filters.html) used in `update` * @param {Object} [opts.deleteOne.filter] Delete the first document that matches this filter * @param {Object} [opts.deleteMany.filter] Delete all documents that match this filter * @param {Object} [opts.replaceOne.filter] Replace the first document that matches this filter * @param {Object} [opts.replaceOne.replacement] The replacement document * @param {Boolean} [opts.replaceOne.upsert=false] If true, insert a doc if no documents match `filter` * @param {Object} [options] * @param {Boolean} [options.ordered=true] If true, execute writes in order and stop at the first error. If false, execute writes in parallel and continue until all writes have either succeeded or errored. * @param {ClientSession} [options.session=null] The session associated with this bulk write. See [transactions docs](/docs/transactions.html). * @param {String|number} [options.w=1] The [write concern](https://docs.mongodb.com/manual/reference/write-concern/). See [`Query#w()`](/docs/api.html#query_Query-w) for more information. * @param {number} [options.wtimeout=null] The [write concern timeout](https://docs.mongodb.com/manual/reference/write-concern/#wtimeout). * @param {Boolean} [options.j=true] If false, disable [journal acknowledgement](https://docs.mongodb.com/manual/reference/write-concern/#j-option) * @param {Boolean} [options.bypassDocumentValidation=false] If true, disable [MongoDB server-side schema validation](https://docs.mongodb.com/manual/core/schema-validation/) for all writes in this bulk. * @param {Boolean} [options.strict=null] Overwrites the [`strict` option](/docs/guide.html#strict) on schema. If false, allows filtering and writing fields not defined in the schema for all writes in this bulk. * @param {Function} [callback] callback `function(error, bulkWriteOpResult) {}` * @return {Promise} resolves to a [`BulkWriteOpResult`](http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~BulkWriteOpResult) if the operation succeeds * @api public */ Model.bulkWrite = function(ops, options, callback) { _checkContext(this, 'bulkWrite'); if (typeof options === 'function') { callback = options; options = null; } options = options || {}; const validations = ops.map(op => castBulkWrite(this, op, options)); callback = this.$handleCallbackError(callback); return promiseOrCallback(callback, cb => { cb = this.$wrapCallback(cb); each(validations, (fn, cb) => fn(cb), error => { if (error) { return cb(error); } this.collection.bulkWrite(ops, options, (error, res) => { if (error) { return cb(error); } cb(null, res); }); }); }, this.events); }; /** * Shortcut for creating a new Document from existing raw data, pre-saved in the DB. * The document returned has no paths marked as modified initially. * * ####Example: * * // hydrate previous data into a Mongoose document * var mongooseCandy = Candy.hydrate({ _id: '54108337212ffb6d459f854c', type: 'jelly bean' }); * * @param {Object} obj * @return {Document} document instance * @api public */ Model.hydrate = function(obj) { _checkContext(this, 'hydrate'); const model = require('./queryhelpers').createModel(this, obj); model.init(obj); return model; }; /** * Updates one document in the database without returning it. * * This function triggers the following middleware. * * - `update()` * * ####Examples: * * MyModel.update({ age: { $gt: 18 } }, { oldEnough: true }, fn); * * const res = await MyModel.update({ name: 'Tobi' }, { ferret: true }); * res.n; // Number of documents that matched `{ name: 'Tobi' }` * // Number of documents that were changed. If every doc matched already * // had `ferret` set to `true`, `nModified` will be 0. * res.nModified; * * ####Valid options: * * - `strict` (boolean): overrides the [schema-level `strict` option](/docs/guide.html#strict) for this update * - `upsert` (boolean): whether to create the doc if it doesn't match (false) * - `writeConcern` (object): sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern) * - `omitUndefined` (boolean): If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server. * - `multi` (boolean): whether multiple documents should be updated (false) * - `runValidators`: if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema. * - `setDefaultsOnInsert` (boolean): if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/). * - `timestamps` (boolean): If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set. * - `overwrite` (boolean): disables update-only mode, allowing you to overwrite the doc (false) * * All `update` values are cast to their appropriate SchemaTypes before being sent. * * The `callback` function receives `(err, rawResponse)`. * * - `err` is the error if any occurred * - `rawResponse` is the full response from Mongo * * ####Note: * * All top level keys which are not `atomic` operation names are treated as set operations: * * ####Example: * * var query = { name: 'borne' }; * Model.update(query, { name: 'jason bourne' }, options, callback); * * // is sent as * Model.update(query, { $set: { name: 'jason bourne' }}, options, function(err, res)); * // if overwrite option is false. If overwrite is true, sent without the $set wrapper. * * This helps prevent accidentally overwriting all documents in your collection with `{ name: 'jason bourne' }`. * * ####Note: * * Be careful to not use an existing model instance for the update clause (this won't work and can cause weird behavior like infinite loops). Also, ensure that the update clause does not have an _id property, which causes Mongo to return a "Mod on _id not allowed" error. * * ####Note: * * Mongoose casts values and runs setters when using update. The following * features are **not** applied by default. * * - [defaults](/docs/defaults.html#the-setdefaultsoninsert-option) * - [validators](/docs/validation.html#update-validators) * - middleware * * If you need document middleware and fully-featured validation, load the * document first and then use [`save()`](/docs/api.html#model_Model-save). * * Model.findOne({ name: 'borne' }, function (err, doc) { * if (err) .. * doc.name = 'jason bourne'; * doc.save(callback); * }) * * @see strict http://mongoosejs.com/docs/guide.html#strict * @see response http://docs.mongodb.org/v2.6/reference/command/update/#output * @param {Object} filter * @param {Object} doc * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document * @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern) * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server. * @param {Boolean} [options.multi=false] whether multiple documents should be updated or just the first one that matches `filter`. * @param {Boolean} [options.runValidators=false] if true, runs [update validators](/docs/validation.html#update-validators) on this command. Update validators validate the update operation against the model's schema. * @param {Boolean} [options.setDefaultsOnInsert=false] if this and `upsert` are true, mongoose will apply the [defaults](http://mongoosejs.com/docs/defaults.html) specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on [MongoDB's `$setOnInsert` operator](https://docs.mongodb.org/v2.4/reference/operator/update/setOnInsert/). * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set. * @param {Boolean} [options.overwrite=false] By default, if you don't include any [update operators](https://docs.mongodb.com/manual/reference/operator/update/) in `doc`, Mongoose will wrap `doc` in `$set` for you. This prevents you from accidentally overwriting the document. This option tells Mongoose to skip adding `$set`. * @param {Function} [callback] params are (error, writeOpResult) * @param {Function} [callback] * @return {Query} * @see MongoDB docs https://docs.mongodb.com/manual/reference/command/update/#update-command-output * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult * @see Query docs https://mongoosejs.com/docs/queries.html * @api public */ Model.update = function update(conditions, doc, options, callback) { _checkContext(this, 'update'); return _update(this, 'update', conditions, doc, options, callback); }; /** * Same as `update()`, except MongoDB will update _all_ documents that match * `filter` (as opposed to just the first one) regardless of the value of * the `multi` option. * * **Note** updateMany will _not_ fire update middleware. Use `pre('updateMany')` * and `post('updateMany')` instead. * * ####Example: * const res = await Person.updateMany({ name: /Stark$/ }, { isDeleted: true }); * res.n; // Number of documents matched * res.nModified; // Number of documents modified * * This function triggers the following middleware. * * - `updateMany()` * * @param {Object} filter * @param {Object} doc * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document * @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern) * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server. * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set. * @param {Function} [callback] `function(error, res) {}` where `res` has 3 properties: `n`, `nModified`, `ok`. * @return {Query} * @see Query docs https://mongoosejs.com/docs/queries.html * @see MongoDB docs https://docs.mongodb.com/manual/reference/command/update/#update-command-output * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult * @api public */ Model.updateMany = function updateMany(conditions, doc, options, callback) { _checkContext(this, 'updateMany'); return _update(this, 'updateMany', conditions, doc, options, callback); }; /** * Same as `update()`, except it does not support the `multi` or `overwrite` * options. * * - MongoDB will update _only_ the first document that matches `filter` regardless of the value of the `multi` option. * - Use `replaceOne()` if you want to overwrite an entire document rather than using atomic operators like `$set`. * * ####Example: * const res = await Person.updateOne({ name: 'Jean-Luc Picard' }, { ship: 'USS Enterprise' }); * res.n; // Number of documents matched * res.nModified; // Number of documents modified * * This function triggers the following middleware. * * - `updateOne()` * * @param {Object} filter * @param {Object} doc * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document * @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern) * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server. * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Note that this allows you to overwrite timestamps. Does nothing if schema-level timestamps are not set. * @param {Function} [callback] params are (error, writeOpResult) * @return {Query} * @see Query docs https://mongoosejs.com/docs/queries.html * @see MongoDB docs https://docs.mongodb.com/manual/reference/command/update/#update-command-output * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult * @api public */ Model.updateOne = function updateOne(conditions, doc, options, callback) { _checkContext(this, 'updateOne'); return _update(this, 'updateOne', conditions, doc, options, callback); }; /** * Same as `update()`, except MongoDB replace the existing document with the * given document (no atomic operators like `$set`). * * ####Example: * const res = await Person.replaceOne({ _id: 24601 }, { name: 'Jean Valjean' }); * res.n; // Number of documents matched * res.nModified; // Number of documents modified * * This function triggers the following middleware. * * - `replaceOne()` * * @param {Object} filter * @param {Object} doc * @param {Object} [options] optional see [`Query.prototype.setOptions()`](http://mongoosejs.com/docs/api.html#query_Query-setOptions) * @param {Boolean|String} [options.strict] overwrites the schema's [strict mode option](http://mongoosejs.com/docs/guide.html#strict) * @param {Boolean} [options.upsert=false] if true, and no documents found, insert a new document * @param {Object} [options.writeConcern=null] sets the [write concern](https://docs.mongodb.com/manual/reference/write-concern/) for replica sets. Overrides the [schema-level write concern](/docs/guide.html#writeConcern) * @param {Boolean} [options.omitUndefined=false] If true, delete any properties whose value is `undefined` when casting an update. In other words, if this is set, Mongoose will delete `baz` from the update in `Model.updateOne({}, { foo: 'bar', baz: undefined })` before sending the update to the server. * @param {Boolean} [options.timestamps=null] If set to `false` and [schema-level timestamps](/docs/guide.html#timestamps) are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set. * @param {Function} [callback] `function(error, res) {}` where `res` has 3 properties: `n`, `nModified`, `ok`. * @return {Query} * @see Query docs https://mongoosejs.com/docs/queries.html * @see writeOpResult http://mongodb.github.io/node-mongodb-native/2.2/api/Collection.html#~WriteOpResult * @return {Query} * @api public */ Model.replaceOne = function replaceOne(conditions, doc, options, callback) { _checkContext(this, 'replaceOne'); const versionKey = get(this, 'schema.options.versionKey', null); if (versionKey && !doc[versionKey]) { doc[versionKey] = 0; } return _update(this, 'replaceOne', conditions, doc, options, callback); }; /*! * Common code for `updateOne()`, `updateMany()`, `replaceOne()`, and `update()` * because they need to do the same thing */ function _update(model, op, conditions, doc, options, callback) { const mq = new model.Query({}, {}, model, model.collection); callback = model.$handleCallbackError(callback); // gh-2406 // make local deep copy of conditions if (conditions instanceof Document) { conditions = conditions.toObject(); } else { conditions = utils.clone(conditions); } options = typeof options === 'function' ? options : utils.clone(options); const versionKey = get(model, 'schema.options.versionKey', null); _decorateUpdateWithVersionKey(doc, options, versionKey); return mq[op](conditions, doc, options, callback); } /** * Executes a mapReduce command. * * `o` is an object specifying all mapReduce options as well as the map and reduce functions. All options are delegated to the driver implementation. See [node-mongodb-native mapReduce() documentation](http://mongodb.github.io/node-mongodb-native/api-generated/collection.html#mapreduce) for more detail about options. * * This function does not trigger any middleware. * * ####Example: * * var o = {}; * // `map()` and `reduce()` are run on the MongoDB server, not Node.js, * // these functions are converted to strings * o.map = function () { emit(this.name, 1) }; * o.reduce = function (k, vals) { return vals.length }; * User.mapReduce(o, function (err, results) { * console.log(results) * }) * * ####Other options: * * - `query` {Object} query filter object. * - `sort` {Object} sort input objects using this key * - `limit` {Number} max number of documents * - `keeptemp` {Boolean, default:false} keep temporary data * - `finalize` {Function} finalize function * - `scope` {Object} scope variables exposed to map/reduce/finalize during execution * - `jsMode` {Boolean, default:false} it is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X * - `verbose` {Boolean, default:false} provide statistics on job execution time. * - `readPreference` {String} * - `out*` {Object, default: {inline:1}} sets the output target for the map reduce job. * * ####* out options: * * - `{inline:1}` the results are returned in an array * - `{replace: 'collectionName'}` add the results to collectionName: the results replace the collection * - `{reduce: 'collectionName'}` add the results to collectionName: if dups are detected, uses the reducer / finalize functions * - `{merge: 'collectionName'}` add the results to collectionName: if dups exist the new docs overwrite the old * * If `options.out` is set to `replace`, `merge`, or `reduce`, a Model instance is returned that can be used for further querying. Queries run against this model are all executed with the [`lean` option](/docs/tutorials/lean.html); meaning only the js object is returned and no Mongoose magic is applied (getters, setters, etc). * * ####Example: * * var o = {}; * // You can also define `map()` and `reduce()` as strings if your * // linter complains about `emit()` not being defined * o.map = 'function () { emit(this.name, 1) }'; * o.reduce = 'function (k, vals) { return vals.length }'; * o.out = { replace: 'createdCollectionNameForResults' } * o.verbose = true; * * User.mapReduce(o, function (err, model, stats) { * console.log('map reduce took %d ms', stats.processtime) * model.find().where('value').gt(10).exec(function (err, docs) { * console.log(docs); * }); * }) * * // `mapReduce()` returns a promise. However, ES6 promises can only * // resolve to exactly one value, * o.resolveToObject = true; * var promise = User.mapReduce(o); * promise.then(function (res) { * var model = res.model; * var stats = res.stats; * console.log('map reduce took %d ms', stats.processtime) * return model.find().where('value').gt(10).exec(); * }).then(function (docs) { * console.log(docs); * }).then(null, handleError).end() * * @param {Object} o an object specifying map-reduce options * @param {Function} [callback] optional callback * @see http://www.mongodb.org/display/DOCS/MapReduce * @return {Promise} * @api public */ Model.mapReduce = function mapReduce(o, callback) { _checkContext(this, 'mapReduce'); callback = this.$handleCallbackError(callback); return promiseOrCallback(callback, cb => { cb = this.$wrapCallback(cb); if (!Model.mapReduce.schema) { const opts = { noId: true, noVirtualId: true, strict: false }; Model.mapReduce.schema = new Schema({}, opts); } if (!o.out) o.out = { inline: 1 }; if (o.verbose !== false) o.verbose = true; o.map = String(o.map); o.reduce = String(o.reduce); if (o.query) { let q = new this.Query(o.query); q.cast(this); o.query = q._conditions; q = undefined; } this.collection.mapReduce(null, null, o, (err, res) => { if (err) { return cb(err); } if (res.collection) { // returned a collection, convert to Model const model = Model.compile('_mapreduce_' + res.collection.collectionName, Model.mapReduce.schema, res.collection.collectionName, this.db, this.base); model._mapreduce = true; res.model = model; return cb(null, res); } cb(null, res); }); }, this.events); }; /** * Performs [aggregations](http://docs.mongodb.org/manual/applications/aggregation/) on the models collection. * * If a `callback` is passed, the `aggregate` is executed and a `Promise` is returned. If a callback is not passed, the `aggregate` itself is returned. * * This function triggers the following middleware. * * - `aggregate()` * * ####Example: * * // Find the max balance of all accounts * Users.aggregate([ * { $group: { _id: null, maxBalance: { $max: '$balance' }}}, * { $project: { _id: 0, maxBalance: 1 }} * ]). * then(function (res) { * console.log(res); // [ { maxBalance: 98000 } ] * }); * * // Or use the aggregation pipeline builder. * Users.aggregate(). * group({ _id: null, maxBalance: { $max: '$balance' } }). * project('-id maxBalance'). * exec(function (err, res) { * if (err) return handleError(err); * console.log(res); // [ { maxBalance: 98 } ] * }); * * ####NOTE: * * - Mongoose does **not** cast aggregation pipelines to the model's schema because `$project` and `$group` operators allow redefining the "shape" of the documents at any stage of the pipeline, which may leave documents in an incompatible format. You can use the [mongoose-cast-aggregation plugin](https://github.com/AbdelrahmanHafez/mongoose-cast-aggregation) to enable minimal casting for aggregation pipelines. * - The documents returned are plain javascript objects, not mongoose documents (since any shape of document can be returned). * * @see Aggregate #aggregate_Aggregate * @see MongoDB http://docs.mongodb.org/manual/applications/aggregation/ * @param {Array} [pipeline] aggregation pipeline as an array of objects * @param {Function} [callback] * @return {Aggregate} * @api public */ Model.aggregate = function aggregate(pipeline, callback) { _checkContext(this, 'aggregate'); if (arguments.length > 2 || get(pipeline, 'constructor.name') === 'Object') { throw new MongooseError('Mongoose 5.x disallows passing a spread of operators ' + 'to `Model.aggregate()`. Instead of ' + '`Model.aggregate({ $match }, { $skip })`, do ' + '`Model.aggregate([{ $match }, { $skip }])`'); } if (typeof pipeline === 'function') { callback = pipeline; pipeline = []; } const aggregate = new Aggregate(pipeline || []); aggregate.model(this); if (typeof callback === 'undefined') { return aggregate; } callback = this.$handleCallbackError(callback); callback = this.$wrapCallback(callback); aggregate.exec(callback); return aggregate; }; /** * Casts and validates the given object against this model's schema, passing the * given `context` to custom validators. * * ####Example: * * const Model = mongoose.model('Test', Schema({ * name: { type: String, required: true }, * age: { type: Number, required: true } * }); * * try { * await Model.validate({ name: null }, ['name']) * } catch (err) { * err instanceof mongoose.Error.ValidationError; // true * Object.keys(err.errors); // ['name'] * } * * @param {Object} obj * @param {Array} pathsToValidate * @param {Object} [context] * @param {Function} [callback] * @return {Promise|undefined} * @api public */ Model.validate = function validate(obj, pathsToValidate, context, callback) { return promiseOrCallback(callback, cb => { const schema = this.schema; let paths = Object.keys(schema.paths); if (pathsToValidate != null) { const _pathsToValidate = new Set(pathsToValidate); paths = paths.filter(p => { const pieces = p.split('.'); let cur = pieces[0]; for (const piece of pieces) { if (_pathsToValidate.has(cur)) { return true; } cur += '.' + piece; } return _pathsToValidate.has(p); }); } for (const path of paths) { const schemaType = schema.path(path); if (!schemaType || !schemaType.$isMongooseArray) { continue; } const val = get(obj, path); pushNestedArrayPaths(val, path); } let remaining = paths.length; let error = null; for (const path of paths) { const schemaType = schema.path(path); if (schemaType == null) { _checkDone(); continue; } const pieces = path.split('.'); let cur = obj; for (let i = 0; i < pieces.length - 1; ++i) { cur = cur[pieces[i]]; } let val = get(obj, path, void 0); if (val != null) { try { val = schemaType.cast(val); cur[pieces[pieces.length - 1]] = val; } catch (err) { error = error || new ValidationError(); error.addError(path, err); _checkDone(); continue; } } schemaType.doValidate(val, err => { if (err) { error = error || new ValidationError(); if (err instanceof ValidationError) { for (const _err of Object.keys(err.errors)) { error.addError(`${path}.${err.errors[_err].path}`, _err); } } else { error.addError(err.path, err); } } _checkDone(); }, context, { path: path }); } function pushNestedArrayPaths(nestedArray, path) { if (nestedArray == null) { return; } for (let i = 0; i < nestedArray.length; ++i) { if (Array.isArray(nestedArray[i])) { pushNestedArrayPaths(nestedArray[i], path + '.' + i); } else { paths.push(path + '.' + i); } } } function _checkDone() { if (--remaining <= 0) { return cb(error); } } }); }; /** * Implements `$geoSearch` functionality for Mongoose * * This function does not trigger any middleware * * ####Example: * * var options = { near: [10, 10], maxDistance: 5 }; * Locations.geoSearch({ type : "house" }, options, function(err, res) { * console.log(res); * }); * * ####Options: * - `near` {Array} x,y point to search for * - `maxDistance` {Number} the maximum distance from the point near that a result can be * - `limit` {Number} The maximum number of results to return * - `lean` {Object|Boolean} return the raw object instead of the Mongoose Model * * @param {Object} conditions an object that specifies the match condition (required) * @param {Object} options for the geoSearch, some (near, maxDistance) are required * @param {Object|Boolean} [options.lean] if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See [`Query.lean()`](/docs/api.html#query_Query-lean) and the [Mongoose lean tutorial](/docs/tutorials/lean.html). * @param {Function} [callback] optional callback * @return {Promise} * @see http://docs.mongodb.org/manual/reference/command/geoSearch/ * @see http://docs.mongodb.org/manual/core/geohaystack/ * @api public */ Model.geoSearch = function(conditions, options, callback) { _checkContext(this, 'geoSearch'); if (typeof options === 'function') { callback = options; options = {}; } callback = this.$handleCallbackError(callback); return promiseOrCallback(callback, cb => { cb = this.$wrapCallback(cb); let error; if (conditions === undefined || !utils.isObject(conditions)) { error = new MongooseError('Must pass conditions to geoSearch'); } else if (!options.near) { error = new MongooseError('Must specify the near option in geoSearch'); } else if (!Array.isArray(options.near)) { error = new MongooseError('near option must be an array [x, y]'); } if (error) { return cb(error); } // send the conditions in the options object options.search = conditions; this.collection.geoHaystackSearch(options.near[0], options.near[1], options, (err, res) => { if (err) { return cb(err); } let count = res.results.length; if (options.lean || count === 0) { return cb(null, res.results); } const errSeen = false; function init(err) { if (err && !errSeen) { return cb(err); } if (!--count && !errSeen) { cb(null, res.results); } } for (let i = 0; i < res.results.length; ++i) { const temp = res.results[i]; res.results[i] = new this(); res.results[i].init(temp, {}, init); } }); }, this.events); }; /** * Populates document references. * * ####Available top-level options: * * - path: space delimited path(s) to populate * - select: optional fields to select * - match: optional query conditions to match * - model: optional name of the model to use for population * - options: optional query options like sort, limit, etc * - justOne: optional boolean, if true Mongoose will always set `path` to an array. Inferred from schema by default. * * ####Examples: * * // populates a single object * User.findById(id, function (err, user) { * var opts = [ * { path: 'company', match: { x: 1 }, select: 'name' }, * { path: 'notes', options: { limit: 10 }, model: 'override' } * ]; * * User.populate(user, opts, function (err, user) { * console.log(user); * }); * }); * * // populates an array of objects * User.find(match, function (err, users) { * var opts = [{ path: 'company', match: { x: 1 }, select: 'name' }]; * * var promise = User.populate(users, opts); * promise.then(console.log).end(); * }) * * // imagine a Weapon model exists with two saved documents: * // { _id: 389, name: 'whip' } * // { _id: 8921, name: 'boomerang' } * // and this schema: * // new Schema({ * // name: String, * // weapon: { type: ObjectId, ref: 'Weapon' } * // }); * * var user = { name: 'Indiana Jones', weapon: 389 }; * Weapon.populate(user, { path: 'weapon', model: 'Weapon' }, function (err, user) { * console.log(user.weapon.name); // whip * }) * * // populate many plain objects * var users = [{ name: 'Indiana Jones', weapon: 389 }] * users.push({ name: 'Batman', weapon: 8921 }) * Weapon.populate(users, { path: 'weapon' }, function (err, users) { * users.forEach(function (user) { * console.log('%s uses a %s', users.name, user.weapon.name) * // Indiana Jones uses a whip * // Batman uses a boomerang * }); * }); * // Note that we didn't need to specify the Weapon model because * // it is in the schema's ref * * @param {Document|Array} docs Either a single document or array of documents to populate. * @param {Object|String} options Either the paths to populate or an object specifying all parameters * @param {string} [options.path=null] The path to populate. * @param {boolean} [options.retainNullValues=false] By default, Mongoose removes null and undefined values from populated arrays. Use this option to make `populate()` retain `null` and `undefined` array entries. * @param {boolean} [options.getters=false] If true, Mongoose will call any getters defined on the `localField`. By default, Mongoose gets the raw value of `localField`. For example, you would need to set this option to `true` if you wanted to [add a `lowercase` getter to your `localField`](/docs/schematypes.html#schematype-options). * @param {boolean} [options.clone=false] When you do `BlogPost.find().populate('author')`, blog posts with the same author will share 1 copy of an `author` doc. Enable this option to make Mongoose clone populated docs before assigning them. * @param {Object|Function} [options.match=null] Add an additional filter to the populate query. Can be a filter object containing [MongoDB query syntax](https://docs.mongodb.com/manual/tutorial/query-documents/), or a function that returns a filter object. * @param {Boolean} [options.skipInvalidIds=false] By default, Mongoose throws a cast error if `localField` and `foreignField` schemas don't line up. If you enable this option, Mongoose will instead filter out any `localField` properties that cannot be casted to `foreignField`'s schema type. * @param {Number} [options.perDocumentLimit=null] For legacy reasons, `limit` with `populate()` may give incorrect results because it only executes a single query for every document being populated. If you set `perDocumentLimit`, Mongoose will ensure correct `limit` per document by executing a separate query for each document to `populate()`. For example, `.find().populate({ path: 'test', perDocumentLimit: 2 })` will execute 2 additional queries if `.find()` returns 2 documents. * @param {Object} [options.options=null] Additional options like `limit` and `lean`. * @param {Function} [callback(err,doc)] Optional callback, executed upon completion. Receives `err` and the `doc(s)`. * @return {Promise} * @api public */ Model.populate = function(docs, paths, callback) { _checkContext(this, 'populate'); const _this = this; // normalized paths paths = utils.populate(paths); // data that should persist across subPopulate calls const cache = {}; callback = this.$handleCallbackError(callback); return promiseOrCallback(callback, cb => { cb = this.$wrapCallback(cb); _populate(_this, docs, paths, cache, cb); }, this.events); }; /*! * Populate helper * * @param {Model} model the model to use * @param {Document|Array} docs Either a single document or array of documents to populate. * @param {Object} paths * @param {Function} [cb(err,doc)] Optional callback, executed upon completion. Receives `err` and the `doc(s)`. * @return {Function} * @api private */ function _populate(model, docs, paths, cache, callback) { let pending = paths.length; if (paths.length === 0) { return callback(null, docs); } // each path has its own query options and must be executed separately for (const path of paths) { populate(model, docs, path, next); } function next(err) { if (err) { return callback(err, null); } if (--pending) { return; } callback(null, docs); } } /*! * Populates `docs` */ const excludeIdReg = /\s?-_id\s?/; const excludeIdRegGlobal = /\s?-_id\s?/g; function populate(model, docs, options, callback) { // normalize single / multiple docs passed if (!Array.isArray(docs)) { docs = [docs]; } if (docs.length === 0 || docs.every(utils.isNullOrUndefined)) { return callback(); } const modelsMap = getModelsMapForPopulate(model, docs, options); if (modelsMap instanceof MongooseError) { return immediate(function() { callback(modelsMap); }); } const len = modelsMap.length; let vals = []; function flatten(item) { // no need to include undefined values in our query return undefined !== item; } let _remaining = len; let hasOne = false; const params = []; for (let i = 0; i < len; ++i) { const mod = modelsMap[i]; let select = mod.options.select; const match = _formatMatch(mod.match); let ids = utils.array.flatten(mod.ids, flatten); ids = utils.array.unique(ids); const assignmentOpts = {}; assignmentOpts.sort = get(mod, 'options.options.sort', void 0); assignmentOpts.excludeId = excludeIdReg.test(select) || (select && select._id === 0); if (ids.length === 0 || ids.every(utils.isNullOrUndefined)) { // Ensure that we set populate virtuals to 0 or empty array even // if we don't actually execute a query because they don't have // a value by default. See gh-7731, gh-8230 --_remaining; if (mod.count || mod.isVirtual) { _assign(model, [], mod, assignmentOpts); } continue; } hasOne = true; if (mod.foreignField.size === 1) { const foreignField = Array.from(mod.foreignField)[0]; const foreignSchemaType = mod.model.schema.path(foreignField); if (foreignField !== '_id' || !match['_id']) { ids = _filterInvalidIds(ids, foreignSchemaType, mod.options.skipInvalidIds); match[foreignField] = { $in: ids }; } } else { const $or = []; if (Array.isArray(match.$or)) { match.$and = [{ $or: match.$or }, { $or: $or }]; delete match.$or; } else { match.$or = $or; } for (const foreignField of mod.foreignField) { if (foreignField !== '_id' || !match['_id']) { const foreignSchemaType = mod.model.schema.path(foreignField); ids = _filterInvalidIds(ids, foreignSchemaType, mod.options.skipInvalidIds); $or.push({ [foreignField]: { $in: ids } }); } } } if (assignmentOpts.excludeId) { // override the exclusion from the query so we can use the _id // for document matching during assignment. we'll delete the // _id back off before returning the result. if (typeof select === 'string') { select = select.replace(excludeIdRegGlobal, ' '); } else { // preserve original select conditions by copying select = utils.object.shallowCopy(select); delete select._id; } } if (mod.options.options && mod.options.options.limit != null) { assignmentOpts.originalLimit = mod.options.options.limit; } else if (mod.options.limit != null) { assignmentOpts.originalLimit = mod.options.limit; } params.push([mod, match, select, assignmentOpts, _next]); } if (!hasOne) { // If no models to populate but we have a nested populate, // keep trying, re: gh-8946 if (options.populate != null) { const opts = options.populate.map(pop => Object.assign({}, pop, { path: options.path + '.' + pop.path })); return model.populate(docs, opts, callback); } return callback(); } for (const arr of params) { _execPopulateQuery.apply(null, arr); } function _next(err, valsFromDb) { if (err != null) { return callback(err, null); } vals = vals.concat(valsFromDb); if (--_remaining === 0) { _done(); } } function _done() { for (const arr of params) { const mod = arr[0]; const assignmentOpts = arr[3]; _assign(model, vals, mod, assignmentOpts); } callback(); } } /*! * ignore */ function _execPopulateQuery(mod, match, select, assignmentOpts, callback) { const subPopulate = utils.clone(mod.options.populate); const queryOptions = Object.assign({ skip: mod.options.skip, limit: mod.options.limit, perDocumentLimit: mod.options.perDocumentLimit }, mod.options.options); if (mod.count) { delete queryOptions.skip; } if (queryOptions.perDocumentLimit != null) { queryOptions.limit = queryOptions.perDocumentLimit; delete queryOptions.perDocumentLimit; } else if (queryOptions.limit != null) { queryOptions.limit = queryOptions.limit * mod.ids.length; } const query = mod.model.find(match, select, queryOptions); // If we're doing virtual populate and projection is inclusive and foreign // field is not selected, automatically select it because mongoose needs it. // If projection is exclusive and client explicitly unselected the foreign // field, that's the client's fault. for (const foreignField of mod.foreignField) { if (foreignField !== '_id' && query.selectedInclusively() && !isPathSelectedInclusive(query._fields, foreignField)) { query.select(foreignField); } } // If using count, still need the `foreignField` so we can match counts // to documents, otherwise we would need a separate `count()` for every doc. if (mod.count) { for (const foreignField of mod.foreignField) { query.select(foreignField); } } // If we need to sub-populate, call populate recursively if (subPopulate) { query.populate(subPopulate); } query.exec(callback); } /*! * ignore */ function _assign(model, vals, mod, assignmentOpts) { const options = mod.options; const isVirtual = mod.isVirtual; const justOne = mod.justOne; let _val; const lean = get(options, 'options.lean', false); const projection = parseProjection(get(options, 'select', null), true) || parseProjection(get(options, 'options.select', null), true); const len = vals.length; const rawOrder = {}; const rawDocs = {}; let key; let val; // Clone because `assignRawDocsToIdStructure` will mutate the array const allIds = utils.clone(mod.allIds); // optimization: // record the document positions as returned by // the query result. for (let i = 0; i < len; i++) { val = vals[i]; if (val == null) { continue; } for (const foreignField of mod.foreignField) { _val = utils.getValue(foreignField, val); if (Array.isArray(_val)) { _val = utils.array.flatten(_val); for (let __val of _val) { if (__val instanceof Document) { __val = __val._id; } key = String(__val); if (rawDocs[key]) { if (Array.isArray(rawDocs[key])) { rawDocs[key].push(val); rawOrder[key].push(i); } else { rawDocs[key] = [rawDocs[key], val]; rawOrder[key] = [rawOrder[key], i]; } } else { if (isVirtual && !justOne) { rawDocs[key] = [val]; rawOrder[key] = [i]; } else { rawDocs[key] = val; rawOrder[key] = i; } } } } else { if (_val instanceof Document) { _val = _val._id; } key = String(_val); if (rawDocs[key]) { if (Array.isArray(rawDocs[key])) { rawDocs[key].push(val); rawOrder[key].push(i); } else { rawDocs[key] = [rawDocs[key], val]; rawOrder[key] = [rawOrder[key], i]; } } else { rawDocs[key] = val; rawOrder[key] = i; } } // flag each as result of population if (lean) { leanPopulateMap.set(val, mod.model); } else { val.$__.wasPopulated = true; } // gh-8460: if user used `-foreignField`, assume this means they // want the foreign field unset even if it isn't excluded in the query. if (projection != null && projection.hasOwnProperty('-' + foreignField)) { if (val.$__ != null) { val.set(foreignField, void 0); } else { mpath.unset(foreignField, val); } } } } assignVals({ originalModel: model, // If virtual, make sure to not mutate original field rawIds: mod.isVirtual ? allIds : mod.allIds, allIds: allIds, foreignField: mod.foreignField, rawDocs: rawDocs, rawOrder: rawOrder, docs: mod.docs, path: options.path, options: assignmentOpts, justOne: mod.justOne, isVirtual: mod.isVirtual, allOptions: mod, lean: lean, virtual: mod.virtual, count: mod.count, match: mod.match }); } /*! * Optionally filter out invalid ids that don't conform to foreign field's schema * to avoid cast errors (gh-7706) */ function _filterInvalidIds(ids, foreignSchemaType, skipInvalidIds) { ids = ids.filter(v => !(v instanceof SkipPopulateValue)); if (!skipInvalidIds) { return ids; } return ids.filter(id => { try { foreignSchemaType.cast(id); return true; } catch (err) { return false; } }); } /*! * Format `mod.match` given that it may be an array that we need to $or if * the client has multiple docs with match functions */ function _formatMatch(match) { if (Array.isArray(match)) { if (match.length > 1) { return { $or: [].concat(match.map(m => Object.assign({}, m))) }; } return Object.assign({}, match[0]); } return Object.assign({}, match); } /*! * Compiler utility. * * @param {String|Function} name model name or class extending Model * @param {Schema} schema * @param {String} collectionName * @param {Connection} connection * @param {Mongoose} base mongoose instance */ Model.compile = function compile(name, schema, collectionName, connection, base) { const versioningEnabled = schema.options.versionKey !== false; if (versioningEnabled && !schema.paths[schema.options.versionKey]) { // add versioning to top level documents only const o = {}; o[schema.options.versionKey] = Number; schema.add(o); } let model; if (typeof name === 'function' && name.prototype instanceof Model) { model = name; name = model.name; schema.loadClass(model, false); model.prototype.$isMongooseModelPrototype = true; } else { // generate new class model = function model(doc, fields, skipId) { model.hooks.execPreSync('createModel', doc); if (!(this instanceof model)) { return new model(doc, fields, skipId); } const discriminatorKey = model.schema.options.discriminatorKey; if (model.discriminators == null || doc == null || doc[discriminatorKey] == null) { Model.call(this, doc, fields, skipId); return; } // If discriminator key is set, use the discriminator instead (gh-7586) const Discriminator = model.discriminators[doc[discriminatorKey]] || getDiscriminatorByValue(model, doc[discriminatorKey]); if (Discriminator != null) { return new Discriminator(doc, fields, skipId); } // Otherwise, just use the top-level model Model.call(this, doc, fields, skipId); }; } model.hooks = schema.s.hooks.clone(); model.base = base; model.modelName = name; if (!(model.prototype instanceof Model)) { model.__proto__ = Model; model.prototype.__proto__ = Model.prototype; } model.model = function model(name) { return this.db.model(name); }; model.db = connection; model.prototype.db = connection; model.prototype[modelDbSymbol] = connection; model.discriminators = model.prototype.discriminators = undefined; model[modelSymbol] = true; model.events = new EventEmitter(); model.prototype.$__setSchema(schema); const _userProvidedOptions = schema._userProvidedOptions || {}; // `bufferCommands` is true by default... let bufferCommands = true; // First, take the global option if (connection.base.get('bufferCommands') != null) { bufferCommands = connection.base.get('bufferCommands'); } // Connection-specific overrides the global option if (connection.config.bufferCommands != null) { bufferCommands = connection.config.bufferCommands; } // And schema options override global and connection if (_userProvidedOptions.bufferCommands != null) { bufferCommands = _userProvidedOptions.bufferCommands; } const collectionOptions = { bufferCommands: bufferCommands, capped: schema.options.capped, autoCreate: schema.options.autoCreate, Promise: model.base.Promise }; model.prototype.collection = connection.collection( collectionName, collectionOptions ); model.prototype[modelCollectionSymbol] = model.prototype.collection; // apply methods and statics applyMethods(model, schema); applyStatics(model, schema); applyHooks(model, schema); applyStaticHooks(model, schema.s.hooks, schema.statics); model.schema = model.prototype.schema; model.collection = model.prototype.collection; // Create custom query constructor model.Query = function() { Query.apply(this, arguments); }; model.Query.prototype = Object.create(Query.prototype); model.Query.base = Query.base; applyQueryMiddleware(model.Query, model); applyQueryMethods(model, schema.query); return model; }; /*! * Register custom query methods for this model * * @param {Model} model * @param {Schema} schema */ function applyQueryMethods(model, methods) { for (const i in methods) { model.Query.prototype[i] = methods[i]; } } /*! * Subclass this model with `conn`, `schema`, and `collection` settings. * * @param {Connection} conn * @param {Schema} [schema] * @param {String} [collection] * @return {Model} */ Model.__subclass = function subclass(conn, schema, collection) { // subclass model using this connection and collection name const _this = this; const Model = function Model(doc, fields, skipId) { if (!(this instanceof Model)) { return new Model(doc, fields, skipId); } _this.call(this, doc, fields, skipId); }; Model.__proto__ = _this; Model.prototype.__proto__ = _this.prototype; Model.db = conn; Model.prototype.db = conn; Model.prototype[modelDbSymbol] = conn; _this[subclassedSymbol] = _this[subclassedSymbol] || []; _this[subclassedSymbol].push(Model); if (_this.discriminators != null) { Model.discriminators = {}; for (const key of Object.keys(_this.discriminators)) { Model.discriminators[key] = _this.discriminators[key]. __subclass(_this.db, _this.discriminators[key].schema, collection); } } const s = schema && typeof schema !== 'string' ? schema : _this.prototype.schema; const options = s.options || {}; const _userProvidedOptions = s._userProvidedOptions || {}; if (!collection) { collection = _this.prototype.schema.get('collection') || utils.toCollectionName(_this.modelName, this.base.pluralize()); } let bufferCommands = true; if (s) { if (conn.config.bufferCommands != null) { bufferCommands = conn.config.bufferCommands; } if (_userProvidedOptions.bufferCommands != null) { bufferCommands = _userProvidedOptions.bufferCommands; } } const collectionOptions = { bufferCommands: bufferCommands, capped: s && options.capped }; Model.prototype.collection = conn.collection(collection, collectionOptions); Model.prototype[modelCollectionSymbol] = Model.prototype.collection; Model.collection = Model.prototype.collection; // Errors handled internally, so ignore Model.init(() => {}); return Model; }; Model.$handleCallbackError = function(callback) { if (callback == null) { return callback; } if (typeof callback !== 'function') { throw new MongooseError('Callback must be a function, got ' + callback); } const _this = this; return function() { try { callback.apply(null, arguments); } catch (error) { _this.emit('error', error); } }; }; /*! * ignore */ Model.$wrapCallback = function(callback) { const serverSelectionError = new ServerSelectionError(); const _this = this; return function(err) { if (err != null && err.name === 'MongoServerSelectionError') { arguments[0] = serverSelectionError.assimilateError(err); } if (err != null && err.name === 'MongoNetworkError' && err.message.endsWith('timed out')) { _this.db.emit('timeout'); } return callback.apply(null, arguments); }; }; /** * Helper for console.log. Given a model named 'MyModel', returns the string * `'Model { MyModel }'`. * * ####Example: * * const MyModel = mongoose.model('Test', Schema({ name: String })); * MyModel.inspect(); // 'Model { Test }' * console.log(MyModel); // Prints 'Model { Test }' * * @api public */ Model.inspect = function() { return `Model { ${this.modelName} }`; }; if (util.inspect.custom) { /*! * Avoid Node deprecation warning DEP0079 */ Model[util.inspect.custom] = Model.inspect; } /*! * Module exports. */ module.exports = exports = Model;
1
14,260
You mistakenly removed `/docs` here, please add it
Automattic-mongoose
js
@@ -48,8 +48,9 @@ public interface FileAppender<D> extends Closeable { long length(); /** - * @return a list of offsets for file blocks if applicable, null otherwise. When available, this + * @return a list of offsets for file blocks, if applicable, null otherwise. When available, this * information is used for planning scan tasks whose boundaries are determined by these offsets. + * It is important that the returned list is sorted in ascending order. * Only valid after the file is closed. */ default List<Long> splitOffsets() {
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.io; import java.io.Closeable; import java.util.Iterator; import java.util.List; import org.apache.iceberg.Metrics; public interface FileAppender<D> extends Closeable { void add(D datum); default void addAll(Iterator<D> values) { while (values.hasNext()) { add(values.next()); } } default void addAll(Iterable<D> values) { addAll(values.iterator()); } /** * @return {@link Metrics} for this file. Only valid after the file is closed. */ Metrics metrics(); /** * @return the length of this file. Only valid after the file is closed. */ long length(); /** * @return a list of offsets for file blocks if applicable, null otherwise. When available, this * information is used for planning scan tasks whose boundaries are determined by these offsets. * Only valid after the file is closed. */ default List<Long> splitOffsets() { return null; } }
1
13,464
I missed this earlier, but why does this say "file blocks"? This should probably be "recommended split locations".
apache-iceberg
java
@@ -33,10 +33,10 @@ import ( // AlertsServer implements api.OpenStorageAlertsServer. // In order to use this server implementation just have // AlertsServer pointer properly instantiated with a valid -// alerts.Reader. +// alerts.FilterDeleter. type AlertsServer struct { - // Reader holds pointer to alerts Reader - Reader alerts.Reader + // FilterDeleter holds pointer to alerts FilterDeleter + FilterDeleter alerts.FilterDeleter } func getOpts(opts []*api.SdkAlertsOption) []alerts.Option {
1
/* Package sdk is the gRPC implementation of the SDK gRPC server 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 sdk import ( "context" "sync" "time" "github.com/libopenstorage/openstorage/alerts" "github.com/libopenstorage/openstorage/api" "github.com/libopenstorage/openstorage/pkg/proto/time" "golang.org/x/sync/errgroup" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) // AlertsServer implements api.OpenStorageAlertsServer. // In order to use this server implementation just have // AlertsServer pointer properly instantiated with a valid // alerts.Reader. type AlertsServer struct { // Reader holds pointer to alerts Reader Reader alerts.Reader } func getOpts(opts []*api.SdkAlertsOption) []alerts.Option { var options []alerts.Option for _, opt := range opts { switch opt.GetOpt().(type) { case *api.SdkAlertsOption_MinSeverityType: options = append(options, alerts.NewMinSeverityOption(opt.GetMinSeverityType())) case *api.SdkAlertsOption_IsCleared: options = append(options, alerts.NewFlagCheckOption(opt.GetIsCleared())) case *api.SdkAlertsOption_TimeSpan: options = append(options, alerts.NewTimeSpanOption( prototime.TimestampToTime(opt.GetTimeSpan().GetStartTime()), prototime.TimestampToTime(opt.GetTimeSpan().GetEndTime()))) case *api.SdkAlertsOption_CountSpan: options = append(options, alerts.NewCountSpanOption( opt.GetCountSpan().GetMinCount(), opt.GetCountSpan().GetMaxCount())) } } return options } func getFilters(queries []*api.SdkAlertsQuery) []alerts.Filter { var filters []alerts.Filter // range over all queries for _, x := range queries { switch x.GetQuery().(type) { case *api.SdkAlertsQuery_ResourceTypeQuery: q := x.GetResourceTypeQuery() filters = append(filters, alerts.NewResourceTypeFilter( q.ResourceType, getOpts(x.GetOpts())...)) case *api.SdkAlertsQuery_AlertTypeQuery: q := x.GetAlertTypeQuery() filters = append(filters, alerts.NewAlertTypeFilter( q.AlertType, q.ResourceType, getOpts(x.GetOpts())...)) case *api.SdkAlertsQuery_ResourceIdQuery: q := x.GetResourceIdQuery() filters = append(filters, alerts.NewResourceIDFilter( q.ResourceId, q.AlertType, q.ResourceType, getOpts(x.GetOpts())...)) } } return filters } // Enumerate implements api.OpenStorageAlertsServer for AlertsServer. // Input context should ideally have a deadline, in which case, a // graceful exit is ensured within that deadline. func (g *AlertsServer) Enumerate(ctx context.Context, request *api.SdkAlertsEnumerateRequest) (*api.SdkAlertsEnumerateResponse, error) { // if input has deadline, ensure graceful exit within that deadline. deadline, ok := ctx.Deadline() var cancel context.CancelFunc if ok { // create a new context that will get done on deadline ctx, cancel = context.WithTimeout(ctx, deadline.Sub(time.Now())) defer cancel() } group, _ := errgroup.WithContext(ctx) errChan := make(chan error) resp := new(api.SdkAlertsEnumerateResponse) var mu sync.Mutex queries := request.GetQueries() if queries == nil { return nil, status.Error(codes.InvalidArgument, "must provide a query") } filters := getFilters(queries) // spawn err-group process. // collect output using mutex. group.Go(func() error { if out, err := g.Reader.Enumerate(filters...); err != nil { return err } else { mu.Lock() resp.Alerts = append(resp.Alerts, out...) mu.Unlock() return nil } }) // wait for err-group processes to be done go func() { errChan <- group.Wait() }() // wait only as long as context deadline allows select { case err := <-errChan: if err != nil { return nil, status.Error(codes.Internal, err.Error()) } else { return resp, nil } case <-ctx.Done(): return nil, status.Error(codes.DeadlineExceeded, "deadline is reached, server side func exiting") } }
1
7,387
Please change this to non-exported.
libopenstorage-openstorage
go
@@ -4649,10 +4649,7 @@ stats_get_snapshot(dr_stats_t *drstats) if (!GLOBAL_STATS_ON()) return false; CLIENT_ASSERT(drstats != NULL, "Expected non-null value for parameter drstats."); - /* We are at V1 of the structure, and we can't return less than the one - * field. We need to remove this assert when we add more fields. - */ - CLIENT_ASSERT(drstats->size >= sizeof(dr_stats_t), "Invalid drstats->size value."); drstats->basic_block_count = GLOBAL_STAT(num_bbs); + drstats->peak_num_threads = GLOBAL_STAT(peak_num_threads); return true; }
1
/* ********************************************************** * Copyright (c) 2017 ARM Limited. All rights reserved. * Copyright (c) 2010-2017 Google, Inc. All rights reserved. * Copyright (c) 2000-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. */ /* Copyright (c) 2003-2007 Determina Corp. */ /* Copyright (c) 2001-2003 Massachusetts Institute of Technology */ /* Copyright (c) 2000-2001 Hewlett-Packard Company */ /* * utils.c - miscellaneous utilities */ #include "globals.h" #include "configure_defines.h" #include "utils.h" #include "module_shared.h" #include <string.h> /* for memset */ #include <math.h> #ifdef PROCESS_CONTROL # include "moduledb.h" /* for process control macros */ #endif #ifdef UNIX # include <sys/types.h> # include <sys/stat.h> # include <fcntl.h> # include <stdio.h> # include <stdlib.h> # include <unistd.h> # include <errno.h> #else # include <errno.h> /* FIXME : remove when syslog macros fixed */ # include "events.h" #endif #ifdef SHARING_STUDY # include "fragment.h" /* print_shared_stats */ #endif #ifdef DEBUG # include "fcache.h" # include "synch.h" /* all_threads_synch_lock */ #endif #include <stdarg.h> /* for varargs */ try_except_t global_try_except; int do_once_generation = 1; #ifdef SIDELINE extern void sideline_exit(void); #endif /* use for soft errors that can handle some cleanup: assertions and apichecks * performs some cleanup and then calls os_terminate */ static void soft_terminate() { #ifdef SIDELINE /* kill child threads */ if (dynamo_options.sideline) { sideline_stop(); sideline_exit(); } #endif /* set exited status for shared memory watchers, other threads */ DOSTATS({ if (stats != NULL) GLOBAL_STAT(exited) = true; }); /* do not try to clean up */ os_terminate(NULL, TERMINATE_PROCESS); } #if defined(INTERNAL) || defined(DEBUG) /* checks whether an assert statement should be ignored, * produces a warning if so and returns true, * otherwise returns false */ bool ignore_assert(const char *assert_stmt, const char *expr) { bool ignore = false; if (!IS_STRING_OPTION_EMPTY(ignore_assert_list)) { string_option_read_lock(); ignore = check_filter(DYNAMO_OPTION(ignore_assert_list), assert_stmt); string_option_read_unlock(); } if (IS_LISTSTRING_OPTION_FORALL(ignore_assert_list)) { ignore = true; } if (ignore) { /* FIXME: could have passed message around */ SYSLOG_INTERNAL_WARNING("Ignoring assert %s %s", assert_stmt, expr); } return ignore; } /* Hand-made DO_ONCE used in internal_error b/c ifdefs in * report_dynamorio_problem prevent DO_ONCE itself */ DECLARE_FREQPROT_VAR(static bool do_once_internal_error, false); /* abort on internal dynamo error */ void internal_error(const char *file, int line, const char *expr) { /* note that we no longer obfuscate filenames in non-internal builds * xref PR 303817 */ /* need to produce a SYSLOG Ignore Error here and return right away */ /* to avoid adding another ?: in the ASSERT messsage * we'll reconstruct file and line # here */ if (!IS_STRING_OPTION_EMPTY(ignore_assert_list)) { char assert_stmt[MAXIMUM_PATH]; /* max unique identifier */ /* note the ignore checks are done with a possible recursive * infinte loop if any asserts fail. Not very safe to set and * unset a static bool either since we'll be noisy. */ /* Assert identifiers should be an exact match of message * after Internal Error. Most common look like 'arch/arch.c:142', * but could also look like 'Not implemented @arch/arch.c:142' * or 'Bug #4809 @arch/arch.c:145;Ignore message * @arch/arch.c:146' */ snprintf(assert_stmt, BUFFER_SIZE_ELEMENTS(assert_stmt), "%s:%d", file, line); NULL_TERMINATE_BUFFER(assert_stmt); ASSERT_CURIOSITY((strlen(assert_stmt) + 1) != BUFFER_SIZE_ELEMENTS(assert_stmt)); if (ignore_assert(assert_stmt, expr)) return; /* we can ignore multiple asserts without triggering the do_once */ } if (do_once_internal_error) /* recursing, bail out */ return; else do_once_internal_error = true; report_dynamorio_problem(NULL, DUMPCORE_ASSERTION, NULL, NULL, #ifdef CLIENT_INTERFACE PRODUCT_NAME" debug check failure: %s:%d %s" #else "Internal "PRODUCT_NAME" Error: %s:%d %s" #endif #if defined(DEBUG) && defined(INTERNAL) "\n(Error occurred @%d frags)" #endif , file, line, expr #if defined(DEBUG) && defined(INTERNAL) , stats == NULL ? -1 : GLOBAL_STAT(num_fragments) #endif ); soft_terminate(); } #endif /* defined(INTERNAL) || defined(DEBUG) */ /* abort on external application created error, i.e. apicheck */ void external_error(const char *file, int line, const char *msg) { DO_ONCE({ /* this syslog is before any core dump, unlike our other reports, but * not worth fixing */ SYSLOG(SYSLOG_ERROR, EXTERNAL_ERROR, 4, get_application_name(), get_application_pid(), PRODUCT_NAME, msg); report_dynamorio_problem(NULL, DUMPCORE_FATAL_USAGE_ERROR, NULL, NULL, "Usage error: %s (%s, line %d)", msg, file, line); }); soft_terminate(); } /****************************************************************************/ /* SYNCHRONIZATION */ #ifdef DEADLOCK_AVOIDANCE /* Keeps the head of a linked list of all mutexes currently held by a thread. We also require a LIFO lock unlock order to keep things simpler (and stricter). */ struct _thread_locks_t { mutex_t *last_lock; }; /* These two locks are never deleted, although innermost_lock is grabbed */ DECLARE_CXTSWPROT_VAR(mutex_t outermost_lock, INIT_LOCK_FREE(outermost_lock)); DECLARE_CXTSWPROT_VAR(mutex_t innermost_lock, INIT_LOCK_FREE(innermost_lock)); /* Case 8075: For selfprot we have no way to put a local-scope mutex into * .cspdata, and {add,remove}_process_lock need to write to the * do_threshold_mutex when managing adjacent entries in the lock list, so * we use a global lock instead. Could be a contention issue but it's only * DEADLOCK_AVOIDANCE builds and there are few uses of DO_THRESHOLD_SAFE. */ DECLARE_CXTSWPROT_VAR(mutex_t do_threshold_mutex, INIT_LOCK_FREE(do_threshold_mutex)); /* structure field dumper for both name and value, format with %*s%d */ #define DUMP_NONZERO(v,field) strlen(#field)+1, (v->field ? #field"=" : ""), v->field #ifdef MACOS # define DUMP_CONTENDED(v,field) \ strlen(#field)+1, (ksynch_var_initialized(&v->field) ? #field"=" : ""), v->field.sem #else # define DUMP_CONTENDED DUMP_NONZERO #endif /* common format string used for different log files and loglevels */ #define DUMP_LOCK_INFO_ARGS(depth, cur_lock, prev) \ "%d lock "PFX": name=%s\nrank=%d owner="TIDFMT" owning_dc="PFX" " \ "%*s"PIFX" prev="PFX"\n" \ "lock %*s%8d %*s%8d %*s%8d %*s%8d %*s%8d+2 %s\n", \ depth, cur_lock, cur_lock->name, cur_lock->rank, \ cur_lock->owner, cur_lock->owning_dcontext, \ DUMP_CONTENDED(cur_lock, contended_event), prev, \ DUMP_NONZERO(cur_lock, count_times_acquired), \ DUMP_NONZERO(cur_lock, count_times_contended), \ DUMP_NONZERO(cur_lock, count_times_spin_pause), \ DUMP_NONZERO(cur_lock, count_times_spin_only), \ DUMP_NONZERO(cur_lock, max_contended_requests), \ cur_lock->name #ifdef INTERNAL static void dump_mutex_callstack(mutex_t *lock) { /* from windbg proper command is * 0:001> dds @@(&lock->callstack) L4 */ #ifdef MUTEX_CALLSTACK uint i; if (INTERNAL_OPTION(mutex_callstack) == 0) return; LOG(GLOBAL, LOG_THREADS, 1, "dump_mutex_callstack %s\n", lock->name); for (i=0; i<INTERNAL_OPTION(mutex_callstack); i++) { /* some macro's call this function, so it is easier to ifdef * only references to callstack */ LOG(GLOBAL, LOG_THREADS, 1, " "PFX"\n", lock->callstack[i]); } #endif /* MUTEX_CALLSTACK */ } #endif void dump_owned_locks(dcontext_t *dcontext) { /* LIFO order even though order in releasing doesn't matter */ mutex_t *cur_lock; uint depth = 0; cur_lock = dcontext->thread_owned_locks->last_lock; LOG(THREAD, LOG_THREADS, 1, "Owned locks for thread "TIDFMT" dcontext="PFX"\n", dcontext->owning_thread, dcontext); while (cur_lock != &outermost_lock) { depth++; LOG(THREAD, LOG_THREADS, 1, DUMP_LOCK_INFO_ARGS(depth, cur_lock, cur_lock->prev_owned_lock)); ASSERT(cur_lock->owner == dcontext->owning_thread); cur_lock = cur_lock->prev_owned_lock; } } bool thread_owns_no_locks(dcontext_t *dcontext) { ASSERT(dcontext != NULL); if (!INTERNAL_OPTION(deadlock_avoidance)) return true; /* can't verify since we aren't keeping track of owned locks */ return (dcontext->thread_owned_locks->last_lock == &outermost_lock); } bool thread_owns_one_lock(dcontext_t *dcontext, mutex_t *lock) { mutex_t *cur_lock; ASSERT(dcontext != NULL); if (!INTERNAL_OPTION(deadlock_avoidance)) return true; /* can't verify since we aren't keeping track of owned locks */ cur_lock = dcontext->thread_owned_locks->last_lock; return (cur_lock == lock && cur_lock->prev_owned_lock == &outermost_lock); } /* Returns true if dcontext thread owns lock1 and lock2 and no other locks */ bool thread_owns_two_locks(dcontext_t *dcontext, mutex_t *lock1, mutex_t *lock2) { mutex_t *cur_lock; ASSERT(dcontext != NULL); if (!INTERNAL_OPTION(deadlock_avoidance)) return true; /* can't verify since we aren't keeping track of owned locks */ cur_lock = dcontext->thread_owned_locks->last_lock; return (cur_lock == lock1 && cur_lock->prev_owned_lock == lock2 && lock2->prev_owned_lock == &outermost_lock); } /* Returns true if dcontext thread owns lock1 and optionally lock2 * (acquired before lock1) and no other locks. */ bool thread_owns_first_or_both_locks_only(dcontext_t *dcontext, mutex_t *lock1, mutex_t *lock2) { mutex_t *cur_lock; ASSERT(dcontext != NULL); if (!INTERNAL_OPTION(deadlock_avoidance)) return true; /* can't verify since we aren't keeping track of owned locks */ cur_lock = dcontext->thread_owned_locks->last_lock; return (cur_lock == lock1 && (cur_lock->prev_owned_lock == &outermost_lock || (cur_lock->prev_owned_lock == lock2 && lock2->prev_owned_lock == &outermost_lock))); } /* dump process locks that have been acquired at least once */ /* FIXME: since most mutexes are global we don't have thread private lock lists */ void dump_process_locks() { mutex_t *cur_lock; uint depth = 0; uint total_acquired = 0; uint total_contended = 0; LOG(GLOBAL, LOG_STATS, 2, "Currently live process locks:\n"); /* global list access needs to be synchronized */ mutex_lock(&innermost_lock); cur_lock = &innermost_lock; do { depth++; LOG(GLOBAL, LOG_STATS, (cur_lock->count_times_contended ? 1U: 2U), /* elevate contended ones */ DUMP_LOCK_INFO_ARGS(depth, cur_lock, cur_lock->next_process_lock)); DOLOG((cur_lock->count_times_contended ? 2U: 3U), /* elevate contended ones */ LOG_THREADS, { /* last recorded callstack, not necessarily the most contended path */ dump_mutex_callstack(cur_lock); }); cur_lock = cur_lock->next_process_lock; total_acquired += cur_lock->count_times_acquired; total_contended += cur_lock->count_times_contended; ASSERT(cur_lock); ASSERT(cur_lock->next_process_lock->prev_process_lock == cur_lock); ASSERT(cur_lock->prev_process_lock->next_process_lock == cur_lock); ASSERT(cur_lock->prev_process_lock != cur_lock || cur_lock == &innermost_lock); ASSERT(cur_lock->next_process_lock != cur_lock || cur_lock == &innermost_lock); } while (cur_lock != &innermost_lock); mutex_unlock(&innermost_lock); LOG(GLOBAL, LOG_STATS, 1, "Currently live process locks: %d, acquired %d, contended %d (current only)\n", depth, total_acquired, total_contended); } uint locks_not_closed() { mutex_t *cur_lock; uint forgotten = 0; uint ignored = 0; /* Case 8075: we use a global do_threshold_mutex for DEADLOCK_AVOIDANCE. * Leaving the code for a local var here via this bool in case we run * this routine in release build while somehow avoiding the global lock. */ static const bool allow_do_threshold_leaks = false; /* we assume that we would have removed them from the process list in mutex_close */ /* locks assigned with do_threshold_mutex are 'leaked' because it * is too much hassle to find a good place to DELETE them -- though we * now use a global mutex for DEADLOCK_AVOIDANCE so that's not the case. */ mutex_lock(&innermost_lock); /* innermost will stay */ cur_lock = innermost_lock.next_process_lock; while (cur_lock != &innermost_lock) { if (allow_do_threshold_leaks && cur_lock->rank == LOCK_RANK(do_threshold_mutex)) { ignored++; } else if (cur_lock->deleted && (IF_WINDOWS(cur_lock->rank == LOCK_RANK(debugbox_lock) || cur_lock->rank == LOCK_RANK(dump_core_lock) ||) cur_lock->rank == LOCK_RANK(report_buf_lock) || cur_lock->rank == LOCK_RANK(datasec_selfprot_lock) || cur_lock->rank == LOCK_RANK(logdir_mutex) || cur_lock->rank == LOCK_RANK(options_lock))) { /* i#1058: curiosities during exit re-acquire these locks. */ ignored++; } else { LOG(GLOBAL, LOG_STATS, 1, "missing DELETE_LOCK on lock "PFX" %s\n", cur_lock, cur_lock->name); forgotten++; } cur_lock = cur_lock->next_process_lock; } mutex_unlock(&innermost_lock); LOG(GLOBAL, LOG_STATS, 3, "locks_not_closed= %d remaining, %d ignored\n", forgotten, ignored); return forgotten; } void locks_thread_init(dcontext_t *dcontext) { thread_locks_t *new_thread_locks; new_thread_locks = (thread_locks_t *) UNPROTECTED_GLOBAL_ALLOC(sizeof(thread_locks_t) HEAPACCT(ACCT_OTHER)); LOG(THREAD, LOG_STATS, 2, "thread_locks="PFX" size=%d\n", new_thread_locks, sizeof(thread_locks_t)); /* initialize any thread bookkeeping fields before assigning to dcontext */ new_thread_locks->last_lock = &outermost_lock; dcontext->thread_owned_locks = new_thread_locks; } void locks_thread_exit(dcontext_t *dcontext) { /* using global heap and always have to clean up */ if (dcontext->thread_owned_locks) { thread_locks_t *old_thread_locks = dcontext->thread_owned_locks; /* when exiting, another thread may be holding the lock instead of the current, CHECK: is this true for detaching */ ASSERT(dcontext->thread_owned_locks->last_lock == &thread_initexit_lock || dcontext->thread_owned_locks->last_lock == &outermost_lock /* PR 546016: sideline client thread might hold client lock */ IF_CLIENT_INTERFACE(|| dcontext->thread_owned_locks->last_lock->rank == dr_client_mutex_rank)); /* disable thread lock checks before freeing memory */ dcontext->thread_owned_locks = NULL; UNPROTECTED_GLOBAL_FREE(old_thread_locks, sizeof(thread_locks_t) HEAPACCT(ACCT_OTHER)); } } static void add_process_lock(mutex_t *lock) { /* add to global locks circular double linked list */ LOG(THREAD_GET, LOG_THREADS, 5, "add_process_lock" DUMP_LOCK_INFO_ARGS(0, lock, lock->prev_process_lock)); mutex_lock(&innermost_lock); if (lock->prev_process_lock != NULL) { /* race: someone already added (can only happen for read locks) */ LOG(THREAD_GET, LOG_THREADS, 2, "\talready added\n"); ASSERT(lock->next_process_lock != NULL); mutex_unlock(&innermost_lock); return; } ASSERT(lock->next_process_lock == NULL || lock == &innermost_lock); ASSERT(lock->prev_process_lock == NULL || lock == &innermost_lock); if (innermost_lock.prev_process_lock == NULL) { innermost_lock.next_process_lock = &innermost_lock; innermost_lock.prev_process_lock = &innermost_lock; } lock->next_process_lock = &innermost_lock; innermost_lock.prev_process_lock->next_process_lock = lock; lock->prev_process_lock = innermost_lock.prev_process_lock; innermost_lock.prev_process_lock = lock; ASSERT(lock->next_process_lock->prev_process_lock == lock); ASSERT(lock->prev_process_lock->next_process_lock == lock); ASSERT(lock->prev_process_lock != lock || lock == &innermost_lock); ASSERT(lock->next_process_lock != lock || lock == &innermost_lock); mutex_unlock(&innermost_lock); } static void remove_process_lock(mutex_t *lock) { LOG(THREAD_GET, LOG_THREADS, 3, "remove_process_lock " DUMP_LOCK_INFO_ARGS(0, lock, lock->prev_process_lock)); STATS_ADD(total_acquired, lock->count_times_acquired); STATS_ADD(total_contended, lock->count_times_contended); if (lock->count_times_acquired == 0) { ASSERT(lock->prev_process_lock == NULL); LOG(THREAD_GET, LOG_THREADS, 3, "\tnever acquired\n"); return; } ASSERT(lock->prev_process_lock && "if ever acquired should be on the list"); ASSERT(lock != &innermost_lock && "innermost will be 'leaked'"); /* remove from global locks list */ mutex_lock(&innermost_lock); /* innermost should always have both fields set here */ lock->next_process_lock->prev_process_lock = lock->prev_process_lock; lock->prev_process_lock->next_process_lock = lock->next_process_lock; lock->next_process_lock = NULL; lock->prev_process_lock = NULL; /* so we catch uses after closing */ mutex_unlock(&innermost_lock); } #ifdef MUTEX_CALLSTACK /* FIXME: generalize and merge w/ CALL_PROFILE? */ static void mutex_collect_callstack(mutex_t *lock) { uint max_depth = INTERNAL_OPTION(mutex_callstack); uint depth = 0; uint skip = 2; /* ignore calls from deadlock_avoidance() and mutex_lock() */ /* FIXME: write_lock could ignore one level further */ byte *fp; dcontext_t *dcontext = get_thread_private_dcontext(); GET_FRAME_PTR(fp); /* only interested in DR addresses which should all be readable */ while (depth < max_depth && (is_on_initstack(fp) || is_on_dstack(dcontext, fp)) && /* is_on_initstack() and is_on_dstack() do include the guard pages * yet we cannot afford to call is_readable_without_exception() */ !is_stack_overflow(dcontext, fp)) { app_pc our_ret = *((app_pc*)fp+1); fp = *(byte **)fp; if (skip) { skip--; continue; } lock->callstack[depth] = our_ret; depth++; } } #endif /* MUTEX_CALLSTACK */ enum {LOCK_NOT_OWNABLE, LOCK_OWNABLE}; /* if not acquired only update statistics, if not ownable (i.e. read lock) only check against previous locks, but don't add to thread owned list */ static void deadlock_avoidance_lock(mutex_t *lock, bool acquired, bool ownable) { if (acquired) { lock->count_times_acquired++; /* CHECK: everything here works without mutex_trylock's */ LOG(GLOBAL, LOG_THREADS, 6, "acquired lock "PFX" %s rank=%d, %s dcontext, tid:%d, %d time\n", lock, lock->name, lock->rank, get_thread_private_dcontext() ? "valid" : "not valid", get_thread_id(), lock->count_times_acquired ); LOG(THREAD_GET, LOG_THREADS, 6, "acquired lock "PFX" %s rank=%d\n", lock, lock->name, lock->rank); ASSERT(lock->rank > 0 && "initialize with INIT_LOCK_FREE"); if (ownable) { ASSERT(!lock->owner); lock->owner = get_thread_id(); lock->owning_dcontext = get_thread_private_dcontext(); } /* add to global list */ if (lock->prev_process_lock == NULL && lock != &innermost_lock) { add_process_lock(lock); } /* cannot hold thread_initexit_lock while couldbelinking, else will * deadlock with flushers */ ASSERT(lock != &thread_initexit_lock || !is_self_couldbelinking()); if (INTERNAL_OPTION(deadlock_avoidance) && get_thread_private_dcontext() != NULL) { dcontext_t *dcontext = get_thread_private_dcontext(); if (dcontext->thread_owned_locks != NULL) { #ifdef CLIENT_INTERFACE /* PR 198871: same label used for all client locks so allow same rank. * For now we ignore rank order when client lock is 1st, as well, * to support decode_trace() for 0.9.6 release PR 198871 covers safer * long-term fix. */ bool first_client = (dcontext->thread_owned_locks->last_lock->rank == dr_client_mutex_rank); bool both_client = (first_client && lock->rank == dr_client_mutex_rank); #endif if (dcontext->thread_owned_locks->last_lock->rank >= lock->rank IF_CLIENT_INTERFACE(&& !first_client/*FIXME PR 198871: remove */ && !both_client)) { /* like syslog don't synchronize options for dumpcore_mask */ if (TEST(DUMPCORE_DEADLOCK, DYNAMO_OPTION(dumpcore_mask))) os_dump_core("rank order violation"); /* report rank order violation */ SYSLOG_INTERNAL_NO_OPTION_SYNCH (SYSLOG_CRITICAL, "rank order violation %s acquired after %s in tid:%x", lock->name, dcontext->thread_owned_locks->last_lock->name, get_thread_id()); dump_owned_locks(dcontext); } ASSERT((dcontext->thread_owned_locks->last_lock->rank < lock->rank IF_CLIENT_INTERFACE(|| first_client/*FIXME PR 198871: remove */ || both_client)) && "rank order violation"); if (ownable) { lock->prev_owned_lock = dcontext->thread_owned_locks->last_lock; dcontext->thread_owned_locks->last_lock = lock; } DOLOG(6, LOG_THREADS, { dump_owned_locks(dcontext); }); } } if (INTERNAL_OPTION(mutex_callstack) != 0 && ownable && get_thread_private_dcontext() != NULL) { #ifdef MUTEX_CALLSTACK mutex_collect_callstack(lock); #endif } } else { /* NOTE check_wait_at_safe_spot makes the assumption that no system * calls are made on the non acquired path here */ ASSERT(lock->rank > 0 && "initialize with INIT_LOCK_FREE"); if (INTERNAL_OPTION(deadlock_avoidance) && ownable) { ASSERT(lock->owner != get_thread_id() && "deadlock on recursive mutex_lock"); } lock->count_times_contended++; } } /* FIXME: exported only for the linux hack -- make static once that's fixed */ void deadlock_avoidance_unlock(mutex_t *lock, bool ownable) { if (INTERNAL_OPTION(simulate_contention)) { /* with higher chances another thread will have to wait */ os_thread_yield(); } LOG(GLOBAL, LOG_THREADS, 6, "released lock "PFX" %s rank=%d, %s dcontext, tid:%d \n", lock, lock->name, lock->rank, get_thread_private_dcontext() ? "valid" : "not valid", get_thread_id()); LOG(THREAD_GET, LOG_THREADS, 6, "released lock "PFX" %s rank=%d\n", lock, lock->name, lock->rank); if (!ownable) return; ASSERT(lock->owner == get_thread_id()); if (INTERNAL_OPTION(deadlock_avoidance) && lock->owning_dcontext != NULL && lock->owning_dcontext != GLOBAL_DCONTEXT) { dcontext_t *dcontext = get_thread_private_dcontext(); if (dcontext == NULL) { #ifdef DEBUG /* thread_initexit_lock and all_threads_synch_lock * are unlocked after tearing down thread structures */ # if defined(UNIX) && !defined(HAVE_TLS) extern mutex_t tls_lock; # endif bool null_ok = (lock == &thread_initexit_lock || lock == &all_threads_synch_lock # if defined(UNIX) && !defined(HAVE_TLS) || lock == &tls_lock # endif ); ASSERT(null_ok); #endif } else { ASSERT(lock->owning_dcontext == dcontext); if (dcontext->thread_owned_locks != NULL) { DOLOG(6, LOG_THREADS, { dump_owned_locks(dcontext); }); /* LIFO order even though order in releasing doesn't matter */ ASSERT(dcontext->thread_owned_locks->last_lock == lock); dcontext->thread_owned_locks->last_lock = lock->prev_owned_lock; lock->prev_owned_lock = NULL; } } } lock->owner = INVALID_THREAD_ID; lock->owning_dcontext = NULL; } #define DEADLOCK_AVOIDANCE_LOCK(lock, acquired, ownable) \ deadlock_avoidance_lock(lock, acquired, ownable) #define DEADLOCK_AVOIDANCE_UNLOCK(lock, ownable) deadlock_avoidance_unlock(lock, ownable) #else # define DEADLOCK_AVOIDANCE_LOCK(lock, acquired, ownable) /* do nothing */ # define DEADLOCK_AVOIDANCE_UNLOCK(lock, ownable) /* do nothing */ #endif /* DEADLOCK_AVOIDANCE */ #ifdef UNIX void mutex_fork_reset(mutex_t *mutex) { /* i#239/PR 498752: need to free locks held by other threads at fork time. * We can't call ASSIGN_INIT_LOCK_FREE as that clobbers any contention event * (=> leak) and the debug-build lock lists (=> asserts like PR 504594). * If the synch before fork succeeded, this is unecessary. If we encounter * more deadlocks after fork because of synch failure, we can add more calls * to reset locks on a case by case basis. */ mutex->lock_requests = LOCK_FREE_STATE; # ifdef DEADLOCK_AVOIDANCE mutex->owner = INVALID_THREAD_ID; mutex->owning_dcontext = NULL; # endif } #endif static uint spinlock_count = 0; /* initialized in utils_init, but 0 is always safe */ DECLARE_FREQPROT_VAR(static uint random_seed, 1234); /* initialized in utils_init */ DEBUG_DECLARE(static uint initial_random_seed;) void utils_init() { /* FIXME: We need to find a formula (or a better constant) based on real experiments also see comment on spinlock_count_on_SMP in optionsx.h */ /* we want to make sure it is 0 on UP, the rest is speculation */ spinlock_count = (get_num_processors() - 1) * DYNAMO_OPTION(spinlock_count_on_SMP); /* allow reproducing PRNG sequence * (of course, thread scheduling may still affect requests) */ random_seed = (DYNAMO_OPTION(prng_seed) == 0) ? os_random_seed() : DYNAMO_OPTION(prng_seed); /* logged only at end, preserved so can be looked up in a dump */ DODEBUG(initial_random_seed = random_seed;); /* sanity check since we cast back and forth */ ASSERT(sizeof(spin_mutex_t) == sizeof(mutex_t)); ASSERT(sizeof(uint64) == 8); ASSERT(sizeof(uint32) == 4); ASSERT(sizeof(uint) == 4); ASSERT(sizeof(reg_t) == sizeof(void *)); #ifdef UNIX /* after options_init(), before we open logfile or call instrument_init() */ os_file_init(); #endif set_exception_strings(NULL, NULL); /* use defaults */ } /* NOTE since used by spinmutex_lock_no_yield, can make no system calls before * the lock is grabbed (required by check_wait_at_safe_spot). */ bool spinmutex_trylock(spin_mutex_t *spin_lock) { mutex_t *lock = &spin_lock->lock; int mutexval; mutexval = atomic_swap(&lock->lock_requests, LOCK_SET_STATE); ASSERT(mutexval == LOCK_FREE_STATE || mutexval == LOCK_SET_STATE); DEADLOCK_AVOIDANCE_LOCK(lock, mutexval == LOCK_FREE_STATE, LOCK_OWNABLE); return (mutexval == LOCK_FREE_STATE); } void spinmutex_lock(spin_mutex_t *spin_lock) { /* busy-wait until mutex is locked */ while (!spinmutex_trylock(spin_lock)) { os_thread_yield(); } return; } /* special version of spinmutex_lock that makes no system calls (i.e. no yield) * as required by check_wait_at_safe_spot */ void spinmutex_lock_no_yield(spin_mutex_t *spin_lock) { /* busy-wait until mutex is locked */ while (!spinmutex_trylock(spin_lock)) { #ifdef DEADLOCK_AVOIDANCE mutex_t *lock = &spin_lock->lock; /* Trylock inc'ed count_times_contended, but since we are prob. going * to spin a lot, we'd rather attribute that to a separate counter * count_times_spin_pause to keep the counts meaningful. */ lock->count_times_contended--; lock->count_times_spin_pause++; #endif SPINLOCK_PAUSE(); } return; } void spinmutex_unlock(spin_mutex_t *spin_lock) { mutex_t *lock = &spin_lock->lock; /* if this fails, it means you don't already own the lock. */ ASSERT(lock->lock_requests > LOCK_FREE_STATE && "lock not owned"); ASSERT(lock->lock_requests == LOCK_SET_STATE); DEADLOCK_AVOIDANCE_UNLOCK(lock, LOCK_OWNABLE); lock->lock_requests = LOCK_FREE_STATE; /* NOTE - check_wait_at_safe_spot requires that no system calls be made * after we release the lock */ return; } void spinmutex_delete(spin_mutex_t *spin_lock) { ASSERT(!ksynch_var_initialized(&spin_lock->lock.contended_event)); mutex_delete(&spin_lock->lock); } #ifdef DEADLOCK_AVOIDANCE static bool mutex_ownable(mutex_t *lock) { bool ownable = LOCK_OWNABLE; # ifdef CLIENT_INTERFACE /* i#779: support DR locks used as app locks */ if (lock->app_lock) { ASSERT(lock->rank == dr_client_mutex_rank); ownable = LOCK_NOT_OWNABLE; } # endif return ownable; } #endif void mutex_lock_app(mutex_t *lock _IF_CLIENT_INTERFACE(priv_mcontext_t *mc)) { bool acquired; #ifdef DEADLOCK_AVOIDANCE bool ownable = mutex_ownable(lock); #endif /* we may want to first spin the lock for a while if we are on a multiprocessor * machine */ /* option is external only so that we can set it to 0 on a uniprocessor */ if (spinlock_count) { uint i; /* in the common case we'll just get it */ if (mutex_trylock(lock)) return; /* otherwise contended, we should spin for some time */ i = spinlock_count; /* while spinning we are PAUSEing and reading without LOCKing the bus in the * spin loop */ do { /* hint we are spinning */ SPINLOCK_PAUSE(); /* We spin only while lock_requests == 0 which means that exactly one thread holds the lock, while the current one (and possibly a few others) are contending on who will grab it next. It doesn't make much sense to spin when the lock->lock_requests > 0 (which means that at least one thread is already blocked). And of course, we also break if it is LOCK_FREE_STATE. */ if (lock->lock_requests != LOCK_SET_STATE) { # ifdef DEADLOCK_AVOIDANCE lock->count_times_spin_only++; # endif break; } i--; } while (i>0); } /* we have strong intentions to grab this lock, increment requests */ acquired = atomic_inc_and_test(&lock->lock_requests); DEADLOCK_AVOIDANCE_LOCK(lock, acquired, ownable); if (!acquired) { mutex_wait_contended_lock(lock _IF_CLIENT_INTERFACE(mc)); # ifdef DEADLOCK_AVOIDANCE DEADLOCK_AVOIDANCE_LOCK(lock, true, ownable); /* now we got it */ /* this and previous owner are not included in lock_requests */ if (lock->max_contended_requests < (uint)lock->lock_requests) lock->max_contended_requests = (uint)lock->lock_requests; # endif } } void mutex_lock(mutex_t *lock) { mutex_lock_app(lock _IF_CLIENT_INTERFACE(NULL)); } /* try once to grab the lock, return whether or not successful */ bool mutex_trylock(mutex_t *lock) { bool acquired; #ifdef DEADLOCK_AVOIDANCE bool ownable = mutex_ownable(lock); #endif /* preserve old value in case not LOCK_FREE_STATE */ acquired = atomic_compare_exchange(&lock->lock_requests, LOCK_FREE_STATE, LOCK_SET_STATE); /* if old value was free, that means we just obtained lock old value may be >=0 when several threads are trying to acquire lock, so we should return false */ DEADLOCK_AVOIDANCE_LOCK(lock, acquired, ownable); return acquired; } /* free the lock */ void mutex_unlock(mutex_t *lock) { #ifdef DEADLOCK_AVOIDANCE bool ownable = mutex_ownable(lock); #endif ASSERT(lock->lock_requests > LOCK_FREE_STATE && "lock not owned"); DEADLOCK_AVOIDANCE_UNLOCK(lock, ownable); if (atomic_dec_and_test(&lock->lock_requests)) return; /* if we were not the last one to hold the lock, (i.e. final value is not LOCK_FREE_STATE) we need to notify another waiting thread */ mutex_notify_released_lock(lock); } /* releases any associated kernel objects */ void mutex_delete(mutex_t *lock) { LOG(GLOBAL, LOG_THREADS, 3, "mutex_delete lock "PFX"\n", lock); /* When doing detach, application locks may be held on threads which have * already been interrupted and will never execute lock code again. Just * ignore the assert on the lock_requests field below in those cases. */ DEBUG_DECLARE(bool skip_lock_request_assert = false;) #ifdef DEADLOCK_AVOIDANCE LOG(THREAD_GET, LOG_THREADS, 3, "mutex_delete " DUMP_LOCK_INFO_ARGS(0, lock, lock->prev_process_lock)); remove_process_lock(lock); lock->deleted = true; if (doing_detach) { /* For possible re-attach we clear the acquired count. We leave * deleted==true as it is not used much and we don't have a simple method for * clearing it: we'd have to keep a special list of all locks used (appending * as they're deleted) and then walk it from dynamo_exit_post_detach(). */ lock->count_times_acquired = 0; # if defined(CLIENT_INTERFACE) && defined(DEBUG) skip_lock_request_assert = lock->app_lock; # endif /* CLIENT_INTERFACE && DEBUG */ } #else # ifdef DEBUG /* We don't support !DEADLOCK_AVOIDANCE && DEBUG: we need to know whether to * skip the assert lock_requests but don't know if this lock is an app lock */ # error DEBUG mode not supported without DEADLOCK_AVOIDANCE # endif /* DEBUG */ #endif /* DEADLOCK_AVOIDANCE */ ASSERT(skip_lock_request_assert || lock->lock_requests == LOCK_FREE_STATE); if (ksynch_var_initialized(&lock->contended_event)) { mutex_free_contended_event(lock); } } #ifdef CLIENT_INTERFACE void mutex_mark_as_app(mutex_t *lock) { # ifdef DEADLOCK_AVOIDANCE lock->app_lock = true; # endif } #endif static inline void own_recursive_lock(recursive_lock_t *lock) { ASSERT(lock->owner == INVALID_THREAD_ID); ASSERT(lock->count == 0); lock->owner = get_thread_id(); ASSERT(lock->owner != INVALID_THREAD_ID); lock->count = 1; } void acquire_recursive_app_lock(recursive_lock_t *lock _IF_CLIENT_INTERFACE(priv_mcontext_t *mc)) { /* we no longer use the pattern of implementing acquire_lock as a busy try_lock */ /* ASSUMPTION: reading owner field is atomic */ if (lock->owner == get_thread_id()) { lock->count++; } else { mutex_lock_app(&lock->lock _IF_CLIENT_INTERFACE(mc)); own_recursive_lock(lock); } } /* FIXME: rename recursive routines to parallel mutex_ routines */ void acquire_recursive_lock(recursive_lock_t *lock) { acquire_recursive_app_lock(lock _IF_CLIENT_INTERFACE(NULL)); } bool try_recursive_lock(recursive_lock_t *lock) { /* ASSUMPTION: reading owner field is atomic */ if (lock->owner == get_thread_id()) { lock->count++; } else { if (!mutex_trylock(&lock->lock)) return false; own_recursive_lock(lock); } return true; } void release_recursive_lock(recursive_lock_t *lock) { ASSERT(lock->owner == get_thread_id()); ASSERT(lock->count > 0); lock->count--; if (lock->count == 0) { lock->owner = INVALID_THREAD_ID; mutex_unlock(&lock->lock); } } bool self_owns_recursive_lock(recursive_lock_t *lock) { /* ASSUMPTION: reading owner field is atomic */ return (lock->owner == get_thread_id()); } /* Read write locks */ /* A read write lock allows multiple readers or alternatively a single writer */ /* We're keeping here an older implementation under INTERNAL_OPTION(spin_yield_rwlock) that spins on the contention path. In the Attic we also have the initial naive implementation wrapping mutex_t'es !INTERNAL_OPTION(fast_rwlock). */ /* FIXME: Since we are using multiple words to contain the state, we still have to keep looping on contention events. We need to switch to using a single variable for this but for now let's first put all pieces of the kernel objects support together. PLAN: All state should be in one 32bit word. Then we need one atomic operation that decrements readers and tells us: 1) whether there was a writer (e.g. MSB set) 2) whether this was the last reader (e.g. 0 in all other bits) Only when 1) & 2) are true (e.g. 0x80000000) we need to notify the writer. Think about using XADD: atomic_add_exchange(state, -1) */ /* FIXME: See /usr/src/linux-2.4/include/asm-i386/rwlock.h, spinlock.h and /usr/src/linux-2.4/arch/i386/kernel/semaphore.c for the Linux kernel implementation on x86. */ /* Currently we are using kernel objects to block on contention paths. Writers are blocked from each other at the mutex_t, and are notified by previous readers by an auto event. Readers, of course, can have the lock simultaneously, but block on a previous writer - note also on an auto event. Broadcasting to all readers is done by explicitly waking up each by the previous one, while the writer continues execution. There is no fairness to the readers that are blocked vs any new readers that will grab the lock immediately, and for that matter vs any new writers. FIXME: Keep in mind that a successful wait on the kernel events in read locks should not be used as a guarantee that the current thread can proceed with a granted request. We should rather keep looping to verify that we are back on the fast path. Due to the two reasons above we still have unbound loops in the rwlock primitives. It also lets the Linux implementation just yield. */ void read_lock(read_write_lock_t *rw) { /* wait for writer here if lock is held * FIXME: generalize DEADLOCK_AVOIDANCE to both detect * order violations and gather contention stats for * this mutex-less synch */ if (INTERNAL_OPTION(spin_yield_rwlock)) { do { while (mutex_testlock(&rw->lock)) { /* contended read */ /* am I the writer? * ASSUMPTION: reading field is atomic * For linux get_thread_id() is expensive -- we * should either address that through special handling * of native and new thread cases, or switch this * routine to pass in dcontext and use that. * Update: linux get_thread_id() now calls get_tls_thread_id() * and avoids the syscall (xref PR 473640). * FIXME: we could also reorganize this check so that it is done only once * instead of in the loop body but it doesn't seem wortwhile */ if (rw->writer == get_thread_id()) { /* we would share the code below but we do not want * the deadlock avoidance to consider this an acquire */ ATOMIC_INC(int, rw->num_readers); return; } DEADLOCK_AVOIDANCE_LOCK(&rw->lock, false, LOCK_NOT_OWNABLE); /* FIXME: last places where we yield instead of wait */ os_thread_yield(); } ATOMIC_INC(int, rw->num_readers); if (!mutex_testlock(&rw->lock)) break; /* else, race with writer, must try again */ ATOMIC_DEC(int, rw->num_readers); } while (true); DEADLOCK_AVOIDANCE_LOCK(&rw->lock, true, LOCK_NOT_OWNABLE); return; } /* event based notification, yet still need to loop */ do { while (mutex_testlock(&rw->lock)) { /* contended read */ /* am I the writer? * ASSUMPTION: reading field is atomic * For linux get_thread_id() is expensive -- we * should either address that through special handling * of native and new thread cases, or switch this * routine to pass in dcontext and use that. * Update: linux get_thread_id() now calls get_tls_thread_id() * and avoids the syscall (xref PR 473640). */ if (rw->writer == get_thread_id()) { /* we would share the code below but we do not want * the deadlock avoidance to consider this an acquire */ /* we also have to do this check on the read_unlock path */ ATOMIC_INC(int, rw->num_readers); return; } DEADLOCK_AVOIDANCE_LOCK(&rw->lock, false, LOCK_NOT_OWNABLE); ATOMIC_INC(int, rw->num_pending_readers); /* if we get interrupted before we have incremented this counter? Then no signal will be send our way, so we shouldn't be waiting then */ if (mutex_testlock(&rw->lock)) { /* still holding up */ rwlock_wait_contended_reader(rw); } else { /* otherwise race with writer */ /* after the write lock is released pending readers should no longer wait since no one will wake them up */ /* no need to pause */ } /* Even if we didn't wait another reader may be waiting for notification */ if (!atomic_dec_becomes_zero(&rw->num_pending_readers)) { /* If we were not the last pending reader, we need to notify another waiting one so that it can get out of the contention path. */ rwlock_notify_readers(rw); /* Keep in mind that here we don't guarantee that after blocking we have an automatic right to claim the lock. */ } } /* fast path */ ATOMIC_INC(int, rw->num_readers); if (!mutex_testlock(&rw->lock)) break; /* else, race with writer, must try again */ /* FIXME: need to get num_readers and the mutex in one place, or otherwise add a mutex grabbed by readers for the above test. */ ATOMIC_DEC(int, rw->num_readers); /* What if a writer thought that this reader has already taken turn - and will then wait thinking this guy has grabbed the read lock first? For now we'll have to wake up the writer to retry even if it spuriously wakes up the next writer. */ // FIXME: we need to do only when num_readers has become zero, // but it is OK for now as this won't usually happen rwlock_notify_writer(rw); /* --ok since writers still have to loop */ /* hint we are spinning */ SPINLOCK_PAUSE(); } while (true); DEADLOCK_AVOIDANCE_LOCK(&rw->lock, true, LOCK_NOT_OWNABLE); } void write_lock(read_write_lock_t *rw) { /* we do not follow the pattern of having lock call trylock in * a loop because that would be unfair to writers -- first guy * in this implementation gets to write */ if (INTERNAL_OPTION(spin_yield_rwlock)) { mutex_lock(&rw->lock); while (rw->num_readers > 0) { /* contended write */ DEADLOCK_AVOIDANCE_LOCK(&rw->lock, false, LOCK_NOT_OWNABLE); /* FIXME: last places where we yield instead of wait */ os_thread_yield(); } rw->writer = get_thread_id(); return; } mutex_lock(&rw->lock); /* We still do this in a loop, since the event signal doesn't guarantee that num_readers is 0 when unblocked. */ while (rw->num_readers > 0) { /* contended write */ DEADLOCK_AVOIDANCE_LOCK(&rw->lock, false, LOCK_NOT_OWNABLE); rwlock_wait_contended_writer(rw); } rw->writer = get_thread_id(); } bool write_trylock(read_write_lock_t *rw) { if (mutex_trylock(&rw->lock)) { ASSERT_NOT_TESTED(); if (rw->num_readers == 0) { rw->writer = get_thread_id(); return true; } else { /* We need to duplicate the bottom of write_unlock() */ /* since if a new reader has appeared after we have acquired the lock that one may already be waiting on the broadcast event */ mutex_unlock(&rw->lock); /* check whether any reader is currently waiting */ if (rw->num_pending_readers > 0) { /* after we've released the write lock, pending * readers will no longer wait */ rwlock_notify_readers(rw); } } } return false; } void read_unlock(read_write_lock_t *rw) { if (INTERNAL_OPTION(spin_yield_rwlock)) { ATOMIC_DEC(int, rw->num_readers); DEADLOCK_AVOIDANCE_UNLOCK(&rw->lock, LOCK_NOT_OWNABLE); return; } /* if we were the last reader to hold the lock, (i.e. final value is 0) we may need to notify a waiting writer */ /* unfortunately even on the hot path (of a single reader) we have to check if the writer is in fact waiting. Even though this is not atomic we don't need to loop here - write_lock() will loop. */ if (atomic_dec_becomes_zero(&rw->num_readers)) { /* if the writer is waiting it definitely needs to hold the mutex */ if (mutex_testlock(&rw->lock)) { /* test that it was not this thread owning both write and read lock */ if (rw->writer != get_thread_id()) { /* we're assuming the writer has been forced to wait, but since we can't tell whether it did indeed wait this notify may leave signaled the event for the next turn If the writer has grabbed the mutex and checked when num_readers==0 and has gone assuming to be the rwlock owner. In that case the above rwlock_notify_writer will give the wrong signal to the next writer. --ok since writers still have to loop */ rwlock_notify_writer(rw); } } } DEADLOCK_AVOIDANCE_UNLOCK(&rw->lock, LOCK_NOT_OWNABLE); } void write_unlock(read_write_lock_t *rw) { #ifdef DEADLOCK_AVOIDANCE ASSERT(rw->writer == rw->lock.owner); #endif rw->writer = INVALID_THREAD_ID; if (INTERNAL_OPTION(spin_yield_rwlock)) { mutex_unlock(&rw->lock); return; } /* we need to signal all waiting readers (if any) that they can now go ahead. No writer should be allowed to lock until all currently waiting readers are unblocked. */ /* We first unlock so that any blocked readers can start making progress as soon as they are notified. Further field accesses however have to be assumed unprotected. */ mutex_unlock(&rw->lock); /* check whether any reader is currently waiting */ if (rw->num_pending_readers > 0) { /* after we've released the write lock, pending readers will no longer wait */ rwlock_notify_readers(rw); } } bool self_owns_write_lock(read_write_lock_t *rw) { /* ASSUMPTION: reading owner field is atomic */ return (rw->writer == get_thread_id()); } /****************************************************************************/ /* HASHING */ ptr_uint_t hash_value(ptr_uint_t val, hash_function_t func, ptr_uint_t mask, uint bits) { if (func == HASH_FUNCTION_NONE) return val; switch (func) { case HASH_FUNCTION_MULTIPLY_PHI: { /* case 8457: keep in sync w/ HASH_VALUE_FOR_TABLE() */ return ((val * HASH_PHI) >> (HASH_TAG_BITS - bits)); } #ifdef INTERNAL case HASH_FUNCTION_LOWER_BSWAP: { IF_X64(ASSERT_NOT_IMPLEMENTED(false)); return (((val & 0xFFFF0000)) | ((val & 0x000000FF) << 8) | ((val & 0x0000FF00) >> 8)); } case HASH_FUNCTION_BSWAP_XOR: { IF_X64(ASSERT_NOT_IMPLEMENTED(false)); return (val ^ (((val & 0x000000FF) << 24) | ((val & 0x0000FF00) << 8) | ((val & 0x00FF0000) >> 8) | ((val & 0xFF000000) >> 24))); } case HASH_FUNCTION_SWAP_12TO15: { IF_X64(ASSERT_NOT_IMPLEMENTED(false)); return (((val & 0xFFFF0FF0)) | ((val & 0x0000F000) >> 12) | ((val & 0x0000000F) << 12)); } case HASH_FUNCTION_SWAP_12TO15_AND_NONE: { IF_X64(ASSERT_NOT_IMPLEMENTED(false)); return (mask <= 0xFFF ? val : (((val & 0xFFFF0FF0)) | ((val & 0x0000F000) >> 12) | ((val & 0x0000000F) << 12))); } case HASH_FUNCTION_SHIFT_XOR: { IF_X64(ASSERT_NOT_IMPLEMENTED(false)); return val ^ (val >> 12) ^ (val << 12); } #endif case HASH_FUNCTION_STRING: case HASH_FUNCTION_STRING_NOCASE: { const char *s = (const char *) val; char c; ptr_uint_t hash = 0; uint i, shift; uint max_shift = ALIGN_FORWARD(bits, 8); /* Simple hash function that combines unbiased via xor and * shifts to get input chars to cover the full range. We clamp * the shift to avoid useful bits being truncated. An * alternative is to combine blocks of 4 chars at a time but * that's more complex. */ for (i = 0; s[i] != '\0'; i++) { c = s[i]; if (func == HASH_FUNCTION_STRING_NOCASE) c = (char) tolower(c); shift = (i % 4) * 8; hash ^= (c << MIN(shift, max_shift)); } return hash; } default: { ASSERT_NOT_REACHED(); return 0; } } } uint hashtable_num_bits(uint size) { uint bits = 0; uint sz = size; while (sz > 0) { sz = sz >> 1; bits++; } ASSERT(HASHTABLE_SIZE(bits) > size && HASHTABLE_SIZE(bits) <= size*2); return bits; } /****************************************************************************/ /* BITMAP */ /* Since there is no ffs() on windows we use the one from * /usr/src/linux-2.4/include/linux/bitops.h. TODO: An easier * x86-specific way using BSF is * /usr/src/linux-2.4/include/asm/bitops.h */ /* Returns the position of the first set bit - betwen 0 and 31 */ static inline uint bitmap_find_first_set_bit(bitmap_element_t x) { int r = 0; ASSERT(x); if (!(x & 0xffff)) { x >>= 16; r += 16; } if (!(x & 0xff)) { x >>= 8; r += 8; } if (!(x & 0xf)) { x >>= 4; r += 4; } if (!(x & 3)) { x >>= 2; r += 2; } if (!(x & 1)) { x >>= 1; r += 1; } return r; } /* A block is marked free with a set bit. Returns -1 if no block is found! */ static inline uint bitmap_find_set_block(bitmap_t b, uint bitmap_size) { uint i = 0; uint last_index = BITMAP_INDEX(bitmap_size); while (b[i] == 0 && i < last_index) i++; if (i == last_index) return BITMAP_NOT_FOUND; return i*BITMAP_DENSITY + bitmap_find_first_set_bit(b[i]); } /* Looks for a sequence of free blocks * Returns -1 if no such sequence is found! * Considering the fact that the majority of our allocations will be * for a single block this operation is not terribly efficient. */ static uint bitmap_find_set_block_sequence(bitmap_t b, uint bitmap_size, uint requested) { uint last_bit = bitmap_size - requested + 1; /* find quickly at least a single block */ uint first = bitmap_find_set_block(b, bitmap_size); if (first == BITMAP_NOT_FOUND) return BITMAP_NOT_FOUND; do { /* now check if there is room for the requested number of bits */ uint hole_size = 1; while (hole_size < requested && bitmap_test(b, first + hole_size)) { hole_size++; } if (hole_size == requested) return first; /* otherwise first + hole_size is not set, so we should skip that */ first += hole_size + 1; while (first < last_bit && !bitmap_test(b, first)) first++; } while (first < last_bit); return BITMAP_NOT_FOUND; } void bitmap_initialize_free(bitmap_t b, uint bitmap_size) { memset(b, 0xff, BITMAP_INDEX(bitmap_size) * sizeof(bitmap_element_t)); } uint bitmap_allocate_blocks(bitmap_t b, uint bitmap_size, uint request_blocks) { uint i, res; if (request_blocks == 1) { i = bitmap_find_set_block(b, bitmap_size); } else { i = bitmap_find_set_block_sequence(b, bitmap_size, request_blocks); } res = i; if (res == BITMAP_NOT_FOUND) return BITMAP_NOT_FOUND; do { bitmap_clear(b, i++); } while (--request_blocks); return res; } void bitmap_free_blocks(bitmap_t b, uint bitmap_size, uint first_block, uint num_free) { ASSERT(first_block + num_free <= bitmap_size); do { ASSERT(!bitmap_test(b, first_block)); bitmap_set(b, first_block++); } while (--num_free); } #ifdef DEBUG /* used only for ASSERTs */ bool bitmap_are_reserved_blocks(bitmap_t b, uint bitmap_size, uint first_block, uint num_blocks) { ASSERT(first_block + num_blocks <= bitmap_size); do { if (bitmap_test(b, first_block)) return false; first_block++; } while (--num_blocks); return true; } static inline uint bitmap_count_set_bits(bitmap_element_t x) { int r = 0; /* count set bits in each element */ while (x) { r++; x &= x - 1; } return r; } bool bitmap_check_consistency(bitmap_t b, uint bitmap_size, uint expect_free) { uint last_index = BITMAP_INDEX(bitmap_size); uint i; uint current = 0; for (i=0; i < last_index; i++) { current += bitmap_count_set_bits(b[i]); } LOG(GLOBAL, LOG_HEAP, 3, "bitmap_check_consistency(b="PFX", bitmap_size=%d)" " expected=%d current=%d\n", b, bitmap_size, expect_free, current); return expect_free == current; } #endif /* DEBUG */ /****************************************************************************/ /* LOGGING */ file_t get_thread_private_logfile() { #ifdef DEBUG dcontext_t *dcontext = get_thread_private_dcontext(); if (dcontext == NULL) dcontext = GLOBAL_DCONTEXT; return THREAD; #else return INVALID_FILE; #endif } #ifdef DEBUG DECLARE_FREQPROT_VAR(static bool do_once_do_file_write, false); #endif /* FIXME: add buffering? */ ssize_t do_file_write(file_t f, const char *fmt, va_list ap) { ssize_t size, written; char logbuf[MAX_LOG_LENGTH]; #ifndef NOLIBC /* W/ libc, we cannot print while .data is protected. We assume * that DATASEC_RARELY_PROT is .data. */ if (DATASEC_PROTECTED(DATASEC_RARELY_PROT)) { ASSERT(TEST(SELFPROT_DATA_RARE, dynamo_options.protect_mask)); ASSERT(strcmp(DATASEC_NAMES[DATASEC_RARELY_PROT], ".data") == 0); return -1; } #endif if (f == INVALID_FILE) return -1; size = vsnprintf(logbuf, BUFFER_SIZE_ELEMENTS(logbuf), fmt, ap); NULL_TERMINATE_BUFFER(logbuf); /* always NULL terminate */ /* note that we can't print %f on windows with NOLIBC (returns error * size == -1), use double_print() or divide_uint64_print() as needed */ DOCHECK(1, { /* we have our own do-once to avoid infinite recursion w/ protect_data_section */ if (size < 0 || size >= BUFFER_SIZE_ELEMENTS(logbuf)) { if (!do_once_do_file_write) { do_once_do_file_write = true; ASSERT_CURIOSITY(size >= 0 && size < sizeof(logbuf)); } } }); /* handle failure values */ if (size >= BUFFER_SIZE_ELEMENTS(logbuf) || size < 0) size = strlen(logbuf); written = os_write(f, logbuf, size); if (written < 0) return -1; return written; } /* a little utiliy for printing a float that is formed by dividing 2 uints, * gives back high and low parts for printing, also supports percentages * FIXME : we might need to handle signed numbers at some point (but not yet), * also could be smarter about overflow conditions (i.e. for calculating * bottom or top) but we never call with numbers that big, also truncates * instead of rounding * Usage : given a, b (uint[64]); d_int()==divide_uint64_print(); * uint c, d tmp; parameterized on precision p and width w * note that %f is eqv. to %.6f, 3rd ex. is a percentage ex. * "%.pf", a/(float)b => d_int(a, b, false, p, &c, &d); "%u.%.pu", c,d * "%w.pf", a/(float)b => d_int(a, b, false, p, &c, &d); "%(w-p-1)u.%.pu", c,d * "%.pf%%", 100*(a/(float)b) => d_int(a, b, true, p, &c, &d); "%u.%.pu%%", c,d */ void divide_uint64_print(uint64 numerator, uint64 denominator, bool percentage, uint precision, uint *top, uint *bottom) { uint i, precision_multiple, multiple = percentage ? 100 : 1; #ifdef HOT_PATCHING_INTERFACE /* case 6657: hotp_only does not have many of the DR stats, so * numerator and/or denominator may be 0 */ ASSERT(denominator != 0 || DYNAMO_OPTION(hotp_only)); #else ASSERT(denominator != 0); #endif ASSERT(top != NULL && bottom != NULL); if (denominator == 0) return; ASSERT_TRUNCATE(*top, uint, ((multiple * numerator) / denominator)); *top = (uint) ((multiple * numerator) / denominator); for (i = 0, precision_multiple = 1; i < precision; i++) precision_multiple *= 10; ASSERT_TRUNCATE(*bottom, uint, (((precision_multiple * multiple * numerator) / denominator) - (precision_multiple * *top))); /* FUNNY: if I forget the above ) I crash the preprocessor: cc1 * internal compiler error couldn't reproduce in a smaller set to * file a bug against gcc version 3.3.3 (cygwin special) */ *bottom = (uint) (((precision_multiple * multiple * numerator) / denominator) - (precision_multiple * *top)); } #if (defined(DEBUG) || defined(INTERNAL) || defined(CLIENT_INTERFACE) || \ defined(STANDALONE_UNIT_TEST)) /* When building with /QIfist casting rounds instead of truncating (i#763) * so we use these routines from io.c. */ extern long double2int_trunc(double d); /* for printing a float (can't use %f on windows with NOLIBC), NOTE: you must * preserve floating point state to call this function!! * FIXME : truncates instead of rounding, also negative with width looks funny, * finally width can be one off if negative * Usage : given double/float a; uint c, d and char *s tmp; dp==double_print * parameterized on precision p width w * note that %f is eqv. to %.6f * "%.pf", a => dp(a, p, &c, &d, &s) "%s%u.%.pu", s, c, d * "%w.pf", a => dp(a, p, &c, &d, &s) "%s%(w-p-1)u.%.pu", s, c, d */ void double_print(double val, uint precision, uint *top, uint *bottom, const char **sign) { uint i, precision_multiple; ASSERT(top != NULL && bottom != NULL && sign != NULL); if (val < 0.0) { val = -val; *sign = "-"; } else { *sign = ""; } for (i = 0, precision_multiple = 1; i < precision; i++) precision_multiple *= 10; /* when building with /QIfist casting rounds instead of truncating (i#763) */ *top = double2int_trunc(val); *bottom = double2int_trunc((val - *top) * precision_multiple); } #endif /* DEBUG || INTERNAL || CLIENT_INTERFACE || STANDALONE_UNIT_TEST */ #ifdef WINDOWS /* for pre_inject, injector, and core shared files, is just wrapper for syslog * internal */ void display_error(char *msg) { SYSLOG_INTERNAL_ERROR("%s", msg); } #endif #ifdef DEBUG # ifdef WINDOWS /* print_symbolic_address is in module.c */ # else /* prints a symbolic name, or best guess of it into a caller provided buffer */ void print_symbolic_address(app_pc tag, char *buf, int max_chars, bool exact_only) { buf[0]='\0'; } # endif #endif /* DEBUG */ void print_file(file_t f, const char *fmt, ...) { va_list ap; va_start(ap, fmt); do_file_write(f, fmt, ap); va_end(ap); } /* For repeated appending to a buffer. The "sofar" var should be set * to 0 by the caller before the first call to print_to_buffer. * Returns false if there was not room for the string plus a null, * but still prints the maximum that will fit plus a null. */ static bool vprint_to_buffer(char *buf, size_t bufsz, size_t *sofar INOUT, const char *fmt, va_list ap) { /* in io.c */ extern int our_vsnprintf(char *s, size_t max, const char *fmt, va_list ap); ssize_t len; bool ok; /* we use our_vsnprintf for consistent return value and to handle floats */ len = our_vsnprintf(buf + *sofar, bufsz - *sofar, fmt, ap); /* we support appending an empty string (len==0) */ ok = (len >= 0 && len < (ssize_t)(bufsz - *sofar)); *sofar += (len == -1 ? (bufsz - *sofar - 1) : (len < 0 ? 0 : len)); /* be paranoid: though usually many calls in a row and could delay until end */ buf[bufsz-1] = '\0'; return ok; } /* For repeated appending to a buffer. The "sofar" var should be set * to 0 by the caller before the first call to print_to_buffer. * Returns false if there was not room for the string plus a null, * but still prints the maximum that will fit plus a null. */ bool print_to_buffer(char *buf, size_t bufsz, size_t *sofar INOUT, const char *fmt, ...) { va_list ap; bool ok; va_start(ap, fmt); ok = vprint_to_buffer(buf, bufsz, sofar, fmt, ap); va_end(ap); return ok; } /* N.B.: this routine is duplicated in instrument.c's dr_log! * Maybe export this routine itself, or make another layer of * calls that passes the va_list (-> less efficient)? * For now I'm assuming this routine changes little. */ void print_log(file_t logfile, uint mask, uint level, const char *fmt, ...) { va_list ap; #ifdef DEBUG /* FIXME: now the LOG macro checks these, remove here? */ if (logfile == INVALID_FILE || (stats != NULL && ((stats->logmask & mask) == 0 || stats->loglevel < level))) return; #else return; #endif KSTART(logging); va_start(ap, fmt); do_file_write(logfile, fmt, ap); va_end(ap); KSTOP_NOT_PROPAGATED(logging); } #ifdef WINDOWS static void do_syslog(syslog_event_type_t priority, uint message_id, uint substitutions_num, ...) { va_list ap; va_start(ap, substitutions_num); os_syslog(priority, message_id, substitutions_num, ap); va_end(ap); } #endif /* notify present a notification message to one or more destinations, * depending on the runtime parameters and the priority: * -syslog_mask controls sending to the system log * -stderr_mask controls sending to stderr * -msgbox_mask controls sending to an interactive pop-up window, or * a wait for a keypress on linux */ void notify(syslog_event_type_t priority, bool internal, bool synch, IF_WINDOWS_(uint message_id) uint substitution_num, const char *prefix, const char *fmt, ...) { char msgbuf[MAX_LOG_LENGTH]; int size; va_list ap; va_start(ap, fmt); /* FIXME : the vsnprintf call is not needed in the most common case where * we are going to just os_syslog, but it gets pretty ugly to do that */ size = vsnprintf(msgbuf, sizeof(msgbuf), fmt, ap); NULL_TERMINATE_BUFFER(msgbuf); /* always NULL terminate */ /* not a good idea to assert here since we'll just die and lose original message, * so we don't check size return value and just go ahead and truncate */ va_end(ap); LOG(GLOBAL, LOG_ALL, 1, "%s: %s\n", prefix, msgbuf); /* so can skip synchronizing when failure is in option parsing to avoid * infinite recursion, still could be issue with exception, but separate * recursive bailout will at least kill us then, FIXME, note will use * default masks below if original parse */ if (synch) synchronize_dynamic_options(); /* TODO: dynamic THREAD mask */ LOG(THREAD_GET, LOG_ALL, 1, "%s: %s\n", prefix, msgbuf); #ifdef WINDOWS if (TEST(priority, dynamo_options.syslog_mask)) { if (internal) { if (TEST(priority, INTERNAL_OPTION(syslog_internal_mask))) { do_syslog(priority, message_id, 3, get_application_name(), get_application_pid(), msgbuf); } } else { va_start(ap, fmt); os_syslog(priority, message_id, substitution_num, ap); va_end(ap); } } #else /* syslog not yet implemented on linux, FIXME */ #endif if (TEST(priority, dynamo_options.stderr_mask)) print_file(STDERR, "<%s>\n", msgbuf); if (TEST(priority, dynamo_options.msgbox_mask)) { #ifdef WINDOWS /* XXX: could use os_countdown_msgbox (if ever implemented) here to * do a timed out messagebox, could then also replace the os_timeout in * vmareas.c */ debugbox(msgbuf); #else /* i#116/PR 394985: this won't work for apps that are * themselves reading from stdin, but this is a simple way to * pause and continue, allowing gdb to attach */ if (DYNAMO_OPTION(pause_via_loop)) { while (DYNAMO_OPTION(pause_via_loop)) { /* infinite loop */ os_thread_yield(); } } else { char keypress; print_file(STDERR, "<press enter to continue>\n"); os_read(STDIN, &keypress, sizeof(keypress)); } #endif } } /**************************************************************************** * REPORTING DYNAMORIO PROBLEMS * Including assertions, curiosity asserts, API usage errors, * deadlock timeouts, internal exceptions, and the app modifying our memory. * * The following constants are for the pieces of a buffer we will send * to the event log, to diagnostics, and to stderr/msgbox/logfile. * It's static to avoid adding 500+ bytes to the stack on a critical * path, and so needs synchronization, but the risk of a problem with * the lock is worth getting a clear message on the first exception. * * Here's a sample of a report. First four lines here are the * passed-in custom string fmt, subsequent are the options and call * stack, which are always appended: * Platform exception at PC 0x15003075 * 0xc0000005 0x00000000 0x15003075 0x15003075 0x00000001 0x00000037 * Registers: eax 0x00000000 ebx 0x00000000 ecx 0x177c9040 edx 0x177c9040 * esi 0x00000b56 edi 0x0000015f esp 0x177e3eb0 eflags 0x00010246 * Base: 0x15000000 * internal version, custom build * -loglevel 2 -msgbox_mask 12 -stderr_mask 12 * 0x00342ee8 0x150100f2 * 0x00342f64 0x15010576 * 0x00342f84 0x1503d77b * 0x00342fb0 0x1503f12c * 0x00342ff4 0x150470e9 * 0x77f82b95 0x565308ec */ /* The magic number 271 comes from MAXIMUM_PATH (on WINDOWS = 260) + 11 for PR 204171 * (in other words historical reasons). Xref PR 226547 we use a constant value here * instead of MAXIMUM_PATH since it has different length on Linux and makes this buffer * too long. */ #ifdef X64 # define REPORT_MSG_MAX (271+17*8+8*23+2) /* wider, + more regs */ #elif defined(ARM) # define REPORT_MSG_MAX (271+17*8) /* more regs */ #else # define REPORT_MSG_MAX (271) #endif #define REPORT_LEN_VERSION IF_CLIENT_INTERFACE_ELSE(96,37) /* example: "\ninternal version, build 94201\n" * For custom builds, the build # is generated as follows * (cut-and-paste from Makefile): * # custom builds: 9XYYZ * # X = developer, YY = tree, Z = diffnum * # YY defaults to 1st 2 letters of CUR_TREE, unless CASENUM is defined, * # in which case it is the last 2 letters of CASENUM (all % 10 of course) */ #define REPORT_LEN_OPTIONS IF_CLIENT_INTERFACE_ELSE(324, 192) /* still not long enough for ALL non-default options but I'll wager money we'll never * see this option string truncated, at least for non-internal builds * (famous last words?) => yes! For clients this can get quite long. * List options from staging mode could be problematic though. */ #define REPORT_NUM_STACK IF_CLIENT_INTERFACE_ELSE(15, 10) #ifdef X64 # define REPORT_LEN_STACK_EACH (22+2*8) #else # define REPORT_LEN_STACK_EACH 22 #endif /* just frame ptr, ret addr: "0x0342fc7c 0x77f8c6dd\n" == 22 chars per line */ #define REPORT_LEN_STACK (REPORT_LEN_STACK_EACH)*(REPORT_NUM_STACK) #ifdef CLIENT_INTERFACE /* We have to stay under MAX_LOG_LENGTH so we limit to ~10 basenames */ # define REPORT_LEN_PRIVLIBS (45 * 10) #endif /* Not persistent across code cache execution, so not protected */ DECLARE_NEVERPROT_VAR(static char reportbuf[REPORT_MSG_MAX + REPORT_LEN_VERSION + REPORT_LEN_OPTIONS + REPORT_LEN_STACK + IF_CLIENT_INTERFACE(REPORT_LEN_PRIVLIBS +) 1], {0,}); DECLARE_CXTSWPROT_VAR(static mutex_t report_buf_lock, INIT_LOCK_FREE(report_buf_lock)); /* Avoid deadlock w/ nested reports */ DECLARE_CXTSWPROT_VAR(static thread_id_t report_buf_lock_owner, 0); #define ASSERT_ROOM(reportbuf, curbuf, maxlen) \ ASSERT(curbuf + maxlen < reportbuf + sizeof(reportbuf)) /* random number generator */ DECLARE_CXTSWPROT_VAR(static mutex_t prng_lock, INIT_LOCK_FREE(prng_lock)); #ifdef DEBUG /* callers should play it safe - no memory allocations, no grabbing locks */ bool under_internal_exception() { # ifdef DEADLOCK_AVOIDANCE /* ASSUMPTION: reading owner field is atomic */ return (report_buf_lock.owner == get_thread_id()); # else /* mutexes normally don't have an owner, stay safe no matter who owns */ return mutex_testlock(&report_buf_lock); # endif /* DEADLOCK_AVOIDANCE */ } #endif /* DEBUG */ /* Defaults, overridable by the client (i#1470) */ const char *exception_label_core = PRODUCT_NAME; static const char *exception_report_url = BUG_REPORT_URL; #ifdef CLIENT_INTERFACE const char *exception_label_client = "Client"; #endif /* We allow clients to display their version instead of DR's */ static char display_version[REPORT_LEN_VERSION]; /* HACK: to avoid duplicating the prefix of the event log message, we * skip it for the SYSLOG, but not the other notifications */ static char exception_prefix[MAXIMUM_PATH]; static inline size_t report_exception_skip_prefix(void) { return strlen(exception_prefix); } #ifdef CLIENT_INTERFACE static char client_exception_prefix[MAXIMUM_PATH]; static inline size_t report_client_exception_skip_prefix(void) { return strlen(client_exception_prefix); } #endif void set_exception_strings(const char *override_label, const char *override_url) { if (dynamo_initialized) SELF_UNPROTECT_DATASEC(DATASEC_RARELY_PROT); if (override_url != NULL) exception_report_url = override_url; if (override_label != NULL) exception_label_core = override_label; ASSERT(strlen(CRASH_NAME) == strlen(STACK_OVERFLOW_NAME)); snprintf(exception_prefix, BUFFER_SIZE_ELEMENTS(exception_prefix), "%s %s at PC "PFX, exception_label_core, CRASH_NAME, 0); NULL_TERMINATE_BUFFER(exception_prefix); #ifdef CLIENT_INTERFACE if (override_label != NULL) exception_label_client = override_label; snprintf(client_exception_prefix, BUFFER_SIZE_ELEMENTS(client_exception_prefix), "%s %s at PC "PFX, exception_label_client, CRASH_NAME, 0); NULL_TERMINATE_BUFFER(client_exception_prefix); #endif #ifdef WINDOWS debugbox_setup_title(); #endif if (dynamo_initialized) SELF_PROTECT_DATASEC(DATASEC_RARELY_PROT); } void set_display_version(const char *ver) { if (dynamo_initialized) SELF_UNPROTECT_DATASEC(DATASEC_RARELY_PROT); snprintf(display_version, BUFFER_SIZE_ELEMENTS(display_version), "%s", ver); NULL_TERMINATE_BUFFER(display_version); if (dynamo_initialized) SELF_PROTECT_DATASEC(DATASEC_RARELY_PROT); } /* Fine to pass NULL for dcontext, will obtain it for you. * If TEST(DUMPCORE_INTERNAL_EXCEPTION, dumpcore_flag), does a full SYSLOG; * else, does a SYSLOG_INTERNAL_ERROR. * Fine to pass NULL for report_ebp: will use current ebp for you. */ void report_dynamorio_problem(dcontext_t *dcontext, uint dumpcore_flag, app_pc exception_addr, app_pc report_ebp, const char *fmt, ...) { /* WARNING: this routine is called for fatal errors, and * a fault in DR means that potentially anything could be * inconsistent or corrupted! Do not grab locks or traverse * data structures or read memory if you can avoid it! */ char *curbuf; ptr_uint_t *pc; uint num; int len; va_list ap; /* synchronize dynamic options */ synchronize_dynamic_options(); ASSERT(sizeof(reportbuf) < MAX_LOG_LENGTH); if (dcontext == NULL) dcontext = get_thread_private_dcontext(); if (dcontext == NULL) dcontext = GLOBAL_DCONTEXT; if (report_buf_lock_owner == get_thread_id()) { /* nested report: can't do much except bail on inner */ return; } mutex_lock(&report_buf_lock); report_buf_lock_owner = get_thread_id(); /* we assume the caller does a DO_ONCE to prevent hanging on a * fault in this routine, if called to report a fatal error. */ /* now build up the report */ curbuf = reportbuf; ASSERT_ROOM(reportbuf, curbuf, REPORT_MSG_MAX); va_start(ap, fmt); len = vsnprintf(curbuf, REPORT_MSG_MAX, fmt, ap); curbuf += (len == -1 ? REPORT_MSG_MAX : (len < 0 ? 0 : len)); va_end(ap); if (display_version[0] != '\0') { len = snprintf(curbuf, REPORT_LEN_VERSION, "\n%s\n", display_version); curbuf += (len == -1 ? REPORT_LEN_VERSION : (len < 0 ? 0 : len)); } else { /* don't use dynamorio_version_string, we don't need copyright notice */ ASSERT_ROOM(reportbuf, curbuf, REPORT_LEN_VERSION); len = snprintf(curbuf, REPORT_LEN_VERSION, "\n%s, %s\n", VERSION_NUMBER_STRING, BUILD_NUMBER_STRING); curbuf += (len == -1 ? REPORT_LEN_VERSION : (len < 0 ? 0 : len)); } ASSERT_ROOM(reportbuf, curbuf, REPORT_LEN_OPTIONS); /* leave room for newline */ get_dynamo_options_string(&dynamo_options, curbuf, REPORT_LEN_OPTIONS-1, true); /* get_dynamo_options_string will null-terminate even if truncates */ curbuf += strlen(curbuf); *(curbuf++) = '\n'; /* print just frame ptr and ret addr for top of call stack */ ASSERT_ROOM(reportbuf, curbuf, REPORT_LEN_STACK); if (report_ebp == NULL) { GET_FRAME_PTR(report_ebp); } for (num = 0, pc = (ptr_uint_t *) report_ebp; num < REPORT_NUM_STACK && pc != NULL && is_readable_without_exception_query_os_noblock((app_pc) pc, 2*sizeof(reg_t)); num++, pc = (ptr_uint_t *) *pc) { len = snprintf(curbuf, REPORT_LEN_STACK_EACH, PFX" "PFX"\n", pc, *(pc+1)); curbuf += (len == -1 ? REPORT_LEN_STACK_EACH : (len < 0 ? 0 : len)); } #ifdef CLIENT_INTERFACE /* Only walk the module list if we think the data structs are safe */ if (!TEST(DUMPCORE_INTERNAL_EXCEPTION, dumpcore_flag)) { size_t sofar = 0; /* We decided it's better to include the paths even if it means we may * not fit all the modules (i#968). We plan to add the modules to the * forensics file to have complete info (i#972). */ privload_print_modules(true/*include path*/, false/*no lock*/, curbuf, REPORT_LEN_PRIVLIBS, &sofar); curbuf += sofar; } #endif /* SYSLOG_INTERNAL and diagnostics expect no trailing newline */ if (*(curbuf-1) == '\n') /* won't be if we truncated something */ curbuf--; /* now we for sure have room for \0 */ *curbuf = '\0'; /* now done with reportbuf */ if (TEST(dumpcore_flag, DYNAMO_OPTION(dumpcore_mask)) && DYNAMO_OPTION(live_dump)) { /* non-fatal coredumps attempted before printing further diagnostics */ os_dump_core(reportbuf); } /* we already synchronized the options at the top of this function and we * might be stack critical so use _NO_OPTION_SYNCH */ if (TEST(DUMPCORE_INTERNAL_EXCEPTION, dumpcore_flag) IF_CLIENT_INTERFACE(|| TEST(DUMPCORE_CLIENT_EXCEPTION, dumpcore_flag))) { char saddr[IF_X64_ELSE(19,11)]; snprintf(saddr, BUFFER_SIZE_ELEMENTS(saddr), PFX, exception_addr); NULL_TERMINATE_BUFFER(saddr); if (TEST(DUMPCORE_INTERNAL_EXCEPTION, dumpcore_flag)) { SYSLOG_NO_OPTION_SYNCH(SYSLOG_CRITICAL, EXCEPTION, 7/*#args*/, get_application_name(), get_application_pid(), exception_label_core, TEST(DUMPCORE_STACK_OVERFLOW, dumpcore_flag) ? STACK_OVERFLOW_NAME : CRASH_NAME, saddr, exception_report_url, /* skip the prefix since the event log string * already has it */ reportbuf + report_exception_skip_prefix()); } #ifdef CLIENT_INTERFACE else { SYSLOG_NO_OPTION_SYNCH(SYSLOG_CRITICAL, CLIENT_EXCEPTION, 7/*#args*/, get_application_name(), get_application_pid(), exception_label_client, TEST(DUMPCORE_STACK_OVERFLOW, dumpcore_flag) ? STACK_OVERFLOW_NAME : CRASH_NAME, saddr, exception_report_url, reportbuf + report_client_exception_skip_prefix()); } #endif } else if (TEST(DUMPCORE_ASSERTION, dumpcore_flag)) { /* We need to report ASSERTS in DEBUG=1 INTERNAL=0 builds since we're still * going to kill the process. Xref PR 232783. internal_error() already * obfuscated the which file info. */ SYSLOG_NO_OPTION_SYNCH(SYSLOG_ERROR, INTERNAL_SYSLOG_ERROR, 3, get_application_name(), get_application_pid(), reportbuf); } else if (TEST(DUMPCORE_CURIOSITY, dumpcore_flag)) { SYSLOG_INTERNAL_NO_OPTION_SYNCH(SYSLOG_WARNING, "%s", reportbuf); } else { SYSLOG_INTERNAL_NO_OPTION_SYNCH(SYSLOG_ERROR, "%s", reportbuf); } /* no forensics files for usage error */ if (dumpcore_flag != DUMPCORE_FATAL_USAGE_ERROR) { /* NULL for the threat id * We always assume BAD state, even for curiosity asserts, etc., since * diagnostics grabs memory when ok and we can't have that at arbitrary points! */ report_diagnostics(reportbuf, NULL, NO_VIOLATION_BAD_INTERNAL_STATE); } /* Print out pretty call stack to logfile where we have plenty of room. * This avoids grabbing a lock b/c print_symbolic_address() checks * under_internal_exception(). However we cannot include module info b/c * that grabs locks: hence the fancier callstack in the main report * for client and app crashes but not DR crashes. */ DOLOG(1, LOG_ALL, { if (TEST(DUMPCORE_INTERNAL_EXCEPTION, dumpcore_flag)) dump_callstack(exception_addr, report_ebp, THREAD, DUMP_NOT_XML); else dump_dr_callstack(THREAD); }); report_buf_lock_owner = 0; mutex_unlock(&report_buf_lock); if (dumpcore_flag != DUMPCORE_CURIOSITY) { /* print out stats, can't be done inside the report_buf_lock * because of non-trivial lock rank order violation on the * snapshot_lock */ DOLOG(1, LOG_ALL, { dump_global_stats(false); if (dcontext != GLOBAL_DCONTEXT) dump_thread_stats(dcontext, false); }); } if (TEST(dumpcore_flag, DYNAMO_OPTION(dumpcore_mask)) && !DYNAMO_OPTION(live_dump)) { /* fatal coredump goes last */ os_dump_core(reportbuf); } } void report_app_problem(dcontext_t *dcontext, uint appfault_flag, app_pc pc, app_pc report_ebp, const char *fmt, ...) { char buf[MAX_LOG_LENGTH]; size_t sofar = 0; va_list ap; char excpt_addr[IF_X64_ELSE(20,12)]; if (!TEST(appfault_flag, DYNAMO_OPTION(appfault_mask))) return; snprintf(excpt_addr, BUFFER_SIZE_ELEMENTS(excpt_addr), PFX, pc); NULL_TERMINATE_BUFFER(excpt_addr); va_start(ap, fmt); vprint_to_buffer(buf, BUFFER_SIZE_ELEMENTS(buf), &sofar, fmt, ap); va_end(ap); print_to_buffer(buf, BUFFER_SIZE_ELEMENTS(buf), &sofar, "Callstack:\n"); if (report_ebp == NULL) GET_FRAME_PTR(report_ebp); /* We decided it's better to include the paths even if it means we may * not fit all the modules (i#968). A forensics file can be requested * to get full info. */ dump_callstack_to_buffer(buf, BUFFER_SIZE_ELEMENTS(buf), &sofar, pc, report_ebp, CALLSTACK_MODULE_INFO | CALLSTACK_MODULE_PATH); SYSLOG(SYSLOG_WARNING, APP_EXCEPTION, 4, get_application_name(), get_application_pid(), excpt_addr, buf); report_diagnostics(buf, NULL, NO_VIOLATION_OK_INTERNAL_STATE); if (TEST(DUMPCORE_APP_EXCEPTION, DYNAMO_OPTION(dumpcore_mask))) os_dump_core("application fault"); } bool is_readable_without_exception_try(byte *pc, size_t size) { dcontext_t *dcontext = get_thread_private_dcontext(); /* note we need a dcontext for a TRY block */ if (dcontext == NULL) { /* FIXME: should rename the current * is_readable_without_exception() to * is_readable_without_exception_os_read(). On each platform * we should pick the fastest implementation for the * non-faulting common case as the default version of * is_readable_without_exception(). Some callers may still call a * specific version if the fast path is not as common. */ return is_readable_without_exception(pc, size); } TRY_EXCEPT(dcontext, { byte *check_pc = (byte *) ALIGN_BACKWARD(pc, PAGE_SIZE); if (size > (size_t)((byte *)POINTER_MAX - pc)) { ASSERT_NOT_TESTED(); size = (byte *)POINTER_MAX - pc; } do { PROBE_READ_PC(check_pc); /* note the minor perf benefit - we check the whole loop * in a single TRY/EXCEPT, and no system calls xref * is_readable_without_exception() [based on safe_read] * and is_readable_without_exception_query_os() [based on * query_virtual_memory]. */ check_pc += PAGE_SIZE; } while (check_pc != 0/*overflow*/ && check_pc < pc+size); /* TRY usage note: can't return here */ }, { /* EXCEPT */ /* no state to preserve */ return false; }); return true; } bool is_string_readable_without_exception(char *str, size_t *str_length /* OPTIONAL OUT */) { size_t length = 0; dcontext_t *dcontext = get_thread_private_dcontext(); if (str == NULL) return false; if (dcontext != NULL) { TRY_EXCEPT(dcontext, /* try */ { length = strlen(str); if (str_length != NULL) *str_length = length; /* NOTE - can't return here (try usage restriction) */ }, /* except */ { return false; }); return true; } else { /* ok have to do this the hard way... */ char *cur_page = (char *)ALIGN_BACKWARD(str, PAGE_SIZE); char *cur_str = str; do { if (!is_readable_without_exception((byte *)cur_str, (cur_page+PAGE_SIZE)-cur_str)) { return false; } while (cur_str < cur_page + PAGE_SIZE) { if (*cur_str == '\0') { if (str_length != NULL) *str_length = length; return true; } cur_str++; length++; } cur_page += PAGE_SIZE; ASSERT(cur_page == cur_str && ALIGNED(cur_page, PAGE_SIZE)); } while (true); ASSERT_NOT_REACHED(); return false; } } bool safe_write_try_except(void *base, size_t size, const void *in_buf, size_t *bytes_written) { uint prot; byte *region_base; size_t region_size; dcontext_t *dcontext = get_thread_private_dcontext(); bool res = false; if (bytes_written != NULL) *bytes_written = 0; if (dcontext != NULL) { TRY_EXCEPT(dcontext, { /* We abort on the 1st fault, just like safe_read */ memcpy(base, in_buf, size); res = true; } , { /* EXCEPT */ /* nothing: res is already false */ }); } else { /* this is subject to races, but should only happen at init/attach when * there should only be one live thread. */ /* on x86 must be readable to be writable so start with that */ if (is_readable_without_exception(base, size) && IF_UNIX_ELSE(get_memory_info_from_os, get_memory_info) (base, &region_base, &region_size, &prot) && TEST(MEMPROT_WRITE, prot)) { size_t bytes_checked = region_size - ((byte *)base - region_base); while (bytes_checked < size) { if (!IF_UNIX_ELSE(get_memory_info_from_os, get_memory_info) (region_base + region_size, &region_base, &region_size, &prot) || !TEST(MEMPROT_WRITE, prot)) return false; bytes_checked += region_size; } } else { return false; } /* ok, checks passed do the copy, FIXME - because of races this isn't safe! */ memcpy(base, in_buf, size); res = true; } if (res) { if (bytes_written != NULL) *bytes_written = size; } return res; } const char * memprot_string(uint prot) { switch (prot) { case (MEMPROT_READ|MEMPROT_WRITE|MEMPROT_EXEC): return "rwx"; case (MEMPROT_READ|MEMPROT_WRITE ): return "rw-"; case (MEMPROT_READ| MEMPROT_EXEC): return "r-x"; case (MEMPROT_READ ): return "r--"; case ( MEMPROT_WRITE|MEMPROT_EXEC): return "-wx"; case ( MEMPROT_WRITE ): return "-w-"; case ( MEMPROT_EXEC): return "--x"; case (0 ): return "---"; } return "<error>"; } /* returns true if every byte in the region addr to addr+size is set to val */ bool is_region_memset_to_char(byte *addr, size_t size, byte val) { /* FIXME : we could make this much faster with arch specific implementation * (for x86 repe scasd w/proper alignment handling) */ size_t i; for (i = 0; i < size; i++) { if (*addr++ != val) return false; } return true; } /* returns pointer to first char of string that matches either c1 or c2 * or NULL if can't find */ char * double_strchr(char *string, char c1, char c2) { while (*string != '\0') { if (*string == c1 || *string == c2) { return string; } string++; } return NULL; } #ifndef WINDOWS /* returns pointer to last char of string that matches either c1 or c2 * or NULL if can't find */ const char * double_strrchr(const char *string, char c1, char c2) { const char *ret = NULL; while (*string != '\0') { if (*string == c1 || *string == c2) { ret = string; } string++; } return ret; } #else /* in inject_shared.c, FIXME : move both copies to a common location */ #endif #ifdef WINDOWS /* Just like wcslen, but if the string is >= MAX characters long returns MAX * whithout interrogating past str+MAX. NOTE - this matches most library * implementations, but does NOT work the same way as the strnlen etc. * functions in the hotpatch2 module (they return MAX+1 for strings > MAX). * The hotpatch2 module implementation is scheduled to be changed. FIXME - * eventually would be nice to share the various string routines used both by * the core and the hotpatch2 module. */ size_t our_wcsnlen(const wchar_t *str, size_t max) { const wchar_t *s = str; size_t i = 0; while (i < max && *s != L'\0') { i++; s++; } return i; } #endif static int strcasecmp_with_wildcards(const char *regexp, const char *consider) { char cr, cc; while (true) { if (*regexp == '\0') { if (*consider == '\0') return 0; return -1; } else if (*consider == '\0') return 1; ASSERT(*regexp != EOF && *consider != EOF); cr = (char)tolower(*regexp); cc = (char)tolower(*consider); if (cr != '?' && cr != cc) { if (cr < cc) return -1; else return 1; } regexp++; consider++; } } bool str_case_prefix(const char *str, const char *pfx) { while (true) { if (*pfx == '\0') return true; if (*str == '\0') return false; if (tolower(*str) != tolower(*pfx)) return false; str++; pfx++; } return false; } static bool check_filter_common(const char *filter, const char *short_name, bool wildcards) { const char *next, *prev; /* FIXME: can we shrink this? not using full paths here */ char consider[MAXIMUM_PATH]; bool done = false; ASSERT(short_name != NULL && filter != NULL); /* FIXME: consider replacing most of this with strtok_r(copy_filter, ";", &pos) */ prev = filter; do { next = strchr(prev, ';'); if (next == NULL) { next = prev + strlen(prev); if (next == prev) break; done = true; } strncpy(consider, prev, MIN(BUFFER_SIZE_ELEMENTS(consider), (next-prev))); consider[next-prev] = '\0'; /* if max no null */ LOG(THREAD_GET, LOG_ALL, 3, "considering \"%s\" == \"%s\"\n", consider, short_name); if (wildcards && strcasecmp_with_wildcards(consider, short_name) == 0) return true; else if (strcasecmp(consider, short_name) == 0) return true; prev = next + 1; } while (!done); return false; } bool check_filter(const char *filter, const char *short_name) { return check_filter_common(filter, short_name, false/*no wildcards*/); } bool check_filter_with_wildcards(const char *filter, const char *short_name) { return check_filter_common(filter, short_name, true/*allow wildcards*/); } static char logdir[MAXIMUM_PATH]; static bool logdir_initialized = false; static char basedir[MAXIMUM_PATH]; static bool basedir_initialized = false; /* below used in the create_log_dir function to avoid having it on the stack * on what is a critical path for stack depth (diagnostics->create_log_dir-> * get_parameter */ static char old_basedir[MAXIMUM_PATH]; /* this lock is recursive because current implementation recurses to create the * basedir when called to create the logdir before the basedir is created, is * also useful in case we receive an exception in the create_log_dir function * since it is called in the diagnostics path, we should relook this though * as is probably not the best way to avoid the diagnostics problem FIXME */ DECLARE_CXTSWPROT_VAR(static recursive_lock_t logdir_mutex, INIT_RECURSIVE_LOCK(logdir_mutex)); /* enable creating a new base logdir (for a fork, e.g.) */ void enable_new_log_dir() { logdir_initialized = false; } void create_log_dir(int dir_type) { #ifdef UNIX char *pre_execve = getenv(DYNAMORIO_VAR_EXECVE_LOGDIR); bool sharing_logdir = false; #endif /* synchronize */ acquire_recursive_lock(&logdir_mutex); SELF_UNPROTECT_DATASEC(DATASEC_RARELY_PROT); #ifdef UNIX if (dir_type == PROCESS_DIR && pre_execve != NULL) { /* if this app has a logdir option or config, that should trump sharing * the pre-execve logdir. a logdir env var should not. */ bool is_env; if (IS_STRING_OPTION_EMPTY(logdir) && (get_config_val_ex(DYNAMORIO_VAR_LOGDIR, NULL, &is_env) == NULL || is_env)) { /* use same dir as pre-execve! */ sharing_logdir = true; strncpy(logdir, pre_execve, BUFFER_SIZE_ELEMENTS(logdir)); NULL_TERMINATE_BUFFER(logdir); /* if max no null */ logdir_initialized = true; } /* important to remove it, don't want to propagate to forked children */ /* i#909: unsetenv is unsafe as it messes up auxv access, so we disable */ disable_env(DYNAMORIO_VAR_EXECVE_LOGDIR); /* check that it's gone: we've had problems with unsetenv */ ASSERT(getenv(DYNAMORIO_VAR_EXECVE_LOGDIR) == NULL); } #endif /* used to be an else: leaving indentation though */ if (dir_type == BASE_DIR) { int retval; ASSERT(sizeof(basedir) == sizeof(old_basedir)); strncpy(old_basedir, basedir, sizeof(old_basedir)); /* option takes precedence over config var */ if (IS_STRING_OPTION_EMPTY(logdir)) { retval = get_parameter(PARAM_STR(DYNAMORIO_VAR_LOGDIR), basedir, BUFFER_SIZE_ELEMENTS(basedir)); if (IS_GET_PARAMETER_FAILURE(retval)) basedir[0] = '\0'; } else { string_option_read_lock(); strncpy(basedir, DYNAMO_OPTION(logdir), BUFFER_SIZE_ELEMENTS(basedir)); string_option_read_unlock(); } basedir[sizeof(basedir)-1] = '\0'; if (!basedir_initialized || strncmp(old_basedir, basedir, sizeof(basedir))) { /* need to create basedir, is changed or not yet created */ basedir_initialized = true; /* skip creating dir basedir if is empty */ if (basedir[0] == '\0') { #ifndef STATIC_LIBRARY SYSLOG(SYSLOG_WARNING, WARNING_EMPTY_OR_NONEXISTENT_LOGDIR_KEY, 2, get_application_name(), get_application_pid()); #endif } else { if (!os_create_dir(basedir, CREATE_DIR_ALLOW_EXISTING)) { /* try to create full path */ char swap; char *end = double_strchr(basedir, DIRSEP, ALT_DIRSEP); bool res; #ifdef WINDOWS /* skip the drive */ if (end != NULL && end > basedir && *(end - 1) == ':') end = double_strchr(++end, DIRSEP, ALT_DIRSEP); #endif while (end) { swap = *end; *end = '\0'; res = os_create_dir(basedir, CREATE_DIR_ALLOW_EXISTING); *end = swap; end = double_strchr(++end, DIRSEP, ALT_DIRSEP); } res = os_create_dir(basedir, CREATE_DIR_ALLOW_EXISTING); /* check for success */ if (!res) { SYSLOG(SYSLOG_ERROR, ERROR_UNABLE_TO_CREATE_BASEDIR, 3, get_application_name(), get_application_pid(), basedir); /* everything should work out fine, individual log * dirs will also fail to open and just won't be * logged to */ } } } } } /* only create one logging directory (i.e. not dynamic) */ else if (dir_type == PROCESS_DIR && !logdir_initialized) { char *base = basedir; if (!basedir_initialized) { create_log_dir(BASE_DIR); } ASSERT(basedir_initialized); logdir_initialized = true; /* skip creating if basedir is empty */ if (*base != '\0') { if (!get_unique_logfile("", logdir, sizeof(logdir), true, NULL)) { SYSLOG_INTERNAL_WARNING("Unable to create log directory %s", logdir); } } } SELF_PROTECT_DATASEC(DATASEC_RARELY_PROT); release_recursive_lock(&logdir_mutex); #ifdef DEBUG if (stats != NULL) { /* if null, we're trying to report an error (probably via a core dump), * so who cares if we lose logdir name */ strncpy(stats->logdir, logdir, sizeof(stats->logdir)); stats->logdir[sizeof(stats->logdir)-1] = '\0'; /* if max no null */ } if (dir_type == PROCESS_DIR # ifdef UNIX && !sharing_logdir # endif ) SYSLOG_INTERNAL_INFO("log dir=%s", logdir); #endif /* DEBUG */ } /* Copies the name of the specified directory into buffer, returns true if * the specified buffer has been initialized (if it hasn't then no copying is * done). * Will not copy more than *buffer_length bytes and does not ensure null * termination. * buffer can be NULL * buffer_length can be NULL, but only if buffer is NULL * on return (if it is not NULL) *buffer_length will hold the length of the * specified directory's name (including the terminating NULL, i.e. the number * of chars written to the buffer assuming the buffer was not NULL and large * enough) */ bool get_log_dir(log_dir_t dir_type, char *buffer, uint *buffer_length) { bool target_initialized = false; char *target_dir = NULL; ASSERT(buffer == NULL || buffer_length != NULL); acquire_recursive_lock(&logdir_mutex); if (dir_type == BASE_DIR) { target_dir = basedir; target_initialized = basedir_initialized; } else if (dir_type == PROCESS_DIR) { target_dir = logdir; target_initialized = logdir_initialized; } else { /* should never get here */ ASSERT(false); } if (buffer != NULL && target_initialized) { strncpy(buffer, target_dir, *buffer_length); } if (buffer_length != NULL && target_initialized) { ASSERT_TRUNCATE(*buffer_length, uint, strlen(target_dir) + 1); *buffer_length = (uint) strlen(target_dir) + 1; } release_recursive_lock(&logdir_mutex); return target_initialized; } /*#ifdef UNIX * N.B.: if you create a log file, you'll probably want to create a new one * upon a fork. Should we require a callback passed in to this routine? * For clients we have a dynamorio_fork_init routine. For internal modules, * for now make your own fork_init routine. * For closing on fork, since could have many threads with their own files * open, we use our fd_table to close. *#endif */ file_t open_log_file(const char *basename, char *finalname_with_path, uint maxlen) { file_t file; char name[MAXIMUM_PATH]; uint name_size = BUFFER_SIZE_ELEMENTS(name); /* all logfiles are auto-closed on fork; we then make new ones */ uint flags = OS_OPEN_WRITE|OS_OPEN_ALLOW_LARGE|OS_OPEN_CLOSE_ON_FORK; name[0] = '\0'; DODEBUG({ if (INTERNAL_OPTION(log_to_stderr)) return STDERR; }); if (!get_log_dir(PROCESS_DIR, name, &name_size)) { create_log_dir(PROCESS_DIR); if (!get_log_dir(PROCESS_DIR, name, &name_size)) { ASSERT_NOT_REACHED(); } } NULL_TERMINATE_BUFFER(name); /* skip if logdir empty */ if (name[0] == '\0') return INVALID_FILE; snprintf(&name[strlen(name)], BUFFER_SIZE_ELEMENTS(name) - strlen(name), "%c%s.%d."TIDFMT".html", DIRSEP, basename, get_thread_num(get_thread_id()), get_thread_id()); NULL_TERMINATE_BUFFER(name); #ifdef UNIX if (post_execve) /* reuse same log file */ file = os_open_protected(name, flags|OS_OPEN_APPEND); else #endif file = os_open_protected(name, flags|OS_OPEN_REQUIRE_NEW); if (file == INVALID_FILE) { SYSLOG_INTERNAL_WARNING_ONCE("Cannot create log file %s", name); /* everything should work out fine, log statements will just fail to * write since invalid handle */ } /* full path is often too long, so just print final dir and file name */ #ifdef UNIX if (!post_execve) { #endif /* Note that we won't receive a message for the global logfile * since the caller won't have set it yet. However, we will get * all thread log files logged here. */ LOG(GLOBAL, LOG_THREADS, 1, "created log file %d=%s\n", file, double_strrchr(name, DIRSEP, ALT_DIRSEP) + 1); #ifdef UNIX } #endif if (finalname_with_path != NULL) { strncpy(finalname_with_path, name, maxlen); finalname_with_path[maxlen-1] = '\0'; /* if max no null */ } return file; } void close_log_file(file_t f) { os_close_protected(f); } /* Generalize further as needed * Creates a unique file or directory of the form * BASEDIR/[app_name].[pid].<unique num of up to 8 digits>[file_type] * If the filename_buffer is not NULL, the filename of the obtained file * is copied there. For creating a directory the file argument is expected * to be null. Return true if the requested file or directory was created * and, in the case of a file, returns a handle to file in the file argument. */ bool get_unique_logfile(const char *file_type, char *filename_buffer, uint maxlen, bool open_directory, file_t *file) { char buf[MAXIMUM_PATH]; uint size = BUFFER_SIZE_ELEMENTS(buf), counter = 0, base_offset; bool success = false; ASSERT((open_directory && file == NULL) || (!open_directory && file != NULL)); if (!open_directory) *file = INVALID_FILE; create_log_dir(BASE_DIR); if (get_log_dir(BASE_DIR, buf, &size)) { NULL_TERMINATE_BUFFER(buf); ASSERT_TRUNCATE(base_offset, uint, strlen(buf)); base_offset = (uint) strlen(buf); buf[base_offset++] = DIRSEP; size = BUFFER_SIZE_ELEMENTS(buf) - base_offset; do { snprintf(&(buf[base_offset]), size, "%s.%s.%.8d%s", get_app_name_for_path(), get_application_pid(), counter, file_type); NULL_TERMINATE_BUFFER(buf); if (open_directory) { success = os_create_dir(buf, CREATE_DIR_REQUIRE_NEW); } else { *file = os_open(buf, OS_OPEN_REQUIRE_NEW|OS_OPEN_WRITE); success = (*file != INVALID_FILE); } } while (!success && counter++ < 99999999 && os_file_exists(buf, open_directory)); DOLOG(1, LOG_ALL, { if (!success) LOG(GLOBAL, LOG_ALL, 1, "Failed to create unique logfile %s\n", buf); else LOG(GLOBAL, LOG_ALL, 1, "Created unique logfile %s\n", buf); }); } /* copy the filename over if we have a valid buffer */ if (NULL != filename_buffer) { strncpy(filename_buffer, buf, maxlen); filename_buffer[maxlen - 1] = '\0'; /* NULL terminate */ } return success; } const char* get_app_name_for_path() { return get_short_name(get_application_name()); } const char* get_short_name(const char *exename) { const char *exe; exe = double_strrchr(exename, DIRSEP, ALT_DIRSEP); if (exe == NULL) exe = exename; else exe++; /* skip (back)slash */ return exe; } /****************************************************************************/ #ifdef DEBUG # ifdef FRAGMENT_SIZES_STUDY /* to isolate sqrt dependence */ /* given an array of size size of integers, computes and prints the * min, max, mean, and stddev */ void print_statistics(int *data, int size) { int i; int min, max; double mean, stddev, sum; uint top, bottom; const char *sign; /* our context switch does not save & restore floating point state, * so we have to do it here! */ PRESERVE_FLOATING_POINT_STATE_START(); sum = 0.; min = max = data[0]; for (i=0; i<size; i++) { if (data[i] < min) min = data[i]; if (data[i] > max) max = data[i]; sum += data[i]; } mean = sum / (double)size; stddev = 0.; for (i=0; i<size; i++) { double diff = ((double)data[i]) - mean; stddev += diff*diff; } stddev /= (double)size; /* FIXME i#46: We need a private sqrt impl. libc's sqrt can actually * clobber errno, too! */ ASSERT(!DYNAMO_OPTION(early_inject) && "FRAGMENT_SIZES_STUDY incompatible with early injection"); stddev = sqrt(stddev); LOG(GLOBAL, LOG_ALL, 0, "\t# = %9d\n", size); LOG(GLOBAL, LOG_ALL, 0, "\tmin = %9d\n", min); LOG(GLOBAL, LOG_ALL, 0, "\tmax = %9d\n", max); double_print(mean, 1, &top, &bottom, &sign); LOG(GLOBAL, LOG_ALL, 0, "\tmean = %s%7u.%.1u\n", sign, top, bottom); double_print(stddev, 1, &top, &bottom, &sign); LOG(GLOBAL, LOG_ALL, 0, "\tstddev = %s%7u.%.1u\n", sign, top, bottom); PRESERVE_FLOATING_POINT_STATE_END(); } # endif /* FIXME: these should be under ifdef STATS, not necessarily ifdef DEBUG */ void stats_thread_init(dcontext_t *dcontext) { thread_local_statistics_t *new_thread_stats; if (!INTERNAL_OPTION(thread_stats)) return; /* dcontext->thread_stats stays NULL */ new_thread_stats = HEAP_TYPE_ALLOC(dcontext, thread_local_statistics_t, ACCT_STATS, UNPROTECTED); LOG(THREAD, LOG_STATS, 2, "thread_stats="PFX" size=%d\n", new_thread_stats, sizeof(thread_local_statistics_t)); /* initialize any thread stats bookkeeping fields before assigning to dcontext */ memset(new_thread_stats, 0x0, sizeof(thread_local_statistics_t)); new_thread_stats->thread_id = get_thread_id(); ASSIGN_INIT_LOCK_FREE(new_thread_stats->thread_stats_lock, thread_stats_lock); dcontext->thread_stats = new_thread_stats; } void stats_thread_exit(dcontext_t *dcontext) { #ifdef DEBUG /* for non-debug we do fast exit path and don't free local heap */ /* no clean up needed */ if (dcontext->thread_stats) { thread_local_statistics_t *old_thread_stats = dcontext->thread_stats; DELETE_LOCK(old_thread_stats->thread_stats_lock); dcontext->thread_stats = NULL; /* disable thread stats before freeing memory */ HEAP_TYPE_FREE(dcontext, old_thread_stats, thread_local_statistics_t, ACCT_STATS, UNPROTECTED); } #endif } void dump_thread_stats(dcontext_t *dcontext, bool raw) { /* Note that this routine may be called by another thread, but we want the LOGs and the STATs to be for the thread getting dumped Make sure we use the passed dcontext everywhere here. Avoid implicit use of get_thread_private_dcontext (e.g. THREAD_GET). */ /* Each use of THREAD causes cl to make two implicit local variables * (without optimizations on) (culprit is the ? : syntax). Since the * number of locals sums over scopes, this leads to stack usage * of ~3kb for this function due to the many LOGs. * Instead we use THREAD once here and use a local below, cutting stack * usage to 12 bytes, ref bug 2203 */ file_t logfile = THREAD; if (!THREAD_STATS_ON(dcontext)) return; /* FIXME: for now we'll have code duplication with dump_global_stats() * with the only difference being THREAD vs GLOBAL, e.g. LOG(GLOBAL and GLOBAL_STAT * Keep in sync or make a template statistics dump macro for both cases. */ LOG(logfile, LOG_STATS, 1, "(Begin) Thread statistics @%d global, %d thread fragments ", GLOBAL_STAT(num_fragments), THREAD_STAT(dcontext, num_fragments)); DOLOG(1, LOG_STATS, { print_timestamp(logfile); }); /* give up right away if thread stats lock already held, will dump next time most likely thread interrupted while dumping state */ if (!mutex_trylock(&dcontext->thread_stats->thread_stats_lock)) { LOG(logfile, LOG_STATS, 1, " WARNING: skipped! Another dump in progress.\n"); return; } LOG(logfile, LOG_STATS, 1, ":\n"); #define STATS_DEF(desc, stat) if (THREAD_STAT(dcontext, stat)) { \ if (raw) { \ LOG(logfile, LOG_STATS, 1, "\t%s\t= "SSZFMT"\n", \ #stat, THREAD_STAT(dcontext, stat)); \ } else { \ LOG(logfile, LOG_STATS, 1, "%50s %s:"IF_X64_ELSE("%18","%9") \ SSZFC"\n", desc, "(thread)", THREAD_STAT(dcontext, stat)); \ } \ } # include "statsx.h" #undef STATS_DEF LOG(logfile, LOG_STATS, 1, "(End) Thread statistics\n"); mutex_unlock(&dcontext->thread_stats->thread_stats_lock); /* TODO: update thread statistics, using the thread stats delta when implemented */ #ifdef KSTATS dump_thread_kstats(dcontext); #endif } void dump_global_stats(bool raw) { DOLOG(1, LOG_MEMSTATS, { if (!dynamo_exited_and_cleaned) mem_stats_snapshot(); }); if (!dynamo_exited_and_cleaned) print_vmm_heap_data(GLOBAL); if (GLOBAL_STATS_ON()) { LOG(GLOBAL, LOG_STATS, 1, "(Begin) All statistics @%d ", GLOBAL_STAT(num_fragments)); DOLOG(1, LOG_STATS, { print_timestamp(GLOBAL); }); LOG(GLOBAL, LOG_STATS, 1, ":\n"); #define STATS_DEF(desc, stat) if (GLOBAL_STAT(stat)) { \ if (raw) { \ LOG(GLOBAL, LOG_STATS, 1, "\t%s\t= "SSZFMT"\n", #stat, GLOBAL_STAT(stat)); \ } else { \ LOG(GLOBAL, LOG_STATS, 1, "%50s :"IF_X64_ELSE("%18","%9")SSZFC \ "\n", desc, GLOBAL_STAT(stat)); \ } \ } # include "statsx.h" #undef STATS_DEF LOG(GLOBAL, LOG_STATS, 1, "(End) All statistics\n"); } #ifdef HEAP_ACCOUNTING DOLOG(1, LOG_HEAP|LOG_STATS, { print_heap_statistics(); }); #endif DOLOG(1, LOG_CACHE, { /* shared cache stats */ fcache_stats_exit(); }); #ifdef SHARING_STUDY DOLOG(1, LOG_ALL, { if (INTERNAL_OPTION(fragment_sharing_study) && !dynamo_exited) print_shared_stats(); }); #endif # ifdef DEADLOCK_AVOIDANCE dump_process_locks(); # endif } uint print_timestamp_to_buffer(char *buffer, size_t len) { uint min, sec, msec; size_t print_len = MIN(len, PRINT_TIMESTAMP_MAX_LENGTH); static uint64 initial_time = 0ULL; /* in milliseconds */ uint64 current_time; if (initial_time == 0ULL) initial_time = query_time_millis(); current_time = query_time_millis(); if (current_time == 0ULL) /* call failed */ return 0; current_time -= initial_time; /* elapsed */ sec = (uint) (current_time / 1000); msec = (uint) (current_time % 1000); min = sec / 60; sec = sec % 60; return our_snprintf(buffer, print_len, "(%ld:%02ld.%03ld)", min, sec, msec); } /* prints elapsed time since program startup to the given logfile * TODO: should also print absolute timestamp * TODO: and relative time from thread start */ uint print_timestamp(file_t logfile) { char buffer[PRINT_TIMESTAMP_MAX_LENGTH]; uint len = print_timestamp_to_buffer(buffer, PRINT_TIMESTAMP_MAX_LENGTH); if (len > 0) print_file(logfile, buffer); return len; } #endif /* DEBUG */ void dump_global_rstats_to_stderr(void) { if (GLOBAL_STATS_ON()) { print_file(STDERR, "%s statistics:\n", PRODUCT_NAME); #undef RSTATS_DEF /* It doesn't make sense to print Current stats. We assume no rstat starts * with "Cu". */ #define RSTATS_DEF(desc, stat) \ if (GLOBAL_STAT(stat) && (desc[0] != 'C' || desc[1] != 'u')) { \ print_file(STDERR, "%50s :"IF_X64_ELSE("%18","%9")SSZFC \ "\n", desc, GLOBAL_STAT(stat)); \ } #define RSTATS_ONLY #include "statsx.h" #undef RSTATS_ONLY #undef RSTATS_DEF } } static void dump_buffer_as_ascii(file_t logfile, char *buffer, size_t len) { size_t i; for (i = 0; i < len; i++) { print_file(logfile, "%c", isprint_fast(buffer[i]) ? buffer[i] : '.'); } } void dump_buffer_as_bytes (file_t logfile, void *buffer, size_t len, int flags) { bool octal = TEST(DUMP_OCTAL, flags); bool raw = TEST(DUMP_RAW, flags); bool usechars = !raw && !TEST(DUMP_NO_CHARS, flags); bool replayable = usechars && !TEST(DUMP_NO_QUOTING, flags); bool dword = TEST(DUMP_DWORD, flags); bool prepend_address = TEST(DUMP_ADDRESS, flags); bool append_ascii = TEST(DUMP_APPEND_ASCII, flags); unsigned char *buf = (unsigned char*) buffer; int per_line = (flags & DUMP_PER_LINE) ? (flags & DUMP_PER_LINE) : DUMP_PER_LINE_DEFAULT; size_t i; int nonprint = 0; size_t line_start = 0; if (!raw) print_file(logfile, "%s", "\""); for (i=0; i + (dword ? 4 : 1) <= len; i += (dword ? 4 : 1)) { if (i > 0 && 0 == i % per_line) { if (append_ascii) { print_file(logfile, "%s", " "); /* append current line as ASCII */ ASSERT(line_start == (i - per_line)); dump_buffer_as_ascii(logfile, (char *)buf + line_start, per_line); line_start = i; } /* new line */ print_file(logfile, "%s", raw ? "\n" : "\"\n\""); } if (prepend_address && 0 == i % per_line) // prepend address on new line print_file(logfile, PFX" ", buf+i); if (replayable) { if (isdigit_fast(buf[i]) && nonprint) { print_file(logfile, "%s", "\"\""); // to make \01 into \0""1 } if (buf[i] == '"') { print_file(logfile, "%s", "\\\""); continue; } if (buf[i] == '\\') print_file(logfile, "%s", "\\"); } if (usechars && isprint_fast(buf[i])) { print_file(logfile, "%c", buf[i]); nonprint = 0; } else { if (!raw) { print_file(logfile, "%s", octal ? "\\" : "\\x"); } if (dword) print_file(logfile, "%08x", *((uint*)(buf+i))); else print_file(logfile, octal ? "%03o" : "%02x", buf[i]); nonprint = 1; if (raw) { print_file(logfile, "%s", " "); } } } if (append_ascii) { /* append last line as ASCII */ /* pad to align columns */ size_t empty = ALIGN_FORWARD(buf + len, per_line); uint size = (dword ? 4 : 1); /* In general we expect dword requests to be dword aligned but * we don't enforce it. Note that we don't print DWORDs that * may extend beyond valid len, but we'll print as ASCII any * bytes included in valid len even if not printed in hex. */ for (i = ALIGN_BACKWARD(buf + len, size); i < empty; i += size) { if (dword) { print_file(logfile, "%8c ", ' '); } else { print_file(logfile, octal ? "%3c " : "%2c ", ' '); } } print_file(logfile, "%s", " "); dump_buffer_as_ascii(logfile, (char *)buf + line_start, len - line_start); } if (!raw) print_file(logfile, "%s", "\";\n"); } /******************************************************************************/ /* xml escaping routines, presumes iso-8859-1 encoding */ bool is_valid_xml_char(char c) { /* FIXME - wld.exe xml parsing complains about any C0 control character other * then \t \r and \n. However, in this encoding (to my understanding) all values * should be valid and IE doesn't complain opening an xml file in this encoding * with these characters. Not sure where the wld.exe problem lies, but since it is * our primary consumer we work around here. */ if ((uchar)c < 0x20 && c != '\t' && c != '\n' && c != '\r') { return false; } return true; } static bool is_valid_xml_string(const char *str) { while (*str != '\0') { if (!is_valid_xml_char(*str)) return false; str++; } return true; } /* NOTE - string should not include the <![CDATA[ ]]> markup as one thing * this routine checks for is an inadvertant ending sequence ]]>. Caller is * responsible for correct markup. */ static bool is_valid_xml_cdata_string(const char *str) { /* check for end CDATA tag */ /* FIXME - optimization,combine the two walks of the string into a * single walk.*/ return (strstr(str, "]]>") == NULL && is_valid_xml_string(str)) ; } #if 0 /* Not yet used */ static bool is_valid_xml_body_string(const char *str) { /* check for & < > */ /* FIXME - optimization, combine into a single walk of the string. */ return (strchr(str, '>') == NULL && strchr(str, '<') == NULL && strchr(str, '&') == NULL && is_valid_xml_string(str)); } static bool is_valid_xml_attribute_string(const char *str) { /* check for & < > ' " */ /* FIXME - optimization, combine into a single walk of the string. */ return (strchr(str, '\'') == NULL && strchr(str, '\"') == NULL && is_valid_xml_body_string(str)); } #endif /* NOTE - string should not include the <![CDATA[ ]]> markup as one thing * this routine checks for is an inadvertant ending sequence ]]> (in which * case the first ] will be escaped). We escape using \%03d, note that since * we don't escape \ , '\003' and "\003" will be indistinguishable (FIXME), * but given that these should really be normal ascii strings we'll live with * that. */ void print_xml_cdata(file_t f, const char *str) { if (is_valid_xml_cdata_string(str)) { print_file(f, "%s", str); } else { while (*str != '\0') { if (!is_valid_xml_char(*str) || (*str == ']' && *(str+1) == ']' && *(str+2) == '>')) { print_file(f, "\\%03d", (int)*(uchar *)str); } else { /* FIXME : could batch up printing normal chars for perf. * but we usually expect to have valid strings anyways. */ print_file(f, "%c", *str); } str++; } } } /* TODO - NYI print_xml_body_string, print_xml_attribute_string */ void print_version_and_app_info(file_t file) { print_file(file, "%s\n", dynamorio_version_string); /* print qualified name (not stats->process_name) to get cmdline */ print_file(file, "Running: %s\n", get_application_name()); #ifdef WINDOWS /* FIXME: also get linux cmdline -- separate since wide on win32 */ print_file(file, "App cmdline: %S\n", get_application_cmdline()); #endif print_file(file, PRODUCT_NAME" built with: %s\n", DYNAMORIO_DEFINES); print_file(file, PRODUCT_NAME" built on: %s\n", dynamorio_buildmark); #ifndef _WIN32_WCE print_file(file, DYNAMORIO_VAR_OPTIONS": %s\n", option_string); #endif } void utils_exit() { LOG(GLOBAL, LOG_STATS, 1, "-prng_seed "PFX" for reproducing random sequence\n", initial_random_seed); DELETE_LOCK(report_buf_lock); DELETE_RECURSIVE_LOCK(logdir_mutex); DELETE_LOCK(prng_lock); #ifdef DEADLOCK_AVOIDANCE DELETE_LOCK(do_threshold_mutex); #endif spinlock_count = 0; } /* returns a pseudo random number in [0, max_offset) */ /* FIXME: [minor security] while the first user may get more * randomness from the lower bits of the seed, I am not sure the * following users should strongly prefer higher or lower bits. */ size_t get_random_offset(size_t max_offset) { /* These linear congruential constants taken from * http://remus.rutgers.edu/~rhoads/Code/random.c * FIXME: Look up Knuth's recommendations in vol. 2 */ enum { LCM_A = 279470273, LCM_Q = 15, LCM_R = 102913196 }; /* I prefer not risking any of the randomness in our seed to go * through the fishy LCM and value generation - it doesn't buy us * anything for the first instance which is all we currently use. * Calculating value based on the previous seed also removes * dependencies from the critical path and will be faster if we * use this on a critical path.. */ size_t value; /* Avoids div-by-zero if offset is 0; see case 8602 for implications. */ if (max_offset == 0) return 0; /* process-shared random sequence */ mutex_lock(&prng_lock); /* FIXME: this is not getting the best randomness * see srand() comments why taking higher order bits is usually better * j=1+(int) (10.0*rand()/(RAND_MAX+1.0)); * but I want to do it without floating point */ value = random_seed % max_offset; random_seed = LCM_A*(random_seed % LCM_Q) - LCM_R*(random_seed / LCM_Q); mutex_unlock(&prng_lock); LOG(GLOBAL, LOG_ALL, 2, "get_random_offset: value=%d (mod %d), new rs=%d\n", value, max_offset, random_seed); return value; } void set_random_seed(uint seed) { random_seed = seed; } uint get_random_seed(void) { return random_seed; } /* millis is the number of milliseconds since Jan 1, 1601 (this is * the current UTC time). */ void convert_millis_to_date(uint64 millis, dr_time_t *dr_time OUT) { uint64 time = millis; uint days, year, month, q; #define DAYS_IN_400_YEARS (400 * 365 + 97) dr_time->milliseconds = (uint)(time % 1000); time /= 1000; dr_time->second = (uint)(time % 60); time /= 60; dr_time->minute = (uint)(time % 60); time /= 60; dr_time->hour = (uint)(time % 24); time /= 24; /* Time is now number of days since 1 Jan 1601 (Gregorian). * We rebase to 1 Mar 1600 (Gregorian) as this day immediately * follows the irregular element in each cycle: 12-month cycle, * 4-year cycle, 100-year cycle, 400-year cycle. * Noon, 1 Jan 1601 is the start of Julian Day 2305814. * Noon, 1 Mar 1600 is the start of Julian Day 2305508. */ time += 2305814 - 2305508; /* Reduce modulo 400 years, which gets us into the range of a uint. */ year = 1600 + (uint)(time / DAYS_IN_400_YEARS) * 400; days = (uint)(time % DAYS_IN_400_YEARS); /* The constants used in the rest of this function are difficult to * get right, but the number of days in 400 years is small enough for * us to test this code exhaustively, which we will, of course, do. */ /* Sunday is 0, Monday is 1, ... 1 Mar 1600 was Wednesday. */ dr_time->day_of_week = (days + 3) % 7; /* Determine century: divide by average number of days in a century, * 36524.25 = 146097 / 4, rounding up because the long century comes last. */ q = (days * 4 + 3) / 146097; year += q * 100; days -= q * 146097 / 4; /* Determine year: divide by average number of days in a year, * 365.25 = 1461 / 4, rounding up because the long year comes last. * The average is 365.25 because we ignore the irregular year at the * end of the century, which we can safely do because it is shorter. */ q = (days * 4 + 3) / 1461; year += q; days -= q * 1461 / 4; /* Determine month: divide by (31 + 30 + 31 + 30 + 31) / 5, with carefully tuned * rounding to get the consecutive 31-day months in the right place. This works * because the number of days in a month follows a cycle, starting in March: * 31, 30, 31, 30, 31; 31, 30, 31, 30, 31; 31, ... This is followed by Februrary, * of course, but that is not a problem because it is shorter rather than longer * than expected. The values "2" and "2" are easiest to determine experimentally. */ month = (days * 5 + 2) / 153; days -= (month * 153 + 2) / 5; /* Adjust for calendar year starting in January rather than March. */ dr_time->day = days + 1; dr_time->month = month < 10 ? month + 3 : month - 9; dr_time->year = month < 10 ? year : year + 1; } /* millis is the number of milliseconds since Jan 1, 1601 (this is * the current UTC time). */ void convert_date_to_millis(const dr_time_t *dr_time, uint64 *millis OUT) { /* Formula adapted from http://en.wikipedia.org/wiki/Julian_day. * We rebase the input year from -4800 to +1600, and we rebase * the output day from from 1 Mar -4800 (Gregorian) to 1 Jan 1601. * Noon, 1 Mar 1600 (Gregorian) is the start of Julian Day 2305508. * Noon, 1 Mar -4800 (Gregorian) is the start of Julian Day -32044. * Noon, 1 Jan 1601 (Gregorian) is the start of Julian Day 2305814. */ uint a = dr_time->month < 3 ? 1 : 0; uint y = dr_time->year - a - 1600; uint m = dr_time->month + 12 * a - 3; uint64 days = ((dr_time->day + (153 * m + 2) / 5 + y / 4 - y / 100 + y / 400) + 365 * (uint64)y - 32045 + 2305508 + 32044 - 2305814); *millis = ((((days * 24 + dr_time->hour) * 60 + dr_time->minute) * 60 + dr_time->second) * 1000 + dr_time->milliseconds); } static const uint crctab[] = { 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d }; /* This function implements the Ethernet AUTODIN II CRC32 algorithm. */ uint crc32(const char *buf, const uint len) { uint i; uint crc = 0xFFFFFFFF; for (i = 0; i < len; i++) crc = (crc >> 8) ^ crctab[(crc ^ buf[i]) & 0xFF]; return crc; } /* MD5 is used for persistent and process-shared caches, process_control, and * ASLR persistent sharing. The definition of MD5 below has a public * license; source: http://stuff.mit.edu/afs/sipb/user/kenta/lj/clive/clive-0.4.5/ */ /*----------------------------------------------------------------------------*/ /* This code implements the MD5 message-digest algorithm. * The algorithm is due to Ron Rivest. This code was * written by Colin Plumb in 1993, no copyright is claimed. * This code is in the public domain; do with it what you wish. * * Equivalent code is available from RSA Data Security, Inc. * This code has been tested against that, and is equivalent, * except that you don't need to include two pages of legalese * with every copy. * * To compute the message digest of a chunk of bytes, declare an * MD5Context structure, pass it to MD5Init, call MD5Update as * needed on buffers full of bytes, and then call MD5Final, which * will fill a supplied 16-byte array with the digest. */ static void MD5Transform(uint32 state[4], const unsigned char block[MD5_BLOCK_LENGTH]); #define PUT_64BIT_LE(cp, value) do { \ (cp)[7] = (unsigned char)((value) >> 56); \ (cp)[6] = (unsigned char)((value) >> 48); \ (cp)[5] = (unsigned char)((value) >> 40); \ (cp)[4] = (unsigned char)((value) >> 32); \ (cp)[3] = (unsigned char)((value) >> 24); \ (cp)[2] = (unsigned char)((value) >> 16); \ (cp)[1] = (unsigned char)((value) >> 8); \ (cp)[0] = (unsigned char)(value); } while (0) #define PUT_32BIT_LE(cp, value) do { \ (cp)[3] = (unsigned char)((value) >> 24); \ (cp)[2] = (unsigned char)((value) >> 16); \ (cp)[1] = (unsigned char)((value) >> 8); \ (cp)[0] = (unsigned char)(value); } while (0) static unsigned char PADDING[MD5_BLOCK_LENGTH] = { 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; /* * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious * initialization constants. */ void MD5Init(struct MD5Context *ctx) { ctx->count = 0; ctx->state[0] = 0x67452301; ctx->state[1] = 0xefcdab89; ctx->state[2] = 0x98badcfe; ctx->state[3] = 0x10325476; } /* * Update context to reflect the concatenation of another buffer full * of bytes. */ void MD5Update(struct MD5Context *ctx, const unsigned char *input, size_t len) { size_t have, need; /* Check how many bytes we already have and how many more we need. */ have = (size_t)((ctx->count >> 3) & (MD5_BLOCK_LENGTH - 1)); need = MD5_BLOCK_LENGTH - have; /* Update bitcount */ ctx->count += (uint64)len << 3; if (len >= need) { if (have != 0) { memcpy(ctx->buffer + have, input, need); MD5Transform(ctx->state, ctx->buffer); input += need; len -= need; have = 0; } /* Process data in MD5_BLOCK_LENGTH-byte chunks. */ while (len >= MD5_BLOCK_LENGTH) { MD5Transform(ctx->state, input); input += MD5_BLOCK_LENGTH; len -= MD5_BLOCK_LENGTH; } } /* Handle any remaining bytes of data. */ if (len != 0) memcpy(ctx->buffer + have, input, len); } /* * Pad pad to 64-byte boundary with the bit pattern * 1 0* (64-bit count of bits processed, MSB-first) */ static void MD5Pad(struct MD5Context *ctx) { unsigned char count[8]; size_t padlen; /* Convert count to 8 bytes in little endian order. */ PUT_64BIT_LE(count, ctx->count); /* Pad out to 56 mod 64. */ padlen = (size_t) (MD5_BLOCK_LENGTH - ((ctx->count >> 3) & (MD5_BLOCK_LENGTH - 1))); if (padlen < 1 + 8) padlen += MD5_BLOCK_LENGTH; MD5Update(ctx, PADDING, padlen - 8); /* padlen - 8 <= 64 */ MD5Update(ctx, count, 8); } /* * Final wrapup--call MD5Pad, fill in digest and zero out ctx. */ void MD5Final(unsigned char digest[MD5_RAW_BYTES], struct MD5Context *ctx) { int i; MD5Pad(ctx); if (digest != NULL) { for (i = 0; i < 4; i++) PUT_32BIT_LE(digest + i * 4, ctx->state[i]); } memset(ctx, 0, sizeof(*ctx)); /* in case it's sensitive */ } /* The four core functions - F1 is optimized somewhat */ /* #define F1(x, y, z) (x & y | ~x & z) */ #define F1(x, y, z) (z ^ (x & (y ^ z))) #define F2(x, y, z) F1(z, x, y) #define F3(x, y, z) (x ^ y ^ z) #define F4(x, y, z) (y ^ (x | ~z)) /* This is the central step in the MD5 algorithm. */ #define MD5STEP(f, w, x, y, z, data, s) \ ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x ) /* * The core of the MD5 algorithm, this alters an existing MD5 hash to * reflect the addition of 16 longwords of new data. MD5Update blocks * the data and converts bytes into longwords for this routine. */ static void MD5Transform(uint32 state[4], const unsigned char block[MD5_BLOCK_LENGTH]) { uint32 a, b, c, d, in[MD5_BLOCK_LENGTH / 4]; #if BYTE_ORDER == LITTLE_ENDIAN memcpy(in, block, sizeof(in)); #else for (a = 0; a < MD5_BLOCK_LENGTH / 4; a++) { in[a] = (uint32) ((uint32)(block[a * 4 + 0]) | (uint32)(block[a * 4 + 1]) << 8 | (uint32)(block[a * 4 + 2]) << 16 | (uint32)(block[a * 4 + 3]) << 24); } #endif a = state[0]; b = state[1]; c = state[2]; d = state[3]; MD5STEP(F1, a, b, c, d, in[ 0] + 0xd76aa478, 7); MD5STEP(F1, d, a, b, c, in[ 1] + 0xe8c7b756, 12); MD5STEP(F1, c, d, a, b, in[ 2] + 0x242070db, 17); MD5STEP(F1, b, c, d, a, in[ 3] + 0xc1bdceee, 22); MD5STEP(F1, a, b, c, d, in[ 4] + 0xf57c0faf, 7); MD5STEP(F1, d, a, b, c, in[ 5] + 0x4787c62a, 12); MD5STEP(F1, c, d, a, b, in[ 6] + 0xa8304613, 17); MD5STEP(F1, b, c, d, a, in[ 7] + 0xfd469501, 22); MD5STEP(F1, a, b, c, d, in[ 8] + 0x698098d8, 7); MD5STEP(F1, d, a, b, c, in[ 9] + 0x8b44f7af, 12); MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17); MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22); MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7); MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12); MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17); MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22); MD5STEP(F2, a, b, c, d, in[ 1] + 0xf61e2562, 5); MD5STEP(F2, d, a, b, c, in[ 6] + 0xc040b340, 9); MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14); MD5STEP(F2, b, c, d, a, in[ 0] + 0xe9b6c7aa, 20); MD5STEP(F2, a, b, c, d, in[ 5] + 0xd62f105d, 5); MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9); MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14); MD5STEP(F2, b, c, d, a, in[ 4] + 0xe7d3fbc8, 20); MD5STEP(F2, a, b, c, d, in[ 9] + 0x21e1cde6, 5); MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9); MD5STEP(F2, c, d, a, b, in[ 3] + 0xf4d50d87, 14); MD5STEP(F2, b, c, d, a, in[ 8] + 0x455a14ed, 20); MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5); MD5STEP(F2, d, a, b, c, in[ 2] + 0xfcefa3f8, 9); MD5STEP(F2, c, d, a, b, in[ 7] + 0x676f02d9, 14); MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20); MD5STEP(F3, a, b, c, d, in[ 5] + 0xfffa3942, 4); MD5STEP(F3, d, a, b, c, in[ 8] + 0x8771f681, 11); MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16); MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23); MD5STEP(F3, a, b, c, d, in[ 1] + 0xa4beea44, 4); MD5STEP(F3, d, a, b, c, in[ 4] + 0x4bdecfa9, 11); MD5STEP(F3, c, d, a, b, in[ 7] + 0xf6bb4b60, 16); MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23); MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4); MD5STEP(F3, d, a, b, c, in[ 0] + 0xeaa127fa, 11); MD5STEP(F3, c, d, a, b, in[ 3] + 0xd4ef3085, 16); MD5STEP(F3, b, c, d, a, in[ 6] + 0x04881d05, 23); MD5STEP(F3, a, b, c, d, in[ 9] + 0xd9d4d039, 4); MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11); MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16); MD5STEP(F3, b, c, d, a, in[2 ] + 0xc4ac5665, 23); MD5STEP(F4, a, b, c, d, in[ 0] + 0xf4292244, 6); MD5STEP(F4, d, a, b, c, in[7 ] + 0x432aff97, 10); MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15); MD5STEP(F4, b, c, d, a, in[5 ] + 0xfc93a039, 21); MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6); MD5STEP(F4, d, a, b, c, in[3 ] + 0x8f0ccc92, 10); MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15); MD5STEP(F4, b, c, d, a, in[1 ] + 0x85845dd1, 21); MD5STEP(F4, a, b, c, d, in[8 ] + 0x6fa87e4f, 6); MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10); MD5STEP(F4, c, d, a, b, in[6 ] + 0xa3014314, 15); MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21); MD5STEP(F4, a, b, c, d, in[4 ] + 0xf7537e82, 6); MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10); MD5STEP(F4, c, d, a, b, in[2 ] + 0x2ad7d2bb, 15); MD5STEP(F4, b, c, d, a, in[9 ] + 0xeb86d391, 21); state[0] += a; state[1] += b; state[2] += c; state[3] += d; } #undef F1 #undef F2 #undef F3 #undef F4 #undef MD5STEP /*----------------------------------------------------------------------------*/ bool module_digests_equal(const module_digest_t *calculated_digest, const module_digest_t *matching_digest, bool check_short, bool check_full) { bool match = true; if (check_short) { match = match && md5_digests_equal(calculated_digest->short_MD5, matching_digest->short_MD5); } if (check_full) { match = match && md5_digests_equal(calculated_digest->full_MD5, matching_digest->full_MD5); } return match; } /* Reads the full file, returns it in a buffer and sets buf_len to the size * of the buffer allocated on the specified heap, if successful. Returns NULL * and sets buf_len to 0 on failure. Defined when fixing case 8187. */ char * read_entire_file(const char *file, size_t *buf_len /* OUT */ HEAPACCT(which_heap_t heap)) { ssize_t bytes_read; file_t fd = INVALID_FILE; char *buf = NULL; uint64 buf_len64 = 0; /* No point in reading the file if the length can't be returned - the caller * won't be able to free the buffer without the size. */ if (file == NULL || buf_len == NULL) return NULL; *buf_len = 0; fd = os_open((char *)file, OS_OPEN_READ); if (fd == INVALID_FILE ) return NULL; if (!os_get_file_size(file, &buf_len64)) { os_close(fd); return NULL; } ASSERT_TRUNCATE(*buf_len, uint, buf_len64); /* Though only 1 byte is needed for the \0 at the end of the buffer, * 4 may be allocated to work around case 8048. FIXME: remove * alignment after case is resolved. */ *buf_len = (uint) ALIGN_FORWARD((buf_len64 + 1), 4); buf = (char *) heap_alloc(GLOBAL_DCONTEXT, *buf_len HEAPACCT(heap)); bytes_read = os_read(fd, buf, *buf_len); if (bytes_read <= 0) { heap_free(GLOBAL_DCONTEXT, buf, *buf_len HEAPACCT(heap)); os_close(fd); return NULL; } ASSERT(CHECK_TRUNCATE_TYPE_uint(bytes_read)); ASSERT((uint)bytes_read != *buf_len && "buffer too small"); ASSERT((uint)bytes_read < *buf_len); /* use MIN below just to be safe */ buf[MIN((uint)bytes_read, *buf_len - 1)] = 0; os_close(fd); return buf; } /* returns false if we are too low on disk to create a file of desired size */ bool check_low_disk_threshold(file_t f, uint64 new_file_size) { /* FIXME: we only use UserAvailable to find the minimum expressed * as absolute bytes to leave available. In addition we could * also have percentage limits, where minimum available should be * based on TotalQuotaBytes, and maximum cache size on * TotalVolumeBytes. */ uint64 user_available_bytes; /* FIXME: does this work for compressed volumes? */ bool ok = os_get_disk_free_space(f, &user_available_bytes, NULL, NULL); if (ok) { LOG(THREAD_GET, LOG_SYSCALLS|LOG_THREADS, 2, "available disk space quota %dMB\n", user_available_bytes/1024/1024); /* note that the actual needed bytes are in fact aligned to a * cluster, so this is somewhat imprecise */ ok = (user_available_bytes > new_file_size) && (user_available_bytes - new_file_size) > DYNAMO_OPTION(min_free_disk); if (!ok) { /* FIXME: notify the customer that they are low on disk space? */ SYSLOG_INTERNAL_WARNING_ONCE("reached minimal free disk space limit," " available "UINT64_FORMAT_STRING "MB, limit %dMB, " "asking for "UINT64_FORMAT_STRING"KB", user_available_bytes/1024/1024, DYNAMO_OPTION(min_free_disk)/1024/1024, new_file_size/1024); /* ONCE, even though later we may succeed and start failing again */ } } else { /* impersonated thread may not have rights to even query */ /* or we have an invalid path */ /* do nothing */ LOG(THREAD_GET, LOG_SYSCALLS|LOG_THREADS, 2, "unable to retrieve available disk space\n"); } return ok; } #ifdef PROCESS_CONTROL /* currently used for only for this; need not be so */ /* Note: Reading the full file in one shot will cause committed memory and * wss to shoot up. Even if this memory is freed, only wss will come down. * While this may be ok for fcache mode, it is probably not for hotp_only mode, * and definitely not for thin_client mode. The main use of thin_client today * is process_control, which means that MD5 will be computed in thin_client * mode. * * The options for this memory issue are to mmap the memory and unmap it after * use rather than use the heap or to use a moderate sized buffer and read the * file in chunks, which is wat I have chosen. If startup performance becomes * a problem because of this play with bigger pages or just use mmap and munmap. * * Measurements on my laptop on a total of 5076 executables showed, * Average size : 233 kb * Standard deviation : 684 kb * Median size : 68 kb! * 80% percentile : 205 kb * 90% percentile : 469 kb * So a buffer of 16 kb seems reasonable, even though the data is not based * on frequency of usage. * * FIXME: use nt_map_view_of_section with SEC_MAPPED && !SEC_IMAGE. */ #define MD5_FILE_READ_BUF_SIZE (4 * PAGE_SIZE) /* Reads 'file', computes MD5 hash for it, which is returned in hash_buf * when successful and true is returned. On failure false is returned and * hash_buf contents invalid. * Note: Reads in file in 16k chunks to avoid private/committed memory * increase. */ bool get_md5_for_file(const char *file, char *hash_buf /* OUT */) { ssize_t bytes_read; int i; file_t fd; char *file_buf; struct MD5Context md5_cxt; unsigned char md5_buf[MD5_STRING_LENGTH/2]; if (file == NULL || hash_buf == NULL) return false; fd = os_open((char *)file, OS_OPEN_READ); if (fd == INVALID_FILE) return false; MD5Init(&md5_cxt); file_buf = (char *) heap_alloc(GLOBAL_DCONTEXT, MD5_FILE_READ_BUF_SIZE HEAPACCT(ACCT_OTHER)); while ((bytes_read = os_read(fd, file_buf, MD5_FILE_READ_BUF_SIZE)) > 0) { ASSERT(CHECK_TRUNCATE_TYPE_uint(bytes_read)); MD5Update(&md5_cxt, (byte *) file_buf, (uint)bytes_read); } MD5Final(md5_buf, &md5_cxt); /* Convert 16-byte signature into 32-byte string, which is how MD5 is * usually printed/used. n is 3, 2 for chars & 1 for the '\0'; */ for (i = 0; i < BUFFER_SIZE_ELEMENTS(md5_buf); i++) snprintf(hash_buf + (i * 2), 3, "%02X", md5_buf[i]); /* Just be safe & terminate the buffer; assuming it has 33 chars! */ hash_buf[MD5_STRING_LENGTH] = '\0'; heap_free(GLOBAL_DCONTEXT, file_buf, MD5_FILE_READ_BUF_SIZE HEAPACCT(ACCT_OTHER)); os_close(fd); return true; } #endif /* PROCESS_CONTROL */ /* Computes and caches MD5 for the application if it isn't there; returns it. */ /* Note: this function isn't under PROCESS_CONTROL even though that is what * uses this because md5 for the executable may be needed in future. * Also, this avoids having to define 2 types of process start events. * Further, if we decide to remove process control in future leaving the * md5 in the start event will prevent needless backward compatibility * problems caused by removing md5 from it. */ const char * get_application_md5(void) { /* Though exe_md5 is used in the process start event, it is currently set * only by process_control. BTW, 1 for the terminating '\0'. */ static char exe_md5[MD5_STRING_LENGTH + 1] = {0}; #ifdef PROCESS_CONTROL /* MD5 is computed only if process control is turned on, otherwise the cost * isn't paid (roughly 10ms for a 350kb exe), i.e. "" is returned. */ if (exe_md5[0] == '\0') { if (IS_PROCESS_CONTROL_ON()) { DEBUG_DECLARE(bool res;) # ifdef WINDOWS /* FIXME - inefficient, we use stack buffer here to convert wchar to char, * and later we'll use another stack buffer to convert char to wchar to * open the file. That said this is only done once (either at startup or * for process_control nudge [app_stack]) so as long as the stack doesn't * overflow it doesn't really matter. */ char exe_name[MAXIMUM_PATH]; snprintf(exe_name, BUFFER_SIZE_ELEMENTS(exe_name), "%ls", get_own_unqualified_name()); NULL_TERMINATE_BUFFER(exe_name); # else /* FIXME - will need to strip out qualifications if we add those to Linux */ const char *exe_name = get_application_name(); # endif /* Change protection to make .data writable; this is a nop at init * time - which is the most common case. For the nudge case we * will pay full price of data protection if MD5 hasn't been * computed yet; this is rare, so it is ok. */ SELF_UNPROTECT_DATASEC(DATASEC_RARELY_PROT); DEBUG_DECLARE(res = ) get_md5_for_file(exe_name, exe_md5); ASSERT(res && strlen(exe_md5) == MD5_STRING_LENGTH); NULL_TERMINATE_BUFFER(exe_md5); /* just be safe */ SELF_PROTECT_DATASEC(DATASEC_RARELY_PROT); /* restore protection */ } } else { /* If it isn't null then it must be a full MD5 and process control * should be turned on. */ ASSERT(strlen(exe_md5) == MD5_STRING_LENGTH); ASSERT(IS_PROCESS_CONTROL_ON()); } #else /* If there is no process control, for now, app MD5 isn't computed. */ ASSERT(exe_md5[0] == '\0'); #endif return exe_md5; } /* Producing a single MD5 digest for a given readable memory region. * * An empty region is not expected, though legal, since produces a * constant value. */ void get_md5_for_region(const byte *region_start, uint len, unsigned char digest[MD5_RAW_BYTES] /* OUT */) { struct MD5Context md5_cxt; MD5Init(&md5_cxt); ASSERT(region_start != NULL); ASSERT_CURIOSITY(len != 0); if (region_start != NULL && len != 0) MD5Update(&md5_cxt, region_start, len); MD5Final(digest, &md5_cxt); ASSERT_NOT_TESTED(); } bool md5_digests_equal(const byte digest1[MD5_RAW_BYTES], const byte digest2[MD5_RAW_BYTES]) { return (memcmp(digest1, digest2, MD5_RAW_BYTES) == 0); } /* calculates intersection of two regions defined as open ended intervals * [region1_start, region1_start + region1_len) \intersect * [region2_start, region2_start + region2_len) * * intersection_len is set to 0 if the regions do not overlap * otherwise returns the intersecting region * [intersection_start, intersection_start + intersection_len) */ void region_intersection(app_pc *intersection_start /* OUT */, size_t *intersection_len /* OUT */, const app_pc region1_start, size_t region1_len, const app_pc region2_start, size_t region2_len) { /* intersection */ app_pc intersection_end = MIN(region1_start + region1_len, region2_start + region2_len); ASSERT(intersection_start != NULL); ASSERT(intersection_len != NULL); *intersection_start = MAX(region1_start, region2_start); /* set length as long as result is a proper intersecting region, * max(0, intersection_end - intersection_start) if signed */ *intersection_len = (intersection_end > *intersection_start) ? (intersection_end - *intersection_start) : 0; } /***************************************************************************/ #ifdef CALL_PROFILE typedef struct _profile_callers_t { app_pc caller[MAX_CALL_PROFILE_DEPTH]; uint count; struct _profile_callers_t *next; } profile_callers_t; /* debug-only so neverprot */ DECLARE_NEVERPROT_VAR(static profile_callers_t *profcalls, NULL); DECLARE_CXTSWPROT_VAR(static mutex_t profile_callers_lock, INIT_LOCK_FREE(profile_callers_lock)); /* Usage: * Simply place a profile_callers() call in the routine you wish to profile. * You MUST build without optimizations to enable call stack walking. * Results go to a separate log file and are dumped only at exit. * FIXME: combine w/ a generalized mutex_collect_callstack()? */ void profile_callers() { profile_callers_t *entry; uint *pc; uint num = 0; app_pc our_ebp = 0; app_pc caller[MAX_CALL_PROFILE_DEPTH]; app_pc saferead[2]; if (DYNAMO_OPTION(prof_caller) == 0 || dynamo_exited_and_cleaned/*no heap*/) return; ASSERT(DYNAMO_OPTION(prof_caller) <= MAX_CALL_PROFILE_DEPTH); GET_FRAME_PTR(our_ebp); memset(caller, 0, sizeof(caller)); pc = (uint *) our_ebp; /* FIXME: mutex_collect_callstack() assumes caller addresses are in * DR and thus are safe to read, but checks for dstack, etc. * Should combine the two into a general routine. */ while (pc != NULL && safe_read((byte *)pc, sizeof(saferead), saferead)) { caller[num] = saferead[1]; num++; /* yes I've seen weird recursive cases before */ if (pc == (uint *) saferead[0] || num >= DYNAMO_OPTION(prof_caller)) break; pc = (uint *) saferead[0]; } /* Assumption: there aren't many unique callstacks being profiled, so a * linear search is sufficient! * FIXME: make this more performant if necessary */ for (entry = profcalls; entry != NULL; entry = entry->next) { bool match = true; for (num = 0; num < DYNAMO_OPTION(prof_caller); num++) { if (entry->caller[num] != caller[num]) { match = false; break; } } if (match) { entry->count++; break; } } if (entry == NULL) { entry = global_heap_alloc(sizeof(profile_callers_t) HEAPACCT(ACCT_OTHER)); memcpy(entry->caller, caller, sizeof(caller)); entry->count = 1; mutex_lock(&profile_callers_lock); entry->next = profcalls; profcalls = entry; mutex_unlock(&profile_callers_lock); } } void profile_callers_exit() { profile_callers_t *entry, *next; file_t file; if (DYNAMO_OPTION(prof_caller) > 0) { mutex_lock(&profile_callers_lock); file = open_log_file("callprof", NULL, 0); for (entry = profcalls; entry != NULL; entry = next) { uint num; next = entry->next; for (num = 0; num < DYNAMO_OPTION(prof_caller); num++) { print_file(file, PFX" ", entry->caller[num]); } print_file(file, "%d\n", entry->count); global_heap_free(entry, sizeof(profile_callers_t) HEAPACCT(ACCT_OTHER)); } close_log_file(file); profcalls = NULL; mutex_unlock(&profile_callers_lock); } DELETE_LOCK(profile_callers_lock); } #endif /* CALL_PROFILE */ #ifdef STANDALONE_UNIT_TEST # ifdef printf # undef printf # endif # define printf(...) print_file(STDERR, __VA_ARGS__) static void test_date_conversion_millis(uint64 millis) { dr_time_t dr_time; uint64 res; convert_millis_to_date(millis, &dr_time); convert_date_to_millis(&dr_time, &res); if (res != millis || dr_time.day_of_week != (millis / (24 * 60 * 60 * 1000) + 1) % 7 || dr_time.month < 1 || dr_time.month > 12 || dr_time.day < 1 || dr_time.day > 31 || dr_time.hour > 23 || dr_time.minute > 59 || dr_time.second > 59 || dr_time.milliseconds > 999) { printf("FAIL : test_date_conversion_millis\n"); exit(-1); } } static void test_date_conversion_day(dr_time_t *dr_time) { uint64 millis; dr_time_t res; convert_date_to_millis(dr_time, &millis); convert_millis_to_date(millis, &res); if (res.year != dr_time->year || res.month != dr_time->month || res.day != dr_time->day || res.hour != dr_time->hour || res.minute != dr_time->minute || res.second != dr_time->second || res.milliseconds != dr_time->milliseconds) { printf("FAIL : test_date_conversion_day\n"); exit(-1); } } /* Tests for double_print(), divide_uint64_print(), and date routines. */ void unit_test_utils(void) { char buf[128]; uint c, d; const char *s; int t; dr_time_t dr_time; # define DO_TEST(a, b, p, percent, fmt, result) \ divide_uint64_print(a, b, percent, p, &c, &d); \ snprintf(buf, BUFFER_SIZE_ELEMENTS(buf), fmt, c, d); \ NULL_TERMINATE_BUFFER(buf); \ if (strcmp(buf, result) == 0) { \ printf("PASS\n"); \ } else { \ printf("FAIL : \"%s\" doesn't match \"%s\"\n", buf, result); \ exit(-1); \ } DO_TEST(1, 20, 3, false, "%u.%.3u", "0.050"); DO_TEST(2, 5, 2, false, "%3u.%.2u", " 0.40"); DO_TEST(100, 7, 4, false, "%u.%.4u", "14.2857"); DO_TEST(475, 1000, 2, true, "%u.%.2u%%", "47.50%"); # undef DO_TEST # define DO_TEST(a, p, fmt, result) \ double_print(a, p, &c, &d, &s); \ snprintf(buf, BUFFER_SIZE_ELEMENTS(buf), fmt, s, c, d); \ NULL_TERMINATE_BUFFER(buf); \ if (strcmp(buf, result) == 0) { \ printf("PASS\n"); \ } else { \ printf("FAIL : \"%s\" doesn't match \"%s\"\n", buf, result); \ exit(-1); \ } DO_TEST(-2.06, 3, "%s%u.%.3u", "-2.060"); DO_TEST(2.06, 4, "%s%u.%.4u", "2.0600"); DO_TEST(.0563, 2, "%s%u.%.2u", "0.05"); DO_TEST(-.0563, 2, "%s%u.%.2u", "-0.05"); DO_TEST(23.0456, 5, "%s%4u.%.5u", " 23.04560"); DO_TEST(-23.0456, 5, "%s%4u.%.5u", "- 23.04560"); # undef DO_TEST EXPECT(BOOLS_MATCH(1, 1), true); EXPECT(BOOLS_MATCH(1, 0), false); EXPECT(BOOLS_MATCH(0, 1), false); EXPECT(BOOLS_MATCH(0, 0), true); EXPECT(BOOLS_MATCH(1, 2), true); EXPECT(BOOLS_MATCH(2, 1), true); EXPECT(BOOLS_MATCH(1, -1), true); /* Test each millisecond in first and last 100 seconds. */ for (t = 0; t < 100000; t++) { test_date_conversion_millis(t); test_date_conversion_millis(-t - 1); } /* Test each second in first and last day and a bit. */ for (t = 0; t < 100000; t++) { test_date_conversion_millis(t * 1000); test_date_conversion_millis(-(t * 1000) - 1); } /* Test each day from 1601 to 2148. */ for (t = 0; t < 200000; t++) test_date_conversion_millis((uint64)t * 24 * 60 * 60 * 1000); /* Test the first of each month from 1601 to 99999. */ dr_time.day_of_week = 0; /* not checked */ dr_time.day = 1; dr_time.hour = 0; dr_time.minute = 0; dr_time.second = 0; dr_time.milliseconds = 0; for (t = 0; t < (99999 - 1601) * 12; t++) { dr_time.year = 1601 + t / 12; dr_time.month = 1 + t % 12; test_date_conversion_day(&dr_time); } } # undef printf #endif /* STANDALONE_UNIT_TEST */ char * dr_strdup(const char *str HEAPACCT(which_heap_t which)) { char *dup; size_t str_len; if (str == NULL) return NULL; str_len = strlen(str) + 1; /* Extra 1 char for the '\0' at the end. */ dup = (char*) heap_alloc(GLOBAL_DCONTEXT, str_len HEAPACCT(which)); strncpy (dup, str, str_len); dup[str_len - 1] = '\0'; /* Being on the safe side. */ return dup; } #ifdef WINDOWS /* Allocates a new char *(NOT a new wchar_t*) from a wchar_t* */ char * dr_wstrdup(const wchar_t *str HEAPACCT(which_heap_t which)) { char *dup; ssize_t encode_len; size_t str_len; int res; if (str == NULL) return NULL; /* FIXME: should have a max length and truncate? * I'm assuming we're using not directly on external inputs. * If we do put in a max length, should do the same for dr_strdup. */ encode_len = utf16_to_utf8_size(str, 0/*no max*/, NULL); if (encode_len < 0) str_len = 1; else str_len = encode_len + 1; /* Extra 1 char for the '\0' at the end. */ dup = (char*) heap_alloc(GLOBAL_DCONTEXT, str_len HEAPACCT(which)); if (encode_len >= 0) { res = snprintf(dup, str_len, "%S", str); if (res < 0 || (size_t)res < str_len - 1) { ASSERT_NOT_REACHED(); if (res < 0) dup[0] = '\0'; /* apparently for some versions of ntdll!_snprintf, if %S * conversion hits a non-ASCII char it will write a NULL and * snprintf will return -1 (that's the libc behavior) or the * number of chars to that point. we don't want strlen to return * fewer chars than we allocated so we fill it in (i#347). */ /* Xref i#347, though we shouldn't get here b/c utf16_to_utf8_size uses * the same code. We fall back on filling with '?'. */ memset(dup + strlen(dup), '?', str_len - 1 - strlen(dup)); } } dup[str_len - 1] = '\0'; /* Being on the safe side. */ /* Ensure when we free we'll pass the same size (i#347) */ ASSERT(strlen(dup) == str_len - 1); return dup; } #endif /* Frees a char *string (NOT a wchar_t*) allocated via dr_strdup or * dr_wstrdup that has not been modified since being copied! */ void dr_strfree(const char *str HEAPACCT(which_heap_t which)) { size_t str_len; ASSERT_CURIOSITY(str != NULL); if (str == NULL) return; str_len = strlen(str) + 1; /* Extra 1 char for the '\0' at the end. */ heap_free(GLOBAL_DCONTEXT, (void *)str, str_len HEAPACCT(which)); } /* Merges two unsorted arrays, treating their elements as type void* * (but will work on other types of same size as void*) * as an intersection if intersect is true or as a union (removing * duplicates) otherwise. Allocates a new array on dcontext's heap * for the result and returns it and its size; if the new size is 0, * does NOT allocate anything and points the new array at NULL. */ void array_merge(dcontext_t *dcontext, bool intersect /* else union */, void **src1, uint src1_num, void **src2, uint src2_num, /*OUT*/ void ***dst, /*OUT*/ uint *dst_num HEAPACCT(which_heap_t which)) { /* Two passes: one to find number of unique entries, and second to * fill them in. * FIXME: if this routine is ever on a performance-critical path then * we should switch to a temp hashtable and avoid this quadratic cost. */ uint num; void **vec = NULL; uint i, j; DEBUG_DECLARE(uint res;) ASSERT(dst != NULL && dst_num != NULL); ASSERT(src1 != NULL || src1_num == 0); ASSERT(src2 != NULL || src2_num == 0); if (src1 == NULL || src2 == NULL || dst == NULL) /* paranoid */ return; /* FIXME: return a bool? */ if (src1_num == 0 && src2_num == 0) { *dst = NULL; *dst_num = 0; return; } num = intersect ? 0 : src1_num; for (i = 0; i < src2_num; i++) { for (j = 0; j < src1_num; j++) { if (src2[i] == src1[j]) { if (intersect) num++; break; } } if (!intersect && j == src1_num) num++; } if (num > 0) { vec = HEAP_ARRAY_ALLOC(dcontext, void *, num, which, PROTECTED); if (!intersect) memcpy(vec, src1, sizeof(void *) * src1_num); DODEBUG(res = num;); num = intersect ? 0 : src1_num; for (i = 0; i < src2_num; i++) { for (j = 0; j < src1_num; j++) { if (src2[i] == src1[j]) { if (intersect) vec[num++] = src2[i]; break; } } if (!intersect && j == src1_num) vec[num++] = src2[i]; } ASSERT(num == res); } else { ASSERT(intersect); ASSERT(vec == NULL); } *dst = vec; *dst_num = num; } bool stats_get_snapshot(dr_stats_t *drstats) { if (!GLOBAL_STATS_ON()) return false; CLIENT_ASSERT(drstats != NULL, "Expected non-null value for parameter drstats."); /* We are at V1 of the structure, and we can't return less than the one * field. We need to remove this assert when we add more fields. */ CLIENT_ASSERT(drstats->size >= sizeof(dr_stats_t), "Invalid drstats->size value."); drstats->basic_block_count = GLOBAL_STAT(num_bbs); return true; }
1
13,406
This is ignoring compatibility: it needs to check the size to ensure this field exists in the client.
DynamoRIO-dynamorio
c
@@ -96,10 +96,11 @@ public class RoundChangePayloadValidator { return false; } - if (certificate.getPreparePayloads().size() < minimumPrepareMessages) { + if (certificate.getPreparePayloads().stream().map(SignedData::getAuthor).distinct().count() + < minimumPrepareMessages) { LOG.info( - "Invalid RoundChange message, insufficient Prepare messages exist to justify " - + "prepare certificate."); + "Invalid RoundChange message, insufficient uniquely authored Prepare messages exist to " + + " justify prepare certificate."); return false; }
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.consensus.ibft.validation; import org.hyperledger.besu.consensus.ibft.ConsensusRoundIdentifier; import org.hyperledger.besu.consensus.ibft.payload.PreparePayload; import org.hyperledger.besu.consensus.ibft.payload.PreparedCertificate; import org.hyperledger.besu.consensus.ibft.payload.ProposalPayload; import org.hyperledger.besu.consensus.ibft.payload.RoundChangePayload; import org.hyperledger.besu.consensus.ibft.payload.SignedData; import org.hyperledger.besu.ethereum.core.Address; import java.util.Collection; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class RoundChangePayloadValidator { private static final Logger LOG = LogManager.getLogger(); private final MessageValidatorForHeightFactory messageValidatorFactory; private final Collection<Address> validators; private final long minimumPrepareMessages; private final long chainHeight; public RoundChangePayloadValidator( final MessageValidatorForHeightFactory messageValidatorFactory, final Collection<Address> validators, final long minimumPrepareMessages, final long chainHeight) { this.messageValidatorFactory = messageValidatorFactory; this.validators = validators; this.minimumPrepareMessages = minimumPrepareMessages; this.chainHeight = chainHeight; } public boolean validateRoundChange(final SignedData<RoundChangePayload> msg) { if (!validators.contains(msg.getAuthor())) { LOG.info( "Invalid RoundChange message, was not transmitted by a validator for the associated" + " round."); return false; } final ConsensusRoundIdentifier targetRound = msg.getPayload().getRoundIdentifier(); if (targetRound.getSequenceNumber() != chainHeight) { LOG.info("Invalid RoundChange message, not valid for local chain height."); return false; } if (msg.getPayload().getPreparedCertificate().isPresent()) { final PreparedCertificate certificate = msg.getPayload().getPreparedCertificate().get(); return validatePrepareCertificate(certificate, targetRound); } return true; } private boolean validatePrepareCertificate( final PreparedCertificate certificate, final ConsensusRoundIdentifier roundChangeTarget) { final SignedData<ProposalPayload> proposalMessage = certificate.getProposalPayload(); final ConsensusRoundIdentifier proposalRoundIdentifier = proposalMessage.getPayload().getRoundIdentifier(); if (!validatePreparedCertificateRound(proposalRoundIdentifier, roundChangeTarget)) { return false; } final SignedDataValidator signedDataValidator = messageValidatorFactory.createAt(proposalRoundIdentifier); return validateConsistencyOfPrepareCertificateMessages(certificate, signedDataValidator); } private boolean validateConsistencyOfPrepareCertificateMessages( final PreparedCertificate certificate, final SignedDataValidator signedDataValidator) { if (!signedDataValidator.validateProposal(certificate.getProposalPayload())) { LOG.info("Invalid RoundChange message, embedded Proposal message failed validation."); return false; } if (certificate.getPreparePayloads().size() < minimumPrepareMessages) { LOG.info( "Invalid RoundChange message, insufficient Prepare messages exist to justify " + "prepare certificate."); return false; } for (final SignedData<PreparePayload> prepareMsg : certificate.getPreparePayloads()) { if (!signedDataValidator.validatePrepare(prepareMsg)) { LOG.info("Invalid RoundChange message, embedded Prepare message failed validation."); return false; } } return true; } private boolean validatePreparedCertificateRound( final ConsensusRoundIdentifier prepareCertRound, final ConsensusRoundIdentifier roundChangeTarget) { if (prepareCertRound.getSequenceNumber() != roundChangeTarget.getSequenceNumber()) { LOG.info("Invalid RoundChange message, PreparedCertificate is not for local chain height."); return false; } if (prepareCertRound.getRoundNumber() >= roundChangeTarget.getRoundNumber()) { LOG.info( "Invalid RoundChange message, PreparedCertificate not older than RoundChange target."); return false; } return true; } @FunctionalInterface public interface MessageValidatorForHeightFactory { SignedDataValidator createAt(final ConsensusRoundIdentifier roundIdentifier); } }
1
24,044
Do all the prepare authors also need to be unique? Or is it enough the we have minimumPrepareMessages. I guess I'm wondering if need a hasDuplicateAuthors check like in the RoundChangeCertificateValidator.
hyperledger-besu
java
@@ -4,12 +4,17 @@ package stdlib import ( _ "github.com/influxdata/flux/stdlib/csv" + _ "github.com/influxdata/flux/stdlib/date" _ "github.com/influxdata/flux/stdlib/generate" _ "github.com/influxdata/flux/stdlib/http" _ "github.com/influxdata/flux/stdlib/influxdata/influxdb" _ "github.com/influxdata/flux/stdlib/influxdata/influxdb/v1" _ "github.com/influxdata/flux/stdlib/kafka" _ "github.com/influxdata/flux/stdlib/math" + _ "github.com/influxdata/flux/stdlib/mqtt" + _ "github.com/influxdata/flux/stdlib/promql" + _ "github.com/influxdata/flux/stdlib/regexp" + _ "github.com/influxdata/flux/stdlib/runtime" _ "github.com/influxdata/flux/stdlib/socket" _ "github.com/influxdata/flux/stdlib/sql" _ "github.com/influxdata/flux/stdlib/strings"
1
// DO NOT EDIT: This file is autogenerated via the builtin command. package stdlib import ( _ "github.com/influxdata/flux/stdlib/csv" _ "github.com/influxdata/flux/stdlib/generate" _ "github.com/influxdata/flux/stdlib/http" _ "github.com/influxdata/flux/stdlib/influxdata/influxdb" _ "github.com/influxdata/flux/stdlib/influxdata/influxdb/v1" _ "github.com/influxdata/flux/stdlib/kafka" _ "github.com/influxdata/flux/stdlib/math" _ "github.com/influxdata/flux/stdlib/socket" _ "github.com/influxdata/flux/stdlib/sql" _ "github.com/influxdata/flux/stdlib/strings" _ "github.com/influxdata/flux/stdlib/system" _ "github.com/influxdata/flux/stdlib/testing" _ "github.com/influxdata/flux/stdlib/universe" )
1
11,271
we had some situations where we merged some promql bits then took them out. i'm not sure what's going on here, but unless your code actually needs promql (probably not?) let's remove this line.
influxdata-flux
go
@@ -32,9 +32,9 @@ class SettingValueDataFixture extends AbstractReferenceFixture implements Depend { $termsAndConditions = $this->getReference(ArticleDataFixture::ARTICLE_TERMS_AND_CONDITIONS_1); $privacyPolicy = $this->getReference(ArticleDataFixture::ARTICLE_PRIVACY_POLICY_1); - /* @var $termsAndConditions \Shopsys\FrameworkBundle\Model\Article\Article */ + /* @var $termsAndConditions \Shopsys\ShopBundle\Model\Article\Article */ $cookies = $this->getReference(ArticleDataFixture::ARTICLE_COOKIES_1); - /* @var $cookies \Shopsys\FrameworkBundle\Model\Article\Article */ + /* @var $cookies \Shopsys\ShopBundle\Model\Article\Article */ $personalDataDisplaySiteContent = 'By entering an email below, you can view your personal information that we register in our online store. An email with a link will be sent to you after entering your email address, to verify your identity.
1
<?php declare(strict_types=1); namespace Shopsys\ShopBundle\DataFixtures\Demo; use Doctrine\Common\DataFixtures\DependentFixtureInterface; use Doctrine\Common\Persistence\ObjectManager; use Shopsys\FrameworkBundle\Component\DataFixture\AbstractReferenceFixture; use Shopsys\FrameworkBundle\Component\Domain\Domain; use Shopsys\FrameworkBundle\Component\Setting\Setting; class SettingValueDataFixture extends AbstractReferenceFixture implements DependentFixtureInterface { /** * @var \Shopsys\FrameworkBundle\Component\Setting\Setting */ protected $setting; /** * @param \Shopsys\FrameworkBundle\Component\Setting\Setting $setting */ public function __construct(Setting $setting) { $this->setting = $setting; } /** * @param \Doctrine\Common\Persistence\ObjectManager $manager */ public function load(ObjectManager $manager) { $termsAndConditions = $this->getReference(ArticleDataFixture::ARTICLE_TERMS_AND_CONDITIONS_1); $privacyPolicy = $this->getReference(ArticleDataFixture::ARTICLE_PRIVACY_POLICY_1); /* @var $termsAndConditions \Shopsys\FrameworkBundle\Model\Article\Article */ $cookies = $this->getReference(ArticleDataFixture::ARTICLE_COOKIES_1); /* @var $cookies \Shopsys\FrameworkBundle\Model\Article\Article */ $personalDataDisplaySiteContent = 'By entering an email below, you can view your personal information that we register in our online store. An email with a link will be sent to you after entering your email address, to verify your identity. Clicking on the link will take you to a page listing all the personal details we have connected to your email address.'; $personalDataExportSiteContent = 'By entering an email below, you can download your personal and other information (for example, order history) from our online store. An email with a link will be sent to you after entering your email address, to verify your identity. Clicking on the link will take you to a page where you’ll be able to download these informations in readable format - it will be the data registered to given email address on this online store domain.'; $this->setting->setForDomain(Setting::COOKIES_ARTICLE_ID, $cookies->getId(), Domain::FIRST_DOMAIN_ID); $this->setting->setForDomain(Setting::TERMS_AND_CONDITIONS_ARTICLE_ID, $termsAndConditions->getId(), Domain::FIRST_DOMAIN_ID); $this->setting->setForDomain(Setting::PRIVACY_POLICY_ARTICLE_ID, $privacyPolicy->getId(), Domain::FIRST_DOMAIN_ID); $this->setting->setForDomain(Setting::PERSONAL_DATA_DISPLAY_SITE_CONTENT, $personalDataDisplaySiteContent, Domain::FIRST_DOMAIN_ID); $this->setting->setForDomain(Setting::PERSONAL_DATA_EXPORT_SITE_CONTENT, $personalDataExportSiteContent, Domain::FIRST_DOMAIN_ID); } /** * {@inheritDoc} */ public function getDependencies() { return [ ArticleDataFixture::class, PricingGroupDataFixture::class, ]; } }
1
18,623
Annotations in this hunk should follow PhpDoc style (above the occurrence, type first)
shopsys-shopsys
php
@@ -100,7 +100,7 @@ public class Wildcard implements Type { } else if (type == BoundType.EXTENDS) { return "? extends " + boundedType.describe(); } else { - throw new UnsupportedOperationException(); + throw new UnsupportedOperationException(String.format("%s is not supported", type)); } }
1
/* * Copyright 2016 Federico Tomassetti * * 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 com.github.javaparser.symbolsolver.model.typesystem; import com.github.javaparser.symbolsolver.model.declarations.TypeParameterDeclaration; import java.util.Map; /** * A wildcard can be: * - unbounded (?) * - have a lower bound (? super Number) * - have an upper bound (? extends Number) * It is not possible to have both a lower and an upper bound at the same time. * * @author Federico Tomassetti */ public class Wildcard implements Type { public static Wildcard UNBOUNDED = new Wildcard(null, null); private BoundType type; private Type boundedType; private Wildcard(BoundType type, Type boundedType) { if (type == null && boundedType != null) { throw new IllegalArgumentException(); } if (type != null && boundedType == null) { throw new IllegalArgumentException(); } this.type = type; this.boundedType = boundedType; } public static Wildcard superBound(Type type) { return new Wildcard(BoundType.SUPER, type); } public static Wildcard extendsBound(Type type) { return new Wildcard(BoundType.EXTENDS, type); } @Override public String toString() { return "WildcardUsage{" + "type=" + type + ", boundedType=" + boundedType + '}'; } public boolean isWildcard() { return true; } public Wildcard asWildcard() { return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Wildcard)) return false; Wildcard that = (Wildcard) o; if (boundedType != null ? !boundedType.equals(that.boundedType) : that.boundedType != null) return false; if (type != that.type) return false; return true; } @Override public int hashCode() { int result = type != null ? type.hashCode() : 0; result = 31 * result + (boundedType != null ? boundedType.hashCode() : 0); return result; } @Override public String describe() { if (type == null) { return "?"; } else if (type == BoundType.SUPER) { return "? super " + boundedType.describe(); } else if (type == BoundType.EXTENDS) { return "? extends " + boundedType.describe(); } else { throw new UnsupportedOperationException(); } } public boolean isSuper() { return type == BoundType.SUPER; } public boolean isExtends() { return type == BoundType.EXTENDS; } public boolean isBounded() { return isSuper() || isExtends(); } public Type getBoundedType() { if (boundedType == null) { throw new IllegalStateException(); } return boundedType; } @Override public boolean isAssignableBy(Type other) { if (boundedType == null) { //return other.isReferenceType() && other.asReferenceType().getQualifiedName().equals(Object.class.getCanonicalName()); return false; } else if (type == BoundType.SUPER) { return boundedType.isAssignableBy(other); } else if (type == BoundType.EXTENDS) { return false; } else { throw new RuntimeException(); } } @Override public Type replaceTypeVariables(TypeParameterDeclaration tpToReplace, Type replaced, Map<TypeParameterDeclaration, Type> inferredTypes) { if (replaced == null) { throw new IllegalArgumentException(); } if (boundedType == null) { return this; } Type boundedTypeReplaced = boundedType.replaceTypeVariables(tpToReplace, replaced, inferredTypes); if (boundedTypeReplaced == null) { throw new RuntimeException(); } if (boundedTypeReplaced != boundedType) { return new Wildcard(type, boundedTypeReplaced); } else { return this; } } public enum BoundType { SUPER, EXTENDS } }
1
14,157
This is an improvement - thanks! Could we rephrase slightly to not use the phrase "is not supported" -- instead stating _WHAT_ isn't valid please? e.g. maybe `String.format("Unsupported BoundType provided: %s" type)` or something like that.
javaparser-javaparser
java
@@ -30,7 +30,7 @@ type linuxWatcher struct { gid uint32 pid int32 mtx sync.Mutex - procfh *os.File + procfh int starttime string uid uint32 }
1
// +build linux package peertracker import ( "errors" "fmt" "io/ioutil" "os" "strings" "sync" "syscall" ) type linuxTracker struct{} func newTracker() (linuxTracker, error) { return linuxTracker{}, nil } func (linuxTracker) NewWatcher(info CallerInfo) (Watcher, error) { return newLinuxWatcher(info) } func (linuxTracker) Close() { return } type linuxWatcher struct { gid uint32 pid int32 mtx sync.Mutex procfh *os.File starttime string uid uint32 } func newLinuxWatcher(info CallerInfo) (*linuxWatcher, error) { // If PID == 0, something is wrong... if info.PID == 0 { return nil, errors.New("could not resolve caller information") } // Grab a handle to proc first since that's the fastest thing we can do procfh, err := os.Open(fmt.Sprintf("/proc/%v", info.PID)) if err != nil { return nil, fmt.Errorf("could not open caller's proc directory: %v", err) } starttime, err := getStarttime(info.PID) if err != nil { return nil, err } return &linuxWatcher{ gid: info.GID, pid: info.PID, procfh: procfh, starttime: starttime, uid: info.UID, }, nil } func (l *linuxWatcher) Close() { l.mtx.Lock() defer l.mtx.Unlock() if l.procfh == nil { return } l.procfh.Close() l.procfh = nil } func (l *linuxWatcher) IsAlive() error { l.mtx.Lock() defer l.mtx.Unlock() if l.procfh == nil { return errors.New("caller is no longer being watched") } // First we will check if we can read from the original directory handle. If the // process has exited since we opened it, the read should fail. _, err := l.procfh.Readdir(1) if err != nil { return errors.New("caller exit suspected due to failed proc read") } // A successful fd read should indicate that the original process is still alive, however // it is not clear if the original inode can be freed by Linux while it is still referenced. // This _shouldn't_ happen, but if it does, then there might be room for a reused PID to // collide with the original inode making the read successful. As an extra measure, ensure // that the current `starttime` matches the one we saw originally. // // This is probably overkill. // TODO: Evaluate the use of `starttime` as the primary exit detection mechanism. currentStarttime, err := getStarttime(l.pid) if err != nil { return errors.New("caller exit suspected due to failed proc read") } if currentStarttime != l.starttime { return errors.New("new process detected: starttime mismatch") } // Finally, read the UID and GID off the proc directory to determine the owner. If // we got beaten by a PID race when opening the proc handle originally, we can at // least get to know that the race winner is running as the same user and group as // the original caller by comparing it to the received CallerInfo. info, err := l.procfh.Stat() if err != nil { return errors.New("caller exit suspected due to failed proc read") } stat, ok := info.Sys().(*syscall.Stat_t) if !ok { return errors.New("failed to read proc ownership info: is this a supported system?") } if stat.Uid != l.uid { return fmt.Errorf("new process detected: process uid %v does not match original caller %v", stat.Uid, l.uid) } if stat.Gid != l.gid { return fmt.Errorf("new process detected: process gid %v does not match original caller %v", stat.Gid, l.gid) } return nil } func (l *linuxWatcher) PID() int32 { return l.pid } func parseTaskStat(stat string) ([]string, error) { b := strings.IndexByte(stat, '(') e := strings.LastIndexByte(stat, ')') if b == -1 || e == -1 { return nil, errors.New("task name is not parenthesized") } fields := make([]string, 0, 52) fields = append(fields, strings.Split(stat[:b-1], " ")...) fields = append(fields, stat[b+1:e]) fields = append(fields, strings.Split(stat[e+2:], " ")...) return fields, nil } func getStarttime(pid int32) (string, error) { statfd, err := os.Open(fmt.Sprintf("/proc/%v/stat", pid)) if err != nil { return "", fmt.Errorf("could not open caller stats: %v", err) } statBytes, err := ioutil.ReadAll(statfd) if err != nil { return "", fmt.Errorf("could not read caller stats: %v", err) } statFields, err := parseTaskStat(string(statBytes)) if err != nil { return "", fmt.Errorf("bad stat data: %v", err) } // starttime is the 22nd field in the proc stat data // Field number 38 was introduced in Linux 2.1.22 // Protect against invalid index and reject anything before 2.1.22 if len(statFields) < 38 { return "", errors.New("bad stat data or unsupported platform") } return statFields[21], nil }
1
11,900
nit: `procfd` seems more appropriate now?
spiffe-spire
go
@@ -1045,6 +1045,10 @@ def access_put(owner, package_name, user): "Only the package owner can grant access" ) + django_headers = { + AUTHORIZATION_HEADER: g.auth_header + } + package = ( Package.query .with_for_update()
1
# Copyright (c) 2017 Quilt Data, Inc. All rights reserved. """ API routes. """ from datetime import timedelta, timezone from functools import wraps import json import time from urllib.parse import urlencode import boto3 from flask import abort, g, redirect, render_template, request, Response from flask_cors import CORS from flask_json import as_json, jsonify import httpagentparser from jsonschema import Draft4Validator, ValidationError from oauthlib.oauth2 import OAuth2Error import requests from requests_oauthlib import OAuth2Session import sqlalchemy as sa from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import undefer import stripe from . import app, db from .analytics import MIXPANEL_EVENT, mp from .const import EMAILREGEX, PaymentPlan, PUBLIC from .core import decode_node, find_object_hashes, hash_contents, FileNode, GroupNode, RootNode from .models import (Access, Customer, Instance, Invitation, Log, Package, S3Blob, Tag, Version) from .schemas import LOG_SCHEMA, PACKAGE_SCHEMA QUILT_CDN = 'https://cdn.quiltdata.com/' DEPLOYMENT_ID = app.config['DEPLOYMENT_ID'] OAUTH_ACCESS_TOKEN_URL = app.config['OAUTH']['access_token_url'] OAUTH_AUTHORIZE_URL = app.config['OAUTH']['authorize_url'] OAUTH_CLIENT_ID = app.config['OAUTH']['client_id'] OAUTH_CLIENT_SECRET = app.config['OAUTH']['client_secret'] OAUTH_REDIRECT_URL = app.config['OAUTH']['redirect_url'] OAUTH_USER_API = app.config['OAUTH']['user_api'] OAUTH_PROFILE_API = app.config['OAUTH']['profile_api'] OAUTH_HAVE_REFRESH_TOKEN = app.config['OAUTH']['have_refresh_token'] CATALOG_REDIRECT_URLS = app.config['CATALOG_REDIRECT_URLS'] AUTHORIZATION_HEADER = 'Authorization' INVITE_SEND_URL = app.config['INVITE_SEND_URL'] PACKAGE_BUCKET_NAME = app.config['PACKAGE_BUCKET_NAME'] PACKAGE_URL_EXPIRATION = app.config['PACKAGE_URL_EXPIRATION'] S3_HEAD_OBJECT = 'head_object' S3_GET_OBJECT = 'get_object' S3_PUT_OBJECT = 'put_object' OBJ_DIR = 'objs' # Limit the JSON metadata to 100MB. # This is mostly a sanity check; it's already limited by app.config['MAX_CONTENT_LENGTH']. MAX_METADATA_SIZE = 100 * 1024 * 1024 PREVIEW_MAX_CHILDREN = 10 PREVIEW_MAX_DEPTH = 4 s3_client = boto3.client( 's3', endpoint_url=app.config.get('S3_ENDPOINT'), aws_access_key_id=app.config.get('AWS_ACCESS_KEY_ID'), aws_secret_access_key=app.config.get('AWS_SECRET_ACCESS_KEY') ) stripe.api_key = app.config['STRIPE_SECRET_KEY'] HAVE_PAYMENTS = stripe.api_key is not None class QuiltCli(httpagentparser.Browser): look_for = 'quilt-cli' version_markers = [('/', '')] httpagentparser.detectorshub.register(QuiltCli()) ### Web routes ### def _create_session(next=''): return OAuth2Session( client_id=OAUTH_CLIENT_ID, redirect_uri=OAUTH_REDIRECT_URL, state=json.dumps(dict(next=next)) ) @app.route('/healthcheck') def healthcheck(): """ELB health check; just needs to return a 200 status code.""" return Response("ok", content_type='text/plain') ROBOTS_TXT = ''' User-agent: * Disallow: / '''.lstrip() @app.route('/robots.txt') def robots(): """Disallow crawlers; there's nothing useful for them here.""" return Response(ROBOTS_TXT, mimetype='text/plain') def _valid_catalog_redirect(next): return next is None or any(next.startswith(url) for url in CATALOG_REDIRECT_URLS) @app.route('/login') def login(): next = request.args.get('next') if not _valid_catalog_redirect(next): return render_template('oauth_fail.html', error="Invalid redirect", QUILT_CDN=QUILT_CDN) session = _create_session(next=next) url, state = session.authorization_url(url=OAUTH_AUTHORIZE_URL) return redirect(url) @app.route('/oauth_callback') def oauth_callback(): # TODO: Check `state`? Do we need CSRF protection here? try: state = json.loads(request.args.get('state', '{}')) except ValueError: abort(requests.codes.bad_request) if not isinstance(state, dict): abort(requests.codes.bad_request) next = state.get('next') if not _valid_catalog_redirect(next): abort(requests.codes.bad_request) error = request.args.get('error') if error is not None: return render_template('oauth_fail.html', error=error, QUILT_CDN=QUILT_CDN) code = request.args.get('code') if code is None: abort(requests.codes.bad_request) session = _create_session() try: resp = session.fetch_token( token_url=OAUTH_ACCESS_TOKEN_URL, code=code, client_secret=OAUTH_CLIENT_SECRET ) if next: return redirect('%s#%s' % (next, urlencode(resp))) else: token = resp['refresh_token' if OAUTH_HAVE_REFRESH_TOKEN else 'access_token'] return render_template('oauth_success.html', code=token, QUILT_CDN=QUILT_CDN) except OAuth2Error as ex: return render_template('oauth_fail.html', error=ex.error, QUILT_CDN=QUILT_CDN) @app.route('/api/token', methods=['POST']) @as_json def token(): refresh_token = request.values.get('refresh_token') if refresh_token is None: abort(requests.codes.bad_request) if not OAUTH_HAVE_REFRESH_TOKEN: return dict( refresh_token='', access_token=refresh_token, expires_at=float('inf') ) session = _create_session() try: resp = session.refresh_token( token_url=OAUTH_ACCESS_TOKEN_URL, client_id=OAUTH_CLIENT_ID, # Why??? The session object already has it! client_secret=OAUTH_CLIENT_SECRET, refresh_token=refresh_token ) except OAuth2Error as ex: return dict(error=ex.error) return dict( refresh_token=resp['refresh_token'], access_token=resp['access_token'], expires_at=resp['expires_at'] ) ### API routes ### # Allow CORS requests to API routes. # The "*" origin is more secure than specific origins because it blocks cookies. # Cache the settings for a day to avoid pre-flight requests. CORS(app, resources={"/api/*": {"origins": "*", "max_age": timedelta(days=1)}}) class Auth: """ Info about the user making the API request. """ def __init__(self, user, email): self.user = user self.email = email class ApiException(Exception): """ Base class for API exceptions. """ def __init__(self, status_code, message): super().__init__() self.status_code = status_code self.message = message class PackageNotFoundException(ApiException): """ API exception for missing packages. """ def __init__(self, owner, package, logged_in=True): message = "Package %s/%s does not exist" % (owner, package) if not logged_in: message = "%s (do you need to log in?)" % message super().__init__(requests.codes.not_found, message) @app.errorhandler(ApiException) def handle_api_exception(error): """ Converts an API exception into an error response. """ _mp_track( type="exception", status_code=error.status_code, message=error.message, ) response = jsonify(dict( message=error.message )) response.status_code = error.status_code return response def api(require_login=True, schema=None): """ Decorator for API requests. Handles auth and adds the username as the first argument. """ if schema is not None: Draft4Validator.check_schema(schema) validator = Draft4Validator(schema) else: validator = None def innerdec(f): @wraps(f) def wrapper(*args, **kwargs): g.auth = Auth(PUBLIC, None) user_agent_str = request.headers.get('user-agent', '') g.user_agent = httpagentparser.detect(user_agent_str, fill_none=True) if validator is not None: try: validator.validate(request.get_json(cache=True)) except ValidationError as ex: raise ApiException(requests.codes.bad_request, ex.message) auth = request.headers.get(AUTHORIZATION_HEADER) g.auth_header = auth if auth is None: if require_login: raise ApiException(requests.codes.unauthorized, "Not logged in") else: headers = { AUTHORIZATION_HEADER: auth } try: resp = requests.get(OAUTH_USER_API, headers=headers) resp.raise_for_status() data = resp.json() # TODO(dima): Generalize this. user = data.get('current_user', data.get('login')) assert user email = data['email'] g.auth = Auth(user, email) except requests.HTTPError as ex: if resp.status_code == requests.codes.unauthorized: raise ApiException( requests.codes.unauthorized, "Invalid credentials" ) else: raise ApiException(requests.codes.server_error, "Server error") except (ConnectionError, requests.RequestException) as ex: raise ApiException(requests.codes.server_error, "Server error") return f(*args, **kwargs) return wrapper return innerdec def _get_package(auth, owner, package_name): """ Helper for looking up a package and checking permissions. Only useful for *_list functions; all others should use more efficient queries. """ package = ( Package.query .filter_by(owner=owner, name=package_name) .join(Package.access) .filter(Access.user.in_([auth.user, PUBLIC])) .one_or_none() ) if package is None: raise PackageNotFoundException(owner, package_name, auth.user is not PUBLIC) return package def _get_instance(auth, owner, package_name, package_hash): instance = ( Instance.query .filter_by(hash=package_hash) .options(undefer('contents')) # Contents is deferred by default. .join(Instance.package) .filter_by(owner=owner, name=package_name) .join(Package.access) .filter(Access.user.in_([auth.user, PUBLIC])) .one_or_none() ) if instance is None: raise ApiException( requests.codes.not_found, "Package hash does not exist" ) return instance def _utc_datetime_to_ts(dt): """ Convert a UTC datetime object to a UNIX timestamp. """ return dt.replace(tzinfo=timezone.utc).timestamp() def _mp_track(**kwargs): if g.user_agent['browser']['name'] == 'QuiltCli': source = 'cli' else: source = 'web' # Use the user ID if the user is logged in; otherwise, let MP use the IP address. distinct_id = g.auth.user if g.auth.user != PUBLIC else None # Try to get the ELB's forwarded IP, and fall back to the actual IP (in dev). ip_addr = request.headers.get('x-forwarded-for', request.remote_addr) # Set common attributes sent with each event. kwargs cannot override these. all_args = dict( kwargs, time=time.time(), ip=ip_addr, user=g.auth.user, source=source, browser_name=g.user_agent['browser']['name'], browser_version=g.user_agent['browser']['version'], platform_name=g.user_agent['platform']['name'], platform_version=g.user_agent['platform']['version'], deployment_id=DEPLOYMENT_ID, ) mp.track(distinct_id, MIXPANEL_EVENT, all_args) def _generate_presigned_url(method, owner, blob_hash): return s3_client.generate_presigned_url( method, Params=dict( Bucket=PACKAGE_BUCKET_NAME, Key='%s/%s/%s' % (OBJ_DIR, owner, blob_hash) ), ExpiresIn=PACKAGE_URL_EXPIRATION ) def _get_or_create_customer(): assert HAVE_PAYMENTS, "Payments are not enabled" assert g.auth.user != PUBLIC db_customer = Customer.query.filter_by(id=g.auth.user).one_or_none() if db_customer is None: try: # Insert a placeholder with no Stripe ID just to lock the row. db_customer = Customer(id=g.auth.user) db.session.add(db_customer) db.session.flush() except IntegrityError: # Someone else just created it, so look it up. db.session.rollback() db_customer = Customer.query.filter_by(id=g.auth.user).one() else: # Create a new customer. plan = PaymentPlan.FREE.value customer = stripe.Customer.create( email=g.auth.email, description=g.auth.user, ) stripe.Subscription.create( customer=customer.id, plan=plan, ) db_customer.stripe_customer_id = customer.id db.session.commit() customer = stripe.Customer.retrieve(db_customer.stripe_customer_id) assert customer.subscriptions.total_count == 1 return customer def _get_customer_plan(customer): return PaymentPlan(customer.subscriptions.data[0].plan.id) @app.route('/api/blob/<owner>/<blob_hash>', methods=['GET']) @api() @as_json def blob_get(owner, blob_hash): if g.auth.user != owner: raise ApiException(requests.codes.forbidden, "Only the owner can upload objects.") return dict( head=_generate_presigned_url(S3_HEAD_OBJECT, owner, blob_hash), get=_generate_presigned_url(S3_GET_OBJECT, owner, blob_hash), put=_generate_presigned_url(S3_PUT_OBJECT, owner, blob_hash), ) @app.route('/api/package/<owner>/<package_name>/<package_hash>', methods=['PUT']) @api(schema=PACKAGE_SCHEMA) @as_json def package_put(owner, package_name, package_hash): # TODO: Write access for collaborators. if g.auth.user != owner: raise ApiException(requests.codes.forbidden, "Only the package owner can push packages.") # TODO: Description. data = json.loads(request.data.decode('utf-8'), object_hook=decode_node) dry_run = data.get('dry_run', False) public = data.get('public', False) contents = data['contents'] if hash_contents(contents) != package_hash: raise ApiException(requests.codes.bad_request, "Wrong contents hash") all_hashes = set(find_object_hashes(contents)) # Insert a package if it doesn't already exist. # TODO: Separate endpoint for just creating a package with no versions? package = ( Package.query .with_for_update() .filter_by(owner=owner, name=package_name) .one_or_none() ) if package is None: # Check for case-insensitive matches, and reject the push. package_ci = ( Package.query .filter( sa.and_( sa.func.lower(Package.owner) == sa.func.lower(owner), sa.func.lower(Package.name) == sa.func.lower(package_name) ) ) .one_or_none() ) if package_ci is not None: raise ApiException( requests.codes.forbidden, "Package already exists: %s/%s" % (package_ci.owner, package_ci.name) ) if HAVE_PAYMENTS and not public: customer = _get_or_create_customer() plan = _get_customer_plan(customer) if plan == PaymentPlan.FREE: raise ApiException( requests.codes.payment_required, ("Insufficient permissions. Run `quilt push --public %s/%s` to make " + "this package public, or upgrade your service plan to create " + "private packages: https://quiltdata.com/profile.") % (owner, package_name) ) package = Package(owner=owner, name=package_name) db.session.add(package) owner_access = Access(package=package, user=owner) db.session.add(owner_access) if public: public_access = Access(package=package, user=PUBLIC) db.session.add(public_access) else: if public: public_access = ( Access.query .filter(sa.and_( Access.package == package, Access.user == PUBLIC )) .one_or_none() ) if public_access is None: raise ApiException( requests.codes.forbidden, ("%(user)s/%(pkg)s is private. To make it public, " + "run `quilt access add %(user)s/%(pkg)s public`.") % dict(user=owner, pkg=package_name) ) # Insert an instance if it doesn't already exist. instance = ( Instance.query .with_for_update() .filter_by(package=package, hash=package_hash) .one_or_none() ) # No more error checking at this point, so return from dry-run early. if dry_run: db.session.rollback() # List of signed URLs is potentially huge, so stream it. def _generate(): yield '{"upload_urls":{' for idx, blob_hash in enumerate(all_hashes): comma = ('' if idx == 0 else ',') value = dict( head=_generate_presigned_url(S3_HEAD_OBJECT, owner, blob_hash), put=_generate_presigned_url(S3_PUT_OBJECT, owner, blob_hash) ) yield '%s%s:%s' % (comma, json.dumps(blob_hash), json.dumps(value)) yield '}}' return Response(_generate(), content_type='application/json') if instance is None: instance = Instance( package=package, contents=contents, hash=package_hash, created_by=g.auth.user, updated_by=g.auth.user ) # Add all the hashes that don't exist yet. blobs = ( S3Blob.query .with_for_update() .filter( sa.and_( S3Blob.owner == owner, S3Blob.hash.in_(all_hashes) ) ) .all() ) if all_hashes else [] existing_hashes = {blob.hash for blob in blobs} for blob_hash in all_hashes: if blob_hash not in existing_hashes: instance.blobs.append(S3Blob(owner=owner, hash=blob_hash)) else: # Just update the contents dictionary. # Nothing else could've changed without invalidating the hash. instance.contents = contents instance.updated_by = g.auth.user db.session.add(instance) # Insert a log. log = Log( package=package, instance=instance, author=owner, ) db.session.add(log) db.session.commit() _mp_track( type="push", package_owner=owner, package_name=package_name, public=public, ) return dict() @app.route('/api/package/<owner>/<package_name>/<package_hash>', methods=['GET']) @api(require_login=False) @as_json def package_get(owner, package_name, package_hash): subpath = request.args.get('subpath') instance = _get_instance(g.auth, owner, package_name, package_hash) assert isinstance(instance.contents, RootNode) subnode = instance.contents for component in subpath.split('/') if subpath else []: try: subnode = subnode.children[component] except (AttributeError, KeyError): raise ApiException(requests.codes.not_found, "Invalid subpath: %r" % component) all_hashes = set(find_object_hashes(subnode)) urls = { blob_hash: _generate_presigned_url(S3_GET_OBJECT, owner, blob_hash) for blob_hash in all_hashes } _mp_track( type="install", package_owner=owner, package_name=package_name, subpath=subpath, ) return dict( contents=instance.contents, urls=urls, created_by=instance.created_by, created_at=_utc_datetime_to_ts(instance.created_at), updated_by=instance.updated_by, updated_at=_utc_datetime_to_ts(instance.updated_at), ) def _generate_preview(node, max_depth=PREVIEW_MAX_DEPTH): if isinstance(node, GroupNode): max_children = PREVIEW_MAX_CHILDREN if max_depth else 0 children_preview = [ (name, _generate_preview(child, max_depth - 1)) for name, child in sorted(node.children.items())[:max_children] ] if len(node.children) > max_children: children_preview.append(('...', None)) return children_preview else: return None @app.route('/api/package_preview/<owner>/<package_name>/<package_hash>', methods=['GET']) @api(require_login=False) @as_json def package_preview(owner, package_name, package_hash): instance = _get_instance(g.auth, owner, package_name, package_hash) assert isinstance(instance.contents, RootNode) readme = instance.contents.children.get('README') if isinstance(readme, FileNode): assert len(readme.hashes) == 1 readme_url = _generate_presigned_url(S3_GET_OBJECT, owner, readme.hashes[0]) else: readme_url = None contents_preview = _generate_preview(instance.contents) _mp_track( type="preview", package_owner=owner, package_name=package_name, ) return dict( preview=contents_preview, readme_url=readme_url, created_by=instance.created_by, created_at=_utc_datetime_to_ts(instance.created_at), updated_by=instance.updated_by, updated_at=_utc_datetime_to_ts(instance.updated_at), ) @app.route('/api/package/<owner>/<package_name>/', methods=['GET']) @api(require_login=False) @as_json def package_list(owner, package_name): package = _get_package(g.auth, owner, package_name) instances = ( Instance.query .filter_by(package=package) ) return dict( hashes=[instance.hash for instance in instances] ) @app.route('/api/package/<owner>/<package_name>/', methods=['DELETE']) @api() @as_json def package_delete(owner, package_name): if g.auth.user != owner: raise ApiException(requests.codes.forbidden, "Only the package owner can delete packages.") package = _get_package(g.auth, owner, package_name) db.session.delete(package) db.session.commit() return dict() @app.route('/api/package/<owner>/', methods=['GET']) @api(require_login=False) @as_json def user_packages(owner): packages = ( db.session.query(Package, sa.func.bool_or(Access.user == PUBLIC)) .filter_by(owner=owner) .join(Package.access) .filter(Access.user.in_([g.auth.user, PUBLIC])) .group_by(Package.id) .order_by(Package.name) .all() ) return dict( packages=[ dict( name=package.name, is_public=is_public ) for package, is_public in packages ] ) @app.route('/api/log/<owner>/<package_name>/', methods=['GET']) @api(require_login=False) @as_json def logs_list(owner, package_name): package = _get_package(g.auth, owner, package_name) logs = ( db.session.query(Log, Instance) .filter_by(package=package) .join(Log.instance) # Sort chronologically, but rely on IDs in case of duplicate created times. .order_by(Log.created, Log.id) ) return dict( logs=[dict( hash=instance.hash, created=_utc_datetime_to_ts(log.created), author=log.author ) for log, instance in logs] ) VERSION_SCHEMA = { 'type': 'object', 'properties': { 'hash': { 'type': 'string' } }, 'required': ['hash'] } def normalize_version(version): try: version = Version.normalize(version) except ValueError: raise ApiException(requests.codes.bad_request, "Malformed version") return version @app.route('/api/version/<owner>/<package_name>/<package_version>', methods=['PUT']) @api(schema=VERSION_SCHEMA) @as_json def version_put(owner, package_name, package_version): # TODO: Write access for collaborators. if g.auth.user != owner: raise ApiException( requests.codes.forbidden, "Only the package owner can create versions" ) user_version = package_version package_version = normalize_version(package_version) data = request.get_json() package_hash = data['hash'] instance = ( Instance.query .filter_by(hash=package_hash) .join(Instance.package) .filter_by(owner=owner, name=package_name) .one_or_none() ) if instance is None: raise ApiException(requests.codes.not_found, "Package hash does not exist") version = Version( package_id=instance.package_id, version=package_version, user_version=user_version, instance=instance ) try: db.session.add(version) db.session.commit() except IntegrityError: raise ApiException(requests.codes.conflict, "Version already exists") return dict() @app.route('/api/version/<owner>/<package_name>/<package_version>', methods=['GET']) @api(require_login=False) @as_json def version_get(owner, package_name, package_version): package_version = normalize_version(package_version) package = _get_package(g.auth, owner, package_name) instance = ( Instance.query .join(Instance.versions) .filter_by(package=package, version=package_version) .one_or_none() ) if instance is None: raise ApiException( requests.codes.not_found, "Version %s does not exist" % package_version ) _mp_track( type="get_hash", package_owner=owner, package_name=package_name, package_version=package_version, ) return dict( hash=instance.hash, created_by=instance.created_by, created_at=_utc_datetime_to_ts(instance.created_at), updated_by=instance.updated_by, updated_at=_utc_datetime_to_ts(instance.updated_at), ) @app.route('/api/version/<owner>/<package_name>/', methods=['GET']) @api(require_login=False) @as_json def version_list(owner, package_name): package = _get_package(g.auth, owner, package_name) versions = ( db.session.query(Version, Instance) .filter_by(package=package) .join(Version.instance) .all() ) sorted_versions = sorted(versions, key=lambda row: row.Version.sort_key()) return dict( versions=[ dict( version=version.user_version, hash=instance.hash ) for version, instance in sorted_versions ] ) TAG_SCHEMA = { 'type': 'object', 'properties': { 'hash': { 'type': 'string' } }, 'required': ['hash'] } @app.route('/api/tag/<owner>/<package_name>/<package_tag>', methods=['PUT']) @api(schema=TAG_SCHEMA) @as_json def tag_put(owner, package_name, package_tag): # TODO: Write access for collaborators. if g.auth.user != owner: raise ApiException( requests.codes.forbidden, "Only the package owner can modify tags" ) data = request.get_json() package_hash = data['hash'] instance = ( Instance.query .filter_by(hash=package_hash) .join(Instance.package) .filter_by(owner=owner, name=package_name) .one_or_none() ) if instance is None: raise ApiException(requests.codes.not_found, "Package hash does not exist") # Update an existing tag or create a new one. tag = ( Tag.query .with_for_update() .filter_by(package_id=instance.package_id, tag=package_tag) .one_or_none() ) if tag is None: tag = Tag( package_id=instance.package_id, tag=package_tag, instance=instance ) db.session.add(tag) else: tag.instance = instance db.session.commit() return dict() @app.route('/api/tag/<owner>/<package_name>/<package_tag>', methods=['GET']) @api(require_login=False) @as_json def tag_get(owner, package_name, package_tag): package = _get_package(g.auth, owner, package_name) instance = ( Instance.query .join(Instance.tags) .filter_by(package=package, tag=package_tag) .one_or_none() ) if instance is None: raise ApiException( requests.codes.not_found, "Tag %r does not exist" % package_tag ) _mp_track( type="get_hash", package_owner=owner, package_name=package_name, package_tag=package_tag, ) return dict( hash=instance.hash, created_by=instance.created_by, created_at=_utc_datetime_to_ts(instance.created_at), updated_by=instance.updated_by, updated_at=_utc_datetime_to_ts(instance.updated_at), ) @app.route('/api/tag/<owner>/<package_name>/<package_tag>', methods=['DELETE']) @api() @as_json def tag_delete(owner, package_name, package_tag): # TODO: Write access for collaborators. if g.auth.user != owner: raise ApiException( requests.codes.forbidden, "Only the package owner can delete tags" ) tag = ( Tag.query .with_for_update() .filter_by(tag=package_tag) .join(Tag.package) .filter_by(owner=owner, name=package_name) .one_or_none() ) if tag is None: raise ApiException( requests.codes.not_found, "Package %s/%s tag %r does not exist" % (owner, package_name, package_tag) ) db.session.delete(tag) db.session.commit() return dict() @app.route('/api/tag/<owner>/<package_name>/', methods=['GET']) @api(require_login=False) @as_json def tag_list(owner, package_name): package = _get_package(g.auth, owner, package_name) tags = ( db.session.query(Tag, Instance) .filter_by(package=package) .order_by(Tag.tag) .join(Tag.instance) .all() ) return dict( tags=[ dict( tag=tag.tag, hash=instance.hash ) for tag, instance in tags ] ) @app.route('/api/access/<owner>/<package_name>/<user>', methods=['PUT']) @api() @as_json def access_put(owner, package_name, user): # TODO: use re to check for valid username (e.g., not ../, etc.) if not user: raise ApiException(requests.codes.bad_request, "A valid user is required") if g.auth.user != owner: raise ApiException( requests.codes.forbidden, "Only the package owner can grant access" ) package = ( Package.query .with_for_update() .filter_by(owner=owner, name=package_name) .one_or_none() ) if package is None: raise PackageNotFoundException(owner, package_name) if EMAILREGEX.match(user): email = user.lower() invitation = Invitation(package=package, email=email) db.session.add(invitation) db.session.commit() # Call to Django to send invitation email headers = { AUTHORIZATION_HEADER: g.auth_header } resp = requests.post(INVITE_SEND_URL, headers=headers, data=dict(email=email, owner=g.auth.user, package=package.name, client_id=OAUTH_CLIENT_ID, client_secret=OAUTH_CLIENT_SECRET, callback_url=OAUTH_REDIRECT_URL)) if resp.status_code == requests.codes.unauthorized: raise ApiException( requests.codes.unauthorized, "Invalid credentials" ) elif resp.status_code != requests.codes.ok: raise ApiException(requests.codes.server_error, "Server error") return dict() else: if user != PUBLIC: resp = requests.get(OAUTH_PROFILE_API % user) if resp.status_code == requests.codes.not_found: raise ApiException( requests.codes.not_found, "User %s does not exist" % user ) elif resp.status_code != requests.codes.ok: raise ApiException( requests.codes.server_error, "Unknown error" ) try: access = Access(package=package, user=user) db.session.add(access) db.session.commit() except IntegrityError: raise ApiException(requests.codes.conflict, "The user already has access") return dict() @app.route('/api/access/<owner>/<package_name>/<user>', methods=['GET']) @api() @as_json def access_get(owner, package_name, user): if g.auth.user != owner: raise ApiException( requests.codes.forbidden, "Only the package owner can view access" ) access = ( db.session.query(Access) .filter_by(user=user) .join(Access.package) .filter_by(owner=owner, name=package_name) .one_or_none() ) if access is None: raise PackageNotFoundException(owner, package_name) return dict() @app.route('/api/access/<owner>/<package_name>/<user>', methods=['DELETE']) @api() @as_json def access_delete(owner, package_name, user): if g.auth.user != owner: raise ApiException( requests.codes.forbidden, "Only the package owner can revoke access" ) if user == owner: raise ApiException( requests.codes.forbidden, "Cannot revoke the owner's access" ) if HAVE_PAYMENTS and user == PUBLIC: customer = _get_or_create_customer() plan = _get_customer_plan(customer) if plan == PaymentPlan.FREE: raise ApiException( requests.codes.payment_required, "Insufficient permissions. " + "Upgrade your plan to create private packages: https://quiltdata.com/profile." ) access = ( Access.query .with_for_update() .filter_by(user=user) .join(Access.package) .filter_by(owner=owner, name=package_name) .one_or_none() ) if access is None: raise PackageNotFoundException(owner, package_name) db.session.delete(access) db.session.commit() return dict() @app.route('/api/access/<owner>/<package_name>/', methods=['GET']) @api() @as_json def access_list(owner, package_name): accesses = ( Access.query .join(Access.package) .filter_by(owner=owner, name=package_name) ) can_access = [access.user for access in accesses] is_collaborator = g.auth.user in can_access is_public = PUBLIC in can_access if is_public or is_collaborator: return dict(users=can_access) else: raise PackageNotFoundException(owner, package_name) @app.route('/api/recent_packages/', methods=['GET']) @api(require_login=False) @as_json def recent_packages(): try: count = int(request.args.get('count', '')) except ValueError: count = 10 results = ( db.session.query(Package, sa.func.max(Instance.updated_at)) .join(Package.access) .filter_by(user=PUBLIC) .join(Package.instances) .group_by(Package.id) .order_by(sa.func.max(Instance.updated_at).desc()) .limit(count) .all() ) return dict( packages=[ dict( owner=package.owner, name=package.name, updated_at=updated_at ) for package, updated_at in results ] ) @app.route('/api/search/', methods=['GET']) @api(require_login=False) @as_json def search(): query = request.args.get('q', '') keywords = query.split() if len(keywords) > 5: # Let's not overload the DB with crazy queries. raise ApiException(requests.codes.bad_request, "Too many search terms (max is 5)") filter_list = [ sa.func.strpos( sa.func.lower(sa.func.concat(Package.owner, '/', Package.name)), sa.func.lower(keyword) ) > 0 for keyword in keywords ] results = ( db.session.query(Package, sa.func.bool_or(Access.user == PUBLIC)) .filter(sa.and_(*filter_list)) .join(Package.access) .filter(Access.user.in_([g.auth.user, PUBLIC])) .group_by(Package.id) .order_by( sa.func.lower(Package.owner), sa.func.lower(Package.name) ) .all() ) return dict( packages=[ dict( owner=package.owner, name=package.name, is_public=is_public, ) for package, is_public in results ] ) @app.route('/api/profile', methods=['GET']) @api() @as_json def profile(): if HAVE_PAYMENTS: customer = _get_or_create_customer() plan = _get_customer_plan(customer).value have_cc = customer.sources.total_count > 0 else: plan = None have_cc = None public_access = sa.orm.aliased(Access) # Check for outstanding package sharing invitations invitations = ( db.session.query(Invitation, Package) .filter_by(email=g.auth.email.lower()) .join(Invitation.package) ) for invitation, package in invitations: access = Access(package=package, user=g.auth.user) db.session.add(access) db.session.delete(invitation) if invitations: db.session.commit() packages = ( db.session.query(Package, public_access.user.isnot(None)) .join(Package.access) .filter(Access.user == g.auth.user) .outerjoin(public_access, sa.and_( Package.id == public_access.package_id, public_access.user == PUBLIC)) .order_by(Package.owner, Package.name) .all() ) return dict( packages=dict( own=[ dict( owner=package.owner, name=package.name, is_public=bool(is_public) ) for package, is_public in packages if package.owner == g.auth.user ], shared=[ dict( owner=package.owner, name=package.name, is_public=bool(is_public) ) for package, is_public in packages if package.owner != g.auth.user ], ), plan=plan, have_credit_card=have_cc, ) @app.route('/api/payments/update_plan', methods=['POST']) @api() @as_json def payments_update_plan(): if not HAVE_PAYMENTS: raise ApiException(requests.codes.not_found, "Payments not enabled") plan = request.values.get('plan') try: plan = PaymentPlan(plan) except ValueError: raise ApiException(requests.codes.bad_request, "Invalid plan: %r" % plan) if plan not in (PaymentPlan.FREE, PaymentPlan.INDIVIDUAL, PaymentPlan.BUSINESS_ADMIN): # Cannot switch to the BUSINESS_MEMBER plan manually. raise ApiException(requests.codes.forbidden, "Not allowed to switch to plan: %r" % plan) stripe_token = request.values.get('token') customer = _get_or_create_customer() if _get_customer_plan(customer) == PaymentPlan.BUSINESS_MEMBER: raise ApiException( requests.codes.forbidden, "Not allowed to leave Business plan; contact your admin." ) if stripe_token is not None: customer.source = stripe_token try: customer.save() except stripe.InvalidRequestError as ex: raise ApiException(requests.codes.bad_request, str(ex)) assert customer.sources.total_count if plan != PaymentPlan.FREE and not customer.sources.total_count: # No payment info. raise ApiException( requests.codes.payment_required, "Payment information required to upgrade to %r" % plan.value ) subscription = customer.subscriptions.data[0] subscription.plan = plan.value try: subscription.save() except stripe.InvalidRequestError as ex: raise ApiException(requests.codes.server_error, str(ex)) return dict( plan=plan.value ) @app.route('/api/payments/update_payment', methods=['POST']) @api() @as_json def payments_update_payment(): if not HAVE_PAYMENTS: raise ApiException(requests.codes.not_found, "Payments not enabled") stripe_token = request.values.get('token') if not stripe_token: raise ApiException(requests.codes.bad_request, "Missing token") customer = _get_or_create_customer() customer.source = stripe_token try: customer.save() except stripe.InvalidRequestError as ex: raise ApiException(requests.codes.bad_request, str(ex)) return dict() @app.route('/api/invite/', methods=['GET']) @api(require_login=False) @as_json def invitation_user_list(): invitations = ( db.session.query(Invitation, Package) .filter_by(email=g.auth.email.lower()) .join(Invitation.package) .all() ) return dict(invitations=[dict(invitation_id=invite.id, owner=package.owner, package=package.name, email=invite.email, invited_at=invite.invited_at) for invite, package in invitations]) @app.route('/api/invite/<owner>/<package_name>/', methods=['GET']) @api() @as_json def invitation_package_list(owner, package_name): package = _get_package(g.auth, owner, package_name) invitations = ( Invitation.query .filter_by(package_id=package.id) ) return dict(invitations=[dict(invitation_id=invite.id, owner=package.owner, package=package.name, email=invite.email, invited_at=invite.invited_at) for invite in invitations]) @app.route('/api/log', methods=['POST']) @api(require_login=False, schema=LOG_SCHEMA) @as_json def client_log(): data = request.get_json() for event in data: _mp_track(**event) return dict()
1
15,649
Let's not call it django. Maybe `auth_provider_headers`? `auth_headers`?
quiltdata-quilt
py
@@ -252,7 +252,8 @@ func (s *Server) isClientAuthorized(c *client) bool { tlsMap := s.opts.TLSMap s.optsMu.RUnlock() - // Check custom auth first, then jwts, then nkeys, then multiple users, then token, then single user/pass. + // Check custom auth first, then jwts, then nkeys, then + // multiple users, then token, then single user/pass. if customClientAuthentication != nil { return customClientAuthentication.Check(c) }
1
// Copyright 2012-2018 The NATS 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 server import ( "crypto/tls" "encoding/base64" "net" "strings" "github.com/nats-io/jwt" "github.com/nats-io/nkeys" "golang.org/x/crypto/bcrypt" ) // Authentication is an interface for implementing authentication type Authentication interface { // Check if a client is authorized to connect Check(c ClientAuthentication) bool } // ClientAuthentication is an interface for client authentication type ClientAuthentication interface { // Get options associated with a client GetOpts() *clientOpts // If TLS is enabled, TLS ConnectionState, nil otherwise GetTLSConnectionState() *tls.ConnectionState // Optionally map a user after auth. RegisterUser(*User) // RemoteAddress expose the connection information of the client RemoteAddress() net.Addr } // NkeyUser is for multiple nkey based users type NkeyUser struct { Nkey string `json:"user"` Permissions *Permissions `json:"permissions,omitempty"` Account *Account `json:"account,omitempty"` } // User is for multiple accounts/users. type User struct { Username string `json:"user"` Password string `json:"password"` Permissions *Permissions `json:"permissions,omitempty"` Account *Account `json:"account,omitempty"` } // clone performs a deep copy of the User struct, returning a new clone with // all values copied. func (u *User) clone() *User { if u == nil { return nil } clone := &User{} *clone = *u clone.Permissions = u.Permissions.clone() return clone } // clone performs a deep copy of the NkeyUser struct, returning a new clone with // all values copied. func (n *NkeyUser) clone() *NkeyUser { if n == nil { return nil } clone := &NkeyUser{} *clone = *n clone.Permissions = n.Permissions.clone() return clone } // SubjectPermission is an individual allow and deny struct for publish // and subscribe authorizations. type SubjectPermission struct { Allow []string `json:"allow,omitempty"` Deny []string `json:"deny,omitempty"` } // Permissions are the allowed subjects on a per // publish or subscribe basis. type Permissions struct { Publish *SubjectPermission `json:"publish"` Subscribe *SubjectPermission `json:"subscribe"` } // RoutePermissions are similar to user permissions // but describe what a server can import/export from and to // another server. type RoutePermissions struct { Import *SubjectPermission `json:"import"` Export *SubjectPermission `json:"export"` } // clone will clone an individual subject permission. func (p *SubjectPermission) clone() *SubjectPermission { if p == nil { return nil } clone := &SubjectPermission{} if p.Allow != nil { clone.Allow = make([]string, len(p.Allow)) copy(clone.Allow, p.Allow) } if p.Deny != nil { clone.Deny = make([]string, len(p.Deny)) copy(clone.Deny, p.Deny) } return clone } // clone performs a deep copy of the Permissions struct, returning a new clone // with all values copied. func (p *Permissions) clone() *Permissions { if p == nil { return nil } clone := &Permissions{} if p.Publish != nil { clone.Publish = p.Publish.clone() } if p.Subscribe != nil { clone.Subscribe = p.Subscribe.clone() } return clone } // checkAuthforWarnings will look for insecure settings and log concerns. // Lock is assumed held. func (s *Server) checkAuthforWarnings() { warn := false if s.opts.Password != "" && !isBcrypt(s.opts.Password) { warn = true } for _, u := range s.users { // Skip warn if using TLS certs based auth // unless a password has been left in the config. if u.Password == "" && s.opts.TLSMap { continue } if !isBcrypt(u.Password) { warn = true break } } if warn { // Warning about using plaintext passwords. s.Warnf("Plaintext passwords detected, use nkeys or bcrypt.") } } // If opts.Users or opts.Nkeys have definitions without an account // defined assign them to the default global account. // Lock should be held. func (s *Server) assignGlobalAccountToOrphanUsers() { for _, u := range s.users { if u.Account == nil { u.Account = s.gacc } } for _, u := range s.nkeys { if u.Account == nil { u.Account = s.gacc } } } // configureAuthorization will do any setup needed for authorization. // Lock is assumed held. func (s *Server) configureAuthorization() { if s.opts == nil { return } // Snapshot server options. opts := s.getOpts() // Check for multiple users first // This just checks and sets up the user map if we have multiple users. if opts.CustomClientAuthentication != nil { s.info.AuthRequired = true } else if len(s.trustedKeys) > 0 { s.info.AuthRequired = true } else if opts.Nkeys != nil || opts.Users != nil { // Support both at the same time. if opts.Nkeys != nil { s.nkeys = make(map[string]*NkeyUser) for _, u := range opts.Nkeys { copy := u.clone() if u.Account != nil { copy.Account = s.accounts[u.Account.Name] } s.nkeys[u.Nkey] = copy } } if opts.Users != nil { s.users = make(map[string]*User) for _, u := range opts.Users { copy := u.clone() if u.Account != nil { copy.Account = s.accounts[u.Account.Name] } s.users[u.Username] = copy } } s.assignGlobalAccountToOrphanUsers() s.info.AuthRequired = true } else if opts.Username != "" || opts.Authorization != "" { s.info.AuthRequired = true } else { s.users = nil s.info.AuthRequired = false } } // checkAuthentication will check based on client type and // return boolean indicating if client is authorized. func (s *Server) checkAuthentication(c *client) bool { switch c.kind { case CLIENT: return s.isClientAuthorized(c) case ROUTER: return s.isRouterAuthorized(c) case GATEWAY: return s.isGatewayAuthorized(c) default: return false } } // isClientAuthorized will check the client against the proper authorization method and data. // This could be nkey, token, or username/password based. func (s *Server) isClientAuthorized(c *client) bool { // Snapshot server options by hand and only grab what we really need. s.optsMu.RLock() customClientAuthentication := s.opts.CustomClientAuthentication authorization := s.opts.Authorization username := s.opts.Username password := s.opts.Password tlsMap := s.opts.TLSMap s.optsMu.RUnlock() // Check custom auth first, then jwts, then nkeys, then multiple users, then token, then single user/pass. if customClientAuthentication != nil { return customClientAuthentication.Check(c) } // Grab under lock but process after. var ( nkey *NkeyUser juc *jwt.UserClaims acc *Account user *User ok bool err error ) s.mu.Lock() authRequired := s.info.AuthRequired if !authRequired { // TODO(dlc) - If they send us credentials should we fail? s.mu.Unlock() return true } // Check if we have trustedKeys defined in the server. If so we require a user jwt. if s.trustedKeys != nil { if c.opts.JWT == "" { s.mu.Unlock() c.Debugf("Authentication requires a user JWT") return false } // So we have a valid user jwt here. juc, err = jwt.DecodeUserClaims(c.opts.JWT) if err != nil { s.mu.Unlock() c.Debugf("User JWT not valid: %v", err) return false } vr := jwt.CreateValidationResults() juc.Validate(vr) if vr.IsBlocking(true) { s.mu.Unlock() c.Debugf("User JWT no longer valid: %+v", vr) return false } } // Check if we have nkeys or users for client. hasNkeys := s.nkeys != nil hasUsers := s.users != nil if hasNkeys && c.opts.Nkey != "" { nkey, ok = s.nkeys[c.opts.Nkey] if !ok { s.mu.Unlock() return false } } else if hasUsers { // Check if we are tls verify and are mapping users from the client_certificate if tlsMap { tlsState := c.GetTLSConnectionState() if tlsState == nil { c.Debugf("User required in cert, no TLS connection state") s.mu.Unlock() return false } if len(tlsState.PeerCertificates) == 0 { c.Debugf("User required in cert, no peer certificates found") s.mu.Unlock() return false } cert := tlsState.PeerCertificates[0] if len(tlsState.PeerCertificates) > 1 { c.Debugf("Multiple peer certificates found, selecting first") } hasEmailAddresses := len(cert.EmailAddresses) > 0 hasSubject := len(cert.Subject.String()) > 0 if !hasEmailAddresses && !hasSubject { c.Debugf("User required in cert, none found") s.mu.Unlock() return false } var euser string if hasEmailAddresses { euser = cert.EmailAddresses[0] if len(cert.EmailAddresses) > 1 { c.Debugf("Multiple users found in cert, selecting first [%q]", euser) } } else { euser = cert.Subject.String() } user, ok = s.users[euser] if !ok { c.Debugf("User in cert [%q], not found", euser) s.mu.Unlock() return false } if c.opts.Username != "" { s.Warnf("User found in connect proto, but user required from cert - %v", c) } // Already checked that the client didn't send a user in connect // but we set it here to be able to identify it in the logs. c.opts.Username = euser } else if c.opts.Username != "" { user, ok = s.users[c.opts.Username] if !ok { s.mu.Unlock() return false } } } s.mu.Unlock() // If we have a jwt and a userClaim, make sure we have the Account, etc associated. // We need to look up the account. This will use an account resolver if one is present. if juc != nil { if acc, _ = s.LookupAccount(juc.Issuer); acc == nil { c.Debugf("Account JWT can not be found") return false } if !s.isTrustedIssuer(acc.Issuer) { c.Debugf("Account JWT not signed by trusted operator") return false } if acc.IsExpired() { c.Debugf("Account JWT has expired") return false } // Verify the signature against the nonce. if c.opts.Sig == "" { c.Debugf("Signature missing") return false } sig, err := base64.RawURLEncoding.DecodeString(c.opts.Sig) if err != nil { // Allow fallback to normal base64. sig, err = base64.StdEncoding.DecodeString(c.opts.Sig) if err != nil { c.Debugf("Signature not valid base64") return false } } pub, err := nkeys.FromPublicKey(juc.Subject) if err != nil { c.Debugf("User nkey not valid: %v", err) return false } if err := pub.Verify(c.nonce, sig); err != nil { c.Debugf("Signature not verified") return false } nkey = buildInternalNkeyUser(juc, acc) c.RegisterNkeyUser(nkey) // Generate an event if we have a system account. s.accountConnectEvent(c) // Check if we need to set an auth timer if the user jwt expires. c.checkExpiration(juc.Claims()) return true } if nkey != nil { if c.opts.Sig == "" { c.Debugf("Signature missing") return false } sig, err := base64.RawURLEncoding.DecodeString(c.opts.Sig) if err != nil { // Allow fallback to normal base64. sig, err = base64.StdEncoding.DecodeString(c.opts.Sig) if err != nil { c.Debugf("Signature not valid base64") return false } } pub, err := nkeys.FromPublicKey(c.opts.Nkey) if err != nil { c.Debugf("User nkey not valid: %v", err) return false } if err := pub.Verify(c.nonce, sig); err != nil { c.Debugf("Signature not verified") return false } c.RegisterNkeyUser(nkey) return true } if user != nil { ok = comparePasswords(user.Password, c.opts.Password) // If we are authorized, register the user which will properly setup any permissions // for pub/sub authorizations. if ok { c.RegisterUser(user) } return ok } if authorization != "" { return comparePasswords(authorization, c.opts.Authorization) } else if username != "" { if username != c.opts.Username { return false } return comparePasswords(password, c.opts.Password) } return false } // checkRouterAuth checks optional router authorization which can be nil or username/password. func (s *Server) isRouterAuthorized(c *client) bool { // Snapshot server options. opts := s.getOpts() if s.opts.CustomRouterAuthentication != nil { return s.opts.CustomRouterAuthentication.Check(c) } if opts.Cluster.Username == "" { return true } if opts.Cluster.Username != c.opts.Username { return false } if !comparePasswords(opts.Cluster.Password, c.opts.Password) { return false } return true } // isGatewayAuthorized checks optional gateway authorization which can be nil or username/password. func (s *Server) isGatewayAuthorized(c *client) bool { // Snapshot server options. opts := s.getOpts() if opts.Gateway.Username == "" { return true } if opts.Gateway.Username != c.opts.Username { return false } return comparePasswords(opts.Gateway.Password, c.opts.Password) } // Support for bcrypt stored passwords and tokens. const bcryptPrefix = "$2a$" // isBcrypt checks whether the given password or token is bcrypted. func isBcrypt(password string) bool { return strings.HasPrefix(password, bcryptPrefix) } func comparePasswords(serverPassword, clientPassword string) bool { // Check to see if the server password is a bcrypt hash if isBcrypt(serverPassword) { if err := bcrypt.CompareHashAndPassword([]byte(serverPassword), []byte(clientPassword)); err != nil { return false } } else if serverPassword != clientPassword { return false } return true }
1
8,699
Should we mention TLS map here?
nats-io-nats-server
go
@@ -25,9 +25,12 @@ package net.runelite.client.plugins.playerindicators; import java.awt.Color; + +import net.runelite.api.ClanMemberRank; import net.runelite.client.config.Config; import net.runelite.client.config.ConfigGroup; import net.runelite.client.config.ConfigItem; +import net.runelite.client.config.Range; @ConfigGroup("playerindicators") public interface PlayerIndicatorsConfig extends Config
1
/* * Copyright (c) 2018, Tomas Slusny <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. 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. * * 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. */ package net.runelite.client.plugins.playerindicators; import java.awt.Color; import net.runelite.client.config.Config; import net.runelite.client.config.ConfigGroup; import net.runelite.client.config.ConfigItem; @ConfigGroup("playerindicators") public interface PlayerIndicatorsConfig extends Config { @ConfigItem( position = 0, keyName = "drawOwnName", name = "Highlight own player", description = "Configures whether or not your own player should be highlighted" ) default boolean highlightOwnPlayer() { return false; } @ConfigItem( position = 1, keyName = "ownNameColor", name = "Own player color", description = "Color of your own player" ) default Color getOwnPlayerColor() { return new Color(0, 184, 212); } @ConfigItem( position = 2, keyName = "drawFriendNames", name = "Highlight friends", description = "Configures whether or not friends should be highlighted" ) default boolean highlightFriends() { return true; } @ConfigItem( position = 3, keyName = "friendNameColor", name = "Friend color", description = "Color of friend names" ) default Color getFriendColor() { return new Color(0, 200, 83); } @ConfigItem( position = 4, keyName = "drawClanMemberNames", name = "Highlight clan members", description = "Configures whether or clan members should be highlighted" ) default boolean drawClanMemberNames() { return true; } @ConfigItem( position = 5, keyName = "clanMemberColor", name = "Clan member color", description = "Color of clan members" ) default Color getClanMemberColor() { return new Color(170, 0, 255); } @ConfigItem( position = 6, keyName = "drawTeamMemberNames", name = "Highlight team members", description = "Configures whether or not team members should be highlighted" ) default boolean highlightTeamMembers() { return true; } @ConfigItem( position = 7, keyName = "teamMemberColor", name = "Team member color", description = "Color of team members" ) default Color getTeamMemberColor() { return new Color(19, 110, 247); } @ConfigItem( position = 8, keyName = "drawNonClanMemberNames", name = "Highlight non-clan members", description = "Configures whether or not non-clan members should be highlighted" ) default boolean highlightNonClanMembers() { return false; } @ConfigItem( position = 9, keyName = "nonClanMemberColor", name = "Non-clan member color", description = "Color of non-clan member names" ) default Color getNonClanMemberColor() { return Color.RED; } @ConfigItem( position = 10, keyName = "drawAttackerNames", name = "Highlight attacker players", description = "Configures whether or not attacker players should be highlighted" ) default boolean highlightAttackerPlayers() { return false; } @ConfigItem( position = 11, keyName = "attackerColor", name = "Attacker player color", description = "Color of attacking player names" ) default Color getAttackerPlayerColor() { return new Color(241, 0, 108); } @ConfigItem( position = 12, keyName = "drawAttackableNames", name = "Highlight attackable players", description = "Configures whether or not attackable players should be highlighted" ) default boolean highlightAttackablePlayers() { return false; } @ConfigItem( position = 13, keyName = "attackableColor", name = "Attackable player color", description = "Color of attackable player names" ) default Color getAttackablePlayerColor() { return new Color(231, 122,- 0); } @ConfigItem( position = 14, keyName = "drawPlayerTiles", name = "Draw tiles under players", description = "Configures whether or not tiles under highlighted players should be drawn" ) default boolean drawTiles() { return false; } @ConfigItem( position = 15, keyName = "drawOverheadPlayerNames", name = "Draw names above players", description = "Configures whether or not player names should be drawn above players" ) default boolean drawOverheadPlayerNames() { return true; } @ConfigItem( position = 16, keyName = "drawOverheadLevels", name = "Draw combat levels above players", description = "Configures whether or not combat levels should be drawn above players" ) default boolean drawOverheadLevels() { return false; } @ConfigItem( position = 17, keyName = "drawMinimapNames", name = "Draw names on minimap", description = "Configures whether or not minimap names for players with rendered names should be drawn" ) default boolean drawMinimapNames() { return false; } @ConfigItem( position = 18, keyName = "colorPlayerMenu", name = "Colorize player menu", description = "Color right click menu for players" ) default boolean colorPlayerMenu() { return true; } @ConfigItem( position = 19, keyName = "clanMenuIcons", name = "Show clan ranks", description = "Add clan rank to right click menu and next to player names" ) default boolean showClanRanks() { return true; } @ConfigItem( position = 20, keyName = "showOfflineFriends", name = "Show offline friends", description = "Draw friends names even if they're offline" ) default boolean showOfflineFriends() { return true; } @ConfigItem( position = 21, keyName = "drawHighlightedNames", name = "Draw highlighted player names", description = "Configures whether or not highlighted player names should be drawn" ) default boolean drawHighlightedNames() { return false; } @ConfigItem( keyName = "highlightedNames", name = "Highlighted names", description = "Clan caller names separated by a comma" ) default String getHighlightedNames() { return ""; } @ConfigItem( keyName = "highlightedNamesColor", name = "Highlighted names color", description = "Color of highlighted names" ) default Color getHighlightedNamesColor() { return Color.ORANGE; } @ConfigItem( position = 22, keyName = "drawHighlightedTargetNames", name = "Draw highlighted target names", description = "Configures whether or not highlighted target names should be drawn" ) default boolean drawHighlightedTargetNames() { return false; } @ConfigItem( position = 23, keyName = "highlightedTargetColor", name = "Highlighted target color", description = "Color of highlighted target names" ) default Color getHighlightedTargetColor() { return new Color(255, 100, 183); } @ConfigItem( position = 24, keyName = "limitLevel", name = "Limit Level", description = "Limit the players to show +-x your level. Useful for BH" ) default boolean limitLevel() { return false; } @ConfigItem( position = 25, keyName = "level", name = "Level", description = "The level to limit players shown +-x" ) default int intLevel() { return 5; } @ConfigItem( position = 26, keyName = "wildernessOnly", name = "Show only in wilderness", description = "Toggle whether or not to only show player indicators in the wilderness" ) default boolean showInWildernessOnly() { return false; } /* @ConfigItem( position = 27, keyName="rightClickOverhead", name="Add Overheads to Right Click Menu", description="Feature shows a player's overhead prayer in the right click menu. Useful for DDs, or extremely crowded areas.") default boolean rightClickOverhead() { return false; }*/ }
1
14,800
remove this empty line pl0x
open-osrs-runelite
java
@@ -34,4 +34,10 @@ class NcrDispatcher < LinearDispatcher end } end + + def on_approver_removal(proposal, approvers) + approvers.each{|approver| + CommunicartMailer.notification_for_subscriber(approver.email_address,proposal,"removed").deliver_now + } + end end
1
# This is a temporary way to handle a notification preference # that will eventually be managed at the user level # https://www.pivotaltracker.com/story/show/87656734 class NcrDispatcher < LinearDispatcher def requires_approval_notice?(approval) final_approval(approval.proposal) == approval end def final_approval(proposal) proposal.individual_approvals.last end # Notify approvers who have already approved that this proposal has been # modified. Also notify current approvers that the proposal has been updated def on_proposal_update(proposal) proposal.individual_approvals.approved.each{|approval| CommunicartMailer.notification_for_subscriber(approval.user_email_address, proposal, "already_approved", approval).deliver_now } proposal.currently_awaiting_approvals.each{|approval| if approval.api_token # Approver's been notified through some other means CommunicartMailer.actions_for_approver(approval.user_email_address, approval, "updated").deliver_now else approval.create_api_token! CommunicartMailer.actions_for_approver(approval.user_email_address, approval).deliver_now end } proposal.observers.each{|observer| if observer.role_on(proposal).active_observer? CommunicartMailer.notification_for_subscriber(observer.email_address, proposal, "updated").deliver_now end } end end
1
13,663
Why not have this in the `Dispatcher`? Doesn't seem like NCR-specific functionality.
18F-C2
rb
@@ -26,6 +26,11 @@ import ( ) func CreateTestKV(t *testing.T) kv.RwDB { + s, _, _ := CreateTestSentry(t) + return s.DB +} + +func CreateTestSentry(t *testing.T) (*stages.MockSentry, *core.ChainPack, []*core.ChainPack) { // Configure and generate a sample block chain var ( key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291")
1
package rpcdaemontest import ( "context" "encoding/binary" "math/big" "net" "testing" "github.com/holiman/uint256" "github.com/ledgerwatch/erigon-lib/gointerfaces/txpool" "github.com/ledgerwatch/erigon-lib/kv" "github.com/ledgerwatch/erigon/accounts/abi/bind" "github.com/ledgerwatch/erigon/accounts/abi/bind/backends" "github.com/ledgerwatch/erigon/cmd/rpcdaemon/commands/contracts" "github.com/ledgerwatch/erigon/common" "github.com/ledgerwatch/erigon/consensus/ethash" "github.com/ledgerwatch/erigon/core" "github.com/ledgerwatch/erigon/core/types" "github.com/ledgerwatch/erigon/crypto" "github.com/ledgerwatch/erigon/ethdb/privateapi" "github.com/ledgerwatch/erigon/params" "github.com/ledgerwatch/erigon/turbo/stages" "google.golang.org/grpc" "google.golang.org/grpc/test/bufconn" ) func CreateTestKV(t *testing.T) kv.RwDB { // Configure and generate a sample block chain var ( key, _ = crypto.HexToECDSA("b71c71a67e1177ad4e901695e1b4b9ee17ae16c6668d313eac2f96dbcda3f291") key1, _ = crypto.HexToECDSA("49a7b37aa6f6645917e7b807e9d1c00d4fa71f18343b0d4122a4d2df64dd6fee") key2, _ = crypto.HexToECDSA("8a1f9a8f95be41cd7ccb6168179afb4504aefe388d1e14474d32c45c72ce7b7a") address = crypto.PubkeyToAddress(key.PublicKey) address1 = crypto.PubkeyToAddress(key1.PublicKey) address2 = crypto.PubkeyToAddress(key2.PublicKey) theAddr = common.Address{1} gspec = &core.Genesis{ Config: params.AllEthashProtocolChanges, Alloc: core.GenesisAlloc{ address: {Balance: big.NewInt(9000000000000000000)}, address1: {Balance: big.NewInt(200000000000000000)}, address2: {Balance: big.NewInt(300000000000000000)}, }, GasLimit: 10000000, } chainId = big.NewInt(1337) // this code generates a log signer = types.LatestSignerForChainID(nil) ) m := stages.MockWithGenesis(t, gspec, key) contractBackend := backends.NewSimulatedBackendWithConfig(gspec.Alloc, gspec.Config, gspec.GasLimit) defer contractBackend.Close() transactOpts, _ := bind.NewKeyedTransactorWithChainID(key, chainId) transactOpts1, _ := bind.NewKeyedTransactorWithChainID(key1, chainId) transactOpts2, _ := bind.NewKeyedTransactorWithChainID(key2, chainId) var poly *contracts.Poly var err error var tokenContract *contracts.Token // Generate empty chain to have some orphaned blocks for tests orphanedChain, err := core.GenerateChain(m.ChainConfig, m.Genesis, m.Engine, m.DB, 5, func(i int, block *core.BlockGen) { }, true) if err != nil { t.Fatal(err) } // We generate the blocks without plainstant because it's not supported in core.GenerateChain chain, err := core.GenerateChain(m.ChainConfig, m.Genesis, m.Engine, m.DB, 10, func(i int, block *core.BlockGen) { var ( txn types.Transaction txs []types.Transaction err error ) ctx := context.Background() switch i { case 0: txn, err = types.SignTx(types.NewTransaction(0, theAddr, uint256.NewInt(1000000000000000), 21000, new(uint256.Int), nil), *signer, key) if err != nil { panic(err) } err = contractBackend.SendTransaction(ctx, txn) if err != nil { panic(err) } case 1: txn, err = types.SignTx(types.NewTransaction(1, theAddr, uint256.NewInt(1000000000000000), 21000, new(uint256.Int), nil), *signer, key) if err != nil { panic(err) } err = contractBackend.SendTransaction(ctx, txn) if err != nil { panic(err) } case 2: _, txn, tokenContract, err = contracts.DeployToken(transactOpts, contractBackend, address1) case 3: txn, err = tokenContract.Mint(transactOpts1, address2, big.NewInt(10)) case 4: txn, err = tokenContract.Transfer(transactOpts2, address, big.NewInt(3)) case 5: // Multiple transactions sending small amounts of ether to various accounts var j uint64 var toAddr common.Address nonce := block.TxNonce(address) for j = 1; j <= 32; j++ { binary.BigEndian.PutUint64(toAddr[:], j) txn, err = types.SignTx(types.NewTransaction(nonce, toAddr, uint256.NewInt(1_000_000_000_000_000), 21000, new(uint256.Int), nil), *signer, key) if err != nil { panic(err) } err = contractBackend.SendTransaction(ctx, txn) if err != nil { panic(err) } txs = append(txs, txn) nonce++ } case 6: _, txn, tokenContract, err = contracts.DeployToken(transactOpts, contractBackend, address1) if err != nil { panic(err) } txs = append(txs, txn) txn, err = tokenContract.Mint(transactOpts1, address2, big.NewInt(100)) if err != nil { panic(err) } txs = append(txs, txn) // Multiple transactions sending small amounts of ether to various accounts var j uint64 var toAddr common.Address for j = 1; j <= 32; j++ { binary.BigEndian.PutUint64(toAddr[:], j) txn, err = tokenContract.Transfer(transactOpts2, toAddr, big.NewInt(1)) if err != nil { panic(err) } txs = append(txs, txn) } case 7: var toAddr common.Address nonce := block.TxNonce(address) binary.BigEndian.PutUint64(toAddr[:], 4) txn, err = types.SignTx(types.NewTransaction(nonce, toAddr, uint256.NewInt(1000000000000000), 21000, new(uint256.Int), nil), *signer, key) if err != nil { panic(err) } err = contractBackend.SendTransaction(ctx, txn) if err != nil { panic(err) } txs = append(txs, txn) binary.BigEndian.PutUint64(toAddr[:], 12) txn, err = tokenContract.Transfer(transactOpts2, toAddr, big.NewInt(1)) if err != nil { panic(err) } txs = append(txs, txn) case 8: _, txn, poly, err = contracts.DeployPoly(transactOpts, contractBackend) if err != nil { panic(err) } txs = append(txs, txn) case 9: txn, err = poly.DeployAndDestruct(transactOpts, big.NewInt(0)) if err != nil { panic(err) } txs = append(txs, txn) } if err != nil { panic(err) } if txs == nil && txn != nil { txs = append(txs, txn) } for _, txn := range txs { block.AddTx(txn) } contractBackend.Commit() }, true) if err != nil { t.Fatal(err) } if err = m.InsertChain(orphanedChain); err != nil { t.Fatal(err) } if err = m.InsertChain(chain); err != nil { t.Fatal(err) } return m.DB } type IsMiningMock struct{} func (*IsMiningMock) IsMining() bool { return false } func CreateTestGrpcConn(t *testing.T, m *stages.MockSentry) (context.Context, *grpc.ClientConn) { //nolint ctx, cancel := context.WithCancel(context.Background()) apis := m.Engine.APIs(nil) if len(apis) < 1 { t.Fatal("couldn't instantiate Engine api") } ethashApi := apis[1].Service.(*ethash.API) server := grpc.NewServer() txpool.RegisterTxpoolServer(server, privateapi.NewTxPoolServer(ctx, m.TxPoolP2PServer.TxPool)) txpool.RegisterMiningServer(server, privateapi.NewMiningServer(ctx, &IsMiningMock{}, ethashApi)) listener := bufconn.Listen(1024 * 1024) dialer := func() func(context.Context, string) (net.Conn, error) { go func() { if err := server.Serve(listener); err != nil { panic(err) } }() return func(context.Context, string) (net.Conn, error) { return listener.Dial() } } conn, err := grpc.DialContext(ctx, "", grpc.WithInsecure(), grpc.WithContextDialer(dialer())) if err != nil { t.Fatal(err) } t.Cleanup(func() { cancel() conn.Close() }) return ctx, conn }
1
22,569
If you need only test db, use `memdb.NewTestDB(t)`
ledgerwatch-erigon
go
@@ -533,7 +533,7 @@ namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http await ProduceEnd(); // ForZeroContentLength does not complete the reader nor the writer - if (!messageBody.IsEmpty && _keepAlive) + if (!messageBody.IsEmpty) { // Finish reading the request body in case the app did not. await messageBody.ConsumeAsync();
1
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Buffers; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.IO.Pipelines; using System.Linq; using System.Net; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting.Server; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Protocols; using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Primitives; // ReSharper disable AccessToModifiedClosure namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http { public abstract partial class HttpProtocol : IHttpResponseControl { private static readonly byte[] _bytesConnectionClose = Encoding.ASCII.GetBytes("\r\nConnection: close"); private static readonly byte[] _bytesConnectionKeepAlive = Encoding.ASCII.GetBytes("\r\nConnection: keep-alive"); private static readonly byte[] _bytesTransferEncodingChunked = Encoding.ASCII.GetBytes("\r\nTransfer-Encoding: chunked"); private static readonly byte[] _bytesServer = Encoding.ASCII.GetBytes("\r\nServer: " + Constants.ServerName); private static readonly Action<PipeWriter, ArraySegment<byte>> _writeChunk = WriteChunk; private readonly object _onStartingSync = new Object(); private readonly object _onCompletedSync = new Object(); protected Streams _streams; protected Stack<KeyValuePair<Func<object, Task>, object>> _onStarting; protected Stack<KeyValuePair<Func<object, Task>, object>> _onCompleted; protected volatile int _requestAborted; protected CancellationTokenSource _abortedCts; private CancellationToken? _manuallySetRequestAbortToken; protected RequestProcessingStatus _requestProcessingStatus; protected volatile bool _keepAlive = true; // volatile, see: https://msdn.microsoft.com/en-us/library/x13ttww7.aspx protected bool _upgradeAvailable; private bool _canHaveBody; private bool _autoChunk; protected Exception _applicationException; private BadHttpRequestException _requestRejectedException; protected HttpVersion _httpVersion; private string _requestId; protected int _requestHeadersParsed; protected long _responseBytesWritten; private readonly IHttpProtocolContext _context; private string _scheme = null; public HttpProtocol(IHttpProtocolContext context) { _context = context; ServerOptions = ServiceContext.ServerOptions; HttpResponseControl = this; RequestBodyPipe = CreateRequestBodyPipe(); } public IHttpResponseControl HttpResponseControl { get; set; } public Pipe RequestBodyPipe { get; } public ServiceContext ServiceContext => _context.ServiceContext; private IPEndPoint LocalEndPoint => _context.LocalEndPoint; private IPEndPoint RemoteEndPoint => _context.RemoteEndPoint; public IFeatureCollection ConnectionFeatures => _context.ConnectionFeatures; public IHttpOutputProducer Output { get; protected set; } protected IKestrelTrace Log => ServiceContext.Log; private DateHeaderValueManager DateHeaderValueManager => ServiceContext.DateHeaderValueManager; // Hold direct reference to ServerOptions since this is used very often in the request processing path protected KestrelServerOptions ServerOptions { get; } protected string ConnectionId => _context.ConnectionId; public string ConnectionIdFeature { get; set; } public bool HasStartedConsumingRequestBody { get; set; } public long? MaxRequestBodySize { get; set; } public bool AllowSynchronousIO { get; set; } /// <summary> /// The request id. <seealso cref="HttpContext.TraceIdentifier"/> /// </summary> public string TraceIdentifier { set => _requestId = value; get { // don't generate an ID until it is requested if (_requestId == null) { _requestId = CreateRequestId(); } return _requestId; } } public abstract bool IsUpgradableRequest { get; } public bool IsUpgraded { get; set; } public IPAddress RemoteIpAddress { get; set; } public int RemotePort { get; set; } public IPAddress LocalIpAddress { get; set; } public int LocalPort { get; set; } public string Scheme { get; set; } public string Method { get; set; } public string PathBase { get; set; } public string Path { get; set; } public string QueryString { get; set; } public string RawTarget { get; set; } public string HttpVersion { get { if (_httpVersion == Http.HttpVersion.Http11) { return HttpUtilities.Http11Version; } if (_httpVersion == Http.HttpVersion.Http10) { return HttpUtilities.Http10Version; } if (_httpVersion == Http.HttpVersion.Http2) { return HttpUtilities.Http2Version; } return string.Empty; } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { // GetKnownVersion returns versions which ReferenceEquals interned string // As most common path, check for this only in fast-path and inline if (ReferenceEquals(value, HttpUtilities.Http11Version)) { _httpVersion = Http.HttpVersion.Http11; } else if (ReferenceEquals(value, HttpUtilities.Http10Version)) { _httpVersion = Http.HttpVersion.Http10; } else if (ReferenceEquals(value, HttpUtilities.Http2Version)) { _httpVersion = Http.HttpVersion.Http2; } else { HttpVersionSetSlow(value); } } } [MethodImpl(MethodImplOptions.NoInlining)] private void HttpVersionSetSlow(string value) { if (value == HttpUtilities.Http11Version) { _httpVersion = Http.HttpVersion.Http11; } else if (value == HttpUtilities.Http10Version) { _httpVersion = Http.HttpVersion.Http10; } else if (value == HttpUtilities.Http2Version) { _httpVersion = Http.HttpVersion.Http2; } else { _httpVersion = Http.HttpVersion.Unknown; } } public IHeaderDictionary RequestHeaders { get; set; } public Stream RequestBody { get; set; } private int _statusCode; public int StatusCode { get => _statusCode; set { if (HasResponseStarted) { ThrowResponseAlreadyStartedException(nameof(StatusCode)); } _statusCode = value; } } private string _reasonPhrase; public string ReasonPhrase { get => _reasonPhrase; set { if (HasResponseStarted) { ThrowResponseAlreadyStartedException(nameof(ReasonPhrase)); } _reasonPhrase = value; } } public IHeaderDictionary ResponseHeaders { get; set; } public Stream ResponseBody { get; set; } public CancellationToken RequestAborted { get { // If a request abort token was previously explicitly set, return it. if (_manuallySetRequestAbortToken.HasValue) { return _manuallySetRequestAbortToken.Value; } // Otherwise, get the abort CTS. If we have one, which would mean that someone previously // asked for the RequestAborted token, simply return its token. If we don't, // check to see whether we've already aborted, in which case just return an // already canceled token. Finally, force a source into existence if we still // don't have one, and return its token. var cts = _abortedCts; return cts != null ? cts.Token : (_requestAborted == 1) ? new CancellationToken(true) : RequestAbortedSource.Token; } set { // Set an abort token, overriding one we create internally. This setter and associated // field exist purely to support IHttpRequestLifetimeFeature.set_RequestAborted. _manuallySetRequestAbortToken = value; } } private CancellationTokenSource RequestAbortedSource { get { // Get the abort token, lazily-initializing it if necessary. // Make sure it's canceled if an abort request already came in. // EnsureInitialized can return null since _abortedCts is reset to null // after it's already been initialized to a non-null value. // If EnsureInitialized does return null, this property was accessed between // requests so it's safe to return an ephemeral CancellationTokenSource. var cts = LazyInitializer.EnsureInitialized(ref _abortedCts, () => new CancellationTokenSource()) ?? new CancellationTokenSource(); if (_requestAborted == 1) { cts.Cancel(); } return cts; } } public bool HasResponseStarted => _requestProcessingStatus == RequestProcessingStatus.ResponseStarted; protected HttpRequestHeaders HttpRequestHeaders { get; } = new HttpRequestHeaders(); protected HttpResponseHeaders HttpResponseHeaders { get; } = new HttpResponseHeaders(); public MinDataRate MinRequestBodyDataRate { get; set; } public MinDataRate MinResponseDataRate { get; set; } public void InitializeStreams(MessageBody messageBody) { if (_streams == null) { _streams = new Streams(bodyControl: this, httpResponseControl: this); } (RequestBody, ResponseBody) = _streams.Start(messageBody); } public void PauseStreams() => _streams.Pause(); public void StopStreams() => _streams.Stop(); // For testing internal void ResetState() { _requestProcessingStatus = RequestProcessingStatus.RequestPending; } public void Reset() { _onStarting = null; _onCompleted = null; _requestProcessingStatus = RequestProcessingStatus.RequestPending; _autoChunk = false; _applicationException = null; _requestRejectedException = null; ResetFeatureCollection(); HasStartedConsumingRequestBody = false; MaxRequestBodySize = ServerOptions.Limits.MaxRequestBodySize; AllowSynchronousIO = ServerOptions.AllowSynchronousIO; TraceIdentifier = null; Method = null; PathBase = null; Path = null; RawTarget = null; QueryString = null; _httpVersion = Http.HttpVersion.Unknown; _statusCode = StatusCodes.Status200OK; _reasonPhrase = null; RemoteIpAddress = RemoteEndPoint?.Address; RemotePort = RemoteEndPoint?.Port ?? 0; LocalIpAddress = LocalEndPoint?.Address; LocalPort = LocalEndPoint?.Port ?? 0; ConnectionIdFeature = ConnectionId; HttpRequestHeaders.Reset(); HttpResponseHeaders.Reset(); RequestHeaders = HttpRequestHeaders; ResponseHeaders = HttpResponseHeaders; if (_scheme == null) { var tlsFeature = ConnectionFeatures?[typeof(ITlsConnectionFeature)]; _scheme = tlsFeature != null ? "https" : "http"; } Scheme = _scheme; _manuallySetRequestAbortToken = null; _abortedCts = null; // Allow two bytes for \r\n after headers _requestHeadersParsed = 0; _responseBytesWritten = 0; MinRequestBodyDataRate = ServerOptions.Limits.MinRequestBodyDataRate; MinResponseDataRate = ServerOptions.Limits.MinResponseDataRate; OnReset(); } protected abstract void OnReset(); protected virtual void OnRequestProcessingEnding() { } protected virtual void OnRequestProcessingEnded() { } protected virtual void BeginRequestProcessing() { } protected virtual bool BeginRead(out ValueAwaiter<ReadResult> awaitable) { awaitable = default; return false; } protected abstract string CreateRequestId(); protected abstract MessageBody CreateMessageBody(); protected abstract bool TryParseRequest(ReadResult result, out bool endConnection); private void CancelRequestAbortedToken() { try { RequestAbortedSource.Cancel(); _abortedCts = null; } catch (Exception ex) { Log.ApplicationError(ConnectionId, TraceIdentifier, ex); } } /// <summary> /// Immediate kill the connection and poison the request and response streams. /// </summary> public void Abort(Exception error) { if (Interlocked.Exchange(ref _requestAborted, 1) == 0) { _keepAlive = false; _streams?.Abort(error); Output.Abort(error); // Potentially calling user code. CancelRequestAbortedToken logs any exceptions. ServiceContext.ThreadPool.UnsafeRun(state => ((HttpProtocol)state).CancelRequestAbortedToken(), this); } } public void OnHeader(Span<byte> name, Span<byte> value) { _requestHeadersParsed++; if (_requestHeadersParsed > ServerOptions.Limits.MaxRequestHeaderCount) { ThrowRequestRejected(RequestRejectionReason.TooManyHeaders); } var valueString = value.GetAsciiStringNonNullCharacters(); HttpRequestHeaders.Append(name, valueString); } public async Task ProcessRequestsAsync<TContext>(IHttpApplication<TContext> application) { try { while (_keepAlive) { BeginRequestProcessing(); var result = default(ReadResult); var endConnection = false; do { if (BeginRead(out var awaitable)) { result = await awaitable; } } while (!TryParseRequest(result, out endConnection)); if (endConnection) { return; } var messageBody = CreateMessageBody(); if (!messageBody.RequestKeepAlive) { _keepAlive = false; } _upgradeAvailable = messageBody.RequestUpgrade; InitializeStreams(messageBody); var httpContext = application.CreateContext(this); try { try { KestrelEventSource.Log.RequestStart(this); await application.ProcessRequestAsync(httpContext); if (_requestAborted == 0) { VerifyResponseContentLength(); } } catch (Exception ex) { ReportApplicationError(ex); if (ex is BadHttpRequestException) { throw; } } finally { KestrelEventSource.Log.RequestStop(this); // Trigger OnStarting if it hasn't been called yet and the app hasn't // already failed. If an OnStarting callback throws we can go through // our normal error handling in ProduceEnd. // https://github.com/aspnet/KestrelHttpServer/issues/43 if (!HasResponseStarted && _applicationException == null && _onStarting != null) { await FireOnStarting(); } PauseStreams(); if (_onCompleted != null) { await FireOnCompleted(); } } // If _requestAbort is set, the connection has already been closed. if (_requestAborted == 0) { // Call ProduceEnd() before consuming the rest of the request body to prevent // delaying clients waiting for the chunk terminator: // // https://github.com/dotnet/corefx/issues/17330#issuecomment-288248663 // // This also prevents the 100 Continue response from being sent if the app // never tried to read the body. // https://github.com/aspnet/KestrelHttpServer/issues/2102 // // ProduceEnd() must be called before _application.DisposeContext(), to ensure // HttpContext.Response.StatusCode is correctly set when // IHttpContextFactory.Dispose(HttpContext) is called. await ProduceEnd(); // ForZeroContentLength does not complete the reader nor the writer if (!messageBody.IsEmpty && _keepAlive) { // Finish reading the request body in case the app did not. await messageBody.ConsumeAsync(); } } else if (!HasResponseStarted) { // If the request was aborted and no response was sent, there's no // meaningful status code to log. StatusCode = 0; } } catch (BadHttpRequestException ex) { // Handle BadHttpRequestException thrown during app execution or remaining message body consumption. // This has to be caught here so StatusCode is set properly before disposing the HttpContext // (DisposeContext logs StatusCode). SetBadRequestState(ex); } finally { application.DisposeContext(httpContext, _applicationException); // StopStreams should be called before the end of the "if (!_requestProcessingStopping)" block // to ensure InitializeStreams has been called. StopStreams(); if (HasStartedConsumingRequestBody) { RequestBodyPipe.Reader.Complete(); // Wait for MessageBody.PumpAsync() to call RequestBodyPipe.Writer.Complete(). await messageBody.StopAsync(); // At this point both the request body pipe reader and writer should be completed. RequestBodyPipe.Reset(); } } } } catch (BadHttpRequestException ex) { // Handle BadHttpRequestException thrown during request line or header parsing. // SetBadRequestState logs the error. SetBadRequestState(ex); } catch (ConnectionResetException ex) { // Don't log ECONNRESET errors made between requests. Browsers like IE will reset connections regularly. if (_requestProcessingStatus != RequestProcessingStatus.RequestPending) { Log.RequestProcessingError(ConnectionId, ex); } } catch (IOException ex) { Log.RequestProcessingError(ConnectionId, ex); } catch (Exception ex) { Log.LogWarning(0, ex, CoreStrings.RequestProcessingEndError); } finally { try { OnRequestProcessingEnding(); await TryProduceInvalidRequestResponse(); Output.Dispose(); } catch (Exception ex) { Log.LogWarning(0, ex, CoreStrings.ConnectionShutdownError); } finally { OnRequestProcessingEnded(); } } } public void OnStarting(Func<object, Task> callback, object state) { lock (_onStartingSync) { if (HasResponseStarted) { ThrowResponseAlreadyStartedException(nameof(OnStarting)); } if (_onStarting == null) { _onStarting = new Stack<KeyValuePair<Func<object, Task>, object>>(); } _onStarting.Push(new KeyValuePair<Func<object, Task>, object>(callback, state)); } } public void OnCompleted(Func<object, Task> callback, object state) { lock (_onCompletedSync) { if (_onCompleted == null) { _onCompleted = new Stack<KeyValuePair<Func<object, Task>, object>>(); } _onCompleted.Push(new KeyValuePair<Func<object, Task>, object>(callback, state)); } } protected Task FireOnStarting() { Stack<KeyValuePair<Func<object, Task>, object>> onStarting; lock (_onStartingSync) { onStarting = _onStarting; _onStarting = null; } if (onStarting == null) { return Task.CompletedTask; } else { return FireOnStartingMayAwait(onStarting); } } private Task FireOnStartingMayAwait(Stack<KeyValuePair<Func<object, Task>, object>> onStarting) { try { var count = onStarting.Count; for (var i = 0; i < count; i++) { var entry = onStarting.Pop(); var task = entry.Key.Invoke(entry.Value); if (!ReferenceEquals(task, Task.CompletedTask)) { return FireOnStartingAwaited(task, onStarting); } } } catch (Exception ex) { ReportApplicationError(ex); } return Task.CompletedTask; } private async Task FireOnStartingAwaited(Task currentTask, Stack<KeyValuePair<Func<object, Task>, object>> onStarting) { try { await currentTask; var count = onStarting.Count; for (var i = 0; i < count; i++) { var entry = onStarting.Pop(); await entry.Key.Invoke(entry.Value); } } catch (Exception ex) { ReportApplicationError(ex); } } protected Task FireOnCompleted() { Stack<KeyValuePair<Func<object, Task>, object>> onCompleted; lock (_onCompletedSync) { onCompleted = _onCompleted; _onCompleted = null; } if (onCompleted == null) { return Task.CompletedTask; } else { return FireOnCompletedAwaited(onCompleted); } } private async Task FireOnCompletedAwaited(Stack<KeyValuePair<Func<object, Task>, object>> onCompleted) { foreach (var entry in onCompleted) { try { await entry.Key.Invoke(entry.Value); } catch (Exception ex) { ReportApplicationError(ex); } } } public Task FlushAsync(CancellationToken cancellationToken = default(CancellationToken)) { if (!HasResponseStarted) { var initializeTask = InitializeResponseAsync(0); // If return is Task.CompletedTask no awaiting is required if (!ReferenceEquals(initializeTask, Task.CompletedTask)) { return FlushAsyncAwaited(initializeTask, cancellationToken); } } return Output.FlushAsync(cancellationToken); } [MethodImpl(MethodImplOptions.NoInlining)] private async Task FlushAsyncAwaited(Task initializeTask, CancellationToken cancellationToken) { await initializeTask; await Output.FlushAsync(cancellationToken); } public Task WriteAsync(ArraySegment<byte> data, CancellationToken cancellationToken = default(CancellationToken)) { // For the first write, ensure headers are flushed if WriteDataAsync isn't called. var firstWrite = !HasResponseStarted; if (firstWrite) { var initializeTask = InitializeResponseAsync(data.Count); // If return is Task.CompletedTask no awaiting is required if (!ReferenceEquals(initializeTask, Task.CompletedTask)) { return WriteAsyncAwaited(initializeTask, data, cancellationToken); } } else { VerifyAndUpdateWrite(data.Count); } if (_canHaveBody) { if (_autoChunk) { if (data.Count == 0) { return !firstWrite ? Task.CompletedTask : FlushAsync(cancellationToken); } return WriteChunkedAsync(data, cancellationToken); } else { CheckLastWrite(); return Output.WriteDataAsync(data, cancellationToken: cancellationToken); } } else { HandleNonBodyResponseWrite(); return !firstWrite ? Task.CompletedTask : FlushAsync(cancellationToken); } } public async Task WriteAsyncAwaited(Task initializeTask, ArraySegment<byte> data, CancellationToken cancellationToken) { await initializeTask; // WriteAsyncAwaited is only called for the first write to the body. // Ensure headers are flushed if Write(Chunked)Async isn't called. if (_canHaveBody) { if (_autoChunk) { if (data.Count == 0) { await FlushAsync(cancellationToken); return; } await WriteChunkedAsync(data, cancellationToken); } else { CheckLastWrite(); await Output.WriteDataAsync(data, cancellationToken: cancellationToken); } } else { HandleNonBodyResponseWrite(); await FlushAsync(cancellationToken); } } private void VerifyAndUpdateWrite(int count) { var responseHeaders = HttpResponseHeaders; if (responseHeaders != null && !responseHeaders.HasTransferEncoding && responseHeaders.ContentLength.HasValue && _responseBytesWritten + count > responseHeaders.ContentLength.Value) { _keepAlive = false; throw new InvalidOperationException( CoreStrings.FormatTooManyBytesWritten(_responseBytesWritten + count, responseHeaders.ContentLength.Value)); } _responseBytesWritten += count; } private void CheckLastWrite() { var responseHeaders = HttpResponseHeaders; // Prevent firing request aborted token if this is the last write, to avoid // aborting the request if the app is still running when the client receives // the final bytes of the response and gracefully closes the connection. // // Called after VerifyAndUpdateWrite(), so _responseBytesWritten has already been updated. if (responseHeaders != null && !responseHeaders.HasTransferEncoding && responseHeaders.ContentLength.HasValue && _responseBytesWritten == responseHeaders.ContentLength.Value) { _abortedCts = null; } } protected void VerifyResponseContentLength() { var responseHeaders = HttpResponseHeaders; if (!HttpMethods.IsHead(Method) && !responseHeaders.HasTransferEncoding && responseHeaders.ContentLength.HasValue && _responseBytesWritten < responseHeaders.ContentLength.Value) { // We need to close the connection if any bytes were written since the client // cannot be certain of how many bytes it will receive. if (_responseBytesWritten > 0) { _keepAlive = false; } ReportApplicationError(new InvalidOperationException( CoreStrings.FormatTooFewBytesWritten(_responseBytesWritten, responseHeaders.ContentLength.Value))); } } private Task WriteChunkedAsync(ArraySegment<byte> data, CancellationToken cancellationToken) { return Output.WriteAsync(_writeChunk, data); } private static void WriteChunk(PipeWriter writableBuffer, ArraySegment<byte> buffer) { var writer = OutputWriter.Create(writableBuffer); if (buffer.Count > 0) { ChunkWriter.WriteBeginChunkBytes(ref writer, buffer.Count); writer.Write(new ReadOnlySpan<byte>(buffer.Array, buffer.Offset, buffer.Count)); ChunkWriter.WriteEndChunkBytes(ref writer); } } private static ArraySegment<byte> CreateAsciiByteArraySegment(string text) { var bytes = Encoding.ASCII.GetBytes(text); return new ArraySegment<byte>(bytes); } public void ProduceContinue() { if (HasResponseStarted) { return; } if (_httpVersion != Http.HttpVersion.Http10 && RequestHeaders.TryGetValue("Expect", out var expect) && (expect.FirstOrDefault() ?? "").Equals("100-continue", StringComparison.OrdinalIgnoreCase)) { Output.Write100ContinueAsync(default(CancellationToken)).GetAwaiter().GetResult(); } } public Task InitializeResponseAsync(int firstWriteByteCount) { var startingTask = FireOnStarting(); // If return is Task.CompletedTask no awaiting is required if (!ReferenceEquals(startingTask, Task.CompletedTask)) { return InitializeResponseAwaited(startingTask, firstWriteByteCount); } if (_applicationException != null) { ThrowResponseAbortedException(); } VerifyAndUpdateWrite(firstWriteByteCount); ProduceStart(appCompleted: false); return Task.CompletedTask; } [MethodImpl(MethodImplOptions.NoInlining)] public async Task InitializeResponseAwaited(Task startingTask, int firstWriteByteCount) { await startingTask; if (_applicationException != null) { ThrowResponseAbortedException(); } VerifyAndUpdateWrite(firstWriteByteCount); ProduceStart(appCompleted: false); } private void ProduceStart(bool appCompleted) { if (HasResponseStarted) { return; } _requestProcessingStatus = RequestProcessingStatus.ResponseStarted; CreateResponseHeader(appCompleted); } protected Task TryProduceInvalidRequestResponse() { // If _requestAborted is set, the connection has already been closed. if (_requestRejectedException != null && _requestAborted == 0) { return ProduceEnd(); } return Task.CompletedTask; } protected Task ProduceEnd() { if (_requestRejectedException != null || _applicationException != null) { if (HasResponseStarted) { // We can no longer change the response, so we simply close the connection. _keepAlive = false; return Task.CompletedTask; } // If the request was rejected, the error state has already been set by SetBadRequestState and // that should take precedence. if (_requestRejectedException != null) { SetErrorResponseException(_requestRejectedException); } else { // 500 Internal Server Error SetErrorResponseHeaders(statusCode: StatusCodes.Status500InternalServerError); } } if (!HasResponseStarted) { return ProduceEndAwaited(); } return WriteSuffix(); } [MethodImpl(MethodImplOptions.NoInlining)] private async Task ProduceEndAwaited() { ProduceStart(appCompleted: true); // Force flush await Output.FlushAsync(default(CancellationToken)); await WriteSuffix(); } private Task WriteSuffix() { // _autoChunk should be checked after we are sure ProduceStart() has been called // since ProduceStart() may set _autoChunk to true. if (_autoChunk || _httpVersion == Http.HttpVersion.Http2) { return WriteSuffixAwaited(); } if (_keepAlive) { Log.ConnectionKeepAlive(ConnectionId); } if (HttpMethods.IsHead(Method) && _responseBytesWritten > 0) { Log.ConnectionHeadResponseBodyWrite(ConnectionId, _responseBytesWritten); } return Task.CompletedTask; } private async Task WriteSuffixAwaited() { // For the same reason we call CheckLastWrite() in Content-Length responses. _abortedCts = null; await Output.WriteStreamSuffixAsync(default(CancellationToken)); if (_keepAlive) { Log.ConnectionKeepAlive(ConnectionId); } if (HttpMethods.IsHead(Method) && _responseBytesWritten > 0) { Log.ConnectionHeadResponseBodyWrite(ConnectionId, _responseBytesWritten); } } private void CreateResponseHeader(bool appCompleted) { var responseHeaders = HttpResponseHeaders; var hasConnection = responseHeaders.HasConnection; var connectionOptions = HttpHeaders.ParseConnection(responseHeaders.HeaderConnection); var hasTransferEncoding = responseHeaders.HasTransferEncoding; var transferCoding = HttpHeaders.GetFinalTransferCoding(responseHeaders.HeaderTransferEncoding); if (_keepAlive && hasConnection && (connectionOptions & ConnectionOptions.KeepAlive) != ConnectionOptions.KeepAlive) { _keepAlive = false; } // https://tools.ietf.org/html/rfc7230#section-3.3.1 // If any transfer coding other than // chunked is applied to a response payload body, the sender MUST either // apply chunked as the final transfer coding or terminate the message // by closing the connection. if (hasTransferEncoding && transferCoding != TransferCoding.Chunked) { _keepAlive = false; } // Set whether response can have body _canHaveBody = StatusCanHaveBody(StatusCode) && Method != "HEAD"; // Don't set the Content-Length or Transfer-Encoding headers // automatically for HEAD requests or 204, 205, 304 responses. if (_canHaveBody) { if (!hasTransferEncoding && !responseHeaders.ContentLength.HasValue) { if (appCompleted && StatusCode != StatusCodes.Status101SwitchingProtocols) { // Since the app has completed and we are only now generating // the headers we can safely set the Content-Length to 0. responseHeaders.ContentLength = 0; } else { // Note for future reference: never change this to set _autoChunk to true on HTTP/1.0 // connections, even if we were to infer the client supports it because an HTTP/1.0 request // was received that used chunked encoding. Sending a chunked response to an HTTP/1.0 // client would break compliance with RFC 7230 (section 3.3.1): // // A server MUST NOT send a response containing Transfer-Encoding unless the corresponding // request indicates HTTP/1.1 (or later). // // This also covers HTTP/2, which forbids chunked encoding in RFC 7540 (section 8.1: // // The chunked transfer encoding defined in Section 4.1 of [RFC7230] MUST NOT be used in HTTP/2. if (_httpVersion == Http.HttpVersion.Http11 && StatusCode != StatusCodes.Status101SwitchingProtocols) { _autoChunk = true; responseHeaders.SetRawTransferEncoding("chunked", _bytesTransferEncodingChunked); } else { _keepAlive = false; } } } } else if (hasTransferEncoding) { RejectNonBodyTransferEncodingResponse(appCompleted); } responseHeaders.SetReadOnly(); if (!hasConnection && _httpVersion != Http.HttpVersion.Http2) { if (!_keepAlive) { responseHeaders.SetRawConnection("close", _bytesConnectionClose); } else if (_httpVersion == Http.HttpVersion.Http10) { responseHeaders.SetRawConnection("keep-alive", _bytesConnectionKeepAlive); } } if (ServerOptions.AddServerHeader && !responseHeaders.HasServer) { responseHeaders.SetRawServer(Constants.ServerName, _bytesServer); } if (!responseHeaders.HasDate) { var dateHeaderValues = DateHeaderValueManager.GetDateHeaderValues(); responseHeaders.SetRawDate(dateHeaderValues.String, dateHeaderValues.Bytes); } Output.WriteResponseHeaders(StatusCode, ReasonPhrase, responseHeaders); } public bool StatusCanHaveBody(int statusCode) { // List of status codes taken from Microsoft.Net.Http.Server.Response return statusCode != StatusCodes.Status204NoContent && statusCode != StatusCodes.Status205ResetContent && statusCode != StatusCodes.Status304NotModified; } private void ThrowResponseAlreadyStartedException(string value) { throw new InvalidOperationException(CoreStrings.FormatParameterReadOnlyAfterResponseStarted(value)); } private void RejectNonBodyTransferEncodingResponse(bool appCompleted) { var ex = new InvalidOperationException(CoreStrings.FormatHeaderNotAllowedOnResponse("Transfer-Encoding", StatusCode)); if (!appCompleted) { // Back out of header creation surface exeception in user code _requestProcessingStatus = RequestProcessingStatus.AppStarted; throw ex; } else { ReportApplicationError(ex); // 500 Internal Server Error SetErrorResponseHeaders(statusCode: StatusCodes.Status500InternalServerError); } } private void SetErrorResponseException(BadHttpRequestException ex) { SetErrorResponseHeaders(ex.StatusCode); if (!StringValues.IsNullOrEmpty(ex.AllowedHeader)) { HttpResponseHeaders.HeaderAllow = ex.AllowedHeader; } } private void SetErrorResponseHeaders(int statusCode) { Debug.Assert(!HasResponseStarted, $"{nameof(SetErrorResponseHeaders)} called after response had already started."); StatusCode = statusCode; ReasonPhrase = null; var responseHeaders = HttpResponseHeaders; responseHeaders.Reset(); var dateHeaderValues = DateHeaderValueManager.GetDateHeaderValues(); responseHeaders.SetRawDate(dateHeaderValues.String, dateHeaderValues.Bytes); responseHeaders.ContentLength = 0; if (ServerOptions.AddServerHeader) { responseHeaders.SetRawServer(Constants.ServerName, _bytesServer); } } public void HandleNonBodyResponseWrite() { // Writes to HEAD response are ignored and logged at the end of the request if (Method != "HEAD") { // Throw Exception for 204, 205, 304 responses. throw new InvalidOperationException(CoreStrings.FormatWritingToResponseBodyNotSupported(StatusCode)); } } private void ThrowResponseAbortedException() { throw new ObjectDisposedException(CoreStrings.UnhandledApplicationException, _applicationException); } public void ThrowRequestRejected(RequestRejectionReason reason) => throw BadHttpRequestException.GetException(reason); public void ThrowRequestRejected(RequestRejectionReason reason, string detail) => throw BadHttpRequestException.GetException(reason, detail); public void ThrowRequestTargetRejected(Span<byte> target) => throw GetInvalidRequestTargetException(target); private BadHttpRequestException GetInvalidRequestTargetException(Span<byte> target) => BadHttpRequestException.GetException( RequestRejectionReason.InvalidRequestTarget, Log.IsEnabled(LogLevel.Information) ? target.GetAsciiStringEscaped(Constants.MaxExceptionDetailSize) : string.Empty); public void SetBadRequestState(RequestRejectionReason reason) { SetBadRequestState(BadHttpRequestException.GetException(reason)); } public void SetBadRequestState(BadHttpRequestException ex) { Log.ConnectionBadRequest(ConnectionId, ex); if (!HasResponseStarted) { SetErrorResponseException(ex); } _keepAlive = false; _requestRejectedException = ex; } protected void ReportApplicationError(Exception ex) { if (_applicationException == null) { _applicationException = ex; } else if (_applicationException is AggregateException) { _applicationException = new AggregateException(_applicationException, ex).Flatten(); } else { _applicationException = new AggregateException(_applicationException, ex); } Log.ApplicationError(ConnectionId, TraceIdentifier, ex); } private Pipe CreateRequestBodyPipe() => new Pipe(new PipeOptions ( pool: _context.MemoryPool, readerScheduler: ServiceContext.ThreadPool, writerScheduler: PipeScheduler.Inline, pauseWriterThreshold: 1, resumeWriterThreshold: 1 )); } }
1
14,772
I'm not sure I like setting the IsEmpty property true for upgraded connections since it feels a middle misleading. Maybe we can leave the ForUpgrade class as is and change this condition to `if (!messageBody.IsEmpty && !messageBody.RequestUpgrade)` to make things more explicit.
aspnet-KestrelHttpServer
.cs
@@ -141,7 +141,7 @@ ActiveRecord::Schema.define(version: 20151123235600) do t.integer "client_data_id" t.string "client_data_type", limit: 255 t.integer "requester_id" - t.string "public_id" + t.string "public_id", limit: 255 end add_index "proposals", ["client_data_id", "client_data_type"], name: "index_proposals_on_client_data_id_and_client_data_type", using: :btree
1
# encoding: UTF-8 # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your # database schema. If you need to create the application database on another # system, you should be using db:schema:load, not running all the migrations # from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 20151123235600) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" create_table "active_admin_comments", force: :cascade do |t| t.string "namespace" t.text "body" t.string "resource_id", null: false t.string "resource_type", null: false t.integer "author_id" t.string "author_type" t.datetime "created_at" t.datetime "updated_at" end add_index "active_admin_comments", ["author_type", "author_id"], name: "index_active_admin_comments_on_author_type_and_author_id", using: :btree add_index "active_admin_comments", ["namespace"], name: "index_active_admin_comments_on_namespace", using: :btree add_index "active_admin_comments", ["resource_type", "resource_id"], name: "index_active_admin_comments_on_resource_type_and_resource_id", using: :btree create_table "api_tokens", force: :cascade do |t| t.string "access_token", limit: 255 t.datetime "expires_at" t.datetime "created_at" t.datetime "updated_at" t.datetime "used_at" t.integer "step_id" end add_index "api_tokens", ["access_token"], name: "index_api_tokens_on_access_token", unique: true, using: :btree create_table "approval_delegates", force: :cascade do |t| t.integer "assigner_id" t.integer "assignee_id" t.datetime "created_at" t.datetime "updated_at" end create_table "attachments", force: :cascade do |t| t.string "file_file_name", limit: 255 t.string "file_content_type", limit: 255 t.integer "file_file_size" t.datetime "file_updated_at" t.integer "proposal_id" t.integer "user_id" t.datetime "created_at" t.datetime "updated_at" end create_table "comments", force: :cascade do |t| t.text "comment_text" t.datetime "created_at" t.datetime "updated_at" t.integer "user_id" t.integer "proposal_id" t.boolean "update_comment" end add_index "comments", ["proposal_id"], name: "index_comments_on_proposal_id", using: :btree create_table "delayed_jobs", force: :cascade do |t| t.integer "priority", default: 0, null: false t.integer "attempts", default: 0, null: false t.text "handler", null: false t.text "last_error" t.datetime "run_at" t.datetime "locked_at" t.datetime "failed_at" t.string "locked_by" t.string "queue" t.datetime "created_at" t.datetime "updated_at" end add_index "delayed_jobs", ["priority", "run_at"], name: "delayed_jobs_priority", using: :btree create_table "gsa18f_procurements", force: :cascade do |t| t.string "office", limit: 255 t.text "justification", default: "", null: false t.string "link_to_product", limit: 255, default: "", null: false t.integer "quantity" t.datetime "date_requested" t.string "additional_info", limit: 255 t.decimal "cost_per_unit" t.text "product_name_and_description" t.boolean "recurring", default: false, null: false t.string "recurring_interval", limit: 255, default: "Daily" t.integer "recurring_length" t.datetime "created_at" t.datetime "updated_at" t.integer "urgency" t.integer "purchase_type", null: false end create_table "ncr_work_orders", force: :cascade do |t| t.decimal "amount" t.string "expense_type", limit: 255 t.string "vendor", limit: 255 t.boolean "not_to_exceed", default: false, null: false t.string "building_number", limit: 255 t.boolean "emergency", default: false, null: false t.string "rwa_number", limit: 255 t.string "org_code", limit: 255 t.string "code", limit: 255 t.string "project_title", limit: 255 t.text "description" t.datetime "created_at" t.datetime "updated_at" t.boolean "direct_pay", default: false, null: false t.string "cl_number", limit: 255 t.string "function_code", limit: 255 t.string "soc_code", limit: 255 end create_table "proposal_roles", force: :cascade do |t| t.integer "role_id", null: false t.integer "user_id", null: false t.integer "proposal_id", null: false end add_index "proposal_roles", ["role_id", "user_id", "proposal_id"], name: "index_proposal_roles_on_role_id_and_user_id_and_proposal_id", unique: true, using: :btree create_table "proposals", force: :cascade do |t| t.string "status", limit: 255 t.string "flow", limit: 255, default: "parallel" t.datetime "created_at" t.datetime "updated_at" t.integer "client_data_id" t.string "client_data_type", limit: 255 t.integer "requester_id" t.string "public_id" end add_index "proposals", ["client_data_id", "client_data_type"], name: "index_proposals_on_client_data_id_and_client_data_type", using: :btree create_table "roles", force: :cascade do |t| t.string "name" t.datetime "created_at" t.datetime "updated_at" end add_index "roles", ["name"], name: "roles_name_idx", unique: true, using: :btree create_table "steps", force: :cascade do |t| t.integer "user_id" t.string "status", limit: 255 t.datetime "created_at" t.datetime "updated_at" t.integer "position" t.integer "proposal_id" t.datetime "approved_at" t.string "type" t.integer "parent_id" t.integer "min_children_needed" t.integer "completer_id" end add_index "steps", ["completer_id"], name: "index_steps_on_completer_id", using: :btree add_index "steps", ["user_id", "proposal_id"], name: "steps_user_proposal_idx", unique: true, using: :btree create_table "taggings", force: :cascade do |t| t.integer "tag_id" t.integer "taggable_id" t.string "taggable_type" t.integer "tagger_id" t.string "tagger_type" t.string "context", limit: 128 t.datetime "created_at" end add_index "taggings", ["tag_id", "taggable_id", "taggable_type", "context", "tagger_id", "tagger_type"], name: "taggings_idx", unique: true, using: :btree add_index "taggings", ["taggable_id", "taggable_type", "context"], name: "index_taggings_on_taggable_id_and_taggable_type_and_context", using: :btree create_table "tags", force: :cascade do |t| t.string "name" t.integer "taggings_count", default: 0 end add_index "tags", ["name"], name: "index_tags_on_name", unique: true, using: :btree create_table "user_roles", force: :cascade do |t| t.integer "user_id", null: false t.integer "role_id", null: false end add_index "user_roles", ["user_id", "role_id"], name: "index_user_roles_on_user_id_and_role_id", unique: true, using: :btree create_table "users", force: :cascade do |t| t.string "email_address", limit: 255 t.string "first_name", limit: 255 t.string "last_name", limit: 255 t.datetime "created_at" t.datetime "updated_at" t.string "client_slug", limit: 255 t.boolean "active", default: true end create_table "versions", force: :cascade do |t| t.string "item_type", null: false t.integer "item_id", null: false t.string "event", null: false t.string "whodunnit" t.text "object" t.datetime "created_at" end add_index "versions", ["item_type", "item_id"], name: "index_versions_on_item_type_and_item_id", using: :btree add_foreign_key "approval_delegates", "users", column: "assignee_id", name: "assignee_id_fkey" add_foreign_key "approval_delegates", "users", column: "assigner_id", name: "assigner_id_fkey" add_foreign_key "attachments", "proposals", name: "proposal_id_fkey" add_foreign_key "attachments", "users", name: "user_id_fkey" add_foreign_key "comments", "proposals", name: "proposal_id_fkey" add_foreign_key "comments", "users", name: "user_id_fkey" add_foreign_key "proposal_roles", "proposals", name: "proposal_id_fkey" add_foreign_key "proposal_roles", "roles", name: "role_id_fkey" add_foreign_key "proposal_roles", "users", name: "user_id_fkey" add_foreign_key "proposals", "users", column: "requester_id", name: "requester_id_fkey" add_foreign_key "steps", "proposals", name: "proposal_id_fkey" add_foreign_key "steps", "steps", column: "parent_id", name: "parent_id_fkey", on_delete: :cascade add_foreign_key "steps", "users", column: "completer_id", name: "completer_id_fkey" add_foreign_key "steps", "users", name: "user_id_fkey" add_foreign_key "user_roles", "roles", name: "role_id_fkey" add_foreign_key "user_roles", "users", name: "user_id_fkey" end
1
15,754
git checkout since this is unrelated to this PR? (running migrations also changes this for me -- not sure why it keeps going back and forth
18F-C2
rb
@@ -154,7 +154,7 @@ class _TLSSignature(_GenericTLSSessionInheritance): #XXX 'sig_alg' should be set in __init__ depending on the context. """ name = "TLS Digital Signature" - fields_desc = [SigAndHashAlgField("sig_alg", 0x0401, _tls_hash_sig), + fields_desc = [SigAndHashAlgField("sig_alg", 0x0804, _tls_hash_sig), SigLenField("sig_len", None, fmt="!H", length_of="sig_val"), SigValField("sig_val", None,
1
# This file is part of Scapy # Copyright (C) 2007, 2008, 2009 Arnaud Ebalard # 2015, 2016, 2017 Maxence Tury # This program is published under a GPLv2 license """ TLS key exchange logic. """ from __future__ import absolute_import import math import struct from scapy.config import conf, crypto_validator from scapy.error import warning from scapy.fields import ByteEnumField, ByteField, EnumField, FieldLenField, \ FieldListField, PacketField, ShortEnumField, ShortField, \ StrFixedLenField, StrLenField from scapy.compat import orb from scapy.packet import Packet, Raw, Padding from scapy.layers.tls.cert import PubKeyRSA, PrivKeyRSA from scapy.layers.tls.session import _GenericTLSSessionInheritance from scapy.layers.tls.basefields import _tls_version, _TLSClientVersionField from scapy.layers.tls.crypto.pkcs1 import pkcs_i2osp, pkcs_os2ip from scapy.layers.tls.crypto.groups import _ffdh_groups, _tls_named_curves import scapy.modules.six as six if conf.crypto_valid: from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import dh, ec ############################################################################### # Common Fields # ############################################################################### _tls_hash_sig = {0x0000: "none+anon", 0x0001: "none+rsa", 0x0002: "none+dsa", 0x0003: "none+ecdsa", 0x0100: "md5+anon", 0x0101: "md5+rsa", 0x0102: "md5+dsa", 0x0103: "md5+ecdsa", 0x0200: "sha1+anon", 0x0201: "sha1+rsa", 0x0202: "sha1+dsa", 0x0203: "sha1+ecdsa", 0x0300: "sha224+anon", 0x0301: "sha224+rsa", 0x0302: "sha224+dsa", 0x0303: "sha224+ecdsa", 0x0400: "sha256+anon", 0x0401: "sha256+rsa", 0x0402: "sha256+dsa", 0x0403: "sha256+ecdsa", 0x0500: "sha384+anon", 0x0501: "sha384+rsa", 0x0502: "sha384+dsa", 0x0503: "sha384+ecdsa", 0x0600: "sha512+anon", 0x0601: "sha512+rsa", 0x0602: "sha512+dsa", 0x0603: "sha512+ecdsa", 0x0804: "sha256+rsaepss", 0x0805: "sha384+rsaepss", 0x0806: "sha512+rsaepss", 0x0807: "ed25519", 0x0808: "ed448", 0x0809: "sha256+rsapss", 0x080a: "sha384+rsapss", 0x080b: "sha512+rsapss"} def phantom_mode(pkt): """ We expect this. If tls_version is not set, this means we did not process any complete ClientHello, so we're most probably reading/building a signature_algorithms extension, hence we cannot be in phantom_mode. However, if the tls_version has been set, we test for TLS 1.2. """ if not pkt.tls_session: return False if not pkt.tls_session.tls_version: return False return pkt.tls_session.tls_version < 0x0303 def phantom_decorate(f, get_or_add): """ Decorator for version-dependent fields. If get_or_add is True (means get), we return s, self.phantom_value. If it is False (means add), we return s. """ def wrapper(*args): self, pkt, s = args[:3] if phantom_mode(pkt): if get_or_add: return s, self.phantom_value return s return f(*args) return wrapper class SigAndHashAlgField(EnumField): """Used in _TLSSignature.""" phantom_value = None getfield = phantom_decorate(EnumField.getfield, True) addfield = phantom_decorate(EnumField.addfield, False) class SigAndHashAlgsLenField(FieldLenField): """Used in TLS_Ext_SignatureAlgorithms and TLSCertificateResquest.""" phantom_value = 0 getfield = phantom_decorate(FieldLenField.getfield, True) addfield = phantom_decorate(FieldLenField.addfield, False) class SigAndHashAlgsField(FieldListField): """Used in TLS_Ext_SignatureAlgorithms and TLSCertificateResquest.""" phantom_value = [] getfield = phantom_decorate(FieldListField.getfield, True) addfield = phantom_decorate(FieldListField.addfield, False) class SigLenField(FieldLenField): """There is a trick for SSLv2, which uses implicit lengths...""" def getfield(self, pkt, s): v = pkt.tls_session.tls_version if v and v < 0x0300: return s, None return super(SigLenField, self).getfield(pkt, s) def addfield(self, pkt, s, val): """With SSLv2 you will never be able to add a sig_len.""" v = pkt.tls_session.tls_version if v and v < 0x0300: return s return super(SigLenField, self).addfield(pkt, s, val) class SigValField(StrLenField): """There is a trick for SSLv2, which uses implicit lengths...""" def getfield(self, pkt, m): s = pkt.tls_session if s.tls_version and s.tls_version < 0x0300: if len(s.client_certs) > 0: sig_len = s.client_certs[0].pubKey.pubkey.key_size // 8 else: warning("No client certificate provided. " "We're making a wild guess about the signature size.") sig_len = 256 return m[sig_len:], self.m2i(pkt, m[:sig_len]) return super(SigValField, self).getfield(pkt, m) class _TLSSignature(_GenericTLSSessionInheritance): """ Prior to TLS 1.2, digitally-signed structure implicitly used the concatenation of a MD5 hash and a SHA-1 hash. Then TLS 1.2 introduced explicit SignatureAndHashAlgorithms, i.e. couples of (hash_alg, sig_alg). See RFC 5246, section 7.4.1.4.1. By default, the _TLSSignature implements the TLS 1.2 scheme, but if it is provided a TLS context with a tls_version < 0x0303 at initialization, it will fall back to the implicit signature. Even more, the 'sig_len' field won't be used with SSLv2. #XXX 'sig_alg' should be set in __init__ depending on the context. """ name = "TLS Digital Signature" fields_desc = [SigAndHashAlgField("sig_alg", 0x0401, _tls_hash_sig), SigLenField("sig_len", None, fmt="!H", length_of="sig_val"), SigValField("sig_val", None, length_from=lambda pkt: pkt.sig_len)] def __init__(self, *args, **kargs): super(_TLSSignature, self).__init__(*args, **kargs) if (self.tls_session and self.tls_session.tls_version): if self.tls_session.tls_version < 0x0303: self.sig_alg = None elif self.tls_session.tls_version == 0x0304: # For TLS 1.3 signatures, set the signature # algorithm to RSA-PSS self.sig_alg = 0x0804 def _update_sig(self, m, key): """ Sign 'm' with the PrivKey 'key' and update our own 'sig_val'. Note that, even when 'sig_alg' is not None, we use the signature scheme of the PrivKey (neither do we care to compare the both of them). """ if self.sig_alg is None: if self.tls_session.tls_version >= 0x0300: self.sig_val = key.sign(m, t='pkcs', h='md5-sha1') else: self.sig_val = key.sign(m, t='pkcs', h='md5') else: h, sig = _tls_hash_sig[self.sig_alg].split('+') if sig.endswith('pss'): t = "pss" else: t = "pkcs" self.sig_val = key.sign(m, t=t, h=h) def _verify_sig(self, m, cert): """ Verify that our own 'sig_val' carries the signature of 'm' by the key associated to the Cert 'cert'. """ if self.sig_val: if self.sig_alg: h, sig = _tls_hash_sig[self.sig_alg].split('+') if sig.endswith('pss'): t = "pss" else: t = "pkcs" return cert.verify(m, self.sig_val, t=t, h=h) else: if self.tls_session.tls_version >= 0x0300: return cert.verify(m, self.sig_val, t='pkcs', h='md5-sha1') else: return cert.verify(m, self.sig_val, t='pkcs', h='md5') return False def guess_payload_class(self, p): return Padding class _TLSSignatureField(PacketField): """ Used for 'digitally-signed struct' in several ServerKeyExchange, and also in CertificateVerify. We can handle the anonymous case. """ __slots__ = ["length_from"] def __init__(self, name, default, length_from=None, remain=0): self.length_from = length_from PacketField.__init__(self, name, default, _TLSSignature, remain=remain) def m2i(self, pkt, m): tmp_len = self.length_from(pkt) if tmp_len == 0: return None return _TLSSignature(m, tls_session=pkt.tls_session) def getfield(self, pkt, s): i = self.m2i(pkt, s) if i is None: return s, None remain = b"" if conf.padding_layer in i: r = i[conf.padding_layer] del r.underlayer.payload remain = r.load return remain, i class _TLSServerParamsField(PacketField): """ This is a dispatcher for the Server*DHParams below, used in TLSServerKeyExchange and based on the key_exchange.server_kx_msg_cls. When this cls is None, it means that we should not see a ServerKeyExchange, so we grab everything within length_from and make it available using Raw. When the context has not been set (e.g. when no ServerHello was parsed or dissected beforehand), we (kinda) clumsily set the cls by trial and error. XXX We could use Serv*DHParams.check_params() once it has been implemented. """ __slots__ = ["length_from"] def __init__(self, name, default, length_from=None, remain=0): self.length_from = length_from PacketField.__init__(self, name, default, None, remain=remain) def m2i(self, pkt, m): s = pkt.tls_session tmp_len = self.length_from(pkt) if s.prcs: cls = s.prcs.key_exchange.server_kx_msg_cls(m) if cls is None: return None, Raw(m[:tmp_len]) / Padding(m[tmp_len:]) return cls(m, tls_session=s) else: try: p = ServerDHParams(m, tls_session=s) if pkcs_os2ip(p.load[:2]) not in _tls_hash_sig: raise Exception return p except Exception: cls = _tls_server_ecdh_cls_guess(m) p = cls(m, tls_session=s) if pkcs_os2ip(p.load[:2]) not in _tls_hash_sig: return None, Raw(m[:tmp_len]) / Padding(m[tmp_len:]) return p ############################################################################### # Server Key Exchange parameters & value # ############################################################################### # Finite Field Diffie-Hellman class ServerDHParams(_GenericTLSSessionInheritance): """ ServerDHParams for FFDH-based key exchanges, as defined in RFC 5246/7.4.3. Either with .fill_missing() or .post_dissection(), the server_kx_privkey or server_kx_pubkey of the TLS context are updated according to the parsed/assembled values. It is the user's responsibility to store and restore the original values if he wants to keep them. For instance, this could be done between the writing of a ServerKeyExchange and the receiving of a ClientKeyExchange (which includes secret generation). """ name = "Server FFDH parameters" fields_desc = [FieldLenField("dh_plen", None, length_of="dh_p"), StrLenField("dh_p", "", length_from=lambda pkt: pkt.dh_plen), FieldLenField("dh_glen", None, length_of="dh_g"), StrLenField("dh_g", "", length_from=lambda pkt: pkt.dh_glen), FieldLenField("dh_Yslen", None, length_of="dh_Ys"), StrLenField("dh_Ys", "", length_from=lambda pkt: pkt.dh_Yslen)] @crypto_validator def fill_missing(self): """ We do not want TLSServerKeyExchange.build() to overload and recompute things every time it is called. This method can be called specifically to have things filled in a smart fashion. Note that we do not expect default_params.g to be more than 0xff. """ s = self.tls_session default_params = _ffdh_groups['modp2048'][0].parameter_numbers() default_mLen = _ffdh_groups['modp2048'][1] if not self.dh_p: self.dh_p = pkcs_i2osp(default_params.p, default_mLen // 8) if self.dh_plen is None: self.dh_plen = len(self.dh_p) if not self.dh_g: self.dh_g = pkcs_i2osp(default_params.g, 1) if self.dh_glen is None: self.dh_glen = 1 p = pkcs_os2ip(self.dh_p) g = pkcs_os2ip(self.dh_g) real_params = dh.DHParameterNumbers(p, g).parameters(default_backend()) if not self.dh_Ys: s.server_kx_privkey = real_params.generate_private_key() pubkey = s.server_kx_privkey.public_key() y = pubkey.public_numbers().y self.dh_Ys = pkcs_i2osp(y, pubkey.key_size // 8) # else, we assume that the user wrote the server_kx_privkey by himself if self.dh_Yslen is None: self.dh_Yslen = len(self.dh_Ys) if not s.client_kx_ffdh_params: s.client_kx_ffdh_params = real_params @crypto_validator def register_pubkey(self): """ XXX Check that the pubkey received is in the group. """ p = pkcs_os2ip(self.dh_p) g = pkcs_os2ip(self.dh_g) pn = dh.DHParameterNumbers(p, g) y = pkcs_os2ip(self.dh_Ys) public_numbers = dh.DHPublicNumbers(y, pn) s = self.tls_session s.server_kx_pubkey = public_numbers.public_key(default_backend()) if not s.client_kx_ffdh_params: s.client_kx_ffdh_params = pn.parameters(default_backend()) def post_dissection(self, r): try: self.register_pubkey() except ImportError: pass def guess_payload_class(self, p): """ The signature after the params gets saved as Padding. This way, the .getfield() which _TLSServerParamsField inherits from PacketField will return the signature remain as expected. """ return Padding # Elliptic Curve Diffie-Hellman _tls_ec_curve_types = {1: "explicit_prime", 2: "explicit_char2", 3: "named_curve"} _tls_ec_basis_types = {0: "ec_basis_trinomial", 1: "ec_basis_pentanomial"} class ECCurvePkt(Packet): name = "Elliptic Curve" fields_desc = [FieldLenField("alen", None, length_of="a", fmt="B"), StrLenField("a", "", length_from=lambda pkt: pkt.alen), FieldLenField("blen", None, length_of="b", fmt="B"), StrLenField("b", "", length_from=lambda pkt: pkt.blen)] # Char2 Curves class ECTrinomialBasis(Packet): name = "EC Trinomial Basis" val = 0 fields_desc = [FieldLenField("klen", None, length_of="k", fmt="B"), StrLenField("k", "", length_from=lambda pkt: pkt.klen)] def guess_payload_class(self, p): return Padding class ECPentanomialBasis(Packet): name = "EC Pentanomial Basis" val = 1 fields_desc = [FieldLenField("k1len", None, length_of="k1", fmt="B"), StrLenField("k1", "", length_from=lambda pkt: pkt.k1len), FieldLenField("k2len", None, length_of="k2", fmt="B"), StrLenField("k2", "", length_from=lambda pkt: pkt.k2len), FieldLenField("k3len", None, length_of="k3", fmt="B"), StrLenField("k3", "", length_from=lambda pkt: pkt.k3len)] def guess_payload_class(self, p): return Padding _tls_ec_basis_cls = {0: ECTrinomialBasis, 1: ECPentanomialBasis} class _ECBasisTypeField(ByteEnumField): __slots__ = ["basis_type_of"] def __init__(self, name, default, enum, basis_type_of, remain=0): self.basis_type_of = basis_type_of EnumField.__init__(self, name, default, enum, "B") def i2m(self, pkt, x): if x is None: fld, fval = pkt.getfield_and_val(self.basis_type_of) x = fld.i2basis_type(pkt, fval) return x class _ECBasisField(PacketField): __slots__ = ["clsdict", "basis_type_from"] def __init__(self, name, default, basis_type_from, clsdict, remain=0): self.clsdict = clsdict self.basis_type_from = basis_type_from PacketField.__init__(self, name, default, None, remain=remain) def m2i(self, pkt, m): basis = self.basis_type_from(pkt) cls = self.clsdict[basis] return cls(m) def i2basis_type(self, pkt, x): val = 0 try: val = x.val except Exception: pass return val # Distinct ECParameters ## # To support the different ECParameters structures defined in Sect. 5.4 of # RFC 4492, we define 3 separates classes for implementing the 3 associated # ServerECDHParams: ServerECDHNamedCurveParams, ServerECDHExplicitPrimeParams # and ServerECDHExplicitChar2Params (support for this one is only partial). # The most frequent encounter of the 3 is (by far) ServerECDHNamedCurveParams. class ServerECDHExplicitPrimeParams(_GenericTLSSessionInheritance): """ We provide parsing abilities for ExplicitPrimeParams, but there is no support from the cryptography library, hence no context operations. """ name = "Server ECDH parameters - Explicit Prime" fields_desc = [ByteEnumField("curve_type", 1, _tls_ec_curve_types), FieldLenField("plen", None, length_of="p", fmt="B"), StrLenField("p", "", length_from=lambda pkt: pkt.plen), PacketField("curve", None, ECCurvePkt), FieldLenField("baselen", None, length_of="base", fmt="B"), StrLenField("base", "", length_from=lambda pkt: pkt.baselen), FieldLenField("orderlen", None, length_of="order", fmt="B"), StrLenField("order", "", length_from=lambda pkt: pkt.orderlen), FieldLenField("cofactorlen", None, length_of="cofactor", fmt="B"), StrLenField("cofactor", "", length_from=lambda pkt: pkt.cofactorlen), FieldLenField("pointlen", None, length_of="point", fmt="B"), StrLenField("point", "", length_from=lambda pkt: pkt.pointlen)] def fill_missing(self): """ Note that if it is not set by the user, the cofactor will always be 1. It is true for most, but not all, TLS elliptic curves. """ if self.curve_type is None: self.curve_type = _tls_ec_curve_types["explicit_prime"] def guess_payload_class(self, p): return Padding class ServerECDHExplicitChar2Params(_GenericTLSSessionInheritance): """ We provide parsing abilities for Char2Params, but there is no support from the cryptography library, hence no context operations. """ name = "Server ECDH parameters - Explicit Char2" fields_desc = [ByteEnumField("curve_type", 2, _tls_ec_curve_types), ShortField("m", None), _ECBasisTypeField("basis_type", None, _tls_ec_basis_types, "basis"), _ECBasisField("basis", ECTrinomialBasis(), lambda pkt: pkt.basis_type, _tls_ec_basis_cls), PacketField("curve", ECCurvePkt(), ECCurvePkt), FieldLenField("baselen", None, length_of="base", fmt="B"), StrLenField("base", "", length_from=lambda pkt: pkt.baselen), ByteField("order", None), ByteField("cofactor", None), FieldLenField("pointlen", None, length_of="point", fmt="B"), StrLenField("point", "", length_from=lambda pkt: pkt.pointlen)] def fill_missing(self): if self.curve_type is None: self.curve_type = _tls_ec_curve_types["explicit_char2"] def guess_payload_class(self, p): return Padding class ServerECDHNamedCurveParams(_GenericTLSSessionInheritance): name = "Server ECDH parameters - Named Curve" fields_desc = [ByteEnumField("curve_type", 3, _tls_ec_curve_types), ShortEnumField("named_curve", None, _tls_named_curves), FieldLenField("pointlen", None, length_of="point", fmt="B"), StrLenField("point", None, length_from=lambda pkt: pkt.pointlen)] @crypto_validator def fill_missing(self): """ We do not want TLSServerKeyExchange.build() to overload and recompute things every time it is called. This method can be called specifically to have things filled in a smart fashion. XXX We should account for the point_format (before 'point' filling). """ s = self.tls_session if self.curve_type is None: self.curve_type = _tls_ec_curve_types["named_curve"] if self.named_curve is None: curve = ec.SECP256R1() s.server_kx_privkey = ec.generate_private_key(curve, default_backend()) self.named_curve = next((cid for cid, name in six.iteritems(_tls_named_curves) # noqa: E501 if name == curve.name), 0) else: curve_name = _tls_named_curves.get(self.named_curve) if curve_name is None: # this fallback is arguable curve = ec.SECP256R1() else: curve_cls = ec._CURVE_TYPES.get(curve_name) if curve_cls is None: # this fallback is arguable curve = ec.SECP256R1() else: curve = curve_cls() s.server_kx_privkey = ec.generate_private_key(curve, default_backend()) if self.point is None: pubkey = s.server_kx_privkey.public_key() try: # cryptography >= 2.5 self.point = pubkey.public_bytes( serialization.Encoding.X962, serialization.PublicFormat.UncompressedPoint ) except TypeError: # older versions self.key_exchange = pubkey.public_numbers().encode_point() # else, we assume that the user wrote the server_kx_privkey by himself if self.pointlen is None: self.pointlen = len(self.point) if not s.client_kx_ecdh_params: s.client_kx_ecdh_params = curve @crypto_validator def register_pubkey(self): """ XXX Support compressed point format. XXX Check that the pubkey received is on the curve. """ # point_format = 0 # if self.point[0] in [b'\x02', b'\x03']: # point_format = 1 curve_name = _tls_named_curves[self.named_curve] curve = ec._CURVE_TYPES[curve_name]() s = self.tls_session try: # cryptography >= 2.5 import_point = ec.EllipticCurvePublicKey.from_encoded_point s.server_kx_pubkey = import_point(curve, self.point) except AttributeError: import_point = ec.EllipticCurvePublicNumbers.from_encoded_point pubnum = import_point(curve, self.point) s.server_kx_pubkey = pubnum.public_key(default_backend()) if not s.client_kx_ecdh_params: s.client_kx_ecdh_params = curve def post_dissection(self, r): try: self.register_pubkey() except ImportError: pass def guess_payload_class(self, p): return Padding _tls_server_ecdh_cls = {1: ServerECDHExplicitPrimeParams, 2: ServerECDHExplicitChar2Params, 3: ServerECDHNamedCurveParams} def _tls_server_ecdh_cls_guess(m): if not m: return None curve_type = orb(m[0]) return _tls_server_ecdh_cls.get(curve_type, None) # RSA Encryption (export) class ServerRSAParams(_GenericTLSSessionInheritance): """ Defined for RSA_EXPORT kx : it enables servers to share RSA keys shorter than their principal {>512}-bit key, when it is not allowed for kx. This should not appear in standard RSA kx negotiation, as the key has already been advertised in the Certificate message. """ name = "Server RSA_EXPORT parameters" fields_desc = [FieldLenField("rsamodlen", None, length_of="rsamod"), StrLenField("rsamod", "", length_from=lambda pkt: pkt.rsamodlen), FieldLenField("rsaexplen", None, length_of="rsaexp"), StrLenField("rsaexp", "", length_from=lambda pkt: pkt.rsaexplen)] @crypto_validator def fill_missing(self): k = PrivKeyRSA() k.fill_and_store(modulusLen=512) self.tls_session.server_tmp_rsa_key = k pubNum = k.pubkey.public_numbers() if not self.rsamod: self.rsamod = pkcs_i2osp(pubNum.n, k.pubkey.key_size // 8) if self.rsamodlen is None: self.rsamodlen = len(self.rsamod) rsaexplen = math.ceil(math.log(pubNum.e) / math.log(2) / 8.) if not self.rsaexp: self.rsaexp = pkcs_i2osp(pubNum.e, rsaexplen) if self.rsaexplen is None: self.rsaexplen = len(self.rsaexp) @crypto_validator def register_pubkey(self): mLen = self.rsamodlen m = self.rsamod e = self.rsaexp self.tls_session.server_tmp_rsa_key = PubKeyRSA((e, m, mLen)) def post_dissection(self, pkt): try: self.register_pubkey() except ImportError: pass def guess_payload_class(self, p): return Padding # Pre-Shared Key class ServerPSKParams(Packet): """ XXX We provide some parsing abilities for ServerPSKParams, but the context operations have not been implemented yet. See RFC 4279. Note that we do not cover the (EC)DHE_PSK key exchange, which should contain a Server*DHParams after 'psk_identity_hint'. """ name = "Server PSK parameters" fields_desc = [FieldLenField("psk_identity_hint_len", None, length_of="psk_identity_hint", fmt="!H"), StrLenField("psk_identity_hint", "", length_from=lambda pkt: pkt.psk_identity_hint_len)] # noqa: E501 def fill_missing(self): pass def post_dissection(self, pkt): pass def guess_payload_class(self, p): return Padding ############################################################################### # Client Key Exchange value # ############################################################################### # FFDH/ECDH class ClientDiffieHellmanPublic(_GenericTLSSessionInheritance): """ If the user provides a value for dh_Yc attribute, we assume he will set the pms and ms accordingly and trigger the key derivation on his own. XXX As specified in 7.4.7.2. of RFC 4346, we should distinguish the needs for implicit or explicit value depending on availability of DH parameters in *client* certificate. For now we can only do ephemeral/explicit DH. """ name = "Client DH Public Value" fields_desc = [FieldLenField("dh_Yclen", None, length_of="dh_Yc"), StrLenField("dh_Yc", "", length_from=lambda pkt: pkt.dh_Yclen)] @crypto_validator def fill_missing(self): s = self.tls_session params = s.client_kx_ffdh_params s.client_kx_privkey = params.generate_private_key() pubkey = s.client_kx_privkey.public_key() y = pubkey.public_numbers().y self.dh_Yc = pkcs_i2osp(y, pubkey.key_size // 8) if s.client_kx_privkey and s.server_kx_pubkey: pms = s.client_kx_privkey.exchange(s.server_kx_pubkey) s.pre_master_secret = pms s.compute_ms_and_derive_keys() def post_build(self, pkt, pay): if not self.dh_Yc: try: self.fill_missing() except ImportError: pass if self.dh_Yclen is None: self.dh_Yclen = len(self.dh_Yc) return pkcs_i2osp(self.dh_Yclen, 2) + self.dh_Yc + pay def post_dissection(self, m): """ First we update the client DHParams. Then, we try to update the server DHParams generated during Server*DHParams building, with the shared secret. Finally, we derive the session keys and update the context. """ s = self.tls_session # if there are kx params and keys, we assume the crypto library is ok if s.client_kx_ffdh_params: y = pkcs_os2ip(self.dh_Yc) param_numbers = s.client_kx_ffdh_params.parameter_numbers() public_numbers = dh.DHPublicNumbers(y, param_numbers) s.client_kx_pubkey = public_numbers.public_key(default_backend()) if s.server_kx_privkey and s.client_kx_pubkey: ZZ = s.server_kx_privkey.exchange(s.client_kx_pubkey) s.pre_master_secret = ZZ s.compute_ms_and_derive_keys() def guess_payload_class(self, p): return Padding class ClientECDiffieHellmanPublic(_GenericTLSSessionInheritance): """ Note that the 'len' field is 1 byte longer than with the previous class. """ name = "Client ECDH Public Value" fields_desc = [FieldLenField("ecdh_Yclen", None, length_of="ecdh_Yc", fmt="B"), StrLenField("ecdh_Yc", "", length_from=lambda pkt: pkt.ecdh_Yclen)] @crypto_validator def fill_missing(self): s = self.tls_session params = s.client_kx_ecdh_params s.client_kx_privkey = ec.generate_private_key(params, default_backend()) pubkey = s.client_kx_privkey.public_key() x = pubkey.public_numbers().x y = pubkey.public_numbers().y self.ecdh_Yc = (b"\x04" + pkcs_i2osp(x, params.key_size // 8) + pkcs_i2osp(y, params.key_size // 8)) if s.client_kx_privkey and s.server_kx_pubkey: pms = s.client_kx_privkey.exchange(ec.ECDH(), s.server_kx_pubkey) s.pre_master_secret = pms s.compute_ms_and_derive_keys() def post_build(self, pkt, pay): if not self.ecdh_Yc: try: self.fill_missing() except ImportError: pass if self.ecdh_Yclen is None: self.ecdh_Yclen = len(self.ecdh_Yc) return pkcs_i2osp(self.ecdh_Yclen, 1) + self.ecdh_Yc + pay def post_dissection(self, m): s = self.tls_session # if there are kx params and keys, we assume the crypto library is ok if s.client_kx_ecdh_params: try: # cryptography >= 2.5 import_point = ec.EllipticCurvePublicKey.from_encoded_point s.client_kx_pubkey = import_point(s.client_kx_ecdh_params, self.ecdh_Yc) except AttributeError: import_point = ec.EllipticCurvePublicNumbers.from_encoded_point pub_num = import_point(s.client_kx_ecdh_params, self.ecdh_Yc) s.client_kx_pubkey = pub_num.public_key(default_backend()) if s.server_kx_privkey and s.client_kx_pubkey: ZZ = s.server_kx_privkey.exchange(ec.ECDH(), s.client_kx_pubkey) s.pre_master_secret = ZZ s.compute_ms_and_derive_keys() # RSA Encryption (standard & export) class _UnEncryptedPreMasterSecret(Raw): """ When the content of an EncryptedPreMasterSecret could not be deciphered, we use this class to represent the encrypted data. """ name = "RSA Encrypted PreMaster Secret (protected)" def __init__(self, *args, **kargs): kargs.pop('tls_session', None) return super(_UnEncryptedPreMasterSecret, self).__init__(*args, **kargs) # noqa: E501 class EncryptedPreMasterSecret(_GenericTLSSessionInheritance): """ Pay attention to implementation notes in section 7.4.7.1 of RFC 5246. """ name = "RSA Encrypted PreMaster Secret" fields_desc = [_TLSClientVersionField("client_version", None, _tls_version), StrFixedLenField("random", None, 46)] @classmethod def dispatch_hook(cls, _pkt=None, *args, **kargs): if 'tls_session' in kargs: s = kargs['tls_session'] if s.server_tmp_rsa_key is None and s.server_rsa_key is None: return _UnEncryptedPreMasterSecret return EncryptedPreMasterSecret def pre_dissect(self, m): s = self.tls_session tbd = m tls_version = s.tls_version if tls_version is None: tls_version = s.advertised_tls_version if tls_version >= 0x0301: if len(m) < 2: # Should not happen return m tmp_len = struct.unpack("!H", m[:2])[0] if len(m) != tmp_len + 2: err = "TLS 1.0+, but RSA Encrypted PMS with no explicit length" warning(err) else: tbd = m[2:] if s.server_tmp_rsa_key is not None: # priority is given to the tmp_key, if there is one decrypted = s.server_tmp_rsa_key.decrypt(tbd) pms = decrypted[-48:] elif s.server_rsa_key is not None: decrypted = s.server_rsa_key.decrypt(tbd) pms = decrypted[-48:] else: # the dispatch_hook is supposed to prevent this case pms = b"\x00" * 48 err = "No server RSA key to decrypt Pre Master Secret. Skipping." warning(err) s.pre_master_secret = pms s.compute_ms_and_derive_keys() return pms def post_build(self, pkt, pay): """ We encrypt the premaster secret (the 48 bytes) with either the server certificate or the temporary RSA key provided in a server key exchange message. After that step, we add the 2 bytes to provide the length, as described in implementation notes at the end of section 7.4.7.1. """ enc = pkt s = self.tls_session s.pre_master_secret = enc s.compute_ms_and_derive_keys() if s.server_tmp_rsa_key is not None: enc = s.server_tmp_rsa_key.encrypt(pkt, t="pkcs") elif s.server_certs is not None and len(s.server_certs) > 0: enc = s.server_certs[0].encrypt(pkt, t="pkcs") else: warning("No material to encrypt Pre Master Secret") tmp_len = b"" tls_version = s.tls_version if tls_version is None: tls_version = s.advertised_tls_version if tls_version >= 0x0301: tmp_len = struct.pack("!H", len(enc)) return tmp_len + enc + pay def guess_payload_class(self, p): return Padding # Pre-Shared Key class ClientPSKIdentity(Packet): """ XXX We provide parsing abilities for ServerPSKParams, but the context operations have not been implemented yet. See RFC 4279. Note that we do not cover the (EC)DHE_PSK nor the RSA_PSK key exchange, which should contain either an EncryptedPMS or a ClientDiffieHellmanPublic. """ name = "Server PSK parameters" fields_desc = [FieldLenField("psk_identity_len", None, length_of="psk_identity", fmt="!H"), StrLenField("psk_identity", "", length_from=lambda pkt: pkt.psk_identity_len)]
1
17,446
Is this change needed?
secdev-scapy
py
@@ -1321,7 +1321,7 @@ void MolPickler::_pickleAtom(std::ostream &ss, const Atom *atom) { streamWrite(ss, ENDQUERY); } if (getAtomMapNumber(atom, tmpInt)) { - if (tmpInt < 128) { + if (tmpInt >= 0 && tmpInt < 128) { tmpChar = static_cast<char>(tmpInt % 128); streamWrite(ss, ATOM_MAPNUMBER, tmpChar); } else {
1
// // Copyright (C) 2001-2018 Greg Landrum and Rational Discovery LLC // // @@ All Rights Reserved @@ // This file is part of the RDKit. // The contents are covered by the terms of the BSD license // which is included in the file license.txt, found at the root // of the RDKit source tree. // #include <GraphMol/RDKitBase.h> #include <GraphMol/RDKitQueries.h> #include <GraphMol/MolPickler.h> #include <GraphMol/MonomerInfo.h> #include <GraphMol/StereoGroup.h> #include <GraphMol/SubstanceGroup.h> #include <RDGeneral/utils.h> #include <RDGeneral/RDLog.h> #include <RDGeneral/StreamOps.h> #include <RDGeneral/types.h> #include <DataStructs/DatastructsStreamOps.h> #include <Query/QueryObjects.h> #include <map> #include <cstdint> #include <boost/algorithm/string.hpp> #ifdef RDK_THREADSAFE_SSS #include <mutex> #endif using std::int32_t; using std::uint32_t; namespace RDKit { const int32_t MolPickler::versionMajor = 10; const int32_t MolPickler::versionMinor = 1; const int32_t MolPickler::versionPatch = 0; const int32_t MolPickler::endianId = 0xDEADBEEF; void streamWrite(std::ostream &ss, MolPickler::Tags tag) { unsigned char tmp = static_cast<unsigned char>(tag); streamWrite(ss, tmp); } template <typename T> void streamWrite(std::ostream &ss, MolPickler::Tags tag, const T &what) { streamWrite(ss, tag); streamWrite(ss, what); }; void streamRead(std::istream &ss, MolPickler::Tags &tag, int version) { if (version < 7000) { int32_t tmp; streamRead(ss, tmp, version); tag = static_cast<MolPickler::Tags>(tmp); } else { unsigned char tmp; streamRead(ss, tmp, version); tag = static_cast<MolPickler::Tags>(tmp); } } namespace { static unsigned int defaultProperties = PicklerOps::NoProps; static CustomPropHandlerVec defaultPropHandlers = {}; #ifdef RDK_THREADSAFE_SSS std::mutex &propmutex_get() { // create on demand static std::mutex _mutex; return _mutex; } void propmutex_create() { std::mutex &mutex = propmutex_get(); std::lock_guard<std::mutex> test_lock(mutex); } std::mutex &GetPropMutex() { static std::once_flag flag; std::call_once(flag, propmutex_create); return propmutex_get(); } #endif } // namespace unsigned int MolPickler::getDefaultPickleProperties() { #ifdef RDK_THREADSAFE_SSS std::lock_guard<std::mutex> lock(GetPropMutex()); #endif unsigned int props = defaultProperties; return props; } void MolPickler::setDefaultPickleProperties(unsigned int props) { #ifdef RDK_THREADSAFE_SSS std::lock_guard<std::mutex> lock(GetPropMutex()); #endif defaultProperties = props; } const CustomPropHandlerVec &MolPickler::getCustomPropHandlers() { #ifdef RDK_THREADSAFE_SSS std::lock_guard<std::mutex> lock(GetPropMutex()); #endif if (defaultPropHandlers.size() == 0) { // initialize handlers defaultPropHandlers.push_back(std::make_shared<DataStructsExplicitBitVecPropHandler>()); } return defaultPropHandlers; } void MolPickler::addCustomPropHandler(const CustomPropHandler &handler) { #ifdef RDK_THREADSAFE_SSS std::lock_guard<std::mutex> lock(GetPropMutex()); #endif if (defaultPropHandlers.size() == 0) { // initialize handlers defaultPropHandlers.push_back(std::make_shared<DataStructsExplicitBitVecPropHandler>()); } defaultPropHandlers.push_back(std::shared_ptr<CustomPropHandler>(handler.clone())); } namespace { using namespace Queries; template <class T> void pickleQuery(std::ostream &ss, const Query<int, T const *, true> *query) { PRECONDITION(query, "no query"); streamWrite(ss, query->getDescription()); if (query->getNegation()) streamWrite(ss, MolPickler::QUERY_ISNEGATED); int32_t queryVal; // if (typeid(*query)==typeid(ATOM_BOOL_QUERY)){ // streamWrite(ss,QUERY_BOOL); if (typeid(*query) == typeid(AndQuery<int, T const *, true>)) { streamWrite(ss, MolPickler::QUERY_AND); } else if (typeid(*query) == typeid(OrQuery<int, T const *, true>)) { streamWrite(ss, MolPickler::QUERY_OR); } else if (typeid(*query) == typeid(XOrQuery<int, T const *, true>)) { streamWrite(ss, MolPickler::QUERY_XOR); } else if (typeid(*query) == typeid(EqualityQuery<int, T const *, true>)) { streamWrite(ss, MolPickler::QUERY_EQUALS); queryVal = static_cast<const EqualityQuery<int, T const *, true> *>(query) ->getVal(); streamWrite(ss, MolPickler::QUERY_VALUE, queryVal); queryVal = static_cast<const EqualityQuery<int, T const *, true> *>(query) ->getTol(); streamWrite(ss, queryVal); } else if (typeid(*query) == typeid(GreaterQuery<int, T const *, true>)) { streamWrite(ss, MolPickler::QUERY_GREATER); queryVal = static_cast<const GreaterQuery<int, T const *, true> *>(query) ->getVal(); streamWrite(ss, MolPickler::QUERY_VALUE, queryVal); queryVal = static_cast<const GreaterQuery<int, T const *, true> *>(query) ->getTol(); streamWrite(ss, queryVal); } else if (typeid(*query) == typeid(GreaterEqualQuery<int, T const *, true>)) { streamWrite(ss, MolPickler::QUERY_GREATEREQUAL); queryVal = static_cast<const GreaterEqualQuery<int, T const *, true> *>(query) ->getVal(); streamWrite(ss, MolPickler::QUERY_VALUE, queryVal); queryVal = static_cast<const GreaterEqualQuery<int, T const *, true> *>(query) ->getTol(); streamWrite(ss, queryVal); } else if (typeid(*query) == typeid(LessQuery<int, T const *, true>)) { streamWrite(ss, MolPickler::QUERY_LESS); queryVal = static_cast<const LessQuery<int, T const *, true> *>(query)->getVal(); streamWrite(ss, MolPickler::QUERY_VALUE, queryVal); queryVal = static_cast<const LessQuery<int, T const *, true> *>(query)->getTol(); streamWrite(ss, queryVal); } else if (typeid(*query) == typeid(LessEqualQuery<int, T const *, true>)) { streamWrite(ss, MolPickler::QUERY_LESSEQUAL); queryVal = static_cast<const LessEqualQuery<int, T const *, true> *>(query) ->getVal(); streamWrite(ss, MolPickler::QUERY_VALUE, queryVal); queryVal = static_cast<const LessEqualQuery<int, T const *, true> *>(query) ->getTol(); streamWrite(ss, queryVal); } else if (typeid(*query) == typeid(RangeQuery<int, T const *, true>)) { streamWrite(ss, MolPickler::QUERY_RANGE); queryVal = static_cast<const RangeQuery<int, T const *, true> *>(query) ->getLower(); streamWrite(ss, MolPickler::QUERY_VALUE, queryVal); queryVal = static_cast<const RangeQuery<int, T const *, true> *>(query) ->getUpper(); streamWrite(ss, queryVal); queryVal = static_cast<const RangeQuery<int, T const *, true> *>(query)->getTol(); streamWrite(ss, queryVal); char ends; bool lowerOpen, upperOpen; boost::tie(lowerOpen, upperOpen) = static_cast<const RangeQuery<int, T const *, true> *>(query) ->getEndsOpen(); ends = 0 | (rdcast<int>(lowerOpen) << 1) | rdcast<int>(upperOpen); streamWrite(ss, ends); } else if (typeid(*query) == typeid(SetQuery<int, T const *, true>)) { streamWrite(ss, MolPickler::QUERY_SET); queryVal = static_cast<const SetQuery<int, T const *, true> *>(query)->size(); streamWrite(ss, MolPickler::QUERY_VALUE, queryVal); typename SetQuery<int, T const *, true>::CONTAINER_TYPE::const_iterator cit; for (cit = static_cast<const SetQuery<int, T const *, true> *>(query) ->beginSet(); cit != static_cast<const SetQuery<int, T const *, true> *>(query)->endSet(); ++cit) { queryVal = *cit; streamWrite(ss, queryVal); } } else if (typeid(*query) == typeid(AtomRingQuery)) { streamWrite(ss, MolPickler::QUERY_ATOMRING); queryVal = static_cast<const EqualityQuery<int, T const *, true> *>(query) ->getVal(); streamWrite(ss, MolPickler::QUERY_VALUE, queryVal); queryVal = static_cast<const EqualityQuery<int, T const *, true> *>(query) ->getTol(); streamWrite(ss, queryVal); } else if (typeid(*query) == typeid(RecursiveStructureQuery)) { streamWrite(ss, MolPickler::QUERY_RECURSIVE); streamWrite(ss, MolPickler::QUERY_VALUE); MolPickler::pickleMol( ((const RecursiveStructureQuery *)query)->getQueryMol(), ss); } else if (typeid(*query) == typeid(Query<int, T const *, true>)) { streamWrite(ss, MolPickler::QUERY_NULL); } else { throw MolPicklerException("do not know how to pickle part of the query."); } // now the children: streamWrite(ss, MolPickler::QUERY_NUMCHILDREN, static_cast<unsigned char>(query->endChildren() - query->beginChildren())); typename Query<int, T const *, true>::CHILD_VECT_CI cit; for (cit = query->beginChildren(); cit != query->endChildren(); ++cit) { pickleQuery(ss, cit->get()); } } void finalizeQueryFromDescription(Query<int, Atom const *, true> *query, Atom const *owner) { std::string descr = query->getDescription(); RDUNUSED_PARAM(owner); if (boost::starts_with(descr, "range_")) { descr = descr.substr(6); } else if (boost::starts_with(descr, "less_")) { descr = descr.substr(5); } else if (boost::starts_with(descr, "greater_")) { descr = descr.substr(8); } Query<int, Atom const *, true> *tmpQuery; if (descr == "AtomRingBondCount") { query->setDataFunc(queryAtomRingBondCount); } else if (descr == "AtomHasRingBond") { query->setDataFunc(queryAtomHasRingBond); } else if (descr == "AtomRingSize") { tmpQuery = makeAtomInRingOfSizeQuery( static_cast<ATOM_EQUALS_QUERY *>(query)->getVal()); query->setDataFunc(tmpQuery->getDataFunc()); delete tmpQuery; } else if (descr == "AtomMinRingSize") { query->setDataFunc(queryAtomMinRingSize); } else if (descr == "AtomRingBondCount") { query->setDataFunc(queryAtomRingBondCount); } else if (descr == "AtomImplicitValence") { query->setDataFunc(queryAtomImplicitValence); } else if (descr == "AtomTotalValence") { query->setDataFunc(queryAtomTotalValence); } else if (descr == "AtomAtomicNum") { query->setDataFunc(queryAtomNum); } else if (descr == "AtomExplicitDegree") { query->setDataFunc(queryAtomExplicitDegree); } else if (descr == "AtomTotalDegree") { query->setDataFunc(queryAtomTotalDegree); } else if (descr == "AtomHeavyAtomDegree") { query->setDataFunc(queryAtomHeavyAtomDegree); } else if (descr == "AtomHCount") { query->setDataFunc(queryAtomHCount); } else if (descr == "AtomImplicitHCount") { query->setDataFunc(queryAtomImplicitHCount); } else if (descr == "AtomHasImplicitH") { query->setDataFunc(queryAtomHasImplicitH); } else if (descr == "AtomIsAromatic") { query->setDataFunc(queryAtomAromatic); } else if (descr == "AtomIsAliphatic") { query->setDataFunc(queryAtomAliphatic); } else if (descr == "AtomUnsaturated") { query->setDataFunc(queryAtomUnsaturated); } else if (descr == "AtomMass") { query->setDataFunc(queryAtomMass); } else if (descr == "AtomIsotope") { query->setDataFunc(queryAtomIsotope); } else if (descr == "AtomFormalCharge") { query->setDataFunc(queryAtomFormalCharge); } else if (descr == "AtomHybridization") { query->setDataFunc(queryAtomHybridization); } else if (descr == "AtomInRing") { query->setDataFunc(queryIsAtomInRing); } else if (descr == "AtomInNRings") { query->setDataFunc(queryIsAtomInNRings); } else if (descr == "AtomHasHeteroatomNeighbors") { query->setDataFunc(queryAtomHasHeteroatomNbrs); } else if (descr == "AtomNumHeteroatomNeighbors") { query->setDataFunc(queryAtomNumHeteroatomNbrs); } else if (descr == "AtomHasAliphaticHeteroatomNeighbors") { query->setDataFunc(queryAtomHasAliphaticHeteroatomNbrs); } else if (descr == "AtomNumAliphaticHeteroatomNeighbors") { query->setDataFunc(queryAtomNumAliphaticHeteroatomNbrs); } else if (descr == "AtomNull") { query->setDataFunc(nullDataFun); query->setMatchFunc(nullQueryFun); } else if (descr == "AtomType") { query->setDataFunc(queryAtomType); } else if (descr == "AtomInNRings" || descr == "RecursiveStructure") { // don't need to do anything here because the classes // automatically have everything set } else if (descr == "AtomAnd" || descr == "AtomOr" || descr == "AtomXor") { // don't need to do anything here because the classes // automatically have everything set } else { throw MolPicklerException("Do not know how to finalize query: '" + descr + "'"); } } void finalizeQueryFromDescription(Query<int, Bond const *, true> *query, Bond const *owner) { RDUNUSED_PARAM(owner); std::string descr = query->getDescription(); Query<int, Bond const *, true> *tmpQuery; if (descr == "BondRingSize") { tmpQuery = makeBondInRingOfSizeQuery( static_cast<BOND_EQUALS_QUERY *>(query)->getVal()); query->setDataFunc(tmpQuery->getDataFunc()); delete tmpQuery; } else if (descr == "BondMinRingSize") { query->setDataFunc(queryBondMinRingSize); } else if (descr == "BondOrder") { query->setDataFunc(queryBondOrder); } else if (descr == "BondDir") { query->setDataFunc(queryBondDir); } else if (descr == "BondInRing") { query->setDataFunc(queryIsBondInRing); } else if (descr == "BondInNRings") { query->setDataFunc(queryIsBondInNRings); } else if (descr == "SingleOrAromaticBond") { query->setDataFunc(queryBondIsSingleOrAromatic); } else if (descr == "BondNull") { query->setDataFunc(nullDataFun); query->setMatchFunc(nullQueryFun); } else if (descr == "BondAnd" || descr == "BondOr" || descr == "BondXor") { // don't need to do anything here because the classes // automatically have everything set } else { throw MolPicklerException("Do not know how to finalize query: '" + descr + "'"); } } template <class T> Query<int, T const *, true> *buildBaseQuery(std::istream &ss, T const *owner, MolPickler::Tags tag, int version) { PRECONDITION(owner, "no query"); std::string descr; Query<int, T const *, true> *res = nullptr; int32_t val; int32_t nMembers; char cval; const unsigned int lowerOpen = 1 << 1; const unsigned int upperOpen = 1; switch (tag) { case MolPickler::QUERY_AND: res = new AndQuery<int, T const *, true>(); break; case MolPickler::QUERY_OR: res = new OrQuery<int, T const *, true>(); break; case MolPickler::QUERY_XOR: res = new XOrQuery<int, T const *, true>(); break; case MolPickler::QUERY_EQUALS: res = new EqualityQuery<int, T const *, true>(); streamRead(ss, tag, version); if (tag != MolPickler::QUERY_VALUE) { throw MolPicklerException( "Bad pickle format: QUERY_VALUE tag not found."); } streamRead(ss, val, version); static_cast<EqualityQuery<int, T const *, true> *>(res)->setVal(val); streamRead(ss, val, version); static_cast<EqualityQuery<int, T const *, true> *>(res)->setTol(val); break; case MolPickler::QUERY_GREATER: res = new GreaterQuery<int, T const *, true>(); streamRead(ss, tag, version); if (tag != MolPickler::QUERY_VALUE) { throw MolPicklerException( "Bad pickle format: QUERY_VALUE tag not found."); } streamRead(ss, val, version); static_cast<GreaterQuery<int, T const *, true> *>(res)->setVal(val); streamRead(ss, val, version); static_cast<GreaterQuery<int, T const *, true> *>(res)->setTol(val); break; case MolPickler::QUERY_GREATEREQUAL: res = new GreaterEqualQuery<int, T const *, true>(); streamRead(ss, tag, version); if (tag != MolPickler::QUERY_VALUE) { throw MolPicklerException( "Bad pickle format: QUERY_VALUE tag not found."); } streamRead(ss, val, version); static_cast<GreaterEqualQuery<int, T const *, true> *>(res)->setVal(val); streamRead(ss, val, version); static_cast<GreaterEqualQuery<int, T const *, true> *>(res)->setTol(val); break; case MolPickler::QUERY_LESS: res = new LessQuery<int, T const *, true>(); streamRead(ss, tag, version); if (tag != MolPickler::QUERY_VALUE) { throw MolPicklerException( "Bad pickle format: QUERY_VALUE tag not found."); } streamRead(ss, val, version); static_cast<LessQuery<int, T const *, true> *>(res)->setVal(val); streamRead(ss, val, version); static_cast<LessQuery<int, T const *, true> *>(res)->setTol(val); break; case MolPickler::QUERY_LESSEQUAL: res = new LessEqualQuery<int, T const *, true>(); streamRead(ss, tag, version); if (tag != MolPickler::QUERY_VALUE) { throw MolPicklerException( "Bad pickle format: QUERY_VALUE tag not found."); } streamRead(ss, val, version); static_cast<LessEqualQuery<int, T const *, true> *>(res)->setVal(val); streamRead(ss, val, version); static_cast<LessEqualQuery<int, T const *, true> *>(res)->setTol(val); break; case MolPickler::QUERY_RANGE: res = new RangeQuery<int, T const *, true>(); streamRead(ss, tag, version); if (tag != MolPickler::QUERY_VALUE) { throw MolPicklerException( "Bad pickle format: QUERY_VALUE tag not found."); } streamRead(ss, val, version); static_cast<RangeQuery<int, T const *, true> *>(res)->setLower(val); streamRead(ss, val, version); static_cast<RangeQuery<int, T const *, true> *>(res)->setUpper(val); streamRead(ss, val, version); static_cast<RangeQuery<int, T const *, true> *>(res)->setTol(val); streamRead(ss, cval, version); static_cast<RangeQuery<int, T const *, true> *>(res)->setEndsOpen( cval & lowerOpen, cval & upperOpen); break; case MolPickler::QUERY_SET: res = new SetQuery<int, T const *, true>(); streamRead(ss, tag, version); if (tag != MolPickler::QUERY_VALUE) { throw MolPicklerException( "Bad pickle format: QUERY_VALUE tag not found."); } streamRead(ss, nMembers); while (nMembers > 0) { streamRead(ss, val, version); static_cast<SetQuery<int, T const *, true> *>(res)->insert(val); --nMembers; } break; case MolPickler::QUERY_NULL: res = new Query<int, T const *, true>(); break; default: throw MolPicklerException("unknown query-type tag encountered"); } POSTCONDITION(res, "no match found"); return res; } Query<int, Atom const *, true> *unpickleQuery(std::istream &ss, Atom const *owner, int version) { PRECONDITION(owner, "no query"); std::string descr; bool isNegated = false; Query<int, Atom const *, true> *res; streamRead(ss, descr, version); MolPickler::Tags tag; streamRead(ss, tag, version); if (tag == MolPickler::QUERY_ISNEGATED) { isNegated = true; streamRead(ss, tag, version); } int32_t val; ROMol *tmpMol; switch (tag) { case MolPickler::QUERY_ATOMRING: res = new AtomRingQuery(); streamRead(ss, tag, version); if (tag != MolPickler::QUERY_VALUE) { throw MolPicklerException( "Bad pickle format: QUERY_VALUE tag not found."); } streamRead(ss, val, version); static_cast<EqualityQuery<int, Atom const *, true> *>(res)->setVal(val); streamRead(ss, val, version); static_cast<EqualityQuery<int, Atom const *, true> *>(res)->setTol(val); break; case MolPickler::QUERY_RECURSIVE: streamRead(ss, tag, version); if (tag != MolPickler::QUERY_VALUE) { throw MolPicklerException( "Bad pickle format: QUERY_VALUE tag not found."); } tmpMol = new ROMol(); MolPickler::molFromPickle(ss, tmpMol); res = new RecursiveStructureQuery(tmpMol); break; default: res = buildBaseQuery(ss, owner, tag, version); break; } CHECK_INVARIANT(res, "no query!"); res->setNegation(isNegated); res->setDescription(descr); finalizeQueryFromDescription(res, owner); // read in the children: streamRead(ss, tag, version); if (tag != MolPickler::QUERY_NUMCHILDREN) { throw MolPicklerException( "Bad pickle format: QUERY_NUMCHILDREN tag not found."); } unsigned char numChildren; streamRead(ss, numChildren, version); while (numChildren > 0) { Query<int, Atom const *, true> *child = unpickleQuery(ss, owner, version); res->addChild(Query<int, Atom const *, true>::CHILD_TYPE(child)); --numChildren; } return res; } Query<int, Bond const *, true> *unpickleQuery(std::istream &ss, Bond const *owner, int version) { PRECONDITION(owner, "no query"); std::string descr; bool isNegated = false; Query<int, Bond const *, true> *res; streamRead(ss, descr, version); MolPickler::Tags tag; streamRead(ss, tag, version); if (tag == MolPickler::QUERY_ISNEGATED) { isNegated = true; streamRead(ss, tag, version); } res = buildBaseQuery(ss, owner, tag, version); CHECK_INVARIANT(res, "no query!"); res->setNegation(isNegated); res->setDescription(descr); finalizeQueryFromDescription(res, owner); // read in the children: streamRead(ss, tag, version); if (tag != MolPickler::QUERY_NUMCHILDREN) { throw MolPicklerException( "Bad pickle format: QUERY_NUMCHILDREN tag not found."); } unsigned char numChildren; streamRead(ss, numChildren, version); while (numChildren > 0) { Query<int, Bond const *, true> *child = unpickleQuery(ss, owner, version); res->addChild(Query<int, Bond const *, true>::CHILD_TYPE(child)); --numChildren; } return res; } void pickleAtomPDBResidueInfo(std::ostream &ss, const AtomPDBResidueInfo *info) { PRECONDITION(info, "no info"); if (info->getSerialNumber()) streamWrite(ss, MolPickler::ATOM_PDB_RESIDUE_SERIALNUMBER, info->getSerialNumber()); if (info->getAltLoc() != "") streamWrite(ss, MolPickler::ATOM_PDB_RESIDUE_ALTLOC, info->getAltLoc()); if (info->getResidueName() != "") streamWrite(ss, MolPickler::ATOM_PDB_RESIDUE_RESIDUENAME, info->getResidueName()); if (info->getResidueNumber()) streamWrite(ss, MolPickler::ATOM_PDB_RESIDUE_RESIDUENUMBER, info->getResidueNumber()); if (info->getChainId() != "") streamWrite(ss, MolPickler::ATOM_PDB_RESIDUE_CHAINID, info->getChainId()); if (info->getInsertionCode() != "") streamWrite(ss, MolPickler::ATOM_PDB_RESIDUE_INSERTIONCODE, info->getInsertionCode()); if (info->getOccupancy()) streamWrite(ss, MolPickler::ATOM_PDB_RESIDUE_OCCUPANCY, info->getOccupancy()); if (info->getTempFactor()) streamWrite(ss, MolPickler::ATOM_PDB_RESIDUE_TEMPFACTOR, info->getTempFactor()); if (info->getIsHeteroAtom()) streamWrite(ss, MolPickler::ATOM_PDB_RESIDUE_ISHETEROATOM, static_cast<char>(info->getIsHeteroAtom())); if (info->getSecondaryStructure()) streamWrite(ss, MolPickler::ATOM_PDB_RESIDUE_SECONDARYSTRUCTURE, info->getSecondaryStructure()); if (info->getSegmentNumber()) streamWrite(ss, MolPickler::ATOM_PDB_RESIDUE_SEGMENTNUMBER, info->getSegmentNumber()); } void unpickleAtomPDBResidueInfo(std::istream &ss, AtomPDBResidueInfo *info, int version) { PRECONDITION(info, "no info"); std::string sval; double dval; char cval; unsigned int uival; int ival; MolPickler::Tags tag = MolPickler::BEGIN_ATOM_MONOMER; while (tag != MolPickler::END_ATOM_MONOMER) { streamRead(ss, tag, version); switch (tag) { case MolPickler::ATOM_PDB_RESIDUE_SERIALNUMBER: streamRead(ss, ival, version); info->setSerialNumber(ival); break; case MolPickler::ATOM_PDB_RESIDUE_ALTLOC: streamRead(ss, sval, version); info->setAltLoc(sval); break; case MolPickler::ATOM_PDB_RESIDUE_RESIDUENAME: streamRead(ss, sval, version); info->setResidueName(sval); break; case MolPickler::ATOM_PDB_RESIDUE_RESIDUENUMBER: streamRead(ss, ival, version); info->setResidueNumber(ival); break; case MolPickler::ATOM_PDB_RESIDUE_CHAINID: streamRead(ss, sval, version); info->setChainId(sval); break; case MolPickler::ATOM_PDB_RESIDUE_INSERTIONCODE: streamRead(ss, sval, version); info->setInsertionCode(sval); break; case MolPickler::ATOM_PDB_RESIDUE_OCCUPANCY: streamRead(ss, dval, version); info->setOccupancy(dval); break; case MolPickler::ATOM_PDB_RESIDUE_TEMPFACTOR: streamRead(ss, dval, version); info->setTempFactor(dval); break; case MolPickler::ATOM_PDB_RESIDUE_ISHETEROATOM: streamRead(ss, cval, version); info->setIsHeteroAtom(cval); break; case MolPickler::ATOM_PDB_RESIDUE_SECONDARYSTRUCTURE: streamRead(ss, uival, version); info->setSecondaryStructure(uival); break; case MolPickler::ATOM_PDB_RESIDUE_SEGMENTNUMBER: streamRead(ss, uival, version); info->setSegmentNumber(uival); break; case MolPickler::END_ATOM_MONOMER: break; default: throw MolPicklerException( "unrecognized tag while parsing atom peptide residue info"); } } } void pickleAtomMonomerInfo(std::ostream &ss, const AtomMonomerInfo *info) { PRECONDITION(info, "no info"); streamWrite(ss, info->getName()); streamWrite(ss, static_cast<unsigned int>(info->getMonomerType())); switch (info->getMonomerType()) { case AtomMonomerInfo::UNKNOWN: case AtomMonomerInfo::OTHER: break; case AtomMonomerInfo::PDBRESIDUE: pickleAtomPDBResidueInfo(ss, static_cast<const AtomPDBResidueInfo *>(info)); break; default: throw MolPicklerException("unrecognized MonomerType"); } } AtomMonomerInfo *unpickleAtomMonomerInfo(std::istream &ss, int version) { MolPickler::Tags tag; std::string nm; streamRead(ss, nm, version); unsigned int typ; streamRead(ss, typ, version); AtomMonomerInfo *res; switch (typ) { case AtomMonomerInfo::UNKNOWN: case AtomMonomerInfo::OTHER: res = new AtomMonomerInfo(RDKit::AtomMonomerInfo::AtomMonomerType(typ), nm); streamRead(ss, tag, version); if (tag != MolPickler::END_ATOM_MONOMER) throw MolPicklerException( "did not find expected end of atom monomer info"); break; case AtomMonomerInfo::PDBRESIDUE: res = static_cast<AtomMonomerInfo *>(new AtomPDBResidueInfo(nm)); unpickleAtomPDBResidueInfo(ss, static_cast<AtomPDBResidueInfo *>(res), version); break; default: throw MolPicklerException("unrecognized MonomerType"); } return res; } } // end of anonymous namespace void MolPickler::pickleMol(const ROMol *mol, std::ostream &ss) { pickleMol(mol, ss, MolPickler::getDefaultPickleProperties()); } void MolPickler::pickleMol(const ROMol *mol, std::ostream &ss, unsigned int propertyFlags) { PRECONDITION(mol, "empty molecule"); streamWrite(ss, endianId); streamWrite(ss, static_cast<int>(VERSION)); streamWrite(ss, versionMajor); streamWrite(ss, versionMinor); streamWrite(ss, versionPatch); #ifndef OLD_PICKLE if (mol->getNumAtoms() > 255) { _pickle<int32_t>(mol, ss, propertyFlags); } else { _pickle<unsigned char>(mol, ss, propertyFlags); } #else _pickleV1(mol, ss); #endif } void MolPickler::pickleMol(const ROMol &mol, std::ostream &ss) { pickleMol(&mol, ss, MolPickler::getDefaultPickleProperties()); } void MolPickler::pickleMol(const ROMol *mol, std::string &res) { pickleMol(mol, res, MolPickler::getDefaultPickleProperties()); } void MolPickler::pickleMol(const ROMol *mol, std::string &res, unsigned int pickleFlags) { PRECONDITION(mol, "empty molecule"); std::stringstream ss(std::ios_base::binary | std::ios_base::out | std::ios_base::in); MolPickler::pickleMol(mol, ss, pickleFlags); res = ss.str(); } void MolPickler::pickleMol(const ROMol &mol, std::string &ss) { pickleMol(&mol, ss, MolPickler::getDefaultPickleProperties()); } // NOTE: if the mol passed in here already has atoms and bonds, they will // be left intact. The side effect is that ALL atom and bond bookmarks // will be blown out by the end of this process. void MolPickler::molFromPickle(std::istream &ss, ROMol *mol) { PRECONDITION(mol, "empty molecule"); int32_t tmpInt; mol->clearAllAtomBookmarks(); mol->clearAllBondBookmarks(); streamRead(ss, tmpInt); if (tmpInt != endianId) { throw MolPicklerException( "Bad pickle format: bad endian ID or invalid file format"); } streamRead(ss, tmpInt); if (static_cast<Tags>(tmpInt) != VERSION) { throw MolPicklerException("Bad pickle format: no version tag"); } int32_t majorVersion, minorVersion, patchVersion; streamRead(ss, majorVersion); streamRead(ss, minorVersion); streamRead(ss, patchVersion); if (majorVersion > versionMajor || (majorVersion == versionMajor && minorVersion > versionMinor)) { BOOST_LOG(rdWarningLog) << "Depickling from a version number (" << majorVersion << "." << minorVersion << ")" << "that is higher than our version (" << versionMajor << "." << versionMinor << ").\nThis probably won't work." << std::endl; } majorVersion = 1000 * majorVersion + minorVersion * 10 + patchVersion; if (majorVersion == 1) { _depickleV1(ss, mol); } else { int32_t numAtoms; streamRead(ss, numAtoms, majorVersion); if (numAtoms > 255) { _depickle<int32_t>(ss, mol, majorVersion, numAtoms); } else { _depickle<unsigned char>(ss, mol, majorVersion, numAtoms); } } mol->clearAllAtomBookmarks(); mol->clearAllBondBookmarks(); if (majorVersion < 4000) { // FIX for issue 220 - probably better to change the pickle format later MolOps::assignStereochemistry(*mol, true); } } void MolPickler::molFromPickle(const std::string &pickle, ROMol *mol) { PRECONDITION(mol, "empty molecule"); std::stringstream ss(std::ios_base::binary | std::ios_base::out | std::ios_base::in); ss.write(pickle.c_str(), pickle.length()); MolPickler::molFromPickle(ss, mol); } //-------------------------------------- // // Molecules // //-------------------------------------- template <typename T> void MolPickler::_pickle(const ROMol *mol, std::ostream &ss, unsigned int propertyFlags) { PRECONDITION(mol, "empty molecule"); int32_t tmpInt; bool includeAtomCoords = true; std::map<int, int> atomIdxMap; std::map<int, int> bondIdxMap; tmpInt = static_cast<int32_t>(mol->getNumAtoms()); streamWrite(ss, tmpInt); tmpInt = static_cast<int32_t>(mol->getNumBonds()); streamWrite(ss, tmpInt); char flag = 0; if (includeAtomCoords) flag |= 0x1 << 7; streamWrite(ss, flag); // ------------------- // // Write Atoms // // ------------------- streamWrite(ss, BEGINATOM); ROMol::ConstAtomIterator atIt; int nWritten = 0; for (atIt = mol->beginAtoms(); atIt != mol->endAtoms(); ++atIt) { _pickleAtom<T>(ss, *atIt); atomIdxMap[(*atIt)->getIdx()] = nWritten; nWritten++; } // ------------------- // // Write Bonds // // ------------------- streamWrite(ss, BEGINBOND); for (unsigned int i = 0; i < mol->getNumBonds(); i++) { auto bond = mol->getBondWithIdx(i); _pickleBond<T>(ss, bond, atomIdxMap); bondIdxMap[bond->getIdx()] = i; } // ------------------- // // Write Rings (if present) // // ------------------- const RingInfo *ringInfo = mol->getRingInfo(); if (ringInfo && ringInfo->isInitialized()) { streamWrite(ss, BEGINSSSR); _pickleSSSR<T>(ss, ringInfo, atomIdxMap); } // ------------------- // // Write SubstanceGroups (if present) // // ------------------- const auto &sgroups = getSubstanceGroups(*mol); if (!sgroups.empty()) { streamWrite(ss, BEGINSGROUP); tmpInt = static_cast<int32_t>(sgroups.size()); streamWrite(ss, tmpInt); for (const auto &sgroup : sgroups) { _pickleSubstanceGroup<T>(ss, sgroup, atomIdxMap, bondIdxMap); } } // Write Stereo Groups { auto &stereo_groups = mol->getStereoGroups(); if (stereo_groups.size() > 0u) { streamWrite(ss, BEGINSTEREOGROUP); _pickleStereo<T>(ss, stereo_groups, atomIdxMap); } } // pickle the conformations if necessary if (includeAtomCoords) { streamWrite(ss, BEGINCONFS); tmpInt = static_cast<int32_t>(mol->getNumConformers()); streamWrite(ss, tmpInt); for (auto ci = mol->beginConformers(); ci != mol->endConformers(); ++ci) { const Conformer *conf = ci->get(); _pickleConformer<T>(ss, conf); } if (propertyFlags & PicklerOps::MolProps) { streamWrite(ss, BEGINCONFPROPS); for (auto ci = mol->beginConformers(); ci != mol->endConformers(); ++ci) { const Conformer *conf = ci->get(); _pickleProperties(ss, *conf, propertyFlags); } } } if (propertyFlags & PicklerOps::MolProps) { streamWrite(ss, BEGINPROPS); _pickleProperties(ss, *mol, propertyFlags); streamWrite(ss, ENDPROPS); } if (propertyFlags & PicklerOps::AtomProps) { streamWrite(ss, BEGINATOMPROPS); for (ROMol::ConstAtomIterator atIt = mol->beginAtoms(); atIt != mol->endAtoms(); ++atIt) { _pickleProperties(ss, **atIt, propertyFlags); } streamWrite(ss, ENDPROPS); } if (propertyFlags & PicklerOps::BondProps) { streamWrite(ss, BEGINBONDPROPS); for (ROMol::ConstBondIterator bondIt = mol->beginBonds(); bondIt != mol->endBonds(); ++bondIt) { _pickleProperties(ss, **bondIt, propertyFlags); } streamWrite(ss, ENDPROPS); } streamWrite(ss, ENDMOL); } template <typename T> void MolPickler::_depickle(std::istream &ss, ROMol *mol, int version, int numAtoms) { PRECONDITION(mol, "empty molecule"); bool directMap = mol->getNumAtoms() == 0; Tags tag; int32_t tmpInt; // int numAtoms,numBonds; int numBonds; bool haveQuery = false; streamRead(ss, tmpInt, version); numBonds = tmpInt; // did we include coordinates bool includeCoords = false; if (version >= 3000) { char flag; streamRead(ss, flag, version); if (flag & 0x1 << 7) includeCoords = true; } // ------------------- // // Read Atoms // // ------------------- streamRead(ss, tag, version); if (tag != BEGINATOM) { throw MolPicklerException("Bad pickle format: BEGINATOM tag not found."); } Conformer *conf = nullptr; if ((version >= 2000 && version < 3000) && includeCoords) { // there can only one conformation - since the poositions were stored on // the atoms themselves in this version conf = new Conformer(numAtoms); mol->addConformer(conf, true); } for (int i = 0; i < numAtoms; i++) { RDGeom::Point3D pos; Atom *atom = _addAtomFromPickle<T>(ss, mol, pos, version, directMap); if ((version >= 2000 && version < 3000) && includeCoords) { // this is a older pickle so we go the pos conf->setAtomPos(i, pos); } if (!directMap) { mol->setAtomBookmark(atom, i); } if (atom->hasQuery()) { haveQuery = true; } } // ------------------- // // Read Bonds // // ------------------- streamRead(ss, tag, version); if (tag != BEGINBOND) { throw MolPicklerException("Bad pickle format: BEGINBOND tag not found."); } for (int i = 0; i < numBonds; i++) { Bond *bond = _addBondFromPickle<T>(ss, mol, version, directMap); if (!directMap) { mol->setBondBookmark(bond, i); } } // ------------------- // // Read Rings (if needed) // // ------------------- streamRead(ss, tag, version); if (tag == BEGINSSSR) { _addRingInfoFromPickle<T>(ss, mol, version, directMap); streamRead(ss, tag, version); } // ------------------- // // Read SubstanceGroups (if needed) // // ------------------- if (tag == BEGINSGROUP) { streamRead(ss, tmpInt, version); // Create SubstanceGroups for (int i = 0; i < tmpInt; ++i) { auto sgroup = _getSubstanceGroupFromPickle<T>(ss, mol, version); addSubstanceGroup(*mol, sgroup); } streamRead(ss, tag, version); } if (tag == BEGINSTEREOGROUP) { _depickleStereo<T>(ss, mol, version); streamRead(ss, tag, version); } if (tag == BEGINCONFS) { // read in the conformation streamRead(ss, tmpInt, version); std::vector<unsigned int> cids(tmpInt); for (auto i = 0; i < tmpInt; i++) { Conformer *conf = _conformerFromPickle<T>(ss, version); mol->addConformer(conf); cids[i] = conf->getId(); } streamRead(ss, tag, version); if(tag==BEGINCONFPROPS){ for (auto cid : cids) { _unpickleProperties(ss, mol->getConformer(cid)); } streamRead(ss, tag, version); } } while (tag != ENDMOL) { if (tag == BEGINPROPS) { _unpickleProperties(ss, *mol); streamRead(ss, tag, version); } else if (tag == BEGINATOMPROPS) { for (ROMol::AtomIterator atIt = mol->beginAtoms(); atIt != mol->endAtoms(); ++atIt) { _unpickleProperties(ss, **atIt); } streamRead(ss, tag, version); } else if (tag == BEGINBONDPROPS) { for (ROMol::BondIterator bdIt = mol->beginBonds(); bdIt != mol->endBonds(); ++bdIt) { _unpickleProperties(ss, **bdIt); } streamRead(ss, tag, version); } else if (tag == BEGINQUERYATOMDATA) { for (ROMol::AtomIterator atIt = mol->beginAtoms(); atIt != mol->endAtoms(); ++atIt) { _unpickleAtomData(ss, *atIt, version); } streamRead(ss, tag, version); } else { break; // break to tag != ENDMOL } if (tag != ENDPROPS) { throw MolPicklerException("Bad pickle format: ENDPROPS tag not found."); } streamRead(ss, tag, version); } if (tag != ENDMOL) { throw MolPicklerException("Bad pickle format: ENDMOL tag not found."); } if (haveQuery) { // we didn't read any property info for atoms with associated // queries. update their property caches // (was sf.net Issue 3316407) for (ROMol::AtomIterator atIt = mol->beginAtoms(); atIt != mol->endAtoms(); ++atIt) { Atom *atom = *atIt; if (atom->hasQuery()) { atom->updatePropertyCache(false); } } } } //-------------------------------------- // // Atoms // //-------------------------------------- namespace { bool getAtomMapNumber(const Atom *atom, int &mapNum) { PRECONDITION(atom, "bad atom"); if (!atom->hasProp(common_properties::molAtomMapNumber)) return false; bool res = true; int tmpInt; try { atom->getProp(common_properties::molAtomMapNumber, tmpInt); } catch (boost::bad_any_cast &) { const std::string &tmpSVal = atom->getProp<std::string>(common_properties::molAtomMapNumber); try { tmpInt = boost::lexical_cast<int>(tmpSVal); } catch (boost::bad_lexical_cast &) { res = false; } } if (res) mapNum = tmpInt; return res; } } // namespace int32_t MolPickler::_pickleAtomData(std::ostream &tss, const Atom *atom) { int32_t propFlags = 0; char tmpChar; signed char tmpSchar; // tmpFloat=atom->getMass()-PeriodicTable::getTable()->getAtomicWeight(atom->getAtomicNum()); // if(fabs(tmpFloat)>.0001){ // propFlags |= 1; // streamWrite(tss,tmpFloat); // } tmpSchar = static_cast<signed char>(atom->getFormalCharge()); if (tmpSchar != 0) { propFlags |= 1 << 1; streamWrite(tss, tmpSchar); } tmpChar = static_cast<char>(atom->getChiralTag()); if (tmpChar != 0) { propFlags |= 1 << 2; streamWrite(tss, tmpChar); } tmpChar = static_cast<char>(atom->getHybridization()); if (tmpChar != static_cast<char>(Atom::SP3)) { propFlags |= 1 << 3; streamWrite(tss, tmpChar); } tmpChar = static_cast<char>(atom->getNumExplicitHs()); if (tmpChar != 0) { propFlags |= 1 << 4; streamWrite(tss, tmpChar); } if (atom->d_explicitValence > 0) { tmpChar = static_cast<char>(atom->d_explicitValence); propFlags |= 1 << 5; streamWrite(tss, tmpChar); } if (atom->d_implicitValence > 0) { tmpChar = static_cast<char>(atom->d_implicitValence); propFlags |= 1 << 6; streamWrite(tss, tmpChar); } tmpChar = static_cast<char>(atom->getNumRadicalElectrons()); if (tmpChar != 0) { propFlags |= 1 << 7; streamWrite(tss, tmpChar); } unsigned int tmpuint = atom->getIsotope(); if (tmpuint > 0) { propFlags |= 1 << 8; streamWrite(tss, tmpuint); } return propFlags; } void MolPickler::_unpickleAtomData(std::istream &ss, Atom *atom, int version) { int propFlags; char tmpChar; signed char tmpSchar; streamRead(ss, propFlags, version); if (propFlags & 1) { float tmpFloat; streamRead(ss, tmpFloat, version); int iso = static_cast<int>(floor(tmpFloat + atom->getMass() + .0001)); atom->setIsotope(iso); } if (propFlags & (1 << 1)) { streamRead(ss, tmpSchar, version); } else { tmpSchar = 0; } atom->setFormalCharge(static_cast<int>(tmpSchar)); if (propFlags & (1 << 2)) { streamRead(ss, tmpChar, version); } else { tmpChar = 0; } atom->setChiralTag(static_cast<Atom::ChiralType>(tmpChar)); if (propFlags & (1 << 3)) { streamRead(ss, tmpChar, version); } else { tmpChar = Atom::SP3; } atom->setHybridization(static_cast<Atom::HybridizationType>(tmpChar)); if (propFlags & (1 << 4)) { streamRead(ss, tmpChar, version); } else { tmpChar = 0; } atom->setNumExplicitHs(tmpChar); if (propFlags & (1 << 5)) { streamRead(ss, tmpChar, version); } else { tmpChar = 0; } atom->d_explicitValence = tmpChar; if (propFlags & (1 << 6)) { streamRead(ss, tmpChar, version); } else { tmpChar = 0; } atom->d_implicitValence = tmpChar; if (propFlags & (1 << 7)) { streamRead(ss, tmpChar, version); } else { tmpChar = 0; } atom->d_numRadicalElectrons = static_cast<unsigned int>(tmpChar); atom->d_isotope = 0; if (propFlags & (1 << 8)) { unsigned int tmpuint; streamRead(ss, tmpuint, version); atom->setIsotope(tmpuint); } } // T refers to the type of the atom indices written template <typename T> void MolPickler::_pickleAtom(std::ostream &ss, const Atom *atom) { PRECONDITION(atom, "empty atom"); char tmpChar; unsigned char tmpUchar; int tmpInt; char flags; tmpUchar = atom->getAtomicNum() % 256; streamWrite(ss, tmpUchar); flags = 0; if (atom->getIsAromatic()) flags |= 0x1 << 6; if (atom->getNoImplicit()) flags |= 0x1 << 5; if (atom->hasQuery()) flags |= 0x1 << 4; if (getAtomMapNumber(atom, tmpInt)) flags |= 0x1 << 3; if (atom->hasProp(common_properties::dummyLabel)) flags |= 0x1 << 2; if (atom->getMonomerInfo()) flags |= 0x1 << 1; streamWrite(ss, flags); std::stringstream tss(std::ios_base::binary | std::ios_base::out | std::ios_base::in); int32_t propFlags = _pickleAtomData(tss, atom); streamWrite(ss, propFlags); ss.write(tss.str().c_str(), tss.str().size()); if (atom->hasQuery()) { streamWrite(ss, BEGINQUERY); pickleQuery(ss, static_cast<const QueryAtom *>(atom)->getQuery()); streamWrite(ss, ENDQUERY); } if (getAtomMapNumber(atom, tmpInt)) { if (tmpInt < 128) { tmpChar = static_cast<char>(tmpInt % 128); streamWrite(ss, ATOM_MAPNUMBER, tmpChar); } else { tmpChar = static_cast<char>(255); streamWrite(ss, ATOM_MAPNUMBER, tmpChar); streamWrite(ss, tmpInt); } } if (atom->hasProp(common_properties::dummyLabel)) { streamWrite(ss, ATOM_DUMMYLABEL, atom->getProp<std::string>(common_properties::dummyLabel)); } if (atom->getMonomerInfo()) { streamWrite(ss, BEGIN_ATOM_MONOMER); pickleAtomMonomerInfo(ss, atom->getMonomerInfo()); streamWrite(ss, END_ATOM_MONOMER); } } template <typename T> void MolPickler::_pickleConformer(std::ostream &ss, const Conformer *conf) { PRECONDITION(conf, "empty conformer"); char tmpChr = static_cast<int>(conf->is3D()); streamWrite(ss, tmpChr); int32_t tmpInt = static_cast<int32_t>(conf->getId()); streamWrite(ss, tmpInt); T tmpT = static_cast<T>(conf->getNumAtoms()); streamWrite(ss, tmpT); const RDGeom::POINT3D_VECT &pts = conf->getPositions(); for (const auto &pt : pts) { float tmpFloat; tmpFloat = static_cast<float>(pt.x); streamWrite(ss, tmpFloat); tmpFloat = static_cast<float>(pt.y); streamWrite(ss, tmpFloat); tmpFloat = static_cast<float>(pt.z); streamWrite(ss, tmpFloat); } } template <typename T> Conformer *MolPickler::_conformerFromPickle(std::istream &ss, int version) { float tmpFloat; bool is3D = true; if (version > 4000) { char tmpChr; streamRead(ss, tmpChr, version); is3D = static_cast<bool>(tmpChr); } int tmpInt; streamRead(ss, tmpInt, version); unsigned int cid = static_cast<unsigned int>(tmpInt); T tmpT; streamRead(ss, tmpT, version); unsigned int numAtoms = static_cast<unsigned int>(tmpT); auto *conf = new Conformer(numAtoms); conf->setId(cid); conf->set3D(is3D); for (unsigned int i = 0; i < numAtoms; i++) { streamRead(ss, tmpFloat, version); conf->getAtomPos(i).x = static_cast<double>(tmpFloat); streamRead(ss, tmpFloat, version); conf->getAtomPos(i).y = static_cast<double>(tmpFloat); streamRead(ss, tmpFloat, version); conf->getAtomPos(i).z = static_cast<double>(tmpFloat); } return conf; } template <typename T> Atom *MolPickler::_addAtomFromPickle(std::istream &ss, ROMol *mol, RDGeom::Point3D &pos, int version, bool directMap) { RDUNUSED_PARAM(directMap); PRECONDITION(mol, "empty molecule"); float x, y, z; char tmpChar; unsigned char tmpUchar; signed char tmpSchar; char flags; Tags tag; Atom *atom = nullptr; int atomicNum = 0; streamRead(ss, tmpUchar, version); atomicNum = tmpUchar; bool hasQuery = false; streamRead(ss, flags, version); if (version > 5000) { hasQuery = flags & 0x1 << 4; } if (!hasQuery) { atom = new Atom(atomicNum); } else { atom = new QueryAtom(); if (atomicNum) { // can't set this in the constructor because that builds a // query and we're going to take care of that later: atom->setAtomicNum(atomicNum); } } atom->setIsAromatic(flags & 0x1 << 6); atom->setNoImplicit(flags & 0x1 << 5); bool hasAtomMap = 0, hasDummyLabel = 0; if (version >= 6020) { hasAtomMap = flags & 0x1 << 3; hasDummyLabel = flags & 0x1 << 2; } bool hasMonomerInfo = 0; if (version >= 7020) { hasMonomerInfo = flags & 0x1 << 1; } // are coordinates present? if (flags & 0x1 << 7) { streamRead(ss, x, version); pos.x = static_cast<double>(x); streamRead(ss, y, version); pos.y = static_cast<double>(y); streamRead(ss, z, version); pos.z = static_cast<double>(z); } if (version <= 5000 || !hasQuery) { if (version < 7000) { if (version < 6030) { streamRead(ss, tmpSchar, version); // FIX: technically should be handling this in order to maintain true // backwards compatibility // atom->setMass(PeriodicTable::getTable()->getAtomicWeight(atom->getAtomicNum())+ // static_cast<int>(tmpSchar)); } else { float tmpFloat; streamRead(ss, tmpFloat, version); // FIX: technically should be handling this in order to maintain true // backwards compatibility // atom->setMass(tmpFloat); } streamRead(ss, tmpSchar, version); atom->setFormalCharge(static_cast<int>(tmpSchar)); streamRead(ss, tmpChar, version); atom->setChiralTag(static_cast<Atom::ChiralType>(tmpChar)); streamRead(ss, tmpChar, version); atom->setHybridization(static_cast<Atom::HybridizationType>(tmpChar)); streamRead(ss, tmpChar, version); atom->setNumExplicitHs(static_cast<int>(tmpChar)); streamRead(ss, tmpChar, version); atom->d_explicitValence = tmpChar; streamRead(ss, tmpChar, version); atom->d_implicitValence = tmpChar; if (version > 6000) { streamRead(ss, tmpChar, version); atom->d_numRadicalElectrons = static_cast<unsigned int>(tmpChar); } } else { _unpickleAtomData(ss, atom, version); } } else if (version > 5000) { // we have a query if (version >= 9000) { _unpickleAtomData(ss, atom, version); } streamRead(ss, tag, version); if (tag != BEGINQUERY) { throw MolPicklerException("Bad pickle format: BEGINQUERY tag not found."); } static_cast<QueryAtom *>(atom)->setQuery(unpickleQuery(ss, atom, version)); streamRead(ss, tag, version); if (tag != ENDQUERY) { throw MolPicklerException("Bad pickle format: ENDQUERY tag not found."); } // atom->setNumExplicitHs(0); } if (version > 5000) { if (version < 6020) { unsigned int sPos = rdcast<unsigned int>(ss.tellg()); Tags tag; streamRead(ss, tag, version); if (tag == ATOM_MAPNUMBER) { int32_t tmpInt; streamRead(ss, tmpChar, version); tmpInt = tmpChar; atom->setProp(common_properties::molAtomMapNumber, tmpInt); } else { ss.seekg(sPos); } } else { if (hasAtomMap) { Tags tag; streamRead(ss, tag, version); if (tag != ATOM_MAPNUMBER) { throw MolPicklerException( "Bad pickle format: ATOM_MAPNUMBER tag not found."); } int tmpInt; streamRead(ss, tmpChar, version); // the test for tmpChar below seems redundant, but on at least // the POWER8 architecture it seems that chars may be unsigned // by default. if ((tmpChar < 0 || tmpChar > 127) && version > 9000) { streamRead(ss, tmpInt, version); } else { tmpInt = tmpChar; } atom->setProp(common_properties::molAtomMapNumber, tmpInt); } if (hasDummyLabel) { streamRead(ss, tag, version); if (tag != ATOM_DUMMYLABEL) { throw MolPicklerException( "Bad pickle format: ATOM_DUMMYLABEL tag not found."); } std::string tmpStr; streamRead(ss, tmpStr, version); atom->setProp(common_properties::dummyLabel, tmpStr); } } } if (version >= 7020) { if (hasMonomerInfo) { streamRead(ss, tag, version); if (tag != BEGIN_ATOM_MONOMER) { throw MolPicklerException( "Bad pickle format: BEGIN_ATOM_MONOMER tag not found."); } atom->setMonomerInfo(unpickleAtomMonomerInfo(ss, version)); } } mol->addAtom(atom, false, true); return atom; } //-------------------------------------- // // Bonds // //-------------------------------------- template <typename T> void MolPickler::_pickleBond(std::ostream &ss, const Bond *bond, std::map<int, int> &atomIdxMap) { PRECONDITION(bond, "empty bond"); T tmpT; char tmpChar; char flags; tmpT = static_cast<T>(atomIdxMap[bond->getBeginAtomIdx()]); streamWrite(ss, tmpT); tmpT = static_cast<T>(atomIdxMap[bond->getEndAtomIdx()]); streamWrite(ss, tmpT); flags = 0; if (bond->getIsAromatic()) flags |= 0x1 << 6; if (bond->getIsConjugated()) flags |= 0x1 << 5; if (bond->hasQuery()) flags |= 0x1 << 4; if (bond->getBondType() != Bond::SINGLE) flags |= 0x1 << 3; if (bond->getBondDir() != Bond::NONE) flags |= 0x1 << 2; if (bond->getStereo() != Bond::STEREONONE) flags |= 0x1 << 1; streamWrite(ss, flags); if (bond->getBondType() != Bond::SINGLE) { tmpChar = static_cast<char>(bond->getBondType()); streamWrite(ss, tmpChar); } if (bond->getBondDir() != Bond::NONE) { tmpChar = static_cast<char>(bond->getBondDir()); streamWrite(ss, tmpChar); } // write info about the stereochemistry: if (bond->getStereo() != Bond::STEREONONE) { tmpChar = static_cast<char>(bond->getStereo()); streamWrite(ss, tmpChar); const INT_VECT &stereoAts = bond->getStereoAtoms(); tmpChar = rdcast<unsigned int>(stereoAts.size()); streamWrite(ss, tmpChar); for (int stereoAt : stereoAts) { tmpT = static_cast<T>(stereoAt); streamWrite(ss, tmpT); } } if (bond->hasQuery()) { streamWrite(ss, BEGINQUERY); pickleQuery(ss, static_cast<const QueryBond *>(bond)->getQuery()); streamWrite(ss, ENDQUERY); } } template <typename T> Bond *MolPickler::_addBondFromPickle(std::istream &ss, ROMol *mol, int version, bool directMap) { PRECONDITION(mol, "empty molecule"); char tmpChar; char flags; int begIdx, endIdx; T tmpT; Bond *bond = nullptr; streamRead(ss, tmpT, version); if (directMap) { begIdx = tmpT; } else { begIdx = mol->getAtomWithBookmark(static_cast<int>(tmpT))->getIdx(); } streamRead(ss, tmpT, version); if (directMap) { endIdx = tmpT; } else { endIdx = mol->getAtomWithBookmark(static_cast<int>(tmpT))->getIdx(); } streamRead(ss, flags, version); bool hasQuery = flags & 0x1 << 4; if (version <= 5000 || (version <= 7000 && !hasQuery) || version > 7000) { bond = new Bond(); bond->setIsAromatic(flags & 0x1 << 6); bond->setIsConjugated(flags & 0x1 << 5); if (version < 7000) { streamRead(ss, tmpChar, version); bond->setBondType(static_cast<Bond::BondType>(tmpChar)); streamRead(ss, tmpChar, version); bond->setBondDir(static_cast<Bond::BondDir>(tmpChar)); if (version > 3000) { streamRead(ss, tmpChar, version); Bond::BondStereo stereo = static_cast<Bond::BondStereo>(tmpChar); bond->setStereo(stereo); if (stereo != Bond::STEREONONE) { streamRead(ss, tmpChar, version); for (char i = 0; i < tmpChar; ++i) { streamRead(ss, tmpT, version); bond->getStereoAtoms().push_back(static_cast<int>(tmpT)); } } } } else { if (flags & (0x1 << 3)) { streamRead(ss, tmpChar, version); bond->setBondType(static_cast<Bond::BondType>(tmpChar)); } else { bond->setBondType(Bond::SINGLE); } if (flags & (0x1 << 2)) { streamRead(ss, tmpChar, version); bond->setBondDir(static_cast<Bond::BondDir>(tmpChar)); } else { bond->setBondDir(Bond::NONE); } if (flags & (0x1 << 1)) { streamRead(ss, tmpChar, version); Bond::BondStereo stereo = static_cast<Bond::BondStereo>(tmpChar); streamRead(ss, tmpChar, version); for (char i = 0; i < tmpChar; ++i) { streamRead(ss, tmpT, version); bond->getStereoAtoms().push_back(static_cast<int>(tmpT)); } bond->setStereo(stereo); } else { bond->setStereo(Bond::STEREONONE); } } } if (version > 5000 && hasQuery) { Tags tag; if (bond) { Bond *tbond = bond; bond = new QueryBond(*bond); delete tbond; } else { bond = new QueryBond(); } // we have a query: streamRead(ss, tag, version); if (tag != BEGINQUERY) { throw MolPicklerException("Bad pickle format: BEGINQUERY tag not found."); } static_cast<QueryBond *>(bond)->setQuery(unpickleQuery(ss, bond, version)); streamRead(ss, tag, version); if (tag != ENDQUERY) { throw MolPicklerException("Bad pickle format: ENDQUERY tag not found."); } } if (bond) { bond->setBeginAtomIdx(begIdx); bond->setEndAtomIdx(endIdx); mol->addBond(bond, true); } return bond; } //-------------------------------------- // // Rings // //-------------------------------------- template <typename T> void MolPickler::_pickleSSSR(std::ostream &ss, const RingInfo *ringInfo, std::map<int, int> &atomIdxMap) { PRECONDITION(ringInfo, "missing ring info"); T tmpT; tmpT = ringInfo->numRings(); streamWrite(ss, tmpT); for (unsigned int i = 0; i < ringInfo->numRings(); i++) { INT_VECT ring; ring = ringInfo->atomRings()[i]; tmpT = static_cast<T>(ring.size()); streamWrite(ss, tmpT); for (int &j : ring) { tmpT = static_cast<T>(atomIdxMap[j]); streamWrite(ss, tmpT); } #if 0 ring = ringInfo->bondRings()[i]; tmpT = static_cast<T>(ring.size()); streamWrite(ss,tmpT); for(unsigned int j=0;j<ring.size();j++){ tmpT = static_cast<T>(ring[j]); streamWrite(ss,tmpT); } #endif } } template <typename T> void MolPickler::_addRingInfoFromPickle(std::istream &ss, ROMol *mol, int version, bool directMap) { PRECONDITION(mol, "empty molecule"); RingInfo *ringInfo = mol->getRingInfo(); if (!ringInfo->isInitialized()) ringInfo->initialize(); T numRings; streamRead(ss, numRings, version); if (numRings > 0) { ringInfo->preallocate(mol->getNumAtoms(), mol->getNumBonds()); for (unsigned int i = 0; i < static_cast<unsigned int>(numRings); i++) { T tmpT; T ringSize; streamRead(ss, ringSize, version); INT_VECT atoms(static_cast<int>(ringSize)); INT_VECT bonds(static_cast<int>(ringSize)); for (unsigned int j = 0; j < static_cast<unsigned int>(ringSize); j++) { streamRead(ss, tmpT, version); if (directMap) { atoms[j] = static_cast<int>(tmpT); } else { atoms[j] = mol->getAtomWithBookmark(static_cast<int>(tmpT))->getIdx(); } } if (version < 7000) { for (unsigned int j = 0; j < static_cast<unsigned int>(ringSize); j++) { streamRead(ss, tmpT, version); if (directMap) { bonds[j] = static_cast<int>(tmpT); } else { bonds[j] = mol->getBondWithBookmark(static_cast<int>(tmpT))->getIdx(); } } } else { for (unsigned int j = 1; j < static_cast<unsigned int>(ringSize); ++j) { bonds[j - 1] = mol->getBondBetweenAtoms(atoms[j - 1], atoms[j])->getIdx(); } bonds[ringSize - 1] = mol->getBondBetweenAtoms(atoms[0], atoms[ringSize - 1])->getIdx(); } ringInfo->addRing(atoms, bonds); } } } //-------------------------------------- // // SubstanceGroups // //-------------------------------------- template <typename T> void MolPickler::_pickleSubstanceGroup(std::ostream &ss, const SubstanceGroup &sgroup, std::map<int, int> &atomIdxMap, std::map<int, int> &bondIdxMap) { T tmpT; streamWriteProps(ss, sgroup); const auto &atoms = sgroup.getAtoms(); streamWrite(ss, static_cast<T>(atoms.size())); for (const auto &atom : atoms) { tmpT = static_cast<T>(atomIdxMap[atom]); streamWrite(ss, tmpT); } const auto &p_atoms = sgroup.getParentAtoms(); streamWrite(ss, static_cast<T>(p_atoms.size())); for (const auto &p_atom : p_atoms) { tmpT = static_cast<T>(atomIdxMap[p_atom]); streamWrite(ss, tmpT); } const auto &bonds = sgroup.getBonds(); streamWrite(ss, static_cast<T>(bonds.size())); for (const auto &bond : bonds) { tmpT = static_cast<T>(bondIdxMap[bond]); streamWrite(ss, tmpT); } const auto &brackets = sgroup.getBrackets(); streamWrite(ss, static_cast<T>(brackets.size())); for (const auto &bracket : brackets) { // 3 point per bracket; 3rd point and all z are zeros, // but this might change in the future. for (const auto &pt : bracket) { float tmpFloat; tmpFloat = static_cast<float>(pt.x); streamWrite(ss, tmpFloat); tmpFloat = static_cast<float>(pt.y); streamWrite(ss, tmpFloat); tmpFloat = static_cast<float>(pt.z); streamWrite(ss, tmpFloat); } } const auto &cstates = sgroup.getCStates(); streamWrite(ss, static_cast<T>(cstates.size())); for (const auto &cstate : cstates) { // Bond tmpT = static_cast<T>(bondIdxMap[cstate.bondIdx]); streamWrite(ss, tmpT); // Vector -- existence depends on SubstanceGroup type if ("SUP" == sgroup.getProp<std::string>("TYPE")) { float tmpFloat; tmpFloat = static_cast<float>(cstate.vector.x); streamWrite(ss, tmpFloat); tmpFloat = static_cast<float>(cstate.vector.y); streamWrite(ss, tmpFloat); tmpFloat = static_cast<float>(cstate.vector.z); streamWrite(ss, tmpFloat); } } const auto &attachPoints = sgroup.getAttachPoints(); streamWrite(ss, static_cast<T>(attachPoints.size())); for (const auto &attachPoint : attachPoints) { // aIdx -- always present tmpT = static_cast<T>(atomIdxMap[attachPoint.aIdx]); streamWrite(ss, tmpT); // lvIdx -- may be -1 if not used (0 in spec) auto tmpInt = -1; if (attachPoint.lvIdx != -1) { tmpInt = static_cast<signed int>(atomIdxMap[attachPoint.lvIdx]); } streamWrite(ss, tmpInt); // id -- may be blank auto tmpS = static_cast<const std::string>(attachPoint.id); streamWrite(ss, tmpS); } } template <typename T> SubstanceGroup MolPickler::_getSubstanceGroupFromPickle(std::istream &ss, ROMol *mol, int version) { T tmpT; T numItems; float tmpFloat; int tmpInt = -1; std::string tmpS; // temporarily accept empty TYPE SubstanceGroup sgroup(mol, ""); // Read RDProps, overriding ID, TYPE and COMPNO streamReadProps(ss, sgroup, MolPickler::getCustomPropHandlers()); streamRead(ss, numItems, version); for (int i = 0; i < numItems; ++i) { streamRead(ss, tmpT, version); sgroup.addAtomWithIdx(tmpT); } streamRead(ss, numItems, version); for (int i = 0; i < numItems; ++i) { streamRead(ss, tmpT, version); sgroup.addParentAtomWithIdx(tmpT); } streamRead(ss, numItems, version); for (int i = 0; i < numItems; ++i) { streamRead(ss, tmpT, version); sgroup.addBondWithIdx(tmpT); } streamRead(ss, numItems, version); for (int i = 0; i < numItems; ++i) { SubstanceGroup::Bracket bracket; for (auto j = 0; j < 3; ++j) { streamRead(ss, tmpFloat, version); double x = static_cast<double>(tmpFloat); streamRead(ss, tmpFloat, version); double y = static_cast<double>(tmpFloat); streamRead(ss, tmpFloat, version); double z = static_cast<double>(tmpFloat); bracket[j] = RDGeom::Point3D(x, y, z); } sgroup.addBracket(bracket); } streamRead(ss, numItems, version); for (int i = 0; i < numItems; ++i) { streamRead(ss, tmpT, version); RDGeom::Point3D vector; if ("SUP" == sgroup.getProp<std::string>("TYPE")) { streamRead(ss, tmpFloat, version); vector.x = static_cast<double>(tmpFloat); streamRead(ss, tmpFloat, version); vector.y = static_cast<double>(tmpFloat); streamRead(ss, tmpFloat, version); vector.z = static_cast<double>(tmpFloat); } sgroup.addCState(tmpT, vector); } streamRead(ss, numItems, version); for (int i = 0; i < numItems; ++i) { streamRead(ss, tmpT, version); unsigned int aIdx = tmpT; streamRead(ss, tmpInt, version); int lvIdx = tmpInt; std::string id; streamRead(ss, id, version); sgroup.addAttachPoint(aIdx, lvIdx, id); } return sgroup; } template <typename T> void MolPickler::_pickleStereo(std::ostream &ss, const std::vector<StereoGroup> &groups, std::map<int, int> &atomIdxMap) { T tmpT = static_cast<T>(groups.size()); streamWrite(ss, tmpT); for (auto &&group : groups) { streamWrite(ss, static_cast<T>(group.getGroupType())); auto &atoms = group.getAtoms(); streamWrite(ss, static_cast<T>(atoms.size())); for (auto &&atom : atoms) { tmpT = static_cast<T>(atomIdxMap[atom->getIdx()]); streamWrite(ss, tmpT); } } } template <typename T> void MolPickler::_depickleStereo(std::istream &ss, ROMol *mol, int version) { T tmpT; streamRead(ss, tmpT, version); const unsigned numGroups = static_cast<unsigned>(tmpT); if (numGroups > 0u) { std::vector<StereoGroup> groups; for (unsigned group = 0u; group < numGroups; ++group) { T tmpT; streamRead(ss, tmpT, version); const auto groupType = static_cast<RDKit::StereoGroupType>(tmpT); streamRead(ss, tmpT, version); const unsigned numAtoms = static_cast<unsigned>(tmpT); std::vector<Atom *> atoms; atoms.reserve(numAtoms); for (unsigned i = 0u; i < numAtoms; ++i) { streamRead(ss, tmpT, version); atoms.push_back(mol->getAtomWithIdx(tmpT)); } groups.emplace_back(groupType, std::move(atoms)); } mol->setStereoGroups(std::move(groups)); } } void MolPickler::_pickleProperties(std::ostream &ss, const RDProps &props, unsigned int pickleFlags) { if (!pickleFlags) return; streamWriteProps(ss, props, pickleFlags & PicklerOps::PrivateProps, pickleFlags & PicklerOps::ComputedProps, MolPickler::getCustomPropHandlers() ); } //! unpickle standard properties void MolPickler::_unpickleProperties(std::istream &ss, RDProps &props) { streamReadProps(ss, props, MolPickler::getCustomPropHandlers()); } //-------------------------------------- // // Version 1 Pickler: // // NOTE: this is not 64bit clean, but it shouldn't be used anymore anyway // //-------------------------------------- void MolPickler::_pickleV1(const ROMol *mol, std::ostream &ss) { PRECONDITION(mol, "empty molecule"); ROMol::ConstAtomIterator atIt; const Conformer *conf = nullptr; if (mol->getNumConformers() > 0) { conf = &(mol->getConformer()); } for (atIt = mol->beginAtoms(); atIt != mol->endAtoms(); ++atIt) { const Atom *atom = *atIt; streamWrite(ss, BEGINATOM); streamWrite(ss, ATOM_NUMBER, atom->getAtomicNum()); streamWrite(ss, ATOM_INDEX, atom->getIdx()); streamWrite(ss, ATOM_POS); RDGeom::Point3D p; if (conf) { p = conf->getAtomPos(atom->getIdx()); } streamWrite(ss, p.x); streamWrite(ss, p.y); streamWrite(ss, p.z); if (atom->getFormalCharge() != 0) { streamWrite(ss, ATOM_CHARGE, atom->getFormalCharge()); } if (atom->getNumExplicitHs() != 0) { streamWrite(ss, ATOM_NEXPLICIT, atom->getNumExplicitHs()); } if (atom->getChiralTag() != 0) { streamWrite(ss, ATOM_CHIRALTAG, atom->getChiralTag()); } if (atom->getIsAromatic()) { streamWrite(ss, ATOM_ISAROMATIC, static_cast<char>(atom->getIsAromatic())); } streamWrite(ss, ENDATOM); } ROMol::ConstBondIterator bondIt; for (bondIt = mol->beginBonds(); bondIt != mol->endBonds(); ++bondIt) { const Bond *bond = *bondIt; streamWrite(ss, BEGINBOND); streamWrite(ss, BOND_INDEX, bond->getIdx()); streamWrite(ss, BOND_BEGATOMIDX, bond->getBeginAtomIdx()); streamWrite(ss, BOND_ENDATOMIDX, bond->getEndAtomIdx()); streamWrite(ss, BOND_TYPE, bond->getBondType()); if (bond->getBondDir()) { streamWrite(ss, BOND_DIR, bond->getBondDir()); } streamWrite(ss, ENDBOND); } streamWrite(ss, ENDMOL); } void MolPickler::_depickleV1(std::istream &ss, ROMol *mol) { PRECONDITION(mol, "empty molecule"); Tags tag; auto *conf = new Conformer(); mol->addConformer(conf); streamRead(ss, tag, 1); while (tag != ENDMOL) { switch (tag) { case BEGINATOM: _addAtomFromPickleV1(ss, mol); break; case BEGINBOND: _addBondFromPickleV1(ss, mol); break; default: UNDER_CONSTRUCTION("bad tag in pickle"); } streamRead(ss, tag, 1); } mol->clearAllAtomBookmarks(); mol->clearAllBondBookmarks(); } void MolPickler::_addAtomFromPickleV1(std::istream &ss, ROMol *mol) { PRECONDITION(mol, "empty molecule"); Tags tag; int intVar; double dblVar; char charVar; int version = 1; streamRead(ss, tag, version); auto *atom = new Atom(); Conformer &conf = mol->getConformer(); RDGeom::Point3D pos; while (tag != ENDATOM) { switch (tag) { case ATOM_INDEX: streamRead(ss, intVar, version); mol->setAtomBookmark(atom, intVar); break; case ATOM_NUMBER: streamRead(ss, intVar, version); atom->setAtomicNum(intVar); break; case ATOM_POS: streamRead(ss, pos.x, version); streamRead(ss, pos.y, version); streamRead(ss, pos.z, version); break; case ATOM_CHARGE: streamRead(ss, intVar, version); atom->setFormalCharge(intVar); break; case ATOM_NEXPLICIT: streamRead(ss, intVar, version); atom->setNumExplicitHs(intVar); break; case ATOM_CHIRALTAG: streamRead(ss, intVar, version); atom->setChiralTag(static_cast<Atom::ChiralType>(intVar)); break; case ATOM_MASS: streamRead(ss, dblVar, version); // we don't need to set this anymore, but we do need to read it in // order to maintain backwards compatibility break; case ATOM_ISAROMATIC: streamRead(ss, charVar, version); atom->setIsAromatic(charVar); break; default: ASSERT_INVARIANT(0, "bad tag in atom block of pickle"); } streamRead(ss, tag, version); } unsigned int id = mol->addAtom(atom, false, true); conf.setAtomPos(id, pos); } void MolPickler::_addBondFromPickleV1(std::istream &ss, ROMol *mol) { PRECONDITION(mol, "empty molecule"); Tags tag; int intVar, idx = -1; int version = 1; Bond::BondType bt; Bond::BondDir bd; streamRead(ss, tag, version); auto *bond = new Bond(); while (tag != ENDBOND) { switch (tag) { case BOND_INDEX: streamRead(ss, idx, version); break; case BOND_BEGATOMIDX: streamRead(ss, intVar, version); bond->setBeginAtomIdx(mol->getAtomWithBookmark(intVar)->getIdx()); break; case BOND_ENDATOMIDX: streamRead(ss, intVar, version); bond->setEndAtomIdx(mol->getAtomWithBookmark(intVar)->getIdx()); break; case BOND_TYPE: streamRead(ss, bt, version); bond->setBondType(bt); break; case BOND_DIR: streamRead(ss, bd, version); bond->setBondDir(bd); break; default: ASSERT_INVARIANT(0, "bad tag in bond block of pickle"); } streamRead(ss, tag, version); } mol->addBond(bond, true); } }; // namespace RDKit
1
17,011
Isn't the % 128 redundant here?
rdkit-rdkit
cpp
@@ -34,7 +34,9 @@ func TestCmdMarshalProto(t *testing.T) { "sticky": false, "group_enforced": false, "compressed": false, - "cascaded": false + "cascaded": false, + "loopdev": false, + "ramdisk": false }`, data, )
1
package cli import ( "testing" "github.com/libopenstorage/openstorage/api" "github.com/stretchr/testify/require" ) func TestCmdMarshalProto(t *testing.T) { volumeSpec := &api.VolumeSpec{ Size: 64, Format: api.FSType_FS_TYPE_EXT4, } data := cmdMarshalProto(volumeSpec, false) require.Equal( t, `{ "ephemeral": false, "size": "64", "format": "ext4", "block_size": "0", "ha_level": "0", "cos": "none", "io_profile": "sequential", "dedupe": false, "snapshot_interval": 0, "shared": false, "aggregation_level": 0, "encrypted": false, "passphrase": "", "snapshot_schedule": "", "scale": 0, "sticky": false, "group_enforced": false, "compressed": false, "cascaded": false }`, data, ) }
1
6,239
Are you testing that the values are always false? I think you should test for setting values to true or false, right? Who is going to take action with these values?
libopenstorage-openstorage
go
@@ -35,6 +35,9 @@ extern const struct batch_queue_module batch_queue_wq; extern const struct batch_queue_module batch_queue_mesos; extern const struct batch_queue_module batch_queue_k8s; extern const struct batch_queue_module batch_queue_dryrun; +#ifdef MPI +extern const struct batch_queue_module batch_queue_mpi; +#endif static struct batch_queue_module batch_queue_unknown = { BATCH_QUEUE_TYPE_UNKNOWN, "unknown",
1
/* Copyright (C) 2003-2004 Douglas Thain and the University of Wisconsin Copyright (C) 2005- The University of Notre Dame This software is distributed under the GNU General Public License. See the file COPYING for details. */ #include "batch_job.h" #include "batch_job_internal.h" #include "debug.h" #include "itable.h" #include "stringtools.h" #include "xxmalloc.h" #include <sys/stat.h> #include <stdlib.h> #include <string.h> extern const struct batch_queue_module batch_queue_amazon; extern const struct batch_queue_module batch_queue_lambda; extern const struct batch_queue_module batch_queue_amazon_batch; extern const struct batch_queue_module batch_queue_chirp; extern const struct batch_queue_module batch_queue_cluster; extern const struct batch_queue_module batch_queue_condor; extern const struct batch_queue_module batch_queue_local; extern const struct batch_queue_module batch_queue_moab; extern const struct batch_queue_module batch_queue_sge; extern const struct batch_queue_module batch_queue_pbs; extern const struct batch_queue_module batch_queue_torque; extern const struct batch_queue_module batch_queue_blue_waters; extern const struct batch_queue_module batch_queue_slurm; extern const struct batch_queue_module batch_queue_wq; extern const struct batch_queue_module batch_queue_mesos; extern const struct batch_queue_module batch_queue_k8s; extern const struct batch_queue_module batch_queue_dryrun; static struct batch_queue_module batch_queue_unknown = { BATCH_QUEUE_TYPE_UNKNOWN, "unknown", NULL, NULL, NULL, NULL, {NULL, NULL, NULL}, {NULL, NULL, NULL, NULL, NULL, NULL, NULL}, }; #define BATCH_JOB_SYSTEMS "local, wq, condor, sge, torque, mesos, k8s, moab, slurm, chirp, amazon, dryrun, lambda, amazon-batch" const struct batch_queue_module * const batch_queue_modules[] = { &batch_queue_amazon, &batch_queue_amazon_batch, &batch_queue_lambda, #ifdef CCTOOLS_WITH_CHIRP &batch_queue_chirp, #endif &batch_queue_cluster, &batch_queue_condor, &batch_queue_local, &batch_queue_moab, &batch_queue_sge, &batch_queue_pbs, &batch_queue_torque, &batch_queue_blue_waters, &batch_queue_slurm, &batch_queue_wq, &batch_queue_mesos, &batch_queue_k8s, &batch_queue_dryrun, &batch_queue_unknown }; struct batch_job_info *batch_job_info_create() { struct batch_job_info *info = calloc(1,sizeof(*info)); return info; } void batch_job_info_delete(struct batch_job_info *info) { free(info); } struct batch_queue *batch_queue_create(batch_queue_type_t type) { int i; struct batch_queue *q; q = xxmalloc(sizeof(*q)); q->type = type; strncpy(q->logfile, "", sizeof(q->logfile)); q->options = hash_table_create(0, NULL); q->features = hash_table_create(0, NULL); q->job_table = itable_create(0); q->output_table = itable_create(0); q->data = NULL; batch_queue_set_feature(q, "local_job_queue", "yes"); batch_queue_set_feature(q, "absolute_path", "yes"); batch_queue_set_feature(q, "output_directories", "yes"); batch_queue_set_feature(q, "batch_log_name", "%s.batchlog"); batch_queue_set_feature(q, "gc_size", "yes"); q->module = NULL; for (i = 0; batch_queue_modules[i]->type != BATCH_QUEUE_TYPE_UNKNOWN; i++) if (batch_queue_modules[i]->type == type) q->module = batch_queue_modules[i]; if (q->module == NULL) { batch_queue_delete(q); return NULL; } if(q->module->create(q) == -1) { batch_queue_delete(q); return NULL; } debug(D_BATCH, "created queue %p (%s)", q, q->module->typestr); return q; } void batch_queue_delete(struct batch_queue *q) { if(q) { char *key; char *value; debug(D_BATCH, "deleting queue %p", q); q->module->free(q); for (hash_table_firstkey(q->options); hash_table_nextkey(q->options, &key, (void **) &value); free(value)) ; hash_table_delete(q->options); for (hash_table_firstkey(q->features); hash_table_nextkey(q->features, &key, (void **) &value); free(value)) ; hash_table_delete(q->features); itable_delete(q->job_table); itable_delete(q->output_table); free(q); } } const char *batch_queue_get_option (struct batch_queue *q, const char *what) { return hash_table_lookup(q->options, what); } const char *batch_queue_supports_feature (struct batch_queue *q, const char *what) { return hash_table_lookup(q->features, what); } batch_queue_type_t batch_queue_get_type(struct batch_queue *q) { return q->type; } void batch_queue_set_logfile(struct batch_queue *q, const char *logfile) { strncpy(q->logfile, logfile, sizeof(q->logfile)); q->logfile[sizeof(q->logfile)-1] = '\0'; debug(D_BATCH, "set logfile to `%s'", logfile); const char *tr_pattern = batch_queue_supports_feature(q, "batch_log_transactions"); if(tr_pattern) { char *tr_name = string_format(tr_pattern, q->logfile); batch_queue_set_option(q, "batch_log_transactions_name", tr_name); free(tr_name); } } int batch_queue_port(struct batch_queue *q) { return q->module->port(q); } void batch_queue_set_option (struct batch_queue *q, const char *what, const char *value) { char *current = hash_table_remove(q->options, what); if(value) { hash_table_insert(q->options, what, xxstrdup(value)); debug(D_BATCH, "set option `%s' to `%s'", what, value); } else { debug(D_BATCH, "cleared option `%s'", what); } free(current); q->module->option_update(q, what, value); } void batch_queue_set_feature (struct batch_queue *q, const char *what, const char *value) { char *current = hash_table_remove(q->features, what); if(value) { hash_table_insert(q->features, what, xxstrdup(value)); debug(D_BATCH, "set feature `%s' to `%s'", what, value); } else { debug(D_BATCH, "cleared feature `%s'", what); } free(current); } void batch_queue_set_int_option(struct batch_queue *q, const char *what, int value) { char *str_value = string_format("%d", value); batch_queue_set_option(q, what, str_value); free(str_value); } batch_queue_type_t batch_queue_type_from_string(const char *str) { int i; for (i = 0; batch_queue_modules[i]->type != BATCH_QUEUE_TYPE_UNKNOWN; i++) if (strcmp(batch_queue_modules[i]->typestr, str) == 0) return batch_queue_modules[i]->type; return BATCH_QUEUE_TYPE_UNKNOWN; } const char *batch_queue_type_to_string(batch_queue_type_t t) { int i; for (i = 0; batch_queue_modules[i]->type != BATCH_QUEUE_TYPE_UNKNOWN; i++) if (batch_queue_modules[i]->type == t) return batch_queue_modules[i]->typestr; return "unknown"; } const char *batch_queue_type_string() { return BATCH_JOB_SYSTEMS; } batch_job_id_t batch_job_submit(struct batch_queue * q, const char *cmd, const char *extra_input_files, const char *extra_output_files, struct jx *envlist, const struct rmsummary *resources) { return q->module->job.submit(q, cmd, extra_input_files, extra_output_files, envlist, resources); } batch_job_id_t batch_job_wait(struct batch_queue * q, struct batch_job_info * info) { return q->module->job.wait(q, info, 0); } batch_job_id_t batch_job_wait_timeout(struct batch_queue * q, struct batch_job_info * info, time_t stoptime) { return q->module->job.wait(q, info, stoptime); } int batch_job_remove(struct batch_queue *q, batch_job_id_t jobid) { return q->module->job.remove(q, jobid); } int batch_fs_chdir (struct batch_queue *q, const char *path) { return q->module->fs.chdir(q, path); } int batch_fs_getcwd (struct batch_queue *q, char *buf, size_t size) { return q->module->fs.getcwd(q, buf, size); } int batch_fs_mkdir (struct batch_queue *q, const char *path, mode_t mode, int recursive) { return q->module->fs.mkdir(q, path, mode, recursive); } int batch_fs_putfile (struct batch_queue *q, const char *lpath, const char *rpath) { return q->module->fs.putfile(q, lpath, rpath); } int batch_fs_rename (struct batch_queue *q, const char *lpath, const char *rpath) { return q->module->fs.rename(q, lpath, rpath); } int batch_fs_stat (struct batch_queue *q, const char *path, struct stat *buf) { return q->module->fs.stat(q, path, buf); } int batch_fs_unlink (struct batch_queue *q, const char *path) { return q->module->fs.unlink(q, path); } /* vim: set noexpandtab tabstop=4: */
1
14,413
Please change MPI to CCTOOLS_WITH_MPI
cooperative-computing-lab-cctools
c
@@ -16,6 +16,11 @@ #include "oneapi/dal/algo/decision_forest/common.hpp" #include "oneapi/dal/algo/decision_forest/detail/model_impl.hpp" +#include "oneapi/dal/exceptions.hpp" + +#define DAL_CHECK_DOMAIN_COND(cond, description) \ + if (!(cond)) \ + throw domain_error(description); namespace oneapi::dal::decision_forest {
1
/******************************************************************************* * Copyright 2020 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. *******************************************************************************/ #include "oneapi/dal/algo/decision_forest/common.hpp" #include "oneapi/dal/algo/decision_forest/detail/model_impl.hpp" namespace oneapi::dal::decision_forest { template <> class detail::descriptor_impl<task::classification> : public base { public: double observations_per_tree_fraction = 1.0; double impurity_threshold = 0.0; double min_weight_fraction_in_leaf_node = 0.0; double min_impurity_decrease_in_split_node = 0.0; std::int64_t class_count = 2; std::int64_t tree_count = 100; std::int64_t features_per_node = 0; std::int64_t max_tree_depth = 0; std::int64_t min_observations_in_leaf_node = 1; std::int64_t min_observations_in_split_node = 2; std::int64_t max_leaf_nodes = 0; error_metric_mode error_metric_mode_value = error_metric_mode::none; infer_mode infer_mode_value = infer_mode::class_labels; bool memory_saving_mode = false; bool bootstrap = true; variable_importance_mode variable_importance_mode_value = variable_importance_mode::none; voting_mode voting_mode_value = voting_mode::weighted; }; template <> class detail::descriptor_impl<task::regression> : public base { public: double observations_per_tree_fraction = 1.0; double impurity_threshold = 0.0; double min_weight_fraction_in_leaf_node = 0.0; double min_impurity_decrease_in_split_node = 0.0; std::int64_t class_count = 0; std::int64_t tree_count = 100; std::int64_t features_per_node = 0; std::int64_t max_tree_depth = 0; std::int64_t min_observations_in_leaf_node = 5; std::int64_t min_observations_in_split_node = 2; std::int64_t max_leaf_nodes = 0; error_metric_mode error_metric_mode_value = error_metric_mode::none; infer_mode infer_mode_value = infer_mode::class_labels; bool memory_saving_mode = false; bool bootstrap = true; // engine field variable_importance_mode variable_importance_mode_value = variable_importance_mode::none; voting_mode voting_mode_value = voting_mode::weighted; }; using detail::descriptor_impl; using detail::model_impl; /* descriptor_base implementation */ template <typename Task> descriptor_base<Task>::descriptor_base() : impl_(new descriptor_impl<Task>{}) {} /*getters implementation*/ template <typename Task> double descriptor_base<Task>::get_observations_per_tree_fraction() const { return impl_->observations_per_tree_fraction; } template <typename Task> double descriptor_base<Task>::get_impurity_threshold() const { return impl_->impurity_threshold; } template <typename Task> double descriptor_base<Task>::get_min_weight_fraction_in_leaf_node() const { return impl_->min_weight_fraction_in_leaf_node; } template <typename Task> double descriptor_base<Task>::get_min_impurity_decrease_in_split_node() const { return impl_->min_impurity_decrease_in_split_node; } template <typename Task> std::int64_t descriptor_base<Task>::get_tree_count() const { return impl_->tree_count; } template <typename Task> std::int64_t descriptor_base<Task>::get_features_per_node() const { return impl_->features_per_node; } template <typename Task> std::int64_t descriptor_base<Task>::get_max_tree_depth() const { return impl_->max_tree_depth; } template <typename Task> std::int64_t descriptor_base<Task>::get_min_observations_in_leaf_node() const { return impl_->min_observations_in_leaf_node; } template <typename Task> std::int64_t descriptor_base<Task>::get_min_observations_in_split_node() const { return impl_->min_observations_in_split_node; } template <typename Task> std::int64_t descriptor_base<Task>::get_max_leaf_nodes() const { return impl_->max_leaf_nodes; } template <typename Task> error_metric_mode descriptor_base<Task>::get_error_metric_mode() const { return impl_->error_metric_mode_value; } template <typename Task> bool descriptor_base<Task>::get_memory_saving_mode() const { return impl_->memory_saving_mode; } template <typename Task> bool descriptor_base<Task>::get_bootstrap() const { return impl_->bootstrap; } template <typename Task> variable_importance_mode descriptor_base<Task>::get_variable_importance_mode() const { return impl_->variable_importance_mode_value; } template <typename Task> infer_mode descriptor_base<Task>::get_infer_mode_impl() const { return impl_->infer_mode_value; } template <typename Task> std::int64_t descriptor_base<Task>::get_class_count_impl() const { return impl_->class_count; } template <typename Task> voting_mode descriptor_base<Task>::get_voting_mode_impl() const { return impl_->voting_mode_value; } /*setters implementation*/ template <typename Task> void descriptor_base<Task>::set_observations_per_tree_fraction_impl(double value) { impl_->observations_per_tree_fraction = value; } template <typename Task> void descriptor_base<Task>::set_impurity_threshold_impl(double value) { impl_->impurity_threshold = value; } template <typename Task> void descriptor_base<Task>::set_min_weight_fraction_in_leaf_node_impl(double value) { impl_->min_weight_fraction_in_leaf_node = value; } template <typename Task> void descriptor_base<Task>::set_min_impurity_decrease_in_split_node_impl(double value) { impl_->min_impurity_decrease_in_split_node = value; } template <typename Task> void descriptor_base<Task>::set_tree_count_impl(std::int64_t value) { impl_->tree_count = value; } template <typename Task> void descriptor_base<Task>::set_features_per_node_impl(std::int64_t value) { impl_->features_per_node = value; } template <typename Task> void descriptor_base<Task>::set_max_tree_depth_impl(std::int64_t value) { impl_->max_tree_depth = value; } template <typename Task> void descriptor_base<Task>::set_min_observations_in_leaf_node_impl(std::int64_t value) { impl_->min_observations_in_leaf_node = value; } template <typename Task> void descriptor_base<Task>::set_min_observations_in_split_node_impl(std::int64_t value) { impl_->min_observations_in_split_node = value; } template <typename Task> void descriptor_base<Task>::set_max_leaf_nodes_impl(std::int64_t value) { impl_->max_leaf_nodes = value; } template <typename Task> void descriptor_base<Task>::set_error_metric_mode_impl(error_metric_mode value) { impl_->error_metric_mode_value = value; } template <typename Task> void descriptor_base<Task>::set_infer_mode_impl(infer_mode value) { impl_->infer_mode_value = value; } template <typename Task> void descriptor_base<Task>::set_memory_saving_mode_impl(bool value) { impl_->memory_saving_mode = value; } template <typename Task> void descriptor_base<Task>::set_bootstrap_impl(bool value) { impl_->bootstrap = value; } template <typename Task> void descriptor_base<Task>::set_variable_importance_mode_impl(variable_importance_mode value) { impl_->variable_importance_mode_value = value; } template <typename Task> void descriptor_base<Task>::set_class_count_impl(std::int64_t value) { impl_->class_count = value; } template <typename Task> void descriptor_base<Task>::set_voting_mode_impl(voting_mode value) { impl_->voting_mode_value = value; } template class ONEAPI_DAL_EXPORT descriptor_base<task::classification>; template class ONEAPI_DAL_EXPORT descriptor_base<task::regression>; /* model implementation */ template <typename Task> model<Task>::model() : impl_(new detail::model_impl<Task>{}) {} template <typename Task> model<Task>::model(const model::pimpl& impl) : impl_(impl) {} template <typename Task> std::int64_t model<Task>::get_tree_count() const { return impl_->get_tree_count(); } template <typename Task> std::int64_t model<Task>::get_class_count_impl() const { return impl_->get_class_count(); } template <typename Task> void model<Task>::clear() { impl_->clear(); } template class ONEAPI_DAL_EXPORT model<task::classification>; template class ONEAPI_DAL_EXPORT model<task::regression>; } // namespace oneapi::dal::decision_forest
1
24,060
Why you can't use function here?
oneapi-src-oneDAL
cpp
@@ -0,0 +1,16 @@ +// Copyright 2018 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 ssm + +//go:generate go run ../../scripts/generate/mockgen.go github.com/aws/aws-sdk-go/service/ssm/ssmiface SSMAPI mocks/ssmiface_mocks.go
1
1
21,017
We should scope this down to only the methods we use.
aws-amazon-ecs-agent
go
@@ -800,7 +800,7 @@ public final class HashSet<T> implements Set<T>, Serializable { @Override public String toString() { - return mkString(", ", "HashSet(", ")"); + return mkString("HashSet(", ", ", ")"); } private static <T> HashArrayMappedTrie<T, T> addAll(HashArrayMappedTrie<T, T> initial,
1
/* / \____ _ _ ____ ______ / \ ____ __ _ _____ * / / \/ \ / \/ \ / /\__\/ // \/ \ / / _ \ Javaslang * _/ / /\ \ \/ / /\ \\__\\ \ // /\ \ /\\/ \__/ / Copyright 2014-now Daniel Dietrich * /___/\_/ \_/\____/\_/ \_/\__\/__/___\_/ \_// \__/_____/ Licensed under the Apache License, Version 2.0 */ package javaslang.collection; import java.io.IOException; import java.io.InvalidObjectException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.Comparator; import java.util.NoSuchElementException; import java.util.Objects; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.BinaryOperator; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.stream.Collector; import javaslang.Lazy; import javaslang.Tuple; import javaslang.Tuple2; import javaslang.Tuple3; import javaslang.control.None; import javaslang.control.Option; import javaslang.control.Some; /** * An immutable {@code HashSet} implementation. * * @param <T> Component type * @author Ruslan Sennov, Patryk Najda, Daniel Dietrich * @since 2.0.0 */ public final class HashSet<T> implements Set<T>, Serializable { private static final long serialVersionUID = 1L; private static final HashSet<?> EMPTY = new HashSet<>(HashArrayMappedTrie.empty()); private final HashArrayMappedTrie<T, T> tree; private final transient Lazy<Integer> hash; private HashSet(HashArrayMappedTrie<T, T> tree) { this.tree = tree; this.hash = Lazy.of(() -> Traversable.hash(tree::iterator)); } @SuppressWarnings("unchecked") public static <T> HashSet<T> empty() { return (HashSet<T>) EMPTY; } /** * 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.HashSet}. * * @param <T> Component type of the HashSet. * @return A javaslang.collection.HashSet Collector. */ public static <T> Collector<T, ArrayList<T>, HashSet<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>, HashSet<T>> finisher = HashSet::ofAll; return Collector.of(supplier, accumulator, combiner, finisher); } /** * Returns a singleton {@code HashSet}, i.e. a {@code HashSet} of one element. * * @param element An element. * @param <T> The component type * @return A new HashSet instance containing the given element */ public static <T> HashSet<T> of(T element) { return HashSet.<T> empty().add(element); } /** * Creates a HashSet of the given elements. * * <pre><code>HashSet.ofAll(1, 2, 3, 4)</code></pre> * * @param <T> Component type of the HashSet. * @param elements Zero or more elements. * @return A set containing the given elements. * @throws NullPointerException if {@code elements} is null */ @SafeVarargs public static <T> HashSet<T> ofAll(T... elements) { Objects.requireNonNull(elements, "elements is null"); HashArrayMappedTrie<T, T> tree = HashArrayMappedTrie.empty(); for (T element : elements) { tree = tree.put(element, element); } return new HashSet<>(tree); } /** * Creates a HashSet of the given elements. * * @param elements Set elements * @param <T> The value type * @return A new HashSet containing the given entries */ @SuppressWarnings("unchecked") public static <T> HashSet<T> ofAll(java.lang.Iterable<? extends T> elements) { Objects.requireNonNull(elements, "elements is null"); if (elements instanceof HashSet) { return (HashSet<T>) elements; } else { final HashArrayMappedTrie<T, T> tree = addAll(HashArrayMappedTrie.empty(), elements); return tree.isEmpty() ? empty() : new HashSet<>(tree); } } /** * Creates a HashSet based on the elements of a boolean array. * * @param array a boolean array * @return A new HashSet of Boolean values */ public static HashSet<Boolean> ofAll(boolean[] array) { Objects.requireNonNull(array, "array is null"); return HashSet.ofAll(Iterator.ofAll(array)); } /** * Creates a HashSet based on the elements of a byte array. * * @param array a byte array * @return A new HashSet of Byte values */ public static HashSet<Byte> ofAll(byte[] array) { Objects.requireNonNull(array, "array is null"); return HashSet.ofAll(Iterator.ofAll(array)); } /** * Creates a HashSet based on the elements of a char array. * * @param array a char array * @return A new HashSet of Character values */ public static HashSet<Character> ofAll(char[] array) { Objects.requireNonNull(array, "array is null"); return HashSet.ofAll(Iterator.ofAll(array)); } /** * Creates a HashSet based on the elements of a double array. * * @param array a double array * @return A new HashSet of Double values */ public static HashSet<Double> ofAll(double[] array) { Objects.requireNonNull(array, "array is null"); return HashSet.ofAll(Iterator.ofAll(array)); } /** * Creates a HashSet based on the elements of a float array. * * @param array a float array * @return A new HashSet of Float values */ public static HashSet<Float> ofAll(float[] array) { Objects.requireNonNull(array, "array is null"); return HashSet.ofAll(Iterator.ofAll(array)); } /** * Creates a HashSet based on the elements of an int array. * * @param array an int array * @return A new HashSet of Integer values */ public static HashSet<Integer> ofAll(int[] array) { Objects.requireNonNull(array, "array is null"); return HashSet.ofAll(Iterator.ofAll(array)); } /** * Creates a HashSet based on the elements of a long array. * * @param array a long array * @return A new HashSet of Long values */ public static HashSet<Long> ofAll(long[] array) { Objects.requireNonNull(array, "array is null"); return HashSet.ofAll(Iterator.ofAll(array)); } /** * Creates a HashSet based on the elements of a short array. * * @param array a short array * @return A new HashSet of Short values */ public static HashSet<Short> ofAll(short[] array) { Objects.requireNonNull(array, "array is null"); return HashSet.ofAll(Iterator.ofAll(array)); } /** * Creates a HashSet of int numbers starting from {@code from}, extending to {@code toExclusive - 1}. * <p> * Examples: * <pre> * <code> * HashSet.range(0, 0) // = HashSet() * HashSet.range(2, 0) // = HashSet() * HashSet.range(-2, 2) // = HashSet(-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} */ public static HashSet<Integer> range(int from, int toExclusive) { return HashSet.ofAll(Iterator.range(from, toExclusive)); } public static HashSet<Character> range(char from, char toExclusive) { return HashSet.ofAll(Iterator.range(from, toExclusive)); } /** * Creates a HashSet of int numbers starting from {@code from}, extending to {@code toExclusive - 1}, * with {@code step}. * <p> * Examples: * <pre> * <code> * HashSet.rangeBy(1, 3, 1) // = HashSet(1, 2) * HashSet.rangeBy(1, 4, 2) // = HashSet(1, 3) * HashSet.rangeBy(4, 1, -2) // = HashSet(4, 2) * HashSet.rangeBy(4, 1, 2) // = HashSet() * </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 */ public static HashSet<Integer> rangeBy(int from, int toExclusive, int step) { return HashSet.ofAll(Iterator.rangeBy(from, toExclusive, step)); } public static HashSet<Character> rangeBy(char from, char toExclusive, int step) { return HashSet.ofAll(Iterator.rangeBy(from, toExclusive, step)); } public static HashSet<Double> rangeBy(double from, double toExclusive, double step) { return HashSet.ofAll(Iterator.rangeBy(from, toExclusive, step)); } /** * Creates a HashSet of long numbers starting from {@code from}, extending to {@code toExclusive - 1}. * <p> * Examples: * <pre> * <code> * HashSet.range(0L, 0L) // = HashSet() * HashSet.range(2L, 0L) // = HashSet() * HashSet.range(-2L, 2L) // = HashSet(-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} */ public static HashSet<Long> range(long from, long toExclusive) { return HashSet.ofAll(Iterator.range(from, toExclusive)); } /** * Creates a HashSet of long numbers starting from {@code from}, extending to {@code toExclusive - 1}, * with {@code step}. * <p> * Examples: * <pre> * <code> * HashSet.rangeBy(1L, 3L, 1L) // = HashSet(1L, 2L) * HashSet.rangeBy(1L, 4L, 2L) // = HashSet(1L, 3L) * HashSet.rangeBy(4L, 1L, -2L) // = HashSet(4L, 2L) * HashSet.rangeBy(4L, 1L, 2L) // = HashSet() * </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 */ public static HashSet<Long> rangeBy(long from, long toExclusive, long step) { return HashSet.ofAll(Iterator.rangeBy(from, toExclusive, step)); } /** * Creates a HashSet of int numbers starting from {@code from}, extending to {@code toInclusive}. * <p> * Examples: * <pre> * <code> * HashSet.rangeClosed(0, 0) // = HashSet(0) * HashSet.rangeClosed(2, 0) // = HashSet() * HashSet.rangeClosed(-2, 2) // = HashSet(-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} */ public static HashSet<Integer> rangeClosed(int from, int toInclusive) { return HashSet.ofAll(Iterator.rangeClosed(from, toInclusive)); } public static HashSet<Character> rangeClosed(char from, char toInclusive) { return HashSet.ofAll(Iterator.rangeClosed(from, toInclusive)); } /** * Creates a HashSet of int numbers starting from {@code from}, extending to {@code toInclusive}, * with {@code step}. * <p> * Examples: * <pre> * <code> * HashSet.rangeClosedBy(1, 3, 1) // = HashSet(1, 2, 3) * HashSet.rangeClosedBy(1, 4, 2) // = HashSet(1, 3) * HashSet.rangeClosedBy(4, 1, -2) // = HashSet(4, 2) * HashSet.rangeClosedBy(4, 1, 2) // = HashSet() * </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 */ public static HashSet<Integer> rangeClosedBy(int from, int toInclusive, int step) { return HashSet.ofAll(Iterator.rangeClosedBy(from, toInclusive, step)); } public static HashSet<Character> rangeClosedBy(char from, char toInclusive, int step) { return HashSet.ofAll(Iterator.rangeClosedBy(from, toInclusive, step)); } public static HashSet<Double> rangeClosedBy(double from, double toInclusive, double step) { return HashSet.ofAll(Iterator.rangeClosedBy(from, toInclusive, step)); } /** * Creates a HashSet of long numbers starting from {@code from}, extending to {@code toInclusive}. * <p> * Examples: * <pre> * <code> * HashSet.rangeClosed(0L, 0L) // = HashSet(0L) * HashSet.rangeClosed(2L, 0L) // = HashSet() * HashSet.rangeClosed(-2L, 2L) // = HashSet(-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} */ public static HashSet<Long> rangeClosed(long from, long toInclusive) { return HashSet.ofAll(Iterator.rangeClosed(from, toInclusive)); } /** * Creates a HashSet of long numbers starting from {@code from}, extending to {@code toInclusive}, * with {@code step}. * <p> * Examples: * <pre> * <code> * HashSet.rangeClosedBy(1L, 3L, 1L) // = HashSet(1L, 2L, 3L) * HashSet.rangeClosedBy(1L, 4L, 2L) // = HashSet(1L, 3L) * HashSet.rangeClosedBy(4L, 1L, -2L) // = HashSet(4L, 2L) * HashSet.rangeClosedBy(4L, 1L, 2L) // = HashSet() * </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 */ public static HashSet<Long> rangeClosedBy(long from, long toInclusive, long step) { return HashSet.ofAll(Iterator.rangeClosedBy(from, toInclusive, step)); } @Override public HashSet<T> add(T element) { return new HashSet<>(tree.put(element, element)); } @Override public HashSet<T> addAll(java.lang.Iterable<? extends T> elements) { Objects.requireNonNull(elements, "elements is null"); final HashArrayMappedTrie<T, T> that = addAll(tree, elements); if (that.size() == tree.size()) { return this; } else { return new HashSet<>(that); } } @Override public HashSet<T> clear() { return empty(); } @Override public boolean contains(T element) { return tree.get(element).isDefined(); } @Override public HashSet<T> diff(Set<? extends T> elements) { Objects.requireNonNull(elements, "elements is null"); if (isEmpty() || elements.isEmpty()) { return this; } else { return removeAll(elements); } } @Override public HashSet<T> distinct() { return this; } @Override public HashSet<T> distinctBy(Comparator<? super T> comparator) { Objects.requireNonNull(comparator, "comparator is null"); return HashSet.ofAll(iterator().distinctBy(comparator)); } @Override public <U> HashSet<T> distinctBy(Function<? super T, ? extends U> keyExtractor) { Objects.requireNonNull(keyExtractor, "keyExtractor is null"); return HashSet.ofAll(iterator().distinctBy(keyExtractor)); } @Override public HashSet<T> drop(int n) { if (n <= 0) { return this; } else { return HashSet.ofAll(iterator().drop(n)); } } @Override public HashSet<T> dropRight(int n) { return drop(n); } @Override public HashSet<T> dropWhile(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); final HashSet<T> dropped = HashSet.ofAll(iterator().dropWhile(predicate)); return dropped.length() == length() ? this : dropped; } @Override public HashSet<T> filter(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); final HashSet<T> filtered = HashSet.ofAll(iterator().filter(predicate)); return filtered.length() == length() ? this : filtered; } @Override public <U> HashSet<U> flatMap(Function<? super T, ? extends java.lang.Iterable<? extends U>> mapper) { Objects.requireNonNull(mapper, "mapper is null"); if (isEmpty()) { return empty(); } else { final HashArrayMappedTrie<U, U> that = foldLeft(HashArrayMappedTrie.empty(), (tree, t) -> addAll(tree, mapper.apply(t))); return new HashSet<>(that); } } @SuppressWarnings("unchecked") @Override public <U> HashSet<U> flatten() { try { return ((HashSet<? extends Iterable<U>>) this).flatMap(Function.identity()); } catch(ClassCastException x) { throw new UnsupportedOperationException("flatten of non-iterable elements"); } } @Override public <U> U foldRight(U zero, BiFunction<? super T, ? super U, ? extends U> f) { return foldLeft(zero, (u, t) -> f.apply(t, u)); } @Override public <C> Map<C, HashSet<T>> groupBy(Function<? super T, ? extends C> classifier) { return foldLeft(HashMap.empty(), (map, t) -> { final C key = classifier.apply(t); final HashSet<T> values = map.get(key).map(ts -> ts.add(t)).orElse(HashSet.of(t)); return map.put(key, values); }); } @Override public boolean hasDefiniteSize() { return true; } @Override public T head() { if (tree.isEmpty()) { throw new NoSuchElementException("head of empty set"); } return iterator().next(); } @Override public Option<T> headOption() { return iterator().headOption(); } @Override public HashSet<T> init() { return tail(); } @Override public Option<HashSet<T>> initOption() { return tailOption(); } @Override public HashSet<T> intersect(Set<? extends T> elements) { Objects.requireNonNull(elements, "elements is null"); if (isEmpty() || elements.isEmpty()) { return empty(); } else { return retainAll(elements); } } @Override public boolean isEmpty() { return tree.isEmpty(); } @Override public boolean isTraversableAgain() { return true; } @Override public Iterator<T> iterator() { return tree.iterator().map(t -> t._1); } @Override public int length() { return tree.size(); } @Override public <U> HashSet<U> map(Function<? super T, ? extends U> mapper) { Objects.requireNonNull(mapper, "mapper is null"); if (isEmpty()) { return empty(); } else { final HashArrayMappedTrie<U, U> that = foldLeft(HashArrayMappedTrie.empty(), (tree, t) -> { final U u = mapper.apply(t); return tree.put(u, u); }); return new HashSet<>(that); } } @Override public String mkString(CharSequence prefix, CharSequence delimiter, CharSequence suffix) { return iterator().mkString(prefix, delimiter, suffix); } @Override public Tuple2<HashSet<T>, HashSet<T>> partition(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); final Tuple2<Iterator<T>, Iterator<T>> p = iterator().partition(predicate); return Tuple.of(HashSet.ofAll(p._1), HashSet.ofAll(p._2)); } @Override public HashSet<T> peek(Consumer<? super T> action) { Objects.requireNonNull(action, "action is null"); if (!isEmpty()) { action.accept(iterator().head()); } return this; } @Override public HashSet<T> remove(T element) { final HashArrayMappedTrie<T, T> newTree = tree.remove(element); return (newTree == tree) ? this : new HashSet<>(newTree); } @Override public HashSet<T> removeAll(java.lang.Iterable<? extends T> elements) { Objects.requireNonNull(elements, "elements is null"); HashArrayMappedTrie<T, T> trie = tree; for (T element : elements) { trie = trie.remove(element); } return (trie == tree) ? this : new HashSet<>(trie); } @Override public HashSet<T> replace(T currentElement, T newElement) { if (tree.containsKey(currentElement)) { return remove(currentElement).add(newElement); } else { return this; } } @Override public HashSet<T> replaceAll(T currentElement, T newElement) { return replace(currentElement, newElement); } @Override public HashSet<T> retainAll(java.lang.Iterable<? extends T> elements) { Objects.requireNonNull(elements, "elements is null"); final HashArrayMappedTrie<T, T> kept = addAll(HashArrayMappedTrie.empty(), elements); HashArrayMappedTrie<T, T> that = HashArrayMappedTrie.empty(); for (T element : this) { if (kept.containsKey(element)) { that = that.put(element, element); } } return new HashSet<>(that); } @Override public Tuple2<HashSet<T>, HashSet<T>> span(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); final Tuple2<Iterator<T>, Iterator<T>> t = iterator().span(predicate); return Tuple.of(HashSet.ofAll(t._1), HashSet.ofAll(t._2)); } @Override public HashSet<T> tail() { if (tree.isEmpty()) { throw new UnsupportedOperationException("tail of empty set"); } return remove(head()); } @Override public Option<HashSet<T>> tailOption() { if (tree.isEmpty()) { return None.instance(); } else { return new Some<>(tail()); } } @Override public HashSet<T> take(int n) { if (tree.size() <= n) { return this; } return HashSet.ofAll(() -> iterator().take(n)); } @Override public HashSet<T> takeRight(int n) { return take(n); } @Override public HashSet<T> takeUntil(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); return takeWhile(predicate.negate()); } @Override public HashSet<T> takeWhile(Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); HashSet<T> taken = HashSet.ofAll(iterator().takeWhile(predicate)); return taken.length() == length() ? this : taken; } @SuppressWarnings("unchecked") @Override public HashSet<T> union(Set<? extends T> elements) { Objects.requireNonNull(elements, "elements is null"); if (isEmpty()) { if (elements instanceof HashSet) { return (HashSet<T>) elements; } else { return HashSet.ofAll(elements); } } else if (elements.isEmpty()) { return this; } else { final HashArrayMappedTrie<T, T> that = addAll(tree, elements); if (that.size() == tree.size()) { return this; } else { return new HashSet<>(that); } } } @Override public <T1, T2> Tuple2<HashSet<T1>, HashSet<T2>> unzip( Function<? super T, Tuple2<? extends T1, ? extends T2>> unzipper) { Objects.requireNonNull(unzipper, "unzipper is null"); Tuple2<Iterator<T1>, Iterator<T2>> t = iterator().unzip(unzipper); return Tuple.of(HashSet.ofAll(t._1), HashSet.ofAll(t._2)); } @Override public <T1, T2, T3> Tuple3<HashSet<T1>, HashSet<T2>, HashSet<T3>> unzip3( Function<? super T, Tuple3<? extends T1, ? extends T2, ? extends T3>> unzipper) { Objects.requireNonNull(unzipper, "unzipper is null"); Tuple3<Iterator<T1>, Iterator<T2>, Iterator<T3>> t = iterator().unzip3(unzipper); return Tuple.of(HashSet.ofAll(t._1), HashSet.ofAll(t._2), HashSet.ofAll(t._3)); } @Override public <U> HashSet<Tuple2<T, U>> zip(java.lang.Iterable<U> that) { Objects.requireNonNull(that, "that is null"); return HashSet.ofAll(iterator().zip(that)); } @Override public <U> HashSet<Tuple2<T, U>> zipAll(java.lang.Iterable<U> that, T thisElem, U thatElem) { Objects.requireNonNull(that, "that is null"); return HashSet.ofAll(iterator().zipAll(that, thisElem, thatElem)); } @Override public HashSet<Tuple2<T, Integer>> zipWithIndex() { return HashSet.ofAll(iterator().zipWithIndex()); } // -- Object @Override public int hashCode() { return hash.get(); } @SuppressWarnings("unchecked") @Override public boolean equals(Object o) { if (o == this) { return true; } else if (o instanceof HashSet) { final HashSet<?> that = (HashSet<?>) o; return this.length() == that.length() && ((HashSet<Object>) this).containsAll(that); } else { return false; } } @Override public String toString() { return mkString(", ", "HashSet(", ")"); } private static <T> HashArrayMappedTrie<T, T> addAll(HashArrayMappedTrie<T, T> initial, Iterable<? extends T> additional) { HashArrayMappedTrie<T, T> that = initial; for (T t : additional) { that = that.put(t, t); } return that; } // -- Serialization /** * {@code writeReplace} method for the serialization proxy pattern. * <p> * The presence of this method causes the serialization system to emit a SerializationProxy instance instead of * an instance of the enclosing class. * * @return A SerialiationProxy for this enclosing class. */ private Object writeReplace() { return new SerializationProxy<>(this.tree); } /** * {@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 HashArrayMappedTrie<T, T> tree; /** * Constructor for the case of serialization, called by {@link HashSet#writeReplace()}. * <p/> * The constructor of a SerializationProxy takes an argument that concisely represents the logical state of * an instance of the enclosing class. * * @param tree a Cons */ SerializationProxy(HashArrayMappedTrie<T, T> tree) { this.tree = tree; } /** * 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(tree.size()); for (Tuple2<T, T> e : tree) { s.writeObject(e._1); } } /** * 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"); } HashArrayMappedTrie<T, T> temp = HashArrayMappedTrie.empty(); for (int i = 0; i < size; i++) { @SuppressWarnings("unchecked") final T element = (T) s.readObject(); temp = temp.put(element, element); } tree = temp; } /** * {@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 tree.isEmpty() ? HashSet.empty() : new HashSet<>(tree); } } }
1
6,689
Oh, thanks for catching - I thought I've catched all after changing `mkString(infix, prefix, suffix)` to `mkString(prefix, infix, suffix)`.
vavr-io-vavr
java
@@ -33,6 +33,14 @@ const ( // Issued indicates that a CertificateRequest has been completed, and that // the `status.certificate` field is set. CertificateRequestReasonIssued = "Issued" + + // Approved indicates that a CertificateRequest has been approved by the + // approver, and the CertificateRequest is ready for signing. + CertificateRequestReasonApproved = "Approved" + + // Denied indicates that a CertificateRequest has been denied by the + // approver, and the CertificateRequest will be never be signed. + CertificateRequestReasonDenied = "Denied" ) // +genclient
1
/* Copyright 2020 The cert-manager 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 v1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" cmmeta "github.com/jetstack/cert-manager/pkg/apis/meta/v1" ) const ( // Pending indicates that a CertificateRequest is still in progress. CertificateRequestReasonPending = "Pending" // Failed indicates that a CertificateRequest has failed, either due to // timing out or some other critical failure. CertificateRequestReasonFailed = "Failed" // Issued indicates that a CertificateRequest has been completed, and that // the `status.certificate` field is set. CertificateRequestReasonIssued = "Issued" ) // +genclient // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // +kubebuilder:storageversion // A CertificateRequest is used to request a signed certificate from one of the // configured issuers. // // All fields within the CertificateRequest's `spec` are immutable after creation. // A CertificateRequest will either succeed or fail, as denoted by its `status.state` // field. // // A CertificateRequest is a one-shot resource, meaning it represents a single // point in time request for a certificate and cannot be re-used. // +k8s:openapi-gen=true type CertificateRequest struct { metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` // Desired state of the CertificateRequest resource. Spec CertificateRequestSpec `json:"spec"` // Status of the CertificateRequest. This is set and managed automatically. // +optional Status CertificateRequestStatus `json:"status"` } // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // CertificateRequestList is a list of Certificates type CertificateRequestList struct { metav1.TypeMeta `json:",inline"` metav1.ListMeta `json:"metadata"` Items []CertificateRequest `json:"items"` } // CertificateRequestSpec defines the desired state of CertificateRequest type CertificateRequestSpec struct { // The requested 'duration' (i.e. lifetime) of the Certificate. // This option may be ignored/overridden by some issuer types. // +optional Duration *metav1.Duration `json:"duration,omitempty"` // IssuerRef is a reference to the issuer for this CertificateRequest. If // the `kind` field is not set, or set to `Issuer`, an Issuer resource with // the given name in the same namespace as the CertificateRequest will be // used. If the `kind` field is set to `ClusterIssuer`, a ClusterIssuer with // the provided name will be used. The `name` field in this stanza is // required at all times. The group field refers to the API group of the // issuer which defaults to `cert-manager.io` if empty. IssuerRef cmmeta.ObjectReference `json:"issuerRef"` // The PEM-encoded x509 certificate signing request to be submitted to the // CA for signing. Request []byte `json:"request"` // IsCA will request to mark the certificate as valid for certificate signing // when submitting to the issuer. // This will automatically add the `cert sign` usage to the list of `usages`. // +optional IsCA bool `json:"isCA,omitempty"` // Usages is the set of x509 usages that are requested for the certificate. // If usages are set they SHOULD be encoded inside the CSR spec // Defaults to `digital signature` and `key encipherment` if not specified. // +optional Usages []KeyUsage `json:"usages,omitempty"` // Username contains the name of the user that created the CertificateRequest. // Populated by the cert-manager webhook on creation and immutable. // +optional Username string `json:"username,omitempty"` // UID contains the uid of the user that created the CertificateRequest. // Populated by the cert-manager webhook on creation and immutable. // +optional UID string `json:"uid,omitempty"` // Groups contains group membership of the user that created the CertificateRequest. // Populated by the cert-manager webhook on creation and immutable. // +listType=atomic // +optional Groups []string `json:"groups,omitempty"` // Extra contains extra attributes of the user that created the CertificateRequest. // Populated by the cert-manager webhook on creation and immutable. // +optional Extra map[string][]string `json:"extra,omitempty"` } // CertificateRequestStatus defines the observed state of CertificateRequest and // resulting signed certificate. type CertificateRequestStatus struct { // List of status conditions to indicate the status of a CertificateRequest. // Known condition types are `Ready` and `InvalidRequest`. // +optional Conditions []CertificateRequestCondition `json:"conditions,omitempty"` // The PEM encoded x509 certificate resulting from the certificate // signing request. // If not set, the CertificateRequest has either not been completed or has // failed. More information on failure can be found by checking the // `conditions` field. // +optional Certificate []byte `json:"certificate,omitempty"` // The PEM encoded x509 certificate of the signer, also known as the CA // (Certificate Authority). // This is set on a best-effort basis by different issuers. // If not set, the CA is assumed to be unknown/not available. // +optional CA []byte `json:"ca,omitempty"` // FailureTime stores the time that this CertificateRequest failed. This is // used to influence garbage collection and back-off. // +optional FailureTime *metav1.Time `json:"failureTime,omitempty"` } // CertificateRequestCondition contains condition information for a CertificateRequest. type CertificateRequestCondition struct { // Type of the condition, known values are (`Ready`, `InvalidRequest`). Type CertificateRequestConditionType `json:"type"` // Status of the condition, one of (`True`, `False`, `Unknown`). Status cmmeta.ConditionStatus `json:"status"` // LastTransitionTime is the timestamp corresponding to the last status // change of this condition. // +optional LastTransitionTime *metav1.Time `json:"lastTransitionTime,omitempty"` // Reason is a brief machine readable explanation for the condition's last // transition. // +optional Reason string `json:"reason,omitempty"` // Message is a human readable description of the details of the last // transition, complementing reason. // +optional Message string `json:"message,omitempty"` } // CertificateRequestConditionType represents an Certificate condition value. type CertificateRequestConditionType string const ( // CertificateRequestConditionReady indicates that a certificate is ready for use. // This is defined as: // - The target certificate exists in CertificateRequest.Status CertificateRequestConditionReady CertificateRequestConditionType = "Ready" // CertificateRequestConditionInvalidRequest indicates that a certificate // signer has refused to sign the request due to at least one of the input // parameters being invalid. Additional information about why the request // was rejected can be found in the `reason` and `message` fields. CertificateRequestConditionInvalidRequest CertificateRequestConditionType = "InvalidRequest" )
1
25,467
Suggestion: `.. the CertificateRequest is ready for signing` - could we perhaps word this differently? I understand that in this case it will be the associated X.509 certificate that can now be signed, so maybe `the certificate is ready for signing` ? (Same with `CertificateRequestReasonDenied`).
jetstack-cert-manager
go
@@ -54,6 +54,10 @@ export default function PropertySelect() { } }, [ propertyID, selectProperty ] ); + if ( ! accountID ) { + return null; + } + if ( isLoading ) { return <ProgressBar small />; }
1
/** * GA4 Property Select component. * * Site Kit by Google, Copyright 2021 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 { useCallback } from '@wordpress/element'; import { __, sprintf } from '@wordpress/i18n'; /** * Internal dependencies */ import Data from 'googlesitekit-data'; import { Select, Option } from '../../../../material-components'; import ProgressBar from '../../../../components/ProgressBar'; import { STORE_NAME, PROPERTY_CREATE } from '../../datastore/constants'; import { MODULES_ANALYTICS } from '../../../analytics/datastore/constants'; import { isValidAccountID } from '../../../analytics/util'; import { trackEvent } from '../../../../util'; const { useSelect, useDispatch } = Data; export default function PropertySelect() { // TODO: Update this select hook to pull accountID from the modules/analytics-4 datastore when GA4 module becomes separated from the Analytics one const accountID = useSelect( ( select ) => select( MODULES_ANALYTICS ).getAccountID() ); const properties = useSelect( ( select ) => select( STORE_NAME ).getProperties( accountID ) || [] ); const propertyID = useSelect( ( select ) => select( STORE_NAME ).getPropertyID() ); const isLoading = useSelect( ( select ) => ( ! select( MODULES_ANALYTICS ).hasFinishedResolution( 'getAccounts' ) || ! select( STORE_NAME ).hasFinishedResolution( 'getProperties', [ accountID ] ) ) ); const { selectProperty } = useDispatch( STORE_NAME ); const onChange = useCallback( ( index, item ) => { const newPropertyID = item.dataset.value; if ( propertyID !== newPropertyID ) { selectProperty( newPropertyID ); trackEvent( 'analytics_setup', 'property_change', newPropertyID ); } }, [ propertyID, selectProperty ] ); if ( isLoading ) { return <ProgressBar small />; } return ( <Select className="googlesitekit-analytics__select-property" label={ __( 'Property', 'google-site-kit' ) } value={ propertyID } onEnhancedChange={ onChange } disabled={ ! isValidAccountID( accountID ) } enhanced outlined > { ( properties || [] ) .concat( { _id: PROPERTY_CREATE, displayName: __( 'Set up a new property', 'google-site-kit' ), } ) .map( ( { _id, displayName }, index ) => ( <Option key={ index } value={ _id } > { _id === PROPERTY_CREATE ? displayName : sprintf( /* translators: 1: Property name. 2: Property ID. */ __( '%1$s (%2$s)', 'google-site-kit' ), displayName, _id ) } </Option> ) ) } </Select> ); }
1
38,334
We should use `! isValidAccountID( accountID )` for the `accountID` checks.
google-site-kit-wp
js
@@ -6,7 +6,9 @@ require 'bolt/error' module Bolt class Target attr_reader :uri, :options - attr_writer :inventory + # CODEREVIEW: this feels wrong. The altertative is threading inventory through the + # executor to the RemoteTransport + attr_accessor :inventory PRINT_OPTS ||= %w[host user port protocol].freeze
1
# frozen_string_literal: true require 'addressable/uri' require 'bolt/error' module Bolt class Target attr_reader :uri, :options attr_writer :inventory PRINT_OPTS ||= %w[host user port protocol].freeze # Satisfies the Puppet datatypes API def self.from_asserted_hash(hash) new(hash['uri'], hash['options']) end def initialize(uri, options = nil) @uri = uri @uri_obj = parse(uri) @options = options || {} @options.freeze if @options['user'] @user = @options['user'] end if @options['password'] @password = @options['password'] end if @options['port'] @port = @options['port'] end if @options['protocol'] @protocol = @options['protocol'] end end def update_conf(conf) @protocol = conf[:transport] t_conf = conf[:transports][protocol.to_sym] # Override url methods @user = t_conf['user'] @password = t_conf['password'] @port = t_conf['port'] # Preserve everything in options so we can easily create copies of a Target. @options = t_conf.merge(@options) self end def parse(string) if string =~ %r{^[^:]+://} Addressable::URI.parse(string) else # Initialize with an empty scheme to ensure we parse the hostname correctly Addressable::URI.parse("//#{string}") end end private :parse def features if @inventory @inventory.features(self) else Set.new end end def eql?(other) self.class.equal?(other.class) && @uri == other.uri end alias == eql? def hash @uri.hash ^ @options.hash end def to_s opts = @options.select { |k, _| PRINT_OPTS.include? k } "Target('#{@uri}', #{opts})" end def host @uri_obj.hostname end # name is currently just uri but should be used instead to identify the # Target ouside the transport or uri options. def name uri end def port @uri_obj.port || @port end def protocol @uri_obj.scheme || @protocol end def user Addressable::URI.unencode_component(@uri_obj.user) || @user end def password Addressable::URI.unencode_component(@uri_obj.password) || @password end end end
1
10,096
That alternative does seem better. Did you want to try to do it in this PR? It makes sense to me that the inventory would always be available before creating the executor.
puppetlabs-bolt
rb
@@ -545,8 +545,12 @@ module Beaker on host, "apt-get install -y hiera=#{opts[:hiera_version]}-1puppetlabs1" end - puppet_pkg = opts[:version] ? "puppet=#{opts[:version]}-1puppetlabs1" : 'puppet' - on host, "apt-get install -y #{puppet_pkg}" + if opts[:version] + on host, "apt-get install -y puppet-common=#{opts[:version]}-1puppetlabs1" + on host, "apt-get install -y puppet=#{opts[:version]}-1puppetlabs1" + else + on host, 'apt-get install -y puppet' + end end # Installs Puppet and dependencies from msi
1
require 'pathname' module Beaker module DSL # # This module contains methods to help cloning, extracting git info, # ordering of Puppet packages, and installing ruby projects that # contain an `install.rb` script. # # To mix this is into a class you need the following: # * a method *hosts* that yields any hosts implementing # {Beaker::Host}'s interface to act upon. # * a method *options* that provides an options hash, see {Beaker::Options::OptionsHash} # * the module {Beaker::DSL::Roles} that provides access to the various hosts implementing # {Beaker::Host}'s interface to act upon # * the module {Beaker::DSL::Wrappers} the provides convenience methods for {Beaker::DSL::Command} creation module InstallUtils # The default install path SourcePath = "/opt/puppet-git-repos" # A regex to know if the uri passed is pointing to a git repo GitURI = %r{^(git|https?|file)://|^git@|^gitmirror@} # Github's ssh signature for cloning via ssh GitHubSig = 'github.com,207.97.227.239 ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAq2A7hRGmdnm9tUDbO9IDSwBK6TbQa+PXYPCPy6rbTrTtw7PHkccKrpp0yVhp5HdEIcKr6pLlVDBfOLX9QUsyCOV0wzfjIJNlGEYsdlLJizHhbn2mUjvSAHQqZETYP81eFzLQNnPHt4EVVUh7VfDESU84KezmD5QlWpXLmvU31/yMf+Se8xhHTvKSCZIFImWwoG6mbUoWf9nzpIoaSjB+weqqUUmpaaasXVal72J+UX2B+2RPW3RcT0eOzQgqlJL3RKrTJvdsjE3JEAvGq3lGHSZXy28G3skua2SmVi/w4yCE6gbODqnTWlg7+wC604ydGXA8VJiS5ap43JXiUFFAaQ==' # @param [String] uri A uri in the format of <git uri>#<revision> # the `git://`, `http://`, `https://`, and ssh # (if cloning as the remote git user) protocols # are valid for <git uri> # # @example Usage # project = extract_repo_info_from '[email protected]:puppetlabs/SuperSecretSauce#what_is_justin_doing' # # puts project[:name] # #=> 'SuperSecretSauce' # # puts project[:rev] # #=> 'what_is_justin_doing' # # @return [Hash{Symbol=>String}] Returns a hash containing the project # name, repository path, and revision # (defaults to HEAD) # # @api dsl def extract_repo_info_from uri project = {} repo, rev = uri.split('#', 2) project[:name] = Pathname.new(repo).basename('.git').to_s project[:path] = repo project[:rev] = rev || 'HEAD' return project end # Takes an array of package info hashes (like that returned from # {#extract_repo_info_from}) and sorts the `puppet`, `facter`, `hiera` # packages so that puppet's dependencies will be installed first. # # @!visibility private def order_packages packages_array puppet = packages_array.select {|e| e[:name] == 'puppet' } puppet_depends_on = packages_array.select do |e| e[:name] == 'hiera' or e[:name] == 'facter' end depends_on_puppet = (packages_array - puppet) - puppet_depends_on [puppet_depends_on, puppet, depends_on_puppet].flatten end # @param [Host] host An object implementing {Beaker::Hosts}'s # interface. # @param [String] path The path on the remote [host] to the repository # @param [Hash{Symbol=>String}] repository A hash representing repo # info like that emitted by # {#extract_repo_info_from} # # @example Getting multiple project versions # versions = [puppet_repo, facter_repo, hiera_repo].inject({}) do |vers, repo_info| # vers.merge(find_git_repo_versions(host, '/opt/git-puppet-repos', repo_info) ) # end # @return [Hash] Executes git describe on [host] and returns a Hash # with the key of [repository[:name]] and value of # the output from git describe. # # @note This requires the helper methods: # * {Beaker::DSL::Structure#step} # * {Beaker::DSL::Helpers#on} # # @api dsl def find_git_repo_versions host, path, repository version = {} step "Grab version for #{repository[:name]}" do on host, "cd #{path}/#{repository[:name]} && " + "git describe || true" do version[repository[:name]] = stdout.chomp end end version end # # @see #find_git_repo_versions def install_from_git host, path, repository name = repository[:name] repo = repository[:path] rev = repository[:rev] target = "#{path}/#{name}" step "Clone #{repo} if needed" do on host, "test -d #{path} || mkdir -p #{path}" on host, "test -d #{target} || git clone #{repo} #{target}" end step "Update #{name} and check out revision #{rev}" do commands = ["cd #{target}", "remote rm origin", "remote add origin #{repo}", "fetch origin", "clean -fdx", "checkout -f #{rev}"] on host, commands.join(" && git ") end step "Install #{name} on the system" do # The solaris ruby IPS package has bindir set to /usr/ruby/1.8/bin. # However, this is not the path to which we want to deliver our # binaries. So if we are using solaris, we have to pass the bin and # sbin directories to the install.rb install_opts = '' install_opts = '--bindir=/usr/bin --sbindir=/usr/sbin' if host['platform'].include? 'solaris' on host, "cd #{target} && " + "if [ -f install.rb ]; then " + "ruby ./install.rb #{install_opts}; " + "else true; fi" end end #Create the PE install command string based upon the host and options settings # @param [Host] host The host that PE is to be installed on # For UNIX machines using the full PE installer, the host object must have the 'pe_installer' field set correctly. # @param [Hash{Symbol=>String}] opts The options # @option opts [String] :pe_ver_win Default PE version to install or upgrade to on Windows hosts # (Othersie uses individual Windows hosts pe_ver) # @option opts [String :pe_ver Default PE version to install or upgrade to # (Otherwise uses individual hosts pe_ver) # @example # on host, "#{installer_cmd(host, opts)} -a #{host['working_dir']}/answers" # @api private def installer_cmd(host, opts) version = host['pe_ver'] || opts[:pe_ver] if host['platform'] =~ /windows/ version = opts[:pe_ver_win] || host['pe_ver'] "cd #{host['working_dir']} && cmd /C 'start /w msiexec.exe /qn /i puppet-enterprise-#{version}.msi PUPPET_MASTER_SERVER=#{master} PUPPET_AGENT_CERTNAME=#{host}'" elsif host['platform'] =~ /osx/ version = host['pe_ver'] || opts[:pe_ver] "cd #{host['working_dir']} && hdiutil attach #{host['dist']}.dmg && installer -pkg /Volumes/puppet-enterprise-#{version}/puppet-enterprise-installer-#{version}.pkg -target /" # Frictionless install didn't exist pre-3.2.0, so in that case we fall # through and do a regular install. elsif host['roles'].include? 'frictionless' and ! version_is_less(version, '3.2.0') "cd #{host['working_dir']} && curl -kO https://#{master}:8140/packages/#{version}/install.bash && bash install.bash" else "cd #{host['working_dir']}/#{host['dist']} && ./#{host['pe_installer']} -a #{host['working_dir']}/answers" end end #Determine is a given URL is accessible #@param [String] link The URL to examine #@return [Boolean] true if the URL has a '200' HTTP response code, false otherwise #@example # extension = link_exists?("#{URL}.tar.gz") ? ".tar.gz" : ".tar" # @api private def link_exists?(link) require "net/http" require "net/https" require "open-uri" url = URI.parse(link) http = Net::HTTP.new(url.host, url.port) http.use_ssl = (url.scheme == 'https') http.start do |http| return http.head(url.request_uri).code == "200" end end #Determine the PE package to download/upload on a mac host, download/upload that package onto the host. # Assumed file name format: puppet-enterprise-3.3.0-rc1-559-g97f0833-osx-10.9-x86_64.dmg. # @param [Host] host The mac host to download/upload and unpack PE onto # @param [Hash{Symbol=>Symbol, String}] opts The options # @option opts [String] :pe_dir Default directory or URL to pull PE package from # (Otherwise uses individual hosts pe_dir) # @api private def fetch_puppet_on_mac(host, opts) path = host['pe_dir'] || opts[:pe_dir] local = File.directory?(path) filename = "#{host['dist']}" extension = ".dmg" if local if not File.exists?("#{path}/#{filename}#{extension}") raise "attempting installation on #{host}, #{path}/#{filename}#{extension} does not exist" end scp_to host, "#{path}/#{filename}#{extension}", "#{host['working_dir']}/#{filename}#{extension}" else if not link_exists?("#{path}/#{filename}#{extension}") raise "attempting installation on #{host}, #{path}/#{filename}#{extension} does not exist" end on host, "cd #{host['working_dir']}; curl -O #{path}/#{filename}#{extension}" end end #Determine the PE package to download/upload on a windows host, download/upload that package onto the host. #Assumed file name format: puppet-enterprise-3.3.0-rc1-559-g97f0833.msi # @param [Host] host The windows host to download/upload and unpack PE onto # @param [Hash{Symbol=>Symbol, String}] opts The options # @option opts [String] :pe_dir Default directory or URL to pull PE package from # (Otherwise uses individual hosts pe_dir) # @option opts [String] :pe_ver_win Default PE version to install or upgrade to # (Otherwise uses individual hosts pe_ver) # @api private def fetch_puppet_on_windows(host, opts) path = host['pe_dir'] || opts[:pe_dir] local = File.directory?(path) version = host['pe_ver'] || opts[:pe_ver_win] filename = "puppet-enterprise-#{version}" extension = ".msi" if local if not File.exists?("#{path}/#{filename}#{extension}") raise "attempting installation on #{host}, #{path}/#{filename}#{extension} does not exist" end scp_to host, "#{path}/#{filename}#{extension}", "#{host['working_dir']}/#{filename}#{extension}" else if not link_exists?("#{path}/#{filename}#{extension}") raise "attempting installation on #{host}, #{path}/#{filename}#{extension} does not exist" end on host, "cd #{host['working_dir']}; curl -O #{path}/#{filename}#{extension}" end end #Determine the PE package to download/upload on a unix style host, download/upload that package onto the host #and unpack it. # @param [Host] host The unix style host to download/upload and unpack PE onto # @param [Hash{Symbol=>Symbol, String}] opts The options # @option opts [String] :pe_dir Default directory or URL to pull PE package from # (Otherwise uses individual hosts pe_dir) # @api private def fetch_puppet_on_unix(host, opts) path = host['pe_dir'] || opts[:pe_dir] local = File.directory?(path) filename = "#{host['dist']}" if local extension = File.exists?("#{path}/#{filename}.tar.gz") ? ".tar.gz" : ".tar" if not File.exists?("#{path}/#{filename}#{extension}") raise "attempting installation on #{host}, #{path}/#{filename}#{extension} does not exist" end scp_to host, "#{path}/#{filename}#{extension}", "#{host['working_dir']}/#{filename}#{extension}" if extension =~ /gz/ on host, "cd #{host['working_dir']}; gunzip #{filename}#{extension}" end if extension =~ /tar/ on host, "cd #{host['working_dir']}; tar -xvf #{filename}.tar" end else extension = link_exists?("#{path}/#{filename}.tar.gz") ? ".tar.gz" : ".tar" if not link_exists?("#{path}/#{filename}#{extension}") raise "attempting installation on #{host}, #{path}/#{filename}#{extension} does not exist" end unpack = 'tar -xvf -' unpack = extension =~ /gz/ ? 'gunzip | ' + unpack : unpack on host, "cd #{host['working_dir']}; curl #{path}/#{filename}#{extension} | #{unpack}" end end #Determine the PE package to download/upload per-host, download/upload that package onto the host #and unpack it. # @param [Array<Host>] hosts The hosts to download/upload and unpack PE onto # @param [Hash{Symbol=>Symbol, String}] opts The options # @option opts [String] :pe_dir Default directory or URL to pull PE package from # (Otherwise uses individual hosts pe_dir) # @option opts [String] :pe_ver Default PE version to install or upgrade to # (Otherwise uses individual hosts pe_ver) # @option opts [String] :pe_ver_win Default PE version to install or upgrade to on Windows hosts # (Otherwise uses individual Windows hosts pe_ver) # @api private def fetch_puppet(hosts, opts) hosts.each do |host| # We install Puppet from the master for frictionless installs, so we don't need to *fetch* anything next if host['roles'].include? 'frictionless' and ! version_is_less(opts[:pe_ver] || host['pe_ver'], '3.2.0') if host['platform'] =~ /windows/ fetch_puppet_on_windows(host, opts) elsif host['platform'] =~ /osx/ fetch_puppet_on_mac(host, opts) else fetch_puppet_on_unix(host, opts) end end end #Classify the master so that it can deploy frictionless packages for a given host. # @param [Host] host The host to install pacakges for # @api private def deploy_frictionless_to_master(host) klass = host['platform'].gsub(/-/, '_').gsub(/\./,'') klass = "pe_repo::platform::#{klass}" on dashboard, "cd /opt/puppet/share/puppet-dashboard && /opt/puppet/bin/bundle exec /opt/puppet/bin/rake nodeclass:add[#{klass},skip]" on dashboard, "cd /opt/puppet/share/puppet-dashboard && /opt/puppet/bin/bundle exec /opt/puppet/bin/rake node:addclass[#{master},#{klass}]" on master, "puppet agent -t", :acceptable_exit_codes => [0,2] end #Perform a Puppet Enterprise upgrade or install # @param [Array<Host>] hosts The hosts to install or upgrade PE on # @param [Hash{Symbol=>Symbol, String}] opts The options # @option opts [String] :pe_dir Default directory or URL to pull PE package from # (Otherwise uses individual hosts pe_dir) # @option opts [String] :pe_ver Default PE version to install or upgrade to # (Otherwise uses individual hosts pe_ver) # @option opts [String] :pe_ver_win Default PE version to install or upgrade to on Windows hosts # (Otherwise uses individual Windows hosts pe_ver) # @option opts [Symbol] :type (:install) One of :upgrade or :install # @option opts [Hash<String>] :answers Pre-set answers based upon ENV vars and defaults # (See {Beaker::Options::Presets.env_vars}) # # @example # do_install(hosts, {:type => :upgrade, :pe_dir => path, :pe_ver => version, :pe_ver_win => version_win}) # # @api private # def do_install hosts, opts = {} opts[:type] = opts[:type] || :install hostcert='uname | grep -i sunos > /dev/null && hostname || hostname -s' master_certname = on(master, hostcert).stdout.strip pre30database = version_is_less(opts[:pe_ver] || database['pe_ver'], '3.0') pre30master = version_is_less(opts[:pe_ver] || master['pe_ver'], '3.0') # Set PE distribution for all the hosts, create working dir use_all_tar = ENV['PE_USE_ALL_TAR'] == 'true' hosts.each do |host| host['pe_installer'] ||= 'puppet-enterprise-installer' if host['platform'] !~ /windows|osx/ platform = use_all_tar ? 'all' : host['platform'] version = host['pe_ver'] || opts[:pe_ver] host['dist'] = "puppet-enterprise-#{version}-#{platform}" elsif host['platform'] =~ /osx/ version = host['pe_ver'] || opts[:pe_ver] host['dist'] = "puppet-enterprise-#{version}-#{host['platform']}" end host['working_dir'] = "/tmp/" + Time.new.strftime("%Y-%m-%d_%H.%M.%S") #unique working dirs make me happy on host, "mkdir #{host['working_dir']}" end fetch_puppet(hosts, opts) # If we're installing a database version less than 3.0, ignore the database host install_hosts = hosts.dup install_hosts.delete(database) if pre30database and database != master and database != dashboard install_hosts.each do |host| if host['platform'] =~ /windows/ on host, installer_cmd(host, opts) elsif host['platform'] =~ /osx/ on host, installer_cmd(host, opts) #set the certname and master on host, puppet("config set server #{master}") on host, puppet("config set certname #{host}") #run once to request cert on host, puppet_agent('-t'), :acceptable_exit_codes => [1] else # We only need answers if we're using the classic installer version = host['pe_ver'] || opts[:pe_ver] if (! host['roles'].include? 'frictionless') || version_is_less(version, '3.2.0') answers = Beaker::Answers.answers(opts[:pe_ver] || host['pe_ver'], hosts, master_certname, opts) create_remote_file host, "#{host['working_dir']}/answers", Beaker::Answers.answer_string(host, answers) else # If We're *not* running the classic installer, we want # to make sure the master has packages for us. deploy_frictionless_to_master(host) end on host, installer_cmd(host, opts) end # On each agent, we ensure the certificate is signed then shut down the agent sign_certificate_for(host) stop_agent_on(host) end # Wait for PuppetDB to be totally up and running (post 3.0 version of pe only) sleep_until_puppetdb_started(database) unless pre30database # Run the agent once to ensure everything is in the dashboard install_hosts.each do |host| on host, puppet_agent('-t'), :acceptable_exit_codes => [0,2] # Workaround for PE-1105 when deploying 3.0.0 # The installer did not respect our database host answers in 3.0.0, # and would cause puppetdb to be bounced by the agent run. By sleeping # again here, we ensure that if that bounce happens during an upgrade # test we won't fail early in the install process. if host['pe_ver'] == '3.0.0' and host == database sleep_until_puppetdb_started(database) end end install_hosts.each do |host| wait_for_host_in_dashboard(host) end if pre30master task = 'nodegroup:add_all_nodes group=default' else task = 'defaultgroup:ensure_default_group' end on dashboard, "/opt/puppet/bin/rake -sf /opt/puppet/share/puppet-dashboard/Rakefile #{task} RAILS_ENV=production" # Now that all hosts are in the dashbaord, run puppet one more # time to configure mcollective on install_hosts, puppet_agent('-t'), :acceptable_exit_codes => [0,2] end #Sort array of hosts so that it has the correct order for PE installation based upon each host's role # @example # h = sorted_hosts # # @note Order for installation should be # First : master # Second: database host (if not same as master) # Third: dashboard (if not same as master or database) # Fourth: everything else # # @!visibility private def sorted_hosts special_nodes = [master, database, dashboard].uniq real_agents = agents - special_nodes special_nodes + real_agents end #Install FOSS based upon host configuration and options # @example will install puppet 3.6.1 from native puppetlabs provided packages wherever possible and will fail over to gem installation when impossible # install_puppet({ # :version => '3.6.1', # :facter_version => '2.0.1', # :hiera_version => '1.3.3', # :default_action => 'gem_install' # # @example Will install latest packages on Enterprise Linux and Debian based distros and fail hard on all othere platforms. # install_puppet() # # @note This will attempt to add a repository for apt.puppetlabs.com on # Debian or Ubuntu machines, or yum.puppetlabs.com on EL or Fedora # machines, then install the package 'puppet'. # # @api dsl # @return nil # @raise [StandardError] When encountering an unsupported platform by default, or if gem cannot be found when default_action => 'gem_install' # @raise [FailTest] When error occurs during the actual installation process def install_puppet(opts = {}) hosts.each do |host| if host['platform'] =~ /el-(5|6|7)/ relver = $1 install_puppet_from_rpm host, opts.merge(:release => relver, :family => 'el') elsif host['platform'] =~ /fedora-(\d+)/ relver = $1 install_puppet_from_rpm host, opts.merge(:release => relver, :family => 'fedora') elsif host['platform'] =~ /(ubuntu|debian)/ install_puppet_from_deb host, opts elsif host['platform'] =~ /windows/ relver = opts[:version] install_puppet_from_msi host, opts elsif host['platform'] =~ /osx/ install_puppet_from_dmg host, opts else if opts[:default_action] == 'gem_install' install_puppet_from_gem host, opts else raise "install_puppet() called for unsupported platform '#{host['platform']}' on '#{host.name}'" end end end nil end # Installs Puppet and dependencies using rpm # # @param [Host] host The host to install packages on # @param [Hash{Symbol=>String}] opts An options hash # @option opts [String] :version The version of Puppet to install, if nil installs latest version # @option opts [String] :facter_version The version of Facter to install, if nil installs latest version # @option opts [String] :hiera_version The version of Hiera to install, if nil installs latest version # @option opts [String] :default_action What to do if we don't know how to install native packages on host. # Valid value is 'gem_install' or nil. If nil raises an exception when # on an unsupported platform. When 'gem_install' attempts to install # Puppet via gem. # @option opts [String] :release The major release of the OS # @option opts [String] :family The OS family (one of 'el' or 'fedora') # # @return nil # @api private def install_puppet_from_rpm( host, opts ) release_package_string = "http://yum.puppetlabs.com/puppetlabs-release-#{opts[:family]}-#{opts[:release]}.noarch.rpm" on host, "rpm -ivh #{release_package_string}" if opts[:facter_version] on host, "yum install -y facter-#{opts[:facter_version]}" end if opts[:hiera_version] on host, "yum install -y hiera-#{opts[:hiera_version]}" end puppet_pkg = opts[:version] ? "puppet-#{opts[:version]}" : 'puppet' on host, "yum install -y #{puppet_pkg}" end # Installs Puppet and dependencies from deb # # @param [Host] host The host to install packages on # @param [Hash{Symbol=>String}] opts An options hash # @option opts [String] :version The version of Puppet to install, if nil installs latest version # @option opts [String] :facter_version The version of Facter to install, if nil installs latest version # @option opts [String] :hiera_version The version of Hiera to install, if nil installs latest version # # @return nil # @api private def install_puppet_from_deb( host, opts ) if ! host.check_for_package 'lsb-release' host.install_package('lsb-release') end if ! host.check_for_package 'curl' on host, 'apt-get install -y curl' end on host, 'curl -O http://apt.puppetlabs.com/puppetlabs-release-$(lsb_release -c -s).deb' on host, 'dpkg -i puppetlabs-release-$(lsb_release -c -s).deb' on host, 'apt-get update' if opts[:facter_version] on host, "apt-get install -y facter=#{opts[:facter_version]}-1puppetlabs1" end if opts[:hiera_version] on host, "apt-get install -y hiera=#{opts[:hiera_version]}-1puppetlabs1" end puppet_pkg = opts[:version] ? "puppet=#{opts[:version]}-1puppetlabs1" : 'puppet' on host, "apt-get install -y #{puppet_pkg}" end # Installs Puppet and dependencies from msi # # @param [Host] host The host to install packages on # @param [Hash{Symbol=>String}] opts An options hash # @option opts [String] :version The version of Puppet to install, required # # @return nil # @api private def install_puppet_from_msi( host, opts ) on host, "curl -O http://downloads.puppetlabs.com/windows/puppet-#{opts[:version]}.msi" on host, "msiexec /qn /i puppet-#{relver}.msi" #Because the msi installer doesn't add Puppet to the environment path if fact_on(host, 'architecture').eql?('x86_64') install_dir = '/cygdrive/c/Program Files (x86)/Puppet Labs/Puppet/bin' else install_dir = '/cygdrive/c/Program Files/Puppet Labs/Puppet/bin' end on host, %Q{ echo 'export PATH=$PATH:"#{install_dir}"' > /etc/bash.bashrc } end # Installs Puppet and dependencies from dmg # # @param [Host] host The host to install packages on # @param [Hash{Symbol=>String}] opts An options hash # @option opts [String] :version The version of Puppet to install, required # @option opts [String] :facter_version The version of Facter to install, required # @option opts [String] :hiera_version The version of Hiera to install, required # # @return nil # @api private def install_puppet_from_dmg( host, opts ) puppet_ver = opts[:version] facter_ver = opts[:facter_version] hiera_ver = opts[:hiera_version] on host, "curl -O http://downloads.puppetlabs.com/mac/puppet-#{puppet_ver}.dmg" on host, "curl -O http://downloads.puppetlabs.com/mac/facter-#{facter_ver}.dmg" on host, "curl -O http://downloads.puppetlabs.com/mac/hiera-#{hiera_ver}.dmg" on host, "hdiutil attach puppet-#{puppet_ver}.dmg" on host, "hdiutil attach facter-#{facter_ver}.dmg" on host, "hdiutil attach hiera-#{hiera_ver}.dmg" on host, "installer -pkg /Volumes/puppet-#{puppet_ver}/puppet-#{puppet_ver}.pkg -target /" on host, "installer -pkg /Volumes/facter-#{facter_ver}/facter-#{facter_ver}.pkg -target /" on host, "installer -pkg /Volumes/hiera-#{hiera_ver}/hiera-#{hiera_ver}.pkg -target /" end # Installs Puppet and dependencies from gem # # @param [Host] host The host to install packages on # @param [Hash{Symbol=>String}] opts An options hash # @option opts [String] :version The version of Puppet to install, if nil installs latest # @option opts [String] :facter_version The version of Facter to install, if nil installs latest # @option opts [String] :hiera_version The version of Hiera to install, if nil installs latest # # @return nil # @raise [StandardError] if gem does not exist on target host # @api private def install_puppet_from_gem( host, opts ) if host.check_for_package( 'gem' ) if opts[:facter_version] on host, "gem install facter -v#{opts[:facter_version]}" end if opts[:hiera_version] on host, "gem install hiera -v#{opts[:hiera_version]}" end ver_cmd = opts[:version] ? "-v#{opts[:version]}" : '' on host, "gem install puppet #{ver_cmd}" else raise "install_puppet() called with default_action 'gem_install' but program `gem' not installed on #{host.name}" end end #Install PE based upon host configuration and options # @example # install_pe # # @note Either pe_ver and pe_dir should be set in the ENV or each host should have pe_ver and pe_dir set individually. # Install file names are assumed to be of the format puppet-enterprise-VERSION-PLATFORM.(tar)|(tar.gz) # for Unix like systems and puppet-enterprise-VERSION.msi for Windows systems. # # @api dsl def install_pe #process the version files if necessary hosts.each do |host| host['pe_dir'] ||= options[:pe_dir] if host['platform'] =~ /windows/ host['pe_ver'] = host['pe_ver'] || options['pe_ver'] || Beaker::Options::PEVersionScraper.load_pe_version(host[:pe_dir] || options[:pe_dir], options[:pe_version_file_win]) else host['pe_ver'] = host['pe_ver'] || options['pe_ver'] || Beaker::Options::PEVersionScraper.load_pe_version(host[:pe_dir] || options[:pe_dir], options[:pe_version_file]) end end #send in the global options hash do_install sorted_hosts, options end #Upgrade PE based upon host configuration and options # @param [String] path A path (either local directory or a URL to a listing of PE builds). # Will contain a LATEST file indicating the latest build to install. # This is ignored if a pe_upgrade_ver and pe_upgrade_dir are specified # in the host configuration file. # @example # upgrade_pe("http://neptune.puppetlabs.lan/3.0/ci-ready/") # # @note Install file names are assumed to be of the format puppet-enterprise-VERSION-PLATFORM.(tar)|(tar.gz) # for Unix like systems and puppet-enterprise-VERSION.msi for Windows systems. # @api dsl def upgrade_pe path=nil hosts.each do |host| host['pe_dir'] = host['pe_upgrade_dir'] || path if host['platform'] =~ /windows/ host['pe_ver'] = host['pe_upgrade_ver'] || options['pe_upgrade_ver'] || Options::PEVersionScraper.load_pe_version(host['pe_dir'], options[:pe_version_file_win]) else host['pe_ver'] = host['pe_upgrade_ver'] || options['pe_upgrade_ver'] || Options::PEVersionScraper.load_pe_version(host['pe_dir'], options[:pe_version_file]) end if version_is_less(host['pe_ver'], '3.0') host['pe_installer'] ||= 'puppet-enterprise-upgrader' end end #send in the global options hash do_install(sorted_hosts, options.merge({:type => :upgrade})) options['upgrade'] = true end end end end
1
6,383
Missing the `-y` argument which all other `apt-get install` commands have.
voxpupuli-beaker
rb
@@ -1295,7 +1295,8 @@ bool CoreChecks::ValidatePipelineUnlocked(const PIPELINE_STATE *pPipeline, uint3 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).", + "Invalid Pipeline CreateInfo[%" PRIu32 + "] 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; }
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 != 0 && vertex_buffer_stride < attribute_binding_extent) { skip |= LogError(pCB->commandBuffer(), "VUID-vkCmdBindVertexBuffers2EXT-pStrides-06209", "The pStrides[%u] (%u) parameter in the last call to vkCmdBindVertexBuffers2EXT is not 0 " "and 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); } } } auto color_write = lvl_find_in_chain<VkPipelineColorWriteCreateInfoEXT>(pPipeline->graphicsPipelineCI.pColorBlendState->pNext); if (color_write) { if (color_write->attachmentCount != color_blend_state->attachmentCount) { skip |= LogError( device, "VUID-VkPipelineColorWriteCreateInfoEXT-attachmentCount-04802", "vkCreateGraphicsPipelines(): VkPipelineColorWriteCreateInfoEXT in the pNext chain of pPipelines[%" PRIu32 "].pColorBlendState has different attachmentCount (%" PRIu32 ") than pColorBlendState.attachmentCount (%" PRIu32 ").", pipelineIndex, color_write->attachmentCount, color_blend_state->attachmentCount); } if (!enabled_features.color_write_features.colorWriteEnable) { for (uint32_t i = 0; i < color_write->attachmentCount; ++i) { if (color_write->pColorWriteEnables[i] != VK_TRUE) { skip |= LogError(device, "VUID-VkPipelineColorWriteCreateInfoEXT-pAttachments-04801", "vkCreateGraphicsPipelines(): pPipelines[%" PRIu32 "].pColorBlendState pNext chain includes VkPipelineColorWriteCreateInfoEXT with " "pColorWriteEnables[%" PRIu32 "] = VK_FALSE, but colorWriteEnable is not enabled.", pipelineIndex, i); } } } } } 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); } } const auto *discard_rectangle_state = LvlFindInChain<VkPipelineDiscardRectangleStateCreateInfoEXT>(pPipeline->graphicsPipelineCI.pNext); if (discard_rectangle_state) { if (discard_rectangle_state->discardRectangleCount > phys_dev_ext_props.discard_rectangle_props.maxDiscardRectangles) { skip |= LogError( device, "VUID-VkPipelineDiscardRectangleStateCreateInfoEXT-discardRectangleCount-00582", "vkCreateGraphicsPipelines(): VkPipelineDiscardRectangleStateCreateInfoEXT::discardRectangleCount (%" PRIu32 ") in pNext chain of pCreateInfo[%" PRIu32 "] is not less than VkPhysicalDeviceDiscardRectanglePropertiesEXT::maxDiscardRectangles (%" PRIu32 ".", discard_rectangle_state->discardRectangleCount, pipelineIndex, phys_dev_ext_props.discard_rectangle_props.maxDiscardRectangles); } } // 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 *shader_atomic_float_feature2 = LvlFindInChain<VkPhysicalDeviceShaderAtomicFloat2FeaturesEXT>(pCreateInfo->pNext); if (shader_atomic_float_feature2) { if (shader_atomic_float_feature2->sparseImageFloat32AtomicMinMax && !shader_atomic_float_feature2->shaderImageFloat32AtomicMinMax) { skip |= LogError( pd_state->phys_device, "VUID-VkDeviceCreateInfo-sparseImageFloat32AtomicMinMax-04975", "vkCreateDevice: if sparseImageFloat32AtomicMinMax feature is enabled then shaderImageFloat32AtomicMinMax " "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"); } if (chained_device_group_struct->signalSemaphoreCount != submit->signalSemaphoreCount) { skip |= LogError(queue, "VUID-VkDeviceGroupSubmitInfo-signalSemaphoreCount-00084", "pSubmits[%" PRIu32 "] signalSemaphoreCount (%" PRIu32 ") is different than signalSemaphoreCount (%" PRIu32 ") of the VkDeviceGroupSubmitInfo in its pNext chain", submit_idx, submit->signalSemaphoreCount, chained_device_group_struct->signalSemaphoreCount); } if (chained_device_group_struct->waitSemaphoreCount != submit->waitSemaphoreCount) { skip |= LogError(queue, "VUID-VkDeviceGroupSubmitInfo-waitSemaphoreCount-00082", "pSubmits[%" PRIu32 "] waitSemaphoreCount (%" PRIu32 ") is different than waitSemaphoreCount (%" PRIu32 ") of the VkDeviceGroupSubmitInfo in its pNext chain", submit_idx, submit->waitSemaphoreCount, chained_device_group_struct->waitSemaphoreCount); } if (chained_device_group_struct->commandBufferCount != submit->commandBufferCount) { skip |= LogError(queue, "VUID-VkDeviceGroupSubmitInfo-commandBufferCount-00083", "pSubmits[%" PRIu32 "] commandBufferCount (%" PRIu32 ") is different than commandBufferCount (%" PRIu32 ") of the VkDeviceGroupSubmitInfo in its pNext chain", submit_idx, submit->commandBufferCount, chained_device_group_struct->commandBufferCount); } } 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, "VUID-VkDeviceQueueInfo2-flags-06225", "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)); } } } } if (pipeline_state->getPipelineCreateFlags() & VK_PIPELINE_CREATE_LIBRARY_BIT_KHR) { skip |= LogError( pipeline, "VUID-vkCmdBindPipeline-pipeline-03382", "vkCmdBindPipeline(): Cannot bind a pipeline that was created with the VK_PIPELINE_CREATE_LIBRARY_BIT_KHR flag."); } } 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); for (uint32_t i = 0; i < bufferMemoryBarrierCount; ++i) { if (pBufferMemoryBarriers[i].srcQueueFamilyIndex != pBufferMemoryBarriers[i].dstQueueFamilyIndex) { skip |= LogError(commandBuffer, "VUID-vkCmdWaitEvents-srcQueueFamilyIndex-02803", "vkCmdWaitEvents(): pBufferMemoryBarriers[%" PRIu32 "] has different srcQueueFamilyIndex (%" PRIu32 ") and dstQueueFamilyIndex (%" PRIu32 ").", i, pBufferMemoryBarriers[i].srcQueueFamilyIndex, pBufferMemoryBarriers[i].dstQueueFamilyIndex); } } for (uint32_t i = 0; i < imageMemoryBarrierCount; ++i) { if (pImageMemoryBarriers[i].srcQueueFamilyIndex != pImageMemoryBarriers[i].dstQueueFamilyIndex) { skip |= LogError(commandBuffer, "VUID-vkCmdWaitEvents-srcQueueFamilyIndex-02803", "vkCmdWaitEvents(): pImageMemoryBarriers[%" PRIu32 "] has different srcQueueFamilyIndex (%" PRIu32 ") and dstQueueFamilyIndex (%" PRIu32 ").", i, pImageMemoryBarriers[i].srcQueueFamilyIndex, pImageMemoryBarriers[i].dstQueueFamilyIndex); } } 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: case VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_OPTIMAL: case VK_IMAGE_LAYOUT_STENCIL_READ_ONLY_OPTIMAL: 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_READ_ONLY_OPTIMAL, " "VK_IMAGE_LAYOUT_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; const VkDeviceGroupRenderPassBeginInfo *device_group_render_pass_begin_info = LvlFindInChain<VkDeviceGroupRenderPassBeginInfo>(pRenderPassBegin->pNext); if (device_extensions.vk_khr_device_group) { device_group = true; if (device_group_render_pass_begin_info) { device_group_area_count = device_group_render_pass_begin_info->deviceRenderAreaCount; } } const safe_VkFramebufferCreateInfo *framebuffer_info = &GetFramebufferState(pRenderPassBegin->framebuffer)->createInfo; if (device_group && device_group_area_count > 0) { for (uint32_t i = 0; i < device_group_render_pass_begin_info->deviceRenderAreaCount; ++i) { const auto &deviceRenderArea = device_group_render_pass_begin_info->pDeviceRenderAreas[i]; if (deviceRenderArea.offset.x < 0) { skip |= LogError(pRenderPassBegin->renderPass, "VUID-VkRenderPassBeginInfo-pNext-02854", "%s: Cannot execute a render pass with renderArea not within the bound of the framebuffer, " "VkDeviceGroupRenderPassBeginInfo::pDeviceRenderAreas[%" PRIu32 "].offset.x is negative (%" PRIi32 ").", func_name, i, deviceRenderArea.offset.x); } if (deviceRenderArea.offset.y < 0) { skip |= LogError(pRenderPassBegin->renderPass, "VUID-VkRenderPassBeginInfo-pNext-02855", "%s: Cannot execute a render pass with renderArea not within the bound of the framebuffer, " "VkDeviceGroupRenderPassBeginInfo::pDeviceRenderAreas[%" PRIu32 "].offset.y is negative (%" PRIi32 ").", func_name, i, deviceRenderArea.offset.y); } if ((deviceRenderArea.offset.x + deviceRenderArea.extent.width) > framebuffer_info->width) { skip |= LogError(pRenderPassBegin->renderPass, "VUID-VkRenderPassBeginInfo-pNext-02856", "%s: Cannot execute a render pass with renderArea not within the bound of the framebuffer, " "VkDeviceGroupRenderPassBeginInfo::pDeviceRenderAreas[%" PRIu32 "] offset.x (%" PRIi32 ") + extent.width (%" PRIi32 ") is greater than framebuffer width (%" PRIi32 ").", func_name, i, deviceRenderArea.offset.x, deviceRenderArea.extent.width, framebuffer_info->width); } if ((deviceRenderArea.offset.y + deviceRenderArea.extent.height) > framebuffer_info->height) { skip |= LogError(pRenderPassBegin->renderPass, "VUID-VkRenderPassBeginInfo-pNext-02857", "%s: Cannot execute a render pass with renderArea not within the bound of the framebuffer, " "VkDeviceGroupRenderPassBeginInfo::pDeviceRenderAreas[%" PRIu32 "] offset.y (%" PRIi32 ") + extent.height (%" PRIi32 ") is greater than framebuffer height (%" PRIi32 ").", func_name, i, deviceRenderArea.offset.y, deviceRenderArea.extent.height, framebuffer_info->height); } } } else { 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) && pRenderPassBegin->pClearValues) { 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)); } } } const auto *display_present_info = LvlFindInChain<VkDisplayPresentInfoKHR>(pPresentInfo->pNext); if (display_present_info) { if (display_present_info->srcRect.offset.x < 0 || display_present_info->srcRect.offset.y < 0 || display_present_info->srcRect.offset.x + display_present_info->srcRect.extent.width > image_state->createInfo.extent.width || display_present_info->srcRect.offset.y + display_present_info->srcRect.extent.height > image_state->createInfo.extent.height) { skip |= LogError(queue, "VUID-VkDisplayPresentInfoKHR-srcRect-01257", "vkQueuePresentKHR(): VkDisplayPresentInfoKHR::srcRect (offset (%" PRIu32 ", %" PRIu32 "), extent (%" PRIu32 ", %" PRIu32 ")) in the pNext chain of VkPresentInfoKHR is not a subset of the image begin presented " "(extent (%" PRIu32 ", %" PRIu32 ")).", display_present_info->srcRect.offset.x, display_present_info->srcRect.offset.y, display_present_info->srcRect.extent.width, display_present_info->srcRect.extent.height, image_state->createInfo.extent.width, image_state->createInfo.extent.height); } } } // 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); } } const auto *present_id_info = LvlFindInChain<VkPresentIdKHR>(pPresentInfo->pNext); if (present_id_info) { if (!enabled_features.present_id_features.presentId) { skip |= LogError(pPresentInfo->pSwapchains[0], kVUID_Features_PresentIdKHR, "vkQueuePresentKHR(): VkPresentIdKHR structure in VkPresentInfoKHR structure, but presentId feature is not enabled"); } if (pPresentInfo->swapchainCount != present_id_info->swapchainCount) { skip |= LogError(pPresentInfo->pSwapchains[0], "VUID-VkPresentIdKHR-swapchainCount-04998", "vkQueuePresentKHR(): VkPresentIdKHR.swapchainCount is %" PRIu32 " but pPresentInfo->swapchainCount is %" PRIu32 ". VkPresentIdKHR.swapchainCount must be the same value as VkPresentInfoKHR::swapchainCount", present_id_info->swapchainCount, pPresentInfo->swapchainCount); } for (uint32_t i = 0; i < present_id_info->swapchainCount; i++) { const auto swapchain_state = GetSwapchainState(pPresentInfo->pSwapchains[i]); if ((present_id_info->pPresentIds[i] != 0) && (present_id_info->pPresentIds[i] <= swapchain_state->max_present_id)) { skip |= LogError(pPresentInfo->pSwapchains[i], "VUID-VkPresentIdKHR-presentIds-04999", "vkQueuePresentKHR(): VkPresentIdKHR.pPresentId[%" PRIu32 "] is %" PRIu64 " and the largest presentId sent for this swapchain is %" PRIu64 ". Each presentIds entry must be greater than any previous presentIds entry passed for the " "associated pSwapchains entry", i, present_id_info->pPresentIds[i], swapchain_state->max_present_id); } } } } 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) { const char *vuid = cmd_version == CMD_VERSION_2 ? "VUID-VkAcquireNextImageInfoKHR-semaphore-01288" : "VUID-vkAcquireNextImageKHR-semaphore-01286"; skip |= LogError(semaphore, vuid, "%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) { const char *vuid = cmd_version == CMD_VERSION_2 ? "VUID-VkAcquireNextImageInfoKHR-swapchain-01675" : "VUID-vkAcquireNextImageKHR-swapchain-01285"; skip |= LogError(swapchain, vuid, "%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::PreCallValidateWaitForPresentKHR(VkDevice device, VkSwapchainKHR swapchain, uint64_t presentId, uint64_t timeout) const { bool skip = false; if (!enabled_features.present_wait_features.presentWait) { skip |= LogError(swapchain, kVUID_Features_PresentWaitKHR, "vkWaitForPresentKHR(): VkWaitForPresent called but presentWait feature is not enabled"); } const auto swapchain_state = GetSwapchainState(swapchain); if (swapchain_state) { if (swapchain_state->retired) { skip |= LogError(swapchain, "VUID-vkWaitForPresentKHR-swapchain-04997", "vkWaitForPresentKHR() called with a retired swapchain."); } } 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()); } } } for (uint32_t i = 0; i < pCreateInfo->descriptorUpdateEntryCount; ++i) { const auto &descriptor_update = pCreateInfo->pDescriptorUpdateEntries[i]; if (descriptor_update.descriptorType == VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT) { if (descriptor_update.dstArrayElement & 3) { skip |= LogError(pCreateInfo->pipelineLayout, "VUID-VkDescriptorUpdateTemplateEntry-descriptor-02226", "%s: pCreateInfo->pDescriptorUpdateEntries[%" PRIu32 "] has descriptorType VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT, but dstArrayElement (%" PRIu32 ") is not a " "multiple of 4).", func_name, i, descriptor_update.dstArrayElement); } if (descriptor_update.descriptorCount & 3) { skip |= LogError(pCreateInfo->pipelineLayout, "VUID-VkDescriptorUpdateTemplateEntry-descriptor-02227", "%s: pCreateInfo->pDescriptorUpdateEntries[%" PRIu32 "] has descriptorType VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT, but descriptorCount (%" PRIu32 ")is not a " "multiple of 4).", func_name, i, descriptor_update.descriptorCount); } } } 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; bool skip = false; skip |= ValidateCmdEndQuery(cb_state, query_obj, index, CMD_ENDQUERYINDEXEDEXT, "vkCmdEndQueryIndexedEXT()", &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-vkCmdEndQueryIndexedEXT-queryType-02346", "vkCmdEndQueryIndexedEXT(): index %" PRIu32 " must be less than VkPhysicalDeviceTransformFeedbackPropertiesEXT::maxTransformFeedbackStreams %" PRIu32 ".", index, phys_dev_ext_props.transform_feedback_props.maxTransformFeedbackStreams); } } else if (index != 0) { skip |= LogError(cb_state->commandBuffer(), "VUID-vkCmdEndQueryIndexedEXT-queryType-02347", "vkCmdEndQueryIndexedEXT(): index %" PRIu32 " must be zero if %s was not created with type VK_QUERY_TYPE_TRANSFORM_FEEDBACK_STREAM_EXT.", index, report_data->FormatHandle(queryPool).c_str()); } return skip; } 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"); for (uint32_t i = 0; i < discardRectangleCount; ++i) { if (pDiscardRectangles[i].offset.x < 0) { skip |= LogError(cb_state->commandBuffer(), "VUID-vkCmdSetDiscardRectangleEXT-x-00587", "vkCmdSetDiscardRectangleEXT(): pDiscardRectangles[%" PRIu32 "].x (%" PRIi32 ") is negative.", i, pDiscardRectangles[i].offset.x); } if (pDiscardRectangles[i].offset.y < 0) { skip |= LogError(cb_state->commandBuffer(), "VUID-vkCmdSetDiscardRectangleEXT-x-00587", "vkCmdSetDiscardRectangleEXT(): pDiscardRectangles[%" PRIu32 "].y (%" PRIi32 ") is negative.", i, pDiscardRectangles[i].offset.y); } } 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-pAccelerationStructures-06215", "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
19,009
So I think we are going to settle on the "concise and elegant" `PRI` macros as they are the safest option for now. Even though they make my eyes bleed a little...
KhronosGroup-Vulkan-ValidationLayers
cpp
@@ -112,7 +112,7 @@ func (r *Replacer) ReplaceFunc(input string, f ReplacementFunc) (string, error) func (r *Replacer) replace(input, empty string, treatUnknownAsEmpty, errOnEmpty, errOnUnknown bool, f ReplacementFunc) (string, error) { - if !strings.Contains(input, string(phOpen)) { + if !strings.Contains(input, string(phOpen)) && !strings.Contains(input, string(phClose)) { return input, nil }
1
// Copyright 2015 Matthew Holt and The Caddy 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 caddy import ( "fmt" "os" "path/filepath" "runtime" "strings" "time" ) // NewReplacer returns a new Replacer. func NewReplacer() *Replacer { rep := &Replacer{ static: make(map[string]string), } rep.providers = []ReplacerFunc{ globalDefaultReplacements, rep.fromStatic, } return rep } // Replacer can replace values in strings. // A default/empty Replacer is not valid; // use NewReplacer to make one. type Replacer struct { providers []ReplacerFunc static map[string]string } // Map adds mapFunc to the list of value providers. // mapFunc will be executed only at replace-time. func (r *Replacer) Map(mapFunc ReplacerFunc) { r.providers = append(r.providers, mapFunc) } // Set sets a custom variable to a static value. func (r *Replacer) Set(variable, value string) { r.static[variable] = value } // Get gets a value from the replacer. It returns // the value and whether the variable was known. func (r *Replacer) Get(variable string) (string, bool) { for _, mapFunc := range r.providers { if val, ok := mapFunc(variable); ok { return val, true } } return "", false } // Delete removes a variable with a static value // that was created using Set. func (r *Replacer) Delete(variable string) { delete(r.static, variable) } // fromStatic provides values from r.static. func (r *Replacer) fromStatic(key string) (val string, ok bool) { val, ok = r.static[key] return } // ReplaceOrErr is like ReplaceAll, but any placeholders // that are empty or not recognized will cause an error to // be returned. func (r *Replacer) ReplaceOrErr(input string, errOnEmpty, errOnUnknown bool) (string, error) { return r.replace(input, "", false, errOnEmpty, errOnUnknown, nil) } // ReplaceKnown is like ReplaceAll but only replaces // placeholders that are known (recognized). Unrecognized // placeholders will remain in the output. func (r *Replacer) ReplaceKnown(input, empty string) string { out, _ := r.replace(input, empty, false, false, false, nil) return out } // ReplaceAll efficiently replaces placeholders in input with // their values. All placeholders are replaced in the output // whether they are recognized or not. Values that are empty // string will be substituted with empty. func (r *Replacer) ReplaceAll(input, empty string) string { out, _ := r.replace(input, empty, true, false, false, nil) return out } // ReplaceFunc calls ReplaceAll efficiently replaces placeholders in input with // their values. All placeholders are replaced in the output // whether they are recognized or not. Values that are empty // string will be substituted with empty. func (r *Replacer) ReplaceFunc(input string, f ReplacementFunc) (string, error) { return r.replace(input, "", true, false, false, f) } func (r *Replacer) replace(input, empty string, treatUnknownAsEmpty, errOnEmpty, errOnUnknown bool, f ReplacementFunc) (string, error) { if !strings.Contains(input, string(phOpen)) { return input, nil } var sb strings.Builder // it is reasonable to assume that the output // will be approximately as long as the input sb.Grow(len(input)) // iterate the input to find each placeholder var lastWriteCursor int for i := 0; i < len(input); i++ { if input[i] != phOpen { continue } // find the end of the placeholder end := strings.Index(input[i:], string(phClose)) + i if end < i { continue } // write the substring from the last cursor to this point sb.WriteString(input[lastWriteCursor:i]) // trim opening bracket key := input[i+1 : end] // try to get a value for this key, handle empty values accordingly val, found := r.Get(key) if !found { // placeholder is unknown (unrecognized); handle accordingly if errOnUnknown { return "", fmt.Errorf("unrecognized placeholder %s%s%s", string(phOpen), key, string(phClose)) } else if !treatUnknownAsEmpty { // if treatUnknownAsEmpty is true, we'll // handle an empty val later; so only // continue otherwise lastWriteCursor = i continue } } // apply any transformations if f != nil { var err error val, err = f(key, val) if err != nil { return "", err } } // write the value; if it's empty, either return // an error or write a default value if val == "" { if errOnEmpty { return "", fmt.Errorf("evaluated placeholder %s%s%s is empty", string(phOpen), key, string(phClose)) } else if empty != "" { sb.WriteString(empty) } } else { sb.WriteString(val) } // advance cursor to end of placeholder i = end lastWriteCursor = i + 1 } // flush any unwritten remainder sb.WriteString(input[lastWriteCursor:]) return sb.String(), nil } // ReplacerFunc is a function that returns a replacement // for the given key along with true if the function is able // to service that key (even if the value is blank). If the // function does not recognize the key, false should be // returned. type ReplacerFunc func(key string) (val string, ok bool) func globalDefaultReplacements(key string) (string, bool) { // check environment variable const envPrefix = "env." if strings.HasPrefix(key, envPrefix) { return os.Getenv(key[len(envPrefix):]), true } switch key { case "system.hostname": // OK if there is an error; just return empty string name, _ := os.Hostname() return name, true case "system.slash": return string(filepath.Separator), true case "system.os": return runtime.GOOS, true case "system.arch": return runtime.GOARCH, true case "time.now.common_log": return nowFunc().Format("02/Jan/2006:15:04:05 -0700"), true } return "", false } // ReplacementFunc is a function that is called when a // replacement is being performed. It receives the // variable (i.e. placeholder name) and the value that // will be the replacement, and returns the value that // will actually be the replacement, or an error. Note // that errors are sometimes ignored by replacers. type ReplacementFunc func(variable, val string) (string, error) // nowFunc is a variable so tests can change it // in order to obtain a deterministic time. var nowFunc = time.Now // ReplacerCtxKey is the context key for a replacer. const ReplacerCtxKey CtxKey = "replacer" const phOpen, phClose = '{', '}'
1
14,291
Interesting, was this needed for a test case to pass? I figured if there is no opening brace, there is definitely no placeholder -- we don't even have to check for a closing one.
caddyserver-caddy
go
@@ -122,8 +122,10 @@ ChainLoop: return []explorer.Transfer{}, err } - for i := len(blk.Transfers) - 1; i >= 0; i-- { - if showCoinBase || !blk.Transfers[i].IsCoinbase() { + transfers, _, _ := action.ClassifyActions(blk.Actions) + + for i := len(transfers) - 1; i >= 0; i-- { + if showCoinBase || !transfers[i].IsCoinbase() { transferCount++ }
1
// Copyright (c) 2018 IoTeX // This is an alpha (internal) release and is not suitable for production. This source code is provided 'as is' and no // warranties are given as to title or non-infringement, merchantability or fitness for purpose and, to the extent // permitted by law, all liability for your use of the code is disclaimed. This source code is governed by Apache // License 2.0 that can be found in the LICENSE file. package explorer import ( "encoding/hex" "math/big" "github.com/pkg/errors" "github.com/prometheus/client_golang/prometheus" "github.com/iotexproject/iotex-core/action" "github.com/iotexproject/iotex-core/actpool" "github.com/iotexproject/iotex-core/blockchain" "github.com/iotexproject/iotex-core/config" "github.com/iotexproject/iotex-core/consensus" "github.com/iotexproject/iotex-core/dispatcher" "github.com/iotexproject/iotex-core/explorer/idl/explorer" "github.com/iotexproject/iotex-core/indexservice" "github.com/iotexproject/iotex-core/logger" "github.com/iotexproject/iotex-core/network" "github.com/iotexproject/iotex-core/pkg/hash" "github.com/iotexproject/iotex-core/pkg/keypair" pb "github.com/iotexproject/iotex-core/proto" ) var ( // ErrInternalServer indicates the internal server error ErrInternalServer = errors.New("internal server error") // ErrTransfer indicates the error of transfer ErrTransfer = errors.New("invalid transfer") // ErrVote indicates the error of vote ErrVote = errors.New("invalid vote") // ErrExecution indicates the error of execution ErrExecution = errors.New("invalid execution") // ErrReceipt indicates the error of receipt ErrReceipt = errors.New("invalid receipt") ) var ( requestMtc = prometheus.NewCounterVec( prometheus.CounterOpts{ Name: "iotex_explorer_request", Help: "IoTeX Explorer request counter.", }, []string{"method", "succeed"}, ) ) func init() { prometheus.MustRegister(requestMtc) } // Service provide api for user to query blockchain data type Service struct { bc blockchain.Blockchain c consensus.Consensus dp dispatcher.Dispatcher ap actpool.ActPool p2p network.Overlay cfg config.Explorer idx *indexservice.Server } // GetBlockchainHeight returns the current blockchain tip height func (exp *Service) GetBlockchainHeight() (int64, error) { tip := exp.bc.TipHeight() return int64(tip), nil } // GetAddressBalance returns the balance of an address func (exp *Service) GetAddressBalance(address string) (string, error) { state, err := exp.bc.StateByAddr(address) if err != nil { return "", err } return state.Balance.String(), nil } // GetAddressDetails returns the properties of an address func (exp *Service) GetAddressDetails(address string) (explorer.AddressDetails, error) { state, err := exp.bc.StateByAddr(address) if err != nil { return explorer.AddressDetails{}, err } pendingNonce, err := exp.ap.GetPendingNonce(address) if err != nil { return explorer.AddressDetails{}, err } details := explorer.AddressDetails{ Address: address, TotalBalance: state.Balance.String(), Nonce: int64((*state).Nonce), PendingNonce: int64(pendingNonce), IsCandidate: (*state).IsCandidate, } return details, nil } // GetLastTransfersByRange returns transfers in [-(offset+limit-1), -offset] from block // with height startBlockHeight func (exp *Service) GetLastTransfersByRange(startBlockHeight int64, offset int64, limit int64, showCoinBase bool) ([]explorer.Transfer, error) { var res []explorer.Transfer transferCount := int64(0) ChainLoop: for height := startBlockHeight; height >= 0; height-- { var blkID string hash, err := exp.bc.GetHashByHeight(uint64(height)) if err != nil { return []explorer.Transfer{}, err } blkID = hex.EncodeToString(hash[:]) blk, err := exp.bc.GetBlockByHeight(uint64(height)) if err != nil { return []explorer.Transfer{}, err } for i := len(blk.Transfers) - 1; i >= 0; i-- { if showCoinBase || !blk.Transfers[i].IsCoinbase() { transferCount++ } if transferCount <= offset { continue } // if showCoinBase is true, add coinbase transfers, else only put non-coinbase transfers if showCoinBase || !blk.Transfers[i].IsCoinbase() { if int64(len(res)) >= limit { break ChainLoop } explorerTransfer, err := convertTsfToExplorerTsf(blk.Transfers[i], false) if err != nil { return []explorer.Transfer{}, errors.Wrapf(err, "failed to convert transfer %v to explorer's JSON transfer", blk.Transfers[i]) } explorerTransfer.Timestamp = int64(blk.ConvertToBlockHeaderPb().Timestamp) explorerTransfer.BlockID = blkID res = append(res, explorerTransfer) } } } return res, nil } // GetTransferByID returns transfer by transfer id func (exp *Service) GetTransferByID(transferID string) (explorer.Transfer, error) { bytes, err := hex.DecodeString(transferID) if err != nil { return explorer.Transfer{}, err } var transferHash hash.Hash32B copy(transferHash[:], bytes) return getTransfer(exp.bc, exp.ap, transferHash, exp.idx, exp.cfg.UseRDS) } // GetTransfersByAddress returns all transfers associated with an address func (exp *Service) GetTransfersByAddress(address string, offset int64, limit int64) ([]explorer.Transfer, error) { var res []explorer.Transfer var transfers []hash.Hash32B if exp.cfg.UseRDS { transferHistory, err := exp.idx.Indexer().GetTransferHistory(address) if err != nil { return []explorer.Transfer{}, err } transfers = append(transfers, transferHistory...) } else { transfersFromAddress, err := exp.bc.GetTransfersFromAddress(address) if err != nil { return []explorer.Transfer{}, err } transfersToAddress, err := exp.bc.GetTransfersToAddress(address) if err != nil { return []explorer.Transfer{}, err } transfersFromAddress = append(transfersFromAddress, transfersToAddress...) transfers = append(transfers, transfersFromAddress...) } for i, transferHash := range transfers { if int64(i) < offset { continue } if int64(len(res)) >= limit { break } explorerTransfer, err := getTransfer(exp.bc, exp.ap, transferHash, exp.idx, exp.cfg.UseRDS) if err != nil { return []explorer.Transfer{}, err } res = append(res, explorerTransfer) } return res, nil } // GetUnconfirmedTransfersByAddress returns all unconfirmed transfers in actpool associated with an address func (exp *Service) GetUnconfirmedTransfersByAddress(address string, offset int64, limit int64) ([]explorer.Transfer, error) { res := make([]explorer.Transfer, 0) if _, err := exp.bc.StateByAddr(address); err != nil { return []explorer.Transfer{}, err } acts := exp.ap.GetUnconfirmedActs(address) tsfIndex := int64(0) for _, act := range acts { transfer, ok := act.(*action.Transfer) if !ok { continue } if tsfIndex < offset { tsfIndex++ continue } if int64(len(res)) >= limit { break } explorerTransfer, err := convertTsfToExplorerTsf(transfer, true) if err != nil { return []explorer.Transfer{}, errors.Wrapf(err, "failed to convert transfer %v to explorer's JSON transfer", transfer) } res = append(res, explorerTransfer) } return res, nil } // GetTransfersByBlockID returns transfers in a block func (exp *Service) GetTransfersByBlockID(blkID string, offset int64, limit int64) ([]explorer.Transfer, error) { var res []explorer.Transfer bytes, err := hex.DecodeString(blkID) if err != nil { return []explorer.Transfer{}, err } var hash hash.Hash32B copy(hash[:], bytes) blk, err := exp.bc.GetBlockByHash(hash) if err != nil { return []explorer.Transfer{}, err } for i, transfer := range blk.Transfers { if int64(i) < offset { continue } if int64(len(res)) >= limit { break } explorerTransfer, err := convertTsfToExplorerTsf(transfer, false) if err != nil { return []explorer.Transfer{}, errors.Wrapf(err, "failed to convert transfer %v to explorer's JSON transfer", transfer) } explorerTransfer.Timestamp = int64(blk.ConvertToBlockHeaderPb().Timestamp) explorerTransfer.BlockID = blkID res = append(res, explorerTransfer) } return res, nil } // GetLastVotesByRange returns votes in [-(offset+limit-1), -offset] from block // with height startBlockHeight func (exp *Service) GetLastVotesByRange(startBlockHeight int64, offset int64, limit int64) ([]explorer.Vote, error) { var res []explorer.Vote voteCount := uint64(0) ChainLoop: for height := startBlockHeight; height >= 0; height-- { hash, err := exp.bc.GetHashByHeight(uint64(height)) if err != nil { return []explorer.Vote{}, err } blkID := hex.EncodeToString(hash[:]) blk, err := exp.bc.GetBlockByHeight(uint64(height)) if err != nil { return []explorer.Vote{}, err } for i := int64(len(blk.Votes) - 1); i >= 0; i-- { voteCount++ if voteCount <= uint64(offset) { continue } if int64(len(res)) >= limit { break ChainLoop } explorerVote, err := convertVoteToExplorerVote(blk.Votes[i], false) if err != nil { return []explorer.Vote{}, errors.Wrapf(err, "failed to convert vote %v to explorer's JSON vote", blk.Votes[i]) } explorerVote.Timestamp = int64(blk.ConvertToBlockHeaderPb().Timestamp) explorerVote.BlockID = blkID res = append(res, explorerVote) } } return res, nil } // GetVoteByID returns vote by vote id func (exp *Service) GetVoteByID(voteID string) (explorer.Vote, error) { bytes, err := hex.DecodeString(voteID) if err != nil { return explorer.Vote{}, err } var voteHash hash.Hash32B copy(voteHash[:], bytes) return getVote(exp.bc, exp.ap, voteHash, exp.idx, exp.cfg.UseRDS) } // GetVotesByAddress returns all votes associated with an address func (exp *Service) GetVotesByAddress(address string, offset int64, limit int64) ([]explorer.Vote, error) { var res []explorer.Vote var votes []hash.Hash32B if exp.cfg.UseRDS { voteHistory, err := exp.idx.Indexer().GetVoteHistory(address) if err != nil { return []explorer.Vote{}, err } votes = append(votes, voteHistory...) } else { votesFromAddress, err := exp.bc.GetVotesFromAddress(address) if err != nil { return []explorer.Vote{}, err } votesToAddress, err := exp.bc.GetVotesToAddress(address) if err != nil { return []explorer.Vote{}, err } votesFromAddress = append(votesFromAddress, votesToAddress...) votes = append(votes, votesFromAddress...) } for i, voteHash := range votes { if int64(i) < offset { continue } if int64(len(res)) >= limit { break } explorerVote, err := getVote(exp.bc, exp.ap, voteHash, exp.idx, exp.cfg.UseRDS) if err != nil { return []explorer.Vote{}, err } res = append(res, explorerVote) } return res, nil } // GetUnconfirmedVotesByAddress returns all unconfirmed votes in actpool associated with an address func (exp *Service) GetUnconfirmedVotesByAddress(address string, offset int64, limit int64) ([]explorer.Vote, error) { res := make([]explorer.Vote, 0) if _, err := exp.bc.StateByAddr(address); err != nil { return []explorer.Vote{}, err } acts := exp.ap.GetUnconfirmedActs(address) voteIndex := int64(0) for _, act := range acts { vote, ok := act.(*action.Vote) if !ok { continue } if voteIndex < offset { voteIndex++ continue } if int64(len(res)) >= limit { break } explorerVote, err := convertVoteToExplorerVote(vote, true) if err != nil { return []explorer.Vote{}, errors.Wrapf(err, "failed to convert vote %v to explorer's JSON vote", vote) } res = append(res, explorerVote) } return res, nil } // GetVotesByBlockID returns votes in a block func (exp *Service) GetVotesByBlockID(blkID string, offset int64, limit int64) ([]explorer.Vote, error) { var res []explorer.Vote bytes, err := hex.DecodeString(blkID) if err != nil { return []explorer.Vote{}, err } var hash hash.Hash32B copy(hash[:], bytes) blk, err := exp.bc.GetBlockByHash(hash) if err != nil { return []explorer.Vote{}, err } for i, vote := range blk.Votes { if int64(i) < offset { continue } if int64(len(res)) >= limit { break } explorerVote, err := convertVoteToExplorerVote(vote, false) if err != nil { return []explorer.Vote{}, errors.Wrapf(err, "failed to convert vote %v to explorer's JSON vote", vote) } explorerVote.Timestamp = int64(blk.ConvertToBlockHeaderPb().Timestamp) explorerVote.BlockID = blkID res = append(res, explorerVote) } return res, nil } // GetLastExecutionsByRange returns executions in [-(offset+limit-1), -offset] from block // with height startBlockHeight func (exp *Service) GetLastExecutionsByRange(startBlockHeight int64, offset int64, limit int64) ([]explorer.Execution, error) { var res []explorer.Execution executionCount := uint64(0) ChainLoop: for height := startBlockHeight; height >= 0; height-- { hash, err := exp.bc.GetHashByHeight(uint64(height)) if err != nil { return []explorer.Execution{}, err } blkID := hex.EncodeToString(hash[:]) blk, err := exp.bc.GetBlockByHeight(uint64(height)) if err != nil { return []explorer.Execution{}, err } for i := int64(len(blk.Executions) - 1); i >= 0; i-- { executionCount++ if executionCount <= uint64(offset) { continue } if int64(len(res)) >= limit { break ChainLoop } explorerExecution, err := convertExecutionToExplorerExecution(blk.Executions[i], false) if err != nil { return []explorer.Execution{}, errors.Wrapf(err, "failed to convert execution %v to explorer's JSON execution", blk.Executions[i]) } explorerExecution.Timestamp = int64(blk.ConvertToBlockHeaderPb().Timestamp) explorerExecution.BlockID = blkID res = append(res, explorerExecution) } } return res, nil } // GetExecutionByID returns execution by execution id func (exp *Service) GetExecutionByID(executionID string) (explorer.Execution, error) { bytes, err := hex.DecodeString(executionID) if err != nil { return explorer.Execution{}, err } var executionHash hash.Hash32B copy(executionHash[:], bytes) return getExecution(exp.bc, exp.ap, executionHash, exp.idx, exp.cfg.UseRDS) } // GetExecutionsByAddress returns all executions associated with an address func (exp *Service) GetExecutionsByAddress(address string, offset int64, limit int64) ([]explorer.Execution, error) { var res []explorer.Execution var executions []hash.Hash32B if exp.cfg.UseRDS { executionHistory, err := exp.idx.Indexer().GetExecutionHistory(address) if err != nil { return []explorer.Execution{}, err } executions = append(executions, executionHistory...) } else { executionsFromAddress, err := exp.bc.GetExecutionsFromAddress(address) if err != nil { return []explorer.Execution{}, err } executionsToAddress, err := exp.bc.GetExecutionsToAddress(address) if err != nil { return []explorer.Execution{}, err } executionsFromAddress = append(executionsFromAddress, executionsToAddress...) executions = append(executions, executionsFromAddress...) } for i, executionHash := range executions { if int64(i) < offset { continue } if int64(len(res)) >= limit { break } explorerExecution, err := getExecution(exp.bc, exp.ap, executionHash, exp.idx, exp.cfg.UseRDS) if err != nil { return []explorer.Execution{}, err } res = append(res, explorerExecution) } return res, nil } // GetUnconfirmedExecutionsByAddress returns all unconfirmed executions in actpool associated with an address func (exp *Service) GetUnconfirmedExecutionsByAddress(address string, offset int64, limit int64) ([]explorer.Execution, error) { res := make([]explorer.Execution, 0) if _, err := exp.bc.StateByAddr(address); err != nil { return []explorer.Execution{}, err } acts := exp.ap.GetUnconfirmedActs(address) executionIndex := int64(0) for _, act := range acts { execution, ok := act.(*action.Execution) if !ok { continue } if executionIndex < offset { executionIndex++ continue } if int64(len(res)) >= limit { break } explorerExecution, err := convertExecutionToExplorerExecution(execution, true) if err != nil { return []explorer.Execution{}, errors.Wrapf(err, "failed to convert execution %v to explorer's JSON execution", execution) } res = append(res, explorerExecution) } return res, nil } // GetExecutionsByBlockID returns executions in a block func (exp *Service) GetExecutionsByBlockID(blkID string, offset int64, limit int64) ([]explorer.Execution, error) { var res []explorer.Execution bytes, err := hex.DecodeString(blkID) if err != nil { return []explorer.Execution{}, err } var hash hash.Hash32B copy(hash[:], bytes) blk, err := exp.bc.GetBlockByHash(hash) if err != nil { return []explorer.Execution{}, err } for i, execution := range blk.Executions { if int64(i) < offset { continue } if int64(len(res)) >= limit { break } explorerExecution, err := convertExecutionToExplorerExecution(execution, false) if err != nil { return []explorer.Execution{}, errors.Wrapf(err, "failed to convert execution %v to explorer's JSON execution", execution) } explorerExecution.Timestamp = int64(blk.ConvertToBlockHeaderPb().Timestamp) explorerExecution.BlockID = blkID res = append(res, explorerExecution) } return res, nil } // GetReceiptByExecutionID gets receipt with corresponding execution id func (exp *Service) GetReceiptByExecutionID(id string) (explorer.Receipt, error) { bytes, err := hex.DecodeString(id) if err != nil { return explorer.Receipt{}, err } var executionHash hash.Hash32B copy(executionHash[:], bytes) receipt, err := exp.bc.GetReceiptByExecutionHash(executionHash) if err != nil { return explorer.Receipt{}, err } return convertReceiptToExplorerReceipt(receipt) } // GetLastBlocksByRange get block with height [offset-limit+1, offset] func (exp *Service) GetLastBlocksByRange(offset int64, limit int64) ([]explorer.Block, error) { var res []explorer.Block for height := offset; height >= 0 && int64(len(res)) < limit; height-- { blk, err := exp.bc.GetBlockByHeight(uint64(height)) if err != nil { return []explorer.Block{}, err } blockHeaderPb := blk.ConvertToBlockHeaderPb() hash, err := exp.bc.GetHashByHeight(uint64(height)) if err != nil { return []explorer.Block{}, err } totalAmount := big.NewInt(0) totalSize := uint32(0) for _, transfer := range blk.Transfers { totalAmount.Add(totalAmount, transfer.Amount()) totalSize += transfer.TotalSize() } explorerBlock := explorer.Block{ ID: hex.EncodeToString(hash[:]), Height: int64(blockHeaderPb.Height), Timestamp: int64(blockHeaderPb.Timestamp), Transfers: int64(len(blk.Transfers)), Votes: int64(len(blk.Votes)), Executions: int64(len(blk.Executions)), Amount: totalAmount.String(), Size: int64(totalSize), GenerateBy: explorer.BlockGenerator{ Name: "", Address: keypair.EncodePublicKey(blk.Header.Pubkey), }, } res = append(res, explorerBlock) } return res, nil } // GetBlockByID returns block by block id func (exp *Service) GetBlockByID(blkID string) (explorer.Block, error) { bytes, err := hex.DecodeString(blkID) if err != nil { return explorer.Block{}, err } var hash hash.Hash32B copy(hash[:], bytes) blk, err := exp.bc.GetBlockByHash(hash) if err != nil { return explorer.Block{}, err } blkHeaderPb := blk.ConvertToBlockHeaderPb() totalAmount := big.NewInt(0) totalSize := uint32(0) for _, transfer := range blk.Transfers { totalAmount.Add(totalAmount, transfer.Amount()) totalSize += transfer.TotalSize() } explorerBlock := explorer.Block{ ID: blkID, Height: int64(blkHeaderPb.Height), Timestamp: int64(blkHeaderPb.Timestamp), Transfers: int64(len(blk.Transfers)), Votes: int64(len(blk.Votes)), Executions: int64(len(blk.Executions)), Amount: totalAmount.String(), Size: int64(totalSize), GenerateBy: explorer.BlockGenerator{ Name: "", Address: keypair.EncodePublicKey(blk.Header.Pubkey), }, } return explorerBlock, nil } // GetCoinStatistic returns stats in blockchain func (exp *Service) GetCoinStatistic() (explorer.CoinStatistic, error) { stat := explorer.CoinStatistic{} tipHeight := exp.bc.TipHeight() totalTransfers, err := exp.bc.GetTotalTransfers() if err != nil { return stat, err } totalVotes, err := exp.bc.GetTotalVotes() if err != nil { return stat, err } totalExecutions, err := exp.bc.GetTotalExecutions() if err != nil { return stat, err } blockLimit := int64(exp.cfg.TpsWindow) if blockLimit <= 0 { return stat, errors.Wrapf(ErrInternalServer, "block limit is %d", blockLimit) } // avoid genesis block if int64(tipHeight) < blockLimit { blockLimit = int64(tipHeight) } blks, err := exp.GetLastBlocksByRange(int64(tipHeight), blockLimit) if err != nil { return stat, err } if len(blks) == 0 { return stat, errors.New("get 0 blocks! not able to calculate aps") } timeDuration := blks[0].Timestamp - blks[len(blks)-1].Timestamp // if time duration is less than 1 second, we set it to be 1 second if timeDuration == 0 { timeDuration = 1 } actionNumber := int64(0) for _, blk := range blks { actionNumber += blk.Transfers + blk.Votes + blk.Executions } aps := actionNumber / timeDuration explorerCoinStats := explorer.CoinStatistic{ Height: int64(tipHeight), Supply: blockchain.Gen.TotalSupply.String(), Transfers: int64(totalTransfers), Votes: int64(totalVotes), Executions: int64(totalExecutions), Aps: aps, } return explorerCoinStats, nil } // GetConsensusMetrics returns the latest consensus metrics func (exp *Service) GetConsensusMetrics() (explorer.ConsensusMetrics, error) { cm, err := exp.c.Metrics() if err != nil { return explorer.ConsensusMetrics{}, err } dStrs := make([]string, len(cm.LatestDelegates)) copy(dStrs, cm.LatestDelegates) var bpStr string if cm.LatestBlockProducer != "" { bpStr = cm.LatestBlockProducer } cStrs := make([]string, len(cm.Candidates)) copy(cStrs, cm.Candidates) return explorer.ConsensusMetrics{ LatestEpoch: int64(cm.LatestEpoch), LatestDelegates: dStrs, LatestBlockProducer: bpStr, Candidates: cStrs, }, nil } // GetCandidateMetrics returns the latest delegates metrics func (exp *Service) GetCandidateMetrics() (explorer.CandidateMetrics, error) { cm, err := exp.c.Metrics() if err != nil { return explorer.CandidateMetrics{}, errors.Wrapf( err, "Failed to get the candidate metrics") } delegateSet := make(map[string]bool, len(cm.LatestDelegates)) for _, d := range cm.LatestDelegates { delegateSet[d] = true } allCandidates, err := exp.bc.CandidatesByHeight(cm.LatestHeight) if err != nil { return explorer.CandidateMetrics{}, errors.Wrapf(err, "Failed to get the candidate metrics") } candidates := make([]explorer.Candidate, len(cm.Candidates)) for i, c := range allCandidates { candidates[i] = explorer.Candidate{ Address: c.Address, TotalVote: c.Votes.String(), CreationHeight: int64(c.CreationHeight), LastUpdateHeight: int64(c.LastUpdateHeight), IsDelegate: false, IsProducer: false, } if _, ok := delegateSet[c.Address]; ok { candidates[i].IsDelegate = true } if cm.LatestBlockProducer == c.Address { candidates[i].IsProducer = true } } return explorer.CandidateMetrics{ Candidates: candidates, LatestEpoch: int64(cm.LatestEpoch), LatestHeight: int64(cm.LatestHeight), }, nil } // GetCandidateMetricsByHeight returns the candidates metrics for given height. func (exp *Service) GetCandidateMetricsByHeight(h int64) (explorer.CandidateMetrics, error) { if h < 0 { return explorer.CandidateMetrics{}, errors.New("Invalid height") } allCandidates, err := exp.bc.CandidatesByHeight(uint64(h)) if err != nil { return explorer.CandidateMetrics{}, errors.Wrapf(err, "Failed to get the candidate metrics") } candidates := make([]explorer.Candidate, 0, len(allCandidates)) for _, c := range allCandidates { pubKey, err := keypair.BytesToPubKeyString(c.PublicKey[:]) if err != nil { return explorer.CandidateMetrics{}, errors.Wrapf(err, "Invalid candidate pub key") } candidates = append(candidates, explorer.Candidate{ Address: c.Address, PubKey: pubKey, TotalVote: c.Votes.String(), CreationHeight: int64(c.CreationHeight), LastUpdateHeight: int64(c.LastUpdateHeight), }) } return explorer.CandidateMetrics{ Candidates: candidates, }, nil } // SendTransfer sends a transfer func (exp *Service) SendTransfer(tsfJSON explorer.SendTransferRequest) (resp explorer.SendTransferResponse, err error) { logger.Debug().Msg("receive send transfer request") defer func() { succeed := "true" if err != nil { succeed = "false" } requestMtc.WithLabelValues("SendTransfer", succeed).Inc() }() payload, err := hex.DecodeString(tsfJSON.Payload) if err != nil { return explorer.SendTransferResponse{}, err } if uint64(len(payload)) > exp.cfg.MaxTransferPayloadBytes { return explorer.SendTransferResponse{}, errors.Wrapf( ErrTransfer, "transfer payload contains %d bytes, and is longer than %d bytes limit", len(payload), exp.cfg.MaxTransferPayloadBytes, ) } senderPubKey, err := keypair.StringToPubKeyBytes(tsfJSON.SenderPubKey) if err != nil { return explorer.SendTransferResponse{}, err } signature, err := hex.DecodeString(tsfJSON.Signature) if err != nil { return explorer.SendTransferResponse{}, err } amount, ok := big.NewInt(0).SetString(tsfJSON.Amount, 10) if !ok { return explorer.SendTransferResponse{}, errors.New("failed to set transfer amount") } gasPrice, ok := big.NewInt(0).SetString(tsfJSON.GasPrice, 10) if !ok { return explorer.SendTransferResponse{}, errors.New("failed to set transfer gas price") } actPb := &pb.ActionPb{ Action: &pb.ActionPb_Transfer{ Transfer: &pb.TransferPb{ Amount: amount.Bytes(), Sender: tsfJSON.Sender, Recipient: tsfJSON.Recipient, Payload: payload, SenderPubKey: senderPubKey, IsCoinbase: tsfJSON.IsCoinbase, }, }, Version: uint32(tsfJSON.Version), Nonce: uint64(tsfJSON.Nonce), GasLimit: uint64(tsfJSON.GasLimit), GasPrice: gasPrice.Bytes(), Signature: signature, } // broadcast to the network if err = exp.p2p.Broadcast(exp.bc.ChainID(), actPb); err != nil { return explorer.SendTransferResponse{}, err } // send to actpool via dispatcher exp.dp.HandleBroadcast(exp.bc.ChainID(), actPb, nil) tsf := &action.Transfer{} tsf.LoadProto(actPb) h := tsf.Hash() return explorer.SendTransferResponse{Hash: hex.EncodeToString(h[:])}, nil } // SendVote sends a vote func (exp *Service) SendVote(voteJSON explorer.SendVoteRequest) (resp explorer.SendVoteResponse, err error) { logger.Debug().Msg("receive send vote request") defer func() { succeed := "true" if err != nil { succeed = "false" } requestMtc.WithLabelValues("SendVote", succeed).Inc() }() selfPubKey, err := keypair.StringToPubKeyBytes(voteJSON.VoterPubKey) if err != nil { return explorer.SendVoteResponse{}, err } signature, err := hex.DecodeString(voteJSON.Signature) if err != nil { return explorer.SendVoteResponse{}, err } gasPrice, ok := big.NewInt(0).SetString(voteJSON.GasPrice, 10) if !ok { return explorer.SendVoteResponse{}, errors.New("failed to set vote gas price") } actPb := &pb.ActionPb{ Action: &pb.ActionPb_Vote{ Vote: &pb.VotePb{ SelfPubkey: selfPubKey, VoterAddress: voteJSON.Voter, VoteeAddress: voteJSON.Votee, }, }, Version: uint32(voteJSON.Version), Nonce: uint64(voteJSON.Nonce), GasLimit: uint64(voteJSON.GasLimit), GasPrice: gasPrice.Bytes(), Signature: signature, } // broadcast to the network if err = exp.p2p.Broadcast(exp.bc.ChainID(), actPb); err != nil { return explorer.SendVoteResponse{}, err } // send to actpool via dispatcher exp.dp.HandleBroadcast(exp.bc.ChainID(), actPb, nil) v := &action.Vote{} v.LoadProto(actPb) h := v.Hash() return explorer.SendVoteResponse{Hash: hex.EncodeToString(h[:])}, nil } // PutSubChainBlock put block merkel root on root chain. func (exp *Service) PutSubChainBlock(putBlockJSON explorer.PutSubChainBlockRequest) (resp explorer.PutSubChainBlockResponse, err error) { logger.Debug().Msg("receive put block request") defer func() { succeed := "true" if err != nil { succeed = "false" } requestMtc.WithLabelValues("PutBlock", succeed).Inc() }() senderPubKey, err := keypair.StringToPubKeyBytes(putBlockJSON.SenderPubKey) if err != nil { return explorer.PutSubChainBlockResponse{}, err } signature, err := hex.DecodeString(putBlockJSON.Signature) if err != nil { return explorer.PutSubChainBlockResponse{}, err } gasPrice, ok := big.NewInt(0).SetString(putBlockJSON.GasPrice, 10) if !ok { return explorer.PutSubChainBlockResponse{}, errors.New("failed to set vote gas price") } roots := make(map[string][]byte) for _, mr := range putBlockJSON.Roots { v, err := hex.DecodeString(mr.Value) if err != nil { return explorer.PutSubChainBlockResponse{}, err } roots[mr.Name] = v } actPb := &pb.ActionPb{ Action: &pb.ActionPb_PutBlock{ PutBlock: &pb.PutBlockPb{ SubChainAddress: putBlockJSON.SubChainAddress, Height: uint64(putBlockJSON.Height), Roots: roots, ProducerAddress: putBlockJSON.SenderAddress, ProducerPublicKey: senderPubKey, }, }, Version: uint32(putBlockJSON.Version), Nonce: uint64(putBlockJSON.Nonce), GasLimit: uint64(putBlockJSON.GasLimit), GasPrice: gasPrice.Bytes(), Signature: signature, } // broadcast to the network if err = exp.p2p.Broadcast(exp.bc.ChainID(), actPb); err != nil { return explorer.PutSubChainBlockResponse{}, err } // send to actpool via dispatcher exp.dp.HandleBroadcast(exp.bc.ChainID(), actPb, nil) v := &action.PutBlock{} v.LoadProto(actPb) h := v.Hash() return explorer.PutSubChainBlockResponse{Hash: hex.EncodeToString(h[:])}, nil } // GetPeers return a list of node peers and itself's network addsress info. func (exp *Service) GetPeers() (explorer.GetPeersResponse, error) { var peers []explorer.Node for _, p := range exp.p2p.GetPeers() { peers = append(peers, explorer.Node{ Address: p.String(), }) } return explorer.GetPeersResponse{ Self: explorer.Node{Address: exp.p2p.Self().String()}, Peers: peers, }, nil } // SendSmartContract sends a smart contract func (exp *Service) SendSmartContract(execution explorer.Execution) (resp explorer.SendSmartContractResponse, err error) { logger.Debug().Msg("receive send smart contract request") defer func() { succeed := "true" if err != nil { succeed = "false" } requestMtc.WithLabelValues("SendSmartContract", succeed).Inc() }() executorPubKey, err := keypair.StringToPubKeyBytes(execution.ExecutorPubKey) if err != nil { return explorer.SendSmartContractResponse{}, err } data, err := hex.DecodeString(execution.Data) if err != nil { return explorer.SendSmartContractResponse{}, err } signature, err := hex.DecodeString(execution.Signature) if err != nil { return explorer.SendSmartContractResponse{}, err } amount, ok := big.NewInt(0).SetString(execution.Amount, 10) if !ok { return explorer.SendSmartContractResponse{}, errors.New("failed to set execution amount") } gasPrice, ok := big.NewInt(0).SetString(execution.GasPrice, 10) if !ok { return explorer.SendSmartContractResponse{}, errors.New("failed to set execution gas price") } actPb := &pb.ActionPb{ Action: &pb.ActionPb_Execution{ Execution: &pb.ExecutionPb{ Amount: amount.Bytes(), Executor: execution.Executor, Contract: execution.Contract, ExecutorPubKey: executorPubKey, Data: data, }, }, Version: uint32(execution.Version), Nonce: uint64(execution.Nonce), GasLimit: uint64(execution.GasLimit), GasPrice: gasPrice.Bytes(), Signature: signature, } // broadcast to the network if err = exp.p2p.Broadcast(exp.bc.ChainID(), actPb); err != nil { return explorer.SendSmartContractResponse{}, err } // send to actpool via dispatcher exp.dp.HandleBroadcast(exp.bc.ChainID(), actPb, nil) sc := &action.Execution{} sc.LoadProto(actPb) h := sc.Hash() return explorer.SendSmartContractResponse{Hash: hex.EncodeToString(h[:])}, nil } // ReadExecutionState reads the state in a contract address specified by the slot func (exp *Service) ReadExecutionState(execution explorer.Execution) (string, error) { logger.Debug().Msg("receive read smart contract request") data, err := hex.DecodeString(execution.Data) if err != nil { return "", err } signature, err := hex.DecodeString(execution.Signature) if err != nil { return "", err } amount, ok := big.NewInt(0).SetString(execution.Amount, 10) if !ok { return "", errors.New("failed to set execution amount") } gasPrice, ok := big.NewInt(0).SetString(execution.GasPrice, 10) if !ok { return "", errors.New("failed to set execution gas price") } actPb := &pb.ActionPb{ Action: &pb.ActionPb_Execution{ Execution: &pb.ExecutionPb{ Amount: amount.Bytes(), Executor: execution.Executor, Contract: execution.Contract, ExecutorPubKey: nil, Data: data, }, }, Version: uint32(execution.Version), Nonce: uint64(execution.Nonce), GasLimit: uint64(execution.GasLimit), GasPrice: gasPrice.Bytes(), Signature: signature, } sc := &action.Execution{} sc.LoadProto(actPb) res, err := exp.bc.ExecuteContractRead(sc) if err != nil { return "", err } return hex.EncodeToString(res), nil } // GetBlockOrActionByHash get block or action by a hash func (exp *Service) GetBlockOrActionByHash(hashStr string) (explorer.GetBlkOrActResponse, error) { if blk, err := exp.GetBlockByID(hashStr); err == nil { return explorer.GetBlkOrActResponse{Block: &blk}, nil } if tsf, err := exp.GetTransferByID(hashStr); err == nil { return explorer.GetBlkOrActResponse{Transfer: &tsf}, nil } if vote, err := exp.GetVoteByID(hashStr); err == nil { return explorer.GetBlkOrActResponse{Vote: &vote}, nil } if exe, err := exp.GetExecutionByID(hashStr); err == nil { return explorer.GetBlkOrActResponse{Execution: &exe}, nil } return explorer.GetBlkOrActResponse{}, nil } // getTransfer takes in a blockchain and transferHash and returns an Explorer Transfer func getTransfer(bc blockchain.Blockchain, ap actpool.ActPool, transferHash hash.Hash32B, idx *indexservice.Server, useRDS bool) (explorer.Transfer, error) { explorerTransfer := explorer.Transfer{} transfer, err := bc.GetTransferByTransferHash(transferHash) if err != nil { // Try to fetch pending transfer from actpool act, err := ap.GetActionByHash(transferHash) if err != nil || act == nil { return explorerTransfer, err } transfer = act.(*action.Transfer) return convertTsfToExplorerTsf(transfer, true) } // Fetch from block var blkHash hash.Hash32B if useRDS { hash, err := idx.Indexer().GetBlockByTransfer(transferHash) if err != nil { return explorerTransfer, err } blkHash = hash } else { hash, err := bc.GetBlockHashByTransferHash(transferHash) if err != nil { return explorerTransfer, err } blkHash = hash } blk, err := bc.GetBlockByHash(blkHash) if err != nil { return explorerTransfer, err } if explorerTransfer, err = convertTsfToExplorerTsf(transfer, false); err != nil { return explorerTransfer, errors.Wrapf(err, "failed to convert transfer %v to explorer's JSON transfer", transfer) } explorerTransfer.Timestamp = int64(blk.ConvertToBlockHeaderPb().Timestamp) explorerTransfer.BlockID = hex.EncodeToString(blkHash[:]) return explorerTransfer, nil } // getVote takes in a blockchain and voteHash and returns an Explorer Vote func getVote(bc blockchain.Blockchain, ap actpool.ActPool, voteHash hash.Hash32B, idx *indexservice.Server, useRDS bool) (explorer.Vote, error) { explorerVote := explorer.Vote{} vote, err := bc.GetVoteByVoteHash(voteHash) if err != nil { // Try to fetch pending vote from actpool act, err := ap.GetActionByHash(voteHash) if err != nil || act == nil { return explorerVote, err } vote = act.(*action.Vote) return convertVoteToExplorerVote(vote, true) } // Fetch from block var blkHash hash.Hash32B if useRDS { hash, err := idx.Indexer().GetBlockByVote(voteHash) if err != nil { return explorerVote, err } blkHash = hash } else { hash, err := bc.GetBlockHashByVoteHash(voteHash) if err != nil { return explorerVote, err } blkHash = hash } blk, err := bc.GetBlockByHash(blkHash) if err != nil { return explorerVote, err } if explorerVote, err = convertVoteToExplorerVote(vote, false); err != nil { return explorerVote, errors.Wrapf(err, "failed to convert vote %v to explorer's JSON vote", vote) } explorerVote.Timestamp = int64(blk.ConvertToBlockHeaderPb().Timestamp) explorerVote.BlockID = hex.EncodeToString(blkHash[:]) return explorerVote, nil } // getExecution takes in a blockchain and executionHash and returns an Explorer execution func getExecution(bc blockchain.Blockchain, ap actpool.ActPool, executionHash hash.Hash32B, idx *indexservice.Server, useRDS bool) (explorer.Execution, error) { explorerExecution := explorer.Execution{} execution, err := bc.GetExecutionByExecutionHash(executionHash) if err != nil { // Try to fetch pending execution from actpool act, err := ap.GetActionByHash(executionHash) if err != nil || act == nil { return explorerExecution, err } execution = act.(*action.Execution) return convertExecutionToExplorerExecution(execution, true) } // Fetch from block var blkHash hash.Hash32B if useRDS { hash, err := idx.Indexer().GetBlockByExecution(executionHash) if err != nil { return explorerExecution, err } blkHash = hash } else { hash, err := bc.GetBlockHashByExecutionHash(executionHash) if err != nil { return explorerExecution, err } blkHash = hash } blk, err := bc.GetBlockByHash(blkHash) if err != nil { return explorerExecution, err } if explorerExecution, err = convertExecutionToExplorerExecution(execution, false); err != nil { return explorerExecution, errors.Wrapf(err, "failed to convert execution %v to explorer's JSON execution", execution) } explorerExecution.Timestamp = int64(blk.ConvertToBlockHeaderPb().Timestamp) explorerExecution.BlockID = hex.EncodeToString(blkHash[:]) return explorerExecution, nil } func convertTsfToExplorerTsf(transfer *action.Transfer, isPending bool) (explorer.Transfer, error) { if transfer == nil { return explorer.Transfer{}, errors.Wrap(ErrTransfer, "transfer cannot be nil") } hash := transfer.Hash() explorerTransfer := explorer.Transfer{ Nonce: int64(transfer.Nonce()), ID: hex.EncodeToString(hash[:]), Sender: transfer.Sender(), Recipient: transfer.Recipient(), Fee: "", // TODO: we need to get the actual fee. Payload: hex.EncodeToString(transfer.Payload()), GasLimit: int64(transfer.GasLimit()), IsPending: isPending, } if transfer.Amount() != nil && len(transfer.Amount().String()) > 0 { explorerTransfer.Amount = transfer.Amount().String() } if transfer.GasPrice() != nil && len(transfer.GasPrice().String()) > 0 { explorerTransfer.GasPrice = transfer.GasPrice().String() } return explorerTransfer, nil } func convertVoteToExplorerVote(vote *action.Vote, isPending bool) (explorer.Vote, error) { if vote == nil { return explorer.Vote{}, errors.Wrap(ErrVote, "vote cannot be nil") } hash := vote.Hash() voterPubkey := vote.VoterPublicKey() explorerVote := explorer.Vote{ ID: hex.EncodeToString(hash[:]), Nonce: int64(vote.Nonce()), Voter: vote.Voter(), VoterPubKey: hex.EncodeToString(voterPubkey[:]), Votee: vote.Votee(), GasLimit: int64(vote.GasLimit()), GasPrice: vote.GasPrice().String(), IsPending: isPending, } return explorerVote, nil } func convertExecutionToExplorerExecution(execution *action.Execution, isPending bool) (explorer.Execution, error) { if execution == nil { return explorer.Execution{}, errors.Wrap(ErrExecution, "execution cannot be nil") } hash := execution.Hash() explorerExecution := explorer.Execution{ Nonce: int64(execution.Nonce()), ID: hex.EncodeToString(hash[:]), Executor: execution.Executor(), Contract: execution.Contract(), GasLimit: int64(execution.GasLimit()), Data: hex.EncodeToString(execution.Data()), IsPending: isPending, } if execution.Amount() != nil && len(execution.Amount().String()) > 0 { explorerExecution.Amount = execution.Amount().String() } if execution.GasPrice() != nil && len(execution.GasPrice().String()) > 0 { explorerExecution.GasPrice = execution.GasPrice().String() } return explorerExecution, nil } func convertReceiptToExplorerReceipt(receipt *blockchain.Receipt) (explorer.Receipt, error) { if receipt == nil { return explorer.Receipt{}, errors.Wrap(ErrReceipt, "receipt cannot be nil") } logs := []explorer.Log{} for _, log := range receipt.Logs { topics := []string{} for _, topic := range log.Topics { topics = append(topics, hex.EncodeToString(topic[:])) } logs = append(logs, explorer.Log{ Address: log.Address, Topics: topics, Data: hex.EncodeToString(log.Data), BlockNumber: int64(log.BlockNumber), TxnHash: hex.EncodeToString(log.TxnHash[:]), BlockHash: hex.EncodeToString(log.BlockHash[:]), Index: int64(log.Index), }) } return explorer.Receipt{ ReturnValue: hex.EncodeToString(receipt.ReturnValue), Status: int64(receipt.Status), Hash: hex.EncodeToString(receipt.Hash[:]), GasConsumed: int64(receipt.GasConsumed), ContractAddress: receipt.ContractAddress, Logs: logs, }, nil }
1
12,880
I think we want to provide getAction API instead
iotexproject-iotex-core
go
@@ -117,12 +117,7 @@ class SynthDriver(SynthDriver): @classmethod def check(cls): - if not hasattr(sys, "frozen"): - # #3793: Source copies don't report the correct version on Windows 10 because Python isn't manifested for higher versions. - # We want this driver to work for source copies on Windows 10, so just return True here. - # If this isn't in fact Windows 10, it will fail when constructed, which is okay. - return True - # For binary copies, only present this as an available synth if this is Windows 10. + # Only present this as an available synth if this is Windows 10. return winVersion.winVersion.major >= 10 def _get_supportsProsodyOptions(self):
1
#synthDrivers/oneCore.py #A part of NonVisual Desktop Access (NVDA) #Copyright (C) 2016-2019 Tyler Spivey, NV Access Limited, James Teh, Leonard de Ruijter #This file is covered by the GNU General Public License. #See the file COPYING for more details. """Synth driver for Windows OneCore voices. """ import os import sys from collections import OrderedDict import ctypes import winreg import wave from synthDriverHandler import SynthDriver, VoiceInfo, synthIndexReached, synthDoneSpeaking import io from logHandler import log import config import nvwave import speech import speechXml import languageHandler import winVersion import NVDAHelper #: The number of 100-nanosecond units in 1 second. HUNDRED_NS_PER_SEC = 10000000 # 1000000000 ns per sec / 100 ns ocSpeech_Callback = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_int, ctypes.c_wchar_p) class _OcSsmlConverter(speechXml.SsmlConverter): def _convertProsody(self, command, attr, default, base=None): if base is None: base = default if command.multiplier == 1 and base == default: # Returning to synth default. return speechXml.DelAttrCommand("prosody", attr) else: # Multiplication isn't supported, only addition/subtraction. # The final value must therefore be relative to the synthesizer's default. val = base * command.multiplier - default return speechXml.SetAttrCommand("prosody", attr, "%d%%" % val) def convertRateCommand(self, command): return self._convertProsody(command, "rate", 50) def convertPitchCommand(self, command): return self._convertProsody(command, "pitch", 50) def convertVolumeCommand(self, command): return self._convertProsody(command, "volume", 100) def convertCharacterModeCommand(self, command): # OneCore's character speech sounds weird and doesn't support pitch alteration. # Therefore, we don't use it. return None def convertLangChangeCommand(self, command): lcid = languageHandler.localeNameToWindowsLCID(command.lang) if lcid is languageHandler.LCID_NONE: log.debugWarning("Invalid language: %s" % command.lang) return None return super(_OcSsmlConverter, self).convertLangChangeCommand(command) class _OcPreAPI5SsmlConverter(_OcSsmlConverter): def __init__(self, defaultLanguage, rate, pitch, volume): super(_OcPreAPI5SsmlConverter, self).__init__(defaultLanguage) self._rate = rate self._pitch = pitch self._volume = volume def generateBalancerCommands(self, speechSequence): commands = super(_OcPreAPI5SsmlConverter, self).generateBalancerCommands(speechSequence) # The EncloseAllCommand from SSML must be first. yield next(commands) # OneCore didn't provide a way to set base prosody values before API version 5. # Therefore, the base values need to be set using SSML. yield self.convertRateCommand(speech.RateCommand(multiplier=1)) yield self.convertVolumeCommand(speech.VolumeCommand(multiplier=1)) yield self.convertPitchCommand(speech.PitchCommand(multiplier=1)) for command in commands: yield command def convertRateCommand(self, command): return self._convertProsody(command, "rate", 50, self._rate) def convertPitchCommand(self, command): return self._convertProsody(command, "pitch", 50, self._pitch) def convertVolumeCommand(self, command): return self._convertProsody(command, "volume", 100, self._volume) class SynthDriver(SynthDriver): MIN_PITCH = 0.0 MAX_PITCH = 2.0 MIN_RATE = 0.5 DEFAULT_MAX_RATE = 1.5 BOOSTED_MAX_RATE = 6.0 name = "oneCore" # Translators: Description for a speech synthesizer. description = _("Windows OneCore voices") supportedCommands = { speech.IndexCommand, speech.CharacterModeCommand, speech.LangChangeCommand, speech.BreakCommand, speech.PitchCommand, speech.RateCommand, speech.VolumeCommand, speech.PhonemeCommand, } supportedNotifications = {synthIndexReached, synthDoneSpeaking} @classmethod def check(cls): if not hasattr(sys, "frozen"): # #3793: Source copies don't report the correct version on Windows 10 because Python isn't manifested for higher versions. # We want this driver to work for source copies on Windows 10, so just return True here. # If this isn't in fact Windows 10, it will fail when constructed, which is okay. return True # For binary copies, only present this as an available synth if this is Windows 10. return winVersion.winVersion.major >= 10 def _get_supportsProsodyOptions(self): self.supportsProsodyOptions = self._dll.ocSpeech_supportsProsodyOptions() return self.supportsProsodyOptions def _get_supportedSettings(self): self.supportedSettings = settings = [ SynthDriver.VoiceSetting(), SynthDriver.RateSetting(), ] if self.supportsProsodyOptions: settings.append(SynthDriver.RateBoostSetting()) settings.extend([ SynthDriver.PitchSetting(), SynthDriver.VolumeSetting(), ]) return settings def __init__(self): super(SynthDriver, self).__init__() self._dll = NVDAHelper.getHelperLocalWin10Dll() self._dll.ocSpeech_getCurrentVoiceLanguage.restype = ctypes.c_wchar_p # Set initial values for parameters that can't be queried when prosody is not supported. # This initialises our cache for the value. # When prosody is supported, the values are used for cachign reasons. self._rate = 50 self._pitch = 50 self._volume = 100 if self.supportsProsodyOptions: self._dll.ocSpeech_getPitch.restype = ctypes.c_double self._dll.ocSpeech_getVolume.restype = ctypes.c_double self._dll.ocSpeech_getRate.restype = ctypes.c_double else: log.debugWarning("Prosody options not supported") self._handle = self._dll.ocSpeech_initialize() self._callbackInst = ocSpeech_Callback(self._callback) self._dll.ocSpeech_setCallback(self._handle, self._callbackInst) self._dll.ocSpeech_getVoices.restype = NVDAHelper.bstrReturn self._dll.ocSpeech_getCurrentVoiceId.restype = ctypes.c_wchar_p self._player= None # Initialize state. self._queuedSpeech = [] self._wasCancelled = False self._isProcessing = False # Initialize the voice to a sane default self.voice=self._getDefaultVoice() def _maybeInitPlayer(self, wav): """Initialize audio playback based on the wave header provided by the synthesizer. If the sampling rate has not changed, the existing player is used. Otherwise, a new one is created with the appropriate parameters. """ samplesPerSec = wav.getframerate() if self._player and self._player.samplesPerSec == samplesPerSec: return if self._player: # Finalise any pending audio. self._player.idle() bytesPerSample = wav.getsampwidth() self._bytesPerSec = samplesPerSec * bytesPerSample self._player = nvwave.WavePlayer(channels=wav.getnchannels(), samplesPerSec=samplesPerSec, bitsPerSample=bytesPerSample * 8, outputDevice=config.conf["speech"]["outputDevice"]) def terminate(self): super(SynthDriver, self).terminate() self._dll.ocSpeech_terminate(self._handle) # Drop the ctypes function instance for the callback, # as it is holding a reference to an instance method, which causes a reference cycle. self._callbackInst = None def cancel(self): # Set a flag to tell the callback not to push more audio. self._wasCancelled = True log.debug("Cancelling") # There might be more text pending. Throw it away. if self.supportsProsodyOptions: # In this case however, we must keep any parameter changes. self._queuedSpeech = [item for item in self._queuedSpeech if not isinstance(item, str)] else: self._queuedSpeech = [] if self._player: self._player.stop() def speak(self, speechSequence): if self.supportsProsodyOptions: conv = _OcSsmlConverter(self.language) else: conv = _OcPreAPI5SsmlConverter(self.language, self._rate, self._pitch, self._volume) text = conv.convertToXml(speechSequence) # #7495: Calling WaveOutOpen blocks for ~100 ms if called from the callback # when the SSML includes marks. # We're not quite sure why. # To work around this, open the device before queuing. if self._player: self._player.open() self._queueSpeech(text) def _queueSpeech(self, item): self._queuedSpeech.append(item) # We only process the queue here if it isn't already being processed. if not self._isProcessing: self._processQueue() @classmethod def _percentToParam(self, percent, min, max): """Overrides SynthDriver._percentToParam to return floating point parameter values. """ return float(percent) / 100 * (max - min) + min def _get_pitch(self): if not self.supportsProsodyOptions: return self._pitch rawPitch = self._dll.ocSpeech_getPitch(self._handle) return self._paramToPercent(rawPitch, self.MIN_PITCH, self.MAX_PITCH) def _set_pitch(self, pitch): self._pitch = pitch if not self.supportsProsodyOptions: return rawPitch = self._percentToParam(pitch, self.MIN_PITCH, self.MAX_PITCH) self._queuedSpeech.append((self._dll.ocSpeech_setPitch, rawPitch)) def _get_volume(self): if not self.supportsProsodyOptions: return self._volume rawVolume = self._dll.ocSpeech_getVolume(self._handle) return int(rawVolume * 100) def _set_volume(self, volume): self._volume = volume if not self.supportsProsodyOptions: return rawVolume = volume / 100.0 self._queuedSpeech.append((self._dll.ocSpeech_setVolume, rawVolume)) def _get_rate(self): if not self.supportsProsodyOptions: return self._rate rawRate = self._dll.ocSpeech_getRate(self._handle) maxRate = self.BOOSTED_MAX_RATE if self._rateBoost else self.DEFAULT_MAX_RATE return self._paramToPercent(rawRate, self.MIN_RATE, maxRate) def _set_rate(self, rate): self._rate = rate if not self.supportsProsodyOptions: return maxRate = self.BOOSTED_MAX_RATE if self._rateBoost else self.DEFAULT_MAX_RATE rawRate = self._percentToParam(rate, self.MIN_RATE, maxRate) self._queuedSpeech.append((self._dll.ocSpeech_setRate, rawRate)) _rateBoost = False def _get_rateBoost(self): return self._rateBoost def _set_rateBoost(self, enable): if enable == self._rateBoost: return # Use the cached rate to calculate the new rate with rate boost enabled. # If we don't, getting the rate property will return the default rate when initializing the driver and applying settings. rate = self._rate self._rateBoost = enable self.rate = rate def _processQueue(self): if not self._queuedSpeech: # There are no more queued utterances at this point, so call idle. # This blocks while waiting for the final chunk to play, # so by the time this is done, there might be something queued. log.debug("Calling idle on audio player") self._player.idle() synthDoneSpeaking.notify(synth=self) while self._queuedSpeech: item = self._queuedSpeech.pop(0) if isinstance(item, tuple): # Parameter change. # Note that, if prosody otions aren't supported, this code will never be executed. func, value = item value = ctypes.c_double(value) func(self._handle, value) continue self._wasCancelled = False log.debug("Begin processing speech") self._isProcessing = True # ocSpeech_speak is async. # It will call _callback in a background thread once done, # which will eventually process the queue again. self._dll.ocSpeech_speak(self._handle, item) return log.debug("Queue empty, done processing") self._isProcessing = False def _callback(self, bytes, len, markers): if len == 0: # The C++ code will log an error with details. log.debugWarning("ocSpeech_speak failed!") self._processQueue() return # This gets called in a background thread. stream = io.BytesIO(ctypes.string_at(bytes, len)) wav = wave.open(stream, "r") self._maybeInitPlayer(wav) data = wav.readframes(wav.getnframes()) if markers: markers = markers.split('|') else: markers = [] prevPos = 0 # Push audio up to each marker so we can sync the audio with the markers. for marker in markers: if self._wasCancelled: break name, pos = marker.split(':') index = int(name) pos = int(pos) # pos is a time offset in 100-nanosecond units. # Convert this to a byte offset. # Order the equation so we don't have to do floating point. # #9641 (Py3 review required): one way to ensure no floating point is doing a floor division to obtain an integer. # Because one slash operator will do true division in Python 3, which will return a float. pos = pos * self._bytesPerSec // HUNDRED_NS_PER_SEC # Push audio up to this marker. self._player.feed(data[prevPos:pos], onDone=lambda index=index: synthIndexReached.notify(synth=self, index=index)) prevPos = pos if self._wasCancelled: log.debug("Cancelled, stopped pushing audio") else: self._player.feed(data[prevPos:]) log.debug("Done pushing audio") self._processQueue() def _getVoiceInfoFromOnecoreVoiceString(self, voiceStr): """ Produces an NVDA VoiceInfo object representing the given voice string from Onecore speech. """ # The voice string is made up of the ID, the language, and the display name. ID,language,name=voiceStr.split(':') language=language.replace('-','_') return VoiceInfo(ID,name,language=language) def _getAvailableVoices(self): voices = OrderedDict() # Fetch the full list of voices that Onecore speech knows about. # Note that it may give back voices that are uninstalled or broken. voicesStr = self._dll.ocSpeech_getVoices(self._handle).split('|') for index,voiceStr in enumerate(voicesStr): voiceInfo=self._getVoiceInfoFromOnecoreVoiceString(voiceStr) # Filter out any invalid voices. if not self._isVoiceValid(voiceInfo.id): continue voiceInfo.onecoreIndex=index voices[voiceInfo.id] = voiceInfo return voices def _isVoiceValid(self,ID): """ Checks that the given voice actually exists and is valid. It checks the Registry, and also ensures that its data files actually exist on this machine. @param ID: the ID of the requested voice. @type ID: string @returns: True if the voice is valid, false otherwise. @rtype: boolean """ IDParts = ID.split('\\') rootKey = getattr(winreg, IDParts[0]) subkey = "\\".join(IDParts[1:]) try: hkey = winreg.OpenKey(rootKey, subkey) except WindowsError as e: log.debugWarning("Could not open registry key %s, %r" % (ID, e)) return False try: langDataPath = winreg.QueryValueEx(hkey, 'langDataPath') except WindowsError as e: log.debugWarning("Could not open registry value 'langDataPath', %r" % e) return False if not langDataPath or not isinstance(langDataPath[0], str): log.debugWarning("Invalid langDataPath value") return False if not os.path.isfile(os.path.expandvars(langDataPath[0])): log.debugWarning("Missing language data file: %s" % langDataPath[0]) return False try: voicePath = winreg.QueryValueEx(hkey, 'voicePath') except WindowsError as e: log.debugWarning("Could not open registry value 'langDataPath', %r" % e) return False if not voicePath or not isinstance(voicePath[0],str): log.debugWarning("Invalid voicePath value") return False if not os.path.isfile(os.path.expandvars(voicePath[0] + '.apm')): log.debugWarning("Missing voice file: %s" % voicePath[0] + ".apm") return False return True def _get_voice(self): return self._dll.ocSpeech_getCurrentVoiceId(self._handle) def _set_voice(self, id): voices = self.availableVoices # Try setting the requested voice # #9067 (Py3 review required): voices is an ordered dictionary. for voice in voices.values(): if voice.id == id: self._dll.ocSpeech_setVoice(self._handle, voice.onecoreIndex) return raise LookupError("No such voice: %s"%id) def _getDefaultVoice(self): """ Finds the best available voice that can be used as a default. It first tries finding a voice with the same language and country as the user's configured Windows language (E.g. en_AU), else one that matches just the language (E.g. en), else simply the first available. @returns: the ID of the voice, suitable for passing to self.voice for setting. @rtype: string """ voices = self.availableVoices # Try matching to NVDA language fullLanguage=languageHandler.getWindowsLanguage() for voice in voices.values(): if voice.language==fullLanguage: return voice.id baseLanguage=fullLanguage.split('_')[0] if baseLanguage!=fullLanguage: for voice in voices.values(): if voice.language.startswith(baseLanguage): return voice.id # Just use the first available for voice in voices.values(): return voice.id raise RuntimeError("No voices available") def _get_language(self): return self._dll.ocSpeech_getCurrentVoiceLanguage(self._handle) def pause(self, switch): if self._player: self._player.pause(switch)
1
26,162
There is also `winVersion.isWin10`. I think this should be converted to use the helper function. The helper has a note that it doesn't work in source copies, but looking at the implementation it looks equivalent to what you have here.
nvaccess-nvda
py
@@ -37,6 +37,7 @@ RSpec.configure do |config| config.use_transactional_fixtures = false config.use_instantiated_fixtures = false config.fixture_path = "#{::Rails.root}/spec/fixtures" + config.fail_fast = true config.include Paperclip::Shoulda::Matchers config.include EmailSpec::Helpers
1
require 'codeclimate-test-reporter' CodeClimate::TestReporter.configure do |config| config.logger.level = Logger::WARN end CodeClimate::TestReporter.start if ENV["COVERAGE"] require 'simplecov' SimpleCov.start 'rails' end ENV["RAILS_ENV"] ||= 'test' require File.expand_path("../../config/environment", __FILE__) require 'rspec/autorun' require 'rspec/rails' require 'paperclip/matchers' require 'email_spec' require 'webmock/rspec' require 'clearance/testing' WebMock.disable_net_connect!(allow_localhost: true, allow: 'codeclimate.com') Dir[File.expand_path(File.join(File.dirname(__FILE__),'support','**','*.rb'))].each {|f| require f} FakeStripeRunner.boot FakeGithubRunner.boot Delayed::Worker.delay_jobs = false Capybara.javascript_driver = :webkit Capybara.configure do |config| config.match = :prefer_exact config.ignore_hidden_elements = false end RSpec.configure do |config| config.use_transactional_fixtures = false config.use_instantiated_fixtures = false config.fixture_path = "#{::Rails.root}/spec/fixtures" config.include Paperclip::Shoulda::Matchers config.include EmailSpec::Helpers config.include EmailSpec::Matchers config.include FactoryGirl::Syntax::Methods config.include Subscriptions config.include PurchaseHelpers config.include StripeHelpers config.include SessionHelpers, type: :feature config.include PaypalHelpers, type: :feature config.mock_with :mocha config.treat_symbols_as_metadata_keys_with_true_values = true end
1
9,113
This doesn't seem like it should be part of this pull request.
thoughtbot-upcase
rb
@@ -4,6 +4,7 @@ class ProductsController < ApplicationController def show @product = Product.find(params[:id]) + @offering = @product @viewable_subscription = ViewableSubscription.new(current_user, subscription_product) if signed_in? && @product.purchase_for(current_user)
1
class ProductsController < ApplicationController def index end def show @product = Product.find(params[:id]) @viewable_subscription = ViewableSubscription.new(current_user, subscription_product) if signed_in? && @product.purchase_for(current_user) redirect_to @product.purchase_for(current_user) else km.record("Viewed Product", { "Product Name" => @product.name }) end end end
1
7,128
Is the idea that `@product` (and `@workshop` for `workshops_controller`) would eventually go away here?
thoughtbot-upcase
rb
@@ -0,0 +1,8 @@ +package headerdownload + +var bscMainnetPreverifiedHashes = []string{ + "0d21840abff46b96c84b2ac9e10e4f5cdaeb5693cb665db62a2f3b02d2d57b5b", + "04055304e432294a65ff31069c4d3092ff8b58f009cdb50eba5351e0332ad0f6", +} + +const bscMainnetPreverifiedHeight uint64 = 1
1
1
22,958
We should add those only once we have successfully synced to the BSC main net, we have a utility to generate those. Please remove for now
ledgerwatch-erigon
go
@@ -376,7 +376,7 @@ def test_set_env_from_file(config_instance): def test_set_env_from_file_returns_original_env_when_env_file_not_found( - config_instance + config_instance, ): env = config.set_env_from_file({}, 'file-not-found')
1
# Copyright (c) 2015-2018 Cisco Systems, 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. import os import pytest from molecule import config from molecule import platforms from molecule import scenario from molecule import state from molecule import util from molecule.dependency import ansible_galaxy from molecule.dependency import gilt from molecule.dependency import shell from molecule.lint import yamllint from molecule.provisioner import ansible from molecule.verifier import testinfra from molecule.verifier import ansible as ansible_verifier def test_molecule_file_private_member(molecule_file_fixture, config_instance): assert molecule_file_fixture == config_instance.molecule_file def test_args_member(config_instance): assert {} == config_instance.args def test_command_args_member(config_instance): x = {'subcommand': 'test'} assert x == config_instance.command_args def test_debug_property(config_instance): assert not config_instance.debug def test_env_file_property(config_instance): config_instance.args = {'env_file': '.env'} result = config_instance.env_file assert util.abs_path(config_instance.args.get('env_file')) == result def test_subcommand_property(config_instance): assert 'test' == config_instance.subcommand def test_action_property(config_instance): assert config_instance.action is None def test_action_setter(config_instance): config_instance.action = 'foo' assert 'foo' == config_instance.action def test_init_calls_validate(patched_config_validate, config_instance): patched_config_validate.assert_called_once_with() def test_project_directory_property(config_instance): assert os.getcwd() == config_instance.project_directory def test_molecule_directory_property(config_instance): x = os.path.join(os.getcwd(), 'molecule') assert x == config_instance.molecule_directory def test_dependency_property(config_instance): assert isinstance(config_instance.dependency, ansible_galaxy.AnsibleGalaxy) @pytest.fixture def _config_dependency_gilt_section_data(): return {'dependency': {'name': 'gilt'}} @pytest.mark.parametrize( 'config_instance', ['_config_dependency_gilt_section_data'], indirect=True ) def test_dependency_property_is_gilt(config_instance): assert isinstance(config_instance.dependency, gilt.Gilt) @pytest.fixture def _config_dependency_shell_section_data(): return {'dependency': {'name': 'shell', 'command': 'bin/command'}} @pytest.mark.parametrize( 'config_instance', ['_config_dependency_shell_section_data'], indirect=True ) def test_dependency_property_is_shell(config_instance): assert isinstance(config_instance.dependency, shell.Shell) @pytest.fixture def _config_driver_delegated_section_data(): return {'driver': {'name': 'delegated', 'options': {'managed': False}}} def test_env(config_instance): config_instance.args = {'env_file': '.env'} x = { 'MOLECULE_DEBUG': 'False', 'MOLECULE_FILE': config_instance.config_file, 'MOLECULE_ENV_FILE': util.abs_path(config_instance.args.get('env_file')), 'MOLECULE_INVENTORY_FILE': config_instance.provisioner.inventory_file, 'MOLECULE_EPHEMERAL_DIRECTORY': config_instance.scenario.ephemeral_directory, 'MOLECULE_SCENARIO_DIRECTORY': config_instance.scenario.directory, 'MOLECULE_PROJECT_DIRECTORY': config_instance.project_directory, 'MOLECULE_INSTANCE_CONFIG': config_instance.driver.instance_config, 'MOLECULE_DEPENDENCY_NAME': 'galaxy', 'MOLECULE_DRIVER_NAME': 'docker', 'MOLECULE_LINT_NAME': 'yamllint', 'MOLECULE_PROVISIONER_NAME': 'ansible', 'MOLECULE_PROVISIONER_LINT_NAME': 'ansible-lint', 'MOLECULE_SCENARIO_NAME': 'default', 'MOLECULE_STATE_FILE': config_instance.state.state_file, 'MOLECULE_VERIFIER_NAME': 'testinfra', 'MOLECULE_VERIFIER_LINT_NAME': 'flake8', 'MOLECULE_VERIFIER_TEST_DIRECTORY': config_instance.verifier.directory, } assert x == config_instance.env def test_lint_property(config_instance): assert isinstance(config_instance.lint, yamllint.Yamllint) def test_platforms_property(config_instance): assert isinstance(config_instance.platforms, platforms.Platforms) def test_provisioner_property(config_instance): assert isinstance(config_instance.provisioner, ansible.Ansible) def test_scenario_property(config_instance): assert isinstance(config_instance.scenario, scenario.Scenario) def test_state_property(config_instance): assert isinstance(config_instance.state, state.State) def test_verifier_property(config_instance): assert isinstance(config_instance.verifier, testinfra.Testinfra) @pytest.fixture def _config_verifier_ansible_section_data(): return {'verifier': {'name': 'ansible', 'lint': {'name': 'ansible-lint'}}} @pytest.mark.parametrize( 'config_instance', ['_config_verifier_ansible_section_data'], indirect=True ) def test_verifier_property_is_ansible(config_instance): assert isinstance(config_instance.verifier, ansible_verifier.Ansible) def test_get_driver_name_from_state_file(config_instance): config_instance.state.change_state('driver', 'state-driver') assert 'state-driver' == config_instance._get_driver_name() def test_get_driver_name_from_cli(config_instance): config_instance.command_args = {'driver_name': 'cli-driver'} assert 'cli-driver' == config_instance._get_driver_name() def test_get_driver_name(config_instance): assert 'docker' == config_instance._get_driver_name() def test_get_driver_name_raises_when_different_driver_used( patched_logger_critical, config_instance ): config_instance.state.change_state('driver', 'foo') config_instance.command_args = {'driver_name': 'bar'} with pytest.raises(SystemExit) as e: config_instance._get_driver_name() assert 1 == e.value.code msg = ( "Instance(s) were created with the 'foo' driver, " "but the subcommand is using 'bar' driver." ) patched_logger_critical.assert_called_once_with(msg) def test_get_config(config_instance): assert isinstance(config_instance._get_config(), dict) def test_get_config_with_base_config(config_instance): config_instance.args = {'base_config': './foo.yml'} contents = {'foo': 'bar'} util.write_file(config_instance.args['base_config'], util.safe_dump(contents)) result = config_instance._get_config() assert result['foo'] == 'bar' def test_reget_config(config_instance): assert isinstance(config_instance._reget_config(), dict) def test_interpolate(patched_logger_critical, config_instance): string = 'foo: $HOME' x = 'foo: {}'.format(os.environ['HOME']) assert x == config_instance._interpolate(string, os.environ, None) def test_interpolate_curly(patched_logger_critical, config_instance): string = 'foo: ${HOME}' x = 'foo: {}'.format(os.environ['HOME']) assert x == config_instance._interpolate(string, os.environ, None) def test_interpolate_default(patched_logger_critical, config_instance): string = 'foo: ${NONE-default}' x = 'foo: default' assert x == config_instance._interpolate(string, os.environ, None) def test_interpolate_default_colon(patched_logger_critical, config_instance): string = 'foo: ${NONE:-default}' x = 'foo: default' assert x == config_instance._interpolate(string, os.environ, None) def test_interpolate_default_variable(patched_logger_critical, config_instance): string = 'foo: ${NONE:-$HOME}' x = 'foo: {}'.format(os.environ['HOME']) assert x == config_instance._interpolate(string, os.environ, None) def test_interpolate_curly_default_variable(patched_logger_critical, config_instance): string = 'foo: ${NONE-$HOME}' x = 'foo: {}'.format(os.environ['HOME']) assert x == config_instance._interpolate(string, os.environ, None) def test_interpolate_raises_on_failed_interpolation( patched_logger_critical, config_instance ): string = '$6$8I5Cfmpr$kGZB' with pytest.raises(SystemExit) as e: config_instance._interpolate(string, os.environ, None) assert 1 == e.value.code msg = ( "parsing config file '{}'.\n\n" 'Invalid placeholder in string: line 1, col 1\n' '$6$8I5Cfmpr$kGZB' ).format(config_instance.molecule_file) patched_logger_critical.assert_called_once_with(msg) def test_get_defaults(config_instance, mocker): mocker.patch.object( config_instance, 'molecule_file', '/path/to/test_scenario_name/molecule.yml' ) defaults = config_instance._get_defaults() assert defaults['scenario']['name'] == 'test_scenario_name' def test_preflight(mocker, config_instance, patched_logger_info): m = mocker.patch('molecule.model.schema_v2.pre_validate') m.return_value = None config_instance._preflight('foo') m.assert_called_once_with('foo', os.environ, config.MOLECULE_KEEP_STRING) def test_preflight_exists_when_validation_fails( mocker, patched_logger_critical, config_instance ): m = mocker.patch('molecule.model.schema_v2.pre_validate') m.return_value = 'validation errors' with pytest.raises(SystemExit) as e: config_instance._preflight('invalid stream') assert 1 == e.value.code msg = 'Failed to validate.\n\nvalidation errors' patched_logger_critical.assert_called_once_with(msg) def test_validate(mocker, config_instance, patched_logger_info, patched_logger_success): m = mocker.patch('molecule.model.schema_v2.validate') m.return_value = None config_instance._validate() msg = 'Validating schema {}.'.format(config_instance.molecule_file) patched_logger_info.assert_called_once_with(msg) m.assert_called_once_with(config_instance.config) msg = 'Validation completed successfully.' patched_logger_success.assert_called_once_with(msg) def test_validate_exists_when_validation_fails( mocker, patched_logger_critical, config_instance ): m = mocker.patch('molecule.model.schema_v2.validate') m.return_value = 'validation errors' with pytest.raises(SystemExit) as e: config_instance._validate() assert 1 == e.value.code msg = 'Failed to validate.\n\nvalidation errors' patched_logger_critical.assert_called_once_with(msg) def test_molecule_directory(): assert '/foo/bar/molecule' == config.molecule_directory('/foo/bar') def test_molecule_file(): assert '/foo/bar/molecule.yml' == config.molecule_file('/foo/bar') def test_set_env_from_file(config_instance): config_instance.args = {'env_file': '.env'} contents = {'foo': 'bar', 'BAZ': 'zzyzx'} env_file = config_instance.args.get('env_file') util.write_file(env_file, util.safe_dump(contents)) env = config.set_env_from_file({}, env_file) assert contents == env def test_set_env_from_file_returns_original_env_when_env_file_not_found( config_instance ): env = config.set_env_from_file({}, 'file-not-found') assert {} == env def test_write_config(config_instance): config_instance.write() assert os.path.isfile(config_instance.config_file)
1
10,305
And how is that related?
ansible-community-molecule
py
@@ -55,7 +55,8 @@ func AdminAddOrUpdateRemoteCluster(c *cli.Context) { defer cancel() _, err := adminClient.AddOrUpdateRemoteCluster(ctx, &adminservice.AddOrUpdateRemoteClusterRequest{ - FrontendAddress: getRequiredOption(c, FlagFrontendAddressWithAlias), + FrontendAddress: c.String(FlagFrontendAddressWithAlias), + EnableRemoteClusterConnection: c.BoolT(FlagConnectionEnableAlias), }) if err != nil { ErrorAndExit("Operation AddOrUpdateRemoteCluster failed.", err)
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 cli import ( "github.com/urfave/cli" "go.temporal.io/server/api/adminservice/v1" ) // AdminDescribeCluster is used to dump information about the cluster func AdminDescribeCluster(c *cli.Context) { adminClient := cFactory.AdminClient(c) ctx, cancel := newContext(c) defer cancel() clusterName := c.String(FlagCluster) response, err := adminClient.DescribeCluster(ctx, &adminservice.DescribeClusterRequest{ ClusterName: clusterName, }) if err != nil { ErrorAndExit("Operation DescribeCluster failed.", err) } prettyPrintJSONObject(response) } // AdminAddOrUpdateRemoteCluster is used to add or update remote cluster information func AdminAddOrUpdateRemoteCluster(c *cli.Context) { adminClient := cFactory.AdminClient(c) ctx, cancel := newContext(c) defer cancel() _, err := adminClient.AddOrUpdateRemoteCluster(ctx, &adminservice.AddOrUpdateRemoteClusterRequest{ FrontendAddress: getRequiredOption(c, FlagFrontendAddressWithAlias), }) if err != nil { ErrorAndExit("Operation AddOrUpdateRemoteCluster failed.", err) } } // AdminRemoveRemoteCluster is used to remove remote cluster information from the cluster func AdminRemoveRemoteCluster(c *cli.Context) { adminClient := cFactory.AdminClient(c) ctx, cancel := newContext(c) defer cancel() clusterName := getRequiredOption(c, FlagCluster) _, err := adminClient.RemoveRemoteCluster(ctx, &adminservice.RemoveRemoteClusterRequest{ ClusterName: clusterName, }) if err != nil { ErrorAndExit("Operation RemoveRemoteCluster failed.", err) } }
1
13,420
this should be required
temporalio-temporal
go
@@ -18,6 +18,7 @@ import com.google.api.codegen.SnippetSetRunner; import com.google.auto.value.AutoValue; import java.util.List; import javax.annotation.Nullable; +import javax.validation.constraints.Null; @AutoValue public abstract class DynamicLangXApiView implements ViewModel {
1
/* Copyright 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. */ package com.google.api.codegen.viewmodel; import com.google.api.codegen.SnippetSetRunner; import com.google.auto.value.AutoValue; import java.util.List; import javax.annotation.Nullable; @AutoValue public abstract class DynamicLangXApiView implements ViewModel { public abstract String templateFileName(); public abstract FileHeaderView fileHeader(); public abstract String protoFilename(); public abstract ServiceDocView doc(); public abstract String name(); public abstract String serviceAddress(); public abstract Integer servicePort(); public abstract String serviceTitle(); public abstract Iterable<String> authScopes(); public abstract List<PathTemplateView> pathTemplates(); public abstract List<FormatResourceFunctionView> formatResourceFunctions(); public abstract List<ParseResourceFunctionView> parseResourceFunctions(); public boolean hasFormatOrParseResourceFunctions() { return formatResourceFunctions().size() > 0 || parseResourceFunctions().size() > 0; } public abstract List<PathTemplateGetterFunctionView> pathTemplateGetterFunctions(); public abstract List<PageStreamingDescriptorView> pageStreamingDescriptors(); @Nullable public abstract List<BatchingDescriptorView> batchingDescriptors(); public abstract List<LongRunningOperationDetailView> longRunningDescriptors(); public abstract List<GrpcStreamingDetailView> grpcStreamingDescriptors(); public abstract List<String> methodKeys(); public abstract String clientConfigPath(); public abstract String interfaceKey(); public abstract String grpcClientTypeName(); public abstract List<GrpcStubView> stubs(); public abstract String outputPath(); public abstract List<ApiMethodView> apiMethods(); public abstract boolean hasPageStreamingMethods(); public abstract boolean hasBatchingMethods(); public abstract boolean hasLongRunningOperations(); public boolean hasGrpcStreamingMethods() { return grpcStreamingDescriptors().size() > 0; } public abstract boolean hasDefaultServiceAddress(); public abstract boolean hasDefaultServiceScopes(); public boolean missingDefaultServiceAddress() { return !hasDefaultServiceAddress(); } public boolean missingDefaultServiceScopes() { return !hasDefaultServiceScopes(); } public boolean hasMissingDefaultOptions() { return missingDefaultServiceAddress() || missingDefaultServiceScopes(); } public abstract String toolkitVersion(); @Nullable public abstract String packageVersion(); public abstract boolean packageHasMultipleServices(); @Nullable public abstract String packageServiceName(); @Nullable public abstract List<String> validDescriptorsNames(); @Nullable public abstract String constructorName(); public abstract boolean isGcloud(); /** * The name of the class that controls the credentials information of an api. It is currently only * used by Ruby. */ @Nullable public abstract String fullyQualifiedCredentialsClassName(); @Nullable public abstract String servicePhraseName(); @Nullable public abstract String gapicPackageName(); @Override public String resourceRoot() { return SnippetSetRunner.SNIPPET_RESOURCE_ROOT; } public static Builder newBuilder() { return new AutoValue_DynamicLangXApiView.Builder() .isGcloud(false) .packageHasMultipleServices(false); } @AutoValue.Builder public abstract static class Builder { public abstract Builder templateFileName(String val); public abstract Builder fileHeader(FileHeaderView val); public abstract Builder protoFilename(String simpleName); public abstract Builder doc(ServiceDocView doc); public abstract Builder name(String val); public abstract Builder serviceAddress(String val); public abstract Builder servicePort(Integer val); public abstract Builder serviceTitle(String val); public abstract Builder authScopes(Iterable<String> val); public abstract Builder pathTemplates(List<PathTemplateView> val); public abstract Builder formatResourceFunctions(List<FormatResourceFunctionView> val); public abstract Builder parseResourceFunctions(List<ParseResourceFunctionView> val); public abstract Builder pathTemplateGetterFunctions(List<PathTemplateGetterFunctionView> val); public abstract Builder pageStreamingDescriptors(List<PageStreamingDescriptorView> val); public abstract Builder batchingDescriptors(List<BatchingDescriptorView> val); public abstract Builder longRunningDescriptors(List<LongRunningOperationDetailView> val); public abstract Builder grpcStreamingDescriptors(List<GrpcStreamingDetailView> val); public abstract Builder methodKeys(List<String> val); public abstract Builder clientConfigPath(String val); public abstract Builder interfaceKey(String val); public abstract Builder grpcClientTypeName(String val); public abstract Builder stubs(List<GrpcStubView> val); public abstract Builder outputPath(String val); public abstract Builder apiMethods(List<ApiMethodView> val); public abstract Builder hasPageStreamingMethods(boolean val); public abstract Builder hasBatchingMethods(boolean val); public abstract Builder hasLongRunningOperations(boolean val); public abstract Builder hasDefaultServiceAddress(boolean val); public abstract Builder hasDefaultServiceScopes(boolean val); public abstract Builder toolkitVersion(String val); public abstract Builder packageVersion(String val); public abstract Builder packageHasMultipleServices(boolean val); /** The name of the property of the api export that exports this service. Used in Node.js. */ public abstract Builder packageServiceName(String val); public abstract Builder validDescriptorsNames(List<String> strings); public abstract Builder constructorName(String val); public abstract Builder isGcloud(boolean val); public abstract Builder fullyQualifiedCredentialsClassName(String val); public abstract Builder servicePhraseName(String val); public abstract Builder gapicPackageName(String val); public abstract DynamicLangXApiView build(); } }
1
23,586
This appears to be unused
googleapis-gapic-generator
java
@@ -63,6 +63,19 @@ public class SnapshotUtil { return ancestorIds(table.currentSnapshot(), table::snapshot); } + /** + * Traverses the history of the table's state and finds the oldest Snapshot. + * @return null if the table is empty, else the oldest Snapshot. + */ + public static Snapshot oldestSnapshot(Table table) { + Snapshot current = table.currentSnapshot(); + while (current != null && current.parentId() != null) { + current = table.snapshot(current.parentId()); + } + + return current; + } + /** * Returns list of snapshot ids in the range - (fromSnapshotId, toSnapshotId] * <p>
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.util; import java.util.List; import java.util.function.Function; import org.apache.iceberg.DataFile; import org.apache.iceberg.Snapshot; import org.apache.iceberg.Table; import org.apache.iceberg.exceptions.ValidationException; import org.apache.iceberg.relocated.com.google.common.collect.Iterables; import org.apache.iceberg.relocated.com.google.common.collect.Lists; public class SnapshotUtil { private SnapshotUtil() { } /** * Returns whether ancestorSnapshotId is an ancestor of snapshotId. */ public static boolean ancestorOf(Table table, long snapshotId, long ancestorSnapshotId) { Snapshot current = table.snapshot(snapshotId); while (current != null) { long id = current.snapshotId(); if (ancestorSnapshotId == id) { return true; } else if (current.parentId() != null) { current = table.snapshot(current.parentId()); } else { return false; } } return false; } /** * Return the snapshot IDs for the ancestors of the current table state. * <p> * Ancestor IDs are ordered by commit time, descending. The first ID is the current snapshot, followed by its parent, * and so on. * * @param table a {@link Table} * @return a set of snapshot IDs of the known ancestor snapshots, including the current ID */ public static List<Long> currentAncestors(Table table) { return ancestorIds(table.currentSnapshot(), table::snapshot); } /** * Returns list of snapshot ids in the range - (fromSnapshotId, toSnapshotId] * <p> * This method assumes that fromSnapshotId is an ancestor of toSnapshotId. */ public static List<Long> snapshotIdsBetween(Table table, long fromSnapshotId, long toSnapshotId) { List<Long> snapshotIds = Lists.newArrayList(ancestorIds(table.snapshot(toSnapshotId), snapshotId -> snapshotId != fromSnapshotId ? table.snapshot(snapshotId) : null)); return snapshotIds; } public static List<Long> ancestorIds(Snapshot snapshot, Function<Long, Snapshot> lookup) { List<Long> ancestorIds = Lists.newArrayList(); Snapshot current = snapshot; while (current != null) { ancestorIds.add(current.snapshotId()); if (current.parentId() != null) { current = lookup.apply(current.parentId()); } else { current = null; } } return ancestorIds; } public static List<DataFile> newFiles(Long baseSnapshotId, long latestSnapshotId, Function<Long, Snapshot> lookup) { List<DataFile> newFiles = Lists.newArrayList(); Long currentSnapshotId = latestSnapshotId; while (currentSnapshotId != null && !currentSnapshotId.equals(baseSnapshotId)) { Snapshot currentSnapshot = lookup.apply(currentSnapshotId); if (currentSnapshot == null) { throw new ValidationException( "Cannot determine history between read snapshot %s and current %s", baseSnapshotId, currentSnapshotId); } Iterables.addAll(newFiles, currentSnapshot.addedFiles()); currentSnapshotId = currentSnapshot.parentId(); } return newFiles; } }
1
38,183
I think that "table's state" isn't clear enough. How about "history of the table's current snapshot" like the one below?
apache-iceberg
java
@@ -457,3 +457,17 @@ instr_is_exclusive_store(instr_t *instr) } return false; } + +DR_API +bool +instr_is_scatter(instr_t *instr) +{ + return false; +} + +DR_API +bool +instr_is_gather(instr_t *instr) +{ + return false; +}
1
/* ********************************************************** * Copyright (c) 2017 Google, Inc. All rights reserved. * Copyright (c) 2016 ARM Limited. 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 ARM Limited 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 ARM LIMITED 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 "../globals.h" #include "instr.h" #include "decode.h" #include "opcode_names.h" bool instr_set_isa_mode(instr_t *instr, dr_isa_mode_t mode) { return (mode == DR_ISA_ARM_A64); } dr_isa_mode_t instr_get_isa_mode(instr_t *instr) { return DR_ISA_ARM_A64; } int instr_length_arch(dcontext_t *dcontext, instr_t *instr) { if (instr_get_opcode(instr) == OP_LABEL) return 0; if (instr_get_opcode(instr) == OP_ldstex) { ASSERT(instr->length != 0); return instr->length; } ASSERT(instr_get_opcode(instr) != OP_ldstex); return AARCH64_INSTR_SIZE; } bool opc_is_not_a_real_memory_load(int opc) { return (opc == OP_adr || opc == OP_adrp); } uint instr_branch_type(instr_t *cti_instr) { int opcode = instr_get_opcode(cti_instr); switch (opcode) { case OP_b: case OP_bcond: case OP_cbnz: case OP_cbz: case OP_tbnz: case OP_tbz: return LINK_DIRECT | LINK_JMP; case OP_bl: return LINK_DIRECT | LINK_CALL; case OP_blr: return LINK_INDIRECT | LINK_CALL; case OP_br: return LINK_INDIRECT | LINK_JMP; case OP_ret: return LINK_INDIRECT | LINK_RETURN; } CLIENT_ASSERT(false, "instr_branch_type: unknown opcode"); return LINK_INDIRECT; } const char * get_opcode_name(int opc) { return opcode_names[opc]; } bool instr_is_mov(instr_t *instr) { ASSERT_NOT_IMPLEMENTED(false); /* FIXME i#1569 */ return false; } bool instr_is_call_arch(instr_t *instr) { int opc = instr->opcode; /* caller ensures opcode is valid */ return (opc == OP_bl || opc == OP_blr); } bool instr_is_call_direct(instr_t *instr) { int opc = instr_get_opcode(instr); return (opc == OP_bl); } bool instr_is_near_call_direct(instr_t *instr) { int opc = instr_get_opcode(instr); return (opc == OP_bl); } bool instr_is_call_indirect(instr_t *instr) { int opc = instr_get_opcode(instr); return (opc == OP_blr); } bool instr_is_return(instr_t *instr) { int opc = instr_get_opcode(instr); return (opc == OP_ret); } bool instr_is_cbr_arch(instr_t *instr) { int opc = instr->opcode; /* caller ensures opcode is valid */ return (opc == OP_bcond || /* clang-format: keep */ opc == OP_cbnz || opc == OP_cbz || /* clang-format: keep */ opc == OP_tbnz || opc == OP_tbz); } bool instr_is_mbr_arch(instr_t *instr) { int opc = instr->opcode; /* caller ensures opcode is valid */ return (opc == OP_blr || opc == OP_br || opc == OP_ret); } bool instr_is_far_cti(instr_t *instr) { return false; } bool instr_is_ubr_arch(instr_t *instr) { int opc = instr->opcode; /* caller ensures opcode is valid */ return (opc == OP_b); } bool instr_is_near_ubr(instr_t *instr) { return instr_is_ubr(instr); } bool instr_is_cti_short(instr_t *instr) { /* The branch with smallest reach is TBNZ/TBZ, with range +/- 32 KiB. * We have restricted MAX_FRAGMENT_SIZE on AArch64 accordingly. */ return false; } bool instr_is_cti_loop(instr_t *instr) { return false; } bool instr_is_cti_short_rewrite(instr_t *instr, byte *pc) { return false; } bool instr_is_interrupt(instr_t *instr) { int opc = instr_get_opcode(instr); return (opc == OP_svc); } bool instr_is_syscall(instr_t *instr) { int opc = instr_get_opcode(instr); return (opc == OP_svc); } bool instr_is_mov_constant(instr_t *instr, ptr_int_t *value) { uint opc = instr_get_opcode(instr); /* We include several instructions that an assembler might generate for * "MOV reg, #imm", but not EOR or SUB or other instructions that could * in theory be used to generate a zero, nor "MOV reg, wzr/xzr" (for now). */ /* movn/movz reg, imm */ if (opc == OP_movn || opc == OP_movz) { opnd_t op = instr_get_src(instr, 0); if (opnd_is_immed_int(op)) { ptr_int_t imm = opnd_get_immed_int(op); *value = (opc == OP_movn ? ~imm : imm); return true; } else return false; } /* orr/add/sub reg, xwr/xzr, imm */ if (opc == OP_orr || opc == OP_add || opc == OP_sub) { opnd_t reg = instr_get_src(instr, 0); opnd_t imm = instr_get_src(instr, 1); if (opnd_is_reg(reg) && (opnd_get_reg(reg) == DR_REG_WZR || opnd_get_reg(reg) == DR_REG_XZR) && opnd_is_immed_int(imm)) { *value = opnd_get_immed_int(imm); return true; } else return false; } return false; } bool instr_is_prefetch(instr_t *instr) { /* FIXME i#1569: NYI */ return false; } bool instr_is_string_op(instr_t *instr) { return false; } bool instr_is_rep_string_op(instr_t *instr) { return false; } bool instr_saves_float_pc(instr_t *instr) { return false; } /* Is this an instruction that we must intercept in order to detect a * self-modifying program? */ bool instr_is_icache_op(instr_t *instr) { int opc = instr_get_opcode(instr); #define SYS_ARG_IC_IVAU 0x1ba9 if (opc == OP_sys && opnd_get_immed_int(instr_get_src(instr, 0)) == SYS_ARG_IC_IVAU) return true; /* ic ivau, xT */ if (opc == OP_isb) return true; /* isb */ return false; } bool instr_is_undefined(instr_t *instr) { /* FIXME i#1569: Without a complete decoder we cannot recognise all * unallocated encodings, but for testing purposes we can recognise * some of them: blocks at the top and bottom of the encoding space. */ if (instr_opcode_valid(instr) && instr_get_opcode(instr) == OP_xx) { uint enc = opnd_get_immed_int(instr_get_src(instr, 0)); return ((enc & 0x18000000) == 0 || (~enc & 0xde000000) == 0); } return false; } void instr_invert_cbr(instr_t *instr) { ASSERT_NOT_IMPLEMENTED(false); /* FIXME i#1569 */ } bool instr_cbr_taken(instr_t *instr, priv_mcontext_t *mc, bool pre) { ASSERT_NOT_IMPLEMENTED(false); /* FIXME i#1569 */ return false; } bool instr_predicate_reads_srcs(dr_pred_type_t pred) { ASSERT_NOT_IMPLEMENTED(false); /* FIXME i#1569 */ return false; } bool instr_predicate_writes_eflags(dr_pred_type_t pred) { return false; } bool instr_predicate_is_cond(dr_pred_type_t pred) { return pred != DR_PRED_NONE && pred != DR_PRED_AL && pred != DR_PRED_NV; } bool reg_is_gpr(reg_id_t reg) { return (DR_REG_X0 <= reg && reg <= DR_REG_WSP); } bool reg_is_simd(reg_id_t reg) { return (DR_REG_Q0 <= reg && reg <= DR_REG_B31); } bool reg_is_opmask(reg_id_t reg) { return false; } bool reg_is_bnd(reg_id_t reg) { return false; } bool reg_is_strictly_zmm(reg_id_t reg) { return false; } bool reg_is_ymm(reg_id_t reg) { /* i#1312: check why this assertion is here and not * in the other x86 related reg_is_ functions. */ ASSERT_NOT_IMPLEMENTED(false); /* FIXME i#1569 */ return false; } bool reg_is_strictly_ymm(reg_id_t reg) { return false; } bool reg_is_xmm(reg_id_t reg) { return false; } bool reg_is_strictly_xmm(reg_id_t reg) { return false; } bool reg_is_mmx(reg_id_t reg) { return false; } bool instr_is_opmask(instr_t *instr) { return false; } bool reg_is_fp(reg_id_t reg) { ASSERT_NOT_IMPLEMENTED(false); /* FIXME i#1569 */ return false; } bool instr_is_nop(instr_t *instr) { uint opc = instr_get_opcode(instr); return (opc == OP_nop); } bool opnd_same_sizes_ok(opnd_size_t s1, opnd_size_t s2, bool is_reg) { return (s1 == s2); } instr_t * instr_create_nbyte_nop(dcontext_t *dcontext, uint num_bytes, bool raw) { ASSERT_NOT_IMPLEMENTED(false); /* FIXME i#1569 */ return NULL; } bool instr_reads_thread_register(instr_t *instr) { return (instr_get_opcode(instr) == OP_mrs && opnd_is_reg(instr_get_src(instr, 0)) && opnd_get_reg(instr_get_src(instr, 0)) == DR_REG_TPIDR_EL0); } bool instr_writes_thread_register(instr_t *instr) { return (instr_get_opcode(instr) == OP_msr && instr_num_dsts(instr) == 1 && opnd_is_reg(instr_get_dst(instr, 0)) && opnd_get_reg(instr_get_dst(instr, 0)) == DR_REG_TPIDR_EL0); } DR_API bool instr_is_exclusive_store(instr_t *instr) { switch (instr_get_opcode(instr)) { case OP_stlxp: case OP_stlxr: case OP_stlxrb: case OP_stlxrh: case OP_stxp: case OP_stxr: case OP_stxrb: case OP_stxrh: return true; } return false; }
1
18,983
This looks like a bug: pretty sure there are scatter-gather instructions on AArch64. Ditto below.
DynamoRIO-dynamorio
c
@@ -55,9 +55,10 @@ func Mux(pattern string, mux *http.ServeMux) InboundOption { // sharing this transport. func (t *Transport) NewInbound(addr string, opts ...InboundOption) *Inbound { i := &Inbound{ - once: sync.Once(), - addr: addr, - tracer: t.tracer, + once: sync.Once(), + addr: addr, + tracer: t.tracer, + transport: t, } for _, opt := range opts { opt(i)
1
// Copyright (c) 2017 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 http import ( "net" "net/http" "go.uber.org/yarpc/api/transport" "go.uber.org/yarpc/internal/errors" "go.uber.org/yarpc/internal/introspection" intnet "go.uber.org/yarpc/internal/net" "go.uber.org/yarpc/internal/sync" "github.com/opentracing/opentracing-go" ) // InboundOption customizes the behavior of an HTTP Inbound constructed with // NewInbound. type InboundOption func(*Inbound) func (InboundOption) httpOption() {} // Mux specifies that the HTTP server should make the YARPC endpoint available // under the given pattern on the given ServeMux. By default, the YARPC // service is made available on all paths of the HTTP server. By specifying a // ServeMux, users can narrow the endpoints under which the YARPC service is // available and offer their own non-YARPC endpoints. func Mux(pattern string, mux *http.ServeMux) InboundOption { return func(i *Inbound) { i.mux = mux i.muxPattern = pattern } } // NewInbound builds a new HTTP inbound that listens on the given address and // sharing this transport. func (t *Transport) NewInbound(addr string, opts ...InboundOption) *Inbound { i := &Inbound{ once: sync.Once(), addr: addr, tracer: t.tracer, } for _, opt := range opts { opt(i) } return i } // Inbound receives YARPC requests using an HTTP server. It may be constructed // using the NewInbound method on the Transport. type Inbound struct { addr string mux *http.ServeMux muxPattern string server *intnet.HTTPServer router transport.Router tracer opentracing.Tracer once sync.LifecycleOnce } // Tracer configures a tracer on this inbound. func (i *Inbound) Tracer(tracer opentracing.Tracer) *Inbound { i.tracer = tracer return i } // SetRouter configures a router to handle incoming requests. // This satisfies the transport.Inbound interface, and would be called // by a dispatcher when it starts. func (i *Inbound) SetRouter(router transport.Router) { i.router = router } // Transports returns the inbound's HTTP transport. func (i *Inbound) Transports() []transport.Transport { // TODO factor out transport and return it here. return []transport.Transport{} } // Start starts the inbound with a given service detail, opening a listening // socket. func (i *Inbound) Start() error { return i.once.Start(i.start) } func (i *Inbound) start() error { if i.router == nil { return errors.ErrNoRouter } var httpHandler http.Handler = handler{ router: i.router, tracer: i.tracer, } if i.mux != nil { i.mux.Handle(i.muxPattern, httpHandler) httpHandler = i.mux } i.server = intnet.NewHTTPServer(&http.Server{ Addr: i.addr, Handler: httpHandler, }) if err := i.server.ListenAndServe(); err != nil { return err } i.addr = i.server.Listener().Addr().String() // in case it changed return nil } // Stop the inbound, closing the listening socket. func (i *Inbound) Stop() error { return i.once.Stop(i.stop) } func (i *Inbound) stop() error { if i.server == nil { return nil } return i.server.Stop() } // IsRunning returns whether the inbound is currently running func (i *Inbound) IsRunning() bool { return i.once.IsRunning() } // Addr returns the address on which the server is listening. Returns nil if // Start has not been called yet. func (i *Inbound) Addr() net.Addr { if i.server == nil { return nil } listener := i.server.Listener() if listener == nil { return nil } return listener.Addr() } // Introspect returns the state of the inbound for introspection purposes. func (i *Inbound) Introspect() introspection.InboundStatus { state := "Stopped" if i.IsRunning() { state = "Started" } return introspection.InboundStatus{ Transport: "http", Endpoint: i.Addr().String(), State: state, } }
1
13,177
No need to change this: id love if we changed as a team to unkeyed fields, it ends up catching a lot more at compile time, at minimal cost
yarpc-yarpc-go
go
@@ -105,6 +105,11 @@ func (m LBFargateManifest) DockerfilePath() string { return m.Image.Build } +// AppName returns the name of the application +func (m LBFargateManifest) AppName() string { + return m.Name +} + // EnvConf returns the application configuration with environment overrides. // If the environment passed in does not have any overrides then we return the default values. func (m *LBFargateManifest) EnvConf(envName string) LBFargateConfig {
1
// Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package manifest import ( "bytes" "text/template" "github.com/aws/amazon-ecs-cli-v2/templates" ) // LBFargateManifest holds the configuration to build a container image with an exposed port that receives // requests through a load balancer with AWS Fargate as the compute engine. type LBFargateManifest struct { AppManifest `yaml:",inline"` Image ImageWithPort `yaml:",flow"` LBFargateConfig `yaml:",inline"` Environments map[string]LBFargateConfig `yaml:",flow"` // Fields to override per environment. } // ImageWithPort represents a container image with an exposed port. type ImageWithPort struct { AppImage `yaml:",inline"` Port int `yaml:"port"` } // LBFargateConfig represents a load balanced web application with AWS Fargate as compute. type LBFargateConfig struct { RoutingRule `yaml:"http,flow"` ContainersConfig `yaml:",inline"` Scaling *AutoScalingConfig `yaml:",flow"` } // ContainersConfig represents the resource boundaries and environment variables for the containers in the service. type ContainersConfig struct { CPU int `yaml:"cpu"` Memory int `yaml:"memory"` Count int `yaml:"count"` Variables map[string]string `yaml:"variables"` Secrets map[string]string `yaml:"secrets"` } // RoutingRule holds the path to route requests to the service. type RoutingRule struct { Path string `yaml:"path"` } // AutoScalingConfig is the configuration to scale the service with target tracking scaling policies. type AutoScalingConfig struct { MinCount int `yaml:"minCount"` MaxCount int `yaml:"maxCount"` TargetCPU float64 `yaml:"targetCPU"` TargetMemory float64 `yaml:"targetMemory"` } // NewLoadBalancedFargateManifest creates a new public load balanced web service with an exposed port of 80, receives // all the requests from the load balancer and has a single task with minimal CPU and Memory thresholds. func NewLoadBalancedFargateManifest(appName string, dockerfile string) *LBFargateManifest { return &LBFargateManifest{ AppManifest: AppManifest{ Name: appName, Type: LoadBalancedWebApplication, }, Image: ImageWithPort{ AppImage: AppImage{ Build: dockerfile, }, Port: 80, }, LBFargateConfig: LBFargateConfig{ RoutingRule: RoutingRule{ Path: "*", }, ContainersConfig: ContainersConfig{ CPU: 256, Memory: 512, Count: 1, }, }, } } // Marshal serializes the manifest object into a YAML document. func (m *LBFargateManifest) Marshal() ([]byte, error) { box := templates.Box() content, err := box.FindString("lb-fargate-service/manifest.yml") if err != nil { return nil, err } tpl, err := template.New("template").Parse(content) if err != nil { return nil, err } var buf bytes.Buffer if err := tpl.Execute(&buf, *m); err != nil { return nil, err } return buf.Bytes(), nil } // DockerfilePath returns the image build path. func (m LBFargateManifest) DockerfilePath() string { return m.Image.Build } // EnvConf returns the application configuration with environment overrides. // If the environment passed in does not have any overrides then we return the default values. func (m *LBFargateManifest) EnvConf(envName string) LBFargateConfig { if _, ok := m.Environments[envName]; !ok { return m.LBFargateConfig } // We don't want to modify the default settings, so deep copy into a "conf" variable. envVars := make(map[string]string, len(m.Variables)) for k, v := range m.Variables { envVars[k] = v } secrets := make(map[string]string, len(m.Secrets)) for k, v := range m.Secrets { secrets[k] = v } var scaling *AutoScalingConfig if m.Scaling != nil { scaling = &AutoScalingConfig{ MinCount: m.Scaling.MinCount, MaxCount: m.Scaling.MaxCount, TargetCPU: m.Scaling.TargetCPU, TargetMemory: m.Scaling.TargetMemory, } } conf := LBFargateConfig{ RoutingRule: RoutingRule{ Path: m.Path, }, ContainersConfig: ContainersConfig{ CPU: m.CPU, Memory: m.Memory, Count: m.Count, Variables: envVars, Secrets: secrets, }, Scaling: scaling, } // Override with fields set in the environment. target := m.Environments[envName] if target.RoutingRule.Path != "" { conf.RoutingRule.Path = target.RoutingRule.Path } if target.CPU != 0 { conf.CPU = target.CPU } if target.Memory != 0 { conf.Memory = target.Memory } if target.Count != 0 { conf.Count = target.Count } for k, v := range target.Variables { conf.Variables[k] = v } for k, v := range target.Secrets { conf.Secrets[k] = v } if target.Scaling != nil { if conf.Scaling == nil { conf.Scaling = &AutoScalingConfig{} } if target.Scaling.MinCount != 0 { conf.Scaling.MinCount = target.Scaling.MinCount } if target.Scaling.MaxCount != 0 { conf.Scaling.MaxCount = target.Scaling.MaxCount } if target.Scaling.TargetCPU != 0 { conf.Scaling.TargetCPU = target.Scaling.TargetCPU } if target.Scaling.TargetMemory != 0 { conf.Scaling.TargetMemory = target.Scaling.TargetMemory } } return conf } // CFNTemplate serializes the manifest object into a CloudFormation template. func (m *LBFargateManifest) CFNTemplate() (string, error) { return "", nil }
1
11,284
Should this be in the parent struct? `AppManifest` since it's embedded to `LBFargateManifest` it'll get the method as well.
aws-copilot-cli
go
@@ -18,7 +18,12 @@ package openvpn import ( + "bufio" + "bytes" "errors" + log "github.com/cihub/seelog" + "io" + "net/textproto" "os/exec" "strconv" "syscall"
1
/* * Copyright (C) 2017 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 openvpn import ( "errors" "os/exec" "strconv" "syscall" ) // CheckOpenvpnBinary function checks that openvpn is available, given path to openvpn binary func CheckOpenvpnBinary(openvpnBinary string) error { process := NewProcess(openvpnBinary, "[openvpn binary check] ") if err := process.Start([]string{"--version"}); err != nil { return err } cmdResult := process.Wait() exitCode, err := extractExitCodeFromCmdResult(cmdResult) if err != nil { return err } //openvpn returns exit code 1 in case of --version parameter, if anything else is returned - treat as error if exitCode != 1 { return errors.New("unexpected openvpn code: " + strconv.Itoa(exitCode)) } return nil } //given error value from cmd.Wait() extract exit code if possible, otherwise returns error itself //this is ugly but there is no standart and os independent way to extract exit status in golang func extractExitCodeFromCmdResult(cmdResult error) (int, error) { exitError, ok := cmdResult.(*exec.ExitError) if !ok { return 0, cmdResult } exitStatus, ok := exitError.Sys().(syscall.WaitStatus) if !ok { return 0, cmdResult } return exitStatus.ExitStatus(), nil }
1
11,305
"Openvpn check" we could move this to separate prefix.
mysteriumnetwork-node
go
@@ -380,8 +380,15 @@ class RemoteConnection(object): # Authorization header headers["Authorization"] = "Basic %s" % auth - self._conn.request(method, parsed_url.path, data, headers) - resp = self._conn.getresponse() + if body and method != 'POST' and method != 'PUT': + body = None + try: + self._conn.request(method, parsed_url.path, body, headers) + resp = self._conn.getresponse() + except httplib.HTTPException: + self._conn.close() + raise + statuscode = resp.status statusmessage = resp.msg LOGGER.debug('%s %s' % (statuscode, statusmessage))
1
# Copyright 2008-2009 WebDriver committers # Copyright 2008-2009 Google Inc. # Copyright 2013 BrowserStack # # 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. import logging import socket import string import base64 try: import http.client as httplib except ImportError: import httplib as httplib try: from urllib import request as url_request except ImportError: import urllib2 as url_request try: from urllib import parse except ImportError: import urlparse as parse from .command import Command from .errorhandler import ErrorCode from . import utils LOGGER = logging.getLogger(__name__) class Request(url_request.Request): """ Extends the url_request.Request to support all HTTP request types. """ def __init__(self, url, data=None, method=None): """ Initialise a new HTTP request. :Args: - url - String for the URL to send the request to. - data - Data to send with the request. """ if method is None: method = data is not None and 'POST' or 'GET' elif method != 'POST' and method != 'PUT': data = None self._method = method url_request.Request.__init__(self, url, data=data) def get_method(self): """ Returns the HTTP method used by this request. """ return self._method class Response(object): """ Represents an HTTP response. """ def __init__(self, fp, code, headers, url): """ Initialise a new Response. :Args: - fp - The response body file object. - code - The HTTP status code returned by the server. - headers - A dictionary of headers returned by the server. - url - URL of the retrieved resource represented by this Response. """ self.fp = fp self.read = fp.read self.code = code self.headers = headers self.url = url def close(self): """ Close the response body file object. """ self.read = None self.fp = None def info(self): """ Returns the response headers. """ return self.headers def geturl(self): """ Returns the URL for the resource returned in this response. """ return self.url class HttpErrorHandler(url_request.HTTPDefaultErrorHandler): """ A custom HTTP error handler. Used to return Response objects instead of raising an HTTPError exception. """ def http_error_default(self, req, fp, code, msg, headers): """ Default HTTP error handler. :Args: - req - The original Request object. - fp - The response body file object. - code - The HTTP status code returned by the server. - msg - The HTTP status message returned by the server. - headers - The response headers. :Returns: A new Response object. """ return Response(fp, code, headers, req.get_full_url()) class RemoteConnection(object): """ A connection with the Remote WebDriver server. Communicates with the server using the WebDriver wire protocol: http://code.google.com/p/selenium/wiki/JsonWireProtocol """ def __init__(self, remote_server_addr): # Attempt to resolve the hostname and get an IP address. parsed_url = parse.urlparse(remote_server_addr) addr = "" if parsed_url.hostname: try: netloc = socket.gethostbyname(parsed_url.hostname) addr = netloc if parsed_url.port: netloc += ':%d' % parsed_url.port if parsed_url.username: auth = parsed_url.username if parsed_url.password: auth += ':%s' % parsed_url.password netloc = '%s@%s' % (auth, netloc) remote_server_addr = parse.urlunparse( (parsed_url.scheme, netloc, parsed_url.path, parsed_url.params, parsed_url.query, parsed_url.fragment)) except socket.gaierror: LOGGER.info('Could not get IP address for host: %s' % parsed_url.hostname) self._url = remote_server_addr self._conn = httplib.HTTPConnection(str(addr), str(parsed_url.port)) self._commands = { Command.STATUS: ('GET', '/status'), Command.NEW_SESSION: ('POST', '/session'), Command.GET_ALL_SESSIONS: ('GET', '/sessions'), Command.QUIT: ('DELETE', '/session/$sessionId'), Command.GET_CURRENT_WINDOW_HANDLE: ('GET', '/session/$sessionId/window_handle'), Command.GET_WINDOW_HANDLES: ('GET', '/session/$sessionId/window_handles'), Command.GET: ('POST', '/session/$sessionId/url'), Command.GO_FORWARD: ('POST', '/session/$sessionId/forward'), Command.GO_BACK: ('POST', '/session/$sessionId/back'), Command.REFRESH: ('POST', '/session/$sessionId/refresh'), Command.EXECUTE_SCRIPT: ('POST', '/session/$sessionId/execute'), Command.GET_CURRENT_URL: ('GET', '/session/$sessionId/url'), Command.GET_TITLE: ('GET', '/session/$sessionId/title'), Command.GET_PAGE_SOURCE: ('GET', '/session/$sessionId/source'), Command.SCREENSHOT: ('GET', '/session/$sessionId/screenshot'), Command.SET_BROWSER_VISIBLE: ('POST', '/session/$sessionId/visible'), Command.IS_BROWSER_VISIBLE: ('GET', '/session/$sessionId/visible'), Command.FIND_ELEMENT: ('POST', '/session/$sessionId/element'), Command.FIND_ELEMENTS: ('POST', '/session/$sessionId/elements'), Command.GET_ACTIVE_ELEMENT: ('POST', '/session/$sessionId/element/active'), Command.FIND_CHILD_ELEMENT: ('POST', '/session/$sessionId/element/$id/element'), Command.FIND_CHILD_ELEMENTS: ('POST', '/session/$sessionId/element/$id/elements'), Command.CLICK_ELEMENT: ('POST', '/session/$sessionId/element/$id/click'), Command.CLEAR_ELEMENT: ('POST', '/session/$sessionId/element/$id/clear'), Command.SUBMIT_ELEMENT: ('POST', '/session/$sessionId/element/$id/submit'), Command.GET_ELEMENT_TEXT: ('GET', '/session/$sessionId/element/$id/text'), Command.SEND_KEYS_TO_ELEMENT: ('POST', '/session/$sessionId/element/$id/value'), Command.SEND_KEYS_TO_ACTIVE_ELEMENT: ('POST', '/session/$sessionId/keys'), Command.UPLOAD_FILE: ('POST', "/session/$sessionId/file"), Command.GET_ELEMENT_VALUE: ('GET', '/session/$sessionId/element/$id/value'), Command.GET_ELEMENT_TAG_NAME: ('GET', '/session/$sessionId/element/$id/name'), Command.IS_ELEMENT_SELECTED: ('GET', '/session/$sessionId/element/$id/selected'), Command.SET_ELEMENT_SELECTED: ('POST', '/session/$sessionId/element/$id/selected'), Command.IS_ELEMENT_ENABLED: ('GET', '/session/$sessionId/element/$id/enabled'), Command.IS_ELEMENT_DISPLAYED: ('GET', '/session/$sessionId/element/$id/displayed'), Command.GET_ELEMENT_LOCATION: ('GET', '/session/$sessionId/element/$id/location'), Command.GET_ELEMENT_LOCATION_ONCE_SCROLLED_INTO_VIEW: ('GET', '/session/$sessionId/element/$id/location_in_view'), Command.GET_ELEMENT_SIZE: ('GET', '/session/$sessionId/element/$id/size'), Command.GET_ELEMENT_ATTRIBUTE: ('GET', '/session/$sessionId/element/$id/attribute/$name'), Command.ELEMENT_EQUALS: ('GET', '/session/$sessionId/element/$id/equals/$other'), Command.GET_ALL_COOKIES: ('GET', '/session/$sessionId/cookie'), Command.ADD_COOKIE: ('POST', '/session/$sessionId/cookie'), Command.DELETE_ALL_COOKIES: ('DELETE', '/session/$sessionId/cookie'), Command.DELETE_COOKIE: ('DELETE', '/session/$sessionId/cookie/$name'), Command.SWITCH_TO_FRAME: ('POST', '/session/$sessionId/frame'), Command.SWITCH_TO_WINDOW: ('POST', '/session/$sessionId/window'), Command.CLOSE: ('DELETE', '/session/$sessionId/window'), Command.GET_ELEMENT_VALUE_OF_CSS_PROPERTY: ('GET', '/session/$sessionId/element/$id/css/$propertyName'), Command.IMPLICIT_WAIT: ('POST', '/session/$sessionId/timeouts/implicit_wait'), Command.EXECUTE_ASYNC_SCRIPT: ('POST', '/session/$sessionId/execute_async'), Command.SET_SCRIPT_TIMEOUT: ('POST', '/session/$sessionId/timeouts/async_script'), Command.SET_TIMEOUTS: ('POST', '/session/$sessionId/timeouts'), Command.DISMISS_ALERT: ('POST', '/session/$sessionId/dismiss_alert'), Command.ACCEPT_ALERT: ('POST', '/session/$sessionId/accept_alert'), Command.SET_ALERT_VALUE: ('POST', '/session/$sessionId/alert_text'), Command.GET_ALERT_TEXT: ('GET', '/session/$sessionId/alert_text'), Command.CLICK: ('POST', '/session/$sessionId/click'), Command.DOUBLE_CLICK: ('POST', '/session/$sessionId/doubleclick'), Command.MOUSE_DOWN: ('POST', '/session/$sessionId/buttondown'), Command.MOUSE_UP: ('POST', '/session/$sessionId/buttonup'), Command.MOVE_TO: ('POST', '/session/$sessionId/moveto'), Command.GET_WINDOW_SIZE: ('GET', '/session/$sessionId/window/$windowHandle/size'), Command.SET_WINDOW_SIZE: ('POST', '/session/$sessionId/window/$windowHandle/size'), Command.GET_WINDOW_POSITION: ('GET', '/session/$sessionId/window/$windowHandle/position'), Command.SET_WINDOW_POSITION: ('POST', '/session/$sessionId/window/$windowHandle/position'), Command.MAXIMIZE_WINDOW: ('POST', '/session/$sessionId/window/$windowHandle/maximize'), Command.SET_SCREEN_ORIENTATION: ('POST', '/session/$sessionId/orientation'), Command.GET_SCREEN_ORIENTATION: ('GET', '/session/$sessionId/orientation'), Command.SINGLE_TAP: ('POST', '/session/$sessionId/touch/click'), Command.TOUCH_DOWN: ('POST', '/session/$sessionId/touch/down'), Command.TOUCH_UP: ('POST', '/session/$sessionId/touch/up'), Command.TOUCH_MOVE: ('POST', '/session/$sessionId/touch/move'), Command.TOUCH_SCROLL: ('POST', '/session/$sessionId/touch/scroll'), Command.DOUBLE_TAP: ('POST', '/session/$sessionId/touch/doubleclick'), Command.LONG_PRESS: ('POST', '/session/$sessionId/touch/longclick'), Command.FLICK: ('POST', '/session/$sessionId/touch/flick'), Command.EXECUTE_SQL: ('POST', '/session/$sessionId/execute_sql'), Command.GET_LOCATION: ('GET', '/session/$sessionId/location'), Command.SET_LOCATION: ('POST', '/session/$sessionId/location'), Command.GET_APP_CACHE: ('GET', '/session/$sessionId/application_cache'), Command.GET_APP_CACHE_STATUS: ('GET', '/session/$sessionId/application_cache/status'), Command.CLEAR_APP_CACHE: ('DELETE', '/session/$sessionId/application_cache/clear'), Command.IS_BROWSER_ONLINE: ('GET', '/session/$sessionId/browser_connection'), Command.SET_BROWSER_ONLINE: ('POST', '/session/$sessionId/browser_connection'), Command.GET_LOCAL_STORAGE_ITEM: ('GET', '/session/$sessionId/local_storage/key/$key'), Command.REMOVE_LOCAL_STORAGE_ITEM: ('DELETE', '/session/$sessionId/local_storage/key/$key'), Command.GET_LOCAL_STORAGE_KEYS: ('GET', '/session/$sessionId/local_storage'), Command.SET_LOCAL_STORAGE_ITEM: ('POST', '/session/$sessionId/local_storage'), Command.CLEAR_LOCAL_STORAGE: ('DELETE', '/session/$sessionId/local_storage'), Command.GET_LOCAL_STORAGE_SIZE: ('GET', '/session/$sessionId/local_storage/size'), Command.GET_SESSION_STORAGE_ITEM: ('GET', '/session/$sessionId/session_storage/key/$key'), Command.REMOVE_SESSION_STORAGE_ITEM: ('DELETE', '/session/$sessionId/session_storage/key/$key'), Command.GET_SESSION_STORAGE_KEYS: ('GET', '/session/$sessionId/session_storage'), Command.SET_SESSION_STORAGE_ITEM: ('POST', '/session/$sessionId/session_storage'), Command.CLEAR_SESSION_STORAGE: ('DELETE', '/session/$sessionId/session_storage'), Command.GET_SESSION_STORAGE_SIZE: ('GET', '/session/$sessionId/session_storage/size'), Command.GET_LOG: ('POST', '/session/$sessionId/log'), Command.GET_AVAILABLE_LOG_TYPES: ('GET', '/session/$sessionId/log/types'), } def execute(self, command, params): """ Send a command to the remote server. Any path subtitutions required for the URL mapped to the command should be included in the command parameters. :Args: - command - A string specifying the command to execute. - params - A dictionary of named parameters to send with the command as its JSON payload. """ command_info = self._commands[command] assert command_info is not None, 'Unrecognised command %s' % command data = utils.dump_json(params) path = string.Template(command_info[1]).substitute(params) url = '%s%s' % (self._url, path) return self._request(url, method=command_info[0], data=data) def _request(self, url, data=None, method=None): """ Send an HTTP request to the remote server. :Args: - method - A string for the HTTP method to send the request with. - url - The URL to send the request to. - body - The message body to send. :Returns: A dictionary with the server's parsed JSON response. """ LOGGER.debug('%s %s %s' % (method, url, data)) parsed_url = parse.urlparse(url) headers = {"Connection": "keep-alive", method: parsed_url.path, "User-Agent": "Python http auth", "Content-type": "application/json;charset=\"UTF-8\"", "Accept": "application/json"} # for basic auth if parsed_url.username: auth = base64.standard_b64encode('%s:%s' % (parsed_url.username, parsed_url.password)).replace('\n', '') # Authorization header headers["Authorization"] = "Basic %s" % auth self._conn.request(method, parsed_url.path, data, headers) resp = self._conn.getresponse() statuscode = resp.status statusmessage = resp.msg LOGGER.debug('%s %s' % (statuscode, statusmessage)) data = resp.read() try: if 399 < statuscode < 500: return {'status': statuscode, 'value': data} if 300 <= statuscode < 304: return self._request(resp.getheader('location'), method='GET') body = data.decode('utf-8').replace('\x00', '').strip() content_type = [] if resp.getheader('Content-Type') is not None: content_type = resp.getheader('Content-Type').split(';') if not any([x.startswith('image/png') for x in content_type]): try: data = utils.load_json(body.strip()) except ValueError: if 199 < statuscode < 300: status = ErrorCode.SUCCESS else: status = ErrorCode.UNKNOWN_ERROR return {'status': status, 'value': body.strip()} assert type(data) is dict, ( 'Invalid server response body: %s' % body) assert 'status' in data, ( 'Invalid server response; no status: %s' % body) # Some of the drivers incorrectly return a response # with no 'value' field when they should return null. if 'value' not in data: data['value'] = None return data else: data = {'status': 0, 'value': body.strip()} return data finally: LOGGER.debug("Finished Request") resp.close()
1
10,707
body is being used here for the first time without every being populated. This will error. To run tests do `./go clean test_py` and that will run the Firefox tests
SeleniumHQ-selenium
rb
@@ -42,8 +42,6 @@ void LookUpEdgeIndexProcessor::process(const cpp2::LookUpIndexRequest& req) { } else { this->pushResultCode(this->to(code), partId); } - this->onFinished(); - return; } });
1
/* Copyright (c) 2019 vesoft inc. All rights reserved. * * This source code is licensed under Apache 2.0 License, * attached with Common Clause Condition 1.0, found in the LICENSES directory. */ #include "LookUpEdgeIndexProcessor.h" namespace nebula { namespace storage { void LookUpEdgeIndexProcessor::process(const cpp2::LookUpIndexRequest& req) { /** * step 1 : prepare index meta and structure of return columns. */ auto ret = prepareRequest(req); if (ret != cpp2::ErrorCode::SUCCEEDED) { putResultCodes(ret, req.get_parts()); return; } /** * step 2 : build execution plan */ ret = buildExecutionPlan(req.get_filter()); if (ret != cpp2::ErrorCode::SUCCEEDED) { putResultCodes(ret, req.get_parts()); return; } /** * step 3 : execute index scan. */ std::for_each(req.get_parts().begin(), req.get_parts().end(), [&](auto& partId) { auto code = executeExecutionPlan(partId); if (code != kvstore::ResultCode::SUCCEEDED) { VLOG(1) << "Error! ret = " << static_cast<int32_t>(code) << ", spaceId = " << spaceId_ << ", partId = " << partId; if (code == kvstore::ResultCode::ERR_LEADER_CHANGED) { this->handleLeaderChanged(spaceId_, partId); } else { this->pushResultCode(this->to(code), partId); } this->onFinished(); return; } }); /** * step 4 : collect result. */ if (schema_ != nullptr) { decltype(resp_.schema) s; decltype(resp_.schema.columns) cols; for (auto i = 0; i < static_cast<int64_t>(schema_->getNumFields()); i++) { cols.emplace_back(columnDef(schema_->getFieldName(i), schema_->getFieldType(i).get_type())); } s.set_columns(std::move(cols)); this->resp_.set_schema(std::move(s)); } this->resp_.set_rows(std::move(edgeRows_)); this->onFinished(); } } // namespace storage } // namespace nebula
1
28,317
We don't return now?
vesoft-inc-nebula
cpp
@@ -18,7 +18,7 @@ module Travis end def install - uses_make? then: 'true', else: 'go get -d -v ./... && go build -v ./...', fold: 'install' + uses_make? then: 'true', else: 'go get -d -v ./... && go build -v ./...', fold: 'install', retry: true end def script
1
module Travis module Build class Script class Go < Script DEFAULTS = {} def export super set 'GOPATH', "#{HOME_DIR}/gopath" end def setup super cmd "mkdir -p $GOPATH/src/github.com/#{data.slug}" cmd "cp -r $TRAVIS_BUILD_DIR/ $GOPATH/src/github.com/#{data.slug}" set "TRAVIS_BUILD_DIR", "$GOPATH/src/github.com/#{data.slug}" cd "$GOPATH" end def install uses_make? then: 'true', else: 'go get -d -v ./... && go build -v ./...', fold: 'install' end def script uses_make? then: 'make', else: 'go test -v ./...' end private def uses_make?(*args) self.if '-f Makefile', *args end end end end end
1
10,634
This might end up not doing exactly what we want (the retry only picks up the `go get`, not the `go build`, due to the `&&`).
travis-ci-travis-build
rb
@@ -1,4 +1,4 @@ -// <copyright file="ConsoleExporterOptions.cs" company="OpenTelemetry Authors"> +// <copyright file="ConsoleExporterOptions.cs" company="OpenTelemetry Authors"> // Copyright The OpenTelemetry Authors // // Licensed under the Apache License, Version 2.0 (the "License");
1
// <copyright file="ConsoleExporterOptions.cs" company="OpenTelemetry Authors"> // 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. // </copyright> namespace OpenTelemetry.Exporter.Console { public class ConsoleExporterOptions { public bool Pretty { get; set; } } }
1
14,549
Is there a BOM change?
open-telemetry-opentelemetry-dotnet
.cs
@@ -142,8 +142,6 @@ public final class Const { public static final String REGISTRY_SERVICE_NAME = "SERVICECENTER"; - public static final String REGISTRY_VERSION = "3.0.0"; - public static final String APP_SERVICE_SEPARATOR = ":"; public static final String PATH_CHECKSESSION = "checksession";
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.serviceregistry.api; import io.servicecomb.serviceregistry.config.ServiceRegistryConfig; /** * Created by on 2017/1/9. */ public final class Const { private Const() { } public static final class REGISTRY_API { public static final String DOMAIN_NAME = ServiceRegistryConfig.INSTANCE.getDomainName(); public static final String CURRENT_VERSION = ServiceRegistryConfig.INSTANCE.getRegistryApiVersion(); // 2017-10-21 add new implementations for v4. We can remove v3 support after a period. public static final String VERSION_V3 = "v3"; public static final String LASTEST_API_VERSION = "v4"; public static final String V4_PREFIX = String.format("/v4/%s/registry", DOMAIN_NAME); public static final String MICROSERVICE_OPERATION_ALL; static { if (VERSION_V3.equals(CURRENT_VERSION)) { MICROSERVICE_OPERATION_ALL = "/registry/v3/microservices"; } else { MICROSERVICE_OPERATION_ALL = V4_PREFIX + "/microservices"; } } public static final String MICROSERVICE_OPERATION_ONE; static { if (VERSION_V3.equals(CURRENT_VERSION)) { MICROSERVICE_OPERATION_ONE = "/registry/v3/microservices/%s"; } else { MICROSERVICE_OPERATION_ONE = V4_PREFIX + "/microservices/%s"; } } public static final String MICROSERVICE_INSTANCE_OPERATION_ALL; static { if (VERSION_V3.equals(CURRENT_VERSION)) { MICROSERVICE_INSTANCE_OPERATION_ALL = "/registry/v3/microservices/%s/instances"; } else { MICROSERVICE_INSTANCE_OPERATION_ALL = V4_PREFIX + "/microservices/%s/instances"; } } public static final String MICROSERVICE_INSTANCE_OPERATION_ONE; static { if (VERSION_V3.equals(CURRENT_VERSION)) { MICROSERVICE_INSTANCE_OPERATION_ONE = "/registry/v3/microservices/%s/instances/%s"; } else { MICROSERVICE_INSTANCE_OPERATION_ONE = V4_PREFIX + "/microservices/%s/instances/%s"; } } public static final String MICROSERVICE_INSTANCES; static { if (VERSION_V3.equals(CURRENT_VERSION)) { MICROSERVICE_INSTANCES = "/registry/v3/instances"; } else { MICROSERVICE_INSTANCES = V4_PREFIX + "/instances"; } } public static final String MICROSERVICE_PROPERTIES; static { if (VERSION_V3.equals(CURRENT_VERSION)) { MICROSERVICE_PROPERTIES = "/registry/v3/microservices/%s/properties"; } else { MICROSERVICE_PROPERTIES = V4_PREFIX + "/microservices/%s/properties"; } } public static final String MICROSERVICE_INSTANCE_PROPERTIES; static { if (VERSION_V3.equals(CURRENT_VERSION)) { MICROSERVICE_INSTANCE_PROPERTIES = "/registry/v3/microservices/%s/instances/%s/properties"; } else { MICROSERVICE_INSTANCE_PROPERTIES = V4_PREFIX + "/microservices/%s/instances/%s/properties"; } } public static final String MICROSERVICE_HEARTBEAT; static { if (VERSION_V3.equals(CURRENT_VERSION)) { MICROSERVICE_HEARTBEAT = "/registry/v3/microservices/%s/instances/%s/heartbeat"; } else { MICROSERVICE_HEARTBEAT = V4_PREFIX + "/microservices/%s/instances/%s/heartbeat"; } } public static final String MICROSERVICE_EXISTENCE; static { if (VERSION_V3.equals(CURRENT_VERSION)) { MICROSERVICE_EXISTENCE = "/registry/v3/existence"; } else { MICROSERVICE_EXISTENCE = V4_PREFIX + "/existence"; } } public static final String MICROSERVICE_SCHEMA; static { if (VERSION_V3.equals(CURRENT_VERSION)) { MICROSERVICE_SCHEMA = "/registry/v3/microservices/%s/schemas/%s"; } else { MICROSERVICE_SCHEMA = V4_PREFIX + "/microservices/%s/schemas/%s"; } } public static final String MICROSERVICE_WATCH; static { if (VERSION_V3.equals(CURRENT_VERSION)) { MICROSERVICE_WATCH = "/registry/v3/microservices/%s/watcher"; } else { MICROSERVICE_WATCH = V4_PREFIX + "/microservices/%s/watcher"; } } } public static final String REGISTRY_APP_ID = "default"; public static final String REGISTRY_SERVICE_NAME = "SERVICECENTER"; public static final String REGISTRY_VERSION = "3.0.0"; public static final String APP_SERVICE_SEPARATOR = ":"; public static final String PATH_CHECKSESSION = "checksession"; public static final String URL_PREFIX = "urlPrefix"; }
1
7,235
It's not a good practise to delete the public static constant.
apache-servicecomb-java-chassis
java
@@ -467,13 +467,7 @@ func (eval *BlockEvaluator) transaction(txn transactions.SignedTxn, ad transacti return TransactionInLedgerError{txn.ID()} } - // Well-formed on its own? - err = txn.Txn.WellFormed(spec, eval.proto) - if err != nil { - return fmt.Errorf("transaction %v: malformed: %v", txn.ID(), err) - } - - // Properly signed? + // Well-formed and signed properly? if eval.txcache == nil || !eval.txcache.Verified(txn) { err = verify.TxnPool(&txn, spec, eval.proto, eval.verificationPool) if err != nil {
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 ledger import ( "context" "errors" "fmt" "github.com/algorand/go-algorand/config" "github.com/algorand/go-algorand/crypto" "github.com/algorand/go-algorand/data/basics" "github.com/algorand/go-algorand/data/bookkeeping" "github.com/algorand/go-algorand/data/committee" "github.com/algorand/go-algorand/data/transactions" "github.com/algorand/go-algorand/data/transactions/logic" "github.com/algorand/go-algorand/data/transactions/verify" "github.com/algorand/go-algorand/logging" "github.com/algorand/go-algorand/protocol" "github.com/algorand/go-algorand/util/execpool" ) // ErrNoSpace indicates insufficient space for transaction in block var ErrNoSpace = errors.New("block does not have space for transaction") // evalAux is left after removing explicit reward claims, // in case we need this infrastructure in the future. type evalAux struct { } // VerifiedTxnCache captures the interface for a cache of previously // verified transactions. This is expected to match the transaction // pool object. type VerifiedTxnCache interface { Verified(txn transactions.SignedTxn) bool } type roundCowBase struct { l ledgerForEvaluator // The round number of the previous block, for looking up prior state. rnd basics.Round // TxnCounter from previous block header. txnCount uint64 // The current protocol consensus params. proto config.ConsensusParams } func (x *roundCowBase) lookup(addr basics.Address) (basics.AccountData, error) { return x.l.LookupWithoutRewards(x.rnd, addr) } func (x *roundCowBase) isDup(firstValid basics.Round, txid transactions.Txid, txl txlease) (bool, error) { return x.l.isDup(x.proto, x.rnd+1, firstValid, x.rnd, txid, txl) } func (x *roundCowBase) txnCounter() uint64 { return x.txnCount } // wrappers for roundCowState to satisfy the (current) transactions.Balances interface func (cs *roundCowState) Get(addr basics.Address, withPendingRewards bool) (basics.BalanceRecord, error) { acctdata, err := cs.lookup(addr) if err != nil { return basics.BalanceRecord{}, err } if withPendingRewards { acctdata = acctdata.WithUpdatedRewards(cs.proto, cs.rewardsLevel()) } return basics.BalanceRecord{Addr: addr, AccountData: acctdata}, nil } func (cs *roundCowState) Put(record basics.BalanceRecord) error { olddata, err := cs.lookup(record.Addr) if err != nil { return err } cs.put(record.Addr, olddata, record.AccountData) return nil } func (cs *roundCowState) Move(from basics.Address, to basics.Address, amt basics.MicroAlgos, fromRewards *basics.MicroAlgos, toRewards *basics.MicroAlgos) error { rewardlvl := cs.rewardsLevel() fromBal, err := cs.lookup(from) if err != nil { return err } fromBalNew := fromBal.WithUpdatedRewards(cs.proto, rewardlvl) if fromRewards != nil { var ot basics.OverflowTracker newFromRewards := ot.AddA(*fromRewards, ot.SubA(fromBalNew.MicroAlgos, fromBal.MicroAlgos)) if ot.Overflowed { return fmt.Errorf("overflowed tracking of fromRewards for account %v: %d + (%d - %d)", from, *fromRewards, fromBalNew.MicroAlgos, fromBal.MicroAlgos) } *fromRewards = newFromRewards } var overflowed bool fromBalNew.MicroAlgos, overflowed = basics.OSubA(fromBalNew.MicroAlgos, amt) if overflowed { return fmt.Errorf("overspend (account %v, data %+v, tried to spend %v)", from, fromBal, amt) } cs.put(from, fromBal, fromBalNew) toBal, err := cs.lookup(to) if err != nil { return err } toBalNew := toBal.WithUpdatedRewards(cs.proto, rewardlvl) if toRewards != nil { var ot basics.OverflowTracker newToRewards := ot.AddA(*toRewards, ot.SubA(toBalNew.MicroAlgos, toBal.MicroAlgos)) if ot.Overflowed { return fmt.Errorf("overflowed tracking of toRewards for account %v: %d + (%d - %d)", to, *toRewards, toBalNew.MicroAlgos, toBal.MicroAlgos) } *toRewards = newToRewards } toBalNew.MicroAlgos, overflowed = basics.OAddA(toBalNew.MicroAlgos, amt) if overflowed { return fmt.Errorf("balance overflow (account %v, data %+v, was going to receive %v)", to, toBal, amt) } cs.put(to, toBal, toBalNew) return nil } func (cs *roundCowState) ConsensusParams() config.ConsensusParams { return cs.proto } // BlockEvaluator represents an in-progress evaluation of a block // against the ledger. type BlockEvaluator struct { state *roundCowState aux *evalAux validate bool generate bool txcache VerifiedTxnCache prevHeader bookkeeping.BlockHeader // cached proto config.ConsensusParams genesisHash crypto.Digest block bookkeeping.Block blockTxBytes int verificationPool execpool.BacklogPool } type ledgerForEvaluator interface { GenesisHash() crypto.Digest BlockHdr(basics.Round) (bookkeeping.BlockHeader, error) Lookup(basics.Round, basics.Address) (basics.AccountData, error) Totals(basics.Round) (AccountTotals, error) isDup(config.ConsensusParams, basics.Round, basics.Round, basics.Round, transactions.Txid, txlease) (bool, error) LookupWithoutRewards(basics.Round, basics.Address) (basics.AccountData, error) } // StartEvaluator creates a BlockEvaluator, given a ledger and a block header // of the block that the caller is planning to evaluate. func (l *Ledger) StartEvaluator(hdr bookkeeping.BlockHeader, txcache VerifiedTxnCache, executionPool execpool.BacklogPool) (*BlockEvaluator, error) { return startEvaluator(l, hdr, nil, true, true, txcache, executionPool) } func startEvaluator(l ledgerForEvaluator, hdr bookkeeping.BlockHeader, aux *evalAux, validate bool, generate bool, txcache VerifiedTxnCache, executionPool execpool.BacklogPool) (*BlockEvaluator, error) { proto, ok := config.Consensus[hdr.CurrentProtocol] if !ok { return nil, ProtocolError(hdr.CurrentProtocol) } if aux == nil { aux = &evalAux{} } base := &roundCowBase{ l: l, // round that lookups come from is previous block. We validate // the block at this round below, so underflow will be caught. // If we are not validating, we must have previously checked // an agreement.Certificate attesting that hdr is valid. rnd: hdr.Round - 1, proto: proto, } eval := &BlockEvaluator{ aux: aux, validate: validate, generate: generate, txcache: txcache, block: bookkeeping.Block{BlockHeader: hdr}, proto: proto, genesisHash: l.GenesisHash(), verificationPool: executionPool, } if hdr.Round > 0 { var err error eval.prevHeader, err = l.BlockHdr(base.rnd) if err != nil { return nil, fmt.Errorf("can't evaluate block %v without previous header: %v", hdr.Round, err) } base.txnCount = eval.prevHeader.TxnCounter } prevTotals, err := l.Totals(eval.prevHeader.Round) if err != nil { return nil, err } poolAddr := eval.prevHeader.RewardsPool incentivePoolData, err := l.Lookup(eval.prevHeader.Round, poolAddr) if err != nil { return nil, err } if generate { if eval.proto.SupportGenesisHash { eval.block.BlockHeader.GenesisHash = eval.genesisHash } eval.block.BlockHeader.RewardsState = eval.prevHeader.NextRewardsState(hdr.Round, proto, incentivePoolData.MicroAlgos, prevTotals.RewardUnits()) } // set the eval state with the current header eval.state = makeRoundCowState(base, eval.block.BlockHeader) if validate { err := eval.block.BlockHeader.PreCheck(eval.prevHeader) if err != nil { return nil, err } // Check that the rewards rate, level and residue match expected values expectedRewardsState := eval.prevHeader.NextRewardsState(hdr.Round, proto, incentivePoolData.MicroAlgos, prevTotals.RewardUnits()) if eval.block.RewardsState != expectedRewardsState { return nil, fmt.Errorf("bad rewards state: %+v != %+v", eval.block.RewardsState, expectedRewardsState) } // For backwards compatibility: introduce Genesis Hash value if eval.proto.SupportGenesisHash && eval.block.BlockHeader.GenesisHash != eval.genesisHash { return nil, fmt.Errorf("wrong genesis hash: %s != %s", eval.block.BlockHeader.GenesisHash, eval.genesisHash) } } // Withdraw rewards from the incentive pool var ot basics.OverflowTracker rewardsPerUnit := ot.Sub(eval.block.BlockHeader.RewardsLevel, eval.prevHeader.RewardsLevel) if ot.Overflowed { return nil, fmt.Errorf("overflowed subtracting rewards(%d, %d) levels for block %v", eval.block.BlockHeader.RewardsLevel, eval.prevHeader.RewardsLevel, hdr.Round) } poolOld, err := eval.state.Get(poolAddr, true) if err != nil { return nil, err } // hotfix for testnet stall 08/26/2019; move some algos from testnet bank to rewards pool to give it enough time until protocol upgrade occur. poolOld, err = eval.workaroundOverspentRewards(poolOld, hdr.Round) if err != nil { return nil, err } poolNew := poolOld poolNew.MicroAlgos = ot.SubA(poolOld.MicroAlgos, basics.MicroAlgos{Raw: ot.Mul(prevTotals.RewardUnits(), rewardsPerUnit)}) if ot.Overflowed { return nil, fmt.Errorf("overflowed subtracting reward unit for block %v", hdr.Round) } err = eval.state.Put(poolNew) if err != nil { return nil, err } // ensure that we have at least MinBalance after withdrawing rewards ot.SubA(poolNew.MicroAlgos, basics.MicroAlgos{Raw: proto.MinBalance}) if ot.Overflowed { // TODO this should never happen; should we panic here? return nil, fmt.Errorf("overflowed subtracting rewards for block %v", hdr.Round) } return eval, nil } // hotfix for testnet stall 08/26/2019; move some algos from testnet bank to rewards pool to give it enough time until protocol upgrade occur. func (eval *BlockEvaluator) workaroundOverspentRewards(rewardPoolBalance basics.BalanceRecord, headerRound basics.Round) (poolOld basics.BalanceRecord, err error) { // verify that we patch the correct round. if headerRound != 1499995 { return rewardPoolBalance, nil } // verify that we're patching the correct genesis ( i.e. testnet ) testnetGenesisHash, _ := crypto.DigestFromString("JBR3KGFEWPEE5SAQ6IWU6EEBZMHXD4CZU6WCBXWGF57XBZIJHIRA") if eval.genesisHash != testnetGenesisHash { return rewardPoolBalance, nil } // get the testnet bank ( dispenser ) account address. bankAddr, _ := basics.UnmarshalChecksumAddress("GD64YIY3TWGDMCNPP553DZPPR6LDUSFQOIJVFDPPXWEG3FVOJCCDBBHU5A") amount := basics.MicroAlgos{Raw: 20000000000} err = eval.state.Move(bankAddr, eval.prevHeader.RewardsPool, amount, nil, nil) if err != nil { err = fmt.Errorf("unable to move funds from testnet bank to incentive pool: %v", err) return } poolOld, err = eval.state.Get(eval.prevHeader.RewardsPool, true) return } // Round returns the round number of the block being evaluated by the BlockEvaluator. func (eval *BlockEvaluator) Round() basics.Round { return eval.block.Round() } // ResetTxnBytes resets the number of bytes tracked by the BlockEvaluator to // zero. This is a specialized operation used by the transaction pool to // simulate the effect of putting pending transactions in multiple blocks. func (eval *BlockEvaluator) ResetTxnBytes() { eval.blockTxBytes = 0 } // Transaction tentatively adds a new transaction as part of this block evaluation. // If the transaction cannot be added to the block without violating some constraints, // an error is returned and the block evaluator state is unchanged. func (eval *BlockEvaluator) Transaction(txn transactions.SignedTxn, ad transactions.ApplyData) error { return eval.transactionGroup([]transactions.SignedTxnWithAD{ transactions.SignedTxnWithAD{ SignedTxn: txn, ApplyData: ad, }, }, true) } // TransactionGroup tentatively adds a new transaction group as part of this block evaluation. // If the transaction group cannot be added to the block without violating some constraints, // an error is returned and the block evaluator state is unchanged. func (eval *BlockEvaluator) TransactionGroup(txads []transactions.SignedTxnWithAD) error { return eval.transactionGroup(txads, true) } // TestTransactionGroup checks if a given transaction group could be executed at this // point in the block evaluator, but does not actually add the transactions to the block // evaluator, or modify the block evaluator state in any other visible way. func (eval *BlockEvaluator) TestTransactionGroup(txgroup []transactions.SignedTxn) error { txads := make([]transactions.SignedTxnWithAD, len(txgroup)) for i := range txgroup { txads[i].SignedTxn = txgroup[i] } return eval.transactionGroup(txads, false) } // transactionGroup tentatively executes a group of transactions as part of this block evaluation. // If the transaction group cannot be added to the block without violating some constraints, // an error is returned and the block evaluator state is unchanged. If remember is true, // the transaction group is added to the block evaluator state; otherwise, the block evaluator // is not modified and does not remember this transaction group. func (eval *BlockEvaluator) transactionGroup(txgroup []transactions.SignedTxnWithAD, remember bool) error { // Nothing to do if there are no transactions. if len(txgroup) == 0 { return nil } if len(txgroup) > eval.proto.MaxTxGroupSize { return fmt.Errorf("group size %d exceeds maximum %d", len(txgroup), eval.proto.MaxTxGroupSize) } var txibs []transactions.SignedTxnInBlock var group transactions.TxGroup var groupTxBytes int cow := eval.state.child() for gi, txad := range txgroup { var txib transactions.SignedTxnInBlock err := eval.transaction(txad.SignedTxn, txad.ApplyData, txgroup, gi, cow, &txib) if err != nil { return err } txibs = append(txibs, txib) if eval.validate { groupTxBytes += len(protocol.Encode(txib)) if eval.blockTxBytes+groupTxBytes > eval.proto.MaxTxnBytesPerBlock { return ErrNoSpace } } // Make sure all transactions in group have the same group value if txad.SignedTxn.Txn.Group != txgroup[0].SignedTxn.Txn.Group { return fmt.Errorf("transactionGroup: inconsistent group values: %v != %v", txad.SignedTxn.Txn.Group, txgroup[0].SignedTxn.Txn.Group) } if !txad.SignedTxn.Txn.Group.IsZero() { txWithoutGroup := txad.SignedTxn.Txn txWithoutGroup.Group = crypto.Digest{} txWithoutGroup.ResetCaches() group.TxGroupHashes = append(group.TxGroupHashes, crypto.HashObj(txWithoutGroup)) } else if len(txgroup) > 1 { return fmt.Errorf("transactionGroup: [%d] had zero Group but was submitted in a group of %d", gi, len(txgroup)) } } // If we had a non-zero Group value, check that all group members are present. if group.TxGroupHashes != nil { if txgroup[0].SignedTxn.Txn.Group != crypto.HashObj(group) { return fmt.Errorf("transactionGroup: incomplete group: %v != %v (%v)", txgroup[0].SignedTxn.Txn.Group, crypto.HashObj(group), group) } } if remember { eval.block.Payset = append(eval.block.Payset, txibs...) eval.blockTxBytes += groupTxBytes cow.commitToParent() } return nil } // transaction tentatively executes a new transaction as part of this block evaluation. // If the transaction cannot be added to the block without violating some constraints, // an error is returned and the block evaluator state is unchanged. func (eval *BlockEvaluator) transaction(txn transactions.SignedTxn, ad transactions.ApplyData, txgroup []transactions.SignedTxnWithAD, groupIndex int, cow *roundCowState, txib *transactions.SignedTxnInBlock) error { var err error spec := transactions.SpecialAddresses{ FeeSink: eval.block.BlockHeader.FeeSink, RewardsPool: eval.block.BlockHeader.RewardsPool, } if eval.validate { // Transaction valid (not expired)? err = txn.Txn.Alive(eval.block) if err != nil { return err } // Transaction already in the ledger? txid := txn.ID() dup, err := cow.isDup(txn.Txn.First(), txid, txlease{sender: txn.Txn.Sender, lease: txn.Txn.Lease}) if err != nil { return err } if dup { return TransactionInLedgerError{txn.ID()} } // Well-formed on its own? err = txn.Txn.WellFormed(spec, eval.proto) if err != nil { return fmt.Errorf("transaction %v: malformed: %v", txn.ID(), err) } // Properly signed? if eval.txcache == nil || !eval.txcache.Verified(txn) { err = verify.TxnPool(&txn, spec, eval.proto, eval.verificationPool) if err != nil { return fmt.Errorf("transaction %v: failed to verify: %v", txn.ID(), err) } } // Verify that groups are supported. if !txn.Txn.Group.IsZero() && !eval.proto.SupportTxGroups { return fmt.Errorf("transaction groups not supported") } if !txn.Lsig.Blank() { recs := make([]basics.BalanceRecord, len(txgroup)) for i := range recs { var err error recs[i], err = cow.Get(txgroup[i].Txn.Sender, true) if err != nil { return fmt.Errorf("transaction %v: cannot get sender record: %v", txn.ID(), err) } } ep := logic.EvalParams{ Txn: &txn, Block: &eval.block, Proto: &eval.proto, TxnGroup: txgroup, GroupIndex: groupIndex, GroupSenders: recs, Seed: eval.prevHeader.Seed[:], MoreSeed: txid[:], } pass, err := logic.Eval(txn.Lsig.Logic, ep) if err != nil { return fmt.Errorf("transaction %v: rejected by logic err=%s", txn.ID(), err) } if !pass { return fmt.Errorf("transaction %v: rejected by logic", txn.ID()) } } } // Apply the transaction, updating the cow balances applyData, err := txn.Txn.Apply(cow, spec, cow.txnCounter()) if err != nil { return fmt.Errorf("transaction %v: %v", txn.ID(), err) } // Validate applyData if we are validating an existing block. // If we are validating and generating, we have no ApplyData yet. if eval.validate && !eval.generate { if eval.proto.ApplyData { if ad != applyData { return fmt.Errorf("transaction %v: applyData mismatch: %v != %v", txn.ID(), ad, applyData) } } else { if ad != (transactions.ApplyData{}) { return fmt.Errorf("transaction %v: applyData not supported", txn.ID()) } } } // Check if the transaction fits in the block, now that we can encode it. *txib, err = eval.block.EncodeSignedTxn(txn, applyData) if err != nil { return err } // Check if any affected accounts dipped below MinBalance (unless they are // completely zero, which means the account will be deleted.) rewardlvl := cow.rewardsLevel() for _, addr := range cow.modifiedAccounts() { data, err := cow.lookup(addr) if err != nil { return err } // It's always OK to have the account move to an empty state, // because the accounts DB can delete it. Otherwise, we will // enforce MinBalance. if data.IsZero() { continue } // Skip FeeSink and RewardsPool MinBalance checks here. // There's only two accounts, so space isn't an issue, and we don't // expect them to have low balances, but if they do, it may cause // surprises for every transaction. if addr == spec.FeeSink || addr == spec.RewardsPool { continue } dataNew := data.WithUpdatedRewards(eval.proto, rewardlvl) if dataNew.MicroAlgos.Raw < basics.MulSaturate(eval.proto.MinBalance, uint64(1+len(dataNew.Assets))) { return fmt.Errorf("transaction %v: account %v balance %d below min %d (%d assets)", txn.ID(), addr, dataNew.MicroAlgos.Raw, eval.proto.MinBalance, len(dataNew.Assets)) } } // Remember this txn cow.addTx(txn.Txn) return nil } // Call "endOfBlock" after all the block's rewards and transactions are processed. Applies any deferred balance updates. func (eval *BlockEvaluator) endOfBlock() error { if eval.generate { eval.block.TxnRoot = eval.block.Payset.Commit(eval.proto.PaysetCommitFlat) if eval.proto.TxnCounter { eval.block.TxnCounter = eval.state.txnCounter() } else { eval.block.TxnCounter = 0 } } return nil } // FinalValidation does the validation that must happen after the block is built and all state updates are computed func (eval *BlockEvaluator) finalValidation() error { if eval.validate { // check commitments txnRoot := eval.block.Payset.Commit(eval.proto.PaysetCommitFlat) if txnRoot != eval.block.TxnRoot { return fmt.Errorf("txn root wrong: %v != %v", txnRoot, eval.block.TxnRoot) } var expectedTxnCount uint64 if eval.proto.TxnCounter { expectedTxnCount = eval.state.txnCounter() } if eval.block.TxnCounter != expectedTxnCount { return fmt.Errorf("txn count wrong: %d != %d", eval.block.TxnCounter, expectedTxnCount) } } return nil } // GenerateBlock produces a complete block from the BlockEvaluator. This is // used during proposal to get an actual block that will be proposed, after // feeding in tentative transactions into this block evaluator. func (eval *BlockEvaluator) GenerateBlock() (*ValidatedBlock, error) { if !eval.generate { logging.Base().Panicf("GenerateBlock() called but generate is false") } err := eval.endOfBlock() if err != nil { return nil, err } err = eval.finalValidation() if err != nil { return nil, err } vb := ValidatedBlock{ blk: eval.block, delta: eval.state.mods, aux: *eval.aux, } return &vb, nil } func (l *Ledger) eval(ctx context.Context, blk bookkeeping.Block, aux *evalAux, validate bool, txcache VerifiedTxnCache, executionPool execpool.BacklogPool) (stateDelta, evalAux, error) { eval, err := startEvaluator(l, blk.BlockHeader, aux, validate, false, txcache, executionPool) if err != nil { return stateDelta{}, evalAux{}, err } // TODO: batch tx sig verification: ingest blk.Payset and output a list of ValidatedTx // Next, transactions paysetgroups, err := blk.DecodePaysetGroups() if err != nil { return stateDelta{}, evalAux{}, err } for _, txgroup := range paysetgroups { select { case <-ctx.Done(): return stateDelta{}, evalAux{}, ctx.Err() default: } err = eval.TransactionGroup(txgroup) if err != nil { return stateDelta{}, evalAux{}, err } } // Finally, procees any pending end-of-block state changes err = eval.endOfBlock() if err != nil { return stateDelta{}, evalAux{}, err } // If validating, do final block checks that depend on our new state if validate { err = eval.finalValidation() if err != nil { return stateDelta{}, evalAux{}, err } } return eval.state.mods, *eval.aux, nil } // Validate uses the ledger to validate block blk as a candidate next block. // It returns an error if blk is not the expected next block, or if blk is // not a valid block (e.g., it has duplicate transactions, overspends some // account, etc). func (l *Ledger) Validate(ctx context.Context, blk bookkeeping.Block, txcache VerifiedTxnCache, executionPool execpool.BacklogPool) (*ValidatedBlock, error) { delta, aux, err := l.eval(ctx, blk, nil, true, txcache, executionPool) if err != nil { return nil, err } vb := ValidatedBlock{ blk: blk, delta: delta, aux: aux, } return &vb, nil } // ValidatedBlock represents the result of a block validation. It can // be used to efficiently add the block to the ledger, without repeating // the work of applying the block's changes to the ledger state. type ValidatedBlock struct { blk bookkeeping.Block delta stateDelta aux evalAux } // Block returns the underlying Block for a ValidatedBlock. func (vb ValidatedBlock) Block() bookkeeping.Block { return vb.blk } // WithSeed returns a copy of the ValidatedBlock with a modified seed. func (vb ValidatedBlock) WithSeed(s committee.Seed) ValidatedBlock { newblock := vb.blk newblock.BlockHeader.Seed = s return ValidatedBlock{ blk: newblock, delta: vb.delta, aux: vb.aux, } }
1
36,476
I deleted this because `WellFormed` is immediately called by `verify.TxnPool` below. Can someone please double check this for me since it's... pretty important
algorand-go-algorand
go
@@ -70,6 +70,7 @@ setup( "kaitaistruct>=0.7,<0.9", "ldap3>=2.5,<2.6", "passlib>=1.6.5, <1.8", + "ply>=3.4, <3.12", "pyasn1>=0.3.1,<0.5", "pyOpenSSL>=17.5,<18.1", "pyparsing>=2.1.3, <2.3",
1
import os from codecs import open import re from setuptools import setup, find_packages # Based on https://github.com/pypa/sampleproject/blob/master/setup.py # and https://python-packaging-user-guide.readthedocs.org/ here = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() with open(os.path.join(here, "mitmproxy", "version.py")) as f: VERSION = re.search(r'VERSION = "(.+?)(?:-0x|")', f.read()).group(1) setup( name="mitmproxy", version=VERSION, description="An interactive, SSL-capable, man-in-the-middle HTTP proxy for penetration testers and software developers.", long_description=long_description, url="http://mitmproxy.org", author="Aldo Cortesi", author_email="[email protected]", license="MIT", classifiers=[ "License :: OSI Approved :: MIT License", "Development Status :: 5 - Production/Stable", "Environment :: Console", "Environment :: Console :: Curses", "Operating System :: MacOS :: MacOS X", "Operating System :: POSIX", "Operating System :: Microsoft :: Windows", "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: Implementation :: CPython", "Topic :: Security", "Topic :: Internet", "Topic :: Internet :: WWW/HTTP", "Topic :: Internet :: Proxy Servers", "Topic :: Software Development :: Testing" ], packages=find_packages(include=[ "mitmproxy", "mitmproxy.*", "pathod", "pathod.*", ]), include_package_data=True, entry_points={ 'console_scripts': [ "mitmproxy = mitmproxy.tools.main:mitmproxy", "mitmdump = mitmproxy.tools.main:mitmdump", "mitmweb = mitmproxy.tools.main:mitmweb", "pathod = pathod.pathod_cmdline:go_pathod", "pathoc = pathod.pathoc_cmdline:go_pathoc" ] }, # https://packaging.python.org/en/latest/requirements/#install-requires # It is not considered best practice to use install_requires to pin dependencies to specific versions. install_requires=[ "blinker>=1.4, <1.5", "brotlipy>=0.7.0,<0.8", "certifi>=2015.11.20.1", # no semver here - this should always be on the last release! "click>=6.2, <7", "cryptography>=2.1.4,<2.3", "h2>=3.0.1,<4", "hyperframe>=5.1.0,<6", "kaitaistruct>=0.7,<0.9", "ldap3>=2.5,<2.6", "passlib>=1.6.5, <1.8", "pyasn1>=0.3.1,<0.5", "pyOpenSSL>=17.5,<18.1", "pyparsing>=2.1.3, <2.3", "pyperclip>=1.6.0, <1.7", "ruamel.yaml>=0.13.2, <0.16", "sortedcontainers>=1.5.4,<2.1", "tornado>=4.3,<5.1", "urwid>=2.0.1,<2.1", "wsproto>=0.11.0,<0.12.0", ], extras_require={ ':sys_platform == "win32"': [ "pydivert>=2.0.3,<2.2", ], 'dev': [ "asynctest>=0.12.0", "flake8>=3.5, <3.6", "Flask>=1.0,<1.1", "mypy>=0.590,<0.591", "parver>=0.1,<2.0", "pytest-asyncio>=0.8", "pytest-cov>=2.5.1,<3", "pytest-faulthandler>=1.3.1,<2", "pytest-timeout>=1.2.1,<2", "pytest-xdist>=1.22,<2", "pytest>=3.3,<4", "requests>=2.9.1, <3", "tox>=3.0,<3.1", "rstcheck>=2.2, <4.0", ], 'examples': [ "beautifulsoup4>=4.4.1, <4.7" ] } )
1
14,145
Did you actually test this with ply 3.4? That release is pretty old (2011), so I think we can bump this to at least 3.6 (2015) or even 3.10 (2017)...
mitmproxy-mitmproxy
py
@@ -130,6 +130,12 @@ func (r *ReconcileHiveConfig) deployHive(hLog log.FieldLogger, h *resource.Helpe r.includeGlobalPullSecret(hLog, h, instance, hiveDeployment) + if instance.Spec.MaintenanceMode != nil && *instance.Spec.MaintenanceMode { + hLog.Warn("maintenanceMode enabled in HiveConfig, setting hive-controllers replicas to 0") + replicas := int32(0) + hiveDeployment.Spec.Replicas = &replicas + } + result, err := h.ApplyRuntimeObject(hiveDeployment, scheme.Scheme) if err != nil { hLog.WithError(err).Error("error applying deployment")
1
package hive import ( "bytes" "context" "crypto/md5" "fmt" "os" "strconv" log "github.com/sirupsen/logrus" hivev1 "github.com/openshift/hive/pkg/apis/hive/v1alpha1" "github.com/openshift/hive/pkg/constants" hiveconstants "github.com/openshift/hive/pkg/constants" "github.com/openshift/hive/pkg/controller/images" "github.com/openshift/hive/pkg/operator/assets" "github.com/openshift/hive/pkg/operator/util" "github.com/openshift/hive/pkg/resource" oappsv1 "github.com/openshift/api/apps/v1" "github.com/openshift/library-go/pkg/operator/events" "github.com/openshift/library-go/pkg/operator/resource/resourceread" appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/kubernetes/scheme" "sigs.k8s.io/controller-runtime/pkg/client" ) const ( dnsServersEnvVar = "ZONE_CHECK_DNS_SERVERS" // hiveAdditionalCASecret is the name of the secret in the hive namespace // that will contain the aggregate of all AdditionalCertificateAuthorities // secrets specified in HiveConfig hiveAdditionalCASecret = "hive-additional-ca" ) func (r *ReconcileHiveConfig) deployHive(hLog log.FieldLogger, h *resource.Helper, instance *hivev1.HiveConfig, recorder events.Recorder) error { asset := assets.MustAsset("config/manager/deployment.yaml") hLog.Debug("reading deployment") hiveDeployment := resourceread.ReadDeploymentV1OrDie(asset) hiveContainer := &hiveDeployment.Spec.Template.Spec.Containers[0] if r.hiveImage != "" { hiveContainer.Image = r.hiveImage hiveImageEnvVar := corev1.EnvVar{ Name: images.HiveImageEnvVar, Value: r.hiveImage, } hiveContainer.Env = append(hiveContainer.Env, hiveImageEnvVar) } if r.hiveImagePullPolicy != "" { hiveContainer.ImagePullPolicy = r.hiveImagePullPolicy hiveContainer.Env = append( hiveContainer.Env, corev1.EnvVar{ Name: images.HiveImagePullPolicyEnvVar, Value: string(r.hiveImagePullPolicy), }, ) } if e := instance.Spec.ExternalDNS; e != nil { switch { case e.AWS != nil: hiveContainer.Env = append( hiveContainer.Env, corev1.EnvVar{ Name: constants.ExternalDNSAWSCredsEnvVar, Value: e.AWS.Credentials.Name, }, ) case e.GCP != nil: hiveContainer.Env = append( hiveContainer.Env, corev1.EnvVar{ Name: constants.ExternalDNSGCPCredsEnvVar, Value: e.GCP.Credentials.Name, }, ) } addManagedDomainsVolume(&hiveDeployment.Spec.Template.Spec) } // By default we will try to gather logs on failed installs: logsEnvVar := corev1.EnvVar{ Name: constants.SkipGatherLogsEnvVar, Value: strconv.FormatBool(instance.Spec.FailedProvisionConfig.SkipGatherLogs), } hiveContainer.Env = append(hiveContainer.Env, logsEnvVar) if zoneCheckDNSServers := os.Getenv(dnsServersEnvVar); len(zoneCheckDNSServers) > 0 { dnsServersEnvVar := corev1.EnvVar{ Name: dnsServersEnvVar, Value: zoneCheckDNSServers, } hiveContainer.Env = append(hiveContainer.Env, dnsServersEnvVar) } if instance.Spec.Backup.Velero.Enabled { hLog.Infof("Velero Backup Enabled.") tmpEnvVar := corev1.EnvVar{ Name: hiveconstants.VeleroBackupEnvVar, Value: "true", } hiveContainer.Env = append(hiveContainer.Env, tmpEnvVar) } if instance.Spec.Backup.MinBackupPeriodSeconds != nil { hLog.Infof("MinBackupPeriodSeconds specified.") tmpEnvVar := corev1.EnvVar{ Name: hiveconstants.MinBackupPeriodSecondsEnvVar, Value: strconv.Itoa(*instance.Spec.Backup.MinBackupPeriodSeconds), } hiveContainer.Env = append(hiveContainer.Env, tmpEnvVar) } if err := r.includeAdditionalCAs(hLog, h, instance, hiveDeployment); err != nil { return err } r.includeGlobalPullSecret(hLog, h, instance, hiveDeployment) result, err := h.ApplyRuntimeObject(hiveDeployment, scheme.Scheme) if err != nil { hLog.WithError(err).Error("error applying deployment") return err } hLog.Infof("deployment applied (%s)", result) applyAssets := []string{ "config/manager/service.yaml", "config/rbac/hive_frontend_role.yaml", "config/rbac/hive_frontend_role_binding.yaml", "config/rbac/hive_frontend_serviceaccount.yaml", // Due to bug with OLM not updating CRDs on upgrades, we are re-applying // the latest in the operator to ensure updates roll out. // TODO: Attempt removing this once Hive is running purely on 4.x, // as it requires a significant privilege escalation we would rather // leave in the hands of OLM. "config/crds/hive_v1alpha1_checkpoint.yaml", "config/crds/hive_v1alpha1_clusterdeployment.yaml", "config/crds/hive_v1alpha1_clusterdeprovisionrequest.yaml", "config/crds/hive_v1alpha1_clusterimageset.yaml", "config/crds/hive_v1alpha1_clusterprovision.yaml", "config/crds/hive_v1alpha1_clusterstate.yaml", "config/crds/hive_v1alpha1_dnsendpoint.yaml", "config/crds/hive_v1alpha1_dnszone.yaml", "config/crds/hive_v1alpha1_hiveconfig.yaml", "config/crds/hive_v1alpha1_selectorsyncidentityprovider.yaml", "config/crds/hive_v1alpha1_selectorsyncset.yaml", "config/crds/hive_v1alpha1_syncidentityprovider.yaml", "config/crds/hive_v1alpha1_syncset.yaml", "config/crds/hive_v1alpha1_syncsetinstance.yaml", "config/configmaps/install-log-regexes-configmap.yaml", } // In very rare cases we use OpenShift specific types which will not apply if running on // vanilla Kubernetes. Detect this and skip if so. openshiftSpecificAssets := []string{ "config/rbac/hive_admin_role.yaml", "config/rbac/hive_admin_role_binding.yaml", "config/rbac/hive_reader_role.yaml", "config/rbac/hive_reader_role_binding.yaml", } for _, a := range applyAssets { err = util.ApplyAsset(h, a, hLog) if err != nil { return err } } if r.runningOnOpenShift(hLog) { hLog.Info("deploying OpenShift specific assets") for _, a := range openshiftSpecificAssets { err = util.ApplyAsset(h, a, hLog) if err != nil { return err } } } else { hLog.Warn("hive is not running on OpenShift, some optional assets will not be deployed") } // Remove legacy ClusterImageSets we do not want installable anymore. removeImageSets := []string{ "openshift-v4.0-beta3", "openshift-v4.0-beta4", "openshift-v4.0-latest", } for _, isName := range removeImageSets { clusterImageSet := &hivev1.ClusterImageSet{} err := r.Get(context.Background(), types.NamespacedName{Name: isName}, clusterImageSet) if err != nil && !errors.IsNotFound(err) { hLog.WithError(err).Error("error looking for obsolete ClusterImageSet") return err } else if err != nil { hLog.WithField("clusterImageSet", isName).Debug("legacy ClusterImageSet does not exist") } else { err = r.Delete(context.Background(), clusterImageSet) if err != nil { hLog.WithError(err).WithField("clusterImageSet", clusterImageSet).Error( "error deleting outdated ClusterImageSet") return err } hLog.WithField("clusterImageSet", isName).Info("deleted outdated ClusterImageSet") } } hLog.Info("all hive components successfully reconciled") return nil } func (r *ReconcileHiveConfig) includeAdditionalCAs(hLog log.FieldLogger, h *resource.Helper, instance *hivev1.HiveConfig, hiveDeployment *appsv1.Deployment) error { additionalCA := &bytes.Buffer{} for _, clientCARef := range instance.Spec.AdditionalCertificateAuthorities { caSecret := &corev1.Secret{} err := r.Get(context.TODO(), types.NamespacedName{Namespace: constants.HiveNamespace, Name: clientCARef.Name}, caSecret) if err != nil { hLog.WithError(err).WithField("secret", clientCARef.Name).Errorf("Cannot read client CA secret") continue } crt, ok := caSecret.Data["ca.crt"] if !ok { hLog.WithField("secret", clientCARef.Name).Warning("Secret does not contain expected key (ca.crt)") } fmt.Fprintf(additionalCA, "%s\n", crt) } if additionalCA.Len() == 0 { caSecret := &corev1.Secret{} err := r.Get(context.TODO(), types.NamespacedName{Namespace: constants.HiveNamespace, Name: hiveAdditionalCASecret}, caSecret) if err == nil { err = r.Delete(context.TODO(), caSecret) if err != nil { hLog.WithError(err).WithField("secret", fmt.Sprintf("%s/%s", constants.HiveNamespace, hiveAdditionalCASecret)). Error("cannot delete hive additional ca secret") return err } } return nil } caSecret := &corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ Namespace: constants.HiveNamespace, Name: hiveAdditionalCASecret, }, Data: map[string][]byte{ "ca.crt": additionalCA.Bytes(), }, } result, err := h.ApplyRuntimeObject(caSecret, scheme.Scheme) if err != nil { hLog.WithError(err).Error("error applying additional cert secret") return err } hLog.Infof("additional cert secret applied (%s)", result) // Generating a volume name with a hash based on the contents of the additional CA // secret will ensure that when there are changes to the secret, the hive controller // will be re-deployed. hash := fmt.Sprintf("%x", md5.Sum(additionalCA.Bytes())) volumeName := fmt.Sprintf("additionalca-%s", hash[:20]) hiveDeployment.Spec.Template.Spec.Volumes = append(hiveDeployment.Spec.Template.Spec.Volumes, corev1.Volume{ Name: volumeName, VolumeSource: corev1.VolumeSource{ Secret: &corev1.SecretVolumeSource{ SecretName: hiveAdditionalCASecret, }, }, }) hiveDeployment.Spec.Template.Spec.Containers[0].VolumeMounts = append(hiveDeployment.Spec.Template.Spec.Containers[0].VolumeMounts, corev1.VolumeMount{ Name: volumeName, MountPath: "/additional/ca", ReadOnly: true, }) hiveDeployment.Spec.Template.Spec.Containers[0].Env = append(hiveDeployment.Spec.Template.Spec.Containers[0].Env, corev1.EnvVar{ Name: "ADDITIONAL_CA", Value: "/additional/ca/ca.crt", }) return nil } func (r *ReconcileHiveConfig) includeGlobalPullSecret(hLog log.FieldLogger, h *resource.Helper, instance *hivev1.HiveConfig, hiveDeployment *appsv1.Deployment) { if instance.Spec.GlobalPullSecret == nil || instance.Spec.GlobalPullSecret.Name == "" { hLog.Debug("GlobalPullSecret is not provided in HiveConfig, it will not be deployed") return } globalPullSecretEnvVar := corev1.EnvVar{ Name: hiveconstants.GlobalPullSecret, Value: instance.Spec.GlobalPullSecret.Name, } hiveDeployment.Spec.Template.Spec.Containers[0].Env = append(hiveDeployment.Spec.Template.Spec.Containers[0].Env, globalPullSecretEnvVar) } func (r *ReconcileHiveConfig) runningOnOpenShift(hLog log.FieldLogger) bool { // DeploymentConfig is an OpenShift specific type we have go types vendored for, see // if we can list them to determine if we're running on OpenShift or vanilla Kube. dcs := &oappsv1.DeploymentConfigList{} err := r.List(context.Background(), dcs, client.InNamespace(constants.HiveNamespace)) if err != nil { hLog.WithError(err).Debug("error listing DeploymentConfig to determine if running on OpenShift") } return err == nil }
1
10,385
This can be simplified somewhat to `pointer.Int32Ptr(0)`. But it is not necessary.
openshift-hive
go
@@ -226,9 +226,7 @@ static bool checkBondStereo(const MCSBondCompareParameters& p, Bond::BondStereo bs1 = b1->getStereo(); Bond::BondStereo bs2 = b2->getStereo(); if (b1->getBondType() == Bond::DOUBLE && b2->getBondType() == Bond::DOUBLE) { - if ((bs1 == Bond::STEREOZ || bs1 == Bond::STEREOE) && - !(bs2 == Bond::STEREOZ || bs2 == Bond::STEREOE)) - return false; + if (bs1 > Bond::STEREOANY && !(bs2 > Bond::STEREOANY)) return false; } return true; }
1
// // Copyright (C) 2014 Novartis Institutes for BioMedical Research // // @@ All Rights Reserved @@ // This file is part of the RDKit. // The contents are covered by the terms of the BSD license // which is included in the file license.txt, found at the root // of the RDKit source tree. // #include <list> #include <algorithm> #include <math.h> #include <RDGeneral/BoostStartInclude.h> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> #include <RDGeneral/BoostEndInclude.h> #include <iostream> #include <sstream> #include "SubstructMatchCustom.h" #include "MaximumCommonSubgraph.h" namespace RDKit { void parseMCSParametersJSON(const char* json, MCSParameters* params) { if (params && json && 0 != strlen(json)) { std::istringstream ss; ss.str(json); boost::property_tree::ptree pt; boost::property_tree::read_json(ss, pt); RDKit::MCSParameters& p = *params; p.MaximizeBonds = pt.get<bool>("MaximizeBonds", p.MaximizeBonds); p.Threshold = pt.get<double>("Threshold", p.Threshold); p.Timeout = pt.get<unsigned>("Timeout", p.Timeout); p.AtomCompareParameters.MatchValences = pt.get<bool>("MatchValences", p.AtomCompareParameters.MatchValences); p.AtomCompareParameters.MatchChiralTag = pt.get<bool>("MatchChiralTag", p.AtomCompareParameters.MatchChiralTag); p.BondCompareParameters.RingMatchesRingOnly = pt.get<bool>( "RingMatchesRingOnly", p.BondCompareParameters.RingMatchesRingOnly); p.BondCompareParameters.CompleteRingsOnly = pt.get<bool>( "CompleteRingsOnly", p.BondCompareParameters.CompleteRingsOnly); p.BondCompareParameters.MatchStereo = pt.get<bool>("MatchStereo", p.BondCompareParameters.MatchStereo); std::string s = pt.get<std::string>("AtomCompare", "def"); if (0 == strcmp("Any", s.c_str())) p.AtomTyper = MCSAtomCompareAny; else if (0 == strcmp("Elements", s.c_str())) p.AtomTyper = MCSAtomCompareElements; else if (0 == strcmp("Isotopes", s.c_str())) p.AtomTyper = MCSAtomCompareIsotopes; s = pt.get<std::string>("BondCompare", "def"); if (0 == strcmp("Any", s.c_str())) p.BondTyper = MCSBondCompareAny; else if (0 == strcmp("Order", s.c_str())) p.BondTyper = MCSBondCompareOrder; else if (0 == strcmp("OrderExact", s.c_str())) p.BondTyper = MCSBondCompareOrderExact; p.InitialSeed = pt.get<std::string>("InitialSeed", ""); } } MCSResult findMCS(const std::vector<ROMOL_SPTR>& mols, const MCSParameters* params) { MCSParameters p; if (0 == params) params = &p; RDKit::FMCS::MaximumCommonSubgraph fmcs(params); return fmcs.find(mols); } MCSResult findMCS_P(const std::vector<ROMOL_SPTR>& mols, const char* params_json) { MCSParameters p; parseMCSParametersJSON(params_json, &p); return findMCS(mols, &p); } MCSResult findMCS(const std::vector<ROMOL_SPTR>& mols, bool maximizeBonds, double threshold, unsigned timeout, bool verbose, bool matchValences, bool ringMatchesRingOnly, bool completeRingsOnly, bool matchChiralTag, AtomComparator atomComp, BondComparator bondComp) { // AtomComparator atomComp=AtomCompareElements; // BondComparator bondComp=BondCompareOrder; MCSParameters* ps = new MCSParameters(); ps->MaximizeBonds = maximizeBonds; ps->Threshold = threshold; ps->Timeout = timeout; ps->Verbose = verbose; ps->AtomCompareParameters.MatchValences = matchValences; ps->AtomCompareParameters.MatchChiralTag = matchChiralTag; switch (atomComp) { case AtomCompareAny: ps->AtomTyper = MCSAtomCompareAny; break; case AtomCompareElements: ps->AtomTyper = MCSAtomCompareElements; break; case AtomCompareIsotopes: ps->AtomTyper = MCSAtomCompareIsotopes; break; } switch (bondComp) { case BondCompareAny: ps->BondTyper = MCSBondCompareAny; break; case BondCompareOrder: ps->BondTyper = MCSBondCompareOrder; break; case BondCompareOrderExact: ps->BondTyper = MCSBondCompareOrderExact; break; } ps->BondCompareParameters.RingMatchesRingOnly = ringMatchesRingOnly; ps->BondCompareParameters.CompleteRingsOnly = completeRingsOnly; MCSResult res = findMCS(mols, ps); delete ps; return res; } bool MCSProgressCallbackTimeout(const MCSProgressData& stat, const MCSParameters& params, void* userData) { RDUNUSED_PARAM(stat); unsigned long long* t0 = (unsigned long long*)userData; unsigned long long t = nanoClock(); return t - *t0 <= params.Timeout * 1000000ULL; } // PREDEFINED FUNCTORS: //=== ATOM COMPARE ======================================================== static bool checkAtomChirality(const MCSAtomCompareParameters& p, const ROMol& mol1, unsigned int atom1, const ROMol& mol2, unsigned int atom2) { RDUNUSED_PARAM(p); const Atom& a1 = *mol1.getAtomWithIdx(atom1); const Atom& a2 = *mol2.getAtomWithIdx(atom2); Atom::ChiralType ac1 = a1.getChiralTag(); Atom::ChiralType ac2 = a2.getChiralTag(); if (ac1 == Atom::CHI_TETRAHEDRAL_CW || ac1 == Atom::CHI_TETRAHEDRAL_CCW) { return (ac2 == Atom::CHI_TETRAHEDRAL_CW || ac2 == Atom::CHI_TETRAHEDRAL_CCW); } return true; } bool MCSAtomCompareAny(const MCSAtomCompareParameters& p, const ROMol& mol1, unsigned int atom1, const ROMol& mol2, unsigned int atom2, void*) { if (p.MatchChiralTag) return checkAtomChirality(p, mol1, atom1, mol2, atom2); return true; } bool MCSAtomCompareElements(const MCSAtomCompareParameters& p, const ROMol& mol1, unsigned int atom1, const ROMol& mol2, unsigned int atom2, void*) { const Atom& a1 = *mol1.getAtomWithIdx(atom1); const Atom& a2 = *mol2.getAtomWithIdx(atom2); if (a1.getAtomicNum() != a2.getAtomicNum()) return false; if (p.MatchValences && a1.getTotalValence() != a2.getTotalValence()) return false; if (p.MatchChiralTag) return checkAtomChirality(p, mol1, atom1, mol2, atom2); return true; } bool MCSAtomCompareIsotopes(const MCSAtomCompareParameters& p, const ROMol& mol1, unsigned int atom1, const ROMol& mol2, unsigned int atom2, void* ud) { RDUNUSED_PARAM(ud); // ignore everything except isotope information: // if( ! MCSAtomCompareElements (p, mol1, atom1, mol2, atom2, ud)) // return false; const Atom& a1 = *mol1.getAtomWithIdx(atom1); const Atom& a2 = *mol2.getAtomWithIdx(atom2); if (a1.getIsotope() != a2.getIsotope()) return false; if (p.MatchChiralTag) return checkAtomChirality(p, mol1, atom1, mol2, atom2); return true; } //=== BOND COMPARE ======================================================== class BondMatchOrderMatrix { bool MatchMatrix[Bond::ZERO + 1][Bond::ZERO + 1]; public: BondMatchOrderMatrix(bool ignoreAromatization) { memset(MatchMatrix, 0, sizeof(MatchMatrix)); for (size_t i = 0; i <= Bond::ZERO; i++) { // fill cells of the same and unspecified type MatchMatrix[i][i] = true; MatchMatrix[Bond::UNSPECIFIED][i] = MatchMatrix[i][Bond::UNSPECIFIED] = true; MatchMatrix[Bond::ZERO][i] = MatchMatrix[i][Bond::ZERO] = true; } if (ignoreAromatization) { MatchMatrix[Bond::SINGLE][Bond::AROMATIC] = MatchMatrix[Bond::AROMATIC][Bond::SINGLE] = true; MatchMatrix[Bond::SINGLE][Bond::ONEANDAHALF] = MatchMatrix[Bond::ONEANDAHALF][Bond::SINGLE] = true; MatchMatrix[Bond::DOUBLE][Bond::TWOANDAHALF] = MatchMatrix[Bond::TWOANDAHALF][Bond::DOUBLE] = true; MatchMatrix[Bond::TRIPLE][Bond::THREEANDAHALF] = MatchMatrix[Bond::THREEANDAHALF][Bond::TRIPLE] = true; MatchMatrix[Bond::QUADRUPLE][Bond::FOURANDAHALF] = MatchMatrix[Bond::FOURANDAHALF][Bond::QUADRUPLE] = true; MatchMatrix[Bond::QUINTUPLE][Bond::FIVEANDAHALF] = MatchMatrix[Bond::FIVEANDAHALF][Bond::QUINTUPLE] = true; } } inline bool isEqual(unsigned i, unsigned j) const { return MatchMatrix[i][j]; } }; static bool checkBondStereo(const MCSBondCompareParameters& p, const ROMol& mol1, unsigned int bond1, const ROMol& mol2, unsigned int bond2) { RDUNUSED_PARAM(p); const Bond* b1 = mol1.getBondWithIdx(bond1); const Bond* b2 = mol2.getBondWithIdx(bond2); Bond::BondStereo bs1 = b1->getStereo(); Bond::BondStereo bs2 = b2->getStereo(); if (b1->getBondType() == Bond::DOUBLE && b2->getBondType() == Bond::DOUBLE) { if ((bs1 == Bond::STEREOZ || bs1 == Bond::STEREOE) && !(bs2 == Bond::STEREOZ || bs2 == Bond::STEREOE)) return false; } return true; } static bool checkRingMatch(const MCSBondCompareParameters& p, const ROMol& mol1, unsigned int bond1, const ROMol& mol2, unsigned int bond2, void* v_ringMatchMatrixSet) { if (!v_ringMatchMatrixSet) throw "v_ringMatchMatrixSet is NULL"; // never FMCS::RingMatchTableSet* ringMatchMatrixSet = static_cast<FMCS::RingMatchTableSet*>(v_ringMatchMatrixSet); const std::vector<size_t>& ringsIdx1 = ringMatchMatrixSet->getQueryBondRings(bond1); // indeces of rings const std::vector<size_t>& ringsIdx2 = ringMatchMatrixSet->getTargetBondRings(&mol2, bond2); // indeces of rings bool bond1inRing = !ringsIdx1.empty(); bool bond2inRing = !ringsIdx2.empty(); if (bond1inRing != bond2inRing) return false; if ((!bond1inRing)) // the same: && (! bond2inRing)) // both bonds are NOT // in rings return true; // both bonds are in rings if (p.CompleteRingsOnly) { const RingInfo::VECT_INT_VECT& r1 = mol1.getRingInfo()->bondRings(); const RingInfo::VECT_INT_VECT& r2 = mol2.getRingInfo()->bondRings(); // for each query ring contains bond1 for (std::vector<size_t>::const_iterator r1i = ringsIdx1.begin(); r1i != ringsIdx1.end(); r1i++) { const INT_VECT& br1 = r1[*r1i]; // ring contains bond1 // check all target rings contained bond2 for (std::vector<size_t>::const_iterator r2i = ringsIdx2.begin(); r2i != ringsIdx2.end(); r2i++) { const INT_VECT& br2 = r2[*r2i]; // ring contains bond2 if (br1.size() != br2.size()) // rings are different continue; // compare rings as substructures if (ringMatchMatrixSet->isEqual(&br1, &br2, &mol2)) // EQUAL Rings found return true; } } // all rings are different return false; } else return true; // bond1inRing && bond2inRing; // both bonds are in rings } bool MCSBondCompareAny(const MCSBondCompareParameters& p, const ROMol& mol1, unsigned int bond1, const ROMol& mol2, unsigned int bond2, void* ud) { if (p.MatchStereo && !checkBondStereo(p, mol1, bond1, mol2, bond2)) return false; if (p.RingMatchesRingOnly) return checkRingMatch(p, mol1, bond1, mol2, bond2, ud); return true; } bool MCSBondCompareOrder(const MCSBondCompareParameters& p, const ROMol& mol1, unsigned int bond1, const ROMol& mol2, unsigned int bond2, void* ud) { static const BondMatchOrderMatrix match(true); // ignore Aromatization const Bond* b1 = mol1.getBondWithIdx(bond1); const Bond* b2 = mol2.getBondWithIdx(bond2); Bond::BondType t1 = b1->getBondType(); Bond::BondType t2 = b2->getBondType(); if (match.isEqual(t1, t2)) { if (p.MatchStereo && !checkBondStereo(p, mol1, bond1, mol2, bond2)) return false; if (p.RingMatchesRingOnly) return checkRingMatch(p, mol1, bond1, mol2, bond2, ud); return true; } return false; } bool MCSBondCompareOrderExact(const MCSBondCompareParameters& p, const ROMol& mol1, unsigned int bond1, const ROMol& mol2, unsigned int bond2, void* ud) { static const BondMatchOrderMatrix match(false); // AROMATIC != SINGLE const Bond* b1 = mol1.getBondWithIdx(bond1); const Bond* b2 = mol2.getBondWithIdx(bond2); Bond::BondType t1 = b1->getBondType(); Bond::BondType t2 = b2->getBondType(); if (match.isEqual(t1, t2)) { if (p.MatchStereo && !checkBondStereo(p, mol1, bond1, mol2, bond2)) return false; if (p.RingMatchesRingOnly) return checkRingMatch(p, mol1, bond1, mol2, bond2, ud); return true; } return false; } bool FinalChiralityCheckFunction(const short unsigned c1[], const short unsigned c2[], const ROMol& mol1, const FMCS::Graph& query, const ROMol& mol2, const FMCS::Graph& target, const MCSParameters* /*unused*/) { const unsigned int qna = boost::num_vertices(query); // getNumAtoms() // check chiral atoms only: for (unsigned int i = 0; i < qna; ++i) { const Atom& a1 = *mol1.getAtomWithIdx(query[c1[i]]); Atom::ChiralType ac1 = a1.getChiralTag(); const Atom& a2 = *mol2.getAtomWithIdx(target[c2[i]]); Atom::ChiralType ac2 = a2.getChiralTag(); ///*------------------ OLD Code : // ???: non chiral query atoms ARE ALLOWED TO MATCH to Chiral target atoms // (see test for issue 481) if (a1.getDegree() < 3 ||//#688: doesn't deal with "explicit" Hs properly !(ac1 == Atom::CHI_TETRAHEDRAL_CW || ac1 == Atom::CHI_TETRAHEDRAL_CCW)) continue; // skip non chiral center QUERY atoms if (!(ac2 == Atom::CHI_TETRAHEDRAL_CW || ac2 == Atom::CHI_TETRAHEDRAL_CCW)) return false; //-------------------- /* More accurate check: if( !(ac1 == Atom::CHI_TETRAHEDRAL_CW || ac1 == Atom::CHI_TETRAHEDRAL_CCW) && !(ac2 == Atom::CHI_TETRAHEDRAL_CW || ac2 == Atom::CHI_TETRAHEDRAL_CCW)) continue; // skip check if both atoms are non chiral center if(!( (ac1 == Atom::CHI_TETRAHEDRAL_CW || ac1 == Atom::CHI_TETRAHEDRAL_CCW) && (ac2 == Atom::CHI_TETRAHEDRAL_CW || ac2 == Atom::CHI_TETRAHEDRAL_CCW)))//ac2 != ac1) return false; // both atoms must be chiral or not without a query priority */ const unsigned a1Degree = boost::out_degree(c1[i], query); // a1.getDegree(); //number of all connected atoms in a seed if (a1Degree > a2.getDegree()) { //#688 was != . // FIX issue 631 // printf("atoms Degree (%u, %u) %u [%u], %u\n", query[c1[i]], // target[c2[i]], a1Degree, a1.getDegree(), a2.getDegree()); if (1 == a1Degree && a1.getDegree() == a2.getDegree()) continue; // continue to grow the seed else return false; } INT_LIST qOrder; for (unsigned int j = 0; j < qna && qOrder.size() != a1Degree; ++j) { const Bond* qB = mol1.getBondBetweenAtoms(query[c1[i]], query[c1[j]]); if (qB) qOrder.push_back(qB->getIdx()); } //#688 INT_LIST qmoOrder; { ROMol::OEDGE_ITER dbeg, dend; boost::tie(dbeg, dend) = mol1.getAtomBonds(&a1); for (; dbeg != dend; dbeg++) { int dbidx = mol1[*dbeg]->getIdx(); if (std::find(qOrder.begin(), qOrder.end(), dbidx) != qOrder.end()) qmoOrder.push_back(dbidx); // else // qmoOrder.push_back(-1); } } int qPermCount = //was: a1.getPerturbationOrder(qOrder); static_cast<int>(countSwapsToInterconvert(qmoOrder, qOrder)); INT_LIST mOrder; for (unsigned int j = 0; j < qna && mOrder.size() != a2.getDegree(); ++j) { const Bond* mB = mol2.getBondBetweenAtoms(target[c2[i]], target[c2[j]]); if (mB) mOrder.push_back(mB->getIdx()); } //#688 while (mOrder.size() < a2.getDegree()) { mOrder.push_back(-1); } INT_LIST moOrder; ROMol::OEDGE_ITER dbeg, dend; boost::tie(dbeg, dend) = mol2.getAtomBonds(&a2); for (; dbeg != dend; dbeg++) { int dbidx = mol2[*dbeg]->getIdx(); if (std::find(mOrder.begin(), mOrder.end(), dbidx) != mOrder.end()) moOrder.push_back(dbidx); else moOrder.push_back(-1); } int mPermCount = //was: a2.getPerturbationOrder(mOrder); static_cast<int>(countSwapsToInterconvert(moOrder, mOrder)); //---- if ((qPermCount % 2 == mPermCount % 2 && a1.getChiralTag() != a2.getChiralTag()) || (qPermCount % 2 != mPermCount % 2 && a1.getChiralTag() == a2.getChiralTag())) return false; } // check double bonds ONLY (why ???) const unsigned int qnb = boost::num_edges(query); std::map<unsigned int, unsigned int> qMap; for (unsigned int j = 0; j < qna; ++j) qMap[query[c1[j]]] = j; RDKit::FMCS::Graph::BOND_ITER_PAIR bpIter = boost::edges(query); RDKit::FMCS::Graph::EDGE_ITER bIter = bpIter.first; for (unsigned int i = 0; i < qnb; i++, ++bIter) { const Bond* qBnd = mol1.getBondWithIdx(query[*bIter]); if (qBnd->getBondType() != Bond::DOUBLE || (qBnd->getStereo() != Bond::STEREOZ && qBnd->getStereo() != Bond::STEREOE)) continue; // don't think this can actually happen, but check to be sure: if (qBnd->getStereoAtoms().size() != 2) // MUST check it in the seed, not // in full query molecule, but // never happens !!! continue; const Bond* mBnd = mol2.getBondBetweenAtoms(target[c2[qMap[qBnd->getBeginAtomIdx()]]], target[c2[qMap[qBnd->getEndAtomIdx()]]]); CHECK_INVARIANT(mBnd, "Matching bond not found"); if (mBnd->getBondType() != Bond::DOUBLE || (mBnd->getStereo() != Bond::STEREOZ && mBnd->getStereo() != Bond::STEREOE)) continue; // don't think this can actually happen, but check to be sure: if (mBnd->getStereoAtoms().size() != 2) continue; unsigned int end1Matches = 0; unsigned int end2Matches = 0; if (target[c2[qMap[qBnd->getBeginAtomIdx()]]] == rdcast<unsigned int>(mBnd->getBeginAtomIdx())) { // query Begin == mol Begin if (target[c2[qMap[qBnd->getStereoAtoms()[0]]]] == rdcast<unsigned int>(mBnd->getStereoAtoms()[0])) end1Matches = 1; if (target[c2[qMap[qBnd->getStereoAtoms()[1]]]] == rdcast<unsigned int>(mBnd->getStereoAtoms()[1])) end2Matches = 1; } else { // query End == mol Begin if (target[c2[qMap[qBnd->getStereoAtoms()[0]]]] == rdcast<unsigned int>(mBnd->getStereoAtoms()[1])) end1Matches = 1; if (target[c2[qMap[qBnd->getStereoAtoms()[1]]]] == rdcast<unsigned int>(mBnd->getStereoAtoms()[0])) end2Matches = 1; } // std::cerr<<" bnd: "<<qBnd->getIdx()<<":"<<qBnd->getStereo()<<" - // "<<mBnd->getIdx()<<":"<<mBnd->getStereo()<<" -- "<<end1Matches<<" // "<<end2Matches<<std::endl; if (mBnd->getStereo() == qBnd->getStereo() && (end1Matches + end2Matches) == 1) return false; if (mBnd->getStereo() != qBnd->getStereo() && (end1Matches + end2Matches) != 1) return false; } return true; } bool FinalChiralityCheckFunction_1(const short unsigned c1[], const short unsigned c2[], const ROMol& mol1, const FMCS::Graph& query, const ROMol& mol2, const FMCS::Graph& target, const MCSParameters* p) { RDUNUSED_PARAM(p); const unsigned int qna = boost::num_vertices(query); // getNumAtoms() // check chiral atoms: for (unsigned int i = 0; i < qna; ++i) { const Atom& a1 = *mol1.getAtomWithIdx(query[c1[i]]); Atom::ChiralType ac1 = a1.getChiralTag(); if (!(ac1 == Atom::CHI_TETRAHEDRAL_CW || ac1 == Atom::CHI_TETRAHEDRAL_CCW)) continue; // skip non chiral center query atoms const Atom& a2 = *mol2.getAtomWithIdx(target[c2[i]]); Atom::ChiralType ac2 = a2.getChiralTag(); if (!(ac2 == Atom::CHI_TETRAHEDRAL_CW || ac2 == Atom::CHI_TETRAHEDRAL_CCW)) continue; // skip non chiral center TARGET atoms even if query atom is // chiral //// return false; // both atoms are chiral: const unsigned a1Degree = boost::out_degree(c1[i], query); // a1.getDegree(); if (a1Degree != a2.getDegree()) // number of all connected atoms in seed return false; // ??? INT_LIST qOrder; for (unsigned int j = 0; j < qna && qOrder.size() != a1Degree; ++j) { const Bond* qB = mol1.getBondBetweenAtoms(query[c1[i]], query[c1[j]]); if (qB) qOrder.push_back(qB->getIdx()); } int qPermCount = a1.getPerturbationOrder(qOrder); INT_LIST mOrder; for (unsigned int j = 0; j < qna && mOrder.size() != a2.getDegree(); ++j) { const Bond* mB = mol2.getBondBetweenAtoms(target[c2[i]], target[c2[j]]); if (mB) mOrder.push_back(mB->getIdx()); } int mPermCount = a2.getPerturbationOrder(mOrder); if ((qPermCount % 2 == mPermCount % 2 && a1.getChiralTag() != a2.getChiralTag()) || (qPermCount % 2 != mPermCount % 2 && a1.getChiralTag() == a2.getChiralTag())) return false; } // check double bonds ONLY (why ???) const unsigned int qnb = boost::num_edges(query); std::map<unsigned int, unsigned int> qMap; for (unsigned int j = 0; j < qna; ++j) qMap[query[c1[j]]] = j; RDKit::FMCS::Graph::BOND_ITER_PAIR bpIter = boost::edges(query); RDKit::FMCS::Graph::EDGE_ITER bIter = bpIter.first; for (unsigned int i = 0; i < qnb; i++, ++bIter) { const Bond* qBnd = mol1.getBondWithIdx(query[*bIter]); if (qBnd->getBondType() != Bond::DOUBLE || (qBnd->getStereo() != Bond::STEREOZ && qBnd->getStereo() != Bond::STEREOE)) continue; // don't think this can actually happen, but check to be sure: if (qBnd->getStereoAtoms().size() != 2) // MUST check it in the seed, not // in full query molecule, but // never happens !!! continue; const Bond* mBnd = mol2.getBondBetweenAtoms(target[c2[qMap[qBnd->getBeginAtomIdx()]]], target[c2[qMap[qBnd->getEndAtomIdx()]]]); CHECK_INVARIANT(mBnd, "Matching bond not found"); if (mBnd->getBondType() != Bond::DOUBLE || (mBnd->getStereo() != Bond::STEREOZ && mBnd->getStereo() != Bond::STEREOE)) continue; // don't think this can actually happen, but check to be sure: if (mBnd->getStereoAtoms().size() != 2) continue; unsigned int end1Matches = 0; unsigned int end2Matches = 0; if (target[c2[qMap[qBnd->getBeginAtomIdx()]]] == mBnd->getBeginAtomIdx()) { // query Begin == mol Begin if (target[c2[qMap[qBnd->getStereoAtoms()[0]]]] == rdcast<unsigned int>(mBnd->getStereoAtoms()[0])) end1Matches = 1; if (target[c2[qMap[qBnd->getStereoAtoms()[1]]]] == rdcast<unsigned int>(mBnd->getStereoAtoms()[1])) end2Matches = 1; } else { // query End == mol Begin if (target[c2[qMap[qBnd->getStereoAtoms()[0]]]] == rdcast<unsigned int>(mBnd->getStereoAtoms()[1])) end1Matches = 1; if (target[c2[qMap[qBnd->getStereoAtoms()[1]]]] == rdcast<unsigned int>(mBnd->getStereoAtoms()[0])) end2Matches = 1; } // std::cerr<<" bnd: "<<qBnd->getIdx()<<":"<<qBnd->getStereo()<<" - // "<<mBnd->getIdx()<<":"<<mBnd->getStereo()<<" -- "<<end1Matches<<" // "<<end2Matches<<std::endl; if (mBnd->getStereo() == qBnd->getStereo() && (end1Matches + end2Matches) == 1) return false; if (mBnd->getStereo() != qBnd->getStereo() && (end1Matches + end2Matches) != 1) return false; } return true; } } // namespace RDKit
1
16,619
Clever but perhaps confusing.
rdkit-rdkit
cpp
@@ -360,10 +360,14 @@ func (r *ReconcileSyncSetInstance) syncDeletedSyncSetInstance(ssi *hivev1.SyncSe ssiLog.Info("deleting syncset resources on target cluster") err = r.deleteSyncSetResources(ssi, dynamicClient, ssiLog) - if err == nil { - return reconcile.Result{}, r.removeSyncSetInstanceFinalizer(ssi, ssiLog) + if err != nil { + return reconcile.Result{}, err + } + err = r.deleteSyncSetSecretReferences(ssi, dynamicClient, ssiLog) + if err != nil { + return reconcile.Result{}, err } - return reconcile.Result{}, err + return reconcile.Result{}, r.removeSyncSetInstanceFinalizer(ssi, ssiLog) } func (r *ReconcileSyncSetInstance) applySyncSet(ssi *hivev1.SyncSetInstance, spec *hivev1.SyncSetCommonSpec, dynamicClient dynamic.Interface, h Applier, kubeConfig []byte, ssiLog log.FieldLogger) error {
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 syncsetinstance import ( "context" "crypto/md5" "encoding/json" "fmt" "reflect" "time" log "github.com/sirupsen/logrus" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" "k8s.io/client-go/dynamic" "k8s.io/client-go/kubernetes/scheme" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/controller" "sigs.k8s.io/controller-runtime/pkg/handler" "sigs.k8s.io/controller-runtime/pkg/manager" "sigs.k8s.io/controller-runtime/pkg/reconcile" "sigs.k8s.io/controller-runtime/pkg/source" hivev1 "github.com/openshift/hive/pkg/apis/hive/v1alpha1" "github.com/openshift/hive/pkg/constants" hivemetrics "github.com/openshift/hive/pkg/controller/metrics" controllerutils "github.com/openshift/hive/pkg/controller/utils" hiveresource "github.com/openshift/hive/pkg/resource" ) const ( controllerName = "syncsetinstance" unknownObjectFoundReason = "UnknownObjectFound" applySucceededReason = "ApplySucceeded" applyFailedReason = "ApplyFailed" deletionFailedReason = "DeletionFailed" reapplyInterval = 2 * time.Hour secretsResource = "secrets" secretKind = "Secret" secretAPIVersion = "v1" ) // Applier knows how to Apply, Patch and return Info for []byte arrays describing objects and patches. type Applier interface { Apply(obj []byte) (hiveresource.ApplyResult, error) Info(obj []byte) (*hiveresource.Info, error) Patch(name types.NamespacedName, kind, apiVersion string, patch []byte, patchType string) error ApplyRuntimeObject(obj runtime.Object, scheme *runtime.Scheme) (hiveresource.ApplyResult, error) } // Add creates a new SyncSet controller and adds it to the manager with default RBAC. The manager will set fields on the // controller and start it when the manager starts. func Add(mgr manager.Manager) error { return AddToManager(mgr, NewReconciler(mgr)) } // NewReconciler returns a new reconcile.Reconciler func NewReconciler(mgr manager.Manager) reconcile.Reconciler { r := &ReconcileSyncSetInstance{ Client: controllerutils.NewClientWithMetricsOrDie(mgr, controllerName), scheme: mgr.GetScheme(), logger: log.WithField("controller", controllerName), applierBuilder: applierBuilderFunc, dynamicClientBuilder: controllerutils.BuildDynamicClientFromKubeconfig, } r.hash = r.resourceHash return r } // applierBuilderFunc returns an Applier which implements Info, Apply and Patch func applierBuilderFunc(kubeConfig []byte, logger log.FieldLogger) Applier { var helper Applier = hiveresource.NewHelper(kubeConfig, logger) return helper } // AddToManager adds a new Controller to mgr with r as the reconcile.Reconciler func AddToManager(mgr manager.Manager, r reconcile.Reconciler) error { // Create a new controller c, err := controller.New("syncsetinstance-controller", mgr, controller.Options{Reconciler: r, MaxConcurrentReconciles: controllerutils.GetConcurrentReconciles()}) if err != nil { return err } // Watch for changes to SyncSetInstance err = c.Watch(&source.Kind{Type: &hivev1.SyncSetInstance{}}, &handler.EnqueueRequestForObject{}) if err != nil { return err } // Watch for changes to ClusterDeployments err = c.Watch(&source.Kind{Type: &hivev1.ClusterDeployment{}}, &handler.EnqueueRequestsFromMapFunc{ ToRequests: handler.ToRequestsFunc(r.(*ReconcileSyncSetInstance).handleClusterDeployment), }) if err != nil { return err } return nil } func (r *ReconcileSyncSetInstance) handleClusterDeployment(a handler.MapObject) []reconcile.Request { cd, ok := a.Object.(*hivev1.ClusterDeployment) if !ok { return []reconcile.Request{} } syncSetInstanceList := &hivev1.SyncSetInstanceList{} err := r.List(context.TODO(), syncSetInstanceList, client.InNamespace(cd.Namespace)) if err != nil { r.logger.WithError(err).Error("cannot list syncSetInstances for cluster deployment") return []reconcile.Request{} } retval := []reconcile.Request{} for _, syncSetInstance := range syncSetInstanceList.Items { if metav1.IsControlledBy(&syncSetInstance, cd) { retval = append(retval, reconcile.Request{ NamespacedName: types.NamespacedName{ Name: cd.Name, Namespace: cd.Namespace, }, }) } } return retval } var _ reconcile.Reconciler = &ReconcileSyncSetInstance{} // ReconcileSyncSetInstance reconciles a ClusterDeployment and the SyncSets associated with it type ReconcileSyncSetInstance struct { client.Client scheme *runtime.Scheme logger log.FieldLogger applierBuilder func([]byte, log.FieldLogger) Applier hash func([]byte) string dynamicClientBuilder func(string, string) (dynamic.Interface, error) } // Reconcile applies SyncSet or SelectorSyncSets associated with SyncSetInstances to the owning cluster. func (r *ReconcileSyncSetInstance) Reconcile(request reconcile.Request) (reconcile.Result, error) { start := time.Now() ssiLog := r.logger.WithField("syncsetinstance", request.NamespacedName) defer func() { dur := time.Since(start) hivemetrics.MetricControllerReconcileTime.WithLabelValues(controllerName).Observe(dur.Seconds()) ssiLog.WithField("elapsed", dur).Info("reconcile complete") }() ssi := &hivev1.SyncSetInstance{} // Fetch the syncsetinstance err := r.Get(context.TODO(), request.NamespacedName, ssi) if err != nil { if errors.IsNotFound(err) { // Object not found, return return reconcile.Result{}, nil } // Error reading the object - requeue the request r.logger.WithError(err).Error("error looking up syncsetinstance") return reconcile.Result{}, err } if ssi.DeletionTimestamp != nil { if !controllerutils.HasFinalizer(ssi, hivev1.FinalizerSyncSetInstance) { return reconcile.Result{}, nil } return r.syncDeletedSyncSetInstance(ssi, ssiLog) } if !controllerutils.HasFinalizer(ssi, hivev1.FinalizerSyncSetInstance) { ssiLog.Debug("adding finalizer") return reconcile.Result{}, r.addSyncSetInstanceFinalizer(ssi, ssiLog) } cd, err := r.getClusterDeployment(ssi, ssiLog) if err != nil { return reconcile.Result{}, err } if cd.Annotations[constants.SyncsetPauseAnnotation] == "true" { log.Warn(constants.SyncsetPauseAnnotation, " is present, hence syncing to cluster is disabled") return reconcile.Result{}, nil } if !cd.DeletionTimestamp.IsZero() { ssiLog.Debug("clusterdeployment is being deleted") return reconcile.Result{}, nil } if !cd.Spec.Installed { ssiLog.Debug("cluster installation is not complete") return reconcile.Result{}, nil } // If the cluster is unreachable, return from here. if controllerutils.HasUnreachableCondition(cd) { ssiLog.Debug("skipping cluster with unreachable condition") return reconcile.Result{}, nil } if len(cd.Status.AdminKubeconfigSecret.Name) == 0 { ssiLog.Debug("admin kubeconfig secret name is not set on clusterdeployment") return reconcile.Result{}, nil } ssiLog.Info("reconciling syncsetinstance") spec, deleted, err := r.getSyncSetCommonSpec(ssi, ssiLog) if (!deleted && spec == nil) || err != nil { return reconcile.Result{}, err } if deleted { ssiLog.Info("source has been deleted, deleting syncsetinstance") err = r.Delete(context.TODO(), ssi) if err != nil { ssiLog.WithError(err).Error("failed to delete syncsetinstance") } return reconcile.Result{}, err } // get kubeconfig for the cluster adminKubeconfigSecret, err := r.getKubeconfigSecret(cd, ssiLog) if err != nil { return reconcile.Result{}, err } kubeConfig, err := controllerutils.FixupKubeconfigSecretData(adminKubeconfigSecret.Data) if err != nil { ssiLog.WithError(err).Error("unable to fixup cluster client") return reconcile.Result{}, err } dynamicClient, err := r.dynamicClientBuilder(string(kubeConfig), controllerName) if err != nil { ssiLog.WithError(err).Error("unable to build dynamic client") return reconcile.Result{}, err } ssiLog.Debug("applying sync set") original := ssi.DeepCopy() applier := r.applierBuilder(kubeConfig, ssiLog) applyErr := r.applySyncSet(ssi, spec, dynamicClient, applier, kubeConfig, ssiLog) err = r.updateSyncSetInstanceStatus(ssi, original, ssiLog) if err != nil { ssiLog.WithError(err).Errorf("error updating syncsetinstance status") return reconcile.Result{}, err } ssiLog.Info("done reconciling syncsetinstance") return reconcile.Result{}, applyErr } func (r *ReconcileSyncSetInstance) getClusterDeployment(ssi *hivev1.SyncSetInstance, ssiLog log.FieldLogger) (*hivev1.ClusterDeployment, error) { cd := &hivev1.ClusterDeployment{} cdName := types.NamespacedName{Namespace: ssi.Namespace, Name: ssi.Spec.ClusterDeployment.Name} ssiLog = ssiLog.WithField("clusterdeployment", cdName) err := r.Get(context.TODO(), cdName, cd) if err != nil { ssiLog.WithError(err).Error("error looking up clusterdeployment") return nil, err } return cd, nil } func (r *ReconcileSyncSetInstance) getKubeconfigSecret(cd *hivev1.ClusterDeployment, ssiLog log.FieldLogger) (*corev1.Secret, error) { if len(cd.Status.AdminKubeconfigSecret.Name) == 0 { return nil, fmt.Errorf("no kubeconfigconfig secret is set on clusterdeployment") } secret := &corev1.Secret{} secretName := types.NamespacedName{Name: cd.Status.AdminKubeconfigSecret.Name, Namespace: cd.Namespace} err := r.Get(context.TODO(), secretName, secret) if err != nil { ssiLog.WithError(err).WithField("secret", secretName).Error("unable to load admin kubeconfig secret") return nil, err } return secret, nil } func (r *ReconcileSyncSetInstance) addSyncSetInstanceFinalizer(ssi *hivev1.SyncSetInstance, ssiLog log.FieldLogger) error { ssiLog.Debug("adding finalizer") controllerutils.AddFinalizer(ssi, hivev1.FinalizerSyncSetInstance) err := r.Update(context.TODO(), ssi) if err != nil { ssiLog.WithError(err).Error("cannot add finalizer") } return err } func (r *ReconcileSyncSetInstance) removeSyncSetInstanceFinalizer(ssi *hivev1.SyncSetInstance, ssiLog log.FieldLogger) error { ssiLog.Debug("removing finalizer") controllerutils.DeleteFinalizer(ssi, hivev1.FinalizerSyncSetInstance) err := r.Update(context.TODO(), ssi) if err != nil { ssiLog.WithError(err).Error("cannot remove finalizer") } return err } func (r *ReconcileSyncSetInstance) syncDeletedSyncSetInstance(ssi *hivev1.SyncSetInstance, ssiLog log.FieldLogger) (reconcile.Result, error) { if ssi.Spec.ResourceApplyMode != hivev1.SyncResourceApplyMode { ssiLog.Debug("syncset is deleted and there is nothing to clean up, removing finalizer") return reconcile.Result{}, r.removeSyncSetInstanceFinalizer(ssi, ssiLog) } cd, err := r.getClusterDeployment(ssi, ssiLog) if errors.IsNotFound(err) { // clusterdeployment has been deleted, should just remove the finalizer return reconcile.Result{}, r.removeSyncSetInstanceFinalizer(ssi, ssiLog) } else if err != nil { // unknown error, try again return reconcile.Result{}, err } if !cd.DeletionTimestamp.IsZero() { ssiLog.Debug("clusterdeployment is being deleted") return reconcile.Result{}, r.removeSyncSetInstanceFinalizer(ssi, ssiLog) } // If the cluster is unreachable, do not reconcile. if controllerutils.HasUnreachableCondition(cd) { ssiLog.Debug("skipping cluster with unreachable condition") return reconcile.Result{}, nil } kubeconfigSecret, err := r.getKubeconfigSecret(cd, ssiLog) if errors.IsNotFound(err) { // kubeconfig secret cannot be found, just remove the finalizer return reconcile.Result{}, r.removeSyncSetInstanceFinalizer(ssi, ssiLog) } else if err != nil { // unknown error, try again return reconcile.Result{}, err } kubeConfig, err := controllerutils.FixupKubeconfigSecretData(kubeconfigSecret.Data) if err != nil { ssiLog.WithError(err).Error("unable to fixup cluster client") return reconcile.Result{}, err } dynamicClient, err := r.dynamicClientBuilder(string(kubeConfig), controllerName) if err != nil { ssiLog.WithError(err).Error("unable to build dynamic client") return reconcile.Result{}, err } ssiLog.Info("deleting syncset resources on target cluster") err = r.deleteSyncSetResources(ssi, dynamicClient, ssiLog) if err == nil { return reconcile.Result{}, r.removeSyncSetInstanceFinalizer(ssi, ssiLog) } return reconcile.Result{}, err } func (r *ReconcileSyncSetInstance) applySyncSet(ssi *hivev1.SyncSetInstance, spec *hivev1.SyncSetCommonSpec, dynamicClient dynamic.Interface, h Applier, kubeConfig []byte, ssiLog log.FieldLogger) error { defer func() { // Temporary fix for status hot loop: do not update ssi.Status.{Patches,Resources,SecretReferences} with empty slice. if len(ssi.Status.Resources) == 0 { ssi.Status.Resources = nil } if len(ssi.Status.Patches) == 0 { ssi.Status.Patches = nil } if len(ssi.Status.SecretReferences) == 0 { ssi.Status.SecretReferences = nil } }() err := r.applySyncSetResources(ssi, spec.Resources, dynamicClient, h, ssiLog) if err != nil { ssiLog.WithError(err).Error("an error occurred applying syncset resources") return err } err = r.applySyncSetPatches(ssi, spec.Patches, kubeConfig, ssiLog) if err != nil { ssiLog.WithError(err).Error("an error occurred applying syncset patches") return err } err = r.applySyncSetSecretReferences(ssi, spec.SecretReferences, dynamicClient, h, ssiLog) if err != nil { ssiLog.WithError(err).Error("an error occurred applying syncset secret references") return err } return nil } func (r *ReconcileSyncSetInstance) deleteSyncSetResources(ssi *hivev1.SyncSetInstance, dynamicClient dynamic.Interface, ssiLog log.FieldLogger) error { var lastError error for index, resourceStatus := range ssi.Status.Resources { itemLog := ssiLog.WithField("resource", fmt.Sprintf("%s/%s", resourceStatus.Namespace, resourceStatus.Name)). WithField("apiversion", resourceStatus.APIVersion). WithField("kind", resourceStatus.Kind) gv, err := schema.ParseGroupVersion(resourceStatus.APIVersion) if err != nil { itemLog.WithError(err).Error("cannot parse resource apiVersion, skipping deletiong") continue } gvr := gv.WithResource(resourceStatus.Resource) itemLog.Debug("deleting resource") err = dynamicClient.Resource(gvr).Namespace(resourceStatus.Namespace).Delete(resourceStatus.Name, &metav1.DeleteOptions{}) if err != nil { switch { case errors.IsNotFound(err): itemLog.Debug("resource not found, nothing to do") case errors.IsForbidden(err): itemLog.WithError(err).Error("forbidden resource deletion, skipping") default: lastError = err itemLog.WithError(err).Error("error deleting resource") ssi.Status.Resources[index].Conditions = r.setDeletionFailedSyncCondition(ssi.Status.Resources[index].Conditions, fmt.Errorf("failed to delete resource: %v", err)) } } } return lastError } // getSyncSetCommonSpec returns the common spec of the associated syncset or selectorsyncset. It returns a boolean indicating // whether the source object (syncset or selectorsyncset) has been deleted or is in the process of being deleted. func (r *ReconcileSyncSetInstance) getSyncSetCommonSpec(ssi *hivev1.SyncSetInstance, ssiLog log.FieldLogger) (*hivev1.SyncSetCommonSpec, bool, error) { if ssi.Spec.SyncSet != nil { syncSet := &hivev1.SyncSet{} syncSetName := types.NamespacedName{Namespace: ssi.Namespace, Name: ssi.Spec.SyncSet.Name} err := r.Get(context.TODO(), syncSetName, syncSet) if errors.IsNotFound(err) || !syncSet.DeletionTimestamp.IsZero() { ssiLog.WithError(err).WithField("syncset", syncSetName).Warning("syncset is being deleted") return nil, true, nil } if err != nil { ssiLog.WithError(err).WithField("syncset", syncSetName).Error("cannot get associated syncset") return nil, false, err } if !syncSet.DeletionTimestamp.IsZero() { ssiLog.WithError(err).WithField("syncset", syncSetName).Warning("syncset is being deleted") return nil, false, nil } return &syncSet.Spec.SyncSetCommonSpec, false, nil } else if ssi.Spec.SelectorSyncSet != nil { selectorSyncSet := &hivev1.SelectorSyncSet{} selectorSyncSetName := types.NamespacedName{Name: ssi.Spec.SelectorSyncSet.Name} err := r.Get(context.TODO(), selectorSyncSetName, selectorSyncSet) if errors.IsNotFound(err) || !selectorSyncSet.DeletionTimestamp.IsZero() { ssiLog.WithField("selectorsyncset", selectorSyncSetName).Warning("selectorsyncset is being deleted") return nil, true, nil } if err != nil { ssiLog.WithField("selectorsyncset", selectorSyncSetName).Error("cannot get associated selectorsyncset") return nil, false, err } return &selectorSyncSet.Spec.SyncSetCommonSpec, false, nil } ssiLog.Error("invalid syncsetinstance, no reference found to syncset or selectorsyncset") return nil, false, nil } // findSyncStatus returns a SyncStatus matching the provided status from a list of SyncStatus func findSyncStatus(status hivev1.SyncStatus, statusList []hivev1.SyncStatus) *hivev1.SyncStatus { for _, ss := range statusList { if status.Name == ss.Name && status.Namespace == ss.Namespace && status.APIVersion == ss.APIVersion && status.Kind == ss.Kind { return &ss } } return nil } // needToReApply determines if the provided status indicates that the resource, secret or patch needs to be re-applied func needToReApply(applyTerm string, newStatus, existingStatus hivev1.SyncStatus, ssiLog log.FieldLogger) bool { // Re-apply if hash has changed if existingStatus.Hash != newStatus.Hash { ssiLog.Debugf("%s %s/%s (%s) has changed, will re-apply", applyTerm, newStatus.Namespace, newStatus.Name, newStatus.Kind) return true } // Re-apply if failure occurred if failureCondition := controllerutils.FindSyncCondition(existingStatus.Conditions, hivev1.ApplyFailureSyncCondition); failureCondition != nil { if failureCondition.Status == corev1.ConditionTrue { ssiLog.Debugf("%s %s/%s (%s) failed last time, will re-apply", applyTerm, newStatus.Namespace, newStatus.Name, newStatus.Kind) return true } } // Re-apply if past reapplyInterval if applySuccessCondition := controllerutils.FindSyncCondition(existingStatus.Conditions, hivev1.ApplySuccessSyncCondition); applySuccessCondition != nil { since := time.Since(applySuccessCondition.LastProbeTime.Time) if since > reapplyInterval { ssiLog.Debugf("It has been %v since %s %s/%s (%s) was last applied, will re-apply", applyTerm, since, newStatus.Namespace, newStatus.Name, newStatus.Kind) return true } } return false } // applySyncSetResources evaluates resource objects from RawExtension and applies them to the cluster identified by kubeConfig func (r *ReconcileSyncSetInstance) applySyncSetResources(ssi *hivev1.SyncSetInstance, resources []runtime.RawExtension, dynamicClient dynamic.Interface, h Applier, ssiLog log.FieldLogger) error { // determine if we can gather info for all resources infos := []hiveresource.Info{} for i, resource := range resources { info, err := h.Info(resource.Raw) if err != nil { ssi.Status.Conditions = r.setUnknownObjectSyncCondition(ssi.Status.Conditions, err, i) return err } infos = append(infos, *info) } ssi.Status.Conditions = r.clearUnknownObjectSyncCondition(ssi.Status.Conditions) syncStatusList := []hivev1.SyncStatus{} var applyErr error for i, resource := range resources { resourceSyncStatus := hivev1.SyncStatus{ APIVersion: infos[i].APIVersion, Kind: infos[i].Kind, Resource: infos[i].Resource, Name: infos[i].Name, Namespace: infos[i].Namespace, Hash: r.hash(resource.Raw), } if rss := findSyncStatus(resourceSyncStatus, ssi.Status.Resources); rss == nil || needToReApply("resource", resourceSyncStatus, *rss, ssiLog) { // Apply resource ssiLog.Debugf("applying resource: %s/%s (%s)", resourceSyncStatus.Namespace, resourceSyncStatus.Name, resourceSyncStatus.Kind) var applyResult hiveresource.ApplyResult applyResult, applyErr = h.Apply(resource.Raw) var resourceSyncConditions []hivev1.SyncCondition if rss != nil { resourceSyncConditions = rss.Conditions } resourceSyncStatus.Conditions = r.setApplySyncConditions(resourceSyncConditions, applyErr) if applyErr != nil { ssiLog.WithError(applyErr).Errorf("error applying resource %s/%s (%s)", resourceSyncStatus.Namespace, resourceSyncStatus.Name, resourceSyncStatus.Kind) } else { ssiLog.Debugf("resource %s/%s (%s): %s", resourceSyncStatus.Namespace, resourceSyncStatus.Name, resourceSyncStatus.Kind, applyResult) } } else { // Do not apply resource ssiLog.Debugf("resource %s/%s (%s) has not changed, will not apply", resourceSyncStatus.Namespace, resourceSyncStatus.Name, resourceSyncStatus.Kind) resourceSyncStatus.Conditions = rss.Conditions } syncStatusList = append(syncStatusList, resourceSyncStatus) // If an error applying occurred, stop processing right here if applyErr != nil { break } } ssi.Status.Resources = r.reconcileDeleted("resource", ssi.Spec.ResourceApplyMode, dynamicClient, ssi.Status.Resources, syncStatusList, applyErr, ssiLog) // Return applyErr for the controller to trigger retries and go into exponential backoff // if the problem does not resolve itself. if applyErr != nil { return applyErr } return nil } func (r *ReconcileSyncSetInstance) reconcileDeleted(deleteTerm string, applyMode hivev1.SyncSetResourceApplyMode, dynamicClient dynamic.Interface, existingStatusList, newStatusList []hivev1.SyncStatus, err error, ssiLog log.FieldLogger) []hivev1.SyncStatus { ssiLog.Debugf("reconciling syncset %ss, existing: %d, actual: %d", deleteTerm, len(existingStatusList), len(newStatusList)) if applyMode == "" || applyMode == hivev1.UpsertResourceApplyMode { ssiLog.Debugf("apply mode is upsert, remote %ss will not be deleted", deleteTerm) return newStatusList } deletedStatusList := []hivev1.SyncStatus{} for _, existingStatus := range existingStatusList { if ss := findSyncStatus(existingStatus, newStatusList); ss == nil { ssiLog.WithField(deleteTerm, fmt.Sprintf("%s/%s", existingStatus.Namespace, existingStatus.Name)). WithField("apiversion", existingStatus.APIVersion). WithField("kind", existingStatus.Kind).Debugf("%s not found in updated status, will queue up for deletion", deleteTerm) deletedStatusList = append(deletedStatusList, existingStatus) } } // If an error occurred applying resources, do not delete yet if err != nil { ssiLog.Debugf("an error occurred applying %ss, will preserve all syncset status items", deleteTerm) return append(newStatusList, deletedStatusList...) } for _, deletedStatus := range deletedStatusList { itemLog := ssiLog.WithField(deleteTerm, fmt.Sprintf("%s/%s", deletedStatus.Namespace, deletedStatus.Name)). WithField("apiversion", deletedStatus.APIVersion). WithField("kind", deletedStatus.Kind) gv, err := schema.ParseGroupVersion(deletedStatus.APIVersion) if err != nil { itemLog.WithError(err).Errorf("unable to delete %s, cannot parse group version", deleteTerm) deletedStatus.Conditions = r.setDeletionFailedSyncCondition(deletedStatus.Conditions, err) newStatusList = append(newStatusList, deletedStatus) continue } gvr := gv.WithResource(deletedStatus.Resource) itemLog.Debugf("deleting %s", deleteTerm) err = dynamicClient.Resource(gvr).Namespace(deletedStatus.Namespace).Delete(deletedStatus.Name, &metav1.DeleteOptions{}) if err != nil { if !errors.IsNotFound(err) { itemLog.WithError(err).Errorf("error deleting %s", deleteTerm) deletedStatus.Conditions = r.setDeletionFailedSyncCondition(deletedStatus.Conditions, err) newStatusList = append(newStatusList, deletedStatus) } else { itemLog.Debugf("%s not found, nothing to do", deleteTerm) } } } return newStatusList } // applySyncSetPatches applies patches to cluster identified by kubeConfig func (r *ReconcileSyncSetInstance) applySyncSetPatches(ssi *hivev1.SyncSetInstance, ssPatches []hivev1.SyncObjectPatch, kubeConfig []byte, ssiLog log.FieldLogger) error { h := r.applierBuilder(kubeConfig, r.logger) for _, ssPatch := range ssPatches { b, err := json.Marshal(ssPatch) if err != nil { ssiLog.WithError(err).Error("cannot serialize syncset patch") return err } patchSyncStatus := hivev1.SyncStatus{ APIVersion: ssPatch.APIVersion, Kind: ssPatch.Kind, Name: ssPatch.Name, Namespace: ssPatch.Namespace, Hash: r.hash(b), } if pss := findSyncStatus(patchSyncStatus, ssi.Status.Patches); pss == nil || needToReApply("patch", patchSyncStatus, *pss, ssiLog) { // Apply patch ssiLog.Debugf("applying patch: %s/%s (%s)", ssPatch.Namespace, ssPatch.Name, ssPatch.Kind) namespacedName := types.NamespacedName{ Name: ssPatch.Name, Namespace: ssPatch.Namespace, } err := h.Patch(namespacedName, ssPatch.Kind, ssPatch.APIVersion, []byte(ssPatch.Patch), ssPatch.PatchType) var patchSyncConditions []hivev1.SyncCondition if pss != nil { patchSyncConditions = pss.Conditions } patchSyncStatus.Conditions = r.setApplySyncConditions(patchSyncConditions, err) ssi.Status.Patches = appendOrUpdateSyncStatus(ssi.Status.Patches, patchSyncStatus) if err != nil { return err } } else { // Do not apply patch ssiLog.Debugf("patch %s/%s (%s) has not changed, will not apply", patchSyncStatus.Namespace, patchSyncStatus.Name, patchSyncStatus.Kind) patchSyncStatus.Conditions = pss.Conditions } } return nil } // applySyncSetSecretReferences evaluates secret references and applies them to the cluster identified by kubeConfig func (r *ReconcileSyncSetInstance) applySyncSetSecretReferences(ssi *hivev1.SyncSetInstance, secretReferences []hivev1.SecretReference, dynamicClient dynamic.Interface, h Applier, ssiLog log.FieldLogger) error { syncStatusList := []hivev1.SyncStatus{} var applyErr error for _, secretReference := range secretReferences { apiVersion := secretAPIVersion if secretReference.Target.APIVersion != "" { apiVersion = secretReference.Target.APIVersion } secretReferenceSyncStatus := hivev1.SyncStatus{ APIVersion: apiVersion, Kind: secretKind, Name: secretReference.Target.Name, Namespace: secretReference.Target.Namespace, Resource: secretsResource, } rss := findSyncStatus(secretReferenceSyncStatus, ssi.Status.SecretReferences) var secretReferenceSyncConditions []hivev1.SyncCondition if rss != nil { secretReferenceSyncConditions = rss.Conditions } secret := &corev1.Secret{} applyErr = r.Get(context.Background(), types.NamespacedName{Name: secretReference.Source.Name, Namespace: secretReference.Source.Namespace}, secret) if applyErr != nil { ssiLog.WithError(applyErr).WithField("secret", fmt.Sprintf("%s/%s", secretReference.Source.Name, secretReference.Source.Namespace)).Error("cannot read secret") secretReferenceSyncStatus.Conditions = r.setApplySyncConditions(secretReferenceSyncConditions, applyErr) syncStatusList = append(syncStatusList, secretReferenceSyncStatus) break } secret.Name = secretReference.Target.Name secret.Namespace = secretReference.Target.Namespace // These pieces of metadata need to be set to nil values to perform an update from the original secret secret.Generation = 0 secret.ResourceVersion = "" secret.UID = "" secret.OwnerReferences = nil var hash string hash, applyErr = controllerutils.GetChecksumOfObject(secret) if applyErr != nil { ssiLog.WithError(applyErr).WithField("secret", fmt.Sprintf("%s/%s", secretReference.Source.Name, secretReference.Source.Namespace)).Error("unable to compute secret hash") secretReferenceSyncStatus.Conditions = r.setApplySyncConditions(secretReferenceSyncConditions, applyErr) syncStatusList = append(syncStatusList, secretReferenceSyncStatus) break } secretReferenceSyncStatus.Hash = hash if rss == nil || needToReApply("secret", secretReferenceSyncStatus, *rss, ssiLog) { // Apply secret ssiLog.Debugf("applying secret: %s/%s (%s)", secret.Namespace, secret.Name, secret.Kind) var result hiveresource.ApplyResult result, applyErr = h.ApplyRuntimeObject(secret, scheme.Scheme) var secretReferenceSyncConditions []hivev1.SyncCondition if rss != nil { secretReferenceSyncConditions = rss.Conditions } secretReferenceSyncStatus.Conditions = r.setApplySyncConditions(secretReferenceSyncConditions, applyErr) if applyErr != nil { ssiLog.WithError(applyErr).Errorf("error applying secret %s/%s (%s)", secret.Namespace, secret.Name, secret.Kind) } else { ssiLog.Debugf("resource %s/%s (%s): %s", secret.Namespace, secret.Name, secret.Kind, result) } } else { // Do not apply secret ssiLog.Debugf("resource %s/%s (%s) has not changed, will not apply", secret.Namespace, secret.Name, secret.Kind) secretReferenceSyncStatus.Conditions = rss.Conditions } syncStatusList = append(syncStatusList, secretReferenceSyncStatus) // If an error applying occurred, stop processing right here if applyErr != nil { break } } ssi.Status.SecretReferences = r.reconcileDeleted("secret", ssi.Spec.ResourceApplyMode, dynamicClient, ssi.Status.SecretReferences, syncStatusList, applyErr, ssiLog) // Return applyErr for the controller to trigger retries nd go into exponential backoff // if the problem does not resolve itself. if applyErr != nil { return applyErr } return nil } func appendOrUpdateSyncStatus(statusList []hivev1.SyncStatus, syncStatus hivev1.SyncStatus) []hivev1.SyncStatus { for i, ss := range statusList { if ss.Name == syncStatus.Name && ss.Namespace == syncStatus.Namespace && ss.Kind == syncStatus.Kind { statusList[i] = syncStatus return statusList } } return append(statusList, syncStatus) } func (r *ReconcileSyncSetInstance) updateSyncSetInstanceStatus(ssi *hivev1.SyncSetInstance, original *hivev1.SyncSetInstance, ssiLog log.FieldLogger) error { // Update syncsetinstance status if changed: if !reflect.DeepEqual(ssi.Status, original.Status) { ssiLog.Infof("syncset instance status has changed, updating") err := r.Status().Update(context.TODO(), ssi) if err != nil { ssiLog.WithError(err).Error("error updating syncsetinstance status") return err } } return nil } func (r *ReconcileSyncSetInstance) setUnknownObjectSyncCondition(syncSetConditions []hivev1.SyncCondition, err error, index int) []hivev1.SyncCondition { return controllerutils.SetSyncCondition( syncSetConditions, hivev1.UnknownObjectSyncCondition, corev1.ConditionTrue, unknownObjectFoundReason, fmt.Sprintf("Unable to gather Info for SyncSet resource at index %v in resources: %v", index, err), controllerutils.UpdateConditionIfReasonOrMessageChange, ) } func (r *ReconcileSyncSetInstance) clearUnknownObjectSyncCondition(syncSetConditions []hivev1.SyncCondition) []hivev1.SyncCondition { return controllerutils.SetSyncCondition( syncSetConditions, hivev1.UnknownObjectSyncCondition, corev1.ConditionFalse, unknownObjectFoundReason, fmt.Sprintf("Info available for all SyncSet resources"), controllerutils.UpdateConditionIfReasonOrMessageChange, ) } func (r *ReconcileSyncSetInstance) setApplySyncConditions(resourceSyncConditions []hivev1.SyncCondition, err error) []hivev1.SyncCondition { var reason, message string var successStatus, failureStatus corev1.ConditionStatus var updateCondition controllerutils.UpdateConditionCheck if err == nil { reason = applySucceededReason message = "Apply successful" successStatus = corev1.ConditionTrue failureStatus = corev1.ConditionFalse updateCondition = controllerutils.UpdateConditionAlways } else { reason = applyFailedReason // TODO: we cannot include the actual error here as it currently contains a temp filename which always changes, // which triggers a hotloop by always updating status and then reconciling again. If we were to filter out the portion // of the error message with filename, we could re-add this here. message = "Apply failed" successStatus = corev1.ConditionFalse failureStatus = corev1.ConditionTrue updateCondition = controllerutils.UpdateConditionIfReasonOrMessageChange } resourceSyncConditions = controllerutils.SetSyncCondition( resourceSyncConditions, hivev1.ApplySuccessSyncCondition, successStatus, reason, message, updateCondition) resourceSyncConditions = controllerutils.SetSyncCondition( resourceSyncConditions, hivev1.ApplyFailureSyncCondition, failureStatus, reason, message, updateCondition) // If we are reporting that apply succeeded or failed, it means we no longer // want to delete this resource. Set that failure condition to false in case // it was previously set to true. resourceSyncConditions = controllerutils.SetSyncCondition( resourceSyncConditions, hivev1.DeletionFailedSyncCondition, corev1.ConditionFalse, reason, message, updateCondition) return resourceSyncConditions } func (r *ReconcileSyncSetInstance) setDeletionFailedSyncCondition(resourceSyncConditions []hivev1.SyncCondition, err error) []hivev1.SyncCondition { if err == nil { return resourceSyncConditions } return controllerutils.SetSyncCondition( resourceSyncConditions, hivev1.DeletionFailedSyncCondition, corev1.ConditionTrue, deletionFailedReason, fmt.Sprintf("Failed to delete resource: %v", err), controllerutils.UpdateConditionAlways) } func (r *ReconcileSyncSetInstance) resourceHash(data []byte) string { return fmt.Sprintf("%x", md5.Sum(data)) }
1
8,536
@abutcher Is it a safe assumption that secrets are the only objects that need to get attached to syncsets?
openshift-hive
go
@@ -1605,7 +1605,8 @@ func (o *consumer) needAck(sseq uint64) bool { state, err := o.store.State() if err != nil || state == nil { o.mu.RUnlock() - return false + // Fall back to what we track internally for now. + return sseq > o.asflr } asflr, osseq = state.AckFloor.Stream, o.sseq pending = state.Pending
1
// Copyright 2019-2021 The NATS 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 server import ( "bytes" "encoding/binary" "encoding/json" "errors" "fmt" "math/rand" "reflect" "sort" "strconv" "strings" "sync" "sync/atomic" "time" "github.com/nats-io/nuid" "golang.org/x/time/rate" ) type ConsumerInfo struct { Stream string `json:"stream_name"` Name string `json:"name"` Created time.Time `json:"created"` Config *ConsumerConfig `json:"config,omitempty"` Delivered SequencePair `json:"delivered"` AckFloor SequencePair `json:"ack_floor"` NumAckPending int `json:"num_ack_pending"` NumRedelivered int `json:"num_redelivered"` NumWaiting int `json:"num_waiting"` NumPending uint64 `json:"num_pending"` Cluster *ClusterInfo `json:"cluster,omitempty"` } type ConsumerConfig struct { Durable string `json:"durable_name,omitempty"` DeliverSubject string `json:"deliver_subject,omitempty"` DeliverPolicy DeliverPolicy `json:"deliver_policy"` OptStartSeq uint64 `json:"opt_start_seq,omitempty"` OptStartTime *time.Time `json:"opt_start_time,omitempty"` AckPolicy AckPolicy `json:"ack_policy"` AckWait time.Duration `json:"ack_wait,omitempty"` MaxDeliver int `json:"max_deliver,omitempty"` FilterSubject string `json:"filter_subject,omitempty"` ReplayPolicy ReplayPolicy `json:"replay_policy"` RateLimit uint64 `json:"rate_limit_bps,omitempty"` // Bits per sec SampleFrequency string `json:"sample_freq,omitempty"` MaxWaiting int `json:"max_waiting,omitempty"` MaxAckPending int `json:"max_ack_pending,omitempty"` Heartbeat time.Duration `json:"idle_heartbeat,omitempty"` FlowControl bool `json:"flow_control,omitempty"` // Don't add to general clients. Direct bool `json:"direct,omitempty"` } type CreateConsumerRequest struct { Stream string `json:"stream_name"` Config ConsumerConfig `json:"config"` } // DeliverPolicy determines how the consumer should select the first message to deliver. type DeliverPolicy int const ( // DeliverAll will be the default so can be omitted from the request. DeliverAll DeliverPolicy = iota // DeliverLast will start the consumer with the last sequence received. DeliverLast // DeliverNew will only deliver new messages that are sent after the consumer is created. DeliverNew // DeliverByStartSequence will look for a defined starting sequence to start. DeliverByStartSequence // DeliverByStartTime will select the first messsage with a timestamp >= to StartTime DeliverByStartTime ) func (dp DeliverPolicy) String() string { switch dp { case DeliverAll: return "all" case DeliverLast: return "last" case DeliverNew: return "new" case DeliverByStartSequence: return "by_start_sequence" case DeliverByStartTime: return "by_start_time" default: return "undefined" } } // AckPolicy determines how the consumer should acknowledge delivered messages. type AckPolicy int const ( // AckNone requires no acks for delivered messages. AckNone AckPolicy = iota // AckAll when acking a sequence number, this implicitly acks all sequences below this one as well. AckAll // AckExplicit requires ack or nack for all messages. AckExplicit ) func (a AckPolicy) String() string { switch a { case AckNone: return "none" case AckAll: return "all" default: return "explicit" } } // ReplayPolicy determines how the consumer should replay messages it already has queued in the stream. type ReplayPolicy int const ( // ReplayInstant will replay messages as fast as possible. ReplayInstant ReplayPolicy = iota // ReplayOriginal will maintain the same timing as the messages were received. ReplayOriginal ) func (r ReplayPolicy) String() string { switch r { case ReplayInstant: return "instant" default: return "original" } } // OK const OK = "+OK" // Ack responses. Note that a nil or no payload is same as AckAck var ( // Ack AckAck = []byte("+ACK") // nil or no payload to ack subject also means ACK AckOK = []byte(OK) // deprecated but +OK meant ack as well. // Nack AckNak = []byte("-NAK") // Progress indicator AckProgress = []byte("+WPI") // Ack + Deliver the next message(s). AckNext = []byte("+NXT") // Terminate delivery of the message. AckTerm = []byte("+TERM") ) // Consumer is a jetstream consumer. type consumer struct { mu sync.RWMutex js *jetStream mset *stream acc *Account srv *Server client *client sysc *client sid int name string stream string sseq uint64 dseq uint64 adflr uint64 asflr uint64 sgap uint64 dsubj string rlimit *rate.Limiter reqSub *subscription ackSub *subscription ackReplyT string ackSubj string nextMsgSubj string maxp int pblimit int maxpb int pbytes int fcsz int fcid string fcSub *subscription outq *jsOutQ pending map[uint64]*Pending ptmr *time.Timer rdq []uint64 rdqi map[uint64]struct{} rdc map[uint64]uint64 maxdc uint64 waiting *waitQueue cfg ConsumerConfig store ConsumerStore active bool replay bool filterWC bool dtmr *time.Timer gwdtmr *time.Timer dthresh time.Duration mch chan struct{} qch chan struct{} inch chan bool sfreq int32 ackEventT string deliveryExcEventT string created time.Time closed bool // Clustered. ca *consumerAssignment node RaftNode infoSub *subscription lqsent time.Time // R>1 proposals pch chan struct{} phead *proposal ptail *proposal } type proposal struct { data []byte next *proposal } const ( // JsAckWaitDefault is the default AckWait, only applicable on explicit ack policy consumers. JsAckWaitDefault = 30 * time.Second // JsDeleteWaitTimeDefault is the default amount of time we will wait for non-durable // consumers to be in an inactive state before deleting them. JsDeleteWaitTimeDefault = 5 * time.Second // JsFlowControlMaxPending specifies default pending bytes during flow control that can be // outstanding. JsFlowControlMaxPending = 1 * 1024 * 1024 // JsDefaultMaxAckPending is set for consumers with explicit ack that do not set the max ack pending. JsDefaultMaxAckPending = 20_000 ) func (mset *stream) addConsumer(config *ConsumerConfig) (*consumer, error) { return mset.addConsumerWithAssignment(config, _EMPTY_, nil) } func (mset *stream) addConsumerWithAssignment(config *ConsumerConfig, oname string, ca *consumerAssignment) (*consumer, error) { mset.mu.RLock() s, jsa := mset.srv, mset.jsa mset.mu.RUnlock() // If we do not have the consumer currently assigned to us in cluster mode we will proceed but warn. // This can happen on startup with restored state where on meta replay we still do not have // the assignment. Running in single server mode this always returns true. if oname != _EMPTY_ && !jsa.consumerAssigned(mset.name(), oname) { s.Debugf("Consumer %q > %q does not seem to be assigned to this server", mset.name(), oname) } if config == nil { return nil, fmt.Errorf("consumer config required") } var err error // For now expect a literal subject if its not empty. Empty means work queue mode (pull mode). if config.DeliverSubject != _EMPTY_ { if !subjectIsLiteral(config.DeliverSubject) { return nil, fmt.Errorf("consumer deliver subject has wildcards") } if mset.deliveryFormsCycle(config.DeliverSubject) { return nil, fmt.Errorf("consumer deliver subject forms a cycle") } if config.MaxWaiting != 0 { return nil, fmt.Errorf("consumer in push mode can not set max waiting") } if config.MaxAckPending > 0 && config.AckPolicy == AckNone { return nil, fmt.Errorf("consumer requires ack policy for max ack pending") } if config.Heartbeat > 0 && config.Heartbeat < 100*time.Millisecond { return nil, fmt.Errorf("consumer idle heartbeat needs to be >= 100ms") } } else { // Pull mode / work queue mode require explicit ack. if config.AckPolicy != AckExplicit { return nil, fmt.Errorf("consumer in pull mode requires explicit ack policy") } // They are also required to be durable since otherwise we will not know when to // clean them up. if config.Durable == _EMPTY_ { return nil, fmt.Errorf("consumer in pull mode requires a durable name") } if config.RateLimit > 0 { return nil, fmt.Errorf("consumer in pull mode can not have rate limit set") } if config.MaxWaiting < 0 { return nil, fmt.Errorf("consumer max waiting needs to be positive") } // Set to default if not specified. if config.MaxWaiting == 0 { config.MaxWaiting = JSWaitQueueDefaultMax } if config.Heartbeat > 0 { return nil, fmt.Errorf("consumer idle heartbeat requires a push based consumer") } if config.FlowControl { return nil, fmt.Errorf("consumer flow control requires a push based consumer") } } // Direct need to be non-mapped ephemerals. if config.Direct { if config.DeliverSubject == _EMPTY_ { return nil, fmt.Errorf("consumer direct requires a push based consumer") } if isDurableConsumer(config) { return nil, fmt.Errorf("consumer direct requires an ephemeral consumer") } if ca != nil { return nil, fmt.Errorf("consumer direct on a mapped consumer") } } // Setup proper default for ack wait if we are in explicit ack mode. if config.AckWait == 0 && (config.AckPolicy == AckExplicit || config.AckPolicy == AckAll) { config.AckWait = JsAckWaitDefault } // Setup default of -1, meaning no limit for MaxDeliver. if config.MaxDeliver == 0 { config.MaxDeliver = -1 } // Set proper default for max ack pending if we are ack explicit and none has been set. if config.AckPolicy == AckExplicit && config.MaxAckPending == 0 { config.MaxAckPending = JsDefaultMaxAckPending } // Make sure any partition subject is also a literal. if config.FilterSubject != _EMPTY_ { subjects, hasExt := mset.allSubjects() if !validFilteredSubject(config.FilterSubject, subjects) && !hasExt { return nil, fmt.Errorf("consumer filter subject is not a valid subset of the interest subjects") } } // Check on start position conflicts. switch config.DeliverPolicy { case DeliverAll: if config.OptStartSeq > 0 { return nil, fmt.Errorf("consumer delivery policy is deliver all, but optional start sequence is also set") } if config.OptStartTime != nil { return nil, fmt.Errorf("consumer delivery policy is deliver all, but optional start time is also set") } case DeliverLast: if config.OptStartSeq > 0 { return nil, fmt.Errorf("consumer delivery policy is deliver last, but optional start sequence is also set") } if config.OptStartTime != nil { return nil, fmt.Errorf("consumer delivery policy is deliver last, but optional start time is also set") } case DeliverNew: if config.OptStartSeq > 0 { return nil, fmt.Errorf("consumer delivery policy is deliver new, but optional start sequence is also set") } if config.OptStartTime != nil { return nil, fmt.Errorf("consumer delivery policy is deliver new, but optional start time is also set") } case DeliverByStartSequence: if config.OptStartSeq == 0 { return nil, fmt.Errorf("consumer delivery policy is deliver by start sequence, but optional start sequence is not set") } if config.OptStartTime != nil { return nil, fmt.Errorf("consumer delivery policy is deliver by start sequence, but optional start time is also set") } case DeliverByStartTime: if config.OptStartTime == nil { return nil, fmt.Errorf("consumer delivery policy is deliver by start time, but optional start time is not set") } if config.OptStartSeq != 0 { return nil, fmt.Errorf("consumer delivery policy is deliver by start time, but optional start sequence is also set") } } sampleFreq := 0 if config.SampleFrequency != "" { s := strings.TrimSuffix(config.SampleFrequency, "%") sampleFreq, err = strconv.Atoi(s) if err != nil { return nil, fmt.Errorf("failed to parse consumer sampling configuration: %v", err) } } // Grab the client, account and server reference. c := mset.client if c == nil { return nil, fmt.Errorf("stream not valid") } c.mu.Lock() s, a := c.srv, c.acc c.mu.Unlock() // Hold mset lock here. mset.mu.Lock() // If this one is durable and already exists, we let that be ok as long as the configs match. if isDurableConsumer(config) { if eo, ok := mset.consumers[config.Durable]; ok { mset.mu.Unlock() ocfg := eo.config() if reflect.DeepEqual(&ocfg, config) { return eo, nil } else { // If we are a push mode and not active and the only difference // is deliver subject then update and return. if configsEqualSansDelivery(ocfg, *config) && eo.hasNoLocalInterest() { eo.updateDeliverSubject(config.DeliverSubject) return eo, nil } else { return nil, fmt.Errorf("consumer already exists") } } } } // Check for any limits, if the config for the consumer sets a limit we check against that // but if not we use the value from account limits, if account limits is more restrictive // than stream config we prefer the account limits to handle cases where account limits are // updated during the lifecycle of the stream maxc := mset.cfg.MaxConsumers if mset.cfg.MaxConsumers <= 0 || mset.jsa.limits.MaxConsumers < mset.cfg.MaxConsumers { maxc = mset.jsa.limits.MaxConsumers } if maxc > 0 && len(mset.consumers) >= maxc { mset.mu.Unlock() return nil, fmt.Errorf("maximum consumers limit reached") } // Check on stream type conflicts with WorkQueues. if mset.cfg.Retention == WorkQueuePolicy && !config.Direct { // Force explicit acks here. if config.AckPolicy != AckExplicit { mset.mu.Unlock() return nil, fmt.Errorf("workqueue stream requires explicit ack") } if len(mset.consumers) > 0 { if config.FilterSubject == _EMPTY_ { mset.mu.Unlock() return nil, fmt.Errorf("multiple non-filtered consumers not allowed on workqueue stream") } else if !mset.partitionUnique(config.FilterSubject) { // We have a partition but it is not unique amongst the others. mset.mu.Unlock() return nil, fmt.Errorf("filtered consumer not unique on workqueue stream") } } if config.DeliverPolicy != DeliverAll { mset.mu.Unlock() return nil, fmt.Errorf("consumer must be deliver all on workqueue stream") } } // Set name, which will be durable name if set, otherwise we create one at random. o := &consumer{ mset: mset, js: s.getJetStream(), acc: a, srv: s, client: s.createInternalJetStreamClient(), sysc: s.createInternalJetStreamClient(), cfg: *config, dsubj: config.DeliverSubject, outq: mset.outq, active: true, qch: make(chan struct{}), mch: make(chan struct{}, 1), sfreq: int32(sampleFreq), maxdc: uint64(config.MaxDeliver), maxp: config.MaxAckPending, created: time.Now().UTC(), } // Bind internal client to the user account. o.client.registerWithAccount(a) // Bind to the system account. o.sysc.registerWithAccount(s.SystemAccount()) if isDurableConsumer(config) { if len(config.Durable) > JSMaxNameLen { mset.mu.Unlock() return nil, fmt.Errorf("consumer name is too long, maximum allowed is %d", JSMaxNameLen) } o.name = config.Durable if o.isPullMode() { o.waiting = newWaitQueue(config.MaxWaiting) } } else if oname != _EMPTY_ { o.name = oname } else { for { o.name = createConsumerName() if _, ok := mset.consumers[o.name]; !ok { break } } } // Check if we have a rate limit set. if config.RateLimit != 0 { // TODO(dlc) - Make sane values or error if not sane? // We are configured in bits per sec so adjust to bytes. rl := rate.Limit(config.RateLimit / 8) // Burst should be set to maximum msg size for this account, etc. var burst int if mset.cfg.MaxMsgSize > 0 { burst = int(mset.cfg.MaxMsgSize) } else if mset.jsa.account.limits.mpay > 0 { burst = int(mset.jsa.account.limits.mpay) } else { s := mset.jsa.account.srv burst = int(s.getOpts().MaxPayload) } o.rlimit = rate.NewLimiter(rl, burst) } // Check if we have filtered subject that is a wildcard. if config.FilterSubject != _EMPTY_ && subjectHasWildcard(config.FilterSubject) { o.filterWC = true } // already under lock, mset.Name() would deadlock o.stream = mset.cfg.Name o.ackEventT = JSMetricConsumerAckPre + "." + o.stream + "." + o.name o.deliveryExcEventT = JSAdvisoryConsumerMaxDeliveryExceedPre + "." + o.stream + "." + o.name if !config.Direct { store, err := mset.store.ConsumerStore(o.name, config) if err != nil { mset.mu.Unlock() o.deleteWithoutAdvisory() return nil, fmt.Errorf("error creating store for consumer: %v", err) } o.store = store } if !isValidName(o.name) { mset.mu.Unlock() o.deleteWithoutAdvisory() return nil, fmt.Errorf("durable name can not contain '.', '*', '>'") } // Select starting sequence number o.selectStartingSeqNo() // Now register with mset and create the ack subscription. // Check if we already have this one registered. if eo, ok := mset.consumers[o.name]; ok { mset.mu.Unlock() if !o.isDurable() || !o.isPushMode() { o.name = _EMPTY_ // Prevent removal since same name. o.deleteWithoutAdvisory() return nil, fmt.Errorf("consumer already exists") } // If we are here we have already registered this durable. If it is still active that is an error. if eo.isActive() { o.name = _EMPTY_ // Prevent removal since same name. o.deleteWithoutAdvisory() return nil, fmt.Errorf("consumer already exists and is still active") } // Since we are here this means we have a potentially new durable so we should update here. // Check that configs are the same. if !configsEqualSansDelivery(o.cfg, eo.cfg) { o.name = _EMPTY_ // Prevent removal since same name. o.deleteWithoutAdvisory() return nil, fmt.Errorf("consumer replacement durable config not the same") } // Once we are here we have a replacement push-based durable. eo.updateDeliverSubject(o.cfg.DeliverSubject) return eo, nil } // Set up the ack subscription for this consumer. Will use wildcard for all acks. // We will remember the template to generate replies with sequence numbers and use // that to scanf them back in. mn := mset.cfg.Name pre := fmt.Sprintf(jsAckT, mn, o.name) o.ackReplyT = fmt.Sprintf("%s.%%d.%%d.%%d.%%d.%%d", pre) o.ackSubj = fmt.Sprintf("%s.*.*.*.*.*", pre) o.nextMsgSubj = fmt.Sprintf(JSApiRequestNextT, mn, o.name) if o.isPushMode() { o.dthresh = JsDeleteWaitTimeDefault if !o.isDurable() { // Check if we are not durable that the delivery subject has interest. // Check in place here for interest. Will setup properly in setLeader. r := o.acc.sl.Match(o.cfg.DeliverSubject) if !o.hasDeliveryInterest(len(r.psubs)+len(r.qsubs) > 0) { // Directs can let the interest come to us eventually, but setup delete timer. if config.Direct { o.updateDeliveryInterest(false) } else { mset.mu.Unlock() o.deleteWithoutAdvisory() return nil, errNoInterest } } } } // Set our ca. if ca != nil { o.setConsumerAssignment(ca) } mset.setConsumer(o) mset.mu.Unlock() if config.Direct || (!s.JetStreamIsClustered() && s.standAloneMode()) { o.setLeader(true) } // This is always true in single server mode. if o.isLeader() { // Send advisory. var suppress bool if !s.standAloneMode() && ca == nil { suppress = true } else if ca != nil { suppress = ca.responded } if !suppress { o.sendCreateAdvisory() } } return o, nil } func (o *consumer) consumerAssignment() *consumerAssignment { o.mu.RLock() defer o.mu.RUnlock() return o.ca } func (o *consumer) setConsumerAssignment(ca *consumerAssignment) { o.mu.Lock() defer o.mu.Unlock() o.ca = ca // Set our node. if ca != nil { o.node = ca.Group.node } } // Lock should be held. func (o *consumer) isLeader() bool { if o.node != nil { return o.node.Leader() } return true } func (o *consumer) setLeader(isLeader bool) { o.mu.RLock() mset := o.mset isRunning := o.ackSub != nil o.mu.RUnlock() // If we are here we have a change in leader status. if isLeader { if mset == nil || isRunning { return } mset.mu.RLock() s, jsa, stream := mset.srv, mset.jsa, mset.cfg.Name mset.mu.RUnlock() o.mu.Lock() // Restore our saved state. During non-leader status we just update our underlying store. o.readStoredState() // Do info sub. if o.infoSub == nil && jsa != nil { isubj := fmt.Sprintf(clusterConsumerInfoT, jsa.acc(), stream, o.name) // Note below the way we subscribe here is so that we can send requests to ourselves. o.infoSub, _ = s.systemSubscribe(isubj, _EMPTY_, false, o.sysc, o.handleClusterConsumerInfoRequest) } var err error if o.ackSub, err = o.subscribeInternal(o.ackSubj, o.processAck); err != nil { o.mu.Unlock() o.deleteWithoutAdvisory() return } // Setup the internal sub for next message requests regardless. // Will error if wrong mode to provide feedback to users. if o.reqSub, err = o.subscribeInternal(o.nextMsgSubj, o.processNextMsgReq); err != nil { o.mu.Unlock() o.deleteWithoutAdvisory() return } // Check on flow control settings. if o.cfg.FlowControl { o.setMaxPendingBytes(JsFlowControlMaxPending) fcsubj := fmt.Sprintf(jsFlowControl, stream, o.name) if o.fcSub, err = o.subscribeInternal(fcsubj, o.processFlowControl); err != nil { o.mu.Unlock() o.deleteWithoutAdvisory() return } } // Setup initial pending. o.setInitialPending() // If push mode, register for notifications on interest. if o.isPushMode() { o.inch = make(chan bool, 8) o.acc.sl.RegisterNotification(o.cfg.DeliverSubject, o.inch) if o.active = <-o.inch; !o.active { // Check gateways in case they are enabled. if s.gateway.enabled { o.active = s.hasGatewayInterest(o.acc.Name, o.cfg.DeliverSubject) stopAndClearTimer(&o.gwdtmr) o.gwdtmr = time.AfterFunc(time.Second, func() { o.watchGWinterest() }) } } } // If we are not in ReplayInstant mode mark us as in replay state until resolved. if o.cfg.ReplayPolicy != ReplayInstant { o.replay = true } // Recreate quit channel. o.qch = make(chan struct{}) qch := o.qch node := o.node if node != nil && o.pch == nil { o.pch = make(chan struct{}, 1) } o.mu.Unlock() // Now start up Go routine to deliver msgs. go o.loopAndGatherMsgs(qch) // If we are R>1 spin up our proposal loop. if node != nil { go o.loopAndForwardProposals(qch) } } else { // Shutdown the go routines and the subscriptions. o.mu.Lock() o.unsubscribe(o.ackSub) o.unsubscribe(o.reqSub) o.unsubscribe(o.fcSub) o.ackSub = nil o.reqSub = nil o.fcSub = nil if o.infoSub != nil { o.srv.sysUnsubscribe(o.infoSub) o.infoSub = nil } if o.qch != nil { close(o.qch) o.qch = nil } o.mu.Unlock() } } func (o *consumer) handleClusterConsumerInfoRequest(sub *subscription, c *client, subject, reply string, msg []byte) { o.mu.RLock() sysc := o.sysc o.mu.RUnlock() sysc.sendInternalMsg(reply, _EMPTY_, nil, o.info()) } // Lock should be held. func (o *consumer) subscribeInternal(subject string, cb msgHandler) (*subscription, error) { c := o.client if c == nil { return nil, fmt.Errorf("invalid consumer") } if !c.srv.eventsEnabled() { return nil, ErrNoSysAccount } if cb == nil { return nil, fmt.Errorf("undefined message handler") } o.sid++ // Now create the subscription return c.processSub([]byte(subject), nil, []byte(strconv.Itoa(o.sid)), cb, false) } // Unsubscribe from our subscription. // Lock should be held. func (o *consumer) unsubscribe(sub *subscription) { if sub == nil || o.client == nil { return } o.client.processUnsub(sub.sid) } // We need to make sure we protect access to the outq. // Do all advisory sends here. func (o *consumer) sendAdvisory(subj string, msg []byte) { o.outq.send(&jsPubMsg{subj, subj, _EMPTY_, nil, msg, nil, 0, nil}) } func (o *consumer) sendDeleteAdvisoryLocked() { e := JSConsumerActionAdvisory{ TypedEvent: TypedEvent{ Type: JSConsumerActionAdvisoryType, ID: nuid.Next(), Time: time.Now().UTC(), }, Stream: o.stream, Consumer: o.name, Action: DeleteEvent, } j, err := json.Marshal(e) if err != nil { return } subj := JSAdvisoryConsumerDeletedPre + "." + o.stream + "." + o.name o.sendAdvisory(subj, j) } func (o *consumer) sendCreateAdvisory() { o.mu.Lock() defer o.mu.Unlock() e := JSConsumerActionAdvisory{ TypedEvent: TypedEvent{ Type: JSConsumerActionAdvisoryType, ID: nuid.Next(), Time: time.Now().UTC(), }, Stream: o.stream, Consumer: o.name, Action: CreateEvent, } j, err := json.Marshal(e) if err != nil { return } subj := JSAdvisoryConsumerCreatedPre + "." + o.stream + "." + o.name o.sendAdvisory(subj, j) } // Created returns created time. func (o *consumer) createdTime() time.Time { o.mu.Lock() created := o.created o.mu.Unlock() return created } // Internal to allow creation time to be restored. func (o *consumer) setCreatedTime(created time.Time) { o.mu.Lock() o.created = created o.mu.Unlock() } // This will check for extended interest in a subject. If we have local interest we just return // that, but in the absence of local interest and presence of gateways or service imports we need // to check those as well. func (o *consumer) hasDeliveryInterest(localInterest bool) bool { o.mu.Lock() mset := o.mset if mset == nil { o.mu.Unlock() return false } acc := o.acc deliver := o.cfg.DeliverSubject o.mu.Unlock() if localInterest { return true } // If we are here check gateways. if s := acc.srv; s != nil && s.hasGatewayInterest(acc.Name, deliver) { return true } return false } func (s *Server) hasGatewayInterest(account, subject string) bool { gw := s.gateway if !gw.enabled { return false } gw.RLock() defer gw.RUnlock() for _, gwc := range gw.outo { psi, qr := gwc.gatewayInterest(account, subject) if psi || qr != nil { return true } } return false } // This processes an update to the local interest for a deliver subject. func (o *consumer) updateDeliveryInterest(localInterest bool) bool { interest := o.hasDeliveryInterest(localInterest) o.mu.Lock() defer o.mu.Unlock() mset := o.mset if mset == nil || o.isPullMode() { return false } if interest && !o.active { o.signalNewMessages() } o.active = interest // If the delete timer has already been set do not clear here and return. if o.dtmr != nil && !o.isDurable() && !interest { return true } // Stop and clear the delete timer always. stopAndClearTimer(&o.dtmr) // If we do not have interest anymore and we are not durable start // a timer to delete us. We wait for a bit in case of server reconnect. if !o.isDurable() && !interest { o.dtmr = time.AfterFunc(o.dthresh, func() { o.deleteNotActive() }) return true } return false } func (o *consumer) deleteNotActive() { // Need to check again if there is not an interest now that the timer fires. if !o.hasNoLocalInterest() { return } o.mu.RLock() if o.mset == nil { o.mu.RUnlock() return } s, js := o.mset.srv, o.mset.srv.js acc, stream, name := o.acc.Name, o.stream, o.name o.mu.RUnlock() // If we are clustered, check if we still have this consumer assigned. // If we do forward a proposal to delete ourselves to the metacontroller leader. if s.JetStreamIsClustered() { js.mu.RLock() ca := js.consumerAssignment(acc, stream, name) cc := js.cluster js.mu.RUnlock() if ca != nil && cc != nil { cca := *ca cca.Reply = _EMPTY_ meta, removeEntry := cc.meta, encodeDeleteConsumerAssignment(&cca) meta.ForwardProposal(removeEntry) // Check to make sure we went away. // Don't think this needs to be a monitored go routine. go func() { ticker := time.NewTicker(time.Second) defer ticker.Stop() for range ticker.C { js.mu.RLock() ca := js.consumerAssignment(acc, stream, name) js.mu.RUnlock() if ca != nil { s.Warnf("Consumer assignment not cleaned up, retrying") meta.ForwardProposal(removeEntry) } else { return } } }() } } // We will delete here regardless. o.delete() } func (o *consumer) watchGWinterest() { pa := o.isActive() // If there is no local interest... if o.hasNoLocalInterest() { o.updateDeliveryInterest(false) if !pa && o.isActive() { o.signalNewMessages() } } // We want this to always be running so we can also pick up on interest returning. o.mu.Lock() if o.gwdtmr != nil { o.gwdtmr.Reset(time.Second) } else { stopAndClearTimer(&o.gwdtmr) o.gwdtmr = time.AfterFunc(time.Second, func() { o.watchGWinterest() }) } o.mu.Unlock() } // Config returns the consumer's configuration. func (o *consumer) config() ConsumerConfig { o.mu.Lock() defer o.mu.Unlock() return o.cfg } // Force expiration of all pending. // Lock should be held. func (o *consumer) forceExpirePending() { var expired []uint64 for seq := range o.pending { if !o.onRedeliverQueue(seq) { expired = append(expired, seq) } } if len(expired) > 0 { sort.Slice(expired, func(i, j int) bool { return expired[i] < expired[j] }) o.addToRedeliverQueue(expired...) // Now we should update the timestamp here since we are redelivering. // We will use an incrementing time to preserve order for any other redelivery. off := time.Now().UnixNano() - o.pending[expired[0]].Timestamp for _, seq := range expired { if p, ok := o.pending[seq]; ok && p != nil { p.Timestamp += off } } o.ptmr.Reset(o.ackWait(0)) } o.signalNewMessages() } // This is a config change for the delivery subject for a // push based consumer. func (o *consumer) updateDeliverSubject(newDeliver string) { // Update the config and the dsubj o.mu.Lock() defer o.mu.Unlock() if o.closed || o.isPullMode() || o.cfg.DeliverSubject == newDeliver { return } // Force redeliver of all pending on change of delivery subject. if len(o.pending) > 0 { o.forceExpirePending() } o.acc.sl.ClearNotification(o.dsubj, o.inch) o.dsubj, o.cfg.DeliverSubject = newDeliver, newDeliver // When we register new one it will deliver to update state loop. o.acc.sl.RegisterNotification(newDeliver, o.inch) } // Check that configs are equal but allow delivery subjects to be different. func configsEqualSansDelivery(a, b ConsumerConfig) bool { // These were copied in so can set Delivery here. a.DeliverSubject, b.DeliverSubject = _EMPTY_, _EMPTY_ return a == b } // Helper to send a reply to an ack. func (o *consumer) sendAckReply(subj string) { o.mu.Lock() defer o.mu.Unlock() o.sendAdvisory(subj, nil) } // Process a message for the ack reply subject delivered with a message. func (o *consumer) processAck(_ *subscription, c *client, subject, reply string, rmsg []byte) { _, msg := c.msgParts(rmsg) sseq, dseq, dc := ackReplyInfo(subject) skipAckReply := sseq == 0 switch { case len(msg) == 0, bytes.Equal(msg, AckAck), bytes.Equal(msg, AckOK): o.ackMsg(sseq, dseq, dc) case bytes.HasPrefix(msg, AckNext): o.ackMsg(sseq, dseq, dc) // processNextMsgReq can be invoked from an internal subscription or from here. // Therefore, it has to call msgParts(), so we can't simply pass msg[len(AckNext):] // with current c.pa.hdr because it would cause a panic. We will save the current // c.pa.hdr value and disable headers before calling processNextMsgReq and then // restore so that we don't mess with the calling stack in case it is used // somewhere else. phdr := c.pa.hdr c.pa.hdr = -1 o.processNextMsgReq(nil, c, subject, reply, msg[len(AckNext):]) c.pa.hdr = phdr skipAckReply = true case bytes.Equal(msg, AckNak): o.processNak(sseq, dseq) case bytes.Equal(msg, AckProgress): o.progressUpdate(sseq) case bytes.Equal(msg, AckTerm): o.processTerm(sseq, dseq, dc) } // Ack the ack if requested. if len(reply) > 0 && !skipAckReply { o.sendAckReply(reply) } } // Used to process a working update to delay redelivery. func (o *consumer) progressUpdate(seq uint64) { o.mu.Lock() if len(o.pending) > 0 { if p, ok := o.pending[seq]; ok { p.Timestamp = time.Now().UnixNano() // Update store system. o.updateDelivered(p.Sequence, seq, 1, p.Timestamp) } } o.mu.Unlock() } // Lock should be held. func (o *consumer) updateSkipped() { // Clustered mode and R>1 only. if o.node == nil || !o.isLeader() { return } var b [1 + 8]byte b[0] = byte(updateSkipOp) var le = binary.LittleEndian le.PutUint64(b[1:], o.sseq) o.propose(b[:]) } func (o *consumer) loopAndForwardProposals(qch chan struct{}) { o.mu.RLock() node, pch := o.node, o.pch o.mu.RUnlock() if node == nil || pch == nil { return } forwardProposals := func() { o.mu.Lock() proposal := o.phead o.phead, o.ptail = nil, nil o.mu.Unlock() // 256k max for now per batch. const maxBatch = 256 * 1024 var entries []*Entry for sz := 0; proposal != nil; proposal = proposal.next { entries = append(entries, &Entry{EntryNormal, proposal.data}) sz += len(proposal.data) if sz > maxBatch { node.ProposeDirect(entries) sz, entries = 0, entries[:0] } } if len(entries) > 0 { node.ProposeDirect(entries) } } for { select { case <-qch: forwardProposals() return case <-pch: forwardProposals() } } } // Lock should be held. func (o *consumer) propose(entry []byte) { var notify bool p := &proposal{data: entry} if o.phead == nil { o.phead = p notify = true } else { o.ptail.next = p } o.ptail = p // Kick our looper routine if needed. if notify { select { case o.pch <- struct{}{}: default: } } } // Lock should be held. func (o *consumer) updateDelivered(dseq, sseq, dc uint64, ts int64) { // Clustered mode and R>1. if o.node != nil { // Inline for now, use variable compression. var b [4*binary.MaxVarintLen64 + 1]byte b[0] = byte(updateDeliveredOp) n := 1 n += binary.PutUvarint(b[n:], dseq) n += binary.PutUvarint(b[n:], sseq) n += binary.PutUvarint(b[n:], dc) n += binary.PutVarint(b[n:], ts) o.propose(b[:n]) } if o.store != nil { // Update local state always. o.store.UpdateDelivered(dseq, sseq, dc, ts) } } // Lock should be held. func (o *consumer) updateAcks(dseq, sseq uint64) { if o.node != nil { // Inline for now, use variable compression. var b [2*binary.MaxVarintLen64 + 1]byte b[0] = byte(updateAcksOp) n := 1 n += binary.PutUvarint(b[n:], dseq) n += binary.PutUvarint(b[n:], sseq) o.propose(b[:n]) } else if o.store != nil { o.store.UpdateAcks(dseq, sseq) } } // Process a NAK. func (o *consumer) processNak(sseq, dseq uint64) { o.mu.Lock() defer o.mu.Unlock() // Check for out of range. if dseq <= o.adflr || dseq > o.dseq { return } // If we are explicit ack make sure this is still on our pending list. if len(o.pending) > 0 { if _, ok := o.pending[sseq]; !ok { return } } // If already queued up also ignore. if !o.onRedeliverQueue(sseq) { o.addToRedeliverQueue(sseq) } o.signalNewMessages() } // Process a TERM func (o *consumer) processTerm(sseq, dseq, dc uint64) { // Treat like an ack to suppress redelivery. o.processAckMsg(sseq, dseq, dc, false) o.mu.Lock() defer o.mu.Unlock() // Deliver an advisory e := JSConsumerDeliveryTerminatedAdvisory{ TypedEvent: TypedEvent{ Type: JSConsumerDeliveryTerminatedAdvisoryType, ID: nuid.Next(), Time: time.Now().UTC(), }, Stream: o.stream, Consumer: o.name, ConsumerSeq: dseq, StreamSeq: sseq, Deliveries: dc, } j, err := json.Marshal(e) if err != nil { return } subj := JSAdvisoryConsumerMsgTerminatedPre + "." + o.stream + "." + o.name o.sendAdvisory(subj, j) } // Introduce a small delay in when timer fires to check pending. // Allows bursts to be treated in same time frame. const ackWaitDelay = time.Millisecond // ackWait returns how long to wait to fire the pending timer. func (o *consumer) ackWait(next time.Duration) time.Duration { if next > 0 { return next + ackWaitDelay } return o.cfg.AckWait + ackWaitDelay } // This will restore the state from disk. func (o *consumer) readStoredState() error { if o.store == nil { return nil } state, err := o.store.State() if err == nil && state != nil { o.applyState(state) } return err } // Apply the consumer stored state. func (o *consumer) applyState(state *ConsumerState) { if state == nil { return } o.dseq = state.Delivered.Consumer + 1 o.sseq = state.Delivered.Stream + 1 o.adflr = state.AckFloor.Consumer o.asflr = state.AckFloor.Stream o.pending = state.Pending o.rdc = state.Redelivered // Setup tracking timer if we have restored pending. if len(o.pending) > 0 && o.ptmr == nil { o.ptmr = time.AfterFunc(o.ackWait(0), o.checkPending) } } func (o *consumer) readStoreState() *ConsumerState { o.mu.RLock() defer o.mu.RUnlock() if o.store == nil { return nil } state, _ := o.store.State() return state } // Sets our store state from another source. Used in clustered mode on snapshot restore. func (o *consumer) setStoreState(state *ConsumerState) error { if state == nil || o.store == nil { return nil } o.applyState(state) return o.store.Update(state) } // Update our state to the store. func (o *consumer) writeStoreState() error { o.mu.Lock() defer o.mu.Unlock() if o.store == nil { return nil } state := ConsumerState{ Delivered: SequencePair{ Consumer: o.dseq - 1, Stream: o.sseq - 1, }, AckFloor: SequencePair{ Consumer: o.adflr, Stream: o.asflr, }, Pending: o.pending, Redelivered: o.rdc, } return o.store.Update(&state) } // Info returns our current consumer state. func (o *consumer) info() *ConsumerInfo { o.mu.RLock() mset := o.mset if mset == nil || mset.srv == nil { o.mu.RUnlock() return nil } js := o.js o.mu.RUnlock() if js == nil { return nil } ci := js.clusterInfo(o.raftGroup()) o.mu.RLock() defer o.mu.RUnlock() cfg := o.cfg info := &ConsumerInfo{ Stream: o.stream, Name: o.name, Created: o.created, Config: &cfg, Delivered: SequencePair{ Consumer: o.dseq - 1, Stream: o.sseq - 1, }, AckFloor: SequencePair{ Consumer: o.adflr, Stream: o.asflr, }, NumAckPending: len(o.pending), NumRedelivered: len(o.rdc), NumPending: o.sgap, Cluster: ci, } // If we are a pull mode consumer, report on number of waiting requests. if o.isPullMode() { info.NumWaiting = o.waiting.len() } return info } // Will signal us that new messages are available. Will break out of waiting. func (o *consumer) signalNewMessages() { // Kick our new message channel select { case o.mch <- struct{}{}: default: } } // shouldSample lets us know if we are sampling metrics on acks. func (o *consumer) shouldSample() bool { switch { case o.sfreq <= 0: return false case o.sfreq >= 100: return true } // TODO(ripienaar) this is a tad slow so we need to rethink here, however this will only // hit for those with sampling enabled and its not the default return rand.Int31n(100) <= o.sfreq } func (o *consumer) sampleAck(sseq, dseq, dc uint64) { if !o.shouldSample() { return } now := time.Now().UTC() unow := now.UnixNano() e := JSConsumerAckMetric{ TypedEvent: TypedEvent{ Type: JSConsumerAckMetricType, ID: nuid.Next(), Time: now, }, Stream: o.stream, Consumer: o.name, ConsumerSeq: dseq, StreamSeq: sseq, Delay: unow - o.pending[sseq].Timestamp, Deliveries: dc, } j, err := json.Marshal(e) if err != nil { return } o.sendAdvisory(o.ackEventT, j) } // Process an ack for a message. func (o *consumer) ackMsg(sseq, dseq, dc uint64) { o.processAckMsg(sseq, dseq, dc, true) } func (o *consumer) processAckMsg(sseq, dseq, dc uint64, doSample bool) { o.mu.Lock() var sagap uint64 var needSignal bool switch o.cfg.AckPolicy { case AckExplicit: if p, ok := o.pending[sseq]; ok { if doSample { o.sampleAck(sseq, dseq, dc) } if o.maxp > 0 && len(o.pending) >= o.maxp { needSignal = true } delete(o.pending, sseq) // Use the original deliver sequence from our pending record. dseq = p.Sequence } if len(o.pending) == 0 { o.adflr, o.asflr = o.dseq-1, o.sseq-1 } else if dseq == o.adflr+1 { o.adflr, o.asflr = dseq, sseq for ss := sseq + 1; ss < o.sseq; ss++ { if p, ok := o.pending[ss]; ok { if p.Sequence > 0 { o.adflr, o.asflr = p.Sequence-1, ss-1 } break } } } // We do these regardless. delete(o.rdc, sseq) o.removeFromRedeliverQueue(sseq) case AckAll: // no-op if dseq <= o.adflr || sseq <= o.asflr { o.mu.Unlock() return } if o.maxp > 0 && len(o.pending) >= o.maxp { needSignal = true } sagap = sseq - o.asflr o.adflr, o.asflr = dseq, sseq for seq := sseq; seq > sseq-sagap; seq-- { delete(o.pending, seq) delete(o.rdc, seq) o.removeFromRedeliverQueue(seq) } case AckNone: // FIXME(dlc) - This is error but do we care? o.mu.Unlock() return } // Update underlying store. o.updateAcks(dseq, sseq) mset := o.mset clustered := o.node != nil o.mu.Unlock() // Let the owning stream know if we are interest or workqueue retention based. // If this consumer is clustered this will be handled by processReplicatedAck // after the ack has propagated. if !clustered && mset != nil && mset.cfg.Retention != LimitsPolicy { if sagap > 1 { // FIXME(dlc) - This is very inefficient, will need to fix. for seq := sseq; seq > sseq-sagap; seq-- { mset.ackMsg(o, seq) } } else { mset.ackMsg(o, sseq) } } // If we had max ack pending set and were at limit we need to unblock folks. if needSignal { o.signalNewMessages() } } // Check if we need an ack for this store seq. // This is called for interest based retention streams to remove messages. func (o *consumer) needAck(sseq uint64) bool { var needAck bool var asflr, osseq uint64 var pending map[uint64]*Pending o.mu.RLock() if o.isLeader() { asflr, osseq = o.asflr, o.sseq pending = o.pending } else { if o.store == nil { o.mu.RUnlock() return false } state, err := o.store.State() if err != nil || state == nil { o.mu.RUnlock() return false } asflr, osseq = state.AckFloor.Stream, o.sseq pending = state.Pending } switch o.cfg.AckPolicy { case AckNone, AckAll: needAck = sseq > asflr case AckExplicit: if sseq > asflr { // Generally this means we need an ack, but just double check pending acks. needAck = true if sseq < osseq { if len(pending) == 0 { needAck = false } else { _, needAck = pending[sseq] } } } } o.mu.RUnlock() return needAck } // Helper for the next message requests. func nextReqFromMsg(msg []byte) (time.Time, int, bool, error) { req := bytes.TrimSpace(msg) switch { case len(req) == 0: return time.Time{}, 1, false, nil case req[0] == '{': var cr JSApiConsumerGetNextRequest if err := json.Unmarshal(req, &cr); err != nil { return time.Time{}, -1, false, err } if cr.Expires == time.Duration(0) { return time.Time{}, cr.Batch, cr.NoWait, nil } return time.Now().Add(cr.Expires), cr.Batch, cr.NoWait, nil default: if n, err := strconv.Atoi(string(req)); err == nil { return time.Time{}, n, false, nil } } return time.Time{}, 1, false, nil } // Represents a request that is on the internal waiting queue type waitingRequest struct { client *client reply string n int // For batching expires time.Time noWait bool } // waiting queue for requests that are waiting for new messages to arrive. type waitQueue struct { rp, wp int reqs []*waitingRequest } // Create a new ring buffer with at most max items. func newWaitQueue(max int) *waitQueue { return &waitQueue{rp: -1, reqs: make([]*waitingRequest, max)} } var ( errWaitQueueFull = errors.New("wait queue is full") errWaitQueueNil = errors.New("wait queue is nil") ) // Adds in a new request. func (wq *waitQueue) add(req *waitingRequest) error { if wq == nil { return errWaitQueueNil } if wq.isFull() { return errWaitQueueFull } wq.reqs[wq.wp] = req // TODO(dlc) - Could make pow2 and get rid of mod. wq.wp = (wq.wp + 1) % cap(wq.reqs) // Adjust read pointer if we were empty. if wq.rp < 0 { wq.rp = 0 } return nil } func (wq *waitQueue) isFull() bool { return wq.rp == wq.wp } func (wq *waitQueue) len() int { if wq == nil || wq.rp < 0 { return 0 } if wq.rp < wq.wp { return wq.wp - wq.rp } return cap(wq.reqs) - wq.rp + wq.wp } // Peek will return the next request waiting or nil if empty. func (wq *waitQueue) peek() *waitingRequest { if wq == nil { return nil } var wr *waitingRequest if wq.rp >= 0 { wr = wq.reqs[wq.rp] } return wr } // pop will return the next request and move the read cursor. func (wq *waitQueue) pop() *waitingRequest { wr := wq.peek() if wr != nil { wr.n-- if wr.n <= 0 { wq.reqs[wq.rp] = nil wq.rp = (wq.rp + 1) % cap(wq.reqs) // Check if we are empty. if wq.rp == wq.wp { wq.rp, wq.wp = -1, 0 } } } return wr } // processNextMsgReq will process a request for the next message available. A nil message payload means deliver // a single message. If the payload is a formal request or a number parseable with Atoi(), then we will send a // batch of messages without requiring another request to this endpoint, or an ACK. func (o *consumer) processNextMsgReq(_ *subscription, c *client, _, reply string, msg []byte) { _, msg = c.msgParts(msg) o.mu.Lock() defer o.mu.Unlock() s, mset, js := o.srv, o.mset, o.js if mset == nil { return } sendErr := func(status int, description string) { hdr := []byte(fmt.Sprintf("NATS/1.0 %d %s\r\n\r\n", status, description)) o.outq.send(&jsPubMsg{reply, _EMPTY_, _EMPTY_, hdr, nil, nil, 0, nil}) } if o.isPushMode() { sendErr(409, "Consumer is push based") return } if o.waiting.isFull() { // Try to expire some of the requests. if expired := o.expireWaiting(); expired == 0 { // Force expiration if needed. o.forceExpireFirstWaiting() } } // Check payload here to see if they sent in batch size or a formal request. expires, batchSize, noWait, err := nextReqFromMsg(msg) if err != nil { sendErr(400, fmt.Sprintf("Bad Request - %v", err)) return } if o.maxp > 0 && batchSize > o.maxp { sendErr(409, "Exceeded MaxAckPending") return } // In case we have to queue up this request. wr := waitingRequest{client: c, reply: reply, n: batchSize, noWait: noWait, expires: expires} // If we are in replay mode, defer to processReplay for delivery. if o.replay { o.waiting.add(&wr) o.signalNewMessages() return } sendBatch := func(wr *waitingRequest) { for i, batchSize := 0, wr.n; i < batchSize; i++ { // See if we have more messages available. if subj, hdr, msg, seq, dc, ts, err := o.getNextMsg(); err == nil { o.deliverMsg(reply, subj, hdr, msg, seq, dc, ts) // Need to discount this from the total n for the request. wr.n-- } else { if wr.noWait { switch err { case errMaxAckPending: sendErr(409, "Exceeded MaxAckPending") default: sendErr(404, "No Messages") } } else { o.waiting.add(wr) } return } } } // If this is direct from a client can proceed inline. if c.kind == CLIENT { sendBatch(&wr) } else { // Check for API outstanding requests. if apiOut := atomic.AddInt64(&js.apiCalls, 1); apiOut > 1024 { atomic.AddInt64(&js.apiCalls, -1) o.mu.Unlock() sendErr(503, "JetStream API limit exceeded") s.Warnf("JetStream API limit exceeded: %d calls outstanding", apiOut) return } // Dispatch the API call to its own Go routine. go func() { o.mu.Lock() sendBatch(&wr) o.mu.Unlock() atomic.AddInt64(&js.apiCalls, -1) }() } } // Increase the delivery count for this message. // ONLY used on redelivery semantics. // Lock should be held. func (o *consumer) incDeliveryCount(sseq uint64) uint64 { if o.rdc == nil { o.rdc = make(map[uint64]uint64) } o.rdc[sseq] += 1 return o.rdc[sseq] + 1 } // send a delivery exceeded advisory. func (o *consumer) notifyDeliveryExceeded(sseq, dc uint64) { e := JSConsumerDeliveryExceededAdvisory{ TypedEvent: TypedEvent{ Type: JSConsumerDeliveryExceededAdvisoryType, ID: nuid.Next(), Time: time.Now().UTC(), }, Stream: o.stream, Consumer: o.name, StreamSeq: sseq, Deliveries: dc, } j, err := json.Marshal(e) if err != nil { return } o.sendAdvisory(o.deliveryExcEventT, j) } // Check to see if the candidate subject matches a filter if its present. // Lock should be held. func (o *consumer) isFilteredMatch(subj string) bool { // No filter is automatic match. if o.cfg.FilterSubject == _EMPTY_ { return true } if !o.filterWC { return subj == o.cfg.FilterSubject } // If we are here we have a wildcard filter subject. // TODO(dlc) at speed might be better to just do a sublist with L2 and/or possibly L1. return subjectIsSubsetMatch(subj, o.cfg.FilterSubject) } var ( errMaxAckPending = errors.New("max ack pending reached") errBadConsumer = errors.New("consumer not valid") errNoInterest = errors.New("consumer requires interest for delivery subject when ephemeral") ) // Get next available message from underlying store. // Is partition aware and redeliver aware. // Lock should be held. func (o *consumer) getNextMsg() (subj string, hdr, msg []byte, seq uint64, dc uint64, ts int64, err error) { if o.mset == nil || o.mset.store == nil { return _EMPTY_, nil, nil, 0, 0, 0, errBadConsumer } for { seq, dc := o.sseq, uint64(1) if o.hasRedeliveries() { seq = o.getNextToRedeliver() dc = o.incDeliveryCount(seq) if o.maxdc > 0 && dc > o.maxdc { // Only send once if dc == o.maxdc+1 { o.notifyDeliveryExceeded(seq, dc-1) } // Make sure to remove from pending. delete(o.pending, seq) continue } } else if o.maxp > 0 && len(o.pending) >= o.maxp { // maxp only set when ack policy != AckNone and user set MaxAckPending // Stall if we have hit max pending. return _EMPTY_, nil, nil, 0, 0, 0, errMaxAckPending } subj, hdr, msg, ts, err := o.mset.store.LoadMsg(seq) if err == nil { if dc == 1 { // First delivery. o.sseq++ if o.cfg.FilterSubject != _EMPTY_ && !o.isFilteredMatch(subj) { o.updateSkipped() continue } } // We have the msg here. return subj, hdr, msg, seq, dc, ts, nil } // We got an error here. If this is an EOF we will return, otherwise // we can continue looking. if err == ErrStoreEOF || err == ErrStoreClosed { return _EMPTY_, nil, nil, 0, 0, 0, err } // Skip since its probably deleted or expired. o.sseq++ } } // forceExpireFirstWaiting will force expire the first waiting. // Lock should be held. func (o *consumer) forceExpireFirstWaiting() *waitingRequest { // FIXME(dlc) - Should we do advisory here as well? wr := o.waiting.pop() if wr == nil { return wr } // If we are expiring this and we think there is still interest, alert. if rr := o.acc.sl.Match(wr.reply); len(rr.psubs)+len(rr.qsubs) > 0 && o.mset != nil { // We still appear to have interest, so send alert as courtesy. hdr := []byte("NATS/1.0 408 Request Timeout\r\n\r\n") o.outq.send(&jsPubMsg{wr.reply, _EMPTY_, _EMPTY_, hdr, nil, nil, 0, nil}) } return wr } // Will check for expiration and lack of interest on waiting requests. func (o *consumer) expireWaiting() int { var expired int now := time.Now() for wr := o.waiting.peek(); wr != nil; wr = o.waiting.peek() { if !wr.expires.IsZero() && now.After(wr.expires) { o.forceExpireFirstWaiting() expired++ continue } s, acc := o.acc.srv, o.acc rr := acc.sl.Match(wr.reply) if len(rr.psubs)+len(rr.qsubs) > 0 { break } // If we are here check on gateways. if s != nil && s.hasGatewayInterest(acc.Name, wr.reply) { break } // No more interest so go ahead and remove this one from our list. o.forceExpireFirstWaiting() expired++ } return expired } // Will check to make sure those waiting still have registered interest. func (o *consumer) checkWaitingForInterest() bool { o.expireWaiting() return o.waiting.len() > 0 } // Lock should be held. func (o *consumer) hbTimer() (time.Duration, *time.Timer) { if o.cfg.Heartbeat == 0 { return 0, nil } return o.cfg.Heartbeat, time.NewTimer(o.cfg.Heartbeat) } func (o *consumer) loopAndGatherMsgs(qch chan struct{}) { // On startup check to see if we are in a a reply situation where replay policy is not instant. var ( lts int64 // last time stamp seen, used for replay. lseq uint64 ) o.mu.Lock() s := o.srv if o.replay { // consumer is closed when mset is set to nil. if o.mset == nil { o.mu.Unlock() return } lseq = o.mset.state().LastSeq } // For idle heartbeat support. var hbc <-chan time.Time hbd, hb := o.hbTimer() if hb != nil { hbc = hb.C } // Interest changes. inch := o.inch o.mu.Unlock() // Deliver all the msgs we have now, once done or on a condition, we wait for new ones. for { var ( seq, dc uint64 subj, dsubj string hdr []byte msg []byte err error ts int64 delay time.Duration ) o.mu.Lock() // consumer is closed when mset is set to nil. if o.mset == nil { o.mu.Unlock() return } // If we are in push mode and not active or under flowcontrol let's stop sending. if o.isPushMode() { if !o.active { goto waitForMsgs } if o.maxpb > 0 && o.pbytes > o.maxpb { goto waitForMsgs } } // If we are in pull mode and no one is waiting already break and wait. if o.isPullMode() && !o.checkWaitingForInterest() { goto waitForMsgs } subj, hdr, msg, seq, dc, ts, err = o.getNextMsg() // On error either wait or return. if err != nil { if err == ErrStoreMsgNotFound || err == ErrStoreEOF || err == errMaxAckPending { goto waitForMsgs } else { o.mu.Unlock() s.Errorf("Received an error looking up message for consumer: %v", err) return } } if wr := o.waiting.pop(); wr != nil { dsubj = wr.reply } else { dsubj = o.dsubj } // If we are in a replay scenario and have not caught up check if we need to delay here. if o.replay && lts > 0 { if delay = time.Duration(ts - lts); delay > time.Millisecond { o.mu.Unlock() select { case <-qch: return case <-time.After(delay): } o.mu.Lock() } } // Track this regardless. lts = ts // If we have a rate limit set make sure we check that here. if o.rlimit != nil { now := time.Now() r := o.rlimit.ReserveN(now, len(msg)+len(hdr)+len(subj)+len(dsubj)+len(o.ackReplyT)) delay := r.DelayFrom(now) if delay > 0 { o.mu.Unlock() select { case <-qch: return case <-time.After(delay): } o.mu.Lock() } } // Do actual delivery. o.deliverMsg(dsubj, subj, hdr, msg, seq, dc, ts) // Reset our idle heartbeat timer if set. if hb != nil { hb.Reset(hbd) } o.mu.Unlock() continue waitForMsgs: // If we were in a replay state check to see if we are caught up. If so clear. if o.replay && o.sseq > lseq { o.replay = false } // We will wait here for new messages to arrive. mch, outq, odsubj, sseq, dseq := o.mch, o.outq, o.cfg.DeliverSubject, o.sseq-1, o.dseq-1 o.mu.Unlock() select { case interest := <-inch: // inch can be nil on pull-based, but then this will // just block and not fire. o.updateDeliveryInterest(interest) case <-qch: return case <-mch: // Messages are waiting. case <-hbc: if o.isActive() { const t = "NATS/1.0 100 Idle Heartbeat\r\n%s: %d\r\n%s: %d\r\n\r\n" hdr := []byte(fmt.Sprintf(t, JSLastConsumerSeq, dseq, JSLastStreamSeq, sseq)) outq.send(&jsPubMsg{odsubj, _EMPTY_, _EMPTY_, hdr, nil, nil, 0, nil}) } // Reset our idle heartbeat timer. hb.Reset(hbd) // Now check on flowcontrol if enabled. Make sure if we have any outstanding to resend. if o.fcOut() { o.sendFlowControl() } } } } func (o *consumer) ackReply(sseq, dseq, dc uint64, ts int64, pending uint64) string { return fmt.Sprintf(o.ackReplyT, dc, sseq, dseq, ts, pending) } // Used mostly for testing. Sets max pending bytes for flow control setups. func (o *consumer) setMaxPendingBytes(limit int) { o.pblimit = limit o.maxpb = limit / 16 if o.maxpb == 0 { o.maxpb = 1 } } // Deliver a msg to the consumer. // Lock should be held and o.mset validated to be non-nil. func (o *consumer) deliverMsg(dsubj, subj string, hdr, msg []byte, seq, dc uint64, ts int64) { if o.mset == nil { return } // Update pending on first attempt if dc == 1 && o.sgap > 0 { o.sgap-- } dseq := o.dseq o.dseq++ pmsg := &jsPubMsg{dsubj, subj, o.ackReply(seq, dseq, dc, ts, o.sgap), hdr, msg, o, seq, nil} if o.maxpb > 0 { o.pbytes += pmsg.size() } mset := o.mset ap := o.cfg.AckPolicy // Send message. o.outq.send(pmsg) // If we are ack none and mset is interest only we should make sure stream removes interest. if ap == AckNone && mset.cfg.Retention != LimitsPolicy && mset.amch != nil { mset.amch <- seq } if ap == AckExplicit || ap == AckAll { o.trackPending(seq, dseq) } else if ap == AckNone { o.adflr = dseq o.asflr = seq } // Flow control. if o.maxpb > 0 && o.needFlowControl() { o.sendFlowControl() } // FIXME(dlc) - Capture errors? o.updateDelivered(dseq, seq, dc, ts) } func (o *consumer) needFlowControl() bool { if o.maxpb == 0 { return false } // Decide whether to send a flow control message which we will need the user to respond. // We send when we are over 50% of our current window limit. if o.fcid == _EMPTY_ && o.pbytes > o.maxpb/2 { return true } return false } func (o *consumer) processFlowControl(_ *subscription, c *client, subj, _ string, _ []byte) { o.mu.Lock() defer o.mu.Unlock() // Ignore if not the latest we have sent out. if subj != o.fcid { return } // For slow starts and ramping up. if o.maxpb < o.pblimit { o.maxpb *= 2 if o.maxpb > o.pblimit { o.maxpb = o.pblimit } } // Update accounting. o.pbytes -= o.fcsz o.fcid, o.fcsz = _EMPTY_, 0 // In case they are sent out of order or we get duplicates etc. if o.pbytes < 0 { o.pbytes = 0 } o.signalNewMessages() } // Lock should be held. func (o *consumer) fcReply() string { var sb strings.Builder sb.WriteString(jsFlowControlPre) sb.WriteString(o.stream) sb.WriteByte(btsep) sb.WriteString(o.name) sb.WriteByte(btsep) var b [4]byte rn := rand.Int63() for i, l := 0, rn; i < len(b); i++ { b[i] = digits[l%base] l /= base } sb.Write(b[:]) return sb.String() } func (o *consumer) fcOut() bool { o.mu.RLock() defer o.mu.RUnlock() return o.fcid != _EMPTY_ } // sendFlowControl will send a flow control packet to the consumer. // Lock should be held. func (o *consumer) sendFlowControl() { if !o.isPushMode() { return } subj, rply := o.cfg.DeliverSubject, o.fcReply() o.fcsz, o.fcid = o.pbytes, rply hdr := []byte("NATS/1.0 100 FlowControl Request\r\n\r\n") o.outq.send(&jsPubMsg{subj, _EMPTY_, rply, hdr, nil, nil, 0, nil}) } // Tracks our outstanding pending acks. Only applicable to AckExplicit mode. // Lock should be held. func (o *consumer) trackPending(sseq, dseq uint64) { if o.pending == nil { o.pending = make(map[uint64]*Pending) } if o.ptmr == nil { o.ptmr = time.AfterFunc(o.ackWait(0), o.checkPending) } if p, ok := o.pending[sseq]; ok { p.Timestamp = time.Now().UnixNano() } else { o.pending[sseq] = &Pending{dseq, time.Now().UnixNano()} } } // didNotDeliver is called when a delivery for a consumer message failed. // Depending on our state, we will process the failure. func (o *consumer) didNotDeliver(seq uint64) { o.mu.Lock() mset := o.mset if mset == nil { o.mu.Unlock() return } var checkDeliveryInterest bool if o.isPushMode() { o.active = false checkDeliveryInterest = true } else if o.pending != nil { // pull mode and we have pending. if _, ok := o.pending[seq]; ok { // We found this messsage on pending, we need // to queue it up for immediate redelivery since // we know it was not delivered. if !o.onRedeliverQueue(seq) { o.addToRedeliverQueue(seq) o.signalNewMessages() } } } o.mu.Unlock() // If we do not have interest update that here. if checkDeliveryInterest && o.hasNoLocalInterest() { o.updateDeliveryInterest(false) } } // Lock should be held. func (o *consumer) addToRedeliverQueue(seqs ...uint64) { if o.rdqi == nil { o.rdqi = make(map[uint64]struct{}) } o.rdq = append(o.rdq, seqs...) for _, seq := range seqs { o.rdqi[seq] = struct{}{} } } // Lock should be held. func (o *consumer) hasRedeliveries() bool { return len(o.rdq) > 0 } func (o *consumer) getNextToRedeliver() uint64 { if len(o.rdq) == 0 { return 0 } seq := o.rdq[0] if len(o.rdq) == 1 { o.rdq, o.rdqi = nil, nil } else { o.rdq = append(o.rdq[:0], o.rdq[1:]...) delete(o.rdqi, seq) } return seq } // This checks if we already have this sequence queued for redelivery. // FIXME(dlc) - This is O(n) but should be fast with small redeliver size. // Lock should be held. func (o *consumer) onRedeliverQueue(seq uint64) bool { if o.rdqi == nil { return false } _, ok := o.rdqi[seq] return ok } // Remove a sequence from the redelivery queue. // Lock should be held. func (o *consumer) removeFromRedeliverQueue(seq uint64) bool { if !o.onRedeliverQueue(seq) { return false } for i, rseq := range o.rdq { if rseq == seq { if len(o.rdq) == 1 { o.rdq, o.rdqi = nil, nil } else { o.rdq = append(o.rdq[:i], o.rdq[i+1:]...) delete(o.rdqi, seq) } return true } } return false } // Checks the pending messages. func (o *consumer) checkPending() { o.mu.Lock() defer o.mu.Unlock() mset := o.mset if mset == nil { return } ttl := int64(o.cfg.AckWait) next := int64(o.ackWait(0)) now := time.Now().UnixNano() // Since we can update timestamps, we have to review all pending. // We may want to unlock here or warn if list is big. var expired []uint64 for seq, p := range o.pending { elapsed := now - p.Timestamp if elapsed >= ttl { if !o.onRedeliverQueue(seq) { expired = append(expired, seq) o.signalNewMessages() } } else if ttl-elapsed < next { // Update when we should fire next. next = ttl - elapsed } } if len(expired) > 0 { // We need to sort. sort.Slice(expired, func(i, j int) bool { return expired[i] < expired[j] }) o.addToRedeliverQueue(expired...) // Now we should update the timestamp here since we are redelivering. // We will use an incrementing time to preserve order for any other redelivery. off := now - o.pending[expired[0]].Timestamp for _, seq := range expired { if p, ok := o.pending[seq]; ok { p.Timestamp += off } } } if len(o.pending) > 0 { o.ptmr.Reset(o.ackWait(time.Duration(next))) } else { o.ptmr.Stop() o.ptmr = nil } } // SeqFromReply will extract a sequence number from a reply subject. func (o *consumer) seqFromReply(reply string) uint64 { _, dseq, _ := ackReplyInfo(reply) return dseq } // StreamSeqFromReply will extract the stream sequence from the reply subject. func (o *consumer) streamSeqFromReply(reply string) uint64 { sseq, _, _ := ackReplyInfo(reply) return sseq } // Quick parser for positive numbers in ack reply encoding. func parseAckReplyNum(d string) (n int64) { if len(d) == 0 { return -1 } for _, dec := range d { if dec < asciiZero || dec > asciiNine { return -1 } n = n*10 + (int64(dec) - asciiZero) } return n } const expectedNumReplyTokens = 9 // Grab encoded information in the reply subject for a delivered message. func replyInfo(subject string) (sseq, dseq, dc uint64, ts int64, pending uint64) { tsa := [expectedNumReplyTokens]string{} start, tokens := 0, tsa[:0] for i := 0; i < len(subject); i++ { if subject[i] == btsep { tokens = append(tokens, subject[start:i]) start = i + 1 } } tokens = append(tokens, subject[start:]) if len(tokens) != expectedNumReplyTokens || tokens[0] != "$JS" || tokens[1] != "ACK" { return 0, 0, 0, 0, 0 } // TODO(dlc) - Should we error if we do not match consumer name? // stream is tokens[2], consumer is 3. dc = uint64(parseAckReplyNum(tokens[4])) sseq, dseq = uint64(parseAckReplyNum(tokens[5])), uint64(parseAckReplyNum(tokens[6])) ts = parseAckReplyNum(tokens[7]) pending = uint64(parseAckReplyNum(tokens[8])) return sseq, dseq, dc, ts, pending } func ackReplyInfo(subject string) (sseq, dseq, dc uint64) { tsa := [expectedNumReplyTokens]string{} start, tokens := 0, tsa[:0] for i := 0; i < len(subject); i++ { if subject[i] == btsep { tokens = append(tokens, subject[start:i]) start = i + 1 } } tokens = append(tokens, subject[start:]) if len(tokens) != expectedNumReplyTokens || tokens[0] != "$JS" || tokens[1] != "ACK" { return 0, 0, 0 } dc = uint64(parseAckReplyNum(tokens[4])) sseq, dseq = uint64(parseAckReplyNum(tokens[5])), uint64(parseAckReplyNum(tokens[6])) return sseq, dseq, dc } // NextSeq returns the next delivered sequence number for this consumer. func (o *consumer) nextSeq() uint64 { o.mu.Lock() dseq := o.dseq o.mu.Unlock() return dseq } // This will select the store seq to start with based on the // partition subject. func (o *consumer) selectSubjectLast() { stats := o.mset.store.State() if stats.LastSeq == 0 { o.sseq = stats.LastSeq return } // FIXME(dlc) - this is linear and can be optimized by store layer. for seq := stats.LastSeq; seq >= stats.FirstSeq; seq-- { subj, _, _, _, err := o.mset.store.LoadMsg(seq) if err == ErrStoreMsgNotFound { continue } if o.isFilteredMatch(subj) { o.sseq = seq o.updateSkipped() return } } } // Will select the starting sequence. func (o *consumer) selectStartingSeqNo() { stats := o.mset.store.State() if o.cfg.OptStartSeq == 0 { if o.cfg.DeliverPolicy == DeliverAll { o.sseq = stats.FirstSeq } else if o.cfg.DeliverPolicy == DeliverLast { o.sseq = stats.LastSeq // If we are partitioned here we may need to walk backwards. if o.cfg.FilterSubject != _EMPTY_ { o.selectSubjectLast() } } else if o.cfg.OptStartTime != nil { // If we are here we are time based. // TODO(dlc) - Once clustered can't rely on this. o.sseq = o.mset.store.GetSeqFromTime(*o.cfg.OptStartTime) } else { // Default is deliver new only. o.sseq = stats.LastSeq + 1 } } else { o.sseq = o.cfg.OptStartSeq } if stats.FirstSeq == 0 { o.sseq = 1 } else if o.sseq < stats.FirstSeq { o.sseq = stats.FirstSeq } else if o.sseq > stats.LastSeq { o.sseq = stats.LastSeq + 1 } // Always set delivery sequence to 1. o.dseq = 1 // Set ack delivery floor to delivery-1 o.adflr = o.dseq - 1 // Set ack store floor to store-1 o.asflr = o.sseq - 1 } // Test whether a config represents a durable subscriber. func isDurableConsumer(config *ConsumerConfig) bool { return config != nil && config.Durable != _EMPTY_ } func (o *consumer) isDurable() bool { return o.cfg.Durable != _EMPTY_ } // Are we in push mode, delivery subject, etc. func (o *consumer) isPushMode() bool { return o.cfg.DeliverSubject != _EMPTY_ } func (o *consumer) isPullMode() bool { return o.cfg.DeliverSubject == _EMPTY_ } // Name returns the name of this consumer. func (o *consumer) String() string { o.mu.RLock() n := o.name o.mu.RUnlock() return n } func createConsumerName() string { return string(getHash(nuid.Next())) } // deleteConsumer will delete the consumer from this stream. func (mset *stream) deleteConsumer(o *consumer) error { return o.delete() } func (o *consumer) streamName() string { o.mu.RLock() mset := o.mset o.mu.RUnlock() if mset != nil { return mset.name() } return _EMPTY_ } // Active indicates if this consumer is still active. func (o *consumer) isActive() bool { o.mu.RLock() active := o.active && o.mset != nil o.mu.RUnlock() return active } // hasNoLocalInterest return true if we have no local interest. func (o *consumer) hasNoLocalInterest() bool { o.mu.RLock() rr := o.acc.sl.Match(o.cfg.DeliverSubject) o.mu.RUnlock() return len(rr.psubs)+len(rr.qsubs) == 0 } // This is when the underlying stream has been purged. func (o *consumer) purge(sseq uint64) { o.mu.Lock() o.sseq = sseq o.asflr = sseq - 1 o.adflr = o.dseq - 1 o.sgap = 0 if len(o.pending) > 0 { o.pending = nil if o.ptmr != nil { o.ptmr.Stop() // Do not nil this out here. This allows checkPending to fire // and still be ok and not panic. } } // We need to remove all those being queued for redelivery under o.rdq if len(o.rdq) > 0 { rdq := o.rdq o.rdq, o.rdqi = nil, nil for _, sseq := range rdq { if sseq >= o.sseq { o.addToRedeliverQueue(sseq) } } } o.mu.Unlock() o.writeStoreState() } func stopAndClearTimer(tp **time.Timer) { if *tp == nil { return } // Will get drained in normal course, do not try to // drain here. (*tp).Stop() *tp = nil } // Stop will shutdown the consumer for the associated stream. func (o *consumer) stop() error { return o.stopWithFlags(false, true, false) } func (o *consumer) deleteWithoutAdvisory() error { return o.stopWithFlags(true, true, false) } // Delete will delete the consumer for the associated stream and send advisories. func (o *consumer) delete() error { return o.stopWithFlags(true, true, true) } func (o *consumer) stopWithFlags(dflag, doSignal, advisory bool) error { o.mu.Lock() if o.closed { o.mu.Unlock() return nil } o.closed = true if dflag && advisory && o.isLeader() { o.sendDeleteAdvisoryLocked() } if o.qch != nil { close(o.qch) o.qch = nil } a := o.acc store := o.store mset := o.mset o.mset = nil o.active = false o.unsubscribe(o.ackSub) o.unsubscribe(o.reqSub) o.unsubscribe(o.fcSub) o.ackSub = nil o.reqSub = nil o.fcSub = nil if o.infoSub != nil { o.srv.sysUnsubscribe(o.infoSub) o.infoSub = nil } c := o.client o.client = nil sysc := o.sysc o.sysc = nil stopAndClearTimer(&o.ptmr) stopAndClearTimer(&o.dtmr) stopAndClearTimer(&o.gwdtmr) delivery := o.cfg.DeliverSubject o.waiting = nil // Break us out of the readLoop. if doSignal { o.signalNewMessages() } n := o.node o.mu.Unlock() if c != nil { c.closeConnection(ClientClosed) } if sysc != nil { sysc.closeConnection(ClientClosed) } if delivery != _EMPTY_ { a.sl.ClearNotification(delivery, o.inch) } mset.mu.Lock() mset.removeConsumer(o) rp := mset.cfg.Retention mset.mu.Unlock() // We need to optionally remove all messages since we are interest based retention. // We will do this consistently on all replicas. Note that if in clustered mode the // non-leader consumers will need to restore state first. if dflag && rp == InterestPolicy { stop := mset.lastSeq() o.mu.Lock() if !o.isLeader() { o.readStoredState() } start := o.asflr o.mu.Unlock() rmseqs := make([]uint64, 0, stop-start+1) mset.mu.RLock() for seq := start; seq <= stop; seq++ { if !mset.checkInterest(seq, o) { rmseqs = append(rmseqs, seq) } } mset.mu.RUnlock() for _, seq := range rmseqs { mset.store.RemoveMsg(seq) } } // Cluster cleanup. if n != nil { if dflag { n.Delete() } else { n.Stop() } } var err error if store != nil { if dflag { err = store.Delete() } else { err = store.Stop() } } return err } // Check that we do not form a cycle by delivering to a delivery subject // that is part of the interest group. func (mset *stream) deliveryFormsCycle(deliverySubject string) bool { mset.mu.RLock() defer mset.mu.RUnlock() for _, subject := range mset.cfg.Subjects { if subjectIsSubsetMatch(deliverySubject, subject) { return true } } return false } func validFilteredSubject(filteredSubject string, subjects []string) bool { for _, subject := range subjects { if subjectIsSubsetMatch(filteredSubject, subject) { return true } } return false } // SetInActiveDeleteThreshold sets the delete threshold for how long to wait // before deleting an inactive ephemeral consumer. func (o *consumer) setInActiveDeleteThreshold(dthresh time.Duration) error { o.mu.Lock() defer o.mu.Unlock() if o.isPullMode() { return fmt.Errorf("consumer is not push-based") } if o.isDurable() { return fmt.Errorf("consumer is not durable") } deleteWasRunning := o.dtmr != nil stopAndClearTimer(&o.dtmr) o.dthresh = dthresh if deleteWasRunning { o.dtmr = time.AfterFunc(o.dthresh, func() { o.deleteNotActive() }) } return nil } // switchToEphemeral is called on startup when recovering ephemerals. func (o *consumer) switchToEphemeral() { o.mu.Lock() o.cfg.Durable = _EMPTY_ store, ok := o.store.(*consumerFileStore) rr := o.acc.sl.Match(o.cfg.DeliverSubject) o.mu.Unlock() // Update interest o.updateDeliveryInterest(len(rr.psubs)+len(rr.qsubs) > 0) // Write out new config if ok { store.updateConfig(o.cfg) } } // RequestNextMsgSubject returns the subject to request the next message when in pull or worker mode. // Returns empty otherwise. func (o *consumer) requestNextMsgSubject() string { return o.nextMsgSubj } // Will set the initial pending. // mset lock should be held. func (o *consumer) setInitialPending() { mset := o.mset if mset == nil { return } // notFiltered means we want all messages. notFiltered := o.cfg.FilterSubject == _EMPTY_ if !notFiltered { // Check to see if we directly match the configured stream. // Many clients will always send a filtered subject. cfg := mset.cfg if len(cfg.Subjects) == 1 && cfg.Subjects[0] == o.cfg.FilterSubject { notFiltered = true } } if notFiltered { state := mset.store.State() if state.Msgs > 0 { o.sgap = state.Msgs - (o.sseq - state.FirstSeq) } } else { // Here we are filtered. o.sgap = o.mset.store.NumFilteredPending(o.sseq, o.cfg.FilterSubject) } } func (o *consumer) decStreamPending(sseq uint64, subj string) { o.mu.Lock() // Ignore if we have already seen this one. if sseq >= o.sseq && o.sgap > 0 && o.isFilteredMatch(subj) { o.sgap-- } // Check if this message was pending. p, wasPending := o.pending[sseq] var rdc uint64 = 1 if o.rdc != nil { rdc = o.rdc[sseq] } o.mu.Unlock() // If it was pending process it like an ack. // TODO(dlc) - we could do a term here instead with a reason to generate the advisory. if wasPending { o.processAckMsg(sseq, p.Sequence, rdc, false) } } func (o *consumer) account() *Account { o.mu.RLock() a := o.acc o.mu.RUnlock() return a }
1
13,245
Should you capture o.asflr before releasing consumer's lock?
nats-io-nats-server
go
@@ -51,6 +51,10 @@ public class WinePrefixContainerWineToolsTab extends Tab { final VBox toolsPane = new VBox(); final Text title = new TextWithStyle(tr("Wine tools"), TITLE_CSS_CLASS); + if (engineTools == null) { + return; + } + toolsPane.getStyleClass().add(CONFIGURATION_PANE_CSS_CLASS); toolsPane.getChildren().add(title);
1
package org.phoenicis.javafx.views.mainwindow.containers; import javafx.application.Platform; import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.control.Tab; import javafx.scene.layout.TilePane; import javafx.scene.layout.VBox; import javafx.scene.text.Text; import org.phoenicis.containers.dto.WinePrefixContainerDTO; import org.phoenicis.containers.wine.WinePrefixContainerController; import org.phoenicis.engines.EngineToolsManager; import org.phoenicis.javafx.views.common.ErrorMessage; import org.phoenicis.javafx.views.common.TextWithStyle; import org.phoenicis.repository.dto.ApplicationDTO; import org.phoenicis.repository.dto.ScriptDTO; import java.util.ArrayList; import java.util.List; import static org.phoenicis.configuration.localisation.Localisation.tr; /** * Created by marc on 27.05.17. */ public class WinePrefixContainerWineToolsTab extends Tab { private static final String CONFIGURATION_PANE_CSS_CLASS = "containerConfigurationPane"; private static final String TITLE_CSS_CLASS = "title"; private final WinePrefixContainerDTO container; private final WinePrefixContainerController winePrefixContainerController; private EngineToolsManager engineToolsManager; private final List<Node> lockableElements = new ArrayList<>(); public WinePrefixContainerWineToolsTab(WinePrefixContainerDTO container, WinePrefixContainerController winePrefixContainerController, EngineToolsManager engineToolsManager, ApplicationDTO engineTools) { super(tr("Wine tools")); this.container = container; this.winePrefixContainerController = winePrefixContainerController; this.engineToolsManager = engineToolsManager; this.setClosable(false); this.populate(engineTools); } private void populate(ApplicationDTO engineTools) { final VBox toolsPane = new VBox(); final Text title = new TextWithStyle(tr("Wine tools"), TITLE_CSS_CLASS); toolsPane.getStyleClass().add(CONFIGURATION_PANE_CSS_CLASS); toolsPane.getChildren().add(title); final TilePane toolsContentPane = new TilePane(); toolsContentPane.setPrefColumns(3); toolsContentPane.getStyleClass().add("grid"); for (ScriptDTO tool : engineTools.getScripts()) { Button toolButton = new Button(tool.getScriptName()); toolButton.getStyleClass().addAll("toolButton"); toolButton.setStyle("-fx-background-image: url('" + tool.getIcon() + "');"); toolButton.setOnMouseClicked(event -> { this.lockAll(); this.engineToolsManager.runTool(container.getEngine(), container.getName(), tool.getId(), this::unlockAll, e -> Platform.runLater(() -> new ErrorMessage("Error", e).show())); }); this.lockableElements.add(toolButton); toolsContentPane.getChildren().add(toolButton); } toolsPane.getChildren().add(toolsContentPane); this.setContent(toolsPane); } public void unlockAll() { for (Node element : lockableElements) { element.setDisable(false); } } private void lockAll() { for (Node element : lockableElements) { element.setDisable(true); } } }
1
11,494
Just asking: Should this happen, that null is passed? If this is the case I think we should think about passing an `Optional` object to the method.
PhoenicisOrg-phoenicis
java
@@ -10,6 +10,17 @@ class HomeController < ApplicationController def me end + def edit_me + first_name = params[:first_name] + last_name = params[:last_name] + user = current_user + user.first_name = first_name + user.last_name = last_name + user.save! + flash[:success] = "Your profile is updated!" + redirect_to :me + end + def error raise "test exception" end
1
class HomeController < ApplicationController # just to cut down on exception spam before_action :authenticate_user!, only: :error def index render(layout: false) end def me end def error raise "test exception" end end
1
15,450
what about making a `ProfilesController` or `UserProfilesController` and having this be a `show` action instead? That would be more Railsy (although that can be considered a compliment or a dis, depending on who you are :hamburger: )
18F-C2
rb
@@ -2378,7 +2378,11 @@ void PostCallRecordCreateDevice(VkPhysicalDevice gpu, const VkDeviceCreateInfo * } layer_data *device_data = GetLayerDataPtr(get_dispatch_key(*pDevice), layer_data_map); - device_data->enabled_features.core = *enabled_features_found; + if (nullptr == enabled_features_found) { + device_data->enabled_features.core = {}; + } else { + device_data->enabled_features.core = *enabled_features_found; + } uint32_t count; instance_data->dispatch_table.GetPhysicalDeviceQueueFamilyProperties(gpu, &count, nullptr);
1
/* Copyright (c) 2015-2019 The Khronos Group Inc. * Copyright (c) 2015-2019 Valve Corporation * Copyright (c) 2015-2019 LunarG, Inc. * Copyright (C) 2015-2019 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: 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]> */ // Allow use of STL min and max functions in Windows #define NOMINMAX #include <algorithm> #include <array> #include <assert.h> #include <cmath> #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_dispatch_table_helper.h" #include "vk_enum_string_helper.h" #if defined(__GNUC__) #pragma GCC diagnostic ignored "-Wwrite-strings" #endif #if defined(__GNUC__) #pragma GCC diagnostic warning "-Wwrite-strings" #endif #include "convert_to_renderpass2.h" #include "core_validation.h" #include "buffer_validation.h" #include "shader_validation.h" #include "vk_layer_data.h" #include "vk_layer_utils.h" // This intentionally includes a cpp file #include "vk_safe_struct.cpp" using mutex_t = std::mutex; using lock_guard_t = std::lock_guard<mutex_t>; using unique_lock_t = std::unique_lock<mutex_t>; // These functions are defined *outside* the core_validation namespace as their type // is also defined outside that namespace size_t PipelineLayoutCompatDef::hash() const { hash_util::HashCombiner hc; // The set number is integral to the CompatDef's distinctiveness hc << set << push_constant_ranges.get(); const auto &descriptor_set_layouts = *set_layouts_id.get(); for (uint32_t i = 0; i <= set; i++) { hc << descriptor_set_layouts[i].get(); } return hc.Value(); } bool PipelineLayoutCompatDef::operator==(const PipelineLayoutCompatDef &other) const { if ((set != other.set) || (push_constant_ranges != other.push_constant_ranges)) { return false; } if (set_layouts_id == other.set_layouts_id) { // if it's the same set_layouts_id, then *any* subset will match return true; } // They aren't exactly the same PipelineLayoutSetLayouts, so we need to check if the required subsets match const auto &descriptor_set_layouts = *set_layouts_id.get(); assert(set < descriptor_set_layouts.size()); const auto &other_ds_layouts = *other.set_layouts_id.get(); assert(set < other_ds_layouts.size()); for (uint32_t i = 0; i <= set; i++) { if (descriptor_set_layouts[i] != other_ds_layouts[i]) { return false; } } return true; } namespace core_validation { using std::max; using std::string; using std::stringstream; using std::unique_ptr; using std::unordered_map; using std::unordered_set; using std::vector; // WSI Image Objects bypass usual Image Object creation methods. A special Memory // Object value will be used to identify them internally. static const VkDeviceMemory MEMTRACKER_SWAP_CHAIN_IMAGE_KEY = (VkDeviceMemory)(-1); // 2nd special memory handle used to flag object as unbound from memory static const VkDeviceMemory MEMORY_UNBOUND = VkDeviceMemory(~((uint64_t)(0)) - 1); // TODO : Do we need to guard access to layer_data_map w/ lock? unordered_map<void *, layer_data *> layer_data_map; unordered_map<void *, instance_layer_data *> instance_layer_data_map; // TODO : This can be much smarter, using separate locks for separate global data mutex_t global_lock; // Get the global map of pending releases GlobalQFOTransferBarrierMap<VkImageMemoryBarrier> &GetGlobalQFOReleaseBarrierMap( layer_data *dev_data, const QFOTransferBarrier<VkImageMemoryBarrier>::Tag &type_tag) { return dev_data->qfo_release_image_barrier_map; } GlobalQFOTransferBarrierMap<VkBufferMemoryBarrier> &GetGlobalQFOReleaseBarrierMap( layer_data *dev_data, const QFOTransferBarrier<VkBufferMemoryBarrier>::Tag &type_tag) { return dev_data->qfo_release_buffer_barrier_map; } // Get the image viewstate for a given framebuffer attachment IMAGE_VIEW_STATE *GetAttachmentImageViewState(layer_data *dev_data, FRAMEBUFFER_STATE *framebuffer, uint32_t index) { assert(framebuffer && (index < framebuffer->createInfo.attachmentCount)); #ifdef FRAMEBUFFER_ATTACHMENT_STATE_CACHE return framebuffer->attachments[index].view_state; #else const VkImageView &image_view = framebuffer->createInfo.pAttachments[index]; return GetImageViewState(dev_data, image_view); #endif } // Return IMAGE_VIEW_STATE ptr for specified imageView or else NULL IMAGE_VIEW_STATE *GetImageViewState(const layer_data *dev_data, VkImageView image_view) { auto iv_it = dev_data->imageViewMap.find(image_view); if (iv_it == dev_data->imageViewMap.end()) { return nullptr; } return iv_it->second.get(); } // Return sampler node ptr for specified sampler or else NULL SAMPLER_STATE *GetSamplerState(const layer_data *dev_data, VkSampler sampler) { auto sampler_it = dev_data->samplerMap.find(sampler); if (sampler_it == dev_data->samplerMap.end()) { return nullptr; } return sampler_it->second.get(); } // Return image state ptr for specified image or else NULL IMAGE_STATE *GetImageState(const layer_data *dev_data, VkImage image) { auto img_it = dev_data->imageMap.find(image); if (img_it == dev_data->imageMap.end()) { return nullptr; } return img_it->second.get(); } // Return buffer state ptr for specified buffer or else NULL BUFFER_STATE *GetBufferState(const layer_data *dev_data, VkBuffer buffer) { auto buff_it = dev_data->bufferMap.find(buffer); if (buff_it == dev_data->bufferMap.end()) { return nullptr; } return buff_it->second.get(); } // Return swapchain node for specified swapchain or else NULL SWAPCHAIN_NODE *GetSwapchainNode(const layer_data *dev_data, VkSwapchainKHR swapchain) { auto swp_it = dev_data->swapchainMap.find(swapchain); if (swp_it == dev_data->swapchainMap.end()) { return nullptr; } return swp_it->second.get(); } // Return buffer node ptr for specified buffer or else NULL BUFFER_VIEW_STATE *GetBufferViewState(const layer_data *dev_data, VkBufferView buffer_view) { auto bv_it = dev_data->bufferViewMap.find(buffer_view); if (bv_it == dev_data->bufferViewMap.end()) { return nullptr; } return bv_it->second.get(); } FENCE_NODE *GetFenceNode(layer_data *dev_data, VkFence fence) { auto it = dev_data->fenceMap.find(fence); if (it == dev_data->fenceMap.end()) { return nullptr; } return &it->second; } EVENT_STATE *GetEventNode(layer_data *dev_data, VkEvent event) { auto it = dev_data->eventMap.find(event); if (it == dev_data->eventMap.end()) { return nullptr; } return &it->second; } QUERY_POOL_NODE *GetQueryPoolNode(layer_data *dev_data, VkQueryPool query_pool) { auto it = dev_data->queryPoolMap.find(query_pool); if (it == dev_data->queryPoolMap.end()) { return nullptr; } return &it->second; } QUEUE_STATE *GetQueueState(layer_data *dev_data, VkQueue queue) { auto it = dev_data->queueMap.find(queue); if (it == dev_data->queueMap.end()) { return nullptr; } return &it->second; } SEMAPHORE_NODE *GetSemaphoreNode(layer_data *dev_data, VkSemaphore semaphore) { auto it = dev_data->semaphoreMap.find(semaphore); if (it == dev_data->semaphoreMap.end()) { return nullptr; } return &it->second; } COMMAND_POOL_NODE *GetCommandPoolNode(layer_data *dev_data, VkCommandPool pool) { auto it = dev_data->commandPoolMap.find(pool); if (it == dev_data->commandPoolMap.end()) { return nullptr; } return &it->second; } PHYSICAL_DEVICE_STATE *GetPhysicalDeviceState(instance_layer_data *instance_data, VkPhysicalDevice phys) { auto it = instance_data->physical_device_map.find(phys); if (it == instance_data->physical_device_map.end()) { return nullptr; } return &it->second; } SURFACE_STATE *GetSurfaceState(instance_layer_data *instance_data, VkSurfaceKHR surface) { auto it = instance_data->surface_map.find(surface); if (it == instance_data->surface_map.end()) { return nullptr; } return &it->second; } // Return ptr to memory binding for given handle of specified type static BINDABLE *GetObjectMemBinding(layer_data *dev_data, uint64_t handle, VulkanObjectType type) { switch (type) { case kVulkanObjectTypeImage: return GetImageState(dev_data, VkImage(handle)); case kVulkanObjectTypeBuffer: return GetBufferState(dev_data, VkBuffer(handle)); default: break; } return nullptr; } std::unordered_map<VkSamplerYcbcrConversion, uint64_t> *GetYcbcrConversionFormatMap(core_validation::layer_data *device_data) { return &device_data->ycbcr_conversion_ahb_fmt_map; } std::unordered_set<uint64_t> *GetAHBExternalFormatsSet(core_validation::layer_data *device_data) { return &device_data->ahb_ext_formats_set; } // prototype GLOBAL_CB_NODE *GetCBNode(layer_data const *, const VkCommandBuffer); // Return ptr to info in map container containing mem, or NULL if not found // Calls to this function should be wrapped in mutex DEVICE_MEM_INFO *GetMemObjInfo(const layer_data *dev_data, const VkDeviceMemory mem) { auto mem_it = dev_data->memObjMap.find(mem); if (mem_it == dev_data->memObjMap.end()) { return NULL; } return mem_it->second.get(); } static void AddMemObjInfo(layer_data *dev_data, void *object, const VkDeviceMemory mem, const VkMemoryAllocateInfo *pAllocateInfo) { assert(object != NULL); auto *mem_info = new DEVICE_MEM_INFO(object, mem, pAllocateInfo); dev_data->memObjMap[mem] = unique_ptr<DEVICE_MEM_INFO>(mem_info); auto dedicated = lvl_find_in_chain<VkMemoryDedicatedAllocateInfoKHR>(pAllocateInfo->pNext); if (dedicated) { mem_info->is_dedicated = true; mem_info->dedicated_buffer = dedicated->buffer; mem_info->dedicated_image = dedicated->image; } auto export_info = lvl_find_in_chain<VkExportMemoryAllocateInfo>(pAllocateInfo->pNext); if (export_info) { mem_info->is_export = true; mem_info->export_handle_type_flags = export_info->handleTypes; } } // Create binding link between given sampler and command buffer node void AddCommandBufferBindingSampler(GLOBAL_CB_NODE *cb_node, SAMPLER_STATE *sampler_state) { sampler_state->cb_bindings.insert(cb_node); cb_node->object_bindings.insert({HandleToUint64(sampler_state->sampler), kVulkanObjectTypeSampler}); } // Create binding link between given image node and command buffer node void AddCommandBufferBindingImage(const layer_data *dev_data, GLOBAL_CB_NODE *cb_node, IMAGE_STATE *image_state) { // Skip validation if this image was created through WSI if (image_state->binding.mem != MEMTRACKER_SWAP_CHAIN_IMAGE_KEY) { // First update CB binding in MemObj mini CB list for (auto mem_binding : image_state->GetBoundMemory()) { DEVICE_MEM_INFO *pMemInfo = GetMemObjInfo(dev_data, mem_binding); if (pMemInfo) { pMemInfo->cb_bindings.insert(cb_node); // Now update CBInfo's Mem reference list cb_node->memObjs.insert(mem_binding); } } // Now update cb binding for image cb_node->object_bindings.insert({HandleToUint64(image_state->image), kVulkanObjectTypeImage}); image_state->cb_bindings.insert(cb_node); } } // Create binding link between given image view node and its image with command buffer node void AddCommandBufferBindingImageView(const layer_data *dev_data, GLOBAL_CB_NODE *cb_node, IMAGE_VIEW_STATE *view_state) { // First add bindings for imageView view_state->cb_bindings.insert(cb_node); cb_node->object_bindings.insert({HandleToUint64(view_state->image_view), kVulkanObjectTypeImageView}); auto image_state = GetImageState(dev_data, view_state->create_info.image); // Add bindings for image within imageView if (image_state) { AddCommandBufferBindingImage(dev_data, cb_node, image_state); } } // Create binding link between given buffer node and command buffer node void AddCommandBufferBindingBuffer(const layer_data *dev_data, GLOBAL_CB_NODE *cb_node, BUFFER_STATE *buffer_state) { // First update CB binding in MemObj mini CB list for (auto mem_binding : buffer_state->GetBoundMemory()) { DEVICE_MEM_INFO *pMemInfo = GetMemObjInfo(dev_data, mem_binding); if (pMemInfo) { pMemInfo->cb_bindings.insert(cb_node); // Now update CBInfo's Mem reference list cb_node->memObjs.insert(mem_binding); } } // Now update cb binding for buffer cb_node->object_bindings.insert({HandleToUint64(buffer_state->buffer), kVulkanObjectTypeBuffer}); buffer_state->cb_bindings.insert(cb_node); } // Create binding link between given buffer view node and its buffer with command buffer node void AddCommandBufferBindingBufferView(const layer_data *dev_data, GLOBAL_CB_NODE *cb_node, BUFFER_VIEW_STATE *view_state) { // First add bindings for bufferView view_state->cb_bindings.insert(cb_node); cb_node->object_bindings.insert({HandleToUint64(view_state->buffer_view), kVulkanObjectTypeBufferView}); auto buffer_state = GetBufferState(dev_data, view_state->create_info.buffer); // Add bindings for buffer within bufferView if (buffer_state) { AddCommandBufferBindingBuffer(dev_data, cb_node, buffer_state); } } // For every mem obj bound to particular CB, free bindings related to that CB static void ClearCmdBufAndMemReferences(layer_data *dev_data, GLOBAL_CB_NODE *cb_node) { if (cb_node) { if (cb_node->memObjs.size() > 0) { for (auto mem : cb_node->memObjs) { DEVICE_MEM_INFO *pInfo = GetMemObjInfo(dev_data, mem); if (pInfo) { pInfo->cb_bindings.erase(cb_node); } } cb_node->memObjs.clear(); } } } // Clear a single object binding from given memory object static void ClearMemoryObjectBinding(layer_data *dev_data, uint64_t handle, VulkanObjectType type, VkDeviceMemory mem) { DEVICE_MEM_INFO *mem_info = GetMemObjInfo(dev_data, mem); // This obj is bound to a memory object. Remove the reference to this object in that memory object's list if (mem_info) { mem_info->obj_bindings.erase({handle, type}); } } // ClearMemoryObjectBindings clears the binding of objects to memory // For the given object it pulls the memory bindings and makes sure that the bindings // no longer refer to the object being cleared. This occurs when objects are destroyed. void ClearMemoryObjectBindings(layer_data *dev_data, uint64_t handle, VulkanObjectType type) { BINDABLE *mem_binding = GetObjectMemBinding(dev_data, handle, type); if (mem_binding) { if (!mem_binding->sparse) { ClearMemoryObjectBinding(dev_data, handle, type, mem_binding->binding.mem); } else { // Sparse, clear all bindings for (auto &sparse_mem_binding : mem_binding->sparse_bindings) { ClearMemoryObjectBinding(dev_data, handle, type, sparse_mem_binding.mem); } } } } // For given mem object, verify that it is not null or UNBOUND, if it is, report error. Return skip value. bool VerifyBoundMemoryIsValid(const layer_data *dev_data, VkDeviceMemory mem, uint64_t handle, const char *api_name, const char *type_name, std::string error_code) { bool result = false; if (VK_NULL_HANDLE == mem) { result = log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, handle, error_code, "%s: Vk%s object 0x%" PRIx64 " used with no memory bound. Memory should be bound by calling vkBind%sMemory().", api_name, type_name, handle, type_name); } else if (MEMORY_UNBOUND == mem) { result = log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, handle, error_code, "%s: Vk%s object 0x%" PRIx64 " used with no memory bound and previously bound memory was freed. Memory must not be freed prior to this " "operation.", api_name, type_name, handle); } return result; } // Check to see if memory was ever bound to this image bool ValidateMemoryIsBoundToImage(const layer_data *dev_data, const IMAGE_STATE *image_state, const char *api_name, const std::string &error_code) { bool result = false; if (0 == (static_cast<uint32_t>(image_state->createInfo.flags) & VK_IMAGE_CREATE_SPARSE_BINDING_BIT)) { result = VerifyBoundMemoryIsValid(dev_data, image_state->binding.mem, HandleToUint64(image_state->image), api_name, "Image", error_code); } return result; } // Check to see if memory was bound to this buffer bool ValidateMemoryIsBoundToBuffer(const layer_data *dev_data, const BUFFER_STATE *buffer_state, const char *api_name, const std::string &error_code) { bool result = false; if (0 == (static_cast<uint32_t>(buffer_state->createInfo.flags) & VK_BUFFER_CREATE_SPARSE_BINDING_BIT)) { result = VerifyBoundMemoryIsValid(dev_data, buffer_state->binding.mem, HandleToUint64(buffer_state->buffer), api_name, "Buffer", error_code); } return result; } // SetMemBinding is used to establish immutable, non-sparse binding between a single image/buffer object and memory object. // Corresponding valid usage checks are in ValidateSetMemBinding(). static void SetMemBinding(layer_data *dev_data, VkDeviceMemory mem, BINDABLE *mem_binding, VkDeviceSize memory_offset, uint64_t handle, VulkanObjectType type) { assert(mem_binding); mem_binding->binding.mem = mem; mem_binding->UpdateBoundMemorySet(); // force recreation of cached set mem_binding->binding.offset = memory_offset; mem_binding->binding.size = mem_binding->requirements.size; if (mem != VK_NULL_HANDLE) { DEVICE_MEM_INFO *mem_info = GetMemObjInfo(dev_data, mem); if (mem_info) { mem_info->obj_bindings.insert({handle, type}); // For image objects, make sure default memory state is correctly set // TODO : What's the best/correct way to handle this? if (kVulkanObjectTypeImage == type) { auto const image_state = reinterpret_cast<const IMAGE_STATE *>(mem_binding); if (image_state) { VkImageCreateInfo ici = image_state->createInfo; if (ici.usage & (VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT)) { // TODO:: More memory state transition stuff. } } } } } } // 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. static bool ValidateSetMemBinding(layer_data *dev_data, VkDeviceMemory mem, uint64_t handle, VulkanObjectType type, const char *apiName) { bool skip = false; // It's an error to bind an object to NULL memory if (mem != VK_NULL_HANDLE) { BINDABLE *mem_binding = GetObjectMemBinding(dev_data, handle, type); assert(mem_binding); if (mem_binding->sparse) { std::string error_code = "VUID-vkBindImageMemory-image-01045"; const char *handle_type = "IMAGE"; if (type == kVulkanObjectTypeBuffer) { error_code = "VUID-vkBindBufferMemory-buffer-01030"; handle_type = "BUFFER"; } else { assert(type == kVulkanObjectTypeImage); } skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT, HandleToUint64(mem), error_code, "In %s, attempting to bind memory (0x%" PRIx64 ") to object (0x%" PRIx64 ") which was created with sparse memory flags (VK_%s_CREATE_SPARSE_*_BIT).", apiName, HandleToUint64(mem), handle, handle_type); } DEVICE_MEM_INFO *mem_info = GetMemObjInfo(dev_data, mem); if (mem_info) { DEVICE_MEM_INFO *prev_binding = GetMemObjInfo(dev_data, mem_binding->binding.mem); if (prev_binding) { std::string error_code = "VUID-vkBindImageMemory-image-01044"; if (type == kVulkanObjectTypeBuffer) { error_code = "VUID-vkBindBufferMemory-buffer-01029"; } else { assert(type == kVulkanObjectTypeImage); } skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT, HandleToUint64(mem), error_code, "In %s, attempting to bind memory (0x%" PRIx64 ") to object (0x%" PRIx64 ") which has already been bound to mem object 0x%" PRIx64 ".", apiName, HandleToUint64(mem), handle, HandleToUint64(prev_binding->mem)); } else if (mem_binding->binding.mem == MEMORY_UNBOUND) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT, HandleToUint64(mem), kVUID_Core_MemTrack_RebindObject, "In %s, attempting to bind memory (0x%" PRIx64 ") to object (0x%" PRIx64 ") 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, HandleToUint64(mem), handle); } } } return skip; } // For NULL mem case, clear any previous binding Else... // Make sure given object is in its object map // IF a previous binding existed, update binding // Add reference from objectInfo to memoryInfo // Add reference off of object's binding info // Return VK_TRUE if addition is successful, VK_FALSE otherwise static bool SetSparseMemBinding(layer_data *dev_data, MEM_BINDING binding, uint64_t handle, VulkanObjectType type) { bool skip = VK_FALSE; // Handle NULL case separately, just clear previous binding & decrement reference if (binding.mem == VK_NULL_HANDLE) { // TODO : This should cause the range of the resource to be unbound according to spec } else { BINDABLE *mem_binding = GetObjectMemBinding(dev_data, handle, type); assert(mem_binding); if (mem_binding) { // Invalid handles are reported by object tracker, but Get returns NULL for them, so avoid SEGV here assert(mem_binding->sparse); DEVICE_MEM_INFO *mem_info = GetMemObjInfo(dev_data, binding.mem); if (mem_info) { mem_info->obj_bindings.insert({handle, type}); // Need to set mem binding for this object mem_binding->sparse_bindings.insert(binding); mem_binding->UpdateBoundMemorySet(); } } } return skip; } // Check object status for selected flag state static bool ValidateStatus(layer_data *dev_data, GLOBAL_CB_NODE *pNode, CBStatusFlags status_mask, VkFlags msg_flags, const char *fail_msg, std::string const msg_code) { if (!(pNode->status & status_mask)) { return log_msg(dev_data->report_data, msg_flags, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(pNode->commandBuffer), msg_code, "command buffer object 0x%" PRIx64 ": %s..", HandleToUint64(pNode->commandBuffer), fail_msg); } return false; } // Retrieve pipeline node ptr for given pipeline object PIPELINE_STATE *GetPipelineState(layer_data const *dev_data, VkPipeline pipeline) { auto it = dev_data->pipelineMap.find(pipeline); if (it == dev_data->pipelineMap.end()) { return nullptr; } return it->second.get(); } RENDER_PASS_STATE *GetRenderPassState(layer_data const *dev_data, VkRenderPass renderpass) { auto it = dev_data->renderPassMap.find(renderpass); if (it == dev_data->renderPassMap.end()) { return nullptr; } return it->second.get(); } std::shared_ptr<RENDER_PASS_STATE> GetRenderPassStateSharedPtr(layer_data const *dev_data, VkRenderPass renderpass) { auto it = dev_data->renderPassMap.find(renderpass); if (it == dev_data->renderPassMap.end()) { return nullptr; } return it->second; } FRAMEBUFFER_STATE *GetFramebufferState(const layer_data *dev_data, VkFramebuffer framebuffer) { auto it = dev_data->frameBufferMap.find(framebuffer); if (it == dev_data->frameBufferMap.end()) { return nullptr; } return it->second.get(); } std::shared_ptr<cvdescriptorset::DescriptorSetLayout const> const GetDescriptorSetLayout(layer_data const *dev_data, VkDescriptorSetLayout dsLayout) { auto it = dev_data->descriptorSetLayoutMap.find(dsLayout); if (it == dev_data->descriptorSetLayoutMap.end()) { return nullptr; } return it->second; } static PIPELINE_LAYOUT_NODE const *GetPipelineLayout(layer_data const *dev_data, VkPipelineLayout pipeLayout) { auto it = dev_data->pipelineLayoutMap.find(pipeLayout); if (it == dev_data->pipelineLayoutMap.end()) { return nullptr; } return &it->second; } shader_module const *GetShaderModuleState(layer_data const *dev_data, VkShaderModule module) { auto it = dev_data->shaderModuleMap.find(module); if (it == dev_data->shaderModuleMap.end()) { return nullptr; } return it->second.get(); } const TEMPLATE_STATE *GetDescriptorTemplateState(const layer_data *dev_data, VkDescriptorUpdateTemplateKHR descriptor_update_template) { const auto it = dev_data->desc_template_map.find(descriptor_update_template); if (it == dev_data->desc_template_map.cend()) { return nullptr; } return it->second.get(); } // Return true if for a given PSO, the given state enum is dynamic, else return false static bool IsDynamic(const PIPELINE_STATE *pPipeline, const VkDynamicState state) { 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 static bool ValidateDrawStateFlags(layer_data *dev_data, GLOBAL_CB_NODE *pCB, const PIPELINE_STATE *pPipe, bool indexed, std::string const msg_code) { bool result = false; if (pPipe->topology_at_rasterizer == VK_PRIMITIVE_TOPOLOGY_LINE_LIST || pPipe->topology_at_rasterizer == VK_PRIMITIVE_TOPOLOGY_LINE_STRIP) { result |= ValidateStatus(dev_data, pCB, CBSTATUS_LINE_WIDTH_SET, VK_DEBUG_REPORT_ERROR_BIT_EXT, "Dynamic line width state not set for this command buffer", msg_code); } if (pPipe->graphicsPipelineCI.pRasterizationState && (pPipe->graphicsPipelineCI.pRasterizationState->depthBiasEnable == VK_TRUE)) { result |= ValidateStatus(dev_data, pCB, CBSTATUS_DEPTH_BIAS_SET, VK_DEBUG_REPORT_ERROR_BIT_EXT, "Dynamic depth bias state not set for this command buffer", msg_code); } if (pPipe->blendConstantsEnabled) { result |= ValidateStatus(dev_data, pCB, CBSTATUS_BLEND_CONSTANTS_SET, VK_DEBUG_REPORT_ERROR_BIT_EXT, "Dynamic blend constants state not set for this command buffer", msg_code); } if (pPipe->graphicsPipelineCI.pDepthStencilState && (pPipe->graphicsPipelineCI.pDepthStencilState->depthBoundsTestEnable == VK_TRUE)) { result |= ValidateStatus(dev_data, pCB, CBSTATUS_DEPTH_BOUNDS_SET, VK_DEBUG_REPORT_ERROR_BIT_EXT, "Dynamic depth bounds state not set for this command buffer", msg_code); } if (pPipe->graphicsPipelineCI.pDepthStencilState && (pPipe->graphicsPipelineCI.pDepthStencilState->stencilTestEnable == VK_TRUE)) { result |= ValidateStatus(dev_data, pCB, CBSTATUS_STENCIL_READ_MASK_SET, VK_DEBUG_REPORT_ERROR_BIT_EXT, "Dynamic stencil read mask state not set for this command buffer", msg_code); result |= ValidateStatus(dev_data, pCB, CBSTATUS_STENCIL_WRITE_MASK_SET, VK_DEBUG_REPORT_ERROR_BIT_EXT, "Dynamic stencil write mask state not set for this command buffer", msg_code); result |= ValidateStatus(dev_data, pCB, CBSTATUS_STENCIL_REFERENCE_SET, VK_DEBUG_REPORT_ERROR_BIT_EXT, "Dynamic stencil reference state not set for this command buffer", msg_code); } if (indexed) { result |= ValidateStatus(dev_data, pCB, CBSTATUS_INDEX_BUFFER_BOUND, VK_DEBUG_REPORT_ERROR_BIT_EXT, "Index buffer object not bound to this command buffer when Indexed Draw attempted", msg_code); } return result; } static bool LogInvalidAttachmentMessage(layer_data const *dev_data, 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, std::string error_code) { return log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT, HandleToUint64(rp1_state->renderPass), error_code, "%s: RenderPasses incompatible between %s w/ renderPass 0x%" PRIx64 " and %s w/ renderPass 0x%" PRIx64 " Attachment %u is not compatible with %u: %s.", caller, type1_string, HandleToUint64(rp1_state->renderPass), type2_string, HandleToUint64(rp2_state->renderPass), primary_attach, secondary_attach, msg); } static bool ValidateAttachmentCompatibility(layer_data const *dev_data, 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, std::string error_code) { bool skip = false; const auto &primaryPassCI = rp1_state->createInfo; const auto &secondaryPassCI = rp2_state->createInfo; if (primaryPassCI.attachmentCount <= primary_attach) { primary_attach = VK_ATTACHMENT_UNUSED; } if (secondaryPassCI.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(dev_data, 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(dev_data, 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 (primaryPassCI.pAttachments[primary_attach].format != secondaryPassCI.pAttachments[secondary_attach].format) { skip |= LogInvalidAttachmentMessage(dev_data, type1_string, rp1_state, type2_string, rp2_state, primary_attach, secondary_attach, "They have different formats.", caller, error_code); } if (primaryPassCI.pAttachments[primary_attach].samples != secondaryPassCI.pAttachments[secondary_attach].samples) { skip |= LogInvalidAttachmentMessage(dev_data, type1_string, rp1_state, type2_string, rp2_state, primary_attach, secondary_attach, "They have different samples.", caller, error_code); } if (primaryPassCI.pAttachments[primary_attach].flags != secondaryPassCI.pAttachments[secondary_attach].flags) { skip |= LogInvalidAttachmentMessage(dev_data, type1_string, rp1_state, type2_string, rp2_state, primary_attach, secondary_attach, "They have different flags.", caller, error_code); } return skip; } static bool ValidateSubpassCompatibility(layer_data const *dev_data, 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, std::string error_code) { bool skip = false; const auto &primary_desc = rp1_state->createInfo.pSubpasses[subpass]; const auto &secondary_desc = rp2_state->createInfo.pSubpasses[subpass]; uint32_t maxInputAttachmentCount = std::max(primary_desc.inputAttachmentCount, secondary_desc.inputAttachmentCount); for (uint32_t i = 0; i < maxInputAttachmentCount; ++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(dev_data, type1_string, rp1_state, type2_string, rp2_state, primary_input_attach, secondary_input_attach, caller, error_code); } uint32_t maxColorAttachmentCount = std::max(primary_desc.colorAttachmentCount, secondary_desc.colorAttachmentCount); for (uint32_t i = 0; i < maxColorAttachmentCount; ++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(dev_data, 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(dev_data, 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(dev_data, type1_string, rp1_state, type2_string, rp2_state, primary_depthstencil_attach, secondary_depthstencil_attach, caller, error_code); return skip; } // 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 static bool ValidateRenderPassCompatibility(layer_data const *dev_data, const char *type1_string, const RENDER_PASS_STATE *rp1_state, const char *type2_string, const RENDER_PASS_STATE *rp2_state, const char *caller, std::string error_code) { bool skip = false; if (rp1_state->createInfo.subpassCount != rp2_state->createInfo.subpassCount) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT, HandleToUint64(rp1_state->renderPass), error_code, "%s: RenderPasses incompatible between %s w/ renderPass 0x%" PRIx64 " with a subpassCount of %u and %s w/ renderPass 0x%" PRIx64 " with a subpassCount of %u.", caller, type1_string, HandleToUint64(rp1_state->renderPass), rp1_state->createInfo.subpassCount, type2_string, HandleToUint64(rp2_state->renderPass), rp2_state->createInfo.subpassCount); } else { for (uint32_t i = 0; i < rp1_state->createInfo.subpassCount; ++i) { skip |= ValidateSubpassCompatibility(dev_data, type1_string, rp1_state, type2_string, rp2_state, i, caller, error_code); } } return skip; } // Return Set node ptr for specified set or else NULL cvdescriptorset::DescriptorSet *GetSetNode(const layer_data *dev_data, VkDescriptorSet set) { auto set_it = dev_data->setMap.find(set); if (set_it == dev_data->setMap.end()) { return NULL; } return set_it->second; } // 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 << ","; } } } } // Validate draw-time state related to the PSO static bool ValidatePipelineDrawtimeState(layer_data const *dev_data, LAST_BOUND_STATE const &state, const GLOBAL_CB_NODE *pCB, CMD_TYPE cmd_type, PIPELINE_STATE const *pPipeline, const char *caller) { bool skip = false; // 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 ((pCB->current_draw_data.vertex_buffer_bindings.size() < (vertex_binding + 1)) || (pCB->current_draw_data.vertex_buffer_bindings[vertex_binding].buffer == VK_NULL_HANDLE)) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(pCB->commandBuffer), kVUID_Core_DrawState_VtxIndexOutOfBounds, "The Pipeline State Object (0x%" PRIx64 ") 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.", HandleToUint64(state.pipeline_state->pipeline), 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 attribute_format = attribute_description.format; 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 < pCB->current_draw_data.vertex_buffer_bindings.size()) && (pCB->current_draw_data.vertex_buffer_bindings[vertex_binding].buffer != VK_NULL_HANDLE)) { const auto vertex_buffer_stride = pPipeline->vertex_binding_descriptions_[vertex_binding_map_it->second].stride; const auto vertex_buffer_offset = pCB->current_draw_data.vertex_buffer_bindings[vertex_binding].offset; const auto buffer_state = GetBufferState(dev_data, pCB->current_draw_data.vertex_buffer_bindings[vertex_binding].buffer); // Use only memory binding offset as base memory should be properly aligned by the driver const auto buffer_binding_address = buffer_state->binding.offset + vertex_buffer_offset; // Use 1 as vertex/instance index to use buffer stride as well const auto attrib_address = buffer_binding_address + vertex_buffer_stride + attribute_offset; uint32_t vtx_attrib_req_alignment = FormatElementSize(attribute_format); if (FormatElementIsTexel(attribute_format)) { vtx_attrib_req_alignment /= FormatChannelCount(attribute_format); } if (SafeModulo(attrib_address, vtx_attrib_req_alignment) != 0) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT, HandleToUint64(pCB->current_draw_data.vertex_buffer_bindings[vertex_binding].buffer), kVUID_Core_DrawState_InvalidVtxAttributeAlignment, "Invalid attribAddress alignment for vertex attribute " PRINTF_SIZE_T_SPECIFIER " from " "pipeline (0x%" PRIx64 ") and vertex buffer (0x%" PRIx64 ").", i, HandleToUint64(state.pipeline_state->pipeline), HandleToUint64(pCB->current_draw_data.vertex_buffer_bindings[vertex_binding].buffer)); } } } } else { if ((!pCB->current_draw_data.vertex_buffer_bindings.empty()) && (!pCB->vertex_buffer_used)) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_PERFORMANCE_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(pCB->commandBuffer), kVUID_Core_DrawState_VtxIndexOutOfBounds, "Vertex buffers are bound to command buffer (0x%" PRIx64 ") but no vertex buffers are attached to this Pipeline State Object (0x%" PRIx64 ").", HandleToUint64(pCB->commandBuffer), HandleToUint64(state.pipeline_state->pipeline)); } } // If Viewport or scissors are dynamic, verify that dynamic count matches PSO count. // Skip check if rasterization is disabled or there is no viewport. if ((!pPipeline->graphicsPipelineCI.pRasterizationState || (pPipeline->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable == VK_FALSE)) && pPipeline->graphicsPipelineCI.pViewportState) { bool dynViewport = IsDynamic(pPipeline, VK_DYNAMIC_STATE_VIEWPORT); bool dynScissor = IsDynamic(pPipeline, VK_DYNAMIC_STATE_SCISSOR); if (dynViewport) { const auto requiredViewportsMask = (1 << pPipeline->graphicsPipelineCI.pViewportState->viewportCount) - 1; const auto missingViewportMask = ~pCB->viewportMask & requiredViewportsMask; if (missingViewportMask) { std::stringstream ss; ss << "Dynamic viewport(s) "; ListBits(ss, missingViewportMask); ss << " are used by pipeline state object, but were not provided via calls to vkCmdSetViewport()."; skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, kVUID_Core_DrawState_ViewportScissorMismatch, "%s", ss.str().c_str()); } } if (dynScissor) { const auto requiredScissorMask = (1 << pPipeline->graphicsPipelineCI.pViewportState->scissorCount) - 1; const auto missingScissorMask = ~pCB->scissorMask & requiredScissorMask; if (missingScissorMask) { std::stringstream ss; ss << "Dynamic scissor(s) "; ListBits(ss, missingScissorMask); ss << " are used by pipeline state object, but were not provided via calls to vkCmdSetScissor()."; skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, kVUID_Core_DrawState_ViewportScissorMismatch, "%s", ss.str().c_str()); } } } // 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 VkSubpassDescription2KHR *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 |= (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 |= (unsigned)render_pass_info->pAttachments[attachment].samples; } if (!(dev_data->extensions.vk_amd_mixed_attachment_samples || dev_data->extensions.vk_nv_framebuffer_mixed_samples) && ((subpass_num_samples & static_cast<unsigned>(pso_num_samples)) != subpass_num_samples)) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, HandleToUint64(pPipeline->pipeline), kVUID_Core_DrawState_NumSamplesMismatch, "Num samples mismatch! At draw-time in Pipeline (0x%" PRIx64 ") with %u samples while current RenderPass (0x%" PRIx64 ") w/ %u samples!", HandleToUint64(pPipeline->pipeline), pso_num_samples, HandleToUint64(pCB->activeRenderPass->renderPass), subpass_num_samples); } } else { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, HandleToUint64(pPipeline->pipeline), kVUID_Core_DrawState_NoActiveRenderpass, "No active render pass found at draw-time in Pipeline (0x%" PRIx64 ")!", HandleToUint64(pPipeline->pipeline)); } } // Verify that PSO creation renderPass is compatible with active renderPass if (pCB->activeRenderPass) { // TODO: Move all of the error codes common across different Draws into a LUT accessed by cmd_type // TODO: AMD extension codes are included here, but actual function entrypoints are not yet intercepted // Error codes for renderpass and subpass mismatches auto rp_error = "VUID-vkCmdDraw-renderPass-00435", sp_error = "VUID-vkCmdDraw-subpass-00436"; switch (cmd_type) { case CMD_DRAWINDEXED: rp_error = "VUID-vkCmdDrawIndexed-renderPass-00454"; sp_error = "VUID-vkCmdDrawIndexed-subpass-00455"; break; case CMD_DRAWINDIRECT: rp_error = "VUID-vkCmdDrawIndirect-renderPass-00479"; sp_error = "VUID-vkCmdDrawIndirect-subpass-00480"; break; case CMD_DRAWINDIRECTCOUNTAMD: rp_error = "VUID-vkCmdDrawIndirectCountAMD-renderPass-00507"; sp_error = "VUID-vkCmdDrawIndirectCountAMD-subpass-00508"; break; case CMD_DRAWINDIRECTCOUNTKHR: rp_error = "VUID-vkCmdDrawIndirectCountKHR-renderPass-03113"; sp_error = "VUID-vkCmdDrawIndirectCountKHR-subpass-03114"; break; case CMD_DRAWINDEXEDINDIRECT: rp_error = "VUID-vkCmdDrawIndexedIndirect-renderPass-00531"; sp_error = "VUID-vkCmdDrawIndexedIndirect-subpass-00532"; break; case CMD_DRAWINDEXEDINDIRECTCOUNTAMD: rp_error = "VUID-vkCmdDrawIndexedIndirectCountAMD-renderPass-00560"; sp_error = "VUID-vkCmdDrawIndexedIndirectCountAMD-subpass-00561"; break; case CMD_DRAWINDEXEDINDIRECTCOUNTKHR: rp_error = "VUID-vkCmdDrawIndexedIndirectCountKHR-renderPass-03145"; sp_error = "VUID-vkCmdDrawIndexedIndirectCountKHR-subpass-03146"; break; case CMD_DRAWMESHTASKSNV: rp_error = "VUID-vkCmdDrawMeshTasksNV-renderPass-02120"; sp_error = "VUID-vkCmdDrawMeshTasksNV-subpass-02121"; break; case CMD_DRAWMESHTASKSINDIRECTNV: rp_error = "VUID-vkCmdDrawMeshTasksIndirectNV-renderPass-02148"; sp_error = "VUID-vkCmdDrawMeshTasksIndirectNV-subpass-02149"; break; case CMD_DRAWMESHTASKSINDIRECTCOUNTNV: rp_error = "VUID-vkCmdDrawMeshTasksIndirectCountNV-renderPass-02184"; sp_error = "VUID-vkCmdDrawMeshTasksIndirectCountNV-subpass-02185"; break; default: assert(CMD_DRAW == cmd_type); break; } std::string err_string; 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(dev_data, "active render pass", pCB->activeRenderPass, "pipeline state object", pPipeline->rp_state.get(), caller, rp_error); } if (pPipeline->graphicsPipelineCI.subpass != pCB->activeSubpass) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, HandleToUint64(pPipeline->pipeline), sp_error, "Pipeline was built for subpass %u but used in subpass %u.", pPipeline->graphicsPipelineCI.subpass, pCB->activeSubpass); } } return skip; } // For given cvdescriptorset::DescriptorSet, verify that its Set is compatible w/ the setLayout corresponding to // pipelineLayout[layoutIndex] static bool VerifySetLayoutCompatibility(const cvdescriptorset::DescriptorSet *descriptor_set, PIPELINE_LAYOUT_NODE const *pipeline_layout, const uint32_t layoutIndex, string &errorMsg) { auto num_sets = pipeline_layout->set_layouts.size(); if (layoutIndex >= num_sets) { stringstream errorStr; errorStr << "VkPipelineLayout (" << 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 = errorStr.str(); return false; } if (descriptor_set->IsPushDescriptor()) return true; auto layout_node = pipeline_layout->set_layouts[layoutIndex]; return descriptor_set->IsCompatible(layout_node.get(), &errorMsg); } // Validate overall state at the time of a draw call static bool ValidateCmdBufDrawState(layer_data *dev_data, GLOBAL_CB_NODE *cb_node, CMD_TYPE cmd_type, const bool indexed, const VkPipelineBindPoint bind_point, const char *function, const std::string &pipe_err_code, const std::string &state_err_code) { bool result = false; auto const &state = cb_node->lastBound[bind_point]; PIPELINE_STATE *pPipe = state.pipeline_state; if (nullptr == pPipe) { return log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(cb_node->commandBuffer), pipe_err_code, "Must not call %s on this command buffer while there is no %s pipeline bound.", function, bind_point == VK_PIPELINE_BIND_POINT_GRAPHICS ? "Graphics" : "Compute"); } // First check flag states if (VK_PIPELINE_BIND_POINT_GRAPHICS == bind_point) result = ValidateDrawStateFlags(dev_data, cb_node, pPipe, indexed, state_err_code); // Now complete other state checks string errorString; auto const &pipeline_layout = pPipe->pipeline_layout; for (const auto &set_binding_pair : pPipe->active_slots) { uint32_t setIndex = set_binding_pair.first; // If valid set is not bound throw an error if ((state.boundDescriptorSets.size() <= setIndex) || (!state.boundDescriptorSets[setIndex])) { result |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(cb_node->commandBuffer), kVUID_Core_DrawState_DescriptorSetNotBound, "VkPipeline 0x%" PRIx64 " uses set #%u but that set is not bound.", HandleToUint64(pPipe->pipeline), setIndex); } else if (!VerifySetLayoutCompatibility(state.boundDescriptorSets[setIndex], &pipeline_layout, setIndex, errorString)) { // Set is bound but not compatible w/ overlapping pipeline_layout from PSO VkDescriptorSet setHandle = state.boundDescriptorSets[setIndex]->GetSet(); result |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT, HandleToUint64(setHandle), kVUID_Core_DrawState_PipelineLayoutsIncompatible, "VkDescriptorSet (0x%" PRIx64 ") bound as set #%u is not compatible with overlapping VkPipelineLayout 0x%" PRIx64 " due to: %s", HandleToUint64(setHandle), setIndex, HandleToUint64(pipeline_layout.layout), errorString.c_str()); } else { // Valid set is bound and layout compatible, validate that it's updated // Pull the set node cvdescriptorset::DescriptorSet *descriptor_set = state.boundDescriptorSets[setIndex]; // Validate the draw-time state for this descriptor set std::string err_str; if (!descriptor_set->IsPushDescriptor()) { // 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. const cvdescriptorset::PrefilterBindRequestMap reduced_map(*descriptor_set, set_binding_pair.second, cb_node, pPipe); const auto &binding_req_map = reduced_map.Map(); if (!descriptor_set->ValidateDrawState(binding_req_map, state.dynamicOffsets[setIndex], cb_node, function, &err_str)) { auto set = descriptor_set->GetSet(); result |= log_msg( dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT, HandleToUint64(set), kVUID_Core_DrawState_DescriptorSetNotUpdated, "Descriptor set 0x%" PRIx64 " bound as set #%u encountered the following validation error at %s time: %s", HandleToUint64(set), setIndex, function, err_str.c_str()); } } } } // Check general pipeline state that needs to be validated at drawtime if (VK_PIPELINE_BIND_POINT_GRAPHICS == bind_point) result |= ValidatePipelineDrawtimeState(dev_data, state, cb_node, cmd_type, pPipe, function); return result; } static void UpdateDrawState(layer_data *dev_data, GLOBAL_CB_NODE *cb_state, const VkPipelineBindPoint bind_point) { auto const &state = cb_state->lastBound[bind_point]; PIPELINE_STATE *pPipe = state.pipeline_state; if (VK_NULL_HANDLE != state.pipeline_layout) { for (const auto &set_binding_pair : pPipe->active_slots) { uint32_t setIndex = set_binding_pair.first; // Pull the set node cvdescriptorset::DescriptorSet *descriptor_set = state.boundDescriptorSets[setIndex]; if (!descriptor_set->IsPushDescriptor()) { // For the "bindless" style resource usage with many descriptors, need to optimize command <-> descriptor binding const cvdescriptorset::PrefilterBindRequestMap reduced_map(*descriptor_set, set_binding_pair.second, cb_state); const auto &binding_req_map = reduced_map.Map(); // Bind this set and its active descriptor resources to the command buffer descriptor_set->UpdateDrawState(cb_state, binding_req_map); // For given active slots record updated images & buffers descriptor_set->GetStorageUpdates(binding_req_map, &cb_state->updateBuffers, &cb_state->updateImages); } } } if (!pPipe->vertex_binding_descriptions_.empty()) { cb_state->vertex_buffer_used = true; } } static bool ValidatePipelineLocked(layer_data *dev_data, std::vector<std::unique_ptr<PIPELINE_STATE>> const &pPipelines, int pipelineIndex) { bool skip = false; PIPELINE_STATE *pPipeline = 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 (pPipeline->graphicsPipelineCI.flags & VK_PIPELINE_CREATE_DERIVATIVE_BIT) { PIPELINE_STATE *pBasePipeline = nullptr; if (!((pPipeline->graphicsPipelineCI.basePipelineHandle != VK_NULL_HANDLE) ^ (pPipeline->graphicsPipelineCI.basePipelineIndex != -1))) { // This check is a superset of "VUID-VkGraphicsPipelineCreateInfo-flags-00724" and // "VUID-VkGraphicsPipelineCreateInfo-flags-00725" skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, HandleToUint64(pPipeline->pipeline), kVUID_Core_DrawState_InvalidPipelineCreateState, "Invalid Pipeline CreateInfo: exactly one of base pipeline index and handle must be specified"); } else if (pPipeline->graphicsPipelineCI.basePipelineIndex != -1) { if (pPipeline->graphicsPipelineCI.basePipelineIndex >= pipelineIndex) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, HandleToUint64(pPipeline->pipeline), "VUID-vkCreateGraphicsPipelines-flags-00720", "Invalid Pipeline CreateInfo: base pipeline must occur earlier in array than derivative pipeline."); } else { pBasePipeline = pPipelines[pPipeline->graphicsPipelineCI.basePipelineIndex].get(); } } else if (pPipeline->graphicsPipelineCI.basePipelineHandle != VK_NULL_HANDLE) { pBasePipeline = GetPipelineState(dev_data, pPipeline->graphicsPipelineCI.basePipelineHandle); } if (pBasePipeline && !(pBasePipeline->graphicsPipelineCI.flags & VK_PIPELINE_CREATE_ALLOW_DERIVATIVES_BIT)) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, HandleToUint64(pPipeline->pipeline), kVUID_Core_DrawState_InvalidPipelineCreateState, "Invalid Pipeline CreateInfo: base pipeline does not allow derivatives."); } } return skip; } // UNLOCKED pipeline validation. DO NOT lookup objects in the layer_data->* maps in this function. static bool ValidatePipelineUnlocked(layer_data *dev_data, std::vector<std::unique_ptr<PIPELINE_STATE>> const &pPipelines, int pipelineIndex) { bool skip = false; PIPELINE_STATE *pPipeline = pPipelines[pipelineIndex].get(); // Ensure the subpass index is valid. If not, then ValidateAndCapturePipelineShaderState // 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 |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, HandleToUint64(pPipeline->pipeline), "VUID-VkGraphicsPipelineCreateInfo-subpass-00759", "Invalid Pipeline CreateInfo State: Subpass index %u is out of range for this renderpass (0..%u).", 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 (color_blend_state->attachmentCount != subpass_desc->colorAttachmentCount) { skip |= log_msg( dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, HandleToUint64(pPipeline->pipeline), "VUID-VkGraphicsPipelineCreateInfo-attachmentCount-00746", "vkCreateGraphicsPipelines(): Render pass (0x%" PRIx64 ") subpass %u has colorAttachmentCount of %u which doesn't match the pColorBlendState->attachmentCount of %u.", HandleToUint64(pPipeline->rp_state->renderPass), pPipeline->graphicsPipelineCI.subpass, subpass_desc->colorAttachmentCount, color_blend_state->attachmentCount); } if (!dev_data->enabled_features.core.independentBlend) { if (pPipeline->attachments.size() > 1) { VkPipelineColorBlendAttachmentState *pAttachments = &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 *>(pAttachments), static_cast<const void *>(&pAttachments[i]), sizeof(pAttachments[0]))) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, HandleToUint64(pPipeline->pipeline), "VUID-VkPipelineColorBlendStateCreateInfo-pAttachments-00605", "Invalid Pipeline CreateInfo: If independent blend feature not enabled, all elements of " "pAttachments must be identical."); break; } } } } if (!dev_data->enabled_features.core.logicOp && (pPipeline->graphicsPipelineCI.pColorBlendState->logicOpEnable != VK_FALSE)) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, HandleToUint64(pPipeline->pipeline), "VUID-VkPipelineColorBlendStateCreateInfo-logicOpEnable-00606", "Invalid Pipeline CreateInfo: If logic operations feature not enabled, logicOpEnable must be VK_FALSE."); } 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 (!dev_data->enabled_features.core.dualSrcBlend) { skip |= log_msg( dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, HandleToUint64(pPipeline->pipeline), "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 (!dev_data->enabled_features.core.dualSrcBlend) { skip |= log_msg( dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, HandleToUint64(pPipeline->pipeline), "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 (!dev_data->enabled_features.core.dualSrcBlend) { skip |= log_msg( dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, HandleToUint64(pPipeline->pipeline), "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 (!dev_data->enabled_features.core.dualSrcBlend) { skip |= log_msg( dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, HandleToUint64(pPipeline->pipeline), "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 (ValidateAndCapturePipelineShaderState(dev_data, 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 |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, HandleToUint64(pPipeline->pipeline), kVUID_Core_DrawState_InvalidPipelineCreateState, "Invalid Pipeline CreateInfo State: Multiple shaders provided for stage %s", string_VkShaderStageFlagBits(VkShaderStageFlagBits(stage))); } } } if (dev_data->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 |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, HandleToUint64(pPipeline->pipeline), "VUID-VkGraphicsPipelineCreateInfo-stage-02096", "Invalid Pipeline CreateInfo State: Vertex Shader or Mesh Shader required."); } // 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 |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, HandleToUint64(pPipeline->pipeline), "VUID-VkGraphicsPipelineCreateInfo-pStages-02095", "Invalid Pipeline CreateInfo State: Geometric shader stages must either be all mesh (mesh | task) " "or all VTG (vertex, tess control, tess eval, geom)."); } } else { // VS is required if (!(pPipeline->active_shaders & VK_SHADER_STAGE_VERTEX_BIT)) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, HandleToUint64(pPipeline->pipeline), "VUID-VkGraphicsPipelineCreateInfo-stage-00727", "Invalid Pipeline CreateInfo State: Vertex Shader required."); } } if (!dev_data->enabled_features.mesh_shader.meshShader && (pPipeline->active_shaders & VK_SHADER_STAGE_MESH_BIT_NV)) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, HandleToUint64(pPipeline->pipeline), "VUID-VkPipelineShaderStageCreateInfo-stage-02091", "Invalid Pipeline CreateInfo State: Mesh Shader not supported."); } if (!dev_data->enabled_features.mesh_shader.taskShader && (pPipeline->active_shaders & VK_SHADER_STAGE_TASK_BIT_NV)) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, HandleToUint64(pPipeline->pipeline), "VUID-VkPipelineShaderStageCreateInfo-stage-02092", "Invalid Pipeline CreateInfo State: Task Shader not supported."); } // 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 |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, HandleToUint64(pPipeline->pipeline), "VUID-VkGraphicsPipelineCreateInfo-pStages-00729", "Invalid Pipeline CreateInfo State: TE and TC shaders must be included or excluded as a pair."); } if (!has_control && has_eval) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, HandleToUint64(pPipeline->pipeline), "VUID-VkGraphicsPipelineCreateInfo-pStages-00730", "Invalid Pipeline CreateInfo State: TE and TC shaders must be included or excluded as a pair."); } // Compute shaders should be specified independent of Gfx shaders if (pPipeline->active_shaders & VK_SHADER_STAGE_COMPUTE_BIT) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, HandleToUint64(pPipeline->pipeline), "VUID-VkGraphicsPipelineCreateInfo-stage-00728", "Invalid Pipeline CreateInfo State: Do not specify Compute Shader for Gfx Pipeline."); } if ((pPipeline->active_shaders & VK_SHADER_STAGE_VERTEX_BIT) && !pPipeline->graphicsPipelineCI.pInputAssemblyState) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, HandleToUint64(pPipeline->pipeline), "VUID-VkGraphicsPipelineCreateInfo-pStages-02098", "Invalid Pipeline CreateInfo State: Missing pInputAssemblyState."); } // 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 |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, HandleToUint64(pPipeline->pipeline), "VUID-VkGraphicsPipelineCreateInfo-pStages-00736", "Invalid Pipeline CreateInfo State: VK_PRIMITIVE_TOPOLOGY_PATCH_LIST must be set as IA topology for " "tessellation pipelines."); } if (pPipeline->graphicsPipelineCI.pInputAssemblyState && pPipeline->graphicsPipelineCI.pInputAssemblyState->topology == VK_PRIMITIVE_TOPOLOGY_PATCH_LIST) { if (!has_control || !has_eval) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, HandleToUint64(pPipeline->pipeline), "VUID-VkGraphicsPipelineCreateInfo-topology-00737", "Invalid Pipeline CreateInfo State: VK_PRIMITIVE_TOPOLOGY_PATCH_LIST primitive topology is only valid " "for tessellation pipelines."); } } // If a rasterization state is provided... if (pPipeline->graphicsPipelineCI.pRasterizationState) { if ((pPipeline->graphicsPipelineCI.pRasterizationState->depthClampEnable == VK_TRUE) && (!dev_data->enabled_features.core.depthClamp)) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, HandleToUint64(pPipeline->pipeline), "VUID-VkPipelineRasterizationStateCreateInfo-depthClampEnable-00782", "vkCreateGraphicsPipelines(): the depthClamp device feature is disabled: the depthClampEnable member " "of the VkPipelineRasterizationStateCreateInfo structure must be set to VK_FALSE."); } if (!IsDynamic(pPipeline, VK_DYNAMIC_STATE_DEPTH_BIAS) && (pPipeline->graphicsPipelineCI.pRasterizationState->depthBiasClamp != 0.0) && (!dev_data->enabled_features.core.depthBiasClamp)) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, HandleToUint64(pPipeline->pipeline), kVUID_Core_DrawState_InvalidFeature, "vkCreateGraphicsPipelines(): 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"); } // If rasterization is enabled... if (pPipeline->graphicsPipelineCI.pRasterizationState->rasterizerDiscardEnable == VK_FALSE) { if ((pPipeline->graphicsPipelineCI.pMultisampleState->alphaToOneEnable == VK_TRUE) && (!dev_data->enabled_features.core.alphaToOne)) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, HandleToUint64(pPipeline->pipeline), "VUID-VkPipelineMultisampleStateCreateInfo-alphaToOneEnable-00785", "vkCreateGraphicsPipelines(): the alphaToOne device feature is disabled: the alphaToOneEnable " "member of the VkPipelineMultisampleStateCreateInfo structure must be set to VK_FALSE."); } // 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 |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, HandleToUint64(pPipeline->pipeline), "VUID-VkGraphicsPipelineCreateInfo-rasterizerDiscardEnable-00752", "Invalid Pipeline CreateInfo State: pDepthStencilState is NULL when rasterization is enabled " "and subpass uses a depth/stencil attachment."); } else if ((pPipeline->graphicsPipelineCI.pDepthStencilState->depthBoundsTestEnable == VK_TRUE) && (!dev_data->enabled_features.core.depthBounds)) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, HandleToUint64(pPipeline->pipeline), "VUID-VkPipelineDepthStencilStateCreateInfo-depthBoundsTestEnable-00598", "vkCreateGraphicsPipelines(): the depthBounds device feature is disabled: the " "depthBoundsTestEnable member of the VkPipelineDepthStencilStateCreateInfo structure must be " "set to VK_FALSE."); } } // 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 |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, HandleToUint64(pPipeline->pipeline), "VUID-VkGraphicsPipelineCreateInfo-rasterizerDiscardEnable-00753", "Invalid Pipeline CreateInfo State: pColorBlendState is NULL when rasterization is enabled and " "subpass uses color attachments."); } } } } if ((pPipeline->active_shaders & VK_SHADER_STAGE_VERTEX_BIT) && !pPipeline->graphicsPipelineCI.pVertexInputState) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, HandleToUint64(pPipeline->pipeline), "VUID-VkGraphicsPipelineCreateInfo-pStages-02097", "Invalid Pipeline CreateInfo State: Missing pVertexInputState."); } 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; dev_data->instance_data->dispatch_table.GetPhysicalDeviceFormatProperties(dev_data->physical_device, format, &properties); if ((properties.bufferFeatures & VK_FORMAT_FEATURE_VERTEX_BUFFER_BIT) == 0) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkVertexInputAttributeDescription-format-00623", "vkCreateGraphicsPipelines: pCreateInfo[%d].pVertexInputState->vertexAttributeDescriptions[%d].format " "(%s) is not a supported vertex buffer format.", pipelineIndex, j, string_VkFormat(format)); } } } auto accumColorSamples = [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 (!(dev_data->extensions.vk_amd_mixed_attachment_samples || dev_data->extensions.vk_nv_framebuffer_mixed_samples)) { uint32_t raster_samples = static_cast<uint32_t>(GetNumSamples(pPipeline)); uint32_t subpass_num_samples = 0; accumColorSamples(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 |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, HandleToUint64(pPipeline->pipeline), "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 (dev_data->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) && (pPipeline->graphicsPipelineCI.pMultisampleState->rasterizationSamples != max_sample_count)) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, HandleToUint64(pPipeline->pipeline), "VUID-VkGraphicsPipelineCreateInfo-subpass-01505", "vkCreateGraphicsPipelines: pCreateInfo[%d].pMultisampleState->rasterizationSamples (%s) != max " "attachment samples (%s) used in subpass %u.", pipelineIndex, string_VkSampleCountFlagBits(pPipeline->graphicsPipelineCI.pMultisampleState->rasterizationSamples), string_VkSampleCountFlagBits(max_sample_count), pPipeline->graphicsPipelineCI.subpass); } } if (dev_data->extensions.vk_nv_framebuffer_mixed_samples) { uint32_t raster_samples = static_cast<uint32_t>(GetNumSamples(pPipeline)); uint32_t subpass_color_samples = 0; accumColorSamples(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 |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, HandleToUint64(pPipeline->pipeline), "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 |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, HandleToUint64(pPipeline->pipeline), "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 (pPipeline->graphicsPipelineCI.pMultisampleState) { if ((raster_samples > subpass_color_samples) && (pPipeline->graphicsPipelineCI.pMultisampleState->sampleShadingEnable == VK_TRUE)) { skip |= log_msg( dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, HandleToUint64(pPipeline->pipeline), "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 = lvl_find_in_chain<VkPipelineCoverageModulationStateCreateInfoNV>( pPipeline->graphicsPipelineCI.pMultisampleState->pNext); if (coverage_modulation_state && (coverage_modulation_state->coverageModulationTableEnable == VK_TRUE)) { if (coverage_modulation_state->coverageModulationTableCount != (raster_samples / subpass_color_samples)) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, HandleToUint64(pPipeline->pipeline), "VUID-VkPipelineCoverageModulationStateCreateInfoNV-coverageModulationTableEnable-01405", "vkCreateGraphicsPipelines: pCreateInfos[%d] VkPipelineCoverageModulationStateCreateInfoNV " "coverageModulationTableCount of %u is invalid.", pipelineIndex, coverage_modulation_state->coverageModulationTableCount); } } } } } if (dev_data->extensions.vk_nv_fragment_coverage_to_color) { const auto coverage_to_color_state = lvl_find_in_chain<VkPipelineCoverageToColorStateCreateInfoNV>(pPipeline->graphicsPipelineCI.pMultisampleState); 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: string_sprintf(&error_detail, "references an attachment with an invalid format (%s).", string_VkFormat(color_attachment.format)); break; } } else { string_sprintf(&error_detail, "references an invalid attachment. The subpass pColorAttachments[%" PRIu32 "].attachment has the value " "VK_ATTACHMENT_UNUSED.", coverage_to_color_state->coverageToColorLocation); } } else { string_sprintf(&error_detail, "references an non-existing attachment since the subpass colorAttachmentCount is %" PRIu32 ".", subpass_desc->colorAttachmentCount); } if (!attachment_is_valid) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, HandleToUint64(pPipeline->pipeline), "VUID-VkPipelineCoverageToColorStateCreateInfoNV-coverageToColorEnable-01404", "vkCreateGraphicsPipelines: pCreateInfos[%" PRId32 "].pMultisampleState VkPipelineCoverageToColorStateCreateInfoNV " "coverageToColorLocation = %" PRIu32 " %s", pipelineIndex, coverage_to_color_state->coverageToColorLocation, error_detail.c_str()); } } } return skip; } // Block of code at start here specifically for managing/tracking DSs // Return Pool node ptr for specified pool or else NULL DESCRIPTOR_POOL_STATE *GetDescriptorPoolState(const layer_data *dev_data, const VkDescriptorPool pool) { auto pool_it = dev_data->descriptorPoolMap.find(pool); if (pool_it == dev_data->descriptorPoolMap.end()) { return NULL; } return pool_it->second; } // 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) static bool ValidateIdleDescriptorSet(const layer_data *dev_data, VkDescriptorSet set, std::string func_str) { if (dev_data->instance_data->disabled.idle_descriptor_set) return false; bool skip = false; auto set_node = dev_data->setMap.find(set); if (set_node == dev_data->setMap.end()) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT, HandleToUint64(set), kVUID_Core_DrawState_DoubleDestroy, "Cannot call %s() on descriptor set 0x%" PRIx64 " that has not been allocated.", func_str.c_str(), HandleToUint64(set)); } else { // TODO : This covers various error cases so should pass error enum into this function and use passed in enum here if (set_node->second->in_use.load()) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT, HandleToUint64(set), "VUID-vkFreeDescriptorSets-pDescriptorSets-00309", "Cannot call %s() on descriptor set 0x%" PRIx64 " that is in use by a command buffer.", func_str.c_str(), HandleToUint64(set)); } } return skip; } // Remove set from setMap and delete the set static void FreeDescriptorSet(layer_data *dev_data, cvdescriptorset::DescriptorSet *descriptor_set) { dev_data->setMap.erase(descriptor_set->GetSet()); delete descriptor_set; } // Free all DS Pools including their Sets & related sub-structs // NOTE : Calls to this function should be wrapped in mutex static void DeletePools(layer_data *dev_data) { for (auto ii = dev_data->descriptorPoolMap.begin(); ii != dev_data->descriptorPoolMap.end();) { // Remove this pools' sets from setMap and delete them for (auto ds : ii->second->sets) { FreeDescriptorSet(dev_data, ds); } ii->second->sets.clear(); delete ii->second; ii = dev_data->descriptorPoolMap.erase(ii); } } // For given CB object, fetch associated CB Node from map GLOBAL_CB_NODE *GetCBNode(layer_data const *dev_data, const VkCommandBuffer cb) { auto it = dev_data->commandBufferMap.find(cb); if (it == dev_data->commandBufferMap.end()) { return NULL; } return it->second; } // If a renderpass is active, verify that the given command type is appropriate for current subpass state bool ValidateCmdSubpassState(const layer_data *dev_data, const GLOBAL_CB_NODE *pCB, const CMD_TYPE cmd_type) { 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_NEXTSUBPASS2KHR && cmd_type != CMD_ENDRENDERPASS2KHR)) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(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 |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(pCB->commandBuffer), kVUID_Core_DrawState_InvalidCommandBuffer, "vkCmdExecuteCommands() cannot be called in a subpass using inline commands."); } return skip; } bool ValidateCmdQueueFlags(layer_data *dev_data, const GLOBAL_CB_NODE *cb_node, const char *caller_name, VkQueueFlags required_flags, const std::string &error_code) { auto pool = GetCommandPoolNode(dev_data, cb_node->createInfo.commandPool); if (pool) { VkQueueFlags queue_flags = dev_data->phys_dev_properties.queue_family_properties[pool->queueFamilyIndex].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}) { if (flag & required_flags) { if (required_flags_string.size()) { required_flags_string += " or "; } required_flags_string += string_VkQueueFlagBits(flag); } } return log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(cb_node->commandBuffer), error_code, "Cannot call %s on a command buffer allocated from a pool without %s capabilities..", caller_name, required_flags_string.c_str()); } } return false; } static char const *GetCauseStr(VK_OBJECT obj) { if (obj.type == kVulkanObjectTypeDescriptorSet) return "destroyed or updated"; if (obj.type == kVulkanObjectTypeCommandBuffer) return "destroyed or rerecorded"; return "destroyed"; } static bool ReportInvalidCommandBuffer(layer_data *dev_data, const GLOBAL_CB_NODE *cb_state, const char *call_source) { bool skip = false; for (auto obj : cb_state->broken_bindings) { const char *type_str = object_string[obj.type]; const char *cause_str = GetCauseStr(obj); skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(cb_state->commandBuffer), kVUID_Core_DrawState_InvalidCommandBuffer, "You are adding %s to command buffer 0x%" PRIx64 " that is invalid because bound %s 0x%" PRIx64 " was %s.", call_source, HandleToUint64(cb_state->commandBuffer), type_str, obj.handle, cause_str); } return skip; } // 'commandBuffer must be in the recording state' valid usage error code for each command // Note: grepping for ^^^^^^^^^ in vk_validation_database is easily massaged into the following list // Note: C++11 doesn't automatically devolve enum types to the underlying type for hash traits purposes (fixed in C++14) using CmdTypeHashType = std::underlying_type<CMD_TYPE>::type; static const std::unordered_map<CmdTypeHashType, std::string> must_be_recording_map = { {CMD_NONE, kVUIDUndefined}, // UNMATCHED {CMD_BEGINQUERY, "VUID-vkCmdBeginQuery-commandBuffer-recording"}, {CMD_BEGINRENDERPASS, "VUID-vkCmdBeginRenderPass-commandBuffer-recording"}, {CMD_BEGINRENDERPASS2KHR, "VUID-vkCmdBeginRenderPass2KHR-commandBuffer-recording"}, {CMD_BINDDESCRIPTORSETS, "VUID-vkCmdBindDescriptorSets-commandBuffer-recording"}, {CMD_BINDINDEXBUFFER, "VUID-vkCmdBindIndexBuffer-commandBuffer-recording"}, {CMD_BINDPIPELINE, "VUID-vkCmdBindPipeline-commandBuffer-recording"}, {CMD_BINDSHADINGRATEIMAGE, "VUID-vkCmdBindShadingRateImageNV-commandBuffer-recording"}, {CMD_BINDVERTEXBUFFERS, "VUID-vkCmdBindVertexBuffers-commandBuffer-recording"}, {CMD_BLITIMAGE, "VUID-vkCmdBlitImage-commandBuffer-recording"}, {CMD_CLEARATTACHMENTS, "VUID-vkCmdClearAttachments-commandBuffer-recording"}, {CMD_CLEARCOLORIMAGE, "VUID-vkCmdClearColorImage-commandBuffer-recording"}, {CMD_CLEARDEPTHSTENCILIMAGE, "VUID-vkCmdClearDepthStencilImage-commandBuffer-recording"}, {CMD_COPYBUFFER, "VUID-vkCmdCopyBuffer-commandBuffer-recording"}, {CMD_COPYBUFFERTOIMAGE, "VUID-vkCmdCopyBufferToImage-commandBuffer-recording"}, {CMD_COPYIMAGE, "VUID-vkCmdCopyImage-commandBuffer-recording"}, {CMD_COPYIMAGETOBUFFER, "VUID-vkCmdCopyImageToBuffer-commandBuffer-recording"}, {CMD_COPYQUERYPOOLRESULTS, "VUID-vkCmdCopyQueryPoolResults-commandBuffer-recording"}, {CMD_DEBUGMARKERBEGINEXT, "VUID-vkCmdDebugMarkerBeginEXT-commandBuffer-recording"}, {CMD_DEBUGMARKERENDEXT, "VUID-vkCmdDebugMarkerEndEXT-commandBuffer-recording"}, {CMD_DEBUGMARKERINSERTEXT, "VUID-vkCmdDebugMarkerInsertEXT-commandBuffer-recording"}, {CMD_DISPATCH, "VUID-vkCmdDispatch-commandBuffer-recording"}, // Exclude KHX (if not already present) { CMD_DISPATCHBASEKHX, "VUID-vkCmdDispatchBase-commandBuffer-recording" }, {CMD_DISPATCHINDIRECT, "VUID-vkCmdDispatchIndirect-commandBuffer-recording"}, {CMD_DRAW, "VUID-vkCmdDraw-commandBuffer-recording"}, {CMD_DRAWINDEXED, "VUID-vkCmdDrawIndexed-commandBuffer-recording"}, {CMD_DRAWINDEXEDINDIRECT, "VUID-vkCmdDrawIndexedIndirect-commandBuffer-recording"}, // Exclude vendor ext (if not already present) { CMD_DRAWINDEXEDINDIRECTCOUNTAMD, // "VUID-vkCmdDrawIndexedIndirectCountAMD-commandBuffer-recording" }, {CMD_DRAWINDEXEDINDIRECTCOUNTKHR, "VUID-vkCmdDrawIndexedIndirectCountKHR-commandBuffer-recording"}, {CMD_DRAWINDIRECT, "VUID-vkCmdDrawIndirect-commandBuffer-recording"}, // Exclude vendor ext (if not already present) { CMD_DRAWINDIRECTCOUNTAMD, // "VUID-vkCmdDrawIndirectCountAMD-commandBuffer-recording" }, {CMD_DRAWINDIRECTCOUNTKHR, "VUID-vkCmdDrawIndirectCountKHR-commandBuffer-recording"}, {CMD_DRAWMESHTASKSNV, "VUID-vkCmdDrawMeshTasksNV-commandBuffer-recording"}, {CMD_DRAWMESHTASKSINDIRECTNV, "VUID-vkCmdDrawMeshTasksIndirectNV-commandBuffer-recording"}, {CMD_DRAWMESHTASKSINDIRECTCOUNTNV, "VUID-vkCmdDrawMeshTasksIndirectCountNV-commandBuffer-recording"}, {CMD_ENDCOMMANDBUFFER, "VUID-vkEndCommandBuffer-commandBuffer-00059"}, {CMD_ENDQUERY, "VUID-vkCmdEndQuery-commandBuffer-recording"}, {CMD_ENDRENDERPASS, "VUID-vkCmdEndRenderPass-commandBuffer-recording"}, {CMD_ENDRENDERPASS2KHR, "VUID-vkCmdEndRenderPass2KHR-commandBuffer-recording"}, {CMD_EXECUTECOMMANDS, "VUID-vkCmdExecuteCommands-commandBuffer-recording"}, {CMD_FILLBUFFER, "VUID-vkCmdFillBuffer-commandBuffer-recording"}, {CMD_NEXTSUBPASS, "VUID-vkCmdNextSubpass-commandBuffer-recording"}, {CMD_NEXTSUBPASS2KHR, "VUID-vkCmdNextSubpass2KHR-commandBuffer-recording"}, {CMD_PIPELINEBARRIER, "VUID-vkCmdPipelineBarrier-commandBuffer-recording"}, // Exclude vendor ext (if not already present) { CMD_PROCESSCOMMANDSNVX, "VUID-vkCmdProcessCommandsNVX-commandBuffer-recording" // }, {CMD_PUSHCONSTANTS, "VUID-vkCmdPushConstants-commandBuffer-recording"}, {CMD_PUSHDESCRIPTORSETKHR, "VUID-vkCmdPushDescriptorSetKHR-commandBuffer-recording"}, {CMD_PUSHDESCRIPTORSETWITHTEMPLATEKHR, "VUID-vkCmdPushDescriptorSetWithTemplateKHR-commandBuffer-recording"}, // Exclude vendor ext (if not already present) { CMD_RESERVESPACEFORCOMMANDSNVX, // "VUID-vkCmdReserveSpaceForCommandsNVX-commandBuffer-recording" }, {CMD_RESETEVENT, "VUID-vkCmdResetEvent-commandBuffer-recording"}, {CMD_RESETQUERYPOOL, "VUID-vkCmdResetQueryPool-commandBuffer-recording"}, {CMD_RESOLVEIMAGE, "VUID-vkCmdResolveImage-commandBuffer-recording"}, {CMD_SETBLENDCONSTANTS, "VUID-vkCmdSetBlendConstants-commandBuffer-recording"}, {CMD_SETDEPTHBIAS, "VUID-vkCmdSetDepthBias-commandBuffer-recording"}, {CMD_SETDEPTHBOUNDS, "VUID-vkCmdSetDepthBounds-commandBuffer-recording"}, // Exclude KHX (if not already present) { CMD_SETDEVICEMASKKHX, "VUID-vkCmdSetDeviceMask-commandBuffer-recording" }, {CMD_SETDISCARDRECTANGLEEXT, "VUID-vkCmdSetDiscardRectangleEXT-commandBuffer-recording"}, {CMD_SETEVENT, "VUID-vkCmdSetEvent-commandBuffer-recording"}, {CMD_SETEXCLUSIVESCISSOR, "VUID-vkCmdSetExclusiveScissorNV-commandBuffer-recording"}, {CMD_SETLINEWIDTH, "VUID-vkCmdSetLineWidth-commandBuffer-recording"}, {CMD_SETSAMPLELOCATIONSEXT, "VUID-vkCmdSetSampleLocationsEXT-commandBuffer-recording"}, {CMD_SETSCISSOR, "VUID-vkCmdSetScissor-commandBuffer-recording"}, {CMD_SETSTENCILCOMPAREMASK, "VUID-vkCmdSetStencilCompareMask-commandBuffer-recording"}, {CMD_SETSTENCILREFERENCE, "VUID-vkCmdSetStencilReference-commandBuffer-recording"}, {CMD_SETSTENCILWRITEMASK, "VUID-vkCmdSetStencilWriteMask-commandBuffer-recording"}, {CMD_SETVIEWPORT, "VUID-vkCmdSetViewport-commandBuffer-recording"}, {CMD_SETVIEWPORTSHADINGRATEPALETTE, "VUID-vkCmdSetViewportShadingRatePaletteNV-commandBuffer-recording"}, // Exclude vendor ext (if not already present) { CMD_SETVIEWPORTWSCALINGNV, // "VUID-vkCmdSetViewportWScalingNV-commandBuffer-recording" }, {CMD_UPDATEBUFFER, "VUID-vkCmdUpdateBuffer-commandBuffer-recording"}, {CMD_WAITEVENTS, "VUID-vkCmdWaitEvents-commandBuffer-recording"}, {CMD_WRITETIMESTAMP, "VUID-vkCmdWriteTimestamp-commandBuffer-recording"}, }; // Validate the given command being added to the specified cmd buffer, flagging errors if CB is not in the recording state or if // there's an issue with the Cmd ordering bool ValidateCmd(layer_data *dev_data, const GLOBAL_CB_NODE *cb_state, const CMD_TYPE cmd, const char *caller_name) { switch (cb_state->state) { case CB_RECORDING: return ValidateCmdSubpassState(dev_data, cb_state, cmd); case CB_INVALID_COMPLETE: case CB_INVALID_INCOMPLETE: return ReportInvalidCommandBuffer(dev_data, cb_state, caller_name); default: auto error_it = must_be_recording_map.find(cmd); // This assert lets us know that a vkCmd.* entrypoint has been added without enabling it in the map assert(error_it != must_be_recording_map.cend()); if (error_it == must_be_recording_map.cend()) { error_it = must_be_recording_map.find(CMD_NONE); // But we'll handle the asserting case, in case of a test gap } const auto error = error_it->second; return log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(cb_state->commandBuffer), error, "You must call vkBeginCommandBuffer() before this call to %s.", caller_name); } } // For given object struct return a ptr of BASE_NODE type for its wrapping struct BASE_NODE *GetStateStructPtrFromObject(layer_data *dev_data, VK_OBJECT object_struct) { BASE_NODE *base_ptr = nullptr; switch (object_struct.type) { case kVulkanObjectTypeDescriptorSet: { base_ptr = GetSetNode(dev_data, reinterpret_cast<VkDescriptorSet &>(object_struct.handle)); break; } case kVulkanObjectTypeSampler: { base_ptr = GetSamplerState(dev_data, reinterpret_cast<VkSampler &>(object_struct.handle)); break; } case kVulkanObjectTypeQueryPool: { base_ptr = GetQueryPoolNode(dev_data, reinterpret_cast<VkQueryPool &>(object_struct.handle)); break; } case kVulkanObjectTypePipeline: { base_ptr = GetPipelineState(dev_data, reinterpret_cast<VkPipeline &>(object_struct.handle)); break; } case kVulkanObjectTypeBuffer: { base_ptr = GetBufferState(dev_data, reinterpret_cast<VkBuffer &>(object_struct.handle)); break; } case kVulkanObjectTypeBufferView: { base_ptr = GetBufferViewState(dev_data, reinterpret_cast<VkBufferView &>(object_struct.handle)); break; } case kVulkanObjectTypeImage: { base_ptr = GetImageState(dev_data, reinterpret_cast<VkImage &>(object_struct.handle)); break; } case kVulkanObjectTypeImageView: { base_ptr = GetImageViewState(dev_data, reinterpret_cast<VkImageView &>(object_struct.handle)); break; } case kVulkanObjectTypeEvent: { base_ptr = GetEventNode(dev_data, reinterpret_cast<VkEvent &>(object_struct.handle)); break; } case kVulkanObjectTypeDescriptorPool: { base_ptr = GetDescriptorPoolState(dev_data, reinterpret_cast<VkDescriptorPool &>(object_struct.handle)); break; } case kVulkanObjectTypeCommandPool: { base_ptr = GetCommandPoolNode(dev_data, reinterpret_cast<VkCommandPool &>(object_struct.handle)); break; } case kVulkanObjectTypeFramebuffer: { base_ptr = GetFramebufferState(dev_data, reinterpret_cast<VkFramebuffer &>(object_struct.handle)); break; } case kVulkanObjectTypeRenderPass: { base_ptr = GetRenderPassState(dev_data, reinterpret_cast<VkRenderPass &>(object_struct.handle)); break; } case kVulkanObjectTypeDeviceMemory: { base_ptr = GetMemObjInfo(dev_data, reinterpret_cast<VkDeviceMemory &>(object_struct.handle)); break; } default: // TODO : Any other objects to be handled here? assert(0); break; } return base_ptr; } // Tie the VK_OBJECT to the cmd buffer which includes: // Add object_binding to cmd buffer // Add cb_binding to object static void AddCommandBufferBinding(std::unordered_set<GLOBAL_CB_NODE *> *cb_bindings, VK_OBJECT obj, GLOBAL_CB_NODE *cb_node) { cb_bindings->insert(cb_node); cb_node->object_bindings.insert(obj); } // For a given object, if cb_node is in that objects cb_bindings, remove cb_node static void RemoveCommandBufferBinding(layer_data *dev_data, VK_OBJECT const *object, GLOBAL_CB_NODE *cb_node) { BASE_NODE *base_obj = GetStateStructPtrFromObject(dev_data, *object); if (base_obj) base_obj->cb_bindings.erase(cb_node); } // Reset the command buffer state // Maintain the createInfo and set state to CB_NEW, but clear all other state static void ResetCommandBufferState(layer_data *dev_data, const VkCommandBuffer cb) { GLOBAL_CB_NODE *pCB = dev_data->commandBufferMap[cb]; if (pCB) { pCB->in_use.store(0); // Reset CB state (note that createInfo is not cleared) pCB->commandBuffer = cb; memset(&pCB->beginInfo, 0, sizeof(VkCommandBufferBeginInfo)); memset(&pCB->inheritanceInfo, 0, sizeof(VkCommandBufferInheritanceInfo)); pCB->hasDrawCmd = false; pCB->state = CB_NEW; pCB->submitCount = 0; pCB->image_layout_change_count = 1; // Start at 1. 0 is insert value for validation cache versions, s.t. new == dirty pCB->status = 0; pCB->static_status = 0; pCB->viewportMask = 0; pCB->scissorMask = 0; for (auto &item : pCB->lastBound) { item.second.reset(); } memset(&pCB->activeRenderPassBeginInfo, 0, sizeof(pCB->activeRenderPassBeginInfo)); pCB->activeRenderPass = nullptr; pCB->activeSubpassContents = VK_SUBPASS_CONTENTS_INLINE; pCB->activeSubpass = 0; pCB->broken_bindings.clear(); pCB->waitedEvents.clear(); pCB->events.clear(); pCB->writeEventsBeforeWait.clear(); pCB->waitedEventsBeforeQueryReset.clear(); pCB->queryToStateMap.clear(); pCB->activeQueries.clear(); pCB->startedQueries.clear(); pCB->imageLayoutMap.clear(); pCB->eventToStageMap.clear(); pCB->draw_data.clear(); pCB->current_draw_data.vertex_buffer_bindings.clear(); pCB->vertex_buffer_used = false; pCB->primaryCommandBuffer = VK_NULL_HANDLE; // If secondary, invalidate any primary command buffer that may call us. if (pCB->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) { InvalidateCommandBuffers(dev_data, pCB->linkedCommandBuffers, {HandleToUint64(cb), kVulkanObjectTypeCommandBuffer}); } // Remove reverse command buffer links. for (auto pSubCB : pCB->linkedCommandBuffers) { pSubCB->linkedCommandBuffers.erase(pCB); } pCB->linkedCommandBuffers.clear(); pCB->updateImages.clear(); pCB->updateBuffers.clear(); ClearCmdBufAndMemReferences(dev_data, pCB); pCB->queue_submit_functions.clear(); pCB->cmd_execute_commands_functions.clear(); pCB->eventUpdates.clear(); pCB->queryUpdates.clear(); // Remove object bindings for (auto obj : pCB->object_bindings) { RemoveCommandBufferBinding(dev_data, &obj, pCB); } pCB->object_bindings.clear(); // Remove this cmdBuffer's reference from each FrameBuffer's CB ref list for (auto framebuffer : pCB->framebuffers) { auto fb_state = GetFramebufferState(dev_data, framebuffer); if (fb_state) fb_state->cb_bindings.erase(pCB); } pCB->framebuffers.clear(); pCB->activeFramebuffer = VK_NULL_HANDLE; memset(&pCB->index_buffer_binding, 0, sizeof(pCB->index_buffer_binding)); pCB->qfo_transfer_image_barriers.Reset(); pCB->qfo_transfer_buffer_barriers.Reset(); } } CBStatusFlags MakeStaticStateMask(VkPipelineDynamicStateCreateInfo const *ds) { // initially assume everything is static state CBStatusFlags flags = CBSTATUS_ALL_STATE_SET; if (ds) { for (uint32_t i = 0; i < ds->dynamicStateCount; i++) { switch (ds->pDynamicStates[i]) { case VK_DYNAMIC_STATE_LINE_WIDTH: flags &= ~CBSTATUS_LINE_WIDTH_SET; break; case VK_DYNAMIC_STATE_DEPTH_BIAS: flags &= ~CBSTATUS_DEPTH_BIAS_SET; break; case VK_DYNAMIC_STATE_BLEND_CONSTANTS: flags &= ~CBSTATUS_BLEND_CONSTANTS_SET; break; case VK_DYNAMIC_STATE_DEPTH_BOUNDS: flags &= ~CBSTATUS_DEPTH_BOUNDS_SET; break; case VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK: flags &= ~CBSTATUS_STENCIL_READ_MASK_SET; break; case VK_DYNAMIC_STATE_STENCIL_WRITE_MASK: flags &= ~CBSTATUS_STENCIL_WRITE_MASK_SET; break; case VK_DYNAMIC_STATE_STENCIL_REFERENCE: flags &= ~CBSTATUS_STENCIL_REFERENCE_SET; break; case VK_DYNAMIC_STATE_SCISSOR: flags &= ~CBSTATUS_SCISSOR_SET; break; case VK_DYNAMIC_STATE_VIEWPORT: flags &= ~CBSTATUS_VIEWPORT_SET; break; case VK_DYNAMIC_STATE_EXCLUSIVE_SCISSOR_NV: flags &= ~CBSTATUS_EXCLUSIVE_SCISSOR_SET; break; case VK_DYNAMIC_STATE_VIEWPORT_SHADING_RATE_PALETTE_NV: flags &= ~CBSTATUS_SHADING_RATE_PALETTE_SET; break; default: break; } } } return flags; } // 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 InsideRenderPass(const layer_data *dev_data, const GLOBAL_CB_NODE *pCB, const char *apiName, const std::string &msgCode) { bool inside = false; if (pCB->activeRenderPass) { inside = log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(pCB->commandBuffer), msgCode, "%s: It is invalid to issue this call inside an active render pass (0x%" PRIx64 ").", apiName, HandleToUint64(pCB->activeRenderPass->renderPass)); } 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 OutsideRenderPass(const layer_data *dev_data, GLOBAL_CB_NODE *pCB, const char *apiName, const std::string &msgCode) { 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 = log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(pCB->commandBuffer), msgCode, "%s: This call must be issued inside an active render pass.", apiName); } return outside; } static void InitGpuValidation(instance_layer_data *instance_data) { // Process the layer settings file. enum CoreValidationGpuFlagBits { CORE_VALIDATION_GPU_VALIDATION_ALL_BIT = 0x00000001, CORE_VALIDATION_GPU_VALIDATION_RESERVE_BINDING_SLOT_BIT = 0x00000002, }; typedef VkFlags CoreGPUFlags; static const std::unordered_map<std::string, VkFlags> gpu_flags_option_definitions = { {std::string("all"), CORE_VALIDATION_GPU_VALIDATION_ALL_BIT}, {std::string("reserve_binding_slot"), CORE_VALIDATION_GPU_VALIDATION_RESERVE_BINDING_SLOT_BIT}, }; std::string gpu_flags_key = "lunarg_core_validation.gpu_validation"; CoreGPUFlags gpu_flags = GetLayerOptionFlags(gpu_flags_key, gpu_flags_option_definitions, 0); if (gpu_flags & CORE_VALIDATION_GPU_VALIDATION_ALL_BIT) { instance_data->enabled.gpu_validation = true; } if (gpu_flags & CORE_VALIDATION_GPU_VALIDATION_RESERVE_BINDING_SLOT_BIT) { instance_data->enabled.gpu_validation_reserve_binding_slot = true; } } // For the given ValidationCheck enum, set all relevant instance disabled flags to true void SetDisabledFlags(instance_layer_data *instance_data, const VkValidationFlagsEXT *val_flags_struct) { for (uint32_t i = 0; i < val_flags_struct->disabledValidationCheckCount; ++i) { switch (val_flags_struct->pDisabledValidationChecks[i]) { case VK_VALIDATION_CHECK_SHADERS_EXT: instance_data->disabled.shader_validation = true; break; case VK_VALIDATION_CHECK_ALL_EXT: // Set all disabled flags to true instance_data->disabled.SetAll(true); break; default: break; } } } void SetValidationFeatures(instance_layer_data *instance_data, const VkValidationFeaturesEXT *val_features_struct) { for (uint32_t i = 0; i < val_features_struct->disabledValidationFeatureCount; ++i) { switch (val_features_struct->pDisabledValidationFeatures[i]) { case VK_VALIDATION_FEATURE_DISABLE_SHADERS_EXT: instance_data->disabled.shader_validation = true; break; case VK_VALIDATION_FEATURE_DISABLE_ALL_EXT: // Set all disabled flags to true instance_data->disabled.SetAll(true); break; default: break; } } for (uint32_t i = 0; i < val_features_struct->enabledValidationFeatureCount; ++i) { switch (val_features_struct->pEnabledValidationFeatures[i]) { case VK_VALIDATION_FEATURE_ENABLE_GPU_ASSISTED_EXT: instance_data->enabled.gpu_validation = true; break; case VK_VALIDATION_FEATURE_ENABLE_GPU_ASSISTED_RESERVE_BINDING_SLOT_EXT: instance_data->enabled.gpu_validation_reserve_binding_slot = true; break; default: break; } } } void PostCallRecordCreateInstance(const VkInstanceCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkInstance *pInstance, VkResult result) { instance_layer_data *instance_data = GetLayerDataPtr(get_dispatch_key(*pInstance), instance_layer_data_map); if (VK_SUCCESS != result) return; // Parse any pNext chains const auto *validation_flags_ext = lvl_find_in_chain<VkValidationFlagsEXT>(pCreateInfo->pNext); if (validation_flags_ext) { SetDisabledFlags(instance_data, validation_flags_ext); } const auto *validation_features_ext = lvl_find_in_chain<VkValidationFeaturesEXT>(pCreateInfo->pNext); if (validation_features_ext) { SetValidationFeatures(instance_data, validation_features_ext); } InitGpuValidation(instance_data); } static bool ValidatePhysicalDeviceQueueFamily(instance_layer_data *instance_data, const PHYSICAL_DEVICE_STATE *pd_state, uint32_t requested_queue_family, std::string err_code, const char *cmd_name, const char *queue_family_var_name) { bool skip = false; const char *conditional_ext_cmd = instance_data->extensions.vk_khr_get_physical_device_properties_2 ? " or vkGetPhysicalDeviceQueueFamilyProperties2[KHR]" : ""; std::string count_note = (UNCALLED == pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState) ? "the pQueueFamilyPropertyCount was never obtained" : "i.e. is not less than " + std::to_string(pd_state->queue_family_count); if (requested_queue_family >= pd_state->queue_family_count) { skip |= log_msg(instance_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT, HandleToUint64(pd_state->phys_device), err_code, "%s: %s (= %" PRIu32 ") is not less than any previously obtained pQueueFamilyPropertyCount from " "vkGetPhysicalDeviceQueueFamilyProperties%s (%s).", cmd_name, queue_family_var_name, requested_queue_family, conditional_ext_cmd, count_note.c_str()); } return skip; } // Verify VkDeviceQueueCreateInfos static bool ValidateDeviceQueueCreateInfos(instance_layer_data *instance_data, const PHYSICAL_DEVICE_STATE *pd_state, uint32_t info_count, const VkDeviceQueueCreateInfo *infos) { bool skip = false; for (uint32_t i = 0; i < info_count; ++i) { const auto requested_queue_family = infos[i].queueFamilyIndex; // Verify that requested queue family is known to be valid at this point in time std::string queue_family_var_name = "pCreateInfo->pQueueCreateInfos[" + std::to_string(i) + "].queueFamilyIndex"; skip |= ValidatePhysicalDeviceQueueFamily(instance_data, pd_state, requested_queue_family, "VUID-VkDeviceQueueCreateInfo-queueFamilyIndex-00381", "vkCreateDevice", queue_family_var_name.c_str()); // 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_count) { const auto requested_queue_count = infos[i].queueCount; const auto queue_family_props_count = pd_state->queue_family_properties.size(); const bool queue_family_has_props = requested_queue_family < queue_family_props_count; const char *conditional_ext_cmd = instance_data->extensions.vk_khr_get_physical_device_properties_2 ? " or vkGetPhysicalDeviceQueueFamilyProperties2[KHR]" : ""; std::string count_note = !queue_family_has_props ? "the pQueueFamilyProperties[" + std::to_string(requested_queue_family) + "] was never obtained" : "i.e. is not less than or equal to " + std::to_string(pd_state->queue_family_properties[requested_queue_family].queueCount); if (!queue_family_has_props || requested_queue_count > pd_state->queue_family_properties[requested_queue_family].queueCount) { skip |= log_msg( instance_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT, HandleToUint64(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 PreCallValidateCreateDevice(VkPhysicalDevice gpu, const VkDeviceCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkDevice *pDevice) { instance_layer_data *instance_data = GetLayerDataPtr(get_dispatch_key(gpu), instance_layer_data_map); bool skip = false; auto pd_state = GetPhysicalDeviceState(instance_data, 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 (!GetPhysicalDeviceState(instance_data, gpu)) { skip |= log_msg(instance_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT, 0, kVUID_Core_DevLimit_MustQueryCount, "Invalid call to vkCreateDevice() w/o first calling vkEnumeratePhysicalDevices()."); } skip |= ValidateDeviceQueueCreateInfos(instance_data, pd_state, pCreateInfo->queueCreateInfoCount, pCreateInfo->pQueueCreateInfos); return skip; } void PostCallRecordCreateDevice(VkPhysicalDevice gpu, const VkDeviceCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkDevice *pDevice, VkResult result) { instance_layer_data *instance_data = GetLayerDataPtr(get_dispatch_key(gpu), instance_layer_data_map); if (VK_SUCCESS != result) return; const VkPhysicalDeviceFeatures *enabled_features_found = pCreateInfo->pEnabledFeatures; if (nullptr == enabled_features_found) { const auto *features2 = lvl_find_in_chain<VkPhysicalDeviceFeatures2KHR>(pCreateInfo->pNext); if (features2) { enabled_features_found = &(features2->features); } } layer_data *device_data = GetLayerDataPtr(get_dispatch_key(*pDevice), layer_data_map); device_data->enabled_features.core = *enabled_features_found; uint32_t count; instance_data->dispatch_table.GetPhysicalDeviceQueueFamilyProperties(gpu, &count, nullptr); device_data->phys_dev_properties.queue_family_properties.resize(count); instance_data->dispatch_table.GetPhysicalDeviceQueueFamilyProperties( gpu, &count, &device_data->phys_dev_properties.queue_family_properties[0]); const auto *device_group_ci = lvl_find_in_chain<VkDeviceGroupDeviceCreateInfo>(pCreateInfo->pNext); device_data->physical_device_count = device_group_ci && device_group_ci->physicalDeviceCount > 0 ? device_group_ci->physicalDeviceCount : 1; const auto *descriptor_indexing_features = lvl_find_in_chain<VkPhysicalDeviceDescriptorIndexingFeaturesEXT>(pCreateInfo->pNext); if (descriptor_indexing_features) { device_data->enabled_features.descriptor_indexing = *descriptor_indexing_features; } const auto *eight_bit_storage_features = lvl_find_in_chain<VkPhysicalDevice8BitStorageFeaturesKHR>(pCreateInfo->pNext); if (eight_bit_storage_features) { device_data->enabled_features.eight_bit_storage = *eight_bit_storage_features; } const auto *exclusive_scissor_features = lvl_find_in_chain<VkPhysicalDeviceExclusiveScissorFeaturesNV>(pCreateInfo->pNext); if (exclusive_scissor_features) { device_data->enabled_features.exclusive_scissor = *exclusive_scissor_features; } const auto *shading_rate_image_features = lvl_find_in_chain<VkPhysicalDeviceShadingRateImageFeaturesNV>(pCreateInfo->pNext); if (shading_rate_image_features) { device_data->enabled_features.shading_rate_image = *shading_rate_image_features; } const auto *mesh_shader_features = lvl_find_in_chain<VkPhysicalDeviceMeshShaderFeaturesNV>(pCreateInfo->pNext); if (mesh_shader_features) { device_data->enabled_features.mesh_shader = *mesh_shader_features; } const auto *inline_uniform_block_features = lvl_find_in_chain<VkPhysicalDeviceInlineUniformBlockFeaturesEXT>(pCreateInfo->pNext); if (inline_uniform_block_features) { device_data->enabled_features.inline_uniform_block = *inline_uniform_block_features; } const auto *transform_feedback_features = lvl_find_in_chain<VkPhysicalDeviceTransformFeedbackFeaturesEXT>(pCreateInfo->pNext); if (transform_feedback_features) { device_data->enabled_features.transform_feedback_features = *transform_feedback_features; } const auto *float16_int8_features = lvl_find_in_chain<VkPhysicalDeviceFloat16Int8FeaturesKHR>(pCreateInfo->pNext); if (float16_int8_features) { device_data->enabled_features.float16_int8 = *float16_int8_features; } const auto *vtx_attrib_div_features = lvl_find_in_chain<VkPhysicalDeviceVertexAttributeDivisorFeaturesEXT>(pCreateInfo->pNext); if (vtx_attrib_div_features) { device_data->enabled_features.vtx_attrib_divisor_features = *vtx_attrib_div_features; } const auto *scalar_block_layout_features = lvl_find_in_chain<VkPhysicalDeviceScalarBlockLayoutFeaturesEXT>(pCreateInfo->pNext); if (scalar_block_layout_features) { device_data->enabled_features.scalar_block_layout_features = *scalar_block_layout_features; } const auto *buffer_address = lvl_find_in_chain<VkPhysicalDeviceBufferAddressFeaturesEXT>(pCreateInfo->pNext); if (buffer_address) { device_data->enabled_features.buffer_address = *buffer_address; } // Store physical device properties and physical device mem limits into device layer_data structs instance_data->dispatch_table.GetPhysicalDeviceMemoryProperties(gpu, &device_data->phys_dev_mem_props); instance_data->dispatch_table.GetPhysicalDeviceProperties(gpu, &device_data->phys_dev_props); if (device_data->extensions.vk_khr_push_descriptor) { // Get the needed push_descriptor limits auto push_descriptor_prop = lvl_init_struct<VkPhysicalDevicePushDescriptorPropertiesKHR>(); auto prop2 = lvl_init_struct<VkPhysicalDeviceProperties2KHR>(&push_descriptor_prop); instance_data->dispatch_table.GetPhysicalDeviceProperties2KHR(gpu, &prop2); device_data->phys_dev_ext_props.max_push_descriptors = push_descriptor_prop.maxPushDescriptors; } if (device_data->extensions.vk_ext_descriptor_indexing) { // Get the needed descriptor_indexing limits auto descriptor_indexing_props = lvl_init_struct<VkPhysicalDeviceDescriptorIndexingPropertiesEXT>(); auto prop2 = lvl_init_struct<VkPhysicalDeviceProperties2KHR>(&descriptor_indexing_props); instance_data->dispatch_table.GetPhysicalDeviceProperties2KHR(gpu, &prop2); device_data->phys_dev_ext_props.descriptor_indexing_props = descriptor_indexing_props; } if (device_data->extensions.vk_nv_shading_rate_image) { // Get the needed shading rate image limits auto shading_rate_image_props = lvl_init_struct<VkPhysicalDeviceShadingRateImagePropertiesNV>(); auto prop2 = lvl_init_struct<VkPhysicalDeviceProperties2KHR>(&shading_rate_image_props); instance_data->dispatch_table.GetPhysicalDeviceProperties2KHR(gpu, &prop2); device_data->phys_dev_ext_props.shading_rate_image_props = shading_rate_image_props; } if (device_data->extensions.vk_nv_mesh_shader) { // Get the needed mesh shader limits auto mesh_shader_props = lvl_init_struct<VkPhysicalDeviceMeshShaderPropertiesNV>(); auto prop2 = lvl_init_struct<VkPhysicalDeviceProperties2KHR>(&mesh_shader_props); instance_data->dispatch_table.GetPhysicalDeviceProperties2KHR(gpu, &prop2); device_data->phys_dev_ext_props.mesh_shader_props = mesh_shader_props; } if (device_data->extensions.vk_ext_inline_uniform_block) { // Get the needed inline uniform block limits auto inline_uniform_block_props = lvl_init_struct<VkPhysicalDeviceInlineUniformBlockPropertiesEXT>(); auto prop2 = lvl_init_struct<VkPhysicalDeviceProperties2KHR>(&inline_uniform_block_props); instance_data->dispatch_table.GetPhysicalDeviceProperties2KHR(gpu, &prop2); device_data->phys_dev_ext_props.inline_uniform_block_props = inline_uniform_block_props; } if (device_data->extensions.vk_ext_vertex_attribute_divisor) { // Get the needed vertex attribute divisor limits auto vtx_attrib_divisor_props = lvl_init_struct<VkPhysicalDeviceVertexAttributeDivisorPropertiesEXT>(); auto prop2 = lvl_init_struct<VkPhysicalDeviceProperties2KHR>(&vtx_attrib_divisor_props); instance_data->dispatch_table.GetPhysicalDeviceProperties2KHR(gpu, &prop2); device_data->phys_dev_ext_props.vtx_attrib_divisor_props = vtx_attrib_divisor_props; } if (device_data->extensions.vk_khr_depth_stencil_resolve) { // Get the needed depth and stencil resolve modes auto depth_stencil_resolve_props = lvl_init_struct<VkPhysicalDeviceDepthStencilResolvePropertiesKHR>(); auto prop2 = lvl_init_struct<VkPhysicalDeviceProperties2KHR>(&depth_stencil_resolve_props); instance_data->dispatch_table.GetPhysicalDeviceProperties2KHR(gpu, &prop2); device_data->phys_dev_ext_props.depth_stencil_resolve_props = depth_stencil_resolve_props; } if (GetEnables(device_data)->gpu_validation) { // Copy any needed instance data into the gpu validation state device_data->gpu_validation_state.reserve_binding_slot = device_data->instance_data->enabled.gpu_validation_reserve_binding_slot; GpuPostCallRecordCreateDevice(device_data); } } void PreCallRecordDestroyDevice(VkDevice device, const VkAllocationCallbacks *pAllocator) { if (!device) return; layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); if (GetEnables(device_data)->gpu_validation) { GpuPreCallRecordDestroyDevice(device_data); } device_data->pipelineMap.clear(); device_data->renderPassMap.clear(); for (auto ii = device_data->commandBufferMap.begin(); ii != device_data->commandBufferMap.end(); ++ii) { delete (*ii).second; } device_data->commandBufferMap.clear(); // This will also delete all sets in the pool & remove them from setMap DeletePools(device_data); // All sets should be removed assert(device_data->setMap.empty()); device_data->descriptorSetLayoutMap.clear(); device_data->imageViewMap.clear(); device_data->imageMap.clear(); device_data->imageSubresourceMap.clear(); device_data->imageLayoutMap.clear(); device_data->bufferViewMap.clear(); device_data->bufferMap.clear(); // Queues persist until device is destroyed device_data->queueMap.clear(); layer_debug_utils_destroy_device(device); } // For given stage mask, if Geometry shader stage is on w/o GS being enabled, report geo_error_id // and if Tessellation Control or Evaluation shader stages are on w/o TS being enabled, report tess_error_id. // Similarly for mesh and task shaders. static bool ValidateStageMaskGsTsEnables(const layer_data *dev_data, VkPipelineStageFlags stageMask, const char *caller, std::string geo_error_id, std::string tess_error_id, std::string mesh_error_id, std::string task_error_id) { bool skip = false; if (!dev_data->enabled_features.core.geometryShader && (stageMask & VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT)) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, geo_error_id, "%s call includes a stageMask with VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT bit set when device does not have " "geometryShader feature enabled.", caller); } if (!dev_data->enabled_features.core.tessellationShader && (stageMask & (VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT | VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT))) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, tess_error_id, "%s call includes a stageMask with VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT and/or " "VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT bit(s) set when device does not have " "tessellationShader feature enabled.", caller); } if (!dev_data->enabled_features.mesh_shader.meshShader && (stageMask & VK_PIPELINE_STAGE_MESH_SHADER_BIT_NV)) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, mesh_error_id, "%s call includes a stageMask with VK_PIPELINE_STAGE_MESH_SHADER_BIT_NV bit set when device does not have " "VkPhysicalDeviceMeshShaderFeaturesNV::meshShader feature enabled.", caller); } if (!dev_data->enabled_features.mesh_shader.taskShader && (stageMask & VK_PIPELINE_STAGE_TASK_SHADER_BIT_NV)) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, task_error_id, "%s call includes a stageMask with VK_PIPELINE_STAGE_TASK_SHADER_BIT_NV bit set when device does not have " "VkPhysicalDeviceMeshShaderFeaturesNV::taskShader feature enabled.", caller); } return skip; } // Loop through bound objects and increment their in_use counts. static void IncrementBoundObjects(layer_data *dev_data, GLOBAL_CB_NODE const *cb_node) { for (auto obj : cb_node->object_bindings) { auto base_obj = GetStateStructPtrFromObject(dev_data, obj); if (base_obj) { base_obj->in_use.fetch_add(1); } } } // Track which resources are in-flight by atomically incrementing their "in_use" count static void IncrementResources(layer_data *dev_data, GLOBAL_CB_NODE *cb_node) { cb_node->submitCount++; cb_node->in_use.fetch_add(1); // First Increment for all "generic" objects bound to cmd buffer, followed by special-case objects below IncrementBoundObjects(dev_data, cb_node); // TODO : We should be able to remove the NULL look-up checks from the code below as long as // all the corresponding cases are verified to cause CB_INVALID state and the CB_INVALID state // should then be flagged prior to calling this function for (auto draw_data_element : cb_node->draw_data) { for (auto &vertex_buffer : draw_data_element.vertex_buffer_bindings) { auto buffer_state = GetBufferState(dev_data, vertex_buffer.buffer); if (buffer_state) { buffer_state->in_use.fetch_add(1); } } } for (auto event : cb_node->writeEventsBeforeWait) { auto event_state = GetEventNode(dev_data, event); if (event_state) event_state->write_in_use++; } } // 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. static bool VerifyQueueStateToSeq(layer_data *dev_data, QUEUE_STATE *initial_queue, uint64_t initial_seq) { bool skip = false; // sequence number we want to validate up to, per queue std::unordered_map<QUEUE_STATE *, uint64_t> target_seqs{{initial_queue, initial_seq}}; // sequence number we've completed validation for, per queue std::unordered_map<QUEUE_STATE *, uint64_t> done_seqs; std::vector<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(dev_data, 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 static bool VerifyQueueStateToFence(layer_data *dev_data, VkFence fence) { auto fence_state = GetFenceNode(dev_data, fence); if (fence_state && fence_state->scope == kSyncScopeInternal && VK_NULL_HANDLE != fence_state->signaler.first) { return VerifyQueueStateToSeq(dev_data, GetQueueState(dev_data, fence_state->signaler.first), fence_state->signaler.second); } return false; } // Decrement in-use count for objects bound to command buffer static void DecrementBoundResources(layer_data *dev_data, GLOBAL_CB_NODE const *cb_node) { BASE_NODE *base_obj = nullptr; for (auto obj : cb_node->object_bindings) { base_obj = GetStateStructPtrFromObject(dev_data, obj); if (base_obj) { base_obj->in_use.fetch_sub(1); } } } static void RetireWorkOnQueue(layer_data *dev_data, QUEUE_STATE *pQueue, uint64_t seq) { std::unordered_map<VkQueue, uint64_t> otherQueueSeqs; // Roll this queue forward, one submission at a time. while (pQueue->seq < seq) { auto &submission = pQueue->submissions.front(); for (auto &wait : submission.waitSemaphores) { auto pSemaphore = GetSemaphoreNode(dev_data, wait.semaphore); if (pSemaphore) { pSemaphore->in_use.fetch_sub(1); } auto &lastSeq = otherQueueSeqs[wait.queue]; lastSeq = std::max(lastSeq, wait.seq); } for (auto &semaphore : submission.signalSemaphores) { auto pSemaphore = GetSemaphoreNode(dev_data, semaphore); if (pSemaphore) { pSemaphore->in_use.fetch_sub(1); } } for (auto &semaphore : submission.externalSemaphores) { auto pSemaphore = GetSemaphoreNode(dev_data, semaphore); if (pSemaphore) { pSemaphore->in_use.fetch_sub(1); } } for (auto cb : submission.cbs) { auto cb_node = GetCBNode(dev_data, cb); if (!cb_node) { continue; } // First perform decrement on general case bound objects DecrementBoundResources(dev_data, cb_node); for (auto draw_data_element : cb_node->draw_data) { for (auto &vertex_buffer_binding : draw_data_element.vertex_buffer_bindings) { auto buffer_state = GetBufferState(dev_data, vertex_buffer_binding.buffer); if (buffer_state) { buffer_state->in_use.fetch_sub(1); } } } for (auto event : cb_node->writeEventsBeforeWait) { auto eventNode = dev_data->eventMap.find(event); if (eventNode != dev_data->eventMap.end()) { eventNode->second.write_in_use--; } } for (auto queryStatePair : cb_node->queryToStateMap) { dev_data->queryToStateMap[queryStatePair.first] = queryStatePair.second; } for (auto eventStagePair : cb_node->eventToStageMap) { dev_data->eventMap[eventStagePair.first].stageMask = eventStagePair.second; } cb_node->in_use.fetch_sub(1); } auto pFence = GetFenceNode(dev_data, submission.fence); if (pFence && pFence->scope == kSyncScopeInternal) { pFence->state = FENCE_RETIRED; } pQueue->submissions.pop_front(); pQueue->seq++; } // Roll other queues forward to the highest seq we saw a wait for for (auto qs : otherQueueSeqs) { RetireWorkOnQueue(dev_data, GetQueueState(dev_data, qs.first), qs.second); } } // Submit a fence to a queue, delimiting previous fences and previous untracked // work by it. static void SubmitFence(QUEUE_STATE *pQueue, FENCE_NODE *pFence, uint64_t submitCount) { pFence->state = FENCE_INFLIGHT; pFence->signaler.first = pQueue->queue; pFence->signaler.second = pQueue->seq + pQueue->submissions.size() + submitCount; } static bool ValidateCommandBufferSimultaneousUse(layer_data *dev_data, GLOBAL_CB_NODE *pCB, int current_submit_count) { bool skip = false; if ((pCB->in_use.load() || current_submit_count > 1) && !(pCB->beginInfo.flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT)) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, 0, "VUID-vkQueueSubmit-pCommandBuffers-00071", "Command Buffer 0x%" PRIx64 " is already in use and is not marked for simultaneous use.", HandleToUint64(pCB->commandBuffer)); } return skip; } static bool ValidateCommandBufferState(layer_data *dev_data, GLOBAL_CB_NODE *cb_state, const char *call_source, int current_submit_count, std::string vu_id) { bool skip = false; if (dev_data->instance_data->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 |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, 0, kVUID_Core_DrawState_CommandBufferSingleSubmitViolation, "Commandbuffer 0x%" PRIx64 " was begun w/ VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT set, but has been submitted 0x%" PRIxLEAST64 " times.", HandleToUint64(cb_state->commandBuffer), 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(dev_data, cb_state, call_source); break; case CB_NEW: skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, (uint64_t)(cb_state->commandBuffer), vu_id, "Command buffer 0x%" PRIx64 " used in the call to %s is unrecorded and contains no commands.", HandleToUint64(cb_state->commandBuffer), call_source); break; case CB_RECORDING: skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(cb_state->commandBuffer), kVUID_Core_DrawState_NoEndCommandBuffer, "You must call vkEndCommandBuffer() on command buffer 0x%" PRIx64 " before this call to %s!", HandleToUint64(cb_state->commandBuffer), call_source); break; default: /* recorded */ break; } return skip; } static bool ValidateResources(layer_data *dev_data, GLOBAL_CB_NODE *cb_node) { bool skip = false; // TODO : We should be able to remove the NULL look-up checks from the code below as long as // all the corresponding cases are verified to cause CB_INVALID state and the CB_INVALID state // should then be flagged prior to calling this function for (const auto &draw_data_element : cb_node->draw_data) { for (const auto &vertex_buffer_binding : draw_data_element.vertex_buffer_bindings) { auto buffer_state = GetBufferState(dev_data, vertex_buffer_binding.buffer); if ((vertex_buffer_binding.buffer != VK_NULL_HANDLE) && (!buffer_state)) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT, HandleToUint64(vertex_buffer_binding.buffer), kVUID_Core_DrawState_InvalidBuffer, "Cannot submit cmd buffer using deleted buffer 0x%" PRIx64 ".", HandleToUint64(vertex_buffer_binding.buffer)); } } } return skip; } // Check that the queue family index of 'queue' matches one of the entries in pQueueFamilyIndices bool ValidImageBufferQueue(layer_data *dev_data, GLOBAL_CB_NODE *cb_node, const VK_OBJECT *object, VkQueue queue, uint32_t count, const uint32_t *indices) { bool found = false; bool skip = false; auto queue_state = GetQueueState(dev_data, queue); if (queue_state) { for (uint32_t i = 0; i < count; i++) { if (indices[i] == queue_state->queueFamilyIndex) { found = true; break; } } if (!found) { skip = log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, get_debug_report_enum[object->type], object->handle, kVUID_Core_DrawState_InvalidQueueFamily, "vkQueueSubmit: Command buffer 0x%" PRIx64 " contains %s 0x%" PRIx64 " which was not created allowing concurrent access to this queue family %d.", HandleToUint64(cb_node->commandBuffer), object_string[object->type], object->handle, queue_state->queueFamilyIndex); } } return skip; } // Validate that queueFamilyIndices of primary command buffers match this queue // Secondary command buffers were previously validated in vkCmdExecuteCommands(). static bool ValidateQueueFamilyIndices(layer_data *dev_data, GLOBAL_CB_NODE *pCB, VkQueue queue) { bool skip = false; auto pPool = GetCommandPoolNode(dev_data, pCB->createInfo.commandPool); auto queue_state = GetQueueState(dev_data, queue); if (pPool && queue_state) { if (pPool->queueFamilyIndex != queue_state->queueFamilyIndex) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(pCB->commandBuffer), "VUID-vkQueueSubmit-pCommandBuffers-00074", "vkQueueSubmit: Primary command buffer 0x%" PRIx64 " created in queue family %d is being submitted on queue 0x%" PRIx64 " from queue family %d.", HandleToUint64(pCB->commandBuffer), pPool->queueFamilyIndex, HandleToUint64(queue), queue_state->queueFamilyIndex); } // Ensure that any bound images or buffers created with SHARING_MODE_CONCURRENT have access to the current queue family for (auto object : pCB->object_bindings) { if (object.type == kVulkanObjectTypeImage) { auto image_state = GetImageState(dev_data, reinterpret_cast<VkImage &>(object.handle)); if (image_state && image_state->createInfo.sharingMode == VK_SHARING_MODE_CONCURRENT) { skip |= ValidImageBufferQueue(dev_data, pCB, &object, queue, image_state->createInfo.queueFamilyIndexCount, image_state->createInfo.pQueueFamilyIndices); } } else if (object.type == kVulkanObjectTypeBuffer) { auto buffer_state = GetBufferState(dev_data, reinterpret_cast<VkBuffer &>(object.handle)); if (buffer_state && buffer_state->createInfo.sharingMode == VK_SHARING_MODE_CONCURRENT) { skip |= ValidImageBufferQueue(dev_data, pCB, &object, queue, buffer_state->createInfo.queueFamilyIndexCount, buffer_state->createInfo.pQueueFamilyIndices); } } } } return skip; } static bool ValidatePrimaryCommandBufferState(layer_data *dev_data, GLOBAL_CB_NODE *pCB, int current_submit_count, QFOTransferCBScoreboards<VkImageMemoryBarrier> *qfo_image_scoreboards, QFOTransferCBScoreboards<VkBufferMemoryBarrier> *qfo_buffer_scoreboards) { // Track in-use for resources off of primary and any secondary CBs bool skip = false; // If USAGE_SIMULTANEOUS_USE_BIT not set then CB cannot already be executing // on device skip |= ValidateCommandBufferSimultaneousUse(dev_data, pCB, current_submit_count); skip |= ValidateResources(dev_data, pCB); skip |= ValidateQueuedQFOTransfers(dev_data, pCB, qfo_image_scoreboards, qfo_buffer_scoreboards); for (auto pSubCB : pCB->linkedCommandBuffers) { skip |= ValidateResources(dev_data, pSubCB); skip |= ValidateQueuedQFOTransfers(dev_data, pSubCB, qfo_image_scoreboards, qfo_buffer_scoreboards); // TODO: replace with InvalidateCommandBuffers() at recording. if ((pSubCB->primaryCommandBuffer != pCB->commandBuffer) && !(pSubCB->beginInfo.flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT)) { log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, 0, "VUID-vkQueueSubmit-pCommandBuffers-00073", "Commandbuffer 0x%" PRIx64 " was submitted with secondary buffer 0x%" PRIx64 " but that buffer has subsequently been bound to primary cmd buffer 0x%" PRIx64 " and it does not have VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT set.", HandleToUint64(pCB->commandBuffer), HandleToUint64(pSubCB->commandBuffer), HandleToUint64(pSubCB->primaryCommandBuffer)); } } skip |= ValidateCommandBufferState(dev_data, pCB, "vkQueueSubmit()", current_submit_count, "VUID-vkQueueSubmit-pCommandBuffers-00072"); return skip; } static bool ValidateFenceForSubmit(layer_data *dev_data, FENCE_NODE *pFence) { bool skip = false; if (pFence && pFence->scope == kSyncScopeInternal) { if (pFence->state == FENCE_INFLIGHT) { // TODO: opportunities for "VUID-vkQueueSubmit-fence-00064", "VUID-vkQueueBindSparse-fence-01114", // "VUID-vkAcquireNextImageKHR-fence-01287" skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_FENCE_EXT, HandleToUint64(pFence->fence), kVUID_Core_DrawState_InvalidFence, "Fence 0x%" PRIx64 " is already in use by another submission.", HandleToUint64(pFence->fence)); } else if (pFence->state == FENCE_RETIRED) { // TODO: opportunities for "VUID-vkQueueSubmit-fence-00063", "VUID-vkQueueBindSparse-fence-01113", // "VUID-vkAcquireNextImageKHR-fence-01287" skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_FENCE_EXT, HandleToUint64(pFence->fence), kVUID_Core_MemTrack_FenceState, "Fence 0x%" PRIx64 " submitted in SIGNALED state. Fences must be reset before being submitted", HandleToUint64(pFence->fence)); } } return skip; } void PostCallRecordQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo *pSubmits, VkFence fence, VkResult result) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(queue), layer_data_map); uint64_t early_retire_seq = 0; auto pQueue = GetQueueState(device_data, queue); auto pFence = GetFenceNode(device_data, fence); if (pFence) { if (pFence->scope == kSyncScopeInternal) { // Mark fence in use SubmitFence(pQueue, pFence, std::max(1u, submitCount)); if (!submitCount) { // If no submissions, but just dropping a fence on the end of the queue, // record an empty submission with just the fence, so we can determine // its completion. pQueue->submissions.emplace_back(std::vector<VkCommandBuffer>(), std::vector<SEMAPHORE_WAIT>(), std::vector<VkSemaphore>(), std::vector<VkSemaphore>(), fence); } } else { // Retire work up until this fence early, we will not see the wait that corresponds to this signal early_retire_seq = pQueue->seq + pQueue->submissions.size(); if (!device_data->external_sync_warning) { device_data->external_sync_warning = true; log_msg(device_data->report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_FENCE_EXT, HandleToUint64(fence), kVUID_Core_DrawState_QueueForwardProgress, "vkQueueSubmit(): Signaling external fence 0x%" PRIx64 " on queue 0x%" PRIx64 " will disable validation of preceding command buffer lifecycle states and the in-use status of associated " "objects.", HandleToUint64(fence), HandleToUint64(queue)); } } } // Now process each individual submit for (uint32_t submit_idx = 0; submit_idx < submitCount; submit_idx++) { std::vector<VkCommandBuffer> cbs; const VkSubmitInfo *submit = &pSubmits[submit_idx]; vector<SEMAPHORE_WAIT> semaphore_waits; vector<VkSemaphore> semaphore_signals; vector<VkSemaphore> semaphore_externals; for (uint32_t i = 0; i < submit->waitSemaphoreCount; ++i) { VkSemaphore semaphore = submit->pWaitSemaphores[i]; auto pSemaphore = GetSemaphoreNode(device_data, semaphore); if (pSemaphore) { if (pSemaphore->scope == kSyncScopeInternal) { if (pSemaphore->signaler.first != VK_NULL_HANDLE) { semaphore_waits.push_back({semaphore, pSemaphore->signaler.first, pSemaphore->signaler.second}); pSemaphore->in_use.fetch_add(1); } pSemaphore->signaler.first = VK_NULL_HANDLE; pSemaphore->signaled = false; } else { semaphore_externals.push_back(semaphore); pSemaphore->in_use.fetch_add(1); if (pSemaphore->scope == kSyncScopeExternalTemporary) { pSemaphore->scope = kSyncScopeInternal; } } } } for (uint32_t i = 0; i < submit->signalSemaphoreCount; ++i) { VkSemaphore semaphore = submit->pSignalSemaphores[i]; auto pSemaphore = GetSemaphoreNode(device_data, semaphore); if (pSemaphore) { if (pSemaphore->scope == kSyncScopeInternal) { pSemaphore->signaler.first = queue; pSemaphore->signaler.second = pQueue->seq + pQueue->submissions.size() + 1; pSemaphore->signaled = true; pSemaphore->in_use.fetch_add(1); semaphore_signals.push_back(semaphore); } else { // Retire work up until this submit early, we will not see the wait that corresponds to this signal early_retire_seq = std::max(early_retire_seq, pQueue->seq + pQueue->submissions.size() + 1); if (!device_data->external_sync_warning) { device_data->external_sync_warning = true; log_msg(device_data->report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SEMAPHORE_EXT, HandleToUint64(semaphore), kVUID_Core_DrawState_QueueForwardProgress, "vkQueueSubmit(): Signaling external semaphore 0x%" PRIx64 " on queue 0x%" PRIx64 " will disable validation of preceding command buffer lifecycle states and the in-use status of " "associated objects.", HandleToUint64(semaphore), HandleToUint64(queue)); } } } } for (uint32_t i = 0; i < submit->commandBufferCount; i++) { auto cb_node = GetCBNode(device_data, submit->pCommandBuffers[i]); if (cb_node) { cbs.push_back(submit->pCommandBuffers[i]); for (auto secondaryCmdBuffer : cb_node->linkedCommandBuffers) { cbs.push_back(secondaryCmdBuffer->commandBuffer); UpdateCmdBufImageLayouts(device_data, secondaryCmdBuffer); IncrementResources(device_data, secondaryCmdBuffer); RecordQueuedQFOTransfers(device_data, secondaryCmdBuffer); } UpdateCmdBufImageLayouts(device_data, cb_node); IncrementResources(device_data, cb_node); RecordQueuedQFOTransfers(device_data, cb_node); } } pQueue->submissions.emplace_back(cbs, semaphore_waits, semaphore_signals, semaphore_externals, submit_idx == submitCount - 1 ? fence : VK_NULL_HANDLE); } if (early_retire_seq) { RetireWorkOnQueue(device_data, pQueue, early_retire_seq); } if (GetEnables(device_data)->gpu_validation) { GpuPostCallQueueSubmit(device_data, queue, submitCount, pSubmits, fence); } } bool PreCallValidateQueueSubmit(VkQueue queue, uint32_t submitCount, const VkSubmitInfo *pSubmits, VkFence fence) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(queue), layer_data_map); auto pFence = GetFenceNode(device_data, fence); bool skip = ValidateFenceForSubmit(device_data, pFence); if (skip) { return true; } unordered_set<VkSemaphore> signaled_semaphores; unordered_set<VkSemaphore> unsignaled_semaphores; unordered_set<VkSemaphore> internal_semaphores; vector<VkCommandBuffer> current_cmds; unordered_map<ImageSubresourcePair, IMAGE_LAYOUT_NODE> localImageLayoutMap; // Now verify each individual submit for (uint32_t submit_idx = 0; submit_idx < submitCount; submit_idx++) { const VkSubmitInfo *submit = &pSubmits[submit_idx]; for (uint32_t i = 0; i < submit->waitSemaphoreCount; ++i) { skip |= ValidateStageMaskGsTsEnables( device_data, submit->pWaitDstStageMask[i], "vkQueueSubmit()", "VUID-VkSubmitInfo-pWaitDstStageMask-00076", "VUID-VkSubmitInfo-pWaitDstStageMask-00077", "VUID-VkSubmitInfo-pWaitDstStageMask-02089", "VUID-VkSubmitInfo-pWaitDstStageMask-02090"); VkSemaphore semaphore = submit->pWaitSemaphores[i]; auto pSemaphore = GetSemaphoreNode(device_data, semaphore); if (pSemaphore && (pSemaphore->scope == kSyncScopeInternal || internal_semaphores.count(semaphore))) { if (unsignaled_semaphores.count(semaphore) || (!(signaled_semaphores.count(semaphore)) && !(pSemaphore->signaled))) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SEMAPHORE_EXT, HandleToUint64(semaphore), kVUID_Core_DrawState_QueueForwardProgress, "Queue 0x%" PRIx64 " is waiting on semaphore 0x%" PRIx64 " that has no way to be signaled.", HandleToUint64(queue), HandleToUint64(semaphore)); } else { signaled_semaphores.erase(semaphore); unsignaled_semaphores.insert(semaphore); } } if (pSemaphore && pSemaphore->scope == kSyncScopeExternalTemporary) { internal_semaphores.insert(semaphore); } } for (uint32_t i = 0; i < submit->signalSemaphoreCount; ++i) { VkSemaphore semaphore = submit->pSignalSemaphores[i]; auto pSemaphore = GetSemaphoreNode(device_data, semaphore); if (pSemaphore && (pSemaphore->scope == kSyncScopeInternal || internal_semaphores.count(semaphore))) { if (signaled_semaphores.count(semaphore) || (!(unsignaled_semaphores.count(semaphore)) && pSemaphore->signaled)) { skip |= log_msg( device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SEMAPHORE_EXT, HandleToUint64(semaphore), kVUID_Core_DrawState_QueueForwardProgress, "Queue 0x%" PRIx64 " is signaling semaphore 0x%" PRIx64 " that was previously signaled by queue 0x%" PRIx64 " but has not since been waited on by any queue.", HandleToUint64(queue), HandleToUint64(semaphore), HandleToUint64(pSemaphore->signaler.first)); } else { unsignaled_semaphores.erase(semaphore); signaled_semaphores.insert(semaphore); } } } QFOTransferCBScoreboards<VkImageMemoryBarrier> qfo_image_scoreboards; QFOTransferCBScoreboards<VkBufferMemoryBarrier> qfo_buffer_scoreboards; for (uint32_t i = 0; i < submit->commandBufferCount; i++) { auto cb_node = GetCBNode(device_data, submit->pCommandBuffers[i]); if (cb_node) { skip |= ValidateCmdBufImageLayouts(device_data, cb_node, device_data->imageLayoutMap, localImageLayoutMap); current_cmds.push_back(submit->pCommandBuffers[i]); skip |= ValidatePrimaryCommandBufferState( device_data, cb_node, (int)std::count(current_cmds.begin(), current_cmds.end(), submit->pCommandBuffers[i]), &qfo_image_scoreboards, &qfo_buffer_scoreboards); skip |= ValidateQueueFamilyIndices(device_data, cb_node, queue); // Potential early exit here as bad object state may crash in delayed function calls if (skip) { return true; } // Call submit-time functions to validate/update state for (auto &function : cb_node->queue_submit_functions) { skip |= function(); } for (auto &function : cb_node->eventUpdates) { skip |= function(queue); } for (auto &function : cb_node->queryUpdates) { skip |= function(queue); } } } } return skip; } #ifdef VK_USE_PLATFORM_ANDROID_KHR // Android-specific validation that uses types defined only with VK_USE_PLATFORM_ANDROID_KHR // 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_COLOR_OUTPUT VK_IMAGE_USAGE_COLOR_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_COLOR_OUTPUT, VK_IMAGE_USAGE_COLOR_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_COLOR_OUTPUT }, }; 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 PreCallValidateGetAndroidHardwareBufferProperties(const layer_data *dev_data, const AHardwareBuffer *ahb) { 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(ahb, &ahb_desc); uint32_t required_flags = AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE | AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT | AHARDWAREBUFFER_USAGE_GPU_CUBE_MAP | AHARDWAREBUFFER_USAGE_GPU_MIPMAP_COMPLETE | AHARDWAREBUFFER_USAGE_GPU_DATA_BUFFER; if (0 == (ahb_desc.usage & required_flags)) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(dev_data->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; } void PostCallRecordGetAndroidHardwareBufferProperties(layer_data *dev_data, const VkAndroidHardwareBufferPropertiesANDROID *ahb_props) { auto ahb_format_props = lvl_find_in_chain<VkAndroidHardwareBufferFormatPropertiesANDROID>(ahb_props->pNext); if (ahb_format_props) { auto ext_formats = GetAHBExternalFormatsSet(dev_data); ext_formats->insert(ahb_format_props->externalFormat); } } bool PreCallValidateGetMemoryAndroidHardwareBuffer(const layer_data *dev_data, const VkMemoryGetAndroidHardwareBufferInfoANDROID *pInfo) { bool skip = false; unique_lock_t lock(global_lock); DEVICE_MEM_INFO *mem_info = GetMemObjInfo(dev_data, pInfo->memory); // VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID must have been included in // VkExportMemoryAllocateInfoKHR::handleTypes when memory was created. if (!mem_info->is_export || (0 == (mem_info->export_handle_type_flags & VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID))) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(dev_data->device), "VUID-VkMemoryGetAndroidHardwareBufferInfoANDROID-handleTypes-01882", "vkGetMemoryAndroidHardwareBufferANDROID: The VkDeviceMemory (0x%" PRIx64 ") was not allocated for export, or the export handleTypes (0x%" PRIx32 ") did not contain VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID.", HandleToUint64(pInfo->memory), 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->is_dedicated && (VK_NULL_HANDLE != mem_info->dedicated_image)) { auto image_state = GetImageState(dev_data, mem_info->dedicated_image); if ((nullptr == image_state) || (0 == (image_state->GetBoundMemory().count(pInfo->memory)))) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(dev_data->device), "VUID-VkMemoryGetAndroidHardwareBufferInfoANDROID-pNext-01883", "vkGetMemoryAndroidHardwareBufferANDROID: The VkDeviceMemory (0x%" PRIx64 ") was allocated using a dedicated image (0x%" PRIx64 "), but that image is not bound to the VkDeviceMemory object.", HandleToUint64(pInfo->memory), HandleToUint64(mem_info->dedicated_image)); } } return skip; } // // AHB-specific validation within non-AHB APIs // static bool ValidateAllocateMemoryANDROID(layer_data *dev_data, const VkMemoryAllocateInfo *alloc_info) { bool skip = false; auto import_ahb_info = lvl_find_in_chain<VkImportAndroidHardwareBufferInfoANDROID>(alloc_info->pNext); auto exp_mem_alloc_info = lvl_find_in_chain<VkExportMemoryAllocateInfo>(alloc_info->pNext); auto mem_ded_alloc_info = lvl_find_in_chain<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); // If buffer is not NULL, it must be a valid Android hardware buffer object with AHardwareBuffer_Desc::format and // AHardwareBuffer_Desc::usage compatible with Vulkan as described in Android Hardware Buffers. // // 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, and none that are not in the table uint64_t ahb_equiv_usage_bits = AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE | AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT | AHARDWAREBUFFER_USAGE_GPU_CUBE_MAP | AHARDWAREBUFFER_USAGE_GPU_MIPMAP_COMPLETE | AHARDWAREBUFFER_USAGE_PROTECTED_CONTENT; if ((0 == (ahb_desc.usage & ahb_equiv_usage_bits)) || (0 != (ahb_desc.usage & ~ahb_equiv_usage_bits)) || (0 == ahb_format_map_a2v.count(ahb_desc.format))) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(dev_data->device), "VUID-VkImportAndroidHardwareBufferInfoANDROID-buffer-01881", "vkAllocateMemory: The AHardwareBuffer_Desc's format ( %u ) and/or usage ( 0x%" PRIx64 " ) are not compatible with Vulkan.", ahb_desc.format, ahb_desc.usage); } } // Collect external buffer info VkPhysicalDeviceExternalBufferInfo pdebi = {}; pdebi.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_BUFFER_INFO; 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_COLOR_OUTPUT & ahb_desc.usage) { pdebi.usage |= ahb_usage_map_a2v[AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT]; } VkExternalBufferProperties ext_buf_props = {}; ext_buf_props.sType = VK_STRUCTURE_TYPE_EXTERNAL_BUFFER_PROPERTIES; instance_layer_data *instance_data = GetLayerDataPtr(get_dispatch_key(dev_data->instance_data->instance), instance_layer_data_map); instance_data->dispatch_table.GetPhysicalDeviceExternalBufferProperties(dev_data->physical_device, &pdebi, &ext_buf_props); // Collect external format info VkPhysicalDeviceExternalImageFormatInfo pdeifi = {}; pdeifi.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO; pdeifi.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID; VkPhysicalDeviceImageFormatInfo2 pdifi2 = {}; pdifi2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2; pdifi2.pNext = &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_COLOR_OUTPUT & ahb_desc.usage) { pdifi2.usage |= ahb_usage_map_a2v[AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT]; } 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]; } VkExternalImageFormatProperties ext_img_fmt_props = {}; ext_img_fmt_props.sType = VK_STRUCTURE_TYPE_EXTERNAL_IMAGE_FORMAT_PROPERTIES; VkImageFormatProperties2 ifp2 = {}; ifp2.sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2; ifp2.pNext = &ext_img_fmt_props; VkResult fmt_lookup_result = GetPDImageFormatProperties2(dev_data, &pdifi2, &ifp2); // 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)) { if ((VK_SUCCESS != fmt_lookup_result) || (0 == (ext_img_fmt_props.externalMemoryProperties.externalMemoryFeatures & VK_EXTERNAL_MEMORY_FEATURE_IMPORTABLE_BIT))) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(dev_data->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 VkAndroidHardwareBufferFormatPropertiesANDROID ahb_format_props = {}; ahb_format_props.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_FORMAT_PROPERTIES_ANDROID; VkAndroidHardwareBufferPropertiesANDROID ahb_props = {}; ahb_props.sType = VK_STRUCTURE_TYPE_ANDROID_HARDWARE_BUFFER_PROPERTIES_ANDROID; ahb_props.pNext = &ahb_format_props; dev_data->dispatch_table.GetAndroidHardwareBufferPropertiesANDROID(dev_data->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 |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(dev_data->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 |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(dev_data->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_format_props.externalFormat) || (0 == (ahb_desc.usage & AHARDWAREBUFFER_USAGE_GPU_DATA_BUFFER))) { skip |= log_msg( dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(dev_data->device), "VUID-VkMemoryAllocateInfo-pNext-02384", "vkAllocateMemory: VkMemoryAllocateInfo struct with chained VkImportAndroidHardwareBufferInfoANDROID " "struct without a dedicated allocation requirement, while the AHardwareBuffer's external format (0x%" PRIx64 ") is not AHARDWAREBUFFER_FORMAT_BLOB or usage (0x%" PRIx64 ") does not include AHARDWAREBUFFER_USAGE_GPU_DATA_BUFFER.", ahb_format_props.externalFormat, ahb_desc.usage); } } else { // Checks specific to import with a dedicated allocation requirement VkImageCreateInfo *ici = &(GetImageState(dev_data, mem_ded_alloc_info->image)->createInfo); // The Android hardware buffer's usage must include at least one of AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT or // AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE if (0 == (ahb_desc.usage & (AHARDWAREBUFFER_USAGE_GPU_COLOR_OUTPUT | AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE))) { skip |= log_msg( dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(dev_data->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_COLOR_OUTPUT 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 |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(dev_data->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 |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(dev_data->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 |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(dev_data->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)) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(dev_data->device), "VUID-VkMemoryAllocateInfo-pNext-02390", "vkAllocateMemory: VkMemoryAllocateInfo struct with chained VkImportAndroidHardwareBufferInfoANDROID, " "dedicated image usage bits include one or more with no AHardwareBuffer equivalent."); } bool illegal_usage = false; std::vector<VkImageUsageFlags> usages = {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}; for (VkImageUsageFlags ubit : usages) { if (ici->usage & ubit) { uint64_t ahb_usage = ahb_usage_map_v2a[ubit]; if (0 == (ahb_usage & ahb_desc.usage)) illegal_usage = true; } } if (illegal_usage) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(dev_data->device), "VUID-VkMemoryAllocateInfo-pNext-02390", "vkAllocateMemory: VkMemoryAllocateInfo struct with chained " "VkImportAndroidHardwareBufferInfoANDROID, one or more AHardwareBuffer usage bits equivalent to " "the provided image's usage bits are missing from AHardwareBuffer_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 |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(dev_data->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 |= log_msg( dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(dev_data->device), "VUID-VkMemoryAllocateInfo-pNext-01874", "vkAllocateMemory: pNext chain does not indicate a dedicated export allocation, but allocationSize is 0."); }; } } return skip; } bool ValidateGetImageMemoryRequirements2ANDROID(layer_data *dev_data, const VkImage image) { bool skip = false; const debug_report_data *report_data = core_validation::GetReportData(dev_data); IMAGE_STATE *image_state = GetImageState(dev_data, image); if (image_state->imported_ahb && (0 == image_state->GetBoundMemory().size())) { skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, HandleToUint64(image), "VUID-VkImageMemoryRequirementsInfo2-image-01897", "vkGetImageMemoryRequirements2: Attempt to query layout from an image created with " "VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID handleType, which has not yet been " "bound to memory."); } return skip; } static bool ValidateGetPhysicalDeviceImageFormatProperties2ANDROID(const debug_report_data *report_data, const VkPhysicalDeviceImageFormatInfo2 *pImageFormatInfo, const VkImageFormatProperties2 *pImageFormatProperties) { bool skip = false; const VkAndroidHardwareBufferUsageANDROID *ahb_usage = lvl_find_in_chain<VkAndroidHardwareBufferUsageANDROID>(pImageFormatProperties->pNext); if (nullptr != ahb_usage) { const VkPhysicalDeviceExternalImageFormatInfo *pdeifi = lvl_find_in_chain<VkPhysicalDeviceExternalImageFormatInfo>(pImageFormatInfo->pNext); if ((nullptr == pdeifi) || (VK_EXTERNAL_MEMORY_HANDLE_TYPE_ANDROID_HARDWARE_BUFFER_BIT_ANDROID != pdeifi->handleType)) { skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "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; } static bool ValidateCreateSamplerYcbcrConversionANDROID(const layer_data *dev_data, const VkSamplerYcbcrConversionCreateInfo *create_info) { const VkExternalFormatANDROID *ext_format_android = lvl_find_in_chain<VkExternalFormatANDROID>(create_info->pNext); if ((nullptr != ext_format_android) && (VK_FORMAT_UNDEFINED != create_info->format)) { return log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SAMPLER_YCBCR_CONVERSION_EXT, 0, "VUID-VkSamplerYcbcrConversionCreateInfo-format-01904", "vkCreateSamplerYcbcrConversion[KHR]: CreateInfo format is not VK_FORMAT_UNDEFINED while there is a " "chained VkExternalFormatANDROID struct."); } else if ((nullptr == ext_format_android) && (VK_FORMAT_UNDEFINED == create_info->format)) { return log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SAMPLER_YCBCR_CONVERSION_EXT, 0, "VUID-VkSamplerYcbcrConversionCreateInfo-format-01904", "vkCreateSamplerYcbcrConversion[KHR]: CreateInfo format is VK_FORMAT_UNDEFINED with no chained " "VkExternalFormatANDROID struct."); } return false; } static void RecordCreateSamplerYcbcrConversionANDROID(layer_data *dev_data, const VkSamplerYcbcrConversionCreateInfo *create_info, VkSamplerYcbcrConversion ycbcr_conversion) { const VkExternalFormatANDROID *ext_format_android = lvl_find_in_chain<VkExternalFormatANDROID>(create_info->pNext); if (ext_format_android) { dev_data->ycbcr_conversion_ahb_fmt_map.emplace(ycbcr_conversion, ext_format_android->externalFormat); } }; static void RecordDestroySamplerYcbcrConversionANDROID(layer_data *dev_data, VkSamplerYcbcrConversion ycbcr_conversion) { dev_data->ycbcr_conversion_ahb_fmt_map.erase(ycbcr_conversion); }; #else static bool ValidateAllocateMemoryANDROID(layer_data *dev_data, const VkMemoryAllocateInfo *alloc_info) { return false; } static bool ValidateGetPhysicalDeviceImageFormatProperties2ANDROID(const debug_report_data *report_data, const VkPhysicalDeviceImageFormatInfo2 *pImageFormatInfo, const VkImageFormatProperties2 *pImageFormatProperties) { return false; } static bool ValidateCreateSamplerYcbcrConversionANDROID(const layer_data *dev_data, const VkSamplerYcbcrConversionCreateInfo *create_info) { return false; } bool ValidateGetImageMemoryRequirements2ANDROID(layer_data *dev_data, const VkImage image) { return false; } static void RecordCreateSamplerYcbcrConversionANDROID(layer_data *dev_data, const VkSamplerYcbcrConversionCreateInfo *create_info, VkSamplerYcbcrConversion ycbcr_conversion){}; static void RecordDestroySamplerYcbcrConversionANDROID(layer_data *dev_data, VkSamplerYcbcrConversion ycbcr_conversion){}; #endif // VK_USE_PLATFORM_ANDROID_KHR bool PreCallValidateAllocateMemory(VkDevice device, const VkMemoryAllocateInfo *pAllocateInfo, const VkAllocationCallbacks *pAllocator, VkDeviceMemory *pMemory) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); bool skip = false; if (device_data->memObjMap.size() >= device_data->phys_dev_properties.properties.limits.maxMemoryAllocationCount) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device), kVUIDUndefined, "Number of currently valid memory objects is not less than the maximum allowed (%u).", device_data->phys_dev_properties.properties.limits.maxMemoryAllocationCount); } if (GetDeviceExtensions(device_data)->vk_android_external_memory_android_hardware_buffer) { skip |= ValidateAllocateMemoryANDROID(device_data, pAllocateInfo); } else { if (0 == pAllocateInfo->allocationSize) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device), "VUID-VkMemoryAllocateInfo-allocationSize-00638", "vkAllocateMemory: allocationSize is 0."); }; } // TODO: VUIDs ending in 00643, 00644, 00646, 00647, 01742, 01743, 01745, 00645, 00648, 01744 return skip; } void PostCallRecordAllocateMemory(VkDevice device, const VkMemoryAllocateInfo *pAllocateInfo, const VkAllocationCallbacks *pAllocator, VkDeviceMemory *pMemory, VkResult result) { if (VK_SUCCESS == result) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); AddMemObjInfo(device_data, device, *pMemory, pAllocateInfo); } return; } // For given obj node, if it is use, flag a validation error and return callback result, else return false bool ValidateObjectNotInUse(const layer_data *dev_data, BASE_NODE *obj_node, VK_OBJECT obj_struct, const char *caller_name, const std::string &error_code) { if (dev_data->instance_data->disabled.object_in_use) return false; bool skip = false; if (obj_node->in_use.load()) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, get_debug_report_enum[obj_struct.type], obj_struct.handle, error_code, "Cannot call %s on %s 0x%" PRIx64 " that is currently in use by a command buffer.", caller_name, object_string[obj_struct.type], obj_struct.handle); } return skip; } bool PreCallValidateFreeMemory(VkDevice device, VkDeviceMemory mem, const VkAllocationCallbacks *pAllocator) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); DEVICE_MEM_INFO *mem_info = GetMemObjInfo(device_data, mem); VK_OBJECT obj_struct = {HandleToUint64(mem), kVulkanObjectTypeDeviceMemory}; bool skip = false; if (mem_info) { skip |= ValidateObjectNotInUse(device_data, mem_info, obj_struct, "vkFreeMemory", "VUID-vkFreeMemory-memory-00677"); } return skip; } void PreCallRecordFreeMemory(VkDevice device, VkDeviceMemory mem, const VkAllocationCallbacks *pAllocator) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); DEVICE_MEM_INFO *mem_info = GetMemObjInfo(device_data, mem); VK_OBJECT obj_struct = {HandleToUint64(mem), kVulkanObjectTypeDeviceMemory}; // Clear mem binding for any bound objects for (auto obj : mem_info->obj_bindings) { log_msg(device_data->report_data, VK_DEBUG_REPORT_INFORMATION_BIT_EXT, get_debug_report_enum[obj.type], obj.handle, kVUID_Core_MemTrack_FreedMemRef, "VK Object 0x%" PRIx64 " still has a reference to mem obj 0x%" PRIx64, HandleToUint64(obj.handle), HandleToUint64(mem_info->mem)); BINDABLE *bindable_state = nullptr; switch (obj.type) { case kVulkanObjectTypeImage: bindable_state = GetImageState(device_data, reinterpret_cast<VkImage &>(obj.handle)); break; case kVulkanObjectTypeBuffer: bindable_state = GetBufferState(device_data, reinterpret_cast<VkBuffer &>(obj.handle)); break; default: // Should only have buffer or image objects bound to memory assert(0); } assert(bindable_state); bindable_state->binding.mem = MEMORY_UNBOUND; bindable_state->UpdateBoundMemorySet(); } // Any bound cmd buffers are now invalid InvalidateCommandBuffers(device_data, mem_info->cb_bindings, obj_struct); device_data->memObjMap.erase(mem); } // 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 static bool ValidateMapMemRange(layer_data *dev_data, VkDeviceMemory mem, VkDeviceSize offset, VkDeviceSize size) { bool skip = false; if (size == 0) { skip = log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT, HandleToUint64(mem), kVUID_Core_MemTrack_InvalidMap, "VkMapMemory: Attempting to map memory range of size zero"); } auto mem_element = dev_data->memObjMap.find(mem); if (mem_element != dev_data->memObjMap.end()) { auto mem_info = mem_element->second.get(); // It is an application error to call VkMapMemory on an object that is already mapped if (mem_info->mem_range.size != 0) { skip = log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT, HandleToUint64(mem), kVUID_Core_MemTrack_InvalidMap, "VkMapMemory: Attempting to map memory on an already-mapped object 0x%" PRIx64, HandleToUint64(mem)); } // Validate that offset + size is within object's allocationSize if (size == VK_WHOLE_SIZE) { if (offset >= mem_info->alloc_info.allocationSize) { skip = log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT, HandleToUint64(mem), kVUID_Core_MemTrack_InvalidMap, "Mapping Memory from 0x%" PRIx64 " to 0x%" PRIx64 " with size of VK_WHOLE_SIZE oversteps total array size 0x%" PRIx64, offset, mem_info->alloc_info.allocationSize, mem_info->alloc_info.allocationSize); } } else { if ((offset + size) > mem_info->alloc_info.allocationSize) { skip = log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT, HandleToUint64(mem), "VUID-vkMapMemory-size-00681", "Mapping Memory from 0x%" PRIx64 " to 0x%" PRIx64 " oversteps total array size 0x%" PRIx64 ".", offset, size + offset, mem_info->alloc_info.allocationSize); } } } return skip; } static void StoreMemRanges(layer_data *dev_data, VkDeviceMemory mem, VkDeviceSize offset, VkDeviceSize size) { auto mem_info = GetMemObjInfo(dev_data, mem); if (mem_info) { mem_info->mem_range.offset = offset; mem_info->mem_range.size = size; } } // Guard value for pad data static char NoncoherentMemoryFillValue = 0xb; static void InitializeAndTrackMemory(layer_data *dev_data, VkDeviceMemory mem, VkDeviceSize offset, VkDeviceSize size, void **ppData) { auto mem_info = GetMemObjInfo(dev_data, mem); if (mem_info) { mem_info->p_driver_data = *ppData; uint32_t index = mem_info->alloc_info.memoryTypeIndex; if (dev_data->phys_dev_mem_props.memoryTypes[index].propertyFlags & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) { mem_info->shadow_copy = 0; } else { if (size == VK_WHOLE_SIZE) { size = mem_info->alloc_info.allocationSize - offset; } mem_info->shadow_pad_size = dev_data->phys_dev_properties.properties.limits.minMemoryMapAlignment; assert(SafeModulo(mem_info->shadow_pad_size, dev_data->phys_dev_properties.properties.limits.minMemoryMapAlignment) == 0); // Ensure start of mapped region reflects hardware alignment constraints uint64_t map_alignment = dev_data->phys_dev_properties.properties.limits.minMemoryMapAlignment; // From spec: (ppData - offset) must be aligned to at least limits::minMemoryMapAlignment. uint64_t start_offset = offset % map_alignment; // Data passed to driver will be wrapped by a guardband of data to detect over- or under-writes. mem_info->shadow_copy_base = malloc(static_cast<size_t>(2 * mem_info->shadow_pad_size + size + map_alignment + start_offset)); mem_info->shadow_copy = reinterpret_cast<char *>((reinterpret_cast<uintptr_t>(mem_info->shadow_copy_base) + map_alignment) & ~(map_alignment - 1)) + start_offset; assert(SafeModulo(reinterpret_cast<uintptr_t>(mem_info->shadow_copy) + mem_info->shadow_pad_size - start_offset, map_alignment) == 0); memset(mem_info->shadow_copy, NoncoherentMemoryFillValue, static_cast<size_t>(2 * mem_info->shadow_pad_size + size)); *ppData = static_cast<char *>(mem_info->shadow_copy) + mem_info->shadow_pad_size; } } } // Verify that state for fence being waited on is appropriate. That is, // a fence being waited on should not already be signaled and // it should have been submitted on a queue or during acquire next image static inline bool VerifyWaitFenceState(layer_data *dev_data, VkFence fence, const char *apiCall) { bool skip = false; auto pFence = GetFenceNode(dev_data, fence); if (pFence && pFence->scope == kSyncScopeInternal) { if (pFence->state == FENCE_UNSIGNALED) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_FENCE_EXT, HandleToUint64(fence), kVUID_Core_MemTrack_FenceState, "%s called for fence 0x%" PRIx64 " which has not been submitted on a Queue or during acquire next image.", apiCall, HandleToUint64(fence)); } } return skip; } static void RetireFence(layer_data *dev_data, VkFence fence) { auto pFence = GetFenceNode(dev_data, fence); if (pFence && pFence->scope == kSyncScopeInternal) { if (pFence->signaler.first != VK_NULL_HANDLE) { // Fence signaller is a queue -- use this as proof that prior operations on that queue have completed. RetireWorkOnQueue(dev_data, GetQueueState(dev_data, pFence->signaler.first), pFence->signaler.second); } else { // Fence signaller is the WSI. We're not tracking what the WSI op actually /was/ in CV yet, but we need to mark // the fence as retired. pFence->state = FENCE_RETIRED; } } } bool PreCallValidateWaitForFences(layer_data *dev_data, uint32_t fence_count, const VkFence *fences) { if (dev_data->instance_data->disabled.wait_for_fences) return false; bool skip = false; for (uint32_t i = 0; i < fence_count; i++) { skip |= VerifyWaitFenceState(dev_data, fences[i], "vkWaitForFences"); skip |= VerifyQueueStateToFence(dev_data, fences[i]); } return skip; } void PostCallRecordWaitForFences(layer_data *dev_data, uint32_t fence_count, const VkFence *fences, VkBool32 wait_all) { // When we know that all fences are complete we can clean/remove their CBs if ((VK_TRUE == wait_all) || (1 == fence_count)) { for (uint32_t i = 0; i < fence_count; i++) { RetireFence(dev_data, fences[i]); } } // NOTE : Alternate case not handled here is when some fences have completed. In // this case for app to guarantee which fences completed it will have to call // vkGetFenceStatus() at which point we'll clean/remove their CBs if complete. } bool PreCallValidateGetFenceStatus(layer_data *dev_data, VkFence fence) { if (dev_data->instance_data->disabled.get_fence_state) return false; return VerifyWaitFenceState(dev_data, fence, "vkGetFenceStatus"); } void PostCallRecordGetFenceStatus(layer_data *dev_data, VkFence fence) { RetireFence(dev_data, fence); } void PostCallRecordGetDeviceQueue(layer_data *dev_data, uint32_t q_family_index, VkQueue queue) { // Add queue to tracking set only if it is new auto result = dev_data->queues.emplace(queue); if (result.second == true) { QUEUE_STATE *queue_state = &dev_data->queueMap[queue]; queue_state->queue = queue; queue_state->queueFamilyIndex = q_family_index; queue_state->seq = 0; } } bool PreCallValidateQueueWaitIdle(VkQueue queue) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(queue), layer_data_map); QUEUE_STATE *queue_state = GetQueueState(device_data, queue); if (device_data->instance_data->disabled.queue_wait_idle) return false; return VerifyQueueStateToSeq(device_data, queue_state, queue_state->seq + queue_state->submissions.size()); } void PostCallRecordQueueWaitIdle(VkQueue queue, VkResult result) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(queue), layer_data_map); if (VK_SUCCESS != result) return; QUEUE_STATE *queue_state = GetQueueState(device_data, queue); RetireWorkOnQueue(device_data, queue_state, queue_state->seq + queue_state->submissions.size()); } bool PreCallValidateDeviceWaitIdle(layer_data *dev_data) { if (dev_data->instance_data->disabled.device_wait_idle) return false; bool skip = false; for (auto &queue : dev_data->queueMap) { skip |= VerifyQueueStateToSeq(dev_data, &queue.second, queue.second.seq + queue.second.submissions.size()); } return skip; } void PostCallRecordDeviceWaitIdle(layer_data *dev_data) { for (auto &queue : dev_data->queueMap) { RetireWorkOnQueue(dev_data, &queue.second, queue.second.seq + queue.second.submissions.size()); } } bool PreCallValidateDestroyFence(VkDevice device, VkFence fence, const VkAllocationCallbacks *pAllocator) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); FENCE_NODE *fence_node = GetFenceNode(device_data, fence); bool skip = false; if (fence_node) { if (fence_node->scope == kSyncScopeInternal && fence_node->state == FENCE_INFLIGHT) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_FENCE_EXT, HandleToUint64(fence), "VUID-vkDestroyFence-fence-01120", "Fence 0x%" PRIx64 " is in use.", HandleToUint64(fence)); } } return skip; } void PreCallRecordDestroyFence(VkDevice device, VkFence fence, const VkAllocationCallbacks *pAllocator) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); if (!fence) return; device_data->fenceMap.erase(fence); } bool PreCallValidateDestroySemaphore(VkDevice device, VkSemaphore semaphore, const VkAllocationCallbacks *pAllocator) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); SEMAPHORE_NODE *sema_node = GetSemaphoreNode(device_data, semaphore); VK_OBJECT obj_struct = {HandleToUint64(semaphore), kVulkanObjectTypeSemaphore}; if (device_data->instance_data->disabled.destroy_semaphore) return false; bool skip = false; if (sema_node) { skip |= ValidateObjectNotInUse(device_data, sema_node, obj_struct, "vkDestroySemaphore", "VUID-vkDestroySemaphore-semaphore-01137"); } return skip; } void PreCallRecordDestroySemaphore(VkDevice device, VkSemaphore semaphore, const VkAllocationCallbacks *pAllocator) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); if (!semaphore) return; device_data->semaphoreMap.erase(semaphore); } bool PreCallValidateDestroyEvent(VkDevice device, VkEvent event, const VkAllocationCallbacks *pAllocator) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); EVENT_STATE *event_state = GetEventNode(device_data, event); VK_OBJECT obj_struct = {HandleToUint64(event), kVulkanObjectTypeEvent}; bool skip = false; if (event_state) { skip |= ValidateObjectNotInUse(device_data, event_state, obj_struct, "vkDestroyEvent", "VUID-vkDestroyEvent-event-01145"); } return skip; } void PreCallRecordDestroyEvent(VkDevice device, VkEvent event, const VkAllocationCallbacks *pAllocator) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); if (!event) return; EVENT_STATE *event_state = GetEventNode(device_data, event); VK_OBJECT obj_struct = {HandleToUint64(event), kVulkanObjectTypeEvent}; InvalidateCommandBuffers(device_data, event_state->cb_bindings, obj_struct); device_data->eventMap.erase(event); } bool PreCallValidateDestroyQueryPool(VkDevice device, VkQueryPool queryPool, const VkAllocationCallbacks *pAllocator) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); QUERY_POOL_NODE *qp_state = GetQueryPoolNode(device_data, queryPool); VK_OBJECT obj_struct = {HandleToUint64(queryPool), kVulkanObjectTypeQueryPool}; bool skip = false; if (qp_state) { skip |= ValidateObjectNotInUse(device_data, qp_state, obj_struct, "vkDestroyQueryPool", "VUID-vkDestroyQueryPool-queryPool-00793"); } return skip; } void PreCallRecordDestroyQueryPool(VkDevice device, VkQueryPool queryPool, const VkAllocationCallbacks *pAllocator) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); if (!queryPool) return; QUERY_POOL_NODE *qp_state = GetQueryPoolNode(device_data, queryPool); VK_OBJECT obj_struct = {HandleToUint64(queryPool), kVulkanObjectTypeQueryPool}; InvalidateCommandBuffers(device_data, qp_state->cb_bindings, obj_struct); device_data->queryPoolMap.erase(queryPool); } bool PreCallValidateGetQueryPoolResults(layer_data *dev_data, VkQueryPool query_pool, uint32_t first_query, uint32_t query_count, VkQueryResultFlags flags, unordered_map<QueryObject, vector<VkCommandBuffer>> *queries_in_flight) { bool skip = false; auto query_pool_state = dev_data->queryPoolMap.find(query_pool); if (query_pool_state != dev_data->queryPoolMap.end()) { if ((query_pool_state->second.createInfo.queryType == VK_QUERY_TYPE_TIMESTAMP) && (flags & VK_QUERY_RESULT_PARTIAL_BIT)) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_QUERY_POOL_EXT, 0, "VUID-vkGetQueryPoolResults-queryType-00818", "QueryPool 0x%" PRIx64 " was created with a queryType of VK_QUERY_TYPE_TIMESTAMP but flags contains VK_QUERY_RESULT_PARTIAL_BIT.", HandleToUint64(query_pool)); } } // TODO: clean this up, it's insanely wasteful. for (auto cmd_buffer : dev_data->commandBufferMap) { if (cmd_buffer.second->in_use.load()) { for (auto query_state_pair : cmd_buffer.second->queryToStateMap) { (*queries_in_flight)[query_state_pair.first].push_back(cmd_buffer.first); } } } return skip; } void PostCallRecordGetQueryPoolResults(layer_data *dev_data, VkQueryPool query_pool, uint32_t first_query, uint32_t query_count, unordered_map<QueryObject, vector<VkCommandBuffer>> *queries_in_flight) { for (uint32_t i = 0; i < query_count; ++i) { QueryObject query = {query_pool, first_query + i}; auto qif_pair = queries_in_flight->find(query); auto query_state_pair = dev_data->queryToStateMap.find(query); if (query_state_pair != dev_data->queryToStateMap.end()) { // Available and in flight if (qif_pair != queries_in_flight->end() && query_state_pair != dev_data->queryToStateMap.end() && query_state_pair->second) { for (auto cmd_buffer : qif_pair->second) { auto cb = GetCBNode(dev_data, cmd_buffer); auto query_event_pair = cb->waitedEventsBeforeQueryReset.find(query); if (query_event_pair != cb->waitedEventsBeforeQueryReset.end()) { for (auto event : query_event_pair->second) { dev_data->eventMap[event].needsSignaled = true; } } } } } } } // Return true if given ranges intersect, else false // Prereq : For both ranges, range->end - range->start > 0. This case should have already resulted // in an error so not checking that here // pad_ranges bool indicates a linear and non-linear comparison which requires padding // In the case where padding is required, if an alias is encountered then a validation error is reported and skip // may be set by the callback function so caller should merge in skip value if padding case is possible. // This check can be skipped by passing skip_checks=true, for call sites outside the validation path. static bool RangesIntersect(layer_data const *dev_data, MEMORY_RANGE const *range1, MEMORY_RANGE const *range2, bool *skip, bool skip_checks) { *skip = false; auto r1_start = range1->start; auto r1_end = range1->end; auto r2_start = range2->start; auto r2_end = range2->end; VkDeviceSize pad_align = 1; if (range1->linear != range2->linear) { pad_align = dev_data->phys_dev_properties.properties.limits.bufferImageGranularity; } if ((r1_end & ~(pad_align - 1)) < (r2_start & ~(pad_align - 1))) return false; if ((r1_start & ~(pad_align - 1)) > (r2_end & ~(pad_align - 1))) return false; if (!skip_checks && (range1->linear != range2->linear)) { // In linear vs. non-linear case, warn of aliasing const char *r1_linear_str = range1->linear ? "Linear" : "Non-linear"; const char *r1_type_str = range1->image ? "image" : "buffer"; const char *r2_linear_str = range2->linear ? "linear" : "non-linear"; const char *r2_type_str = range2->image ? "image" : "buffer"; auto obj_type = range1->image ? VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT : VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT; *skip |= log_msg( dev_data->report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, obj_type, range1->handle, kVUID_Core_MemTrack_InvalidAliasing, "%s %s 0x%" PRIx64 " is aliased with %s %s 0x%" PRIx64 " which may indicate a bug. For further info refer to the Buffer-Image Granularity section of the Vulkan " "specification. " "(https://www.khronos.org/registry/vulkan/specs/1.0-extensions/xhtml/vkspec.html#resources-bufferimagegranularity)", r1_linear_str, r1_type_str, range1->handle, r2_linear_str, r2_type_str, range2->handle); } // Ranges intersect return true; } // Simplified RangesIntersect that calls above function to check range1 for intersection with offset & end addresses bool RangesIntersect(layer_data const *dev_data, MEMORY_RANGE const *range1, VkDeviceSize offset, VkDeviceSize end) { // Create a local MEMORY_RANGE struct to wrap offset/size MEMORY_RANGE range_wrap; // Synch linear with range1 to avoid padding and potential validation error case range_wrap.linear = range1->linear; range_wrap.start = offset; range_wrap.end = end; bool tmp_bool; return RangesIntersect(dev_data, range1, &range_wrap, &tmp_bool, true); } static bool ValidateInsertMemoryRange(layer_data const *dev_data, uint64_t handle, DEVICE_MEM_INFO *mem_info, VkDeviceSize memoryOffset, VkMemoryRequirements memRequirements, bool is_image, bool is_linear, const char *api_name) { bool skip = false; MEMORY_RANGE range; range.image = is_image; range.handle = handle; range.linear = is_linear; range.memory = mem_info->mem; range.start = memoryOffset; range.size = memRequirements.size; range.end = memoryOffset + memRequirements.size - 1; range.aliases.clear(); // Check for aliasing problems. for (auto &obj_range_pair : mem_info->bound_ranges) { auto check_range = &obj_range_pair.second; bool intersection_error = false; if (RangesIntersect(dev_data, &range, check_range, &intersection_error, false)) { skip |= intersection_error; range.aliases.insert(check_range); } } if (memoryOffset >= mem_info->alloc_info.allocationSize) { std::string error_code = is_image ? "VUID-vkBindImageMemory-memoryOffset-01046" : "VUID-vkBindBufferMemory-memoryOffset-01031"; skip = log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT, HandleToUint64(mem_info->mem), error_code, "In %s, attempting to bind memory (0x%" PRIx64 ") to object (0x%" PRIx64 "), memoryOffset=0x%" PRIxLEAST64 " must be less than the memory allocation size 0x%" PRIxLEAST64 ".", api_name, HandleToUint64(mem_info->mem), HandleToUint64(handle), memoryOffset, mem_info->alloc_info.allocationSize); } return skip; } // Object with given handle is being bound to memory w/ given mem_info struct. // Track the newly bound memory range with given memoryOffset // Also scan any previous ranges, track aliased ranges with new range, and flag an error if a linear // and non-linear range incorrectly overlap. // Return true if an error is flagged and the user callback returns "true", otherwise false // is_image indicates an image object, otherwise handle is for a buffer // is_linear indicates a buffer or linear image static void InsertMemoryRange(layer_data const *dev_data, uint64_t handle, DEVICE_MEM_INFO *mem_info, VkDeviceSize memoryOffset, VkMemoryRequirements memRequirements, bool is_image, bool is_linear) { MEMORY_RANGE range; range.image = is_image; range.handle = handle; range.linear = is_linear; range.memory = mem_info->mem; range.start = memoryOffset; range.size = memRequirements.size; range.end = memoryOffset + memRequirements.size - 1; range.aliases.clear(); // Update Memory aliasing // Save aliased ranges so we can copy into final map entry below. Can't do it in loop b/c we don't yet have final ptr. If we // inserted into map before loop to get the final ptr, then we may enter loop when not needed & we check range against itself std::unordered_set<MEMORY_RANGE *> tmp_alias_ranges; for (auto &obj_range_pair : mem_info->bound_ranges) { auto check_range = &obj_range_pair.second; bool intersection_error = false; if (RangesIntersect(dev_data, &range, check_range, &intersection_error, true)) { range.aliases.insert(check_range); tmp_alias_ranges.insert(check_range); } } mem_info->bound_ranges[handle] = std::move(range); for (auto tmp_range : tmp_alias_ranges) { tmp_range->aliases.insert(&mem_info->bound_ranges[handle]); } if (is_image) mem_info->bound_images.insert(handle); else mem_info->bound_buffers.insert(handle); } static bool ValidateInsertImageMemoryRange(layer_data const *dev_data, VkImage image, DEVICE_MEM_INFO *mem_info, VkDeviceSize mem_offset, VkMemoryRequirements mem_reqs, bool is_linear, const char *api_name) { return ValidateInsertMemoryRange(dev_data, HandleToUint64(image), mem_info, mem_offset, mem_reqs, true, is_linear, api_name); } static void InsertImageMemoryRange(layer_data const *dev_data, VkImage image, DEVICE_MEM_INFO *mem_info, VkDeviceSize mem_offset, VkMemoryRequirements mem_reqs, bool is_linear) { InsertMemoryRange(dev_data, HandleToUint64(image), mem_info, mem_offset, mem_reqs, true, is_linear); } static bool ValidateInsertBufferMemoryRange(layer_data const *dev_data, VkBuffer buffer, DEVICE_MEM_INFO *mem_info, VkDeviceSize mem_offset, VkMemoryRequirements mem_reqs, const char *api_name) { return ValidateInsertMemoryRange(dev_data, HandleToUint64(buffer), mem_info, mem_offset, mem_reqs, false, true, api_name); } static void InsertBufferMemoryRange(layer_data const *dev_data, VkBuffer buffer, DEVICE_MEM_INFO *mem_info, VkDeviceSize mem_offset, VkMemoryRequirements mem_reqs) { InsertMemoryRange(dev_data, HandleToUint64(buffer), mem_info, mem_offset, mem_reqs, false, true); } // Remove MEMORY_RANGE struct for give handle from bound_ranges of mem_info // is_image indicates if handle is for image or buffer // This function will also remove the handle-to-index mapping from the appropriate // map and clean up any aliases for range being removed. static void RemoveMemoryRange(uint64_t handle, DEVICE_MEM_INFO *mem_info, bool is_image) { auto erase_range = &mem_info->bound_ranges[handle]; for (auto alias_range : erase_range->aliases) { alias_range->aliases.erase(erase_range); } erase_range->aliases.clear(); mem_info->bound_ranges.erase(handle); if (is_image) { mem_info->bound_images.erase(handle); } else { mem_info->bound_buffers.erase(handle); } } void RemoveBufferMemoryRange(uint64_t handle, DEVICE_MEM_INFO *mem_info) { RemoveMemoryRange(handle, mem_info, false); } void RemoveImageMemoryRange(uint64_t handle, DEVICE_MEM_INFO *mem_info) { RemoveMemoryRange(handle, mem_info, true); } static bool ValidateMemoryTypes(const layer_data *dev_data, const DEVICE_MEM_INFO *mem_info, const uint32_t memory_type_bits, const char *funcName, std::string msgCode) { bool skip = false; if (((1 << mem_info->alloc_info.memoryTypeIndex) & memory_type_bits) == 0) { skip = log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT, HandleToUint64(mem_info->mem), msgCode, "%s(): MemoryRequirements->memoryTypeBits (0x%X) for this object type are not compatible with the memory " "type (0x%X) of this memory object 0x%" PRIx64 ".", funcName, memory_type_bits, mem_info->alloc_info.memoryTypeIndex, HandleToUint64(mem_info->mem)); } return skip; } bool ValidateBindBufferMemory(layer_data *device_data, VkBuffer buffer, VkDeviceMemory mem, VkDeviceSize memoryOffset, const char *api_name) { BUFFER_STATE *buffer_state = GetBufferState(device_data, buffer); bool skip = false; if (buffer_state) { // Track objects tied to memory uint64_t buffer_handle = HandleToUint64(buffer); skip = ValidateSetMemBinding(device_data, mem, buffer_handle, kVulkanObjectTypeBuffer, api_name); if (!buffer_state->memory_requirements_checked) { // There's not an explicit requirement in the spec to call vkGetBufferMemoryRequirements() prior to calling // BindBufferMemory, but it's implied in that memory being bound must conform with VkMemoryRequirements from // vkGetBufferMemoryRequirements() skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT, buffer_handle, kVUID_Core_DrawState_InvalidBuffer, "%s: Binding memory to buffer 0x%" PRIx64 " but vkGetBufferMemoryRequirements() has not been called on that buffer.", api_name, HandleToUint64(buffer_handle)); // Make the call for them so we can verify the state device_data->dispatch_table.GetBufferMemoryRequirements(device_data->device, buffer, &buffer_state->requirements); } // Validate bound memory range information const auto mem_info = GetMemObjInfo(device_data, mem); if (mem_info) { skip |= ValidateInsertBufferMemoryRange(device_data, buffer, mem_info, memoryOffset, buffer_state->requirements, api_name); skip |= ValidateMemoryTypes(device_data, mem_info, buffer_state->requirements.memoryTypeBits, api_name, "VUID-vkBindBufferMemory-memory-01035"); } // Validate memory requirements alignment if (SafeModulo(memoryOffset, buffer_state->requirements.alignment) != 0) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT, buffer_handle, "VUID-vkBindBufferMemory-memoryOffset-01036", "%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 memory requirements size if (buffer_state->requirements.size > (mem_info->alloc_info.allocationSize - memoryOffset)) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT, buffer_handle, "VUID-vkBindBufferMemory-size-01037", "%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->is_dedicated && ((mem_info->dedicated_buffer != buffer) || (memoryOffset != 0))) { // TODO: Add vkBindBufferMemory2KHR error message when added to spec. auto validation_error = kVUIDUndefined; if (strcmp(api_name, "vkBindBufferMemory()") == 0) { validation_error = "VUID-vkBindBufferMemory-memory-01508"; } skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT, buffer_handle, validation_error, "%s: for dedicated memory allocation 0x%" PRIxLEAST64 ", VkMemoryDedicatedAllocateInfoKHR::buffer 0x%" PRIXLEAST64 " must be equal to buffer 0x%" PRIxLEAST64 " and memoryOffset 0x%" PRIxLEAST64 " must be zero.", api_name, HandleToUint64(mem), HandleToUint64(mem_info->dedicated_buffer), buffer_handle, memoryOffset); } } } return skip; } bool PreCallValidateBindBufferMemory(VkDevice device, VkBuffer buffer, VkDeviceMemory mem, VkDeviceSize memoryOffset) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); const char *api_name = "vkBindBufferMemory()"; return ValidateBindBufferMemory(device_data, buffer, mem, memoryOffset, api_name); } void UpdateBindBufferMemoryState(layer_data *device_data, VkBuffer buffer, VkDeviceMemory mem, VkDeviceSize memoryOffset) { BUFFER_STATE *buffer_state = GetBufferState(device_data, buffer); if (buffer_state) { // Track bound memory range information auto mem_info = GetMemObjInfo(device_data, mem); if (mem_info) { InsertBufferMemoryRange(device_data, buffer, mem_info, memoryOffset, buffer_state->requirements); } // Track objects tied to memory uint64_t buffer_handle = HandleToUint64(buffer); SetMemBinding(device_data, mem, buffer_state, memoryOffset, buffer_handle, kVulkanObjectTypeBuffer); } } void PostCallRecordBindBufferMemory(VkDevice device, VkBuffer buffer, VkDeviceMemory mem, VkDeviceSize memoryOffset, VkResult result) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); if (VK_SUCCESS != result) return; UpdateBindBufferMemoryState(device_data, buffer, mem, memoryOffset); } bool PreCallValidateBindBufferMemory2(VkDevice device, uint32_t bindInfoCount, const VkBindBufferMemoryInfoKHR *pBindInfos) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); char api_name[64]; bool skip = false; for (uint32_t i = 0; i < bindInfoCount; i++) { sprintf(api_name, "vkBindBufferMemory2() pBindInfos[%u]", i); skip |= ValidateBindBufferMemory(device_data, pBindInfos[i].buffer, pBindInfos[i].memory, pBindInfos[i].memoryOffset, api_name); } return skip; } bool PreCallValidateBindBufferMemory2KHR(VkDevice device, uint32_t bindInfoCount, const VkBindBufferMemoryInfoKHR *pBindInfos) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); char api_name[64]; bool skip = false; for (uint32_t i = 0; i < bindInfoCount; i++) { sprintf(api_name, "vkBindBufferMemory2KHR() pBindInfos[%u]", i); skip |= ValidateBindBufferMemory(device_data, pBindInfos[i].buffer, pBindInfos[i].memory, pBindInfos[i].memoryOffset, api_name); } return skip; } void PostCallRecordBindBufferMemory2(VkDevice device, uint32_t bindInfoCount, const VkBindBufferMemoryInfoKHR *pBindInfos, VkResult result) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); for (uint32_t i = 0; i < bindInfoCount; i++) { UpdateBindBufferMemoryState(device_data, pBindInfos[i].buffer, pBindInfos[i].memory, pBindInfos[i].memoryOffset); } } void PostCallRecordBindBufferMemory2KHR(VkDevice device, uint32_t bindInfoCount, const VkBindBufferMemoryInfoKHR *pBindInfos, VkResult result) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); for (uint32_t i = 0; i < bindInfoCount; i++) { UpdateBindBufferMemoryState(device_data, pBindInfos[i].buffer, pBindInfos[i].memory, pBindInfos[i].memoryOffset); } } void PostCallRecordGetBufferMemoryRequirements(layer_data *dev_data, VkBuffer buffer, VkMemoryRequirements *pMemoryRequirements) { BUFFER_STATE *buffer_state; { unique_lock_t lock(global_lock); buffer_state = GetBufferState(dev_data, buffer); } if (buffer_state) { buffer_state->requirements = *pMemoryRequirements; buffer_state->memory_requirements_checked = true; } } bool PreCallValidateGetImageMemoryRequirements2(layer_data *dev_data, const VkImageMemoryRequirementsInfo2 *pInfo) { bool skip = false; if (GetDeviceExtensions(dev_data)->vk_android_external_memory_android_hardware_buffer) { skip |= ValidateGetImageMemoryRequirements2ANDROID(dev_data, pInfo->image); } return skip; } void PostCallRecordGetImageMemoryRequirements(layer_data *dev_data, VkImage image, VkMemoryRequirements *pMemoryRequirements) { IMAGE_STATE *image_state; { unique_lock_t lock(global_lock); image_state = GetImageState(dev_data, image); } if (image_state) { image_state->requirements = *pMemoryRequirements; image_state->memory_requirements_checked = true; } } void PostCallRecordGetImageSparseMemoryRequirements(IMAGE_STATE *image_state, uint32_t req_count, VkSparseImageMemoryRequirements *reqs) { image_state->get_sparse_reqs_called = true; image_state->sparse_requirements.resize(req_count); if (reqs) { std::copy(reqs, reqs + req_count, image_state->sparse_requirements.begin()); } for (const auto &req : image_state->sparse_requirements) { if (req.formatProperties.aspectMask & VK_IMAGE_ASPECT_METADATA_BIT) { image_state->sparse_metadata_required = true; } } } void PostCallRecordGetImageSparseMemoryRequirements2(IMAGE_STATE *image_state, uint32_t req_count, VkSparseImageMemoryRequirements2KHR *reqs) { // reqs is empty, so there is nothing to loop over and read. if (reqs == nullptr) { return; } std::vector<VkSparseImageMemoryRequirements> sparse_reqs(req_count); // Migrate to old struct type for common handling with GetImageSparseMemoryRequirements() for (uint32_t i = 0; i < req_count; ++i) { assert(!reqs[i].pNext); // TODO: If an extension is ever added here we need to handle it sparse_reqs[i] = reqs[i].memoryRequirements; } PostCallRecordGetImageSparseMemoryRequirements(image_state, req_count, sparse_reqs.data()); } bool PreCallValidateGetPhysicalDeviceImageFormatProperties2(const debug_report_data *report_data, const VkPhysicalDeviceImageFormatInfo2 *pImageFormatInfo, const VkImageFormatProperties2 *pImageFormatProperties) { // Can't wrap AHB-specific validation in a device extension check here, but no harm bool skip = ValidateGetPhysicalDeviceImageFormatProperties2ANDROID(report_data, pImageFormatInfo, pImageFormatProperties); return skip; } void PreCallRecordDestroyShaderModule(VkDevice device, VkShaderModule shaderModule, const VkAllocationCallbacks *pAllocator) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); if (!shaderModule) return; device_data->shaderModuleMap.erase(shaderModule); } bool PreCallValidateDestroyPipeline(VkDevice device, VkPipeline pipeline, const VkAllocationCallbacks *pAllocator) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); PIPELINE_STATE *pipeline_state = GetPipelineState(device_data, pipeline); VK_OBJECT obj_struct = {HandleToUint64(pipeline), kVulkanObjectTypePipeline}; if (device_data->instance_data->disabled.destroy_pipeline) return false; bool skip = false; if (pipeline_state) { skip |= ValidateObjectNotInUse(device_data, pipeline_state, obj_struct, "vkDestroyPipeline", "VUID-vkDestroyPipeline-pipeline-00765"); } return skip; } void PreCallRecordDestroyPipeline(VkDevice device, VkPipeline pipeline, const VkAllocationCallbacks *pAllocator) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); if (!pipeline) return; PIPELINE_STATE *pipeline_state = GetPipelineState(device_data, pipeline); VK_OBJECT obj_struct = {HandleToUint64(pipeline), kVulkanObjectTypePipeline}; // Any bound cmd buffers are now invalid InvalidateCommandBuffers(device_data, pipeline_state->cb_bindings, obj_struct); if (GetEnables(device_data)->gpu_validation) { GpuPreCallRecordDestroyPipeline(device_data, pipeline); } device_data->pipelineMap.erase(pipeline); } void PreCallRecordDestroyPipelineLayout(VkDevice device, VkPipelineLayout pipelineLayout, const VkAllocationCallbacks *pAllocator) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); if (!pipelineLayout) return; device_data->pipelineLayoutMap.erase(pipelineLayout); } bool PreCallValidateDestroySampler(VkDevice device, VkSampler sampler, const VkAllocationCallbacks *pAllocator) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); SAMPLER_STATE *sampler_state = GetSamplerState(device_data, sampler); VK_OBJECT obj_struct = {HandleToUint64(sampler), kVulkanObjectTypeSampler}; if (device_data->instance_data->disabled.destroy_sampler) return false; bool skip = false; if (sampler_state) { skip |= ValidateObjectNotInUse(device_data, sampler_state, obj_struct, "vkDestroySampler", "VUID-vkDestroySampler-sampler-01082"); } return skip; } void PreCallRecordDestroySampler(VkDevice device, VkSampler sampler, const VkAllocationCallbacks *pAllocator) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); if (!sampler) return; SAMPLER_STATE *sampler_state = GetSamplerState(device_data, sampler); VK_OBJECT obj_struct = {HandleToUint64(sampler), kVulkanObjectTypeSampler}; // Any bound cmd buffers are now invalid if (sampler_state) { InvalidateCommandBuffers(device_data, sampler_state->cb_bindings, obj_struct); } device_data->samplerMap.erase(sampler); } void PreCallRecordDestroyDescriptorSetLayout(VkDevice device, VkDescriptorSetLayout descriptorSetLayout, const VkAllocationCallbacks *pAllocator) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); if (!descriptorSetLayout) return; auto layout_it = device_data->descriptorSetLayoutMap.find(descriptorSetLayout); if (layout_it != device_data->descriptorSetLayoutMap.end()) { layout_it->second.get()->MarkDestroyed(); device_data->descriptorSetLayoutMap.erase(layout_it); } } bool PreCallValidateDestroyDescriptorPool(VkDevice device, VkDescriptorPool descriptorPool, const VkAllocationCallbacks *pAllocator) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); DESCRIPTOR_POOL_STATE *desc_pool_state = GetDescriptorPoolState(device_data, descriptorPool); VK_OBJECT obj_struct = {HandleToUint64(descriptorPool), kVulkanObjectTypeDescriptorPool}; if (device_data->instance_data->disabled.destroy_descriptor_pool) return false; bool skip = false; if (desc_pool_state) { skip |= ValidateObjectNotInUse(device_data, desc_pool_state, obj_struct, "vkDestroyDescriptorPool", "VUID-vkDestroyDescriptorPool-descriptorPool-00303"); } return skip; } void PreCallRecordDestroyDescriptorPool(VkDevice device, VkDescriptorPool descriptorPool, const VkAllocationCallbacks *pAllocator) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); if (!descriptorPool) return; DESCRIPTOR_POOL_STATE *desc_pool_state = GetDescriptorPoolState(device_data, descriptorPool); VK_OBJECT obj_struct = {HandleToUint64(descriptorPool), kVulkanObjectTypeDescriptorPool}; if (desc_pool_state) { // Any bound cmd buffers are now invalid InvalidateCommandBuffers(device_data, desc_pool_state->cb_bindings, obj_struct); // Free sets that were in this pool for (auto ds : desc_pool_state->sets) { FreeDescriptorSet(device_data, ds); } device_data->descriptorPoolMap.erase(descriptorPool); delete desc_pool_state; } } // 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 static bool CheckCommandBufferInFlight(layer_data *dev_data, const GLOBAL_CB_NODE *cb_node, const char *action, std::string error_code) { bool skip = false; if (cb_node->in_use.load()) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(cb_node->commandBuffer), error_code, "Attempt to %s command buffer (0x%" PRIx64 ") which is in use.", action, HandleToUint64(cb_node->commandBuffer)); } return skip; } // Iterate over all cmdBuffers in given commandPool and verify that each is not in use static bool CheckCommandBuffersInFlight(layer_data *dev_data, COMMAND_POOL_NODE *pPool, const char *action, std::string error_code) { bool skip = false; for (auto cmd_buffer : pPool->commandBuffers) { skip |= CheckCommandBufferInFlight(dev_data, GetCBNode(dev_data, cmd_buffer), action, error_code); } return skip; } // Free all command buffers in given list, removing all references/links to them using ResetCommandBufferState static void FreeCommandBufferStates(layer_data *dev_data, COMMAND_POOL_NODE *pool_state, const uint32_t command_buffer_count, const VkCommandBuffer *command_buffers) { if (GetEnables(dev_data)->gpu_validation) { GpuPreCallRecordFreeCommandBuffers(dev_data, command_buffer_count, command_buffers); } for (uint32_t i = 0; i < command_buffer_count; i++) { auto cb_state = GetCBNode(dev_data, command_buffers[i]); // Remove references to command buffer's state and delete if (cb_state) { // reset prior to delete, removing various references to it. // TODO: fix this, it's insane. ResetCommandBufferState(dev_data, cb_state->commandBuffer); // Remove the cb_state's references from layer_data and COMMAND_POOL_NODE dev_data->commandBufferMap.erase(cb_state->commandBuffer); pool_state->commandBuffers.erase(command_buffers[i]); delete cb_state; } } } bool PreCallValidateFreeCommandBuffers(VkDevice device, VkCommandPool commandPool, uint32_t commandBufferCount, const VkCommandBuffer *pCommandBuffers) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); bool skip = false; for (uint32_t i = 0; i < commandBufferCount; i++) { auto cb_node = GetCBNode(device_data, pCommandBuffers[i]); // Delete CB information structure, and remove from commandBufferMap if (cb_node) { skip |= CheckCommandBufferInFlight(device_data, cb_node, "free", "VUID-vkFreeCommandBuffers-pCommandBuffers-00047"); } } return skip; } void PreCallRecordFreeCommandBuffers(VkDevice device, VkCommandPool commandPool, uint32_t commandBufferCount, const VkCommandBuffer *pCommandBuffers) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); auto pPool = GetCommandPoolNode(device_data, commandPool); FreeCommandBufferStates(device_data, pPool, commandBufferCount, pCommandBuffers); } void PostCallRecordCreateCommandPool(VkDevice device, const VkCommandPoolCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkCommandPool *pCommandPool, VkResult result) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); if (VK_SUCCESS != result) return; device_data->commandPoolMap[*pCommandPool].createFlags = pCreateInfo->flags; device_data->commandPoolMap[*pCommandPool].queueFamilyIndex = pCreateInfo->queueFamilyIndex; } bool PreCallValidateCreateQueryPool(VkDevice device, const VkQueryPoolCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkQueryPool *pQueryPool) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); bool skip = false; if (pCreateInfo && pCreateInfo->queryType == VK_QUERY_TYPE_PIPELINE_STATISTICS) { if (!device_data->enabled_features.core.pipelineStatisticsQuery) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_QUERY_POOL_EXT, 0, "VUID-VkQueryPoolCreateInfo-queryType-00791", "Query pool with type VK_QUERY_TYPE_PIPELINE_STATISTICS created on a device with " "VkDeviceCreateInfo.pEnabledFeatures.pipelineStatisticsQuery == VK_FALSE."); } } return skip; } void PostCallRecordCreateQueryPool(VkDevice device, const VkQueryPoolCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkQueryPool *pQueryPool, VkResult result) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); if (VK_SUCCESS != result) return; QUERY_POOL_NODE *qp_node = &device_data->queryPoolMap[*pQueryPool]; qp_node->createInfo = *pCreateInfo; } bool PreCallValidateDestroyCommandPool(VkDevice device, VkCommandPool commandPool, const VkAllocationCallbacks *pAllocator) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); COMMAND_POOL_NODE *cp_state = GetCommandPoolNode(device_data, commandPool); if (device_data->instance_data->disabled.destroy_command_pool) return false; bool skip = false; if (cp_state) { // Verify that command buffers in pool are complete (not in-flight) skip |= CheckCommandBuffersInFlight(device_data, cp_state, "destroy command pool with", "VUID-vkDestroyCommandPool-commandPool-00041"); } return skip; } void PreCallRecordDestroyCommandPool(VkDevice device, VkCommandPool commandPool, const VkAllocationCallbacks *pAllocator) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); if (!commandPool) return; COMMAND_POOL_NODE *cp_state = GetCommandPoolNode(device_data, commandPool); // Remove cmdpool from cmdpoolmap, after freeing layer data for the command buffers // "When a pool is destroyed, all command buffers allocated from the pool are freed." if (cp_state) { // Create a vector, as FreeCommandBufferStates deletes from cp_state->commandBuffers during iteration. std::vector<VkCommandBuffer> cb_vec{cp_state->commandBuffers.begin(), cp_state->commandBuffers.end()}; FreeCommandBufferStates(device_data, cp_state, static_cast<uint32_t>(cb_vec.size()), cb_vec.data()); device_data->commandPoolMap.erase(commandPool); } } bool PreCallValidateResetCommandPool(layer_data *dev_data, COMMAND_POOL_NODE *pPool) { return CheckCommandBuffersInFlight(dev_data, pPool, "reset command pool with", "VUID-vkResetCommandPool-commandPool-00040"); } void PostCallRecordResetCommandPool(layer_data *dev_data, COMMAND_POOL_NODE *pPool) { for (auto cmdBuffer : pPool->commandBuffers) { ResetCommandBufferState(dev_data, cmdBuffer); } } bool PreCallValidateResetFences(layer_data *dev_data, uint32_t fenceCount, const VkFence *pFences) { bool skip = false; for (uint32_t i = 0; i < fenceCount; ++i) { auto pFence = GetFenceNode(dev_data, pFences[i]); if (pFence && pFence->scope == kSyncScopeInternal && pFence->state == FENCE_INFLIGHT) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_FENCE_EXT, HandleToUint64(pFences[i]), "VUID-vkResetFences-pFences-01123", "Fence 0x%" PRIx64 " is in use.", HandleToUint64(pFences[i])); } } return skip; } void PostCallRecordResetFences(layer_data *dev_data, uint32_t fenceCount, const VkFence *pFences) { for (uint32_t i = 0; i < fenceCount; ++i) { auto pFence = GetFenceNode(dev_data, pFences[i]); if (pFence) { if (pFence->scope == kSyncScopeInternal) { pFence->state = FENCE_UNSIGNALED; } else if (pFence->scope == kSyncScopeExternalTemporary) { pFence->scope = kSyncScopeInternal; } } } } // For given cb_nodes, invalidate them and track object causing invalidation void InvalidateCommandBuffers(const layer_data *dev_data, std::unordered_set<GLOBAL_CB_NODE *> const &cb_nodes, VK_OBJECT obj) { for (auto cb_node : cb_nodes) { if (cb_node->state == CB_RECORDING) { log_msg(dev_data->report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(cb_node->commandBuffer), kVUID_Core_DrawState_InvalidCommandBuffer, "Invalidating a command buffer that's currently being recorded: 0x%" PRIx64 ".", HandleToUint64(cb_node->commandBuffer)); cb_node->state = CB_INVALID_INCOMPLETE; } else if (cb_node->state == CB_RECORDED) { cb_node->state = CB_INVALID_COMPLETE; } cb_node->broken_bindings.push_back(obj); // if secondary, then propagate the invalidation to the primaries that will call us. if (cb_node->createInfo.level == VK_COMMAND_BUFFER_LEVEL_SECONDARY) { InvalidateCommandBuffers(dev_data, cb_node->linkedCommandBuffers, obj); } } } bool PreCallValidateDestroyFramebuffer(VkDevice device, VkFramebuffer framebuffer, const VkAllocationCallbacks *pAllocator) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); FRAMEBUFFER_STATE *framebuffer_state = GetFramebufferState(device_data, framebuffer); VK_OBJECT obj_struct = {HandleToUint64(framebuffer), kVulkanObjectTypeFramebuffer}; bool skip = false; if (framebuffer_state) { skip |= ValidateObjectNotInUse(device_data, framebuffer_state, obj_struct, "vkDestroyFramebuffer", "VUID-vkDestroyFramebuffer-framebuffer-00892"); } return skip; } void PreCallRecordDestroyFramebuffer(VkDevice device, VkFramebuffer framebuffer, const VkAllocationCallbacks *pAllocator) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); if (!framebuffer) return; FRAMEBUFFER_STATE *framebuffer_state = GetFramebufferState(device_data, framebuffer); VK_OBJECT obj_struct = {HandleToUint64(framebuffer), kVulkanObjectTypeFramebuffer}; InvalidateCommandBuffers(device_data, framebuffer_state->cb_bindings, obj_struct); device_data->frameBufferMap.erase(framebuffer); } bool PreCallValidateDestroyRenderPass(VkDevice device, VkRenderPass renderPass, const VkAllocationCallbacks *pAllocator) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); RENDER_PASS_STATE *rp_state = GetRenderPassState(device_data, renderPass); VK_OBJECT obj_struct = {HandleToUint64(renderPass), kVulkanObjectTypeRenderPass}; bool skip = false; if (rp_state) { skip |= ValidateObjectNotInUse(device_data, rp_state, obj_struct, "vkDestroyRenderPass", "VUID-vkDestroyRenderPass-renderPass-00873"); } return skip; } void PreCallRecordDestroyRenderPass(VkDevice device, VkRenderPass renderPass, const VkAllocationCallbacks *pAllocator) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); if (!renderPass) return; RENDER_PASS_STATE *rp_state = GetRenderPassState(device_data, renderPass); VK_OBJECT obj_struct = {HandleToUint64(renderPass), kVulkanObjectTypeRenderPass}; InvalidateCommandBuffers(device_data, rp_state->cb_bindings, obj_struct); device_data->renderPassMap.erase(renderPass); } // Access helper functions for external modules VkFormatProperties GetPDFormatProperties(const core_validation::layer_data *device_data, const VkFormat format) { VkFormatProperties format_properties; instance_layer_data *instance_data = GetLayerDataPtr(get_dispatch_key(device_data->instance_data->instance), instance_layer_data_map); instance_data->dispatch_table.GetPhysicalDeviceFormatProperties(device_data->physical_device, format, &format_properties); return format_properties; } VkResult GetPDImageFormatProperties(core_validation::layer_data *device_data, const VkImageCreateInfo *image_ci, VkImageFormatProperties *pImageFormatProperties) { instance_layer_data *instance_data = GetLayerDataPtr(get_dispatch_key(device_data->instance_data->instance), instance_layer_data_map); return instance_data->dispatch_table.GetPhysicalDeviceImageFormatProperties( device_data->physical_device, image_ci->format, image_ci->imageType, image_ci->tiling, image_ci->usage, image_ci->flags, pImageFormatProperties); } VkResult GetPDImageFormatProperties2(core_validation::layer_data *device_data, const VkPhysicalDeviceImageFormatInfo2 *phys_dev_image_fmt_info, VkImageFormatProperties2 *pImageFormatProperties) { if (!device_data->instance_data->extensions.vk_khr_get_physical_device_properties_2) return VK_ERROR_EXTENSION_NOT_PRESENT; instance_layer_data *instance_data = GetLayerDataPtr(get_dispatch_key(device_data->instance_data->instance), instance_layer_data_map); return instance_data->dispatch_table.GetPhysicalDeviceImageFormatProperties2(device_data->physical_device, phys_dev_image_fmt_info, pImageFormatProperties); } const debug_report_data *GetReportData(const core_validation::layer_data *device_data) { return device_data->report_data; } const VkLayerDispatchTable *GetDispatchTable(const core_validation::layer_data *device_data) { return &device_data->dispatch_table; } const VkPhysicalDeviceProperties *GetPDProperties(const core_validation::layer_data *device_data) { return &device_data->phys_dev_props; } const VkPhysicalDeviceMemoryProperties *GetPhysicalDeviceMemoryProperties(const core_validation::layer_data *device_data) { return &device_data->phys_dev_mem_props; } const CHECK_DISABLED *GetDisables(core_validation::layer_data *device_data) { return &device_data->instance_data->disabled; } const CHECK_ENABLED *GetEnables(core_validation::layer_data *device_data) { return &device_data->instance_data->enabled; } std::unordered_map<VkImage, std::unique_ptr<IMAGE_STATE>> *GetImageMap(core_validation::layer_data *device_data) { return &device_data->imageMap; } std::unordered_map<VkImage, std::vector<ImageSubresourcePair>> *GetImageSubresourceMap(core_validation::layer_data *device_data) { return &device_data->imageSubresourceMap; } std::unordered_map<ImageSubresourcePair, IMAGE_LAYOUT_NODE> *GetImageLayoutMap(layer_data *device_data) { return &device_data->imageLayoutMap; } std::unordered_map<ImageSubresourcePair, IMAGE_LAYOUT_NODE> const *GetImageLayoutMap(layer_data const *device_data) { return &device_data->imageLayoutMap; } std::unordered_map<VkBuffer, std::unique_ptr<BUFFER_STATE>> *GetBufferMap(layer_data *device_data) { return &device_data->bufferMap; } std::unordered_map<VkBufferView, std::unique_ptr<BUFFER_VIEW_STATE>> *GetBufferViewMap(layer_data *device_data) { return &device_data->bufferViewMap; } std::unordered_map<VkImageView, std::unique_ptr<IMAGE_VIEW_STATE>> *GetImageViewMap(layer_data *device_data) { return &device_data->imageViewMap; } const PHYS_DEV_PROPERTIES_NODE *GetPhysDevProperties(const layer_data *device_data) { return &device_data->phys_dev_properties; } const DeviceFeatures *GetEnabledFeatures(const layer_data *device_data) { return &device_data->enabled_features; } const DeviceExtensions *GetDeviceExtensions(const layer_data *device_data) { return &device_data->extensions; } GpuValidationState *GetGpuValidationState(layer_data *device_data) { return &device_data->gpu_validation_state; } const GpuValidationState *GetGpuValidationState(const layer_data *device_data) { return &device_data->gpu_validation_state; } VkDevice GetDevice(const layer_data *device_data) { return device_data->device; } uint32_t GetApiVersion(const layer_data *device_data) { return device_data->api_version; } void PostCallRecordCreateFence(VkDevice device, const VkFenceCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkFence *pFence, VkResult result) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); if (VK_SUCCESS != result) return; auto &fence_node = device_data->fenceMap[*pFence]; fence_node.fence = *pFence; fence_node.createInfo = *pCreateInfo; fence_node.state = (pCreateInfo->flags & VK_FENCE_CREATE_SIGNALED_BIT) ? FENCE_RETIRED : FENCE_UNSIGNALED; } // Validation cache: // CV is the bottommost implementor of this extension. Don't pass calls down. // utility function to set collective state for pipeline void SetPipelineState(PIPELINE_STATE *pPipe) { // If any attachment used by this pipeline has blendEnable, set top-level blendEnable if (pPipe->graphicsPipelineCI.pColorBlendState) { for (size_t i = 0; i < pPipe->attachments.size(); ++i) { if (VK_TRUE == pPipe->attachments[i].blendEnable) { if (((pPipe->attachments[i].dstAlphaBlendFactor >= VK_BLEND_FACTOR_CONSTANT_COLOR) && (pPipe->attachments[i].dstAlphaBlendFactor <= VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA)) || ((pPipe->attachments[i].dstColorBlendFactor >= VK_BLEND_FACTOR_CONSTANT_COLOR) && (pPipe->attachments[i].dstColorBlendFactor <= VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA)) || ((pPipe->attachments[i].srcAlphaBlendFactor >= VK_BLEND_FACTOR_CONSTANT_COLOR) && (pPipe->attachments[i].srcAlphaBlendFactor <= VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA)) || ((pPipe->attachments[i].srcColorBlendFactor >= VK_BLEND_FACTOR_CONSTANT_COLOR) && (pPipe->attachments[i].srcColorBlendFactor <= VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA))) { pPipe->blendConstantsEnabled = true; } } } } } static bool ValidatePipelineVertexDivisors(layer_data *dev_data, vector<std::unique_ptr<PIPELINE_STATE>> const &pipe_state_vec, const uint32_t count, const VkGraphicsPipelineCreateInfo *pipe_cis) { bool skip = false; const VkPhysicalDeviceLimits *device_limits = &(GetPDProperties(dev_data)->limits); for (uint32_t i = 0; i < count; i++) { auto pvids_ci = lvl_find_in_chain<VkPipelineVertexInputDivisorStateCreateInfoEXT>(pipe_cis[i].pVertexInputState->pNext); 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 |= log_msg( dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, HandleToUint64(pipe_state->pipeline), "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 > dev_data->phys_dev_ext_props.vtx_attrib_divisor_props.maxVertexAttribDivisor) { skip |= log_msg( dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, HandleToUint64(pipe_state->pipeline), "VUID-VkVertexInputBindingDivisorDescriptionEXT-divisor-01870", "vkCreateGraphicsPipelines(): Pipeline[%1u] with chained VkPipelineVertexInputDivisorStateCreateInfoEXT, " "pVertexBindingDivisors[%1u] divisor of (%1u) exceeds extension maxVertexAttribDivisor (%1u).", i, j, vibdd->divisor, dev_data->phys_dev_ext_props.vtx_attrib_divisor_props.maxVertexAttribDivisor); } if ((0 == vibdd->divisor) && !dev_data->enabled_features.vtx_attrib_divisor_features.vertexAttributeInstanceRateZeroDivisor) { skip |= log_msg( dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, HandleToUint64(pipe_state->pipeline), "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) && !dev_data->enabled_features.vtx_attrib_divisor_features.vertexAttributeInstanceRateDivisor) { skip |= log_msg( dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, HandleToUint64(pipe_state->pipeline), "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 |= log_msg( dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_EXT, HandleToUint64(pipe_state->pipeline), "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 PreCallValidateCreateGraphicsPipelines(layer_data *dev_data, vector<std::unique_ptr<PIPELINE_STATE>> *pipe_state, const uint32_t count, const VkGraphicsPipelineCreateInfo *pCreateInfos) { bool skip = false; pipe_state->reserve(count); // TODO - State changes and validation need to be untangled here for (uint32_t i = 0; i < count; i++) { pipe_state->push_back(std::unique_ptr<PIPELINE_STATE>(new PIPELINE_STATE)); (*pipe_state)[i]->initGraphicsPipeline(&pCreateInfos[i], GetRenderPassStateSharedPtr(dev_data, pCreateInfos[i].renderPass)); (*pipe_state)[i]->pipeline_layout = *GetPipelineLayout(dev_data, pCreateInfos[i].layout); } for (uint32_t i = 0; i < count; i++) { skip |= ValidatePipelineLocked(dev_data, *pipe_state, i); } for (uint32_t i = 0; i < count; i++) { skip |= ValidatePipelineUnlocked(dev_data, *pipe_state, i); } if (dev_data->extensions.vk_ext_vertex_attribute_divisor) { skip |= ValidatePipelineVertexDivisors(dev_data, *pipe_state, count, pCreateInfos); } return skip; } void PostCallRecordCreateGraphicsPipelines(layer_data *dev_data, vector<std::unique_ptr<PIPELINE_STATE>> *pipe_state, const uint32_t count, const VkGraphicsPipelineCreateInfo *pCreateInfos, const VkAllocationCallbacks *pAllocator, VkPipeline *pPipelines) { for (uint32_t i = 0; i < count; i++) { if (pPipelines[i] != VK_NULL_HANDLE) { (*pipe_state)[i]->pipeline = pPipelines[i]; dev_data->pipelineMap[pPipelines[i]] = std::move((*pipe_state)[i]); } } if (GetEnables(dev_data)->gpu_validation) { GpuPostCallRecordCreateGraphicsPipelines(dev_data, count, pCreateInfos, pAllocator, pPipelines); } } bool PreCallValidateCreateComputePipelines(layer_data *dev_data, vector<std::unique_ptr<PIPELINE_STATE>> *pipe_state, const uint32_t count, const VkComputePipelineCreateInfo *pCreateInfos) { bool skip = false; pipe_state->reserve(count); for (uint32_t i = 0; i < count; i++) { // Create and initialize internal tracking data structure pipe_state->push_back(unique_ptr<PIPELINE_STATE>(new PIPELINE_STATE)); (*pipe_state)[i]->initComputePipeline(&pCreateInfos[i]); (*pipe_state)[i]->pipeline_layout = *GetPipelineLayout(dev_data, pCreateInfos[i].layout); // TODO: Add Compute Pipeline Verification skip |= ValidateComputePipeline(dev_data, (*pipe_state)[i].get()); } return skip; } void PostCallRecordCreateComputePipelines(layer_data *dev_data, vector<std::unique_ptr<PIPELINE_STATE>> *pipe_state, const uint32_t count, VkPipeline *pPipelines) { for (uint32_t i = 0; i < count; i++) { if (pPipelines[i] != VK_NULL_HANDLE) { (*pipe_state)[i]->pipeline = pPipelines[i]; dev_data->pipelineMap[pPipelines[i]] = std::move((*pipe_state)[i]); } } } bool PreCallValidateCreateRayTracingPipelinesNV(layer_data *dev_data, uint32_t count, const VkRayTracingPipelineCreateInfoNV *pCreateInfos, vector<std::unique_ptr<PIPELINE_STATE>> &pipe_state) { bool skip = false; // The order of operations here is a little convoluted but gets the job done // 1. Pipeline create state is first shadowed into PIPELINE_STATE struct // 2. Create state is then validated (which uses flags setup during shadowing) // 3. If everything looks good, we'll then create the pipeline and add NODE to pipelineMap uint32_t i = 0; for (i = 0; i < count; i++) { pipe_state.push_back(std::unique_ptr<PIPELINE_STATE>(new PIPELINE_STATE)); pipe_state[i]->initRayTracingPipelineNV(&pCreateInfos[i]); pipe_state[i]->pipeline_layout = *GetPipelineLayout(dev_data, pCreateInfos[i].layout); } for (i = 0; i < count; i++) { skip |= ValidateRayTracingPipelineNV(dev_data, pipe_state[i].get()); } return skip; } void PostCallRecordCreateRayTracingPipelinesNV(layer_data *dev_data, uint32_t count, vector<std::unique_ptr<PIPELINE_STATE>> &pipe_state, VkPipeline *pPipelines) { for (uint32_t i = 0; i < count; i++) { if (pPipelines[i] != VK_NULL_HANDLE) { pipe_state[i]->pipeline = pPipelines[i]; dev_data->pipelineMap[pPipelines[i]] = std::move(pipe_state[i]); } } } void PostCallRecordCreateSampler(VkDevice device, const VkSamplerCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkSampler *pSampler, VkResult result) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); device_data->samplerMap[*pSampler] = unique_ptr<SAMPLER_STATE>(new SAMPLER_STATE(pSampler, pCreateInfo)); } bool PreCallValidateCreateDescriptorSetLayout(VkDevice device, const VkDescriptorSetLayoutCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkDescriptorSetLayout *pSetLayout) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); if (device_data->instance_data->disabled.create_descriptor_set_layout) return false; return cvdescriptorset::DescriptorSetLayout::ValidateCreateInfo( device_data->report_data, pCreateInfo, device_data->extensions.vk_khr_push_descriptor, device_data->phys_dev_ext_props.max_push_descriptors, device_data->extensions.vk_ext_descriptor_indexing, &device_data->enabled_features.descriptor_indexing, &device_data->enabled_features.inline_uniform_block, &device_data->phys_dev_ext_props.inline_uniform_block_props); } void PostCallRecordCreateDescriptorSetLayout(VkDevice device, const VkDescriptorSetLayoutCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkDescriptorSetLayout *pSetLayout, VkResult result) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); if (VK_SUCCESS != result) return; device_data->descriptorSetLayoutMap[*pSetLayout] = std::make_shared<cvdescriptorset::DescriptorSetLayout>(pCreateInfo, *pSetLayout); } // Used by CreatePipelineLayout and CmdPushConstants. // Note that the index argument is optional and only used by CreatePipelineLayout. static bool ValidatePushConstantRange(const layer_data *dev_data, const uint32_t offset, const uint32_t size, const char *caller_name, uint32_t index = 0) { if (dev_data->instance_data->disabled.push_constant_range) return false; uint32_t const maxPushConstantsSize = dev_data->phys_dev_properties.properties.limits.maxPushConstantsSize; bool skip = false; // Check that offset + size don't exceed the max. // Prevent arithetic overflow here by avoiding addition and testing in this order. if ((offset >= maxPushConstantsSize) || (size > maxPushConstantsSize - offset)) { // This is a pain just to adapt the log message to the caller, but better to sort it out only when there is a problem. if (0 == strcmp(caller_name, "vkCreatePipelineLayout()")) { if (offset >= maxPushConstantsSize) { skip |= log_msg( dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkPushConstantRange-offset-00294", "%s call has push constants index %u with offset %u that exceeds this device's maxPushConstantSize of %u.", caller_name, index, offset, maxPushConstantsSize); } if (size > maxPushConstantsSize - offset) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkPushConstantRange-size-00298", "%s call has push constants index %u with offset %u and size %u that exceeds this device's " "maxPushConstantSize of %u.", caller_name, index, offset, size, maxPushConstantsSize); } } else if (0 == strcmp(caller_name, "vkCmdPushConstants()")) { if (offset >= maxPushConstantsSize) { skip |= log_msg( dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-vkCmdPushConstants-offset-00370", "%s call has push constants index %u with offset %u that exceeds this device's maxPushConstantSize of %u.", caller_name, index, offset, maxPushConstantsSize); } if (size > maxPushConstantsSize - offset) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-vkCmdPushConstants-size-00371", "%s call has push constants index %u with offset %u and size %u that exceeds this device's " "maxPushConstantSize of %u.", caller_name, index, offset, size, maxPushConstantsSize); } } else { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, kVUID_Core_DrawState_InternalError, "%s caller not supported.", caller_name); } } // size needs to be non-zero and a multiple of 4. if ((size == 0) || ((size & 0x3) != 0)) { if (0 == strcmp(caller_name, "vkCreatePipelineLayout()")) { if (size == 0) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkPushConstantRange-size-00296", "%s call has push constants index %u with size %u. Size must be greater than zero.", caller_name, index, size); } if (size & 0x3) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkPushConstantRange-size-00297", "%s call has push constants index %u with size %u. Size must be a multiple of 4.", caller_name, index, size); } } else if (0 == strcmp(caller_name, "vkCmdPushConstants()")) { if (size == 0) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-vkCmdPushConstants-size-arraylength", "%s call has push constants index %u with size %u. Size must be greater than zero.", caller_name, index, size); } if (size & 0x3) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-vkCmdPushConstants-size-00369", "%s call has push constants index %u with size %u. Size must be a multiple of 4.", caller_name, index, size); } } else { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, kVUID_Core_DrawState_InternalError, "%s caller not supported.", caller_name); } } // offset needs to be a multiple of 4. if ((offset & 0x3) != 0) { if (0 == strcmp(caller_name, "vkCreatePipelineLayout()")) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkPushConstantRange-offset-00295", "%s call has push constants index %u with offset %u. Offset must be a multiple of 4.", caller_name, index, offset); } else if (0 == strcmp(caller_name, "vkCmdPushConstants()")) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-vkCmdPushConstants-offset-00368", "%s call has push constants with offset %u. Offset must be a multiple of 4.", caller_name, offset); } else { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, kVUID_Core_DrawState_InternalError, "%s caller not supported.", caller_name); } } return skip; } 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 layer_data *dev_data, 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 (dev_data->enabled_features.core.geometryShader) { stage_flags.push_back(VK_SHADER_STAGE_GEOMETRY_BIT); } if (dev_data->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 (auto dsl : set_layouts) { if (skip_update_after_bind && (dsl->GetCreateFlags() & VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT_EXT)) { 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 layer_data *dev_data, 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 (auto dsl : set_layouts) { if (skip_update_after_bind && (dsl->GetCreateFlags() & VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT_EXT)) { 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 PreCallValidateCreatePipelineLayout(const layer_data *dev_data, const VkPipelineLayoutCreateInfo *pCreateInfo) { bool skip = false; // Validate layout count against device physical limit if (pCreateInfo->setLayoutCount > dev_data->phys_dev_props.limits.maxBoundDescriptorSets) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkPipelineLayoutCreateInfo-setLayoutCount-00286", "vkCreatePipelineLayout(): setLayoutCount (%d) exceeds physical device maxBoundDescriptorSets limit (%d).", pCreateInfo->setLayoutCount, dev_data->phys_dev_props.limits.maxBoundDescriptorSets); } // Validate Push Constant ranges uint32_t i, j; for (i = 0; i < pCreateInfo->pushConstantRangeCount; ++i) { skip |= ValidatePushConstantRange(dev_data, pCreateInfo->pPushConstantRanges[i].offset, pCreateInfo->pPushConstantRanges[i].size, "vkCreatePipelineLayout()", i); if (0 == pCreateInfo->pPushConstantRanges[i].stageFlags) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkPushConstantRange-stageFlags-requiredbitmask", "vkCreatePipelineLayout() call has no stageFlags set."); } } // As of 1.0.28, there is a VU that states that a stage flag cannot appear more than once in the list of push constant ranges. for (i = 0; i < pCreateInfo->pushConstantRangeCount; ++i) { for (j = i + 1; j < pCreateInfo->pushConstantRangeCount; ++j) { if (0 != (pCreateInfo->pPushConstantRanges[i].stageFlags & pCreateInfo->pPushConstantRanges[j].stageFlags)) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkPipelineLayoutCreateInfo-pPushConstantRanges-00292", "vkCreatePipelineLayout() Duplicate stage flags found in ranges %d and %d.", i, j); } } } // Early-out if (skip) return skip; std::vector<std::shared_ptr<cvdescriptorset::DescriptorSetLayout const>> set_layouts(pCreateInfo->setLayoutCount, nullptr); unsigned int push_descriptor_set_count = 0; { unique_lock_t lock(global_lock); // Lock while accessing global state for (i = 0; i < pCreateInfo->setLayoutCount; ++i) { set_layouts[i] = GetDescriptorSetLayout(dev_data, pCreateInfo->pSetLayouts[i]); if (set_layouts[i]->IsPushDescriptor()) ++push_descriptor_set_count; } } // Unlock if (push_descriptor_set_count > 1) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "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(dev_data, set_layouts, true); // Samplers if (max_descriptors_per_stage[DSL_TYPE_SAMPLERS] > dev_data->phys_dev_props.limits.maxPerStageDescriptorSamplers) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkPipelineLayoutCreateInfo-pSetLayouts-00287", "vkCreatePipelineLayout(): max per-stage sampler bindings count (%d) exceeds device " "maxPerStageDescriptorSamplers limit (%d).", max_descriptors_per_stage[DSL_TYPE_SAMPLERS], dev_data->phys_dev_props.limits.maxPerStageDescriptorSamplers); } // Uniform buffers if (max_descriptors_per_stage[DSL_TYPE_UNIFORM_BUFFERS] > dev_data->phys_dev_props.limits.maxPerStageDescriptorUniformBuffers) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkPipelineLayoutCreateInfo-pSetLayouts-00288", "vkCreatePipelineLayout(): max per-stage uniform buffer bindings count (%d) exceeds device " "maxPerStageDescriptorUniformBuffers limit (%d).", max_descriptors_per_stage[DSL_TYPE_UNIFORM_BUFFERS], dev_data->phys_dev_props.limits.maxPerStageDescriptorUniformBuffers); } // Storage buffers if (max_descriptors_per_stage[DSL_TYPE_STORAGE_BUFFERS] > dev_data->phys_dev_props.limits.maxPerStageDescriptorStorageBuffers) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkPipelineLayoutCreateInfo-pSetLayouts-00289", "vkCreatePipelineLayout(): max per-stage storage buffer bindings count (%d) exceeds device " "maxPerStageDescriptorStorageBuffers limit (%d).", max_descriptors_per_stage[DSL_TYPE_STORAGE_BUFFERS], dev_data->phys_dev_props.limits.maxPerStageDescriptorStorageBuffers); } // Sampled images if (max_descriptors_per_stage[DSL_TYPE_SAMPLED_IMAGES] > dev_data->phys_dev_props.limits.maxPerStageDescriptorSampledImages) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkPipelineLayoutCreateInfo-pSetLayouts-00290", "vkCreatePipelineLayout(): max per-stage sampled image bindings count (%d) exceeds device " "maxPerStageDescriptorSampledImages limit (%d).", max_descriptors_per_stage[DSL_TYPE_SAMPLED_IMAGES], dev_data->phys_dev_props.limits.maxPerStageDescriptorSampledImages); } // Storage images if (max_descriptors_per_stage[DSL_TYPE_STORAGE_IMAGES] > dev_data->phys_dev_props.limits.maxPerStageDescriptorStorageImages) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkPipelineLayoutCreateInfo-pSetLayouts-00291", "vkCreatePipelineLayout(): max per-stage storage image bindings count (%d) exceeds device " "maxPerStageDescriptorStorageImages limit (%d).", max_descriptors_per_stage[DSL_TYPE_STORAGE_IMAGES], dev_data->phys_dev_props.limits.maxPerStageDescriptorStorageImages); } // Input attachments if (max_descriptors_per_stage[DSL_TYPE_INPUT_ATTACHMENTS] > dev_data->phys_dev_props.limits.maxPerStageDescriptorInputAttachments) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkPipelineLayoutCreateInfo-pSetLayouts-01676", "vkCreatePipelineLayout(): max per-stage input attachment bindings count (%d) exceeds device " "maxPerStageDescriptorInputAttachments limit (%d).", max_descriptors_per_stage[DSL_TYPE_INPUT_ATTACHMENTS], dev_data->phys_dev_props.limits.maxPerStageDescriptorInputAttachments); } // Inline uniform blocks if (max_descriptors_per_stage[DSL_TYPE_INLINE_UNIFORM_BLOCK] > dev_data->phys_dev_ext_props.inline_uniform_block_props.maxPerStageDescriptorInlineUniformBlocks) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkPipelineLayoutCreateInfo-descriptorType-02214", "vkCreatePipelineLayout(): max per-stage inline uniform block bindings count (%d) exceeds device " "maxPerStageDescriptorInlineUniformBlocks limit (%d).", max_descriptors_per_stage[DSL_TYPE_INLINE_UNIFORM_BLOCK], dev_data->phys_dev_ext_props.inline_uniform_block_props.maxPerStageDescriptorInlineUniformBlocks); } // Total descriptors by type // std::map<uint32_t, uint32_t> sum_all_stages = GetDescriptorSum(dev_data, 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 > dev_data->phys_dev_props.limits.maxDescriptorSetSamplers) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkPipelineLayoutCreateInfo-pSetLayouts-01677", "vkCreatePipelineLayout(): sum of sampler bindings among all stages (%d) exceeds device " "maxDescriptorSetSamplers limit (%d).", sum, dev_data->phys_dev_props.limits.maxDescriptorSetSamplers); } // Uniform buffers if (sum_all_stages[VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER] > dev_data->phys_dev_props.limits.maxDescriptorSetUniformBuffers) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkPipelineLayoutCreateInfo-pSetLayouts-01678", "vkCreatePipelineLayout(): sum of uniform buffer bindings among all stages (%d) exceeds device " "maxDescriptorSetUniformBuffers limit (%d).", sum_all_stages[VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER], dev_data->phys_dev_props.limits.maxDescriptorSetUniformBuffers); } // Dynamic uniform buffers if (sum_all_stages[VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC] > dev_data->phys_dev_props.limits.maxDescriptorSetUniformBuffersDynamic) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkPipelineLayoutCreateInfo-pSetLayouts-01679", "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], dev_data->phys_dev_props.limits.maxDescriptorSetUniformBuffersDynamic); } // Storage buffers if (sum_all_stages[VK_DESCRIPTOR_TYPE_STORAGE_BUFFER] > dev_data->phys_dev_props.limits.maxDescriptorSetStorageBuffers) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkPipelineLayoutCreateInfo-pSetLayouts-01680", "vkCreatePipelineLayout(): sum of storage buffer bindings among all stages (%d) exceeds device " "maxDescriptorSetStorageBuffers limit (%d).", sum_all_stages[VK_DESCRIPTOR_TYPE_STORAGE_BUFFER], dev_data->phys_dev_props.limits.maxDescriptorSetStorageBuffers); } // Dynamic storage buffers if (sum_all_stages[VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC] > dev_data->phys_dev_props.limits.maxDescriptorSetStorageBuffersDynamic) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkPipelineLayoutCreateInfo-pSetLayouts-01681", "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], dev_data->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 > dev_data->phys_dev_props.limits.maxDescriptorSetSampledImages) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkPipelineLayoutCreateInfo-pSetLayouts-01682", "vkCreatePipelineLayout(): sum of sampled image bindings among all stages (%d) exceeds device " "maxDescriptorSetSampledImages limit (%d).", sum, dev_data->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 > dev_data->phys_dev_props.limits.maxDescriptorSetStorageImages) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkPipelineLayoutCreateInfo-pSetLayouts-01683", "vkCreatePipelineLayout(): sum of storage image bindings among all stages (%d) exceeds device " "maxDescriptorSetStorageImages limit (%d).", sum, dev_data->phys_dev_props.limits.maxDescriptorSetStorageImages); } // Input attachments if (sum_all_stages[VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT] > dev_data->phys_dev_props.limits.maxDescriptorSetInputAttachments) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkPipelineLayoutCreateInfo-pSetLayouts-01684", "vkCreatePipelineLayout(): sum of input attachment bindings among all stages (%d) exceeds device " "maxDescriptorSetInputAttachments limit (%d).", sum_all_stages[VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT], dev_data->phys_dev_props.limits.maxDescriptorSetInputAttachments); } // Inline uniform blocks if (sum_all_stages[VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT] > dev_data->phys_dev_ext_props.inline_uniform_block_props.maxDescriptorSetInlineUniformBlocks) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkPipelineLayoutCreateInfo-descriptorType-02216", "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], dev_data->phys_dev_ext_props.inline_uniform_block_props.maxDescriptorSetInlineUniformBlocks); } if (dev_data->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(dev_data, set_layouts, false); // Samplers if (max_descriptors_per_stage_update_after_bind[DSL_TYPE_SAMPLERS] > dev_data->phys_dev_ext_props.descriptor_indexing_props.maxPerStageDescriptorUpdateAfterBindSamplers) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "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], dev_data->phys_dev_ext_props.descriptor_indexing_props.maxPerStageDescriptorUpdateAfterBindSamplers); } // Uniform buffers if (max_descriptors_per_stage_update_after_bind[DSL_TYPE_UNIFORM_BUFFERS] > dev_data->phys_dev_ext_props.descriptor_indexing_props.maxPerStageDescriptorUpdateAfterBindUniformBuffers) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "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], dev_data->phys_dev_ext_props.descriptor_indexing_props.maxPerStageDescriptorUpdateAfterBindUniformBuffers); } // Storage buffers if (max_descriptors_per_stage_update_after_bind[DSL_TYPE_STORAGE_BUFFERS] > dev_data->phys_dev_ext_props.descriptor_indexing_props.maxPerStageDescriptorUpdateAfterBindStorageBuffers) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "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], dev_data->phys_dev_ext_props.descriptor_indexing_props.maxPerStageDescriptorUpdateAfterBindStorageBuffers); } // Sampled images if (max_descriptors_per_stage_update_after_bind[DSL_TYPE_SAMPLED_IMAGES] > dev_data->phys_dev_ext_props.descriptor_indexing_props.maxPerStageDescriptorUpdateAfterBindSampledImages) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "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], dev_data->phys_dev_ext_props.descriptor_indexing_props.maxPerStageDescriptorUpdateAfterBindSampledImages); } // Storage images if (max_descriptors_per_stage_update_after_bind[DSL_TYPE_STORAGE_IMAGES] > dev_data->phys_dev_ext_props.descriptor_indexing_props.maxPerStageDescriptorUpdateAfterBindStorageImages) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "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], dev_data->phys_dev_ext_props.descriptor_indexing_props.maxPerStageDescriptorUpdateAfterBindStorageImages); } // Input attachments if (max_descriptors_per_stage_update_after_bind[DSL_TYPE_INPUT_ATTACHMENTS] > dev_data->phys_dev_ext_props.descriptor_indexing_props.maxPerStageDescriptorUpdateAfterBindInputAttachments) { skip |= log_msg( dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "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], dev_data->phys_dev_ext_props.descriptor_indexing_props.maxPerStageDescriptorUpdateAfterBindInputAttachments); } // Inline uniform blocks if (max_descriptors_per_stage_update_after_bind[DSL_TYPE_INLINE_UNIFORM_BLOCK] > dev_data->phys_dev_ext_props.inline_uniform_block_props.maxPerStageDescriptorUpdateAfterBindInlineUniformBlocks) { skip |= log_msg( dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "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], dev_data->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(dev_data, 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 > dev_data->phys_dev_ext_props.descriptor_indexing_props.maxDescriptorSetUpdateAfterBindSamplers) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkPipelineLayoutCreateInfo-pSetLayouts-03036", "vkCreatePipelineLayout(): sum of sampler bindings among all stages (%d) exceeds device " "maxDescriptorSetUpdateAfterBindSamplers limit (%d).", sum, dev_data->phys_dev_ext_props.descriptor_indexing_props.maxDescriptorSetUpdateAfterBindSamplers); } // Uniform buffers if (sum_all_stages_update_after_bind[VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER] > dev_data->phys_dev_ext_props.descriptor_indexing_props.maxDescriptorSetUpdateAfterBindUniformBuffers) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "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], dev_data->phys_dev_ext_props.descriptor_indexing_props.maxDescriptorSetUpdateAfterBindUniformBuffers); } // Dynamic uniform buffers if (sum_all_stages_update_after_bind[VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC] > dev_data->phys_dev_ext_props.descriptor_indexing_props.maxDescriptorSetUpdateAfterBindUniformBuffersDynamic) { skip |= log_msg( dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "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], dev_data->phys_dev_ext_props.descriptor_indexing_props.maxDescriptorSetUpdateAfterBindUniformBuffersDynamic); } // Storage buffers if (sum_all_stages_update_after_bind[VK_DESCRIPTOR_TYPE_STORAGE_BUFFER] > dev_data->phys_dev_ext_props.descriptor_indexing_props.maxDescriptorSetUpdateAfterBindStorageBuffers) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "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], dev_data->phys_dev_ext_props.descriptor_indexing_props.maxDescriptorSetUpdateAfterBindStorageBuffers); } // Dynamic storage buffers if (sum_all_stages_update_after_bind[VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC] > dev_data->phys_dev_ext_props.descriptor_indexing_props.maxDescriptorSetUpdateAfterBindStorageBuffersDynamic) { skip |= log_msg( dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "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], dev_data->phys_dev_ext_props.descriptor_indexing_props.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 > dev_data->phys_dev_ext_props.descriptor_indexing_props.maxDescriptorSetUpdateAfterBindSampledImages) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkPipelineLayoutCreateInfo-pSetLayouts-03041", "vkCreatePipelineLayout(): sum of sampled image bindings among all stages (%d) exceeds device " "maxDescriptorSetUpdateAfterBindSampledImages limit (%d).", sum, dev_data->phys_dev_ext_props.descriptor_indexing_props.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 > dev_data->phys_dev_ext_props.descriptor_indexing_props.maxDescriptorSetUpdateAfterBindStorageImages) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkPipelineLayoutCreateInfo-pSetLayouts-03042", "vkCreatePipelineLayout(): sum of storage image bindings among all stages (%d) exceeds device " "maxDescriptorSetUpdateAfterBindStorageImages limit (%d).", sum, dev_data->phys_dev_ext_props.descriptor_indexing_props.maxDescriptorSetUpdateAfterBindStorageImages); } // Input attachments if (sum_all_stages_update_after_bind[VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT] > dev_data->phys_dev_ext_props.descriptor_indexing_props.maxDescriptorSetUpdateAfterBindInputAttachments) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "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], dev_data->phys_dev_ext_props.descriptor_indexing_props.maxDescriptorSetUpdateAfterBindInputAttachments); } // Inline uniform blocks if (sum_all_stages_update_after_bind[VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT] > dev_data->phys_dev_ext_props.inline_uniform_block_props.maxDescriptorSetUpdateAfterBindInlineUniformBlocks) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "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], dev_data->phys_dev_ext_props.inline_uniform_block_props.maxDescriptorSetUpdateAfterBindInlineUniformBlocks); } } return skip; } // For repeatable sorting, not very useful for "memory in range" search struct PushConstantRangeCompare { bool operator()(const VkPushConstantRange *lhs, const VkPushConstantRange *rhs) const { if (lhs->offset == rhs->offset) { if (lhs->size == rhs->size) { // The comparison is arbitrary, but avoids false aliasing by comparing all fields. return lhs->stageFlags < rhs->stageFlags; } // If the offsets are the same then sorting by the end of range is useful for validation return lhs->size < rhs->size; } return lhs->offset < rhs->offset; } }; static PushConstantRangesDict push_constant_ranges_dict; PushConstantRangesId GetCanonicalId(const VkPipelineLayoutCreateInfo *info) { if (!info->pPushConstantRanges) { // Hand back the empty entry (creating as needed)... return push_constant_ranges_dict.look_up(PushConstantRanges()); } // Sort the input ranges to ensure equivalent ranges map to the same id std::set<const VkPushConstantRange *, PushConstantRangeCompare> sorted; for (uint32_t i = 0; i < info->pushConstantRangeCount; i++) { sorted.insert(info->pPushConstantRanges + i); } PushConstantRanges ranges(sorted.size()); for (const auto range : sorted) { ranges.emplace_back(*range); } return push_constant_ranges_dict.look_up(std::move(ranges)); } // Dictionary of canoncial form of the pipeline set layout of descriptor set layouts static PipelineLayoutSetLayoutsDict pipeline_layout_set_layouts_dict; // Dictionary of canonical form of the "compatible for set" records static PipelineLayoutCompatDict pipeline_layout_compat_dict; static PipelineLayoutCompatId GetCanonicalId(const uint32_t set_index, const PushConstantRangesId pcr_id, const PipelineLayoutSetLayoutsId set_layouts_id) { return pipeline_layout_compat_dict.look_up(PipelineLayoutCompatDef(set_index, pcr_id, set_layouts_id)); } void PostCallRecordCreatePipelineLayout(layer_data *dev_data, const VkPipelineLayoutCreateInfo *pCreateInfo, const VkPipelineLayout *pPipelineLayout) { unique_lock_t lock(global_lock); // Lock while accessing state PIPELINE_LAYOUT_NODE &plNode = dev_data->pipelineLayoutMap[*pPipelineLayout]; plNode.layout = *pPipelineLayout; plNode.set_layouts.resize(pCreateInfo->setLayoutCount); PipelineLayoutSetLayoutsDef set_layouts(pCreateInfo->setLayoutCount); for (uint32_t i = 0; i < pCreateInfo->setLayoutCount; ++i) { plNode.set_layouts[i] = GetDescriptorSetLayout(dev_data, pCreateInfo->pSetLayouts[i]); set_layouts[i] = plNode.set_layouts[i]->GetLayoutId(); } // Get canonical form IDs for the "compatible for set" contents plNode.push_constant_ranges = GetCanonicalId(pCreateInfo); auto set_layouts_id = pipeline_layout_set_layouts_dict.look_up(set_layouts); plNode.compat_for_set.reserve(pCreateInfo->setLayoutCount); // Create table of "compatible for set N" cannonical forms for trivial accept validation for (uint32_t i = 0; i < pCreateInfo->setLayoutCount; ++i) { plNode.compat_for_set.emplace_back(GetCanonicalId(i, plNode.push_constant_ranges, set_layouts_id)); } // Implicit unlock }; void PostCallRecordCreateDescriptorPool(VkDevice device, const VkDescriptorPoolCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkDescriptorPool *pDescriptorPool, VkResult result) { layer_data *dev_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); if (VK_SUCCESS != result) return; DESCRIPTOR_POOL_STATE *pNewNode = new DESCRIPTOR_POOL_STATE(*pDescriptorPool, pCreateInfo); assert(pNewNode); dev_data->descriptorPoolMap[*pDescriptorPool] = pNewNode; } // Validate that given pool does not store any descriptor sets used by an in-flight CmdBuffer // pool stores the descriptor sets to be validated // 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 PreCallValidateResetDescriptorPool(layer_data *dev_data, VkDescriptorPool descriptorPool) { if (dev_data->instance_data->disabled.idle_descriptor_set) return false; bool skip = false; DESCRIPTOR_POOL_STATE *pPool = GetDescriptorPoolState(dev_data, descriptorPool); if (pPool != nullptr) { for (auto ds : pPool->sets) { if (ds && ds->in_use.load()) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_POOL_EXT, HandleToUint64(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; } void PostCallRecordResetDescriptorPool(layer_data *dev_data, VkDevice device, VkDescriptorPool descriptorPool, VkDescriptorPoolResetFlags flags) { DESCRIPTOR_POOL_STATE *pPool = GetDescriptorPoolState(dev_data, descriptorPool); // TODO: validate flags // For every set off of this pool, clear it, remove from setMap, and free cvdescriptorset::DescriptorSet for (auto ds : pPool->sets) { FreeDescriptorSet(dev_data, ds); } pPool->sets.clear(); // Reset available count for each type and available sets for this pool for (auto it = pPool->availableDescriptorTypeCount.begin(); it != pPool->availableDescriptorTypeCount.end(); ++it) { pPool->availableDescriptorTypeCount[it->first] = pPool->maxDescriptorTypeCount[it->first]; } pPool->availableSets = pPool->maxSets; } // 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 PreCallValidateAllocateDescriptorSets(layer_data *dev_data, const VkDescriptorSetAllocateInfo *pAllocateInfo, cvdescriptorset::AllocateDescriptorSetsData *common_data) { // Always update common data cvdescriptorset::UpdateAllocateDescriptorSetsData(dev_data, pAllocateInfo, common_data); if (dev_data->instance_data->disabled.allocate_descriptor_sets) return false; // All state checks for AllocateDescriptorSets is done in single function return cvdescriptorset::ValidateAllocateDescriptorSets(dev_data, pAllocateInfo, common_data); } // Allocation state was good and call down chain was made so update state based on allocating descriptor sets void PostCallRecordAllocateDescriptorSets(layer_data *dev_data, const VkDescriptorSetAllocateInfo *pAllocateInfo, VkDescriptorSet *pDescriptorSets, const cvdescriptorset::AllocateDescriptorSetsData *common_data) { // All the updates are contained in a single cvdescriptorset function cvdescriptorset::PerformAllocateDescriptorSets(pAllocateInfo, pDescriptorSets, common_data, &dev_data->descriptorPoolMap, &dev_data->setMap, dev_data); } // TODO: PostCallRecord routine is dependent on data generated in PreCallValidate -- needs to be moved out // Verify state before freeing DescriptorSets bool PreCallValidateFreeDescriptorSets(const layer_data *dev_data, VkDescriptorPool pool, uint32_t count, const VkDescriptorSet *descriptor_sets) { if (dev_data->instance_data->disabled.free_descriptor_sets) return false; bool skip = false; // First make sure sets being destroyed are not currently in-use for (uint32_t i = 0; i < count; ++i) { if (descriptor_sets[i] != VK_NULL_HANDLE) { skip |= ValidateIdleDescriptorSet(dev_data, descriptor_sets[i], "vkFreeDescriptorSets"); } } DESCRIPTOR_POOL_STATE *pool_state = GetDescriptorPoolState(dev_data, pool); if (pool_state && !(VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT & pool_state->createInfo.flags)) { // Can't Free from a NON_FREE pool skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_POOL_EXT, HandleToUint64(pool), "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; } // Sets are being returned to the pool so update the pool state void PreCallRecordFreeDescriptorSets(layer_data *dev_data, VkDescriptorPool pool, uint32_t count, const VkDescriptorSet *descriptor_sets) { DESCRIPTOR_POOL_STATE *pool_state = GetDescriptorPoolState(dev_data, pool); // Update available descriptor sets in pool pool_state->availableSets += count; // For each freed descriptor add its resources back into the pool as available and remove from pool and setMap for (uint32_t i = 0; i < count; ++i) { if (descriptor_sets[i] != VK_NULL_HANDLE) { auto descriptor_set = dev_data->setMap[descriptor_sets[i]]; uint32_t type_index = 0, descriptor_count = 0; for (uint32_t j = 0; j < descriptor_set->GetBindingCount(); ++j) { type_index = static_cast<uint32_t>(descriptor_set->GetTypeFromIndex(j)); descriptor_count = descriptor_set->GetDescriptorCountFromIndex(j); pool_state->availableDescriptorTypeCount[type_index] += descriptor_count; } FreeDescriptorSet(dev_data, descriptor_set); pool_state->sets.erase(descriptor_set); } } } // TODO : This is a Proof-of-concept for core validation architecture // Really we'll want to break out these functions to separate files but // keeping it all together here to prove out design // PreCallValidate* handles validating all of the state prior to calling down chain to UpdateDescriptorSets() bool PreCallValidateUpdateDescriptorSets(layer_data *dev_data, uint32_t descriptorWriteCount, const VkWriteDescriptorSet *pDescriptorWrites, uint32_t descriptorCopyCount, const VkCopyDescriptorSet *pDescriptorCopies) { if (dev_data->instance_data->disabled.update_descriptor_sets) return false; // 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 cvdescriptorset::ValidateUpdateDescriptorSets(dev_data->report_data, dev_data, descriptorWriteCount, pDescriptorWrites, descriptorCopyCount, pDescriptorCopies, "vkUpdateDescriptorSets()"); } // PostCallRecord* handles recording state updates following call down chain to UpdateDescriptorSets() void PreCallRecordUpdateDescriptorSets(layer_data *dev_data, uint32_t descriptorWriteCount, const VkWriteDescriptorSet *pDescriptorWrites, uint32_t descriptorCopyCount, const VkCopyDescriptorSet *pDescriptorCopies) { cvdescriptorset::PerformUpdateDescriptorSets(dev_data, descriptorWriteCount, pDescriptorWrites, descriptorCopyCount, pDescriptorCopies); } void PostCallRecordAllocateCommandBuffers(VkDevice device, const VkCommandBufferAllocateInfo *pCreateInfo, VkCommandBuffer *pCommandBuffer, VkResult result) { if (VK_SUCCESS != result) return; layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); auto pPool = GetCommandPoolNode(device_data, pCreateInfo->commandPool); if (pPool) { for (uint32_t i = 0; i < pCreateInfo->commandBufferCount; i++) { // Add command buffer to its commandPool map pPool->commandBuffers.insert(pCommandBuffer[i]); GLOBAL_CB_NODE *pCB = new GLOBAL_CB_NODE; // Add command buffer to map device_data->commandBufferMap[pCommandBuffer[i]] = pCB; ResetCommandBufferState(device_data, pCommandBuffer[i]); pCB->createInfo = *pCreateInfo; pCB->device = device; } if (GetEnables(device_data)->gpu_validation) { GpuPostCallRecordAllocateCommandBuffers(device_data, pCreateInfo, pCommandBuffer); } } } // Add bindings between the given cmd buffer & framebuffer and the framebuffer's children static void AddFramebufferBinding(layer_data *dev_data, GLOBAL_CB_NODE *cb_state, FRAMEBUFFER_STATE *fb_state) { AddCommandBufferBinding(&fb_state->cb_bindings, {HandleToUint64(fb_state->framebuffer), kVulkanObjectTypeFramebuffer}, cb_state); const uint32_t attachmentCount = fb_state->createInfo.attachmentCount; for (uint32_t attachment = 0; attachment < attachmentCount; ++attachment) { auto view_state = GetAttachmentImageViewState(dev_data, fb_state, attachment); if (view_state) { AddCommandBufferBindingImageView(dev_data, cb_state, view_state); } } } bool PreCallValidateBeginCommandBuffer(const VkCommandBuffer commandBuffer, const VkCommandBufferBeginInfo *pBeginInfo) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(commandBuffer), layer_data_map); GLOBAL_CB_NODE *cb_state = GetCBNode(device_data, commandBuffer); if (!cb_state) return false; bool skip = false; if (cb_state->in_use.load()) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(commandBuffer), "VUID-vkBeginCommandBuffer-commandBuffer-00049", "Calling vkBeginCommandBuffer() on active command buffer %" PRIx64 " before it has completed. You must check command buffer fence before this call.", HandleToUint64(commandBuffer)); } if (cb_state->createInfo.level != VK_COMMAND_BUFFER_LEVEL_PRIMARY) { // Secondary Command Buffer const VkCommandBufferInheritanceInfo *pInfo = pBeginInfo->pInheritanceInfo; if (!pInfo) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(commandBuffer), "VUID-vkBeginCommandBuffer-commandBuffer-00051", "vkBeginCommandBuffer(): Secondary Command Buffer (0x%" PRIx64 ") must have inheritance info.", HandleToUint64(commandBuffer)); } else { if (pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT) { assert(pInfo->renderPass); string errorString = ""; auto framebuffer = GetFramebufferState(device_data, pInfo->framebuffer); if (framebuffer) { if (framebuffer->createInfo.renderPass != pInfo->renderPass) { // renderPass that framebuffer was created with must be compatible with local renderPass skip |= ValidateRenderPassCompatibility(device_data, "framebuffer", framebuffer->rp_state.get(), "command buffer", GetRenderPassState(device_data, pInfo->renderPass), "vkBeginCommandBuffer()", "VUID-VkCommandBufferBeginInfo-flags-00055"); } } } if ((pInfo->occlusionQueryEnable == VK_FALSE || device_data->enabled_features.core.occlusionQueryPrecise == VK_FALSE) && (pInfo->queryFlags & VK_QUERY_CONTROL_PRECISE_BIT)) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(commandBuffer), "VUID-vkBeginCommandBuffer-commandBuffer-00052", "vkBeginCommandBuffer(): Secondary Command Buffer (0x%" PRIx64 ") must not have VK_QUERY_CONTROL_PRECISE_BIT if occulusionQuery is disabled or the device " "does not support precise occlusion queries.", HandleToUint64(commandBuffer)); } } if (pInfo && pInfo->renderPass != VK_NULL_HANDLE) { auto renderPass = GetRenderPassState(device_data, pInfo->renderPass); if (renderPass) { if (pInfo->subpass >= renderPass->createInfo.subpassCount) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(commandBuffer), "VUID-VkCommandBufferBeginInfo-flags-00054", "vkBeginCommandBuffer(): Secondary Command Buffers (0x%" PRIx64 ") must have a subpass index (%d) that is less than the number of subpasses (%d).", HandleToUint64(commandBuffer), pInfo->subpass, renderPass->createInfo.subpassCount); } } } } if (CB_RECORDING == cb_state->state) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(commandBuffer), "VUID-vkBeginCommandBuffer-commandBuffer-00049", "vkBeginCommandBuffer(): Cannot call Begin on command buffer (0x%" PRIx64 ") in the RECORDING state. Must first call vkEndCommandBuffer().", HandleToUint64(commandBuffer)); } else if (CB_RECORDED == cb_state->state || CB_INVALID_COMPLETE == cb_state->state) { VkCommandPool cmdPool = cb_state->createInfo.commandPool; auto pPool = GetCommandPoolNode(device_data, cmdPool); if (!(VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT & pPool->createFlags)) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(commandBuffer), "VUID-vkBeginCommandBuffer-commandBuffer-00050", "Call to vkBeginCommandBuffer() on command buffer (0x%" PRIx64 ") attempts to implicitly reset cmdBuffer created from command pool (0x%" PRIx64 ") that does NOT have the VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT bit set.", HandleToUint64(commandBuffer), HandleToUint64(cmdPool)); } } return skip; } void PreCallRecordBeginCommandBuffer(const VkCommandBuffer commandBuffer, const VkCommandBufferBeginInfo *pBeginInfo) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(commandBuffer), layer_data_map); GLOBAL_CB_NODE *cb_state = GetCBNode(device_data, commandBuffer); if (!cb_state) return; // This implicitly resets the Cmd Buffer so make sure any fence is done and then clear memory references ClearCmdBufAndMemReferences(device_data, cb_state); if (cb_state->createInfo.level != VK_COMMAND_BUFFER_LEVEL_PRIMARY) { // Secondary Command Buffer const VkCommandBufferInheritanceInfo *pInfo = pBeginInfo->pInheritanceInfo; if (pInfo) { if (pBeginInfo->flags & VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT) { assert(pInfo->renderPass); auto framebuffer = GetFramebufferState(device_data, pInfo->framebuffer); if (framebuffer) { // Connect this framebuffer and its children to this cmdBuffer AddFramebufferBinding(device_data, cb_state, framebuffer); } } } } if (CB_RECORDED == cb_state->state || CB_INVALID_COMPLETE == cb_state->state) { ResetCommandBufferState(device_data, commandBuffer); } // Set updated state here in case implicit reset occurs above cb_state->state = CB_RECORDING; cb_state->beginInfo = *pBeginInfo; if (cb_state->beginInfo.pInheritanceInfo) { cb_state->inheritanceInfo = *(cb_state->beginInfo.pInheritanceInfo); cb_state->beginInfo.pInheritanceInfo = &cb_state->inheritanceInfo; // If we are a secondary command-buffer and inheriting. Update the items we should inherit. if ((cb_state->createInfo.level != VK_COMMAND_BUFFER_LEVEL_PRIMARY) && (cb_state->beginInfo.flags & VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT)) { cb_state->activeRenderPass = GetRenderPassState(device_data, cb_state->beginInfo.pInheritanceInfo->renderPass); cb_state->activeSubpass = cb_state->beginInfo.pInheritanceInfo->subpass; cb_state->activeFramebuffer = cb_state->beginInfo.pInheritanceInfo->framebuffer; cb_state->framebuffers.insert(cb_state->beginInfo.pInheritanceInfo->framebuffer); } } } bool PreCallValidateEndCommandBuffer(VkCommandBuffer commandBuffer) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(commandBuffer), layer_data_map); GLOBAL_CB_NODE *cb_state = GetCBNode(device_data, 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(device_data, cb_state, "vkEndCommandBuffer()", "VUID-vkEndCommandBuffer-commandBuffer-00060"); } skip |= ValidateCmd(device_data, cb_state, CMD_ENDCOMMANDBUFFER, "vkEndCommandBuffer()"); for (auto query : cb_state->activeQueries) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(commandBuffer), "VUID-vkEndCommandBuffer-commandBuffer-00061", "Ending command buffer with in progress query: queryPool 0x%" PRIx64 ", index %d.", HandleToUint64(query.pool), query.index); } return skip; } void PostCallRecordEndCommandBuffer(VkCommandBuffer commandBuffer, VkResult result) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(commandBuffer), layer_data_map); GLOBAL_CB_NODE *cb_state = GetCBNode(device_data, commandBuffer); if (!cb_state) return; // Cached validation is specific to a specific recording of a specific command buffer. for (auto descriptor_set : cb_state->validated_descriptor_sets) { descriptor_set->ClearCachedValidation(cb_state); } cb_state->validated_descriptor_sets.clear(); if (VK_SUCCESS == result) { cb_state->state = CB_RECORDED; } } bool PreCallValidateResetCommandBuffer(VkCommandBuffer commandBuffer, VkCommandBufferResetFlags flags) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(commandBuffer), layer_data_map); bool skip = false; GLOBAL_CB_NODE *pCB = GetCBNode(device_data, commandBuffer); if (!pCB) return false; VkCommandPool cmdPool = pCB->createInfo.commandPool; auto pPool = GetCommandPoolNode(device_data, cmdPool); if (!(VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT & pPool->createFlags)) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(commandBuffer), "VUID-vkResetCommandBuffer-commandBuffer-00046", "Attempt to reset command buffer (0x%" PRIx64 ") created from command pool (0x%" PRIx64 ") that does NOT have the VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT bit set.", HandleToUint64(commandBuffer), HandleToUint64(cmdPool)); } skip |= CheckCommandBufferInFlight(device_data, pCB, "reset", "VUID-vkResetCommandBuffer-commandBuffer-00045"); return skip; } void PostCallRecordResetCommandBuffer(VkCommandBuffer commandBuffer, VkCommandBufferResetFlags flags, VkResult result) { if (VK_SUCCESS == result) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(commandBuffer), layer_data_map); ResetCommandBufferState(device_data, commandBuffer); } } bool PreCallValidateCmdBindPipeline(layer_data *dev_data, GLOBAL_CB_NODE *cb_state) { bool skip = ValidateCmdQueueFlags(dev_data, cb_state, "vkCmdBindPipeline()", VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT, "VUID-vkCmdBindPipeline-commandBuffer-cmdpool"); skip |= ValidateCmd(dev_data, cb_state, CMD_BINDPIPELINE, "vkCmdBindPipeline()"); // TODO: "VUID-vkCmdBindPipeline-pipelineBindPoint-00777" "VUID-vkCmdBindPipeline-pipelineBindPoint-00779" -- using // ValidatePipelineBindPoint return skip; } void PreCallRecordCmdBindPipeline(layer_data *dev_data, GLOBAL_CB_NODE *cb_state, VkPipelineBindPoint pipelineBindPoint, VkPipeline pipeline) { auto pipe_state = GetPipelineState(dev_data, pipeline); if (VK_PIPELINE_BIND_POINT_GRAPHICS == pipelineBindPoint) { cb_state->status &= ~cb_state->static_status; cb_state->static_status = MakeStaticStateMask(pipe_state->graphicsPipelineCI.ptr()->pDynamicState); cb_state->status |= cb_state->static_status; } cb_state->lastBound[pipelineBindPoint].pipeline_state = pipe_state; SetPipelineState(pipe_state); AddCommandBufferBinding(&pipe_state->cb_bindings, {HandleToUint64(pipeline), kVulkanObjectTypePipeline}, cb_state); } bool PreCallValidateCmdSetViewport(layer_data *dev_data, GLOBAL_CB_NODE *cb_state, VkCommandBuffer commandBuffer) { bool skip = ValidateCmdQueueFlags(dev_data, cb_state, "vkCmdSetViewport()", VK_QUEUE_GRAPHICS_BIT, "VUID-vkCmdSetViewport-commandBuffer-cmdpool"); skip |= ValidateCmd(dev_data, cb_state, CMD_SETVIEWPORT, "vkCmdSetViewport()"); if (cb_state->static_status & CBSTATUS_VIEWPORT_SET) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(commandBuffer), "VUID-vkCmdSetViewport-None-01221", "vkCmdSetViewport(): pipeline was created without VK_DYNAMIC_STATE_VIEWPORT flag.."); } return skip; } void PreCallRecordCmdSetViewport(GLOBAL_CB_NODE *cb_state, uint32_t firstViewport, uint32_t viewportCount) { cb_state->viewportMask |= ((1u << viewportCount) - 1u) << firstViewport; cb_state->status |= CBSTATUS_VIEWPORT_SET; } bool PreCallValidateCmdSetScissor(layer_data *dev_data, GLOBAL_CB_NODE *cb_state, VkCommandBuffer commandBuffer) { bool skip = ValidateCmdQueueFlags(dev_data, cb_state, "vkCmdSetScissor()", VK_QUEUE_GRAPHICS_BIT, "VUID-vkCmdSetScissor-commandBuffer-cmdpool"); skip |= ValidateCmd(dev_data, cb_state, CMD_SETSCISSOR, "vkCmdSetScissor()"); if (cb_state->static_status & CBSTATUS_SCISSOR_SET) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(commandBuffer), "VUID-vkCmdSetScissor-None-00590", "vkCmdSetScissor(): pipeline was created without VK_DYNAMIC_STATE_SCISSOR flag.."); } return skip; } void PreCallRecordCmdSetScissor(GLOBAL_CB_NODE *cb_state, uint32_t firstScissor, uint32_t scissorCount) { cb_state->scissorMask |= ((1u << scissorCount) - 1u) << firstScissor; cb_state->status |= CBSTATUS_SCISSOR_SET; } bool PreCallValidateCmdSetExclusiveScissorNV(layer_data *dev_data, GLOBAL_CB_NODE *cb_state, VkCommandBuffer commandBuffer) { bool skip = ValidateCmdQueueFlags(dev_data, cb_state, "vkCmdSetExclusiveScissorNV()", VK_QUEUE_GRAPHICS_BIT, "VUID-vkCmdSetExclusiveScissorNV-commandBuffer-cmdpool"); skip |= ValidateCmd(dev_data, cb_state, CMD_SETEXCLUSIVESCISSOR, "vkCmdSetExclusiveScissorNV()"); if (cb_state->static_status & CBSTATUS_EXCLUSIVE_SCISSOR_SET) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(commandBuffer), "VUID-vkCmdSetExclusiveScissorNV-None-02032", "vkCmdSetExclusiveScissorNV(): pipeline was created without VK_DYNAMIC_STATE_EXCLUSIVE_SCISSOR_NV flag."); } if (!GetEnabledFeatures(dev_data)->exclusive_scissor.exclusiveScissor) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(commandBuffer), "VUID-vkCmdSetExclusiveScissorNV-None-02031", "vkCmdSetExclusiveScissorNV: The exclusiveScissor feature is disabled."); } return skip; } void PreCallRecordCmdSetExclusiveScissorNV(GLOBAL_CB_NODE *cb_state, uint32_t firstExclusiveScissor, uint32_t exclusiveScissorCount) { // XXX TODO: We don't have VUIDs for validating that all exclusive scissors have been set. // cb_state->exclusiveScissorMask |= ((1u << exclusiveScissorCount) - 1u) << firstExclusiveScissor; cb_state->status |= CBSTATUS_EXCLUSIVE_SCISSOR_SET; } bool PreCallValidateCmdBindShadingRateImageNV(layer_data *dev_data, GLOBAL_CB_NODE *cb_state, VkCommandBuffer commandBuffer, VkImageView imageView, VkImageLayout imageLayout) { bool skip = ValidateCmdQueueFlags(dev_data, cb_state, "vkCmdBindShadingRateImageNV()", VK_QUEUE_GRAPHICS_BIT, "VUID-vkCmdBindShadingRateImageNV-commandBuffer-cmdpool"); skip |= ValidateCmd(dev_data, cb_state, CMD_BINDSHADINGRATEIMAGE, "vkCmdBindShadingRateImageNV()"); if (!GetEnabledFeatures(dev_data)->shading_rate_image.shadingRateImage) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(commandBuffer), "VUID-vkCmdBindShadingRateImageNV-None-02058", "vkCmdBindShadingRateImageNV: The shadingRateImage feature is disabled."); } if (imageView != VK_NULL_HANDLE) { auto view_state = GetImageViewState(dev_data, 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 |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_VIEW_EXT, HandleToUint64(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 |= log_msg( dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_VIEW_EXT, HandleToUint64(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(dev_data, view_state->create_info.image)->createInfo : nullptr; if (ici && !(ici->usage & VK_IMAGE_USAGE_SHADING_RATE_IMAGE_BIT_NV)) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_VIEW_EXT, HandleToUint64(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) { auto image_state = GetImageState(dev_data, 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. VkImageSubresourceRange &range = view_state->create_info.subresourceRange; VkImageSubresourceLayers subresource = {range.aspectMask, range.baseMipLevel, range.baseArrayLayer, range.layerCount}; if (image_state) { skip |= VerifyImageLayout(dev_data, 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; } void PreCallRecordCmdBindShadingRateImageNV(layer_data *dev_data, GLOBAL_CB_NODE *cb_state, VkImageView imageView) { if (imageView != VK_NULL_HANDLE) { auto view_state = GetImageViewState(dev_data, imageView); AddCommandBufferBindingImageView(dev_data, cb_state, view_state); } } bool PreCallValidateCmdSetViewportShadingRatePaletteNV(layer_data *dev_data, GLOBAL_CB_NODE *cb_state, VkCommandBuffer commandBuffer, uint32_t firstViewport, uint32_t viewportCount, const VkShadingRatePaletteNV *pShadingRatePalettes) { bool skip = ValidateCmdQueueFlags(dev_data, cb_state, "vkCmdSetViewportShadingRatePaletteNV()", VK_QUEUE_GRAPHICS_BIT, "VUID-vkCmdSetViewportShadingRatePaletteNV-commandBuffer-cmdpool"); skip |= ValidateCmd(dev_data, cb_state, CMD_SETVIEWPORTSHADINGRATEPALETTE, "vkCmdSetViewportShadingRatePaletteNV()"); if (!GetEnabledFeatures(dev_data)->shading_rate_image.shadingRateImage) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(commandBuffer), "VUID-vkCmdSetViewportShadingRatePaletteNV-None-02064", "vkCmdSetViewportShadingRatePaletteNV: The shadingRateImage feature is disabled."); } if (cb_state->static_status & CBSTATUS_SHADING_RATE_PALETTE_SET) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(commandBuffer), "VUID-vkCmdSetViewportShadingRatePaletteNV-None-02065", "vkCmdSetViewportShadingRatePaletteNV(): pipeline was created without " "VK_DYNAMIC_STATE_VIEWPORT_SHADING_RATE_PALETTE_NV flag."); } for (uint32_t i = 0; i < viewportCount; ++i) { auto *palette = &pShadingRatePalettes[i]; if (palette->shadingRatePaletteEntryCount == 0 || palette->shadingRatePaletteEntryCount > dev_data->phys_dev_ext_props.shading_rate_image_props.shadingRatePaletteSize) { skip |= log_msg( dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(commandBuffer), "VUID-VkShadingRatePaletteNV-shadingRatePaletteEntryCount-02071", "vkCmdSetViewportShadingRatePaletteNV: shadingRatePaletteEntryCount must be between 1 and shadingRatePaletteSize."); } } return skip; } void PreCallRecordCmdSetViewportShadingRatePaletteNV(GLOBAL_CB_NODE *cb_state, uint32_t firstViewport, uint32_t viewportCount) { // XXX TODO: We don't have VUIDs for validating that all shading rate palettes have been set. // cb_state->shadingRatePaletteMask |= ((1u << viewportCount) - 1u) << firstViewport; cb_state->status |= CBSTATUS_SHADING_RATE_PALETTE_SET; } bool PreCallValidateCmdSetLineWidth(layer_data *dev_data, GLOBAL_CB_NODE *cb_state, VkCommandBuffer commandBuffer) { bool skip = ValidateCmdQueueFlags(dev_data, cb_state, "vkCmdSetLineWidth()", VK_QUEUE_GRAPHICS_BIT, "VUID-vkCmdSetLineWidth-commandBuffer-cmdpool"); skip |= ValidateCmd(dev_data, cb_state, CMD_SETLINEWIDTH, "vkCmdSetLineWidth()"); if (cb_state->static_status & CBSTATUS_LINE_WIDTH_SET) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(commandBuffer), "VUID-vkCmdSetLineWidth-None-00787", "vkCmdSetLineWidth called but pipeline was created without VK_DYNAMIC_STATE_LINE_WIDTH flag."); } return skip; } void PreCallRecordCmdSetLineWidth(GLOBAL_CB_NODE *cb_state) { cb_state->status |= CBSTATUS_LINE_WIDTH_SET; } bool PreCallValidateCmdSetDepthBias(layer_data *dev_data, GLOBAL_CB_NODE *cb_state, VkCommandBuffer commandBuffer, float depthBiasClamp) { bool skip = ValidateCmdQueueFlags(dev_data, cb_state, "vkCmdSetDepthBias()", VK_QUEUE_GRAPHICS_BIT, "VUID-vkCmdSetDepthBias-commandBuffer-cmdpool"); skip |= ValidateCmd(dev_data, cb_state, CMD_SETDEPTHBIAS, "vkCmdSetDepthBias()"); if (cb_state->static_status & CBSTATUS_DEPTH_BIAS_SET) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(commandBuffer), "VUID-vkCmdSetDepthBias-None-00789", "vkCmdSetDepthBias(): pipeline was created without VK_DYNAMIC_STATE_DEPTH_BIAS flag.."); } if ((depthBiasClamp != 0.0) && (!dev_data->enabled_features.core.depthBiasClamp)) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(commandBuffer), "VUID-vkCmdSetDepthBias-depthBiasClamp-00790", "vkCmdSetDepthBias(): the depthBiasClamp device feature is disabled: the depthBiasClamp parameter must " "be set to 0.0."); } return skip; } void PreCallRecordCmdSetDepthBias(GLOBAL_CB_NODE *cb_state) { cb_state->status |= CBSTATUS_DEPTH_BIAS_SET; } bool PreCallValidateCmdSetBlendConstants(layer_data *dev_data, GLOBAL_CB_NODE *cb_state, VkCommandBuffer commandBuffer) { bool skip = ValidateCmdQueueFlags(dev_data, cb_state, "vkCmdSetBlendConstants()", VK_QUEUE_GRAPHICS_BIT, "VUID-vkCmdSetBlendConstants-commandBuffer-cmdpool"); skip |= ValidateCmd(dev_data, cb_state, CMD_SETBLENDCONSTANTS, "vkCmdSetBlendConstants()"); if (cb_state->static_status & CBSTATUS_BLEND_CONSTANTS_SET) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(commandBuffer), "VUID-vkCmdSetBlendConstants-None-00612", "vkCmdSetBlendConstants(): pipeline was created without VK_DYNAMIC_STATE_BLEND_CONSTANTS flag.."); } return skip; } void PreCallRecordCmdSetBlendConstants(GLOBAL_CB_NODE *cb_state) { cb_state->status |= CBSTATUS_BLEND_CONSTANTS_SET; } bool PreCallValidateCmdSetDepthBounds(layer_data *dev_data, GLOBAL_CB_NODE *cb_state, VkCommandBuffer commandBuffer) { bool skip = ValidateCmdQueueFlags(dev_data, cb_state, "vkCmdSetDepthBounds()", VK_QUEUE_GRAPHICS_BIT, "VUID-vkCmdSetDepthBounds-commandBuffer-cmdpool"); skip |= ValidateCmd(dev_data, cb_state, CMD_SETDEPTHBOUNDS, "vkCmdSetDepthBounds()"); if (cb_state->static_status & CBSTATUS_DEPTH_BOUNDS_SET) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(commandBuffer), "VUID-vkCmdSetDepthBounds-None-00599", "vkCmdSetDepthBounds(): pipeline was created without VK_DYNAMIC_STATE_DEPTH_BOUNDS flag.."); } return skip; } void PreCallRecordCmdSetDepthBounds(GLOBAL_CB_NODE *cb_state) { cb_state->status |= CBSTATUS_DEPTH_BOUNDS_SET; } bool PreCallValidateCmdSetStencilCompareMask(layer_data *dev_data, GLOBAL_CB_NODE *cb_state, VkCommandBuffer commandBuffer) { bool skip = ValidateCmdQueueFlags(dev_data, cb_state, "vkCmdSetStencilCompareMask()", VK_QUEUE_GRAPHICS_BIT, "VUID-vkCmdSetStencilCompareMask-commandBuffer-cmdpool"); skip |= ValidateCmd(dev_data, cb_state, CMD_SETSTENCILCOMPAREMASK, "vkCmdSetStencilCompareMask()"); if (cb_state->static_status & CBSTATUS_STENCIL_READ_MASK_SET) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(commandBuffer), "VUID-vkCmdSetStencilCompareMask-None-00602", "vkCmdSetStencilCompareMask(): pipeline was created without VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK flag.."); } return skip; } void PreCallRecordCmdSetStencilCompareMask(GLOBAL_CB_NODE *cb_state) { cb_state->status |= CBSTATUS_STENCIL_READ_MASK_SET; } bool PreCallValidateCmdSetStencilWriteMask(layer_data *dev_data, GLOBAL_CB_NODE *cb_state, VkCommandBuffer commandBuffer) { bool skip = ValidateCmdQueueFlags(dev_data, cb_state, "vkCmdSetStencilWriteMask()", VK_QUEUE_GRAPHICS_BIT, "VUID-vkCmdSetStencilWriteMask-commandBuffer-cmdpool"); skip |= ValidateCmd(dev_data, cb_state, CMD_SETSTENCILWRITEMASK, "vkCmdSetStencilWriteMask()"); if (cb_state->static_status & CBSTATUS_STENCIL_WRITE_MASK_SET) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(commandBuffer), "VUID-vkCmdSetStencilWriteMask-None-00603", "vkCmdSetStencilWriteMask(): pipeline was created without VK_DYNAMIC_STATE_STENCIL_WRITE_MASK flag.."); } return skip; } void PreCallRecordCmdSetStencilWriteMask(GLOBAL_CB_NODE *cb_state) { cb_state->status |= CBSTATUS_STENCIL_WRITE_MASK_SET; } bool PreCallValidateCmdSetStencilReference(layer_data *dev_data, GLOBAL_CB_NODE *cb_state, VkCommandBuffer commandBuffer) { bool skip = ValidateCmdQueueFlags(dev_data, cb_state, "vkCmdSetStencilReference()", VK_QUEUE_GRAPHICS_BIT, "VUID-vkCmdSetStencilReference-commandBuffer-cmdpool"); skip |= ValidateCmd(dev_data, cb_state, CMD_SETSTENCILREFERENCE, "vkCmdSetStencilReference()"); if (cb_state->static_status & CBSTATUS_STENCIL_REFERENCE_SET) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(commandBuffer), "VUID-vkCmdSetStencilReference-None-00604", "vkCmdSetStencilReference(): pipeline was created without VK_DYNAMIC_STATE_STENCIL_REFERENCE flag.."); } return skip; } void PreCallRecordCmdSetStencilReference(GLOBAL_CB_NODE *cb_state) { cb_state->status |= CBSTATUS_STENCIL_REFERENCE_SET; } // Update pipeline_layout bind points applying the "Pipeline Layout Compatibility" rules static void UpdateLastBoundDescriptorSets(layer_data *device_data, GLOBAL_CB_NODE *cb_state, VkPipelineBindPoint pipeline_bind_point, const PIPELINE_LAYOUT_NODE *pipeline_layout, uint32_t first_set, uint32_t set_count, const std::vector<cvdescriptorset::DescriptorSet *> descriptor_sets, uint32_t dynamic_offset_count, const uint32_t *p_dynamic_offsets) { // Defensive assert(set_count); if (0 == set_count) return; assert(pipeline_layout); if (!pipeline_layout) return; uint32_t required_size = first_set + set_count; const uint32_t last_binding_index = required_size - 1; assert(last_binding_index < pipeline_layout->compat_for_set.size()); // Some useful shorthand auto &last_bound = cb_state->lastBound[pipeline_bind_point]; auto &bound_sets = last_bound.boundDescriptorSets; auto &dynamic_offsets = last_bound.dynamicOffsets; auto &bound_compat_ids = last_bound.compat_id_for_set; auto &pipe_compat_ids = pipeline_layout->compat_for_set; const uint32_t current_size = static_cast<uint32_t>(bound_sets.size()); assert(current_size == dynamic_offsets.size()); assert(current_size == bound_compat_ids.size()); // We need this three times in this function, but nowhere else auto push_descriptor_cleanup = [&last_bound](const cvdescriptorset::DescriptorSet *ds) -> bool { if (ds && ds->IsPushDescriptor()) { assert(ds == last_bound.push_descriptor_set.get()); last_bound.push_descriptor_set = nullptr; return true; } return false; }; // Clean up the "disturbed" before and after the range to be set if (required_size < current_size) { if (bound_compat_ids[last_binding_index] != pipe_compat_ids[last_binding_index]) { // We're disturbing those after last, we'll shrink below, but first need to check for and cleanup the push_descriptor for (auto set_idx = required_size; set_idx < current_size; ++set_idx) { if (push_descriptor_cleanup(bound_sets[set_idx])) break; } } else { // We're not disturbing past last, so leave the upper binding data alone. required_size = current_size; } } // We resize if we need more set entries or if those past "last" are disturbed if (required_size != current_size) { // TODO: put these size tied things in a struct (touches many lines) bound_sets.resize(required_size); dynamic_offsets.resize(required_size); bound_compat_ids.resize(required_size); } // For any previously bound sets, need to set them to "invalid" if they were disturbed by this update for (uint32_t set_idx = 0; set_idx < first_set; ++set_idx) { if (bound_compat_ids[set_idx] != pipe_compat_ids[set_idx]) { push_descriptor_cleanup(bound_sets[set_idx]); bound_sets[set_idx] = nullptr; dynamic_offsets[set_idx].clear(); bound_compat_ids[set_idx] = pipe_compat_ids[set_idx]; } } // Now update the bound sets with the input sets const uint32_t *input_dynamic_offsets = p_dynamic_offsets; // "read" pointer for dynamic offset data for (uint32_t input_idx = 0; input_idx < set_count; input_idx++) { auto set_idx = input_idx + first_set; // set_idx is index within layout, input_idx is index within input descriptor sets cvdescriptorset::DescriptorSet *descriptor_set = descriptor_sets[input_idx]; // Record binding (or push) if (descriptor_set != last_bound.push_descriptor_set.get()) { // Only cleanup the push descriptors if they aren't the currently used set. push_descriptor_cleanup(bound_sets[set_idx]); } bound_sets[set_idx] = descriptor_set; bound_compat_ids[set_idx] = pipe_compat_ids[set_idx]; // compat ids are canonical *per* set index if (descriptor_set) { auto set_dynamic_descriptor_count = descriptor_set->GetDynamicDescriptorCount(); // TODO: Add logic for tracking push_descriptor offsets (here or in caller) if (set_dynamic_descriptor_count && input_dynamic_offsets) { const uint32_t *end_offset = input_dynamic_offsets + set_dynamic_descriptor_count; dynamic_offsets[set_idx] = std::vector<uint32_t>(input_dynamic_offsets, end_offset); input_dynamic_offsets = end_offset; assert(input_dynamic_offsets <= (p_dynamic_offsets + dynamic_offset_count)); } else { dynamic_offsets[set_idx].clear(); } if (!descriptor_set->IsPushDescriptor()) { // Can't cache validation of push_descriptors cb_state->validated_descriptor_sets.insert(descriptor_set); } } } } // Update the bound state for the bind point, including the effects of incompatible pipeline layouts void PreCallRecordCmdBindDescriptorSets(layer_data *device_data, GLOBAL_CB_NODE *cb_state, VkPipelineBindPoint pipelineBindPoint, VkPipelineLayout layout, uint32_t firstSet, uint32_t setCount, const VkDescriptorSet *pDescriptorSets, uint32_t dynamicOffsetCount, const uint32_t *pDynamicOffsets) { auto pipeline_layout = GetPipelineLayout(device_data, layout); std::vector<cvdescriptorset::DescriptorSet *> descriptor_sets; descriptor_sets.reserve(setCount); // Construct a list of the descriptors bool found_non_null = false; for (uint32_t i = 0; i < setCount; i++) { cvdescriptorset::DescriptorSet *descriptor_set = GetSetNode(device_data, pDescriptorSets[i]); descriptor_sets.emplace_back(descriptor_set); found_non_null |= descriptor_set != nullptr; } if (found_non_null) { // which implies setCount > 0 UpdateLastBoundDescriptorSets(device_data, cb_state, pipelineBindPoint, pipeline_layout, firstSet, setCount, descriptor_sets, dynamicOffsetCount, pDynamicOffsets); cb_state->lastBound[pipelineBindPoint].pipeline_layout = layout; } } bool PreCallValidateCmdBindDescriptorSets(layer_data *device_data, GLOBAL_CB_NODE *cb_state, VkPipelineBindPoint pipelineBindPoint, VkPipelineLayout layout, uint32_t firstSet, uint32_t setCount, const VkDescriptorSet *pDescriptorSets, uint32_t dynamicOffsetCount, const uint32_t *pDynamicOffsets) { bool skip = false; skip |= ValidateCmdQueueFlags(device_data, cb_state, "vkCmdBindDescriptorSets()", VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT, "VUID-vkCmdBindDescriptorSets-commandBuffer-cmdpool"); skip |= ValidateCmd(device_data, 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 = ""; uint32_t last_set_index = firstSet + setCount - 1; if (last_set_index >= cb_state->lastBound[pipelineBindPoint].boundDescriptorSets.size()) { cb_state->lastBound[pipelineBindPoint].boundDescriptorSets.resize(last_set_index + 1); cb_state->lastBound[pipelineBindPoint].dynamicOffsets.resize(last_set_index + 1); cb_state->lastBound[pipelineBindPoint].compat_id_for_set.resize(last_set_index + 1); } auto pipeline_layout = GetPipelineLayout(device_data, layout); for (uint32_t set_idx = 0; set_idx < setCount; set_idx++) { cvdescriptorset::DescriptorSet *descriptor_set = GetSetNode(device_data, pDescriptorSets[set_idx]); if (descriptor_set) { // Verify that set being bound is compatible with overlapping setLayout of pipelineLayout if (!VerifySetLayoutCompatibility(descriptor_set, pipeline_layout, set_idx + firstSet, error_string)) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT, HandleToUint64(pDescriptorSets[set_idx]), "VUID-vkCmdBindDescriptorSets-pDescriptorSets-00358", "descriptorSet #%u being bound is not compatible with overlapping descriptorSetLayout at index %u of " "pipelineLayout 0x%" PRIx64 " due to: %s.", set_idx, set_idx + firstSet, HandleToUint64(layout), 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) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT, HandleToUint64(pDescriptorSets[set_idx]), kVUID_Core_DrawState_InvalidDynamicOffsetCount, "descriptorSet #%u (0x%" PRIx64 ") 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, HandleToUint64(pDescriptorSets[set_idx]), descriptor_set->GetDynamicDescriptorCount(), (dynamicOffsetCount - total_dynamic_descriptors)); } else { // Validate dynamic offsets and Dynamic Offset Minimums uint32_t cur_dyn_offset = total_dynamic_descriptors; for (uint32_t d = 0; d < descriptor_set->GetTotalDescriptorCount(); d++) { if (descriptor_set->GetTypeFromGlobalIndex(d) == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC) { if (SafeModulo(pDynamicOffsets[cur_dyn_offset], device_data->phys_dev_properties.properties.limits.minUniformBufferOffsetAlignment) != 0) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT, 0, "VUID-vkCmdBindDescriptorSets-pDynamicOffsets-01971", "vkCmdBindDescriptorSets(): pDynamicOffsets[%d] is %d but must be a multiple of " "device limit minUniformBufferOffsetAlignment 0x%" PRIxLEAST64 ".", cur_dyn_offset, pDynamicOffsets[cur_dyn_offset], device_data->phys_dev_properties.properties.limits.minUniformBufferOffsetAlignment); } cur_dyn_offset++; } else if (descriptor_set->GetTypeFromGlobalIndex(d) == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC) { if (SafeModulo(pDynamicOffsets[cur_dyn_offset], device_data->phys_dev_properties.properties.limits.minStorageBufferOffsetAlignment) != 0) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT, 0, "VUID-vkCmdBindDescriptorSets-pDynamicOffsets-01972", "vkCmdBindDescriptorSets(): pDynamicOffsets[%d] is %d but must be a multiple of " "device limit minStorageBufferOffsetAlignment 0x%" PRIxLEAST64 ".", cur_dyn_offset, pDynamicOffsets[cur_dyn_offset], device_data->phys_dev_properties.properties.limits.minStorageBufferOffsetAlignment); } cur_dyn_offset++; } } // Keep running total of dynamic descriptor count to verify at the end total_dynamic_descriptors += set_dynamic_descriptor_count; } } } else { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_SET_EXT, HandleToUint64(pDescriptorSets[set_idx]), kVUID_Core_DrawState_InvalidSet, "Attempt to bind descriptor set 0x%" PRIx64 " that doesn't exist!", HandleToUint64(pDescriptorSets[set_idx])); } } // dynamicOffsetCount must equal the total number of dynamic descriptors in the sets being bound if (total_dynamic_descriptors != dynamicOffsetCount) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(cb_state->commandBuffer), "VUID-vkCmdBindDescriptorSets-dynamicOffsetCount-00359", "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); } 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 ValidatePipelineBindPoint(layer_data *device_data, GLOBAL_CB_NODE *cb_state, VkPipelineBindPoint bind_point, const char *func_name, const std::map<VkPipelineBindPoint, std::string> &bind_errors) { bool skip = false; auto pool = GetCommandPoolNode(device_data, cb_state->createInfo.commandPool); 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_NV, static_cast<VkQueueFlags>(VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT)), }; const auto &qfp = GetPhysDevProperties(device_data)->queue_family_properties[pool->queueFamilyIndex]; if (0 == (qfp.queueFlags & flag_mask.at(bind_point))) { const std::string error = bind_errors.at(bind_point); auto cb_u64 = HandleToUint64(cb_state->commandBuffer); auto cp_u64 = HandleToUint64(cb_state->createInfo.commandPool); skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, cb_u64, error, "%s: CommandBuffer 0x%" PRIxLEAST64 " was allocated from VkCommandPool 0x%" PRIxLEAST64 " that does not support bindpoint %s.", func_name, cb_u64, cp_u64, string_VkPipelineBindPoint(bind_point)); } } return skip; } bool PreCallValidateCmdPushDescriptorSetKHR(layer_data *device_data, GLOBAL_CB_NODE *cb_state, const VkPipelineBindPoint bind_point, const VkPipelineLayout layout, const uint32_t set, const uint32_t descriptor_write_count, const VkWriteDescriptorSet *descriptor_writes, const char *func_name) { bool skip = false; skip |= ValidateCmd(device_data, cb_state, CMD_PUSHDESCRIPTORSETKHR, func_name); skip |= ValidateCmdQueueFlags(device_data, cb_state, func_name, (VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT), "VUID-vkCmdPushDescriptorSetKHR-commandBuffer-cmdpool"); 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_NV, "VUID-vkCmdPushDescriptorSetKHR-pipelineBindPoint-00363")}; skip |= ValidatePipelineBindPoint(device_data, cb_state, bind_point, func_name, bind_errors); auto layout_data = GetPipelineLayout(device_data, 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; const auto layout_u64 = HandleToUint64(layout); if (set < set_layouts.size()) { const auto dsl = set_layouts[set]; if (dsl) { if (!dsl->IsPushDescriptor()) { skip = log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_LAYOUT_EXT, layout_u64, "VUID-vkCmdPushDescriptorSetKHR-set-00365", "%s: Set index %" PRIu32 " does not match push descriptor set layout index for VkPipelineLayout 0x%" PRIxLEAST64 ".", func_name, set, layout_u64); } 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, VK_NULL_HANDLE, dsl, 0, device_data); skip |= proxy_ds.ValidatePushDescriptorsUpdate(device_data->report_data, descriptor_write_count, descriptor_writes, func_name); } } } else { skip = log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_LAYOUT_EXT, layout_u64, "VUID-vkCmdPushDescriptorSetKHR-set-00364", "%s: Set index %" PRIu32 " is outside of range for VkPipelineLayout 0x%" PRIxLEAST64 " (set < %" PRIu32 ").", func_name, set, layout_u64, static_cast<uint32_t>(set_layouts.size())); } } return skip; } void PreCallRecordCmdPushDescriptorSetKHR(layer_data *device_data, GLOBAL_CB_NODE *cb_state, VkPipelineBindPoint pipelineBindPoint, VkPipelineLayout layout, uint32_t set, uint32_t descriptorWriteCount, const VkWriteDescriptorSet *pDescriptorWrites) { const auto &pipeline_layout = GetPipelineLayout(device_data, layout); // Short circuit invalid updates if (!pipeline_layout || (set >= pipeline_layout->set_layouts.size()) || !pipeline_layout->set_layouts[set] || !pipeline_layout->set_layouts[set]->IsPushDescriptor()) return; // We need a descriptor set to update the bindings with, compatible with the passed layout const auto dsl = pipeline_layout->set_layouts[set]; auto &last_bound = cb_state->lastBound[pipelineBindPoint]; auto &push_descriptor_set = last_bound.push_descriptor_set; // if we are disturbing the current push_desriptor_set clear it if (!push_descriptor_set || !CompatForSet(set, last_bound.compat_id_for_set, pipeline_layout->compat_for_set)) { push_descriptor_set.reset(new cvdescriptorset::DescriptorSet(0, 0, dsl, 0, device_data)); } std::vector<cvdescriptorset::DescriptorSet *> descriptor_sets = {push_descriptor_set.get()}; UpdateLastBoundDescriptorSets(device_data, cb_state, pipelineBindPoint, pipeline_layout, set, 1, descriptor_sets, 0, nullptr); last_bound.pipeline_layout = layout; // Now that we have either the new or extant push_descriptor set ... do the write updates against it push_descriptor_set->PerformPushDescriptorsUpdate(descriptorWriteCount, pDescriptorWrites); } static VkDeviceSize GetIndexAlignment(VkIndexType indexType) { switch (indexType) { case VK_INDEX_TYPE_UINT16: return 2; case VK_INDEX_TYPE_UINT32: return 4; default: // Not a real index type. Express no alignment requirement here; we expect upper layer // to have already picked up on the enum being nonsense. return 1; } } bool PreCallValidateCmdBindIndexBuffer(layer_data *dev_data, BUFFER_STATE *buffer_state, GLOBAL_CB_NODE *cb_node, VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, VkIndexType indexType) { bool skip = ValidateBufferUsageFlags(dev_data, buffer_state, VK_BUFFER_USAGE_INDEX_BUFFER_BIT, true, "VUID-vkCmdBindIndexBuffer-buffer-00433", "vkCmdBindIndexBuffer()", "VK_BUFFER_USAGE_INDEX_BUFFER_BIT"); skip |= ValidateCmdQueueFlags(dev_data, cb_node, "vkCmdBindIndexBuffer()", VK_QUEUE_GRAPHICS_BIT, "VUID-vkCmdBindIndexBuffer-commandBuffer-cmdpool"); skip |= ValidateCmd(dev_data, cb_node, CMD_BINDINDEXBUFFER, "vkCmdBindIndexBuffer()"); skip |= ValidateMemoryIsBoundToBuffer(dev_data, buffer_state, "vkCmdBindIndexBuffer()", "VUID-vkCmdBindIndexBuffer-buffer-00434"); auto offset_align = GetIndexAlignment(indexType); if (offset % offset_align) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(commandBuffer), "VUID-vkCmdBindIndexBuffer-offset-00432", "vkCmdBindIndexBuffer() offset (0x%" PRIxLEAST64 ") does not fall on alignment (%s) boundary.", offset, string_VkIndexType(indexType)); } return skip; } void PreCallRecordCmdBindIndexBuffer(BUFFER_STATE *buffer_state, GLOBAL_CB_NODE *cb_node, VkBuffer buffer, VkDeviceSize offset, VkIndexType indexType) { cb_node->status |= CBSTATUS_INDEX_BUFFER_BOUND; cb_node->index_buffer_binding.buffer = buffer; cb_node->index_buffer_binding.size = buffer_state->createInfo.size; cb_node->index_buffer_binding.offset = offset; cb_node->index_buffer_binding.index_type = indexType; } static inline void UpdateResourceTrackingOnDraw(GLOBAL_CB_NODE *pCB) { pCB->draw_data.push_back(pCB->current_draw_data); } bool PreCallValidateCmdBindVertexBuffers(layer_data *dev_data, GLOBAL_CB_NODE *cb_state, uint32_t bindingCount, const VkBuffer *pBuffers, const VkDeviceSize *pOffsets) { bool skip = ValidateCmdQueueFlags(dev_data, cb_state, "vkCmdBindVertexBuffers()", VK_QUEUE_GRAPHICS_BIT, "VUID-vkCmdBindVertexBuffers-commandBuffer-cmdpool"); skip |= ValidateCmd(dev_data, cb_state, CMD_BINDVERTEXBUFFERS, "vkCmdBindVertexBuffers()"); for (uint32_t i = 0; i < bindingCount; ++i) { auto buffer_state = GetBufferState(dev_data, pBuffers[i]); assert(buffer_state); skip |= ValidateBufferUsageFlags(dev_data, buffer_state, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, true, "VUID-vkCmdBindVertexBuffers-pBuffers-00627", "vkCmdBindVertexBuffers()", "VK_BUFFER_USAGE_VERTEX_BUFFER_BIT"); skip |= ValidateMemoryIsBoundToBuffer(dev_data, buffer_state, "vkCmdBindVertexBuffers()", "VUID-vkCmdBindVertexBuffers-pBuffers-00628"); if (pOffsets[i] >= buffer_state->createInfo.size) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT, HandleToUint64(buffer_state->buffer), "VUID-vkCmdBindVertexBuffers-pOffsets-00626", "vkCmdBindVertexBuffers() offset (0x%" PRIxLEAST64 ") is beyond the end of the buffer.", pOffsets[i]); } } return skip; } void PreCallRecordCmdBindVertexBuffers(GLOBAL_CB_NODE *pCB, uint32_t firstBinding, uint32_t bindingCount, const VkBuffer *pBuffers, const VkDeviceSize *pOffsets) { uint32_t end = firstBinding + bindingCount; if (pCB->current_draw_data.vertex_buffer_bindings.size() < end) { pCB->current_draw_data.vertex_buffer_bindings.resize(end); } for (uint32_t i = 0; i < bindingCount; ++i) { auto &vertex_buffer_binding = pCB->current_draw_data.vertex_buffer_bindings[i + firstBinding]; vertex_buffer_binding.buffer = pBuffers[i]; vertex_buffer_binding.offset = pOffsets[i]; } } // Generic function to handle validation for all CmdDraw* type functions static bool ValidateCmdDrawType(layer_data *dev_data, VkCommandBuffer cmd_buffer, bool indexed, VkPipelineBindPoint bind_point, CMD_TYPE cmd_type, GLOBAL_CB_NODE **cb_state, const char *caller, VkQueueFlags queue_flags, const std::string &queue_flag_code, const std::string &renderpass_msg_code, const std::string &pipebound_msg_code, const std::string &dynamic_state_msg_code) { bool skip = false; *cb_state = GetCBNode(dev_data, cmd_buffer); if (*cb_state) { skip |= ValidateCmdQueueFlags(dev_data, *cb_state, caller, queue_flags, queue_flag_code); skip |= ValidateCmd(dev_data, *cb_state, cmd_type, caller); skip |= ValidateCmdBufDrawState(dev_data, *cb_state, cmd_type, indexed, bind_point, caller, pipebound_msg_code, dynamic_state_msg_code); skip |= (VK_PIPELINE_BIND_POINT_GRAPHICS == bind_point) ? OutsideRenderPass(dev_data, *cb_state, caller, renderpass_msg_code) : InsideRenderPass(dev_data, *cb_state, caller, renderpass_msg_code); } return skip; } // Generic function to handle state update for all CmdDraw* and CmdDispatch* type functions static void UpdateStateCmdDrawDispatchType(layer_data *dev_data, GLOBAL_CB_NODE *cb_state, VkPipelineBindPoint bind_point) { UpdateDrawState(dev_data, cb_state, bind_point); } // Generic function to handle state update for all CmdDraw* type functions static void UpdateStateCmdDrawType(layer_data *dev_data, GLOBAL_CB_NODE *cb_state, VkPipelineBindPoint bind_point) { UpdateStateCmdDrawDispatchType(dev_data, cb_state, bind_point); UpdateResourceTrackingOnDraw(cb_state); cb_state->hasDrawCmd = true; } bool PreCallValidateCmdDraw(layer_data *dev_data, VkCommandBuffer cmd_buffer, bool indexed, VkPipelineBindPoint bind_point, GLOBAL_CB_NODE **cb_state, const char *caller) { return ValidateCmdDrawType(dev_data, cmd_buffer, indexed, bind_point, CMD_DRAW, cb_state, caller, VK_QUEUE_GRAPHICS_BIT, "VUID-vkCmdDraw-commandBuffer-cmdpool", "VUID-vkCmdDraw-renderpass", "VUID-vkCmdDraw-None-00442", "VUID-vkCmdDraw-None-00443"); } void PostCallRecordCmdDraw(layer_data *dev_data, GLOBAL_CB_NODE *cb_state, VkPipelineBindPoint bind_point) { UpdateStateCmdDrawType(dev_data, cb_state, bind_point); } bool PreCallValidateCmdDrawIndexed(layer_data *dev_data, VkCommandBuffer cmd_buffer, bool indexed, VkPipelineBindPoint bind_point, GLOBAL_CB_NODE **cb_state, const char *caller, uint32_t indexCount, uint32_t firstIndex) { bool skip = ValidateCmdDrawType(dev_data, cmd_buffer, indexed, bind_point, CMD_DRAWINDEXED, cb_state, caller, VK_QUEUE_GRAPHICS_BIT, "VUID-vkCmdDrawIndexed-commandBuffer-cmdpool", "VUID-vkCmdDrawIndexed-renderpass", "VUID-vkCmdDrawIndexed-None-00461", "VUID-vkCmdDrawIndexed-None-00462"); if (!skip && ((*cb_state)->status & CBSTATUS_INDEX_BUFFER_BOUND)) { unsigned int index_size = 0; const auto &index_buffer_binding = (*cb_state)->index_buffer_binding; if (index_buffer_binding.index_type == VK_INDEX_TYPE_UINT16) { index_size = 2; } else if (index_buffer_binding.index_type == VK_INDEX_TYPE_UINT32) { index_size = 4; } VkDeviceSize end_offset = (index_size * ((VkDeviceSize)firstIndex + indexCount)) + index_buffer_binding.offset; if (end_offset > index_buffer_binding.size) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT, HandleToUint64(index_buffer_binding.buffer), "VUID-vkCmdDrawIndexed-indexSize-00463", "vkCmdDrawIndexed() index size (%d) * (firstIndex (%d) + indexCount (%d)) " "+ binding offset (%" PRIuLEAST64 ") = an ending offset of %" PRIuLEAST64 " bytes, " "which is greater than the index buffer size (%" PRIuLEAST64 ").", index_size, firstIndex, indexCount, index_buffer_binding.offset, end_offset, index_buffer_binding.size); } } return skip; } void PostCallRecordCmdDrawIndexed(layer_data *dev_data, GLOBAL_CB_NODE *cb_state, VkPipelineBindPoint bind_point) { UpdateStateCmdDrawType(dev_data, cb_state, bind_point); } bool PreCallValidateCmdDrawIndirect(layer_data *dev_data, VkCommandBuffer cmd_buffer, VkBuffer buffer, bool indexed, VkPipelineBindPoint bind_point, GLOBAL_CB_NODE **cb_state, BUFFER_STATE **buffer_state, const char *caller) { bool skip = ValidateCmdDrawType(dev_data, cmd_buffer, indexed, bind_point, CMD_DRAWINDIRECT, cb_state, caller, VK_QUEUE_GRAPHICS_BIT, "VUID-vkCmdDrawIndirect-commandBuffer-cmdpool", "VUID-vkCmdDrawIndirect-renderpass", "VUID-vkCmdDrawIndirect-None-00485", "VUID-vkCmdDrawIndirect-None-00486"); *buffer_state = GetBufferState(dev_data, buffer); skip |= ValidateMemoryIsBoundToBuffer(dev_data, *buffer_state, caller, "VUID-vkCmdDrawIndirect-buffer-00474"); // TODO: If the drawIndirectFirstInstance feature is not enabled, all the firstInstance members of the // VkDrawIndirectCommand structures accessed by this command must be 0, which will require access to the contents of 'buffer'. return skip; } void PostCallRecordCmdDrawIndirect(layer_data *dev_data, GLOBAL_CB_NODE *cb_state, VkPipelineBindPoint bind_point, BUFFER_STATE *buffer_state) { UpdateStateCmdDrawType(dev_data, cb_state, bind_point); AddCommandBufferBindingBuffer(dev_data, cb_state, buffer_state); } bool PreCallValidateCmdDrawIndexedIndirect(layer_data *dev_data, VkCommandBuffer cmd_buffer, VkBuffer buffer, bool indexed, VkPipelineBindPoint bind_point, GLOBAL_CB_NODE **cb_state, BUFFER_STATE **buffer_state, const char *caller) { bool skip = ValidateCmdDrawType(dev_data, cmd_buffer, indexed, bind_point, CMD_DRAWINDEXEDINDIRECT, cb_state, caller, VK_QUEUE_GRAPHICS_BIT, "VUID-vkCmdDrawIndexedIndirect-commandBuffer-cmdpool", "VUID-vkCmdDrawIndexedIndirect-renderpass", "VUID-vkCmdDrawIndexedIndirect-None-00537", "VUID-vkCmdDrawIndexedIndirect-None-00538"); *buffer_state = GetBufferState(dev_data, buffer); skip |= ValidateMemoryIsBoundToBuffer(dev_data, *buffer_state, caller, "VUID-vkCmdDrawIndexedIndirect-buffer-00526"); // TODO: If the drawIndirectFirstInstance feature is not enabled, all the firstInstance members of the // VkDrawIndexedIndirectCommand structures accessed by this command must be 0, which will require access to the contents of // 'buffer'. return skip; } void PostCallRecordCmdDrawIndexedIndirect(layer_data *dev_data, GLOBAL_CB_NODE *cb_state, VkPipelineBindPoint bind_point, BUFFER_STATE *buffer_state) { UpdateStateCmdDrawType(dev_data, cb_state, bind_point); AddCommandBufferBindingBuffer(dev_data, cb_state, buffer_state); } bool PreCallValidateCmdDispatch(layer_data *dev_data, VkCommandBuffer cmd_buffer, bool indexed, VkPipelineBindPoint bind_point, GLOBAL_CB_NODE **cb_state, const char *caller) { return ValidateCmdDrawType(dev_data, cmd_buffer, indexed, bind_point, CMD_DISPATCH, cb_state, caller, VK_QUEUE_COMPUTE_BIT, "VUID-vkCmdDispatch-commandBuffer-cmdpool", "VUID-vkCmdDispatch-renderpass", "VUID-vkCmdDispatch-None-00391", kVUIDUndefined); } void PostCallRecordCmdDispatch(layer_data *dev_data, GLOBAL_CB_NODE *cb_state, VkPipelineBindPoint bind_point) { UpdateStateCmdDrawDispatchType(dev_data, cb_state, bind_point); } bool PreCallValidateCmdDispatchIndirect(layer_data *dev_data, VkCommandBuffer cmd_buffer, VkBuffer buffer, bool indexed, VkPipelineBindPoint bind_point, GLOBAL_CB_NODE **cb_state, BUFFER_STATE **buffer_state, const char *caller) { bool skip = ValidateCmdDrawType(dev_data, cmd_buffer, indexed, bind_point, CMD_DISPATCHINDIRECT, cb_state, caller, VK_QUEUE_COMPUTE_BIT, "VUID-vkCmdDispatchIndirect-commandBuffer-cmdpool", "VUID-vkCmdDispatchIndirect-renderpass", "VUID-vkCmdDispatchIndirect-None-00404", kVUIDUndefined); *buffer_state = GetBufferState(dev_data, buffer); skip |= ValidateMemoryIsBoundToBuffer(dev_data, *buffer_state, caller, "VUID-vkCmdDispatchIndirect-buffer-00401"); return skip; } void PostCallRecordCmdDispatchIndirect(layer_data *dev_data, GLOBAL_CB_NODE *cb_state, VkPipelineBindPoint bind_point, BUFFER_STATE *buffer_state) { UpdateStateCmdDrawDispatchType(dev_data, cb_state, bind_point); AddCommandBufferBindingBuffer(dev_data, cb_state, buffer_state); } // Validate that an image's sampleCount matches the requirement for a specific API call bool ValidateImageSampleCount(layer_data *dev_data, IMAGE_STATE *image_state, VkSampleCountFlagBits sample_count, const char *location, const std::string &msgCode) { bool skip = false; if (image_state->createInfo.samples != sample_count) { skip = log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, HandleToUint64(image_state->image), msgCode, "%s for image 0x%" PRIx64 " was created with a sample count of %s but must be %s.", location, HandleToUint64(image_state->image), string_VkSampleCountFlagBits(image_state->createInfo.samples), string_VkSampleCountFlagBits(sample_count)); } return skip; } bool PreCallCmdUpdateBuffer(layer_data *device_data, const GLOBAL_CB_NODE *cb_state, const BUFFER_STATE *dst_buffer_state) { bool skip = false; skip |= ValidateMemoryIsBoundToBuffer(device_data, dst_buffer_state, "vkCmdUpdateBuffer()", "VUID-vkCmdUpdateBuffer-dstBuffer-00035"); // Validate that DST buffer has correct usage flags set skip |= ValidateBufferUsageFlags(device_data, dst_buffer_state, VK_BUFFER_USAGE_TRANSFER_DST_BIT, true, "VUID-vkCmdUpdateBuffer-dstBuffer-00034", "vkCmdUpdateBuffer()", "VK_BUFFER_USAGE_TRANSFER_DST_BIT"); skip |= ValidateCmdQueueFlags(device_data, cb_state, "vkCmdUpdateBuffer()", VK_QUEUE_TRANSFER_BIT | VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT, "VUID-vkCmdUpdateBuffer-commandBuffer-cmdpool"); skip |= ValidateCmd(device_data, cb_state, CMD_UPDATEBUFFER, "vkCmdUpdateBuffer()"); skip |= InsideRenderPass(device_data, cb_state, "vkCmdUpdateBuffer()", "VUID-vkCmdUpdateBuffer-renderpass"); return skip; } void PostCallRecordCmdUpdateBuffer(layer_data *device_data, GLOBAL_CB_NODE *cb_state, BUFFER_STATE *dst_buffer_state) { // Update bindings between buffer and cmd buffer AddCommandBufferBindingBuffer(device_data, cb_state, dst_buffer_state); } bool SetEventStageMask(VkQueue queue, VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) { layer_data *dev_data = GetLayerDataPtr(get_dispatch_key(commandBuffer), layer_data_map); GLOBAL_CB_NODE *pCB = GetCBNode(dev_data, commandBuffer); if (pCB) { pCB->eventToStageMap[event] = stageMask; } auto queue_data = dev_data->queueMap.find(queue); if (queue_data != dev_data->queueMap.end()) { queue_data->second.eventToStageMap[event] = stageMask; } return false; } bool PreCallValidateCmdSetEvent(layer_data *dev_data, GLOBAL_CB_NODE *cb_state, VkPipelineStageFlags stageMask) { bool skip = ValidateCmdQueueFlags(dev_data, cb_state, "vkCmdSetEvent()", VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT, "VUID-vkCmdSetEvent-commandBuffer-cmdpool"); skip |= ValidateCmd(dev_data, cb_state, CMD_SETEVENT, "vkCmdSetEvent()"); skip |= InsideRenderPass(dev_data, cb_state, "vkCmdSetEvent()", "VUID-vkCmdSetEvent-renderpass"); skip |= ValidateStageMaskGsTsEnables(dev_data, stageMask, "vkCmdSetEvent()", "VUID-vkCmdSetEvent-stageMask-01150", "VUID-vkCmdSetEvent-stageMask-01151", "VUID-vkCmdSetEvent-stageMask-02107", "VUID-vkCmdSetEvent-stageMask-02108"); return skip; } void PreCallRecordCmdSetEvent(layer_data *dev_data, GLOBAL_CB_NODE *cb_state, VkCommandBuffer commandBuffer, VkEvent event, VkPipelineStageFlags stageMask) { auto event_state = GetEventNode(dev_data, event); if (event_state) { AddCommandBufferBinding(&event_state->cb_bindings, {HandleToUint64(event), kVulkanObjectTypeEvent}, cb_state); event_state->cb_bindings.insert(cb_state); } cb_state->events.push_back(event); if (!cb_state->waitedEvents.count(event)) { cb_state->writeEventsBeforeWait.push_back(event); } cb_state->eventUpdates.emplace_back([=](VkQueue q) { return SetEventStageMask(q, commandBuffer, event, stageMask); }); } bool PreCallValidateCmdResetEvent(layer_data *dev_data, GLOBAL_CB_NODE *cb_state, VkPipelineStageFlags stageMask) { bool skip = ValidateCmdQueueFlags(dev_data, cb_state, "vkCmdResetEvent()", VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT, "VUID-vkCmdResetEvent-commandBuffer-cmdpool"); skip |= ValidateCmd(dev_data, cb_state, CMD_RESETEVENT, "vkCmdResetEvent()"); skip |= InsideRenderPass(dev_data, cb_state, "vkCmdResetEvent()", "VUID-vkCmdResetEvent-renderpass"); skip |= ValidateStageMaskGsTsEnables(dev_data, stageMask, "vkCmdResetEvent()", "VUID-vkCmdResetEvent-stageMask-01154", "VUID-vkCmdResetEvent-stageMask-01155", "VUID-vkCmdResetEvent-stageMask-02109", "VUID-vkCmdResetEvent-stageMask-02110"); return skip; } void PreCallRecordCmdResetEvent(layer_data *dev_data, GLOBAL_CB_NODE *cb_state, VkCommandBuffer commandBuffer, VkEvent event) { auto event_state = GetEventNode(dev_data, event); if (event_state) { AddCommandBufferBinding(&event_state->cb_bindings, {HandleToUint64(event), kVulkanObjectTypeEvent}, cb_state); event_state->cb_bindings.insert(cb_state); } cb_state->events.push_back(event); if (!cb_state->waitedEvents.count(event)) { cb_state->writeEventsBeforeWait.push_back(event); } // TODO : Add check for "VUID-vkResetEvent-event-01148" cb_state->eventUpdates.emplace_back( [=](VkQueue q) { return SetEventStageMask(q, commandBuffer, event, VkPipelineStageFlags(0)); }); } // Return input pipeline stage flags, expanded for individual bits if VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT is set static VkPipelineStageFlags ExpandPipelineStageFlags(VkPipelineStageFlags inflags) { if (~inflags & VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT) return inflags; return (inflags & ~VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT) | (VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT | VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT | VK_PIPELINE_STAGE_VERTEX_INPUT_BIT | VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT | VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT | VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT | 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 | VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT | VK_PIPELINE_STAGE_SHADING_RATE_IMAGE_BIT_NV | VK_PIPELINE_STAGE_TASK_SHADER_BIT_NV | VK_PIPELINE_STAGE_MESH_SHADER_BIT_NV); } static bool HasNonFramebufferStagePipelineStageFlags(VkPipelineStageFlags 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; } static int GetGraphicsPipelineStageLogicalOrdinal(VkPipelineStageFlagBits flag) { const VkPipelineStageFlagBits ordered_array[] = { VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, VK_PIPELINE_STAGE_VERTEX_SHADER_BIT, VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT, VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT, VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT, // Including the task/mesh shaders here is not technically correct, as they are in a // separate logical pipeline - but it works for the case this is currently used, and // fixing it would require significant rework and end up with the code being far more // verbose for no practical gain. // However, worth paying attention to this if using this function in a new way. VK_PIPELINE_STAGE_TASK_SHADER_BIT_NV, VK_PIPELINE_STAGE_MESH_SHADER_BIT_NV, VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT}; const int ordered_array_length = sizeof(ordered_array) / sizeof(VkPipelineStageFlagBits); for (int i = 0; i < ordered_array_length; ++i) { if (ordered_array[i] == flag) { return i; } } return -1; } // The following two functions technically have O(N^2) complexity, but it's for a value of O that's largely // stable and also rather tiny - this could definitely be rejigged to work more efficiently, but the impact // on runtime is currently negligible, so it wouldn't gain very much. // If we add a lot more graphics pipeline stages, this set of functions should be rewritten to accomodate. static VkPipelineStageFlagBits GetLogicallyEarliestGraphicsPipelineStage(VkPipelineStageFlags inflags) { VkPipelineStageFlagBits earliest_bit = VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT; int earliest_bit_order = GetGraphicsPipelineStageLogicalOrdinal(earliest_bit); for (std::size_t i = 0; i < sizeof(VkPipelineStageFlagBits); ++i) { VkPipelineStageFlagBits current_flag = (VkPipelineStageFlagBits)((inflags & 0x1u) << i); if (current_flag) { int new_order = GetGraphicsPipelineStageLogicalOrdinal(current_flag); if (new_order != -1 && new_order < earliest_bit_order) { earliest_bit_order = new_order; earliest_bit = current_flag; } } inflags = inflags >> 1; } return earliest_bit; } static VkPipelineStageFlagBits GetLogicallyLatestGraphicsPipelineStage(VkPipelineStageFlags inflags) { VkPipelineStageFlagBits latest_bit = VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT; int latest_bit_order = GetGraphicsPipelineStageLogicalOrdinal(latest_bit); for (std::size_t i = 0; i < sizeof(VkPipelineStageFlagBits); ++i) { if (inflags & 0x1u) { int new_order = GetGraphicsPipelineStageLogicalOrdinal((VkPipelineStageFlagBits)((inflags & 0x1u) << i)); if (new_order != -1 && new_order > latest_bit_order) { latest_bit_order = new_order; latest_bit = (VkPipelineStageFlagBits)((inflags & 0x1u) << i); } } inflags = inflags >> 1; } return latest_bit; } // Verify image barrier image state and that the image is consistent with FB image static bool ValidateImageBarrierImage(layer_data *device_data, const char *funcName, GLOBAL_CB_NODE const *cb_state, VkFramebuffer framebuffer, uint32_t active_subpass, const safe_VkSubpassDescription2KHR &sub_desc, uint64_t rp_handle, uint32_t img_index, const VkImageMemoryBarrier &img_barrier) { bool skip = false; const auto &fb_state = GetFramebufferState(device_data, framebuffer); assert(fb_state); const auto img_bar_image = img_barrier.image; bool image_match = false; bool sub_image_found = false; // Do we find a corresponding subpass description VkImageLayout sub_image_layout = VK_IMAGE_LAYOUT_UNDEFINED; uint32_t attach_index = 0; // Verify that a framebuffer image matches barrier image const auto attachmentCount = fb_state->createInfo.attachmentCount; for (uint32_t attachment = 0; attachment < attachmentCount; ++attachment) { auto view_state = GetAttachmentImageViewState(device_data, fb_state, attachment); if (view_state && (img_bar_image == view_state->create_info.image)) { image_match = true; attach_index = attachment; break; } } if (image_match) { // Make sure subpass is referring to matching attachment if (sub_desc.pDepthStencilAttachment && sub_desc.pDepthStencilAttachment->attachment == attach_index) { sub_image_layout = sub_desc.pDepthStencilAttachment->layout; sub_image_found = true; } else if (GetDeviceExtensions(device_data)->vk_khr_depth_stencil_resolve) { const auto *resolve = lvl_find_in_chain<VkSubpassDescriptionDepthStencilResolveKHR>(sub_desc.pNext); if (resolve && resolve->pDepthStencilResolveAttachment && resolve->pDepthStencilResolveAttachment->attachment == attach_index) { sub_image_layout = resolve->pDepthStencilResolveAttachment->layout; sub_image_found = true; } } else { for (uint32_t j = 0; j < sub_desc.colorAttachmentCount; ++j) { if (sub_desc.pColorAttachments && sub_desc.pColorAttachments[j].attachment == attach_index) { sub_image_layout = sub_desc.pColorAttachments[j].layout; sub_image_found = true; break; } else if (sub_desc.pResolveAttachments && sub_desc.pResolveAttachments[j].attachment == attach_index) { sub_image_layout = sub_desc.pResolveAttachments[j].layout; sub_image_found = true; break; } } } if (!sub_image_found) { skip |= log_msg( device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT, rp_handle, "VUID-vkCmdPipelineBarrier-image-01179", "%s: Barrier pImageMemoryBarriers[%d].image (0x%" PRIx64 ") is not referenced by the VkSubpassDescription for active subpass (%d) of current renderPass (0x%" PRIx64 ").", funcName, img_index, HandleToUint64(img_bar_image), active_subpass, rp_handle); } } else { // !image_match auto const fb_handle = HandleToUint64(fb_state->framebuffer); skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_FRAMEBUFFER_EXT, fb_handle, "VUID-vkCmdPipelineBarrier-image-01179", "%s: Barrier pImageMemoryBarriers[%d].image (0x%" PRIx64 ") does not match an image from the current framebuffer (0x%" PRIx64 ").", funcName, img_index, HandleToUint64(img_bar_image), fb_handle); } if (img_barrier.oldLayout != img_barrier.newLayout) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(cb_state->commandBuffer), "VUID-vkCmdPipelineBarrier-oldLayout-01181", "%s: As the Image Barrier for image 0x%" PRIx64 " is being executed within a render pass instance, oldLayout must equal newLayout yet they are %s and %s.", funcName, HandleToUint64(img_barrier.image), string_VkImageLayout(img_barrier.oldLayout), string_VkImageLayout(img_barrier.newLayout)); } else { if (sub_image_found && sub_image_layout != img_barrier.oldLayout) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT, rp_handle, "VUID-vkCmdPipelineBarrier-oldLayout-01180", "%s: Barrier pImageMemoryBarriers[%d].image (0x%" PRIx64 ") is referenced by the VkSubpassDescription for active subpass (%d) of current renderPass (0x%" PRIx64 ") as having layout %s, but image barrier has layout %s.", funcName, img_index, HandleToUint64(img_bar_image), active_subpass, rp_handle, string_VkImageLayout(sub_image_layout), string_VkImageLayout(img_barrier.oldLayout)); } } return skip; } // Validate image barriers within a renderPass static bool ValidateRenderPassImageBarriers(layer_data *device_data, const char *funcName, GLOBAL_CB_NODE *cb_state, uint32_t active_subpass, const safe_VkSubpassDescription2KHR &sub_desc, uint64_t rp_handle, const safe_VkSubpassDependency2KHR *dependencies, const std::vector<uint32_t> &self_dependencies, uint32_t image_mem_barrier_count, const VkImageMemoryBarrier *image_barriers) { bool skip = false; for (uint32_t i = 0; i < image_mem_barrier_count; ++i) { const auto &img_barrier = image_barriers[i]; const auto &img_src_access_mask = img_barrier.srcAccessMask; const auto &img_dst_access_mask = img_barrier.dstAccessMask; bool access_mask_match = false; for (const auto self_dep_index : self_dependencies) { const auto &sub_dep = dependencies[self_dep_index]; access_mask_match = (img_src_access_mask == (sub_dep.srcAccessMask & img_src_access_mask)) && (img_dst_access_mask == (sub_dep.dstAccessMask & img_dst_access_mask)); if (access_mask_match) break; } if (!access_mask_match) { std::stringstream self_dep_ss; stream_join(self_dep_ss, ", ", self_dependencies); skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT, rp_handle, "VUID-vkCmdPipelineBarrier-pDependencies-02285", "%s: Barrier pImageMemoryBarriers[%d].srcAccessMask(0x%X) is not a subset of VkSubpassDependency " "srcAccessMask of subpass %d of renderPass 0x%" PRIx64 ". Candidate VkSubpassDependency are pDependencies entries [%s].", funcName, i, img_src_access_mask, active_subpass, rp_handle, self_dep_ss.str().c_str()); skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT, rp_handle, "VUID-vkCmdPipelineBarrier-pDependencies-02285", "%s: Barrier pImageMemoryBarriers[%d].dstAccessMask(0x%X) is not a subset of VkSubpassDependency " "dstAccessMask of subpass %d of renderPass 0x%" PRIx64 ". Candidate VkSubpassDependency are pDependencies entries [%s].", funcName, i, img_dst_access_mask, active_subpass, rp_handle, self_dep_ss.str().c_str()); } if (VK_QUEUE_FAMILY_IGNORED != img_barrier.srcQueueFamilyIndex || VK_QUEUE_FAMILY_IGNORED != img_barrier.dstQueueFamilyIndex) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT, rp_handle, "VUID-vkCmdPipelineBarrier-srcQueueFamilyIndex-01182", "%s: Barrier pImageMemoryBarriers[%d].srcQueueFamilyIndex is %d and " "pImageMemoryBarriers[%d].dstQueueFamilyIndex is %d but both must be VK_QUEUE_FAMILY_IGNORED.", funcName, i, img_barrier.srcQueueFamilyIndex, i, img_barrier.dstQueueFamilyIndex); } // Secondary CBs can have null framebuffer so queue up validation in that case 'til FB is known if (VK_NULL_HANDLE == cb_state->activeFramebuffer) { assert(VK_COMMAND_BUFFER_LEVEL_SECONDARY == cb_state->createInfo.level); // Secondary CB case w/o FB specified delay validation cb_state->cmd_execute_commands_functions.emplace_back([=](GLOBAL_CB_NODE *primary_cb, VkFramebuffer fb) { return ValidateImageBarrierImage(device_data, funcName, cb_state, fb, active_subpass, sub_desc, rp_handle, i, img_barrier); }); } else { skip |= ValidateImageBarrierImage(device_data, funcName, cb_state, cb_state->activeFramebuffer, active_subpass, sub_desc, rp_handle, i, img_barrier); } } return skip; } // Validate VUs for Pipeline Barriers that are within a renderPass // Pre: cb_state->activeRenderPass must be a pointer to valid renderPass state static bool ValidateRenderPassPipelineBarriers(layer_data *device_data, const char *funcName, GLOBAL_CB_NODE *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) { bool skip = false; const auto rp_state = cb_state->activeRenderPass; const auto active_subpass = cb_state->activeSubpass; auto rp_handle = HandleToUint64(rp_state->renderPass); const auto &self_dependencies = rp_state->self_dependencies[active_subpass]; const auto &dependencies = rp_state->createInfo.pDependencies; if (self_dependencies.size() == 0) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT, rp_handle, "VUID-vkCmdPipelineBarrier-pDependencies-02285", "%s: Barriers cannot be set during subpass %d of renderPass 0x%" PRIx64 " with no self-dependency specified.", funcName, active_subpass, rp_handle); } else { // Grab ref to current subpassDescription up-front for use below const auto &sub_desc = rp_state->createInfo.pSubpasses[active_subpass]; // Look for matching mask in any self-dependency bool stage_mask_match = false; for (const auto self_dep_index : self_dependencies) { const auto &sub_dep = dependencies[self_dep_index]; const auto &sub_src_stage_mask = ExpandPipelineStageFlags(sub_dep.srcStageMask); const auto &sub_dst_stage_mask = ExpandPipelineStageFlags(sub_dep.dstStageMask); stage_mask_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 (stage_mask_match) break; } if (!stage_mask_match) { std::stringstream self_dep_ss; stream_join(self_dep_ss, ", ", self_dependencies); skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT, rp_handle, "VUID-vkCmdPipelineBarrier-pDependencies-02285", "%s: Barrier srcStageMask(0x%X) is not a subset of VkSubpassDependency srcStageMask of any " "self-dependency of subpass %d of renderPass 0x%" PRIx64 " for which dstStageMask is also a subset. " "Candidate VkSubpassDependency are pDependencies entries [%s].", funcName, src_stage_mask, active_subpass, rp_handle, self_dep_ss.str().c_str()); skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT, rp_handle, "VUID-vkCmdPipelineBarrier-pDependencies-02285", "%s: Barrier dstStageMask(0x%X) is not a subset of VkSubpassDependency dstStageMask of any " "self-dependency of subpass %d of renderPass 0x%" PRIx64 " for which srcStageMask is also a subset. " "Candidate VkSubpassDependency are pDependencies entries [%s].", funcName, dst_stage_mask, active_subpass, rp_handle, self_dep_ss.str().c_str()); } if (0 != buffer_mem_barrier_count) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT, rp_handle, "VUID-vkCmdPipelineBarrier-bufferMemoryBarrierCount-01178", "%s: bufferMemoryBarrierCount is non-zero (%d) for subpass %d of renderPass 0x%" PRIx64 ".", funcName, buffer_mem_barrier_count, active_subpass, rp_handle); } for (uint32_t i = 0; i < mem_barrier_count; ++i) { const auto &mb_src_access_mask = mem_barriers[i].srcAccessMask; const auto &mb_dst_access_mask = mem_barriers[i].dstAccessMask; bool access_mask_match = false; for (const auto self_dep_index : self_dependencies) { const auto &sub_dep = dependencies[self_dep_index]; access_mask_match = (mb_src_access_mask == (sub_dep.srcAccessMask & mb_src_access_mask)) && (mb_dst_access_mask == (sub_dep.dstAccessMask & mb_dst_access_mask)); if (access_mask_match) break; } if (!access_mask_match) { std::stringstream self_dep_ss; stream_join(self_dep_ss, ", ", self_dependencies); skip |= log_msg( device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT, rp_handle, "VUID-vkCmdPipelineBarrier-pDependencies-02285", "%s: Barrier pMemoryBarriers[%d].srcAccessMask(0x%X) is not a subset of VkSubpassDependency srcAccessMask " "for any self-dependency of subpass %d of renderPass 0x%" PRIx64 " for which dstAccessMask is also a subset. " "Candidate VkSubpassDependency are pDependencies entries [%s].", funcName, i, mb_src_access_mask, active_subpass, rp_handle, self_dep_ss.str().c_str()); skip |= log_msg( device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT, rp_handle, "VUID-vkCmdPipelineBarrier-pDependencies-02285", "%s: Barrier pMemoryBarriers[%d].dstAccessMask(0x%X) is not a subset of VkSubpassDependency dstAccessMask " "for any self-dependency of subpass %d of renderPass 0x%" PRIx64 " for which srcAccessMask is also a subset. " "Candidate VkSubpassDependency are pDependencies entries [%s].", funcName, i, mb_dst_access_mask, active_subpass, rp_handle, self_dep_ss.str().c_str()); } } skip |= ValidateRenderPassImageBarriers(device_data, funcName, cb_state, active_subpass, sub_desc, rp_handle, dependencies, self_dependencies, image_mem_barrier_count, image_barriers); bool flag_match = false; for (const auto self_dep_index : self_dependencies) { const auto &sub_dep = dependencies[self_dep_index]; flag_match = sub_dep.dependencyFlags == dependency_flags; if (flag_match) break; } if (!flag_match) { std::stringstream self_dep_ss; stream_join(self_dep_ss, ", ", self_dependencies); skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT, rp_handle, "VUID-vkCmdPipelineBarrier-pDependencies-02285", "%s: dependencyFlags param (0x%X) does not equal VkSubpassDependency dependencyFlags value for any " "self-dependency of subpass %d of renderPass 0x%" PRIx64 ". Candidate VkSubpassDependency are pDependencies entries [%s].", funcName, dependency_flags, cb_state->activeSubpass, rp_handle, self_dep_ss.str().c_str()); } } return skip; } // Array to mask individual accessMask to corresponding stageMask // accessMask active bit position (0-31) maps to index const static VkPipelineStageFlags AccessMaskToPipeStage[28] = { // VK_ACCESS_INDIRECT_COMMAND_READ_BIT = 0 VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT, // VK_ACCESS_INDEX_READ_BIT = 1 VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, // VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT = 2 VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, // VK_ACCESS_UNIFORM_READ_BIT = 3 VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT | VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT | VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_TASK_SHADER_BIT_NV | VK_PIPELINE_STAGE_MESH_SHADER_BIT_NV | VK_PIPELINE_STAGE_RAY_TRACING_SHADER_BIT_NV, // VK_ACCESS_INPUT_ATTACHMENT_READ_BIT = 4 VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, // VK_ACCESS_SHADER_READ_BIT = 5 VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT | VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT | VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_TASK_SHADER_BIT_NV | VK_PIPELINE_STAGE_MESH_SHADER_BIT_NV | VK_PIPELINE_STAGE_RAY_TRACING_SHADER_BIT_NV, // VK_ACCESS_SHADER_WRITE_BIT = 6 VK_PIPELINE_STAGE_VERTEX_SHADER_BIT | VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT | VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT | VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT | VK_PIPELINE_STAGE_TASK_SHADER_BIT_NV | VK_PIPELINE_STAGE_MESH_SHADER_BIT_NV | VK_PIPELINE_STAGE_RAY_TRACING_SHADER_BIT_NV, // VK_ACCESS_COLOR_ATTACHMENT_READ_BIT = 7 VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, // VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT = 8 VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, // VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT = 9 VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, // VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT = 10 VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, // VK_ACCESS_TRANSFER_READ_BIT = 11 VK_PIPELINE_STAGE_TRANSFER_BIT, // VK_ACCESS_TRANSFER_WRITE_BIT = 12 VK_PIPELINE_STAGE_TRANSFER_BIT, // VK_ACCESS_HOST_READ_BIT = 13 VK_PIPELINE_STAGE_HOST_BIT, // VK_ACCESS_HOST_WRITE_BIT = 14 VK_PIPELINE_STAGE_HOST_BIT, // VK_ACCESS_MEMORY_READ_BIT = 15 VK_ACCESS_FLAG_BITS_MAX_ENUM, // Always match // VK_ACCESS_MEMORY_WRITE_BIT = 16 VK_ACCESS_FLAG_BITS_MAX_ENUM, // Always match // VK_ACCESS_COMMAND_PROCESS_READ_BIT_NVX = 17 VK_PIPELINE_STAGE_COMMAND_PROCESS_BIT_NVX, // VK_ACCESS_COMMAND_PROCESS_WRITE_BIT_NVX = 18 VK_PIPELINE_STAGE_COMMAND_PROCESS_BIT_NVX, // VK_ACCESS_COLOR_ATTACHMENT_READ_NONCOHERENT_BIT_EXT = 19 VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, // VK_ACCESS_CONDITIONAL_RENDERING_READ_BIT_EXT = 20 VK_PIPELINE_STAGE_CONDITIONAL_RENDERING_BIT_EXT, // VK_ACCESS_ACCELERATION_STRUCTURE_READ_BIT_NV = 21 VK_PIPELINE_STAGE_RAY_TRACING_SHADER_BIT_NV | VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_NV, // VK_ACCESS_ACCELERATION_STRUCTURE_WRITE_BIT_NV = 22 VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_NV, // VK_ACCESS_SHADING_RATE_IMAGE_READ_BIT_NV = 23 VK_PIPELINE_STAGE_SHADING_RATE_IMAGE_BIT_NV, // 24 0, // VK_ACCESS_TRANSFORM_FEEDBACK_WRITE_BIT_EXT = 25 VK_PIPELINE_STAGE_TRANSFORM_FEEDBACK_BIT_EXT, // VK_ACCESS_TRANSFORM_FEEDBACK_COUNTER_READ_BIT_EXT = 26 VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT, // VK_ACCESS_TRANSFORM_FEEDBACK_COUNTER_WRITE_BIT_EXT = 27 VK_PIPELINE_STAGE_TRANSFORM_FEEDBACK_BIT_EXT, }; // Verify that all bits of access_mask are supported by the src_stage_mask static bool ValidateAccessMaskPipelineStage(VkAccessFlags access_mask, VkPipelineStageFlags stage_mask) { // Early out if all commands set, or access_mask NULL if ((stage_mask & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) || (0 == access_mask)) return true; stage_mask = ExpandPipelineStageFlags(stage_mask); int index = 0; // for each of the set bits in access_mask, make sure that supporting stage mask bit(s) are set while (access_mask) { index = (u_ffs(access_mask) - 1); assert(index >= 0); // Must have "!= 0" compare to prevent warning from MSVC if ((AccessMaskToPipeStage[index] & stage_mask) == 0) return false; // early out access_mask &= ~(1 << index); // Mask off bit that's been checked } return true; } namespace barrier_queue_families { enum VuIndex { kSrcOrDstMustBeIgnore, kSpecialOrIgnoreOnly, kSrcIgnoreRequiresDstIgnore, kDstValidOrSpecialIfNotIgnore, kSrcValidOrSpecialIfNotIgnore, kSrcAndDestMustBeIgnore, kBothIgnoreOrBothValid, kSubmitQueueMustMatchSrcOrDst }; static const char *vu_summary[] = {"Source or destination queue family must be ignored.", "Source or destination queue family must be special or ignored.", "Destination queue family must be ignored if source queue family is.", "Destination queue family must be valid, ignored, or special.", "Source queue family must be valid, ignored, or special.", "Source and destination queue family must both be ignored.", "Source and destination queue family must both be ignore or both valid.", "Source or destination queue family must match submit queue family, if not ignored."}; static const std::string image_error_codes[] = { "VUID-VkImageMemoryBarrier-image-01381", // kSrcOrDstMustBeIgnore "VUID-VkImageMemoryBarrier-image-01766", // kSpecialOrIgnoreOnly "VUID-VkImageMemoryBarrier-image-01201", // kSrcIgnoreRequiresDstIgnore "VUID-VkImageMemoryBarrier-image-01768", // kDstValidOrSpecialIfNotIgnore "VUID-VkImageMemoryBarrier-image-01767", // kSrcValidOrSpecialIfNotIgnore "VUID-VkImageMemoryBarrier-image-01199", // kSrcAndDestMustBeIgnore "VUID-VkImageMemoryBarrier-image-01200", // kBothIgnoreOrBothValid "VUID-VkImageMemoryBarrier-image-01205", // kSubmitQueueMustMatchSrcOrDst }; static const std::string buffer_error_codes[] = { "VUID-VkBufferMemoryBarrier-buffer-01191", // kSrcOrDstMustBeIgnore "VUID-VkBufferMemoryBarrier-buffer-01763", // kSpecialOrIgnoreOnly "VUID-VkBufferMemoryBarrier-buffer-01193", // kSrcIgnoreRequiresDstIgnore "VUID-VkBufferMemoryBarrier-buffer-01765", // kDstValidOrSpecialIfNotIgnore "VUID-VkBufferMemoryBarrier-buffer-01764", // kSrcValidOrSpecialIfNotIgnore "VUID-VkBufferMemoryBarrier-buffer-01190", // kSrcAndDestMustBeIgnore "VUID-VkBufferMemoryBarrier-buffer-01192", // kBothIgnoreOrBothValid "VUID-VkBufferMemoryBarrier-buffer-01196", // kSubmitQueueMustMatchSrcOrDst }; class ValidatorState { public: ValidatorState(const layer_data *device_data, const char *func_name, const GLOBAL_CB_NODE *cb_state, const uint64_t barrier_handle64, const VkSharingMode sharing_mode, const VulkanObjectType object_type, const std::string *val_codes) : report_data_(device_data->report_data), func_name_(func_name), cb_handle64_(HandleToUint64(cb_state->commandBuffer)), barrier_handle64_(barrier_handle64), sharing_mode_(sharing_mode), object_type_(object_type), val_codes_(val_codes), limit_(static_cast<uint32_t>(device_data->phys_dev_properties.queue_family_properties.size())), mem_ext_(device_data->extensions.vk_khr_external_memory) {} // Create a validator state from an image state... reducing the image specific to the generic version. ValidatorState(const layer_data *device_data, const char *func_name, const GLOBAL_CB_NODE *cb_state, const VkImageMemoryBarrier *barrier, const IMAGE_STATE *state) : ValidatorState(device_data, func_name, cb_state, HandleToUint64(barrier->image), state->createInfo.sharingMode, kVulkanObjectTypeImage, image_error_codes) {} // Create a validator state from an buffer state... reducing the buffer specific to the generic version. ValidatorState(const layer_data *device_data, const char *func_name, const GLOBAL_CB_NODE *cb_state, const VkBufferMemoryBarrier *barrier, const BUFFER_STATE *state) : ValidatorState(device_data, func_name, cb_state, HandleToUint64(barrier->buffer), state->createInfo.sharingMode, kVulkanObjectTypeImage, buffer_error_codes) {} // Log the messages using boilerplate from object state, and Vu specific information from the template arg // One and two family versions, in the single family version, Vu holds the name of the passed parameter bool LogMsg(VuIndex vu_index, uint32_t family, const char *param_name) const { const std::string val_code = val_codes_[vu_index]; const char *annotation = GetFamilyAnnotation(family); return log_msg(report_data_, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, cb_handle64_, val_code, "%s: Barrier using %s 0x%" PRIx64 " created with sharingMode %s, has %s %u%s. %s", func_name_, GetTypeString(), barrier_handle64_, GetModeString(), param_name, family, annotation, vu_summary[vu_index]); } bool LogMsg(VuIndex vu_index, uint32_t src_family, uint32_t dst_family) const { const std::string val_code = val_codes_[vu_index]; const char *src_annotation = GetFamilyAnnotation(src_family); const char *dst_annotation = GetFamilyAnnotation(dst_family); return log_msg(report_data_, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, cb_handle64_, val_code, "%s: Barrier using %s 0x%" PRIx64 " created with sharingMode %s, has srcQueueFamilyIndex %u%s and dstQueueFamilyIndex %u%s. %s", func_name_, GetTypeString(), barrier_handle64_, GetModeString(), src_family, src_annotation, dst_family, dst_annotation, vu_summary[vu_index]); } // This abstract Vu can only be tested at submit time, thus we need a callback from the closure containing the needed // data. Note that the mem_barrier is copied to the closure as the lambda lifespan exceed the guarantees of validity for // application input. static bool ValidateAtQueueSubmit(const VkQueue queue, const layer_data *device_data, uint32_t src_family, uint32_t dst_family, const ValidatorState &val) { auto queue_data_it = device_data->queueMap.find(queue); if (queue_data_it == device_data->queueMap.end()) return false; uint32_t queue_family = queue_data_it->second.queueFamilyIndex; if ((src_family != queue_family) && (dst_family != queue_family)) { const std::string val_code = val.val_codes_[kSubmitQueueMustMatchSrcOrDst]; const char *src_annotation = val.GetFamilyAnnotation(src_family); const char *dst_annotation = val.GetFamilyAnnotation(dst_family); return log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_QUEUE_EXT, HandleToUint64(queue), val_code, "%s: Barrier submitted to queue with family index %u, using %s 0x%" PRIx64 " created with sharingMode %s, has srcQueueFamilyIndex %u%s and dstQueueFamilyIndex %u%s. %s", "vkQueueSubmit", queue_family, val.GetTypeString(), val.barrier_handle64_, val.GetModeString(), src_family, src_annotation, dst_family, dst_annotation, vu_summary[kSubmitQueueMustMatchSrcOrDst]); } return false; } // Logical helpers for semantic clarity inline bool KhrExternalMem() const { return mem_ext_; } inline bool IsValid(uint32_t queue_family) const { return (queue_family < limit_); } inline bool IsValidOrSpecial(uint32_t queue_family) const { return IsValid(queue_family) || (mem_ext_ && IsSpecial(queue_family)); } inline bool IsIgnored(uint32_t queue_family) const { return queue_family == VK_QUEUE_FAMILY_IGNORED; } // Helpers for LogMsg (and log_msg) const char *GetModeString() const { return string_VkSharingMode(sharing_mode_); } // Descriptive text for the various types of queue family index const char *GetFamilyAnnotation(uint32_t family) const { const char *external = " (VK_QUEUE_FAMILY_EXTERNAL_KHR)"; const char *foreign = " (VK_QUEUE_FAMILY_FOREIGN_EXT)"; const char *ignored = " (VK_QUEUE_FAMILY_IGNORED)"; const char *valid = " (VALID)"; const char *invalid = " (INVALID)"; switch (family) { case VK_QUEUE_FAMILY_EXTERNAL_KHR: return external; case VK_QUEUE_FAMILY_FOREIGN_EXT: return foreign; case VK_QUEUE_FAMILY_IGNORED: return ignored; default: if (IsValid(family)) { return valid; } return invalid; }; } const char *GetTypeString() const { return object_string[object_type_]; } VkSharingMode GetSharingMode() const { return sharing_mode_; } protected: const debug_report_data *const report_data_; const char *const func_name_; const uint64_t cb_handle64_; const uint64_t barrier_handle64_; const VkSharingMode sharing_mode_; const VulkanObjectType object_type_; const std::string *val_codes_; const uint32_t limit_; const bool mem_ext_; }; bool Validate(const layer_data *device_data, const char *func_name, GLOBAL_CB_NODE *cb_state, const ValidatorState &val, const uint32_t src_queue_family, const uint32_t dst_queue_family) { bool skip = false; const bool mode_concurrent = val.GetSharingMode() == VK_SHARING_MODE_CONCURRENT; const bool src_ignored = val.IsIgnored(src_queue_family); const bool dst_ignored = val.IsIgnored(dst_queue_family); if (val.KhrExternalMem()) { if (mode_concurrent) { if (!(src_ignored || dst_ignored)) { skip |= val.LogMsg(kSrcOrDstMustBeIgnore, src_queue_family, dst_queue_family); } if ((src_ignored && !(dst_ignored || IsSpecial(dst_queue_family))) || (dst_ignored && !(src_ignored || IsSpecial(src_queue_family)))) { skip |= val.LogMsg(kSpecialOrIgnoreOnly, src_queue_family, dst_queue_family); } } else { // VK_SHARING_MODE_EXCLUSIVE if (src_ignored && !dst_ignored) { skip |= val.LogMsg(kSrcIgnoreRequiresDstIgnore, src_queue_family, dst_queue_family); } if (!dst_ignored && !val.IsValidOrSpecial(dst_queue_family)) { skip |= val.LogMsg(kDstValidOrSpecialIfNotIgnore, dst_queue_family, "dstQueueFamilyIndex"); } if (!src_ignored && !val.IsValidOrSpecial(src_queue_family)) { skip |= val.LogMsg(kSrcValidOrSpecialIfNotIgnore, src_queue_family, "srcQueueFamilyIndex"); } } } else { // No memory extension if (mode_concurrent) { if (!src_ignored || !dst_ignored) { skip |= val.LogMsg(kSrcAndDestMustBeIgnore, src_queue_family, dst_queue_family); } } else { // VK_SHARING_MODE_EXCLUSIVE if (!((src_ignored && dst_ignored) || (val.IsValid(src_queue_family) && val.IsValid(dst_queue_family)))) { skip |= val.LogMsg(kBothIgnoreOrBothValid, src_queue_family, dst_queue_family); } } } if (!mode_concurrent && !src_ignored && !dst_ignored) { // Only enqueue submit time check if it is needed. If more submit time checks are added, change the criteria // TODO create a better named list, or rename the submit time lists to something that matches the broader usage... // Note: if we want to create a semantic that separates state lookup, validation, and state update this should go // to a local queue of update_state_actions or something. cb_state->eventUpdates.emplace_back([device_data, src_queue_family, dst_queue_family, val](VkQueue queue) { return ValidatorState::ValidateAtQueueSubmit(queue, device_data, src_queue_family, dst_queue_family, val); }); } return skip; } } // namespace barrier_queue_families // Type specific wrapper for image barriers bool ValidateBarrierQueueFamilies(const layer_data *device_data, const char *func_name, GLOBAL_CB_NODE *cb_state, const VkImageMemoryBarrier *barrier, const IMAGE_STATE *state_data) { // State data is required if (!state_data) { return false; } // Create the validator state from the image state barrier_queue_families::ValidatorState val(device_data, func_name, cb_state, barrier, state_data); const uint32_t src_queue_family = barrier->srcQueueFamilyIndex; const uint32_t dst_queue_family = barrier->dstQueueFamilyIndex; return barrier_queue_families::Validate(device_data, func_name, cb_state, val, src_queue_family, dst_queue_family); } // Type specific wrapper for buffer barriers bool ValidateBarrierQueueFamilies(const layer_data *device_data, const char *func_name, GLOBAL_CB_NODE *cb_state, const VkBufferMemoryBarrier *barrier, const BUFFER_STATE *state_data) { // State data is required if (!state_data) { return false; } // Create the validator state from the buffer state barrier_queue_families::ValidatorState val(device_data, func_name, cb_state, barrier, state_data); const uint32_t src_queue_family = barrier->srcQueueFamilyIndex; const uint32_t dst_queue_family = barrier->dstQueueFamilyIndex; return barrier_queue_families::Validate(device_data, func_name, cb_state, val, src_queue_family, dst_queue_family); } static bool ValidateBarriers(layer_data *device_data, const char *funcName, GLOBAL_CB_NODE *cb_state, VkPipelineStageFlags src_stage_mask, VkPipelineStageFlags dst_stage_mask, uint32_t memBarrierCount, const VkMemoryBarrier *pMemBarriers, uint32_t bufferBarrierCount, const VkBufferMemoryBarrier *pBufferMemBarriers, uint32_t imageMemBarrierCount, const VkImageMemoryBarrier *pImageMemBarriers) { bool skip = false; for (uint32_t i = 0; i < memBarrierCount; ++i) { const auto &mem_barrier = pMemBarriers[i]; if (!ValidateAccessMaskPipelineStage(mem_barrier.srcAccessMask, src_stage_mask)) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(cb_state->commandBuffer), "VUID-vkCmdPipelineBarrier-pMemoryBarriers-01184", "%s: pMemBarriers[%d].srcAccessMask (0x%X) is not supported by srcStageMask (0x%X).", funcName, i, mem_barrier.srcAccessMask, src_stage_mask); } if (!ValidateAccessMaskPipelineStage(mem_barrier.dstAccessMask, dst_stage_mask)) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(cb_state->commandBuffer), "VUID-vkCmdPipelineBarrier-pMemoryBarriers-01185", "%s: pMemBarriers[%d].dstAccessMask (0x%X) is not supported by dstStageMask (0x%X).", funcName, i, mem_barrier.dstAccessMask, dst_stage_mask); } } for (uint32_t i = 0; i < imageMemBarrierCount; ++i) { auto mem_barrier = &pImageMemBarriers[i]; if (!ValidateAccessMaskPipelineStage(mem_barrier->srcAccessMask, src_stage_mask)) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(cb_state->commandBuffer), "VUID-vkCmdPipelineBarrier-pMemoryBarriers-01184", "%s: pImageMemBarriers[%d].srcAccessMask (0x%X) is not supported by srcStageMask (0x%X).", funcName, i, mem_barrier->srcAccessMask, src_stage_mask); } if (!ValidateAccessMaskPipelineStage(mem_barrier->dstAccessMask, dst_stage_mask)) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(cb_state->commandBuffer), "VUID-vkCmdPipelineBarrier-pMemoryBarriers-01185", "%s: pImageMemBarriers[%d].dstAccessMask (0x%X) is not supported by dstStageMask (0x%X).", funcName, i, mem_barrier->dstAccessMask, dst_stage_mask); } auto image_data = GetImageState(device_data, mem_barrier->image); skip |= ValidateBarrierQueueFamilies(device_data, funcName, cb_state, mem_barrier, image_data); if (mem_barrier->newLayout == VK_IMAGE_LAYOUT_UNDEFINED || mem_barrier->newLayout == VK_IMAGE_LAYOUT_PREINITIALIZED) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(cb_state->commandBuffer), "VUID-VkImageMemoryBarrier-newLayout-01198", "%s: Image Layout cannot be transitioned to UNDEFINED or PREINITIALIZED.", funcName); } if (image_data) { // There is no VUID for this, but there is blanket text: // "Non-sparse resources must be bound completely and contiguously to a single VkDeviceMemory object before // recording commands in a command buffer." // TODO: Update this when VUID is defined skip |= ValidateMemoryIsBoundToImage(device_data, image_data, funcName, kVUIDUndefined); auto aspect_mask = mem_barrier->subresourceRange.aspectMask; skip |= ValidateImageAspectMask(device_data, image_data->image, image_data->createInfo.format, aspect_mask, funcName); std::string param_name = "pImageMemoryBarriers[" + std::to_string(i) + "].subresourceRange"; skip |= ValidateImageBarrierSubresourceRange(device_data, image_data, mem_barrier->subresourceRange, funcName, param_name.c_str()); } } for (uint32_t i = 0; i < bufferBarrierCount; ++i) { auto mem_barrier = &pBufferMemBarriers[i]; if (!mem_barrier) continue; if (!ValidateAccessMaskPipelineStage(mem_barrier->srcAccessMask, src_stage_mask)) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(cb_state->commandBuffer), "VUID-vkCmdPipelineBarrier-pMemoryBarriers-01184", "%s: pBufferMemBarriers[%d].srcAccessMask (0x%X) is not supported by srcStageMask (0x%X).", funcName, i, mem_barrier->srcAccessMask, src_stage_mask); } if (!ValidateAccessMaskPipelineStage(mem_barrier->dstAccessMask, dst_stage_mask)) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(cb_state->commandBuffer), "VUID-vkCmdPipelineBarrier-pMemoryBarriers-01185", "%s: pBufferMemBarriers[%d].dstAccessMask (0x%X) is not supported by dstStageMask (0x%X).", funcName, i, mem_barrier->dstAccessMask, dst_stage_mask); } // Validate buffer barrier queue family indices auto buffer_state = GetBufferState(device_data, mem_barrier->buffer); skip |= ValidateBarrierQueueFamilies(device_data, funcName, cb_state, mem_barrier, buffer_state); if (buffer_state) { // There is no VUID for this, but there is blanket text: // "Non-sparse resources must be bound completely and contiguously to a single VkDeviceMemory object before // recording commands in a command buffer" // TODO: Update this when VUID is defined skip |= ValidateMemoryIsBoundToBuffer(device_data, buffer_state, funcName, kVUIDUndefined); auto buffer_size = buffer_state->createInfo.size; if (mem_barrier->offset >= buffer_size) { skip |= log_msg( device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(cb_state->commandBuffer), "VUID-VkBufferMemoryBarrier-offset-01187", "%s: Buffer Barrier 0x%" PRIx64 " has offset 0x%" PRIx64 " which is not less than total size 0x%" PRIx64 ".", funcName, HandleToUint64(mem_barrier->buffer), HandleToUint64(mem_barrier->offset), HandleToUint64(buffer_size)); } else if (mem_barrier->size != VK_WHOLE_SIZE && (mem_barrier->offset + mem_barrier->size > buffer_size)) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(cb_state->commandBuffer), "VUID-VkBufferMemoryBarrier-size-01189", "%s: Buffer Barrier 0x%" PRIx64 " has offset 0x%" PRIx64 " and size 0x%" PRIx64 " whose sum is greater than total size 0x%" PRIx64 ".", funcName, HandleToUint64(mem_barrier->buffer), HandleToUint64(mem_barrier->offset), HandleToUint64(mem_barrier->size), HandleToUint64(buffer_size)); } } } skip |= ValidateBarriersQFOTransferUniqueness(device_data, funcName, cb_state, bufferBarrierCount, pBufferMemBarriers, imageMemBarrierCount, pImageMemBarriers); return skip; } bool ValidateEventStageMask(VkQueue queue, GLOBAL_CB_NODE *pCB, uint32_t eventCount, size_t firstEventIndex, VkPipelineStageFlags sourceStageMask) { bool skip = false; VkPipelineStageFlags stageMask = 0; layer_data *dev_data = GetLayerDataPtr(get_dispatch_key(queue), layer_data_map); for (uint32_t i = 0; i < eventCount; ++i) { auto event = pCB->events[firstEventIndex + i]; auto queue_data = dev_data->queueMap.find(queue); if (queue_data == dev_data->queueMap.end()) return false; auto event_data = queue_data->second.eventToStageMap.find(event); if (event_data != queue_data->second.eventToStageMap.end()) { stageMask |= event_data->second; } else { auto global_event_data = GetEventNode(dev_data, event); if (!global_event_data) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_EVENT_EXT, HandleToUint64(event), kVUID_Core_DrawState_InvalidEvent, "Event 0x%" PRIx64 " cannot be waited on if it has never been set.", HandleToUint64(event)); } else { stageMask |= 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 != stageMask && sourceStageMask != (stageMask | VK_PIPELINE_STAGE_HOST_BIT)) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(pCB->commandBuffer), "VUID-vkCmdWaitEvents-srcStageMask-parameter", "Submitting cmdbuffer with call to VkCmdWaitEvents using srcStageMask 0x%X 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%X.", sourceStageMask, stageMask); } return skip; } // Note that we only check bits that HAVE required queueflags -- don't care entries are skipped static std::unordered_map<VkPipelineStageFlags, VkQueueFlags> supported_pipeline_stages_table = { {VK_PIPELINE_STAGE_COMMAND_PROCESS_BIT_NVX, VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT}, {VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT, VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT}, {VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, VK_QUEUE_GRAPHICS_BIT}, {VK_PIPELINE_STAGE_VERTEX_SHADER_BIT, VK_QUEUE_GRAPHICS_BIT}, {VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT, VK_QUEUE_GRAPHICS_BIT}, {VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT, VK_QUEUE_GRAPHICS_BIT}, {VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT, VK_QUEUE_GRAPHICS_BIT}, {VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_QUEUE_GRAPHICS_BIT}, {VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT, VK_QUEUE_GRAPHICS_BIT}, {VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, VK_QUEUE_GRAPHICS_BIT}, {VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_QUEUE_GRAPHICS_BIT}, {VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_QUEUE_COMPUTE_BIT}, {VK_PIPELINE_STAGE_TRANSFER_BIT, VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT | VK_QUEUE_TRANSFER_BIT}, {VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, VK_QUEUE_GRAPHICS_BIT}}; static const VkPipelineStageFlags stage_flag_bit_array[] = {VK_PIPELINE_STAGE_COMMAND_PROCESS_BIT_NVX, VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, VK_PIPELINE_STAGE_VERTEX_SHADER_BIT, VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT, VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT, VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT, 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, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT}; bool CheckStageMaskQueueCompatibility(layer_data *dev_data, VkCommandBuffer command_buffer, VkPipelineStageFlags stage_mask, VkQueueFlags queue_flags, const char *function, const char *src_or_dest, std::string error_code) { bool skip = false; // Lookup each bit in the stagemask and check for overlap between its table bits and queue_flags for (const auto &item : stage_flag_bit_array) { if (stage_mask & item) { if ((supported_pipeline_stages_table[item] & queue_flags) == 0) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(command_buffer), error_code, "%s(): %s flag %s is not compatible with the queue family properties of this command buffer.", function, src_or_dest, string_VkPipelineStageFlagBits(static_cast<VkPipelineStageFlagBits>(item))); } } } return skip; } // Check if all barriers are of a given operation type. template <typename Barrier, typename OpCheck> static bool AllTransferOp(const COMMAND_POOL_NODE *pool, OpCheck &op_check, uint32_t count, const Barrier *barriers) { if (!pool) return false; for (uint32_t b = 0; b < count; b++) { if (!op_check(pool, barriers + b)) return false; } return true; } enum BarrierOperationsType { kAllAcquire, // All Barrier operations are "ownership acquire" operations kAllRelease, // All Barrier operations are "ownership release" operations kGeneral, // Either no ownership operations or a mix of ownership operation types and/or non-ownership operations }; // Look at the barriers to see if we they are all release or all acquire, the result impacts queue properties validation BarrierOperationsType ComputeBarrierOperationsType(layer_data *device_data, GLOBAL_CB_NODE *cb_state, uint32_t buffer_barrier_count, const VkBufferMemoryBarrier *buffer_barriers, uint32_t image_barrier_count, const VkImageMemoryBarrier *image_barriers) { auto pool = GetCommandPoolNode(device_data, cb_state->createInfo.commandPool); BarrierOperationsType op_type = kGeneral; // Look at the barrier details only if they exist // Note: AllTransferOp returns true for count == 0 if ((buffer_barrier_count + image_barrier_count) != 0) { if (AllTransferOp(pool, IsReleaseOp<VkBufferMemoryBarrier>, buffer_barrier_count, buffer_barriers) && AllTransferOp(pool, IsReleaseOp<VkImageMemoryBarrier>, image_barrier_count, image_barriers)) { op_type = kAllRelease; } else if (AllTransferOp(pool, IsAcquireOp<VkBufferMemoryBarrier>, buffer_barrier_count, buffer_barriers) && AllTransferOp(pool, IsAcquireOp<VkImageMemoryBarrier>, image_barrier_count, image_barriers)) { op_type = kAllAcquire; } } return op_type; } bool ValidateStageMasksAgainstQueueCapabilities(layer_data *dev_data, GLOBAL_CB_NODE const *cb_state, VkPipelineStageFlags source_stage_mask, VkPipelineStageFlags dest_stage_mask, BarrierOperationsType barrier_op_type, const char *function, std::string error_code) { bool skip = false; uint32_t queue_family_index = dev_data->commandPoolMap[cb_state->createInfo.commandPool].queueFamilyIndex; instance_layer_data *instance_data = GetLayerDataPtr(get_dispatch_key(dev_data->physical_device), instance_layer_data_map); auto physical_device_state = GetPhysicalDeviceState(instance_data, dev_data->physical_device); // Any pipeline stage included in srcStageMask or dstStageMask must be supported by the capabilities of the queue family // specified by the queueFamilyIndex member of the VkCommandPoolCreateInfo structure that was used to create the VkCommandPool // that commandBuffer was allocated from, as specified in the table of supported pipeline stages. if (queue_family_index < physical_device_state->queue_family_properties.size()) { VkQueueFlags specified_queue_flags = physical_device_state->queue_family_properties[queue_family_index].queueFlags; // Only check the source stage mask if any barriers aren't "acquire ownership" if ((barrier_op_type != kAllAcquire) && (source_stage_mask & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) == 0) { skip |= CheckStageMaskQueueCompatibility(dev_data, cb_state->commandBuffer, source_stage_mask, specified_queue_flags, function, "srcStageMask", error_code); } // Only check the dest stage mask if any barriers aren't "release ownership" if ((barrier_op_type != kAllRelease) && (dest_stage_mask & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) == 0) { skip |= CheckStageMaskQueueCompatibility(dev_data, cb_state->commandBuffer, dest_stage_mask, specified_queue_flags, function, "dstStageMask", error_code); } } return skip; } bool PreCallValidateCmdEventCount(layer_data *dev_data, GLOBAL_CB_NODE *cb_state, VkPipelineStageFlags sourceStageMask, VkPipelineStageFlags dstStageMask, uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount, const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount, const VkImageMemoryBarrier *pImageMemoryBarriers) { auto barrier_op_type = ComputeBarrierOperationsType(dev_data, cb_state, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers); bool skip = ValidateStageMasksAgainstQueueCapabilities(dev_data, cb_state, sourceStageMask, dstStageMask, barrier_op_type, "vkCmdWaitEvents", "VUID-vkCmdWaitEvents-srcStageMask-01164"); skip |= ValidateStageMaskGsTsEnables(dev_data, sourceStageMask, "vkCmdWaitEvents()", "VUID-vkCmdWaitEvents-srcStageMask-01159", "VUID-vkCmdWaitEvents-srcStageMask-01161", "VUID-vkCmdWaitEvents-srcStageMask-02111", "VUID-vkCmdWaitEvents-srcStageMask-02112"); skip |= ValidateStageMaskGsTsEnables(dev_data, dstStageMask, "vkCmdWaitEvents()", "VUID-vkCmdWaitEvents-dstStageMask-01160", "VUID-vkCmdWaitEvents-dstStageMask-01162", "VUID-vkCmdWaitEvents-dstStageMask-02113", "VUID-vkCmdWaitEvents-dstStageMask-02114"); skip |= ValidateCmdQueueFlags(dev_data, cb_state, "vkCmdWaitEvents()", VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT, "VUID-vkCmdWaitEvents-commandBuffer-cmdpool"); skip |= ValidateCmd(dev_data, cb_state, CMD_WAITEVENTS, "vkCmdWaitEvents()"); skip |= ValidateBarriersToImages(dev_data, cb_state, imageMemoryBarrierCount, pImageMemoryBarriers, "vkCmdWaitEvents()"); skip |= ValidateBarriers(dev_data, "vkCmdWaitEvents()", cb_state, sourceStageMask, dstStageMask, memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers); return skip; } void PreCallRecordCmdWaitEvents(layer_data *dev_data, GLOBAL_CB_NODE *cb_state, uint32_t eventCount, const VkEvent *pEvents, VkPipelineStageFlags sourceStageMask, uint32_t imageMemoryBarrierCount, const VkImageMemoryBarrier *pImageMemoryBarriers) { auto first_event_index = cb_state->events.size(); for (uint32_t i = 0; i < eventCount; ++i) { auto event_state = GetEventNode(dev_data, pEvents[i]); if (event_state) { AddCommandBufferBinding(&event_state->cb_bindings, {HandleToUint64(pEvents[i]), kVulkanObjectTypeEvent}, cb_state); event_state->cb_bindings.insert(cb_state); } cb_state->waitedEvents.insert(pEvents[i]); cb_state->events.push_back(pEvents[i]); } cb_state->eventUpdates.emplace_back( [=](VkQueue q) { return ValidateEventStageMask(q, cb_state, eventCount, first_event_index, sourceStageMask); }); TransitionImageLayouts(dev_data, cb_state, imageMemoryBarrierCount, pImageMemoryBarriers); if (GetEnables(dev_data)->gpu_validation) { GpuPreCallValidateCmdWaitEvents(dev_data, sourceStageMask); } } void PostCallRecordCmdWaitEvents(layer_data *dev_data, GLOBAL_CB_NODE *cb_state, uint32_t bufferMemoryBarrierCount, const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount, const VkImageMemoryBarrier *pImageMemoryBarriers) { RecordBarriersQFOTransfers(dev_data, "vkCmdWaitEvents()", cb_state, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers); } bool PreCallValidateCmdPipelineBarrier(layer_data *device_data, GLOBAL_CB_NODE *cb_state, VkPipelineStageFlags srcStageMask, VkPipelineStageFlags dstStageMask, VkDependencyFlags dependencyFlags, uint32_t memoryBarrierCount, const VkMemoryBarrier *pMemoryBarriers, uint32_t bufferMemoryBarrierCount, const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount, const VkImageMemoryBarrier *pImageMemoryBarriers) { bool skip = false; auto barrier_op_type = ComputeBarrierOperationsType(device_data, cb_state, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers); skip |= ValidateStageMasksAgainstQueueCapabilities(device_data, cb_state, srcStageMask, dstStageMask, barrier_op_type, "vkCmdPipelineBarrier", "VUID-vkCmdPipelineBarrier-srcStageMask-01183"); skip |= ValidateCmdQueueFlags(device_data, cb_state, "vkCmdPipelineBarrier()", VK_QUEUE_TRANSFER_BIT | VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT, "VUID-vkCmdPipelineBarrier-commandBuffer-cmdpool"); skip |= ValidateCmd(device_data, cb_state, CMD_PIPELINEBARRIER, "vkCmdPipelineBarrier()"); skip |= ValidateStageMaskGsTsEnables( device_data, srcStageMask, "vkCmdPipelineBarrier()", "VUID-vkCmdPipelineBarrier-srcStageMask-01168", "VUID-vkCmdPipelineBarrier-srcStageMask-01170", "VUID-vkCmdPipelineBarrier-srcStageMask-02115", "VUID-vkCmdPipelineBarrier-srcStageMask-02116"); skip |= ValidateStageMaskGsTsEnables( device_data, dstStageMask, "vkCmdPipelineBarrier()", "VUID-vkCmdPipelineBarrier-dstStageMask-01169", "VUID-vkCmdPipelineBarrier-dstStageMask-01171", "VUID-vkCmdPipelineBarrier-dstStageMask-02117", "VUID-vkCmdPipelineBarrier-dstStageMask-02118"); if (cb_state->activeRenderPass) { skip |= ValidateRenderPassPipelineBarriers(device_data, "vkCmdPipelineBarrier()", cb_state, srcStageMask, dstStageMask, dependencyFlags, memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers); if (skip) return true; // Early return to avoid redundant errors from below calls } skip |= ValidateBarriersToImages(device_data, cb_state, imageMemoryBarrierCount, pImageMemoryBarriers, "vkCmdPipelineBarrier()"); skip |= ValidateBarriers(device_data, "vkCmdPipelineBarrier()", cb_state, srcStageMask, dstStageMask, memoryBarrierCount, pMemoryBarriers, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers); return skip; } void PreCallRecordCmdPipelineBarrier(layer_data *device_data, GLOBAL_CB_NODE *cb_state, VkCommandBuffer commandBuffer, uint32_t bufferMemoryBarrierCount, const VkBufferMemoryBarrier *pBufferMemoryBarriers, uint32_t imageMemoryBarrierCount, const VkImageMemoryBarrier *pImageMemoryBarriers) { RecordBarriersQFOTransfers(device_data, "vkCmdPipelineBarrier()", cb_state, bufferMemoryBarrierCount, pBufferMemoryBarriers, imageMemoryBarrierCount, pImageMemoryBarriers); TransitionImageLayouts(device_data, cb_state, imageMemoryBarrierCount, pImageMemoryBarriers); } static bool SetQueryState(VkQueue queue, VkCommandBuffer commandBuffer, QueryObject object, bool value) { layer_data *dev_data = GetLayerDataPtr(get_dispatch_key(commandBuffer), layer_data_map); GLOBAL_CB_NODE *pCB = GetCBNode(dev_data, commandBuffer); if (pCB) { pCB->queryToStateMap[object] = value; } auto queue_data = dev_data->queueMap.find(queue); if (queue_data != dev_data->queueMap.end()) { queue_data->second.queryToStateMap[object] = value; } return false; } bool PreCallValidateCmdBeginQuery(layer_data *dev_data, GLOBAL_CB_NODE *pCB, VkQueryPool queryPool, VkFlags flags) { bool skip = ValidateCmdQueueFlags(dev_data, pCB, "vkCmdBeginQuery()", VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT, "VUID-vkCmdBeginQuery-commandBuffer-cmdpool"); auto queryType = GetQueryPoolNode(dev_data, queryPool)->createInfo.queryType; if (flags & VK_QUERY_CONTROL_PRECISE_BIT) { if (!dev_data->enabled_features.core.occlusionQueryPrecise) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(pCB->commandBuffer), "VUID-vkCmdBeginQuery-queryType-00800", "VK_QUERY_CONTROL_PRECISE_BIT provided to vkCmdBeginQuery, but precise occlusion queries not enabled " "on the device."); } if (queryType != VK_QUERY_TYPE_OCCLUSION) { skip |= log_msg( dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(pCB->commandBuffer), "VUID-vkCmdBeginQuery-queryType-00800", "VK_QUERY_CONTROL_PRECISE_BIT provided to vkCmdBeginQuery, but pool query type is not VK_QUERY_TYPE_OCCLUSION"); } } skip |= ValidateCmd(dev_data, pCB, CMD_BEGINQUERY, "vkCmdBeginQuery()"); return skip; } void PostCallRecordCmdBeginQuery(layer_data *dev_data, VkQueryPool queryPool, uint32_t slot, GLOBAL_CB_NODE *pCB) { QueryObject query = {queryPool, slot}; pCB->activeQueries.insert(query); pCB->startedQueries.insert(query); AddCommandBufferBinding(&GetQueryPoolNode(dev_data, queryPool)->cb_bindings, {HandleToUint64(queryPool), kVulkanObjectTypeQueryPool}, pCB); } bool PreCallValidateCmdEndQuery(layer_data *dev_data, GLOBAL_CB_NODE *cb_state, const QueryObject &query, VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t slot) { bool skip = false; if (!cb_state->activeQueries.count(query)) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(commandBuffer), "VUID-vkCmdEndQuery-None-01923", "Ending a query before it was started: queryPool 0x%" PRIx64 ", index %d.", HandleToUint64(queryPool), slot); } skip |= ValidateCmdQueueFlags(dev_data, cb_state, "VkCmdEndQuery()", VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT, "VUID-vkCmdEndQuery-commandBuffer-cmdpool"); skip |= ValidateCmd(dev_data, cb_state, CMD_ENDQUERY, "VkCmdEndQuery()"); return skip; } void PostCallRecordCmdEndQuery(layer_data *dev_data, GLOBAL_CB_NODE *cb_state, const QueryObject &query, VkCommandBuffer commandBuffer, VkQueryPool queryPool) { cb_state->activeQueries.erase(query); cb_state->queryUpdates.emplace_back([=](VkQueue q) { return SetQueryState(q, commandBuffer, query, true); }); AddCommandBufferBinding(&GetQueryPoolNode(dev_data, queryPool)->cb_bindings, {HandleToUint64(queryPool), kVulkanObjectTypeQueryPool}, cb_state); } bool PreCallValidateCmdResetQueryPool(layer_data *dev_data, GLOBAL_CB_NODE *cb_state) { bool skip = InsideRenderPass(dev_data, cb_state, "vkCmdResetQueryPool()", "VUID-vkCmdResetQueryPool-renderpass"); skip |= ValidateCmd(dev_data, cb_state, CMD_RESETQUERYPOOL, "VkCmdResetQueryPool()"); skip |= ValidateCmdQueueFlags(dev_data, cb_state, "VkCmdResetQueryPool()", VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT, "VUID-vkCmdResetQueryPool-commandBuffer-cmdpool"); return skip; } void PostCallRecordCmdResetQueryPool(layer_data *dev_data, GLOBAL_CB_NODE *cb_state, VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t firstQuery, uint32_t queryCount) { for (uint32_t i = 0; i < queryCount; i++) { QueryObject query = {queryPool, firstQuery + i}; cb_state->waitedEventsBeforeQueryReset[query] = cb_state->waitedEvents; cb_state->queryUpdates.emplace_back([=](VkQueue q) { return SetQueryState(q, commandBuffer, query, false); }); } AddCommandBufferBinding(&GetQueryPoolNode(dev_data, queryPool)->cb_bindings, {HandleToUint64(queryPool), kVulkanObjectTypeQueryPool}, cb_state); } static bool IsQueryInvalid(layer_data *dev_data, QUEUE_STATE *queue_data, VkQueryPool queryPool, uint32_t queryIndex) { QueryObject query = {queryPool, queryIndex}; auto query_data = queue_data->queryToStateMap.find(query); if (query_data != queue_data->queryToStateMap.end()) { if (!query_data->second) return true; } else { auto it = dev_data->queryToStateMap.find(query); if (it == dev_data->queryToStateMap.end() || !it->second) return true; } return false; } static bool ValidateQuery(VkQueue queue, GLOBAL_CB_NODE *pCB, VkQueryPool queryPool, uint32_t firstQuery, uint32_t queryCount) { bool skip = false; layer_data *dev_data = GetLayerDataPtr(get_dispatch_key(pCB->commandBuffer), layer_data_map); auto queue_data = GetQueueState(dev_data, queue); if (!queue_data) return false; for (uint32_t i = 0; i < queryCount; i++) { if (IsQueryInvalid(dev_data, queue_data, queryPool, firstQuery + i)) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(pCB->commandBuffer), kVUID_Core_DrawState_InvalidQuery, "Requesting a copy from query to buffer with invalid query: queryPool 0x%" PRIx64 ", index %d", HandleToUint64(queryPool), firstQuery + i); } } return skip; } bool PreCallValidateCmdCopyQueryPoolResults(layer_data *dev_data, GLOBAL_CB_NODE *cb_state, BUFFER_STATE *dst_buff_state) { bool skip = ValidateMemoryIsBoundToBuffer(dev_data, dst_buff_state, "vkCmdCopyQueryPoolResults()", "VUID-vkCmdCopyQueryPoolResults-dstBuffer-00826"); // Validate that DST buffer has correct usage flags set skip |= ValidateBufferUsageFlags(dev_data, dst_buff_state, VK_BUFFER_USAGE_TRANSFER_DST_BIT, true, "VUID-vkCmdCopyQueryPoolResults-dstBuffer-00825", "vkCmdCopyQueryPoolResults()", "VK_BUFFER_USAGE_TRANSFER_DST_BIT"); skip |= ValidateCmdQueueFlags(dev_data, cb_state, "vkCmdCopyQueryPoolResults()", VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT, "VUID-vkCmdCopyQueryPoolResults-commandBuffer-cmdpool"); skip |= ValidateCmd(dev_data, cb_state, CMD_COPYQUERYPOOLRESULTS, "vkCmdCopyQueryPoolResults()"); skip |= InsideRenderPass(dev_data, cb_state, "vkCmdCopyQueryPoolResults()", "VUID-vkCmdCopyQueryPoolResults-renderpass"); return skip; } void PostCallRecordCmdCopyQueryPoolResults(layer_data *dev_data, GLOBAL_CB_NODE *cb_state, BUFFER_STATE *dst_buff_state, VkQueryPool queryPool, uint32_t firstQuery, uint32_t queryCount) { AddCommandBufferBindingBuffer(dev_data, cb_state, dst_buff_state); cb_state->queryUpdates.emplace_back([=](VkQueue q) { return ValidateQuery(q, cb_state, queryPool, firstQuery, queryCount); }); AddCommandBufferBinding(&GetQueryPoolNode(dev_data, queryPool)->cb_bindings, {HandleToUint64(queryPool), kVulkanObjectTypeQueryPool}, cb_state); } bool PreCallValidateCmdPushConstants(layer_data *dev_data, VkCommandBuffer commandBuffer, VkPipelineLayout layout, VkShaderStageFlags stageFlags, uint32_t offset, uint32_t size) { bool skip = false; GLOBAL_CB_NODE *cb_state = GetCBNode(dev_data, commandBuffer); if (cb_state) { skip |= ValidateCmdQueueFlags(dev_data, cb_state, "vkCmdPushConstants()", VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT, "VUID-vkCmdPushConstants-commandBuffer-cmdpool"); skip |= ValidateCmd(dev_data, cb_state, CMD_PUSHCONSTANTS, "vkCmdPushConstants()"); } skip |= ValidatePushConstantRange(dev_data, offset, size, "vkCmdPushConstants()"); if (0 == stageFlags) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(commandBuffer), "VUID-vkCmdPushConstants-stageFlags-requiredbitmask", "vkCmdPushConstants() call has no stageFlags set."); } // 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(dev_data, 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) { // "VUID-vkCmdPushConstants-offset-01796" VUID-vkCmdPushConstants-offset-01796 skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(commandBuffer), "VUID-vkCmdPushConstants-offset-01796", "vkCmdPushConstants(): stageFlags (0x%" PRIx32 ", offset (%" PRIu32 "), and size (%" PRIu32 "), " "must contain all stages in overlapping VkPushConstantRange stageFlags (0x%" PRIx32 "), offset (%" PRIu32 "), and size (%" PRIu32 ") in pipeline layout 0x%" PRIx64 ".", (uint32_t)stageFlags, offset, size, (uint32_t)range.stageFlags, range.offset, range.size, HandleToUint64(layout)); } // Accumulate all stages we've found found_stages = matching_stages | found_stages; } } if (found_stages != stageFlags) { // "VUID-vkCmdPushConstants-offset-01795" VUID-vkCmdPushConstants-offset-01795 uint32_t missing_stages = ~found_stages & stageFlags; skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(commandBuffer), "VUID-vkCmdPushConstants-offset-01795", "vkCmdPushConstants(): stageFlags = 0x%" PRIx32 ", VkPushConstantRange in pipeline layout 0x%" PRIx64 " overlapping offset = %d and size = %d, do not contain stageFlags 0x%" PRIx32 ".", (uint32_t)stageFlags, HandleToUint64(layout), offset, size, missing_stages); } } return skip; } bool PreCallValidateCmdWriteTimestamp(layer_data *dev_data, GLOBAL_CB_NODE *cb_state) { bool skip = ValidateCmdQueueFlags(dev_data, cb_state, "vkCmdWriteTimestamp()", VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT | VK_QUEUE_TRANSFER_BIT, "VUID-vkCmdWriteTimestamp-commandBuffer-cmdpool"); skip |= ValidateCmd(dev_data, cb_state, CMD_WRITETIMESTAMP, "vkCmdWriteTimestamp()"); return skip; } void PostCallRecordCmdWriteTimestamp(GLOBAL_CB_NODE *cb_state, VkCommandBuffer commandBuffer, VkQueryPool queryPool, uint32_t slot) { QueryObject query = {queryPool, slot}; cb_state->queryUpdates.emplace_back([=](VkQueue q) { return SetQueryState(q, commandBuffer, query, true); }); } static bool MatchUsage(layer_data *dev_data, uint32_t count, const VkAttachmentReference2KHR *attachments, const VkFramebufferCreateInfo *fbci, VkImageUsageFlagBits usage_flag, std::string error_code) { bool skip = false; 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) { const VkImageView *image_view = &fbci->pAttachments[attachments[attach].attachment]; auto view_state = GetImageViewState(dev_data, *image_view); if (view_state) { const VkImageCreateInfo *ici = &GetImageState(dev_data, view_state->create_info.image)->createInfo; if (ici != nullptr) { if ((ici->usage & usage_flag) == 0) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, error_code, "vkCreateFramebuffer: Framebuffer Attachment (%d) conflicts with the image's " "IMAGE_USAGE flags (%s).", attachments[attach].attachment, string_VkImageUsageFlagBits(usage_flag)); } } } } } } return skip; } // Validate VkFramebufferCreateInfo which includes: // 1. attachmentCount equals renderPass attachmentCount // 2. corresponding framebuffer and renderpass attachments have matching formats // 3. corresponding framebuffer and renderpass attachments have matching sample counts // 4. fb attachments only have a single mip level // 5. fb attachment dimensions are each at least as large as the fb // 6. fb attachments use idenity swizzle // 7. fb attachments used by renderPass for color/input/ds have correct usage bit set // 8. fb dimensions are within physical device limits static bool ValidateFramebufferCreateInfo(layer_data *dev_data, const VkFramebufferCreateInfo *pCreateInfo) { bool skip = false; auto rp_state = GetRenderPassState(dev_data, pCreateInfo->renderPass); if (rp_state) { const VkRenderPassCreateInfo2KHR *rpci = rp_state->createInfo.ptr(); if (rpci->attachmentCount != pCreateInfo->attachmentCount) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT, HandleToUint64(pCreateInfo->renderPass), "VUID-VkFramebufferCreateInfo-attachmentCount-00876", "vkCreateFramebuffer(): VkFramebufferCreateInfo attachmentCount of %u does not match attachmentCount " "of %u of renderPass (0x%" PRIx64 ") being used to create Framebuffer.", pCreateInfo->attachmentCount, rpci->attachmentCount, HandleToUint64(pCreateInfo->renderPass)); } else { // attachmentCounts match, so make sure corresponding attachment details line up const VkImageView *image_views = pCreateInfo->pAttachments; for (uint32_t i = 0; i < pCreateInfo->attachmentCount; ++i) { auto view_state = GetImageViewState(dev_data, image_views[i]); auto &ivci = view_state->create_info; if (ivci.format != rpci->pAttachments[i].format) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT, HandleToUint64(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 renderPass (0x%" PRIx64 ").", i, string_VkFormat(ivci.format), string_VkFormat(rpci->pAttachments[i].format), HandleToUint64(pCreateInfo->renderPass)); } const VkImageCreateInfo *ici = &GetImageState(dev_data, ivci.image)->createInfo; if (ici->samples != rpci->pAttachments[i].samples) { skip |= log_msg( dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT, HandleToUint64(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 renderPass (0x%" PRIx64 ").", i, string_VkSampleCountFlagBits(ici->samples), string_VkSampleCountFlagBits(rpci->pAttachments[i].samples), HandleToUint64(pCreateInfo->renderPass)); } // Verify that view only has a single mip level if (ivci.subresourceRange.levelCount != 1) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "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, ivci.subresourceRange.levelCount); } const uint32_t mip_level = ivci.subresourceRange.baseMipLevel; uint32_t mip_width = max(1u, ici->extent.width >> mip_level); uint32_t mip_height = max(1u, ici->extent.height >> mip_level); if ((ivci.subresourceRange.layerCount < pCreateInfo->layers) || (mip_width < pCreateInfo->width) || (mip_height < pCreateInfo->height)) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkFramebufferCreateInfo-pAttachments-00882", "vkCreateFramebuffer(): VkFramebufferCreateInfo attachment #%u mip level %u has dimensions " "smaller than the corresponding framebuffer dimensions. Here are the respective dimensions for " "attachment #%u, framebuffer:\n" "width: %u, %u\n" "height: %u, %u\n" "layerCount: %u, %u\n", i, ivci.subresourceRange.baseMipLevel, i, mip_width, pCreateInfo->width, mip_height, pCreateInfo->height, ivci.subresourceRange.layerCount, pCreateInfo->layers); } if (((ivci.components.r != VK_COMPONENT_SWIZZLE_IDENTITY) && (ivci.components.r != VK_COMPONENT_SWIZZLE_R)) || ((ivci.components.g != VK_COMPONENT_SWIZZLE_IDENTITY) && (ivci.components.g != VK_COMPONENT_SWIZZLE_G)) || ((ivci.components.b != VK_COMPONENT_SWIZZLE_IDENTITY) && (ivci.components.b != VK_COMPONENT_SWIZZLE_B)) || ((ivci.components.a != VK_COMPONENT_SWIZZLE_IDENTITY) && (ivci.components.a != VK_COMPONENT_SWIZZLE_A))) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "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)); } } } // Verify correct attachment usage flags for (uint32_t subpass = 0; subpass < rpci->subpassCount; subpass++) { // Verify input attachments: skip |= MatchUsage(dev_data, rpci->pSubpasses[subpass].inputAttachmentCount, rpci->pSubpasses[subpass].pInputAttachments, pCreateInfo, VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT, "VUID-VkFramebufferCreateInfo-pAttachments-00879"); // Verify color attachments: skip |= MatchUsage(dev_data, rpci->pSubpasses[subpass].colorAttachmentCount, rpci->pSubpasses[subpass].pColorAttachments, pCreateInfo, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, "VUID-VkFramebufferCreateInfo-pAttachments-00877"); // Verify depth/stencil attachments: if (rpci->pSubpasses[subpass].pDepthStencilAttachment != nullptr) { skip |= MatchUsage(dev_data, 1, rpci->pSubpasses[subpass].pDepthStencilAttachment, pCreateInfo, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, "VUID-VkFramebufferCreateInfo-pAttachments-02603"); } } } // Verify FB dimensions are within physical device limits if (pCreateInfo->width > dev_data->phys_dev_properties.properties.limits.maxFramebufferWidth) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkFramebufferCreateInfo-width-00886", "vkCreateFramebuffer(): Requested VkFramebufferCreateInfo width exceeds physical device limits. Requested " "width: %u, device max: %u\n", pCreateInfo->width, dev_data->phys_dev_properties.properties.limits.maxFramebufferWidth); } if (pCreateInfo->height > dev_data->phys_dev_properties.properties.limits.maxFramebufferHeight) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkFramebufferCreateInfo-height-00888", "vkCreateFramebuffer(): Requested VkFramebufferCreateInfo height exceeds physical device limits. Requested " "height: %u, device max: %u\n", pCreateInfo->height, dev_data->phys_dev_properties.properties.limits.maxFramebufferHeight); } if (pCreateInfo->layers > dev_data->phys_dev_properties.properties.limits.maxFramebufferLayers) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkFramebufferCreateInfo-layers-00890", "vkCreateFramebuffer(): Requested VkFramebufferCreateInfo layers exceeds physical device limits. Requested " "layers: %u, device max: %u\n", pCreateInfo->layers, dev_data->phys_dev_properties.properties.limits.maxFramebufferLayers); } // Verify FB dimensions are greater than zero if (pCreateInfo->width <= 0) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkFramebufferCreateInfo-width-00885", "vkCreateFramebuffer(): Requested VkFramebufferCreateInfo width must be greater than zero."); } if (pCreateInfo->height <= 0) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkFramebufferCreateInfo-height-00887", "vkCreateFramebuffer(): Requested VkFramebufferCreateInfo height must be greater than zero."); } if (pCreateInfo->layers <= 0) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkFramebufferCreateInfo-layers-00889", "vkCreateFramebuffer(): Requested VkFramebufferCreateInfo layers must be greater than zero."); } return skip; } bool PreCallValidateCreateFramebuffer(VkDevice device, const VkFramebufferCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkFramebuffer *pFramebuffer) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); // TODO : Verify that renderPass FB is created with is compatible with FB bool skip = false; skip |= ValidateFramebufferCreateInfo(device_data, pCreateInfo); return skip; } void PostCallRecordCreateFramebuffer(VkDevice device, const VkFramebufferCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkFramebuffer *pFramebuffer, VkResult result) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); if (VK_SUCCESS != result) return; // Shadow create info and store in map std::unique_ptr<FRAMEBUFFER_STATE> fb_state( new FRAMEBUFFER_STATE(*pFramebuffer, pCreateInfo, GetRenderPassStateSharedPtr(device_data, pCreateInfo->renderPass))); for (uint32_t i = 0; i < pCreateInfo->attachmentCount; ++i) { VkImageView view = pCreateInfo->pAttachments[i]; auto view_state = GetImageViewState(device_data, view); if (!view_state) { continue; } #ifdef FRAMEBUFFER_ATTACHMENT_STATE_CACHE MT_FB_ATTACHMENT_INFO fb_info; fb_info.view_state = view_state; fb_info.image = view_state->create_info.image; fb_state->attachments.push_back(fb_info); #endif } device_data->frameBufferMap[*pFramebuffer] = std::move(fb_state); } static bool FindDependency(const uint32_t index, const uint32_t dependent, const std::vector<DAGNode> &subpass_to_node, std::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; } static bool CheckDependencyExists(const layer_data *dev_data, const uint32_t subpass, const std::vector<uint32_t> &dependent_subpasses, const std::vector<DAGNode> &subpass_to_node, bool &skip) { bool result = true; // 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) { if (static_cast<uint32_t>(subpass) == dependent_subpasses[k]) 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(), dependent_subpasses[k]); auto next_elem = std::find(node.next.begin(), node.next.end(), dependent_subpasses[k]); 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. std::unordered_set<uint32_t> processed_nodes; if (!(FindDependency(subpass, dependent_subpasses[k], subpass_to_node, processed_nodes) || FindDependency(dependent_subpasses[k], subpass, subpass_to_node, processed_nodes))) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, kVUID_Core_DrawState_InvalidRenderpass, "A dependency between subpasses %d and %d must exist but one is not specified.", subpass, dependent_subpasses[k]); result = false; } } } return result; } static bool CheckPreserved(const layer_data *dev_data, const VkRenderPassCreateInfo2KHR *pCreateInfo, const int index, const uint32_t attachment, const std::vector<DAGNode> &subpass_to_node, int depth, bool &skip) { 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 VkSubpassDescription2KHR &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(dev_data, 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 |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, 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)); } static bool ValidateDependencies(const layer_data *dev_data, FRAMEBUFFER_STATE const *framebuffer, RENDER_PASS_STATE const *renderPass) { bool skip = false; auto const pFramebufferInfo = framebuffer->createInfo.ptr(); auto const pCreateInfo = renderPass->createInfo.ptr(); auto const &subpass_to_node = renderPass->subpassToNode; std::vector<std::vector<uint32_t>> output_attachment_to_subpass(pCreateInfo->attachmentCount); std::vector<std::vector<uint32_t>> input_attachment_to_subpass(pCreateInfo->attachmentCount); std::vector<std::vector<uint32_t>> overlapping_attachments(pCreateInfo->attachmentCount); // Find overlapping attachments for (uint32_t i = 0; i < pCreateInfo->attachmentCount; ++i) { for (uint32_t j = i + 1; j < pCreateInfo->attachmentCount; ++j) { VkImageView viewi = pFramebufferInfo->pAttachments[i]; VkImageView viewj = pFramebufferInfo->pAttachments[j]; if (viewi == viewj) { overlapping_attachments[i].push_back(j); overlapping_attachments[j].push_back(i); continue; } auto view_state_i = GetImageViewState(dev_data, viewi); auto view_state_j = GetImageViewState(dev_data, 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)) { overlapping_attachments[i].push_back(j); overlapping_attachments[j].push_back(i); continue; } auto image_data_i = GetImageState(dev_data, view_ci_i.image); auto image_data_j = GetImageState(dev_data, view_ci_j.image); if (!image_data_i || !image_data_j) { continue; } if (image_data_i->binding.mem == image_data_j->binding.mem && IsRangeOverlapping(image_data_i->binding.offset, image_data_i->binding.size, image_data_j->binding.offset, image_data_j->binding.size)) { overlapping_attachments[i].push_back(j); overlapping_attachments[j].push_back(i); } } } // Find for each attachment the subpasses that use them. unordered_set<uint32_t> attachmentIndices; for (uint32_t i = 0; i < pCreateInfo->subpassCount; ++i) { const VkSubpassDescription2KHR &subpass = pCreateInfo->pSubpasses[i]; attachmentIndices.clear(); for (uint32_t j = 0; j < subpass.inputAttachmentCount; ++j) { uint32_t attachment = subpass.pInputAttachments[j].attachment; if (attachment == VK_ATTACHMENT_UNUSED) continue; input_attachment_to_subpass[attachment].push_back(i); for (auto overlapping_attachment : overlapping_attachments[attachment]) { input_attachment_to_subpass[overlapping_attachment].push_back(i); } } for (uint32_t j = 0; j < subpass.colorAttachmentCount; ++j) { uint32_t attachment = subpass.pColorAttachments[j].attachment; if (attachment == VK_ATTACHMENT_UNUSED) continue; output_attachment_to_subpass[attachment].push_back(i); for (auto overlapping_attachment : overlapping_attachments[attachment]) { output_attachment_to_subpass[overlapping_attachment].push_back(i); } attachmentIndices.insert(attachment); } if (subpass.pDepthStencilAttachment && subpass.pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED) { uint32_t attachment = subpass.pDepthStencilAttachment->attachment; output_attachment_to_subpass[attachment].push_back(i); for (auto overlapping_attachment : overlapping_attachments[attachment]) { output_attachment_to_subpass[overlapping_attachment].push_back(i); } if (attachmentIndices.count(attachment)) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, 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 < pCreateInfo->subpassCount; ++i) { const VkSubpassDescription2KHR &subpass = pCreateInfo->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(dev_data, i, output_attachment_to_subpass[attachment], 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(dev_data, i, output_attachment_to_subpass[attachment], subpass_to_node, skip); CheckDependencyExists(dev_data, i, input_attachment_to_subpass[attachment], subpass_to_node, skip); } if (subpass.pDepthStencilAttachment && subpass.pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED) { const uint32_t &attachment = subpass.pDepthStencilAttachment->attachment; CheckDependencyExists(dev_data, i, output_attachment_to_subpass[attachment], subpass_to_node, skip); CheckDependencyExists(dev_data, i, input_attachment_to_subpass[attachment], 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 < pCreateInfo->subpassCount; ++i) { const VkSubpassDescription2KHR &subpass = pCreateInfo->pSubpasses[i]; for (uint32_t j = 0; j < subpass.inputAttachmentCount; ++j) { CheckPreserved(dev_data, pCreateInfo, i, subpass.pInputAttachments[j].attachment, subpass_to_node, 0, skip); } } return skip; } static bool RecordRenderPassDAG(const layer_data *dev_data, RenderPassCreateVersion rp_version, const VkRenderPassCreateInfo2KHR *pCreateInfo, RENDER_PASS_STATE *render_pass) { // Shorthand... auto &subpass_to_node = render_pass->subpassToNode; subpass_to_node.resize(pCreateInfo->subpassCount); auto &self_dependencies = render_pass->self_dependencies; self_dependencies.resize(pCreateInfo->subpassCount); bool skip = false; for (uint32_t i = 0; i < pCreateInfo->subpassCount; ++i) { subpass_to_node[i].pass = i; self_dependencies[i].clear(); } for (uint32_t i = 0; i < pCreateInfo->dependencyCount; ++i) { const VkSubpassDependency2KHR &dependency = pCreateInfo->pDependencies[i]; // This VU is actually generalised to *any* pipeline - not just graphics - but only graphics render passes are // currently supported by the spec - so only that pipeline is checked here. // If that is ever relaxed, this check should be extended to cover those pipelines. if (dependency.srcSubpass == dependency.dstSubpass) { self_dependencies[dependency.srcSubpass].push_back(i); } else { subpass_to_node[dependency.dstSubpass].prev.push_back(dependency.srcSubpass); subpass_to_node[dependency.srcSubpass].next.push_back(dependency.dstSubpass); } } return skip; } static bool ValidateRenderPassDAG(const layer_data *dev_data, RenderPassCreateVersion rp_version, const VkRenderPassCreateInfo2KHR *pCreateInfo, RENDER_PASS_STATE *render_pass) { // Shorthand... auto &subpass_to_node = render_pass->subpassToNode; subpass_to_node.resize(pCreateInfo->subpassCount); auto &self_dependencies = render_pass->self_dependencies; self_dependencies.resize(pCreateInfo->subpassCount); bool skip = false; const char *vuid; const bool use_rp2 = (rp_version == RENDER_PASS_VERSION_2); for (uint32_t i = 0; i < pCreateInfo->subpassCount; ++i) { subpass_to_node[i].pass = i; self_dependencies[i].clear(); } for (uint32_t i = 0; i < pCreateInfo->dependencyCount; ++i) { const VkSubpassDependency2KHR &dependency = pCreateInfo->pDependencies[i]; VkPipelineStageFlags exclude_graphics_pipeline_stages = ~(VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT | ExpandPipelineStageFlags(VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT)); VkPipelineStageFlagBits latest_src_stage = GetLogicallyLatestGraphicsPipelineStage(dependency.srcStageMask); VkPipelineStageFlagBits earliest_dst_stage = GetLogicallyEarliestGraphicsPipelineStage(dependency.dstStageMask); // This VU is actually generalised to *any* pipeline - not just graphics - but only graphics render passes are // currently supported by the spec - so only that pipeline is checked here. // If that is ever relaxed, this check should be extended to cover those pipelines. if (dependency.srcSubpass == dependency.dstSubpass && (dependency.srcStageMask & exclude_graphics_pipeline_stages) != 0u && (dependency.dstStageMask & exclude_graphics_pipeline_stages) != 0u) { vuid = use_rp2 ? "VUID-VkSubpassDependency2KHR-srcSubpass-02244" : "VUID-VkSubpassDependency-srcSubpass-01989"; skip |= log_msg( dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid, "Dependency %u is a self-dependency, but specifies stage masks that contain stages not in the GRAPHICS pipeline.", i); } else if (dependency.srcSubpass != VK_SUBPASS_EXTERNAL && (dependency.srcStageMask & VK_PIPELINE_STAGE_HOST_BIT)) { vuid = use_rp2 ? "VUID-VkSubpassDependency2KHR-srcSubpass-03078" : "VUID-VkSubpassDependency-srcSubpass-00858"; skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid, "Dependency %u specifies a dependency from subpass %u, but includes HOST_BIT in the source stage mask.", i, dependency.srcSubpass); } else if (dependency.dstSubpass != VK_SUBPASS_EXTERNAL && (dependency.dstStageMask & VK_PIPELINE_STAGE_HOST_BIT)) { vuid = use_rp2 ? "VUID-VkSubpassDependency2KHR-dstSubpass-03079" : "VUID-VkSubpassDependency-dstSubpass-00859"; skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid, "Dependency %u specifies a dependency to subpass %u, but includes HOST_BIT in the destination stage mask.", i, dependency.dstSubpass); } // These next two VUs are actually generalised to *any* pipeline - not just graphics - but only graphics render passes are // currently supported by the spec - so only that pipeline is checked here. // If that is ever relaxed, these next two checks should be extended to cover those pipelines. else if (dependency.srcSubpass != VK_SUBPASS_EXTERNAL && pCreateInfo->pSubpasses[dependency.srcSubpass].pipelineBindPoint == VK_PIPELINE_BIND_POINT_GRAPHICS && (dependency.srcStageMask & exclude_graphics_pipeline_stages) != 0u) { vuid = use_rp2 ? "VUID-VkRenderPassCreateInfo2KHR-pDependencies-03054" : "VUID-VkRenderPassCreateInfo-pDependencies-00837"; skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid, "Dependency %u specifies a source stage mask that contains stages not in the GRAPHICS pipeline as used " "by the source subpass %u.", i, dependency.srcSubpass); } else if (dependency.dstSubpass != VK_SUBPASS_EXTERNAL && pCreateInfo->pSubpasses[dependency.dstSubpass].pipelineBindPoint == VK_PIPELINE_BIND_POINT_GRAPHICS && (dependency.dstStageMask & exclude_graphics_pipeline_stages) != 0u) { vuid = use_rp2 ? "VUID-VkRenderPassCreateInfo2KHR-pDependencies-03055" : "VUID-VkRenderPassCreateInfo-pDependencies-00838"; skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid, "Dependency %u specifies a destination stage mask that contains stages not in the GRAPHICS pipeline as " "used by the destination subpass %u.", i, dependency.dstSubpass); } // 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. else if (use_rp2 && (dependency.dependencyFlags & VK_DEPENDENCY_VIEW_LOCAL_BIT) && (pCreateInfo->pSubpasses[0].viewMask == 0)) { skip |= log_msg( dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkRenderPassCreateInfo2KHR-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 |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkSubpassDependency2KHR-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-VkSubpassDependency2KHR-srcSubpass-03085" : "VUID-VkSubpassDependency-srcSubpass-00865"; skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, 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-VkSubpassDependency2KHR-dependencyFlags-03090"; } else { vuid = "VUID-VkSubpassDependency2KHR-dependencyFlags-03091"; } } skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, 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-VkSubpassDependency2KHR-srcSubpass-03084" : "VUID-VkSubpassDependency-srcSubpass-00864"; skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, 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 ? kVUID_Core_DrawState_InvalidRenderpass : "VUID-VkRenderPassCreateInfo-pNext-01930"; skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, 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-VkRenderPassCreateInfo2KHR-pDependencies-03060" : "VUID-VkSubpassDependency-srcSubpass-00872"; skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, 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)) && (GetGraphicsPipelineStageLogicalOrdinal(latest_src_stage) > GetGraphicsPipelineStageLogicalOrdinal(earliest_dst_stage))) { vuid = use_rp2 ? "VUID-VkSubpassDependency2KHR-srcSubpass-03087" : "VUID-VkSubpassDependency-srcSubpass-00867"; skip |= log_msg( dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid, "Dependency %u specifies a self-dependency from logically-later stage (%s) to a logically-earlier stage (%s).", i, string_VkPipelineStageFlagBits(latest_src_stage), string_VkPipelineStageFlagBits(earliest_dst_stage)); } else { self_dependencies[dependency.srcSubpass].push_back(i); } } else { subpass_to_node[dependency.dstSubpass].prev.push_back(dependency.srcSubpass); subpass_to_node[dependency.srcSubpass].next.push_back(dependency.dstSubpass); } } return skip; } void PostCallRecordCreateShaderModule(layer_data *dev_data, bool is_spirv, const VkShaderModuleCreateInfo *pCreateInfo, VkShaderModule *pShaderModule, uint32_t unique_shader_id) { spv_target_env spirv_environment = ((GetApiVersion(dev_data) >= VK_API_VERSION_1_1) ? SPV_ENV_VULKAN_1_1 : SPV_ENV_VULKAN_1_0); unique_ptr<shader_module> new_shader_module( is_spirv ? new shader_module(pCreateInfo, *pShaderModule, spirv_environment, unique_shader_id) : new shader_module()); dev_data->shaderModuleMap[*pShaderModule] = std::move(new_shader_module); } static bool ValidateAttachmentIndex(const layer_data *dev_data, RenderPassCreateVersion rp_version, uint32_t attachment, uint32_t attachment_count, const char *type) { bool skip = false; const bool use_rp2 = (rp_version == RENDER_PASS_VERSION_2); const char *const function_name = use_rp2 ? "vkCreateRenderPass2KHR()" : "vkCreateRenderPass()"; if (attachment >= attachment_count && attachment != VK_ATTACHMENT_UNUSED) { const char *vuid = use_rp2 ? "VUID-VkRenderPassCreateInfo2KHR-attachment-03051" : "VUID-VkRenderPassCreateInfo-attachment-00834"; skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid, "%s: %s attachment %d must be less than the total number of attachments %d.", type, function_name, 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)"; } } static bool AddAttachmentUse(const layer_data *dev_data, 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) { 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 ? "vkCreateRenderPass2KHR()" : "vkCreateRenderPass()"; if (uses & new_use) { if (attachment_layouts[attachment] != new_layout) { vuid = use_rp2 ? "VUID-VkSubpassDescription2KHR-layout-02528" : "VUID-VkSubpassDescription-layout-02519"; log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, 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 (uses & ~ATTACHMENT_INPUT || (uses && (new_use == ATTACHMENT_RESOLVE || new_use == ATTACHMENT_PRESERVE))) { /* Note: input attachments are assumed to be done first. */ vuid = use_rp2 ? "VUID-VkSubpassDescription2KHR-pPreserveAttachments-03074" : "VUID-VkSubpassDescription-pPreserveAttachments-00854"; skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, 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; } static bool ValidateRenderpassAttachmentUsage(const layer_data *dev_data, RenderPassCreateVersion rp_version, const VkRenderPassCreateInfo2KHR *pCreateInfo) { bool skip = false; const bool use_rp2 = (rp_version == RENDER_PASS_VERSION_2); const char *vuid; const char *const function_name = use_rp2 ? "vkCreateRenderPass2KHR()" : "vkCreateRenderPass()"; for (uint32_t i = 0; i < pCreateInfo->subpassCount; ++i) { const VkSubpassDescription2KHR &subpass = pCreateInfo->pSubpasses[i]; std::vector<uint8_t> attachment_uses(pCreateInfo->attachmentCount); std::vector<VkImageLayout> attachment_layouts(pCreateInfo->attachmentCount); if (subpass.pipelineBindPoint != VK_PIPELINE_BIND_POINT_GRAPHICS) { vuid = use_rp2 ? "VUID-VkSubpassDescription2KHR-pipelineBindPoint-03062" : "VUID-VkSubpassDescription-pipelineBindPoint-00844"; skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid, "%s: Pipeline bind point for subpass %d must be VK_PIPELINE_BIND_POINT_GRAPHICS.", function_name, i); } for (uint32_t j = 0; j < subpass.inputAttachmentCount; ++j) { auto const &attachment_ref = subpass.pInputAttachments[j]; if (attachment_ref.attachment != VK_ATTACHMENT_UNUSED) { skip |= ValidateAttachmentIndex(dev_data, rp_version, attachment_ref.attachment, pCreateInfo->attachmentCount, "Input"); if (attachment_ref.aspectMask & VK_IMAGE_ASPECT_METADATA_BIT) { vuid = use_rp2 ? kVUID_Core_DrawState_InvalidRenderpass : "VUID-VkInputAttachmentAspectReference-aspectMask-01964"; skip |= log_msg( dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid, "%s: Aspect mask for input attachment reference %d in subpass %d includes VK_IMAGE_ASPECT_METADATA_BIT.", function_name, i, j); } if (attachment_ref.attachment < pCreateInfo->attachmentCount) { skip |= AddAttachmentUse(dev_data, rp_version, i, attachment_uses, attachment_layouts, attachment_ref.attachment, ATTACHMENT_INPUT, attachment_ref.layout); vuid = use_rp2 ? kVUID_Core_DrawState_InvalidRenderpass : "VUID-VkRenderPassCreateInfo-pNext-01963"; skip |= ValidateImageAspectMask(dev_data, VK_NULL_HANDLE, pCreateInfo->pAttachments[attachment_ref.attachment].format, attachment_ref.aspectMask, function_name, vuid); } } 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 (attachment_ref.aspectMask == 0) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkSubpassDescription2KHR-aspectMask-03176", "%s: Input attachment (%d) aspect mask must not be 0.", function_name, j); } 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); // Check for valid aspect mask bits if (attachment_ref.aspectMask & ~valid_bits) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkSubpassDescription2KHR-aspectMask-03175", "%s: Input attachment (%d) aspect mask (0x%" PRIx32 ")is invalid.", function_name, j, attachment_ref.aspectMask); } } } } for (uint32_t j = 0; j < subpass.preserveAttachmentCount; ++j) { uint32_t attachment = subpass.pPreserveAttachments[j]; if (attachment == VK_ATTACHMENT_UNUSED) { vuid = use_rp2 ? "VUID-VkSubpassDescription2KHR-attachment-03073" : "VUID-VkSubpassDescription-attachment-00853"; skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid, "%s: Preserve attachment (%d) must not be VK_ATTACHMENT_UNUSED.", function_name, j); } else { skip |= ValidateAttachmentIndex(dev_data, rp_version, attachment, pCreateInfo->attachmentCount, "Preserve"); if (attachment < pCreateInfo->attachmentCount) { skip |= AddAttachmentUse(dev_data, 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) { auto const &attachment_ref = subpass.pResolveAttachments[j]; if (attachment_ref.attachment != VK_ATTACHMENT_UNUSED) { skip |= ValidateAttachmentIndex(dev_data, rp_version, attachment_ref.attachment, pCreateInfo->attachmentCount, "Resolve"); if (attachment_ref.attachment < pCreateInfo->attachmentCount) { skip |= AddAttachmentUse(dev_data, 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-VkSubpassDescription2KHR-pResolveAttachments-03067" : "VUID-VkSubpassDescription-pResolveAttachments-00849"; skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, 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)); } } } } } if (subpass.pDepthStencilAttachment) { if (subpass.pDepthStencilAttachment->attachment != VK_ATTACHMENT_UNUSED) { skip |= ValidateAttachmentIndex(dev_data, rp_version, subpass.pDepthStencilAttachment->attachment, pCreateInfo->attachmentCount, "Depth"); if (subpass.pDepthStencilAttachment->attachment < pCreateInfo->attachmentCount) { skip |= AddAttachmentUse(dev_data, rp_version, i, attachment_uses, attachment_layouts, subpass.pDepthStencilAttachment->attachment, ATTACHMENT_DEPTH, subpass.pDepthStencilAttachment->layout); } } } uint32_t last_sample_count_attachment = VK_ATTACHMENT_UNUSED; for (uint32_t j = 0; j < subpass.colorAttachmentCount; ++j) { auto const &attachment_ref = subpass.pColorAttachments[j]; skip |= ValidateAttachmentIndex(dev_data, rp_version, attachment_ref.attachment, pCreateInfo->attachmentCount, "Color"); if (attachment_ref.attachment != VK_ATTACHMENT_UNUSED && attachment_ref.attachment < pCreateInfo->attachmentCount) { skip |= AddAttachmentUse(dev_data, rp_version, i, attachment_uses, attachment_layouts, attachment_ref.attachment, ATTACHMENT_COLOR, attachment_ref.layout); VkSampleCountFlagBits current_sample_count = pCreateInfo->pAttachments[attachment_ref.attachment].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-VkSubpassDescription2KHR-pColorAttachments-03069" : "VUID-VkSubpassDescription-pColorAttachments-01417"; skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, 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-VkSubpassDescription2KHR-pResolveAttachments-03066" : "VUID-VkSubpassDescription-pResolveAttachments-00848"; skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid, "%s: Subpass %u requests multisample resolve from attachment %u which has " "VK_SAMPLE_COUNT_1_BIT.", function_name, i, attachment_ref.attachment); } 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 (dev_data->extensions.vk_amd_mixed_attachment_samples) { if (pCreateInfo->pAttachments[attachment_ref.attachment].samples > depth_stencil_sample_count) { vuid = use_rp2 ? "VUID-VkSubpassDescription2KHR-pColorAttachments-03070" : "VUID-VkSubpassDescription-pColorAttachments-01506"; skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid, "%s: Subpass %u pColorAttachments[%u] has %s which is larger than " "depth/stencil attachment %s.", function_name, i, j, string_VkSampleCountFlagBits(pCreateInfo->pAttachments[attachment_ref.attachment].samples), string_VkSampleCountFlagBits(depth_stencil_sample_count)); break; } } if (!dev_data->extensions.vk_amd_mixed_attachment_samples && !dev_data->extensions.vk_nv_framebuffer_mixed_samples && current_sample_count != depth_stencil_sample_count) { vuid = use_rp2 ? "VUID-VkSubpassDescription2KHR-pDepthStencilAttachment-03071" : "VUID-VkSubpassDescription-pDepthStencilAttachment-01418"; skip |= log_msg( dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, 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; } } } if (subpass_performs_resolve && subpass.pResolveAttachments[j].attachment != VK_ATTACHMENT_UNUSED && subpass.pResolveAttachments[j].attachment < pCreateInfo->attachmentCount) { if (attachment_ref.attachment == VK_ATTACHMENT_UNUSED) { vuid = use_rp2 ? "VUID-VkSubpassDescription2KHR-pResolveAttachments-03065" : "VUID-VkSubpassDescription-pResolveAttachments-00847"; skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid, "%s: Subpass %u requests multisample resolve from attachment %u which has " "attachment=VK_ATTACHMENT_UNUSED.", function_name, i, attachment_ref.attachment); } else { const auto &color_desc = pCreateInfo->pAttachments[attachment_ref.attachment]; const auto &resolve_desc = pCreateInfo->pAttachments[subpass.pResolveAttachments[j].attachment]; if (color_desc.format != resolve_desc.format) { vuid = use_rp2 ? "VUID-VkSubpassDescription2KHR-pResolveAttachments-03068" : "VUID-VkSubpassDescription-pResolveAttachments-00850"; skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid, "%s: Subpass %u pColorAttachments[%u] resolves to an attachment with a " "different format. color format: %u, resolve format: %u.", function_name, i, j, color_desc.format, resolve_desc.format); } } } } } return skip; } static void MarkAttachmentFirstUse(RENDER_PASS_STATE *render_pass, uint32_t index, bool is_read) { if (index == VK_ATTACHMENT_UNUSED) return; if (!render_pass->attachment_first_read.count(index)) render_pass->attachment_first_read[index] = is_read; } static bool ValidateCreateRenderPass(const layer_data *dev_data, VkDevice device, RenderPassCreateVersion rp_version, const VkRenderPassCreateInfo2KHR *pCreateInfo, RENDER_PASS_STATE *render_pass) { bool skip = false; const bool use_rp2 = (rp_version == RENDER_PASS_VERSION_2); const char *vuid; const char *const function_name = use_rp2 ? "vkCreateRenderPass2KHR()" : "vkCreateRenderPass()"; // TODO: As part of wrapping up the mem_tracker/core_validation merge the following routine should be consolidated with // ValidateLayouts. skip |= ValidateRenderpassAttachmentUsage(dev_data, rp_version, pCreateInfo); render_pass->renderPass = VK_NULL_HANDLE; skip |= ValidateRenderPassDAG(dev_data, rp_version, pCreateInfo, render_pass); // Validate multiview correlation and view masks bool viewMaskZero = false; bool viewMaskNonZero = false; for (uint32_t i = 0; i < pCreateInfo->subpassCount; ++i) { const VkSubpassDescription2KHR &subpass = pCreateInfo->pSubpasses[i]; if (subpass.viewMask != 0) { viewMaskNonZero = true; } else { viewMaskZero = 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-VkSubpassDescription2KHR-flags-03076" : "VUID-VkSubpassDescription-flags-00856"; skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, 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 (viewMaskNonZero && viewMaskZero) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkRenderPassCreateInfo2KHR-viewMask-03058", "%s: Some view masks are non-zero whilst others are zero.", function_name); } if (viewMaskZero && pCreateInfo->correlatedViewMaskCount != 0) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkRenderPassCreateInfo2KHR-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-VkRenderPassCreateInfo2KHR-pCorrelatedViewMasks-03056" : "VUID-VkRenderPassMultiviewCreateInfo-pCorrelationMasks-00841"; skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid, "%s: pCorrelatedViewMasks[%u] contains a previously appearing view bit.", function_name, i); } aggregated_cvms |= pCreateInfo->pCorrelatedViewMasks[i]; } for (uint32_t i = 0; i < pCreateInfo->dependencyCount; ++i) { auto const &dependency = pCreateInfo->pDependencies[i]; if (rp_version == RENDER_PASS_VERSION_2) { skip |= ValidateStageMaskGsTsEnables( dev_data, dependency.srcStageMask, function_name, "VUID-VkSubpassDependency2KHR-srcStageMask-03080", "VUID-VkSubpassDependency2KHR-srcStageMask-03082", "VUID-VkSubpassDependency2KHR-srcStageMask-02103", "VUID-VkSubpassDependency2KHR-srcStageMask-02104"); skip |= ValidateStageMaskGsTsEnables( dev_data, dependency.dstStageMask, function_name, "VUID-VkSubpassDependency2KHR-dstStageMask-03081", "VUID-VkSubpassDependency2KHR-dstStageMask-03083", "VUID-VkSubpassDependency2KHR-dstStageMask-02105", "VUID-VkSubpassDependency2KHR-dstStageMask-02106"); } else { skip |= ValidateStageMaskGsTsEnables( dev_data, dependency.srcStageMask, function_name, "VUID-VkSubpassDependency-srcStageMask-00860", "VUID-VkSubpassDependency-srcStageMask-00862", "VUID-VkSubpassDependency-srcStageMask-02099", "VUID-VkSubpassDependency-srcStageMask-02100"); skip |= ValidateStageMaskGsTsEnables( dev_data, dependency.dstStageMask, function_name, "VUID-VkSubpassDependency-dstStageMask-00861", "VUID-VkSubpassDependency-dstStageMask-00863", "VUID-VkSubpassDependency-dstStageMask-02101", "VUID-VkSubpassDependency-dstStageMask-02102"); } if (!ValidateAccessMaskPipelineStage(dependency.srcAccessMask, dependency.srcStageMask)) { vuid = use_rp2 ? "VUID-VkSubpassDependency2KHR-srcAccessMask-03088" : "VUID-VkSubpassDependency-srcAccessMask-00868"; skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid, "%s: pDependencies[%u].srcAccessMask (0x%" PRIx32 ") is not supported by srcStageMask (0x%" PRIx32 ").", function_name, i, dependency.srcAccessMask, dependency.srcStageMask); } if (!ValidateAccessMaskPipelineStage(dependency.dstAccessMask, dependency.dstStageMask)) { vuid = use_rp2 ? "VUID-VkSubpassDependency2KHR-dstAccessMask-03089" : "VUID-VkSubpassDependency-dstAccessMask-00869"; skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, vuid, "%s: pDependencies[%u].dstAccessMask (0x%" PRIx32 ") is not supported by dstStageMask (0x%" PRIx32 ").", function_name, i, dependency.dstAccessMask, dependency.dstStageMask); } } if (!skip) { skip |= ValidateLayouts(dev_data, rp_version, device, pCreateInfo); } return skip; } bool PreCallValidateCreateRenderPass(VkDevice device, const VkRenderPassCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkRenderPass *pRenderPass) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); 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 *pMultiviewInfo = lvl_find_in_chain<VkRenderPassMultiviewCreateInfo>(pCreateInfo->pNext); if (pMultiviewInfo) { if (pMultiviewInfo->subpassCount && pMultiviewInfo->subpassCount != pCreateInfo->subpassCount) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkRenderPassCreateInfo-pNext-01928", "Subpass count is %u but multiview info has a subpass count of %u.", pCreateInfo->subpassCount, pMultiviewInfo->subpassCount); } else if (pMultiviewInfo->dependencyCount && pMultiviewInfo->dependencyCount != pCreateInfo->dependencyCount) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkRenderPassCreateInfo-pNext-01929", "Dependency count is %u but multiview info has a dependency count of %u.", pCreateInfo->dependencyCount, pMultiviewInfo->dependencyCount); } } const VkRenderPassInputAttachmentAspectCreateInfo *pInputAttachmentAspectInfo = lvl_find_in_chain<VkRenderPassInputAttachmentAspectCreateInfo>(pCreateInfo->pNext); if (pInputAttachmentAspectInfo) { for (uint32_t i = 0; i < pInputAttachmentAspectInfo->aspectReferenceCount; ++i) { uint32_t subpass = pInputAttachmentAspectInfo->pAspectReferences[i].subpass; uint32_t attachment = pInputAttachmentAspectInfo->pAspectReferences[i].inputAttachmentIndex; if (subpass >= pCreateInfo->subpassCount) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkRenderPassCreateInfo-pNext-01926", "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 |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkRenderPassCreateInfo-pNext-01927", "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); } } } if (!skip) { auto render_pass = std::unique_ptr<RENDER_PASS_STATE>(new RENDER_PASS_STATE(pCreateInfo)); skip |= ValidateCreateRenderPass(device_data, device, RENDER_PASS_VERSION_1, render_pass->createInfo.ptr(), render_pass.get()); } return skip; } void RecordCreateRenderPassState(layer_data *device_data, RenderPassCreateVersion rp_version, std::shared_ptr<RENDER_PASS_STATE> &render_pass, VkRenderPass *pRenderPass) { render_pass->renderPass = *pRenderPass; auto create_info = render_pass->createInfo.ptr(); RecordRenderPassDAG(device_data, RENDER_PASS_VERSION_1, create_info, render_pass.get()); for (uint32_t i = 0; i < create_info->subpassCount; ++i) { const VkSubpassDescription2KHR &subpass = create_info->pSubpasses[i]; for (uint32_t j = 0; j < subpass.colorAttachmentCount; ++j) { MarkAttachmentFirstUse(render_pass.get(), subpass.pColorAttachments[j].attachment, false); // resolve attachments are considered to be written if (subpass.pResolveAttachments) { MarkAttachmentFirstUse(render_pass.get(), subpass.pResolveAttachments[j].attachment, false); } } if (subpass.pDepthStencilAttachment) { MarkAttachmentFirstUse(render_pass.get(), subpass.pDepthStencilAttachment->attachment, false); } for (uint32_t j = 0; j < subpass.inputAttachmentCount; ++j) { MarkAttachmentFirstUse(render_pass.get(), subpass.pInputAttachments[j].attachment, true); } } // Even though render_pass is an rvalue-ref parameter, still must move s.t. move assignment is invoked. device_data->renderPassMap[*pRenderPass] = std::move(render_pass); } // Style note: // Use of rvalue reference exceeds reccommended usage of rvalue refs in google style guide, but intentionally forces caller to move // or copy. This is clearer than passing a pointer to shared_ptr and avoids the atomic increment/decrement of shared_ptr copy // construction or assignment. void PostCallRecordCreateRenderPass(VkDevice device, const VkRenderPassCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkRenderPass *pRenderPass, VkResult result) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); if (VK_SUCCESS != result) return; auto render_pass_state = std::make_shared<RENDER_PASS_STATE>(pCreateInfo); RecordCreateRenderPassState(device_data, RENDER_PASS_VERSION_1, render_pass_state, pRenderPass); } void PostCallRecordCreateRenderPass2KHR(VkDevice device, const VkRenderPassCreateInfo2KHR *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkRenderPass *pRenderPass, VkResult result) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); if (VK_SUCCESS != result) return; auto render_pass_state = std::make_shared<RENDER_PASS_STATE>(pCreateInfo); RecordCreateRenderPassState(device_data, RENDER_PASS_VERSION_2, render_pass_state, pRenderPass); } static bool ValidateDepthStencilResolve(const debug_report_data *report_data, const VkPhysicalDeviceDepthStencilResolvePropertiesKHR &depth_stencil_resolve_props, const VkRenderPassCreateInfo2KHR *pCreateInfo) { bool skip = false; // If the pNext list of VkSubpassDescription2KHR includes a VkSubpassDescriptionDepthStencilResolveKHR structure, // then that structure describes depth/stencil resolve operations for the subpass. for (uint32_t i = 0; i < pCreateInfo->subpassCount; i++) { VkSubpassDescription2KHR subpass = pCreateInfo->pSubpasses[i]; const auto *resolve = lvl_find_in_chain<VkSubpassDescriptionDepthStencilResolveKHR>(subpass.pNext); if (resolve == nullptr) { continue; } if (resolve->pDepthStencilResolveAttachment != nullptr && resolve->pDepthStencilResolveAttachment->attachment != VK_ATTACHMENT_UNUSED) { if (subpass.pDepthStencilAttachment->attachment == VK_ATTACHMENT_UNUSED) { skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkSubpassDescriptionDepthStencilResolveKHR-pDepthStencilResolveAttachment-03177", "vkCreateRenderPass2KHR(): Subpass %u includes a VkSubpassDescriptionDepthStencilResolveKHR " "structure with resolve attachment %u, but pDepthStencilAttachment=VK_ATTACHMENT_UNUSED.", i, resolve->pDepthStencilResolveAttachment->attachment); } if (resolve->depthResolveMode == VK_RESOLVE_MODE_NONE_KHR && resolve->stencilResolveMode == VK_RESOLVE_MODE_NONE_KHR) { skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkSubpassDescriptionDepthStencilResolveKHR-pDepthStencilResolveAttachment-03178", "vkCreateRenderPass2KHR(): Subpass %u includes a VkSubpassDescriptionDepthStencilResolveKHR " "structure with resolve attachment %u, but both depth and stencil resolve modes are " "VK_RESOLVE_MODE_NONE_KHR.", i, resolve->pDepthStencilResolveAttachment->attachment); } } if (resolve->pDepthStencilResolveAttachment != nullptr && pCreateInfo->pAttachments[subpass.pDepthStencilAttachment->attachment].samples == VK_SAMPLE_COUNT_1_BIT) { skip |= log_msg( report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkSubpassDescriptionDepthStencilResolveKHR-pDepthStencilResolveAttachment-03179", "vkCreateRenderPass2KHR(): Subpass %u includes a VkSubpassDescriptionDepthStencilResolveKHR " "structure with resolve attachment %u. However pDepthStencilAttachment has sample count=VK_SAMPLE_COUNT_1_BIT.", i, resolve->pDepthStencilResolveAttachment->attachment); } if (pCreateInfo->pAttachments[resolve->pDepthStencilResolveAttachment->attachment].samples != VK_SAMPLE_COUNT_1_BIT) { skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkSubpassDescriptionDepthStencilResolveKHR-pDepthStencilResolveAttachment-03180", "vkCreateRenderPass2KHR(): Subpass %u includes a VkSubpassDescriptionDepthStencilResolveKHR " "structure with resolve attachment %u which has sample count=VK_SAMPLE_COUNT_1_BIT.", i, resolve->pDepthStencilResolveAttachment->attachment); } VkFormat pDepthStencilAttachmentFormat = pCreateInfo->pAttachments[subpass.pDepthStencilAttachment->attachment].format; VkFormat pDepthStencilResolveAttachmentFormat = pCreateInfo->pAttachments[resolve->pDepthStencilResolveAttachment->attachment].format; if ((FormatDepthSize(pDepthStencilAttachmentFormat) != FormatDepthSize(pDepthStencilResolveAttachmentFormat)) || (FormatDepthNumericalType(pDepthStencilAttachmentFormat) != FormatDepthNumericalType(pDepthStencilResolveAttachmentFormat))) { skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkSubpassDescriptionDepthStencilResolveKHR-pDepthStencilResolveAttachment-03181", "vkCreateRenderPass2KHR(): Subpass %u includes a VkSubpassDescriptionDepthStencilResolveKHR " "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.", i, resolve->pDepthStencilResolveAttachment->attachment, FormatDepthSize(pDepthStencilResolveAttachmentFormat), FormatDepthSize(pDepthStencilAttachmentFormat)); } if ((FormatStencilSize(pDepthStencilAttachmentFormat) != FormatStencilSize(pDepthStencilResolveAttachmentFormat)) || (FormatStencilNumericalType(pDepthStencilAttachmentFormat) != FormatStencilNumericalType(pDepthStencilResolveAttachmentFormat))) { skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkSubpassDescriptionDepthStencilResolveKHR-pDepthStencilResolveAttachment-03182", "vkCreateRenderPass2KHR(): Subpass %u includes a VkSubpassDescriptionDepthStencilResolveKHR " "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.", i, resolve->pDepthStencilResolveAttachment->attachment, FormatStencilSize(pDepthStencilResolveAttachmentFormat), FormatStencilSize(pDepthStencilAttachmentFormat)); } if (!(resolve->depthResolveMode == VK_RESOLVE_MODE_NONE_KHR || resolve->depthResolveMode & depth_stencil_resolve_props.supportedDepthResolveModes)) { skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkSubpassDescriptionDepthStencilResolveKHR-depthResolveMode-03183", "vkCreateRenderPass2KHR(): Subpass %u includes a VkSubpassDescriptionDepthStencilResolveKHR " "structure with invalid depthResolveMode=%u.", i, resolve->depthResolveMode); } if (!(resolve->stencilResolveMode == VK_RESOLVE_MODE_NONE_KHR || resolve->stencilResolveMode & depth_stencil_resolve_props.supportedStencilResolveModes)) { skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkSubpassDescriptionDepthStencilResolveKHR-stencilResolveMode-03184", "vkCreateRenderPass2KHR(): Subpass %u includes a VkSubpassDescriptionDepthStencilResolveKHR " "structure with invalid stencilResolveMode=%u.", i, resolve->stencilResolveMode); } if (FormatIsDepthAndStencil(pDepthStencilResolveAttachmentFormat) && depth_stencil_resolve_props.independentResolve == VK_FALSE && depth_stencil_resolve_props.independentResolveNone == VK_FALSE && !(resolve->depthResolveMode == resolve->stencilResolveMode)) { skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkSubpassDescriptionDepthStencilResolveKHR-pDepthStencilResolveAttachment-03185", "vkCreateRenderPass2KHR(): Subpass %u includes a VkSubpassDescriptionDepthStencilResolveKHR " "structure. The values of depthResolveMode (%u) and stencilResolveMode (%u) must be identical.", i, resolve->depthResolveMode, resolve->stencilResolveMode); } if (FormatIsDepthAndStencil(pDepthStencilResolveAttachmentFormat) && depth_stencil_resolve_props.independentResolve == VK_FALSE && depth_stencil_resolve_props.independentResolveNone == VK_TRUE && !(resolve->depthResolveMode == resolve->stencilResolveMode || resolve->depthResolveMode == VK_RESOLVE_MODE_NONE_KHR || resolve->stencilResolveMode == VK_RESOLVE_MODE_NONE_KHR)) { skip |= log_msg(report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkSubpassDescriptionDepthStencilResolveKHR-pDepthStencilResolveAttachment-03186", "vkCreateRenderPass2KHR(): Subpass %u includes a VkSubpassDescriptionDepthStencilResolveKHR " "structure. The values of depthResolveMode (%u) and stencilResolveMode (%u) must be identical, or " "one of them must be %u.", i, resolve->depthResolveMode, resolve->stencilResolveMode, VK_RESOLVE_MODE_NONE_KHR); } } return skip; } bool PreCallValidateCreateRenderPass2KHR(VkDevice device, const VkRenderPassCreateInfo2KHR *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkRenderPass *pRenderPass) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); bool skip = false; if (GetDeviceExtensions(device_data)->vk_khr_depth_stencil_resolve) { skip |= ValidateDepthStencilResolve(device_data->report_data, device_data->phys_dev_ext_props.depth_stencil_resolve_props, pCreateInfo); } auto render_pass = std::make_shared<RENDER_PASS_STATE>(pCreateInfo); skip |= ValidateCreateRenderPass(device_data, device, RENDER_PASS_VERSION_2, render_pass->createInfo.ptr(), render_pass.get()); return skip; } static bool ValidatePrimaryCommandBuffer(const layer_data *dev_data, const GLOBAL_CB_NODE *pCB, char const *cmd_name, std::string error_code) { bool skip = false; if (pCB->createInfo.level != VK_COMMAND_BUFFER_LEVEL_PRIMARY) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(pCB->commandBuffer), error_code, "Cannot execute command %s on a secondary command buffer.", cmd_name); } return skip; } static bool VerifyRenderAreaBounds(const layer_data *dev_data, const VkRenderPassBeginInfo *pRenderPassBegin) { bool skip = false; const safe_VkFramebufferCreateInfo *pFramebufferInfo = &GetFramebufferState(dev_data, pRenderPassBegin->framebuffer)->createInfo; if (pRenderPassBegin->renderArea.offset.x < 0 || (pRenderPassBegin->renderArea.offset.x + pRenderPassBegin->renderArea.extent.width) > pFramebufferInfo->width || pRenderPassBegin->renderArea.offset.y < 0 || (pRenderPassBegin->renderArea.offset.y + pRenderPassBegin->renderArea.extent.height) > pFramebufferInfo->height) { skip |= static_cast<bool>(log_msg( dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, kVUID_Core_DrawState_InvalidRenderArea, "Cannot execute a render pass with renderArea not within the bound of the framebuffer. RenderArea: x %d, y %d, width " "%d, height %d. Framebuffer: width %d, height %d.", pRenderPassBegin->renderArea.offset.x, pRenderPassBegin->renderArea.offset.y, pRenderPassBegin->renderArea.extent.width, pRenderPassBegin->renderArea.extent.height, pFramebufferInfo->width, pFramebufferInfo->height)); } 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_MEM_INFO 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 PreCallValidateCmdBeginRenderPass(layer_data *dev_data, GLOBAL_CB_NODE *cb_state, RenderPassCreateVersion rp_version, const VkRenderPassBeginInfo *pRenderPassBegin) { auto render_pass_state = pRenderPassBegin ? GetRenderPassState(dev_data, pRenderPassBegin->renderPass) : nullptr; auto framebuffer = pRenderPassBegin ? GetFramebufferState(dev_data, pRenderPassBegin->framebuffer) : nullptr; 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 ? "vkCmdBeginRenderPass2KHR()" : "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 *pSampleLocationsBeginInfo = lvl_find_in_chain<VkRenderPassSampleLocationsBeginInfoEXT>(pRenderPassBegin->pNext); if (pSampleLocationsBeginInfo) { for (uint32_t i = 0; i < pSampleLocationsBeginInfo->attachmentInitialSampleLocationsCount; ++i) { if (pSampleLocationsBeginInfo->pAttachmentInitialSampleLocations[i].attachmentIndex >= render_pass_state->createInfo.attachmentCount) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkAttachmentSampleLocationsEXT-attachmentIndex-01531", "Attachment index %u specified by attachment sample locations %u is greater than the " "attachment count of %u for the render pass being begun.", pSampleLocationsBeginInfo->pAttachmentInitialSampleLocations[i].attachmentIndex, i, render_pass_state->createInfo.attachmentCount); } } for (uint32_t i = 0; i < pSampleLocationsBeginInfo->postSubpassSampleLocationsCount; ++i) { if (pSampleLocationsBeginInfo->pPostSubpassSampleLocations[i].subpassIndex >= render_pass_state->createInfo.subpassCount) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkSubpassSampleLocationsEXT-subpassIndex-01532", "Subpass index %u specified by subpass sample locations %u is greater than the subpass count " "of %u for the render pass being begun.", pSampleLocationsBeginInfo->pPostSubpassSampleLocations[i].subpassIndex, i, render_pass_state->createInfo.subpassCount); } } } for (uint32_t i = 0; i < render_pass_state->createInfo.attachmentCount; ++i) { auto pAttachment = &render_pass_state->createInfo.pAttachments[i]; if (FormatSpecificLoadAndStoreOpSettings(pAttachment->format, pAttachment->loadOp, pAttachment->stencilLoadOp, VK_ATTACHMENT_LOAD_OP_CLEAR)) { clear_op_size = static_cast<uint32_t>(i) + 1; } } if (clear_op_size > pRenderPassBegin->clearValueCount) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_RENDER_PASS_EXT, HandleToUint64(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 " "renderPass 0x%" PRIx64 " 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, HandleToUint64(render_pass_state->renderPass), clear_op_size, clear_op_size - 1); } skip |= VerifyRenderAreaBounds(dev_data, pRenderPassBegin); skip |= VerifyFramebufferAndRenderPassLayouts(dev_data, rp_version, cb_state, pRenderPassBegin, GetFramebufferState(dev_data, pRenderPassBegin->framebuffer)); if (framebuffer->rp_state->renderPass != render_pass_state->renderPass) { skip |= ValidateRenderPassCompatibility(dev_data, "render pass", render_pass_state, "framebuffer", framebuffer->rp_state.get(), function_name, "VUID-VkRenderPassBeginInfo-renderPass-00904"); } vuid = use_rp2 ? "VUID-vkCmdBeginRenderPass2KHR-renderpass" : "VUID-vkCmdBeginRenderPass-renderpass"; skip |= InsideRenderPass(dev_data, cb_state, function_name, vuid); skip |= ValidateDependencies(dev_data, framebuffer, render_pass_state); vuid = use_rp2 ? "VUID-vkCmdBeginRenderPass2KHR-bufferlevel" : "VUID-vkCmdBeginRenderPass-bufferlevel"; skip |= ValidatePrimaryCommandBuffer(dev_data, cb_state, function_name, vuid); vuid = use_rp2 ? "VUID-vkCmdBeginRenderPass2KHR-commandBuffer-cmdpool" : "VUID-vkCmdBeginRenderPass-commandBuffer-cmdpool"; skip |= ValidateCmdQueueFlags(dev_data, cb_state, function_name, VK_QUEUE_GRAPHICS_BIT, vuid); const CMD_TYPE cmd_type = use_rp2 ? CMD_BEGINRENDERPASS2KHR : CMD_BEGINRENDERPASS; skip |= ValidateCmd(dev_data, cb_state, cmd_type, function_name); } return skip; } void PreCallRecordCmdBeginRenderPass(layer_data *dev_data, GLOBAL_CB_NODE *cb_state, const VkRenderPassBeginInfo *pRenderPassBegin, const VkSubpassContents contents) { auto render_pass_state = pRenderPassBegin ? GetRenderPassState(dev_data, pRenderPassBegin->renderPass) : nullptr; auto framebuffer = pRenderPassBegin ? GetFramebufferState(dev_data, pRenderPassBegin->framebuffer) : nullptr; assert(cb_state); if (render_pass_state) { cb_state->activeFramebuffer = pRenderPassBegin->framebuffer; cb_state->activeRenderPass = render_pass_state; // This is a shallow copy as that is all that is needed for now cb_state->activeRenderPassBeginInfo = *pRenderPassBegin; cb_state->activeSubpass = 0; cb_state->activeSubpassContents = contents; cb_state->framebuffers.insert(pRenderPassBegin->framebuffer); // Connect this framebuffer and its children to this cmdBuffer AddFramebufferBinding(dev_data, cb_state, framebuffer); // Connect this RP to cmdBuffer AddCommandBufferBinding(&render_pass_state->cb_bindings, {HandleToUint64(render_pass_state->renderPass), kVulkanObjectTypeRenderPass}, cb_state); // transition attachments to the correct layouts for beginning of renderPass and first subpass TransitionBeginRenderPassLayouts(dev_data, cb_state, render_pass_state, framebuffer); } } bool PreCallValidateCmdNextSubpass(layer_data *dev_data, GLOBAL_CB_NODE *cb_state, RenderPassCreateVersion rp_version, VkCommandBuffer commandBuffer) { bool skip = false; const bool use_rp2 = (rp_version == RENDER_PASS_VERSION_2); const char *vuid; const char *const function_name = use_rp2 ? "vkCmdNextSubpass2KHR()" : "vkCmdNextSubpass()"; vuid = use_rp2 ? "VUID-vkCmdNextSubpass2KHR-bufferlevel" : "VUID-vkCmdNextSubpass-bufferlevel"; skip |= ValidatePrimaryCommandBuffer(dev_data, cb_state, function_name, vuid); vuid = use_rp2 ? "VUID-vkCmdNextSubpass2KHR-commandBuffer-cmdpool" : "VUID-vkCmdNextSubpass-commandBuffer-cmdpool"; skip |= ValidateCmdQueueFlags(dev_data, cb_state, function_name, VK_QUEUE_GRAPHICS_BIT, vuid); const CMD_TYPE cmd_type = use_rp2 ? CMD_NEXTSUBPASS2KHR : CMD_NEXTSUBPASS; skip |= ValidateCmd(dev_data, cb_state, cmd_type, function_name); vuid = use_rp2 ? "VUID-vkCmdNextSubpass2KHR-renderpass" : "VUID-vkCmdNextSubpass-renderpass"; skip |= OutsideRenderPass(dev_data, cb_state, function_name, vuid); auto subpassCount = cb_state->activeRenderPass->createInfo.subpassCount; if (cb_state->activeSubpass == subpassCount - 1) { vuid = use_rp2 ? "VUID-vkCmdNextSubpass2KHR-None-03102" : "VUID-vkCmdNextSubpass-None-00909"; skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(commandBuffer), vuid, "%s: Attempted to advance beyond final subpass.", function_name); } return skip; } void PostCallRecordCmdNextSubpass(layer_data *dev_data, GLOBAL_CB_NODE *cb_node, VkSubpassContents contents) { cb_node->activeSubpass++; cb_node->activeSubpassContents = contents; TransitionSubpassLayouts(dev_data, cb_node, cb_node->activeRenderPass, cb_node->activeSubpass, GetFramebufferState(dev_data, cb_node->activeRenderPassBeginInfo.framebuffer)); } bool PreCallValidateCmdEndRenderPass(layer_data *dev_data, GLOBAL_CB_NODE *cb_state, RenderPassCreateVersion rp_version, VkCommandBuffer commandBuffer) { 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; if (rp_state) { if (cb_state->activeSubpass != rp_state->createInfo.subpassCount - 1) { vuid = use_rp2 ? "VUID-vkCmdEndRenderPass2KHR-None-03103" : "VUID-vkCmdEndRenderPass-None-00910"; skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(commandBuffer), vuid, "%s: Called before reaching final subpass.", function_name); } } vuid = use_rp2 ? "VUID-vkCmdEndRenderPass2KHR-renderpass" : "VUID-vkCmdEndRenderPass-renderpass"; skip |= OutsideRenderPass(dev_data, cb_state, function_name, vuid); vuid = use_rp2 ? "VUID-vkCmdEndRenderPass2KHR-bufferlevel" : "VUID-vkCmdEndRenderPass-bufferlevel"; skip |= ValidatePrimaryCommandBuffer(dev_data, cb_state, function_name, vuid); vuid = use_rp2 ? "VUID-vkCmdEndRenderPass2KHR-commandBuffer-cmdpool" : "VUID-vkCmdEndRenderPass-commandBuffer-cmdpool"; skip |= ValidateCmdQueueFlags(dev_data, cb_state, function_name, VK_QUEUE_GRAPHICS_BIT, vuid); const CMD_TYPE cmd_type = use_rp2 ? CMD_ENDRENDERPASS2KHR : CMD_ENDRENDERPASS; skip |= ValidateCmd(dev_data, cb_state, cmd_type, function_name); return skip; } void PostCallRecordCmdEndRenderPass(layer_data *dev_data, GLOBAL_CB_NODE *cb_state) { FRAMEBUFFER_STATE *framebuffer = GetFramebufferState(dev_data, cb_state->activeFramebuffer); TransitionFinalSubpassLayouts(dev_data, cb_state, &cb_state->activeRenderPassBeginInfo, framebuffer); cb_state->activeRenderPass = nullptr; cb_state->activeSubpass = 0; cb_state->activeFramebuffer = VK_NULL_HANDLE; } static bool ValidateFramebuffer(layer_data *dev_data, VkCommandBuffer primaryBuffer, const GLOBAL_CB_NODE *pCB, VkCommandBuffer secondaryBuffer, const GLOBAL_CB_NODE *pSubCB, const char *caller) { bool skip = false; if (!pSubCB->beginInfo.pInheritanceInfo) { return skip; } VkFramebuffer primary_fb = pCB->activeFramebuffer; VkFramebuffer secondary_fb = pSubCB->beginInfo.pInheritanceInfo->framebuffer; if (secondary_fb != VK_NULL_HANDLE) { if (primary_fb != secondary_fb) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(primaryBuffer), "VUID-vkCmdExecuteCommands-pCommandBuffers-00099", "vkCmdExecuteCommands() called w/ invalid secondary command buffer 0x%" PRIx64 " which has a framebuffer 0x%" PRIx64 " that is not the same as the primary command buffer's current active framebuffer 0x%" PRIx64 ".", HandleToUint64(secondaryBuffer), HandleToUint64(secondary_fb), HandleToUint64(primary_fb)); } auto fb = GetFramebufferState(dev_data, secondary_fb); if (!fb) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(primaryBuffer), kVUID_Core_DrawState_InvalidSecondaryCommandBuffer, "vkCmdExecuteCommands() called w/ invalid Cmd Buffer 0x%" PRIx64 " which has invalid framebuffer 0x%" PRIx64 ".", HandleToUint64(secondaryBuffer), HandleToUint64(secondary_fb)); return skip; } } return skip; } static bool ValidateSecondaryCommandBufferState(layer_data *dev_data, GLOBAL_CB_NODE *pCB, GLOBAL_CB_NODE *pSubCB) { bool skip = false; unordered_set<int> activeTypes; for (auto queryObject : pCB->activeQueries) { auto queryPoolData = dev_data->queryPoolMap.find(queryObject.pool); if (queryPoolData != dev_data->queryPoolMap.end()) { if (queryPoolData->second.createInfo.queryType == VK_QUERY_TYPE_PIPELINE_STATISTICS && pSubCB->beginInfo.pInheritanceInfo) { VkQueryPipelineStatisticFlags cmdBufStatistics = pSubCB->beginInfo.pInheritanceInfo->pipelineStatistics; if ((cmdBufStatistics & queryPoolData->second.createInfo.pipelineStatistics) != cmdBufStatistics) { skip |= log_msg( dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(pCB->commandBuffer), "VUID-vkCmdExecuteCommands-commandBuffer-00104", "vkCmdExecuteCommands() called w/ invalid Cmd Buffer 0x%" PRIx64 " which has invalid active query pool 0x%" PRIx64 ". Pipeline statistics is being queried so the command buffer must have all bits set on the queryPool.", HandleToUint64(pCB->commandBuffer), HandleToUint64(queryPoolData->first)); } } activeTypes.insert(queryPoolData->second.createInfo.queryType); } } for (auto queryObject : pSubCB->startedQueries) { auto queryPoolData = dev_data->queryPoolMap.find(queryObject.pool); if (queryPoolData != dev_data->queryPoolMap.end() && activeTypes.count(queryPoolData->second.createInfo.queryType)) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(pCB->commandBuffer), kVUID_Core_DrawState_InvalidSecondaryCommandBuffer, "vkCmdExecuteCommands() called w/ invalid Cmd Buffer 0x%" PRIx64 " which has invalid active query pool 0x%" PRIx64 " of type %d but a query of that type has been started on secondary Cmd Buffer 0x%" PRIx64 ".", HandleToUint64(pCB->commandBuffer), HandleToUint64(queryPoolData->first), queryPoolData->second.createInfo.queryType, HandleToUint64(pSubCB->commandBuffer)); } } auto primary_pool = GetCommandPoolNode(dev_data, pCB->createInfo.commandPool); auto secondary_pool = GetCommandPoolNode(dev_data, pSubCB->createInfo.commandPool); if (primary_pool && secondary_pool && (primary_pool->queueFamilyIndex != secondary_pool->queueFamilyIndex)) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(pSubCB->commandBuffer), kVUID_Core_DrawState_InvalidQueueFamily, "vkCmdExecuteCommands(): Primary command buffer 0x%" PRIx64 " created in queue family %d has secondary command buffer 0x%" PRIx64 " created in queue family %d.", HandleToUint64(pCB->commandBuffer), primary_pool->queueFamilyIndex, HandleToUint64(pSubCB->commandBuffer), secondary_pool->queueFamilyIndex); } return skip; } bool PreCallValidateCmdExecuteCommands(layer_data *dev_data, GLOBAL_CB_NODE *cb_state, VkCommandBuffer commandBuffer, uint32_t commandBuffersCount, const VkCommandBuffer *pCommandBuffers) { bool skip = false; GLOBAL_CB_NODE *sub_cb_state = NULL; for (uint32_t i = 0; i < commandBuffersCount; i++) { sub_cb_state = GetCBNode(dev_data, pCommandBuffers[i]); assert(sub_cb_state); if (VK_COMMAND_BUFFER_LEVEL_PRIMARY == sub_cb_state->createInfo.level) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(pCommandBuffers[i]), "VUID-vkCmdExecuteCommands-pCommandBuffers-00088", "vkCmdExecuteCommands() called w/ Primary Cmd Buffer 0x%" PRIx64 " in element %u of pCommandBuffers array. All cmd buffers in pCommandBuffers array must be secondary.", HandleToUint64(pCommandBuffers[i]), i); } else if (cb_state->activeRenderPass) { // Secondary CB w/i RenderPass must have *CONTINUE_BIT set if (sub_cb_state->beginInfo.pInheritanceInfo != nullptr) { auto secondary_rp_state = GetRenderPassState(dev_data, sub_cb_state->beginInfo.pInheritanceInfo->renderPass); if (!(sub_cb_state->beginInfo.flags & VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT)) { skip |= log_msg( dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(pCommandBuffers[i]), "VUID-vkCmdExecuteCommands-pCommandBuffers-00096", "vkCmdExecuteCommands(): Secondary Command Buffer (0x%" PRIx64 ") executed within render pass (0x%" PRIx64 ") must have had vkBeginCommandBuffer() called w/ " "VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT set.", HandleToUint64(pCommandBuffers[i]), HandleToUint64(cb_state->activeRenderPass->renderPass)); } else { // 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( dev_data, "primary command buffer", cb_state->activeRenderPass, "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(dev_data, 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); } } } } } // TODO(mlentine): Move more logic into this method skip |= ValidateSecondaryCommandBufferState(dev_data, cb_state, sub_cb_state); skip |= ValidateCommandBufferState(dev_data, 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->in_use.load() || cb_state->linkedCommandBuffers.count(sub_cb_state)) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(cb_state->commandBuffer), "VUID-vkCmdExecuteCommands-pCommandBuffers-00090", "Attempt to simultaneously execute command buffer 0x%" PRIx64 " without VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT set!", HandleToUint64(cb_state->commandBuffer)); } if (cb_state->beginInfo.flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT) { // Warn that non-simultaneous secondary cmd buffer renders primary non-simultaneous skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(pCommandBuffers[i]), kVUID_Core_DrawState_InvalidCommandBufferSimultaneousUse, "vkCmdExecuteCommands(): Secondary Command Buffer (0x%" PRIx64 ") does not have VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT set and will cause primary " "command buffer (0x%" PRIx64 ") to be treated as if it does not have VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT set, even " "though it does.", HandleToUint64(pCommandBuffers[i]), HandleToUint64(cb_state->commandBuffer)); // TODO: Clearing the VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT needs to be moved from the validation step to the // recording step cb_state->beginInfo.flags &= ~VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT; } } if (!cb_state->activeQueries.empty() && !dev_data->enabled_features.core.inheritedQueries) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(pCommandBuffers[i]), "VUID-vkCmdExecuteCommands-commandBuffer-00101", "vkCmdExecuteCommands(): Secondary Command Buffer (0x%" PRIx64 ") cannot be submitted with a query in flight and inherited queries not supported on this device.", HandleToUint64(pCommandBuffers[i])); } // Propagate layout transitions to the primary cmd buffer // Novel Valid usage: "UNASSIGNED-vkCmdExecuteCommands-commandBuffer-00001" // initial layout usage of secondary command buffers resources must match parent command buffer for (const auto &ilm_entry : sub_cb_state->imageLayoutMap) { auto cb_entry = cb_state->imageLayoutMap.find(ilm_entry.first); if (cb_entry != cb_state->imageLayoutMap.end()) { // For exact matches ImageSubresourcePair matches, validate and update the parent entry if ((VK_IMAGE_LAYOUT_UNDEFINED != ilm_entry.second.initialLayout) && (cb_entry->second.layout != ilm_entry.second.initialLayout)) { const VkImageSubresource &subresource = ilm_entry.first.subresource; log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(pCommandBuffers[i]), "UNASSIGNED-vkCmdExecuteCommands-commandBuffer-00001", "%s: Executed secondary command buffer using image 0x%" PRIx64 " (subresource: aspectMask 0x%X array layer %u, mip level %u) which expects layout %s--instead, image " "0x%" PRIx64 "'s current layout is %s.", "vkCmdExecuteCommands():", HandleToUint64(ilm_entry.first.image), subresource.aspectMask, subresource.arrayLayer, subresource.mipLevel, string_VkImageLayout(ilm_entry.second.initialLayout), HandleToUint64(ilm_entry.first.image), string_VkImageLayout(cb_entry->second.layout)); } } else { // Look for partial matches (in aspectMask), and update or create parent map entry in SetLayout assert(ilm_entry.first.hasSubresource); IMAGE_CMD_BUF_LAYOUT_NODE node; if (FindCmdBufLayout(dev_data, cb_state, ilm_entry.first.image, ilm_entry.first.subresource, node)) { if ((VK_IMAGE_LAYOUT_UNDEFINED != ilm_entry.second.initialLayout) && (node.layout != ilm_entry.second.initialLayout)) { const VkImageSubresource &subresource = ilm_entry.first.subresource; log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(pCommandBuffers[i]), "UNASSIGNED-vkCmdExecuteCommands-commandBuffer-00001", "%s: Executed secondary command buffer using image 0x%" PRIx64 " (subresource: aspectMask 0x%X array layer %u, mip level %u) which expects layout %s--instead, " "image 0x%" PRIx64 "'s current layout is %s.", "vkCmdExecuteCommands():", HandleToUint64(ilm_entry.first.image), subresource.aspectMask, subresource.arrayLayer, subresource.mipLevel, string_VkImageLayout(ilm_entry.second.initialLayout), HandleToUint64(ilm_entry.first.image), string_VkImageLayout(node.layout)); } } } } // TODO: Linking command buffers here is necessary to pass existing validation tests--however, this state change still needs // to be removed from the validation step sub_cb_state->primaryCommandBuffer = cb_state->commandBuffer; cb_state->linkedCommandBuffers.insert(sub_cb_state); sub_cb_state->linkedCommandBuffers.insert(cb_state); } skip |= ValidatePrimaryCommandBuffer(dev_data, cb_state, "vkCmdExecuteCommands()", "VUID-vkCmdExecuteCommands-bufferlevel"); skip |= ValidateCmdQueueFlags(dev_data, cb_state, "vkCmdExecuteCommands()", VK_QUEUE_TRANSFER_BIT | VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT, "VUID-vkCmdExecuteCommands-commandBuffer-cmdpool"); skip |= ValidateCmd(dev_data, cb_state, CMD_EXECUTECOMMANDS, "vkCmdExecuteCommands()"); return skip; } void PreCallRecordCmdExecuteCommands(layer_data *dev_data, GLOBAL_CB_NODE *cb_state, uint32_t commandBuffersCount, const VkCommandBuffer *pCommandBuffers) { GLOBAL_CB_NODE *sub_cb_state = NULL; for (uint32_t i = 0; i < commandBuffersCount; i++) { sub_cb_state = GetCBNode(dev_data, pCommandBuffers[i]); assert(sub_cb_state); if (!(sub_cb_state->beginInfo.flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT)) { if (cb_state->beginInfo.flags & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT) { // TODO: Because this is a state change, clearing the VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT needs to be moved // from the validation step to the recording step cb_state->beginInfo.flags &= ~VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT; } } // Propagate layout transitions to the primary cmd buffer // Novel Valid usage: "UNASSIGNED-vkCmdExecuteCommands-commandBuffer-00001" // initial layout usage of secondary command buffers resources must match parent command buffer for (const auto &ilm_entry : sub_cb_state->imageLayoutMap) { auto cb_entry = cb_state->imageLayoutMap.find(ilm_entry.first); if (cb_entry != cb_state->imageLayoutMap.end()) { // For exact matches ImageSubresourcePair matches, update the parent entry cb_entry->second.layout = ilm_entry.second.layout; } else { // Look for partial matches (in aspectMask), and update or create parent map entry in SetLayout assert(ilm_entry.first.hasSubresource); IMAGE_CMD_BUF_LAYOUT_NODE node; if (!FindCmdBufLayout(dev_data, cb_state, ilm_entry.first.image, ilm_entry.first.subresource, node)) { node.initialLayout = ilm_entry.second.initialLayout; } node.layout = ilm_entry.second.layout; SetLayout(dev_data, cb_state, ilm_entry.first, node); } } sub_cb_state->primaryCommandBuffer = cb_state->commandBuffer; cb_state->linkedCommandBuffers.insert(sub_cb_state); sub_cb_state->linkedCommandBuffers.insert(cb_state); for (auto &function : sub_cb_state->queryUpdates) { cb_state->queryUpdates.push_back(function); } for (auto &function : sub_cb_state->queue_submit_functions) { cb_state->queue_submit_functions.push_back(function); } } } bool PreCallValidateMapMemory(VkDevice device, VkDeviceMemory mem, VkDeviceSize offset, VkDeviceSize size, VkFlags flags, void **ppData) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); bool skip = false; DEVICE_MEM_INFO *mem_info = GetMemObjInfo(device_data, mem); if (mem_info) { auto end_offset = (VK_WHOLE_SIZE == size) ? mem_info->alloc_info.allocationSize - 1 : offset + size - 1; skip |= ValidateMapImageLayouts(device_data, device, mem_info, offset, end_offset); if ((device_data->phys_dev_mem_props.memoryTypes[mem_info->alloc_info.memoryTypeIndex].propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) == 0) { skip = log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT, HandleToUint64(mem), "VUID-vkMapMemory-memory-00682", "Mapping Memory without VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT set: mem obj 0x%" PRIx64 ".", HandleToUint64(mem)); } } skip |= ValidateMapMemRange(device_data, mem, offset, size); return skip; } void PostCallRecordMapMemory(VkDevice device, VkDeviceMemory mem, VkDeviceSize offset, VkDeviceSize size, VkFlags flags, void **ppData, VkResult result) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); if (VK_SUCCESS != result) return; // TODO : What's the point of this range? See comment on creating new "bound_range" above, which may replace this StoreMemRanges(device_data, mem, offset, size); InitializeAndTrackMemory(device_data, mem, offset, size, ppData); } bool PreCallValidateUnmapMemory(VkDevice device, VkDeviceMemory mem) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); bool skip = false; auto mem_info = GetMemObjInfo(device_data, mem); if (mem_info && !mem_info->mem_range.size) { // Valid Usage: memory must currently be mapped skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT, HandleToUint64(mem), "VUID-vkUnmapMemory-memory-00689", "Unmapping Memory without memory being mapped: mem obj 0x%" PRIx64 ".", HandleToUint64(mem)); } return skip; } void PreCallRecordUnmapMemory(VkDevice device, VkDeviceMemory mem) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); auto mem_info = GetMemObjInfo(device_data, mem); mem_info->mem_range.size = 0; if (mem_info->shadow_copy) { free(mem_info->shadow_copy_base); mem_info->shadow_copy_base = 0; mem_info->shadow_copy = 0; } } static bool ValidateMemoryIsMapped(layer_data *dev_data, const char *funcName, uint32_t memRangeCount, const VkMappedMemoryRange *pMemRanges) { bool skip = false; for (uint32_t i = 0; i < memRangeCount; ++i) { auto mem_info = GetMemObjInfo(dev_data, pMemRanges[i].memory); if (mem_info) { if (pMemRanges[i].size == VK_WHOLE_SIZE) { if (mem_info->mem_range.offset > pMemRanges[i].offset) { skip |= log_msg( dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT, HandleToUint64(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->mem_range.offset)); } } else { const uint64_t data_end = (mem_info->mem_range.size == VK_WHOLE_SIZE) ? mem_info->alloc_info.allocationSize : (mem_info->mem_range.offset + mem_info->mem_range.size); if ((mem_info->mem_range.offset > pMemRanges[i].offset) || (data_end < (pMemRanges[i].offset + pMemRanges[i].size))) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT, HandleToUint64(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; } static bool ValidateAndCopyNoncoherentMemoryToDriver(layer_data *dev_data, uint32_t mem_range_count, const VkMappedMemoryRange *mem_ranges) { bool skip = false; for (uint32_t i = 0; i < mem_range_count; ++i) { auto mem_info = GetMemObjInfo(dev_data, mem_ranges[i].memory); if (mem_info) { if (mem_info->shadow_copy) { VkDeviceSize size = (mem_info->mem_range.size != VK_WHOLE_SIZE) ? mem_info->mem_range.size : (mem_info->alloc_info.allocationSize - mem_info->mem_range.offset); char *data = static_cast<char *>(mem_info->shadow_copy); for (uint64_t j = 0; j < mem_info->shadow_pad_size; ++j) { if (data[j] != NoncoherentMemoryFillValue) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT, HandleToUint64(mem_ranges[i].memory), kVUID_Core_MemTrack_InvalidMap, "Memory underflow was detected on mem obj 0x%" PRIx64, HandleToUint64(mem_ranges[i].memory)); } } for (uint64_t j = (size + mem_info->shadow_pad_size); j < (2 * mem_info->shadow_pad_size + size); ++j) { if (data[j] != NoncoherentMemoryFillValue) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT, HandleToUint64(mem_ranges[i].memory), kVUID_Core_MemTrack_InvalidMap, "Memory overflow was detected on mem obj 0x%" PRIx64, HandleToUint64(mem_ranges[i].memory)); } } memcpy(mem_info->p_driver_data, static_cast<void *>(data + mem_info->shadow_pad_size), (size_t)(size)); } } } return skip; } static void CopyNoncoherentMemoryFromDriver(layer_data *dev_data, uint32_t mem_range_count, const VkMappedMemoryRange *mem_ranges) { for (uint32_t i = 0; i < mem_range_count; ++i) { auto mem_info = GetMemObjInfo(dev_data, mem_ranges[i].memory); if (mem_info && mem_info->shadow_copy) { VkDeviceSize size = (mem_info->mem_range.size != VK_WHOLE_SIZE) ? mem_info->mem_range.size : (mem_info->alloc_info.allocationSize - mem_ranges[i].offset); char *data = static_cast<char *>(mem_info->shadow_copy); memcpy(data + mem_info->shadow_pad_size, mem_info->p_driver_data, (size_t)(size)); } } } static bool ValidateMappedMemoryRangeDeviceLimits(layer_data *dev_data, const char *func_name, uint32_t mem_range_count, const VkMappedMemoryRange *mem_ranges) { bool skip = false; for (uint32_t i = 0; i < mem_range_count; ++i) { uint64_t atom_size = dev_data->phys_dev_properties.properties.limits.nonCoherentAtomSize; if (SafeModulo(mem_ranges[i].offset, atom_size) != 0) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT, HandleToUint64(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, mem_ranges[i].offset, atom_size); } auto mem_info = GetMemObjInfo(dev_data, mem_ranges[i].memory); if ((mem_ranges[i].size != VK_WHOLE_SIZE) && (mem_ranges[i].size + mem_ranges[i].offset != mem_info->alloc_info.allocationSize) && (SafeModulo(mem_ranges[i].size, atom_size) != 0)) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_MEMORY_EXT, HandleToUint64(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 ").", func_name, i, mem_ranges[i].size, atom_size); } } return skip; } bool PreCallValidateFlushMappedMemoryRanges(VkDevice device, uint32_t memRangeCount, const VkMappedMemoryRange *pMemRanges) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); bool skip = false; skip |= ValidateMappedMemoryRangeDeviceLimits(device_data, "vkFlushMappedMemoryRanges", memRangeCount, pMemRanges); skip |= ValidateAndCopyNoncoherentMemoryToDriver(device_data, memRangeCount, pMemRanges); skip |= ValidateMemoryIsMapped(device_data, "vkFlushMappedMemoryRanges", memRangeCount, pMemRanges); return skip; } bool PreCallValidateInvalidateMappedMemoryRanges(VkDevice device, uint32_t memRangeCount, const VkMappedMemoryRange *pMemRanges) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); bool skip = false; skip |= ValidateMappedMemoryRangeDeviceLimits(device_data, "vkInvalidateMappedMemoryRanges", memRangeCount, pMemRanges); skip |= ValidateMemoryIsMapped(device_data, "vkInvalidateMappedMemoryRanges", memRangeCount, pMemRanges); return skip; } void PostCallRecordInvalidateMappedMemoryRanges(VkDevice device, uint32_t memRangeCount, const VkMappedMemoryRange *pMemRanges, VkResult result) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); if (VK_SUCCESS == result) { // Update our shadow copy with modified driver data CopyNoncoherentMemoryFromDriver(device_data, memRangeCount, pMemRanges); } } bool ValidateBindImageMemory(layer_data *device_data, VkImage image, VkDeviceMemory mem, VkDeviceSize memoryOffset, const char *api_name) { bool skip = false; IMAGE_STATE *image_state = GetImageState(device_data, image); if (image_state) { // Track objects tied to memory uint64_t image_handle = HandleToUint64(image); skip = ValidateSetMemBinding(device_data, mem, image_handle, kVulkanObjectTypeImage, api_name); if (!image_state->memory_requirements_checked) { // There's not an explicit requirement in the spec to call vkGetImageMemoryRequirements() prior to calling // BindImageMemory but it's implied in that memory being bound must conform with VkMemoryRequirements from // vkGetImageMemoryRequirements() skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, image_handle, kVUID_Core_DrawState_InvalidImage, "%s: Binding memory to image 0x%" PRIx64 " but vkGetImageMemoryRequirements() has not been called on that image.", api_name, HandleToUint64(image_handle)); // Make the call for them so we can verify the state device_data->dispatch_table.GetImageMemoryRequirements(device_data->device, image, &image_state->requirements); } // Validate bound memory range information auto mem_info = GetMemObjInfo(device_data, mem); if (mem_info) { skip |= ValidateInsertImageMemoryRange(device_data, image, mem_info, memoryOffset, image_state->requirements, image_state->createInfo.tiling == VK_IMAGE_TILING_LINEAR, api_name); skip |= ValidateMemoryTypes(device_data, mem_info, image_state->requirements.memoryTypeBits, api_name, "VUID-vkBindImageMemory-memory-01047"); } // Validate memory requirements alignment if (SafeModulo(memoryOffset, image_state->requirements.alignment) != 0) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, image_handle, "VUID-vkBindImageMemory-memoryOffset-01048", "%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.", api_name, memoryOffset, image_state->requirements.alignment); } if (mem_info) { // Validate memory requirements size if (image_state->requirements.size > mem_info->alloc_info.allocationSize - memoryOffset) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, image_handle, "VUID-vkBindImageMemory-size-01049", "%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.", api_name, mem_info->alloc_info.allocationSize - memoryOffset, image_state->requirements.size); } // Validate dedicated allocation if (mem_info->is_dedicated && ((mem_info->dedicated_image != image) || (memoryOffset != 0))) { // TODO: Add vkBindImageMemory2KHR error message when added to spec. auto validation_error = kVUIDUndefined; if (strcmp(api_name, "vkBindImageMemory()") == 0) { validation_error = "VUID-vkBindImageMemory-memory-01509"; } skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT, image_handle, validation_error, "%s: for dedicated memory allocation 0x%" PRIxLEAST64 ", VkMemoryDedicatedAllocateInfoKHR::image 0x%" PRIXLEAST64 " must be equal to image 0x%" PRIxLEAST64 " and memoryOffset 0x%" PRIxLEAST64 " must be zero.", api_name, HandleToUint64(mem), HandleToUint64(mem_info->dedicated_image), image_handle, memoryOffset); } } } return skip; } bool PreCallValidateBindImageMemory(VkDevice device, VkImage image, VkDeviceMemory mem, VkDeviceSize memoryOffset) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); return ValidateBindImageMemory(device_data, image, mem, memoryOffset, "vkBindImageMemory()"); } void UpdateBindImageMemoryState(layer_data *device_data, VkImage image, VkDeviceMemory mem, VkDeviceSize memoryOffset) { IMAGE_STATE *image_state = GetImageState(device_data, image); if (image_state) { // Track bound memory range information auto mem_info = GetMemObjInfo(device_data, mem); if (mem_info) { InsertImageMemoryRange(device_data, image, mem_info, memoryOffset, image_state->requirements, image_state->createInfo.tiling == VK_IMAGE_TILING_LINEAR); } // Track objects tied to memory uint64_t image_handle = HandleToUint64(image); SetMemBinding(device_data, mem, image_state, memoryOffset, image_handle, kVulkanObjectTypeImage); } } void PostCallRecordBindImageMemory(VkDevice device, VkImage image, VkDeviceMemory mem, VkDeviceSize memoryOffset, VkResult result) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); if (VK_SUCCESS != result) return; UpdateBindImageMemoryState(device_data, image, mem, memoryOffset); } bool PreCallValidateBindImageMemory2(VkDevice device, uint32_t bindInfoCount, const VkBindImageMemoryInfoKHR *pBindInfos) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); bool skip = false; char api_name[128]; for (uint32_t i = 0; i < bindInfoCount; i++) { sprintf(api_name, "vkBindImageMemory2() pBindInfos[%u]", i); skip |= ValidateBindImageMemory(device_data, pBindInfos[i].image, pBindInfos[i].memory, pBindInfos[i].memoryOffset, api_name); } return skip; } bool PreCallValidateBindImageMemory2KHR(VkDevice device, uint32_t bindInfoCount, const VkBindImageMemoryInfoKHR *pBindInfos) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); bool skip = false; char api_name[128]; for (uint32_t i = 0; i < bindInfoCount; i++) { sprintf(api_name, "vkBindImageMemory2KHR() pBindInfos[%u]", i); skip |= ValidateBindImageMemory(device_data, pBindInfos[i].image, pBindInfos[i].memory, pBindInfos[i].memoryOffset, api_name); } return skip; } void PostCallRecordBindImageMemory2(VkDevice device, uint32_t bindInfoCount, const VkBindImageMemoryInfoKHR *pBindInfos, VkResult result) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); if (VK_SUCCESS != result) return; for (uint32_t i = 0; i < bindInfoCount; i++) { UpdateBindImageMemoryState(device_data, pBindInfos[i].image, pBindInfos[i].memory, pBindInfos[i].memoryOffset); } } void PostCallRecordBindImageMemory2KHR(VkDevice device, uint32_t bindInfoCount, const VkBindImageMemoryInfoKHR *pBindInfos, VkResult result) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); if (VK_SUCCESS != result) return; for (uint32_t i = 0; i < bindInfoCount; i++) { UpdateBindImageMemoryState(device_data, pBindInfos[i].image, pBindInfos[i].memory, pBindInfos[i].memoryOffset); } } bool PreCallValidateSetEvent(layer_data *dev_data, VkEvent event) { bool skip = false; auto event_state = GetEventNode(dev_data, event); if (event_state) { event_state->needsSignaled = false; event_state->stageMask = VK_PIPELINE_STAGE_HOST_BIT; if (event_state->write_in_use) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_EVENT_EXT, HandleToUint64(event), kVUID_Core_DrawState_QueueForwardProgress, "Cannot call vkSetEvent() on event 0x%" PRIx64 " that is already in use by a command buffer.", HandleToUint64(event)); } } return skip; } void PreCallRecordSetEvent(layer_data *dev_data, VkEvent event) { // Host setting event is visible to all queues immediately so update stageMask for any queue that's seen this event // TODO : For correctness this needs separate fix to verify that app doesn't make incorrect assumptions about the // ordering of this command in relation to vkCmd[Set|Reset]Events (see GH297) for (auto queue_data : dev_data->queueMap) { auto event_entry = queue_data.second.eventToStageMap.find(event); if (event_entry != queue_data.second.eventToStageMap.end()) { event_entry->second |= VK_PIPELINE_STAGE_HOST_BIT; } } } bool PreCallValidateQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo *pBindInfo, VkFence fence) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(queue), layer_data_map); auto pFence = GetFenceNode(device_data, fence); bool skip = ValidateFenceForSubmit(device_data, pFence); if (skip) { return true; } unordered_set<VkSemaphore> signaled_semaphores; unordered_set<VkSemaphore> unsignaled_semaphores; unordered_set<VkSemaphore> internal_semaphores; for (uint32_t bindIdx = 0; bindIdx < bindInfoCount; ++bindIdx) { const VkBindSparseInfo &bindInfo = pBindInfo[bindIdx]; std::vector<SEMAPHORE_WAIT> semaphore_waits; std::vector<VkSemaphore> semaphore_signals; for (uint32_t i = 0; i < bindInfo.waitSemaphoreCount; ++i) { VkSemaphore semaphore = bindInfo.pWaitSemaphores[i]; auto pSemaphore = GetSemaphoreNode(device_data, semaphore); if (pSemaphore && (pSemaphore->scope == kSyncScopeInternal || internal_semaphores.count(semaphore))) { if (unsignaled_semaphores.count(semaphore) || (!(signaled_semaphores.count(semaphore)) && !(pSemaphore->signaled))) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SEMAPHORE_EXT, HandleToUint64(semaphore), kVUID_Core_DrawState_QueueForwardProgress, "Queue 0x%" PRIx64 " is waiting on semaphore 0x%" PRIx64 " that has no way to be signaled.", HandleToUint64(queue), HandleToUint64(semaphore)); } else { signaled_semaphores.erase(semaphore); unsignaled_semaphores.insert(semaphore); } } if (pSemaphore && pSemaphore->scope == kSyncScopeExternalTemporary) { internal_semaphores.insert(semaphore); } } for (uint32_t i = 0; i < bindInfo.signalSemaphoreCount; ++i) { VkSemaphore semaphore = bindInfo.pSignalSemaphores[i]; auto pSemaphore = GetSemaphoreNode(device_data, semaphore); if (pSemaphore && pSemaphore->scope == kSyncScopeInternal) { if (signaled_semaphores.count(semaphore) || (!(unsignaled_semaphores.count(semaphore)) && pSemaphore->signaled)) { skip |= log_msg( device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SEMAPHORE_EXT, HandleToUint64(semaphore), kVUID_Core_DrawState_QueueForwardProgress, "Queue 0x%" PRIx64 " is signaling semaphore 0x%" PRIx64 " that was previously signaled by queue 0x%" PRIx64 " but has not since been waited on by any queue.", HandleToUint64(queue), HandleToUint64(semaphore), HandleToUint64(pSemaphore->signaler.first)); } else { unsignaled_semaphores.erase(semaphore); signaled_semaphores.insert(semaphore); } } } // Store sparse binding image_state and after binding is complete make sure that any requiring metadata have it bound std::unordered_set<IMAGE_STATE *> sparse_images; // If we're binding sparse image memory make sure reqs were queried and note if metadata is required and bound for (uint32_t i = 0; i < bindInfo.imageBindCount; ++i) { const auto &image_bind = bindInfo.pImageBinds[i]; auto image_state = GetImageState(device_data, image_bind.image); if (!image_state) continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here. sparse_images.insert(image_state); if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) { if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) { // For now just warning if sparse image binding occurs without calling to get reqs first return log_msg(device_data->report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, HandleToUint64(image_state->image), kVUID_Core_MemTrack_InvalidState, "vkQueueBindSparse(): Binding sparse memory to image 0x%" PRIx64 " without first calling vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.", HandleToUint64(image_state->image)); } } if (!image_state->memory_requirements_checked) { // For now just warning if sparse image binding occurs without calling to get reqs first return log_msg(device_data->report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, HandleToUint64(image_state->image), kVUID_Core_MemTrack_InvalidState, "vkQueueBindSparse(): Binding sparse memory to image 0x%" PRIx64 " without first calling vkGetImageMemoryRequirements() to retrieve requirements.", HandleToUint64(image_state->image)); } } for (uint32_t i = 0; i < bindInfo.imageOpaqueBindCount; ++i) { const auto &image_opaque_bind = bindInfo.pImageOpaqueBinds[i]; auto image_state = GetImageState(device_data, bindInfo.pImageOpaqueBinds[i].image); if (!image_state) continue; // Param/Object validation should report image_bind.image handles being invalid, so just skip here. sparse_images.insert(image_state); if (image_state->createInfo.flags & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) { if (!image_state->get_sparse_reqs_called || image_state->sparse_requirements.empty()) { // For now just warning if sparse image binding occurs without calling to get reqs first return log_msg(device_data->report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, HandleToUint64(image_state->image), kVUID_Core_MemTrack_InvalidState, "vkQueueBindSparse(): Binding opaque sparse memory to image 0x%" PRIx64 " without first calling vkGetImageSparseMemoryRequirements[2KHR]() to retrieve requirements.", HandleToUint64(image_state->image)); } } if (!image_state->memory_requirements_checked) { // For now just warning if sparse image binding occurs without calling to get reqs first return log_msg(device_data->report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, HandleToUint64(image_state->image), kVUID_Core_MemTrack_InvalidState, "vkQueueBindSparse(): Binding opaque sparse memory to image 0x%" PRIx64 " without first calling vkGetImageMemoryRequirements() to retrieve requirements.", HandleToUint64(image_state->image)); } for (uint32_t j = 0; j < image_opaque_bind.bindCount; ++j) { if (image_opaque_bind.pBinds[j].flags & VK_SPARSE_MEMORY_BIND_METADATA_BIT) { image_state->sparse_metadata_bound = true; } } } for (const auto &sparse_image_state : sparse_images) { if (sparse_image_state->sparse_metadata_required && !sparse_image_state->sparse_metadata_bound) { // Warn if sparse image binding metadata required for image with sparse binding, but metadata not bound return log_msg( device_data->report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, HandleToUint64(sparse_image_state->image), kVUID_Core_MemTrack_InvalidState, "vkQueueBindSparse(): Binding sparse memory to image 0x%" PRIx64 " which requires a metadata aspect but no binding with VK_SPARSE_MEMORY_BIND_METADATA_BIT set was made.", HandleToUint64(sparse_image_state->image)); } } } return skip; } void PostCallRecordQueueBindSparse(VkQueue queue, uint32_t bindInfoCount, const VkBindSparseInfo *pBindInfo, VkFence fence, VkResult result) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(queue), layer_data_map); if (result != VK_SUCCESS) return; uint64_t early_retire_seq = 0; auto pFence = GetFenceNode(device_data, fence); auto pQueue = GetQueueState(device_data, queue); if (pFence) { if (pFence->scope == kSyncScopeInternal) { SubmitFence(pQueue, pFence, std::max(1u, bindInfoCount)); if (!bindInfoCount) { // No work to do, just dropping a fence in the queue by itself. pQueue->submissions.emplace_back(std::vector<VkCommandBuffer>(), std::vector<SEMAPHORE_WAIT>(), std::vector<VkSemaphore>(), std::vector<VkSemaphore>(), fence); } } else { // Retire work up until this fence early, we will not see the wait that corresponds to this signal early_retire_seq = pQueue->seq + pQueue->submissions.size(); if (!device_data->external_sync_warning) { device_data->external_sync_warning = true; log_msg(device_data->report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_FENCE_EXT, HandleToUint64(fence), kVUID_Core_DrawState_QueueForwardProgress, "vkQueueBindSparse(): Signaling external fence 0x%" PRIx64 " on queue 0x%" PRIx64 " will disable validation of preceding command buffer lifecycle states and the in-use status of associated " "objects.", HandleToUint64(fence), HandleToUint64(queue)); } } } for (uint32_t bindIdx = 0; bindIdx < bindInfoCount; ++bindIdx) { const VkBindSparseInfo &bindInfo = pBindInfo[bindIdx]; // Track objects tied to memory for (uint32_t j = 0; j < bindInfo.bufferBindCount; j++) { for (uint32_t k = 0; k < bindInfo.pBufferBinds[j].bindCount; k++) { auto sparse_binding = bindInfo.pBufferBinds[j].pBinds[k]; SetSparseMemBinding(device_data, {sparse_binding.memory, sparse_binding.memoryOffset, sparse_binding.size}, HandleToUint64(bindInfo.pBufferBinds[j].buffer), kVulkanObjectTypeBuffer); } } for (uint32_t j = 0; j < bindInfo.imageOpaqueBindCount; j++) { for (uint32_t k = 0; k < bindInfo.pImageOpaqueBinds[j].bindCount; k++) { auto sparse_binding = bindInfo.pImageOpaqueBinds[j].pBinds[k]; SetSparseMemBinding(device_data, {sparse_binding.memory, sparse_binding.memoryOffset, sparse_binding.size}, HandleToUint64(bindInfo.pImageOpaqueBinds[j].image), kVulkanObjectTypeImage); } } for (uint32_t j = 0; j < bindInfo.imageBindCount; j++) { for (uint32_t k = 0; k < bindInfo.pImageBinds[j].bindCount; k++) { auto sparse_binding = bindInfo.pImageBinds[j].pBinds[k]; // TODO: This size is broken for non-opaque bindings, need to update to comprehend full sparse binding data VkDeviceSize size = sparse_binding.extent.depth * sparse_binding.extent.height * sparse_binding.extent.width * 4; SetSparseMemBinding(device_data, {sparse_binding.memory, sparse_binding.memoryOffset, size}, HandleToUint64(bindInfo.pImageBinds[j].image), kVulkanObjectTypeImage); } } std::vector<SEMAPHORE_WAIT> semaphore_waits; std::vector<VkSemaphore> semaphore_signals; std::vector<VkSemaphore> semaphore_externals; for (uint32_t i = 0; i < bindInfo.waitSemaphoreCount; ++i) { VkSemaphore semaphore = bindInfo.pWaitSemaphores[i]; auto pSemaphore = GetSemaphoreNode(device_data, semaphore); if (pSemaphore) { if (pSemaphore->scope == kSyncScopeInternal) { if (pSemaphore->signaler.first != VK_NULL_HANDLE) { semaphore_waits.push_back({semaphore, pSemaphore->signaler.first, pSemaphore->signaler.second}); pSemaphore->in_use.fetch_add(1); } pSemaphore->signaler.first = VK_NULL_HANDLE; pSemaphore->signaled = false; } else { semaphore_externals.push_back(semaphore); pSemaphore->in_use.fetch_add(1); if (pSemaphore->scope == kSyncScopeExternalTemporary) { pSemaphore->scope = kSyncScopeInternal; } } } } for (uint32_t i = 0; i < bindInfo.signalSemaphoreCount; ++i) { VkSemaphore semaphore = bindInfo.pSignalSemaphores[i]; auto pSemaphore = GetSemaphoreNode(device_data, semaphore); if (pSemaphore) { if (pSemaphore->scope == kSyncScopeInternal) { pSemaphore->signaler.first = queue; pSemaphore->signaler.second = pQueue->seq + pQueue->submissions.size() + 1; pSemaphore->signaled = true; pSemaphore->in_use.fetch_add(1); semaphore_signals.push_back(semaphore); } else { // Retire work up until this submit early, we will not see the wait that corresponds to this signal early_retire_seq = std::max(early_retire_seq, pQueue->seq + pQueue->submissions.size() + 1); if (!device_data->external_sync_warning) { device_data->external_sync_warning = true; log_msg(device_data->report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SEMAPHORE_EXT, HandleToUint64(semaphore), kVUID_Core_DrawState_QueueForwardProgress, "vkQueueBindSparse(): Signaling external semaphore 0x%" PRIx64 " on queue 0x%" PRIx64 " will disable validation of preceding command buffer lifecycle states and the in-use status of " "associated objects.", HandleToUint64(semaphore), HandleToUint64(queue)); } } } } pQueue->submissions.emplace_back(std::vector<VkCommandBuffer>(), semaphore_waits, semaphore_signals, semaphore_externals, bindIdx == bindInfoCount - 1 ? fence : VK_NULL_HANDLE); } if (early_retire_seq) { RetireWorkOnQueue(device_data, pQueue, early_retire_seq); } } void PostCallRecordCreateSemaphore(VkDevice device, const VkSemaphoreCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkSemaphore *pSemaphore, VkResult result) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); if (VK_SUCCESS != result) return; SEMAPHORE_NODE *sNode = &device_data->semaphoreMap[*pSemaphore]; sNode->signaler.first = VK_NULL_HANDLE; sNode->signaler.second = 0; sNode->signaled = false; sNode->scope = kSyncScopeInternal; } bool PreCallValidateImportSemaphore(layer_data *dev_data, VkSemaphore semaphore, const char *caller_name) { SEMAPHORE_NODE *sema_node = GetSemaphoreNode(dev_data, semaphore); VK_OBJECT obj_struct = {HandleToUint64(semaphore), kVulkanObjectTypeSemaphore}; bool skip = false; if (sema_node) { skip |= ValidateObjectNotInUse(dev_data, sema_node, obj_struct, caller_name, kVUIDUndefined); } return skip; } void PostCallRecordImportSemaphore(layer_data *dev_data, VkSemaphore semaphore, VkExternalSemaphoreHandleTypeFlagBitsKHR handle_type, VkSemaphoreImportFlagsKHR flags) { SEMAPHORE_NODE *sema_node = GetSemaphoreNode(dev_data, semaphore); if (sema_node && sema_node->scope != kSyncScopeExternalPermanent) { if ((handle_type == VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT_KHR || flags & VK_SEMAPHORE_IMPORT_TEMPORARY_BIT_KHR) && sema_node->scope == kSyncScopeInternal) { sema_node->scope = kSyncScopeExternalTemporary; } else { sema_node->scope = kSyncScopeExternalPermanent; } } } void PostCallRecordGetSemaphore(layer_data *dev_data, VkSemaphore semaphore, VkExternalSemaphoreHandleTypeFlagBitsKHR handle_type) { SEMAPHORE_NODE *sema_node = GetSemaphoreNode(dev_data, semaphore); if (sema_node && handle_type != VK_EXTERNAL_SEMAPHORE_HANDLE_TYPE_SYNC_FD_BIT_KHR) { // Cannot track semaphore state once it is exported, except for Sync FD handle types which have copy transference sema_node->scope = kSyncScopeExternalPermanent; } } bool PreCallValidateImportFence(layer_data *dev_data, VkFence fence, const char *caller_name) { FENCE_NODE *fence_node = GetFenceNode(dev_data, fence); bool skip = false; if (fence_node && fence_node->scope == kSyncScopeInternal && fence_node->state == FENCE_INFLIGHT) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_FENCE_EXT, HandleToUint64(fence), kVUIDUndefined, "Cannot call %s on fence 0x%" PRIx64 " that is currently in use.", caller_name, HandleToUint64(fence)); } return skip; } void PostCallRecordImportFence(layer_data *dev_data, VkFence fence, VkExternalFenceHandleTypeFlagBitsKHR handle_type, VkFenceImportFlagsKHR flags) { FENCE_NODE *fence_node = GetFenceNode(dev_data, fence); if (fence_node && fence_node->scope != kSyncScopeExternalPermanent) { if ((handle_type == VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT_KHR || flags & VK_FENCE_IMPORT_TEMPORARY_BIT_KHR) && fence_node->scope == kSyncScopeInternal) { fence_node->scope = kSyncScopeExternalTemporary; } else { fence_node->scope = kSyncScopeExternalPermanent; } } } void PostCallRecordGetFence(layer_data *dev_data, VkFence fence, VkExternalFenceHandleTypeFlagBitsKHR handle_type) { FENCE_NODE *fence_node = GetFenceNode(dev_data, fence); if (fence_node) { if (handle_type != VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT_KHR) { // Export with reference transference becomes external fence_node->scope = kSyncScopeExternalPermanent; } else if (fence_node->scope == kSyncScopeInternal) { // Export with copy transference has a side effect of resetting the fence fence_node->state = FENCE_UNSIGNALED; } } } void PostCallRecordCreateEvent(VkDevice device, const VkEventCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkEvent *pEvent, VkResult result) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); if (VK_SUCCESS != result) return; device_data->eventMap[*pEvent].needsSignaled = false; device_data->eventMap[*pEvent].write_in_use = 0; device_data->eventMap[*pEvent].stageMask = VkPipelineStageFlags(0); } bool ValidateCreateSwapchain(layer_data *device_data, const char *func_name, VkSwapchainCreateInfoKHR const *pCreateInfo, SURFACE_STATE *surface_state, SWAPCHAIN_NODE *old_swapchain_state) { auto most_recent_swapchain = surface_state->swapchain ? surface_state->swapchain : surface_state->old_swapchain; VkDevice device = device_data->device; // TODO: revisit this. some of these rules are being relaxed. // 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 (!device_data->instance_data->extensions.vk_khr_android_surface) { auto support_predicate = [device_data](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 == device_data->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 (log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(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 (most_recent_swapchain != old_swapchain_state || (surface_state->old_swapchain && surface_state->swapchain)) { if (log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device), kVUID_Core_DrawState_SwapchainAlreadyExists, "%s: surface has an existing swapchain other than oldSwapchain", func_name)) return true; } if (old_swapchain_state && old_swapchain_state->createInfo.surface != pCreateInfo->surface) { if (log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SWAPCHAIN_KHR_EXT, HandleToUint64(pCreateInfo->oldSwapchain), kVUID_Core_DrawState_SwapchainWrongSurface, "%s: pCreateInfo->oldSwapchain's surface is not pCreateInfo->surface", func_name)) return true; } if ((pCreateInfo->imageExtent.width == 0) || (pCreateInfo->imageExtent.height == 0)) { if (log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(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(device_data->instance_data, device_data->physical_device); if (physical_device_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState == UNCALLED) { if (log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT, HandleToUint64(device_data->physical_device), kVUID_Core_DrawState_SwapchainCreateBeforeQuery, "%s: surface capabilities not retrieved for this physical device", func_name)) return true; } else { // have valid capabilities auto &capabilities = physical_device_state->surfaceCapabilities; // Validate pCreateInfo->minImageCount against VkSurfaceCapabilitiesKHR::{min|max}ImageCount: if (pCreateInfo->minImageCount < capabilities.minImageCount) { if (log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device), "VUID-VkSwapchainCreateInfoKHR-minImageCount-01271", "%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 (log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(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 (log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(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 errorString = ""; 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)); errorString += str; for (int i = 0; i < 32; i++) { // Build up the rest of the message: if ((1 << i) & capabilities.supportedTransforms) { const char *newStr = string_VkSurfaceTransformFlagBitsKHR((VkSurfaceTransformFlagBitsKHR)(1 << i)); sprintf(str, " %s\n", newStr); errorString += str; } } // Log the message that we've built up: if (log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device), "VUID-VkSwapchainCreateInfoKHR-preTransform-01279", "%s.", errorString.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 errorString = ""; 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)); errorString += str; for (int i = 0; i < 32; i++) { // Build up the rest of the message: if ((1 << i) & capabilities.supportedCompositeAlpha) { const char *newStr = string_VkCompositeAlphaFlagBitsKHR((VkCompositeAlphaFlagBitsKHR)(1 << i)); sprintf(str, " %s\n", newStr); errorString += str; } } // Log the message that we've built up: if (log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device), "VUID-VkSwapchainCreateInfoKHR-compositeAlpha-01280", "%s.", errorString.c_str())) return true; } // Validate pCreateInfo->imageArrayLayers against VkSurfaceCapabilitiesKHR::maxImageArrayLayers: if (pCreateInfo->imageArrayLayers > capabilities.maxImageArrayLayers) { if (log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(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; } // Validate pCreateInfo->imageUsage against VkSurfaceCapabilitiesKHR::supportedUsageFlags: if (pCreateInfo->imageUsage != (pCreateInfo->imageUsage & capabilities.supportedUsageFlags)) { if (log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device), "VUID-VkSwapchainCreateInfoKHR-imageUsage-01276", "%s called with a non-supported pCreateInfo->imageUsage (i.e. 0x%08x). Supported flag bits are 0x%08x.", func_name, pCreateInfo->imageUsage, capabilities.supportedUsageFlags)) return true; } } // Validate pCreateInfo values with the results of vkGetPhysicalDeviceSurfaceFormatsKHR(): if (physical_device_state->vkGetPhysicalDeviceSurfaceFormatsKHRState != QUERY_DETAILS) { if (log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device), kVUID_Core_DrawState_SwapchainCreateBeforeQuery, "%s called before calling vkGetPhysicalDeviceSurfaceFormatsKHR().", func_name)) return true; } else { // Validate pCreateInfo->imageFormat against VkSurfaceFormatKHR::format: bool foundFormat = false; bool foundColorSpace = false; bool foundMatch = false; for (auto const &format : physical_device_state->surface_formats) { if (pCreateInfo->imageFormat == format.format) { // Validate pCreateInfo->imageColorSpace against VkSurfaceFormatKHR::colorSpace: foundFormat = true; if (pCreateInfo->imageColorSpace == format.colorSpace) { foundMatch = true; break; } } else { if (pCreateInfo->imageColorSpace == format.colorSpace) { foundColorSpace = true; } } } if (!foundMatch) { if (!foundFormat) { if (log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device), "VUID-VkSwapchainCreateInfoKHR-imageFormat-01273", "%s called with a non-supported pCreateInfo->imageFormat (i.e. %d).", func_name, pCreateInfo->imageFormat)) return true; } if (!foundColorSpace) { if (log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device), "VUID-VkSwapchainCreateInfoKHR-imageFormat-01273", "%s called with a non-supported pCreateInfo->imageColorSpace (i.e. %d).", func_name, pCreateInfo->imageColorSpace)) return true; } } } // Validate pCreateInfo values with the results of vkGetPhysicalDeviceSurfacePresentModesKHR(): if (physical_device_state->vkGetPhysicalDeviceSurfacePresentModesKHRState != QUERY_DETAILS) { // FIFO is required to always be supported if (pCreateInfo->presentMode != VK_PRESENT_MODE_FIFO_KHR) { if (log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device), kVUID_Core_DrawState_SwapchainCreateBeforeQuery, "%s called before calling vkGetPhysicalDeviceSurfacePresentModesKHR().", func_name)) return true; } } else { // Validate pCreateInfo->presentMode against vkGetPhysicalDeviceSurfacePresentModesKHR(): bool foundMatch = std::find(physical_device_state->present_modes.begin(), physical_device_state->present_modes.end(), pCreateInfo->presentMode) != physical_device_state->present_modes.end(); if (!foundMatch) { if (log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device), "VUID-VkSwapchainCreateInfoKHR-presentMode-01281", "%s called with a non-supported presentMode (i.e. %s).", func_name, string_VkPresentModeKHR(pCreateInfo->presentMode))) return true; } } // Validate state for shared presentable case if (VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR == pCreateInfo->presentMode || VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR == pCreateInfo->presentMode) { if (!device_data->extensions.vk_khr_shared_presentable_image) { if (log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(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(pCreateInfo->presentMode))) return true; } else if (pCreateInfo->minImageCount != 1) { if (log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(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(pCreateInfo->presentMode), pCreateInfo->minImageCount)) return true; } } if (pCreateInfo->flags & VK_SWAPCHAIN_CREATE_MUTABLE_FORMAT_BIT_KHR) { if (!device_data->extensions.vk_khr_swapchain_mutable_format) { if (log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device), kVUID_Core_DrawState_ExtensionNotEnabled, "%s: pCreateInfo->flags contains VK_SWAPCHAIN_CREATE_MUTABLE_FORMAT_BIT_KHR which requires the " "VK_KHR_swapchain_mutable_format extension, which has not been enabled.", func_name)) return true; } else { const auto *image_format_list = lvl_find_in_chain<VkImageFormatListCreateInfoKHR>(pCreateInfo->pNext); if (image_format_list == nullptr) { if (log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device), "VUID-VkSwapchainCreateInfoKHR-flags-03168", "%s: pCreateInfo->flags contains VK_SWAPCHAIN_CREATE_MUTABLE_FORMAT_BIT_KHR but the pNext chain of " "pCreateInfo does not contain an instance of VkImageFormatListCreateInfoKHR.", func_name)) return true; } else if (image_format_list->viewFormatCount == 0) { if (log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device), "VUID-VkSwapchainCreateInfoKHR-flags-03168", "%s: pCreateInfo->flags contains VK_SWAPCHAIN_CREATE_MUTABLE_FORMAT_BIT_KHR but the viewFormatCount " "member of VkImageFormatListCreateInfoKHR in the pNext chain is zero.", func_name)) return true; } else { bool found_base_format = false; for (uint32_t i = 0; i < image_format_list->viewFormatCount; ++i) { if (image_format_list->pViewFormats[i] == pCreateInfo->imageFormat) { found_base_format = true; break; } } if (!found_base_format) { if (log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device), "VUID-VkSwapchainCreateInfoKHR-flags-03168", "%s: pCreateInfo->flags contains VK_SWAPCHAIN_CREATE_MUTABLE_FORMAT_BIT_KHR but none of the " "elements of the pViewFormats member of VkImageFormatListCreateInfoKHR match " "pCreateInfo->imageFormat.", func_name)) return true; } } } } return false; } bool PreCallValidateCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkSwapchainKHR *pSwapchain) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); auto surface_state = GetSurfaceState(device_data->instance_data, pCreateInfo->surface); auto old_swapchain_state = GetSwapchainNode(device_data, pCreateInfo->oldSwapchain); return ValidateCreateSwapchain(device_data, "vkCreateSwapchainKHR()", pCreateInfo, surface_state, old_swapchain_state); } static void RecordCreateSwapchainState(layer_data *device_data, VkResult result, const VkSwapchainCreateInfoKHR *pCreateInfo, VkSwapchainKHR *pSwapchain, SURFACE_STATE *surface_state, SWAPCHAIN_NODE *old_swapchain_state) { if (VK_SUCCESS == result) { auto swapchain_state = unique_ptr<SWAPCHAIN_NODE>(new SWAPCHAIN_NODE(pCreateInfo, *pSwapchain)); if (VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR == pCreateInfo->presentMode || VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR == pCreateInfo->presentMode) { swapchain_state->shared_presentable = true; } surface_state->swapchain = swapchain_state.get(); device_data->swapchainMap[*pSwapchain] = std::move(swapchain_state); } else { surface_state->swapchain = nullptr; } // Spec requires that even if CreateSwapchainKHR fails, oldSwapchain behaves as replaced. if (old_swapchain_state) { old_swapchain_state->replaced = true; } surface_state->old_swapchain = old_swapchain_state; return; } void PostCallRecordCreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkSwapchainKHR *pSwapchain, VkResult result) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); auto surface_state = GetSurfaceState(device_data->instance_data, pCreateInfo->surface); auto old_swapchain_state = GetSwapchainNode(device_data, pCreateInfo->oldSwapchain); RecordCreateSwapchainState(device_data, result, pCreateInfo, pSwapchain, surface_state, old_swapchain_state); } void PreCallRecordDestroySwapchainKHR(VkDevice device, VkSwapchainKHR swapchain, const VkAllocationCallbacks *pAllocator) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); if (!swapchain) return; auto swapchain_data = GetSwapchainNode(device_data, swapchain); if (swapchain_data) { if (swapchain_data->images.size() > 0) { for (auto swapchain_image : swapchain_data->images) { auto image_sub = device_data->imageSubresourceMap.find(swapchain_image); if (image_sub != device_data->imageSubresourceMap.end()) { for (auto imgsubpair : image_sub->second) { auto image_item = device_data->imageLayoutMap.find(imgsubpair); if (image_item != device_data->imageLayoutMap.end()) { device_data->imageLayoutMap.erase(image_item); } } device_data->imageSubresourceMap.erase(image_sub); } ClearMemoryObjectBindings(device_data, HandleToUint64(swapchain_image), kVulkanObjectTypeSwapchainKHR); EraseQFOImageRelaseBarriers(device_data, swapchain_image); device_data->imageMap.erase(swapchain_image); } } auto surface_state = GetSurfaceState(device_data->instance_data, swapchain_data->createInfo.surface); if (surface_state) { if (surface_state->swapchain == swapchain_data) surface_state->swapchain = nullptr; if (surface_state->old_swapchain == swapchain_data) surface_state->old_swapchain = nullptr; } device_data->swapchainMap.erase(swapchain); } } bool PreCallValidateGetSwapchainImagesKHR(layer_data *device_data, SWAPCHAIN_NODE *swapchain_state, VkDevice device, uint32_t *pSwapchainImageCount, VkImage *pSwapchainImages) { bool skip = false; if (swapchain_state && pSwapchainImages) { lock_guard_t lock(global_lock); // Compare the preliminary value of *pSwapchainImageCount with the value this time: if (swapchain_state->vkGetSwapchainImagesKHRState == UNCALLED) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device), kVUID_Core_Swapchain_PriorCount, "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImageCount; but no prior positive value has " "been seen for pSwapchainImages."); } else if (*pSwapchainImageCount > swapchain_state->get_swapchain_image_count) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device), kVUID_Core_Swapchain_InvalidCount, "vkGetSwapchainImagesKHR() called with non-NULL pSwapchainImageCount, and with pSwapchainImages set to a " "value (%d) that is greater than the value (%d) that was returned when pSwapchainImageCount was NULL.", *pSwapchainImageCount, swapchain_state->get_swapchain_image_count); } } return skip; } void PostCallRecordGetSwapchainImagesKHR(layer_data *device_data, SWAPCHAIN_NODE *swapchain_state, VkDevice device, uint32_t *pSwapchainImageCount, VkImage *pSwapchainImages) { lock_guard_t lock(global_lock); if (*pSwapchainImageCount > swapchain_state->images.size()) swapchain_state->images.resize(*pSwapchainImageCount); if (pSwapchainImages) { if (swapchain_state->vkGetSwapchainImagesKHRState < QUERY_DETAILS) { swapchain_state->vkGetSwapchainImagesKHRState = QUERY_DETAILS; } for (uint32_t i = 0; i < *pSwapchainImageCount; ++i) { if (swapchain_state->images[i] != VK_NULL_HANDLE) continue; // Already retrieved this. IMAGE_LAYOUT_NODE image_layout_node; image_layout_node.layout = VK_IMAGE_LAYOUT_UNDEFINED; image_layout_node.format = swapchain_state->createInfo.imageFormat; // Add imageMap entries for each swapchain image VkImageCreateInfo image_ci = {}; image_ci.flags = 0; image_ci.imageType = VK_IMAGE_TYPE_2D; image_ci.format = swapchain_state->createInfo.imageFormat; image_ci.extent.width = swapchain_state->createInfo.imageExtent.width; image_ci.extent.height = swapchain_state->createInfo.imageExtent.height; image_ci.extent.depth = 1; image_ci.mipLevels = 1; image_ci.arrayLayers = swapchain_state->createInfo.imageArrayLayers; image_ci.samples = VK_SAMPLE_COUNT_1_BIT; image_ci.tiling = VK_IMAGE_TILING_OPTIMAL; image_ci.usage = swapchain_state->createInfo.imageUsage; image_ci.sharingMode = swapchain_state->createInfo.imageSharingMode; device_data->imageMap[pSwapchainImages[i]] = unique_ptr<IMAGE_STATE>(new IMAGE_STATE(pSwapchainImages[i], &image_ci)); auto &image_state = device_data->imageMap[pSwapchainImages[i]]; image_state->valid = false; image_state->binding.mem = MEMTRACKER_SWAP_CHAIN_IMAGE_KEY; swapchain_state->images[i] = pSwapchainImages[i]; ImageSubresourcePair subpair = {pSwapchainImages[i], false, VkImageSubresource()}; device_data->imageSubresourceMap[pSwapchainImages[i]].push_back(subpair); device_data->imageLayoutMap[subpair] = image_layout_node; } } if (*pSwapchainImageCount) { if (swapchain_state->vkGetSwapchainImagesKHRState < QUERY_COUNT) { swapchain_state->vkGetSwapchainImagesKHRState = QUERY_COUNT; } swapchain_state->get_swapchain_image_count = *pSwapchainImageCount; } } bool PreCallValidateQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR *pPresentInfo) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(queue), layer_data_map); bool skip = false; auto queue_state = GetQueueState(device_data, queue); for (uint32_t i = 0; i < pPresentInfo->waitSemaphoreCount; ++i) { auto pSemaphore = GetSemaphoreNode(device_data, pPresentInfo->pWaitSemaphores[i]); if (pSemaphore && !pSemaphore->signaled) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, 0, kVUID_Core_DrawState_QueueForwardProgress, "Queue 0x%" PRIx64 " is waiting on semaphore 0x%" PRIx64 " that has no way to be signaled.", HandleToUint64(queue), HandleToUint64(pPresentInfo->pWaitSemaphores[i])); } } for (uint32_t i = 0; i < pPresentInfo->swapchainCount; ++i) { auto swapchain_data = GetSwapchainNode(device_data, pPresentInfo->pSwapchains[i]); if (swapchain_data) { if (pPresentInfo->pImageIndices[i] >= swapchain_data->images.size()) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SWAPCHAIN_KHR_EXT, HandleToUint64(pPresentInfo->pSwapchains[i]), kVUID_Core_DrawState_SwapchainInvalidImage, "vkQueuePresentKHR: Swapchain image index too large (%u). There are only %u images in this swapchain.", pPresentInfo->pImageIndices[i], (uint32_t)swapchain_data->images.size()); } else { auto image = swapchain_data->images[pPresentInfo->pImageIndices[i]]; auto image_state = GetImageState(device_data, image); if (image_state->shared_presentable) { image_state->layout_locked = true; } if (!image_state->acquired) { skip |= log_msg( device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SWAPCHAIN_KHR_EXT, HandleToUint64(pPresentInfo->pSwapchains[i]), kVUID_Core_DrawState_SwapchainImageNotAcquired, "vkQueuePresentKHR: Swapchain image index %u has not been acquired.", pPresentInfo->pImageIndices[i]); } vector<VkImageLayout> layouts; if (FindLayouts(device_data, image, layouts)) { for (auto layout : layouts) { if ((layout != VK_IMAGE_LAYOUT_PRESENT_SRC_KHR) && (!device_data->extensions.vk_khr_shared_presentable_image || (layout != VK_IMAGE_LAYOUT_SHARED_PRESENT_KHR))) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_QUEUE_EXT, HandleToUint64(queue), "VUID-VkPresentInfoKHR-pImageIndices-01296", "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.", 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 (!device_data->instance_data->extensions.vk_khr_android_surface) { auto surface_state = GetSurfaceState(device_data->instance_data, swapchain_data->createInfo.surface); auto support_it = surface_state->gpu_queue_support.find({device_data->physical_device, queue_state->queueFamilyIndex}); if (support_it == surface_state->gpu_queue_support.end()) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SWAPCHAIN_KHR_EXT, HandleToUint64(pPresentInfo->pSwapchains[i]), kVUID_Core_DrawState_SwapchainUnsupportedQueue, "vkQueuePresentKHR: Presenting image without calling vkGetPhysicalDeviceSurfaceSupportKHR"); } else if (!support_it->second) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SWAPCHAIN_KHR_EXT, HandleToUint64(pPresentInfo->pSwapchains[i]), "VUID-vkQueuePresentKHR-pSwapchains-01292", "vkQueuePresentKHR: Presenting image on queue that cannot present to this surface."); } } } } if (pPresentInfo && pPresentInfo->pNext) { // Verify ext struct const auto *present_regions = lvl_find_in_chain<VkPresentRegionsKHR>(pPresentInfo->pNext); if (present_regions) { for (uint32_t i = 0; i < present_regions->swapchainCount; ++i) { auto swapchain_data = GetSwapchainNode(device_data, 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]; if ((rect.offset.x + rect.extent.width) > swapchain_data->createInfo.imageExtent.width) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SWAPCHAIN_KHR_EXT, HandleToUint64(pPresentInfo->pSwapchains[i]), "VUID-VkRectLayerKHR-offset-01261", "vkQueuePresentKHR(): For VkPresentRegionKHR down pNext chain, " "pRegion[%i].pRectangles[%i], the sum of offset.x (%i) and extent.width (%i) is greater " "than the corresponding swapchain's imageExtent.width (%i).", i, j, rect.offset.x, rect.extent.width, swapchain_data->createInfo.imageExtent.width); } if ((rect.offset.y + rect.extent.height) > swapchain_data->createInfo.imageExtent.height) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SWAPCHAIN_KHR_EXT, HandleToUint64(pPresentInfo->pSwapchains[i]), "VUID-VkRectLayerKHR-offset-01261", "vkQueuePresentKHR(): For VkPresentRegionKHR down pNext chain, " "pRegion[%i].pRectangles[%i], the sum of offset.y (%i) and extent.height (%i) is greater " "than the corresponding swapchain's imageExtent.height (%i).", i, j, rect.offset.y, rect.extent.height, swapchain_data->createInfo.imageExtent.height); } if (rect.layer > swapchain_data->createInfo.imageArrayLayers) { skip |= log_msg( device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SWAPCHAIN_KHR_EXT, HandleToUint64(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 = lvl_find_in_chain<VkPresentTimesInfoGOOGLE>(pPresentInfo->pNext); if (present_times_info) { if (pPresentInfo->swapchainCount != present_times_info->swapchainCount) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SWAPCHAIN_KHR_EXT, HandleToUint64(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; } void PostCallRecordQueuePresentKHR(VkQueue queue, const VkPresentInfoKHR *pPresentInfo, VkResult result) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(queue), layer_data_map); // Semaphore waits occur before error generation, if the call reached the ICD. (Confirm?) for (uint32_t i = 0; i < pPresentInfo->waitSemaphoreCount; ++i) { auto pSemaphore = GetSemaphoreNode(device_data, pPresentInfo->pWaitSemaphores[i]); if (pSemaphore) { pSemaphore->signaler.first = VK_NULL_HANDLE; pSemaphore->signaled = false; } } for (uint32_t i = 0; i < pPresentInfo->swapchainCount; ++i) { // Note: this is imperfect, in that we can get confused about what did or didn't succeed-- but if the app does that, it's // confused itself just as much. auto local_result = pPresentInfo->pResults ? pPresentInfo->pResults[i] : result; if (local_result != VK_SUCCESS && local_result != VK_SUBOPTIMAL_KHR) continue; // this present didn't actually happen. // Mark the image as having been released to the WSI auto swapchain_data = GetSwapchainNode(device_data, pPresentInfo->pSwapchains[i]); if (swapchain_data && (swapchain_data->images.size() > pPresentInfo->pImageIndices[i])) { auto image = swapchain_data->images[pPresentInfo->pImageIndices[i]]; auto image_state = GetImageState(device_data, image); if (image_state) { image_state->acquired = false; } } } // Note: even though presentation is directed to a queue, there is no direct ordering between QP and subsequent work, so QP (and // its semaphore waits) /never/ participate in any completion proof. } bool PreCallValidateCreateSharedSwapchainsKHR(VkDevice device, uint32_t swapchainCount, const VkSwapchainCreateInfoKHR *pCreateInfos, const VkAllocationCallbacks *pAllocator, VkSwapchainKHR *pSwapchains) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); bool skip = false; if (pCreateInfos) { for (uint32_t i = 0; i < swapchainCount; i++) { auto surface_state = GetSurfaceState(device_data->instance_data, pCreateInfos[i].surface); auto old_swapchain_state = GetSwapchainNode(device_data, pCreateInfos[i].oldSwapchain); std::stringstream func_name; func_name << "vkCreateSharedSwapchainsKHR[" << swapchainCount << "]()"; skip |= ValidateCreateSwapchain(device_data, func_name.str().c_str(), &pCreateInfos[i], surface_state, old_swapchain_state); } } return skip; } void PostCallRecordCreateSharedSwapchainsKHR(VkDevice device, uint32_t swapchainCount, const VkSwapchainCreateInfoKHR *pCreateInfos, const VkAllocationCallbacks *pAllocator, VkSwapchainKHR *pSwapchains, VkResult result) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); if (pCreateInfos) { for (uint32_t i = 0; i < swapchainCount; i++) { auto surface_state = GetSurfaceState(device_data->instance_data, pCreateInfos[i].surface); auto old_swapchain_state = GetSwapchainNode(device_data, pCreateInfos[i].oldSwapchain); RecordCreateSwapchainState(device_data, result, &pCreateInfos[i], &pSwapchains[i], surface_state, old_swapchain_state); } } } bool PreCallValidateCommonAcquireNextImage(layer_data *dev_data, VkDevice device, VkSwapchainKHR swapchain, uint64_t timeout, VkSemaphore semaphore, VkFence fence, uint32_t *pImageIndex, const char *func_name) { bool skip = false; if (fence == VK_NULL_HANDLE && semaphore == VK_NULL_HANDLE) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DEVICE_EXT, HandleToUint64(device), "VUID-vkAcquireNextImageKHR-semaphore-01780", "%s: Semaphore and fence cannot both be VK_NULL_HANDLE. There would be no way to " "determine the completion of this operation.", func_name); } auto pSemaphore = GetSemaphoreNode(dev_data, semaphore); if (pSemaphore && pSemaphore->scope == kSyncScopeInternal && pSemaphore->signaled) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SEMAPHORE_EXT, HandleToUint64(semaphore), "VUID-vkAcquireNextImageKHR-semaphore-01286", "%s: Semaphore must not be currently signaled or in a wait state.", func_name); } auto pFence = GetFenceNode(dev_data, fence); if (pFence) { skip |= ValidateFenceForSubmit(dev_data, pFence); } auto swapchain_data = GetSwapchainNode(dev_data, swapchain); if (swapchain_data && swapchain_data->replaced) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SWAPCHAIN_KHR_EXT, HandleToUint64(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(dev_data->instance_data, dev_data->physical_device); if (physical_device_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState != UNCALLED) { uint64_t acquired_images = std::count_if(swapchain_data->images.begin(), swapchain_data->images.end(), [=](VkImage image) { return GetImageState(dev_data, image)->acquired; }); if (acquired_images > swapchain_data->images.size() - physical_device_state->surfaceCapabilities.minImageCount) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SWAPCHAIN_KHR_EXT, HandleToUint64(swapchain), kVUID_Core_DrawState_SwapchainTooManyImages, "%s: Application has already acquired the maximum number of images (0x%" PRIxLEAST64 ")", func_name, acquired_images); } } if (swapchain_data && swapchain_data->images.size() == 0) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SWAPCHAIN_KHR_EXT, HandleToUint64(swapchain), kVUID_Core_DrawState_SwapchainImagesNotFound, "%s: No images found to acquire from. Application probably did not call " "vkGetSwapchainImagesKHR after swapchain creation.", func_name); } return skip; } void PostCallRecordCommonAcquireNextImage(layer_data *dev_data, VkDevice device, VkSwapchainKHR swapchain, uint64_t timeout, VkSemaphore semaphore, VkFence fence, uint32_t *pImageIndex) { auto pFence = GetFenceNode(dev_data, fence); if (pFence && pFence->scope == kSyncScopeInternal) { // Treat as inflight since it is valid to wait on this fence, even in cases where it is technically a temporary // import pFence->state = FENCE_INFLIGHT; pFence->signaler.first = VK_NULL_HANDLE; // ANI isn't on a queue, so this can't participate in a completion proof. } auto pSemaphore = GetSemaphoreNode(dev_data, semaphore); if (pSemaphore && pSemaphore->scope == kSyncScopeInternal) { // Treat as signaled since it is valid to wait on this semaphore, even in cases where it is technically a // temporary import pSemaphore->signaled = true; pSemaphore->signaler.first = VK_NULL_HANDLE; } // Mark the image as acquired. auto swapchain_data = GetSwapchainNode(dev_data, swapchain); if (swapchain_data && (swapchain_data->images.size() > *pImageIndex)) { auto image = swapchain_data->images[*pImageIndex]; auto image_state = GetImageState(dev_data, image); if (image_state) { image_state->acquired = true; image_state->shared_presentable = swapchain_data->shared_presentable; } } } bool PreCallValidateEnumeratePhysicalDevices(instance_layer_data *instance_data, uint32_t *pPhysicalDeviceCount) { bool skip = false; if (UNCALLED == instance_data->vkEnumeratePhysicalDevicesState) { // Flag warning here. You can call this without having queried the count, but it may not be // robust on platforms with multiple physical devices. skip |= log_msg(instance_data->report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_INSTANCE_EXT, 0, kVUID_Core_DevLimit_MissingQueryCount, "Call sequence has vkEnumeratePhysicalDevices() w/ non-NULL pPhysicalDevices. You should first call " "vkEnumeratePhysicalDevices() w/ NULL pPhysicalDevices to query pPhysicalDeviceCount."); } // TODO : Could also flag a warning if re-calling this function in QUERY_DETAILS state else if (instance_data->physical_devices_count != *pPhysicalDeviceCount) { // Having actual count match count from app is not a requirement, so this can be a warning skip |= log_msg(instance_data->report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT, 0, kVUID_Core_DevLimit_CountMismatch, "Call to vkEnumeratePhysicalDevices() w/ pPhysicalDeviceCount value %u, but actual count supported by " "this instance is %u.", *pPhysicalDeviceCount, instance_data->physical_devices_count); } return skip; } void PreCallRecordEnumeratePhysicalDevices(instance_layer_data *instance_data) { instance_data->vkEnumeratePhysicalDevicesState = QUERY_COUNT; } void PostCallRecordEnumeratePhysicalDevices(instance_layer_data *instance_data, const VkResult &result, uint32_t *pPhysicalDeviceCount, VkPhysicalDevice *pPhysicalDevices) { if (NULL == pPhysicalDevices) { instance_data->physical_devices_count = *pPhysicalDeviceCount; } else if (result == VK_SUCCESS || result == VK_INCOMPLETE) { // Save physical devices for (uint32_t i = 0; i < *pPhysicalDeviceCount; i++) { auto &phys_device_state = instance_data->physical_device_map[pPhysicalDevices[i]]; phys_device_state.phys_device = pPhysicalDevices[i]; // Init actual features for each physical device instance_data->dispatch_table.GetPhysicalDeviceFeatures(pPhysicalDevices[i], &phys_device_state.features2.features); } } } // Common function to handle validation for GetPhysicalDeviceQueueFamilyProperties & 2KHR version static bool ValidateCommonGetPhysicalDeviceQueueFamilyProperties(instance_layer_data *instance_data, PHYSICAL_DEVICE_STATE *pd_state, uint32_t requested_queue_family_property_count, bool qfp_null, const char *caller_name) { bool skip = false; if (!qfp_null) { // Verify that for each physical device, this command is called first with NULL pQueueFamilyProperties in order to get count if (UNCALLED == pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState) { skip |= log_msg( instance_data->report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT, HandleToUint64(pd_state->phys_device), kVUID_Core_DevLimit_MissingQueryCount, "%s is called with non-NULL pQueueFamilyProperties before obtaining pQueueFamilyPropertyCount. It is recommended " "to first call %s with NULL pQueueFamilyProperties in order to obtain the maximal pQueueFamilyPropertyCount.", caller_name, caller_name); // Then verify that pCount that is passed in on second call matches what was returned } else if (pd_state->queue_family_count != requested_queue_family_property_count) { skip |= log_msg( instance_data->report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT, HandleToUint64(pd_state->phys_device), kVUID_Core_DevLimit_CountMismatch, "%s is called with non-NULL pQueueFamilyProperties and pQueueFamilyPropertyCount value %" PRIu32 ", but the largest previously returned pQueueFamilyPropertyCount for this physicalDevice is %" PRIu32 ". It is recommended to instead receive all the properties by calling %s with pQueueFamilyPropertyCount that was " "previously obtained by calling %s with NULL pQueueFamilyProperties.", caller_name, requested_queue_family_property_count, pd_state->queue_family_count, caller_name, caller_name); } pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState = QUERY_DETAILS; } return skip; } bool PreCallValidateGetPhysicalDeviceQueueFamilyProperties(instance_layer_data *instance_data, PHYSICAL_DEVICE_STATE *pd_state, uint32_t *pQueueFamilyPropertyCount, VkQueueFamilyProperties *pQueueFamilyProperties) { return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(instance_data, pd_state, *pQueueFamilyPropertyCount, (nullptr == pQueueFamilyProperties), "vkGetPhysicalDeviceQueueFamilyProperties()"); } bool PreCallValidateGetPhysicalDeviceQueueFamilyProperties2(instance_layer_data *instance_data, PHYSICAL_DEVICE_STATE *pd_state, uint32_t *pQueueFamilyPropertyCount, VkQueueFamilyProperties2KHR *pQueueFamilyProperties) { return ValidateCommonGetPhysicalDeviceQueueFamilyProperties(instance_data, pd_state, *pQueueFamilyPropertyCount, (nullptr == pQueueFamilyProperties), "vkGetPhysicalDeviceQueueFamilyProperties2[KHR]()"); } // Common function to update state for GetPhysicalDeviceQueueFamilyProperties & 2KHR version static void StateUpdateCommonGetPhysicalDeviceQueueFamilyProperties(PHYSICAL_DEVICE_STATE *pd_state, uint32_t count, VkQueueFamilyProperties2KHR *pQueueFamilyProperties) { if (!pQueueFamilyProperties) { if (UNCALLED == pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState) pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState = QUERY_COUNT; pd_state->queue_family_count = count; } else { // Save queue family properties pd_state->vkGetPhysicalDeviceQueueFamilyPropertiesState = QUERY_DETAILS; pd_state->queue_family_count = std::max(pd_state->queue_family_count, count); pd_state->queue_family_properties.resize(std::max(static_cast<uint32_t>(pd_state->queue_family_properties.size()), count)); for (uint32_t i = 0; i < count; ++i) { pd_state->queue_family_properties[i] = pQueueFamilyProperties[i].queueFamilyProperties; } } } void PostCallRecordGetPhysicalDeviceQueueFamilyProperties(PHYSICAL_DEVICE_STATE *pd_state, uint32_t count, VkQueueFamilyProperties *pQueueFamilyProperties) { VkQueueFamilyProperties2KHR *pqfp = nullptr; std::vector<VkQueueFamilyProperties2KHR> qfp; qfp.resize(count); if (pQueueFamilyProperties) { for (uint32_t i = 0; i < count; ++i) { qfp[i].sType = VK_STRUCTURE_TYPE_QUEUE_FAMILY_PROPERTIES_2_KHR; qfp[i].pNext = nullptr; qfp[i].queueFamilyProperties = pQueueFamilyProperties[i]; } pqfp = qfp.data(); } StateUpdateCommonGetPhysicalDeviceQueueFamilyProperties(pd_state, count, pqfp); } void PostCallRecordGetPhysicalDeviceQueueFamilyProperties2(PHYSICAL_DEVICE_STATE *pd_state, uint32_t count, VkQueueFamilyProperties2KHR *pQueueFamilyProperties) { StateUpdateCommonGetPhysicalDeviceQueueFamilyProperties(pd_state, count, pQueueFamilyProperties); } bool PreCallValidateDestroySurfaceKHR(VkInstance instance, VkSurfaceKHR surface, const VkAllocationCallbacks *pAllocator) { instance_layer_data *instance_data = GetLayerDataPtr(get_dispatch_key(instance), instance_layer_data_map); auto surface_state = GetSurfaceState(instance_data, surface); bool skip = false; if ((surface_state) && (surface_state->swapchain)) { skip |= log_msg(instance_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_INSTANCE_EXT, HandleToUint64(instance), "VUID-vkDestroySurfaceKHR-surface-01266", "vkDestroySurfaceKHR() called before its associated VkSwapchainKHR was destroyed."); } return skip; } void PreCallRecordValidateDestroySurfaceKHR(VkInstance instance, VkSurfaceKHR surface, const VkAllocationCallbacks *pAllocator) { instance_layer_data *instance_data = GetLayerDataPtr(get_dispatch_key(instance), instance_layer_data_map); instance_data->surface_map.erase(surface); } static void RecordVulkanSurface(instance_layer_data *instance_data, VkSurfaceKHR *pSurface) { instance_data->surface_map[*pSurface] = SURFACE_STATE(*pSurface); } void PostCallRecordCreateDisplayPlaneSurfaceKHR(VkInstance instance, const VkDisplaySurfaceCreateInfoKHR *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkSurfaceKHR *pSurface, VkResult result) { instance_layer_data *instance_data = GetLayerDataPtr(get_dispatch_key(instance), instance_layer_data_map); if (VK_SUCCESS != result) return; RecordVulkanSurface(instance_data, pSurface); } #ifdef VK_USE_PLATFORM_ANDROID_KHR void PostCallRecordCreateAndroidSurfaceKHR(VkInstance instance, const VkAndroidSurfaceCreateInfoKHR *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkSurfaceKHR *pSurface, VkResult result) { instance_layer_data *instance_data = GetLayerDataPtr(get_dispatch_key(instance), instance_layer_data_map); if (VK_SUCCESS != result) return; RecordVulkanSurface(instance_data, pSurface); } #endif // VK_USE_PLATFORM_ANDROID_KHR #ifdef VK_USE_PLATFORM_IOS_MVK void PostCallRecordCreateIOSSurfaceMVK(VkInstance instance, const VkIOSSurfaceCreateInfoMVK *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkSurfaceKHR *pSurface, VkResult result) { instance_layer_data *instance_data = GetLayerDataPtr(get_dispatch_key(instance), instance_layer_data_map); if (VK_SUCCESS != result) return; RecordVulkanSurface(instance_data, pSurface); } #endif // VK_USE_PLATFORM_IOS_MVK #ifdef VK_USE_PLATFORM_MACOS_MVK void PostCallRecordCreateMacOSSurfaceMVK(VkInstance instance, const VkMacOSSurfaceCreateInfoMVK *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkSurfaceKHR *pSurface, VkResult result) { instance_layer_data *instance_data = GetLayerDataPtr(get_dispatch_key(instance), instance_layer_data_map); if (VK_SUCCESS != result) return; RecordVulkanSurface(instance_data, pSurface); } #endif // VK_USE_PLATFORM_MACOS_MVK #ifdef VK_USE_PLATFORM_WAYLAND_KHR void PostCallRecordCreateWaylandSurfaceKHR(VkInstance instance, const VkWaylandSurfaceCreateInfoKHR *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkSurfaceKHR *pSurface, VkResult result) { instance_layer_data *instance_data = GetLayerDataPtr(get_dispatch_key(instance), instance_layer_data_map); if (VK_SUCCESS != result) return; RecordVulkanSurface(instance_data, pSurface); } bool PreCallValidateGetPhysicalDeviceWaylandPresentationSupportKHR(instance_layer_data *instance_data, VkPhysicalDevice physicalDevice, uint32_t queueFamilyIndex) { const auto pd_state = GetPhysicalDeviceState(instance_data, physicalDevice); return ValidatePhysicalDeviceQueueFamily(instance_data, pd_state, queueFamilyIndex, "VUID-vkGetPhysicalDeviceWaylandPresentationSupportKHR-queueFamilyIndex-01306", "vkGetPhysicalDeviceWaylandPresentationSupportKHR", "queueFamilyIndex"); } #endif // VK_USE_PLATFORM_WAYLAND_KHR #ifdef VK_USE_PLATFORM_WIN32_KHR void PostCallRecordCreateWin32SurfaceKHR(VkInstance instance, const VkWin32SurfaceCreateInfoKHR *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkSurfaceKHR *pSurface, VkResult result) { instance_layer_data *instance_data = GetLayerDataPtr(get_dispatch_key(instance), instance_layer_data_map); if (VK_SUCCESS != result) return; RecordVulkanSurface(instance_data, pSurface); } bool PreCallValidateGetPhysicalDeviceWin32PresentationSupportKHR(instance_layer_data *instance_data, VkPhysicalDevice physicalDevice, uint32_t queueFamilyIndex) { const auto pd_state = GetPhysicalDeviceState(instance_data, physicalDevice); return ValidatePhysicalDeviceQueueFamily(instance_data, pd_state, queueFamilyIndex, "VUID-vkGetPhysicalDeviceWin32PresentationSupportKHR-queueFamilyIndex-01309", "vkGetPhysicalDeviceWin32PresentationSupportKHR", "queueFamilyIndex"); } #endif // VK_USE_PLATFORM_WIN32_KHR #ifdef VK_USE_PLATFORM_XCB_KHR void PostCallRecordCreateXcbSurfaceKHR(VkInstance instance, const VkXcbSurfaceCreateInfoKHR *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkSurfaceKHR *pSurface, VkResult result) { instance_layer_data *instance_data = GetLayerDataPtr(get_dispatch_key(instance), instance_layer_data_map); if (VK_SUCCESS != result) return; RecordVulkanSurface(instance_data, pSurface); } bool PreCallValidateGetPhysicalDeviceXcbPresentationSupportKHR(instance_layer_data *instance_data, VkPhysicalDevice physicalDevice, uint32_t queueFamilyIndex) { const auto pd_state = GetPhysicalDeviceState(instance_data, physicalDevice); return ValidatePhysicalDeviceQueueFamily(instance_data, pd_state, queueFamilyIndex, "VUID-vkGetPhysicalDeviceXcbPresentationSupportKHR-queueFamilyIndex-01312", "vkGetPhysicalDeviceXcbPresentationSupportKHR", "queueFamilyIndex"); } #endif // VK_USE_PLATFORM_XCB_KHR #ifdef VK_USE_PLATFORM_XLIB_KHR void PostCallRecordCreateXlibSurfaceKHR(VkInstance instance, const VkXlibSurfaceCreateInfoKHR *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkSurfaceKHR *pSurface, VkResult result) { instance_layer_data *instance_data = GetLayerDataPtr(get_dispatch_key(instance), instance_layer_data_map); if (VK_SUCCESS != result) return; RecordVulkanSurface(instance_data, pSurface); } bool PreCallValidateGetPhysicalDeviceXlibPresentationSupportKHR(instance_layer_data *instance_data, VkPhysicalDevice physicalDevice, uint32_t queueFamilyIndex) { const auto pd_state = GetPhysicalDeviceState(instance_data, physicalDevice); return ValidatePhysicalDeviceQueueFamily(instance_data, pd_state, queueFamilyIndex, "VUID-vkGetPhysicalDeviceXlibPresentationSupportKHR-queueFamilyIndex-01315", "vkGetPhysicalDeviceXlibPresentationSupportKHR", "queueFamilyIndex"); } #endif // VK_USE_PLATFORM_XLIB_KHR void PostCallRecordGetPhysicalDeviceSurfaceCapabilitiesKHR(instance_layer_data *instance_data, VkPhysicalDevice physicalDevice, VkSurfaceCapabilitiesKHR *pSurfaceCapabilities) { auto physical_device_state = GetPhysicalDeviceState(instance_data, physicalDevice); physical_device_state->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS; physical_device_state->surfaceCapabilities = *pSurfaceCapabilities; } void PostCallRecordGetPhysicalDeviceSurfaceCapabilities2KHR(instance_layer_data *instanceData, VkPhysicalDevice physicalDevice, VkSurfaceCapabilities2KHR *pSurfaceCapabilities) { unique_lock_t lock(global_lock); auto physicalDeviceState = GetPhysicalDeviceState(instanceData, physicalDevice); physicalDeviceState->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS; physicalDeviceState->surfaceCapabilities = pSurfaceCapabilities->surfaceCapabilities; } void PostCallRecordGetPhysicalDeviceSurfaceCapabilities2EXT(instance_layer_data *instanceData, VkPhysicalDevice physicalDevice, VkSurfaceCapabilities2EXT *pSurfaceCapabilities) { unique_lock_t lock(global_lock); auto physicalDeviceState = GetPhysicalDeviceState(instanceData, physicalDevice); physicalDeviceState->vkGetPhysicalDeviceSurfaceCapabilitiesKHRState = QUERY_DETAILS; physicalDeviceState->surfaceCapabilities.minImageCount = pSurfaceCapabilities->minImageCount; physicalDeviceState->surfaceCapabilities.maxImageCount = pSurfaceCapabilities->maxImageCount; physicalDeviceState->surfaceCapabilities.currentExtent = pSurfaceCapabilities->currentExtent; physicalDeviceState->surfaceCapabilities.minImageExtent = pSurfaceCapabilities->minImageExtent; physicalDeviceState->surfaceCapabilities.maxImageExtent = pSurfaceCapabilities->maxImageExtent; physicalDeviceState->surfaceCapabilities.maxImageArrayLayers = pSurfaceCapabilities->maxImageArrayLayers; physicalDeviceState->surfaceCapabilities.supportedTransforms = pSurfaceCapabilities->supportedTransforms; physicalDeviceState->surfaceCapabilities.currentTransform = pSurfaceCapabilities->currentTransform; physicalDeviceState->surfaceCapabilities.supportedCompositeAlpha = pSurfaceCapabilities->supportedCompositeAlpha; physicalDeviceState->surfaceCapabilities.supportedUsageFlags = pSurfaceCapabilities->supportedUsageFlags; } bool PreCallValidateGetPhysicalDeviceSurfaceSupportKHR(instance_layer_data *instance_data, PHYSICAL_DEVICE_STATE *physical_device_state, uint32_t queueFamilyIndex) { return ValidatePhysicalDeviceQueueFamily(instance_data, physical_device_state, queueFamilyIndex, "VUID-vkGetPhysicalDeviceSurfaceSupportKHR-queueFamilyIndex-01269", "vkGetPhysicalDeviceSurfaceSupportKHR", "queueFamilyIndex"); } void PostCallRecordGetPhysicalDeviceSurfaceSupportKHR(instance_layer_data *instance_data, VkPhysicalDevice physicalDevice, uint32_t queueFamilyIndex, VkSurfaceKHR surface, VkBool32 *pSupported) { auto surface_state = GetSurfaceState(instance_data, surface); surface_state->gpu_queue_support[{physicalDevice, queueFamilyIndex}] = (*pSupported == VK_TRUE); } void PostCallRecordGetPhysicalDeviceSurfacePresentModesKHR(instance_layer_data *instance_data, VkPhysicalDevice physical_device, uint32_t *pPresentModeCount, VkPresentModeKHR *pPresentModes) { // TODO: this isn't quite right. available modes may differ by surface AND physical device. auto physical_device_state = GetPhysicalDeviceState(instance_data, physical_device); auto &call_state = physical_device_state->vkGetPhysicalDeviceSurfacePresentModesKHRState; if (*pPresentModeCount) { if (call_state < QUERY_COUNT) call_state = QUERY_COUNT; if (*pPresentModeCount > physical_device_state->present_modes.size()) physical_device_state->present_modes.resize(*pPresentModeCount); } if (pPresentModes) { if (call_state < QUERY_DETAILS) call_state = QUERY_DETAILS; for (uint32_t i = 0; i < *pPresentModeCount; i++) { physical_device_state->present_modes[i] = pPresentModes[i]; } } } bool PreCallValidateGetPhysicalDeviceSurfaceFormatsKHR(instance_layer_data *instance_data, PHYSICAL_DEVICE_STATE *physical_device_state, CALL_STATE &call_state, VkPhysicalDevice physicalDevice, uint32_t *pSurfaceFormatCount) { auto prev_format_count = (uint32_t)physical_device_state->surface_formats.size(); bool skip = false; switch (call_state) { case UNCALLED: // Since we haven't recorded a preliminary value of *pSurfaceFormatCount, that likely means that the application // didn't // previously call this function with a NULL value of pSurfaceFormats: skip |= log_msg(instance_data->report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT, HandleToUint64(physicalDevice), kVUID_Core_DevLimit_MustQueryCount, "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount; but no prior " "positive value has been seen for pSurfaceFormats."); break; default: if (prev_format_count != *pSurfaceFormatCount) { skip |= log_msg(instance_data->report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT, HandleToUint64(physicalDevice), kVUID_Core_DevLimit_CountMismatch, "vkGetPhysicalDeviceSurfaceFormatsKHR() called with non-NULL pSurfaceFormatCount, and with " "pSurfaceFormats set to a value (%u) that is greater than the value (%u) that was returned " "when pSurfaceFormatCount was NULL.", *pSurfaceFormatCount, prev_format_count); } break; } return skip; } void PostCallRecordGetPhysicalDeviceSurfaceFormatsKHR(PHYSICAL_DEVICE_STATE *physical_device_state, CALL_STATE &call_state, uint32_t *pSurfaceFormatCount, VkSurfaceFormatKHR *pSurfaceFormats) { if (*pSurfaceFormatCount) { if (call_state < QUERY_COUNT) call_state = QUERY_COUNT; if (*pSurfaceFormatCount > physical_device_state->surface_formats.size()) physical_device_state->surface_formats.resize(*pSurfaceFormatCount); } if (pSurfaceFormats) { if (call_state < QUERY_DETAILS) call_state = QUERY_DETAILS; for (uint32_t i = 0; i < *pSurfaceFormatCount; i++) { physical_device_state->surface_formats[i] = pSurfaceFormats[i]; } } } void PostCallRecordGetPhysicalDeviceSurfaceFormats2KHR(instance_layer_data *instanceData, VkPhysicalDevice physicalDevice, uint32_t *pSurfaceFormatCount, VkSurfaceFormat2KHR *pSurfaceFormats) { unique_lock_t lock(global_lock); auto physicalDeviceState = GetPhysicalDeviceState(instanceData, physicalDevice); if (*pSurfaceFormatCount) { if (physicalDeviceState->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_COUNT) { physicalDeviceState->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_COUNT; } if (*pSurfaceFormatCount > physicalDeviceState->surface_formats.size()) physicalDeviceState->surface_formats.resize(*pSurfaceFormatCount); } if (pSurfaceFormats) { if (physicalDeviceState->vkGetPhysicalDeviceSurfaceFormatsKHRState < QUERY_DETAILS) { physicalDeviceState->vkGetPhysicalDeviceSurfaceFormatsKHRState = QUERY_DETAILS; } for (uint32_t i = 0; i < *pSurfaceFormatCount; i++) { physicalDeviceState->surface_formats[i] = pSurfaceFormats[i].surfaceFormat; } } } void PreCallRecordSetDebugUtilsObjectNameEXT(layer_data *dev_data, const VkDebugUtilsObjectNameInfoEXT *pNameInfo) { if (pNameInfo->pObjectName) { lock_guard_t lock(global_lock); dev_data->report_data->debugUtilsObjectNameMap->insert( std::make_pair<uint64_t, std::string>((uint64_t &&) pNameInfo->objectHandle, pNameInfo->pObjectName)); } else { lock_guard_t lock(global_lock); dev_data->report_data->debugUtilsObjectNameMap->erase(pNameInfo->objectHandle); } } void PreCallRecordQueueBeginDebugUtilsLabelEXT(VkQueue queue, const VkDebugUtilsLabelEXT *pLabelInfo) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(queue), layer_data_map); BeginQueueDebugUtilsLabel(device_data->report_data, queue, pLabelInfo); } void PostCallRecordQueueEndDebugUtilsLabelEXT(VkQueue queue) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(queue), layer_data_map); EndQueueDebugUtilsLabel(device_data->report_data, queue); } void PreCallRecordQueueInsertDebugUtilsLabelEXT(VkQueue queue, const VkDebugUtilsLabelEXT *pLabelInfo) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(queue), layer_data_map); InsertQueueDebugUtilsLabel(device_data->report_data, queue, pLabelInfo); } void PreCallRecordCmdBeginDebugUtilsLabelEXT(layer_data *dev_data, VkCommandBuffer commandBuffer, const VkDebugUtilsLabelEXT *pLabelInfo) { BeginCmdDebugUtilsLabel(dev_data->report_data, commandBuffer, pLabelInfo); } void PostCallRecordCmdEndDebugUtilsLabelEXT(layer_data *dev_data, VkCommandBuffer commandBuffer) { EndCmdDebugUtilsLabel(dev_data->report_data, commandBuffer); } void PreCallRecordCmdInsertDebugUtilsLabelEXT(layer_data *dev_data, VkCommandBuffer commandBuffer, const VkDebugUtilsLabelEXT *pLabelInfo) { InsertCmdDebugUtilsLabel(dev_data->report_data, commandBuffer, pLabelInfo); } void PostCallRecordCreateDebugUtilsMessengerEXT(VkInstance instance, const VkDebugUtilsMessengerCreateInfoEXT *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkDebugUtilsMessengerEXT *pMessenger, VkResult result) { instance_layer_data *instance_data = GetLayerDataPtr(get_dispatch_key(instance), instance_layer_data_map); if (VK_SUCCESS != result) return; layer_create_messenger_callback(instance_data->report_data, false, pCreateInfo, pAllocator, pMessenger); } void PostCallRecordDestroyDebugUtilsMessengerEXT(VkInstance instance, VkDebugUtilsMessengerEXT messenger, const VkAllocationCallbacks *pAllocator) { if (!messenger) return; instance_layer_data *instance_data = GetLayerDataPtr(get_dispatch_key(instance), instance_layer_data_map); layer_destroy_messenger_callback(instance_data->report_data, messenger, pAllocator); } void PostCallRecordCreateDebugReportCallbackEXT(VkInstance instance, const VkDebugReportCallbackCreateInfoEXT *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkDebugReportCallbackEXT *pMsgCallback, VkResult result) { instance_layer_data *instance_data = GetLayerDataPtr(get_dispatch_key(instance), instance_layer_data_map); if (VK_SUCCESS != result) return; layer_create_report_callback(instance_data->report_data, false, pCreateInfo, pAllocator, pMsgCallback); } void PostCallDestroyDebugReportCallbackEXT(instance_layer_data *instance_data, VkDebugReportCallbackEXT msgCallback, const VkAllocationCallbacks *pAllocator) { layer_destroy_report_callback(instance_data->report_data, msgCallback, pAllocator); } bool PreCallValidateEnumeratePhysicalDeviceGroups(VkInstance instance, uint32_t *pPhysicalDeviceGroupCount, VkPhysicalDeviceGroupPropertiesKHR *pPhysicalDeviceGroupProperties) { instance_layer_data *instance_data = GetLayerDataPtr(get_dispatch_key(instance), instance_layer_data_map); bool skip = false; if (instance_data) { // For this instance, flag when EnumeratePhysicalDeviceGroups goes to QUERY_COUNT and then QUERY_DETAILS. if (NULL != pPhysicalDeviceGroupProperties) { if (UNCALLED == instance_data->vkEnumeratePhysicalDeviceGroupsState) { // Flag warning here. You can call this without having queried the count, but it may not be // robust on platforms with multiple physical devices. skip |= log_msg(instance_data->report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_INSTANCE_EXT, 0, kVUID_Core_DevLimit_MissingQueryCount, "Call sequence has vkEnumeratePhysicalDeviceGroups() w/ non-NULL " "pPhysicalDeviceGroupProperties. You should first call vkEnumeratePhysicalDeviceGroups() w/ " "NULL pPhysicalDeviceGroupProperties to query pPhysicalDeviceGroupCount."); } // TODO : Could also flag a warning if re-calling this function in QUERY_DETAILS state else if (instance_data->physical_device_groups_count != *pPhysicalDeviceGroupCount) { // Having actual count match count from app is not a requirement, so this can be a warning skip |= log_msg(instance_data->report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT, 0, kVUID_Core_DevLimit_CountMismatch, "Call to vkEnumeratePhysicalDeviceGroups() w/ pPhysicalDeviceGroupCount value %u, but actual count " "supported by this instance is %u.", *pPhysicalDeviceGroupCount, instance_data->physical_device_groups_count); } } } else { log_msg(instance_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_INSTANCE_EXT, 0, kVUID_Core_DevLimit_InvalidInstance, "Invalid instance (0x%" PRIx64 ") passed into vkEnumeratePhysicalDeviceGroups().", HandleToUint64(instance)); } return skip; } void PreCallRecordEnumeratePhysicalDeviceGroups(instance_layer_data *instance_data, VkPhysicalDeviceGroupPropertiesKHR *pPhysicalDeviceGroupProperties) { if (instance_data) { // For this instance, flag when EnumeratePhysicalDeviceGroups goes to QUERY_COUNT and then QUERY_DETAILS. if (NULL == pPhysicalDeviceGroupProperties) { instance_data->vkEnumeratePhysicalDeviceGroupsState = QUERY_COUNT; } else { instance_data->vkEnumeratePhysicalDeviceGroupsState = QUERY_DETAILS; } } } void PostCallRecordEnumeratePhysicalDeviceGroups(instance_layer_data *instance_data, uint32_t *pPhysicalDeviceGroupCount, VkPhysicalDeviceGroupPropertiesKHR *pPhysicalDeviceGroupProperties) { if (NULL == pPhysicalDeviceGroupProperties) { instance_data->physical_device_groups_count = *pPhysicalDeviceGroupCount; } else { // Save physical devices for (uint32_t i = 0; i < *pPhysicalDeviceGroupCount; i++) { for (uint32_t j = 0; j < pPhysicalDeviceGroupProperties[i].physicalDeviceCount; j++) { VkPhysicalDevice cur_phys_dev = pPhysicalDeviceGroupProperties[i].physicalDevices[j]; auto &phys_device_state = instance_data->physical_device_map[cur_phys_dev]; phys_device_state.phys_device = cur_phys_dev; // Init actual features for each physical device instance_data->dispatch_table.GetPhysicalDeviceFeatures(cur_phys_dev, &phys_device_state.features2.features); } } } } bool ValidateDescriptorUpdateTemplate(const char *func_name, layer_data *device_data, const VkDescriptorUpdateTemplateCreateInfoKHR *pCreateInfo) { bool skip = false; const auto layout = GetDescriptorSetLayout(device_data, pCreateInfo->descriptorSetLayout); if (VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_DESCRIPTOR_SET == pCreateInfo->templateType && !layout) { auto ds_uint = HandleToUint64(pCreateInfo->descriptorSetLayout); skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_DESCRIPTOR_POOL_EXT, ds_uint, "VUID-VkDescriptorUpdateTemplateCreateInfo-templateType-00350", "%s: Invalid pCreateInfo->descriptorSetLayout (%" PRIx64 ")", func_name, ds_uint); } 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); if (!valid_bp) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_UNKNOWN_EXT, 0, "VUID-VkDescriptorUpdateTemplateCreateInfo-templateType-00351", "%s: Invalid pCreateInfo->pipelineBindPoint (%" PRIu32 ").", func_name, static_cast<uint32_t>(bind_point)); } const auto pipeline_layout = GetPipelineLayout(device_data, pCreateInfo->pipelineLayout); if (!pipeline_layout) { uint64_t pl_uint = HandleToUint64(pCreateInfo->pipelineLayout); skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_LAYOUT_EXT, pl_uint, "VUID-VkDescriptorUpdateTemplateCreateInfo-templateType-00352", "%s: Invalid pCreateInfo->pipelineLayout (%" PRIx64 ")", func_name, pl_uint); } 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()) { uint64_t pl_uint = HandleToUint64(pCreateInfo->pipelineLayout); skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_LAYOUT_EXT, pl_uint, "VUID-VkDescriptorUpdateTemplateCreateInfo-templateType-00353", "%s: pCreateInfo->set (%" PRIu32 ") does not refer to the push descriptor set layout for " "pCreateInfo->pipelineLayout (%" PRIx64 ").", func_name, pd_set, pl_uint); } } } return skip; } bool PreCallValidateCreateDescriptorUpdateTemplate(VkDevice device, const VkDescriptorUpdateTemplateCreateInfoKHR *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkDescriptorUpdateTemplateKHR *pDescriptorUpdateTemplate) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); bool skip = ValidateDescriptorUpdateTemplate("vkCreateDescriptorUpdateTemplate()", device_data, pCreateInfo); return skip; } bool PreCallValidateCreateDescriptorUpdateTemplateKHR(VkDevice device, const VkDescriptorUpdateTemplateCreateInfoKHR *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkDescriptorUpdateTemplateKHR *pDescriptorUpdateTemplate) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); bool skip = ValidateDescriptorUpdateTemplate("vkCreateDescriptorUpdateTemplateKHR()", device_data, pCreateInfo); return skip; } void PreCallRecordDestroyDescriptorUpdateTemplate(VkDevice device, VkDescriptorUpdateTemplateKHR descriptorUpdateTemplate, const VkAllocationCallbacks *pAllocator) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); if (!descriptorUpdateTemplate) return; device_data->desc_template_map.erase(descriptorUpdateTemplate); } void PreCallRecordDestroyDescriptorUpdateTemplateKHR(VkDevice device, VkDescriptorUpdateTemplateKHR descriptorUpdateTemplate, const VkAllocationCallbacks *pAllocator) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); if (!descriptorUpdateTemplate) return; device_data->desc_template_map.erase(descriptorUpdateTemplate); } void RecordCreateDescriptorUpdateTemplateState(layer_data *device_data, const VkDescriptorUpdateTemplateCreateInfoKHR *pCreateInfo, VkDescriptorUpdateTemplateKHR *pDescriptorUpdateTemplate) { safe_VkDescriptorUpdateTemplateCreateInfo *local_create_info = new safe_VkDescriptorUpdateTemplateCreateInfo(pCreateInfo); std::unique_ptr<TEMPLATE_STATE> template_state(new TEMPLATE_STATE(*pDescriptorUpdateTemplate, local_create_info)); device_data->desc_template_map[*pDescriptorUpdateTemplate] = std::move(template_state); } void PostCallRecordCreateDescriptorUpdateTemplate(VkDevice device, const VkDescriptorUpdateTemplateCreateInfoKHR *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkDescriptorUpdateTemplateKHR *pDescriptorUpdateTemplate, VkResult result) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); if (VK_SUCCESS != result) return; RecordCreateDescriptorUpdateTemplateState(device_data, pCreateInfo, pDescriptorUpdateTemplate); } void PostCallRecordCreateDescriptorUpdateTemplateKHR(VkDevice device, const VkDescriptorUpdateTemplateCreateInfoKHR *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkDescriptorUpdateTemplateKHR *pDescriptorUpdateTemplate, VkResult result) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); if (VK_SUCCESS != result) return; RecordCreateDescriptorUpdateTemplateState(device_data, pCreateInfo, pDescriptorUpdateTemplate); } bool PreCallValidateUpdateDescriptorSetWithTemplate(layer_data *device_data, VkDescriptorSet descriptorSet, VkDescriptorUpdateTemplateKHR descriptorUpdateTemplate, const void *pData) { bool skip = false; auto const template_map_entry = device_data->desc_template_map.find(descriptorUpdateTemplate); if ((template_map_entry == device_data->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 = cvdescriptorset::ValidateUpdateDescriptorSetsWithTemplateKHR(device_data, descriptorSet, template_state, pData); } } return skip; } void PreCallRecordUpdateDescriptorSetWithTemplate(layer_data *device_data, VkDescriptorSet descriptorSet, VkDescriptorUpdateTemplateKHR descriptorUpdateTemplate, const void *pData) { auto const template_map_entry = device_data->desc_template_map.find(descriptorUpdateTemplate); if ((template_map_entry == device_data->desc_template_map.end()) || (template_map_entry->second.get() == nullptr)) { assert(0); } else { const TEMPLATE_STATE *template_state = template_map_entry->second.get(); // TODO: Record template push descriptor updates if (template_state->create_info.templateType == VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_DESCRIPTOR_SET) { cvdescriptorset::PerformUpdateDescriptorSetsWithTemplateKHR(device_data, descriptorSet, template_state, pData); } } } static std::shared_ptr<cvdescriptorset::DescriptorSetLayout const> GetDslFromPipelineLayout(PIPELINE_LAYOUT_NODE const *layout_data, uint32_t set) { std::shared_ptr<cvdescriptorset::DescriptorSetLayout const> dsl = nullptr; if (layout_data && (set < layout_data->set_layouts.size())) { dsl = layout_data->set_layouts[set]; } return dsl; } bool PreCallValidateCmdPushDescriptorSetWithTemplateKHR(layer_data *device_data, GLOBAL_CB_NODE *cb_state, VkDescriptorUpdateTemplateKHR descriptorUpdateTemplate, VkPipelineLayout layout, uint32_t set, const void *pData) { const char *const func_name = "vkPushDescriptorSetWithTemplateKHR()"; bool skip = false; skip |= ValidateCmd(device_data, cb_state, CMD_PUSHDESCRIPTORSETWITHTEMPLATEKHR, func_name); auto layout_data = GetPipelineLayout(device_data, layout); auto dsl = GetDslFromPipelineLayout(layout_data, set); const auto layout_u64 = HandleToUint64(layout); // Validate the set index points to a push descriptor set and is in range if (dsl) { if (!dsl->IsPushDescriptor()) { skip = log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_LAYOUT_EXT, layout_u64, "VUID-vkCmdPushDescriptorSetKHR-set-00365", "%s: Set index %" PRIu32 " does not match push descriptor set layout index for VkPipelineLayout 0x%" PRIxLEAST64 ".", func_name, set, layout_u64); } } else if (layout_data && (set >= layout_data->set_layouts.size())) { skip = log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PIPELINE_LAYOUT_EXT, layout_u64, "VUID-vkCmdPushDescriptorSetKHR-set-00364", "%s: Set index %" PRIu32 " is outside of range for VkPipelineLayout 0x%" PRIxLEAST64 " (set < %" PRIu32 ").", func_name, set, layout_u64, static_cast<uint32_t>(layout_data->set_layouts.size())); } const auto template_state = GetDescriptorTemplateState(device_data, 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_NV, "VUID-vkCmdPushDescriptorSetWithTemplateKHR-commandBuffer-00366")}; skip |= ValidatePipelineBindPoint(device_data, cb_state, template_ci.pipelineBindPoint, func_name, bind_errors); if (template_ci.templateType != VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_PUSH_DESCRIPTORS_KHR) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(cb_state->commandBuffer), kVUID_Core_PushDescriptorUpdate_TemplateType, "%s: descriptorUpdateTemplate 0x%" PRIxLEAST64 " was not created with flag VK_DESCRIPTOR_UPDATE_TEMPLATE_TYPE_PUSH_DESCRIPTORS_KHR.", func_name, HandleToUint64(descriptorUpdateTemplate)); } if (template_ci.set != set) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(cb_state->commandBuffer), kVUID_Core_PushDescriptorUpdate_Template_SetMismatched, "%s: descriptorUpdateTemplate 0x%" PRIxLEAST64 " created with set %" PRIu32 " does not match command parameter set %" PRIu32 ".", func_name, HandleToUint64(descriptorUpdateTemplate), template_ci.set, set); } if (!CompatForSet(set, layout_data, GetPipelineLayout(device_data, template_ci.pipelineLayout))) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(cb_state->commandBuffer), kVUID_Core_PushDescriptorUpdate_Template_LayoutMismatched, "%s: descriptorUpdateTemplate 0x%" PRIxLEAST64 " created with pipelineLayout 0x%" PRIxLEAST64 " is incompatible with command parameter layout 0x%" PRIxLEAST64 " for set %" PRIu32, func_name, HandleToUint64(descriptorUpdateTemplate), HandleToUint64(template_ci.pipelineLayout), HandleToUint64(layout), 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, VK_NULL_HANDLE, dsl, 0, device_data); // Decode the template into a set of write updates cvdescriptorset::DecodedTemplateUpdate decoded_template(device_data, VK_NULL_HANDLE, template_state, pData, dsl->GetDescriptorSetLayout()); // Validate the decoded update against the proxy_ds skip |= proxy_ds.ValidatePushDescriptorsUpdate(device_data->report_data, static_cast<uint32_t>(decoded_template.desc_writes.size()), decoded_template.desc_writes.data(), func_name); } return skip; } void PreCallRecordCmdPushDescriptorSetWithTemplateKHR(layer_data *device_data, GLOBAL_CB_NODE *cb_state, VkDescriptorUpdateTemplateKHR descriptorUpdateTemplate, VkPipelineLayout layout, uint32_t set, const void *pData) { const auto template_state = GetDescriptorTemplateState(device_data, descriptorUpdateTemplate); if (template_state) { auto layout_data = GetPipelineLayout(device_data, layout); auto dsl = GetDslFromPipelineLayout(layout_data, set); const auto &template_ci = template_state->create_info; if (dsl && !dsl->IsDestroyed()) { // Decode the template into a set of write updates cvdescriptorset::DecodedTemplateUpdate decoded_template(device_data, VK_NULL_HANDLE, template_state, pData, dsl->GetDescriptorSetLayout()); PreCallRecordCmdPushDescriptorSetKHR(device_data, cb_state, template_ci.pipelineBindPoint, layout, set, static_cast<uint32_t>(decoded_template.desc_writes.size()), decoded_template.desc_writes.data()); } } } void PostCallRecordGetPhysicalDeviceDisplayPlanePropertiesKHR(instance_layer_data *instanceData, VkPhysicalDevice physicalDevice, uint32_t *pPropertyCount, void *pProperties) { unique_lock_t lock(global_lock); auto physical_device_state = GetPhysicalDeviceState(instanceData, physicalDevice); if (*pPropertyCount) { if (physical_device_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_COUNT) { physical_device_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_COUNT; } physical_device_state->display_plane_property_count = *pPropertyCount; } if (pProperties) { if (physical_device_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState < QUERY_DETAILS) { physical_device_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState = QUERY_DETAILS; } } } static bool ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(instance_layer_data *instance_data, VkPhysicalDevice physicalDevice, uint32_t planeIndex, const char *api_name) { bool skip = false; auto physical_device_state = GetPhysicalDeviceState(instance_data, physicalDevice); if (physical_device_state->vkGetPhysicalDeviceDisplayPlanePropertiesKHRState == UNCALLED) { skip |= log_msg(instance_data->report_data, VK_DEBUG_REPORT_WARNING_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT, HandleToUint64(physicalDevice), kVUID_Core_Swapchain_GetSupportedDisplaysWithoutQuery, "Potential problem with calling %s() without first querying vkGetPhysicalDeviceDisplayPlanePropertiesKHR " "or vkGetPhysicalDeviceDisplayPlaneProperties2KHR.", api_name); } else { if (planeIndex >= physical_device_state->display_plane_property_count) { skip |= log_msg( instance_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_PHYSICAL_DEVICE_EXT, HandleToUint64(physicalDevice), "VUID-vkGetDisplayPlaneSupportedDisplaysKHR-planeIndex-01249", "%s(): planeIndex must be in the range [0, %d] that was returned by vkGetPhysicalDeviceDisplayPlanePropertiesKHR " "or vkGetPhysicalDeviceDisplayPlaneProperties2KHR. Do you have the plane index hardcoded?", api_name, physical_device_state->display_plane_property_count - 1); } } return skip; } bool PreCallValidateGetDisplayPlaneSupportedDisplaysKHR(instance_layer_data *instance_data, VkPhysicalDevice physicalDevice, uint32_t planeIndex) { bool skip = false; lock_guard_t lock(global_lock); skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(instance_data, physicalDevice, planeIndex, "vkGetDisplayPlaneSupportedDisplaysKHR"); return skip; } bool PreCallValidateGetDisplayPlaneCapabilitiesKHR(instance_layer_data *instance_data, VkPhysicalDevice physicalDevice, uint32_t planeIndex) { bool skip = false; lock_guard_t lock(global_lock); skip |= ValidateGetPhysicalDeviceDisplayPlanePropertiesKHRQuery(instance_data, physicalDevice, planeIndex, "vkGetDisplayPlaneCapabilitiesKHR"); return skip; } void PreCallRecordDebugMarkerSetObjectNameEXT(layer_data *dev_data, const VkDebugMarkerObjectNameInfoEXT *pNameInfo) { if (pNameInfo->pObjectName) { dev_data->report_data->debugObjectNameMap->insert( std::make_pair<uint64_t, std::string>((uint64_t &&) pNameInfo->object, pNameInfo->pObjectName)); } else { dev_data->report_data->debugObjectNameMap->erase(pNameInfo->object); } } bool PreCallValidateCmdDebugMarkerBeginEXT(layer_data *dev_data, GLOBAL_CB_NODE *cb_state) { return ValidateCmd(dev_data, cb_state, CMD_DEBUGMARKERBEGINEXT, "vkCmdDebugMarkerBeginEXT()"); } bool PreCallValidateCmdDebugMarkerEndEXT(layer_data *dev_data, GLOBAL_CB_NODE *cb_state) { return ValidateCmd(dev_data, cb_state, CMD_DEBUGMARKERENDEXT, "vkCmdDebugMarkerEndEXT()"); } bool PreCallValidateCmdSetDiscardRectangleEXT(layer_data *dev_data, GLOBAL_CB_NODE *cb_state) { return ValidateCmd(dev_data, cb_state, CMD_SETDISCARDRECTANGLEEXT, "vkCmdSetDiscardRectangleEXT()"); } bool PreCallValidateCmdSetSampleLocationsEXT(layer_data *dev_data, GLOBAL_CB_NODE *cb_state) { return ValidateCmd(dev_data, cb_state, CMD_SETSAMPLELOCATIONSEXT, "vkCmdSetSampleLocationsEXT()"); } bool PreCallValidateCmdDrawIndirectCountKHR(layer_data *dev_data, VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t stride, GLOBAL_CB_NODE **cb_state, BUFFER_STATE **buffer_state, BUFFER_STATE **count_buffer_state, bool indexed, VkPipelineBindPoint bind_point, const char *caller) { bool skip = false; if (offset & 3) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(commandBuffer), "VUID-vkCmdDrawIndirectCountKHR-offset-03108", "vkCmdDrawIndirectCountKHR() parameter, VkDeviceSize offset (0x%" PRIxLEAST64 "), is not a multiple of 4.", offset); } if (countBufferOffset & 3) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(commandBuffer), "VUID-vkCmdDrawIndirectCountKHR-countBufferOffset-03109", "vkCmdDrawIndirectCountKHR() parameter, VkDeviceSize countBufferOffset (0x%" PRIxLEAST64 "), is not a multiple of 4.", countBufferOffset); } if ((stride & 3) || stride < sizeof(VkDrawIndirectCommand)) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(commandBuffer), "VUID-vkCmdDrawIndirectCountKHR-stride-03110", "vkCmdDrawIndirectCountKHR() parameter, uint32_t stride (0x%" PRIxLEAST32 "), is not a multiple of 4 or smaller than sizeof (VkDrawIndirectCommand).", stride); } skip |= ValidateCmdDrawType(dev_data, commandBuffer, indexed, bind_point, CMD_DRAWINDIRECTCOUNTKHR, cb_state, caller, VK_QUEUE_GRAPHICS_BIT, "VUID-vkCmdDrawIndirectCountKHR-commandBuffer-cmdpool", "VUID-vkCmdDrawIndirectCountKHR-renderpass", "VUID-vkCmdDrawIndirectCountKHR-None-03119", "VUID-vkCmdDrawIndirectCountKHR-None-03120"); *buffer_state = GetBufferState(dev_data, buffer); *count_buffer_state = GetBufferState(dev_data, countBuffer); skip |= ValidateMemoryIsBoundToBuffer(dev_data, *buffer_state, caller, "VUID-vkCmdDrawIndirectCountKHR-buffer-03104"); skip |= ValidateMemoryIsBoundToBuffer(dev_data, *count_buffer_state, caller, "VUID-vkCmdDrawIndirectCountKHR-countBuffer-03106"); return skip; } void PreCallRecordCmdDrawIndirectCountKHR(layer_data *dev_data, GLOBAL_CB_NODE *cb_state, VkPipelineBindPoint bind_point, BUFFER_STATE *buffer_state, BUFFER_STATE *count_buffer_state) { UpdateStateCmdDrawType(dev_data, cb_state, bind_point); AddCommandBufferBindingBuffer(dev_data, cb_state, buffer_state); AddCommandBufferBindingBuffer(dev_data, cb_state, count_buffer_state); } bool PreCallValidateCmdDrawIndexedIndirectCountKHR(layer_data *dev_data, VkCommandBuffer commandBuffer, VkBuffer buffer, VkDeviceSize offset, VkBuffer countBuffer, VkDeviceSize countBufferOffset, uint32_t stride, GLOBAL_CB_NODE **cb_state, BUFFER_STATE **buffer_state, BUFFER_STATE **count_buffer_state, bool indexed, VkPipelineBindPoint bind_point, const char *caller) { bool skip = false; if (offset & 3) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(commandBuffer), "VUID-vkCmdDrawIndexedIndirectCountKHR-offset-03140", "vkCmdDrawIndexedIndirectCountKHR() parameter, VkDeviceSize offset (0x%" PRIxLEAST64 "), is not a multiple of 4.", offset); } if (countBufferOffset & 3) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(commandBuffer), "VUID-vkCmdDrawIndexedIndirectCountKHR-countBufferOffset-03141", "vkCmdDrawIndexedIndirectCountKHR() parameter, VkDeviceSize countBufferOffset (0x%" PRIxLEAST64 "), is not a multiple of 4.", countBufferOffset); } if ((stride & 3) || stride < sizeof(VkDrawIndexedIndirectCommand)) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_COMMAND_BUFFER_EXT, HandleToUint64(commandBuffer), "VUID-vkCmdDrawIndexedIndirectCountKHR-stride-03142", "vkCmdDrawIndexedIndirectCountKHR() parameter, uint32_t stride (0x%" PRIxLEAST32 "), is not a multiple of 4 or smaller than sizeof (VkDrawIndexedIndirectCommand).", stride); } skip |= ValidateCmdDrawType( dev_data, commandBuffer, indexed, bind_point, CMD_DRAWINDEXEDINDIRECTCOUNTKHR, cb_state, caller, VK_QUEUE_GRAPHICS_BIT, "VUID-vkCmdDrawIndexedIndirectCountKHR-commandBuffer-cmdpool", "VUID-vkCmdDrawIndexedIndirectCountKHR-renderpass", "VUID-vkCmdDrawIndexedIndirectCountKHR-None-03151", "VUID-vkCmdDrawIndexedIndirectCountKHR-None-03152"); *buffer_state = GetBufferState(dev_data, buffer); *count_buffer_state = GetBufferState(dev_data, countBuffer); skip |= ValidateMemoryIsBoundToBuffer(dev_data, *buffer_state, caller, "VUID-vkCmdDrawIndexedIndirectCountKHR-buffer-03136"); skip |= ValidateMemoryIsBoundToBuffer(dev_data, *count_buffer_state, caller, "VUID-vkCmdDrawIndexedIndirectCountKHR-countBuffer-03138"); return skip; } void PreCallRecordCmdDrawIndexedIndirectCountKHR(layer_data *dev_data, GLOBAL_CB_NODE *cb_state, VkPipelineBindPoint bind_point, BUFFER_STATE *buffer_state, BUFFER_STATE *count_buffer_state) { UpdateStateCmdDrawType(dev_data, cb_state, bind_point); AddCommandBufferBindingBuffer(dev_data, cb_state, buffer_state); AddCommandBufferBindingBuffer(dev_data, cb_state, count_buffer_state); } bool PreCallValidateCmdDrawMeshTasksNV(layer_data *dev_data, VkCommandBuffer cmd_buffer, bool indexed, VkPipelineBindPoint bind_point, GLOBAL_CB_NODE **cb_state, const char *caller) { bool skip = ValidateCmdDrawType(dev_data, cmd_buffer, indexed, bind_point, CMD_DRAWMESHTASKSNV, cb_state, caller, VK_QUEUE_GRAPHICS_BIT, "VUID-vkCmdDrawMeshTasksNV-commandBuffer-cmdpool", "VUID-vkCmdDrawMeshTasksNV-renderpass", "VUID-vkCmdDrawMeshTasksNV-None-02125", "VUID-vkCmdDrawMeshTasksNV-None-02126"); return skip; } void PreCallRecordCmdDrawMeshTasksNV(layer_data *dev_data, GLOBAL_CB_NODE *cb_state, VkPipelineBindPoint bind_point) { UpdateStateCmdDrawType(dev_data, cb_state, bind_point); } bool PreCallValidateCmdDrawMeshTasksIndirectNV(layer_data *dev_data, VkCommandBuffer cmd_buffer, VkBuffer buffer, bool indexed, VkPipelineBindPoint bind_point, GLOBAL_CB_NODE **cb_state, BUFFER_STATE **buffer_state, const char *caller) { bool skip = ValidateCmdDrawType(dev_data, cmd_buffer, indexed, bind_point, CMD_DRAWMESHTASKSINDIRECTNV, cb_state, caller, VK_QUEUE_GRAPHICS_BIT, "VUID-vkCmdDrawMeshTasksIndirectNV-commandBuffer-cmdpool", "VUID-vkCmdDrawMeshTasksIndirectNV-renderpass", "VUID-vkCmdDrawMeshTasksIndirectNV-None-02154", "VUID-vkCmdDrawMeshTasksIndirectNV-None-02155"); *buffer_state = GetBufferState(dev_data, buffer); skip |= ValidateMemoryIsBoundToBuffer(dev_data, *buffer_state, caller, "VUID-vkCmdDrawMeshTasksIndirectNV-buffer-02143"); return skip; } void PreCallRecordCmdDrawMeshTasksIndirectNV(layer_data *dev_data, GLOBAL_CB_NODE *cb_state, VkPipelineBindPoint bind_point, BUFFER_STATE *buffer_state) { UpdateStateCmdDrawType(dev_data, cb_state, bind_point); if (buffer_state) { AddCommandBufferBindingBuffer(dev_data, cb_state, buffer_state); } } bool PreCallValidateCmdDrawMeshTasksIndirectCountNV(layer_data *dev_data, VkCommandBuffer cmd_buffer, VkBuffer buffer, VkBuffer count_buffer, bool indexed, VkPipelineBindPoint bind_point, GLOBAL_CB_NODE **cb_state, BUFFER_STATE **buffer_state, BUFFER_STATE **count_buffer_state, const char *caller) { bool skip = ValidateCmdDrawType( dev_data, cmd_buffer, indexed, bind_point, CMD_DRAWMESHTASKSINDIRECTCOUNTNV, cb_state, caller, VK_QUEUE_GRAPHICS_BIT, "VUID-vkCmdDrawMeshTasksIndirectCountNV-commandBuffer-cmdpool", "VUID-vkCmdDrawMeshTasksIndirectCountNV-renderpass", "VUID-vkCmdDrawMeshTasksIndirectCountNV-None-02189", "VUID-vkCmdDrawMeshTasksIndirectCountNV-None-02190"); *buffer_state = GetBufferState(dev_data, buffer); *count_buffer_state = GetBufferState(dev_data, count_buffer); skip |= ValidateMemoryIsBoundToBuffer(dev_data, *buffer_state, caller, "VUID-vkCmdDrawMeshTasksIndirectCountNV-buffer-02176"); skip |= ValidateMemoryIsBoundToBuffer(dev_data, *count_buffer_state, caller, "VUID-vkCmdDrawMeshTasksIndirectCountNV-countBuffer-02178"); return skip; } void PreCallRecordCmdDrawMeshTasksIndirectCountNV(layer_data *dev_data, GLOBAL_CB_NODE *cb_state, VkPipelineBindPoint bind_point, BUFFER_STATE *buffer_state, BUFFER_STATE *count_buffer_state) { UpdateStateCmdDrawType(dev_data, cb_state, bind_point); if (buffer_state) { AddCommandBufferBindingBuffer(dev_data, cb_state, buffer_state); } if (count_buffer_state) { AddCommandBufferBindingBuffer(dev_data, cb_state, count_buffer_state); } } static bool ValidateCreateSamplerYcbcrConversion(const layer_data *device_data, const char *func_name, const VkSamplerYcbcrConversionCreateInfo *create_info) { bool skip = false; if (GetDeviceExtensions(device_data)->vk_android_external_memory_android_hardware_buffer) { skip |= ValidateCreateSamplerYcbcrConversionANDROID(device_data, create_info); } else { // Not android hardware buffer if (VK_FORMAT_UNDEFINED == create_info->format) { skip |= log_msg(device_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_SAMPLER_YCBCR_CONVERSION_EXT, 0, "VUID-VkSamplerYcbcrConversionCreateInfo-format-01649", "%s: CreateInfo format type is VK_FORMAT_UNDEFINED.", func_name); } } return skip; } bool PreCallValidateCreateSamplerYcbcrConversion(VkDevice device, const VkSamplerYcbcrConversionCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkSamplerYcbcrConversion *pYcbcrConversion) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); return ValidateCreateSamplerYcbcrConversion(device_data, "vkCreateSamplerYcbcrConversion()", pCreateInfo); } bool PreCallValidateCreateSamplerYcbcrConversionKHR(VkDevice device, const VkSamplerYcbcrConversionCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkSamplerYcbcrConversion *pYcbcrConversion) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); return ValidateCreateSamplerYcbcrConversion(device_data, "vkCreateSamplerYcbcrConversionKHR()", pCreateInfo); } static void RecordCreateSamplerYcbcrConversionState(layer_data *device_data, const VkSamplerYcbcrConversionCreateInfo *create_info, VkSamplerYcbcrConversion ycbcr_conversion) { if (GetDeviceExtensions(device_data)->vk_android_external_memory_android_hardware_buffer) { RecordCreateSamplerYcbcrConversionANDROID(device_data, create_info, ycbcr_conversion); } } void PostCallRecordCreateSamplerYcbcrConversion(VkDevice device, const VkSamplerYcbcrConversionCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkSamplerYcbcrConversion *pYcbcrConversion, VkResult result) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); if (VK_SUCCESS != result) return; RecordCreateSamplerYcbcrConversionState(device_data, pCreateInfo, *pYcbcrConversion); } void PostCallRecordCreateSamplerYcbcrConversionKHR(VkDevice device, const VkSamplerYcbcrConversionCreateInfo *pCreateInfo, const VkAllocationCallbacks *pAllocator, VkSamplerYcbcrConversion *pYcbcrConversion, VkResult result) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); if (VK_SUCCESS != result) return; RecordCreateSamplerYcbcrConversionState(device_data, pCreateInfo, *pYcbcrConversion); } void PostCallRecordDestroySamplerYcbcrConversion(VkDevice device, VkSamplerYcbcrConversion ycbcrConversion, const VkAllocationCallbacks *pAllocator) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); if (!ycbcrConversion) return; if (GetDeviceExtensions(device_data)->vk_android_external_memory_android_hardware_buffer) { RecordDestroySamplerYcbcrConversionANDROID(device_data, ycbcrConversion); } } void PostCallRecordDestroySamplerYcbcrConversionKHR(VkDevice device, VkSamplerYcbcrConversion ycbcrConversion, const VkAllocationCallbacks *pAllocator) { layer_data *device_data = GetLayerDataPtr(get_dispatch_key(device), layer_data_map); if (!ycbcrConversion) return; if (GetDeviceExtensions(device_data)->vk_android_external_memory_android_hardware_buffer) { RecordDestroySamplerYcbcrConversionANDROID(device_data, ycbcrConversion); } } bool PreCallValidateGetBufferDeviceAddressEXT(layer_data *dev_data, const VkBufferDeviceAddressInfoEXT *pInfo) { bool skip = false; if (!GetEnabledFeatures(dev_data)->buffer_address.bufferDeviceAddress) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT, HandleToUint64(pInfo->buffer), "VUID-vkGetBufferDeviceAddressEXT-None-02598", "The bufferDeviceAddress feature must: be enabled."); } if (dev_data->physical_device_count > 1 && !GetEnabledFeatures(dev_data)->buffer_address.bufferDeviceAddressMultiDevice) { skip |= log_msg(dev_data->report_data, VK_DEBUG_REPORT_ERROR_BIT_EXT, VK_DEBUG_REPORT_OBJECT_TYPE_BUFFER_EXT, HandleToUint64(pInfo->buffer), "VUID-vkGetBufferDeviceAddressEXT-device-02599", "If device was created with multiple physical devices, then the " "bufferDeviceAddressMultiDevice feature must: be enabled."); } auto buffer_state = GetBufferState(dev_data, pInfo->buffer); if (buffer_state) { if (!(buffer_state->createInfo.flags & VK_BUFFER_CREATE_DEVICE_ADDRESS_CAPTURE_REPLAY_BIT_EXT)) { skip |= ValidateMemoryIsBoundToBuffer(dev_data, buffer_state, "vkGetBufferDeviceAddressEXT()", "VUID-VkBufferDeviceAddressInfoEXT-buffer-02600"); } skip |= ValidateBufferUsageFlags(dev_data, buffer_state, VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT_EXT, true, "VUID-VkBufferDeviceAddressInfoEXT-buffer-02601", "vkGetBufferDeviceAddressEXT()", "VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT_EXT"); } return skip; } } // namespace core_validation
1
9,931
I'd move the empty assignment and non-null case into the if check directly above (adding an else clause as needed)
KhronosGroup-Vulkan-ValidationLayers
cpp
@@ -215,6 +215,8 @@ class Preference extends Model 'zh-tw' => [Lang::get('system::lang.locale.zh-tw'), 'flag-tw'], 'nb-no' => [Lang::get('system::lang.locale.nb-no'), 'flag-no'], 'el' => [Lang::get('system::lang.locale.el'), 'flag-gr'], + 'ar' => [Lang::get('system::lang.locale.ar'), 'flag-sa'], + ]; $locales = Config::get('app.localeOptions', $localeOptions);
1
<?php namespace Backend\Models; use App; use Lang; use Model; use Config; use Session; use BackendAuth; use DirectoryIterator; use DateTime; use DateTimeZone; use Carbon\Carbon; /** * Backend preferences for the backend user * * @package october\backend * @author Alexey Bobkov, Samuel Georges */ class Preference extends Model { use \October\Rain\Database\Traits\Validation; const DEFAULT_THEME = 'twilight'; /** * @var array Behaviors implemented by this model. */ public $implement = [ \Backend\Behaviors\UserPreferencesModel::class ]; /** * @var string Unique code */ public $settingsCode = 'backend::backend.preferences'; /** * @var mixed Settings form field defitions */ public $settingsFields = 'fields.yaml'; /** * @var array Validation rules */ public $rules = []; /** * Initialize the seed data for this model. This only executes when the * model is first created or reset to default. * @return void */ public function initSettingsData() { $config = App::make('config'); $this->locale = $config->get('app.locale', 'en'); $this->fallback_locale = $this->getFallbackLocale($this->locale); $this->timezone = $config->get('cms.backendTimezone', $config->get('app.timezone')); $this->editor_font_size = $config->get('editor.font_size', 12); $this->editor_word_wrap = $config->get('editor.word_wrap', 'fluid'); $this->editor_code_folding = $config->get('editor.code_folding', 'manual'); $this->editor_tab_size = $config->get('editor.tab_size', 4); $this->editor_theme = $config->get('editor.theme', static::DEFAULT_THEME); $this->editor_show_invisibles = $config->get('editor.show_invisibles', false); $this->editor_highlight_active_line = $config->get('editor.highlight_active_line', true); $this->editor_use_hard_tabs = $config->get('editor.use_hard_tabs', false); $this->editor_show_gutter = $config->get('editor.show_gutter', true); $this->editor_auto_closing = $config->get('editor.auto_closing', false); $this->editor_autocompletion = $config->get('editor.editor_autocompletion', 'manual'); $this->editor_enable_snippets = $config->get('editor.enable_snippets', false); $this->editor_display_indent_guides = $config->get('editor.display_indent_guides', false); $this->editor_show_print_margin = $config->get('editor.show_print_margin', false); } /** * Set the application's locale based on the user preference. * @return void */ public static function setAppLocale() { if (Session::has('locale')) { App::setLocale(Session::get('locale')); } elseif ( ($user = BackendAuth::getUser()) && ($locale = static::get('locale')) ) { Session::put('locale', $locale); App::setLocale($locale); } } /** * Same as setAppLocale except for the fallback definition. * @return void */ public static function setAppFallbackLocale() { if (Session::has('fallback_locale')) { Lang::setFallback(Session::get('fallback_locale')); } elseif ( ($user = BackendAuth::getUser()) && ($locale = static::get('fallback_locale')) ) { Session::put('fallback_locale', $locale); Lang::setFallback($locale); } } // // Events // public function beforeValidate() { $this->fallback_locale = $this->getFallbackLocale($this->locale); } public function afterSave() { Session::put('locale', $this->locale); Session::put('fallback_locale', $this->fallback_locale); } // // Utils // /** * Called when this model is reset to default by the user. * @return void */ public function resetDefault() { parent::resetDefault(); Session::forget('locale'); Session::forget('fallback_locale'); } /** * Overrides the config with the user's preference. * @return void */ public static function applyConfigValues() { $settings = self::instance(); Config::set('app.locale', $settings->locale); Config::set('app.fallback_locale', $settings->fallback_locale); } // // Getters // /** * Attempt to extract the language from the locale, * otherwise use the configuration. * @return string */ protected function getFallbackLocale($locale) { if ($position = strpos($locale, '-')) { $target = substr($locale, 0, $position); $available = $this->getLocaleOptions(); if (isset($available[$target])) { return $target; } } return Config::get('app.fallback_locale'); } /** * Returns available options for the "locale" attribute. * @return array */ public function getLocaleOptions() { $localeOptions = [ 'be' => [Lang::get('system::lang.locale.be'), 'flag-by'], 'cs' => [Lang::get('system::lang.locale.cs'), 'flag-cz'], 'da' => [Lang::get('system::lang.locale.da'), 'flag-dk'], 'en' => [Lang::get('system::lang.locale.en'), 'flag-us'], 'en-au' => [Lang::get('system::lang.locale.en-au'), 'flag-au'], 'en-ca' => [Lang::get('system::lang.locale.en-ca'), 'flag-ca'], 'en-gb' => [Lang::get('system::lang.locale.en-gb'), 'flag-gb'], 'et' => [Lang::get('system::lang.locale.et'), 'flag-ee'], 'de' => [Lang::get('system::lang.locale.de'), 'flag-de'], 'es' => [Lang::get('system::lang.locale.es'), 'flag-es'], 'es-ar' => [Lang::get('system::lang.locale.es-ar'), 'flag-ar'], 'fa' => [Lang::get('system::lang.locale.fa'), 'flag-ir'], 'fr' => [Lang::get('system::lang.locale.fr'), 'flag-fr'], 'fr-ca' => [Lang::get('system::lang.locale.fr-ca'), 'flag-ca'], 'hu' => [Lang::get('system::lang.locale.hu'), 'flag-hu'], 'id' => [Lang::get('system::lang.locale.id'), 'flag-id'], 'it' => [Lang::get('system::lang.locale.it'), 'flag-it'], 'ja' => [Lang::get('system::lang.locale.ja'), 'flag-jp'], 'kr' => [Lang::get('system::lang.locale.kr'), 'flag-kr'], 'lt' => [Lang::get('system::lang.locale.lt'), 'flag-lt'], 'lv' => [Lang::get('system::lang.locale.lv'), 'flag-lv'], 'nl' => [Lang::get('system::lang.locale.nl'), 'flag-nl'], 'pt-br' => [Lang::get('system::lang.locale.pt-br'), 'flag-br'], 'pt-pt' => [Lang::get('system::lang.locale.pt-pt'), 'flag-pt'], 'ro' => [Lang::get('system::lang.locale.ro'), 'flag-ro'], 'ru' => [Lang::get('system::lang.locale.ru'), 'flag-ru'], 'fi' => [Lang::get('system::lang.locale.fi'), 'flag-fi'], 'sv' => [Lang::get('system::lang.locale.sv'), 'flag-se'], 'tr' => [Lang::get('system::lang.locale.tr'), 'flag-tr'], 'uk' => [Lang::get('system::lang.locale.uk'), 'flag-ua'], 'pl' => [Lang::get('system::lang.locale.pl'), 'flag-pl'], 'sk' => [Lang::get('system::lang.locale.sk'), 'flag-sk'], 'zh-cn' => [Lang::get('system::lang.locale.zh-cn'), 'flag-cn'], 'zh-tw' => [Lang::get('system::lang.locale.zh-tw'), 'flag-tw'], 'nb-no' => [Lang::get('system::lang.locale.nb-no'), 'flag-no'], 'el' => [Lang::get('system::lang.locale.el'), 'flag-gr'], ]; $locales = Config::get('app.localeOptions', $localeOptions); // Sort locales alphabetically asort($locales); return $locales; } /** * Returns all available timezone options. * @return array */ public function getTimezoneOptions() { $timezoneIdentifiers = DateTimeZone::listIdentifiers(); $utcTime = new DateTime('now', new DateTimeZone('UTC')); $tempTimezones = []; foreach ($timezoneIdentifiers as $timezoneIdentifier) { $currentTimezone = new DateTimeZone($timezoneIdentifier); $tempTimezones[] = [ 'offset' => (int) $currentTimezone->getOffset($utcTime), 'identifier' => $timezoneIdentifier ]; } // Sort the array by offset, identifier ascending usort($tempTimezones, function ($a, $b) { return $a['offset'] === $b['offset'] ? strcmp($a['identifier'], $b['identifier']) : $a['offset'] - $b['offset']; }); $timezoneList = []; foreach ($tempTimezones as $tz) { $sign = $tz['offset'] > 0 ? '+' : '-'; $offset = gmdate('H:i', abs($tz['offset'])); $timezoneList[$tz['identifier']] = '(UTC ' . $sign . $offset . ') ' . $tz['identifier']; } return $timezoneList; } /** * Returns the theme options for the backend editor. * @return array */ public function getEditorThemeOptions() { $themeDir = new DirectoryIterator("modules/backend/formwidgets/codeeditor/assets/vendor/ace/"); $themes = []; // Iterate through the themes foreach ($themeDir as $node) { // If this file is a theme (starting by "theme-") if (!$node->isDir() && substr($node->getFileName(), 0, 6) == 'theme-') { // Remove the theme- prefix and the .js suffix, create an user friendly and capitalized name $themeId = substr($node->getFileName(), 6, -3); $themeName = ucwords(str_replace("_", " ", $themeId)); // Add the values to the themes array if ($themeId != static::DEFAULT_THEME) { $themes[$themeId] = $themeName; } } } // Sort the theme alphabetically, and push the default theme asort($themes); return [static::DEFAULT_THEME => ucwords(static::DEFAULT_THEME)] + $themes; } }
1
12,885
Please remove this extra line of whitespace
octobercms-october
php
@@ -83,14 +83,15 @@ class ProductSearchExportWithFilterRepository /** * @param int $domainId * @param string $locale - * @param int $startFrom + * @param int $lastProcessedId * @param int $batchSize * @return array */ - public function getProductsData(int $domainId, string $locale, int $startFrom, int $batchSize): array + public function getProductsData(int $domainId, string $locale, int $lastProcessedId, int $batchSize): array { $queryBuilder = $this->createQueryBuilder($domainId) - ->setFirstResult($startFrom) + ->andWhere('p.id > :lastProcessedId') + ->setParameter('lastProcessedId', $lastProcessedId) ->setMaxResults($batchSize); $query = $queryBuilder->getQuery();
1
<?php namespace Shopsys\FrameworkBundle\Model\Product\Search\Export; use Doctrine\ORM\EntityManagerInterface; use Doctrine\ORM\Query\Expr\Join; use Doctrine\ORM\QueryBuilder; use Shopsys\FrameworkBundle\Component\Domain\Domain; use Shopsys\FrameworkBundle\Component\Paginator\QueryPaginator; use Shopsys\FrameworkBundle\Component\Router\FriendlyUrl\FriendlyUrlFacade; use Shopsys\FrameworkBundle\Component\Router\FriendlyUrl\FriendlyUrlRepository; use Shopsys\FrameworkBundle\Model\Product\Parameter\ParameterRepository; use Shopsys\FrameworkBundle\Model\Product\Pricing\ProductPrice; use Shopsys\FrameworkBundle\Model\Product\Product; use Shopsys\FrameworkBundle\Model\Product\ProductFacade; use Shopsys\FrameworkBundle\Model\Product\ProductVisibility; use Shopsys\FrameworkBundle\Model\Product\ProductVisibilityRepository; class ProductSearchExportWithFilterRepository { /** * @var \Doctrine\ORM\EntityManagerInterface */ protected $em; /** * @var \Shopsys\FrameworkBundle\Model\Product\Parameter\ParameterRepository */ protected $parameterRepository; /** * @var \Shopsys\FrameworkBundle\Model\Product\ProductFacade */ protected $productFacade; /** * @var \Shopsys\FrameworkBundle\Component\Router\FriendlyUrl\FriendlyUrlRepository */ protected $friendlyUrlRepository; /** * @var \Shopsys\FrameworkBundle\Component\Domain\Domain */ protected $domain; /** * @var \Shopsys\FrameworkBundle\Model\Product\ProductVisibilityRepository */ protected $productVisibilityRepository; /** * @var \Shopsys\FrameworkBundle\Component\Router\FriendlyUrl\FriendlyUrlFacade */ protected $friendlyUrlFacade; /** * @param \Doctrine\ORM\EntityManagerInterface $em * @param \Shopsys\FrameworkBundle\Model\Product\Parameter\ParameterRepository $parameterRepository * @param \Shopsys\FrameworkBundle\Model\Product\ProductFacade $productFacade * @param \Shopsys\FrameworkBundle\Component\Router\FriendlyUrl\FriendlyUrlRepository $friendlyUrlRepository * @param \Shopsys\FrameworkBundle\Component\Domain\Domain $domain * @param \Shopsys\FrameworkBundle\Model\Product\ProductVisibilityRepository $productVisibilityRepository * @param \Shopsys\FrameworkBundle\Component\Router\FriendlyUrl\FriendlyUrlFacade $friendlyUrlFacade */ public function __construct( EntityManagerInterface $em, ParameterRepository $parameterRepository, ProductFacade $productFacade, FriendlyUrlRepository $friendlyUrlRepository, Domain $domain, ProductVisibilityRepository $productVisibilityRepository, FriendlyUrlFacade $friendlyUrlFacade ) { $this->parameterRepository = $parameterRepository; $this->productFacade = $productFacade; $this->em = $em; $this->friendlyUrlRepository = $friendlyUrlRepository; $this->domain = $domain; $this->productVisibilityRepository = $productVisibilityRepository; $this->friendlyUrlFacade = $friendlyUrlFacade; } /** * @param int $domainId * @param string $locale * @param int $startFrom * @param int $batchSize * @return array */ public function getProductsData(int $domainId, string $locale, int $startFrom, int $batchSize): array { $queryBuilder = $this->createQueryBuilder($domainId) ->setFirstResult($startFrom) ->setMaxResults($batchSize); $query = $queryBuilder->getQuery(); $results = []; /** @var \Shopsys\FrameworkBundle\Model\Product\Product $product */ foreach ($query->getResult() as $product) { $results[] = $this->extractResult($product, $domainId, $locale); } return $results; } /** * @param int $domainId * @param string $locale * @param int[] $productIds * @return array */ public function getProductsDataForIds(int $domainId, string $locale, array $productIds): array { $queryBuilder = $this->createQueryBuilder($domainId) ->andWhere('p.id IN (:productIds)') ->setParameter('productIds', $productIds); $query = $queryBuilder->getQuery(); $result = []; /** @var \Shopsys\FrameworkBundle\Model\Product\Product $product */ foreach ($query->getResult() as $product) { $result[] = $this->extractResult($product, $domainId, $locale); } return $result; } /** * @param int $domainId * @return int */ public function getProductTotalCountForDomain(int $domainId): int { $result = new QueryPaginator($this->createQueryBuilder($domainId)); return $result->getTotalCount(); } /** * @param \Shopsys\FrameworkBundle\Model\Product\Product $product * @param int $domainId * @param string $locale * @return array */ protected function extractResult(Product $product, int $domainId, string $locale): array { $flagIds = $this->extractFlags($product); $categoryIds = $this->extractCategories($domainId, $product); $parameters = $this->extractParameters($locale, $product); $prices = $this->extractPrices($domainId, $product); $visibility = $this->extractVisibility($domainId, $product); $detailUrl = $this->extractDetailUrl($domainId, $product); $variantIds = $this->extractVariantIds($product); return [ 'id' => $product->getId(), 'catnum' => $product->getCatnum(), 'partno' => $product->getPartno(), 'ean' => $product->getEan(), 'name' => $product->getName($locale), 'description' => $product->getDescription($domainId), 'short_description' => $product->getShortDescription($domainId), 'brand' => $product->getBrand() ? $product->getBrand()->getId() : '', 'flags' => $flagIds, 'categories' => $categoryIds, 'in_stock' => $product->getCalculatedAvailability()->getDispatchTime() === 0, 'prices' => $prices, 'parameters' => $parameters, 'ordering_priority' => $product->getOrderingPriority(), 'calculated_selling_denied' => $product->getCalculatedSellingDenied(), 'selling_denied' => $product->isSellingDenied(), 'availability' => $product->getCalculatedAvailability()->getName($locale), 'is_main_variant' => $product->isMainVariant(), 'detail_url' => $detailUrl, 'visibility' => $visibility, 'uuid' => $product->getUuid(), 'unit' => $product->getUnit()->getName($locale), 'is_using_stock' => $product->isUsingStock(), 'stock_quantity' => $product->getStockQuantity(), 'variants' => $variantIds, 'main_variant' => $product->isVariant() ? $product->getMainVariant()->getId() : null, ]; } /** * @param \Shopsys\FrameworkBundle\Model\Product\Product $product * @return int[] */ protected function extractVariantIds(Product $product): array { $variantIds = []; foreach ($product->getVariants() as $variant) { $variantIds[] = $variant->getId(); } return $variantIds; } /** * @param int $domainId * @param \Shopsys\FrameworkBundle\Model\Product\Product $product * @return string */ protected function extractDetailUrl(int $domainId, Product $product): string { $friendlyUrl = $this->friendlyUrlRepository->getMainFriendlyUrl($domainId, 'front_product_detail', $product->getId()); return $this->friendlyUrlFacade->getAbsoluteUrlByFriendlyUrl($friendlyUrl); } /** * @param int $domainId * @return \Doctrine\ORM\QueryBuilder */ protected function createQueryBuilder(int $domainId): QueryBuilder { $queryBuilder = $this->em->createQueryBuilder() ->select('p') ->from(Product::class, 'p') ->where('p.variantType != :variantTypeVariant') ->join(ProductVisibility::class, 'prv', Join::WITH, 'prv.product = p.id') ->andWhere('prv.domainId = :domainId') ->andWhere('prv.visible = TRUE') ->groupBy('p.id') ->orderBy('p.id'); $queryBuilder->setParameter('domainId', $domainId) ->setParameter('variantTypeVariant', Product::VARIANT_TYPE_VARIANT); return $queryBuilder; } /** * @param \Shopsys\FrameworkBundle\Model\Product\Product $product * @return int[] */ protected function extractFlags(Product $product): array { $flagIds = []; foreach ($product->getFlags() as $flag) { $flagIds[] = $flag->getId(); } return $flagIds; } /** * @param int $domainId * @param \Shopsys\FrameworkBundle\Model\Product\Product $product * @return int[] */ protected function extractCategories(int $domainId, Product $product): array { $categoryIds = []; foreach ($product->getCategoriesIndexedByDomainId()[$domainId] as $category) { $categoryIds[] = $category->getId(); } return $categoryIds; } /** * @param string $locale * @param \Shopsys\FrameworkBundle\Model\Product\Product $product * @return array */ protected function extractParameters(string $locale, Product $product): array { $parameters = []; $productParameterValues = $this->parameterRepository->getProductParameterValuesByProductSortedByName($product, $locale); foreach ($productParameterValues as $productParameterValue) { $parameter = $productParameterValue->getParameter(); $parameterValue = $productParameterValue->getValue(); if ($parameter->getName($locale) !== null && $parameterValue->getLocale() === $locale) { $parameters[] = [ 'parameter_id' => $parameter->getId(), 'parameter_value_id' => $parameterValue->getId(), ]; } } return $parameters; } /** * @param int $domainId * @param \Shopsys\FrameworkBundle\Model\Product\Product $product * @return array */ protected function extractPrices(int $domainId, Product $product): array { $prices = []; /** @var \Shopsys\FrameworkBundle\Model\Product\Pricing\ProductSellingPrice[] $productSellingPrices */ $productSellingPrices = $this->productFacade->getAllProductSellingPricesByDomainId($product, $domainId); foreach ($productSellingPrices as $productSellingPrice) { $sellingPrice = $productSellingPrice->getSellingPrice(); $priceFrom = false; if ($sellingPrice instanceof ProductPrice) { $priceFrom = $sellingPrice->isPriceFrom(); } $prices[] = [ 'pricing_group_id' => $productSellingPrice->getPricingGroup()->getId(), 'price_with_vat' => (float)$sellingPrice->getPriceWithVat()->getAmount(), 'price_without_vat' => (float)$sellingPrice->getPriceWithoutVat()->getAmount(), 'vat' => (float)$sellingPrice->getVatAmount()->getAmount(), 'price_from' => $priceFrom, ]; } return $prices; } /** * @param int $domainId * @param \Shopsys\FrameworkBundle\Model\Product\Product $product * @return array */ protected function extractVisibility(int $domainId, Product $product): array { $visibility = []; foreach ($this->productVisibilityRepository->findProductVisibilitiesByDomainIdAndProduct($domainId, $product) as $productVisibility) { $visibility[] = [ 'pricing_group_id' => $productVisibility->getPricingGroup()->getId(), 'visible' => $productVisibility->isVisible(), ]; } return $visibility; } }
1
21,096
maybe it's time to rename `ProductSearchExportWithFilter` to something better, what do you think?
shopsys-shopsys
php
@@ -49,11 +49,11 @@ func (agent *ecsAgent) appendTaskEIACapabilities(capabilities []*ecs.Attribute) } func (agent *ecsAgent) appendFirelensFluentdCapabilities(capabilities []*ecs.Attribute) []*ecs.Attribute { - return capabilities + return appendNameOnlyAttribute(capabilities, attributePrefix+capabilityFirelensFluentd) } func (agent *ecsAgent) appendFirelensFluentbitCapabilities(capabilities []*ecs.Attribute) []*ecs.Attribute { - return capabilities + return appendNameOnlyAttribute(capabilities, attributePrefix+capabilityFirelensFluentbit) } func (agent *ecsAgent) appendEFSCapabilities(capabilities []*ecs.Attribute) []*ecs.Attribute {
1
// +build windows // Copyright 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 app import ( "github.com/aws/amazon-ecs-agent/agent/ecs_client/model/ecs" "github.com/aws/amazon-ecs-agent/agent/ecscni" "github.com/aws/amazon-ecs-agent/agent/taskresource/volume" "github.com/aws/aws-sdk-go/aws" "github.com/cihub/seelog" ) func (agent *ecsAgent) appendVolumeDriverCapabilities(capabilities []*ecs.Attribute) []*ecs.Attribute { // "local" is default docker driver return appendNameOnlyAttribute(capabilities, attributePrefix+capabilityDockerPluginInfix+volume.DockerLocalVolumeDriver) } func (agent *ecsAgent) appendNvidiaDriverVersionAttribute(capabilities []*ecs.Attribute) []*ecs.Attribute { return capabilities } func (agent *ecsAgent) appendENITrunkingCapabilities(capabilities []*ecs.Attribute) []*ecs.Attribute { return capabilities } func (agent *ecsAgent) appendPIDAndIPCNamespaceSharingCapabilities(capabilities []*ecs.Attribute) []*ecs.Attribute { return capabilities } func (agent *ecsAgent) appendAppMeshCapabilities(capabilities []*ecs.Attribute) []*ecs.Attribute { return capabilities } func (agent *ecsAgent) appendTaskEIACapabilities(capabilities []*ecs.Attribute) []*ecs.Attribute { return capabilities } func (agent *ecsAgent) appendFirelensFluentdCapabilities(capabilities []*ecs.Attribute) []*ecs.Attribute { return capabilities } func (agent *ecsAgent) appendFirelensFluentbitCapabilities(capabilities []*ecs.Attribute) []*ecs.Attribute { return capabilities } func (agent *ecsAgent) appendEFSCapabilities(capabilities []*ecs.Attribute) []*ecs.Attribute { return capabilities } func (agent *ecsAgent) appendFirelensLoggingDriverCapabilities(capabilities []*ecs.Attribute) []*ecs.Attribute { return capabilities } func (agent *ecsAgent) appendFirelensConfigCapabilities(capabilities []*ecs.Attribute) []*ecs.Attribute { return capabilities } func (agent *ecsAgent) appendGMSACapabilities(capabilities []*ecs.Attribute) []*ecs.Attribute { if agent.cfg.GMSACapable { return appendNameOnlyAttribute(capabilities, attributePrefix+capabilityGMSA) } return capabilities } func (agent *ecsAgent) appendEFSVolumePluginCapabilities(capabilities []*ecs.Attribute, pluginCapability string) []*ecs.Attribute { return capabilities } func (agent *ecsAgent) appendIPv6Capability(capabilities []*ecs.Attribute) []*ecs.Attribute { return capabilities } func (agent *ecsAgent) appendFSxWindowsFileServerCapabilities(capabilities []*ecs.Attribute) []*ecs.Attribute { if agent.cfg.FSxWindowsFileServerCapable { return appendNameOnlyAttribute(capabilities, attributePrefix+capabilityFSxWindowsFileServer) } return capabilities } // getTaskENIPluginVersionAttribute returns the version information of the ECS // CNI plugins. It just executes the ECSVPCENIPluginName plugin to get the Version information. // Currently, only this plugin is used by ECS Windows for awsvpc mode. func (agent *ecsAgent) getTaskENIPluginVersionAttribute() (*ecs.Attribute, error) { version, err := agent.cniClient.Version(ecscni.ECSVPCENIPluginExecutable) if err != nil { seelog.Warnf( "Unable to determine the version of the plugin '%s': %v", ecscni.ECSVPCENIPluginName, err) return nil, err } return &ecs.Attribute{ Name: aws.String(attributePrefix + cniPluginVersionSuffix), Value: aws.String(version), }, nil }
1
26,271
Instead of adding new code here - can you move these methods to agent_capability.go, so the same is used for unix and windows as well. this will need removal of these methods from agent_capability_unix.go as well.
aws-amazon-ecs-agent
go
@@ -648,7 +648,7 @@ def log(package): str(entry.get('tags', [])), str(entry.get('versions', [])))) _print_table(table) -def push(package, is_public=False, is_team=False, reupload=False): +def push(package, hash=None, is_public=False, is_team=False, reupload=False): """ Push a Quilt data package to the server """
1
# -*- coding: utf-8 -*- """ Command line parsing and command dispatch """ from __future__ import print_function from builtins import input # pylint:disable=W0622 from datetime import datetime from functools import partial import hashlib import json import os import platform import re from shutil import rmtree, copyfile import socket import stat import subprocess import sys import tempfile import time import yaml import numpy as np from packaging.version import Version import pandas as pd import pkg_resources import requests from six import itervalues, string_types from six.moves.urllib.parse import urlparse, urlunparse from tqdm import tqdm from .build import (build_package, build_package_from_contents, generate_build_file, generate_contents, get_or_create_package, BuildException, load_yaml) from .compat import pathlib from .const import DEFAULT_BUILDFILE, DTIMEF, QuiltException, SYSTEM_METADATA, TargetType from .core import (LATEST_TAG, GroupNode, RootNode, decode_node, encode_node, find_object_hashes, hash_contents) from .data_transfer import download_fragments, upload_fragments from .store import PackageStore, StoreException from .util import (BASE_DIR, gzip_compress, is_nodename, fs_link, parse_package as parse_package_util, parse_package_extended as parse_package_extended_util) from ..imports import _from_core_node from .. import nodes DEFAULT_REGISTRY_URL = 'https://pkg.quiltdata.com' GIT_URL_RE = re.compile(r'(?P<url>http[s]?://[\w./~_-]+\.git)(?:@(?P<branch>[\w_-]+))?') LOG_TIMEOUT = 3 # 3 seconds VERSION = pkg_resources.require('quilt')[0].version class CommandException(QuiltException): """ Exception class for all command-related failures. """ pass class HTTPResponseException(CommandException): def __init__(self, message, response): super(HTTPResponseException, self).__init__(message) self.response = response _registry_url = None def parse_package_extended(identifier): #TODO: Unwrap this and modify 'util' version to raise QuiltException try: return parse_package_extended_util(identifier) except ValueError: pkg_format = '[team:]owner/package_name/path[:v:<version> or :t:<tag> or :h:<hash>]' raise CommandException("Specify package as %s." % pkg_format) def parse_package(name, allow_subpath=False): #TODO: Unwrap this and modify 'util' version to raise QuiltException and call check_name() try: if allow_subpath: team, owner, pkg, subpath = parse_package_util(name, allow_subpath) else: team, owner, pkg = parse_package_util(name, allow_subpath) subpath = None except ValueError: pkg_format = '[team:]owner/package_name/path' if allow_subpath else '[team:]owner/package_name' raise CommandException("Specify package as %s." % pkg_format) try: PackageStore.check_name(team, owner, pkg, subpath) except StoreException as ex: raise CommandException(str(ex)) if allow_subpath: return team, owner, pkg, subpath return team, owner, pkg def _load_config(): config_path = os.path.join(BASE_DIR, 'config.json') if os.path.exists(config_path): with open(config_path) as fd: return json.load(fd) return {} def _save_config(cfg): if not os.path.exists(BASE_DIR): os.makedirs(BASE_DIR) config_path = os.path.join(BASE_DIR, 'config.json') with open(config_path, 'w') as fd: json.dump(cfg, fd) def _load_auth(): auth_path = os.path.join(BASE_DIR, 'auth.json') if os.path.exists(auth_path): with open(auth_path) as fd: auth = json.load(fd) if 'access_token' in auth: # Old format; ignore it. auth = {} return auth return {} def _save_auth(cfg): if not os.path.exists(BASE_DIR): os.makedirs(BASE_DIR) auth_path = os.path.join(BASE_DIR, 'auth.json') with open(auth_path, 'w') as fd: os.chmod(auth_path, stat.S_IRUSR | stat.S_IWUSR) json.dump(cfg, fd) def get_registry_url(team): if team is not None: return "https://%s-registry.team.quiltdata.com" % team global _registry_url if _registry_url is not None: return _registry_url # Env variable; overrides the config. url = os.environ.get('QUILT_PKG_URL') if url is None: # Config file (generated by `quilt config`). cfg = _load_config() url = cfg.get('registry_url', '') # '' means default URL. _registry_url = url or DEFAULT_REGISTRY_URL return _registry_url def config(): answer = input("Please enter the URL for your custom Quilt registry (ask your administrator),\n" "or leave this line blank to use the default registry: ") if answer: url = urlparse(answer.rstrip('/')) if (url.scheme not in ['http', 'https'] or not url.netloc or url.path or url.params or url.query or url.fragment): raise CommandException("Invalid URL: %s" % answer) canonical_url = urlunparse(url) else: # When saving the config, store '' instead of the actual URL in case we ever change it. canonical_url = '' cfg = _load_config() cfg['registry_url'] = canonical_url _save_config(cfg) # Clear the cached URL. global _registry_url _registry_url = None def _update_auth(team, refresh_token, timeout=None): response = requests.post("%s/api/token" % get_registry_url(team), timeout=timeout, data=dict( refresh_token=refresh_token, )) if response.status_code != requests.codes.ok: raise CommandException("Authentication error: %s" % response.status_code) data = response.json() error = data.get('error') if error is not None: raise CommandException("Failed to log in: %s" % error) return dict( team=team, refresh_token=data['refresh_token'], access_token=data['access_token'], expires_at=data['expires_at'] ) def _handle_response(team, resp, **kwargs): _ = kwargs # unused pylint:disable=W0613 if resp.status_code == requests.codes.unauthorized: raise CommandException( "Authentication failed. Run `quilt login%s` again." % (' ' + team if team else '') ) elif not resp.ok: try: data = resp.json() raise HTTPResponseException(data['message'], resp) except ValueError: raise HTTPResponseException("Unexpected failure: error %s" % resp.status_code, resp) def _create_auth(team, timeout=None): """ Reads the credentials, updates the access token if necessary, and returns it. """ url = get_registry_url(team) contents = _load_auth() auth = contents.get(url) if auth is not None: # If the access token expires within a minute, update it. if auth['expires_at'] < time.time() + 60: try: auth = _update_auth(team, auth['refresh_token'], timeout) except CommandException as ex: raise CommandException( "Failed to update the access token (%s). Run `quilt login%s` again." % (ex, ' ' + team if team else '') ) contents[url] = auth _save_auth(contents) return auth def _create_session(team, auth): """ Creates a session object to be used for `push`, `install`, etc. """ session = requests.Session() session.hooks.update(dict( response=partial(_handle_response, team) )) session.headers.update({ "Content-Type": "application/json", "Accept": "application/json", "User-Agent": "quilt-cli/%s (%s %s) %s/%s" % ( VERSION, platform.system(), platform.release(), platform.python_implementation(), platform.python_version() ) }) if auth is not None: session.headers["Authorization"] = "Bearer %s" % auth['access_token'] return session _sessions = {} # pylint:disable=C0103 def _get_session(team, timeout=None): """ Creates a session or returns an existing session. """ global _sessions # pylint:disable=C0103 session = _sessions.get(team) if session is None: auth = _create_auth(team, timeout) _sessions[team] = session = _create_session(team, auth) assert session is not None return session def _clear_session(team): global _sessions # pylint:disable=C0103 session = _sessions.pop(team, None) if session is not None: session.close() def _open_url(url): try: if sys.platform == 'win32': os.startfile(url) # pylint:disable=E1101 elif sys.platform == 'darwin': with open(os.devnull, 'r+') as null: subprocess.check_call(['open', url], stdin=null, stdout=null, stderr=null) else: with open(os.devnull, 'r+') as null: subprocess.check_call(['xdg-open', url], stdin=null, stdout=null, stderr=null) except Exception as ex: # pylint:disable=W0703 print("Failed to launch the browser: %s" % ex) def _match_hash(package, hash): team, owner, pkg, _ = parse_package(package, allow_subpath=True) session = _get_session(team) hash = hash.lower() if not (6 <= len(hash) <= 64): raise CommandException('Invalid hash of length {}: {!r}\n ' 'Ensure that the hash is between 6 and 64 characters.' .format(len(hash), hash)) # short-circuit for exact length if len(hash) == 64: return hash response = session.get( "{url}/api/log/{owner}/{pkg}/".format( url=get_registry_url(team), owner=owner, pkg=pkg ) ) matches = set(entry['hash'] for entry in response.json()['logs'] if entry['hash'].startswith(hash)) if len(matches) == 1: return matches.pop() if len(matches) > 1: # Sorting for consistency in testing, as well as visual comparison of hashes ambiguous = '\n'.join(sorted(matches)) raise CommandException( "Ambiguous hash for package {package}: {hash!r} matches the folowing hashes:\n\n{ambiguous}" .format(package=package, hash=hash, ambiguous=ambiguous)) raise CommandException("Invalid hash for package {package}: {hash}".format(package=package, hash=hash)) def _find_logged_in_team(): """ Find a team name in the auth credentials. There should be at most one, since we don't allow multiple team logins. """ contents = _load_auth() auth = next(itervalues(contents), {}) return auth.get('team') def _check_team_login(team): """ Disallow simultaneous public cloud and team logins. """ contents = _load_auth() for auth in itervalues(contents): existing_team = auth.get('team') if team and team != existing_team: raise CommandException( "Can't log in as team %r; log out first." % team ) elif not team and existing_team: raise CommandException( "Can't log in as a public user; log out from team %r first." % existing_team ) team_regex = re.compile('^[a-z]+$') def _check_team_id(team): if team is not None and team_regex.match(team) is None: raise CommandException( "Invalid team name: {team}. Lowercase letters only.".format(team=team) ) def _check_team_exists(team): """ Check that the team registry actually exists. """ if team is None: return hostname = '%s-registry.team.quiltdata.com' % team try: socket.gethostbyname(hostname) except IOError: try: # Do we have internet? socket.gethostbyname('quiltdata.com') except IOError: message = "Can't find quiltdata.com. Check your internet connection." else: message = "Unable to connect to registry. Is the team name %r correct?" % team raise CommandException(message) def login(team=None): """ Authenticate. Launches a web browser and asks the user for a token. """ _check_team_id(team) _check_team_exists(team) _check_team_login(team) login_url = "%s/login" % get_registry_url(team) print("Launching a web browser...") print("If that didn't work, please visit the following URL: %s" % login_url) _open_url(login_url) print() refresh_token = input("Enter the code from the webpage: ") login_with_token(refresh_token, team) def login_with_token(refresh_token, team=None): """ Authenticate using an existing token. """ # Get an access token and a new refresh token. _check_team_id(team) auth = _update_auth(team, refresh_token) url = get_registry_url(team) contents = _load_auth() contents[url] = auth _save_auth(contents) _clear_session(team) def logout(): """ Become anonymous. Useful for testing. """ # TODO revoke refresh token (without logging out of web sessions) if _load_auth(): _save_auth({}) else: print("Already logged out.") global _sessions # pylint:disable=C0103 _sessions = {} def generate(directory, outfilename=DEFAULT_BUILDFILE): """ Generate a build-file for quilt build from a directory of source files. """ try: buildfilepath = generate_build_file(directory, outfilename=outfilename) except BuildException as builderror: raise CommandException(str(builderror)) print("Generated build-file %s." % (buildfilepath)) def check(path=None, env='default'): """ Execute the checks: rules for a given build.yml file. """ # TODO: add files=<list of files> to check only a subset... # also useful for 'quilt build' to exclude certain files? # (if not, then require dry_run=True if files!=None/all) build("dry_run/dry_run", path=path, dry_run=True, env=env) def _clone_git_repo(url, branch, dest): cmd = ['git', 'clone', '-q', '--depth=1'] if branch: cmd += ['-b', branch] cmd += [url, dest] subprocess.check_call(cmd) def _log(team, **kwargs): # TODO(dima): Save logs to a file, then send them when we get a chance. cfg = _load_config() if cfg.get('disable_analytics'): return session = None try: session = _get_session(team, timeout=LOG_TIMEOUT) # Disable error handling. orig_response_hooks = session.hooks.pop('response') session.post( "{url}/api/log".format( url=get_registry_url(team), ), data=json.dumps([kwargs]), timeout=LOG_TIMEOUT, ) except requests.exceptions.RequestException: # Ignore logging errors. pass finally: # restore disabled error-handling if session: session.hooks['response'] = orig_response_hooks def build(package, path=None, dry_run=False, env='default', force=False, build_file=False): """ Compile a Quilt data package, either from a build file or an existing package node. :param package: short package specifier, i.e. 'team:user/pkg' :param path: file path, git url, or existing package node """ # TODO: rename 'path' param to 'target'? team, _, _, subpath = parse_package(package, allow_subpath=True) _check_team_id(team) logged_in_team = _find_logged_in_team() if logged_in_team is not None and team is None and force is False: answer = input("You're logged in as a team member, but you aren't specifying " "a team for the package you're currently building. Maybe you meant:\n" "quilt build {team}:{package}\n" "Are you sure you want to continue? (y/N) ".format( team=logged_in_team, package=package)) if answer.lower() != 'y': return # Backward compatibility: if there's no subpath, we're building a top-level package, # so treat `path` as a build file, not as a data node. if not subpath: build_file = True package_hash = hashlib.md5(package.encode('utf-8')).hexdigest() try: _build_internal(package, path, dry_run, env, build_file) except Exception as ex: _log(team, type='build', package=package_hash, dry_run=dry_run, env=env, error=str(ex)) raise _log(team, type='build', package=package_hash, dry_run=dry_run, env=env) def _build_internal(package, path, dry_run, env, build_file): if build_file and isinstance(path, string_types): # is this a git url? is_git_url = GIT_URL_RE.match(path) if is_git_url: tmpdir = tempfile.mkdtemp() url = is_git_url.group('url') branch = is_git_url.group('branch') try: _clone_git_repo(url, branch, tmpdir) build_from_path(package, tmpdir, dry_run=dry_run, env=env) except Exception as exc: msg = "attempting git clone raised exception: {exc}" raise CommandException(msg.format(exc=exc)) finally: if os.path.exists(tmpdir): rmtree(tmpdir) else: build_from_path(package, path, dry_run=dry_run, env=env) elif isinstance(path, nodes.Node): assert not dry_run # TODO? build_from_node(package, path) elif isinstance(path, string_types + (pd.DataFrame, np.ndarray)): assert not dry_run # TODO? build_from_node(package, nodes.DataNode(None, None, path, {})) elif path is None: assert not dry_run # TODO? build_from_node(package, nodes.GroupNode({})) else: raise ValueError("Expected a GroupNode, path, git URL, DataFrame, ndarray, or None, but got %r" % path) def build_from_node(package, node): """ Compile a Quilt data package from an existing package node. """ team, owner, pkg, subpath = parse_package(package, allow_subpath=True) _check_team_id(team) store = PackageStore() pkg_root = get_or_create_package(store, team, owner, pkg, subpath) if not subpath and not isinstance(node, nodes.GroupNode): raise CommandException("Top-level node must be a group") def _process_node(node, path): if not isinstance(node._meta, dict): raise CommandException( "Error in %s: value must be a dictionary" % '.'.join(path + ['_meta']) ) meta = dict(node._meta) system_meta = meta.pop(SYSTEM_METADATA, {}) if not isinstance(system_meta, dict): raise CommandException( "Error in %s: %s overwritten. %s is a reserved metadata key. Try a different key." % ('.'.join(path + ['_meta']), SYSTEM_METADATA, SYSTEM_METADATA) ) if isinstance(node, nodes.GroupNode): store.add_to_package_group(pkg_root, path, meta) for key, child in node._items(): _process_node(child, path + [key]) elif isinstance(node, nodes.DataNode): # TODO: Reuse existing fragments if we have them. data = node._data() filepath = system_meta.get('filepath') transform = system_meta.get('transform') if isinstance(data, pd.DataFrame): store.add_to_package_df(pkg_root, data, path, TargetType.PANDAS, filepath, transform, meta) elif isinstance(data, np.ndarray): store.add_to_package_numpy(pkg_root, data, path, TargetType.NUMPY, filepath, transform, meta) elif isinstance(data, string_types): store.add_to_package_file(pkg_root, data, path, TargetType.FILE, filepath, transform, meta) else: assert False, "Unexpected data type: %r" % data else: assert False, "Unexpected node type: %r" % node try: _process_node(node, subpath) except StoreException as ex: raise CommandException("Failed to build the package: %s" % ex) store.save_package_contents(pkg_root, team, owner, pkg) def build_from_path(package, path, dry_run=False, env='default', outfilename=DEFAULT_BUILDFILE): """ Compile a Quilt data package from a build file. Path can be a directory, in which case the build file will be generated automatically. """ team, owner, pkg, subpath = parse_package(package, allow_subpath=True) if not os.path.exists(path): raise CommandException("%s does not exist." % path) try: if os.path.isdir(path): buildpath = os.path.join(path, outfilename) if os.path.exists(buildpath): raise CommandException( "Build file already exists. Run `quilt build %r` instead." % buildpath ) contents = generate_contents(path, outfilename) build_package_from_contents(team, owner, pkg, subpath, path, contents, dry_run=dry_run, env=env) else: build_package(team, owner, pkg, subpath, path, dry_run=dry_run, env=env) if not dry_run: print("Built %s successfully." % package) except BuildException as ex: raise CommandException("Failed to build the package: %s" % ex) def log(package): """ List all of the changes to a package on the server. """ team, owner, pkg = parse_package(package) session = _get_session(team) response = session.get( "{url}/api/log/{owner}/{pkg}/".format( url=get_registry_url(team), owner=owner, pkg=pkg ) ) table = [("Hash", "Pushed", "Author", "Tags", "Versions")] for entry in reversed(response.json()['logs']): ugly = datetime.fromtimestamp(entry['created']) nice = ugly.strftime("%Y-%m-%d %H:%M:%S") table.append((entry['hash'], nice, entry['author'], str(entry.get('tags', [])), str(entry.get('versions', [])))) _print_table(table) def push(package, is_public=False, is_team=False, reupload=False): """ Push a Quilt data package to the server """ team, owner, pkg, subpath = parse_package(package, allow_subpath=True) _check_team_id(team) session = _get_session(team) store, pkgroot = PackageStore.find_package(team, owner, pkg) if pkgroot is None: raise CommandException("Package {package} not found.".format(package=package)) pkghash = hash_contents(pkgroot) contents = pkgroot for component in subpath: try: contents = contents.children[component] except (AttributeError, KeyError): raise CommandException("Invalid subpath: %r" % component) def _push_package(dry_run=False, sizes=dict()): data = json.dumps(dict( dry_run=dry_run, is_public=is_public, is_team=is_team, contents=contents, description="", # TODO sizes=sizes ), default=encode_node) compressed_data = gzip_compress(data.encode('utf-8')) if subpath: return session.post( "{url}/api/package_update/{owner}/{pkg}/{subpath}".format( url=get_registry_url(team), owner=owner, pkg=pkg, subpath='/'.join(subpath) ), data=compressed_data, headers={ 'Content-Encoding': 'gzip' } ) else: return session.put( "{url}/api/package/{owner}/{pkg}/{hash}".format( url=get_registry_url(team), owner=owner, pkg=pkg, hash=pkghash ), data=compressed_data, headers={ 'Content-Encoding': 'gzip' } ) print("Fetching upload URLs from the registry...") resp = _push_package(dry_run=True) obj_urls = resp.json()['upload_urls'] assert set(obj_urls) == set(find_object_hashes(contents)) obj_sizes = { obj_hash: os.path.getsize(store.object_path(obj_hash)) for obj_hash in obj_urls } success = upload_fragments(store, obj_urls, obj_sizes, reupload=reupload) if not success: raise CommandException("Failed to upload fragments") print("Uploading package metadata...") resp = _push_package(sizes=obj_sizes) package_url = resp.json()['package_url'] if not subpath: # Update the latest tag. print("Updating the 'latest' tag...") session.put( "{url}/api/tag/{owner}/{pkg}/{tag}".format( url=get_registry_url(team), owner=owner, pkg=pkg, tag=LATEST_TAG ), data=json.dumps(dict( hash=pkghash )) ) print("Push complete. %s is live:\n%s" % (package, package_url)) def version_list(package): """ List the versions of a package. """ team, owner, pkg = parse_package(package) session = _get_session(team) response = session.get( "{url}/api/version/{owner}/{pkg}/".format( url=get_registry_url(team), owner=owner, pkg=pkg ) ) for version in response.json()['versions']: print("%s: %s" % (version['version'], version['hash'])) def version_add(package, version, pkghash, force=False): """ Add a new version for a given package hash. Version format needs to follow PEP 440. Versions are permanent - once created, they cannot be modified or deleted. """ team, owner, pkg = parse_package(package) session = _get_session(team) try: Version(version) except ValueError: url = "https://www.python.org/dev/peps/pep-0440/#examples-of-compliant-version-schemes" raise CommandException( "Invalid version format; see %s" % url ) if not force: answer = input("Versions cannot be modified or deleted; are you sure? (y/n) ") if answer.lower() != 'y': return session.put( "{url}/api/version/{owner}/{pkg}/{version}".format( url=get_registry_url(team), owner=owner, pkg=pkg, version=version ), data=json.dumps(dict( hash=_match_hash(package, pkghash) )) ) def tag_list(package): """ List the tags of a package. """ team, owner, pkg = parse_package(package) session = _get_session(team) response = session.get( "{url}/api/tag/{owner}/{pkg}/".format( url=get_registry_url(team), owner=owner, pkg=pkg ) ) for tag in response.json()['tags']: print("%s: %s" % (tag['tag'], tag['hash'])) def tag_add(package, tag, pkghash): """ Add a new tag for a given package hash. Unlike versions, tags can have an arbitrary format, and can be modified and deleted. When a package is pushed, it gets the "latest" tag. """ team, owner, pkg = parse_package(package) session = _get_session(team) session.put( "{url}/api/tag/{owner}/{pkg}/{tag}".format( url=get_registry_url(team), owner=owner, pkg=pkg, tag=tag ), data=json.dumps(dict( hash=_match_hash(package, pkghash) )) ) def tag_remove(package, tag): """ Delete a tag. """ team, owner, pkg = parse_package(package) session = _get_session(team) session.delete( "{url}/api/tag/{owner}/{pkg}/{tag}".format( url=get_registry_url(team), owner=owner, pkg=pkg, tag=tag ) ) def install_via_requirements(requirements_str, force=False): """ Download multiple Quilt data packages via quilt.xml requirements file. """ if requirements_str[0] == '@': path = requirements_str[1:] if os.path.isfile(path): yaml_data = load_yaml(path) if 'packages' not in yaml_data.keys(): raise CommandException('Error in {filename}: missing "packages" node'.format(filename=path)) else: raise CommandException("Requirements file not found: {filename}".format(filename=path)) else: yaml_data = yaml.safe_load(requirements_str) for pkginfo in yaml_data['packages']: info = parse_package_extended(pkginfo) install(info.full_name, info.hash, info.version, info.tag, force=force) def install(package, hash=None, version=None, tag=None, force=False, meta_only=False): """ Download a Quilt data package from the server and install locally. At most one of `hash`, `version`, or `tag` can be given. If none are given, `tag` defaults to "latest". `package` may be a node tree - in which case, its fragments get downloaded. No other parameters are allowed. """ if isinstance(package, nodes.Node): if not (hash is version is tag is None and force is meta_only is False): raise ValueError("Parameters not allowed when installing a node") _materialize(package) return if hash is version is tag is None: tag = LATEST_TAG # @filename ==> read from file # newline = multiple lines ==> multiple requirements package = package.strip() if len(package) == 0: raise CommandException("package name is empty.") if package[0] == '@' or '\n' in package: return install_via_requirements(package, force=force) assert [hash, version, tag].count(None) == 2 team, owner, pkg, subpath = parse_package(package, allow_subpath=True) _check_team_id(team) session = _get_session(team) store = PackageStore() existing_pkg = store.get_package(team, owner, pkg) print("Downloading package metadata...") try: if version is not None: response = session.get( "{url}/api/version/{owner}/{pkg}/{version}".format( url=get_registry_url(team), owner=owner, pkg=pkg, version=version ) ) pkghash = response.json()['hash'] elif tag is not None: response = session.get( "{url}/api/tag/{owner}/{pkg}/{tag}".format( url=get_registry_url(team), owner=owner, pkg=pkg, tag=tag ) ) pkghash = response.json()['hash'] else: pkghash = _match_hash(package, hash) except HTTPResponseException as e: logged_in_team = _find_logged_in_team() if (team is None and logged_in_team is not None and e.response.status_code == requests.codes.not_found): raise CommandException("Package {owner}/{pkg} does not exist. " "Maybe you meant {team}:{owner}/{pkg}?".format( owner=owner, pkg=pkg, team=logged_in_team)) else: raise assert pkghash is not None response = session.get( "{url}/api/package/{owner}/{pkg}/{hash}".format( url=get_registry_url(team), owner=owner, pkg=pkg, hash=pkghash ), params=dict( subpath='/'.join(subpath), meta_only='true' if meta_only else '' ) ) assert response.ok # other responses handled by _handle_response if existing_pkg is not None and not force: print("{package} already installed.".format(package=package)) overwrite = input("Overwrite? (y/n) ") if overwrite.lower() != 'y': return dataset = response.json(object_hook=decode_node) contents = dataset['contents'] # Verify contents hash if pkghash != hash_contents(contents): raise CommandException("Mismatched hash. Try again.") # TODO: Shouldn't need this? At least don't need the contents store.install_package(team, owner, pkg, contents) obj_urls = dataset['urls'] obj_sizes = dataset['sizes'] # Skip the objects we already have for obj_hash in list(obj_urls): if os.path.exists(store.object_path(obj_hash)): del obj_urls[obj_hash] del obj_sizes[obj_hash] if obj_urls: success = download_fragments(store, obj_urls, obj_sizes) if not success: raise CommandException("Failed to download fragments") else: print("Fragments already downloaded") store.save_package_contents(contents, team, owner, pkg) def _materialize(node): store = PackageStore() hashes = set() stack = [node] while stack: obj = stack.pop() if isinstance(obj, nodes.GroupNode): stack.extend(child for name, child in obj._items()) else: hashes.update(obj._hashes or []) # May be empty for nodes created locally missing_hashes = {obj_hash for obj_hash in hashes if not os.path.exists(store.object_path(obj_hash))} if missing_hashes: print("Requesting %d signed URLs..." % len(missing_hashes)) teams = {None, _find_logged_in_team()} obj_urls = dict() obj_sizes = dict() for team in teams: session = _get_session(team) response = session.post( "{url}/api/get_objects".format(url=get_registry_url(team)), json=list(missing_hashes) ) data = response.json() obj_urls.update(data['urls']) obj_sizes.update(data['sizes']) if len(obj_urls) != len(missing_hashes): not_found = sorted(missing_hashes - set(obj_urls)) raise CommandException("Unable to download the following hashes: %s" % ', '.join(not_found)) success = download_fragments(store, obj_urls, obj_sizes) if not success: raise CommandException("Failed to download fragments") else: print("Fragments already downloaded") def access_list(package): """ Print list of users who can access a package. """ team, owner, pkg = parse_package(package) session = _get_session(team) lookup_url = "{url}/api/access/{owner}/{pkg}/".format(url=get_registry_url(team), owner=owner, pkg=pkg) response = session.get(lookup_url) data = response.json() users = data['users'] print('\n'.join(users)) def access_add(package, user): """ Add access """ team, owner, pkg = parse_package(package) session = _get_session(team) session.put("%s/api/access/%s/%s/%s" % (get_registry_url(team), owner, pkg, user)) print(u'Access added for %s' % user) def access_remove(package, user): """ Remove access """ team, owner, pkg = parse_package(package) session = _get_session(team) session.delete("%s/api/access/%s/%s/%s" % (get_registry_url(team), owner, pkg, user)) print(u'Access removed for %s' % user) def delete(package): """ Delete a package from the server. Irreversibly deletes the package along with its history, tags, versions, etc. """ team, owner, pkg = parse_package(package) answer = input( "Are you sure you want to delete this package and its entire history? " "Type '%s' to confirm: " % package ) if answer != package: print("Not deleting.") return 1 session = _get_session(team) session.delete("%s/api/package/%s/%s/" % (get_registry_url(team), owner, pkg)) print("Deleted.") def search(query, team=None): """ Search for packages """ if team is None: team = _find_logged_in_team() if team is not None: session = _get_session(team) response = session.get("%s/api/search/" % get_registry_url(team), params=dict(q=query)) print("* Packages in team %s" % team) packages = response.json()['packages'] for pkg in packages: print(("%s:" % team) + ("%(owner)s/%(name)s" % pkg)) if len(packages) == 0: print("(No results)") print("* Packages in public cloud") public_session = _get_session(None) response = public_session.get("%s/api/search/" % get_registry_url(None), params=dict(q=query)) packages = response.json()['packages'] for pkg in packages: print("%(owner)s/%(name)s" % pkg) if len(packages) == 0: print("(No results)") def ls(): # pylint:disable=C0103 """ List all installed Quilt data packages """ for pkg_dir in PackageStore.find_store_dirs(): print("%s" % pkg_dir) packages = PackageStore(pkg_dir).ls_packages() for package, tag, pkghash in sorted(packages): print("{0:30} {1:20} {2}".format(package, tag, pkghash)) def inspect(package): """ Inspect package details """ team, owner, pkg = parse_package(package) store, pkgroot = PackageStore.find_package(team, owner, pkg) if pkgroot is None: raise CommandException("Package {package} not found.".format(package=package)) def _print_children(children, prefix, path): for idx, (name, child) in enumerate(children): if idx == len(children) - 1: new_prefix = u"└─" new_child_prefix = u" " else: new_prefix = u"├─" new_child_prefix = u"│ " _print_node(child, prefix + new_prefix, prefix + new_child_prefix, name, path) def _print_node(node, prefix, child_prefix, name, path): name_prefix = u"─ " if isinstance(node, GroupNode): children = list(node.children.items()) if children: name_prefix = u"┬ " print(prefix + name_prefix + name) _print_children(children, child_prefix, path + name) elif node.metadata['q_target'] == TargetType.PANDAS.value: df = store.load_dataframe(node.hashes) assert isinstance(df, pd.DataFrame) types = ", ".join("%r: %s" % (name, dtype) for name, dtype in df.dtypes.items()) if len(types) > 64: types = types[:63] + u"…" info = "shape %s, types %s" % (df.shape, types) print(prefix + name_prefix + name + ": " + info) else: print(prefix + name_prefix + name) print(store.package_path(team, owner, pkg)) _print_children(children=pkgroot.children.items(), prefix='', path='') def rm(package, force=False): """ Remove a package (all instances) from the local store. """ team, owner, pkg = parse_package(package) if not force: confirmed = input("Remove {0}? (y/n) ".format(package)) if confirmed.lower() != 'y': return store = PackageStore() deleted = store.remove_package(team, owner, pkg) for obj in deleted: print("Removed: {0}".format(obj)) def list_users(team=None): # get team from disk if not specified if team is None: team = _find_logged_in_team() session = _get_session(team) url = get_registry_url(team) resp = session.get('%s/api/users/list' % url) return resp.json() def _print_table(table, padding=2): cols_width = [max(len(word) for word in col) for col in zip(*table)] for row in table: print((" " * padding).join(word.ljust(width) for word, width in zip(row, cols_width))) def _cli_list_users(team=None): res = list_users(team) l = [['Name', 'Email', 'Active', 'Superuser']] for user in res.get('results'): name = user.get('username') email = user.get('email') active = user.get('is_active') su = user.get('is_superuser') l.append([name, email, str(active), str(su)]) _print_table(l) def list_users_detailed(team=None): # get team from disk if not specified if team is None: team = _find_logged_in_team() session = _get_session(team) url = get_registry_url(team) resp = session.get('%s/api/users/list_detailed' % url) return resp.json() def create_user(username, email, team): _check_team_id(team) session = _get_session(team) url = get_registry_url(team) session.post('%s/api/users/create' % url, data=json.dumps({'username':username, 'email':email})) def list_packages(username, team=None): # get team from disk if not specified if team is None: team = _find_logged_in_team() session = _get_session(team) url = get_registry_url(team) resp = session.get('%s/api/admin/package_list/%s' % (url, username)) return resp.json() def disable_user(username, team): _check_team_id(team) session = _get_session(team) url = get_registry_url(team) session.post('%s/api/users/disable' % url, data=json.dumps({'username':username})) def enable_user(username, team): _check_team_id(team) session = _get_session(team) url = get_registry_url(team) session.post('%s/api/users/enable' % url, data=json.dumps({'username':username})) def delete_user(username, team, force=False): _check_team_id(team) if not force: confirmed = input("Really delete user '{0}'? (y/n)".format(username)) if confirmed.lower() != 'y': return session = _get_session(team) url = get_registry_url(team) session.post('%s/api/users/delete' % url, data=json.dumps({'username':username})) def audit(user_or_package): parts = user_or_package.split('/') if len(parts) > 2 or not all(is_nodename(part) for part in parts): raise CommandException("Need either a user or a user/package") team = _find_logged_in_team() if not team: raise CommandException("Not logged in as a team user") session = _get_session(team) response = session.get( "{url}/api/audit/{user_or_package}/".format( url=get_registry_url(team), user_or_package=user_or_package ) ) return response.json().get('events') def _cli_audit(user_or_package): events = audit(user_or_package) team = _find_logged_in_team() teamstr = '%s:' % team rows = [['Time', 'User', 'Package', 'Type']] for item in events: time = item.get('created') pretty_time = datetime.fromtimestamp(time).strftime(DTIMEF) user = item.get('user') pkg = '%s%s/%s' % (teamstr, item.get('package_owner'), item.get('package_name')) t = item.get('type') rows.append((pretty_time, user, pkg, t)) _print_table(rows) def reset_password(team, username): _check_team_id(team) session = _get_session(team) session.post( "{url}/api/users/reset_password".format( url=get_registry_url(team), ), data=json.dumps({'username':username}) ) def _load(package, hash=None): info = parse_package_extended(package) # TODO: support tags & versions. if info.tag: raise CommandException("Loading packages by tag is not supported.") elif info.version: raise CommandException("Loading packages by version is not supported.") elif info.hash: raise CommandException("Use hash=HASH to specify package hash.") store, pkgroot = PackageStore.find_package(info.team, info.user, info.name, pkghash=hash) if pkgroot is None: raise CommandException("Package {package} not found.".format(package=package)) node = _from_core_node(store, pkgroot) return node, pkgroot, info def load(pkginfo, hash=None): """ functional interface to "from quilt.data.USER import PKG" """ node, pkgroot, info = _load(pkginfo, hash) for subnode_name in info.subpath: node = node[subnode_name] return node def export(package, output_path='.', force=False, symlinks=False): """Export package file data. Exports specified node (or its children) to files. `symlinks` **Warning** This is an advanced feature, use at your own risk. You must have a thorough understanding of permissions, and it is your responsibility to ensure that the linked files are not modified. If they do become modified, it may corrupt your package store, and you may lose data, or you may use or distribute incorrect data. If `symlinks` is `True`: * Nodes that point to binary data will be symlinked instead of copied. * All other specified nodes (columnar data) will be exported as normal. :param package: package/subpackage name, e.g., user/foo or user/foo/bar :param output_path: distination folder :param symlinks: Use at your own risk. See full description above. :param force: if True, overwrite existing files """ # TODO: (future) Support other tags/versions (via load(), probably) # TODO: (future) This would be *drastically* simplified by a 1:1 source-file to node-name correlation # TODO: (future) This would be significantly simplified if node objects with useful accessors existed # (nodes.Node and subclasses are being phased out, per Kevin) if symlinks is True: from quilt import _DEV_MODE if not _DEV_MODE: response = input("Warning: Exporting using symlinks to the package store.\n" "\tThis is an advanced feature.\n" "\tThe package store must not be written to directly, or it may be corrupted.\n" "\tManaging permissions and usage are your responsibility.\n\n" "Are you sure you want to continue? (yes/No) ") if response != 'yes': raise CommandException("No action taken: 'yes' not given") ## Helpers # Perhaps better as Node.iteritems() def iteritems(node, base_path=None, recursive=False): if base_path is None: base_path = pathlib.PureWindowsPath() assert isinstance(node, nodes.GroupNode) for name, child_node in node._items(): child_path = base_path / name yield child_path, child_node if recursive and isinstance(child_node, nodes.GroupNode): for subpath, subnode in iteritems(child_node, child_path, recursive): yield subpath, subnode # Perhaps better as Node.export_path def get_export_path(node, node_path): # If filepath is not present, generate fake path based on node parentage. filepath = node._meta[SYSTEM_METADATA]['filepath'] if filepath: dest = pathlib.PureWindowsPath(filepath) # PureWindowsPath handles all win/lin/osx separators else: assert isinstance(node_path, pathlib.PureWindowsPath) assert not node_path.anchor print("Warning: Missing export path in metadata. Using node path: {}" .format('/'.join(node_path.parts))) dest = node_path # When exporting dataframes, excel files are to be converted to csv. # check also occurs in export_node(), but done here prevents filename conflicts if node._target() == TargetType.PANDAS: if dest.suffix != '.csv': # avoid name collisions from files with same name but different source, # as we shift all to being csv for export. # foo.tsv -> foo_tsv.csv # foo.xls -> foo_xls.csv # ..etc. dest = dest.with_name(dest.stem + dest.suffix.replace('.', '_')).with_suffix('.csv') # if filepath isn't absolute if not dest.anchor: return pathlib.Path(*dest.parts) # return a native path # filepath is absolute, convert to relative. dest = pathlib.Path(*dest.parts[1:]) # Issue warning as native path, and return it print("Warning: Converted export path to relative path: {}".format(str(dest))) return dest def iter_filename_map(node, base_path): """Yields (<node>, <export path>) pairs for given `node`. If `node` is a group node, yield pairs for children of `node`. Otherwise, yield the path to export to for that node. :returns: Iterator of (<node>, <export path>) pairs """ # Handle singular node export if not isinstance(node, nodes.GroupNode): yield (node, get_export_path(node, base_path)) return for node_path, found_node in iteritems(node, base_path=base_path, recursive=True): if not isinstance(found_node, nodes.GroupNode): yield (found_node, get_export_path(found_node, node_path)) # perhaps better as Node.export() def export_node(node, dest, use_symlinks=False): if not dest.parent.exists(): dest.parent.mkdir(parents=True, exist_ok=True) if node._target() == TargetType.FILE: if use_symlinks is True: fs_link(node(), dest) else: copyfile(node(), str(dest)) elif node._target() == TargetType.PANDAS: df = node() # 100 decimal places of pi will allow you to draw a circle the size of the known # universe, and only vary by approximately the width of a proton. # ..so, hopefully 78 decimal places (256 bits) is ok for float precision in CSV exports. # If not, and someone complains, we can up it or add a parameter. df.to_csv(str(dest), index=False, float_format='%r') else: assert False def resolve_dirpath(dirpath): """Checks the dirpath and ensures it exists and is writable :returns: absolute, resolved dirpath """ # ensure output path is writable. I'd just check stat, but this is fully portable. try: dirpath.mkdir(exist_ok=True) # could be '.' with tempfile.TemporaryFile(dir=str(dirpath), prefix="quilt-export-write-test-", suffix='.tmp'): pass except OSError as error: raise CommandException("Invalid export path: not writable: " + str(error)) return output_path.resolve() # this gets the true absolute path, but requires the path exists. def finalize(outpath, exports): """Finalize exports This performs the following tasks: * Ensure destination doesn't exist * Remove absolute anchor in dest, if any * Prefix destination with target dir :returns: (<source Path / dest Path pairs list>, <set of zero-byte files>) """ # We return list instead of yielding, so that all prep logic is done before write is attempted. final_export_map = [] for node, dest in exports: dest = pathlib.PureWindowsPath(dest) dest = outpath.joinpath(*dest.parts[1:]) if dest.anchor else outpath / dest if dest.parent != outpath and dest.parent.exists() and not force: raise CommandException("Invalid export path: subdir already exists: {!r}" .format(str(dest.parent))) if dest.exists() and not force: raise CommandException("Invalid export path: file already exists: {!r}".format(str(dest))) final_export_map.append((node, dest)) return final_export_map def check_for_conflicts(export_list): """Checks for conflicting exports in the final export map of (src, dest) pairs Export conflicts can be introduced in various ways -- for example: * export-time mapping -- user maps two files to the same name * coded builds -- user creates two files with the same path * re-rooting absolute paths -- user entered absolute paths, which are re-rooted to the export dir * build-time duplication -- user enters the same file path twice under different nodes This checks for these conflicts and raises an error if they have occurred. :raises: CommandException """ results = {} conflicts = set() # Export conflicts.. for src, dest in export_list: if dest in conflicts: continue # already a known conflict if dest not in results: results[dest] = src continue # not a conflict.. if src._target() == TargetType.FILE and src() == results[dest](): continue # not a conflict (same src filename, same dest).. # ..add other conditions that prevent this from being a conflict here.. # dest is a conflict. conflicts.add(dest) if conflicts: conflict_strings = (os.linesep + '\t').join(str(c) for c in conflicts) conflict_error = CommandException( "Invalid export: Identical filename(s) with conflicting contents cannot be exported:\n\t" + conflict_strings ) conflict_error.file_conflicts = conflicts raise conflict_error # Check for filenames that conflict with folder names exports = set(results) dirs = set() for dest in results: dirs.update(dest.parents) file_dir_conflicts = exports & dirs if file_dir_conflicts: conflict_strings = (os.linesep + '\t').join(str(c) for c in file_dir_conflicts) conflict_error = CommandException( "Invalid Export: Filename(s) conflict with folder name(s):\n\t" + conflict_strings ) conflict_error.dir_file_conflicts = file_dir_conflicts raise conflict_error # TODO: return abbreviated list of exports based on found non-conflicting duplicates ## Export Logic output_path = pathlib.Path(output_path) node, _, info = _load(package) if info.subpath: subpath = pathlib.PureWindowsPath(*info.subpath) for name in info.subpath: node = node._get(name) else: subpath = pathlib.PureWindowsPath() resolved_output = resolve_dirpath(output_path) # resolve/create output path exports = iter_filename_map(node, subpath) # Create src / dest map iterator exports = finalize(resolved_output, exports) # Fix absolutes, check dest nonexistent, prefix dest dir check_for_conflicts(exports) # Prevent various potential dir/naming conflicts # Skip it if there's nothing to do if not exports: # Technically successful, but with nothing to do. # package may have no file nodes, or user may have filtered out all applicable targets. # -- should we consider it an error and raise? print("No files to export.") return # All prep done, let's export.. try: fmt = "Exporting file {n_fmt} of {total_fmt} [{elapsed}]" sys.stdout.flush() # flush prior text before making progress bar # bar_format is not respected unless both ncols and total are set. exports_bar = tqdm(exports, desc="Exporting: ", ncols=1, total=len(exports), bar_format=fmt) # tqdm is threaded, and its display may not specify the exact file currently being exported. with exports_bar: for node, dest in exports_bar: # Escape { and } in filenames for .format called by tqdm fname = str(dest.relative_to(resolved_output)).replace('{', "{{").replace('}', '}}') exports_bar.bar_format = fmt + ": " + fname exports_bar.update(0) export_node(node, dest, use_symlinks=symlinks) except OSError as error: commandex = CommandException("Unexpected error during export: " + str(error)) commandex.original_error = error raise commandex
1
17,022
Make it the last parameter, just in case someone uses the API with non-keyword args.
quiltdata-quilt
py
@@ -1,15 +1,15 @@ -class GithubRemovalJob < Struct.new(:github_team, :username) +class GithubRemovalJob < Struct.new(:repository, :username) include ErrorReporting PRIORITY = 1 - def self.enqueue(github_team, username) - Delayed::Job.enqueue(new(github_team, username)) + def self.enqueue(repository, username) + Delayed::Job.enqueue(new(repository, username)) end def perform begin - github_client.remove_team_member(github_team, username) + github_client.remove_collaborator(repository, username) rescue Octokit::NotFound, Net::HTTPBadResponse => e Airbrake.notify(e) end
1
class GithubRemovalJob < Struct.new(:github_team, :username) include ErrorReporting PRIORITY = 1 def self.enqueue(github_team, username) Delayed::Job.enqueue(new(github_team, username)) end def perform begin github_client.remove_team_member(github_team, username) rescue Octokit::NotFound, Net::HTTPBadResponse => e Airbrake.notify(e) end end private def github_client Octokit::Client.new(login: GITHUB_USER, password: GITHUB_PASSWORD) end end
1
14,298
Don't extend an instance initialized by `Struct.new`.
thoughtbot-upcase
rb
@@ -4771,6 +4771,11 @@ static void tdes(pmix_server_trkr_t *t) if (NULL != t->info) { PMIX_INFO_FREE(t->info, t->ninfo); } + pmix_nspace_caddy_t *nm, *nm_next; + PMIX_LIST_FOREACH_SAFE(nm, nm_next, &t->nslist, pmix_nspace_caddy_t) { + pmix_list_remove_item (&t->nslist, &nm->super); + PMIX_RELEASE(nm); + } PMIX_DESTRUCT(&t->nslist); } PMIX_CLASS_INSTANCE(pmix_server_trkr_t,
1
/* -*- Mode: C; c-basic-offset:4 ; indent-tabs-mode:nil -*- */ /* * Copyright (c) 2014-2020 Intel, Inc. All rights reserved. * Copyright (c) 2014-2019 Research Organization for Information Science * and Technology (RIST). All rights reserved. * Copyright (c) 2014-2015 Artem Y. Polyakov <[email protected]>. * All rights reserved. * Copyright (c) 2016-2019 Mellanox Technologies, Inc. * All rights reserved. * Copyright (c) 2016-2020 IBM Corporation. All rights reserved. * Copyright (c) 2021 Nanook Consulting. All rights reserved. * $COPYRIGHT$ * * Additional copyrights may follow * * $HEADER$ */ #include "src/include/pmix_config.h" #include "src/include/pmix_stdint.h" #include "src/include/pmix_socket_errno.h" #include "include/pmix_server.h" #include "src/include/pmix_globals.h" #ifdef HAVE_STRING_H #include <string.h> #endif #ifdef HAVE_SYS_STAT_H #include <sys/stat.h> #endif #include <fcntl.h> #ifdef HAVE_UNISTD_H #include <unistd.h> #endif #ifdef HAVE_SYS_SOCKET_H #include <sys/socket.h> #endif #ifdef HAVE_SYS_UN_H #include <sys/un.h> #endif #ifdef HAVE_SYS_UIO_H #include <sys/uio.h> #endif #ifdef HAVE_SYS_TYPES_H #include <sys/types.h> #endif #ifdef HAVE_TIME_H #include <time.h> #endif #include PMIX_EVENT_HEADER #include "src/class/pmix_hotel.h" #include "src/class/pmix_list.h" #include "src/common/pmix_attributes.h" #include "src/mca/bfrops/bfrops.h" #include "src/mca/plog/plog.h" #include "src/mca/pnet/pnet.h" #include "src/mca/prm/prm.h" #include "src/mca/psensor/psensor.h" #include "src/mca/ptl/base/base.h" #include "src/util/argv.h" #include "src/util/error.h" #include "src/util/output.h" #include "src/util/pmix_environ.h" #include "src/mca/gds/base/base.h" #include "pmix_server_ops.h" /* The rank_blob_t type to collect processes blobs, * this list afterward will form a node modex blob. */ typedef struct { pmix_list_item_t super; pmix_buffer_t *buf; } rank_blob_t; static void bufdes(rank_blob_t *p) { PMIX_RELEASE(p); } static PMIX_CLASS_INSTANCE(rank_blob_t, pmix_list_item_t, NULL, bufdes); pmix_server_module_t pmix_host_server = {0}; pmix_status_t pmix_server_abort(pmix_peer_t *peer, pmix_buffer_t *buf, pmix_op_cbfunc_t cbfunc, void *cbdata) { int32_t cnt; pmix_status_t rc; int status; char *msg; size_t nprocs; pmix_proc_t *procs = NULL; pmix_proc_t proc; pmix_output_verbose(2, pmix_server_globals.base_output, "recvd ABORT"); /* unpack the status */ cnt = 1; PMIX_BFROPS_UNPACK(rc, peer, buf, &status, &cnt, PMIX_STATUS); if (PMIX_SUCCESS != rc) { return rc; } /* unpack the message */ cnt = 1; PMIX_BFROPS_UNPACK(rc, peer, buf, &msg, &cnt, PMIX_STRING); if (PMIX_SUCCESS != rc) { return rc; } /* unpack the number of procs */ cnt = 1; PMIX_BFROPS_UNPACK(rc, peer, buf, &nprocs, &cnt, PMIX_SIZE); if (PMIX_SUCCESS != rc) { return rc; } /* unpack any provided procs - these are the procs the caller * wants aborted */ if (0 < nprocs) { PMIX_PROC_CREATE(procs, nprocs); if (NULL == procs) { if (NULL != msg) { free(msg); } return PMIX_ERR_NOMEM; } cnt = nprocs; PMIX_BFROPS_UNPACK(rc, peer, buf, procs, &cnt, PMIX_PROC); if (PMIX_SUCCESS != rc) { if (NULL != msg) { free(msg); } return rc; } } /* let the local host's server execute it */ if (NULL != pmix_host_server.abort) { pmix_strncpy(proc.nspace, peer->info->pname.nspace, PMIX_MAX_NSLEN); proc.rank = peer->info->pname.rank; rc = pmix_host_server.abort(&proc, peer->info->server_object, status, msg, procs, nprocs, cbfunc, cbdata); } else { rc = PMIX_ERR_NOT_SUPPORTED; } PMIX_PROC_FREE(procs, nprocs); /* the client passed this msg to us so we could give * it to the host server - we are done with it now */ if (NULL != msg) { free(msg); } return rc; } pmix_status_t pmix_server_commit(pmix_peer_t *peer, pmix_buffer_t *buf) { int32_t cnt; pmix_status_t rc; pmix_buffer_t b2, pbkt; pmix_kval_t *kp; pmix_scope_t scope; pmix_namespace_t *nptr; pmix_rank_info_t *info; pmix_proc_t proc; pmix_dmdx_remote_t *dcd, *dcdnext; char *data; size_t sz; pmix_cb_t cb; /* shorthand */ info = peer->info; nptr = peer->nptr; pmix_strncpy(proc.nspace, nptr->nspace, PMIX_MAX_NSLEN); proc.rank = info->pname.rank; pmix_output_verbose(2, pmix_server_globals.fence_output, "%s:%d EXECUTE COMMIT FOR %s:%d", pmix_globals.myid.nspace, pmix_globals.myid.rank, nptr->nspace, info->pname.rank); /* this buffer will contain one or more buffers, each * representing a different scope. These need to be locally * stored separately so we can provide required data based * on the requestor's location */ cnt = 1; PMIX_BFROPS_UNPACK(rc, peer, buf, &scope, &cnt, PMIX_SCOPE); while (PMIX_SUCCESS == rc) { /* unpack and store the blob */ cnt = 1; PMIX_CONSTRUCT(&b2, pmix_buffer_t); PMIX_BFROPS_ASSIGN_TYPE(peer, &b2); PMIX_BFROPS_UNPACK(rc, peer, buf, &b2, &cnt, PMIX_BUFFER); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); return rc; } /* unpack the buffer and store the values - we store them * in this peer's native GDS component so that other local * procs from that nspace can access it */ kp = PMIX_NEW(pmix_kval_t); cnt = 1; PMIX_BFROPS_UNPACK(rc, peer, &b2, kp, &cnt, PMIX_KVAL); while (PMIX_SUCCESS == rc) { if( PMIX_LOCAL == scope || PMIX_GLOBAL == scope){ PMIX_GDS_STORE_KV(rc, peer, &proc, scope, kp); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); PMIX_RELEASE(kp); PMIX_DESTRUCT(&b2); return rc; } } if (PMIX_REMOTE == scope || PMIX_GLOBAL == scope) { PMIX_GDS_STORE_KV(rc, pmix_globals.mypeer, &proc, scope, kp); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); PMIX_RELEASE(kp); PMIX_DESTRUCT(&b2); return rc; } } PMIX_RELEASE(kp); // maintain accounting kp = PMIX_NEW(pmix_kval_t); cnt = 1; PMIX_BFROPS_UNPACK(rc, peer, &b2, kp, &cnt, PMIX_KVAL); } PMIX_RELEASE(kp); // maintain accounting PMIX_DESTRUCT(&b2); if (PMIX_ERR_UNPACK_READ_PAST_END_OF_BUFFER != rc) { PMIX_ERROR_LOG(rc); return rc; } cnt = 1; PMIX_BFROPS_UNPACK(rc, peer, buf, &scope, &cnt, PMIX_SCOPE); } if (PMIX_ERR_UNPACK_READ_PAST_END_OF_BUFFER != rc) { PMIX_ERROR_LOG(rc); return rc; } rc = PMIX_SUCCESS; /* mark us as having successfully received a blob from this proc */ info->modex_recvd = true; /* update the commit counter */ peer->commit_cnt++; /* see if anyone remote is waiting on this data - could be more than one */ PMIX_LIST_FOREACH_SAFE(dcd, dcdnext, &pmix_server_globals.remote_pnd, pmix_dmdx_remote_t) { if (0 != strncmp(dcd->cd->proc.nspace, nptr->nspace, PMIX_MAX_NSLEN)) { continue; } if (dcd->cd->proc.rank == info->pname.rank) { /* we can now fulfill this request - collect the * remote/global data from this proc - note that there * may not be a contribution */ data = NULL; sz = 0; PMIX_CONSTRUCT(&cb, pmix_cb_t); cb.proc = &proc; cb.scope = PMIX_REMOTE; cb.copy = true; PMIX_GDS_FETCH_KV(rc, pmix_globals.mypeer, &cb); if (PMIX_SUCCESS == rc) { /* package it up */ PMIX_CONSTRUCT(&pbkt, pmix_buffer_t); PMIX_LIST_FOREACH(kp, &cb.kvs, pmix_kval_t) { /* we pack this in our native BFROPS form as it * will be sent to another daemon */ PMIX_BFROPS_PACK(rc, pmix_globals.mypeer, &pbkt, kp, 1, PMIX_KVAL); } PMIX_UNLOAD_BUFFER(&pbkt, data, sz); } PMIX_DESTRUCT(&cb); /* execute the callback */ dcd->cd->cbfunc(rc, data, sz, dcd->cd->cbdata); if (NULL != data) { free(data); } /* we have finished this request */ pmix_list_remove_item(&pmix_server_globals.remote_pnd, &dcd->super); PMIX_RELEASE(dcd); } } /* see if anyone local is waiting on this data- could be more than one */ rc = pmix_pending_resolve(nptr, info->pname.rank, PMIX_SUCCESS, NULL); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); } return rc; } /* get an existing object for tracking LOCAL participation in a collective * operation such as "fence". The only way this function can be * called is if at least one local client process is participating * in the operation. Thus, we know that at least one process is * involved AND has called the collective operation. * * NOTE: the host server *cannot* call us with a collective operation * as there is no mechanism by which it can do so. We call the host * server only after all participating local procs have called us. * So it is impossible for us to be called with a collective without * us already knowing about all local participants. * * procs - the array of procs participating in the collective, * regardless of location * nprocs - the number of procs in the array */ static pmix_server_trkr_t* get_tracker(char *id, pmix_proc_t *procs, size_t nprocs, pmix_cmd_t type) { pmix_server_trkr_t *trk; size_t i, j; size_t matches; pmix_output_verbose(5, pmix_server_globals.base_output, "get_tracker called with %d procs", (int)nprocs); /* bozo check - should never happen outside of programmer error */ if (NULL == procs && NULL == id) { PMIX_ERROR_LOG(PMIX_ERR_BAD_PARAM); return NULL; } /* there is no shortcut way to search the trackers - all * we can do is perform a brute-force search. Fortunately, * it is highly unlikely that there will be more than one * or two active at a time, and they are most likely to * involve only a single proc with WILDCARD rank - so this * shouldn't take long */ PMIX_LIST_FOREACH(trk, &pmix_server_globals.collectives, pmix_server_trkr_t) { /* Collective operation if unique identified by * the set of participating processes and the type of collective, * or by the operation ID */ if (NULL != id) { if (NULL != trk->id && 0 == strcmp(id, trk->id)) { return trk; } } else { if (nprocs != trk->npcs) { continue; } if (type != trk->type) { continue; } matches = 0; for (i=0; i < nprocs; i++) { /* the procs may be in different order, so we have * to do an exhaustive search */ for (j=0; j < trk->npcs; j++) { if (0 == strcmp(procs[i].nspace, trk->pcs[j].nspace) && procs[i].rank == trk->pcs[j].rank) { ++matches; break; } } } if (trk->npcs == matches) { return trk; } } } /* No tracker was found */ return NULL; } /* create a new object for tracking LOCAL participation in a collective * operation such as "fence". The only way this function can be * called is if at least one local client process is participating * in the operation. Thus, we know that at least one process is * involved AND has called the collective operation. * * NOTE: the host server *cannot* call us with a collective operation * as there is no mechanism by which it can do so. We call the host * server only after all participating local procs have called us. * So it is impossible for us to be called with a collective without * us already knowing about all local participants. * * procs - the array of procs participating in the collective, * regardless of location * nprocs - the number of procs in the array */ static pmix_server_trkr_t* new_tracker(char *id, pmix_proc_t *procs, size_t nprocs, pmix_cmd_t type) { pmix_server_trkr_t *trk; size_t i; bool all_def, found; pmix_namespace_t *nptr, *ns; pmix_rank_info_t *info; pmix_nspace_caddy_t *nm; pmix_nspace_t first; pmix_output_verbose(5, pmix_server_globals.base_output, "new_tracker called with %d procs", (int)nprocs); /* bozo check - should never happen outside of programmer error */ if (NULL == procs) { PMIX_ERROR_LOG(PMIX_ERR_BAD_PARAM); return NULL; } pmix_output_verbose(5, pmix_server_globals.base_output, "adding new tracker %s with %d procs", (NULL == id) ? "NO-ID" : id, (int)nprocs); /* this tracker is new - create it */ trk = PMIX_NEW(pmix_server_trkr_t); if (NULL == trk) { PMIX_ERROR_LOG(PMIX_ERR_NOMEM); return NULL; } if (NULL != id) { trk->id = strdup(id); } /* copy the procs */ PMIX_PROC_CREATE(trk->pcs, nprocs); if (NULL == trk->pcs) { PMIX_ERROR_LOG(PMIX_ERR_NOMEM); PMIX_RELEASE(trk); return NULL; } memcpy(trk->pcs, procs, nprocs * sizeof(pmix_proc_t)); trk->npcs = nprocs; trk->type = type; trk->local = true; trk->nlocal = 0; all_def = true; PMIX_LOAD_NSPACE(first, NULL); for (i=0; i < nprocs; i++) { /* is this nspace known to us? */ nptr = NULL; PMIX_LIST_FOREACH(ns, &pmix_globals.nspaces, pmix_namespace_t) { if (0 == strcmp(procs[i].nspace, ns->nspace)) { nptr = ns; break; } } /* check if multiple nspaces are involved in this operation */ if (0 == strlen(first)) { PMIX_LOAD_NSPACE(first, procs[i].nspace); } else if (!PMIX_CHECK_NSPACE(first, procs[i].nspace)) { trk->hybrid = true; } if (NULL == nptr) { /* we don't know about this nspace. If there is going to * be at least one local process participating in a fence, * they we require that either at least one process must already * have been registered (via "register client") or that the * nspace itself have been regisered. So either the nspace * wasn't registered because it doesn't include any local * procs, or our host has not been told about this nspace * because it won't host any local procs. We therefore mark * this tracker as including non-local participants. * * NOTE: It is conceivable that someone might want to review * this constraint at a future date. I believe it has to be * required (at least for now) as otherwise we wouldn't have * a way of knowing when all local procs have participated. * It is possible that a new nspace could come along at some * later time and add more local participants - but we don't * know how long to wait. * * The only immediately obvious alternative solutions would * be to either require that RMs always inform all daemons * about the launch of nspaces, regardless of whether or * not they will host local procs; or to drop the aggregation * of local participants and just pass every fence call * directly to the host. Neither of these seems palatable * at this time. */ trk->local = false; /* we don't know any more info about this nspace, so * there isn't anything more we can do */ continue; } /* it is possible we know about this nspace because the host * has registered one or more clients via "register_client", * but the host has not yet called "register_nspace". There is * a very tiny race condition whereby this can happen due * to event-driven processing, but account for it here */ if (SIZE_MAX == nptr->nlocalprocs) { /* delay processing until this nspace is registered */ all_def = false; continue; } if (0 == nptr->nlocalprocs) { /* the host has informed us that this nspace has no local procs */ pmix_output_verbose(5, pmix_server_globals.base_output, "new_tracker: unknown nspace %s", procs[i].nspace); trk->local = false; continue; } /* check and add uniq ns into trk nslist */ found = false; PMIX_LIST_FOREACH(nm, &trk->nslist, pmix_nspace_caddy_t) { if (0 == strcmp(nptr->nspace, nm->ns->nspace)) { found = true; break; } } if (!found) { nm = PMIX_NEW(pmix_nspace_caddy_t); PMIX_RETAIN(nptr); nm->ns = nptr; pmix_list_append(&trk->nslist, &nm->super); } /* if they want all the local members of this nspace, then * add them in here. They told us how many procs will be * local to us from this nspace, but we don't know their * ranks. So as long as they want _all_ of them, we can * handle that case regardless of whether the individual * clients have been "registered" */ if (PMIX_RANK_WILDCARD == procs[i].rank) { trk->nlocal += nptr->nlocalprocs; /* the total number of procs in this nspace was provided * in the data blob delivered to register_nspace, so check * to see if all the procs are local */ if (nptr->nprocs != nptr->nlocalprocs) { trk->local = false; } continue; } /* They don't want all the local clients, or they are at * least listing them individually. Check if all the clients * for this nspace have been registered via "register_client" * so we know the specific ranks on this node */ if (!nptr->all_registered) { /* nope, so no point in going further on this one - we'll * process it once all the procs are known */ all_def = false; pmix_output_verbose(5, pmix_server_globals.base_output, "new_tracker: all clients not registered nspace %s", procs[i].nspace); continue; } /* is this one of my local ranks? */ found = false; PMIX_LIST_FOREACH(info, &nptr->ranks, pmix_rank_info_t) { if (procs[i].rank == info->pname.rank) { pmix_output_verbose(5, pmix_server_globals.base_output, "adding local proc %s.%d to tracker", info->pname.nspace, info->pname.rank); found = true; /* track the count */ trk->nlocal++; break; } } if (!found) { trk->local = false; } } if (all_def) { trk->def_complete = true; } pmix_list_append(&pmix_server_globals.collectives, &trk->super); return trk; } static void fence_timeout(int sd, short args, void *cbdata) { pmix_server_caddy_t *cd = (pmix_server_caddy_t*)cbdata; pmix_output_verbose(2, pmix_server_globals.fence_output, "ALERT: fence timeout fired"); /* execute the provided callback function with the error */ if (NULL != cd->trk->modexcbfunc) { cd->trk->modexcbfunc(PMIX_ERR_TIMEOUT, NULL, 0, cd->trk, NULL, NULL); return; // the cbfunc will have cleaned up the tracker } cd->event_active = false; /* remove it from the list */ pmix_list_remove_item(&cd->trk->local_cbs, &cd->super); PMIX_RELEASE(cd); } static pmix_status_t _collect_data(pmix_server_trkr_t *trk, pmix_buffer_t *buf) { pmix_buffer_t bucket, *pbkt = NULL; pmix_cb_t cb; pmix_kval_t *kv; pmix_byte_object_t bo; pmix_server_caddy_t *scd; pmix_proc_t pcs; pmix_status_t rc = PMIX_SUCCESS; pmix_rank_t rel_rank; pmix_nspace_caddy_t *nm; bool found; pmix_list_t rank_blobs; rank_blob_t *blob; uint32_t kmap_size; /* key names map, the position of the key name * in the array determines the unique key index */ char **kmap = NULL; int i; pmix_gds_modex_blob_info_t blob_info_byte = 0; pmix_gds_modex_key_fmt_t kmap_type = PMIX_MODEX_KEY_INVALID; PMIX_CONSTRUCT(&bucket, pmix_buffer_t); if (PMIX_COLLECT_YES == trk->collect_type) { pmix_output_verbose(2, pmix_server_globals.fence_output, "fence - assembling data"); /* Evaluate key names sizes and their count to select * a format to store key names: * - keymap: use key-map in blob header for key-name resolve * from idx: key names stored as indexes (avoid key duplication) * - regular: key-names stored as is */ if (PMIX_MODEX_KEY_INVALID == kmap_type) { size_t key_fmt_size[PMIX_MODEX_KEY_MAX] = {0}; pmix_value_array_t *key_count_array = PMIX_NEW(pmix_value_array_t); uint32_t *key_count = NULL; pmix_value_array_init(key_count_array, sizeof(uint32_t)); PMIX_LIST_FOREACH(scd, &trk->local_cbs, pmix_server_caddy_t) { pmix_strncpy(pcs.nspace, scd->peer->info->pname.nspace, PMIX_MAX_NSLEN); pcs.rank = scd->peer->info->pname.rank; PMIX_CONSTRUCT(&cb, pmix_cb_t); cb.proc = &pcs; cb.scope = PMIX_REMOTE; cb.copy = true; PMIX_GDS_FETCH_KV(rc, pmix_globals.mypeer, &cb); if (PMIX_SUCCESS == rc) { int key_idx; PMIX_LIST_FOREACH(kv, &cb.kvs, pmix_kval_t) { rc = pmix_argv_append_unique_idx(&key_idx, &kmap, kv->key); if (pmix_value_array_get_size(key_count_array) < (size_t)(key_idx+1)) { size_t new_size; size_t old_size = pmix_value_array_get_size(key_count_array); pmix_value_array_set_size(key_count_array, key_idx+1); new_size = pmix_value_array_get_size(key_count_array); key_count = PMIX_VALUE_ARRAY_GET_BASE(key_count_array, uint32_t); memset(key_count + old_size, 0, sizeof(uint32_t) * (new_size - old_size)); } key_count = PMIX_VALUE_ARRAY_GET_BASE(key_count_array, uint32_t); key_count[key_idx]++; } } } key_count = PMIX_VALUE_ARRAY_GET_BASE(key_count_array, uint32_t); for (i = 0; i < pmix_argv_count(kmap); i++) { pmix_buffer_t tmp; size_t kname_size; size_t kidx_size; PMIX_CONSTRUCT(&tmp, pmix_buffer_t); PMIX_BFROPS_PACK(rc, pmix_globals.mypeer, &tmp, &kmap[i], 1, PMIX_STRING); kname_size = tmp.bytes_used; PMIX_DESTRUCT(&tmp); PMIX_CONSTRUCT(&tmp, pmix_buffer_t); PMIX_BFROPS_PACK(rc, pmix_globals.mypeer, &tmp, &i, 1, PMIX_UINT32); kidx_size = tmp.bytes_used; PMIX_DESTRUCT(&tmp); /* calculate the key names sizes */ key_fmt_size[PMIX_MODEX_KEY_NATIVE_FMT] = kname_size * key_count[i]; key_fmt_size[PMIX_MODEX_KEY_KEYMAP_FMT] = kname_size + key_count[i]*kidx_size; } PMIX_RELEASE(key_count_array); /* select the most efficient key-name pack format */ kmap_type = key_fmt_size[PMIX_MODEX_KEY_NATIVE_FMT] > key_fmt_size[PMIX_MODEX_KEY_KEYMAP_FMT] ? PMIX_MODEX_KEY_KEYMAP_FMT : PMIX_MODEX_KEY_NATIVE_FMT; pmix_output_verbose(5, pmix_server_globals.base_output, "key packing type %s", kmap_type == PMIX_MODEX_KEY_KEYMAP_FMT ? "kmap" : "native"); } PMIX_CONSTRUCT(&rank_blobs, pmix_list_t); PMIX_LIST_FOREACH(scd, &trk->local_cbs, pmix_server_caddy_t) { /* get any remote contribution - note that there * may not be a contribution */ pmix_strncpy(pcs.nspace, scd->peer->info->pname.nspace, PMIX_MAX_NSLEN); pcs.rank = scd->peer->info->pname.rank; PMIX_CONSTRUCT(&cb, pmix_cb_t); cb.proc = &pcs; cb.scope = PMIX_REMOTE; cb.copy = true; PMIX_GDS_FETCH_KV(rc, pmix_globals.mypeer, &cb); if (PMIX_SUCCESS == rc) { /* calculate the throughout rank */ rel_rank = 0; found = false; if (pmix_list_get_size(&trk->nslist) == 1) { found = true; } else { PMIX_LIST_FOREACH(nm, &trk->nslist, pmix_nspace_caddy_t) { if (0 == strcmp(nm->ns->nspace, pcs.nspace)) { found = true; break; } rel_rank += nm->ns->nprocs; } } if (false == found) { rc = PMIX_ERR_NOT_FOUND; PMIX_ERROR_LOG(rc); PMIX_DESTRUCT(&cb); PMIX_DESTRUCT(&rank_blobs); goto cleanup; } rel_rank += pcs.rank; /* pack the relative rank */ pbkt = PMIX_NEW(pmix_buffer_t); PMIX_BFROPS_PACK(rc, pmix_globals.mypeer, pbkt, &rel_rank, 1, PMIX_PROC_RANK); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); PMIX_DESTRUCT(&cb); PMIX_DESTRUCT(&rank_blobs); PMIX_RELEASE(pbkt); goto cleanup; } /* pack the returned kval's */ PMIX_LIST_FOREACH(kv, &cb.kvs, pmix_kval_t) { rc = pmix_gds_base_modex_pack_kval(kmap_type, pbkt, &kmap, kv); if (rc != PMIX_SUCCESS) { PMIX_ERROR_LOG(rc); PMIX_DESTRUCT(&cb); PMIX_DESTRUCT(&rank_blobs); PMIX_RELEASE(pbkt); goto cleanup; } } /* add part of the process modex to the list */ blob = PMIX_NEW(rank_blob_t); blob->buf = pbkt; pmix_list_append(&rank_blobs, &blob->super); pbkt = NULL; } PMIX_DESTRUCT(&cb); } /* mark the collection type so we can check on the * receiving end that all participants did the same. Note * that if the receiving end thinks that the collect flag * is false, then store_modex will not be called on that * node and this information (and the flag) will be ignored, * meaning that no error is generated! */ blob_info_byte |= PMIX_GDS_COLLECT_BIT; if (PMIX_MODEX_KEY_KEYMAP_FMT == kmap_type) { blob_info_byte |= PMIX_GDS_KEYMAP_BIT; } /* pack the modex blob info byte */ PMIX_BFROPS_PACK(rc, pmix_globals.mypeer, &bucket, &blob_info_byte, 1, PMIX_BYTE); if (PMIX_MODEX_KEY_KEYMAP_FMT == kmap_type) { /* pack node part of modex to `bucket` */ /* pack the key names map for the remote server can * use it to match key names by index */ kmap_size = pmix_argv_count(kmap); if (0 < kmap_size) { PMIX_BFROPS_PACK(rc, pmix_globals.mypeer, &bucket, &kmap_size, 1, PMIX_UINT32); PMIX_BFROPS_PACK(rc, pmix_globals.mypeer, &bucket, kmap, kmap_size, PMIX_STRING); } } /* pack the collected blobs of processes */ PMIX_LIST_FOREACH(blob, &rank_blobs, rank_blob_t) { /* extract the blob */ PMIX_UNLOAD_BUFFER(blob->buf, bo.bytes, bo.size); /* pack the returned blob */ PMIX_BFROPS_PACK(rc, pmix_globals.mypeer, &bucket, &bo, 1, PMIX_BYTE_OBJECT); PMIX_BYTE_OBJECT_DESTRUCT(&bo); // releases the data if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto cleanup; } } PMIX_DESTRUCT(&rank_blobs); } else { /* mark the collection type so we can check on the * receiving end that all participants did the same. * Don't do it for non-debug mode so we don't unnecessarily * send the collection bucket. The mdxcbfunc in the * server only calls store_modex if the local collect * flag is set to true. In debug mode, this check will * cause the store_modex function to see that this node * thought the collect flag was not set, and therefore * generate an error */ #if PMIX_ENABLE_DEBUG /* pack the modex blob info byte */ PMIX_BFROPS_PACK(rc, pmix_globals.mypeer, &bucket, &blob_info_byte, 1, PMIX_BYTE); #endif } if (!PMIX_BUFFER_IS_EMPTY(&bucket)) { /* because the remote servers have to unpack things * in chunks, we have to pack the bucket as a single * byte object to allow remote unpack */ PMIX_UNLOAD_BUFFER(&bucket, bo.bytes, bo.size); PMIX_BFROPS_PACK(rc, pmix_globals.mypeer, buf, &bo, 1, PMIX_BYTE_OBJECT); PMIX_BYTE_OBJECT_DESTRUCT(&bo); // releases the data if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); } } cleanup: PMIX_DESTRUCT(&bucket); pmix_argv_free(kmap); return rc; } pmix_status_t pmix_server_fence(pmix_server_caddy_t *cd, pmix_buffer_t *buf, pmix_modex_cbfunc_t modexcbfunc, pmix_op_cbfunc_t opcbfunc) { int32_t cnt; pmix_status_t rc; size_t nprocs; pmix_proc_t *procs=NULL, *newprocs; bool collect_data = false; pmix_server_trkr_t *trk; char *data = NULL; size_t sz = 0; pmix_buffer_t bucket; pmix_info_t *info = NULL; size_t ninfo=0, n, nmbrs, idx; struct timeval tv = {0, 0}; pmix_list_t expand; pmix_group_caddy_t *gcd; pmix_group_t *grp; pmix_output_verbose(2, pmix_server_globals.fence_output, "recvd FENCE"); /* unpack the number of procs */ cnt = 1; PMIX_BFROPS_UNPACK(rc, cd->peer, buf, &nprocs, &cnt, PMIX_SIZE); if (PMIX_SUCCESS != rc) { return rc; } pmix_output_verbose(2, pmix_server_globals.fence_output, "recvd fence from %s:%u with %d procs", cd->peer->info->pname.nspace, cd->peer->info->pname.rank, (int)nprocs); /* there must be at least one as the client has to at least provide * their own namespace */ if (nprocs < 1) { return PMIX_ERR_BAD_PARAM; } /* create space for the procs */ PMIX_PROC_CREATE(procs, nprocs); if (NULL == procs) { return PMIX_ERR_NOMEM; } /* unpack the procs */ cnt = nprocs; PMIX_BFROPS_UNPACK(rc, cd->peer, buf, procs, &cnt, PMIX_PROC); if (PMIX_SUCCESS != rc) { goto cleanup; } /* cycle thru the procs and check to see if any reference * a PMIx group */ nmbrs = nprocs; PMIX_CONSTRUCT(&expand, pmix_list_t); /* use groups as the outer-most loop as there will * usually not be any */ PMIX_LIST_FOREACH(grp, &pmix_server_globals.groups, pmix_group_t) { for (n=0; n < nprocs; n++) { if (PMIX_CHECK_NSPACE(procs[n].nspace, grp->grpid)) { /* we need to replace this proc with grp members */ gcd = PMIX_NEW(pmix_group_caddy_t); gcd->grp = grp; gcd->idx = n; gcd->rank = procs[n].rank; pmix_list_append(&expand, &gcd->super); /* see how many need to come across */ if (PMIX_RANK_WILDCARD == procs[n].rank) { nmbrs += grp->nmbrs - 1; // account for replacing current proc } break; } } } if (0 < pmix_list_get_size(&expand)) { PMIX_PROC_CREATE(newprocs, nmbrs); gcd = (pmix_group_caddy_t*)pmix_list_remove_first(&expand); n=0; idx = 0; while (n < nmbrs) { if (idx != gcd->idx) { memcpy(&newprocs[n], &procs[idx], sizeof(pmix_proc_t)); ++n; } else { /* if we are bringing over just one, then simply replace */ if (PMIX_RANK_WILDCARD != gcd->rank) { memcpy(&newprocs[n], &gcd->grp->members[gcd->rank], sizeof(pmix_proc_t)); ++n; } else { /* take them all */ memcpy(&newprocs[n], gcd->grp->members, gcd->grp->nmbrs * sizeof(pmix_proc_t)); n += gcd->grp->nmbrs; } PMIX_RELEASE(gcd); gcd = (pmix_group_caddy_t*)pmix_list_remove_first(&expand); } ++idx; } PMIX_PROC_FREE(procs, nprocs); procs = newprocs; nprocs = nmbrs; } PMIX_LIST_DESTRUCT(&expand); /* unpack the number of provided info structs */ cnt = 1; PMIX_BFROPS_UNPACK(rc, cd->peer, buf, &ninfo, &cnt, PMIX_SIZE); if (PMIX_SUCCESS != rc) { return rc; } if (0 < ninfo) { PMIX_INFO_CREATE(info, ninfo); if (NULL == info) { PMIX_PROC_FREE(procs, nprocs); return PMIX_ERR_NOMEM; } /* unpack the info */ cnt = ninfo; PMIX_BFROPS_UNPACK(rc, cd->peer, buf, info, &cnt, PMIX_INFO); if (PMIX_SUCCESS != rc) { goto cleanup; } /* see if we are to collect data or enforce a timeout - we don't internally care * about any other directives */ for (n=0; n < ninfo; n++) { if (PMIX_CHECK_KEY(&info[n], PMIX_COLLECT_DATA)) { collect_data = PMIX_INFO_TRUE(&info[n]); } else if (PMIX_CHECK_KEY(&info[n], PMIX_TIMEOUT)) { PMIX_VALUE_GET_NUMBER(rc, &info[n].value, tv.tv_sec, uint32_t); if (PMIX_SUCCESS != rc) { PMIX_PROC_FREE(procs, nprocs); PMIX_INFO_FREE(info, ninfo); return rc; } } } } /* find/create the local tracker for this operation */ if (NULL == (trk = get_tracker(NULL, procs, nprocs, PMIX_FENCENB_CMD))) { /* If no tracker was found - create and initialize it once */ if (NULL == (trk = new_tracker(NULL, procs, nprocs, PMIX_FENCENB_CMD))) { /* only if a bozo error occurs */ PMIX_ERROR_LOG(PMIX_ERROR); /* DO NOT HANG */ if (NULL != opcbfunc) { opcbfunc(PMIX_ERROR, cd); } rc = PMIX_ERROR; goto cleanup; } trk->type = PMIX_FENCENB_CMD; trk->modexcbfunc = modexcbfunc; /* mark if they want the data back */ if (collect_data) { trk->collect_type = PMIX_COLLECT_YES; } else { trk->collect_type = PMIX_COLLECT_NO; } } else { switch (trk->collect_type) { case PMIX_COLLECT_NO: if (collect_data) { trk->collect_type = PMIX_COLLECT_INVALID; } break; case PMIX_COLLECT_YES: if (!collect_data) { trk->collect_type = PMIX_COLLECT_INVALID; } break; default: break; } } /* we only save the info structs from the first caller * who provides them - it is a user error to provide * different values from different participants */ if (NULL == trk->info) { trk->info = info; trk->ninfo = ninfo; } else { /* cleanup */ PMIX_INFO_FREE(info, ninfo); info = NULL; } /* add this contributor to the tracker so they get * notified when we are done */ pmix_list_append(&trk->local_cbs, &cd->super); /* if a timeout was specified, set it */ if (0 < tv.tv_sec) { PMIX_RETAIN(trk); cd->trk = trk; PMIX_THREADSHIFT_DELAY(cd, fence_timeout, tv.tv_sec); cd->event_active = true; } /* if all local contributions have been received, * let the local host's server know that we are at the * "fence" point - they will callback once the barrier * across all participants has been completed */ if (trk->def_complete && pmix_list_get_size(&trk->local_cbs) == trk->nlocal) { pmix_output_verbose(2, pmix_server_globals.fence_output, "fence LOCALLY complete"); /* if this is a purely local fence (i.e., all participants are local), * then it is done and we notify accordingly */ if (pmix_server_globals.fence_localonly_opt && trk->local) { /* the modexcbfunc thread-shifts the call prior to processing, * so it is okay to call it directly from here. The switchyard * will acknowledge successful acceptance of the fence request, * but the client still requires a return from the callback in * that scenario, so we leave this caddy on the list of local cbs */ trk->modexcbfunc(PMIX_SUCCESS, NULL, 0, trk, NULL, NULL); rc = PMIX_SUCCESS; goto cleanup; } /* this fence involves non-local procs - check if the * host supports it */ if (NULL == pmix_host_server.fence_nb) { rc = PMIX_ERR_NOT_SUPPORTED; /* clear the caddy from this tracker so it can be * released upon return - the switchyard will send an * error to this caller, and so the fence completion * function doesn't need to do so */ pmix_list_remove_item(&trk->local_cbs, &cd->super); cd->trk = NULL; /* we need to ensure that all other local participants don't * just hang waiting for the error return, so execute * the fence completion function - it threadshifts the call * prior to processing, so it is okay to call it directly * from here */ trk->host_called = false; // the host will not be calling us back trk->modexcbfunc(rc, NULL, 0, trk, NULL, NULL); goto cleanup; } /* if the user asked us to collect data, then we have * to provide any locally collected data to the host * server so they can circulate it - only take data * from the specified procs as not everyone is necessarily * participating! And only take data intended for remote * or global distribution */ PMIX_CONSTRUCT(&bucket, pmix_buffer_t); if (PMIX_SUCCESS != (rc = _collect_data(trk, &bucket))) { PMIX_ERROR_LOG(rc); PMIX_DESTRUCT(&bucket); /* clear the caddy from this tracker so it can be * released upon return - the switchyard will send an * error to this caller, and so the fence completion * function doesn't need to do so */ pmix_list_remove_item(&trk->local_cbs, &cd->super); cd->trk = NULL; /* we need to ensure that all other local participants don't * just hang waiting for the error return, so execute * the fence completion function - it threadshifts the call * prior to processing, so it is okay to call it directly * from here */ trk->modexcbfunc(rc, NULL, 0, trk, NULL, NULL); goto cleanup; } /* now unload the blob and pass it upstairs */ PMIX_UNLOAD_BUFFER(&bucket, data, sz); PMIX_DESTRUCT(&bucket); trk->host_called = true; rc = pmix_host_server.fence_nb(trk->pcs, trk->npcs, trk->info, trk->ninfo, data, sz, trk->modexcbfunc, trk); if (PMIX_SUCCESS != rc && PMIX_OPERATION_SUCCEEDED != rc) { /* clear the caddy from this tracker so it can be * released upon return - the switchyard will send an * error to this caller, and so the fence completion * function doesn't need to do so */ pmix_list_remove_item(&trk->local_cbs, &cd->super); cd->trk = NULL; /* we need to ensure that all other local participants don't * just hang waiting for the error return, so execute * the fence completion function - it threadshifts the call * prior to processing, so it is okay to call it directly * from here */ trk->host_called = false; // the host will not be calling us back trk->modexcbfunc(rc, NULL, 0, trk, NULL, NULL); } else if (PMIX_OPERATION_SUCCEEDED == rc) { /* the operation was atomically completed and the host will * not be calling us back - ensure we notify all participants. * the modexcbfunc thread-shifts the call prior to processing, * so it is okay to call it directly from here */ trk->host_called = false; // the host will not be calling us back trk->modexcbfunc(PMIX_SUCCESS, NULL, 0, trk, NULL, NULL); /* ensure that the switchyard doesn't release the caddy */ rc = PMIX_SUCCESS; } } cleanup: PMIX_PROC_FREE(procs, nprocs); return rc; } static void opcbfunc(pmix_status_t status, void *cbdata) { pmix_setup_caddy_t *cd = (pmix_setup_caddy_t*)cbdata; if (NULL != cd->keys) { pmix_argv_free(cd->keys); } if (NULL != cd->codes) { free(cd->codes); } if (NULL != cd->info) { PMIX_INFO_FREE(cd->info, cd->ninfo); } if (NULL != cd->opcbfunc) { cd->opcbfunc(status, cd->cbdata); } PMIX_RELEASE(cd); } pmix_status_t pmix_server_publish(pmix_peer_t *peer, pmix_buffer_t *buf, pmix_op_cbfunc_t cbfunc, void *cbdata) { pmix_setup_caddy_t *cd; pmix_status_t rc; int32_t cnt; size_t ninfo; pmix_proc_t proc; uint32_t uid; pmix_output_verbose(2, pmix_server_globals.pub_output, "recvd PUBLISH"); if (NULL == pmix_host_server.publish) { return PMIX_ERR_NOT_SUPPORTED; } /* unpack the effective user id */ cnt=1; PMIX_BFROPS_UNPACK(rc, peer, buf, &uid, &cnt, PMIX_UINT32); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); return rc; } /* unpack the number of info objects */ cnt=1; PMIX_BFROPS_UNPACK(rc, peer, buf, &ninfo, &cnt, PMIX_SIZE); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); return rc; } /* we will be adding one for the user id */ cd = PMIX_NEW(pmix_setup_caddy_t); if (NULL == cd) { return PMIX_ERR_NOMEM; } cd->opcbfunc = cbfunc; cd->cbdata = cbdata; cd->ninfo = ninfo + 1; PMIX_INFO_CREATE(cd->info, cd->ninfo); if (NULL == cd->info) { rc = PMIX_ERR_NOMEM; goto cleanup; } /* unpack the array of info objects */ if (0 < cd->ninfo) { cnt=cd->ninfo; PMIX_BFROPS_UNPACK(rc, peer, buf, cd->info, &cnt, PMIX_INFO); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto cleanup; } } pmix_strncpy(cd->info[cd->ninfo-1].key, PMIX_USERID, PMIX_MAX_KEYLEN); cd->info[cd->ninfo-1].value.type = PMIX_UINT32; cd->info[cd->ninfo-1].value.data.uint32 = uid; /* call the local server */ pmix_strncpy(proc.nspace, peer->info->pname.nspace, PMIX_MAX_NSLEN); proc.rank = peer->info->pname.rank; rc = pmix_host_server.publish(&proc, cd->info, cd->ninfo, opcbfunc, cd); cleanup: if (PMIX_SUCCESS != rc) { if (NULL != cd->info) { PMIX_INFO_FREE(cd->info, cd->ninfo); } PMIX_RELEASE(cd); } return rc; } static void lkcbfunc(pmix_status_t status, pmix_pdata_t data[], size_t ndata, void *cbdata) { pmix_setup_caddy_t *cd = (pmix_setup_caddy_t*)cbdata; /* cleanup the caddy */ if (NULL != cd->keys) { pmix_argv_free(cd->keys); } if (NULL != cd->info) { PMIX_INFO_FREE(cd->info, cd->ninfo); } /* return the results */ if (NULL != cd->lkcbfunc) { cd->lkcbfunc(status, data, ndata, cd->cbdata); } PMIX_RELEASE(cd); } pmix_status_t pmix_server_lookup(pmix_peer_t *peer, pmix_buffer_t *buf, pmix_lookup_cbfunc_t cbfunc, void *cbdata) { pmix_setup_caddy_t *cd; int32_t cnt; pmix_status_t rc; size_t nkeys, i; char *sptr; size_t ninfo; pmix_proc_t proc; uint32_t uid; pmix_output_verbose(2, pmix_server_globals.pub_output, "recvd LOOKUP"); if (NULL == pmix_host_server.lookup) { return PMIX_ERR_NOT_SUPPORTED; } /* unpack the effective user id */ cnt=1; PMIX_BFROPS_UNPACK(rc, peer, buf, &uid, &cnt, PMIX_UINT32); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); return rc; } /* unpack the number of keys */ cnt=1; PMIX_BFROPS_UNPACK(rc, peer, buf, &nkeys, &cnt, PMIX_SIZE); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); return rc; } /* setup the caddy */ cd = PMIX_NEW(pmix_setup_caddy_t); if (NULL == cd) { return PMIX_ERR_NOMEM; } cd->lkcbfunc = cbfunc; cd->cbdata = cbdata; /* unpack the array of keys */ for (i=0; i < nkeys; i++) { cnt=1; PMIX_BFROPS_UNPACK(rc, peer, buf, &sptr, &cnt, PMIX_STRING); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto cleanup; } pmix_argv_append_nosize(&cd->keys, sptr); free(sptr); } /* unpack the number of info objects */ cnt=1; PMIX_BFROPS_UNPACK(rc, peer, buf, &ninfo, &cnt, PMIX_SIZE); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto cleanup; } /* we will be adding one for the user id */ cd->ninfo = ninfo + 1; PMIX_INFO_CREATE(cd->info, cd->ninfo); if (NULL == cd->info) { rc = PMIX_ERR_NOMEM; goto cleanup; } /* unpack the array of info objects */ if (0 < ninfo) { cnt=ninfo; PMIX_BFROPS_UNPACK(rc, peer, buf, cd->info, &cnt, PMIX_INFO); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto cleanup; } } pmix_strncpy(cd->info[cd->ninfo-1].key, PMIX_USERID, PMIX_MAX_KEYLEN); cd->info[cd->ninfo-1].value.type = PMIX_UINT32; cd->info[cd->ninfo-1].value.data.uint32 = uid; /* call the local server */ pmix_strncpy(proc.nspace, peer->info->pname.nspace, PMIX_MAX_NSLEN); proc.rank = peer->info->pname.rank; rc = pmix_host_server.lookup(&proc, cd->keys, cd->info, cd->ninfo, lkcbfunc, cd); cleanup: if (PMIX_SUCCESS != rc) { if (NULL != cd->keys) { pmix_argv_free(cd->keys); } if (NULL != cd->info) { PMIX_INFO_FREE(cd->info, cd->ninfo); } PMIX_RELEASE(cd); } return rc; } pmix_status_t pmix_server_unpublish(pmix_peer_t *peer, pmix_buffer_t *buf, pmix_op_cbfunc_t cbfunc, void *cbdata) { pmix_setup_caddy_t *cd; int32_t cnt; pmix_status_t rc; size_t i, nkeys, ninfo; char *sptr; pmix_proc_t proc; uint32_t uid; pmix_output_verbose(2, pmix_server_globals.pub_output, "recvd UNPUBLISH"); if (NULL == pmix_host_server.unpublish) { return PMIX_ERR_NOT_SUPPORTED; } /* unpack the effective user id */ cnt=1; PMIX_BFROPS_UNPACK(rc, peer, buf, &uid, &cnt, PMIX_UINT32); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); return rc; } /* unpack the number of keys */ cnt=1; PMIX_BFROPS_UNPACK(rc, peer, buf, &nkeys, &cnt, PMIX_SIZE); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); return rc; } /* setup the caddy */ cd = PMIX_NEW(pmix_setup_caddy_t); if (NULL == cd) { return PMIX_ERR_NOMEM; } cd->opcbfunc = cbfunc; cd->cbdata = cbdata; /* unpack the array of keys */ for (i=0; i < nkeys; i++) { cnt=1; PMIX_BFROPS_UNPACK(rc, peer, buf, &sptr, &cnt, PMIX_STRING); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto cleanup; } pmix_argv_append_nosize(&cd->keys, sptr); free(sptr); } /* unpack the number of info objects */ cnt=1; PMIX_BFROPS_UNPACK(rc, peer, buf, &ninfo, &cnt, PMIX_SIZE); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto cleanup; } /* we will be adding one for the user id */ cd->ninfo = ninfo + 1; PMIX_INFO_CREATE(cd->info, cd->ninfo); if (NULL == cd->info) { rc = PMIX_ERR_NOMEM; goto cleanup; } /* unpack the array of info objects */ if (0 < ninfo) { cnt=ninfo; PMIX_BFROPS_UNPACK(rc, peer, buf, cd->info, &cnt, PMIX_INFO); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto cleanup; } } pmix_strncpy(cd->info[cd->ninfo-1].key, PMIX_USERID, PMIX_MAX_KEYLEN); cd->info[cd->ninfo-1].value.type = PMIX_UINT32; cd->info[cd->ninfo-1].value.data.uint32 = uid; /* call the local server */ pmix_strncpy(proc.nspace, peer->info->pname.nspace, PMIX_MAX_NSLEN); proc.rank = peer->info->pname.rank; rc = pmix_host_server.unpublish(&proc, cd->keys, cd->info, cd->ninfo, opcbfunc, cd); cleanup: if (PMIX_SUCCESS != rc) { if (NULL != cd->keys) { pmix_argv_free(cd->keys); } if (NULL != cd->info) { PMIX_INFO_FREE(cd->info, cd->ninfo); } PMIX_RELEASE(cd); } return rc; } static void spcbfunc(pmix_status_t status, char nspace[], void *cbdata) { pmix_setup_caddy_t *cd = (pmix_setup_caddy_t*)cbdata; pmix_iof_req_t *req; pmix_buffer_t *msg; pmix_status_t rc; pmix_iof_cache_t *iof, *ionext; /* if it was successful, and there are IOF requests, then * register them now */ if (PMIX_SUCCESS == status && PMIX_FWD_NO_CHANNELS != cd->channels) { /* record the request */ req = PMIX_NEW(pmix_iof_req_t); if (NULL == req) { status = PMIX_ERR_NOMEM; goto cleanup; } PMIX_RETAIN(cd->peer); req->requestor = cd->peer; req->nprocs = 1; PMIX_PROC_CREATE(req->procs, req->nprocs); PMIX_LOAD_PROCID(&req->procs[0], nspace, PMIX_RANK_WILDCARD); req->channels = cd->channels; req->local_id = pmix_pointer_array_add(&pmix_globals.iof_requests, req); /* process any cached IO */ PMIX_LIST_FOREACH_SAFE(iof, ionext, &pmix_server_globals.iof, pmix_iof_cache_t) { /* if the channels don't match, then ignore it */ if (!(iof->channel & req->channels)) { continue; } /* if the source does not match the request, then ignore it */ if (!PMIX_CHECK_PROCID(&iof->source, &req->procs[0])) { continue; } /* never forward back to the source! This can happen if the source * is a launcher */ if (PMIX_CHECK_PROCID(&iof->source, &req->requestor->info->pname)) { continue; } pmix_output_verbose(2, pmix_server_globals.iof_output, "PMIX:SERVER:SPAWN delivering cached IOF from %s:%d to %s:%d", iof->source.nspace, iof->source.rank, req->requestor->info->pname.nspace, req->requestor->info->pname.rank); /* setup the msg */ if (NULL == (msg = PMIX_NEW(pmix_buffer_t))) { PMIX_ERROR_LOG(PMIX_ERR_OUT_OF_RESOURCE); rc = PMIX_ERR_OUT_OF_RESOURCE; break; } /* provide the source */ PMIX_BFROPS_PACK(rc, req->requestor, msg, &iof->source, 1, PMIX_PROC); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); PMIX_RELEASE(msg); break; } /* provide the channel */ PMIX_BFROPS_PACK(rc, req->requestor, msg, &iof->channel, 1, PMIX_IOF_CHANNEL); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); PMIX_RELEASE(msg); break; } /* provide their local id */ PMIX_BFROPS_PACK(rc, req->requestor, msg, &req->remote_id, 1, PMIX_SIZE); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); PMIX_RELEASE(msg); break; } /* provide any cached info */ PMIX_BFROPS_PACK(rc, req->requestor, msg, &iof->ninfo, 1, PMIX_SIZE); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); PMIX_RELEASE(msg); break; } if (0 < iof->ninfo) { PMIX_BFROPS_PACK(rc, req->requestor, msg, iof->info, iof->ninfo, PMIX_INFO); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); PMIX_RELEASE(msg); break; } } /* pack the data */ PMIX_BFROPS_PACK(rc, req->requestor, msg, iof->bo, 1, PMIX_BYTE_OBJECT); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); PMIX_RELEASE(msg); break; } /* send it to the requestor */ PMIX_PTL_SEND_ONEWAY(rc, req->requestor, msg, PMIX_PTL_TAG_IOF); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); PMIX_RELEASE(msg); } /* remove it from the list since it has now been forwarded */ pmix_list_remove_item(&pmix_server_globals.iof, &iof->super); PMIX_RELEASE(iof); } } cleanup: /* cleanup the caddy */ if (NULL != cd->info) { PMIX_INFO_FREE(cd->info, cd->ninfo); } if (NULL != cd->apps) { PMIX_APP_FREE(cd->apps, cd->napps); } if (NULL != cd->spcbfunc) { cd->spcbfunc(status, nspace, cd->cbdata); } PMIX_RELEASE(cd); } pmix_status_t pmix_server_spawn(pmix_peer_t *peer, pmix_buffer_t *buf, pmix_spawn_cbfunc_t cbfunc, void *cbdata) { pmix_setup_caddy_t *cd; int32_t cnt; pmix_status_t rc; pmix_proc_t proc; size_t ninfo, n; bool stdout_found = false, stderr_found = false, stddiag_found = false; pmix_output_verbose(2, pmix_server_globals.spawn_output, "recvd SPAWN from %s:%d", peer->info->pname.nspace, peer->info->pname.rank); if (NULL == pmix_host_server.spawn) { return PMIX_ERR_NOT_SUPPORTED; } /* setup */ cd = PMIX_NEW(pmix_setup_caddy_t); if (NULL == cd) { return PMIX_ERR_NOMEM; } PMIX_RETAIN(peer); cd->peer = peer; cd->spcbfunc = cbfunc; cd->cbdata = cbdata; /* unpack the number of job-level directives */ cnt=1; PMIX_BFROPS_UNPACK(rc, peer, buf, &ninfo, &cnt, PMIX_SIZE); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); PMIX_RELEASE(cd); return rc; } /* always add one directive that indicates whether the requestor * is a tool or client */ cd->ninfo = ninfo + 1; PMIX_INFO_CREATE(cd->info, cd->ninfo); if (NULL == cd->info) { rc = PMIX_ERR_NOMEM; goto cleanup; } /* unpack the array of directives */ if (0 < ninfo) { cnt = ninfo; PMIX_BFROPS_UNPACK(rc, peer, buf, cd->info, &cnt, PMIX_INFO); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto cleanup; } /* run a quick check of the directives to see if any IOF * requests were included so we can set that up now - helps * to catch any early output - and a request for notification * of job termination so we can setup the event registration */ cd->channels = PMIX_FWD_NO_CHANNELS; for (n=0; n < cd->ninfo; n++) { if (0 == strncmp(cd->info[n].key, PMIX_FWD_STDIN, PMIX_MAX_KEYLEN)) { if (PMIX_INFO_TRUE(&cd->info[n])) { cd->channels |= PMIX_FWD_STDIN_CHANNEL; } } else if (0 == strncmp(cd->info[n].key, PMIX_FWD_STDOUT, PMIX_MAX_KEYLEN)) { stdout_found = true; if (PMIX_INFO_TRUE(&cd->info[n])) { cd->channels |= PMIX_FWD_STDOUT_CHANNEL; } } else if (0 == strncmp(cd->info[n].key, PMIX_FWD_STDERR, PMIX_MAX_KEYLEN)) { stderr_found = true; if (PMIX_INFO_TRUE(&cd->info[n])) { cd->channels |= PMIX_FWD_STDERR_CHANNEL; } } else if (0 == strncmp(cd->info[n].key, PMIX_FWD_STDDIAG, PMIX_MAX_KEYLEN)) { stddiag_found = true; if (PMIX_INFO_TRUE(&cd->info[n])) { cd->channels |= PMIX_FWD_STDDIAG_CHANNEL; } } } /* we will construct any required iof request tracker upon completion of the spawn * as we need the nspace of the spawned application! */ } /* add the directive to the end */ if (PMIX_PEER_IS_TOOL(peer)) { PMIX_INFO_LOAD(&cd->info[ninfo], PMIX_REQUESTOR_IS_TOOL, NULL, PMIX_BOOL); /* if the requestor is a tool, we default to forwarding all * output IO channels */ if (!stdout_found) { cd->channels |= PMIX_FWD_STDOUT_CHANNEL; } if (!stderr_found) { cd->channels |= PMIX_FWD_STDERR_CHANNEL; } if (!stddiag_found) { cd->channels |= PMIX_FWD_STDDIAG_CHANNEL; } } else { PMIX_INFO_LOAD(&cd->info[ninfo], PMIX_REQUESTOR_IS_CLIENT, NULL, PMIX_BOOL); } /* unpack the number of apps */ cnt=1; PMIX_BFROPS_UNPACK(rc, peer, buf, &cd->napps, &cnt, PMIX_SIZE); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto cleanup; } /* unpack the array of apps */ if (0 < cd->napps) { PMIX_APP_CREATE(cd->apps, cd->napps); if (NULL == cd->apps) { rc = PMIX_ERR_NOMEM; goto cleanup; } cnt = cd->napps; PMIX_BFROPS_UNPACK(rc, peer, buf, cd->apps, &cnt, PMIX_APP); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto cleanup; } } /* call the local server */ PMIX_LOAD_PROCID(&proc, peer->info->pname.nspace, peer->info->pname.rank); rc = pmix_host_server.spawn(&proc, cd->info, cd->ninfo, cd->apps, cd->napps, spcbfunc, cd); cleanup: if (PMIX_SUCCESS != rc) { if (NULL != cd->info) { PMIX_INFO_FREE(cd->info, cd->ninfo); } if (NULL != cd->apps) { PMIX_APP_FREE(cd->apps, cd->napps); } PMIX_RELEASE(cd); } return rc; } pmix_status_t pmix_server_disconnect(pmix_server_caddy_t *cd, pmix_buffer_t *buf, pmix_op_cbfunc_t cbfunc) { int32_t cnt; pmix_status_t rc; pmix_info_t *info = NULL; size_t nprocs, ninfo; pmix_server_trkr_t *trk; pmix_proc_t *procs = NULL; if (NULL == pmix_host_server.disconnect) { return PMIX_ERR_NOT_SUPPORTED; } /* unpack the number of procs */ cnt = 1; PMIX_BFROPS_UNPACK(rc, cd->peer, buf, &nprocs, &cnt, PMIX_SIZE); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto cleanup; } /* there must be at least one proc - we do not allow the client * to send us NULL proc as the server has no idea what to do * with that situation. Instead, the client should at least send * us their own namespace for the use-case where the connection * spans all procs in that namespace */ if (nprocs < 1) { PMIX_ERROR_LOG(PMIX_ERR_BAD_PARAM); rc = PMIX_ERR_BAD_PARAM; goto cleanup; } /* unpack the procs */ PMIX_PROC_CREATE(procs, nprocs); if (NULL == procs) { rc = PMIX_ERR_NOMEM; goto cleanup; } cnt = nprocs; PMIX_BFROPS_UNPACK(rc, cd->peer, buf, procs, &cnt, PMIX_PROC); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto cleanup; } /* unpack the number of provided info structs */ cnt = 1; PMIX_BFROPS_UNPACK(rc, cd->peer, buf, &ninfo, &cnt, PMIX_SIZE); if (PMIX_SUCCESS != rc) { return rc; } if (0 < ninfo) { PMIX_INFO_CREATE(info, ninfo); if (NULL == info) { rc = PMIX_ERR_NOMEM; goto cleanup; } /* unpack the info */ cnt = ninfo; PMIX_BFROPS_UNPACK(rc, cd->peer, buf, info, &cnt, PMIX_INFO); if (PMIX_SUCCESS != rc) { goto cleanup; } } /* find/create the local tracker for this operation */ if (NULL == (trk = get_tracker(NULL, procs, nprocs, PMIX_DISCONNECTNB_CMD))) { /* we don't have this tracker yet, so get a new one */ if (NULL == (trk = new_tracker(NULL, procs, nprocs, PMIX_DISCONNECTNB_CMD))) { /* only if a bozo error occurs */ PMIX_ERROR_LOG(PMIX_ERROR); rc = PMIX_ERROR; goto cleanup; } trk->op_cbfunc = cbfunc; } /* if the info keys have not been provided yet, pass * them along here */ if (NULL == trk->info && NULL != info) { trk->info = info; trk->ninfo = ninfo; info = NULL; ninfo = 0; } /* add this contributor to the tracker so they get * notified when we are done */ pmix_list_append(&trk->local_cbs, &cd->super); /* if all local contributions have been received, * let the local host's server know that we are at the * "fence" point - they will callback once the [dis]connect * across all participants has been completed */ if (trk->def_complete && pmix_list_get_size(&trk->local_cbs) == trk->nlocal) { trk->host_called = true; rc = pmix_host_server.disconnect(trk->pcs, trk->npcs, trk->info, trk->ninfo, cbfunc, trk); if (PMIX_SUCCESS != rc && PMIX_OPERATION_SUCCEEDED != rc) { /* clear the caddy from this tracker so it can be * released upon return - the switchyard will send an * error to this caller, and so the op completion * function doesn't need to do so */ pmix_list_remove_item(&trk->local_cbs, &cd->super); cd->trk = NULL; /* we need to ensure that all other local participants don't * just hang waiting for the error return, so execute * the op completion function - it threadshifts the call * prior to processing, so it is okay to call it directly * from here */ trk->host_called = false; // the host will not be calling us back cbfunc(rc, trk); } else if (PMIX_OPERATION_SUCCEEDED == rc) { /* the operation was atomically completed and the host will * not be calling us back - ensure we notify all participants. * the cbfunc thread-shifts the call prior to processing, * so it is okay to call it directly from here */ trk->host_called = false; // the host will not be calling us back cbfunc(PMIX_SUCCESS, trk); /* ensure that the switchyard doesn't release the caddy */ rc = PMIX_SUCCESS; } } else { rc = PMIX_SUCCESS; } cleanup: if (NULL != info) { PMIX_INFO_FREE(info, ninfo); } return rc; } static void connect_timeout(int sd, short args, void *cbdata) { pmix_server_caddy_t *cd = (pmix_server_caddy_t*)cbdata; pmix_output_verbose(2, pmix_server_globals.connect_output, "ALERT: connect timeout fired"); /* execute the provided callback function with the error */ if (NULL != cd->trk->op_cbfunc) { cd->trk->op_cbfunc(PMIX_ERR_TIMEOUT, cd->trk); return; // the cbfunc will have cleaned up the tracker } cd->event_active = false; /* remove it from the list */ pmix_list_remove_item(&cd->trk->local_cbs, &cd->super); PMIX_RELEASE(cd); } pmix_status_t pmix_server_connect(pmix_server_caddy_t *cd, pmix_buffer_t *buf, pmix_op_cbfunc_t cbfunc) { int32_t cnt; pmix_status_t rc; pmix_proc_t *procs = NULL; pmix_info_t *info = NULL; size_t nprocs, ninfo, n; pmix_server_trkr_t *trk; struct timeval tv = {0, 0}; pmix_output_verbose(2, pmix_server_globals.connect_output, "recvd CONNECT from peer %s:%d", cd->peer->info->pname.nspace, cd->peer->info->pname.rank); if (NULL == pmix_host_server.connect) { return PMIX_ERR_NOT_SUPPORTED; } /* unpack the number of procs */ cnt = 1; PMIX_BFROPS_UNPACK(rc, cd->peer, buf, &nprocs, &cnt, PMIX_SIZE); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto cleanup; } /* there must be at least one proc - we do not allow the client * to send us NULL proc as the server has no idea what to do * with that situation. Instead, the client should at least send * us their own namespace for the use-case where the connection * spans all procs in that namespace */ if (nprocs < 1) { PMIX_ERROR_LOG(PMIX_ERR_BAD_PARAM); rc = PMIX_ERR_BAD_PARAM; goto cleanup; } /* unpack the procs */ PMIX_PROC_CREATE(procs, nprocs); if (NULL == procs) { rc = PMIX_ERR_NOMEM; goto cleanup; } cnt = nprocs; PMIX_BFROPS_UNPACK(rc, cd->peer, buf, procs, &cnt, PMIX_PROC); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto cleanup; } /* unpack the number of provided info structs */ cnt = 1; PMIX_BFROPS_UNPACK(rc, cd->peer, buf, &ninfo, &cnt, PMIX_SIZE); if (PMIX_SUCCESS != rc) { return rc; } if (0 < ninfo) { PMIX_INFO_CREATE(info, ninfo); if (NULL == info) { rc = PMIX_ERR_NOMEM; goto cleanup; } /* unpack the info */ cnt = ninfo; PMIX_BFROPS_UNPACK(rc, cd->peer, buf, info, &cnt, PMIX_INFO); if (PMIX_SUCCESS != rc) { goto cleanup; } /* check for a timeout */ for (n=0; n < ninfo; n++) { if (0 == strncmp(info[n].key, PMIX_TIMEOUT, PMIX_MAX_KEYLEN)) { tv.tv_sec = info[n].value.data.uint32; break; } } } /* find/create the local tracker for this operation */ if (NULL == (trk = get_tracker(NULL, procs, nprocs, PMIX_CONNECTNB_CMD))) { /* we don't have this tracker yet, so get a new one */ if (NULL == (trk = new_tracker(NULL, procs, nprocs, PMIX_CONNECTNB_CMD))) { /* only if a bozo error occurs */ PMIX_ERROR_LOG(PMIX_ERROR); /* DO NOT HANG */ if (NULL != cbfunc) { cbfunc(PMIX_ERROR, cd); } rc = PMIX_ERROR; goto cleanup; } trk->op_cbfunc = cbfunc; } /* if the info keys have not been provided yet, pass * them along here */ if (NULL == trk->info && NULL != info) { trk->info = info; trk->ninfo = ninfo; info = NULL; ninfo = 0; } /* add this contributor to the tracker so they get * notified when we are done */ pmix_list_append(&trk->local_cbs, &cd->super); /* if all local contributions have been received, * let the local host's server know that we are at the * "fence" point - they will callback once the [dis]connect * across all participants has been completed */ if (trk->def_complete && pmix_list_get_size(&trk->local_cbs) == trk->nlocal) { trk->host_called = true; rc = pmix_host_server.connect(trk->pcs, trk->npcs, trk->info, trk->ninfo, cbfunc, trk); if (PMIX_SUCCESS != rc && PMIX_OPERATION_SUCCEEDED != rc) { /* clear the caddy from this tracker so it can be * released upon return - the switchyard will send an * error to this caller, and so the op completion * function doesn't need to do so */ pmix_list_remove_item(&trk->local_cbs, &cd->super); cd->trk = NULL; /* we need to ensure that all other local participants don't * just hang waiting for the error return, so execute * the op completion function - it threadshifts the call * prior to processing, so it is okay to call it directly * from here */ trk->host_called = false; // the host will not be calling us back cbfunc(rc, trk); } else if (PMIX_OPERATION_SUCCEEDED == rc) { /* the operation was atomically completed and the host will * not be calling us back - ensure we notify all participants. * the cbfunc thread-shifts the call prior to processing, * so it is okay to call it directly from here */ trk->host_called = false; // the host will not be calling us back cbfunc(PMIX_SUCCESS, trk); /* ensure that the switchyard doesn't release the caddy */ rc = PMIX_SUCCESS; } } else { rc = PMIX_SUCCESS; } /* if a timeout was specified, set it */ if (PMIX_SUCCESS == rc && 0 < tv.tv_sec) { PMIX_RETAIN(trk); cd->trk = trk; PMIX_THREADSHIFT_DELAY(cd, connect_timeout, tv.tv_sec); cd->event_active = true; } cleanup: if (NULL != procs) { PMIX_PROC_FREE(procs, nprocs); } if (NULL != info) { PMIX_INFO_FREE(info, ninfo); } return rc; } static void _check_cached_events(int sd, short args, void *cbdata) { pmix_setup_caddy_t *scd = (pmix_setup_caddy_t*)cbdata; pmix_notify_caddy_t *cd; pmix_range_trkr_t rngtrk; pmix_proc_t proc; int i; size_t k, n; bool found, matched; pmix_buffer_t *relay; pmix_status_t ret = PMIX_SUCCESS; pmix_cmd_t cmd = PMIX_NOTIFY_CMD; /* check if any matching notifications have been cached */ rngtrk.procs = NULL; rngtrk.nprocs = 0; for (i=0; i < pmix_globals.max_events; i++) { pmix_hotel_knock(&pmix_globals.notifications, i, (void**)&cd); if (NULL == cd) { continue; } found = false; if (NULL == scd->codes) { if (!cd->nondefault) { /* they registered a default event handler - always matches */ found = true; } } else { for (k=0; k < scd->ncodes; k++) { if (scd->codes[k] == cd->status) { found = true; break; } } } if (!found) { continue; } /* check if the affected procs (if given) match those they * wanted to know about */ if (!pmix_notify_check_affected(cd->affected, cd->naffected, scd->procs, scd->nprocs)) { continue; } /* check the range */ if (NULL == cd->targets) { rngtrk.procs = &cd->source; rngtrk.nprocs = 1; } else { rngtrk.procs = cd->targets; rngtrk.nprocs = cd->ntargets; } rngtrk.range = cd->range; PMIX_LOAD_PROCID(&proc, scd->peer->info->pname.nspace, scd->peer->info->pname.rank); if (!pmix_notify_check_range(&rngtrk, &proc)) { continue; } /* if we were given specific targets, check if this is one */ found = false; if (NULL != cd->targets) { matched = false; for (n=0; n < cd->ntargets; n++) { /* if the source of the event is the same peer just registered, then ignore it * as the event notification system will have already locally * processed it */ if (PMIX_CHECK_PROCID(&cd->source, &scd->peer->info->pname)) { continue; } if (PMIX_CHECK_PROCID(&scd->peer->info->pname, &cd->targets[n])) { matched = true; /* track the number of targets we have left to notify */ --cd->nleft; /* if this is the last one, then evict this event * from the cache */ if (0 == cd->nleft) { pmix_hotel_checkout(&pmix_globals.notifications, cd->room); found = true; // mark that we should release cd } break; } } if (!matched) { /* do not notify this one */ continue; } } /* all matches - notify */ relay = PMIX_NEW(pmix_buffer_t); if (NULL == relay) { /* nothing we can do */ PMIX_ERROR_LOG(PMIX_ERR_NOMEM); ret = PMIX_ERR_NOMEM; break; } /* pack the info data stored in the event */ PMIX_BFROPS_PACK(ret, scd->peer, relay, &cmd, 1, PMIX_COMMAND); if (PMIX_SUCCESS != ret) { PMIX_ERROR_LOG(ret); break; } PMIX_BFROPS_PACK(ret, scd->peer, relay, &cd->status, 1, PMIX_STATUS); if (PMIX_SUCCESS != ret) { PMIX_ERROR_LOG(ret); break; } PMIX_BFROPS_PACK(ret, scd->peer, relay, &cd->source, 1, PMIX_PROC); if (PMIX_SUCCESS != ret) { PMIX_ERROR_LOG(ret); break; } PMIX_BFROPS_PACK(ret, scd->peer, relay, &cd->ninfo, 1, PMIX_SIZE); if (PMIX_SUCCESS != ret) { PMIX_ERROR_LOG(ret); break; } if (0 < cd->ninfo) { PMIX_BFROPS_PACK(ret, scd->peer, relay, cd->info, cd->ninfo, PMIX_INFO); if (PMIX_SUCCESS != ret) { PMIX_ERROR_LOG(ret); break; } } PMIX_SERVER_QUEUE_REPLY(ret, scd->peer, 0, relay); if (PMIX_SUCCESS != ret) { PMIX_RELEASE(relay); } if (found) { PMIX_RELEASE(cd); } } /* release the caddy */ if (NULL != scd->codes) { free(scd->codes); } if (NULL != scd->info) { PMIX_INFO_FREE(scd->info, scd->ninfo); } if (NULL != scd->opcbfunc) { scd->opcbfunc(ret, scd->cbdata); } PMIX_RELEASE(scd); } /* provide a callback function for the host when it finishes * processing the registration */ static void regevopcbfunc(pmix_status_t status, void *cbdata) { pmix_setup_caddy_t *cd = (pmix_setup_caddy_t*)cbdata; /* if the registration succeeded, then check local cache */ if (PMIX_SUCCESS == status) { _check_cached_events(0, 0, cd); return; } /* it didn't succeed, so cleanup and execute the callback * so we don't hang */ if (NULL != cd->codes) { free(cd->codes); } if (NULL != cd->info) { PMIX_INFO_FREE(cd->info, cd->ninfo); } if (NULL != cd->opcbfunc) { cd->opcbfunc(status, cd->cbdata); } PMIX_RELEASE(cd); } pmix_status_t pmix_server_register_events(pmix_peer_t *peer, pmix_buffer_t *buf, pmix_op_cbfunc_t cbfunc, void *cbdata) { int32_t cnt; pmix_status_t rc; pmix_status_t *codes = NULL; pmix_info_t *info = NULL; size_t ninfo=0, ncodes, n; pmix_regevents_info_t *reginfo; pmix_peer_events_info_t *prev = NULL; pmix_setup_caddy_t *scd; bool enviro_events = false; bool found; pmix_proc_t *affected = NULL; size_t naffected = 0; pmix_output_verbose(2, pmix_server_globals.event_output, "recvd register events for peer %s:%d", peer->info->pname.nspace, peer->info->pname.rank); /* unpack the number of codes */ cnt=1; PMIX_BFROPS_UNPACK(rc, peer, buf, &ncodes, &cnt, PMIX_SIZE); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); return rc; } /* unpack the array of codes */ if (0 < ncodes) { codes = (pmix_status_t*)malloc(ncodes * sizeof(pmix_status_t)); if (NULL == codes) { rc = PMIX_ERR_NOMEM; goto cleanup; } cnt=ncodes; PMIX_BFROPS_UNPACK(rc, peer, buf, codes, &cnt, PMIX_STATUS); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto cleanup; } } /* unpack the number of info objects */ cnt=1; PMIX_BFROPS_UNPACK(rc, peer, buf, &ninfo, &cnt, PMIX_SIZE); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); return rc; } /* unpack the array of info objects */ if (0 < ninfo) { PMIX_INFO_CREATE(info, ninfo); if (NULL == info) { rc = PMIX_ERR_NOMEM; goto cleanup; } cnt=ninfo; PMIX_BFROPS_UNPACK(rc, peer, buf, info, &cnt, PMIX_INFO); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto cleanup; } } /* check the directives */ for (n=0; n < ninfo; n++) { if (PMIX_CHECK_KEY(&info[n], PMIX_EVENT_AFFECTED_PROC)) { if (NULL != affected) { PMIX_ERROR_LOG(PMIX_ERR_BAD_PARAM); rc = PMIX_ERR_BAD_PARAM; goto cleanup; } naffected = 1; PMIX_PROC_CREATE(affected, naffected); memcpy(affected, info[n].value.data.proc, sizeof(pmix_proc_t)); } else if (PMIX_CHECK_KEY(&info[n], PMIX_EVENT_AFFECTED_PROCS)) { if (NULL != affected) { PMIX_ERROR_LOG(PMIX_ERR_BAD_PARAM); rc = PMIX_ERR_BAD_PARAM; goto cleanup; } naffected = info[n].value.data.darray->size; PMIX_PROC_CREATE(affected, naffected); memcpy(affected, info[n].value.data.darray->array, naffected * sizeof(pmix_proc_t)); } } /* check the codes for system events */ for (n=0; n < ncodes; n++) { if (PMIX_SYSTEM_EVENT(codes[n])) { enviro_events = true; break; } } /* if they asked for enviro events, and our host doesn't support * register_events, then we cannot meet the request */ if (enviro_events && NULL == pmix_host_server.register_events) { enviro_events = false; rc = PMIX_ERR_NOT_SUPPORTED; goto cleanup; } /* if they didn't send us any codes, then they are registering a * default event handler. In that case, check only for default * handlers and add this request to it, if not already present */ if (0 == ncodes) { PMIX_LIST_FOREACH(reginfo, &pmix_server_globals.events, pmix_regevents_info_t) { if (PMIX_MAX_ERR_CONSTANT == reginfo->code) { /* both are default handlers */ prev = PMIX_NEW(pmix_peer_events_info_t); if (NULL == prev) { rc = PMIX_ERR_NOMEM; goto cleanup; } PMIX_RETAIN(peer); prev->peer = peer; if (NULL != affected) { PMIX_PROC_CREATE(prev->affected, naffected); prev->naffected = naffected; memcpy(prev->affected, affected, naffected * sizeof(pmix_proc_t)); } pmix_list_append(&reginfo->peers, &prev->super); break; } } rc = PMIX_OPERATION_SUCCEEDED; goto cleanup; } /* store the event registration info so we can call the registered * client when the server notifies the event */ for (n=0; n < ncodes; n++) { found = false; PMIX_LIST_FOREACH(reginfo, &pmix_server_globals.events, pmix_regevents_info_t) { if (PMIX_MAX_ERR_CONSTANT == reginfo->code) { continue; } else if (codes[n] == reginfo->code) { found = true; break; } } if (found) { /* found it - add this request */ prev = PMIX_NEW(pmix_peer_events_info_t); if (NULL == prev) { rc = PMIX_ERR_NOMEM; goto cleanup; } PMIX_RETAIN(peer); prev->peer = peer; if (NULL != affected) { PMIX_PROC_CREATE(prev->affected, naffected); prev->naffected = naffected; memcpy(prev->affected, affected, naffected * sizeof(pmix_proc_t)); } prev->enviro_events = enviro_events; pmix_list_append(&reginfo->peers, &prev->super); } else { /* if we get here, then we didn't find an existing registration for this code */ reginfo = PMIX_NEW(pmix_regevents_info_t); if (NULL == reginfo) { rc = PMIX_ERR_NOMEM; goto cleanup; } reginfo->code = codes[n]; pmix_list_append(&pmix_server_globals.events, &reginfo->super); prev = PMIX_NEW(pmix_peer_events_info_t); if (NULL == prev) { rc = PMIX_ERR_NOMEM; goto cleanup; } PMIX_RETAIN(peer); prev->peer = peer; if (NULL != affected) { PMIX_PROC_CREATE(prev->affected, naffected); prev->naffected = naffected; memcpy(prev->affected, affected, naffected * sizeof(pmix_proc_t)); } prev->enviro_events = enviro_events; pmix_list_append(&reginfo->peers, &prev->super); } } /* if they asked for enviro events, call the local server */ if (enviro_events) { /* if they don't support this, then we cannot do it */ if (NULL == pmix_host_server.register_events) { rc = PMIX_ERR_NOT_SUPPORTED; goto cleanup; } /* need to ensure the arrays don't go away until after the * host RM is done with them */ scd = PMIX_NEW(pmix_setup_caddy_t); if (NULL == scd) { rc = PMIX_ERR_NOMEM; goto cleanup; } PMIX_RETAIN(peer); scd->peer = peer; scd->codes = codes; scd->ncodes = ncodes; scd->info = info; scd->ninfo = ninfo; scd->opcbfunc = cbfunc; scd->cbdata = cbdata; if (PMIX_SUCCESS == (rc = pmix_host_server.register_events(scd->codes, scd->ncodes, scd->info, scd->ninfo, regevopcbfunc, scd))) { /* the host will call us back when completed */ pmix_output_verbose(2, pmix_server_globals.event_output, "server register events: host server processing event registration"); if (NULL != affected) { free(affected); } return rc; } else if (PMIX_OPERATION_SUCCEEDED == rc) { /* we need to check cached notifications, but we want to ensure * that occurs _after_ the client returns from registering the * event handler in case the event is flagged for do_not_cache. * Setup an event to fire after we return as that means it will * occur after we send the registration response back to the client, * thus guaranteeing that the client will get their registration * callback prior to delivery of an event notification */ PMIX_RETAIN(peer); scd->peer = peer; scd->procs = affected; scd->nprocs = naffected; scd->opcbfunc = NULL; scd->cbdata = NULL; PMIX_THREADSHIFT(scd, _check_cached_events); return rc; } else { /* host returned a genuine error and won't be calling the callback function */ pmix_output_verbose(2, pmix_server_globals.event_output, "server register events: host server reg events returned rc =%d", rc); PMIX_RELEASE(scd); goto cleanup; } } else { rc = PMIX_OPERATION_SUCCEEDED; /* we need to check cached notifications, but we want to ensure * that occurs _after_ the client returns from registering the * event handler in case the event is flagged for do_not_cache. * Setup an event to fire after we return as that means it will * occur after we send the registration response back to the client, * thus guaranteeing that the client will get their registration * callback prior to delivery of an event notification */ scd = PMIX_NEW(pmix_setup_caddy_t); PMIX_RETAIN(peer); scd->peer = peer; scd->codes = codes; scd->ncodes = ncodes; scd->procs = affected; scd->nprocs = naffected; scd->opcbfunc = NULL; scd->cbdata = NULL; PMIX_THREADSHIFT(scd, _check_cached_events); if (NULL != info) { PMIX_INFO_FREE(info, ninfo); } return rc; } cleanup: pmix_output_verbose(2, pmix_server_globals.event_output, "server register events: ninfo =%lu rc =%d", ninfo, rc); if (NULL != info) { PMIX_INFO_FREE(info, ninfo); } if (NULL != codes) { free(codes); } if (NULL != affected) { PMIX_PROC_FREE(affected, naffected); } return rc; } void pmix_server_deregister_events(pmix_peer_t *peer, pmix_buffer_t *buf) { int32_t cnt; pmix_status_t rc, code; pmix_regevents_info_t *reginfo = NULL; pmix_regevents_info_t *reginfo_next; pmix_peer_events_info_t *prev; pmix_output_verbose(2, pmix_server_globals.event_output, "recvd deregister events"); /* unpack codes and process until done */ cnt=1; PMIX_BFROPS_UNPACK(rc, peer, buf, &code, &cnt, PMIX_STATUS); while (PMIX_SUCCESS == rc) { PMIX_LIST_FOREACH_SAFE(reginfo, reginfo_next, &pmix_server_globals.events, pmix_regevents_info_t) { if (code == reginfo->code) { /* found it - remove this peer from the list */ PMIX_LIST_FOREACH(prev, &reginfo->peers, pmix_peer_events_info_t) { if (prev->peer == peer) { /* found it */ pmix_list_remove_item(&reginfo->peers, &prev->super); PMIX_RELEASE(prev); break; } } /* if all of the peers for this code are now gone, then remove it */ if (0 == pmix_list_get_size(&reginfo->peers)) { pmix_list_remove_item(&pmix_server_globals.events, &reginfo->super); /* if this was registered with the host, then deregister it */ PMIX_RELEASE(reginfo); } } } cnt=1; PMIX_BFROPS_UNPACK(rc, peer, buf, &code, &cnt, PMIX_STATUS); } if (PMIX_ERR_UNPACK_READ_PAST_END_OF_BUFFER != rc) { PMIX_ERROR_LOG(rc); } } static void local_cbfunc(pmix_status_t status, void *cbdata) { pmix_notify_caddy_t *cd = (pmix_notify_caddy_t*)cbdata; if (NULL != cd->cbfunc) { cd->cbfunc(status, cd->cbdata); } PMIX_RELEASE(cd); } static void intermed_step(pmix_status_t status, void *cbdata) { pmix_notify_caddy_t *cd = (pmix_notify_caddy_t*)cbdata; pmix_status_t rc; if (PMIX_SUCCESS != status) { rc = status; goto complete; } /* check the range directive - if it is LOCAL, then we are * done. Otherwise, it needs to go up to our * host for dissemination */ if (PMIX_RANGE_LOCAL == cd->range) { rc = PMIX_SUCCESS; goto complete; } /* pass it to our host RM for distribution */ rc = pmix_prm.notify(cd->status, &cd->source, cd->range, cd->info, cd->ninfo, local_cbfunc, cd); if (PMIX_SUCCESS == rc) { /* let the callback function respond for us */ return; } if (PMIX_OPERATION_SUCCEEDED == rc) { rc = PMIX_SUCCESS; // local_cbfunc will not be called } complete: if (NULL != cd->cbfunc) { cd->cbfunc(rc, cd->cbdata); } PMIX_RELEASE(cd); } /* Receive an event sent by the client library. Since it was sent * to us by one client, we have to both process it locally to ensure * we notify all relevant local clients AND (assuming a range other * than LOCAL) deliver to our host, requesting that they send it * to all peer servers in the current session */ pmix_status_t pmix_server_event_recvd_from_client(pmix_peer_t *peer, pmix_buffer_t *buf, pmix_op_cbfunc_t cbfunc, void *cbdata) { int32_t cnt; pmix_status_t rc; pmix_notify_caddy_t *cd; size_t ninfo, n; pmix_output_verbose(2, pmix_server_globals.event_output, "%s:%d recvd event notification from client %s:%d", pmix_globals.myid.nspace, pmix_globals.myid.rank, peer->info->pname.nspace, peer->info->pname.rank); cd = PMIX_NEW(pmix_notify_caddy_t); if (NULL == cd) { return PMIX_ERR_NOMEM; } cd->cbfunc = cbfunc; cd->cbdata = cbdata; /* set the source */ PMIX_LOAD_PROCID(&cd->source, peer->info->pname.nspace, peer->info->pname.rank); /* unpack status */ cnt = 1; PMIX_BFROPS_UNPACK(rc, peer, buf, &cd->status, &cnt, PMIX_STATUS); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto exit; } /* unpack the range */ cnt = 1; PMIX_BFROPS_UNPACK(rc, peer, buf, &cd->range, &cnt, PMIX_DATA_RANGE); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto exit; } /* unpack the info keys */ cnt = 1; PMIX_BFROPS_UNPACK(rc, peer, buf, &ninfo, &cnt, PMIX_SIZE); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto exit; } cd->ninfo = ninfo + 1; PMIX_INFO_CREATE(cd->info, cd->ninfo); if (NULL == cd->info) { rc = PMIX_ERR_NOMEM; goto exit; } if (0 < ninfo) { cnt = ninfo; PMIX_BFROPS_UNPACK(rc, peer, buf, cd->info, &cnt, PMIX_INFO); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto exit; } } /* check to see if we already processed this event - it is possible * that a local client "echoed" it back to us and we want to avoid * a potential infinite loop */ for (n=0; n < ninfo; n++) { if (PMIX_CHECK_KEY(&cd->info[n], PMIX_SERVER_INTERNAL_NOTIFY)) { /* yep, we did - so don't do it again! */ rc = PMIX_OPERATION_SUCCEEDED; goto exit; } } /* add an info object to mark that we recvd this internally */ PMIX_INFO_LOAD(&cd->info[cd->ninfo-1], PMIX_SERVER_INTERNAL_NOTIFY, NULL, PMIX_BOOL); /* process it */ if (PMIX_SUCCESS != (rc = pmix_server_notify_client_of_event(cd->status, &cd->source, cd->range, cd->info, cd->ninfo, intermed_step, cd))) { goto exit; } return rc; exit: PMIX_RELEASE(cd); return rc; } pmix_status_t pmix_server_query(pmix_peer_t *peer, pmix_buffer_t *buf, pmix_info_cbfunc_t cbfunc, void *cbdata) { int32_t cnt; pmix_status_t rc; pmix_query_caddy_t *cd; pmix_proc_t proc; pmix_cb_t cb; size_t n, p; pmix_list_t results; pmix_kval_t *kv, *kvnxt; pmix_output_verbose(2, pmix_server_globals.base_output, "recvd query from client"); cd = PMIX_NEW(pmix_query_caddy_t); if (NULL == cd) { return PMIX_ERR_NOMEM; } cd->cbdata = cbdata; /* unpack the number of queries */ cnt = 1; PMIX_BFROPS_UNPACK(rc, peer, buf, &cd->nqueries, &cnt, PMIX_SIZE); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); PMIX_RELEASE(cd); return rc; } /* unpack the queries */ if (0 < cd->nqueries) { PMIX_QUERY_CREATE(cd->queries, cd->nqueries); if (NULL == cd->queries) { rc = PMIX_ERR_NOMEM; PMIX_RELEASE(cd); return rc; } cnt = cd->nqueries; PMIX_BFROPS_UNPACK(rc, peer, buf, cd->queries, &cnt, PMIX_QUERY); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); PMIX_RELEASE(cd); return rc; } } /* check the directives to see if they want us to refresh * the local cached results - if we wanted to optimize this * more, we would check each query and allow those that don't * want to be refreshed to be executed locally, and those that * did would be sent to the host. However, for now we simply * determine that if we don't have it, then ask for everything */ memset(proc.nspace, 0, PMIX_MAX_NSLEN+1); proc.rank = PMIX_RANK_INVALID; PMIX_CONSTRUCT(&results, pmix_list_t); for (n=0; n < cd->nqueries; n++) { /* if they are asking for information on support, then go get it */ if (0 == strcmp(cd->queries[n].keys[0], PMIX_QUERY_ATTRIBUTE_SUPPORT)) { /* we are already in an event, but shift it as the handler expects to */ cd->cbfunc = cbfunc; PMIX_RETAIN(cd); // protect against early release PMIX_THREADSHIFT(cd, pmix_attrs_query_support); PMIX_LIST_DESTRUCT(&results); return PMIX_SUCCESS; } for (p=0; p < cd->queries[n].nqual; p++) { if (PMIX_CHECK_KEY(&cd->queries[n].qualifiers[p], PMIX_QUERY_REFRESH_CACHE)) { if (PMIX_INFO_TRUE(&cd->queries[n].qualifiers[p])) { PMIX_LIST_DESTRUCT(&results); goto query; } } else if (PMIX_CHECK_KEY(&cd->queries[n].qualifiers[p], PMIX_PROCID)) { PMIX_LOAD_NSPACE(proc.nspace, cd->queries[n].qualifiers[p].value.data.proc->nspace); proc.rank = cd->queries[n].qualifiers[p].value.data.proc->rank; } else if (PMIX_CHECK_KEY(&cd->queries[n].qualifiers[p], PMIX_NSPACE)) { PMIX_LOAD_NSPACE(proc.nspace, cd->queries[n].qualifiers[p].value.data.string); } else if (PMIX_CHECK_KEY(&cd->queries[n].qualifiers[p], PMIX_RANK)) { proc.rank = cd->queries[n].qualifiers[p].value.data.rank; } else if (PMIX_CHECK_KEY(&cd->queries[n].qualifiers[p], PMIX_HOSTNAME)) { if (0 != strcmp(cd->queries[n].qualifiers[p].value.data.string, pmix_globals.hostname)) { /* asking about a different host, so ask for the info */ PMIX_LIST_DESTRUCT(&results); goto query; } } } /* we get here if a refresh isn't required - first try a local * "get" on the data to see if we already have it */ PMIX_CONSTRUCT(&cb, pmix_cb_t); cb.copy = false; /* set the proc */ if (PMIX_RANK_INVALID == proc.rank && 0 == strlen(proc.nspace)) { /* use our id */ cb.proc = &pmix_globals.myid; } else { if (0 == strlen(proc.nspace)) { /* use our nspace */ PMIX_LOAD_NSPACE(cb.proc->nspace, pmix_globals.myid.nspace); } if (PMIX_RANK_INVALID == proc.rank) { /* user the wildcard rank */ proc.rank = PMIX_RANK_WILDCARD; } cb.proc = &proc; } for (p=0; NULL != cd->queries[n].keys[p]; p++) { cb.key = cd->queries[n].keys[p]; PMIX_GDS_FETCH_KV(rc, pmix_globals.mypeer, &cb); if (PMIX_SUCCESS != rc) { /* needs to be passed to the host */ PMIX_LIST_DESTRUCT(&results); PMIX_DESTRUCT(&cb); goto query; } /* need to retain this result */ PMIX_LIST_FOREACH_SAFE(kv, kvnxt, &cb.kvs, pmix_kval_t) { pmix_list_remove_item(&cb.kvs, &kv->super); pmix_list_append(&results, &kv->super); } PMIX_DESTRUCT(&cb); } } /* if we get here, then all queries were completely locally * resolved, so construct the results for return */ rc = PMIX_ERR_NOT_FOUND; if (0 < (cd->ninfo = pmix_list_get_size(&results))) { PMIX_INFO_CREATE(cd->info, cd->ninfo); n = 0; PMIX_LIST_FOREACH_SAFE(kv, kvnxt, &results, pmix_kval_t) { PMIX_LOAD_KEY(cd->info[n].key, kv->key); rc = pmix_value_xfer(&cd->info[n].value, kv->value); if (PMIX_SUCCESS != rc) { PMIX_INFO_FREE(cd->info, cd->ninfo); cd->info = NULL; cd->ninfo = 0; break; } ++n; } } /* done with the list of results */ PMIX_LIST_DESTRUCT(&results); /* we can just call the cbfunc here as we are already * in an event - let our internal cbfunc do a threadshift * if necessary */ cbfunc(PMIX_SUCCESS, cd->info, cd->ninfo, cd, NULL, NULL); return PMIX_SUCCESS; query: if (NULL == pmix_host_server.query) { PMIX_RELEASE(cd); return PMIX_ERR_NOT_SUPPORTED; } /* setup the requesting peer name */ PMIX_LOAD_PROCID(&proc, peer->info->pname.nspace, peer->info->pname.rank); /* ask the host for the info */ if (PMIX_SUCCESS != (rc = pmix_host_server.query(&proc, cd->queries, cd->nqueries, cbfunc, cd))) { PMIX_RELEASE(cd); } return rc; } static void logcbfn(pmix_status_t status, void *cbdata) { pmix_shift_caddy_t *cd = (pmix_shift_caddy_t*)cbdata; if (NULL != cd->cbfunc.opcbfn) { cd->cbfunc.opcbfn(status, cd->cbdata); } PMIX_RELEASE(cd); } pmix_status_t pmix_server_log(pmix_peer_t *peer, pmix_buffer_t *buf, pmix_op_cbfunc_t cbfunc, void *cbdata) { int32_t cnt; pmix_status_t rc; pmix_shift_caddy_t *cd; pmix_proc_t proc; time_t timestamp; pmix_output_verbose(2, pmix_server_globals.base_output, "recvd log from client"); /* we need to deliver this to our internal log capability, * which may upcall it to our host if it cannot process * the request itself */ /* setup the requesting peer name */ pmix_strncpy(proc.nspace, peer->info->pname.nspace, PMIX_MAX_NSLEN); proc.rank = peer->info->pname.rank; cd = PMIX_NEW(pmix_shift_caddy_t); if (NULL == cd) { return PMIX_ERR_NOMEM; } cd->cbfunc.opcbfn = cbfunc; cd->cbdata = cbdata; if (PMIX_PEER_IS_EARLIER(peer, 3, 0, 0)) { timestamp = -1; } else { /* unpack the timestamp */ cnt = 1; PMIX_BFROPS_UNPACK(rc, peer, buf, &timestamp, &cnt, PMIX_TIME); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto exit; } } /* unpack the number of data */ cnt = 1; PMIX_BFROPS_UNPACK(rc, peer, buf, &cd->ninfo, &cnt, PMIX_SIZE); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto exit; } cnt = cd->ninfo; PMIX_INFO_CREATE(cd->info, cd->ninfo); /* unpack the data */ if (0 < cnt) { PMIX_BFROPS_UNPACK(rc, peer, buf, cd->info, &cnt, PMIX_INFO); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto exit; } } /* unpack the number of directives */ cnt = 1; PMIX_BFROPS_UNPACK(rc, peer, buf, &cd->ndirs, &cnt, PMIX_SIZE); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto exit; } cnt = cd->ndirs; /* always add the source to the directives so we * can tell downstream if this gets "upcalled" to * our host for relay */ cd->ndirs = cnt + 1; /* if a timestamp was sent, then we add it to the directives */ if (0 < timestamp) { cd->ndirs++; PMIX_INFO_CREATE(cd->directives, cd->ndirs); PMIX_INFO_LOAD(&cd->directives[cnt], PMIX_LOG_SOURCE, &proc, PMIX_PROC); PMIX_INFO_LOAD(&cd->directives[cnt+1], PMIX_LOG_TIMESTAMP, &timestamp, PMIX_TIME); } else { PMIX_INFO_CREATE(cd->directives, cd->ndirs); PMIX_INFO_LOAD(&cd->directives[cnt], PMIX_LOG_SOURCE, &proc, PMIX_PROC); } /* unpack the directives */ if (0 < cnt) { PMIX_BFROPS_UNPACK(rc, peer, buf, cd->directives, &cnt, PMIX_INFO); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto exit; } } /* pass it down */ rc = pmix_plog.log(&proc, cd->info, cd->ninfo, cd->directives, cd->ndirs, logcbfn, cd); return rc; exit: PMIX_RELEASE(cd); return rc; } pmix_status_t pmix_server_alloc(pmix_peer_t *peer, pmix_buffer_t *buf, pmix_info_cbfunc_t cbfunc, void *cbdata) { int32_t cnt; pmix_status_t rc; pmix_query_caddy_t *cd; pmix_proc_t proc; pmix_alloc_directive_t directive; pmix_output_verbose(2, pmix_server_globals.base_output, "recvd query from client"); if (NULL == pmix_host_server.allocate) { return PMIX_ERR_NOT_SUPPORTED; } cd = PMIX_NEW(pmix_query_caddy_t); if (NULL == cd) { return PMIX_ERR_NOMEM; } cd->cbdata = cbdata; /* unpack the directive */ cnt = 1; PMIX_BFROPS_UNPACK(rc, peer, buf, &directive, &cnt, PMIX_ALLOC_DIRECTIVE); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto exit; } /* unpack the number of info objects */ cnt = 1; PMIX_BFROPS_UNPACK(rc, peer, buf, &cd->ninfo, &cnt, PMIX_SIZE); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto exit; } /* unpack the info */ if (0 < cd->ninfo) { PMIX_INFO_CREATE(cd->info, cd->ninfo); cnt = cd->ninfo; PMIX_BFROPS_UNPACK(rc, peer, buf, cd->info, &cnt, PMIX_INFO); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto exit; } } /* setup the requesting peer name */ pmix_strncpy(proc.nspace, peer->info->pname.nspace, PMIX_MAX_NSLEN); proc.rank = peer->info->pname.rank; /* ask the host to execute the request */ if (PMIX_SUCCESS != (rc = pmix_host_server.allocate(&proc, directive, cd->info, cd->ninfo, cbfunc, cd))) { goto exit; } return PMIX_SUCCESS; exit: PMIX_RELEASE(cd); return rc; } typedef struct { pmix_list_item_t super; pmix_epilog_t *epi; } pmix_srvr_epi_caddy_t; static PMIX_CLASS_INSTANCE(pmix_srvr_epi_caddy_t, pmix_list_item_t, NULL, NULL); pmix_status_t pmix_server_job_ctrl(pmix_peer_t *peer, pmix_buffer_t *buf, pmix_info_cbfunc_t cbfunc, void *cbdata) { int32_t cnt, m; pmix_status_t rc; pmix_query_caddy_t *cd; pmix_namespace_t *nptr, *tmp; pmix_peer_t *pr; pmix_proc_t proc; size_t n; bool recurse = false, leave_topdir = false, duplicate; pmix_list_t cachedirs, cachefiles, ignorefiles, epicache; pmix_srvr_epi_caddy_t *epicd = NULL; pmix_cleanup_file_t *cf, *cf2, *cfptr; pmix_cleanup_dir_t *cdir, *cdir2, *cdirptr; pmix_output_verbose(2, pmix_server_globals.base_output, "recvd job control request from client"); if (NULL == pmix_host_server.job_control) { return PMIX_ERR_NOT_SUPPORTED; } cd = PMIX_NEW(pmix_query_caddy_t); if (NULL == cd) { return PMIX_ERR_NOMEM; } cd->cbdata = cbdata; PMIX_CONSTRUCT(&epicache, pmix_list_t); /* unpack the number of targets */ cnt = 1; PMIX_BFROPS_UNPACK(rc, peer, buf, &cd->ntargets, &cnt, PMIX_SIZE); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto exit; } if (0 < cd->ntargets) { PMIX_PROC_CREATE(cd->targets, cd->ntargets); cnt = cd->ntargets; PMIX_BFROPS_UNPACK(rc, peer, buf, cd->targets, &cnt, PMIX_PROC); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto exit; } } /* check targets to find proper place to put any epilog requests */ if (NULL == cd->targets) { epicd = PMIX_NEW(pmix_srvr_epi_caddy_t); epicd->epi = &peer->nptr->epilog; pmix_list_append(&epicache, &epicd->super); } else { for (n=0; n < cd->ntargets; n++) { /* find the nspace of this proc */ nptr = NULL; PMIX_LIST_FOREACH(tmp, &pmix_globals.nspaces, pmix_namespace_t) { if (0 == strcmp(tmp->nspace, cd->targets[n].nspace)) { nptr = tmp; break; } } if (NULL == nptr) { nptr = PMIX_NEW(pmix_namespace_t); if (NULL == nptr) { rc = PMIX_ERR_NOMEM; goto exit; } nptr->nspace = strdup(cd->targets[n].nspace); pmix_list_append(&pmix_globals.nspaces, &nptr->super); } /* if the rank is wildcard, then we use the epilog for the nspace */ if (PMIX_RANK_WILDCARD == cd->targets[n].rank) { epicd = PMIX_NEW(pmix_srvr_epi_caddy_t); epicd->epi = &nptr->epilog; pmix_list_append(&epicache, &epicd->super); } else { /* we need to find the precise peer - we can only * do cleanup for a local client */ for (m=0; m < pmix_server_globals.clients.size; m++) { if (NULL == (pr = (pmix_peer_t*)pmix_pointer_array_get_item(&pmix_server_globals.clients, m))) { continue; } if (0 != strncmp(pr->info->pname.nspace, cd->targets[n].nspace, PMIX_MAX_NSLEN)) { continue; } if (pr->info->pname.rank == cd->targets[n].rank) { epicd = PMIX_NEW(pmix_srvr_epi_caddy_t); epicd->epi = &pr->epilog; pmix_list_append(&epicache, &epicd->super); break; } } } } } /* unpack the number of info objects */ cnt = 1; PMIX_BFROPS_UNPACK(rc, peer, buf, &cd->ninfo, &cnt, PMIX_SIZE); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto exit; } /* unpack the info */ if (0 < cd->ninfo) { PMIX_INFO_CREATE(cd->info, cd->ninfo); cnt = cd->ninfo; PMIX_BFROPS_UNPACK(rc, peer, buf, cd->info, &cnt, PMIX_INFO); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto exit; } } /* if this includes a request for post-termination cleanup, we handle * that request ourselves */ PMIX_CONSTRUCT(&cachedirs, pmix_list_t); PMIX_CONSTRUCT(&cachefiles, pmix_list_t); PMIX_CONSTRUCT(&ignorefiles, pmix_list_t); cnt = 0; // track how many infos are cleanup related for (n=0; n < cd->ninfo; n++) { if (PMIX_CHECK_KEY(&cd->info[n], PMIX_REGISTER_CLEANUP)) { ++cnt; if (PMIX_STRING != cd->info[n].value.type || NULL == cd->info[n].value.data.string) { /* return an error */ rc = PMIX_ERR_BAD_PARAM; goto exit; } cf = PMIX_NEW(pmix_cleanup_file_t); if (NULL == cf) { /* return an error */ rc = PMIX_ERR_NOMEM; goto exit; } cf->path = strdup(cd->info[n].value.data.string); pmix_list_append(&cachefiles, &cf->super); } else if (PMIX_CHECK_KEY(&cd->info[n], PMIX_REGISTER_CLEANUP_DIR)) { ++cnt; if (PMIX_STRING != cd->info[n].value.type || NULL == cd->info[n].value.data.string) { /* return an error */ rc = PMIX_ERR_BAD_PARAM; goto exit; } cdir = PMIX_NEW(pmix_cleanup_dir_t); if (NULL == cdir) { /* return an error */ rc = PMIX_ERR_NOMEM; goto exit; } cdir->path = strdup(cd->info[n].value.data.string); pmix_list_append(&cachedirs, &cdir->super); } else if (PMIX_CHECK_KEY(&cd->info[n], PMIX_CLEANUP_RECURSIVE)) { recurse = PMIX_INFO_TRUE(&cd->info[n]); ++cnt; } else if (PMIX_CHECK_KEY(&cd->info[n], PMIX_CLEANUP_IGNORE)) { if (PMIX_STRING != cd->info[n].value.type || NULL == cd->info[n].value.data.string) { /* return an error */ rc = PMIX_ERR_BAD_PARAM; goto exit; } cf = PMIX_NEW(pmix_cleanup_file_t); if (NULL == cf) { /* return an error */ rc = PMIX_ERR_NOMEM; goto exit; } cf->path = strdup(cd->info[n].value.data.string); pmix_list_append(&ignorefiles, &cf->super); ++cnt; } else if (PMIX_CHECK_KEY(&cd->info[n], PMIX_CLEANUP_LEAVE_TOPDIR)) { leave_topdir = PMIX_INFO_TRUE(&cd->info[n]); ++cnt; } } if (0 < cnt) { /* handle any ignore directives first */ PMIX_LIST_FOREACH(cf, &ignorefiles, pmix_cleanup_file_t) { PMIX_LIST_FOREACH(epicd, &epicache, pmix_srvr_epi_caddy_t) { /* scan the existing list of files for any duplicate */ duplicate = false; PMIX_LIST_FOREACH(cf2, &epicd->epi->cleanup_files, pmix_cleanup_file_t) { if (0 == strcmp(cf2->path, cf->path)) { duplicate = true; break; } } if (!duplicate) { /* append it to the end of the list */ cfptr = PMIX_NEW(pmix_cleanup_file_t); cfptr->path = strdup(cf->path); pmix_list_append(&epicd->epi->ignores, &cf->super); } } } PMIX_LIST_DESTRUCT(&ignorefiles); /* now look at the directories */ PMIX_LIST_FOREACH(cdir, &cachedirs, pmix_cleanup_dir_t) { PMIX_LIST_FOREACH(epicd, &epicache, pmix_srvr_epi_caddy_t) { /* scan the existing list of directories for any duplicate */ duplicate = false; PMIX_LIST_FOREACH(cdir2, &epicd->epi->cleanup_dirs, pmix_cleanup_dir_t) { if (0 == strcmp(cdir2->path, cdir->path)) { /* duplicate - check for difference in flags per RFC * precedence rules */ if (!cdir->recurse && recurse) { cdir->recurse = recurse; } if (!cdir->leave_topdir && leave_topdir) { cdir->leave_topdir = leave_topdir; } duplicate = true; break; } } if (!duplicate) { /* check for conflict with ignore */ PMIX_LIST_FOREACH(cf, &epicd->epi->ignores, pmix_cleanup_file_t) { if (0 == strcmp(cf->path, cdir->path)) { /* return an error */ rc = PMIX_ERR_CONFLICTING_CLEANUP_DIRECTIVES; PMIX_LIST_DESTRUCT(&cachedirs); PMIX_LIST_DESTRUCT(&cachefiles); goto exit; } } /* append it to the end of the list */ cdirptr = PMIX_NEW(pmix_cleanup_dir_t); cdirptr->path = strdup(cdir->path); cdirptr->recurse = recurse; cdirptr->leave_topdir = leave_topdir; pmix_list_append(&epicd->epi->cleanup_dirs, &cdirptr->super); } } } PMIX_LIST_DESTRUCT(&cachedirs); PMIX_LIST_FOREACH(cf, &cachefiles, pmix_cleanup_file_t) { PMIX_LIST_FOREACH(epicd, &epicache, pmix_srvr_epi_caddy_t) { /* scan the existing list of files for any duplicate */ duplicate = false; PMIX_LIST_FOREACH(cf2, &epicd->epi->cleanup_files, pmix_cleanup_file_t) { if (0 == strcmp(cf2->path, cf->path)) { duplicate = true; break; } } if (!duplicate) { /* check for conflict with ignore */ PMIX_LIST_FOREACH(cf2, &epicd->epi->ignores, pmix_cleanup_file_t) { if (0 == strcmp(cf->path, cf2->path)) { /* return an error */ rc = PMIX_ERR_CONFLICTING_CLEANUP_DIRECTIVES; PMIX_LIST_DESTRUCT(&cachedirs); PMIX_LIST_DESTRUCT(&cachefiles); goto exit; } } /* append it to the end of the list */ cfptr = PMIX_NEW(pmix_cleanup_file_t); cfptr->path = strdup(cf->path); pmix_list_append(&epicd->epi->cleanup_files, &cfptr->super); } } } PMIX_LIST_DESTRUCT(&cachefiles); if (cnt == (int)cd->ninfo) { /* nothing more to do */ rc = PMIX_OPERATION_SUCCEEDED; goto exit; } } /* setup the requesting peer name */ pmix_strncpy(proc.nspace, peer->info->pname.nspace, PMIX_MAX_NSLEN); proc.rank = peer->info->pname.rank; /* ask the host to execute the request */ if (PMIX_SUCCESS != (rc = pmix_host_server.job_control(&proc, cd->targets, cd->ntargets, cd->info, cd->ninfo, cbfunc, cd))) { goto exit; } PMIX_LIST_DESTRUCT(&epicache); return PMIX_SUCCESS; exit: PMIX_RELEASE(cd); PMIX_LIST_DESTRUCT(&epicache); return rc; } pmix_status_t pmix_server_monitor(pmix_peer_t *peer, pmix_buffer_t *buf, pmix_info_cbfunc_t cbfunc, void *cbdata) { int32_t cnt; pmix_info_t monitor; pmix_status_t rc, error; pmix_query_caddy_t *cd; pmix_proc_t proc; pmix_output_verbose(2, pmix_server_globals.base_output, "recvd monitor request from client"); cd = PMIX_NEW(pmix_query_caddy_t); if (NULL == cd) { return PMIX_ERR_NOMEM; } cd->cbdata = cbdata; /* unpack what is to be monitored */ PMIX_INFO_CONSTRUCT(&monitor); cnt = 1; PMIX_BFROPS_UNPACK(rc, peer, buf, &monitor, &cnt, PMIX_INFO); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto exit; } /* unpack the error code */ cnt = 1; PMIX_BFROPS_UNPACK(rc, peer, buf, &error, &cnt, PMIX_STATUS); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto exit; } /* unpack the number of directives */ cnt = 1; PMIX_BFROPS_UNPACK(rc, peer, buf, &cd->ninfo, &cnt, PMIX_SIZE); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto exit; } /* unpack the directives */ if (0 < cd->ninfo) { PMIX_INFO_CREATE(cd->info, cd->ninfo); cnt = cd->ninfo; PMIX_BFROPS_UNPACK(rc, peer, buf, cd->info, &cnt, PMIX_INFO); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto exit; } } /* see if they are requesting one of the monitoring * methods we internally support */ rc = pmix_psensor.start(peer, error, &monitor, cd->info, cd->ninfo); if (PMIX_SUCCESS == rc) { rc = PMIX_OPERATION_SUCCEEDED; goto exit; } if (PMIX_ERR_NOT_SUPPORTED != rc) { goto exit; } /* if we don't internally support it, see if * our host does */ if (NULL == pmix_host_server.monitor) { rc = PMIX_ERR_NOT_SUPPORTED; goto exit; } /* setup the requesting peer name */ pmix_strncpy(proc.nspace, peer->info->pname.nspace, PMIX_MAX_NSLEN); proc.rank = peer->info->pname.rank; /* ask the host to execute the request */ if (PMIX_SUCCESS != (rc = pmix_host_server.monitor(&proc, &monitor, error, cd->info, cd->ninfo, cbfunc, cd))) { goto exit; } return PMIX_SUCCESS; exit: PMIX_INFO_DESTRUCT(&monitor); PMIX_RELEASE(cd); return rc; } pmix_status_t pmix_server_get_credential(pmix_peer_t *peer, pmix_buffer_t *buf, pmix_credential_cbfunc_t cbfunc, void *cbdata) { int32_t cnt; pmix_status_t rc; pmix_query_caddy_t *cd; pmix_proc_t proc; pmix_output_verbose(2, pmix_globals.debug_output, "recvd get credential request from client"); if (NULL == pmix_host_server.get_credential) { return PMIX_ERR_NOT_SUPPORTED; } cd = PMIX_NEW(pmix_query_caddy_t); if (NULL == cd) { return PMIX_ERR_NOMEM; } cd->cbdata = cbdata; /* unpack the number of directives */ cnt = 1; PMIX_BFROPS_UNPACK(rc, peer, buf, &cd->ninfo, &cnt, PMIX_SIZE); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto exit; } /* unpack the directives */ if (0 < cd->ninfo) { PMIX_INFO_CREATE(cd->info, cd->ninfo); cnt = cd->ninfo; PMIX_BFROPS_UNPACK(rc, peer, buf, cd->info, &cnt, PMIX_INFO); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto exit; } } /* setup the requesting peer name */ pmix_strncpy(proc.nspace, peer->info->pname.nspace, PMIX_MAX_NSLEN); proc.rank = peer->info->pname.rank; /* ask the host to execute the request */ if (PMIX_SUCCESS != (rc = pmix_host_server.get_credential(&proc, cd->info, cd->ninfo, cbfunc, cd))) { goto exit; } return PMIX_SUCCESS; exit: PMIX_RELEASE(cd); return rc; } pmix_status_t pmix_server_validate_credential(pmix_peer_t *peer, pmix_buffer_t *buf, pmix_validation_cbfunc_t cbfunc, void *cbdata) { int32_t cnt; pmix_status_t rc; pmix_query_caddy_t *cd; pmix_proc_t proc; pmix_output_verbose(2, pmix_globals.debug_output, "recvd validate credential request from client"); if (NULL == pmix_host_server.validate_credential) { return PMIX_ERR_NOT_SUPPORTED; } cd = PMIX_NEW(pmix_query_caddy_t); if (NULL == cd) { return PMIX_ERR_NOMEM; } cd->cbdata = cbdata; /* unpack the credential */ cnt = 1; PMIX_BFROPS_UNPACK(rc, peer, buf, &cd->bo, &cnt, PMIX_BYTE_OBJECT); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto exit; } /* unpack the number of directives */ cnt = 1; PMIX_BFROPS_UNPACK(rc, peer, buf, &cd->ninfo, &cnt, PMIX_SIZE); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto exit; } /* unpack the directives */ if (0 < cd->ninfo) { PMIX_INFO_CREATE(cd->info, cd->ninfo); cnt = cd->ninfo; PMIX_BFROPS_UNPACK(rc, peer, buf, cd->info, &cnt, PMIX_INFO); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto exit; } } /* setup the requesting peer name */ pmix_strncpy(proc.nspace, peer->info->pname.nspace, PMIX_MAX_NSLEN); proc.rank = peer->info->pname.rank; /* ask the host to execute the request */ if (PMIX_SUCCESS != (rc = pmix_host_server.validate_credential(&proc, &cd->bo, cd->info, cd->ninfo, cbfunc, cd))) { goto exit; } return PMIX_SUCCESS; exit: PMIX_RELEASE(cd); return rc; } pmix_status_t pmix_server_iofreg(pmix_peer_t *peer, pmix_buffer_t *buf, pmix_op_cbfunc_t cbfunc, void *cbdata) { int32_t cnt; pmix_status_t rc; pmix_setup_caddy_t *cd; pmix_iof_req_t *req; size_t refid; pmix_output_verbose(2, pmix_server_globals.iof_output, "recvd IOF PULL request from client"); if (NULL == pmix_host_server.iof_pull) { return PMIX_ERR_NOT_SUPPORTED; } cd = PMIX_NEW(pmix_setup_caddy_t); if (NULL == cd) { return PMIX_ERR_NOMEM; } cd->cbdata = cbdata; // this is the pmix_server_caddy_t /* unpack the number of procs */ cnt = 1; PMIX_BFROPS_UNPACK(rc, peer, buf, &cd->nprocs, &cnt, PMIX_SIZE); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto exit; } /* unpack the procs */ if (0 < cd->nprocs) { PMIX_PROC_CREATE(cd->procs, cd->nprocs); cnt = cd->nprocs; PMIX_BFROPS_UNPACK(rc, peer, buf, cd->procs, &cnt, PMIX_PROC); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto exit; } } /* unpack the number of directives */ cnt = 1; PMIX_BFROPS_UNPACK(rc, peer, buf, &cd->ninfo, &cnt, PMIX_SIZE); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto exit; } /* unpack the directives */ if (0 < cd->ninfo) { PMIX_INFO_CREATE(cd->info, cd->ninfo); cnt = cd->ninfo; PMIX_BFROPS_UNPACK(rc, peer, buf, cd->info, &cnt, PMIX_INFO); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto exit; } } /* unpack the channels */ cnt = 1; PMIX_BFROPS_UNPACK(rc, peer, buf, &cd->channels, &cnt, PMIX_IOF_CHANNEL); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto exit; } /* unpack their local reference id */ cnt = 1; PMIX_BFROPS_UNPACK(rc, peer, buf, &refid, &cnt, PMIX_SIZE); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto exit; } /* add this peer/source/channel combination */ req = PMIX_NEW(pmix_iof_req_t); if (NULL == req) { rc = PMIX_ERR_NOMEM; goto exit; } PMIX_RETAIN(peer); req->requestor = peer; req->nprocs = cd->nprocs; if (0 < req->nprocs) { PMIX_PROC_CREATE(req->procs, cd->nprocs); memcpy(req->procs, cd->procs, req->nprocs * sizeof(pmix_proc_t)); } req->channels = cd->channels; req->remote_id = refid; req->local_id = pmix_pointer_array_add(&pmix_globals.iof_requests, req); cd->ncodes = req->local_id; /* ask the host to execute the request */ rc = pmix_host_server.iof_pull(cd->procs, cd->nprocs, cd->info, cd->ninfo, cd->channels, cbfunc, cd); if (PMIX_OPERATION_SUCCEEDED == rc) { /* the host did it atomically - send the response. In * this particular case, we can just use the cbfunc * ourselves as it will threadshift and guarantee * proper handling (i.e. that the refid will be * returned in the response to the client) */ cbfunc(PMIX_SUCCESS, cd); /* returning other than SUCCESS will cause the * switchyard to release the cd object */ } exit: PMIX_RELEASE(cd); return rc; } static void deregcbfn(pmix_status_t status, void *cbdata) { pmix_setup_caddy_t *cd = (pmix_setup_caddy_t*)cbdata; pmix_server_caddy_t *cds = (pmix_server_caddy_t*)cd->cbdata; if (NULL != cd->opcbfunc) { cd->opcbfunc(status, cds); // will have released the cds object } PMIX_RELEASE(cd); } pmix_status_t pmix_server_iofdereg(pmix_peer_t *peer, pmix_buffer_t *buf, pmix_op_cbfunc_t cbfunc, void *cbdata) { int32_t cnt; pmix_status_t rc; pmix_setup_caddy_t *cd; pmix_iof_req_t *req; size_t ninfo, refid; pmix_output_verbose(2, pmix_server_globals.iof_output, "recvd IOF DEREGISTER from client"); if (NULL == pmix_host_server.iof_pull) { return PMIX_ERR_NOT_SUPPORTED; } cd = PMIX_NEW(pmix_setup_caddy_t); if (NULL == cd) { return PMIX_ERR_NOMEM; } cd->opcbfunc = cbfunc; cd->cbdata = cbdata; // this is the pmix_server_caddy_t /* unpack the number of directives */ cnt = 1; PMIX_BFROPS_UNPACK(rc, peer, buf, &ninfo, &cnt, PMIX_SIZE); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto exit; } /* unpack the directives - note that we have to add one * to tell the server to stop forwarding to this channel */ cd->ninfo = ninfo + 1; PMIX_INFO_CREATE(cd->info, cd->ninfo); if (0 < ninfo) { cnt = ninfo; PMIX_BFROPS_UNPACK(rc, peer, buf, cd->info, &cnt, PMIX_INFO); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto exit; } } /* add the directive to stop forwarding */ PMIX_INFO_LOAD(&cd->info[ninfo], PMIX_IOF_STOP, NULL, PMIX_BOOL); /* unpack the handler ID */ cnt = 1; PMIX_BFROPS_UNPACK(rc, peer, buf, &refid, &cnt, PMIX_SIZE); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto exit; } /* get the referenced handler */ req = (pmix_iof_req_t*)pmix_pointer_array_get_item(&pmix_globals.iof_requests, refid); if (NULL == req) { /* already gone? */ rc = PMIX_ERR_NOT_FOUND; goto exit; } pmix_pointer_array_set_item(&pmix_globals.iof_requests, refid, NULL); PMIX_RELEASE(req); /* tell the server to stop */ rc = pmix_host_server.iof_pull(cd->procs, cd->nprocs, cd->info, cd->ninfo, cd->channels, deregcbfn, cd); if (PMIX_OPERATION_SUCCEEDED == rc) { /* the host did it atomically - send the response. In * this particular case, we can just use the cbfunc * ourselves as it will threadshift and guarantee * proper handling */ cbfunc(PMIX_SUCCESS, cbdata); /* returning other than SUCCESS will cause the * switchyard to release the cd object */ } exit: return rc; } static void stdcbfunc(pmix_status_t status, void *cbdata) { pmix_setup_caddy_t *cd = (pmix_setup_caddy_t*)cbdata; if (NULL != cd->opcbfunc) { cd->opcbfunc(status, cd->cbdata); } if (NULL != cd->procs) { PMIX_PROC_FREE(cd->procs, cd->nprocs); } if (NULL != cd->info) { PMIX_INFO_FREE(cd->info, cd->ninfo); } if (NULL != cd->bo) { PMIX_BYTE_OBJECT_FREE(cd->bo, 1); } PMIX_RELEASE(cd); } pmix_status_t pmix_server_iofstdin(pmix_peer_t *peer, pmix_buffer_t *buf, pmix_op_cbfunc_t cbfunc, void *cbdata) { int32_t cnt; pmix_status_t rc; pmix_proc_t source; pmix_setup_caddy_t *cd; pmix_output_verbose(2, pmix_server_globals.iof_output, "recvd stdin IOF data from tool"); if (NULL == pmix_host_server.push_stdin) { return PMIX_ERR_NOT_SUPPORTED; } cd = PMIX_NEW(pmix_setup_caddy_t); if (NULL == cd) { return PMIX_ERR_NOMEM; } cd->opcbfunc = cbfunc; cd->cbdata = cbdata; /* unpack the number of targets */ cnt = 1; PMIX_BFROPS_UNPACK(rc, peer, buf, &cd->nprocs, &cnt, PMIX_SIZE); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto error; } if (0 < cd->nprocs) { PMIX_PROC_CREATE(cd->procs, cd->nprocs); if (NULL == cd->procs) { rc = PMIX_ERR_NOMEM; goto error; } cnt = cd->nprocs; PMIX_BFROPS_UNPACK(rc, peer, buf, cd->procs, &cnt, PMIX_PROC); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto error; } } /* unpack the number of directives */ cnt = 1; PMIX_BFROPS_UNPACK(rc, peer, buf, &cd->ninfo, &cnt, PMIX_SIZE); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto error; } if (0 < cd->ninfo) { PMIX_INFO_CREATE(cd->info, cd->ninfo); if (NULL == cd->info) { rc = PMIX_ERR_NOMEM; goto error; } cnt = cd->ninfo; PMIX_BFROPS_UNPACK(rc, peer, buf, cd->info, &cnt, PMIX_INFO); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto error; } } /* unpack the data */ PMIX_BYTE_OBJECT_CREATE(cd->bo, 1); if (NULL == cd->bo) { rc = PMIX_ERR_NOMEM; goto error; } cnt = 1; PMIX_BFROPS_UNPACK(rc, peer, buf, cd->bo, &cnt, PMIX_BYTE_OBJECT); if (PMIX_ERR_UNPACK_READ_PAST_END_OF_BUFFER == rc) { /* it is okay for them to not send data */ PMIX_BYTE_OBJECT_FREE(cd->bo, 1); } else if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto error; } /* pass the data to the host */ pmix_strncpy(source.nspace, peer->nptr->nspace, PMIX_MAX_NSLEN); source.rank = peer->info->pname.rank; if (PMIX_SUCCESS != (rc = pmix_host_server.push_stdin(&source, cd->procs, cd->nprocs, cd->info, cd->ninfo, cd->bo, stdcbfunc, cd))) { if (PMIX_OPERATION_SUCCEEDED != rc) { goto error; } } return rc; error: PMIX_RELEASE(cd); return rc; } static void grp_timeout(int sd, short args, void *cbdata) { pmix_server_caddy_t *cd = (pmix_server_caddy_t*)cbdata; pmix_buffer_t *reply; pmix_status_t ret, rc = PMIX_ERR_TIMEOUT; pmix_output_verbose(2, pmix_server_globals.fence_output, "ALERT: grp construct timeout fired"); /* send this requestor the reply */ reply = PMIX_NEW(pmix_buffer_t); if (NULL == reply) { goto error; } /* setup the reply, starting with the returned status */ PMIX_BFROPS_PACK(ret, cd->peer, reply, &rc, 1, PMIX_STATUS); if (PMIX_SUCCESS != ret) { PMIX_ERROR_LOG(ret); PMIX_RELEASE(reply); goto error; } pmix_output_verbose(2, pmix_server_globals.base_output, "server:grp_timeout reply being sent to %s:%u", cd->peer->info->pname.nspace, cd->peer->info->pname.rank); PMIX_SERVER_QUEUE_REPLY(ret, cd->peer, cd->hdr.tag, reply); if (PMIX_SUCCESS != ret) { PMIX_RELEASE(reply); } error: cd->event_active = false; /* remove it from the list */ pmix_list_remove_item(&cd->trk->local_cbs, &cd->super); PMIX_RELEASE(cd); } static void _grpcbfunc(int sd, short argc, void *cbdata) { pmix_shift_caddy_t *scd = (pmix_shift_caddy_t*)cbdata; pmix_server_trkr_t *trk = scd->tracker; pmix_server_caddy_t *cd; pmix_buffer_t *reply, xfer; pmix_status_t ret; size_t n, ctxid = SIZE_MAX; pmix_group_t *grp; pmix_byte_object_t *bo = NULL; pmix_nspace_caddy_t *nptr; pmix_list_t nslist; bool found; PMIX_ACQUIRE_OBJECT(scd); if (NULL == trk) { /* give them a release if they want it - this should * never happen, but protect against the possibility */ if (NULL != scd->cbfunc.relfn) { scd->cbfunc.relfn(scd->cbdata); } PMIX_RELEASE(scd); return; } pmix_output_verbose(2, pmix_server_globals.connect_output, "server:grpcbfunc processing WITH %d MEMBERS", (int)pmix_list_get_size(&trk->local_cbs)); /* if the timer is active, clear it */ if (trk->event_active) { pmix_event_del(&trk->ev); } grp = (pmix_group_t*)trk->cbdata; /* the tracker's "hybrid" field is used to indicate construct * vs destruct */ if (trk->hybrid) { /* we destructed the group */ if (NULL != grp) { pmix_list_remove_item(&pmix_server_globals.groups, &grp->super); PMIX_RELEASE(grp); } } else { /* see if this group was assigned a context ID or collected data */ for (n=0; n < scd->ninfo; n++) { if (PMIX_CHECK_KEY(&scd->info[n], PMIX_GROUP_CONTEXT_ID)) { PMIX_VALUE_GET_NUMBER(ret, &scd->info[n].value, ctxid, size_t); } else if (PMIX_CHECK_KEY(&scd->info[n], PMIX_GROUP_ENDPT_DATA)) { bo = &scd->info[n].value.data.bo; } } } /* if data was returned, then we need to have the modex cbfunc * store it for us before releasing the group members */ if (NULL != bo) { PMIX_CONSTRUCT(&xfer, pmix_buffer_t); PMIX_CONSTRUCT(&nslist, pmix_list_t); /* Collect the nptr list with uniq GDS components of all local * participants. It does not allow multiple storing to the * same GDS if participants have mutual GDS. */ PMIX_LIST_FOREACH(cd, &trk->local_cbs, pmix_server_caddy_t) { // see if we already have this nspace found = false; PMIX_LIST_FOREACH(nptr, &nslist, pmix_nspace_caddy_t) { if (0 == strcmp(nptr->ns->compat.gds->name, cd->peer->nptr->compat.gds->name)) { found = true; break; } } if (!found) { // add it nptr = PMIX_NEW(pmix_nspace_caddy_t); PMIX_RETAIN(cd->peer->nptr); nptr->ns = cd->peer->nptr; pmix_list_append(&nslist, &nptr->super); } } PMIX_LIST_FOREACH(nptr, &nslist, pmix_nspace_caddy_t) { PMIX_LOAD_BUFFER(pmix_globals.mypeer, &xfer, bo->bytes, bo->size); PMIX_GDS_STORE_MODEX(ret, nptr->ns, &xfer, trk); if (PMIX_SUCCESS != ret) { PMIX_ERROR_LOG(ret); break; } } } /* loop across all procs in the tracker, sending them the reply */ PMIX_LIST_FOREACH(cd, &trk->local_cbs, pmix_server_caddy_t) { reply = PMIX_NEW(pmix_buffer_t); if (NULL == reply) { break; } /* setup the reply, starting with the returned status */ PMIX_BFROPS_PACK(ret, cd->peer, reply, &scd->status, 1, PMIX_STATUS); if (PMIX_SUCCESS != ret) { PMIX_ERROR_LOG(ret); PMIX_RELEASE(reply); break; } if (!trk->hybrid) { /* if a ctxid was provided, pass it along */ PMIX_BFROPS_PACK(ret, cd->peer, reply, &ctxid, 1, PMIX_SIZE); if (PMIX_SUCCESS != ret) { PMIX_ERROR_LOG(ret); PMIX_RELEASE(reply); break; } } pmix_output_verbose(2, pmix_server_globals.connect_output, "server:grp_cbfunc reply being sent to %s:%u", cd->peer->info->pname.nspace, cd->peer->info->pname.rank); PMIX_SERVER_QUEUE_REPLY(ret, cd->peer, cd->hdr.tag, reply); if (PMIX_SUCCESS != ret) { PMIX_RELEASE(reply); } } /* remove the tracker from the list */ pmix_list_remove_item(&pmix_server_globals.collectives, &trk->super); PMIX_RELEASE(trk); /* we are done */ if (NULL != scd->cbfunc.relfn) { scd->cbfunc.relfn(scd->cbdata); } PMIX_RELEASE(scd); } static void grpcbfunc(pmix_status_t status, pmix_info_t *info, size_t ninfo, void *cbdata, pmix_release_cbfunc_t relfn, void *relcbd) { pmix_server_trkr_t *tracker = (pmix_server_trkr_t*)cbdata; pmix_shift_caddy_t *scd; pmix_output_verbose(2, pmix_server_globals.connect_output, "server:grpcbfunc called with %d info", (int)ninfo); if (NULL == tracker) { /* nothing to do - but be sure to give them * a release if they want it */ if (NULL != relfn) { relfn(relcbd); } return; } /* need to thread-shift this callback as it accesses global data */ scd = PMIX_NEW(pmix_shift_caddy_t); if (NULL == scd) { /* nothing we can do */ if (NULL != relfn) { relfn(cbdata); } return; } scd->status = status; scd->info = info; scd->ninfo = ninfo; scd->tracker = tracker; scd->cbfunc.relfn = relfn; scd->cbdata = relcbd; PMIX_THREADSHIFT(scd, _grpcbfunc); } /* we are being called from the PMIx server's switchyard function, * which means we are in an event and can access global data */ pmix_status_t pmix_server_grpconstruct(pmix_server_caddy_t *cd, pmix_buffer_t *buf) { pmix_peer_t *peer = (pmix_peer_t*)cd->peer; pmix_peer_t *pr; int32_t cnt, m; pmix_status_t rc; char *grpid; pmix_proc_t *procs; pmix_group_t *grp, *pgrp; pmix_info_t *info = NULL, *iptr; size_t n, ninfo, nprocs, n2; pmix_server_trkr_t *trk; struct timeval tv = {0, 0}; bool need_cxtid = false; bool match, force_local = false; bool embed_barrier = false; bool barrier_directive_included = false; pmix_buffer_t bucket; pmix_byte_object_t bo; pmix_list_t mbrs; pmix_namelist_t *nm; bool expanded = false; pmix_output_verbose(2, pmix_server_globals.connect_output, "recvd grpconstruct cmd"); /* unpack the group ID */ cnt = 1; PMIX_BFROPS_UNPACK(rc, peer, buf, &grpid, &cnt, PMIX_STRING); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto error; } /* see if we already have this group */ grp = NULL; PMIX_LIST_FOREACH(pgrp, &pmix_server_globals.groups, pmix_group_t) { if (0 == strcmp(grpid, pgrp->grpid)) { grp = pgrp; break; } } if (NULL == grp) { /* create a new entry */ grp = PMIX_NEW(pmix_group_t); if (NULL == grp) { rc = PMIX_ERR_NOMEM; goto error; } grp->grpid = grpid; pmix_list_append(&pmix_server_globals.groups, &grp->super); } else { free(grpid); } /* unpack the number of procs */ cnt = 1; PMIX_BFROPS_UNPACK(rc, peer, buf, &nprocs, &cnt, PMIX_SIZE); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto error; } if (0 == nprocs) { return PMIX_ERR_BAD_PARAM; } PMIX_PROC_CREATE(procs, nprocs); if (NULL == procs) { rc = PMIX_ERR_NOMEM; goto error; } cnt = nprocs; PMIX_BFROPS_UNPACK(rc, peer, buf, procs, &cnt, PMIX_PROC); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); PMIX_PROC_FREE(procs, nprocs); goto error; } if (NULL == grp->members) { /* see if they used a local proc or local peer * wildcard - if they did, then we need to expand * it here */ PMIX_CONSTRUCT(&mbrs, pmix_list_t); for (n=0; n < nprocs; n++) { if (PMIX_RANK_LOCAL_PEERS == procs[n].rank) { expanded = true; /* expand to all local procs in this nspace */ for (m=0; m < pmix_server_globals.clients.size; m++) { if (NULL == (pr = (pmix_peer_t*)pmix_pointer_array_get_item(&pmix_server_globals.clients, m))) { continue; } if (PMIX_CHECK_NSPACE(procs[n].nspace, pr->info->pname.nspace)) { nm = PMIX_NEW(pmix_namelist_t); nm->pname = &pr->info->pname; pmix_list_append(&mbrs, &nm->super); } } } else if (PMIX_RANK_LOCAL_NODE == procs[n].rank) { expanded = true; /* add in all procs on the node */ for (m=0; m < pmix_server_globals.clients.size; m++) { if (NULL == (pr = (pmix_peer_t*)pmix_pointer_array_get_item(&pmix_server_globals.clients, m))) { continue; } nm = PMIX_NEW(pmix_namelist_t); nm->pname = &pr->info->pname; pmix_list_append(&mbrs, &nm->super); } } else { nm = PMIX_NEW(pmix_namelist_t); /* have to duplicate the name here */ nm->pname = (pmix_name_t*)malloc(sizeof(pmix_name_t)); nm->pname->nspace = strdup(procs[n].nspace); nm->pname->rank = procs[n].rank; pmix_list_append(&mbrs, &nm->super); } } if (expanded) { PMIX_PROC_FREE(procs, nprocs); nprocs = pmix_list_get_size(&mbrs); PMIX_PROC_CREATE(procs, nprocs); n=0; while (NULL != (nm = (pmix_namelist_t*)pmix_list_remove_first(&mbrs))) { PMIX_LOAD_PROCID(&procs[n], nm->pname->nspace, nm->pname->rank); PMIX_RELEASE(nm); } PMIX_DESTRUCT(&mbrs); } grp->members = procs; grp->nmbrs = nprocs; } else { PMIX_PROC_FREE(procs, nprocs); } /* unpack the number of directives */ cnt = 1; PMIX_BFROPS_UNPACK(rc, peer, buf, &ninfo, &cnt, PMIX_SIZE); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto error; } if (0 < ninfo) { PMIX_INFO_CREATE(info, ninfo); cnt = ninfo; PMIX_BFROPS_UNPACK(rc, peer, buf, info, &cnt, PMIX_INFO); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto error; } } /* find/create the local tracker for this operation */ if (NULL == (trk = get_tracker(grp->grpid, grp->members, grp->nmbrs, PMIX_GROUP_CONSTRUCT_CMD))) { /* If no tracker was found - create and initialize it once */ if (NULL == (trk = new_tracker(grp->grpid, grp->members, grp->nmbrs, PMIX_GROUP_CONSTRUCT_CMD))) { /* only if a bozo error occurs */ PMIX_ERROR_LOG(PMIX_ERROR); rc = PMIX_ERROR; goto error; } /* group members must have access to all endpoint info * upon completion of the construct operation */ trk->collect_type = PMIX_COLLECT_YES; /* mark as being a construct operation */ trk->hybrid = false; /* pass along the grp object */ trk->cbdata = grp; /* we only save the info structs from the first caller * who provides them - it is a user error to provide * different values from different participants */ trk->info = info; trk->ninfo = ninfo; /* see if we are to enforce a timeout or if they want * a context ID created - we don't internally care * about any other directives */ for (n=0; n < ninfo; n++) { if (PMIX_CHECK_KEY(&info[n], PMIX_TIMEOUT)) { tv.tv_sec = info[n].value.data.uint32; } else if (PMIX_CHECK_KEY(&info[n], PMIX_GROUP_ASSIGN_CONTEXT_ID)) { need_cxtid = PMIX_INFO_TRUE(&info[n]); } else if (PMIX_CHECK_KEY(&info[n], PMIX_GROUP_LOCAL_ONLY)) { force_local = PMIX_INFO_TRUE(&info[n]); } else if (PMIX_CHECK_KEY(&info[n], PMIX_EMBED_BARRIER)) { embed_barrier = PMIX_INFO_TRUE(&info[n]); barrier_directive_included = true; } } /* see if this constructor only references local processes and isn't * requesting a context ID - if both conditions are met, then we * can just locally process the request without bothering the host. * This is meant to provide an optimized path for a fairly common * operation */ if (force_local) { trk->local = true; } else if (need_cxtid) { trk->local = false; } else { trk->local = true; for (n=0; n < grp->nmbrs; n++) { /* if this entry references the local procs, then * we can skip it */ if (PMIX_RANK_LOCAL_PEERS == grp->members[n].rank || PMIX_RANK_LOCAL_NODE == grp->members[n].rank) { continue; } /* see if it references a specific local proc */ match = false; for (m=0; m < pmix_server_globals.clients.size; m++) { if (NULL == (pr = (pmix_peer_t*)pmix_pointer_array_get_item(&pmix_server_globals.clients, m))) { continue; } if (PMIX_CHECK_PROCID(&grp->members[n], &pr->info->pname)) { match = true; break; } } if (!match) { /* this requires a non_local operation */ trk->local = false; break; } } } } else { /* cleanup */ PMIX_INFO_FREE(info, ninfo); info = NULL; } /* add this contributor to the tracker so they get * notified when we are done */ pmix_list_append(&trk->local_cbs, &cd->super); /* if a timeout was specified, set it */ if (0 < tv.tv_sec) { PMIX_THREADSHIFT_DELAY(trk, grp_timeout, tv.tv_sec); trk->event_active = true; } /* if all local contributions have been received, * let the local host's server know that we are at the * "fence" point - they will callback once the barrier * across all participants has been completed */ if (trk->def_complete && pmix_list_get_size(&trk->local_cbs) == trk->nlocal) { pmix_output_verbose(2, pmix_server_globals.base_output, "local group op complete with %d procs", (int)trk->npcs); if (trk->local) { /* nothing further needs to be done - we have * created the local group. let the grpcbfunc * threadshift the result */ grpcbfunc(PMIX_SUCCESS, NULL, 0, trk, NULL, NULL); return PMIX_SUCCESS; } /* check if our host supports group operations */ if (NULL == pmix_host_server.group) { /* remove the tracker from the list */ pmix_list_remove_item(&pmix_server_globals.collectives, &trk->super); PMIX_RELEASE(trk); return PMIX_ERR_NOT_SUPPORTED; } /* if they direct us to not embed a barrier, then we won't gather * the data for distribution */ if (!barrier_directive_included || (barrier_directive_included && embed_barrier)) { /* collect any remote contributions provided by group members */ PMIX_CONSTRUCT(&bucket, pmix_buffer_t); rc = _collect_data(trk, &bucket); if (PMIX_SUCCESS != rc) { if (trk->event_active) { pmix_event_del(&trk->ev); } /* remove the tracker from the list */ pmix_list_remove_item(&pmix_server_globals.collectives, &trk->super); PMIX_RELEASE(trk); PMIX_DESTRUCT(&bucket); return rc; } /* xfer the results to a byte object */ PMIX_UNLOAD_BUFFER(&bucket, bo.bytes, bo.size); PMIX_DESTRUCT(&bucket); /* load any results into a data object for inclusion in the * fence operation */ n2 = trk->ninfo + 1; PMIX_INFO_CREATE(iptr, n2); for (n=0; n < trk->ninfo; n++) { PMIX_INFO_XFER(&iptr[n], &trk->info[n]); } PMIX_INFO_LOAD(&iptr[ninfo], PMIX_GROUP_ENDPT_DATA, &bo, PMIX_BYTE_OBJECT); PMIX_BYTE_OBJECT_DESTRUCT(&bo); PMIX_INFO_FREE(trk->info, trk->ninfo); trk->info = iptr; trk->ninfo = n2; } rc = pmix_host_server.group(PMIX_GROUP_CONSTRUCT, grp->grpid, trk->pcs, trk->npcs, trk->info, trk->ninfo, grpcbfunc, trk); if (PMIX_SUCCESS != rc) { if (trk->event_active) { pmix_event_del(&trk->ev); } if (PMIX_OPERATION_SUCCEEDED == rc) { /* let the grpcbfunc threadshift the result */ grpcbfunc(PMIX_SUCCESS, NULL, 0, trk, NULL, NULL); return PMIX_SUCCESS; } /* remove the tracker from the list */ pmix_list_remove_item(&pmix_server_globals.collectives, &trk->super); PMIX_RELEASE(trk); return rc; } } return PMIX_SUCCESS; error: if (NULL != info) { PMIX_INFO_FREE(info, ninfo); } return rc; } /* we are being called from the PMIx server's switchyard function, * which means we are in an event and can access global data */ pmix_status_t pmix_server_grpdestruct(pmix_server_caddy_t *cd, pmix_buffer_t *buf) { pmix_peer_t *peer = (pmix_peer_t*)cd->peer; int32_t cnt; pmix_status_t rc; char *grpid; pmix_info_t *info = NULL; size_t n, ninfo; pmix_server_trkr_t *trk; pmix_group_t *grp, *pgrp; struct timeval tv = {0, 0}; pmix_output_verbose(2, pmix_server_globals.iof_output, "recvd grpdestruct cmd"); if (NULL == pmix_host_server.group) { PMIX_ERROR_LOG(PMIX_ERR_NOT_SUPPORTED); return PMIX_ERR_NOT_SUPPORTED; } /* unpack the group ID */ cnt = 1; PMIX_BFROPS_UNPACK(rc, peer, buf, &grpid, &cnt, PMIX_STRING); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto error; } /* find this group in our list */ grp = NULL; PMIX_LIST_FOREACH(pgrp, &pmix_server_globals.groups, pmix_group_t) { if (0 == strcmp(grpid, pgrp->grpid)) { grp = pgrp; break; } } free(grpid); /* if not found, then this is an error - we cannot * destruct a group we don't know about */ if (NULL == grp) { rc = PMIX_ERR_NOT_FOUND; goto error; } /* unpack the number of directives */ cnt = 1; PMIX_BFROPS_UNPACK(rc, peer, buf, &ninfo, &cnt, PMIX_SIZE); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto error; } if (0 < ninfo) { PMIX_INFO_CREATE(info, ninfo); cnt = ninfo; PMIX_BFROPS_UNPACK(rc, peer, buf, info, &cnt, PMIX_INFO); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto error; } /* see if we are to enforce a timeout - we don't internally care * about any other directives */ for (n=0; n < ninfo; n++) { if (PMIX_CHECK_KEY(&info[n], PMIX_TIMEOUT)) { tv.tv_sec = info[n].value.data.uint32; break; } } } /* find/create the local tracker for this operation */ if (NULL == (trk = get_tracker(grp->grpid, grp->members, grp->nmbrs, PMIX_GROUP_DESTRUCT_CMD))) { /* If no tracker was found - create and initialize it once */ if (NULL == (trk = new_tracker(grp->grpid, grp->members, grp->nmbrs, PMIX_GROUP_DESTRUCT_CMD))) { /* only if a bozo error occurs */ PMIX_ERROR_LOG(PMIX_ERROR); rc = PMIX_ERROR; goto error; } trk->collect_type = PMIX_COLLECT_NO; /* mark as being a destruct operation */ trk->hybrid = true; /* pass along the group object */ trk->cbdata = grp; } /* we only save the info structs from the first caller * who provides them - it is a user error to provide * different values from different participants */ if (NULL == trk->info) { trk->info = info; trk->ninfo = ninfo; } else { /* cleanup */ PMIX_INFO_FREE(info, ninfo); info = NULL; } /* add this contributor to the tracker so they get * notified when we are done */ pmix_list_append(&trk->local_cbs, &cd->super); /* if a timeout was specified, set it */ if (0 < tv.tv_sec) { PMIX_THREADSHIFT_DELAY(trk, grp_timeout, tv.tv_sec); trk->event_active = true; } /* if all local contributions have been received, * let the local host's server know that we are at the * "fence" point - they will callback once the barrier * across all participants has been completed */ if (trk->def_complete && pmix_list_get_size(&trk->local_cbs) == trk->nlocal) { pmix_output_verbose(2, pmix_server_globals.base_output, "local group op complete %d", (int)trk->nlocal); rc = pmix_host_server.group(PMIX_GROUP_DESTRUCT, grp->grpid, grp->members, grp->nmbrs, trk->info, trk->ninfo, grpcbfunc, trk); if (PMIX_SUCCESS != rc) { if (trk->event_active) { pmix_event_del(&trk->ev); } if (PMIX_OPERATION_SUCCEEDED == rc) { /* let the grpcbfunc threadshift the result */ grpcbfunc(PMIX_SUCCESS, NULL, 0, trk, NULL, NULL); return PMIX_SUCCESS; } /* remove the tracker from the list */ pmix_list_remove_item(&pmix_server_globals.collectives, &trk->super); PMIX_RELEASE(trk); return rc; } } return PMIX_SUCCESS; error: if (NULL != info) { PMIX_INFO_FREE(info, ninfo); } return rc; } static void _fabric_response(int sd, short args, void *cbdata) { pmix_query_caddy_t *qcd = (pmix_query_caddy_t*)cbdata; qcd->cbfunc(PMIX_SUCCESS, qcd->info, qcd->ninfo, qcd->cbdata, NULL, NULL); PMIX_RELEASE(qcd); } static void frcbfunc(pmix_status_t status, void *cbdata) { pmix_query_caddy_t *qcd = (pmix_query_caddy_t*)cbdata; PMIX_ACQUIRE_OBJECT(qcd); qcd->status = status; PMIX_POST_OBJECT(qcd); PMIX_WAKEUP_THREAD(&qcd->lock); } /* we are being called from the PMIx server's switchyard function, * which means we are in an event and can access global data */ pmix_status_t pmix_server_fabric_register(pmix_server_caddy_t *cd, pmix_buffer_t *buf, pmix_info_cbfunc_t cbfunc) { int32_t cnt; pmix_status_t rc; pmix_query_caddy_t *qcd = NULL; pmix_proc_t proc; pmix_fabric_t fabric; pmix_output_verbose(2, pmix_server_globals.base_output, "recvd register_fabric request from client"); qcd = PMIX_NEW(pmix_query_caddy_t); if (NULL == qcd) { return PMIX_ERR_NOMEM; } PMIX_RETAIN(cd); qcd->cbfunc = cbfunc; qcd->cbdata = cd; /* unpack the number of directives */ cnt = 1; PMIX_BFROPS_UNPACK(rc, cd->peer, buf, &qcd->ninfo, &cnt, PMIX_SIZE); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); PMIX_RELEASE(qcd); goto exit; } /* unpack the directives */ if (0 < qcd->ninfo) { PMIX_INFO_CREATE(cd->info, qcd->ninfo); cnt = qcd->ninfo; PMIX_BFROPS_UNPACK(rc, cd->peer, buf, qcd->info, &cnt, PMIX_INFO); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); PMIX_RELEASE(qcd); goto exit; } } /* see if we support this request ourselves */ PMIX_FABRIC_CONSTRUCT(&fabric); rc = pmix_pnet.register_fabric(&fabric, qcd->info, qcd->ninfo, frcbfunc, qcd); if (PMIX_OPERATION_SUCCEEDED == rc) { /* we need to respond, but we want to ensure * that occurs _after_ the client returns from its API */ if (NULL != qcd->info) { PMIX_INFO_FREE(qcd->info, qcd->ninfo); } qcd->info = fabric.info; qcd->ninfo = fabric.ninfo; PMIX_THREADSHIFT(qcd, _fabric_response); return PMIX_SUCCESS; } else if (PMIX_SUCCESS == rc) { PMIX_WAIT_THREAD(&qcd->lock); /* we need to respond, but we want to ensure * that occurs _after_ the client returns from its API */ if (NULL != qcd->info) { PMIX_INFO_FREE(qcd->info, qcd->ninfo); } qcd->info = fabric.info; qcd->ninfo = fabric.ninfo; PMIX_THREADSHIFT(qcd, _fabric_response); return PMIX_SUCCESS; } /* if we don't internally support it, see if * our host does */ if (NULL == pmix_host_server.fabric) { rc = PMIX_ERR_NOT_SUPPORTED; goto exit; } /* setup the requesting peer name */ PMIX_LOAD_PROCID(&proc, cd->peer->info->pname.nspace, cd->peer->info->pname.rank); /* ask the host to execute the request */ if (PMIX_SUCCESS != (rc = pmix_host_server.fabric(&proc, PMIX_FABRIC_REQUEST_INFO, qcd->info, qcd->ninfo, cbfunc, qcd))) { goto exit; } return PMIX_SUCCESS; exit: if (NULL != qcd) { PMIX_RELEASE(qcd); } return rc; } pmix_status_t pmix_server_fabric_update(pmix_server_caddy_t *cd, pmix_buffer_t *buf, pmix_info_cbfunc_t cbfunc) { int32_t cnt; size_t index; pmix_status_t rc; pmix_query_caddy_t *qcd; pmix_proc_t proc; pmix_fabric_t fabric; pmix_output_verbose(2, pmix_server_globals.base_output, "recvd update_fabric request from client"); qcd = PMIX_NEW(pmix_query_caddy_t); if (NULL == qcd) { return PMIX_ERR_NOMEM; } PMIX_RETAIN(cd); qcd->cbdata = cd; /* unpack the fabric index */ cnt = 1; PMIX_BFROPS_UNPACK(rc, cd->peer, buf, &index, &cnt, PMIX_SIZE); if (PMIX_SUCCESS != rc) { PMIX_ERROR_LOG(rc); goto exit; } /* see if we support this request ourselves */ PMIX_FABRIC_CONSTRUCT(&fabric); fabric.index = index; rc = pmix_pnet.update_fabric(&fabric); if (PMIX_SUCCESS == rc) { /* we need to respond, but we want to ensure * that occurs _after_ the client returns from its API */ if (NULL != qcd->info) { PMIX_INFO_FREE(qcd->info, qcd->ninfo); } qcd->info = fabric.info; qcd->ninfo = fabric.ninfo; PMIX_THREADSHIFT(qcd, _fabric_response); return rc; } /* if we don't internally support it, see if * our host does */ if (NULL == pmix_host_server.fabric) { rc = PMIX_ERR_NOT_SUPPORTED; goto exit; } /* setup the requesting peer name */ pmix_strncpy(proc.nspace, cd->peer->info->pname.nspace, PMIX_MAX_NSLEN); proc.rank = cd->peer->info->pname.rank; /* add the index */ qcd->ninfo = 1; PMIX_INFO_CREATE(qcd->info, qcd->ninfo); PMIX_INFO_LOAD(&qcd->info[0], PMIX_FABRIC_INDEX, &index, PMIX_SIZE); /* ask the host to execute the request */ if (PMIX_SUCCESS != (rc = pmix_host_server.fabric(&proc, PMIX_FABRIC_UPDATE_INFO, qcd->info, qcd->ninfo, cbfunc, qcd))) { goto exit; } return PMIX_SUCCESS; exit: return rc; } /***** INSTANCE SERVER LIBRARY CLASSES *****/ static void tcon(pmix_server_trkr_t *t) { t->event_active = false; t->host_called = false; t->local = true; t->id = NULL; memset(t->pname.nspace, 0, PMIX_MAX_NSLEN+1); t->pname.rank = PMIX_RANK_UNDEF; t->pcs = NULL; t->npcs = 0; PMIX_CONSTRUCT(&t->nslist, pmix_list_t); PMIX_CONSTRUCT_LOCK(&t->lock); t->def_complete = false; PMIX_CONSTRUCT(&t->local_cbs, pmix_list_t); t->nlocal = 0; t->local_cnt = 0; t->info = NULL; t->ninfo = 0; /* this needs to be set explicitly */ t->collect_type = PMIX_COLLECT_INVALID; t->modexcbfunc = NULL; t->op_cbfunc = NULL; t->hybrid = false; t->cbdata = NULL; } static void tdes(pmix_server_trkr_t *t) { if (NULL != t->id) { free(t->id); } PMIX_DESTRUCT_LOCK(&t->lock); if (NULL != t->pcs) { free(t->pcs); } PMIX_LIST_DESTRUCT(&t->local_cbs); if (NULL != t->info) { PMIX_INFO_FREE(t->info, t->ninfo); } PMIX_DESTRUCT(&t->nslist); } PMIX_CLASS_INSTANCE(pmix_server_trkr_t, pmix_list_item_t, tcon, tdes); static void cdcon(pmix_server_caddy_t *cd) { memset(&cd->ev, 0, sizeof(pmix_event_t)); cd->event_active = false; cd->trk = NULL; cd->peer = NULL; cd->info = NULL; cd->ninfo = 0; } static void cddes(pmix_server_caddy_t *cd) { if (cd->event_active) { pmix_event_del(&cd->ev); } if (NULL != cd->trk) { PMIX_RELEASE(cd->trk); } if (NULL != cd->peer) { PMIX_RELEASE(cd->peer); } if (NULL != cd->info) { PMIX_INFO_FREE(cd->info, cd->ninfo); } } PMIX_CLASS_INSTANCE(pmix_server_caddy_t, pmix_list_item_t, cdcon, cddes); static void scadcon(pmix_setup_caddy_t *p) { p->peer = NULL; memset(&p->proc, 0, sizeof(pmix_proc_t)); PMIX_CONSTRUCT_LOCK(&p->lock); p->nspace = NULL; p->codes = NULL; p->ncodes = 0; p->procs = NULL; p->nprocs = 0; p->apps = NULL; p->napps = 0; p->server_object = NULL; p->nlocalprocs = 0; p->info = NULL; p->ninfo = 0; p->keys = NULL; p->channels = PMIX_FWD_NO_CHANNELS; p->bo = NULL; p->nbo = 0; p->cbfunc = NULL; p->opcbfunc = NULL; p->setupcbfunc = NULL; p->lkcbfunc = NULL; p->spcbfunc = NULL; p->cbdata = NULL; } static void scaddes(pmix_setup_caddy_t *p) { if (NULL != p->peer) { PMIX_RELEASE(p->peer); } PMIX_PROC_FREE(p->procs, p->nprocs); if (NULL != p->apps) { PMIX_APP_FREE(p->apps, p->napps); } if (NULL != p->bo) { PMIX_BYTE_OBJECT_FREE(p->bo, p->nbo); } PMIX_DESTRUCT_LOCK(&p->lock); } PMIX_EXPORT PMIX_CLASS_INSTANCE(pmix_setup_caddy_t, pmix_object_t, scadcon, scaddes); PMIX_CLASS_INSTANCE(pmix_trkr_caddy_t, pmix_object_t, NULL, NULL); static void dmcon(pmix_dmdx_remote_t *p) { p->cd = NULL; } static void dmdes(pmix_dmdx_remote_t *p) { if (NULL != p->cd) { PMIX_RELEASE(p->cd); } } PMIX_CLASS_INSTANCE(pmix_dmdx_remote_t, pmix_list_item_t, dmcon, dmdes); static void dmrqcon(pmix_dmdx_request_t *p) { memset(&p->ev, 0, sizeof(pmix_event_t)); p->event_active = false; p->lcd = NULL; } static void dmrqdes(pmix_dmdx_request_t *p) { if (p->event_active) { pmix_event_del(&p->ev); } if (NULL != p->lcd) { PMIX_RELEASE(p->lcd); } } PMIX_CLASS_INSTANCE(pmix_dmdx_request_t, pmix_list_item_t, dmrqcon, dmrqdes); static void lmcon(pmix_dmdx_local_t *p) { memset(&p->proc, 0, sizeof(pmix_proc_t)); PMIX_CONSTRUCT(&p->loc_reqs, pmix_list_t); p->info = NULL; p->ninfo = 0; } static void lmdes(pmix_dmdx_local_t *p) { if (NULL != p->info) { PMIX_INFO_FREE(p->info, p->ninfo); } PMIX_LIST_DESTRUCT(&p->loc_reqs); } PMIX_CLASS_INSTANCE(pmix_dmdx_local_t, pmix_list_item_t, lmcon, lmdes); static void prevcon(pmix_peer_events_info_t *p) { p->peer = NULL; p->affected = NULL; p->naffected = 0; } static void prevdes(pmix_peer_events_info_t *p) { if (NULL != p->peer) { PMIX_RELEASE(p->peer); } if (NULL != p->affected) { PMIX_PROC_FREE(p->affected, p->naffected); } } PMIX_CLASS_INSTANCE(pmix_peer_events_info_t, pmix_list_item_t, prevcon, prevdes); static void regcon(pmix_regevents_info_t *p) { PMIX_CONSTRUCT(&p->peers, pmix_list_t); } static void regdes(pmix_regevents_info_t *p) { PMIX_LIST_DESTRUCT(&p->peers); } PMIX_CLASS_INSTANCE(pmix_regevents_info_t, pmix_list_item_t, regcon, regdes); static void ilcon(pmix_inventory_rollup_t *p) { PMIX_CONSTRUCT_LOCK(&p->lock); p->lock.active = false; p->status = PMIX_SUCCESS; p->requests = 0; p->replies = 0; PMIX_CONSTRUCT(&p->payload, pmix_list_t); p->info = NULL; p->ninfo = 0; p->cbfunc = NULL; p->infocbfunc = NULL; p->opcbfunc = NULL; p->cbdata = NULL; } static void ildes(pmix_inventory_rollup_t *p) { PMIX_DESTRUCT_LOCK(&p->lock); PMIX_LIST_DESTRUCT(&p->payload); } PMIX_CLASS_INSTANCE(pmix_inventory_rollup_t, pmix_object_t, ilcon, ildes); static void grcon(pmix_group_t *p) { p->grpid = NULL; p->members = NULL; p->nmbrs = 0; } static void grdes(pmix_group_t *p) { if (NULL != p->grpid) { free(p->grpid); } if (NULL != p->members) { PMIX_PROC_FREE(p->members, p->nmbrs); } } PMIX_CLASS_INSTANCE(pmix_group_t, pmix_list_item_t, grcon, grdes); PMIX_CLASS_INSTANCE(pmix_group_caddy_t, pmix_list_item_t, NULL, NULL); static void iocon(pmix_iof_cache_t *p) { p->bo = NULL; p->info = NULL; p->ninfo = 0; } static void iodes(pmix_iof_cache_t *p) { PMIX_BYTE_OBJECT_FREE(p->bo, 1); // macro protects against NULL if (0 < p->ninfo) { PMIX_INFO_FREE(p->info, p->ninfo); } } PMIX_CLASS_INSTANCE(pmix_iof_cache_t, pmix_list_item_t, iocon, iodes); static void pscon(pmix_pset_t *p) { p->name = NULL; p->members = NULL; p->nmembers = 0; } static void psdes(pmix_pset_t *p) { if (NULL != p->name) { free(p->name); } if (NULL != p->members) { free(p->members); } } PMIX_CLASS_INSTANCE(pmix_pset_t, pmix_list_item_t, pscon, psdes);
1
9,966
Just wondering - would it make more sense to simply replace `PMIX_DESTRUCT(&t->nslist)` with `PMIX_LIST_DESTRUCT(&t->nslist)` here, and then add `PMIX_RELEASE(p->jobbkt)` to the `pmix_nspace_caddy_t` destructor on line 154 of src/include/pmix_globals.c? Seems to me like we always want to have these things removed/destructed.
openpmix-openpmix
c
@@ -5,7 +5,13 @@ package net.sourceforge.pmd.lang.vf; import net.sourceforge.pmd.AbstractRuleSetFactoryTest; +import net.sourceforge.pmd.lang.apex.rule.ApexXPathRule; public class RuleSetFactoryTest extends AbstractRuleSetFactoryTest { - // no additional tests + public RuleSetFactoryTest() { + super(); + // Copied from net.sourceforge.pmd.lang.apex.RuleSetFactoryTest + // Apex rules are found in the classpath because this module has a dependency on pmd-apex + validXPathClassNames.add(ApexXPathRule.class.getName()); + } }
1
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.lang.vf; import net.sourceforge.pmd.AbstractRuleSetFactoryTest; public class RuleSetFactoryTest extends AbstractRuleSetFactoryTest { // no additional tests }
1
18,045
I think, we should fix/improve AbstractRuleSetFactoryTest. I guess, both apex and visualforce rules are now tested, which is unnecessary.
pmd-pmd
java
@@ -111,6 +111,14 @@ class BackendController extends ControllerBase self::extendableExtendCallback($callback); } + /** + * @inheritDoc + */ + public function callAction($method, $parameters) + { + return parent::callAction($method, array_values($parameters)); + } + /** * Pass unhandled URLs to the CMS Controller, if it exists *
1
<?php namespace Backend\Classes; use Str; use App; use File; use View; use Event; use Config; use Request; use Response; use Illuminate\Routing\Controller as ControllerBase; use October\Rain\Router\Helper as RouterHelper; use System\Classes\PluginManager; use Closure; /** * This is the master controller for all back-end pages. * All requests that are prefixed with the backend URI pattern are sent here, * then the next URI segments are analysed and the request is routed to the * relevant back-end controller. * * For example, a request with the URL `/backend/acme/blog/posts` will look * for the `Posts` controller inside the `Acme.Blog` plugin. * * @see Backend\Classes\Controller Base class for back-end controllers * @package october\backend * @author Alexey Bobkov, Samuel Georges */ class BackendController extends ControllerBase { use \October\Rain\Extension\ExtendableTrait; /** * @var array Behaviors implemented by this controller. */ public $implement; /** * @var string Allows early access to page action. */ public static $action; /** * @var array Allows early access to page parameters. */ public static $params; /** * @var boolean Flag to indicate that the CMS module is handling the current request */ protected $cmsHandling = false; /** * Stores the requested controller so that the constructor is only run once * * @var Backend\Classes\Controller */ protected $requestedController; /** * Instantiate a new BackendController instance. */ public function __construct() { $this->middleware(function ($request, $next) { // Process the request before retrieving controller middleware, to allow for the session and auth data // to be made available to the controller's constructor. $response = $next($request); // Find requested controller to determine if any middleware has been attached $pathParts = explode('/', str_replace(Request::root() . '/', '', Request::url())); if (count($pathParts)) { // Drop off preceding backend URL part if needed if (!empty(Config::get('cms.backendUri', 'backend'))) { array_shift($pathParts); } $path = implode('/', $pathParts); $requestedController = $this->getRequestedController($path); if ( !is_null($requestedController) && is_array($requestedController) && count($requestedController['controller']->getMiddleware()) ) { $action = $requestedController['action']; // Collect applicable middleware and insert middleware into pipeline $controllerMiddleware = collect($requestedController['controller']->getMiddleware()) ->reject(function ($data) use ($action) { return static::methodExcludedByOptions($action, $data['options']); }) ->pluck('middleware'); foreach ($controllerMiddleware as $middleware) { $middleware->call($requestedController['controller'], $request, $response); } } } return $response; }); $this->extendableConstruct(); } /** * Extend this object properties upon construction. */ public static function extend(Closure $callback) { self::extendableExtendCallback($callback); } /** * Pass unhandled URLs to the CMS Controller, if it exists * * @param string $url * @return Response */ protected function passToCmsController($url) { if ( in_array('Cms', Config::get('cms.loadModules', [])) && class_exists('\Cms\Classes\Controller') ) { $this->cmsHandling = true; return App::make('Cms\Classes\Controller')->run($url); } else { return Response::make(View::make('backend::404'), 404); } } /** * Finds and serves the requested backend controller. * If the controller cannot be found, returns the Cms page with the URL /404. * If the /404 page doesn't exist, returns the system 404 page. * @param string $url Specifies the requested page URL. * If the parameter is omitted, the current URL used. * @return string Returns the processed page content. */ public function run($url = null) { $params = RouterHelper::segmentizeUrl($url); // Handle NotFoundHttpExceptions in the backend (usually triggered by abort(404)) Event::listen('exception.beforeRender', function ($exception, $httpCode, $request) { if (!$this->cmsHandling && $exception instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException) { return View::make('backend::404'); } }, 1); /* * Database check */ if (!App::hasDatabase()) { return Config::get('app.debug', false) ? Response::make(View::make('backend::no_database'), 200) : $this->passToCmsController($url); } $controllerRequest = $this->getRequestedController($url); if (!is_null($controllerRequest)) { return $controllerRequest['controller']->run( $controllerRequest['action'], $controllerRequest['params'] ); } /* * Fall back on Cms controller */ return $this->passToCmsController($url); } /** * Determines the controller and action to load in the backend via a provided URL. * * If a suitable controller is found, this will return an array with the controller class name as a string, the * action to call as a string and an array of parameters. If a suitable controller and action cannot be found, * this method will return null. * * @param string $url A URL to determine the requested controller and action for * @return array|null A suitable controller, action and parameters in an array if found, otherwise null. */ protected function getRequestedController($url) { $params = RouterHelper::segmentizeUrl($url); /* * Look for a Module controller */ $module = $params[0] ?? 'backend'; $controller = $params[1] ?? 'index'; self::$action = $action = isset($params[2]) ? $this->parseAction($params[2]) : 'index'; self::$params = $controllerParams = array_slice($params, 3); $controllerClass = '\\'.$module.'\Controllers\\'.$controller; if ($controllerObj = $this->findController( $controllerClass, $action, base_path().'/modules' )) { return [ 'controller' => $controllerObj, 'action' => $action, 'params' => $controllerParams ]; } /* * Look for a Plugin controller */ if (count($params) >= 2) { list($author, $plugin) = $params; $pluginCode = ucfirst($author) . '.' . ucfirst($plugin); if (PluginManager::instance()->isDisabled($pluginCode)) { return Response::make(View::make('backend::404'), 404); } $controller = $params[2] ?? 'index'; self::$action = $action = isset($params[3]) ? $this->parseAction($params[3]) : 'index'; self::$params = $controllerParams = array_slice($params, 4); $controllerClass = '\\'.$author.'\\'.$plugin.'\Controllers\\'.$controller; if ($controllerObj = $this->findController( $controllerClass, $action, plugins_path() )) { return [ 'controller' => $controllerObj, 'action' => $action, 'params' => $controllerParams ]; } } return null; } /** * This method is used internally. * Finds a backend controller with a callable action method. * @param string $controller Specifies a method name to execute. * @param string $action Specifies a method name to execute. * @param string $inPath Base path for class file location. * @return ControllerBase Returns the backend controller object */ protected function findController($controller, $action, $inPath) { if (isset($this->requestedController)) { return $this->requestedController; } /* * Workaround: Composer does not support case insensitivity. */ if (!class_exists($controller)) { $controller = Str::normalizeClassName($controller); $controllerFile = $inPath.strtolower(str_replace('\\', '/', $controller)) . '.php'; if ($controllerFile = File::existsInsensitive($controllerFile)) { include_once $controllerFile; } } if (!class_exists($controller)) { return $this->requestedController = null; } $controllerObj = App::make($controller); if ($controllerObj->actionExists($action)) { return $this->requestedController = $controllerObj; } return $this->requestedController = null; } /** * Process the action name, since dashes are not supported in PHP methods. * @param string $actionName * @return string */ protected function parseAction($actionName) { if (strpos($actionName, '-') !== false) { return camel_case($actionName); } return $actionName; } /** * Determine if the given options exclude a particular method. * * @param string $method * @param array $options * @return bool */ protected static function methodExcludedByOptions($method, array $options) { return (isset($options['only']) && !in_array($method, (array) $options['only'])) || (!empty($options['except']) && in_array($method, (array) $options['except'])); } }
1
19,342
In php8 named parameters were introduced and now it is required to match called method parameter name when setting parameters by array destructing or `call_user_func_array()` etc.
octobercms-october
php
@@ -7,8 +7,10 @@ package javaslang.collection; import javaslang.Function2; import javaslang.Tuple2; +import javaslang.control.Try; import org.junit.Test; +import java.lang.reflect.Field; import java.util.List; import java.util.Random; import java.util.concurrent.ThreadLocalRandom;
1
/* / \____ _ _ ____ ______ / \ ____ __ _______ * / / \/ \ / \/ \ / /\__\/ // \/ \ // /\__\ JΛVΛSLΛNG * _/ / /\ \ \/ / /\ \\__\\ \ // /\ \ /\\/ \ /__\ \ Copyright 2014-2016 Javaslang, http://javaslang.io * /___/\_/ \_/\____/\_/ \_/\__\/__/\__\_/ \_// \__/\_____/ Licensed under the Apache License, Version 2.0 */ package javaslang.collection; import javaslang.Function2; import javaslang.Tuple2; import org.junit.Test; import java.util.List; import java.util.Random; import java.util.concurrent.ThreadLocalRandom; import java.util.function.Function; import java.util.function.Predicate; import static javaslang.API.Tuple; import static javaslang.collection.BitMappedTrie.BRANCHING_FACTOR; import static org.assertj.core.api.Assertions.assertThat; public class VectorPropertyTest { @Test public void shouldCreateAndGet() { for (int i = 0; i < 500; i++) { final Seq<Integer> expected = Array.range(0, i); final Vector<Integer> actual = Vector.ofAll(expected); for (int j = 0; j < actual.size(); j++) { assertThat(expected.get(j)).isEqualTo(actual.get(j)); } assert (i == 0) || !actual.trie.type.type().isPrimitive(); /* boolean */ final Seq<Boolean> expectedBoolean = expected.map(v -> v > 0); final Vector<Boolean> actualBoolean = Vector.ofAll(ArrayType.<boolean[]> asPrimitives(boolean.class, expectedBoolean)); assert (i == 0) || (actualBoolean.trie.type.type() == boolean.class); assertAreEqual(expectedBoolean, actualBoolean); assertAreEqual(expectedBoolean.append(null), actualBoolean.append(null)); /* byte */ final Seq<Byte> expectedByte = expected.map(Integer::byteValue); final Vector<Byte> actualByte = Vector.ofAll(ArrayType.<byte[]> asPrimitives(byte.class, expectedByte)); assert (i == 0) || (actualByte.trie.type.type() == byte.class); assertAreEqual(expectedByte, actualByte); assertAreEqual(expectedByte.append(null), actualByte.append(null)); /* char */ final Seq<Character> expectedChar = expected.map(v -> (char) v.intValue()); final Vector<Character> actualChar = Vector.ofAll(ArrayType.<char[]> asPrimitives(char.class, expectedChar)); assert (i == 0) || (actualChar.trie.type.type() == char.class); assertAreEqual(expectedChar, actualChar); assertAreEqual(expectedChar.append(null), actualChar.append(null)); /* double */ final Seq<Double> expectedDouble = expected.map(Integer::doubleValue); final Vector<Double> actualDouble = Vector.ofAll(ArrayType.<double[]> asPrimitives(double.class, expectedDouble)); assert (i == 0) || (actualDouble.trie.type.type() == double.class); assertAreEqual(expectedDouble, actualDouble); assertAreEqual(expectedDouble.append(null), actualDouble.append(null)); /* float */ final Seq<Float> expectedFloat = expected.map(Integer::floatValue); final Vector<Float> actualFloat = Vector.ofAll(ArrayType.<float[]> asPrimitives(float.class, expectedFloat)); assert (i == 0) || (actualFloat.trie.type.type() == float.class); assertAreEqual(expectedFloat, actualFloat); assertAreEqual(expectedFloat.append(null), actualFloat.append(null)); /* int */ final Vector<Integer> actualInt = Vector.ofAll(ArrayType.<int[]> asPrimitives(int.class, expected)); assert (i == 0) || (actualInt.trie.type.type() == int.class); assertAreEqual(expected, actualInt); assertAreEqual(expected.append(null), actual.append(null)); /* long */ final Seq<Long> expectedLong = expected.map(Integer::longValue); final Vector<Long> actualLong = Vector.ofAll(ArrayType.<long[]> asPrimitives(long.class, expectedLong)); assert (i == 0) || (actualLong.trie.type.type() == long.class); assertAreEqual(expectedLong, actualLong); assertAreEqual(expectedLong.append(null), actualLong.append(null)); /* short */ final Seq<Short> expectedShort = expected.map(Integer::shortValue); final Vector<Short> actualShort = Vector.ofAll(ArrayType.<short[]> asPrimitives(short.class, expectedShort)); assert (i == 0) || (actualShort.trie.type.type() == short.class); assertAreEqual(expectedShort, actualShort); assertAreEqual(expectedShort.append(null), actualShort.append(null)); } } @Test public void shouldIterate() { for (byte depth = 0; depth <= 2; depth++) { for (int i = 0; i < 5000; i++) { final Seq<Integer> expected = Array.range(0, i); final Vector<Integer> actual = Vector.ofAll(expected); assertAreEqual(actual, expected); } } Seq<Integer> expected = Array.range(0, 1000); Vector<Integer> actual = Vector.ofAll(ArrayType.<int[]> asPrimitives(int.class, expected)); for (int drop = 0; drop <= (BRANCHING_FACTOR + 1); drop++) { final Iterator<Integer> expectedIterator = expected.iterator(); actual.trie.<int[]> visit((index, leaf, start, end) -> { for (int i = start; i < end; i++) { assertThat(leaf[i]).isEqualTo(expectedIterator.next()); } return -1; }); expected = expected.tail().init(); actual = actual.tail().init(); } } @Test public void shouldPrepend() { Seq<Integer> expected = Array.empty(); Vector<Integer> actual = Vector.empty(); for (int drop = 0; drop <= (BRANCHING_FACTOR + 1); drop++) { for (Integer value : Iterator.range(0, 1000)) { expected = expected.drop(drop); actual = assertAreEqual(actual, drop, Vector::drop, expected); expected = expected.prepend(value); actual = assertAreEqual(actual, value, Vector::prepend, expected); } } } @Test public void shouldAppend() { Seq<Integer> expected = Array.empty(); Vector<Integer> actual = Vector.empty(); for (int drop = 0; drop <= (BRANCHING_FACTOR + 1); drop++) { for (Integer value : Iterator.range(0, 500)) { expected = expected.drop(drop); actual = assertAreEqual(actual, drop, Vector::drop, expected); expected = expected.append(value); actual = assertAreEqual(actual, value, Vector::append, expected); } } } @Test public void shouldUpdate() { final Function<Integer, Integer> mapper = i -> i + 1; for (byte depth = 0; depth <= 2; depth++) { final int length = 10_000; for (int drop = 0; drop <= (BRANCHING_FACTOR + 1); drop++) { Seq<Integer> expected = Array.range(0, length); Vector<Integer> actual = Vector.ofAll(expected); expected = expected.drop(drop); // test the `trailing` drops and the internal tree offset actual = assertAreEqual(actual, drop, Vector::drop, expected); for (int i = 0; i < actual.length(); i++) { final Integer newValue = mapper.apply(actual.get(i)); actual = actual.update(i, newValue); } assertAreEqual(actual, 0, (a, p) -> a, expected.map(mapper)); } } } @Test public void shouldDrop() { final Seq<Integer> expected = Array.range(0, 2_000); final Vector<Integer> actual = Vector.ofAll(expected); Vector<Integer> actualSingleDrop = actual; for (int i = 0; i <= expected.length(); i++) { final Seq<Integer> expectedDrop = expected.drop(i); assertAreEqual(actual, i, Vector::drop, expectedDrop); assertAreEqual(actualSingleDrop, null, (a, p) -> a, expectedDrop); actualSingleDrop = actualSingleDrop.drop(1); } } @Test public void shouldDropRight() { final Seq<Integer> expected = Array.range(0, 2_000); final Vector<Integer> actual = Vector.ofAll(expected); Vector<Integer> actualSingleDrop = actual; for (int i = 0; i <= expected.length(); i++) { final Seq<Integer> expectedDrop = expected.dropRight(i); assertAreEqual(actual, i, Vector::dropRight, expectedDrop); assertAreEqual(actualSingleDrop, null, (a, p) -> a, expectedDrop); actualSingleDrop = actualSingleDrop.dropRight(1); } } @Test public void shouldSlice() { for (int length = 1, end = 500; length <= end; length++) { Seq<Integer> expected = Array.range(0, length); Vector<Integer> actual = Vector.ofAll(expected); for (int i = 0; i <= expected.length(); i++) { expected = expected.slice(1, expected.size() - 1); actual = assertAreEqual(actual, i, (a, p) -> a.slice(1, a.size() - 1), expected); } } } @Test public void shouldBehaveLikeArray() { final int seed = ThreadLocalRandom.current().nextInt(); System.out.println("using seed " + seed); final Random random = new Random(seed); for (int i = 1; i < 10; i++) { Seq<Object> expected = Array.empty(); Vector<Object> actual = Vector.empty(); for (int j = 0; j < 20_000; j++) { Seq<Tuple2<Seq<Object>, Vector<Object>>> history = Array.empty(); if (percent(random) < 20) { expected = Array.ofAll(Vector.ofAll(randomValues(random, 100)).filter(v -> v instanceof Integer)); actual = (percent(random) < 30) ? Vector.narrow(Vector.ofAll(ArrayType.<int[]> asPrimitives(int.class, expected))) : Vector.ofAll(expected); assertAreEqual(expected, actual); history = history.append(Tuple(expected, actual)); } if (percent(random) < 50) { final Object value = randomValue(random); expected = expected.append(value); actual = assertAreEqual(actual, value, Vector::append, expected); history = history.append(Tuple(expected, actual)); } if (percent(random) < 10) { Iterable<Object> values = randomValues(random, random.nextInt(2 * BRANCHING_FACTOR)); expected = expected.appendAll(values); values = (percent(random) < 50) ? Iterator.ofAll(values.iterator()) : values; /* not traversable again */ actual = assertAreEqual(actual, values, Vector::appendAll, expected); history = history.append(Tuple(expected, actual)); } if (percent(random) < 50) { final Object value = randomValue(random); expected = expected.prepend(value); actual = assertAreEqual(actual, value, Vector::prepend, expected); history = history.append(Tuple(expected, actual)); } if (percent(random) < 10) { Iterable<Object> values = randomValues(random, random.nextInt(2 * BRANCHING_FACTOR)); expected = expected.prependAll(values); values = (percent(random) < 50) ? Iterator.ofAll(values) : values; /* not traversable again */ actual = assertAreEqual(actual, values, Vector::prependAll, expected); history = history.append(Tuple(expected, actual)); } if (percent(random) < 30) { final int n = random.nextInt(expected.size() + 1); expected = expected.drop(n); actual = assertAreEqual(actual, n, Vector::drop, expected); history = history.append(Tuple(expected, actual)); } if (percent(random) < 10) { final int index = random.nextInt(expected.size() + 1); Iterable<Object> values = randomValues(random, random.nextInt(2 * BRANCHING_FACTOR)); expected = expected.insertAll(index, values); values = (percent(random) < 50) ? Iterator.ofAll(values) : values; /* not traversable again */ actual = assertAreEqual(actual, values, (a, p) -> a.insertAll(index, p), expected); history = history.append(Tuple(expected, actual)); } if (percent(random) < 30) { final int n = random.nextInt(expected.size() + 1); expected = expected.take(n); actual = assertAreEqual(actual, n, Vector::take, expected); history = history.append(Tuple(expected, actual)); } if (!expected.isEmpty()) { assertThat(actual.head()).isEqualTo(expected.head()); assertThat(actual.tail().toJavaList()).isEqualTo(expected.tail().toJavaList()); history = history.append(Tuple(expected, actual)); } if (!expected.isEmpty()) { final int index = random.nextInt(expected.size()); assertThat(actual.get(index)).isEqualTo(expected.get(index)); history = history.append(Tuple(expected, actual)); } if (percent(random) < 50) { if (!expected.isEmpty()) { final int index = random.nextInt(expected.size()); final Object value = randomValue(random); expected = expected.update(index, value); actual = assertAreEqual(actual, null, (a, p) -> a.update(index, value), expected); history = history.append(Tuple(expected, actual)); } } if (percent(random) < 20) { final Function<Object, Object> mapper = val -> (val instanceof Integer) ? ((Integer) val + 1) : val; expected = expected.map(mapper); actual = assertAreEqual(actual, null, (a, p) -> a.map(mapper), expected); history = history.append(Tuple(expected, actual)); } if (percent(random) < 30) { final Predicate<Object> filter = val -> (String.valueOf(val).length() % 10) == 0; expected = expected.filter(filter); actual = assertAreEqual(actual, null, (a, p) -> a.filter(filter), expected); history = history.append(Tuple(expected, actual)); } if (percent(random) < 30) { for (int k = 0; k < 2; k++) { if (!expected.isEmpty()) { final int to = random.nextInt(expected.size()); final int from = random.nextInt(to + 1); expected = expected.slice(from, to); actual = assertAreEqual(actual, null, (a, p) -> a.slice(from, to), expected); history = history.append(Tuple(expected, actual)); } } } history.forEach(t -> assertAreEqual(t._1, t._2)); // test that the modifications are persistent } } } private int percent(Random random) { return random.nextInt(101); } private Iterable<Object> randomValues(Random random, int count) { final Vector<Object> values = Vector.range(0, count).map(v -> randomValue(random)); final int percent = percent(random); if (percent < 30) { return values.toJavaList(); /* not Traversable */ } else { return values; } } private Object randomValue(Random random) { final int percent = percent(random); if (percent < 5) { return null; } else if (percent < 10) { return "String"; } else { return random.nextInt(); } } private static <T extends Seq<?>, P> T assertAreEqual(T previousActual, P param, Function2<T, P, T> actualProvider, Seq<?> expected) { final T actual = actualProvider.apply(previousActual, param); assertAreEqual(expected, actual); return actual; // makes debugging a lot easier, as the frame can be dropped and rerun on AssertError } private static void assertAreEqual(Seq<?> expected, Seq<?> actual) { final List<?> actualList = actual.toJavaList(); final List<?> expectedList = expected.toJavaList(); assertThat(actualList).isEqualTo(expectedList); // a lot faster than `hasSameElementsAs` } }
1
11,472
easily possible to get that information without exposing internal information
vavr-io-vavr
java
@@ -65,7 +65,13 @@ module Beaker found_env_vars[:answers][key] = value if key.to_s =~ /q_/ end found_env_vars[:consoleport] &&= found_env_vars[:consoleport].to_i - found_env_vars[:type] = found_env_vars[:is_pe] == 'true' || found_env_vars[:is_pe] == 'yes' ? 'pe' : nil + if found_env_vars[:is_pe] == 'true' || found_env_vars[:is_pe] == 'yes' + found_env_vars[:type] = 'pe' + elsif found_env_vars[:is_pe] == 'false' || found_env_vars[:is_pe] == 'no' + found_env_vars[:type] = 'foss' + else + found_env_vars[:type] = nil + end found_env_vars[:pe_version_file_win] = found_env_vars[:pe_version_file] found_env_vars[:answers].delete_if {|key, value| value.nil? or value.empty? } found_env_vars.delete_if {|key, value| value.nil? or value.empty? }
1
module Beaker module Options #A set of functions representing the environment variables and preset argument values to be incorporated #into the Beaker options Object. module Presets # This is a constant that describes the variables we want to collect # from the environment. The keys correspond to the keys in # `self.presets` (flattened) The values are an optional array of # environment variable names to look for. The array structure allows # us to define multiple environment variables for the same # configuration value. They are checked in the order they are arrayed # so that preferred and "fallback" values work as expected. ENVIRONMENT_SPEC = { :home => 'HOME', :project => ['BEAKER_PROJECT', 'BEAKER_project'], :department => ['BEAKER_DEPARTMENT', 'BEAKER_department'], :jenkins_build_url => ['BEAKER_BUILD_URL', 'BUILD_URL'], :consoleport => ['BEAKER_CONSOLEPORT', 'consoleport'], :is_pe => ['BEAKER_IS_PE', 'IS_PE'], :pe_dir => ['BEAKER_PE_DIR', 'pe_dist_dir'], :pe_version_file => ['BEAKER_PE_VERSION_FILE', 'pe_version_file'], :pe_ver => ['BEAKER_PE_VER', 'pe_ver'], :forge_host => ['BEAKER_FORGE_HOST', 'forge_host'], :package_proxy => ['BEAKER_PACKAGE_PROXY'], :release_apt_repo_url => ['BEAKER_RELEASE_APT_REPO', 'RELEASE_APT_REPO'], :release_yum_repo_url => ['BEAKER_RELEASE_YUM_REPO', 'RELEASE_YUM_REPO'], :dev_builds_url => ['BEAKER_DEV_BUILDS_URL', 'DEV_BUILDS_URL'], :q_puppet_enterpriseconsole_auth_user_email => 'q_puppet_enterpriseconsole_auth_user_email', :q_puppet_enterpriseconsole_auth_password => 'q_puppet_enterpriseconsole_auth_password', :q_puppet_enterpriseconsole_smtp_host => 'q_puppet_enterpriseconsole_smtp_host', :q_puppet_enterpriseconsole_smtp_port => 'q_puppet_enterpriseconsole_smtp_port', :q_puppet_enterpriseconsole_smtp_username => 'q_puppet_enterpriseconsole_smtp_username', :q_puppet_enterpriseconsole_smtp_password => 'q_puppet_enterpriseconsole_smtp_password', :q_puppet_enterpriseconsole_smtp_use_tls => 'q_puppet_enterpriseconsole_smtp_use_tls', :q_verify_packages => 'q_verify_packages', :q_puppetdb_password => 'q_puppetdb_password', } # Takes an environment_spec and searches the processes environment variables accordingly # # @param [Hash{Symbol=>Array,String}] env_var_spec the spec of what env vars to search for # # @return [Hash] Found environment values def self.collect_env_vars( env_var_spec ) env_var_spec.inject({:answers => {}}) do |memo, key_value| key, value = key_value[0], key_value[1] set_env_var = Array(value).detect {|possible_variable| ENV[possible_variable] } memo[key] = ENV[set_env_var] if set_env_var memo end end # Takes a hash where the values are found environment configuration values # and munges them to appropriate Beaker configuration values # # @param [Hash{Symbol=>String}] found_env_vars Environment variables to munge # # @return [Hash] Environment config values munged appropriately def self.munge_found_env_vars( found_env_vars ) found_env_vars[:answers] ||= {} found_env_vars.each_pair do |key,value| found_env_vars[:answers][key] = value if key.to_s =~ /q_/ end found_env_vars[:consoleport] &&= found_env_vars[:consoleport].to_i found_env_vars[:type] = found_env_vars[:is_pe] == 'true' || found_env_vars[:is_pe] == 'yes' ? 'pe' : nil found_env_vars[:pe_version_file_win] = found_env_vars[:pe_version_file] found_env_vars[:answers].delete_if {|key, value| value.nil? or value.empty? } found_env_vars.delete_if {|key, value| value.nil? or value.empty? } end # Generates an OptionsHash of the environment variables of interest to Beaker # # @return [OptionsHash] The supported environment variables in an OptionsHash, # empty or nil environment variables are removed from the OptionsHash def self.env_vars h = Beaker::Options::OptionsHash.new found = munge_found_env_vars( collect_env_vars( ENVIRONMENT_SPEC )) return h.merge( found ) end # Generates an OptionsHash of preset values for arguments supported by Beaker # # @return [OptionsHash] The supported arguments in an OptionsHash def self.presets h = Beaker::Options::OptionsHash.new h.merge({ :project => 'Beaker', :department => ENV['USER'] || ENV['USERNAME'] || 'unknown', :validate => true, :jenkins_build_url => nil, :forge_host => 'vulcan-acceptance.delivery.puppetlabs.net', :log_level => 'verbose', :trace_limit => 10, :"master-start-curl-retries" => 120, :options_file => nil, :type => 'pe', :provision => true, :preserve_hosts => 'never', :root_keys => false, :quiet => false, :project_root => File.expand_path(File.join(File.dirname(__FILE__), "../")), :xml_dir => 'junit', :xml_file => 'beaker_junit.xml', :xml_stylesheet => 'junit.xsl', :log_dir => 'log', :color => true, :dry_run => false, :timeout => 300, :fail_mode => 'slow', :timesync => false, :repo_proxy => false, :package_proxy => false, :add_el_extras => false, :release_apt_repo_url => "http://apt.puppetlabs.com", :release_yum_repo_url => "http://yum.puppetlabs.com", :dev_builds_url => "http://builds.puppetlabs.lan", :consoleport => 443, :pe_dir => '/opt/enterprise/dists', :pe_version_file => 'LATEST', :pe_version_file_win => 'LATEST-win', :answers => { :q_puppet_enterpriseconsole_auth_user_email => '[email protected]', :q_puppet_enterpriseconsole_auth_password => '~!@#$%^*-/ aZ', :q_puppet_enterpriseconsole_smtp_port => 25, :q_puppet_enterpriseconsole_smtp_use_tls => 'n', :q_verify_packages => 'y', :q_puppetdb_password => '~!@#$%^*-/ aZ' }, :dot_fog => File.join(ENV['HOME'], '.fog'), :ec2_yaml => 'config/image_templates/ec2.yaml', :help => false, :collect_perf_data => false, :ssh => { :config => false, :paranoid => false, :timeout => 300, :auth_methods => ["publickey"], :port => 22, :forward_agent => true, :keys => ["#{ENV['HOME']}/.ssh/id_rsa"], :user_known_hosts_file => "#{ENV['HOME']}/.ssh/known_hosts", } }) end end end end
1
7,140
Why do we need tristate logic (pe, foss, nil)?
voxpupuli-beaker
rb
@@ -19,13 +19,13 @@ import ( func TestBlocksAfterFlagTimeout(t *testing.T) { - mu := sync.Mutex{} + mux := sync.Mutex{} blocked := make(map[string]time.Duration) mock := mockBlockLister(func(a swarm.Address, d time.Duration, r string) error { - mu.Lock() + mux.Lock() blocked[a.ByteString()] = d - mu.Unlock() + mux.Unlock() return nil })
1
// Copyright 2021 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 blocker_test import ( "io/ioutil" "sync" "testing" "time" "github.com/ethersphere/bee/pkg/logging" "github.com/ethersphere/bee/pkg/swarm" "github.com/ethersphere/bee/pkg/swarm/test" "github.com/ethersphere/bee/pkg/blocker" ) func TestBlocksAfterFlagTimeout(t *testing.T) { mu := sync.Mutex{} blocked := make(map[string]time.Duration) mock := mockBlockLister(func(a swarm.Address, d time.Duration, r string) error { mu.Lock() blocked[a.ByteString()] = d mu.Unlock() return nil }) logger := logging.New(ioutil.Discard, 0) flagTime := time.Millisecond * 25 checkTime := time.Millisecond * 100 blockTime := time.Second b := blocker.New(mock, flagTime, blockTime, time.Millisecond, nil, logger) addr := test.RandomAddress() b.Flag(addr) mu.Lock() if _, ok := blocked[addr.ByteString()]; ok { mu.Unlock() t.Fatal("blocker did not wait flag duration") } mu.Unlock() midway := time.After(flagTime / 2) check := time.After(checkTime) <-midway b.Flag(addr) // check thats this flag call does not overide previous call <-check mu.Lock() blockedTime, ok := blocked[addr.ByteString()] mu.Unlock() if !ok { t.Fatal("address should be blocked") } if blockedTime != blockTime { t.Fatalf("block time: want %v, got %v", blockTime, blockedTime) } b.Close() } func TestUnflagBeforeBlock(t *testing.T) { mu := sync.Mutex{} blocked := make(map[string]time.Duration) mock := mockBlockLister(func(a swarm.Address, d time.Duration, r string) error { mu.Lock() blocked[a.ByteString()] = d mu.Unlock() return nil }) logger := logging.New(ioutil.Discard, 0) flagTime := time.Millisecond * 25 checkTime := time.Millisecond * 100 blockTime := time.Second b := blocker.New(mock, flagTime, blockTime, time.Millisecond, nil, logger) addr := test.RandomAddress() b.Flag(addr) mu.Lock() if _, ok := blocked[addr.ByteString()]; ok { mu.Unlock() t.Fatal("blocker did not wait flag duration") } mu.Unlock() b.Unflag(addr) time.Sleep(checkTime) mu.Lock() _, ok := blocked[addr.ByteString()] mu.Unlock() if ok { t.Fatal("address should not be blocked") } b.Close() } type blocklister struct { blocklistFunc func(swarm.Address, time.Duration, string) error } func mockBlockLister(f func(swarm.Address, time.Duration, string) error) *blocklister { return &blocklister{ blocklistFunc: f, } } func (b *blocklister) Blocklist(addr swarm.Address, t time.Duration, r string) error { return b.blocklistFunc(addr, t, r) }
1
15,687
this change needs to be reverted to what is on `master`
ethersphere-bee
go
@@ -1076,9 +1076,14 @@ Blockly.WorkspaceSvg.prototype.deleteVariableById = function(id) { * @package */ Blockly.WorkspaceSvg.prototype.createVariable = function(name, opt_type, opt_id) { + var variableInMap = (this.getVariable(name) != null); var newVar = Blockly.WorkspaceSvg.superClass_.createVariable.call(this, name, opt_type, opt_id); - this.refreshToolboxSelection_(); + // For performance reaons, only refresh the the toolbox for new variables. + // Variables that already exist should already be there. + if (!variableInMap) { + this.refreshToolboxSelection_(); + } return newVar; };
1
/** * @license * Visual Blocks Editor * * Copyright 2014 Google Inc. * https://developers.google.com/blockly/ * * 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. */ /** * @fileoverview Object representing a workspace rendered as SVG. * @author [email protected] (Neil Fraser) */ 'use strict'; goog.provide('Blockly.WorkspaceSvg'); // TODO(scr): Fix circular dependencies //goog.require('Blockly.BlockSvg'); goog.require('Blockly.Colours'); goog.require('Blockly.ConnectionDB'); goog.require('Blockly.constants'); goog.require('Blockly.DataCategory'); goog.require('Blockly.DropDownDiv'); goog.require('Blockly.Events'); goog.require('Blockly.Gesture'); goog.require('Blockly.Grid'); goog.require('Blockly.Options'); goog.require('Blockly.ScrollbarPair'); goog.require('Blockly.Touch'); goog.require('Blockly.Trashcan'); //goog.require('Blockly.VerticalFlyout'); goog.require('Blockly.Workspace'); goog.require('Blockly.WorkspaceAudio'); goog.require('Blockly.WorkspaceDragSurfaceSvg'); goog.require('Blockly.Xml'); goog.require('Blockly.ZoomControls'); goog.require('goog.array'); goog.require('goog.dom'); goog.require('goog.math.Coordinate'); goog.require('goog.userAgent'); /** * Class for a workspace. This is an onscreen area with optional trashcan, * scrollbars, bubbles, and dragging. * @param {!Blockly.Options} options Dictionary of options. * @param {Blockly.BlockDragSurfaceSvg=} opt_blockDragSurface Drag surface for * blocks. * @param {Blockly.WorkspaceDragSurfaceSvg=} opt_wsDragSurface Drag surface for * the workspace. * @extends {Blockly.Workspace} * @constructor */ Blockly.WorkspaceSvg = function(options, opt_blockDragSurface, opt_wsDragSurface) { Blockly.WorkspaceSvg.superClass_.constructor.call(this, options); this.getMetrics = options.getMetrics || Blockly.WorkspaceSvg.getTopLevelWorkspaceMetrics_; this.setMetrics = options.setMetrics || Blockly.WorkspaceSvg.setTopLevelWorkspaceMetrics_; Blockly.ConnectionDB.init(this); if (opt_blockDragSurface) { this.blockDragSurface_ = opt_blockDragSurface; } if (opt_wsDragSurface) { this.workspaceDragSurface_ = opt_wsDragSurface; } this.useWorkspaceDragSurface_ = this.workspaceDragSurface_ && Blockly.utils.is3dSupported(); /** * List of currently highlighted blocks. Block highlighting is often used to * visually mark blocks currently being executed. * @type !Array.<!Blockly.BlockSvg> * @private */ this.highlightedBlocks_ = []; /** * Object in charge of loading, storing, and playing audio for a workspace. * @type {Blockly.WorkspaceAudio} * @private */ this.audioManager_ = new Blockly.WorkspaceAudio(options.parentWorkspace); /** * This workspace's grid object or null. * @type {Blockly.Grid} * @private */ this.grid_ = this.options.gridPattern ? new Blockly.Grid(options.gridPattern, options.gridOptions) : null; this.registerToolboxCategoryCallback(Blockly.VARIABLE_CATEGORY_NAME, Blockly.DataCategory); this.registerToolboxCategoryCallback(Blockly.PROCEDURE_CATEGORY_NAME, Blockly.Procedures.flyoutCategory); }; goog.inherits(Blockly.WorkspaceSvg, Blockly.Workspace); /** * A wrapper function called when a resize event occurs. * You can pass the result to `unbindEvent_`. * @type {Array.<!Array>} */ Blockly.WorkspaceSvg.prototype.resizeHandlerWrapper_ = null; /** * The render status of an SVG workspace. * Returns `true` for visible workspaces and `false` for non-visible, * or headless, workspaces. * @type {boolean} */ Blockly.WorkspaceSvg.prototype.rendered = true; /** * Is this workspace the surface for a flyout? * @type {boolean} */ Blockly.WorkspaceSvg.prototype.isFlyout = false; /** * Is this workspace the surface for a mutator? * @type {boolean} * @package */ Blockly.WorkspaceSvg.prototype.isMutator = false; /** * Whether this workspace has resizes enabled. * Disable during batch operations for a performance improvement. * @type {boolean} * @private */ Blockly.WorkspaceSvg.prototype.resizesEnabled_ = true; /** * Whether this workspace is in the middle of a bulk update. * Turn on during batch operations for a performance improvement. * @type {boolean} * @private */ Blockly.WorkspaceSvg.prototype.isBulkUpdating_ = false; /** * Current horizontal scrolling offset in pixel units. * @type {number} */ Blockly.WorkspaceSvg.prototype.scrollX = 0; /** * Current vertical scrolling offset in pixel units. * @type {number} */ Blockly.WorkspaceSvg.prototype.scrollY = 0; /** * Horizontal scroll value when scrolling started in pixel units. * @type {number} */ Blockly.WorkspaceSvg.prototype.startScrollX = 0; /** * Vertical scroll value when scrolling started in pixel units. * @type {number} */ Blockly.WorkspaceSvg.prototype.startScrollY = 0; /** * Distance from mouse to object being dragged. * @type {goog.math.Coordinate} * @private */ Blockly.WorkspaceSvg.prototype.dragDeltaXY_ = null; /** * Current scale. * @type {number} */ Blockly.WorkspaceSvg.prototype.scale = 1; /** * The workspace's trashcan (if any). * @type {Blockly.Trashcan} */ Blockly.WorkspaceSvg.prototype.trashcan = null; /** * This workspace's scrollbars, if they exist. * @type {Blockly.ScrollbarPair} */ Blockly.WorkspaceSvg.prototype.scrollbar = null; /** * The current gesture in progress on this workspace, if any. * @type {Blockly.Gesture} * @private */ Blockly.WorkspaceSvg.prototype.currentGesture_ = null; /** * This workspace's surface for dragging blocks, if it exists. * @type {Blockly.BlockDragSurfaceSvg} * @private */ Blockly.WorkspaceSvg.prototype.blockDragSurface_ = null; /** * This workspace's drag surface, if it exists. * @type {Blockly.WorkspaceDragSurfaceSvg} * @private */ Blockly.WorkspaceSvg.prototype.workspaceDragSurface_ = null; /** * Whether to move workspace to the drag surface when it is dragged. * True if it should move, false if it should be translated directly. * @type {boolean} * @private */ Blockly.WorkspaceSvg.prototype.useWorkspaceDragSurface_ = false; /** * Whether the drag surface is actively in use. When true, calls to * translate will translate the drag surface instead of the translating the * workspace directly. * This is set to true in setupDragSurface and to false in resetDragSurface. * @type {boolean} * @private */ Blockly.WorkspaceSvg.prototype.isDragSurfaceActive_ = false; /** * Last known position of the page scroll. * This is used to determine whether we have recalculated screen coordinate * stuff since the page scrolled. * @type {!goog.math.Coordinate} * @private */ Blockly.WorkspaceSvg.prototype.lastRecordedPageScroll_ = null; /** * The first parent div with 'injectionDiv' in the name, or null if not set. * Access this with getInjectionDiv. * @type {!Element} * @private */ Blockly.WorkspaceSvg.prototype.injectionDiv_ = null; /** * Map from function names to callbacks, for deciding what to do when a button * is clicked. * @type {!Object<string, function(!Blockly.FlyoutButton)>} * @private */ Blockly.WorkspaceSvg.prototype.flyoutButtonCallbacks_ = {}; /** * Map from function names to callbacks, for deciding what to do when a custom * toolbox category is opened. * @type {!Object<string, function(!Blockly.Workspace):!Array<!Element>>} * @private */ Blockly.WorkspaceSvg.prototype.toolboxCategoryCallbacks_ = {}; /** * Inverted screen CTM, for use in mouseToSvg. * @type {SVGMatrix} * @private */ Blockly.WorkspaceSvg.prototype.inverseScreenCTM_ = null; /** * Getter for the inverted screen CTM. * @return {SVGMatrix} The matrix to use in mouseToSvg */ Blockly.WorkspaceSvg.prototype.getInverseScreenCTM = function() { return this.inverseScreenCTM_; }; /** * Update the inverted screen CTM. */ Blockly.WorkspaceSvg.prototype.updateInverseScreenCTM = function() { var ctm = this.getParentSvg().getScreenCTM(); if (ctm) { this.inverseScreenCTM_ = ctm.inverse(); } }; /** * Return the absolute coordinates of the top-left corner of this element, * scales that after canvas SVG element, if it's a descendant. * The origin (0,0) is the top-left corner of the Blockly SVG. * @param {!Element} element Element to find the coordinates of. * @return {!goog.math.Coordinate} Object with .x and .y properties. * @private */ Blockly.WorkspaceSvg.prototype.getSvgXY = function(element) { var x = 0; var y = 0; var scale = 1; if (goog.dom.contains(this.getCanvas(), element) || goog.dom.contains(this.getBubbleCanvas(), element)) { // Before the SVG canvas, scale the coordinates. scale = this.scale; } do { // Loop through this block and every parent. var xy = Blockly.utils.getRelativeXY(element); if (element == this.getCanvas() || element == this.getBubbleCanvas()) { // After the SVG canvas, don't scale the coordinates. scale = 1; } x += xy.x * scale; y += xy.y * scale; element = element.parentNode; } while (element && element != this.getParentSvg()); return new goog.math.Coordinate(x, y); }; /** * Return the position of the workspace origin relative to the injection div * origin in pixels. * The workspace origin is where a block would render at position (0, 0). * It is not the upper left corner of the workspace SVG. * @return {!goog.math.Coordinate} Offset in pixels. * @package */ Blockly.WorkspaceSvg.prototype.getOriginOffsetInPixels = function() { return Blockly.utils.getInjectionDivXY_(this.svgBlockCanvas_); }; /** * Return the injection div that is a parent of this workspace. * Walks the DOM the first time it's called, then returns a cached value. * @return {!Element} The first parent div with 'injectionDiv' in the name. * @package */ Blockly.WorkspaceSvg.prototype.getInjectionDiv = function() { // NB: it would be better to pass this in at createDom, but is more likely to // break existing uses of Blockly. if (!this.injectionDiv_) { var element = this.svgGroup_; while (element) { var classes = element.getAttribute('class') || ''; if ((' ' + classes + ' ').indexOf(' injectionDiv ') != -1) { this.injectionDiv_ = element; break; } element = element.parentNode; } } return this.injectionDiv_; }; /** * Save resize handler data so we can delete it later in dispose. * @param {!Array.<!Array>} handler Data that can be passed to unbindEvent_. */ Blockly.WorkspaceSvg.prototype.setResizeHandlerWrapper = function(handler) { this.resizeHandlerWrapper_ = handler; }; /** * Create the workspace DOM elements. * @param {string=} opt_backgroundClass Either 'blocklyMainBackground' or * 'blocklyMutatorBackground'. * @return {!Element} The workspace's SVG group. */ Blockly.WorkspaceSvg.prototype.createDom = function(opt_backgroundClass) { /** * <g class="blocklyWorkspace"> * <rect class="blocklyMainBackground" height="100%" width="100%"></rect> * [Trashcan and/or flyout may go here] * <g class="blocklyBlockCanvas"></g> * <g class="blocklyBubbleCanvas"></g> * </g> * @type {SVGElement} */ this.svgGroup_ = Blockly.utils.createSvgElement('g', {'class': 'blocklyWorkspace'}, null); // Note that a <g> alone does not receive mouse events--it must have a // valid target inside it. If no background class is specified, as in the // flyout, the workspace will not receive mouse events. if (opt_backgroundClass) { /** @type {SVGElement} */ this.svgBackground_ = Blockly.utils.createSvgElement('rect', {'height': '100%', 'width': '100%', 'class': opt_backgroundClass}, this.svgGroup_); if (opt_backgroundClass == 'blocklyMainBackground' && this.grid_) { this.svgBackground_.style.fill = 'url(#' + this.grid_.getPatternId() + ')'; } } /** @type {SVGElement} */ this.svgBlockCanvas_ = Blockly.utils.createSvgElement('g', {'class': 'blocklyBlockCanvas'}, this.svgGroup_, this); /** @type {SVGElement} */ this.svgBubbleCanvas_ = Blockly.utils.createSvgElement('g', {'class': 'blocklyBubbleCanvas'}, this.svgGroup_, this); var bottom = Blockly.Scrollbar.scrollbarThickness; if (this.options.hasTrashcan) { bottom = this.addTrashcan_(bottom); } if (this.options.zoomOptions && this.options.zoomOptions.controls) { bottom = this.addZoomControls_(bottom); } if (!this.isFlyout) { Blockly.bindEventWithChecks_(this.svgGroup_, 'mousedown', this, this.onMouseDown_); if (this.options.zoomOptions && this.options.zoomOptions.wheel) { // Mouse-wheel. Blockly.bindEventWithChecks_(this.svgGroup_, 'wheel', this, this.onMouseWheel_); } } // Determine if there needs to be a category tree, or a simple list of // blocks. This cannot be changed later, since the UI is very different. if (this.options.hasCategories) { /** * @type {Blockly.Toolbox} * @private */ this.toolbox_ = new Blockly.Toolbox(this); } if (this.grid_) { this.grid_.update(this.scale); } this.recordDeleteAreas(); return this.svgGroup_; }; /** * Dispose of this workspace. * Unlink from all DOM elements to prevent memory leaks. */ Blockly.WorkspaceSvg.prototype.dispose = function() { // Stop rerendering. this.rendered = false; if (this.currentGesture_) { this.currentGesture_.cancel(); } Blockly.WorkspaceSvg.superClass_.dispose.call(this); if (this.svgGroup_) { goog.dom.removeNode(this.svgGroup_); this.svgGroup_ = null; } this.svgBlockCanvas_ = null; this.svgBubbleCanvas_ = null; if (this.toolbox_) { this.toolbox_.dispose(); this.toolbox_ = null; } if (this.flyout_) { this.flyout_.dispose(); this.flyout_ = null; } if (this.trashcan) { this.trashcan.dispose(); this.trashcan = null; } if (this.scrollbar) { this.scrollbar.dispose(); this.scrollbar = null; } if (this.zoomControls_) { this.zoomControls_.dispose(); this.zoomControls_ = null; } if (this.audioManager_) { this.audioManager_.dispose(); this.audioManager_ = null; } if (this.grid_) { this.grid_.dispose(); this.grid_ = null; } if (this.toolboxCategoryCallbacks_) { this.toolboxCategoryCallbacks_ = null; } if (this.flyoutButtonCallbacks_) { this.flyoutButtonCallbacks_ = null; } if (!this.options.parentWorkspace) { // Top-most workspace. Dispose of the div that the // svg is injected into (i.e. injectionDiv). goog.dom.removeNode(this.getParentSvg().parentNode); } if (this.resizeHandlerWrapper_) { Blockly.unbindEvent_(this.resizeHandlerWrapper_); this.resizeHandlerWrapper_ = null; } }; /** * Obtain a newly created block. * @param {?string} prototypeName Name of the language object containing * type-specific functions for this block. * @param {string=} opt_id Optional ID. Use this ID if provided, otherwise * create a new ID. * @return {!Blockly.BlockSvg} The created block. */ Blockly.WorkspaceSvg.prototype.newBlock = function(prototypeName, opt_id) { return new Blockly.BlockSvg(this, prototypeName, opt_id); }; /** * Add a trashcan. * @param {number} bottom Distance from workspace bottom to bottom of trashcan. * @return {number} Distance from workspace bottom to the top of trashcan. * @private */ Blockly.WorkspaceSvg.prototype.addTrashcan_ = function(bottom) { /** @type {Blockly.Trashcan} */ this.trashcan = new Blockly.Trashcan(this); var svgTrashcan = this.trashcan.createDom(); this.svgGroup_.insertBefore(svgTrashcan, this.svgBlockCanvas_); return this.trashcan.init(bottom); }; /** * Add zoom controls. * @param {number} bottom Distance from workspace bottom to bottom of controls. * @return {number} Distance from workspace bottom to the top of controls. * @private */ Blockly.WorkspaceSvg.prototype.addZoomControls_ = function(bottom) { /** @type {Blockly.ZoomControls} */ this.zoomControls_ = new Blockly.ZoomControls(this); var svgZoomControls = this.zoomControls_.createDom(); this.svgGroup_.appendChild(svgZoomControls); return this.zoomControls_.init(bottom); }; /** * Add a flyout element in an element with the given tag name. * @param {string} tagName What type of tag the flyout belongs in. * @return {!Element} The element containing the flyout dom. * @private */ Blockly.WorkspaceSvg.prototype.addFlyout_ = function(tagName) { var workspaceOptions = { disabledPatternId: this.options.disabledPatternId, parentWorkspace: this, RTL: this.RTL, oneBasedIndex: this.options.oneBasedIndex, horizontalLayout: this.horizontalLayout, toolboxPosition: this.options.toolboxPosition }; if (this.horizontalLayout) { this.flyout_ = new Blockly.HorizontalFlyout(workspaceOptions); } else { this.flyout_ = new Blockly.VerticalFlyout(workspaceOptions); } this.flyout_.autoClose = false; // Return the element so that callers can place it in their desired // spot in the dom. For exmaple, mutator flyouts do not go in the same place // as main workspace flyouts. return this.flyout_.createDom(tagName); }; /** * Getter for the flyout associated with this workspace. This flyout may be * owned by either the toolbox or the workspace, depending on toolbox * configuration. It will be null if there is no flyout. * @return {Blockly.Flyout} The flyout on this workspace. * @package */ Blockly.WorkspaceSvg.prototype.getFlyout = function() { if (this.flyout_) { return this.flyout_; } if (this.toolbox_) { return this.toolbox_.flyout_; } return null; }; /** * Update items that use screen coordinate calculations * because something has changed (e.g. scroll position, window size). * @private */ Blockly.WorkspaceSvg.prototype.updateScreenCalculations_ = function() { this.updateInverseScreenCTM(); this.recordDeleteAreas(); }; /** * If enabled, resize the parts of the workspace that change when the workspace * contents (e.g. block positions) change. This will also scroll the * workspace contents if needed. * @package */ Blockly.WorkspaceSvg.prototype.resizeContents = function() { if (!this.resizesEnabled_ || !this.rendered) { return; } if (this.scrollbar) { // TODO(picklesrus): Once rachel-fenichel's scrollbar refactoring // is complete, call the method that only resizes scrollbar // based on contents. this.scrollbar.resize(); } this.updateInverseScreenCTM(); }; /** * Resize and reposition all of the workspace chrome (toolbox, * trash, scrollbars etc.) * This should be called when something changes that * requires recalculating dimensions and positions of the * trash, zoom, toolbox, etc. (e.g. window resize). */ Blockly.WorkspaceSvg.prototype.resize = function() { if (this.toolbox_) { this.toolbox_.position(); } if (this.flyout_) { this.flyout_.position(); } if (this.trashcan) { this.trashcan.position(); } if (this.zoomControls_) { this.zoomControls_.position(); } if (this.scrollbar) { this.scrollbar.resize(); } this.updateScreenCalculations_(); }; /** * Resizes and repositions workspace chrome if the page has a new * scroll position. * @package */ Blockly.WorkspaceSvg.prototype.updateScreenCalculationsIfScrolled = function() { /* eslint-disable indent */ var currScroll = goog.dom.getDocumentScroll(); if (!goog.math.Coordinate.equals(this.lastRecordedPageScroll_, currScroll)) { this.lastRecordedPageScroll_ = currScroll; this.updateScreenCalculations_(); } }; /* eslint-enable indent */ /** * Get the SVG element that forms the drawing surface. * @return {!Element} SVG element. */ Blockly.WorkspaceSvg.prototype.getCanvas = function() { return this.svgBlockCanvas_; }; /** * Get the SVG element that forms the bubble surface. * @return {!SVGGElement} SVG element. */ Blockly.WorkspaceSvg.prototype.getBubbleCanvas = function() { return this.svgBubbleCanvas_; }; /** * Get the SVG element that contains this workspace. * @return {!Element} SVG element. */ Blockly.WorkspaceSvg.prototype.getParentSvg = function() { if (this.cachedParentSvg_) { return this.cachedParentSvg_; } var element = this.svgGroup_; while (element) { if (element.tagName == 'svg') { this.cachedParentSvg_ = element; return element; } element = element.parentNode; } return null; }; /** * Translate this workspace to new coordinates. * @param {number} x Horizontal translation. * @param {number} y Vertical translation. */ Blockly.WorkspaceSvg.prototype.translate = function(x, y) { if (this.useWorkspaceDragSurface_ && this.isDragSurfaceActive_) { this.workspaceDragSurface_.translateSurface(x,y); } else { var translation = 'translate(' + x + ',' + y + ') ' + 'scale(' + this.scale + ')'; this.svgBlockCanvas_.setAttribute('transform', translation); this.svgBubbleCanvas_.setAttribute('transform', translation); } // Now update the block drag surface if we're using one. if (this.blockDragSurface_) { this.blockDragSurface_.translateAndScaleGroup(x, y, this.scale); } }; /** * Called at the end of a workspace drag to take the contents * out of the drag surface and put them back into the workspace svg. * Does nothing if the workspace drag surface is not enabled. * @package */ Blockly.WorkspaceSvg.prototype.resetDragSurface = function() { // Don't do anything if we aren't using a drag surface. if (!this.useWorkspaceDragSurface_) { return; } this.isDragSurfaceActive_ = false; var trans = this.workspaceDragSurface_.getSurfaceTranslation(); this.workspaceDragSurface_.clearAndHide(this.svgGroup_); var translation = 'translate(' + trans.x + ',' + trans.y + ') ' + 'scale(' + this.scale + ')'; this.svgBlockCanvas_.setAttribute('transform', translation); this.svgBubbleCanvas_.setAttribute('transform', translation); }; /** * Called at the beginning of a workspace drag to move contents of * the workspace to the drag surface. * Does nothing if the drag surface is not enabled. * @package */ Blockly.WorkspaceSvg.prototype.setupDragSurface = function() { // Don't do anything if we aren't using a drag surface. if (!this.useWorkspaceDragSurface_) { return; } // This can happen if the user starts a drag, mouses up outside of the // document where the mouseup listener is registered (e.g. outside of an // iframe) and then moves the mouse back in the workspace. On mobile and ff, // we get the mouseup outside the frame. On chrome and safari desktop we do // not. if (this.isDragSurfaceActive_) { return; } this.isDragSurfaceActive_ = true; // Figure out where we want to put the canvas back. The order // in the is important because things are layered. var previousElement = this.svgBlockCanvas_.previousSibling; var width = this.getParentSvg().getAttribute("width"); var height = this.getParentSvg().getAttribute("height"); var coord = Blockly.utils.getRelativeXY(this.svgBlockCanvas_); this.workspaceDragSurface_.setContentsAndShow(this.svgBlockCanvas_, this.svgBubbleCanvas_, previousElement, width, height, this.scale); this.workspaceDragSurface_.translateSurface(coord.x, coord.y); }; /** * Returns the horizontal offset of the workspace. * Intended for LTR/RTL compatibility in XML. * @return {number} Width. */ Blockly.WorkspaceSvg.prototype.getWidth = function() { var metrics = this.getMetrics(); return metrics ? metrics.viewWidth / this.scale : 0; }; /** * Toggles the visibility of the workspace. * Currently only intended for main workspace. * @param {boolean} isVisible True if workspace should be visible. */ Blockly.WorkspaceSvg.prototype.setVisible = function(isVisible) { // Tell the scrollbar whether its container is visible so it can // tell when to hide itself. if (this.scrollbar) { this.scrollbar.setContainerVisible(isVisible); } // Tell the flyout whether its container is visible so it can // tell when to hide itself. if (this.getFlyout()) { this.getFlyout().setContainerVisible(isVisible); } this.getParentSvg().style.display = isVisible ? 'block' : 'none'; if (this.toolbox_) { // Currently does not support toolboxes in mutators. this.toolbox_.HtmlDiv.style.display = isVisible ? 'block' : 'none'; } if (isVisible) { this.render(); // The window may have changed size while the workspace was hidden. // Resize recalculates scrollbar position, delete areas, etc. this.resize(); } else { Blockly.hideChaff(true); Blockly.DropDownDiv.hideWithoutAnimation(); } }; /** * Render all blocks in workspace. */ Blockly.WorkspaceSvg.prototype.render = function() { // Generate list of all blocks. var blocks = this.getAllBlocks(); // Render each block. for (var i = blocks.length - 1; i >= 0; i--) { blocks[i].render(false); } }; /** * Was used back when block highlighting (for execution) and block selection * (for editing) were the same thing. * Any calls of this function can be deleted. * @deprecated October 2016 */ Blockly.WorkspaceSvg.prototype.traceOn = function() { console.warn('Deprecated call to traceOn, delete this.'); }; /** * Highlight or unhighlight a block in the workspace. Block highlighting is * often used to visually mark blocks currently being executed. * @param {?string} id ID of block to highlight/unhighlight, * or null for no block (used to unhighlight all blocks). * @param {boolean=} opt_state If undefined, highlight specified block and * automatically unhighlight all others. If true or false, manually * highlight/unhighlight the specified block. */ Blockly.WorkspaceSvg.prototype.highlightBlock = function(id, opt_state) { if (opt_state === undefined) { // Unhighlight all blocks. for (var i = 0, block; block = this.highlightedBlocks_[i]; i++) { block.setHighlighted(false); } this.highlightedBlocks_.length = 0; } // Highlight/unhighlight the specified block. var block = id ? this.getBlockById(id) : null; if (block) { var state = (opt_state === undefined) || opt_state; // Using Set here would be great, but at the cost of IE10 support. if (!state) { goog.array.remove(this.highlightedBlocks_, block); } else if (this.highlightedBlocks_.indexOf(block) == -1) { this.highlightedBlocks_.push(block); } block.setHighlighted(state); } }; /** * Glow/unglow a block in the workspace. * @param {?string} id ID of block to find. * @param {boolean} isGlowingBlock Whether to glow the block. */ Blockly.WorkspaceSvg.prototype.glowBlock = function(id, isGlowingBlock) { var block = null; if (id) { block = this.getBlockById(id); if (!block) { throw 'Tried to glow block that does not exist.'; } } block.setGlowBlock(isGlowingBlock); }; /** * Glow/unglow a stack in the workspace. * @param {?string} id ID of block which starts the stack. * @param {boolean} isGlowingStack Whether to glow the stack. */ Blockly.WorkspaceSvg.prototype.glowStack = function(id, isGlowingStack) { var block = null; if (id) { block = this.getBlockById(id); if (!block) { throw 'Tried to glow stack on block that does not exist.'; } } block.setGlowStack(isGlowingStack); }; /** * Visually report a value associated with a block. * In Scratch, appears as a pop-up next to the block when a reporter block is clicked. * @param {?string} id ID of block to report associated value. * @param {?string} value String value to visually report. */ Blockly.WorkspaceSvg.prototype.reportValue = function(id, value) { var block = this.getBlockById(id); if (!block) { throw 'Tried to report value on block that does not exist.'; } Blockly.DropDownDiv.hideWithoutAnimation(); Blockly.DropDownDiv.clearContent(); var contentDiv = Blockly.DropDownDiv.getContentDiv(); var valueReportBox = goog.dom.createElement('div'); valueReportBox.setAttribute('class', 'valueReportBox'); valueReportBox.innerHTML = Blockly.utils.encodeEntities(value); contentDiv.appendChild(valueReportBox); Blockly.DropDownDiv.setColour( Blockly.Colours.valueReportBackground, Blockly.Colours.valueReportBorder ); Blockly.DropDownDiv.showPositionedByBlock(this, block); }; /** * Paste the provided block onto the workspace. * @param {!Element} xmlBlock XML block element. */ Blockly.WorkspaceSvg.prototype.paste = function(xmlBlock) { if (!this.rendered) { return; } if (this.currentGesture_) { this.currentGesture_.cancel(); // Dragging while pasting? No. } Blockly.Events.disable(); try { var block = Blockly.Xml.domToBlock(xmlBlock, this); // Scratch-specific: Give shadow dom new IDs to prevent duplicating on paste Blockly.utils.changeObscuredShadowIds(block); // Move the duplicate to original position. var blockX = parseInt(xmlBlock.getAttribute('x'), 10); var blockY = parseInt(xmlBlock.getAttribute('y'), 10); if (!isNaN(blockX) && !isNaN(blockY)) { if (this.RTL) { blockX = -blockX; } // Offset block until not clobbering another block and not in connection // distance with neighbouring blocks. do { var collide = false; var allBlocks = this.getAllBlocks(); for (var i = 0, otherBlock; otherBlock = allBlocks[i]; i++) { var otherXY = otherBlock.getRelativeToSurfaceXY(); if (Math.abs(blockX - otherXY.x) <= 1 && Math.abs(blockY - otherXY.y) <= 1) { collide = true; break; } } if (!collide) { // Check for blocks in snap range to any of its connections. var connections = block.getConnections_(false); for (var i = 0, connection; connection = connections[i]; i++) { var neighbour = connection.closest(Blockly.SNAP_RADIUS, new goog.math.Coordinate(blockX, blockY)); if (neighbour.connection) { collide = true; break; } } } if (collide) { if (this.RTL) { blockX -= Blockly.SNAP_RADIUS; } else { blockX += Blockly.SNAP_RADIUS; } blockY += Blockly.SNAP_RADIUS * 2; } } while (collide); block.moveBy(blockX, blockY); } } finally { Blockly.Events.enable(); } if (Blockly.Events.isEnabled() && !block.isShadow()) { Blockly.Events.fire(new Blockly.Events.BlockCreate(block)); } block.select(); }; /** * Refresh the toolbox unless there's a drag in progress. * @private */ Blockly.WorkspaceSvg.prototype.refreshToolboxSelection_ = function() { if (this.toolbox_ && this.toolbox_.flyout_ && !this.currentGesture_ && !this.isBulkUpdating_) { this.toolbox_.refreshSelection(); } }; /** * Rename a variable by updating its name in the variable list. * @param {string} oldName Variable to rename. * @param {string} newName New variable name. * @package */ Blockly.WorkspaceSvg.prototype.renameVariable = function(oldName, newName) { Blockly.WorkspaceSvg.superClass_.renameVariable.call(this, oldName, newName); this.refreshToolboxSelection_(); }; /** * Rename a variable by updating its name in the variable map. Update the * flyout to show the renamed variable immediately. * @param {string} id Id of the variable to rename. * @param {string} newName New variable name. * @package */ Blockly.WorkspaceSvg.prototype.renameVariableById = function(id, newName) { Blockly.WorkspaceSvg.superClass_.renameVariableById.call(this, id, newName); this.refreshToolboxSelection_(); }; /** * Delete a variable by the passed in name. Update the flyout to show * immediately that the variable is deleted. * @param {string} name Name of variable to delete. * @package */ Blockly.WorkspaceSvg.prototype.deleteVariable = function(name) { Blockly.WorkspaceSvg.superClass_.deleteVariable.call(this, name); this.refreshToolboxSelection_(); }; /** * Delete a variable by the passed in id. Update the flyout to show * immediately that the variable is deleted. * @param {string} id Id of variable to delete. * @package */ Blockly.WorkspaceSvg.prototype.deleteVariableById = function(id) { Blockly.WorkspaceSvg.superClass_.deleteVariableById.call(this, id); this.refreshToolboxSelection_(); }; /** * Create a new variable with the given name. Update the flyout to show the new * variable immediately. * @param {string} name The new variable's name. * @param {string=} opt_type The type of the variable like 'int' or 'string'. * Does not need to be unique. Field_variable can filter variables based on * their type. This will default to '' which is a specific type. * @param {string=} opt_id The unique id of the variable. This will default to * a UUID. * @return {?Blockly.VariableModel} The newly created variable. * @package */ Blockly.WorkspaceSvg.prototype.createVariable = function(name, opt_type, opt_id) { var newVar = Blockly.WorkspaceSvg.superClass_.createVariable.call(this, name, opt_type, opt_id); this.refreshToolboxSelection_(); return newVar; }; /** * Make a list of all the delete areas for this workspace. */ Blockly.WorkspaceSvg.prototype.recordDeleteAreas = function() { if (this.trashcan) { this.deleteAreaTrash_ = this.trashcan.getClientRect(); } else { this.deleteAreaTrash_ = null; } if (this.flyout_) { this.deleteAreaToolbox_ = this.flyout_.getClientRect(); } else if (this.toolbox_) { this.deleteAreaToolbox_ = this.toolbox_.getClientRect(); } else { this.deleteAreaToolbox_ = null; } }; /** * Is the mouse event over a delete area (toolbox or non-closing flyout)? * @param {!Event} e Mouse move event. * @return {?number} Null if not over a delete area, or an enum representing * which delete area the event is over. */ Blockly.WorkspaceSvg.prototype.isDeleteArea = function(e) { var xy = new goog.math.Coordinate(e.clientX, e.clientY); if (this.deleteAreaTrash_ && this.deleteAreaTrash_.contains(xy)) { return Blockly.DELETE_AREA_TRASH; } if (this.deleteAreaToolbox_ && this.deleteAreaToolbox_.contains(xy)) { return Blockly.DELETE_AREA_TOOLBOX; } return Blockly.DELETE_AREA_NONE; }; /** * Handle a mouse-down on SVG drawing surface. * @param {!Event} e Mouse down event. * @private */ Blockly.WorkspaceSvg.prototype.onMouseDown_ = function(e) { var gesture = this.getGesture(e); if (gesture) { gesture.handleWsStart(e, this); } }; /** * Start tracking a drag of an object on this workspace. * @param {!Event} e Mouse down event. * @param {!goog.math.Coordinate} xy Starting location of object. */ Blockly.WorkspaceSvg.prototype.startDrag = function(e, xy) { // Record the starting offset between the bubble's location and the mouse. var point = Blockly.utils.mouseToSvg(e, this.getParentSvg(), this.getInverseScreenCTM()); // Fix scale of mouse event. point.x /= this.scale; point.y /= this.scale; this.dragDeltaXY_ = goog.math.Coordinate.difference(xy, point); }; /** * Track a drag of an object on this workspace. * @param {!Event} e Mouse move event. * @return {!goog.math.Coordinate} New location of object. */ Blockly.WorkspaceSvg.prototype.moveDrag = function(e) { var point = Blockly.utils.mouseToSvg(e, this.getParentSvg(), this.getInverseScreenCTM()); // Fix scale of mouse event. point.x /= this.scale; point.y /= this.scale; return goog.math.Coordinate.sum(this.dragDeltaXY_, point); }; /** * Is the user currently dragging a block or scrolling the flyout/workspace? * @return {boolean} True if currently dragging or scrolling. */ Blockly.WorkspaceSvg.prototype.isDragging = function() { return this.currentGesture_ && this.currentGesture_.isDragging(); }; /** * Is this workspace draggable and scrollable? * @return {boolean} True if this workspace may be dragged. */ Blockly.WorkspaceSvg.prototype.isDraggable = function() { return !!this.scrollbar; }; /** * Handle a mouse-wheel on SVG drawing surface. * @param {!Event} e Mouse wheel event. * @private */ Blockly.WorkspaceSvg.prototype.onMouseWheel_ = function(e) { // TODO: Remove gesture cancellation and compensate for coordinate skew during // zoom. if (this.currentGesture_) { this.currentGesture_.cancel(); } if (e.ctrlKey) { // The vertical scroll distance that corresponds to a click of a zoom button. var PIXELS_PER_ZOOM_STEP = 50; var delta = -e.deltaY / PIXELS_PER_ZOOM_STEP; var position = Blockly.utils.mouseToSvg(e, this.getParentSvg(), this.getInverseScreenCTM()); this.zoom(position.x, position.y, delta); } else { // This is a regular mouse wheel event - scroll the workspace // First hide the WidgetDiv without animation // (mouse scroll makes field out of place with div) Blockly.WidgetDiv.hide(true); Blockly.DropDownDiv.hideWithoutAnimation(); var x = this.scrollX - e.deltaX; var y = this.scrollY - e.deltaY; this.startDragMetrics = this.getMetrics(); this.scroll(x, y); } e.preventDefault(); }; /** * Calculate the bounding box for the blocks on the workspace. * Coordinate system: workspace coordinates. * * @return {Object} Contains the position and size of the bounding box * containing the blocks on the workspace. */ Blockly.WorkspaceSvg.prototype.getBlocksBoundingBox = function() { var topBlocks = this.getTopBlocks(false); // There are no blocks, return empty rectangle. if (!topBlocks.length) { return {x: 0, y: 0, width: 0, height: 0}; } // Initialize boundary using the first block. var boundary = topBlocks[0].getBoundingRectangle(); // Start at 1 since the 0th block was used for initialization for (var i = 1; i < topBlocks.length; i++) { var blockBoundary = topBlocks[i].getBoundingRectangle(); if (blockBoundary.topLeft.x < boundary.topLeft.x) { boundary.topLeft.x = blockBoundary.topLeft.x; } if (blockBoundary.bottomRight.x > boundary.bottomRight.x) { boundary.bottomRight.x = blockBoundary.bottomRight.x; } if (blockBoundary.topLeft.y < boundary.topLeft.y) { boundary.topLeft.y = blockBoundary.topLeft.y; } if (blockBoundary.bottomRight.y > boundary.bottomRight.y) { boundary.bottomRight.y = blockBoundary.bottomRight.y; } } return { x: boundary.topLeft.x, y: boundary.topLeft.y, width: boundary.bottomRight.x - boundary.topLeft.x, height: boundary.bottomRight.y - boundary.topLeft.y }; }; /** * Clean up the workspace by ordering all the blocks in a column. */ Blockly.WorkspaceSvg.prototype.cleanUp = function() { this.setResizesEnabled(false); Blockly.Events.setGroup(true); var topBlocks = this.getTopBlocks(true); var cursorY = 0; for (var i = 0, block; block = topBlocks[i]; i++) { var xy = block.getRelativeToSurfaceXY(); block.moveBy(-xy.x, cursorY - xy.y); block.snapToGrid(); cursorY = block.getRelativeToSurfaceXY().y + block.getHeightWidth().height + Blockly.BlockSvg.MIN_BLOCK_Y; } Blockly.Events.setGroup(false); this.setResizesEnabled(true); }; /** * Show the context menu for the workspace. * @param {!Event} e Mouse event. * @private */ Blockly.WorkspaceSvg.prototype.showContextMenu_ = function(e) { if (this.options.readOnly || this.isFlyout) { return; } var menuOptions = []; var topBlocks = this.getTopBlocks(true); var eventGroup = Blockly.utils.genUid(); var ws = this; // Options to undo/redo previous action. menuOptions.push(Blockly.ContextMenu.wsUndoOption(this)); menuOptions.push(Blockly.ContextMenu.wsRedoOption(this)); // Option to clean up blocks. if (this.scrollbar) { menuOptions.push( Blockly.ContextMenu.wsCleanupOption(this,topBlocks.length)); } if (this.options.collapse) { var hasCollapsedBlocks = false; var hasExpandedBlocks = false; for (var i = 0; i < topBlocks.length; i++) { var block = topBlocks[i]; while (block) { if (block.isCollapsed()) { hasCollapsedBlocks = true; } else { hasExpandedBlocks = true; } block = block.getNextBlock(); } } menuOptions.push(Blockly.ContextMenu.wsCollapseOption(hasExpandedBlocks, topBlocks)); menuOptions.push(Blockly.ContextMenu.wsExpandOption(hasCollapsedBlocks, topBlocks)); } // Option to delete all blocks. // Count the number of blocks that are deletable. var deleteList = Blockly.WorkspaceSvg.buildDeleteList_(topBlocks); // Scratch-specific: don't count shadow blocks in delete count var deleteCount = 0; for (var i = 0; i < deleteList.length; i++) { if (!deleteList[i].isShadow()) { deleteCount++; } } var DELAY = 10; function deleteNext() { Blockly.Events.setGroup(eventGroup); var block = deleteList.shift(); if (block) { if (block.workspace) { block.dispose(false, true); setTimeout(deleteNext, DELAY); } else { deleteNext(); } } Blockly.Events.setGroup(false); } var deleteOption = { text: deleteCount == 1 ? Blockly.Msg.DELETE_BLOCK : Blockly.Msg.DELETE_X_BLOCKS.replace('%1', String(deleteCount)), enabled: deleteCount > 0, callback: function() { if (ws.currentGesture_) { ws.currentGesture_.cancel(); } if (deleteList.length < 2 ) { deleteNext(); } else { Blockly.confirm(Blockly.Msg.DELETE_ALL_BLOCKS. replace('%1', String(deleteCount)), function(ok) { if (ok) { deleteNext(); } }); } } }; menuOptions.push(deleteOption); Blockly.ContextMenu.show(e, menuOptions, this.RTL); }; /** * Build a list of all deletable blocks that are reachable from the given * list of top blocks. * @param {!Array.<!Blockly.BlockSvg>} topBlocks The list of top blocks on the * workspace. * @return {!Array.<!Blockly.BlockSvg>} A list of deletable blocks on the * workspace. * @private */ Blockly.WorkspaceSvg.buildDeleteList_ = function(topBlocks) { var deleteList = []; function addDeletableBlocks(block) { if (block.isDeletable()) { deleteList = deleteList.concat(block.getDescendants()); } else { var children = block.getChildren(); for (var i = 0; i < children.length; i++) { addDeletableBlocks(children[i]); } } } for (var i = 0; i < topBlocks.length; i++) { addDeletableBlocks(topBlocks[i]); } return deleteList; }; /** * Modify the block tree on the existing toolbox. * @param {Node|string} tree DOM tree of blocks, or text representation of same. */ Blockly.WorkspaceSvg.prototype.updateToolbox = function(tree) { tree = Blockly.Options.parseToolboxTree(tree); if (!tree) { if (this.options.languageTree) { throw 'Can\'t nullify an existing toolbox.'; } return; // No change (null to null). } if (!this.options.languageTree) { throw 'Existing toolbox is null. Can\'t create new toolbox.'; } if (tree.getElementsByTagName('category').length) { if (!this.toolbox_) { throw 'Existing toolbox has no categories. Can\'t change mode.'; } this.options.languageTree = tree; this.toolbox_.populate_(tree); this.toolbox_.position(); } else { if (!this.flyout_) { throw 'Existing toolbox has categories. Can\'t change mode.'; } this.options.languageTree = tree; this.flyout_.show(tree.childNodes); } }; /** * Mark this workspace as the currently focused main workspace. */ Blockly.WorkspaceSvg.prototype.markFocused = function() { if (this.options.parentWorkspace) { this.options.parentWorkspace.markFocused(); } else { Blockly.mainWorkspace = this; // We call e.preventDefault in many event handlers which means we // need to explicitly grab focus (e.g from a textarea) because // the browser will not do it for us. How to do this is browser dependant. this.setBrowserFocus(); } }; /** * Set the workspace to have focus in the browser. * @private */ Blockly.WorkspaceSvg.prototype.setBrowserFocus = function() { // Blur whatever was focused since explcitly grabbing focus below does not // work in Edge. if (document.activeElement) { document.activeElement.blur(); } try { // Focus the workspace SVG - this is for Chrome and Firefox. this.getParentSvg().focus(); } catch (e) { // IE and Edge do not support focus on SVG elements. When that fails // above, get the injectionDiv (the workspace's parent) and focus that // instead. This doesn't work in Chrome. try { // In IE11, use setActive (which is IE only) so the page doesn't scroll // to the workspace gaining focus. this.getParentSvg().parentNode.setActive(); } catch (e) { // setActive support was discontinued in Edge so when that fails, call // focus instead. this.getParentSvg().parentNode.focus(); } } }; /** * Zooming the blocks centered in (x, y) coordinate with zooming in or out. * @param {number} x X coordinate of center. * @param {number} y Y coordinate of center. * @param {number} amount Amount of zooming * (negative zooms out and positive zooms in). */ Blockly.WorkspaceSvg.prototype.zoom = function(x, y, amount) { var speed = this.options.zoomOptions.scaleSpeed; var metrics = this.getMetrics(); var center = this.getParentSvg().createSVGPoint(); center.x = x; center.y = y; center = center.matrixTransform(this.getCanvas().getCTM().inverse()); x = center.x; y = center.y; var canvas = this.getCanvas(); // Scale factor. var scaleChange = Math.pow(speed, amount); // Clamp scale within valid range. var newScale = this.scale * scaleChange; if (newScale > this.options.zoomOptions.maxScale) { scaleChange = this.options.zoomOptions.maxScale / this.scale; } else if (newScale < this.options.zoomOptions.minScale) { scaleChange = this.options.zoomOptions.minScale / this.scale; } if (this.scale == newScale) { return; // No change in zoom. } if (this.scrollbar) { var matrix = canvas.getCTM() .translate(x * (1 - scaleChange), y * (1 - scaleChange)) .scale(scaleChange); // newScale and matrix.a should be identical (within a rounding error). // ScrollX and scrollY are in pixels. this.scrollX = matrix.e - metrics.absoluteLeft; this.scrollY = matrix.f - metrics.absoluteTop; } this.setScale(newScale); // Hide the WidgetDiv without animation (zoom makes field out of place with div) Blockly.WidgetDiv.hide(true); Blockly.DropDownDiv.hideWithoutAnimation(); }; /** * Zooming the blocks centered in the center of view with zooming in or out. * @param {number} type Type of zooming (-1 zooming out and 1 zooming in). */ Blockly.WorkspaceSvg.prototype.zoomCenter = function(type) { var metrics = this.getMetrics(); var x = metrics.viewWidth / 2; var y = metrics.viewHeight / 2; this.zoom(x, y, type); }; /** * Zoom the blocks to fit in the workspace if possible. */ Blockly.WorkspaceSvg.prototype.zoomToFit = function() { var metrics = this.getMetrics(); var blocksBox = this.getBlocksBoundingBox(); var blocksWidth = blocksBox.width; var blocksHeight = blocksBox.height; if (!blocksWidth) { return; // Prevents zooming to infinity. } var workspaceWidth = metrics.viewWidth; var workspaceHeight = metrics.viewHeight; if (this.flyout_) { workspaceWidth -= this.flyout_.width_; } if (!this.scrollbar) { // Origin point of 0,0 is fixed, blocks will not scroll to center. blocksWidth += metrics.contentLeft; blocksHeight += metrics.contentTop; } var ratioX = workspaceWidth / blocksWidth; var ratioY = workspaceHeight / blocksHeight; this.setScale(Math.min(ratioX, ratioY)); this.scrollCenter(); }; /** * Center the workspace. */ Blockly.WorkspaceSvg.prototype.scrollCenter = function() { if (!this.scrollbar) { // Can't center a non-scrolling workspace. return; } // Hide the WidgetDiv without animation (zoom makes field out of place with div) Blockly.WidgetDiv.hide(true); Blockly.DropDownDiv.hideWithoutAnimation(); Blockly.hideChaff(false); var metrics = this.getMetrics(); var x = (metrics.contentWidth - metrics.viewWidth) / 2; if (this.flyout_) { x -= this.flyout_.width_ / 2; } var y = (metrics.contentHeight - metrics.viewHeight) / 2; this.scrollbar.set(x, y); }; /** * Set the workspace's zoom factor. * @param {number} newScale Zoom factor. */ Blockly.WorkspaceSvg.prototype.setScale = function(newScale) { if (this.options.zoomOptions.maxScale && newScale > this.options.zoomOptions.maxScale) { newScale = this.options.zoomOptions.maxScale; } else if (this.options.zoomOptions.minScale && newScale < this.options.zoomOptions.minScale) { newScale = this.options.zoomOptions.minScale; } this.scale = newScale; if (this.grid_) { this.grid_.update(this.scale); } if (this.scrollbar) { this.scrollbar.resize(); } else { this.translate(this.scrollX, this.scrollY); } Blockly.hideChaff(false); if (this.flyout_) { // No toolbox, resize flyout. this.flyout_.reflow(); } }; /** * Scroll the workspace by a specified amount, keeping in the bounds. * Be sure to set this.startDragMetrics with cached metrics before calling. * @param {number} x Target X to scroll to * @param {number} y Target Y to scroll to */ Blockly.WorkspaceSvg.prototype.scroll = function(x, y) { var metrics = this.startDragMetrics; // Cached values x = Math.min(x, -metrics.contentLeft); y = Math.min(y, -metrics.contentTop); x = Math.max(x, metrics.viewWidth - metrics.contentLeft - metrics.contentWidth); y = Math.max(y, metrics.viewHeight - metrics.contentTop - metrics.contentHeight); // When the workspace starts scrolling, hide the WidgetDiv without animation. // This is to prevent a dispoal animation from happening in the wrong location. Blockly.WidgetDiv.hide(true); Blockly.DropDownDiv.hideWithoutAnimation(); // Move the scrollbars and the page will scroll automatically. this.scrollbar.set(-x - metrics.contentLeft, -y - metrics.contentTop); }; /** * Update the workspace's stack glow radius to be proportional to scale. * Ensures that stack glows always appear to be a fixed size. */ Blockly.WorkspaceSvg.prototype.updateStackGlowScale_ = function() { // No such def in the flyout workspace. if (this.options.stackGlowBlur) { this.options.stackGlowBlur.setAttribute('stdDeviation', Blockly.STACK_GLOW_RADIUS / this.scale ); } }; /** * Get the dimensions of the given workspace component, in pixels. * @param {Blockly.Toolbox|Blockly.Flyout} elem The element to get the * dimensions of, or null. It should be a toolbox or flyout, and should * implement getWidth() and getHeight(). * @return {!Object} An object containing width and height attributes, which * will both be zero if elem did not exist. * @private */ Blockly.WorkspaceSvg.getDimensionsPx_ = function(elem) { var width = 0; var height = 0; if (elem) { width = elem.getWidth(); height = elem.getHeight(); } return { width: width, height: height }; }; /** * Get the content dimensions of the given workspace, taking into account * whether or not it is scrollable and what size the workspace div is on screen. * @param {!Blockly.WorkspaceSvg} ws The workspace to measure. * @param {!Object} svgSize An object containing height and width attributes in * CSS pixels. Together they specify the size of the visible workspace, not * including areas covered up by the toolbox. * @return {!Object} The dimensions of the contents of the given workspace, as * an object containing at least * - height and width in pixels * - left and top in pixels relative to the workspace origin. * @private */ Blockly.WorkspaceSvg.getContentDimensions_ = function(ws, svgSize) { if (ws.scrollbar) { return Blockly.WorkspaceSvg.getContentDimensionsBounded_(ws, svgSize); } else { return Blockly.WorkspaceSvg.getContentDimensionsExact_(ws); } }; /** * Get the bounding box for all workspace contents, in pixels. * @param {!Blockly.WorkspaceSvg} ws The workspace to inspect. * @return {!Object} The dimensions of the contents of the given workspace, as * an object containing * - height and width in pixels * - left, right, top and bottom in pixels relative to the workspace origin. * @private */ Blockly.WorkspaceSvg.getContentDimensionsExact_ = function(ws) { // Block bounding box is in workspace coordinates. var blockBox = ws.getBlocksBoundingBox(); var scale = ws.scale; // Convert to pixels. var width = blockBox.width * scale; var height = blockBox.height * scale; var left = blockBox.x * scale; var top = blockBox.y * scale; return { left: left, top: top, right: left + width, bottom: top + height, width: width, height: height }; }; /** * Calculate the size of a scrollable workspace, which should include room for a * half screen border around the workspace contents. * @param {!Blockly.WorkspaceSvg} ws The workspace to measure. * @param {!Object} svgSize An object containing height and width attributes in * CSS pixels. Together they specify the size of the visible workspace, not * including areas covered up by the toolbox. * @return {!Object} The dimensions of the contents of the given workspace, as * an object containing * - height and width in pixels * - left and top in pixels relative to the workspace origin. * @private */ Blockly.WorkspaceSvg.getContentDimensionsBounded_ = function(ws, svgSize) { var content = Blockly.WorkspaceSvg.getContentDimensionsExact_(ws); // View height and width are both in pixels, and are the same as the svg size. var viewWidth = svgSize.width; var viewHeight = svgSize.height; var halfWidth = viewWidth / 2; var halfHeight = viewHeight / 2; // Add a border around the content that is at least half a screenful wide. // Ensure border is wide enough that blocks can scroll over entire screen. var left = Math.min(content.left - halfWidth, content.right - viewWidth); var right = Math.max(content.right + halfWidth, content.left + viewWidth); var top = Math.min(content.top - halfHeight, content.bottom - viewHeight); var bottom = Math.max(content.bottom + halfHeight, content.top + viewHeight); var dimensions = { left: left, top: top, height: bottom - top, width: right - left }; return dimensions; }; /** * Return an object with all the metrics required to size scrollbars for a * top level workspace. The following properties are computed: * Coordinate system: pixel coordinates. * .viewHeight: Height of the visible rectangle, * .viewWidth: Width of the visible rectangle, * .contentHeight: Height of the contents, * .contentWidth: Width of the content, * .viewTop: Offset of top edge of visible rectangle from parent, * .viewLeft: Offset of left edge of visible rectangle from parent, * .contentTop: Offset of the top-most content from the y=0 coordinate, * .contentLeft: Offset of the left-most content from the x=0 coordinate. * .absoluteTop: Top-edge of view. * .absoluteLeft: Left-edge of view. * .toolboxWidth: Width of toolbox, if it exists. Otherwise zero. * .toolboxHeight: Height of toolbox, if it exists. Otherwise zero. * .flyoutWidth: Width of the flyout if it is always open. Otherwise zero. * .flyoutHeight: Height of flyout if it is always open. Otherwise zero. * .toolboxPosition: Top, bottom, left or right. * @return {!Object} Contains size and position metrics of a top level * workspace. * @private * @this Blockly.WorkspaceSvg */ Blockly.WorkspaceSvg.getTopLevelWorkspaceMetrics_ = function() { var toolboxDimensions = Blockly.WorkspaceSvg.getDimensionsPx_(this.toolbox_); var flyoutDimensions = Blockly.WorkspaceSvg.getDimensionsPx_(this.flyout_); // Contains height and width in CSS pixels. // svgSize is equivalent to the size of the injectionDiv at this point. var svgSize = Blockly.svgSize(this.getParentSvg()); if (this.toolbox_) { if (this.toolboxPosition == Blockly.TOOLBOX_AT_TOP || this.toolboxPosition == Blockly.TOOLBOX_AT_BOTTOM) { svgSize.height -= toolboxDimensions.height; } else if (this.toolboxPosition == Blockly.TOOLBOX_AT_LEFT || this.toolboxPosition == Blockly.TOOLBOX_AT_RIGHT) { svgSize.width -= toolboxDimensions.width; } } // svgSize is now the space taken up by the Blockly workspace, not including // the toolbox. var contentDimensions = Blockly.WorkspaceSvg.getContentDimensions_(this, svgSize); var absoluteLeft = 0; if (this.toolbox_ && this.toolboxPosition == Blockly.TOOLBOX_AT_LEFT) { absoluteLeft = toolboxDimensions.width; } var absoluteTop = 0; if (this.toolbox_ && this.toolboxPosition == Blockly.TOOLBOX_AT_TOP) { absoluteTop = toolboxDimensions.height; } var metrics = { contentHeight: contentDimensions.height, contentWidth: contentDimensions.width, contentTop: contentDimensions.top, contentLeft: contentDimensions.left, viewHeight: svgSize.height, viewWidth: svgSize.width, viewTop: -this.scrollY, // Must be in pixels, somehow. viewLeft: -this.scrollX, // Must be in pixels, somehow. absoluteTop: absoluteTop, absoluteLeft: absoluteLeft, toolboxWidth: toolboxDimensions.width, toolboxHeight: toolboxDimensions.height, flyoutWidth: flyoutDimensions.width, flyoutHeight: flyoutDimensions.height, toolboxPosition: this.toolboxPosition }; return metrics; }; /** * Sets the X/Y translations of a top level workspace to match the scrollbars. * @param {!Object} xyRatio Contains an x and/or y property which is a float * between 0 and 1 specifying the degree of scrolling. * @private * @this Blockly.WorkspaceSvg */ Blockly.WorkspaceSvg.setTopLevelWorkspaceMetrics_ = function(xyRatio) { if (!this.scrollbar) { throw 'Attempt to set top level workspace scroll without scrollbars.'; } var metrics = this.getMetrics(); if (goog.isNumber(xyRatio.x)) { this.scrollX = -metrics.contentWidth * xyRatio.x - metrics.contentLeft; } if (goog.isNumber(xyRatio.y)) { this.scrollY = -metrics.contentHeight * xyRatio.y - metrics.contentTop; } var x = this.scrollX + metrics.absoluteLeft; var y = this.scrollY + metrics.absoluteTop; this.translate(x, y); if (this.grid_) { this.grid_.moveTo(x, y); } }; /** * Update whether this workspace has resizes enabled. * If enabled, workspace will resize when appropriate. * If disabled, workspace will not resize until re-enabled. * Use to avoid resizing during a batch operation, for performance. * @param {boolean} enabled Whether resizes should be enabled. */ Blockly.WorkspaceSvg.prototype.setResizesEnabled = function(enabled) { var reenabled = (!this.resizesEnabled_ && enabled); this.resizesEnabled_ = enabled; if (reenabled) { // Newly enabled. Trigger a resize. this.resizeContents(); } }; /** * Set whether this workspace is currently doing a bulk update. * A bulk update pauses workspace resizing but also pauses other expensive * operations, such as refreshing the toolbox as variables are added and * removed. * @param {boolean} enabled True if a bulk update is starting, false if a bulk * update is ending. * @package */ Blockly.WorkspaceSvg.prototype.setBulkUpdate = function(enabled) { // This will trigger a resize if necessary. this.setResizesEnabled(!enabled); // Disable resizes when enabling bulk update var stoppedUpdating = (this.isBulkUpdating_ && !enabled); this.isBulkUpdating_ = enabled; if (stoppedUpdating) { // Refresh the toolbox. if (this.toolbox_) { this.toolbox_.refreshSelection(); } } }; /** * Dispose of all blocks in workspace, with an optimization to prevent resizes. */ Blockly.WorkspaceSvg.prototype.clear = function() { this.setBulkUpdate(true); Blockly.WorkspaceSvg.superClass_.clear.call(this); this.setBulkUpdate(false); }; /** * Register a callback function associated with a given key, for clicks on * buttons and labels in the flyout. * For instance, a button specified by the XML * <button text="create variable" callbackKey="CREATE_VARIABLE"></button> * should be matched by a call to * registerButtonCallback("CREATE_VARIABLE", yourCallbackFunction). * @param {string} key The name to use to look up this function. * @param {function(!Blockly.FlyoutButton)} func The function to call when the * given button is clicked. */ Blockly.WorkspaceSvg.prototype.registerButtonCallback = function(key, func) { goog.asserts.assert(goog.isFunction(func), 'Button callbacks must be functions.'); this.flyoutButtonCallbacks_[key] = func; }; /** * Get the callback function associated with a given key, for clicks on buttons * and labels in the flyout. * @param {string} key The name to use to look up the function. * @return {?function(!Blockly.FlyoutButton)} The function corresponding to the * given key for this workspace; null if no callback is registered. */ Blockly.WorkspaceSvg.prototype.getButtonCallback = function(key) { var result = this.flyoutButtonCallbacks_[key]; return result ? result : null; }; /** * Remove a callback for a click on a button in the flyout. * @param {string} key The name associated with the callback function. */ Blockly.WorkspaceSvg.prototype.removeButtonCallback = function(key) { this.flyoutButtonCallbacks_[key] = null; }; /** * Register a callback function associated with a given key, for populating * custom toolbox categories in this workspace. See the variable and procedure * categories as an example. * @param {string} key The name to use to look up this function. * @param {function(!Blockly.Workspace):!Array<!Element>} func The function to * call when the given toolbox category is opened. */ Blockly.WorkspaceSvg.prototype.registerToolboxCategoryCallback = function(key, func) { goog.asserts.assert(goog.isFunction(func), 'Toolbox category callbacks must be functions.'); this.toolboxCategoryCallbacks_[key] = func; }; /** * Get the callback function associated with a given key, for populating * custom toolbox categories in this workspace. * @param {string} key The name to use to look up the function. * @return {?function(!Blockly.Workspace):!Array<!Element>} The function * corresponding to the given key for this workspace, or null if no function * is registered. */ Blockly.WorkspaceSvg.prototype.getToolboxCategoryCallback = function(key) { var result = this.toolboxCategoryCallbacks_[key]; return result ? result : null; }; /** * Remove a callback for a click on a custom category's name in the toolbox. * @param {string} key The name associated with the callback function. */ Blockly.WorkspaceSvg.prototype.removeToolboxCategoryCallback = function(key) { this.toolboxCategoryCallbacks_[key] = null; }; /** * Look up the gesture that is tracking this touch stream on this workspace. * May create a new gesture. * @param {!Event} e Mouse event or touch event * @return {Blockly.Gesture} The gesture that is tracking this touch stream, * or null if no valid gesture exists. * @package */ Blockly.WorkspaceSvg.prototype.getGesture = function(e) { var isStart = (e.type == 'mousedown' || e.type == 'touchstart'); var gesture = this.currentGesture_; if (gesture) { if (isStart && gesture.hasStarted()) { console.warn('tried to start the same gesture twice'); // That's funny. We must have missed a mouse up. // Cancel it, rather than try to retrieve all of the state we need. gesture.cancel(); return null; } return gesture; } // No gesture existed on this workspace, but this looks like the start of a // new gesture. if (isStart) { this.currentGesture_ = new Blockly.Gesture(e, this); return this.currentGesture_; } // No gesture existed and this event couldn't be the start of a new gesture. return null; }; /** * Clear the reference to the current gesture. * @package */ Blockly.WorkspaceSvg.prototype.clearGesture = function() { this.currentGesture_ = null; }; /** * Cancel the current gesture, if one exists. * @package */ Blockly.WorkspaceSvg.prototype.cancelCurrentGesture = function() { if (this.currentGesture_) { this.currentGesture_.cancel(); } }; /** * Don't even think about using this function before talking to rachel-fenichel. * * Force a drag to start without clicking and dragging the block itself. Used * to attach duplicated blocks to the mouse pointer. * @param {!Object} fakeEvent An object with the properties needed to start a * drag, including clientX and clientY. * @param {!Blockly.BlockSvg} block The block to start dragging. * @package */ Blockly.WorkspaceSvg.prototype.startDragWithFakeEvent = function(fakeEvent, block) { Blockly.Touch.clearTouchIdentifier(); Blockly.Touch.checkTouchIdentifier(fakeEvent); var gesture = block.workspace.getGesture(fakeEvent); gesture.forceStartBlockDrag(fakeEvent, block); }; /** * Get the audio manager for this workspace. * @return {Blockly.WorkspaceAudio} The audio manager for this workspace. */ Blockly.WorkspaceSvg.prototype.getAudioManager = function() { return this.audioManager_; }; /** * Get the grid object for this workspace, or null if there is none. * @return {Blockly.Grid} The grid object for this workspace. * @package */ Blockly.WorkspaceSvg.prototype.getGrid = function() { return this.grid_; }; // Export symbols that would otherwise be renamed by Closure compiler. Blockly.WorkspaceSvg.prototype['setVisible'] = Blockly.WorkspaceSvg.prototype.setVisible;
1
8,812
Do you still need to call the superclass `createVariable` if you've already determined that the variable exists?
LLK-scratch-blocks
js
@@ -281,7 +281,10 @@ type EachByPackResult struct { } // EachByPack returns a channel that yields all blobs known to the index -// grouped by packID but ignoring blobs with a packID in packPlacklist. +// grouped by packID but ignoring blobs with a packID in packPlacklist for +// finalized indexes. +// This filtering is used when rebuilding the index where we need to ignore packs +// from the finalized index which have been re-read into a non-finalized index. // When the context is cancelled, the background goroutine // terminates. This blocks any modification of the index. func (idx *Index) EachByPack(ctx context.Context, packBlacklist restic.IDSet) <-chan EachByPackResult {
1
package repository import ( "context" "encoding/json" "io" "sync" "time" "github.com/restic/restic/internal/errors" "github.com/restic/restic/internal/restic" "github.com/restic/restic/internal/debug" ) // In large repositories, millions of blobs are stored in the repository // and restic needs to store an index entry for each blob in memory for // most operations. // Hence the index data structure defined here is one of the main contributions // to the total memory requirements of restic. // // We store the index entries in indexMaps. In these maps, entries take 56 // bytes each, plus 8/4 = 2 bytes of unused pointers on average, not counting // malloc and header struct overhead and ignoring duplicates (those are only // present in edge cases and are also removed by prune runs). // // In the index entries, we need to reference the packID. As one pack may // contain many blobs the packIDs are saved in a separate array and only the index // within this array is saved in the indexEntry // // We assume on average a minimum of 8 blobs per pack; BP=8. // (Note that for large files there should be 3 blobs per pack as the average chunk // size is 1.5 MB and the minimum pack size is 4 MB) // // We have the following sizes: // indexEntry: 56 bytes (on amd64) // each packID: 32 bytes // // To save N index entries, we therefore need: // N * (56 + 2) bytes + N * 32 bytes / BP = N * 62 bytes, // i.e., fewer than 64 bytes per blob in an index. // Index holds lookup tables for id -> pack. type Index struct { m sync.Mutex byType [restic.NumBlobTypes]indexMap packs restic.IDs treePacks restic.IDs // only used by Store, StorePacks does not check for already saved packIDs packIDToIndex map[restic.ID]int final bool // set to true for all indexes read from the backend ("finalized") ids restic.IDs // set to the IDs of the contained finalized indexes supersedes restic.IDs created time.Time } // NewIndex returns a new index. func NewIndex() *Index { return &Index{ packIDToIndex: make(map[restic.ID]int), created: time.Now(), } } // addToPacks saves the given pack ID and return the index. // This procedere allows to use pack IDs which can be easily garbage collected after. func (idx *Index) addToPacks(id restic.ID) int { idx.packs = append(idx.packs, id) return len(idx.packs) - 1 } const maxuint32 = 1<<32 - 1 func (idx *Index) store(packIndex int, blob restic.Blob) { // assert that offset and length fit into uint32! if blob.Offset > maxuint32 || blob.Length > maxuint32 { panic("offset or length does not fit in uint32. You have packs > 4GB!") } m := &idx.byType[blob.Type] m.add(blob.ID, packIndex, uint32(blob.Offset), uint32(blob.Length)) } // Final returns true iff the index is already written to the repository, it is // finalized. func (idx *Index) Final() bool { idx.m.Lock() defer idx.m.Unlock() return idx.final } const ( indexMaxBlobs = 50000 indexMaxAge = 10 * time.Minute ) // IndexFull returns true iff the index is "full enough" to be saved as a preliminary index. var IndexFull = func(idx *Index) bool { idx.m.Lock() defer idx.m.Unlock() debug.Log("checking whether index %p is full", idx) var blobs uint for typ := range idx.byType { blobs += idx.byType[typ].len() } age := time.Since(idx.created) switch { case age >= indexMaxAge: debug.Log("index %p is old enough", idx, age) return true case blobs >= indexMaxBlobs: debug.Log("index %p has %d blobs", idx, blobs) return true } debug.Log("index %p only has %d blobs and is too young (%v)", idx, blobs, age) return false } // Store remembers the id and pack in the index. func (idx *Index) Store(blob restic.PackedBlob) { idx.m.Lock() defer idx.m.Unlock() if idx.final { panic("store new item in finalized index") } debug.Log("%v", blob) // get packIndex and save if new packID packIndex, ok := idx.packIDToIndex[blob.PackID] if !ok { packIndex = idx.addToPacks(blob.PackID) idx.packIDToIndex[blob.PackID] = packIndex } idx.store(packIndex, blob.Blob) } // StorePack remembers the ids of all blobs of a given pack // in the index func (idx *Index) StorePack(id restic.ID, blobs []restic.Blob) { idx.m.Lock() defer idx.m.Unlock() if idx.final { panic("store new item in finalized index") } debug.Log("%v", blobs) packIndex := idx.addToPacks(id) for _, blob := range blobs { idx.store(packIndex, blob) } } func (idx *Index) toPackedBlob(e *indexEntry, typ restic.BlobType) restic.PackedBlob { return restic.PackedBlob{ Blob: restic.Blob{ ID: e.id, Type: typ, Length: uint(e.length), Offset: uint(e.offset), }, PackID: idx.packs[e.packIndex], } } // Lookup queries the index for the blob ID and returns all entries including // duplicates. Adds found entries to blobs and returns the result. func (idx *Index) Lookup(id restic.ID, tpe restic.BlobType, blobs []restic.PackedBlob) []restic.PackedBlob { idx.m.Lock() defer idx.m.Unlock() idx.byType[tpe].foreachWithID(id, func(e *indexEntry) { blobs = append(blobs, idx.toPackedBlob(e, tpe)) }) return blobs } // ListPack returns a list of blobs contained in a pack. func (idx *Index) ListPack(id restic.ID) (list []restic.PackedBlob) { idx.m.Lock() defer idx.m.Unlock() for typ := range idx.byType { m := &idx.byType[typ] m.foreach(func(e *indexEntry) bool { if idx.packs[e.packIndex] == id { list = append(list, idx.toPackedBlob(e, restic.BlobType(typ))) } return true }) } return list } // Has returns true iff the id is listed in the index. func (idx *Index) Has(id restic.ID, tpe restic.BlobType) bool { idx.m.Lock() defer idx.m.Unlock() return idx.byType[tpe].get(id) != nil } // LookupSize returns the length of the plaintext content of the blob with the // given id. func (idx *Index) LookupSize(id restic.ID, tpe restic.BlobType) (plaintextLength uint, found bool) { idx.m.Lock() defer idx.m.Unlock() e := idx.byType[tpe].get(id) if e == nil { return 0, false } return uint(restic.PlaintextLength(int(e.length))), true } // Supersedes returns the list of indexes this index supersedes, if any. func (idx *Index) Supersedes() restic.IDs { return idx.supersedes } // AddToSupersedes adds the ids to the list of indexes superseded by this // index. If the index has already been finalized, an error is returned. func (idx *Index) AddToSupersedes(ids ...restic.ID) error { idx.m.Lock() defer idx.m.Unlock() if idx.final { return errors.New("index already finalized") } idx.supersedes = append(idx.supersedes, ids...) return nil } // Each returns a channel that yields all blobs known to the index. When the // context is cancelled, the background goroutine terminates. This blocks any // modification of the index. func (idx *Index) Each(ctx context.Context) <-chan restic.PackedBlob { idx.m.Lock() ch := make(chan restic.PackedBlob) go func() { defer idx.m.Unlock() defer func() { close(ch) }() for typ := range idx.byType { m := &idx.byType[typ] m.foreach(func(e *indexEntry) bool { select { case <-ctx.Done(): return false case ch <- idx.toPackedBlob(e, restic.BlobType(typ)): return true } }) } }() return ch } type EachByPackResult struct { packID restic.ID blobs []restic.Blob } // EachByPack returns a channel that yields all blobs known to the index // grouped by packID but ignoring blobs with a packID in packPlacklist. // When the context is cancelled, the background goroutine // terminates. This blocks any modification of the index. func (idx *Index) EachByPack(ctx context.Context, packBlacklist restic.IDSet) <-chan EachByPackResult { idx.m.Lock() ch := make(chan EachByPackResult) go func() { defer idx.m.Unlock() defer func() { close(ch) }() for typ := range idx.byType { byPack := make(map[restic.ID][]*indexEntry) m := &idx.byType[typ] m.foreach(func(e *indexEntry) bool { packID := idx.packs[e.packIndex] if !packBlacklist.Has(packID) { byPack[packID] = append(byPack[packID], e) } return true }) for packID, pack := range byPack { var result EachByPackResult result.packID = packID for _, e := range pack { result.blobs = append(result.blobs, idx.toPackedBlob(e, restic.BlobType(typ)).Blob) } select { case <-ctx.Done(): return case ch <- result: } } } }() return ch } // Packs returns all packs in this index func (idx *Index) Packs() restic.IDSet { idx.m.Lock() defer idx.m.Unlock() packs := restic.NewIDSet() for _, packID := range idx.packs { packs.Insert(packID) } return packs } // Count returns the number of blobs of type t in the index. func (idx *Index) Count(t restic.BlobType) (n uint) { debug.Log("counting blobs of type %v", t) idx.m.Lock() defer idx.m.Unlock() return idx.byType[t].len() } type packJSON struct { ID restic.ID `json:"id"` Blobs []blobJSON `json:"blobs"` } type blobJSON struct { ID restic.ID `json:"id"` Type restic.BlobType `json:"type"` Offset uint `json:"offset"` Length uint `json:"length"` } // generatePackList returns a list of packs. func (idx *Index) generatePackList() ([]*packJSON, error) { list := []*packJSON{} packs := make(map[restic.ID]*packJSON) for typ := range idx.byType { m := &idx.byType[typ] m.foreach(func(e *indexEntry) bool { packID := idx.packs[e.packIndex] if packID.IsNull() { panic("null pack id") } debug.Log("handle blob %v", e.id) // see if pack is already in map p, ok := packs[packID] if !ok { // else create new pack p = &packJSON{ID: packID} // and append it to the list and map list = append(list, p) packs[p.ID] = p } // add blob p.Blobs = append(p.Blobs, blobJSON{ ID: e.id, Type: restic.BlobType(typ), Offset: uint(e.offset), Length: uint(e.length), }) return true }) } debug.Log("done") return list, nil } type jsonIndex struct { Supersedes restic.IDs `json:"supersedes,omitempty"` Packs []*packJSON `json:"packs"` } // Encode writes the JSON serialization of the index to the writer w. func (idx *Index) Encode(w io.Writer) error { debug.Log("encoding index") idx.m.Lock() defer idx.m.Unlock() return idx.encode(w) } // encode writes the JSON serialization of the index to the writer w. func (idx *Index) encode(w io.Writer) error { debug.Log("encoding index") list, err := idx.generatePackList() if err != nil { return err } enc := json.NewEncoder(w) idxJSON := jsonIndex{ Supersedes: idx.supersedes, Packs: list, } return enc.Encode(idxJSON) } // Finalize sets the index to final. func (idx *Index) Finalize() { debug.Log("finalizing index") idx.m.Lock() defer idx.m.Unlock() idx.final = true // clear packIDToIndex as no more elements will be added idx.packIDToIndex = nil } // IDs returns the IDs of the index, if available. If the index is not yet // finalized, an error is returned. func (idx *Index) IDs() (restic.IDs, error) { idx.m.Lock() defer idx.m.Unlock() if !idx.final { return nil, errors.New("index not finalized") } return idx.ids, nil } // SetID sets the ID the index has been written to. This requires that // Finalize() has been called before, otherwise an error is returned. func (idx *Index) SetID(id restic.ID) error { idx.m.Lock() defer idx.m.Unlock() if !idx.final { return errors.New("index is not final") } if len(idx.ids) > 0 { return errors.New("ID already set") } debug.Log("ID set to %v", id) idx.ids = append(idx.ids, id) return nil } // Dump writes the pretty-printed JSON representation of the index to w. func (idx *Index) Dump(w io.Writer) error { debug.Log("dumping index") idx.m.Lock() defer idx.m.Unlock() list, err := idx.generatePackList() if err != nil { return err } outer := jsonIndex{ Supersedes: idx.Supersedes(), Packs: list, } buf, err := json.MarshalIndent(outer, "", " ") if err != nil { return err } _, err = w.Write(append(buf, '\n')) if err != nil { return errors.Wrap(err, "Write") } debug.Log("done") return nil } // TreePacks returns a list of packs that contain only tree blobs. func (idx *Index) TreePacks() restic.IDs { return idx.treePacks } // merge() merges indexes, i.e. idx.merge(idx2) merges the contents of idx2 into idx. // During merging exact duplicates are removed; idx2 is not changed by this method. func (idx *Index) merge(idx2 *Index) error { idx.m.Lock() defer idx.m.Unlock() idx2.m.Lock() defer idx2.m.Unlock() if !idx2.final { return errors.New("index to merge is not final") } packlen := len(idx.packs) // first append packs as they might be accessed when looking for duplicates below idx.packs = append(idx.packs, idx2.packs...) // copy all index entries of idx2 to idx for typ := range idx2.byType { m2 := &idx2.byType[typ] m := &idx.byType[typ] // helper func to test if identical entry is contained in idx hasIdenticalEntry := func(e2 *indexEntry) (found bool) { m.foreachWithID(e2.id, func(e *indexEntry) { b := idx.toPackedBlob(e, restic.BlobType(typ)) b2 := idx2.toPackedBlob(e2, restic.BlobType(typ)) if b.Length == b2.Length && b.Offset == b2.Offset && b.PackID == b2.PackID { found = true } }) return found } m2.foreach(func(e2 *indexEntry) bool { if !hasIdenticalEntry(e2) { // packIndex needs to be changed as idx2.pack was appended to idx.pack, see above m.add(e2.id, e2.packIndex+packlen, e2.offset, e2.length) } return true }) } idx.treePacks = append(idx.treePacks, idx2.treePacks...) idx.ids = append(idx.ids, idx2.ids...) idx.supersedes = append(idx.supersedes, idx2.supersedes...) return nil } // isErrOldIndex returns true if the error may be caused by an old index // format. func isErrOldIndex(err error) bool { e, ok := err.(*json.UnmarshalTypeError) return ok && e.Value == "array" } // DecodeIndex unserializes an index from buf. func DecodeIndex(buf []byte, id restic.ID) (idx *Index, oldFormat bool, err error) { debug.Log("Start decoding index") idxJSON := &jsonIndex{} err = json.Unmarshal(buf, idxJSON) if err != nil { debug.Log("Error %v", err) if isErrOldIndex(err) { debug.Log("index is probably old format, trying that") idx, err = decodeOldIndex(buf) return idx, err == nil, err } return nil, false, errors.Wrap(err, "DecodeIndex") } idx = NewIndex() for _, pack := range idxJSON.Packs { var data, tree bool packID := idx.addToPacks(pack.ID) for _, blob := range pack.Blobs { idx.store(packID, restic.Blob{ Type: blob.Type, ID: blob.ID, Offset: blob.Offset, Length: blob.Length, }) switch blob.Type { case restic.DataBlob: data = true case restic.TreeBlob: tree = true } } if !data && tree { idx.treePacks = append(idx.treePacks, pack.ID) } } idx.supersedes = idxJSON.Supersedes idx.ids = append(idx.ids, id) idx.final = true debug.Log("done") return idx, false, nil } // DecodeOldIndex loads and unserializes an index in the old format from rd. func decodeOldIndex(buf []byte) (idx *Index, err error) { debug.Log("Start decoding old index") list := []*packJSON{} err = json.Unmarshal(buf, &list) if err != nil { debug.Log("Error %#v", err) return nil, errors.Wrap(err, "Decode") } idx = NewIndex() for _, pack := range list { var data, tree bool packID := idx.addToPacks(pack.ID) for _, blob := range pack.Blobs { idx.store(packID, restic.Blob{ Type: blob.Type, ID: blob.ID, Offset: blob.Offset, Length: blob.Length, }) switch blob.Type { case restic.DataBlob: data = true case restic.TreeBlob: tree = true } } if !data && tree { idx.treePacks = append(idx.treePacks, pack.ID) } } idx.final = true debug.Log("done") return idx, nil }
1
14,103
Ignoring the pack entry from an existing entry but using the new entry from a non-finalized index, is subtle enough that it needs explaining.
restic-restic
go
@@ -236,9 +236,12 @@ uint32_t Spells::getInstantSpellCount(const Player* player) const InstantSpell* Spells::getInstantSpellById(uint32_t spellId) { - auto it = std::next(instants.begin(), std::min<uint32_t>(spellId, instants.size())); - if (it != instants.end()) { - return it->second; + uint32_t count = 0; + for (const auto& it : instants) { + if (count == spellId) { + return it.second; + } + ++count; } return nullptr; }
1
/** * The Forgotten Server - a free and open-source MMORPG server emulator * Copyright (C) 2017 Mark Samman <[email protected]> * * 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. */ #include "otpch.h" #include "combat.h" #include "configmanager.h" #include "game.h" #include "monster.h" #include "pugicast.h" #include "spells.h" extern Game g_game; extern Spells* g_spells; extern Monsters g_monsters; extern Vocations g_vocations; extern ConfigManager g_config; extern LuaEnvironment g_luaEnvironment; Spells::Spells() { scriptInterface.initState(); } Spells::~Spells() { clear(); } TalkActionResult_t Spells::playerSaySpell(Player* player, std::string& words) { std::string str_words = words; //strip trailing spaces trimString(str_words); InstantSpell* instantSpell = getInstantSpell(str_words); if (!instantSpell) { return TALKACTION_CONTINUE; } std::string param; if (instantSpell->getHasParam()) { size_t spellLen = instantSpell->getWords().length(); size_t paramLen = str_words.length() - spellLen; std::string paramText = str_words.substr(spellLen, paramLen); if (!paramText.empty() && paramText.front() == ' ') { size_t loc1 = paramText.find('"', 1); if (loc1 != std::string::npos) { size_t loc2 = paramText.find('"', loc1 + 1); if (loc2 == std::string::npos) { loc2 = paramText.length(); } else if (paramText.find_last_not_of(' ') != loc2) { return TALKACTION_CONTINUE; } param = paramText.substr(loc1 + 1, loc2 - loc1 - 1); } else { trimString(paramText); loc1 = paramText.find(' ', 0); if (loc1 == std::string::npos) { param = paramText; } else { return TALKACTION_CONTINUE; } } } } if (instantSpell->playerCastInstant(player, param)) { words = instantSpell->getWords(); if (instantSpell->getHasParam() && !param.empty()) { words += " \"" + param + "\""; } return TALKACTION_BREAK; } return TALKACTION_FAILED; } void Spells::clear() { for (const auto& it : runes) { delete it.second; } runes.clear(); for (const auto& it : instants) { delete it.second; } instants.clear(); scriptInterface.reInitState(); } LuaScriptInterface& Spells::getScriptInterface() { return scriptInterface; } std::string Spells::getScriptBaseName() const { return "spells"; } Event* Spells::getEvent(const std::string& nodeName) { if (strcasecmp(nodeName.c_str(), "rune") == 0) { return new RuneSpell(&scriptInterface); } else if (strcasecmp(nodeName.c_str(), "instant") == 0) { return new InstantSpell(&scriptInterface); } else if (strcasecmp(nodeName.c_str(), "conjure") == 0) { return new ConjureSpell(&scriptInterface); } return nullptr; } bool Spells::registerEvent(Event* event, const pugi::xml_node&) { InstantSpell* instant = dynamic_cast<InstantSpell*>(event); if (instant) { auto result = instants.emplace(instant->getWords(), instant); if (!result.second) { std::cout << "[Warning - Spells::registerEvent] Duplicate registered instant spell with words: " << instant->getWords() << std::endl; } return result.second; } RuneSpell* rune = dynamic_cast<RuneSpell*>(event); if (rune) { auto result = runes.emplace(rune->getRuneItemId(), rune); if (!result.second) { std::cout << "[Warning - Spells::registerEvent] Duplicate registered rune with id: " << rune->getRuneItemId() << std::endl; } return result.second; } return false; } Spell* Spells::getSpellByName(const std::string& name) { Spell* spell = getRuneSpellByName(name); if (!spell) { spell = getInstantSpellByName(name); } return spell; } RuneSpell* Spells::getRuneSpell(uint32_t id) { auto it = runes.find(id); if (it == runes.end()) { return nullptr; } return it->second; } RuneSpell* Spells::getRuneSpellByName(const std::string& name) { for (const auto& it : runes) { if (strcasecmp(it.second->getName().c_str(), name.c_str()) == 0) { return it.second; } } return nullptr; } InstantSpell* Spells::getInstantSpell(const std::string& words) { InstantSpell* result = nullptr; for (const auto& it : instants) { InstantSpell* instantSpell = it.second; const std::string& instantSpellWords = instantSpell->getWords(); size_t spellLen = instantSpellWords.length(); if (strncasecmp(instantSpellWords.c_str(), words.c_str(), spellLen) == 0) { if (!result || spellLen > result->getWords().length()) { result = instantSpell; if (words.length() == spellLen) { break; } } } } if (result) { const std::string& resultWords = result->getWords(); if (words.length() > resultWords.length()) { if (!result->getHasParam()) { return nullptr; } size_t spellLen = resultWords.length(); size_t paramLen = words.length() - spellLen; if (paramLen < 2 || words[spellLen] != ' ') { return nullptr; } } return result; } return nullptr; } uint32_t Spells::getInstantSpellCount(const Player* player) const { uint32_t count = 0; for (const auto& it : instants) { InstantSpell* instantSpell = it.second; if (instantSpell->canCast(player)) { ++count; } } return count; } InstantSpell* Spells::getInstantSpellById(uint32_t spellId) { auto it = std::next(instants.begin(), std::min<uint32_t>(spellId, instants.size())); if (it != instants.end()) { return it->second; } return nullptr; } InstantSpell* Spells::getInstantSpellByName(const std::string& name) { for (const auto& it : instants) { if (strcasecmp(it.second->getName().c_str(), name.c_str()) == 0) { return it.second; } } return nullptr; } Position Spells::getCasterPosition(Creature* creature, Direction dir) { return getNextPosition(dir, creature->getPosition()); } CombatSpell::CombatSpell(Combat* combat, bool needTarget, bool needDirection) : Event(&g_spells->getScriptInterface()), combat(combat), needDirection(needDirection), needTarget(needTarget) {} CombatSpell::~CombatSpell() { if (!scripted) { delete combat; } } bool CombatSpell::loadScriptCombat() { combat = g_luaEnvironment.getCombatObject(g_luaEnvironment.lastCombatId); return combat != nullptr; } bool CombatSpell::castSpell(Creature* creature) { if (scripted) { LuaVariant var; var.type = VARIANT_POSITION; if (needDirection) { var.pos = Spells::getCasterPosition(creature, creature->getDirection()); } else { var.pos = creature->getPosition(); } return executeCastSpell(creature, var); } Position pos; if (needDirection) { pos = Spells::getCasterPosition(creature, creature->getDirection()); } else { pos = creature->getPosition(); } combat->doCombat(creature, pos); return true; } bool CombatSpell::castSpell(Creature* creature, Creature* target) { if (scripted) { LuaVariant var; if (combat->hasArea()) { var.type = VARIANT_POSITION; if (needTarget) { var.pos = target->getPosition(); } else if (needDirection) { var.pos = Spells::getCasterPosition(creature, creature->getDirection()); } else { var.pos = creature->getPosition(); } } else { var.type = VARIANT_NUMBER; var.number = target->getID(); } return executeCastSpell(creature, var); } if (combat->hasArea()) { if (needTarget) { combat->doCombat(creature, target->getPosition()); } else { return castSpell(creature); } } else { combat->doCombat(creature, target); } return true; } bool CombatSpell::executeCastSpell(Creature* creature, const LuaVariant& var) { //onCastSpell(creature, var) if (!scriptInterface->reserveScriptEnv()) { std::cout << "[Error - CombatSpell::executeCastSpell] Call stack overflow" << std::endl; return false; } ScriptEnvironment* env = scriptInterface->getScriptEnv(); env->setScriptId(scriptId, scriptInterface); lua_State* L = scriptInterface->getLuaState(); scriptInterface->pushFunction(scriptId); LuaScriptInterface::pushUserdata<Creature>(L, creature); LuaScriptInterface::setCreatureMetatable(L, -1, creature); LuaScriptInterface::pushVariant(L, var); return scriptInterface->callFunction(2); } bool Spell::configureSpell(const pugi::xml_node& node) { pugi::xml_attribute nameAttribute = node.attribute("name"); if (!nameAttribute) { std::cout << "[Error - Spell::configureSpell] Spell without name" << std::endl; return false; } name = nameAttribute.as_string(); static const char* reservedList[] = { "melee", "physical", "poison", "fire", "energy", "drown", "lifedrain", "manadrain", "healing", "speed", "outfit", "invisible", "drunk", "firefield", "poisonfield", "energyfield", "firecondition", "poisoncondition", "energycondition", "drowncondition", "freezecondition", "cursecondition", "dazzlecondition" }; //static size_t size = sizeof(reservedList) / sizeof(const char*); //for (size_t i = 0; i < size; ++i) { for (const char* reserved : reservedList) { if (strcasecmp(reserved, name.c_str()) == 0) { std::cout << "[Error - Spell::configureSpell] Spell is using a reserved name: " << reserved << std::endl; return false; } } pugi::xml_attribute attr; if ((attr = node.attribute("spellid"))) { spellId = pugi::cast<uint16_t>(attr.value()); } if ((attr = node.attribute("group"))) { std::string tmpStr = asLowerCaseString(attr.as_string()); if (tmpStr == "none" || tmpStr == "0") { group = SPELLGROUP_NONE; } else if (tmpStr == "attack" || tmpStr == "1") { group = SPELLGROUP_ATTACK; } else if (tmpStr == "healing" || tmpStr == "2") { group = SPELLGROUP_HEALING; } else if (tmpStr == "support" || tmpStr == "3") { group = SPELLGROUP_SUPPORT; } else if (tmpStr == "special" || tmpStr == "4") { group = SPELLGROUP_SPECIAL; } else { std::cout << "[Warning - Spell::configureSpell] Unknown group: " << attr.as_string() << std::endl; } } if ((attr = node.attribute("groupcooldown"))) { groupCooldown = pugi::cast<uint32_t>(attr.value()); } if ((attr = node.attribute("secondarygroup"))) { std::string tmpStr = asLowerCaseString(attr.as_string()); if (tmpStr == "none" || tmpStr == "0") { secondaryGroup = SPELLGROUP_NONE; } else if (tmpStr == "attack" || tmpStr == "1") { secondaryGroup = SPELLGROUP_ATTACK; } else if (tmpStr == "healing" || tmpStr == "2") { secondaryGroup = SPELLGROUP_HEALING; } else if (tmpStr == "support" || tmpStr == "3") { secondaryGroup = SPELLGROUP_SUPPORT; } else if (tmpStr == "special" || tmpStr == "4") { secondaryGroup = SPELLGROUP_SPECIAL; } else { std::cout << "[Warning - Spell::configureSpell] Unknown secondarygroup: " << attr.as_string() << std::endl; } } if ((attr = node.attribute("secondarygroupcooldown"))) { secondaryGroupCooldown = pugi::cast<uint32_t>(attr.value()); } if ((attr = node.attribute("lvl"))) { level = pugi::cast<uint32_t>(attr.value()); } if ((attr = node.attribute("maglv"))) { magLevel = pugi::cast<uint32_t>(attr.value()); } if ((attr = node.attribute("mana"))) { mana = pugi::cast<uint32_t>(attr.value()); } if ((attr = node.attribute("manapercent"))) { manaPercent = pugi::cast<uint32_t>(attr.value()); } if ((attr = node.attribute("soul"))) { soul = pugi::cast<uint32_t>(attr.value()); } if ((attr = node.attribute("range"))) { range = pugi::cast<int32_t>(attr.value()); } if ((attr = node.attribute("exhaustion")) || (attr = node.attribute("cooldown"))) { cooldown = pugi::cast<uint32_t>(attr.value()); } if ((attr = node.attribute("prem"))) { premium = attr.as_bool(); } if ((attr = node.attribute("enabled"))) { enabled = attr.as_bool(); } if ((attr = node.attribute("needtarget"))) { needTarget = attr.as_bool(); } if ((attr = node.attribute("needweapon"))) { needWeapon = attr.as_bool(); } if ((attr = node.attribute("selftarget"))) { selfTarget = attr.as_bool(); } if ((attr = node.attribute("needlearn"))) { learnable = attr.as_bool(); } if ((attr = node.attribute("blocking"))) { blockingSolid = attr.as_bool(); blockingCreature = blockingSolid; } if ((attr = node.attribute("blocktype"))) { std::string tmpStrValue = asLowerCaseString(attr.as_string()); if (tmpStrValue == "all") { blockingSolid = true; blockingCreature = true; } else if (tmpStrValue == "solid") { blockingSolid = true; } else if (tmpStrValue == "creature") { blockingCreature = true; } else { std::cout << "[Warning - Spell::configureSpell] Blocktype \"" << attr.as_string() << "\" does not exist." << std::endl; } } if ((attr = node.attribute("aggressive"))) { aggressive = booleanString(attr.as_string()); } if (group == SPELLGROUP_NONE) { group = (aggressive ? SPELLGROUP_ATTACK : SPELLGROUP_HEALING); } for (auto vocationNode : node.children()) { if (!(attr = vocationNode.attribute("name"))) { continue; } int32_t vocationId = g_vocations.getVocationId(attr.as_string()); if (vocationId != -1) { attr = vocationNode.attribute("showInDescription"); vocSpellMap[vocationId] = !attr || attr.as_bool(); } else { std::cout << "[Warning - Spell::configureSpell] Wrong vocation name: " << attr.as_string() << std::endl; } } return true; } bool Spell::playerSpellCheck(Player* player) const { if (player->hasFlag(PlayerFlag_CannotUseSpells)) { return false; } if (player->hasFlag(PlayerFlag_IgnoreSpellCheck)) { return true; } if (!enabled) { return false; } if (aggressive && !player->hasFlag(PlayerFlag_IgnoreProtectionZone) && player->getZone() == ZONE_PROTECTION) { player->sendCancelMessage(RETURNVALUE_ACTIONNOTPERMITTEDINPROTECTIONZONE); return false; } if (player->hasCondition(CONDITION_SPELLGROUPCOOLDOWN, group) || player->hasCondition(CONDITION_SPELLCOOLDOWN, spellId) || (secondaryGroup != SPELLGROUP_NONE && player->hasCondition(CONDITION_SPELLGROUPCOOLDOWN, secondaryGroup))) { player->sendCancelMessage(RETURNVALUE_YOUAREEXHAUSTED); if (isInstant()) { g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF); } return false; } if (player->getLevel() < level) { player->sendCancelMessage(RETURNVALUE_NOTENOUGHLEVEL); g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF); return false; } if (player->getMagicLevel() < magLevel) { player->sendCancelMessage(RETURNVALUE_NOTENOUGHMAGICLEVEL); g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF); return false; } if (player->getMana() < getManaCost(player) && !player->hasFlag(PlayerFlag_HasInfiniteMana)) { player->sendCancelMessage(RETURNVALUE_NOTENOUGHMANA); g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF); return false; } if (player->getSoul() < soul && !player->hasFlag(PlayerFlag_HasInfiniteSoul)) { player->sendCancelMessage(RETURNVALUE_NOTENOUGHSOUL); g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF); return false; } if (isInstant() && isLearnable()) { if (!player->hasLearnedInstantSpell(getName())) { player->sendCancelMessage(RETURNVALUE_YOUNEEDTOLEARNTHISSPELL); g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF); return false; } } else if (!vocSpellMap.empty() && vocSpellMap.find(player->getVocationId()) == vocSpellMap.end()) { player->sendCancelMessage(RETURNVALUE_YOURVOCATIONCANNOTUSETHISSPELL); g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF); return false; } if (needWeapon) { switch (player->getWeaponType()) { case WEAPON_SWORD: case WEAPON_CLUB: case WEAPON_AXE: break; default: { player->sendCancelMessage(RETURNVALUE_YOUNEEDAWEAPONTOUSETHISSPELL); g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF); return false; } } } if (isPremium() && !player->isPremium()) { player->sendCancelMessage(RETURNVALUE_YOUNEEDPREMIUMACCOUNT); g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF); return false; } return true; } bool Spell::playerInstantSpellCheck(Player* player, const Position& toPos) { if (toPos.x == 0xFFFF) { return true; } const Position& playerPos = player->getPosition(); if (playerPos.z > toPos.z) { player->sendCancelMessage(RETURNVALUE_FIRSTGOUPSTAIRS); g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF); return false; } else if (playerPos.z < toPos.z) { player->sendCancelMessage(RETURNVALUE_FIRSTGODOWNSTAIRS); g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF); return false; } Tile* tile = g_game.map.getTile(toPos); if (!tile) { tile = new StaticTile(toPos.x, toPos.y, toPos.z); g_game.map.setTile(toPos, tile); } ReturnValue ret = Combat::canDoCombat(player, tile, aggressive); if (ret != RETURNVALUE_NOERROR) { player->sendCancelMessage(ret); g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF); return false; } if (blockingCreature && tile->getBottomVisibleCreature(player) != nullptr) { player->sendCancelMessage(RETURNVALUE_NOTENOUGHROOM); g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF); return false; } if (blockingSolid && tile->hasFlag(TILESTATE_BLOCKSOLID)) { player->sendCancelMessage(RETURNVALUE_NOTENOUGHROOM); g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF); return false; } return true; } bool Spell::playerRuneSpellCheck(Player* player, const Position& toPos) { if (!playerSpellCheck(player)) { return false; } if (toPos.x == 0xFFFF) { return true; } const Position& playerPos = player->getPosition(); if (playerPos.z > toPos.z) { player->sendCancelMessage(RETURNVALUE_FIRSTGOUPSTAIRS); g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF); return false; } else if (playerPos.z < toPos.z) { player->sendCancelMessage(RETURNVALUE_FIRSTGODOWNSTAIRS); g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF); return false; } Tile* tile = g_game.map.getTile(toPos); if (!tile) { player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF); return false; } if (range != -1 && !g_game.canThrowObjectTo(playerPos, toPos, true, range, range)) { player->sendCancelMessage(RETURNVALUE_DESTINATIONOUTOFREACH); g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF); return false; } ReturnValue ret = Combat::canDoCombat(player, tile, aggressive); if (ret != RETURNVALUE_NOERROR) { player->sendCancelMessage(ret); g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF); return false; } const Creature* topVisibleCreature = tile->getBottomVisibleCreature(player); if (blockingCreature && topVisibleCreature) { player->sendCancelMessage(RETURNVALUE_NOTENOUGHROOM); g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF); return false; } else if (blockingSolid && tile->hasFlag(TILESTATE_BLOCKSOLID)) { player->sendCancelMessage(RETURNVALUE_NOTENOUGHROOM); g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF); return false; } if (needTarget && !topVisibleCreature) { player->sendCancelMessage(RETURNVALUE_CANONLYUSETHISRUNEONCREATURES); g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF); return false; } if (aggressive && needTarget && topVisibleCreature && player->hasSecureMode()) { const Player* targetPlayer = topVisibleCreature->getPlayer(); if (targetPlayer && targetPlayer != player && player->getSkullClient(targetPlayer) == SKULL_NONE && !Combat::isInPvpZone(player, targetPlayer)) { player->sendCancelMessage(RETURNVALUE_TURNSECUREMODETOATTACKUNMARKEDPLAYERS); g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF); return false; } } return true; } void Spell::postCastSpell(Player* player, bool finishedCast /*= true*/, bool payCost /*= true*/) const { if (finishedCast) { if (!player->hasFlag(PlayerFlag_HasNoExhaustion)) { if (cooldown > 0) { Condition* condition = Condition::createCondition(CONDITIONID_DEFAULT, CONDITION_SPELLCOOLDOWN, cooldown, 0, false, spellId); player->addCondition(condition); } if (groupCooldown > 0) { Condition* condition = Condition::createCondition(CONDITIONID_DEFAULT, CONDITION_SPELLGROUPCOOLDOWN, groupCooldown, 0, false, group); player->addCondition(condition); } if (secondaryGroupCooldown > 0) { Condition* condition = Condition::createCondition(CONDITIONID_DEFAULT, CONDITION_SPELLGROUPCOOLDOWN, secondaryGroupCooldown, 0, false, secondaryGroup); player->addCondition(condition); } } if (aggressive) { player->addInFightTicks(); } } if (payCost) { Spell::postCastSpell(player, getManaCost(player), getSoulCost()); } } void Spell::postCastSpell(Player* player, uint32_t manaCost, uint32_t soulCost) { if (manaCost > 0) { player->addManaSpent(manaCost); player->changeMana(-static_cast<int32_t>(manaCost)); } if (!player->hasFlag(PlayerFlag_HasInfiniteSoul)) { if (soulCost > 0) { player->changeSoul(-static_cast<int32_t>(soulCost)); } } } uint32_t Spell::getManaCost(const Player* player) const { if (mana != 0) { return mana; } if (manaPercent != 0) { uint32_t maxMana = player->getMaxMana(); uint32_t manaCost = (maxMana * manaPercent) / 100; return manaCost; } return 0; } ReturnValue Spell::CreateIllusion(Creature* creature, const Outfit_t& outfit, int32_t time) { ConditionOutfit* outfitCondition = new ConditionOutfit(CONDITIONID_COMBAT, CONDITION_OUTFIT, time); outfitCondition->setOutfit(outfit); creature->addCondition(outfitCondition); return RETURNVALUE_NOERROR; } ReturnValue Spell::CreateIllusion(Creature* creature, const std::string& name, int32_t time) { const auto mType = g_monsters.getMonsterType(name); if (mType == nullptr) { return RETURNVALUE_CREATUREDOESNOTEXIST; } Player* player = creature->getPlayer(); if (player && !player->hasFlag(PlayerFlag_CanIllusionAll)) { if (!mType->info.isIllusionable) { return RETURNVALUE_NOTPOSSIBLE; } } return CreateIllusion(creature, mType->info.outfit, time); } ReturnValue Spell::CreateIllusion(Creature* creature, uint32_t itemId, int32_t time) { const ItemType& it = Item::items[itemId]; if (it.id == 0) { return RETURNVALUE_NOTPOSSIBLE; } Outfit_t outfit; outfit.lookTypeEx = itemId; return CreateIllusion(creature, outfit, time); } std::string InstantSpell::getScriptEventName() const { return "onCastSpell"; } bool InstantSpell::configureEvent(const pugi::xml_node& node) { if (!Spell::configureSpell(node)) { return false; } if (!TalkAction::configureEvent(node)) { return false; } pugi::xml_attribute attr; if ((attr = node.attribute("params"))) { hasParam = attr.as_bool(); } if ((attr = node.attribute("playernameparam"))) { hasPlayerNameParam = attr.as_bool(); } if ((attr = node.attribute("direction"))) { needDirection = attr.as_bool(); } else if ((attr = node.attribute("casterTargetOrDirection"))) { casterTargetOrDirection = attr.as_bool(); } if ((attr = node.attribute("blockwalls"))) { checkLineOfSight = attr.as_bool(); } return true; } namespace { bool SummonMonster(const InstantSpell* spell, Creature* creature, const std::string& param) { Player* player = creature->getPlayer(); if (!player) { return false; } MonsterType* mType = g_monsters.getMonsterType(param); if (!mType) { player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF); return false; } if (!player->hasFlag(PlayerFlag_CanSummonAll)) { if (!mType->info.isSummonable) { player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF); return false; } if (player->getMana() < mType->info.manaCost) { player->sendCancelMessage(RETURNVALUE_NOTENOUGHMANA); g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF); return false; } if (player->getSummonCount() >= 2) { player->sendCancelMessage("You cannot summon more creatures."); g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF); return false; } } Monster* monster = Monster::createMonster(param); if (!monster) { player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF); return false; } // Place the monster creature->addSummon(monster); if (!g_game.placeCreature(monster, creature->getPosition(), true)) { creature->removeSummon(monster); player->sendCancelMessage(RETURNVALUE_NOTENOUGHROOM); g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF); return false; } Spell::postCastSpell(player, mType->info.manaCost, spell->getSoulCost()); g_game.addMagicEffect(player->getPosition(), CONST_ME_MAGIC_BLUE); g_game.addMagicEffect(monster->getPosition(), CONST_ME_TELEPORT); return true; } bool Levitate(const InstantSpell*, Creature* creature, const std::string& param) { Player* player = creature->getPlayer(); if (!player) { return false; } const Position& currentPos = creature->getPosition(); const Position& destPos = Spells::getCasterPosition(creature, creature->getDirection()); ReturnValue ret = RETURNVALUE_NOTPOSSIBLE; if (strcasecmp(param.c_str(), "up") == 0) { if (currentPos.z != 8) { Tile* tmpTile = g_game.map.getTile(currentPos.x, currentPos.y, currentPos.getZ() - 1); if (tmpTile == nullptr || (tmpTile->getGround() == nullptr && !tmpTile->hasFlag(TILESTATE_IMMOVABLEBLOCKSOLID))) { tmpTile = g_game.map.getTile(destPos.x, destPos.y, destPos.getZ() - 1); if (tmpTile && tmpTile->getGround() && !tmpTile->hasFlag(TILESTATE_IMMOVABLEBLOCKSOLID | TILESTATE_FLOORCHANGE)) { ret = g_game.internalMoveCreature(*player, *tmpTile, FLAG_IGNOREBLOCKITEM | FLAG_IGNOREBLOCKCREATURE); } } } } else if (strcasecmp(param.c_str(), "down") == 0) { if (currentPos.z != 7) { Tile* tmpTile = g_game.map.getTile(destPos); if (tmpTile == nullptr || (tmpTile->getGround() == nullptr && !tmpTile->hasFlag(TILESTATE_BLOCKSOLID))) { tmpTile = g_game.map.getTile(destPos.x, destPos.y, destPos.z + 1); if (tmpTile && tmpTile->getGround() && !tmpTile->hasFlag(TILESTATE_IMMOVABLEBLOCKSOLID | TILESTATE_FLOORCHANGE)) { ret = g_game.internalMoveCreature(*player, *tmpTile, FLAG_IGNOREBLOCKITEM | FLAG_IGNOREBLOCKCREATURE); } } } } if (ret != RETURNVALUE_NOERROR) { player->sendCancelMessage(ret); g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF); return false; } g_game.addMagicEffect(player->getPosition(), CONST_ME_TELEPORT); return true; } bool Illusion(const InstantSpell*, Creature* creature, const std::string& param) { Player* player = creature->getPlayer(); if (!player) { return false; } ReturnValue ret = Spell::CreateIllusion(creature, param, 180000); if (ret != RETURNVALUE_NOERROR) { player->sendCancelMessage(ret); g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF); return false; } g_game.addMagicEffect(player->getPosition(), CONST_ME_MAGIC_RED); return true; } } bool InstantSpell::loadFunction(const pugi::xml_attribute& attr) { const char* functionName = attr.as_string(); if (strcasecmp(functionName, "levitate") == 0) { function = Levitate; } else if (strcasecmp(functionName, "illusion") == 0) { function = Illusion; } else if (strcasecmp(functionName, "summonmonster") == 0) { function = SummonMonster; } else { std::cout << "[Warning - InstantSpell::loadFunction] Function \"" << functionName << "\" does not exist." << std::endl; return false; } scripted = false; return true; } bool InstantSpell::playerCastInstant(Player* player, std::string& param) { if (!playerSpellCheck(player)) { return false; } LuaVariant var; if (selfTarget) { var.type = VARIANT_NUMBER; var.number = player->getID(); } else if (needTarget || casterTargetOrDirection) { Creature* target = nullptr; bool useDirection = false; if (hasParam) { Player* playerTarget = nullptr; ReturnValue ret = g_game.getPlayerByNameWildcard(param, playerTarget); if (playerTarget && playerTarget->isAccessPlayer() && !player->isAccessPlayer()) { playerTarget = nullptr; } target = playerTarget; if (!target || target->getHealth() <= 0) { if (!casterTargetOrDirection) { if (cooldown > 0) { Condition* condition = Condition::createCondition(CONDITIONID_DEFAULT, CONDITION_SPELLCOOLDOWN, cooldown, 0, false, spellId); player->addCondition(condition); } if (groupCooldown > 0) { Condition* condition = Condition::createCondition(CONDITIONID_DEFAULT, CONDITION_SPELLGROUPCOOLDOWN, groupCooldown, 0, false, group); player->addCondition(condition); } if (secondaryGroupCooldown > 0) { Condition* condition = Condition::createCondition(CONDITIONID_DEFAULT, CONDITION_SPELLGROUPCOOLDOWN, secondaryGroupCooldown, 0, false, secondaryGroup); player->addCondition(condition); } player->sendCancelMessage(ret); g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF); return false; } useDirection = true; } if (playerTarget) { param = playerTarget->getName(); } } else { target = player->getAttackedCreature(); if (!target || target->getHealth() <= 0) { if (!casterTargetOrDirection) { player->sendCancelMessage(RETURNVALUE_YOUCANONLYUSEITONCREATURES); g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF); return false; } useDirection = true; } } if (!useDirection) { if (!canThrowSpell(player, target)) { player->sendCancelMessage(RETURNVALUE_CREATUREISNOTREACHABLE); g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF); return false; } var.type = VARIANT_NUMBER; var.number = target->getID(); } else { var.type = VARIANT_POSITION; var.pos = Spells::getCasterPosition(player, player->getDirection()); if (!playerInstantSpellCheck(player, var.pos)) { return false; } } } else if (hasParam) { var.type = VARIANT_STRING; if (getHasPlayerNameParam()) { Player* playerTarget = nullptr; ReturnValue ret = g_game.getPlayerByNameWildcard(param, playerTarget); if (ret != RETURNVALUE_NOERROR) { if (cooldown > 0) { Condition* condition = Condition::createCondition(CONDITIONID_DEFAULT, CONDITION_SPELLCOOLDOWN, cooldown, 0, false, spellId); player->addCondition(condition); } if (groupCooldown > 0) { Condition* condition = Condition::createCondition(CONDITIONID_DEFAULT, CONDITION_SPELLGROUPCOOLDOWN, groupCooldown, 0, false, group); player->addCondition(condition); } if (secondaryGroupCooldown > 0) { Condition* condition = Condition::createCondition(CONDITIONID_DEFAULT, CONDITION_SPELLGROUPCOOLDOWN, secondaryGroupCooldown, 0, false, secondaryGroup); player->addCondition(condition); } player->sendCancelMessage(ret); g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF); return false; } if (playerTarget && (!playerTarget->isAccessPlayer() || player->isAccessPlayer())) { param = playerTarget->getName(); } } var.text = param; } else { var.type = VARIANT_POSITION; if (needDirection) { var.pos = Spells::getCasterPosition(player, player->getDirection()); } else { var.pos = player->getPosition(); } if (!playerInstantSpellCheck(player, var.pos)) { return false; } } bool result = internalCastSpell(player, var); if (result) { postCastSpell(player); } return result; } bool InstantSpell::canThrowSpell(const Creature* creature, const Creature* target) const { const Position& fromPos = creature->getPosition(); const Position& toPos = target->getPosition(); if (fromPos.z != toPos.z || (range == -1 && !g_game.canThrowObjectTo(fromPos, toPos, checkLineOfSight)) || (range != -1 && !g_game.canThrowObjectTo(fromPos, toPos, checkLineOfSight, range, range))) { return false; } return true; } bool InstantSpell::castSpell(Creature* creature) { LuaVariant var; if (casterTargetOrDirection) { Creature* target = creature->getAttackedCreature(); if (target && target->getHealth() > 0) { if (!canThrowSpell(creature, target)) { return false; } var.type = VARIANT_NUMBER; var.number = target->getID(); return internalCastSpell(creature, var); } return false; } else if (needDirection) { var.type = VARIANT_POSITION; var.pos = Spells::getCasterPosition(creature, creature->getDirection()); } else { var.type = VARIANT_POSITION; var.pos = creature->getPosition(); } return internalCastSpell(creature, var); } bool InstantSpell::castSpell(Creature* creature, Creature* target) { if (needTarget) { LuaVariant var; var.type = VARIANT_NUMBER; var.number = target->getID(); return internalCastSpell(creature, var); } else { return castSpell(creature); } } bool InstantSpell::internalCastSpell(Creature* creature, const LuaVariant& var) { if (scripted) { return executeCastSpell(creature, var); } else if (function) { return function(this, creature, var.text); } return false; } bool InstantSpell::executeCastSpell(Creature* creature, const LuaVariant& var) { //onCastSpell(creature, var) if (!scriptInterface->reserveScriptEnv()) { std::cout << "[Error - InstantSpell::executeCastSpell] Call stack overflow" << std::endl; return false; } ScriptEnvironment* env = scriptInterface->getScriptEnv(); env->setScriptId(scriptId, scriptInterface); lua_State* L = scriptInterface->getLuaState(); scriptInterface->pushFunction(scriptId); LuaScriptInterface::pushUserdata<Creature>(L, creature); LuaScriptInterface::setCreatureMetatable(L, -1, creature); LuaScriptInterface::pushVariant(L, var); return scriptInterface->callFunction(2); } bool InstantSpell::canCast(const Player* player) const { if (player->hasFlag(PlayerFlag_CannotUseSpells)) { return false; } if (player->hasFlag(PlayerFlag_IgnoreSpellCheck)) { return true; } if (isLearnable()) { if (player->hasLearnedInstantSpell(getName())) { return true; } } else { if (vocSpellMap.empty() || vocSpellMap.find(player->getVocationId()) != vocSpellMap.end()) { return true; } } return false; } std::string ConjureSpell::getScriptEventName() const { return "onCastSpell"; } bool ConjureSpell::configureEvent(const pugi::xml_node& node) { if (!InstantSpell::configureEvent(node)) { return false; } pugi::xml_attribute attr; if ((attr = node.attribute("conjureId"))) { conjureId = pugi::cast<uint32_t>(attr.value()); } if ((attr = node.attribute("conjureCount"))) { conjureCount = pugi::cast<uint32_t>(attr.value()); } else if (conjureId != 0) { // load default charges from items.xml const ItemType& it = Item::items[conjureId]; if (it.charges != 0) { conjureCount = it.charges; } } if ((attr = node.attribute("reagentId"))) { reagentId = pugi::cast<uint32_t>(attr.value()); } return true; } bool ConjureSpell::loadFunction(const pugi::xml_attribute&) { scripted = false; return true; } bool ConjureSpell::conjureItem(Creature* creature) const { Player* player = creature->getPlayer(); if (!player) { return false; } if (reagentId != 0 && !player->removeItemOfType(reagentId, 1, -1)) { player->sendCancelMessage(RETURNVALUE_YOUNEEDAMAGICITEMTOCASTSPELL); g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF); return false; } Item* newItem = Item::CreateItem(conjureId, conjureCount); if (!newItem) { return false; } ReturnValue ret = g_game.internalPlayerAddItem(player, newItem); if (ret != RETURNVALUE_NOERROR) { player->sendCancelMessage(ret); g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF); delete newItem; return false; } g_game.startDecay(newItem); postCastSpell(player); g_game.addMagicEffect(player->getPosition(), CONST_ME_MAGIC_RED); return true; } bool ConjureSpell::playerCastInstant(Player* player, std::string& param) { if (!playerSpellCheck(player)) { return false; } if (scripted) { LuaVariant var; var.type = VARIANT_STRING; var.text = param; return executeCastSpell(player, var); } return conjureItem(player); } std::string RuneSpell::getScriptEventName() const { return "onCastSpell"; } bool RuneSpell::configureEvent(const pugi::xml_node& node) { if (!Spell::configureSpell(node)) { return false; } if (!Action::configureEvent(node)) { return false; } pugi::xml_attribute attr; if (!(attr = node.attribute("id"))) { std::cout << "[Error - RuneSpell::configureSpell] Rune spell without id." << std::endl; return false; } runeId = pugi::cast<uint16_t>(attr.value()); uint32_t charges; if ((attr = node.attribute("charges"))) { charges = pugi::cast<uint32_t>(attr.value()); } else { charges = 0; } hasCharges = (charges > 0); if (magLevel != 0 || level != 0) { //Change information in the ItemType to get accurate description ItemType& iType = Item::items.getItemType(runeId); iType.runeMagLevel = magLevel; iType.runeLevel = level; iType.charges = charges; } return true; } namespace { bool RuneIllusion(const RuneSpell*, Player* player, const Position& posTo) { Thing* thing = g_game.internalGetThing(player, posTo, 0, 0, STACKPOS_MOVE); if (!thing) { player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF); return false; } Item* illusionItem = thing->getItem(); if (!illusionItem || !illusionItem->isMoveable()) { player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF); return false; } ReturnValue ret = Spell::CreateIllusion(player, illusionItem->getID(), 200000); if (ret != RETURNVALUE_NOERROR) { player->sendCancelMessage(ret); g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF); return false; } g_game.addMagicEffect(player->getPosition(), CONST_ME_MAGIC_RED); return true; } bool Convince(const RuneSpell* spell, Player* player, const Position& posTo) { if (!player->hasFlag(PlayerFlag_CanConvinceAll)) { if (player->getSummonCount() >= 2) { player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF); return false; } } Thing* thing = g_game.internalGetThing(player, posTo, 0, 0, STACKPOS_LOOK); if (!thing) { player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF); return false; } Creature* convinceCreature = thing->getCreature(); if (!convinceCreature) { player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF); return false; } uint32_t manaCost = 0; if (convinceCreature->getMonster()) { manaCost = convinceCreature->getMonster()->getManaCost(); } if (!player->hasFlag(PlayerFlag_HasInfiniteMana) && player->getMana() < manaCost) { player->sendCancelMessage(RETURNVALUE_NOTENOUGHMANA); g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF); return false; } if (!convinceCreature->convinceCreature(player)) { player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); g_game.addMagicEffect(player->getPosition(), CONST_ME_POFF); return false; } Spell::postCastSpell(player, manaCost, spell->getSoulCost()); g_game.updateCreatureType(convinceCreature); g_game.addMagicEffect(player->getPosition(), CONST_ME_MAGIC_RED); return true; } } bool RuneSpell::loadFunction(const pugi::xml_attribute& attr) { const char* functionName = attr.as_string(); if (strcasecmp(functionName, "chameleon") == 0) { runeFunction = RuneIllusion; } else if (strcasecmp(functionName, "convince") == 0) { runeFunction = Convince; } else { std::cout << "[Warning - RuneSpell::loadFunction] Function \"" << functionName << "\" does not exist." << std::endl; return false; } scripted = false; return true; } ReturnValue RuneSpell::canExecuteAction(const Player* player, const Position& toPos) { if (player->hasFlag(PlayerFlag_CannotUseSpells)) { return RETURNVALUE_CANNOTUSETHISOBJECT; } ReturnValue ret = Action::canExecuteAction(player, toPos); if (ret != RETURNVALUE_NOERROR) { return ret; } if (toPos.x == 0xFFFF) { if (needTarget) { return RETURNVALUE_CANONLYUSETHISRUNEONCREATURES; } else if (!selfTarget) { return RETURNVALUE_NOTENOUGHROOM; } } return RETURNVALUE_NOERROR; } bool RuneSpell::executeUse(Player* player, Item* item, const Position&, Thing* target, const Position& toPosition, bool isHotkey) { if (!playerRuneSpellCheck(player, toPosition)) { return false; } bool result = false; if (scripted) { LuaVariant var; if (needTarget) { var.type = VARIANT_NUMBER; if (target == nullptr) { Tile* toTile = g_game.map.getTile(toPosition); if (toTile) { const Creature* visibleCreature = toTile->getBottomVisibleCreature(player); if (visibleCreature) { var.number = visibleCreature->getID(); } } } else { var.number = target->getCreature()->getID(); } } else { var.type = VARIANT_POSITION; var.pos = toPosition; } result = internalCastSpell(player, var, isHotkey); } else if (runeFunction) { result = runeFunction(this, player, toPosition); } if (!result) { return false; } postCastSpell(player); if (hasCharges && item && g_config.getBoolean(ConfigManager::REMOVE_RUNE_CHARGES)) { int32_t newCount = std::max<int32_t>(0, item->getItemCount() - 1); g_game.transformItem(item, item->getID(), newCount); } return true; } bool RuneSpell::castSpell(Creature* creature) { LuaVariant var; var.type = VARIANT_NUMBER; var.number = creature->getID(); return internalCastSpell(creature, var, false); } bool RuneSpell::castSpell(Creature* creature, Creature* target) { LuaVariant var; var.type = VARIANT_NUMBER; var.number = target->getID(); return internalCastSpell(creature, var, false); } bool RuneSpell::internalCastSpell(Creature* creature, const LuaVariant& var, bool isHotkey) { bool result; if (scripted) { result = executeCastSpell(creature, var, isHotkey); } else { result = false; } return result; } bool RuneSpell::executeCastSpell(Creature* creature, const LuaVariant& var, bool isHotkey) { //onCastSpell(creature, var, isHotkey) if (!scriptInterface->reserveScriptEnv()) { std::cout << "[Error - RuneSpell::executeCastSpell] Call stack overflow" << std::endl; return false; } ScriptEnvironment* env = scriptInterface->getScriptEnv(); env->setScriptId(scriptId, scriptInterface); lua_State* L = scriptInterface->getLuaState(); scriptInterface->pushFunction(scriptId); LuaScriptInterface::pushUserdata<Creature>(L, creature); LuaScriptInterface::setCreatureMetatable(L, -1, creature); LuaScriptInterface::pushVariant(L, var); LuaScriptInterface::pushBoolean(L, isHotkey); return scriptInterface->callFunction(3); }
1
14,061
This is a revert, is it really an issue?
otland-forgottenserver
cpp
@@ -26,8 +26,7 @@ namespace OpenTelemetry.Trace using OpenTelemetry.Trace.Export; using OpenTelemetry.Trace.Internal; - /// <inheritdoc/> - public class SpanBuilder : ISpanBuilder + /*public class SpanBuilder { private readonly SpanProcessor spanProcessor; private readonly TracerConfiguration tracerConfiguration;
1
// <copyright file="SpanBuilder.cs" company="OpenTelemetry Authors"> // Copyright 2018, 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. // </copyright> namespace OpenTelemetry.Trace { using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using OpenTelemetry.Context.Propagation; using OpenTelemetry.Resources; using OpenTelemetry.Trace.Configuration; using OpenTelemetry.Trace.Export; using OpenTelemetry.Trace.Internal; /// <inheritdoc/> public class SpanBuilder : ISpanBuilder { private readonly SpanProcessor spanProcessor; private readonly TracerConfiguration tracerConfiguration; private readonly string name; private SpanKind kind; private ISpan parentSpan; private Activity parentActivity; private Activity fromActivity; private SpanContext parentSpanContext; private ContextSource contextSource = ContextSource.CurrentActivityParent; private ISampler sampler; private List<Link> links; private bool recordEvents; private DateTimeOffset startTimestamp; private Resource libraryResource; internal SpanBuilder(string name, SpanProcessor spanProcessor, TracerConfiguration tracerConfiguration, Resource libraryResource) { this.name = name ?? throw new ArgumentNullException(nameof(name)); this.spanProcessor = spanProcessor ?? throw new ArgumentNullException(nameof(spanProcessor)); this.tracerConfiguration = tracerConfiguration ?? throw new ArgumentNullException(nameof(tracerConfiguration)); this.libraryResource = libraryResource ?? throw new ArgumentNullException(nameof(libraryResource)); } private enum ContextSource { CurrentActivityParent, Activity, ExplicitActivityParent, ExplicitSpanParent, ExplicitRemoteParent, NoParent, } /// <inheritdoc/> public ISpanBuilder SetSampler(ISampler sampler) { this.sampler = sampler ?? throw new ArgumentNullException(nameof(sampler)); return this; } /// <inheritdoc/> public ISpanBuilder SetParent(ISpan parentSpan) { this.parentSpan = parentSpan ?? throw new ArgumentNullException(nameof(parentSpan)); this.contextSource = ContextSource.ExplicitSpanParent; this.parentSpanContext = null; this.parentActivity = null; return this; } /// <inheritdoc/> public ISpanBuilder SetParent(Activity parentActivity) { this.parentActivity = parentActivity ?? throw new ArgumentNullException(nameof(parentActivity)); this.contextSource = ContextSource.ExplicitActivityParent; this.parentSpanContext = null; this.parentSpan = null; return this; } /// <inheritdoc/> public ISpanBuilder SetParent(SpanContext remoteParent) { this.parentSpanContext = remoteParent ?? throw new ArgumentNullException(nameof(remoteParent)); this.parentSpan = null; this.parentActivity = null; this.contextSource = ContextSource.ExplicitRemoteParent; return this; } /// <inheritdoc/> public ISpanBuilder SetNoParent() { this.contextSource = ContextSource.NoParent; this.parentSpanContext = null; this.parentActivity = null; this.parentSpan = null; return this; } /// <inheritdoc /> public ISpanBuilder SetCreateChild(bool createChild) { if (!createChild) { var currentActivity = Activity.Current; if (currentActivity == null) { throw new ArgumentException("Current Activity cannot be null"); } if (currentActivity.IdFormat != ActivityIdFormat.W3C) { throw new ArgumentException("Current Activity is not in W3C format"); } if (currentActivity.StartTimeUtc == default || currentActivity.Duration != default) { throw new ArgumentException( "Current Activity is not running: it has not been started or has been stopped"); } this.fromActivity = currentActivity; this.contextSource = ContextSource.Activity; } else { this.contextSource = ContextSource.CurrentActivityParent; } this.parentSpan = null; this.parentSpanContext = null; this.parentActivity = null; return this; } /// <inheritdoc/> public ISpanBuilder SetSpanKind(SpanKind spanKind) { this.kind = spanKind; return this; } /// <inheritdoc/> public ISpanBuilder AddLink(SpanContext spanContext) { // let link validate arguments return this.AddLink(new Link(spanContext)); } /// <inheritdoc/> public ISpanBuilder AddLink(SpanContext spanContext, IDictionary<string, object> attributes) { // let link validate arguments return this.AddLink(new Link(spanContext, attributes)); } /// <inheritdoc/> public ISpanBuilder AddLink(Link link) { if (link == null) { throw new ArgumentNullException(nameof(link)); } if (this.links == null) { this.links = new List<Link>(); } this.links.Add(link); return this; } /// <inheritdoc/> public ISpanBuilder SetRecordEvents(bool recordEvents) { this.recordEvents = recordEvents; return this; } public ISpanBuilder SetStartTimestamp(DateTimeOffset startTimestamp) { this.startTimestamp = startTimestamp; return this; } /// <inheritdoc/> public ISpan StartSpan() { var activityForSpan = this.CreateActivityForSpan(this.contextSource, this.parentSpan, this.parentSpanContext, this.parentActivity, this.fromActivity); if (this.startTimestamp == default) { this.startTimestamp = new DateTimeOffset(activityForSpan.StartTimeUtc); } bool sampledIn = MakeSamplingDecision( this.parentSpanContext, // it is updated in CreateActivityForSpan this.name, this.sampler, this.links, activityForSpan.TraceId, activityForSpan.SpanId, this.tracerConfiguration); if (sampledIn || this.recordEvents) { activityForSpan.ActivityTraceFlags |= ActivityTraceFlags.Recorded; } else { activityForSpan.ActivityTraceFlags &= ~ActivityTraceFlags.Recorded; } var childTracestate = Enumerable.Empty<KeyValuePair<string, string>>(); if (this.parentSpanContext != null && this.parentSpanContext.IsValid) { if (this.parentSpanContext.Tracestate != null && this.parentSpanContext.Tracestate.Any()) { childTracestate = this.parentSpanContext.Tracestate; } } else if (activityForSpan.TraceStateString != null) { var tracestate = new List<KeyValuePair<string, string>>(); if (TracestateUtils.AppendTracestate(activityForSpan.TraceStateString, tracestate)) { childTracestate = tracestate; } } var span = new Span( activityForSpan, childTracestate, this.kind, this.tracerConfiguration, this.spanProcessor, this.startTimestamp, ownsActivity: this.contextSource != ContextSource.Activity, this.libraryResource); if (activityForSpan.OperationName != this.name) { span.UpdateName(this.name); } LinkSpans(span, this.links); return span; } private static bool IsAnyParentLinkSampled(List<Link> parentLinks) { if (parentLinks != null) { foreach (var parentLink in parentLinks) { if ((parentLink.Context.TraceOptions & ActivityTraceFlags.Recorded) != 0) { return true; } } } return false; } private static void LinkSpans(ISpan span, List<Link> parentLinks) { if (parentLinks != null) { foreach (var link in parentLinks) { span.AddLink(link); } } } private static bool MakeSamplingDecision( SpanContext parent, string name, ISampler sampler, List<Link> parentLinks, ActivityTraceId traceId, ActivitySpanId spanId, TracerConfiguration tracerConfiguration) { // If users set a specific sampler in the SpanBuilder, use it. if (sampler != null) { return sampler.ShouldSample(parent, traceId, spanId, name, parentLinks).IsSampled; } // Use the default sampler if this is a root Span or this is an entry point Span (has remote // parent). if (parent == null || !parent.IsValid) { return tracerConfiguration .Sampler .ShouldSample(parent, traceId, spanId, name, parentLinks).IsSampled; } // Parent is always different than null because otherwise we use the default sampler. return (parent.TraceOptions & ActivityTraceFlags.Recorded) != 0 || IsAnyParentLinkSampled(parentLinks); } private static SpanContext ParentContextFromActivity(Activity activity) { if (activity.TraceId != default && activity.ParentSpanId != default) { List<KeyValuePair<string, string>> tracestate = null; if (!string.IsNullOrEmpty(activity.TraceStateString)) { tracestate = new List<KeyValuePair<string, string>>(); TracestateUtils.AppendTracestate(activity.TraceStateString, tracestate); } return new SpanContext( activity.TraceId, activity.ParentSpanId, ActivityTraceFlags.Recorded, tracestate); } return null; } private Activity CreateActivityForSpan(ContextSource contextSource, ISpan explicitParent, SpanContext remoteParent, Activity explicitParentActivity, Activity fromActivity) { Activity spanActivity = null; Activity originalActivity = Activity.Current; bool needRestoreOriginal = true; switch (contextSource) { case ContextSource.CurrentActivityParent: { // Activity will figure out its parent spanActivity = new Activity(this.name) .SetIdFormat(ActivityIdFormat.W3C) .Start(); // chances are, Activity.Current has span attached if (CurrentSpanUtils.CurrentSpan is Span currentSpan) { this.parentSpanContext = currentSpan.Context; } else { this.parentSpanContext = ParentContextFromActivity(spanActivity); } break; } case ContextSource.ExplicitActivityParent: { spanActivity = new Activity(this.name) .SetParentId(this.parentActivity.TraceId, this.parentActivity.SpanId, this.parentActivity.ActivityTraceFlags) .Start(); spanActivity.TraceStateString = this.parentActivity.TraceStateString; this.parentSpanContext = ParentContextFromActivity(spanActivity); break; } case ContextSource.NoParent: { spanActivity = new Activity(this.name) .SetIdFormat(ActivityIdFormat.W3C) .SetParentId(" ") .Start(); this.parentSpanContext = null; break; } case ContextSource.Activity: { this.parentSpanContext = ParentContextFromActivity(this.fromActivity); spanActivity = this.fromActivity; needRestoreOriginal = false; break; } case ContextSource.ExplicitRemoteParent: { spanActivity = new Activity(this.name); if (this.parentSpanContext != null && this.parentSpanContext.IsValid) { spanActivity.SetParentId(this.parentSpanContext.TraceId, this.parentSpanContext.SpanId, this.parentSpanContext.TraceOptions); spanActivity.TraceStateString = TracestateUtils.GetString(this.parentSpanContext.Tracestate); } spanActivity.SetIdFormat(ActivityIdFormat.W3C); spanActivity.Start(); break; } case ContextSource.ExplicitSpanParent: { spanActivity = new Activity(this.name); if (this.parentSpan.Context.IsValid) { spanActivity.SetParentId(this.parentSpan.Context.TraceId, this.parentSpan.Context.SpanId, this.parentSpan.Context.TraceOptions); spanActivity.TraceStateString = TracestateUtils.GetString(this.parentSpan.Context.Tracestate); } spanActivity.SetIdFormat(ActivityIdFormat.W3C); spanActivity.Start(); this.parentSpanContext = this.parentSpan.Context; break; } default: throw new ArgumentException($"Unknown parentType {contextSource}"); } if (needRestoreOriginal) { // Activity Start always puts Activity on top of Current stack // in OpenTelemetry we ask users to enable implicit propagation by calling WithSpan // it will set Current Activity and attach span to it. // we need to work with .NET team to allow starting Activities without updating Current // As a workaround here we are undoing updating Current Activity.Current = originalActivity; } return spanActivity; } } }
1
12,365
can we delete this file altogether?
open-telemetry-opentelemetry-dotnet
.cs
@@ -59,7 +59,9 @@ func InitCoverage(name string) { } // Set up the unit test framework with the required arguments to activate test coverage. - flag.CommandLine.Parse([]string{"-test.coverprofile", tempCoveragePath()}) + if err := flag.CommandLine.Parse([]string{"-test.coverprofile", tempCoveragePath()}); err != nil { + panic(err) + } // Begin periodic logging go wait.Forever(FlushCoverage, flushInterval)
1
/* Copyright 2020 The cert-manager 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 coverage provides tools for coverage-instrumented binaries to collect and // flush coverage information. package coverage import ( "flag" "fmt" "os" "testing" "time" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/klog/v2" ) var coverageFile string // tempCoveragePath returns a temporary file to write coverage information to. // The file is in the same directory as the destination, ensuring os.Rename will work. func tempCoveragePath() string { return coverageFile + ".tmp" } // InitCoverage is called from the dummy unit test to prepare Go's coverage framework. // Clients should never need to call it. func InitCoverage(name string) { // We read the coverage destination in from the COVERPROFILE env var, // or if it's empty we just use a default in /tmp coverageFile = os.Getenv("COVERPROFILE") if coverageFile == "" { coverageFile = "/tmp/cm-" + name + ".cov" } fmt.Println("Dumping coverage information to " + coverageFile) flushInterval := 5 * time.Second requestedInterval := os.Getenv("COVERAGE_FLUSH_INTERVAL") if requestedInterval != "" { if duration, err := time.ParseDuration(requestedInterval); err == nil { flushInterval = duration } else { panic("Invalid COVERAGE_FLUSH_INTERVAL value; try something like '30s'.") } } // Set up the unit test framework with the required arguments to activate test coverage. flag.CommandLine.Parse([]string{"-test.coverprofile", tempCoveragePath()}) // Begin periodic logging go wait.Forever(FlushCoverage, flushInterval) } // FlushCoverage flushes collected coverage information to disk. // The destination file is configured at startup and cannot be changed. // Calling this function also sends a line like "coverage: 5% of statements" to stdout. func FlushCoverage() { // We're not actually going to run any tests, but we need Go to think we did so it writes // coverage information to disk. To achieve this, we create a bunch of empty test suites and // have it "run" them. tests := []testing.InternalTest{} benchmarks := []testing.InternalBenchmark{} examples := []testing.InternalExample{} var deps fakeTestDeps dummyRun := testing.MainStart(deps, tests, benchmarks, examples) dummyRun.Run() // Once it writes to the temporary path, we move it to the intended path. // This gets us atomic updates from the perspective of another process trying to access // the file. if err := os.Rename(tempCoveragePath(), coverageFile); err != nil { klog.Errorf("Couldn't move coverage file from %s to %s", coverageFile, tempCoveragePath()) } }
1
26,677
Suggestion: log some additional info here so we know where we are i.e 'Failed to prepare coverage framework..'
jetstack-cert-manager
go
@@ -0,0 +1,7 @@ +namespace Datadog.Trace +{ + internal static class TracerConstants + { + public const string Language = "dotnet"; + } +}
1
1
15,843
There didn't seem to be any good place to put constants that are .NET Tracer-specific, so I created this internal static class. If there's a better place, let me know.
DataDog-dd-trace-dotnet
.cs
@@ -0,0 +1,19 @@ +package config + +import ( + "github.com/kubeedge/beehive/pkg/common/config" + "github.com/kubeedge/beehive/pkg/common/log" + "github.com/kubeedge/kubeedge/cloud/edgecontroller/pkg/devicecontroller/constants" +) + +// UpdateDeviceStatusBuffer is the size of channel which save update device status message from edge +var UpdateDeviceStatusBuffer int + +func init() { + if psb, err := config.CONFIG.GetValue("devicecontroller.update-device-status-buffer").ToInt(); err != nil { + UpdateDeviceStatusBuffer = constants.DefaultUpdateDeviceStatusBuffer + } else { + UpdateDeviceStatusBuffer = psb + } + log.LOGGER.Infof("update device status buffer: %d", UpdateDeviceStatusBuffer) +}
1
1
9,879
Log message should be started with upper-case word.
kubeedge-kubeedge
go
@@ -126,7 +126,7 @@ namespace NLog.Targets /// Gets or sets the layout that renders event ID. /// </summary> /// <docgen category='Event Log Options' order='10' /> - public Layout EventId { get; set; } + public Layout<int> EventId { get; set; } /// <summary> /// Gets or sets the layout that renders event Category.
1
// // Copyright (c) 2004-2020 Jaroslaw Kowalski <[email protected]>, Kim Christensen, Julian Verdurmen // // 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 Jaroslaw Kowalski 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. // #if !SILVERLIGHT && !__IOS__ && !__ANDROID__ && (!NETSTANDARD || WindowsEventLogPackage) namespace NLog.Targets { using System; using System.ComponentModel; using System.Diagnostics; using Internal.Fakeables; using NLog.Common; using NLog.Config; using NLog.Layouts; /// <summary> /// Writes log message to the Event Log. /// </summary> /// <seealso href="https://github.com/nlog/nlog/wiki/EventLog-target">Documentation on NLog Wiki</seealso> /// <example> /// <p> /// To set up the target in the <a href="config.html">configuration file</a>, /// use the following syntax: /// </p> /// <code lang="XML" source="examples/targets/Configuration File/EventLog/NLog.config" /> /// <p> /// This assumes just one target and a single rule. More configuration /// options are described <a href="config.html">here</a>. /// </p> /// <p> /// To set up the log target programmatically use code like this: /// </p> /// <code lang="C#" source="examples/targets/Configuration API/EventLog/Simple/Example.cs" /> /// </example> [Target("EventLog")] public class EventLogTarget : TargetWithLayout, IInstallable { /// <summary> /// Max size in characters (limitation of the EventLog API). /// </summary> internal const int EventLogMaxMessageLength = 16384; private readonly IEventLogWrapper _eventLogWrapper; /// <summary> /// Initializes a new instance of the <see cref="EventLogTarget"/> class. /// </summary> public EventLogTarget() : this(null, null) { } /// <summary> /// Initializes a new instance of the <see cref="EventLogTarget"/> class. /// </summary> /// <param name="name">Name of the target.</param> public EventLogTarget(string name) : this(null, null) { Name = name; } /// <summary> /// Initializes a new instance of the <see cref="EventLogTarget"/> class. /// </summary> /// <param name="appDomain"><see cref="IAppDomain"/>.<see cref="IAppDomain.FriendlyName"/> to be used as Source.</param> [Obsolete("This constructor will be removed in NLog 5. Marked obsolete on NLog 4.6")] public EventLogTarget(IAppDomain appDomain) : this(null, appDomain) { } /// <summary> /// Initializes a new instance of the <see cref="EventLogTarget"/> class. /// </summary> internal EventLogTarget(IEventLogWrapper eventLogWrapper, IAppDomain appDomain) { _eventLogWrapper = eventLogWrapper ?? new EventLogWrapper(); appDomain = appDomain ?? LogFactory.CurrentAppDomain; Source = appDomain.FriendlyName; Log = "Application"; MachineName = "."; MaxMessageLength = EventLogMaxMessageLength; OptimizeBufferReuse = GetType() == typeof(EventLogTarget); // Class not sealed, reduce breaking changes } /// <summary> /// Gets or sets the name of the machine on which Event Log service is running. /// </summary> /// <docgen category='Event Log Options' order='10' /> [DefaultValue(".")] public string MachineName { get; set; } /// <summary> /// Gets or sets the layout that renders event ID. /// </summary> /// <docgen category='Event Log Options' order='10' /> public Layout EventId { get; set; } /// <summary> /// Gets or sets the layout that renders event Category. /// </summary> /// <docgen category='Event Log Options' order='10' /> public Layout Category { get; set; } /// <summary> /// Optional entry type. When not set, or when not convertible to <see cref="EventLogEntryType"/> then determined by <see cref="NLog.LogLevel"/> /// </summary> /// <docgen category='Event Log Options' order='10' /> public Layout EntryType { get; set; } /// <summary> /// Gets or sets the value to be used as the event Source. /// </summary> /// <remarks> /// By default this is the friendly name of the current AppDomain. /// </remarks> /// <docgen category='Event Log Options' order='10' /> public Layout Source { get; set; } /// <summary> /// Gets or sets the name of the Event Log to write to. This can be System, Application or any user-defined name. /// </summary> /// <docgen category='Event Log Options' order='10' /> [DefaultValue("Application")] public string Log { get; set; } /// <summary> /// Gets or sets the message length limit to write to the Event Log. /// </summary> /// <remarks><value>MaxMessageLength</value> cannot be zero or negative</remarks> /// <docgen category='Event Log Options' order='10' /> [DefaultValue(EventLogMaxMessageLength)] public int MaxMessageLength { get => _maxMessageLength; set { if (value <= 0) throw new ArgumentException("MaxMessageLength cannot be zero or negative."); _maxMessageLength = value; } } private int _maxMessageLength; /// <summary> /// Gets or sets the maximum Event log size in kilobytes. /// </summary> /// <remarks> /// <value>MaxKilobytes</value> cannot be less than 64 or greater than 4194240 or not a multiple of 64. /// If <c>null</c>, the value will not be specified while creating the Event log. /// </remarks> /// <docgen category='Event Log Options' order='10' /> [DefaultValue(null)] public long? MaxKilobytes { get => _maxKilobytes; set { if (value != null && (value < 64 || value > 4194240 || (value % 64 != 0))) // Event log API restrictions throw new ArgumentException("MaxKilobytes must be a multiple of 64, and between 64 and 4194240"); _maxKilobytes = value; } } private long? _maxKilobytes; /// <summary> /// Gets or sets the action to take if the message is larger than the <see cref="MaxMessageLength"/> option. /// </summary> /// <docgen category='Event Log Overflow Action' order='10' /> [DefaultValue(EventLogTargetOverflowAction.Truncate)] public EventLogTargetOverflowAction OnOverflow { get; set; } /// <summary> /// Performs installation which requires administrative permissions. /// </summary> /// <param name="installationContext">The installation context.</param> public void Install(InstallationContext installationContext) { // always throw error to keep backwards compatible behavior. CreateEventSourceIfNeeded(GetFixedSource(), true); } /// <summary> /// Performs uninstallation which requires administrative permissions. /// </summary> /// <param name="installationContext">The installation context.</param> public void Uninstall(InstallationContext installationContext) { var fixedSource = GetFixedSource(); if (string.IsNullOrEmpty(fixedSource)) { InternalLogger.Debug("EventLogTarget(Name={0}): Skipping removing of event source because it contains layout renderers", Name); } else { _eventLogWrapper.DeleteEventSource(fixedSource, MachineName); } } /// <summary> /// Determines whether the item is installed. /// </summary> /// <param name="installationContext">The installation context.</param> /// <returns> /// Value indicating whether the item is installed or null if it is not possible to determine. /// </returns> public bool? IsInstalled(InstallationContext installationContext) { var fixedSource = GetFixedSource(); if (!string.IsNullOrEmpty(fixedSource)) { return _eventLogWrapper.SourceExists(fixedSource, MachineName); } InternalLogger.Debug("EventLogTarget(Name={0}): Unclear if event source exists because it contains layout renderers", Name); return null; //unclear! } /// <summary> /// Initializes the target. /// </summary> protected override void InitializeTarget() { base.InitializeTarget(); CreateEventSourceIfNeeded(GetFixedSource(), false); } /// <summary> /// Writes the specified logging event to the event log. /// </summary> /// <param name="logEvent">The logging event.</param> protected override void Write(LogEventInfo logEvent) { string message = RenderLogEvent(Layout, logEvent); EventLogEntryType entryType = GetEntryType(logEvent); int eventId = 0; string renderEventId = RenderLogEvent(EventId, logEvent); if (!string.IsNullOrEmpty(renderEventId) && !int.TryParse(renderEventId, out eventId)) { InternalLogger.Warn("EventLogTarget(Name={0}): WriteEntry failed to parse EventId={1}", Name, renderEventId); } short category = 0; string renderCategory = RenderLogEvent(Category, logEvent); if (!string.IsNullOrEmpty(renderCategory) && !short.TryParse(renderCategory, out category)) { InternalLogger.Warn("EventLogTarget(Name={0}): WriteEntry failed to parse Category={1}", Name, renderCategory); } var eventLogSource = RenderLogEvent(Source, logEvent); if (string.IsNullOrEmpty(eventLogSource)) { InternalLogger.Warn("EventLogTarget(Name={0}): WriteEntry discarded because Source rendered as empty string", Name); return; } // limitation of EventLog API if (message.Length > MaxMessageLength) { if (OnOverflow == EventLogTargetOverflowAction.Truncate) { message = message.Substring(0, MaxMessageLength); WriteEntry(eventLogSource, message, entryType, eventId, category); } else if (OnOverflow == EventLogTargetOverflowAction.Split) { for (int offset = 0; offset < message.Length; offset += MaxMessageLength) { string chunk = message.Substring(offset, Math.Min(MaxMessageLength, (message.Length - offset))); WriteEntry(eventLogSource, chunk, entryType, eventId, category); } } else if (OnOverflow == EventLogTargetOverflowAction.Discard) { // message should not be written InternalLogger.Debug("EventLogTarget(Name={0}): WriteEntry discarded because too big message size: {1}", Name, message.Length); } } else { WriteEntry(eventLogSource, message, entryType, eventId, category); } } private void WriteEntry(string eventLogSource, string message, EventLogEntryType entryType, int eventId, short category) { var isCacheUpToDate = _eventLogWrapper.IsEventLogAssociated && _eventLogWrapper.Log == Log && _eventLogWrapper.MachineName == MachineName && _eventLogWrapper.Source == eventLogSource; if (!isCacheUpToDate) { InternalLogger.Debug("EventLogTarget(Name={0}): Refresh EventLog Source {1} and Log {2}", Name, eventLogSource, Log); _eventLogWrapper.AssociateNewEventLog(Log, MachineName, eventLogSource); try { if (!_eventLogWrapper.SourceExists(eventLogSource, MachineName)) { InternalLogger.Warn("EventLogTarget(Name={0}): Source {1} does not exist", Name, eventLogSource); } else { var currentLogName = _eventLogWrapper.LogNameFromSourceName(eventLogSource, MachineName); if (!currentLogName.Equals(Log, StringComparison.CurrentCultureIgnoreCase)) { InternalLogger.Debug("EventLogTarget(Name={0}): Source {1} should be mapped to Log {2}, but EventLog.LogNameFromSourceName returns {3}", Name, eventLogSource, Log, currentLogName); } } } catch (Exception ex) { if (LogManager.ThrowExceptions) throw; InternalLogger.Warn(ex, "EventLogTarget(Name={0}): Exception thrown when checking if Source {1} and LogName {2} are valid", Name, eventLogSource, Log); } } _eventLogWrapper.WriteEntry(message, entryType, eventId, category); } /// <summary> /// Get the entry type for logging the message. /// </summary> /// <param name="logEvent">The logging event - for rendering the <see cref="EntryType"/></param> private EventLogEntryType GetEntryType(LogEventInfo logEvent) { string renderEntryType = RenderLogEvent(EntryType, logEvent); if (!string.IsNullOrEmpty(renderEntryType)) { // try parse, if fail, determine auto if (ConversionHelpers.TryParseEnum(renderEntryType, out EventLogEntryType eventLogEntryType)) { return eventLogEntryType; } InternalLogger.Warn("EventLogTarget(Name={0}): WriteEntry failed to parse EntryType={1}", Name, renderEntryType); } // determine auto if (logEvent.Level >= LogLevel.Error) { return EventLogEntryType.Error; } if (logEvent.Level >= LogLevel.Warn) { return EventLogEntryType.Warning; } return EventLogEntryType.Information; } /// <summary> /// Get the source, if and only if the source is fixed. /// </summary> /// <returns><c>null</c> when not <see cref="SimpleLayout.IsFixedText"/></returns> /// <remarks>Internal for unit tests</remarks> internal string GetFixedSource() { if (Source is SimpleLayout simpleLayout && simpleLayout.IsFixedText) { return simpleLayout.FixedText; } return null; } /// <summary> /// (re-)create an event source, if it isn't there. Works only with fixed source names. /// </summary> /// <param name="fixedSource">The source name. If source is not fixed (see <see cref="SimpleLayout.IsFixedText"/>, then pass <c>null</c> or <see cref="string.Empty"/>.</param> /// <param name="alwaysThrowError">always throw an Exception when there is an error</param> private void CreateEventSourceIfNeeded(string fixedSource, bool alwaysThrowError) { if (string.IsNullOrEmpty(fixedSource)) { InternalLogger.Debug("EventLogTarget(Name={0}): Skipping creation of event source because it contains layout renderers", Name); // we can only create event sources if the source is fixed (no layout) return; } // if we throw anywhere, we remain non-operational try { if (_eventLogWrapper.SourceExists(fixedSource, MachineName)) { string currentLogName = _eventLogWrapper.LogNameFromSourceName(fixedSource, MachineName); if (!currentLogName.Equals(Log, StringComparison.CurrentCultureIgnoreCase)) { InternalLogger.Debug("EventLogTarget(Name={0}): Updating source {1} to use log {2}, instead of {3} (Computer restart is needed)", Name, fixedSource, Log, currentLogName); // re-create the association between Log and Source _eventLogWrapper.DeleteEventSource(fixedSource, MachineName); var eventSourceCreationData = new EventSourceCreationData(fixedSource, Log) { MachineName = MachineName }; _eventLogWrapper.CreateEventSource(eventSourceCreationData); } } else { InternalLogger.Debug("EventLogTarget(Name={0}): Creating source {1} to use log {2}", Name, fixedSource, Log); var eventSourceCreationData = new EventSourceCreationData(fixedSource, Log) { MachineName = MachineName }; _eventLogWrapper.CreateEventSource(eventSourceCreationData); } _eventLogWrapper.AssociateNewEventLog(Log, MachineName, fixedSource); if (MaxKilobytes.HasValue && _eventLogWrapper.MaximumKilobytes < MaxKilobytes) { _eventLogWrapper.MaximumKilobytes = MaxKilobytes.Value; } } catch (Exception exception) { InternalLogger.Error(exception, "EventLogTarget(Name={0}): Error when connecting to EventLog. Source={1} in Log={2}", Name, fixedSource, Log); if (alwaysThrowError || LogManager.ThrowExceptions) { throw; } } } /// <summary> /// A wrapper for Windows event log. /// </summary> internal interface IEventLogWrapper { #region Instance methods /// <summary> /// A wrapper for the property <see cref="EventLog.Source"/>. /// </summary> string Source { get; } /// <summary> /// A wrapper for the property <see cref="EventLog.Log"/>. /// </summary> string Log { get; } /// <summary> /// A wrapper for the property <see cref="EventLog.MachineName"/>. /// </summary> string MachineName { get; } /// <summary> /// A wrapper for the property <see cref="EventLog.MaximumKilobytes"/>. /// </summary> long MaximumKilobytes { get; set; } /// <summary> /// Indicates whether an event log instance is associated. /// </summary> bool IsEventLogAssociated { get; } /// <summary> /// A wrapper for the method <see cref="EventLog.WriteEntry(string, EventLogEntryType, int, short)"/>. /// </summary> void WriteEntry(string message, EventLogEntryType entryType, int eventId, short category); #endregion #region "Static" methods /// <summary> /// Creates a new association with an instance of the event log. /// </summary> void AssociateNewEventLog(string logName, string machineName, string source); /// <summary> /// A wrapper for the static method <see cref="EventLog.DeleteEventSource(string, string)"/>. /// </summary> void DeleteEventSource(string source, string machineName); /// <summary> /// A wrapper for the static method <see cref="EventLog.SourceExists(string, string)"/>. /// </summary> bool SourceExists(string source, string machineName); /// <summary> /// A wrapper for the static method <see cref="EventLog.LogNameFromSourceName(string, string)"/>. /// </summary> string LogNameFromSourceName(string source, string machineName); /// <summary> /// A wrapper for the static method <see cref="EventLog.CreateEventSource(EventSourceCreationData)"/>. /// </summary> void CreateEventSource(EventSourceCreationData sourceData); #endregion } /// <summary> /// The implementation of <see cref="IEventLogWrapper"/>, that uses Windows <see cref="EventLog"/>. /// </summary> private sealed class EventLogWrapper : IEventLogWrapper, IDisposable { private EventLog _windowsEventLog; #region Instance methods /// <inheritdoc /> public string Source { get; private set; } /// <inheritdoc /> public string Log { get; private set; } /// <inheritdoc /> public string MachineName { get; private set; } /// <inheritdoc /> public long MaximumKilobytes { get => _windowsEventLog.MaximumKilobytes; set => _windowsEventLog.MaximumKilobytes = value; } /// <inheritdoc /> public bool IsEventLogAssociated => _windowsEventLog != null; /// <inheritdoc /> public void WriteEntry(string message, EventLogEntryType entryType, int eventId, short category) => _windowsEventLog.WriteEntry(message, entryType, eventId, category); #endregion #region "Static" methods /// <inheritdoc /> /// <summary> /// Creates a new association with an instance of Windows <see cref="EventLog"/>. /// </summary> public void AssociateNewEventLog(string logName, string machineName, string source) { var windowsEventLog = _windowsEventLog; _windowsEventLog = new EventLog(logName, machineName, source); Source = source; Log = logName; MachineName = machineName; if (windowsEventLog != null) windowsEventLog.Dispose(); } /// <inheritdoc /> public void DeleteEventSource(string source, string machineName) => EventLog.DeleteEventSource(source, machineName); /// <inheritdoc /> public bool SourceExists(string source, string machineName) => EventLog.SourceExists(source, machineName); /// <inheritdoc /> public string LogNameFromSourceName(string source, string machineName) => EventLog.LogNameFromSourceName(source, machineName); /// <inheritdoc /> public void CreateEventSource(EventSourceCreationData sourceData) => EventLog.CreateEventSource(sourceData); public void Dispose() { _windowsEventLog?.Dispose(); _windowsEventLog = null; } #endregion } } } #endif
1
20,125
changes for example usage in this class
NLog-NLog
.cs
@@ -1,4 +1,4 @@ -define(['browser', 'css!./emby-collapse', 'registerElement', 'emby-button'], function (browser) { +define(['browser', 'css!elements/emby-collapse/emby-collapse', 'registerElement', 'emby-button'], function (browser) { 'use strict'; var EmbyButtonPrototype = Object.create(HTMLDivElement.prototype);
1
define(['browser', 'css!./emby-collapse', 'registerElement', 'emby-button'], function (browser) { 'use strict'; var EmbyButtonPrototype = Object.create(HTMLDivElement.prototype); function slideDownToShow(button, elem) { elem.classList.remove('hide'); elem.classList.add('expanded'); elem.style.height = 'auto'; var height = elem.offsetHeight + 'px'; elem.style.height = '0'; // trigger reflow var newHeight = elem.offsetHeight; elem.style.height = height; setTimeout(function () { if (elem.classList.contains('expanded')) { elem.classList.remove('hide'); } else { elem.classList.add('hide'); } elem.style.height = 'auto'; }, 300); var icon = button.querySelector('i'); //icon.innerHTML = 'expand_less'; icon.classList.add('emby-collapse-expandIconExpanded'); } function slideUpToHide(button, elem) { elem.style.height = elem.offsetHeight + 'px'; // trigger reflow var newHeight = elem.offsetHeight; elem.classList.remove('expanded'); elem.style.height = '0'; setTimeout(function () { if (elem.classList.contains('expanded')) { elem.classList.remove('hide'); } else { elem.classList.add('hide'); } }, 300); var icon = button.querySelector('i'); //icon.innerHTML = 'expand_more'; icon.classList.remove('emby-collapse-expandIconExpanded'); } function onButtonClick(e) { var button = this; var collapseContent = button.parentNode.querySelector('.collapseContent'); if (collapseContent.expanded) { collapseContent.expanded = false; slideUpToHide(button, collapseContent); } else { collapseContent.expanded = true; slideDownToShow(button, collapseContent); } } EmbyButtonPrototype.attachedCallback = function () { if (this.classList.contains('emby-collapse')) { return; } this.classList.add('emby-collapse'); var collapseContent = this.querySelector('.collapseContent'); if (collapseContent) { collapseContent.classList.add('hide'); } var title = this.getAttribute('title'); var html = '<button is="emby-button" type="button" on-click="toggleExpand" id="expandButton" class="emby-collapsible-button iconRight"><h3 class="emby-collapsible-title" title="' + title + '">' + title + '</h3><i class="material-icons emby-collapse-expandIcon expand_more"></i></button>'; this.insertAdjacentHTML('afterbegin', html); var button = this.querySelector('.emby-collapsible-button'); button.addEventListener('click', onButtonClick); if (this.getAttribute('data-expanded') === 'true') { onButtonClick.call(button); } }; document.registerElement('emby-collapse', { prototype: EmbyButtonPrototype, extends: 'div' }); });
1
12,939
I know frameworks that support current directory when loading dependencies, is this a limitation of the requirejs loader or can we fix it somehow?
jellyfin-jellyfin-web
js
@@ -164,6 +164,10 @@ func (a *FakeWebAPI) AddApplication(ctx context.Context, req *webservice.AddAppl return &webservice.AddApplicationResponse{}, nil } +func (a *FakeWebAPI) EnableApplication(ctx context.Context, req *webservice.EnableApplicationRequest) (*webservice.EnableApplicationResponse, error) { + return &webservice.EnableApplicationResponse{}, nil +} + func (a *FakeWebAPI) DisableApplication(ctx context.Context, req *webservice.DisableApplicationRequest) (*webservice.DisableApplicationResponse, error) { return &webservice.DisableApplicationResponse{}, nil }
1
// Copyright 2020 The PipeCD 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 api import ( "context" "fmt" "time" "github.com/google/uuid" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" "github.com/pipe-cd/pipe/pkg/app/api/service/webservice" "github.com/pipe-cd/pipe/pkg/model" ) const ( fakeProjectID = "debug-project" ) // FakeWebAPI implements the fake behaviors for the gRPC definitions of WebAPI. type FakeWebAPI struct { } // NewFakeWebAPI creates a new FakeWebAPI instance. func NewFakeWebAPI() *FakeWebAPI { return &FakeWebAPI{} } // Register registers all handling of this service into the specified gRPC server. func (a *FakeWebAPI) Register(server *grpc.Server) { webservice.RegisterWebServiceServer(server, a) } func (a *FakeWebAPI) AddEnvironment(ctx context.Context, req *webservice.AddEnvironmentRequest) (*webservice.AddEnvironmentResponse, error) { return nil, status.Error(codes.Unimplemented, "") } func (a *FakeWebAPI) UpdateEnvironmentDesc(ctx context.Context, req *webservice.UpdateEnvironmentDescRequest) (*webservice.UpdateEnvironmentDescResponse, error) { return nil, status.Error(codes.Unimplemented, "") } func (a *FakeWebAPI) ListEnvironments(ctx context.Context, req *webservice.ListEnvironmentsRequest) (*webservice.ListEnvironmentsResponse, error) { now := time.Now() envs := []*model.Environment{ { Id: fmt.Sprintf("%s:%s", fakeProjectID, "development"), Name: "development", Desc: "For development", ProjectId: fakeProjectID, CreatedAt: now.Unix(), UpdatedAt: now.Unix(), }, { Id: fmt.Sprintf("%s:%s", fakeProjectID, "staging"), Name: "staging", Desc: "For staging", ProjectId: fakeProjectID, CreatedAt: now.Unix(), UpdatedAt: now.Unix(), }, { Id: fmt.Sprintf("%s:%s", fakeProjectID, "production"), Name: "production", Desc: "For production", ProjectId: fakeProjectID, CreatedAt: now.Unix(), UpdatedAt: now.Unix(), }, } return &webservice.ListEnvironmentsResponse{ Environments: envs, }, nil } func (a *FakeWebAPI) RegisterPiped(ctx context.Context, req *webservice.RegisterPipedRequest) (*webservice.RegisterPipedResponse, error) { return &webservice.RegisterPipedResponse{ Id: "e357d99f-0f83-4ce0-8c8b-27f11f432ef9", Key: "9bf9752a-54a2-451a-a541-444add56f96b", }, nil } func (a *FakeWebAPI) DisablePiped(ctx context.Context, req *webservice.DisablePipedRequest) (*webservice.DisablePipedResponse, error) { return nil, status.Error(codes.Unimplemented, "") } func (a *FakeWebAPI) ListPipeds(ctx context.Context, req *webservice.ListPipedsRequest) (*webservice.ListPipedsResponse, error) { now := time.Now() pipeds := []*webservice.Piped{ { Id: "492220b1-c080-4781-9e55-7e278760e0ef", Desc: "piped for debug 1", Disabled: false, CreatedAt: now.Unix(), UpdatedAt: now.Unix(), }, { Id: "bdd71c9e-5406-46fb-a0e4-b2124ea1c1ea", Desc: "piped for debug 2", Disabled: false, CreatedAt: now.Unix(), UpdatedAt: now.Unix(), }, { Id: "42e9fa90-22c1-4436-b10c-094044329c27", Disabled: false, CreatedAt: now.Unix(), UpdatedAt: now.Unix(), }, } if req.WithStatus { pipeds[0].Status = webservice.PipedConnectionStatus_PIPED_CONNECTION_ONLINE pipeds[1].Status = webservice.PipedConnectionStatus_PIPED_CONNECTION_ONLINE pipeds[2].Status = webservice.PipedConnectionStatus_PIPED_CONNECTION_OFFLINE } return &webservice.ListPipedsResponse{ Pipeds: pipeds, }, nil } func (a *FakeWebAPI) GetPiped(ctx context.Context, req *webservice.GetPipedRequest) (*webservice.GetPipedResponse, error) { now := time.Now() return &webservice.GetPipedResponse{ Piped: &webservice.Piped{ Id: "492220b1-c080-4781-9e55-7e278760e0ef", Desc: "piped for debug 1", ProjectId: fakeProjectID, Version: "debug-version", StartedAt: now.Add(-30 * time.Minute).Unix(), CloudProviders: []*model.Piped_CloudProvider{ { Name: "kubernetes-default", Type: model.CloudProviderKubernetes.String(), }, }, RepositoryIds: []string{ "piped-repo-1", "piped-repo-2", }, Disabled: false, CreatedAt: now.Unix(), UpdatedAt: now.Unix(), }, }, nil } func (a *FakeWebAPI) AddApplication(ctx context.Context, req *webservice.AddApplicationRequest) (*webservice.AddApplicationResponse, error) { return &webservice.AddApplicationResponse{}, nil } func (a *FakeWebAPI) DisableApplication(ctx context.Context, req *webservice.DisableApplicationRequest) (*webservice.DisableApplicationResponse, error) { return &webservice.DisableApplicationResponse{}, nil } func (a *FakeWebAPI) ListApplications(ctx context.Context, req *webservice.ListApplicationsRequest) (*webservice.ListApplicationsResponse, error) { now := time.Now() fakeApplications := []*model.Application{ { Id: fmt.Sprintf("%s:%s:%s", fakeProjectID, "development", "debug-app"), Name: "debug-app", EnvId: fmt.Sprintf("%s:%s", fakeProjectID, "development"), PipedId: "debug-piped", ProjectId: fakeProjectID, Kind: model.ApplicationKind_KUBERNETES, GitPath: &model.ApplicationGitPath{ RepoId: "debug", Path: "k8s", }, CloudProvider: "kubernetes-default", MostRecentlySuccessfulDeployment: &model.ApplicationDeploymentReference{ DeploymentId: "debug-deployment-id-01", Trigger: &model.DeploymentTrigger{ Commit: &model.Commit{ Hash: "3808585b46f1e90196d7ffe8dd04c807a251febc", Message: "Add web page routing (#133)", Author: "cakecatz", Branch: "master", CreatedAt: now.Unix(), }, Commander: "", Timestamp: now.Unix(), }, Version: "v0.1.0", StartedAt: now.Add(-3 * 24 * time.Hour).Unix(), CompletedAt: now.Add(-3 * 24 * time.Hour).Unix(), }, SyncState: &model.ApplicationSyncState{ Status: model.ApplicationSyncStatus_SYNCED, ShortReason: "Short resson", Reason: "Reason", HeadDeploymentId: "debug-deployment-id-01", Timestamp: now.Unix(), }, Disabled: false, CreatedAt: now.Unix(), UpdatedAt: now.Unix(), }, } return &webservice.ListApplicationsResponse{ Applications: fakeApplications, }, nil } func (a *FakeWebAPI) SyncApplication(ctx context.Context, req *webservice.SyncApplicationRequest) (*webservice.SyncApplicationResponse, error) { return &webservice.SyncApplicationResponse{ CommandId: uuid.New().String(), }, nil } func (a *FakeWebAPI) GetApplication(ctx context.Context, req *webservice.GetApplicationRequest) (*webservice.GetApplicationResponse, error) { now := time.Now() application := model.Application{ Id: fmt.Sprintf("%s:%s:%s", fakeProjectID, "development", "debug-app"), Name: "debug-app", EnvId: fmt.Sprintf("%s:%s", fakeProjectID, "development"), PipedId: "debug-piped", ProjectId: fakeProjectID, Kind: model.ApplicationKind_KUBERNETES, GitPath: &model.ApplicationGitPath{ RepoId: "debug", Path: "k8s", }, CloudProvider: "kubernetes-default", MostRecentlySuccessfulDeployment: &model.ApplicationDeploymentReference{ DeploymentId: "debug-deployment-id-01", Trigger: &model.DeploymentTrigger{ Commit: &model.Commit{ Hash: "3808585b46f1e90196d7ffe8dd04c807a251febc", Message: "Add web page routing (#133)", Author: "cakecatz", Branch: "master", CreatedAt: now.Unix(), }, Commander: "", Timestamp: now.Unix(), }, Version: "v0.1.0", StartedAt: now.Add(-3 * 24 * time.Hour).Unix(), CompletedAt: now.Add(-3 * 24 * time.Hour).Unix(), }, SyncState: &model.ApplicationSyncState{ Status: model.ApplicationSyncStatus_SYNCED, ShortReason: "Short resson", Reason: "Reason", HeadDeploymentId: "debug-deployment-id-01", Timestamp: now.Unix(), }, Disabled: false, CreatedAt: now.Unix(), UpdatedAt: now.Unix(), } return &webservice.GetApplicationResponse{ Application: &application, }, nil } func (a *FakeWebAPI) ListDeployments(ctx context.Context, req *webservice.ListDeploymentsRequest) (*webservice.ListDeploymentsResponse, error) { now := time.Now() deploymentTime := now fakeDeployments := make([]*model.Deployment, 15) for i := 0; i < 15; i++ { // 5 hour intervals deploymentTime := deploymentTime.Add(time.Duration(-5*i) * time.Hour) fakeDeployments[i] = &model.Deployment{ Id: fmt.Sprintf("debug-deployment-id-%02d", i), ApplicationId: fmt.Sprintf("%s:%s:%s", fakeProjectID, "development", "debug-app"), EnvId: fmt.Sprintf("%s:%s", fakeProjectID, "development"), PipedId: "debug-piped", ProjectId: fakeProjectID, GitPath: &model.ApplicationGitPath{ RepoId: "debug", Path: "k8s", }, Trigger: &model.DeploymentTrigger{ Commit: &model.Commit{ Hash: "3808585b46f1e90196d7ffe8dd04c807a251febc", Message: "Add web page routing (#133)", Author: "cakecatz", Branch: "master", CreatedAt: deploymentTime.Unix(), }, Commander: "", Timestamp: deploymentTime.Unix(), }, RunningCommitHash: "3808585b46f1e90196d7ffe8dd04c807a251febc", Description: fmt.Sprintf("This deployment is debug-%02d", i), Status: model.DeploymentStatus_DEPLOYMENT_SUCCESS, Stages: []*model.PipelineStage{ { Id: "fake-stage-id-0-0", Name: model.StageK8sCanaryRollout.String(), Index: 0, Predefined: true, Status: model.StageStatus_STAGE_SUCCESS, RetriedCount: 0, CompletedAt: now.Unix(), CreatedAt: now.Unix(), UpdatedAt: now.Unix(), }, { Id: "fake-stage-id-1-0", Name: model.StageK8sCanaryRollout.String(), Index: 0, Predefined: true, Requires: []string{ "fake-stage-id-0-0", }, Status: model.StageStatus_STAGE_RUNNING, RetriedCount: 0, CompletedAt: 0, CreatedAt: now.Unix(), UpdatedAt: now.Unix(), }, { Id: "fake-stage-id-1-1", Name: model.StageK8sPrimaryRollout.String(), Index: 1, Predefined: true, Requires: []string{ "fake-stage-id-0-0", }, Status: model.StageStatus_STAGE_SUCCESS, RetriedCount: 0, CompletedAt: now.Unix(), CreatedAt: now.Unix(), UpdatedAt: now.Unix(), }, { Id: "fake-stage-id-1-2", Name: model.StageK8sCanaryRollout.String(), Index: 2, Predefined: true, Requires: []string{ "fake-stage-id-0-0", }, Status: model.StageStatus_STAGE_FAILURE, RetriedCount: 0, CompletedAt: now.Unix(), CreatedAt: now.Unix(), UpdatedAt: now.Unix(), }, { Id: "fake-stage-id-2-0", Name: model.StageK8sCanaryClean.String(), Desc: "waiting approval", Index: 0, Predefined: true, Requires: []string{ "fake-stage-id-1-0", "fake-stage-id-1-1", "fake-stage-id-1-2", }, Status: model.StageStatus_STAGE_NOT_STARTED_YET, RetriedCount: 0, CompletedAt: 0, CreatedAt: now.Unix(), UpdatedAt: now.Unix(), }, { Id: "fake-stage-id-2-1", Name: model.StageK8sCanaryClean.String(), Desc: "approved by cakecatz", Index: 1, Predefined: true, Requires: []string{ "fake-stage-id-1-0", "fake-stage-id-1-1", "fake-stage-id-1-2", }, Status: model.StageStatus_STAGE_NOT_STARTED_YET, RetriedCount: 0, CompletedAt: 0, CreatedAt: now.Unix(), UpdatedAt: now.Unix(), }, { Id: "fake-stage-id-3-0", Name: model.StageK8sCanaryRollout.String(), Index: 0, Predefined: true, Requires: []string{ "fake-stage-id-2-0", "fake-stage-id-2-1", }, Status: model.StageStatus_STAGE_NOT_STARTED_YET, RetriedCount: 0, CompletedAt: 0, CreatedAt: now.Unix(), UpdatedAt: now.Unix(), }, }, CreatedAt: deploymentTime.Unix(), UpdatedAt: deploymentTime.Unix(), } } return &webservice.ListDeploymentsResponse{ Deployments: fakeDeployments, }, nil } func (a *FakeWebAPI) GetDeployment(ctx context.Context, req *webservice.GetDeploymentRequest) (*webservice.GetDeploymentResponse, error) { now := time.Now() resp := &model.Deployment{ Id: "debug-deployment-id-01", ApplicationId: fmt.Sprintf("%s:%s:%s", fakeProjectID, "development", "debug-app"), EnvId: fmt.Sprintf("%s:%s", fakeProjectID, "development"), PipedId: "debug-piped", ProjectId: fakeProjectID, Kind: model.ApplicationKind_KUBERNETES, GitPath: &model.ApplicationGitPath{ RepoId: "debug", Path: "k8s", }, Trigger: &model.DeploymentTrigger{ Commit: &model.Commit{ Hash: "3808585b46f1e90196d7ffe8dd04c807a251febc", Message: "Add web page routing (#133)", Author: "cakecatz", Branch: "master", CreatedAt: now.Add(-30 * time.Minute).Unix(), }, Commander: "cakecatz", Timestamp: now.Add(-30 * time.Minute).Unix(), }, RunningCommitHash: "3808585b46f1e90196d7ffe8dd04c807a251febc", Description: "This deployment is debug", Status: model.DeploymentStatus_DEPLOYMENT_RUNNING, Stages: []*model.PipelineStage{ { Id: "fake-stage-id-0-0", Name: model.StageK8sCanaryRollout.String(), Index: 0, Predefined: true, Status: model.StageStatus_STAGE_SUCCESS, RetriedCount: 0, CompletedAt: now.Unix(), CreatedAt: now.Unix(), UpdatedAt: now.Unix(), }, { Id: "fake-stage-id-1-0", Name: model.StageK8sCanaryRollout.String(), Index: 0, Predefined: true, Requires: []string{ "fake-stage-id-0-0", }, Status: model.StageStatus_STAGE_RUNNING, RetriedCount: 0, CompletedAt: 0, CreatedAt: now.Unix(), UpdatedAt: now.Unix(), }, { Id: "fake-stage-id-1-1", Name: model.StageK8sPrimaryRollout.String(), Index: 1, Predefined: true, Requires: []string{ "fake-stage-id-0-0", }, Status: model.StageStatus_STAGE_SUCCESS, RetriedCount: 0, CompletedAt: now.Unix(), CreatedAt: now.Unix(), UpdatedAt: now.Unix(), }, { Id: "fake-stage-id-1-2", Name: model.StageK8sCanaryRollout.String(), Index: 2, Predefined: true, Requires: []string{ "fake-stage-id-0-0", }, Status: model.StageStatus_STAGE_FAILURE, RetriedCount: 0, CompletedAt: now.Unix(), CreatedAt: now.Unix(), UpdatedAt: now.Unix(), }, { Id: "fake-stage-id-2-0", Name: model.StageK8sCanaryClean.String(), Desc: "waiting approval", Index: 0, Predefined: true, Requires: []string{ "fake-stage-id-1-0", "fake-stage-id-1-1", "fake-stage-id-1-2", }, Status: model.StageStatus_STAGE_NOT_STARTED_YET, RetriedCount: 0, CompletedAt: 0, CreatedAt: now.Unix(), UpdatedAt: now.Unix(), }, { Id: "fake-stage-id-2-1", Name: model.StageK8sCanaryClean.String(), Desc: "approved by cakecatz", Index: 1, Predefined: true, Requires: []string{ "fake-stage-id-1-0", "fake-stage-id-1-1", "fake-stage-id-1-2", }, Status: model.StageStatus_STAGE_NOT_STARTED_YET, RetriedCount: 0, CompletedAt: 0, CreatedAt: now.Unix(), UpdatedAt: now.Unix(), }, { Id: "fake-stage-id-3-0", Name: model.StageK8sCanaryRollout.String(), Index: 0, Predefined: true, Requires: []string{ "fake-stage-id-2-0", "fake-stage-id-2-1", }, Status: model.StageStatus_STAGE_NOT_STARTED_YET, RetriedCount: 0, CompletedAt: 0, CreatedAt: now.Unix(), UpdatedAt: now.Unix(), }, }, CreatedAt: now.Unix(), UpdatedAt: now.Unix(), } return &webservice.GetDeploymentResponse{ Deployment: resp, }, nil } func (a *FakeWebAPI) GetStageLog(ctx context.Context, req *webservice.GetStageLogRequest) (*webservice.GetStageLogResponse, error) { startTime := time.Now().Add(-10 * time.Minute) resp := []*model.LogBlock{ { Index: 1, Log: "+ make build", Severity: model.LogSeverity_INFO, CreatedAt: startTime.Unix(), }, { Index: 2, Log: "bazelisk --output_base=/workspace/bazel_out build --config=ci -- //...", Severity: model.LogSeverity_INFO, CreatedAt: startTime.Add(5 * time.Second).Unix(), }, { Index: 3, Log: "2020/06/01 08:52:07 Downloading https://releases.bazel.build/3.1.0/release/bazel-3.1.0-linux-x86_64...", Severity: model.LogSeverity_INFO, CreatedAt: startTime.Add(10 * time.Second).Unix(), }, { Index: 4, Log: "Extracting Bazel installation...", Severity: model.LogSeverity_INFO, CreatedAt: startTime.Add(15 * time.Second).Unix(), }, { Index: 5, Log: "Starting local Bazel server and connecting to it...", Severity: model.LogSeverity_INFO, CreatedAt: startTime.Add(20 * time.Second).Unix(), }, { Index: 6, Log: "(08:52:14) Loading: 0 packages loaded", Severity: model.LogSeverity_SUCCESS, CreatedAt: startTime.Add(30 * time.Second).Unix(), }, { Index: 7, Log: "(08:53:21) Analyzing: 157 targets (88 packages loaded, 0 targets configured)", Severity: model.LogSeverity_SUCCESS, CreatedAt: startTime.Add(35 * time.Second).Unix(), }, { Index: 8, Log: "Error: Error building: logged 2 error(s)", Severity: model.LogSeverity_ERROR, CreatedAt: startTime.Add(45 * time.Second).Unix(), }, } return &webservice.GetStageLogResponse{ Blocks: resp, }, nil } func (a *FakeWebAPI) CancelDeployment(ctx context.Context, req *webservice.CancelDeploymentRequest) (*webservice.CancelDeploymentResponse, error) { return &webservice.CancelDeploymentResponse{ CommandId: uuid.New().String(), }, nil } func (a *FakeWebAPI) ApproveStage(ctx context.Context, req *webservice.ApproveStageRequest) (*webservice.ApproveStageResponse, error) { return &webservice.ApproveStageResponse{ CommandId: uuid.New().String(), }, nil } func (a *FakeWebAPI) GetApplicationLiveState(ctx context.Context, req *webservice.GetApplicationLiveStateRequest) (*webservice.GetApplicationLiveStateResponse, error) { now := time.Now() snapshot := &model.ApplicationLiveStateSnapshot{ ApplicationId: fmt.Sprintf("%s:%s:%s", fakeProjectID, "development", "debug-app"), EnvId: fmt.Sprintf("%s:%s", fakeProjectID, "development"), PipedId: "debug-piped", ProjectId: fakeProjectID, Kind: model.ApplicationKind_KUBERNETES, Kubernetes: &model.KubernetesApplicationLiveState{ Resources: []*model.KubernetesResourceState{ { Id: "f2c832a3-1f5b-4982-8f6e-72345ecb3c82", Name: "demo-application", ApiVersion: "networking.k8s.io/v1beta1", Kind: "Ingress", Namespace: "default", CreatedAt: now.Unix(), UpdatedAt: now.Unix(), }, { Id: "8423fb53-5170-4864-a7d2-b84f8d36cb02", Name: "demo-application", ApiVersion: "v1", Kind: "Service", Namespace: "default", CreatedAt: now.Unix(), UpdatedAt: now.Unix(), }, { Id: "660ecdfd-307b-4e47-becd-1fde4e0c1e7a", Name: "demo-application", ApiVersion: "apps/v1", Kind: "Deployment", Namespace: "default", CreatedAt: now.Unix(), UpdatedAt: now.Unix(), }, { Id: "8621f186-6641-4f7a-9be4-5983eb647f8d", OwnerIds: []string{ "660ecdfd-307b-4e47-becd-1fde4e0c1e7a", }, ParentIds: []string{ "660ecdfd-307b-4e47-becd-1fde4e0c1e7a", }, Name: "demo-application-9504e8601a", ApiVersion: "apps/v1", Kind: "ReplicaSet", Namespace: "default", CreatedAt: now.Unix(), UpdatedAt: now.Unix(), }, { Id: "ae5d0031-1f63-4396-b929-fa9987d1e6de", OwnerIds: []string{ "660ecdfd-307b-4e47-becd-1fde4e0c1e7a", }, ParentIds: []string{ "8621f186-6641-4f7a-9be4-5983eb647f8d", }, Name: "demo-application-9504e8601a-7vrdw", ApiVersion: "v1", Kind: "Pod", Namespace: "default", CreatedAt: now.Unix(), UpdatedAt: now.Unix(), }, { Id: "f55c7891-ba25-44bb-bca4-ffbc16b0089f", OwnerIds: []string{ "660ecdfd-307b-4e47-becd-1fde4e0c1e7a", }, ParentIds: []string{ "8621f186-6641-4f7a-9be4-5983eb647f8d", }, Name: "demo-application-9504e8601a-vlgd5", ApiVersion: "v1", Kind: "Pod", Namespace: "default", CreatedAt: now.Unix(), UpdatedAt: now.Unix(), }, { Id: "c2a81415-5bbf-44e8-9101-98bbd636bbeb", OwnerIds: []string{ "660ecdfd-307b-4e47-becd-1fde4e0c1e7a", }, ParentIds: []string{ "8621f186-6641-4f7a-9be4-5983eb647f8d", }, Name: "demo-application-9504e8601a-tmwp5", ApiVersion: "v1", Kind: "Pod", Namespace: "default", CreatedAt: now.Unix(), UpdatedAt: now.Unix(), }, }, }, Version: &model.ApplicationLiveStateVersion{ Index: 1, Timestamp: now.Unix(), }, } return &webservice.GetApplicationLiveStateResponse{ Snapshot: snapshot, }, nil } func (a *FakeWebAPI) GetProject(ctx context.Context, req *webservice.GetProjectRequest) (*webservice.GetProjectResponse, error) { return nil, status.Error(codes.Unimplemented, "") } func (a *FakeWebAPI) GetMe(ctx context.Context, req *webservice.GetMeRequest) (*webservice.GetMeResponse, error) { return nil, status.Error(codes.Unimplemented, "") } func (a *FakeWebAPI) GetCommand(ctx context.Context, req *webservice.GetCommandRequest) (*webservice.GetCommandResponse, error) { now := time.Now() cmd := model.Command{ Id: uuid.New().String(), PipedId: "debug-piped", ApplicationId: "debug-application-id", DeploymentId: "debug-deployment-id", Commander: "anonymous", Status: model.CommandStatus_COMMAND_NOT_HANDLED_YET, Type: model.Command_CANCEL_DEPLOYMENT, CancelDeployment: &model.Command_CancelDeployment{ DeploymentId: "debug-deployment-id-01", }, CreatedAt: now.Unix(), UpdatedAt: now.Unix(), } return &webservice.GetCommandResponse{ Command: &cmd, }, nil }
1
8,245
`ctx` is unused in EnableApplication
pipe-cd-pipe
go