binary.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791
  1. // Copyright (c) 2015-2016 The Khronos Group Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include "source/binary.h"
  15. #include <algorithm>
  16. #include <cassert>
  17. #include <cstring>
  18. #include <iterator>
  19. #include <limits>
  20. #include <string>
  21. #include <unordered_map>
  22. #include <vector>
  23. #include "source/assembly_grammar.h"
  24. #include "source/diagnostic.h"
  25. #include "source/ext_inst.h"
  26. #include "source/latest_version_spirv_header.h"
  27. #include "source/opcode.h"
  28. #include "source/operand.h"
  29. #include "source/spirv_constant.h"
  30. #include "source/spirv_endian.h"
  31. spv_result_t spvBinaryHeaderGet(const spv_const_binary binary,
  32. const spv_endianness_t endian,
  33. spv_header_t* pHeader) {
  34. if (!binary->code) return SPV_ERROR_INVALID_BINARY;
  35. if (binary->wordCount < SPV_INDEX_INSTRUCTION)
  36. return SPV_ERROR_INVALID_BINARY;
  37. if (!pHeader) return SPV_ERROR_INVALID_POINTER;
  38. // TODO: Validation checking?
  39. pHeader->magic = spvFixWord(binary->code[SPV_INDEX_MAGIC_NUMBER], endian);
  40. pHeader->version = spvFixWord(binary->code[SPV_INDEX_VERSION_NUMBER], endian);
  41. pHeader->generator =
  42. spvFixWord(binary->code[SPV_INDEX_GENERATOR_NUMBER], endian);
  43. pHeader->bound = spvFixWord(binary->code[SPV_INDEX_BOUND], endian);
  44. pHeader->schema = spvFixWord(binary->code[SPV_INDEX_SCHEMA], endian);
  45. pHeader->instructions = &binary->code[SPV_INDEX_INSTRUCTION];
  46. return SPV_SUCCESS;
  47. }
  48. namespace {
  49. // A SPIR-V binary parser. A parser instance communicates detailed parse
  50. // results via callbacks.
  51. class Parser {
  52. public:
  53. // The user_data value is provided to the callbacks as context.
  54. Parser(const spv_const_context context, void* user_data,
  55. spv_parsed_header_fn_t parsed_header_fn,
  56. spv_parsed_instruction_fn_t parsed_instruction_fn)
  57. : grammar_(context),
  58. consumer_(context->consumer),
  59. user_data_(user_data),
  60. parsed_header_fn_(parsed_header_fn),
  61. parsed_instruction_fn_(parsed_instruction_fn) {}
  62. // Parses the specified binary SPIR-V module, issuing callbacks on a parsed
  63. // header and for each parsed instruction. Returns SPV_SUCCESS on success.
  64. // Otherwise returns an error code and issues a diagnostic.
  65. spv_result_t parse(const uint32_t* words, size_t num_words,
  66. spv_diagnostic* diagnostic);
  67. private:
  68. // All remaining methods work on the current module parse state.
  69. // Like the parse method, but works on the current module parse state.
  70. spv_result_t parseModule();
  71. // Parses an instruction at the current position of the binary. Assumes
  72. // the header has been parsed, the endian has been set, and the word index is
  73. // still in range. Advances the parsing position past the instruction, and
  74. // updates other parsing state for the current module.
  75. // On success, returns SPV_SUCCESS and issues the parsed-instruction callback.
  76. // On failure, returns an error code and issues a diagnostic.
  77. spv_result_t parseInstruction();
  78. // Parses an instruction operand with the given type, for an instruction
  79. // starting at inst_offset words into the SPIR-V binary.
  80. // If the SPIR-V binary is the same endianness as the host, then the
  81. // endian_converted_inst_words parameter is ignored. Otherwise, this method
  82. // appends the words for this operand, converted to host native endianness,
  83. // to the end of endian_converted_inst_words. This method also updates the
  84. // expected_operands parameter, and the scalar members of the inst parameter.
  85. // On success, returns SPV_SUCCESS, advances past the operand, and pushes a
  86. // new entry on to the operands vector. Otherwise returns an error code and
  87. // issues a diagnostic.
  88. spv_result_t parseOperand(size_t inst_offset, spv_parsed_instruction_t* inst,
  89. const spv_operand_type_t type,
  90. std::vector<uint32_t>* endian_converted_inst_words,
  91. std::vector<spv_parsed_operand_t>* operands,
  92. spv_operand_pattern_t* expected_operands);
  93. // Records the numeric type for an operand according to the type information
  94. // associated with the given non-zero type Id. This can fail if the type Id
  95. // is not a type Id, or if the type Id does not reference a scalar numeric
  96. // type. On success, return SPV_SUCCESS and populates the num_words,
  97. // number_kind, and number_bit_width fields of parsed_operand.
  98. spv_result_t setNumericTypeInfoForType(spv_parsed_operand_t* parsed_operand,
  99. uint32_t type_id);
  100. // Records the number type for an instruction at the given offset, if that
  101. // instruction generates a type. For types that aren't scalar numbers,
  102. // record something with number kind SPV_NUMBER_NONE.
  103. void recordNumberType(size_t inst_offset,
  104. const spv_parsed_instruction_t* inst);
  105. // Returns a diagnostic stream object initialized with current position in
  106. // the input stream, and for the given error code. Any data written to the
  107. // returned object will be propagated to the current parse's diagnostic
  108. // object.
  109. spvtools::DiagnosticStream diagnostic(spv_result_t error) {
  110. return spvtools::DiagnosticStream({0, 0, _.word_index}, consumer_, "",
  111. error);
  112. }
  113. // Returns a diagnostic stream object with the default parse error code.
  114. spvtools::DiagnosticStream diagnostic() {
  115. // The default failure for parsing is invalid binary.
  116. return diagnostic(SPV_ERROR_INVALID_BINARY);
  117. }
  118. // Issues a diagnostic describing an exhaustion of input condition when
  119. // trying to decode an instruction operand, and returns
  120. // SPV_ERROR_INVALID_BINARY.
  121. spv_result_t exhaustedInputDiagnostic(size_t inst_offset, SpvOp opcode,
  122. spv_operand_type_t type) {
  123. return diagnostic() << "End of input reached while decoding Op"
  124. << spvOpcodeString(opcode) << " starting at word "
  125. << inst_offset
  126. << ((_.word_index < _.num_words) ? ": truncated "
  127. : ": missing ")
  128. << spvOperandTypeStr(type) << " operand at word offset "
  129. << _.word_index - inst_offset << ".";
  130. }
  131. // Returns the endian-corrected word at the current position.
  132. uint32_t peek() const { return peekAt(_.word_index); }
  133. // Returns the endian-corrected word at the given position.
  134. uint32_t peekAt(size_t index) const {
  135. assert(index < _.num_words);
  136. return spvFixWord(_.words[index], _.endian);
  137. }
  138. // Data members
  139. const spvtools::AssemblyGrammar grammar_; // SPIR-V syntax utility.
  140. const spvtools::MessageConsumer& consumer_; // Message consumer callback.
  141. void* const user_data_; // Context for the callbacks
  142. const spv_parsed_header_fn_t parsed_header_fn_; // Parsed header callback
  143. const spv_parsed_instruction_fn_t
  144. parsed_instruction_fn_; // Parsed instruction callback
  145. // Describes the format of a typed literal number.
  146. struct NumberType {
  147. spv_number_kind_t type;
  148. uint32_t bit_width;
  149. };
  150. // The state used to parse a single SPIR-V binary module.
  151. struct State {
  152. State(const uint32_t* words_arg, size_t num_words_arg,
  153. spv_diagnostic* diagnostic_arg)
  154. : words(words_arg),
  155. num_words(num_words_arg),
  156. diagnostic(diagnostic_arg),
  157. word_index(0),
  158. endian(),
  159. requires_endian_conversion(false) {
  160. // Temporary storage for parser state within a single instruction.
  161. // Most instructions require fewer than 25 words or operands.
  162. operands.reserve(25);
  163. endian_converted_words.reserve(25);
  164. expected_operands.reserve(25);
  165. }
  166. State() : State(0, 0, nullptr) {}
  167. const uint32_t* words; // Words in the binary SPIR-V module.
  168. size_t num_words; // Number of words in the module.
  169. spv_diagnostic* diagnostic; // Where diagnostics go.
  170. size_t word_index; // The current position in words.
  171. spv_endianness_t endian; // The endianness of the binary.
  172. // Is the SPIR-V binary in a different endiannes from the host native
  173. // endianness?
  174. bool requires_endian_conversion;
  175. // Maps a result ID to its type ID. By convention:
  176. // - a result ID that is a type definition maps to itself.
  177. // - a result ID without a type maps to 0. (E.g. for OpLabel)
  178. std::unordered_map<uint32_t, uint32_t> id_to_type_id;
  179. // Maps a type ID to its number type description.
  180. std::unordered_map<uint32_t, NumberType> type_id_to_number_type_info;
  181. // Maps an ExtInstImport id to the extended instruction type.
  182. std::unordered_map<uint32_t, spv_ext_inst_type_t>
  183. import_id_to_ext_inst_type;
  184. // Used by parseOperand
  185. std::vector<spv_parsed_operand_t> operands;
  186. std::vector<uint32_t> endian_converted_words;
  187. spv_operand_pattern_t expected_operands;
  188. } _;
  189. };
  190. spv_result_t Parser::parse(const uint32_t* words, size_t num_words,
  191. spv_diagnostic* diagnostic_arg) {
  192. _ = State(words, num_words, diagnostic_arg);
  193. const spv_result_t result = parseModule();
  194. // Clear the module state. The tables might be big.
  195. _ = State();
  196. return result;
  197. }
  198. spv_result_t Parser::parseModule() {
  199. if (!_.words) return diagnostic() << "Missing module.";
  200. if (_.num_words < SPV_INDEX_INSTRUCTION)
  201. return diagnostic() << "Module has incomplete header: only " << _.num_words
  202. << " words instead of " << SPV_INDEX_INSTRUCTION;
  203. // Check the magic number and detect the module's endianness.
  204. spv_const_binary_t binary{_.words, _.num_words};
  205. if (spvBinaryEndianness(&binary, &_.endian)) {
  206. return diagnostic() << "Invalid SPIR-V magic number '" << std::hex
  207. << _.words[0] << "'.";
  208. }
  209. _.requires_endian_conversion = !spvIsHostEndian(_.endian);
  210. // Process the header.
  211. spv_header_t header;
  212. if (spvBinaryHeaderGet(&binary, _.endian, &header)) {
  213. // It turns out there is no way to trigger this error since the only
  214. // failure cases are already handled above, with better messages.
  215. return diagnostic(SPV_ERROR_INTERNAL)
  216. << "Internal error: unhandled header parse failure";
  217. }
  218. if (parsed_header_fn_) {
  219. if (auto error = parsed_header_fn_(user_data_, _.endian, header.magic,
  220. header.version, header.generator,
  221. header.bound, header.schema)) {
  222. return error;
  223. }
  224. }
  225. // Process the instructions.
  226. _.word_index = SPV_INDEX_INSTRUCTION;
  227. while (_.word_index < _.num_words)
  228. if (auto error = parseInstruction()) return error;
  229. // Running off the end should already have been reported earlier.
  230. assert(_.word_index == _.num_words);
  231. return SPV_SUCCESS;
  232. }
  233. spv_result_t Parser::parseInstruction() {
  234. // The zero values for all members except for opcode are the
  235. // correct initial values.
  236. spv_parsed_instruction_t inst = {};
  237. const uint32_t first_word = peek();
  238. // If the module's endianness is different from the host native endianness,
  239. // then converted_words contains the the endian-translated words in the
  240. // instruction.
  241. _.endian_converted_words.clear();
  242. _.endian_converted_words.push_back(first_word);
  243. // After a successful parse of the instruction, the inst.operands member
  244. // will point to this vector's storage.
  245. _.operands.clear();
  246. assert(_.word_index < _.num_words);
  247. // Decompose and check the first word.
  248. uint16_t inst_word_count = 0;
  249. spvOpcodeSplit(first_word, &inst_word_count, &inst.opcode);
  250. if (inst_word_count < 1) {
  251. return diagnostic() << "Invalid instruction word count: "
  252. << inst_word_count;
  253. }
  254. spv_opcode_desc opcode_desc;
  255. if (grammar_.lookupOpcode(static_cast<SpvOp>(inst.opcode), &opcode_desc))
  256. return diagnostic() << "Invalid opcode: " << inst.opcode;
  257. // Advance past the opcode word. But remember the of the start
  258. // of the instruction.
  259. const size_t inst_offset = _.word_index;
  260. _.word_index++;
  261. // Maintains the ordered list of expected operand types.
  262. // For many instructions we only need the {numTypes, operandTypes}
  263. // entries in opcode_desc. However, sometimes we need to modify
  264. // the list as we parse the operands. This occurs when an operand
  265. // has its own logical operands (such as the LocalSize operand for
  266. // ExecutionMode), or for extended instructions that may have their
  267. // own operands depending on the selected extended instruction.
  268. _.expected_operands.clear();
  269. for (auto i = 0; i < opcode_desc->numTypes; i++)
  270. _.expected_operands.push_back(
  271. opcode_desc->operandTypes[opcode_desc->numTypes - i - 1]);
  272. while (_.word_index < inst_offset + inst_word_count) {
  273. const uint16_t inst_word_index = uint16_t(_.word_index - inst_offset);
  274. if (_.expected_operands.empty()) {
  275. return diagnostic() << "Invalid instruction Op" << opcode_desc->name
  276. << " starting at word " << inst_offset
  277. << ": expected no more operands after "
  278. << inst_word_index
  279. << " words, but stated word count is "
  280. << inst_word_count << ".";
  281. }
  282. spv_operand_type_t type =
  283. spvTakeFirstMatchableOperand(&_.expected_operands);
  284. if (auto error =
  285. parseOperand(inst_offset, &inst, type, &_.endian_converted_words,
  286. &_.operands, &_.expected_operands)) {
  287. return error;
  288. }
  289. }
  290. if (!_.expected_operands.empty() &&
  291. !spvOperandIsOptional(_.expected_operands.back())) {
  292. return diagnostic() << "End of input reached while decoding Op"
  293. << opcode_desc->name << " starting at word "
  294. << inst_offset << ": expected more operands after "
  295. << inst_word_count << " words.";
  296. }
  297. if ((inst_offset + inst_word_count) != _.word_index) {
  298. return diagnostic() << "Invalid word count: Op" << opcode_desc->name
  299. << " starting at word " << inst_offset
  300. << " says it has " << inst_word_count
  301. << " words, but found " << _.word_index - inst_offset
  302. << " words instead.";
  303. }
  304. // Check the computed length of the endian-converted words vector against
  305. // the declared number of words in the instruction. If endian conversion
  306. // is required, then they should match. If no endian conversion was
  307. // performed, then the vector only contains the initial opcode/word-count
  308. // word.
  309. assert(!_.requires_endian_conversion ||
  310. (inst_word_count == _.endian_converted_words.size()));
  311. assert(_.requires_endian_conversion ||
  312. (_.endian_converted_words.size() == 1));
  313. recordNumberType(inst_offset, &inst);
  314. if (_.requires_endian_conversion) {
  315. // We must wait until here to set this pointer, because the vector might
  316. // have been be resized while we accumulated its elements.
  317. inst.words = _.endian_converted_words.data();
  318. } else {
  319. // If no conversion is required, then just point to the underlying binary.
  320. // This saves time and space.
  321. inst.words = _.words + inst_offset;
  322. }
  323. inst.num_words = inst_word_count;
  324. // We must wait until here to set this pointer, because the vector might
  325. // have been be resized while we accumulated its elements.
  326. inst.operands = _.operands.data();
  327. inst.num_operands = uint16_t(_.operands.size());
  328. // Issue the callback. The callee should know that all the storage in inst
  329. // is transient, and will disappear immediately afterward.
  330. if (parsed_instruction_fn_) {
  331. if (auto error = parsed_instruction_fn_(user_data_, &inst)) return error;
  332. }
  333. return SPV_SUCCESS;
  334. }
  335. spv_result_t Parser::parseOperand(size_t inst_offset,
  336. spv_parsed_instruction_t* inst,
  337. const spv_operand_type_t type,
  338. std::vector<uint32_t>* words,
  339. std::vector<spv_parsed_operand_t>* operands,
  340. spv_operand_pattern_t* expected_operands) {
  341. const SpvOp opcode = static_cast<SpvOp>(inst->opcode);
  342. // We'll fill in this result as we go along.
  343. spv_parsed_operand_t parsed_operand;
  344. parsed_operand.offset = uint16_t(_.word_index - inst_offset);
  345. // Most operands occupy one word. This might be be adjusted later.
  346. parsed_operand.num_words = 1;
  347. // The type argument is the one used by the grammar to parse the instruction.
  348. // But it can exposes internal parser details such as whether an operand is
  349. // optional or actually represents a variable-length sequence of operands.
  350. // The resulting type should be adjusted to avoid those internal details.
  351. // In most cases, the resulting operand type is the same as the grammar type.
  352. parsed_operand.type = type;
  353. // Assume non-numeric values. This will be updated for literal numbers.
  354. parsed_operand.number_kind = SPV_NUMBER_NONE;
  355. parsed_operand.number_bit_width = 0;
  356. if (_.word_index >= _.num_words)
  357. return exhaustedInputDiagnostic(inst_offset, opcode, type);
  358. const uint32_t word = peek();
  359. // Do the words in this operand have to be converted to native endianness?
  360. // True for all but literal strings.
  361. bool convert_operand_endianness = true;
  362. switch (type) {
  363. case SPV_OPERAND_TYPE_TYPE_ID:
  364. if (!word)
  365. return diagnostic(SPV_ERROR_INVALID_ID) << "Error: Type Id is 0";
  366. inst->type_id = word;
  367. break;
  368. case SPV_OPERAND_TYPE_RESULT_ID:
  369. if (!word)
  370. return diagnostic(SPV_ERROR_INVALID_ID) << "Error: Result Id is 0";
  371. inst->result_id = word;
  372. // Save the result ID to type ID mapping.
  373. // In the grammar, type ID always appears before result ID.
  374. if (_.id_to_type_id.find(inst->result_id) != _.id_to_type_id.end())
  375. return diagnostic(SPV_ERROR_INVALID_ID)
  376. << "Id " << inst->result_id << " is defined more than once";
  377. // Record it.
  378. // A regular value maps to its type. Some instructions (e.g. OpLabel)
  379. // have no type Id, and will map to 0. The result Id for a
  380. // type-generating instruction (e.g. OpTypeInt) maps to itself.
  381. _.id_to_type_id[inst->result_id] =
  382. spvOpcodeGeneratesType(opcode) ? inst->result_id : inst->type_id;
  383. break;
  384. case SPV_OPERAND_TYPE_ID:
  385. case SPV_OPERAND_TYPE_OPTIONAL_ID:
  386. if (!word) return diagnostic(SPV_ERROR_INVALID_ID) << "Id is 0";
  387. parsed_operand.type = SPV_OPERAND_TYPE_ID;
  388. if (opcode == SpvOpExtInst && parsed_operand.offset == 3) {
  389. // The current word is the extended instruction set Id.
  390. // Set the extended instruction set type for the current instruction.
  391. auto ext_inst_type_iter = _.import_id_to_ext_inst_type.find(word);
  392. if (ext_inst_type_iter == _.import_id_to_ext_inst_type.end()) {
  393. return diagnostic(SPV_ERROR_INVALID_ID)
  394. << "OpExtInst set Id " << word
  395. << " does not reference an OpExtInstImport result Id";
  396. }
  397. inst->ext_inst_type = ext_inst_type_iter->second;
  398. }
  399. break;
  400. case SPV_OPERAND_TYPE_SCOPE_ID:
  401. case SPV_OPERAND_TYPE_MEMORY_SEMANTICS_ID:
  402. // Check for trivially invalid values. The operand descriptions already
  403. // have the word "ID" in them.
  404. if (!word) return diagnostic() << spvOperandTypeStr(type) << " is 0";
  405. break;
  406. case SPV_OPERAND_TYPE_EXTENSION_INSTRUCTION_NUMBER: {
  407. assert(SpvOpExtInst == opcode);
  408. assert(inst->ext_inst_type != SPV_EXT_INST_TYPE_NONE);
  409. spv_ext_inst_desc ext_inst;
  410. if (grammar_.lookupExtInst(inst->ext_inst_type, word, &ext_inst))
  411. return diagnostic() << "Invalid extended instruction number: " << word;
  412. spvPushOperandTypes(ext_inst->operandTypes, expected_operands);
  413. } break;
  414. case SPV_OPERAND_TYPE_SPEC_CONSTANT_OP_NUMBER: {
  415. assert(SpvOpSpecConstantOp == opcode);
  416. if (grammar_.lookupSpecConstantOpcode(SpvOp(word))) {
  417. return diagnostic()
  418. << "Invalid " << spvOperandTypeStr(type) << ": " << word;
  419. }
  420. spv_opcode_desc opcode_entry = nullptr;
  421. if (grammar_.lookupOpcode(SpvOp(word), &opcode_entry)) {
  422. return diagnostic(SPV_ERROR_INTERNAL)
  423. << "OpSpecConstant opcode table out of sync";
  424. }
  425. // OpSpecConstant opcodes must have a type and result. We've already
  426. // processed them, so skip them when preparing to parse the other
  427. // operants for the opcode.
  428. assert(opcode_entry->hasType);
  429. assert(opcode_entry->hasResult);
  430. assert(opcode_entry->numTypes >= 2);
  431. spvPushOperandTypes(opcode_entry->operandTypes + 2, expected_operands);
  432. } break;
  433. case SPV_OPERAND_TYPE_LITERAL_INTEGER:
  434. case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_INTEGER:
  435. // These are regular single-word literal integer operands.
  436. // Post-parsing validation should check the range of the parsed value.
  437. parsed_operand.type = SPV_OPERAND_TYPE_LITERAL_INTEGER;
  438. // It turns out they are always unsigned integers!
  439. parsed_operand.number_kind = SPV_NUMBER_UNSIGNED_INT;
  440. parsed_operand.number_bit_width = 32;
  441. break;
  442. case SPV_OPERAND_TYPE_TYPED_LITERAL_NUMBER:
  443. case SPV_OPERAND_TYPE_OPTIONAL_TYPED_LITERAL_INTEGER:
  444. parsed_operand.type = SPV_OPERAND_TYPE_TYPED_LITERAL_NUMBER;
  445. if (opcode == SpvOpSwitch) {
  446. // The literal operands have the same type as the value
  447. // referenced by the selector Id.
  448. const uint32_t selector_id = peekAt(inst_offset + 1);
  449. const auto type_id_iter = _.id_to_type_id.find(selector_id);
  450. if (type_id_iter == _.id_to_type_id.end() ||
  451. type_id_iter->second == 0) {
  452. return diagnostic() << "Invalid OpSwitch: selector id " << selector_id
  453. << " has no type";
  454. }
  455. uint32_t type_id = type_id_iter->second;
  456. if (selector_id == type_id) {
  457. // Recall that by convention, a result ID that is a type definition
  458. // maps to itself.
  459. return diagnostic() << "Invalid OpSwitch: selector id " << selector_id
  460. << " is a type, not a value";
  461. }
  462. if (auto error = setNumericTypeInfoForType(&parsed_operand, type_id))
  463. return error;
  464. if (parsed_operand.number_kind != SPV_NUMBER_UNSIGNED_INT &&
  465. parsed_operand.number_kind != SPV_NUMBER_SIGNED_INT) {
  466. return diagnostic() << "Invalid OpSwitch: selector id " << selector_id
  467. << " is not a scalar integer";
  468. }
  469. } else {
  470. assert(opcode == SpvOpConstant || opcode == SpvOpSpecConstant);
  471. // The literal number type is determined by the type Id for the
  472. // constant.
  473. assert(inst->type_id);
  474. if (auto error =
  475. setNumericTypeInfoForType(&parsed_operand, inst->type_id))
  476. return error;
  477. }
  478. break;
  479. case SPV_OPERAND_TYPE_LITERAL_STRING:
  480. case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_STRING: {
  481. convert_operand_endianness = false;
  482. const char* string =
  483. reinterpret_cast<const char*>(_.words + _.word_index);
  484. // Compute the length of the string, but make sure we don't run off the
  485. // end of the input.
  486. const size_t remaining_input_bytes =
  487. sizeof(uint32_t) * (_.num_words - _.word_index);
  488. const size_t string_num_content_bytes =
  489. spv_strnlen_s(string, remaining_input_bytes);
  490. // If there was no terminating null byte, then that's an end-of-input
  491. // error.
  492. if (string_num_content_bytes == remaining_input_bytes)
  493. return exhaustedInputDiagnostic(inst_offset, opcode, type);
  494. // Account for null in the word length, so add 1 for null, then add 3 to
  495. // make sure we round up. The following is equivalent to:
  496. // (string_num_content_bytes + 1 + 3) / 4
  497. const size_t string_num_words = string_num_content_bytes / 4 + 1;
  498. // Make sure we can record the word count without overflow.
  499. //
  500. // This error can't currently be triggered because of validity
  501. // checks elsewhere.
  502. if (string_num_words > std::numeric_limits<uint16_t>::max()) {
  503. return diagnostic() << "Literal string is longer than "
  504. << std::numeric_limits<uint16_t>::max()
  505. << " words: " << string_num_words << " words long";
  506. }
  507. parsed_operand.num_words = uint16_t(string_num_words);
  508. parsed_operand.type = SPV_OPERAND_TYPE_LITERAL_STRING;
  509. if (SpvOpExtInstImport == opcode) {
  510. // Record the extended instruction type for the ID for this import.
  511. // There is only one string literal argument to OpExtInstImport,
  512. // so it's sufficient to guard this just on the opcode.
  513. const spv_ext_inst_type_t ext_inst_type =
  514. spvExtInstImportTypeGet(string);
  515. if (SPV_EXT_INST_TYPE_NONE == ext_inst_type) {
  516. return diagnostic()
  517. << "Invalid extended instruction import '" << string << "'";
  518. }
  519. // We must have parsed a valid result ID. It's a condition
  520. // of the grammar, and we only accept non-zero result Ids.
  521. assert(inst->result_id);
  522. _.import_id_to_ext_inst_type[inst->result_id] = ext_inst_type;
  523. }
  524. } break;
  525. case SPV_OPERAND_TYPE_CAPABILITY:
  526. case SPV_OPERAND_TYPE_SOURCE_LANGUAGE:
  527. case SPV_OPERAND_TYPE_EXECUTION_MODEL:
  528. case SPV_OPERAND_TYPE_ADDRESSING_MODEL:
  529. case SPV_OPERAND_TYPE_MEMORY_MODEL:
  530. case SPV_OPERAND_TYPE_EXECUTION_MODE:
  531. case SPV_OPERAND_TYPE_STORAGE_CLASS:
  532. case SPV_OPERAND_TYPE_DIMENSIONALITY:
  533. case SPV_OPERAND_TYPE_SAMPLER_ADDRESSING_MODE:
  534. case SPV_OPERAND_TYPE_SAMPLER_FILTER_MODE:
  535. case SPV_OPERAND_TYPE_SAMPLER_IMAGE_FORMAT:
  536. case SPV_OPERAND_TYPE_FP_ROUNDING_MODE:
  537. case SPV_OPERAND_TYPE_LINKAGE_TYPE:
  538. case SPV_OPERAND_TYPE_ACCESS_QUALIFIER:
  539. case SPV_OPERAND_TYPE_OPTIONAL_ACCESS_QUALIFIER:
  540. case SPV_OPERAND_TYPE_FUNCTION_PARAMETER_ATTRIBUTE:
  541. case SPV_OPERAND_TYPE_DECORATION:
  542. case SPV_OPERAND_TYPE_BUILT_IN:
  543. case SPV_OPERAND_TYPE_GROUP_OPERATION:
  544. case SPV_OPERAND_TYPE_KERNEL_ENQ_FLAGS:
  545. case SPV_OPERAND_TYPE_KERNEL_PROFILING_INFO:
  546. case SPV_OPERAND_TYPE_DEBUG_BASE_TYPE_ATTRIBUTE_ENCODING:
  547. case SPV_OPERAND_TYPE_DEBUG_COMPOSITE_TYPE:
  548. case SPV_OPERAND_TYPE_DEBUG_TYPE_QUALIFIER:
  549. case SPV_OPERAND_TYPE_DEBUG_OPERATION: {
  550. // A single word that is a plain enum value.
  551. // Map an optional operand type to its corresponding concrete type.
  552. if (type == SPV_OPERAND_TYPE_OPTIONAL_ACCESS_QUALIFIER)
  553. parsed_operand.type = SPV_OPERAND_TYPE_ACCESS_QUALIFIER;
  554. spv_operand_desc entry;
  555. if (grammar_.lookupOperand(type, word, &entry)) {
  556. return diagnostic()
  557. << "Invalid " << spvOperandTypeStr(parsed_operand.type)
  558. << " operand: " << word;
  559. }
  560. // Prepare to accept operands to this operand, if needed.
  561. spvPushOperandTypes(entry->operandTypes, expected_operands);
  562. } break;
  563. case SPV_OPERAND_TYPE_FP_FAST_MATH_MODE:
  564. case SPV_OPERAND_TYPE_FUNCTION_CONTROL:
  565. case SPV_OPERAND_TYPE_LOOP_CONTROL:
  566. case SPV_OPERAND_TYPE_IMAGE:
  567. case SPV_OPERAND_TYPE_OPTIONAL_IMAGE:
  568. case SPV_OPERAND_TYPE_OPTIONAL_MEMORY_ACCESS:
  569. case SPV_OPERAND_TYPE_SELECTION_CONTROL:
  570. case SPV_OPERAND_TYPE_DEBUG_INFO_FLAGS: {
  571. // This operand is a mask.
  572. // Map an optional operand type to its corresponding concrete type.
  573. if (type == SPV_OPERAND_TYPE_OPTIONAL_IMAGE)
  574. parsed_operand.type = SPV_OPERAND_TYPE_IMAGE;
  575. else if (type == SPV_OPERAND_TYPE_OPTIONAL_MEMORY_ACCESS)
  576. parsed_operand.type = SPV_OPERAND_TYPE_MEMORY_ACCESS;
  577. // Check validity of set mask bits. Also prepare for operands for those
  578. // masks if they have any. To get operand order correct, scan from
  579. // MSB to LSB since we can only prepend operands to a pattern.
  580. // The only case in the grammar where you have more than one mask bit
  581. // having an operand is for image operands. See SPIR-V 3.14 Image
  582. // Operands.
  583. uint32_t remaining_word = word;
  584. for (uint32_t mask = (1u << 31); remaining_word; mask >>= 1) {
  585. if (remaining_word & mask) {
  586. spv_operand_desc entry;
  587. if (grammar_.lookupOperand(type, mask, &entry)) {
  588. return diagnostic()
  589. << "Invalid " << spvOperandTypeStr(parsed_operand.type)
  590. << " operand: " << word << " has invalid mask component "
  591. << mask;
  592. }
  593. remaining_word ^= mask;
  594. spvPushOperandTypes(entry->operandTypes, expected_operands);
  595. }
  596. }
  597. if (word == 0) {
  598. // An all-zeroes mask *might* also be valid.
  599. spv_operand_desc entry;
  600. if (SPV_SUCCESS == grammar_.lookupOperand(type, 0, &entry)) {
  601. // Prepare for its operands, if any.
  602. spvPushOperandTypes(entry->operandTypes, expected_operands);
  603. }
  604. }
  605. } break;
  606. default:
  607. return diagnostic() << "Internal error: Unhandled operand type: " << type;
  608. }
  609. assert(spvOperandIsConcrete(parsed_operand.type));
  610. operands->push_back(parsed_operand);
  611. const size_t index_after_operand = _.word_index + parsed_operand.num_words;
  612. // Avoid buffer overrun for the cases where the operand has more than one
  613. // word, and where it isn't a string. (Those other cases have already been
  614. // handled earlier.) For example, this error can occur for a multi-word
  615. // argument to OpConstant, or a multi-word case literal operand for OpSwitch.
  616. if (_.num_words < index_after_operand)
  617. return exhaustedInputDiagnostic(inst_offset, opcode, type);
  618. if (_.requires_endian_conversion) {
  619. // Copy instruction words. Translate to native endianness as needed.
  620. if (convert_operand_endianness) {
  621. const spv_endianness_t endianness = _.endian;
  622. std::transform(_.words + _.word_index, _.words + index_after_operand,
  623. std::back_inserter(*words),
  624. [endianness](const uint32_t raw_word) {
  625. return spvFixWord(raw_word, endianness);
  626. });
  627. } else {
  628. words->insert(words->end(), _.words + _.word_index,
  629. _.words + index_after_operand);
  630. }
  631. }
  632. // Advance past the operand.
  633. _.word_index = index_after_operand;
  634. return SPV_SUCCESS;
  635. }
  636. spv_result_t Parser::setNumericTypeInfoForType(
  637. spv_parsed_operand_t* parsed_operand, uint32_t type_id) {
  638. assert(type_id != 0);
  639. auto type_info_iter = _.type_id_to_number_type_info.find(type_id);
  640. if (type_info_iter == _.type_id_to_number_type_info.end()) {
  641. return diagnostic() << "Type Id " << type_id << " is not a type";
  642. }
  643. const NumberType& info = type_info_iter->second;
  644. if (info.type == SPV_NUMBER_NONE) {
  645. // This is a valid type, but for something other than a scalar number.
  646. return diagnostic() << "Type Id " << type_id
  647. << " is not a scalar numeric type";
  648. }
  649. parsed_operand->number_kind = info.type;
  650. parsed_operand->number_bit_width = info.bit_width;
  651. // Round up the word count.
  652. parsed_operand->num_words = static_cast<uint16_t>((info.bit_width + 31) / 32);
  653. return SPV_SUCCESS;
  654. }
  655. void Parser::recordNumberType(size_t inst_offset,
  656. const spv_parsed_instruction_t* inst) {
  657. const SpvOp opcode = static_cast<SpvOp>(inst->opcode);
  658. if (spvOpcodeGeneratesType(opcode)) {
  659. NumberType info = {SPV_NUMBER_NONE, 0};
  660. if (SpvOpTypeInt == opcode) {
  661. const bool is_signed = peekAt(inst_offset + 3) != 0;
  662. info.type = is_signed ? SPV_NUMBER_SIGNED_INT : SPV_NUMBER_UNSIGNED_INT;
  663. info.bit_width = peekAt(inst_offset + 2);
  664. } else if (SpvOpTypeFloat == opcode) {
  665. info.type = SPV_NUMBER_FLOATING;
  666. info.bit_width = peekAt(inst_offset + 2);
  667. }
  668. // The *result* Id of a type generating instruction is the type Id.
  669. _.type_id_to_number_type_info[inst->result_id] = info;
  670. }
  671. }
  672. } // anonymous namespace
  673. spv_result_t spvBinaryParse(const spv_const_context context, void* user_data,
  674. const uint32_t* code, const size_t num_words,
  675. spv_parsed_header_fn_t parsed_header,
  676. spv_parsed_instruction_fn_t parsed_instruction,
  677. spv_diagnostic* diagnostic) {
  678. spv_context_t hijack_context = *context;
  679. if (diagnostic) {
  680. *diagnostic = nullptr;
  681. spvtools::UseDiagnosticAsMessageConsumer(&hijack_context, diagnostic);
  682. }
  683. Parser parser(&hijack_context, user_data, parsed_header, parsed_instruction);
  684. return parser.parse(code, num_words, diagnostic);
  685. }
  686. // TODO(dneto): This probably belongs in text.cpp since that's the only place
  687. // that a spv_binary_t value is created.
  688. void spvBinaryDestroy(spv_binary binary) {
  689. if (!binary) return;
  690. delete[] binary->code;
  691. delete binary;
  692. }
  693. size_t spv_strnlen_s(const char* str, size_t strsz) {
  694. if (!str) return 0;
  695. for (size_t i = 0; i < strsz; i++) {
  696. if (!str[i]) return i;
  697. }
  698. return strsz;
  699. }