binary.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796
  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, _.instruction_count}, 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. instruction_count(0),
  159. endian(),
  160. requires_endian_conversion(false) {
  161. // Temporary storage for parser state within a single instruction.
  162. // Most instructions require fewer than 25 words or operands.
  163. operands.reserve(25);
  164. endian_converted_words.reserve(25);
  165. expected_operands.reserve(25);
  166. }
  167. State() : State(0, 0, nullptr) {}
  168. const uint32_t* words; // Words in the binary SPIR-V module.
  169. size_t num_words; // Number of words in the module.
  170. spv_diagnostic* diagnostic; // Where diagnostics go.
  171. size_t word_index; // The current position in words.
  172. size_t instruction_count; // The count of processed instructions
  173. spv_endianness_t endian; // The endianness of the binary.
  174. // Is the SPIR-V binary in a different endiannes from the host native
  175. // endianness?
  176. bool requires_endian_conversion;
  177. // Maps a result ID to its type ID. By convention:
  178. // - a result ID that is a type definition maps to itself.
  179. // - a result ID without a type maps to 0. (E.g. for OpLabel)
  180. std::unordered_map<uint32_t, uint32_t> id_to_type_id;
  181. // Maps a type ID to its number type description.
  182. std::unordered_map<uint32_t, NumberType> type_id_to_number_type_info;
  183. // Maps an ExtInstImport id to the extended instruction type.
  184. std::unordered_map<uint32_t, spv_ext_inst_type_t>
  185. import_id_to_ext_inst_type;
  186. // Used by parseOperand
  187. std::vector<spv_parsed_operand_t> operands;
  188. std::vector<uint32_t> endian_converted_words;
  189. spv_operand_pattern_t expected_operands;
  190. } _;
  191. };
  192. spv_result_t Parser::parse(const uint32_t* words, size_t num_words,
  193. spv_diagnostic* diagnostic_arg) {
  194. _ = State(words, num_words, diagnostic_arg);
  195. const spv_result_t result = parseModule();
  196. // Clear the module state. The tables might be big.
  197. _ = State();
  198. return result;
  199. }
  200. spv_result_t Parser::parseModule() {
  201. if (!_.words) return diagnostic() << "Missing module.";
  202. if (_.num_words < SPV_INDEX_INSTRUCTION)
  203. return diagnostic() << "Module has incomplete header: only " << _.num_words
  204. << " words instead of " << SPV_INDEX_INSTRUCTION;
  205. // Check the magic number and detect the module's endianness.
  206. spv_const_binary_t binary{_.words, _.num_words};
  207. if (spvBinaryEndianness(&binary, &_.endian)) {
  208. return diagnostic() << "Invalid SPIR-V magic number '" << std::hex
  209. << _.words[0] << "'.";
  210. }
  211. _.requires_endian_conversion = !spvIsHostEndian(_.endian);
  212. // Process the header.
  213. spv_header_t header;
  214. if (spvBinaryHeaderGet(&binary, _.endian, &header)) {
  215. // It turns out there is no way to trigger this error since the only
  216. // failure cases are already handled above, with better messages.
  217. return diagnostic(SPV_ERROR_INTERNAL)
  218. << "Internal error: unhandled header parse failure";
  219. }
  220. if (parsed_header_fn_) {
  221. if (auto error = parsed_header_fn_(user_data_, _.endian, header.magic,
  222. header.version, header.generator,
  223. header.bound, header.schema)) {
  224. return error;
  225. }
  226. }
  227. // Process the instructions.
  228. _.word_index = SPV_INDEX_INSTRUCTION;
  229. while (_.word_index < _.num_words)
  230. if (auto error = parseInstruction()) return error;
  231. // Running off the end should already have been reported earlier.
  232. assert(_.word_index == _.num_words);
  233. return SPV_SUCCESS;
  234. }
  235. spv_result_t Parser::parseInstruction() {
  236. _.instruction_count++;
  237. // The zero values for all members except for opcode are the
  238. // correct initial values.
  239. spv_parsed_instruction_t inst = {};
  240. const uint32_t first_word = peek();
  241. // If the module's endianness is different from the host native endianness,
  242. // then converted_words contains the the endian-translated words in the
  243. // instruction.
  244. _.endian_converted_words.clear();
  245. _.endian_converted_words.push_back(first_word);
  246. // After a successful parse of the instruction, the inst.operands member
  247. // will point to this vector's storage.
  248. _.operands.clear();
  249. assert(_.word_index < _.num_words);
  250. // Decompose and check the first word.
  251. uint16_t inst_word_count = 0;
  252. spvOpcodeSplit(first_word, &inst_word_count, &inst.opcode);
  253. if (inst_word_count < 1) {
  254. return diagnostic() << "Invalid instruction word count: "
  255. << inst_word_count;
  256. }
  257. spv_opcode_desc opcode_desc;
  258. if (grammar_.lookupOpcode(static_cast<SpvOp>(inst.opcode), &opcode_desc))
  259. return diagnostic() << "Invalid opcode: " << inst.opcode;
  260. // Advance past the opcode word. But remember the of the start
  261. // of the instruction.
  262. const size_t inst_offset = _.word_index;
  263. _.word_index++;
  264. // Maintains the ordered list of expected operand types.
  265. // For many instructions we only need the {numTypes, operandTypes}
  266. // entries in opcode_desc. However, sometimes we need to modify
  267. // the list as we parse the operands. This occurs when an operand
  268. // has its own logical operands (such as the LocalSize operand for
  269. // ExecutionMode), or for extended instructions that may have their
  270. // own operands depending on the selected extended instruction.
  271. _.expected_operands.clear();
  272. for (auto i = 0; i < opcode_desc->numTypes; i++)
  273. _.expected_operands.push_back(
  274. opcode_desc->operandTypes[opcode_desc->numTypes - i - 1]);
  275. while (_.word_index < inst_offset + inst_word_count) {
  276. const uint16_t inst_word_index = uint16_t(_.word_index - inst_offset);
  277. if (_.expected_operands.empty()) {
  278. return diagnostic() << "Invalid instruction Op" << opcode_desc->name
  279. << " starting at word " << inst_offset
  280. << ": expected no more operands after "
  281. << inst_word_index
  282. << " words, but stated word count is "
  283. << inst_word_count << ".";
  284. }
  285. spv_operand_type_t type =
  286. spvTakeFirstMatchableOperand(&_.expected_operands);
  287. if (auto error =
  288. parseOperand(inst_offset, &inst, type, &_.endian_converted_words,
  289. &_.operands, &_.expected_operands)) {
  290. return error;
  291. }
  292. }
  293. if (!_.expected_operands.empty() &&
  294. !spvOperandIsOptional(_.expected_operands.back())) {
  295. return diagnostic() << "End of input reached while decoding Op"
  296. << opcode_desc->name << " starting at word "
  297. << inst_offset << ": expected more operands after "
  298. << inst_word_count << " words.";
  299. }
  300. if ((inst_offset + inst_word_count) != _.word_index) {
  301. return diagnostic() << "Invalid word count: Op" << opcode_desc->name
  302. << " starting at word " << inst_offset
  303. << " says it has " << inst_word_count
  304. << " words, but found " << _.word_index - inst_offset
  305. << " words instead.";
  306. }
  307. // Check the computed length of the endian-converted words vector against
  308. // the declared number of words in the instruction. If endian conversion
  309. // is required, then they should match. If no endian conversion was
  310. // performed, then the vector only contains the initial opcode/word-count
  311. // word.
  312. assert(!_.requires_endian_conversion ||
  313. (inst_word_count == _.endian_converted_words.size()));
  314. assert(_.requires_endian_conversion ||
  315. (_.endian_converted_words.size() == 1));
  316. recordNumberType(inst_offset, &inst);
  317. if (_.requires_endian_conversion) {
  318. // We must wait until here to set this pointer, because the vector might
  319. // have been be resized while we accumulated its elements.
  320. inst.words = _.endian_converted_words.data();
  321. } else {
  322. // If no conversion is required, then just point to the underlying binary.
  323. // This saves time and space.
  324. inst.words = _.words + inst_offset;
  325. }
  326. inst.num_words = inst_word_count;
  327. // We must wait until here to set this pointer, because the vector might
  328. // have been be resized while we accumulated its elements.
  329. inst.operands = _.operands.data();
  330. inst.num_operands = uint16_t(_.operands.size());
  331. // Issue the callback. The callee should know that all the storage in inst
  332. // is transient, and will disappear immediately afterward.
  333. if (parsed_instruction_fn_) {
  334. if (auto error = parsed_instruction_fn_(user_data_, &inst)) return error;
  335. }
  336. return SPV_SUCCESS;
  337. }
  338. spv_result_t Parser::parseOperand(size_t inst_offset,
  339. spv_parsed_instruction_t* inst,
  340. const spv_operand_type_t type,
  341. std::vector<uint32_t>* words,
  342. std::vector<spv_parsed_operand_t>* operands,
  343. spv_operand_pattern_t* expected_operands) {
  344. const SpvOp opcode = static_cast<SpvOp>(inst->opcode);
  345. // We'll fill in this result as we go along.
  346. spv_parsed_operand_t parsed_operand;
  347. parsed_operand.offset = uint16_t(_.word_index - inst_offset);
  348. // Most operands occupy one word. This might be be adjusted later.
  349. parsed_operand.num_words = 1;
  350. // The type argument is the one used by the grammar to parse the instruction.
  351. // But it can exposes internal parser details such as whether an operand is
  352. // optional or actually represents a variable-length sequence of operands.
  353. // The resulting type should be adjusted to avoid those internal details.
  354. // In most cases, the resulting operand type is the same as the grammar type.
  355. parsed_operand.type = type;
  356. // Assume non-numeric values. This will be updated for literal numbers.
  357. parsed_operand.number_kind = SPV_NUMBER_NONE;
  358. parsed_operand.number_bit_width = 0;
  359. if (_.word_index >= _.num_words)
  360. return exhaustedInputDiagnostic(inst_offset, opcode, type);
  361. const uint32_t word = peek();
  362. // Do the words in this operand have to be converted to native endianness?
  363. // True for all but literal strings.
  364. bool convert_operand_endianness = true;
  365. switch (type) {
  366. case SPV_OPERAND_TYPE_TYPE_ID:
  367. if (!word)
  368. return diagnostic(SPV_ERROR_INVALID_ID) << "Error: Type Id is 0";
  369. inst->type_id = word;
  370. break;
  371. case SPV_OPERAND_TYPE_RESULT_ID:
  372. if (!word)
  373. return diagnostic(SPV_ERROR_INVALID_ID) << "Error: Result Id is 0";
  374. inst->result_id = word;
  375. // Save the result ID to type ID mapping.
  376. // In the grammar, type ID always appears before result ID.
  377. if (_.id_to_type_id.find(inst->result_id) != _.id_to_type_id.end())
  378. return diagnostic(SPV_ERROR_INVALID_ID)
  379. << "Id " << inst->result_id << " is defined more than once";
  380. // Record it.
  381. // A regular value maps to its type. Some instructions (e.g. OpLabel)
  382. // have no type Id, and will map to 0. The result Id for a
  383. // type-generating instruction (e.g. OpTypeInt) maps to itself.
  384. _.id_to_type_id[inst->result_id] =
  385. spvOpcodeGeneratesType(opcode) ? inst->result_id : inst->type_id;
  386. break;
  387. case SPV_OPERAND_TYPE_ID:
  388. case SPV_OPERAND_TYPE_OPTIONAL_ID:
  389. if (!word) return diagnostic(SPV_ERROR_INVALID_ID) << "Id is 0";
  390. parsed_operand.type = SPV_OPERAND_TYPE_ID;
  391. if (opcode == SpvOpExtInst && parsed_operand.offset == 3) {
  392. // The current word is the extended instruction set Id.
  393. // Set the extended instruction set type for the current instruction.
  394. auto ext_inst_type_iter = _.import_id_to_ext_inst_type.find(word);
  395. if (ext_inst_type_iter == _.import_id_to_ext_inst_type.end()) {
  396. return diagnostic(SPV_ERROR_INVALID_ID)
  397. << "OpExtInst set Id " << word
  398. << " does not reference an OpExtInstImport result Id";
  399. }
  400. inst->ext_inst_type = ext_inst_type_iter->second;
  401. }
  402. break;
  403. case SPV_OPERAND_TYPE_SCOPE_ID:
  404. case SPV_OPERAND_TYPE_MEMORY_SEMANTICS_ID:
  405. // Check for trivially invalid values. The operand descriptions already
  406. // have the word "ID" in them.
  407. if (!word) return diagnostic() << spvOperandTypeStr(type) << " is 0";
  408. break;
  409. case SPV_OPERAND_TYPE_EXTENSION_INSTRUCTION_NUMBER: {
  410. assert(SpvOpExtInst == opcode);
  411. assert(inst->ext_inst_type != SPV_EXT_INST_TYPE_NONE);
  412. spv_ext_inst_desc ext_inst;
  413. if (grammar_.lookupExtInst(inst->ext_inst_type, word, &ext_inst))
  414. return diagnostic() << "Invalid extended instruction number: " << word;
  415. spvPushOperandTypes(ext_inst->operandTypes, expected_operands);
  416. } break;
  417. case SPV_OPERAND_TYPE_SPEC_CONSTANT_OP_NUMBER: {
  418. assert(SpvOpSpecConstantOp == opcode);
  419. if (grammar_.lookupSpecConstantOpcode(SpvOp(word))) {
  420. return diagnostic()
  421. << "Invalid " << spvOperandTypeStr(type) << ": " << word;
  422. }
  423. spv_opcode_desc opcode_entry = nullptr;
  424. if (grammar_.lookupOpcode(SpvOp(word), &opcode_entry)) {
  425. return diagnostic(SPV_ERROR_INTERNAL)
  426. << "OpSpecConstant opcode table out of sync";
  427. }
  428. // OpSpecConstant opcodes must have a type and result. We've already
  429. // processed them, so skip them when preparing to parse the other
  430. // operants for the opcode.
  431. assert(opcode_entry->hasType);
  432. assert(opcode_entry->hasResult);
  433. assert(opcode_entry->numTypes >= 2);
  434. spvPushOperandTypes(opcode_entry->operandTypes + 2, expected_operands);
  435. } break;
  436. case SPV_OPERAND_TYPE_LITERAL_INTEGER:
  437. case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_INTEGER:
  438. // These are regular single-word literal integer operands.
  439. // Post-parsing validation should check the range of the parsed value.
  440. parsed_operand.type = SPV_OPERAND_TYPE_LITERAL_INTEGER;
  441. // It turns out they are always unsigned integers!
  442. parsed_operand.number_kind = SPV_NUMBER_UNSIGNED_INT;
  443. parsed_operand.number_bit_width = 32;
  444. break;
  445. case SPV_OPERAND_TYPE_TYPED_LITERAL_NUMBER:
  446. case SPV_OPERAND_TYPE_OPTIONAL_TYPED_LITERAL_INTEGER:
  447. parsed_operand.type = SPV_OPERAND_TYPE_TYPED_LITERAL_NUMBER;
  448. if (opcode == SpvOpSwitch) {
  449. // The literal operands have the same type as the value
  450. // referenced by the selector Id.
  451. const uint32_t selector_id = peekAt(inst_offset + 1);
  452. const auto type_id_iter = _.id_to_type_id.find(selector_id);
  453. if (type_id_iter == _.id_to_type_id.end() ||
  454. type_id_iter->second == 0) {
  455. return diagnostic() << "Invalid OpSwitch: selector id " << selector_id
  456. << " has no type";
  457. }
  458. uint32_t type_id = type_id_iter->second;
  459. if (selector_id == type_id) {
  460. // Recall that by convention, a result ID that is a type definition
  461. // maps to itself.
  462. return diagnostic() << "Invalid OpSwitch: selector id " << selector_id
  463. << " is a type, not a value";
  464. }
  465. if (auto error = setNumericTypeInfoForType(&parsed_operand, type_id))
  466. return error;
  467. if (parsed_operand.number_kind != SPV_NUMBER_UNSIGNED_INT &&
  468. parsed_operand.number_kind != SPV_NUMBER_SIGNED_INT) {
  469. return diagnostic() << "Invalid OpSwitch: selector id " << selector_id
  470. << " is not a scalar integer";
  471. }
  472. } else {
  473. assert(opcode == SpvOpConstant || opcode == SpvOpSpecConstant);
  474. // The literal number type is determined by the type Id for the
  475. // constant.
  476. assert(inst->type_id);
  477. if (auto error =
  478. setNumericTypeInfoForType(&parsed_operand, inst->type_id))
  479. return error;
  480. }
  481. break;
  482. case SPV_OPERAND_TYPE_LITERAL_STRING:
  483. case SPV_OPERAND_TYPE_OPTIONAL_LITERAL_STRING: {
  484. convert_operand_endianness = false;
  485. const char* string =
  486. reinterpret_cast<const char*>(_.words + _.word_index);
  487. // Compute the length of the string, but make sure we don't run off the
  488. // end of the input.
  489. const size_t remaining_input_bytes =
  490. sizeof(uint32_t) * (_.num_words - _.word_index);
  491. const size_t string_num_content_bytes =
  492. spv_strnlen_s(string, remaining_input_bytes);
  493. // If there was no terminating null byte, then that's an end-of-input
  494. // error.
  495. if (string_num_content_bytes == remaining_input_bytes)
  496. return exhaustedInputDiagnostic(inst_offset, opcode, type);
  497. // Account for null in the word length, so add 1 for null, then add 3 to
  498. // make sure we round up. The following is equivalent to:
  499. // (string_num_content_bytes + 1 + 3) / 4
  500. const size_t string_num_words = string_num_content_bytes / 4 + 1;
  501. // Make sure we can record the word count without overflow.
  502. //
  503. // This error can't currently be triggered because of validity
  504. // checks elsewhere.
  505. if (string_num_words > std::numeric_limits<uint16_t>::max()) {
  506. return diagnostic() << "Literal string is longer than "
  507. << std::numeric_limits<uint16_t>::max()
  508. << " words: " << string_num_words << " words long";
  509. }
  510. parsed_operand.num_words = uint16_t(string_num_words);
  511. parsed_operand.type = SPV_OPERAND_TYPE_LITERAL_STRING;
  512. if (SpvOpExtInstImport == opcode) {
  513. // Record the extended instruction type for the ID for this import.
  514. // There is only one string literal argument to OpExtInstImport,
  515. // so it's sufficient to guard this just on the opcode.
  516. const spv_ext_inst_type_t ext_inst_type =
  517. spvExtInstImportTypeGet(string);
  518. if (SPV_EXT_INST_TYPE_NONE == ext_inst_type) {
  519. return diagnostic()
  520. << "Invalid extended instruction import '" << string << "'";
  521. }
  522. // We must have parsed a valid result ID. It's a condition
  523. // of the grammar, and we only accept non-zero result Ids.
  524. assert(inst->result_id);
  525. _.import_id_to_ext_inst_type[inst->result_id] = ext_inst_type;
  526. }
  527. } break;
  528. case SPV_OPERAND_TYPE_CAPABILITY:
  529. case SPV_OPERAND_TYPE_SOURCE_LANGUAGE:
  530. case SPV_OPERAND_TYPE_EXECUTION_MODEL:
  531. case SPV_OPERAND_TYPE_ADDRESSING_MODEL:
  532. case SPV_OPERAND_TYPE_MEMORY_MODEL:
  533. case SPV_OPERAND_TYPE_EXECUTION_MODE:
  534. case SPV_OPERAND_TYPE_STORAGE_CLASS:
  535. case SPV_OPERAND_TYPE_DIMENSIONALITY:
  536. case SPV_OPERAND_TYPE_SAMPLER_ADDRESSING_MODE:
  537. case SPV_OPERAND_TYPE_SAMPLER_FILTER_MODE:
  538. case SPV_OPERAND_TYPE_SAMPLER_IMAGE_FORMAT:
  539. case SPV_OPERAND_TYPE_FP_ROUNDING_MODE:
  540. case SPV_OPERAND_TYPE_LINKAGE_TYPE:
  541. case SPV_OPERAND_TYPE_ACCESS_QUALIFIER:
  542. case SPV_OPERAND_TYPE_OPTIONAL_ACCESS_QUALIFIER:
  543. case SPV_OPERAND_TYPE_FUNCTION_PARAMETER_ATTRIBUTE:
  544. case SPV_OPERAND_TYPE_DECORATION:
  545. case SPV_OPERAND_TYPE_BUILT_IN:
  546. case SPV_OPERAND_TYPE_GROUP_OPERATION:
  547. case SPV_OPERAND_TYPE_KERNEL_ENQ_FLAGS:
  548. case SPV_OPERAND_TYPE_KERNEL_PROFILING_INFO:
  549. case SPV_OPERAND_TYPE_DEBUG_BASE_TYPE_ATTRIBUTE_ENCODING:
  550. case SPV_OPERAND_TYPE_DEBUG_COMPOSITE_TYPE:
  551. case SPV_OPERAND_TYPE_DEBUG_TYPE_QUALIFIER:
  552. case SPV_OPERAND_TYPE_DEBUG_OPERATION: {
  553. // A single word that is a plain enum value.
  554. // Map an optional operand type to its corresponding concrete type.
  555. if (type == SPV_OPERAND_TYPE_OPTIONAL_ACCESS_QUALIFIER)
  556. parsed_operand.type = SPV_OPERAND_TYPE_ACCESS_QUALIFIER;
  557. spv_operand_desc entry;
  558. if (grammar_.lookupOperand(type, word, &entry)) {
  559. return diagnostic()
  560. << "Invalid " << spvOperandTypeStr(parsed_operand.type)
  561. << " operand: " << word;
  562. }
  563. // Prepare to accept operands to this operand, if needed.
  564. spvPushOperandTypes(entry->operandTypes, expected_operands);
  565. } break;
  566. case SPV_OPERAND_TYPE_FP_FAST_MATH_MODE:
  567. case SPV_OPERAND_TYPE_FUNCTION_CONTROL:
  568. case SPV_OPERAND_TYPE_LOOP_CONTROL:
  569. case SPV_OPERAND_TYPE_IMAGE:
  570. case SPV_OPERAND_TYPE_OPTIONAL_IMAGE:
  571. case SPV_OPERAND_TYPE_OPTIONAL_MEMORY_ACCESS:
  572. case SPV_OPERAND_TYPE_SELECTION_CONTROL:
  573. case SPV_OPERAND_TYPE_DEBUG_INFO_FLAGS: {
  574. // This operand is a mask.
  575. // Map an optional operand type to its corresponding concrete type.
  576. if (type == SPV_OPERAND_TYPE_OPTIONAL_IMAGE)
  577. parsed_operand.type = SPV_OPERAND_TYPE_IMAGE;
  578. else if (type == SPV_OPERAND_TYPE_OPTIONAL_MEMORY_ACCESS)
  579. parsed_operand.type = SPV_OPERAND_TYPE_MEMORY_ACCESS;
  580. // Check validity of set mask bits. Also prepare for operands for those
  581. // masks if they have any. To get operand order correct, scan from
  582. // MSB to LSB since we can only prepend operands to a pattern.
  583. // The only case in the grammar where you have more than one mask bit
  584. // having an operand is for image operands. See SPIR-V 3.14 Image
  585. // Operands.
  586. uint32_t remaining_word = word;
  587. for (uint32_t mask = (1u << 31); remaining_word; mask >>= 1) {
  588. if (remaining_word & mask) {
  589. spv_operand_desc entry;
  590. if (grammar_.lookupOperand(type, mask, &entry)) {
  591. return diagnostic()
  592. << "Invalid " << spvOperandTypeStr(parsed_operand.type)
  593. << " operand: " << word << " has invalid mask component "
  594. << mask;
  595. }
  596. remaining_word ^= mask;
  597. spvPushOperandTypes(entry->operandTypes, expected_operands);
  598. }
  599. }
  600. if (word == 0) {
  601. // An all-zeroes mask *might* also be valid.
  602. spv_operand_desc entry;
  603. if (SPV_SUCCESS == grammar_.lookupOperand(type, 0, &entry)) {
  604. // Prepare for its operands, if any.
  605. spvPushOperandTypes(entry->operandTypes, expected_operands);
  606. }
  607. }
  608. } break;
  609. default:
  610. return diagnostic() << "Internal error: Unhandled operand type: " << type;
  611. }
  612. assert(spvOperandIsConcrete(parsed_operand.type));
  613. operands->push_back(parsed_operand);
  614. const size_t index_after_operand = _.word_index + parsed_operand.num_words;
  615. // Avoid buffer overrun for the cases where the operand has more than one
  616. // word, and where it isn't a string. (Those other cases have already been
  617. // handled earlier.) For example, this error can occur for a multi-word
  618. // argument to OpConstant, or a multi-word case literal operand for OpSwitch.
  619. if (_.num_words < index_after_operand)
  620. return exhaustedInputDiagnostic(inst_offset, opcode, type);
  621. if (_.requires_endian_conversion) {
  622. // Copy instruction words. Translate to native endianness as needed.
  623. if (convert_operand_endianness) {
  624. const spv_endianness_t endianness = _.endian;
  625. std::transform(_.words + _.word_index, _.words + index_after_operand,
  626. std::back_inserter(*words),
  627. [endianness](const uint32_t raw_word) {
  628. return spvFixWord(raw_word, endianness);
  629. });
  630. } else {
  631. words->insert(words->end(), _.words + _.word_index,
  632. _.words + index_after_operand);
  633. }
  634. }
  635. // Advance past the operand.
  636. _.word_index = index_after_operand;
  637. return SPV_SUCCESS;
  638. }
  639. spv_result_t Parser::setNumericTypeInfoForType(
  640. spv_parsed_operand_t* parsed_operand, uint32_t type_id) {
  641. assert(type_id != 0);
  642. auto type_info_iter = _.type_id_to_number_type_info.find(type_id);
  643. if (type_info_iter == _.type_id_to_number_type_info.end()) {
  644. return diagnostic() << "Type Id " << type_id << " is not a type";
  645. }
  646. const NumberType& info = type_info_iter->second;
  647. if (info.type == SPV_NUMBER_NONE) {
  648. // This is a valid type, but for something other than a scalar number.
  649. return diagnostic() << "Type Id " << type_id
  650. << " is not a scalar numeric type";
  651. }
  652. parsed_operand->number_kind = info.type;
  653. parsed_operand->number_bit_width = info.bit_width;
  654. // Round up the word count.
  655. parsed_operand->num_words = static_cast<uint16_t>((info.bit_width + 31) / 32);
  656. return SPV_SUCCESS;
  657. }
  658. void Parser::recordNumberType(size_t inst_offset,
  659. const spv_parsed_instruction_t* inst) {
  660. const SpvOp opcode = static_cast<SpvOp>(inst->opcode);
  661. if (spvOpcodeGeneratesType(opcode)) {
  662. NumberType info = {SPV_NUMBER_NONE, 0};
  663. if (SpvOpTypeInt == opcode) {
  664. const bool is_signed = peekAt(inst_offset + 3) != 0;
  665. info.type = is_signed ? SPV_NUMBER_SIGNED_INT : SPV_NUMBER_UNSIGNED_INT;
  666. info.bit_width = peekAt(inst_offset + 2);
  667. } else if (SpvOpTypeFloat == opcode) {
  668. info.type = SPV_NUMBER_FLOATING;
  669. info.bit_width = peekAt(inst_offset + 2);
  670. }
  671. // The *result* Id of a type generating instruction is the type Id.
  672. _.type_id_to_number_type_info[inst->result_id] = info;
  673. }
  674. }
  675. } // anonymous namespace
  676. spv_result_t spvBinaryParse(const spv_const_context context, void* user_data,
  677. const uint32_t* code, const size_t num_words,
  678. spv_parsed_header_fn_t parsed_header,
  679. spv_parsed_instruction_fn_t parsed_instruction,
  680. spv_diagnostic* diagnostic) {
  681. spv_context_t hijack_context = *context;
  682. if (diagnostic) {
  683. *diagnostic = nullptr;
  684. spvtools::UseDiagnosticAsMessageConsumer(&hijack_context, diagnostic);
  685. }
  686. Parser parser(&hijack_context, user_data, parsed_header, parsed_instruction);
  687. return parser.parse(code, num_words, diagnostic);
  688. }
  689. // TODO(dneto): This probably belongs in text.cpp since that's the only place
  690. // that a spv_binary_t value is created.
  691. void spvBinaryDestroy(spv_binary binary) {
  692. if (!binary) return;
  693. delete[] binary->code;
  694. delete binary;
  695. }
  696. size_t spv_strnlen_s(const char* str, size_t strsz) {
  697. if (!str) return 0;
  698. for (size_t i = 0; i < strsz; i++) {
  699. if (!str[i]) return i;
  700. }
  701. return strsz;
  702. }