binary.cpp 33 KB

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