disassemble.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. // Copyright (c) 2015-2020 The Khronos Group Inc.
  2. // Modifications Copyright (C) 2020 Advanced Micro Devices, Inc. All rights
  3. // reserved.
  4. //
  5. // Licensed under the Apache License, Version 2.0 (the "License");
  6. // you may not use this file except in compliance with the License.
  7. // You may obtain a copy of the License at
  8. //
  9. // http://www.apache.org/licenses/LICENSE-2.0
  10. //
  11. // Unless required by applicable law or agreed to in writing, software
  12. // distributed under the License is distributed on an "AS IS" BASIS,
  13. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. // See the License for the specific language governing permissions and
  15. // limitations under the License.
  16. // This file contains a disassembler: It converts a SPIR-V binary
  17. // to text.
  18. #include <algorithm>
  19. #include <cassert>
  20. #include <cstring>
  21. #include <iomanip>
  22. #include <memory>
  23. #include <unordered_map>
  24. #include <utility>
  25. #include "source/assembly_grammar.h"
  26. #include "source/binary.h"
  27. #include "source/diagnostic.h"
  28. #include "source/disassemble.h"
  29. #include "source/ext_inst.h"
  30. #include "source/name_mapper.h"
  31. #include "source/opcode.h"
  32. #include "source/parsed_operand.h"
  33. #include "source/print.h"
  34. #include "source/spirv_constant.h"
  35. #include "source/spirv_endian.h"
  36. #include "source/util/hex_float.h"
  37. #include "source/util/make_unique.h"
  38. #include "spirv-tools/libspirv.h"
  39. namespace {
  40. // A Disassembler instance converts a SPIR-V binary to its assembly
  41. // representation.
  42. class Disassembler {
  43. public:
  44. Disassembler(const spvtools::AssemblyGrammar& grammar, uint32_t options,
  45. spvtools::NameMapper name_mapper)
  46. : grammar_(grammar),
  47. print_(spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_PRINT, options)),
  48. color_(spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_COLOR, options)),
  49. indent_(spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_INDENT, options)
  50. ? kStandardIndent
  51. : 0),
  52. text_(),
  53. out_(print_ ? out_stream() : out_stream(text_)),
  54. stream_(out_.get()),
  55. header_(!spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_NO_HEADER, options)),
  56. show_byte_offset_(spvIsInBitfield(
  57. SPV_BINARY_TO_TEXT_OPTION_SHOW_BYTE_OFFSET, options)),
  58. byte_offset_(0),
  59. name_mapper_(std::move(name_mapper)) {}
  60. // Emits the assembly header for the module, and sets up internal state
  61. // so subsequent callbacks can handle the cases where the entire module
  62. // is either big-endian or little-endian.
  63. spv_result_t HandleHeader(spv_endianness_t endian, uint32_t version,
  64. uint32_t generator, uint32_t id_bound,
  65. uint32_t schema);
  66. // Emits the assembly text for the given instruction.
  67. spv_result_t HandleInstruction(const spv_parsed_instruction_t& inst);
  68. // If not printing, populates text_result with the accumulated text.
  69. // Returns SPV_SUCCESS on success.
  70. spv_result_t SaveTextResult(spv_text* text_result) const;
  71. private:
  72. enum { kStandardIndent = 15 };
  73. using out_stream = spvtools::out_stream;
  74. // Emits an operand for the given instruction, where the instruction
  75. // is at offset words from the start of the binary.
  76. void EmitOperand(const spv_parsed_instruction_t& inst,
  77. const uint16_t operand_index);
  78. // Emits a mask expression for the given mask word of the specified type.
  79. void EmitMaskOperand(const spv_operand_type_t type, const uint32_t word);
  80. // Resets the output color, if color is turned on.
  81. void ResetColor() {
  82. if (color_) out_.get() << spvtools::clr::reset{print_};
  83. }
  84. // Sets the output to grey, if color is turned on.
  85. void SetGrey() {
  86. if (color_) out_.get() << spvtools::clr::grey{print_};
  87. }
  88. // Sets the output to blue, if color is turned on.
  89. void SetBlue() {
  90. if (color_) out_.get() << spvtools::clr::blue{print_};
  91. }
  92. // Sets the output to yellow, if color is turned on.
  93. void SetYellow() {
  94. if (color_) out_.get() << spvtools::clr::yellow{print_};
  95. }
  96. // Sets the output to red, if color is turned on.
  97. void SetRed() {
  98. if (color_) out_.get() << spvtools::clr::red{print_};
  99. }
  100. // Sets the output to green, if color is turned on.
  101. void SetGreen() {
  102. if (color_) out_.get() << spvtools::clr::green{print_};
  103. }
  104. const spvtools::AssemblyGrammar& grammar_;
  105. const bool print_; // Should we also print to the standard output stream?
  106. const bool color_; // Should we print in colour?
  107. const int indent_; // How much to indent. 0 means don't indent
  108. spv_endianness_t endian_; // The detected endianness of the binary.
  109. std::stringstream text_; // Captures the text, if not printing.
  110. out_stream out_; // The Output stream. Either to text_ or standard output.
  111. std::ostream& stream_; // The output std::stream.
  112. const bool header_; // Should we output header as the leading comment?
  113. const bool show_byte_offset_; // Should we print byte offset, in hex?
  114. size_t byte_offset_; // The number of bytes processed so far.
  115. spvtools::NameMapper name_mapper_;
  116. };
  117. spv_result_t Disassembler::HandleHeader(spv_endianness_t endian,
  118. uint32_t version, uint32_t generator,
  119. uint32_t id_bound, uint32_t schema) {
  120. endian_ = endian;
  121. if (header_) {
  122. SetGrey();
  123. const char* generator_tool =
  124. spvGeneratorStr(SPV_GENERATOR_TOOL_PART(generator));
  125. stream_ << "; SPIR-V\n"
  126. << "; Version: " << SPV_SPIRV_VERSION_MAJOR_PART(version) << "."
  127. << SPV_SPIRV_VERSION_MINOR_PART(version) << "\n"
  128. << "; Generator: " << generator_tool;
  129. // For unknown tools, print the numeric tool value.
  130. if (0 == strcmp("Unknown", generator_tool)) {
  131. stream_ << "(" << SPV_GENERATOR_TOOL_PART(generator) << ")";
  132. }
  133. // Print the miscellaneous part of the generator word on the same
  134. // line as the tool name.
  135. stream_ << "; " << SPV_GENERATOR_MISC_PART(generator) << "\n"
  136. << "; Bound: " << id_bound << "\n"
  137. << "; Schema: " << schema << "\n";
  138. ResetColor();
  139. }
  140. byte_offset_ = SPV_INDEX_INSTRUCTION * sizeof(uint32_t);
  141. return SPV_SUCCESS;
  142. }
  143. spv_result_t Disassembler::HandleInstruction(
  144. const spv_parsed_instruction_t& inst) {
  145. if (inst.result_id) {
  146. SetBlue();
  147. const std::string id_name = name_mapper_(inst.result_id);
  148. if (indent_)
  149. stream_ << std::setw(std::max(0, indent_ - 3 - int(id_name.size())));
  150. stream_ << "%" << id_name;
  151. ResetColor();
  152. stream_ << " = ";
  153. } else {
  154. stream_ << std::string(indent_, ' ');
  155. }
  156. stream_ << "Op" << spvOpcodeString(static_cast<SpvOp>(inst.opcode));
  157. for (uint16_t i = 0; i < inst.num_operands; i++) {
  158. const spv_operand_type_t type = inst.operands[i].type;
  159. assert(type != SPV_OPERAND_TYPE_NONE);
  160. if (type == SPV_OPERAND_TYPE_RESULT_ID) continue;
  161. stream_ << " ";
  162. EmitOperand(inst, i);
  163. }
  164. if (show_byte_offset_) {
  165. SetGrey();
  166. auto saved_flags = stream_.flags();
  167. auto saved_fill = stream_.fill();
  168. stream_ << " ; 0x" << std::setw(8) << std::hex << std::setfill('0')
  169. << byte_offset_;
  170. stream_.flags(saved_flags);
  171. stream_.fill(saved_fill);
  172. ResetColor();
  173. }
  174. byte_offset_ += inst.num_words * sizeof(uint32_t);
  175. stream_ << "\n";
  176. return SPV_SUCCESS;
  177. }
  178. void Disassembler::EmitOperand(const spv_parsed_instruction_t& inst,
  179. const uint16_t operand_index) {
  180. assert(operand_index < inst.num_operands);
  181. const spv_parsed_operand_t& operand = inst.operands[operand_index];
  182. const uint32_t word = inst.words[operand.offset];
  183. switch (operand.type) {
  184. case SPV_OPERAND_TYPE_RESULT_ID:
  185. assert(false && "<result-id> is not supposed to be handled here");
  186. SetBlue();
  187. stream_ << "%" << name_mapper_(word);
  188. break;
  189. case SPV_OPERAND_TYPE_ID:
  190. case SPV_OPERAND_TYPE_TYPE_ID:
  191. case SPV_OPERAND_TYPE_SCOPE_ID:
  192. case SPV_OPERAND_TYPE_MEMORY_SEMANTICS_ID:
  193. SetYellow();
  194. stream_ << "%" << name_mapper_(word);
  195. break;
  196. case SPV_OPERAND_TYPE_EXTENSION_INSTRUCTION_NUMBER: {
  197. spv_ext_inst_desc ext_inst;
  198. SetRed();
  199. if (grammar_.lookupExtInst(inst.ext_inst_type, word, &ext_inst) ==
  200. SPV_SUCCESS) {
  201. stream_ << ext_inst->name;
  202. } else {
  203. if (!spvExtInstIsNonSemantic(inst.ext_inst_type)) {
  204. assert(false && "should have caught this earlier");
  205. } else {
  206. // for non-semantic instruction sets we can just print the number
  207. stream_ << word;
  208. }
  209. }
  210. } break;
  211. case SPV_OPERAND_TYPE_SPEC_CONSTANT_OP_NUMBER: {
  212. spv_opcode_desc opcode_desc;
  213. if (grammar_.lookupOpcode(SpvOp(word), &opcode_desc))
  214. assert(false && "should have caught this earlier");
  215. SetRed();
  216. stream_ << opcode_desc->name;
  217. } break;
  218. case SPV_OPERAND_TYPE_LITERAL_INTEGER:
  219. case SPV_OPERAND_TYPE_TYPED_LITERAL_NUMBER: {
  220. SetRed();
  221. spvtools::EmitNumericLiteral(&stream_, inst, operand);
  222. ResetColor();
  223. } break;
  224. case SPV_OPERAND_TYPE_LITERAL_STRING: {
  225. stream_ << "\"";
  226. SetGreen();
  227. // Strings are always little-endian, and null-terminated.
  228. // Write out the characters, escaping as needed, and without copying
  229. // the entire string.
  230. auto c_str = reinterpret_cast<const char*>(inst.words + operand.offset);
  231. for (auto p = c_str; *p; ++p) {
  232. if (*p == '"' || *p == '\\') stream_ << '\\';
  233. stream_ << *p;
  234. }
  235. ResetColor();
  236. stream_ << '"';
  237. } break;
  238. case SPV_OPERAND_TYPE_CAPABILITY:
  239. case SPV_OPERAND_TYPE_SOURCE_LANGUAGE:
  240. case SPV_OPERAND_TYPE_EXECUTION_MODEL:
  241. case SPV_OPERAND_TYPE_ADDRESSING_MODEL:
  242. case SPV_OPERAND_TYPE_MEMORY_MODEL:
  243. case SPV_OPERAND_TYPE_EXECUTION_MODE:
  244. case SPV_OPERAND_TYPE_STORAGE_CLASS:
  245. case SPV_OPERAND_TYPE_DIMENSIONALITY:
  246. case SPV_OPERAND_TYPE_SAMPLER_ADDRESSING_MODE:
  247. case SPV_OPERAND_TYPE_SAMPLER_FILTER_MODE:
  248. case SPV_OPERAND_TYPE_SAMPLER_IMAGE_FORMAT:
  249. case SPV_OPERAND_TYPE_FP_ROUNDING_MODE:
  250. case SPV_OPERAND_TYPE_LINKAGE_TYPE:
  251. case SPV_OPERAND_TYPE_ACCESS_QUALIFIER:
  252. case SPV_OPERAND_TYPE_FUNCTION_PARAMETER_ATTRIBUTE:
  253. case SPV_OPERAND_TYPE_DECORATION:
  254. case SPV_OPERAND_TYPE_BUILT_IN:
  255. case SPV_OPERAND_TYPE_GROUP_OPERATION:
  256. case SPV_OPERAND_TYPE_KERNEL_ENQ_FLAGS:
  257. case SPV_OPERAND_TYPE_KERNEL_PROFILING_INFO:
  258. case SPV_OPERAND_TYPE_RAY_FLAGS:
  259. case SPV_OPERAND_TYPE_RAY_QUERY_INTERSECTION:
  260. case SPV_OPERAND_TYPE_RAY_QUERY_COMMITTED_INTERSECTION_TYPE:
  261. case SPV_OPERAND_TYPE_RAY_QUERY_CANDIDATE_INTERSECTION_TYPE:
  262. case SPV_OPERAND_TYPE_DEBUG_BASE_TYPE_ATTRIBUTE_ENCODING:
  263. case SPV_OPERAND_TYPE_DEBUG_COMPOSITE_TYPE:
  264. case SPV_OPERAND_TYPE_DEBUG_TYPE_QUALIFIER:
  265. case SPV_OPERAND_TYPE_DEBUG_OPERATION:
  266. case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_BASE_TYPE_ATTRIBUTE_ENCODING:
  267. case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_COMPOSITE_TYPE:
  268. case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_TYPE_QUALIFIER:
  269. case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_OPERATION:
  270. case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_IMPORTED_ENTITY: {
  271. spv_operand_desc entry;
  272. if (grammar_.lookupOperand(operand.type, word, &entry))
  273. assert(false && "should have caught this earlier");
  274. stream_ << entry->name;
  275. } break;
  276. case SPV_OPERAND_TYPE_FP_FAST_MATH_MODE:
  277. case SPV_OPERAND_TYPE_FUNCTION_CONTROL:
  278. case SPV_OPERAND_TYPE_LOOP_CONTROL:
  279. case SPV_OPERAND_TYPE_IMAGE:
  280. case SPV_OPERAND_TYPE_MEMORY_ACCESS:
  281. case SPV_OPERAND_TYPE_SELECTION_CONTROL:
  282. case SPV_OPERAND_TYPE_DEBUG_INFO_FLAGS:
  283. case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_INFO_FLAGS:
  284. EmitMaskOperand(operand.type, word);
  285. break;
  286. default:
  287. assert(false && "unhandled or invalid case");
  288. }
  289. ResetColor();
  290. }
  291. void Disassembler::EmitMaskOperand(const spv_operand_type_t type,
  292. const uint32_t word) {
  293. // Scan the mask from least significant bit to most significant bit. For each
  294. // set bit, emit the name of that bit. Separate multiple names with '|'.
  295. uint32_t remaining_word = word;
  296. uint32_t mask;
  297. int num_emitted = 0;
  298. for (mask = 1; remaining_word; mask <<= 1) {
  299. if (remaining_word & mask) {
  300. remaining_word ^= mask;
  301. spv_operand_desc entry;
  302. if (grammar_.lookupOperand(type, mask, &entry))
  303. assert(false && "should have caught this earlier");
  304. if (num_emitted) stream_ << "|";
  305. stream_ << entry->name;
  306. num_emitted++;
  307. }
  308. }
  309. if (!num_emitted) {
  310. // An operand value of 0 was provided, so represent it by the name
  311. // of the 0 value. In many cases, that's "None".
  312. spv_operand_desc entry;
  313. if (SPV_SUCCESS == grammar_.lookupOperand(type, 0, &entry))
  314. stream_ << entry->name;
  315. }
  316. }
  317. spv_result_t Disassembler::SaveTextResult(spv_text* text_result) const {
  318. if (!print_) {
  319. size_t length = text_.str().size();
  320. char* str = new char[length + 1];
  321. if (!str) return SPV_ERROR_OUT_OF_MEMORY;
  322. strncpy(str, text_.str().c_str(), length + 1);
  323. spv_text text = new spv_text_t();
  324. if (!text) {
  325. delete[] str;
  326. return SPV_ERROR_OUT_OF_MEMORY;
  327. }
  328. text->str = str;
  329. text->length = length;
  330. *text_result = text;
  331. }
  332. return SPV_SUCCESS;
  333. }
  334. spv_result_t DisassembleHeader(void* user_data, spv_endianness_t endian,
  335. uint32_t /* magic */, uint32_t version,
  336. uint32_t generator, uint32_t id_bound,
  337. uint32_t schema) {
  338. assert(user_data);
  339. auto disassembler = static_cast<Disassembler*>(user_data);
  340. return disassembler->HandleHeader(endian, version, generator, id_bound,
  341. schema);
  342. }
  343. spv_result_t DisassembleInstruction(
  344. void* user_data, const spv_parsed_instruction_t* parsed_instruction) {
  345. assert(user_data);
  346. auto disassembler = static_cast<Disassembler*>(user_data);
  347. return disassembler->HandleInstruction(*parsed_instruction);
  348. }
  349. // Simple wrapper class to provide extra data necessary for targeted
  350. // instruction disassembly.
  351. class WrappedDisassembler {
  352. public:
  353. WrappedDisassembler(Disassembler* dis, const uint32_t* binary, size_t wc)
  354. : disassembler_(dis), inst_binary_(binary), word_count_(wc) {}
  355. Disassembler* disassembler() { return disassembler_; }
  356. const uint32_t* inst_binary() const { return inst_binary_; }
  357. size_t word_count() const { return word_count_; }
  358. private:
  359. Disassembler* disassembler_;
  360. const uint32_t* inst_binary_;
  361. const size_t word_count_;
  362. };
  363. spv_result_t DisassembleTargetHeader(void* user_data, spv_endianness_t endian,
  364. uint32_t /* magic */, uint32_t version,
  365. uint32_t generator, uint32_t id_bound,
  366. uint32_t schema) {
  367. assert(user_data);
  368. auto wrapped = static_cast<WrappedDisassembler*>(user_data);
  369. return wrapped->disassembler()->HandleHeader(endian, version, generator,
  370. id_bound, schema);
  371. }
  372. spv_result_t DisassembleTargetInstruction(
  373. void* user_data, const spv_parsed_instruction_t* parsed_instruction) {
  374. assert(user_data);
  375. auto wrapped = static_cast<WrappedDisassembler*>(user_data);
  376. // Check if this is the instruction we want to disassemble.
  377. if (wrapped->word_count() == parsed_instruction->num_words &&
  378. std::equal(wrapped->inst_binary(),
  379. wrapped->inst_binary() + wrapped->word_count(),
  380. parsed_instruction->words)) {
  381. // Found the target instruction. Disassemble it and signal that we should
  382. // stop searching so we don't output the same instruction again.
  383. if (auto error =
  384. wrapped->disassembler()->HandleInstruction(*parsed_instruction))
  385. return error;
  386. return SPV_REQUESTED_TERMINATION;
  387. }
  388. return SPV_SUCCESS;
  389. }
  390. } // namespace
  391. spv_result_t spvBinaryToText(const spv_const_context context,
  392. const uint32_t* code, const size_t wordCount,
  393. const uint32_t options, spv_text* pText,
  394. spv_diagnostic* pDiagnostic) {
  395. spv_context_t hijack_context = *context;
  396. if (pDiagnostic) {
  397. *pDiagnostic = nullptr;
  398. spvtools::UseDiagnosticAsMessageConsumer(&hijack_context, pDiagnostic);
  399. }
  400. const spvtools::AssemblyGrammar grammar(&hijack_context);
  401. if (!grammar.isValid()) return SPV_ERROR_INVALID_TABLE;
  402. // Generate friendly names for Ids if requested.
  403. std::unique_ptr<spvtools::FriendlyNameMapper> friendly_mapper;
  404. spvtools::NameMapper name_mapper = spvtools::GetTrivialNameMapper();
  405. if (options & SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES) {
  406. friendly_mapper = spvtools::MakeUnique<spvtools::FriendlyNameMapper>(
  407. &hijack_context, code, wordCount);
  408. name_mapper = friendly_mapper->GetNameMapper();
  409. }
  410. // Now disassemble!
  411. Disassembler disassembler(grammar, options, name_mapper);
  412. if (auto error = spvBinaryParse(&hijack_context, &disassembler, code,
  413. wordCount, DisassembleHeader,
  414. DisassembleInstruction, pDiagnostic)) {
  415. return error;
  416. }
  417. return disassembler.SaveTextResult(pText);
  418. }
  419. std::string spvtools::spvInstructionBinaryToText(const spv_target_env env,
  420. const uint32_t* instCode,
  421. const size_t instWordCount,
  422. const uint32_t* code,
  423. const size_t wordCount,
  424. const uint32_t options) {
  425. spv_context context = spvContextCreate(env);
  426. const spvtools::AssemblyGrammar grammar(context);
  427. if (!grammar.isValid()) {
  428. spvContextDestroy(context);
  429. return "";
  430. }
  431. // Generate friendly names for Ids if requested.
  432. std::unique_ptr<spvtools::FriendlyNameMapper> friendly_mapper;
  433. spvtools::NameMapper name_mapper = spvtools::GetTrivialNameMapper();
  434. if (options & SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES) {
  435. friendly_mapper = spvtools::MakeUnique<spvtools::FriendlyNameMapper>(
  436. context, code, wordCount);
  437. name_mapper = friendly_mapper->GetNameMapper();
  438. }
  439. // Now disassemble!
  440. Disassembler disassembler(grammar, options, name_mapper);
  441. WrappedDisassembler wrapped(&disassembler, instCode, instWordCount);
  442. spvBinaryParse(context, &wrapped, code, wordCount, DisassembleTargetHeader,
  443. DisassembleTargetInstruction, nullptr);
  444. spv_text text = nullptr;
  445. std::string output;
  446. if (disassembler.SaveTextResult(&text) == SPV_SUCCESS) {
  447. output.assign(text->str, text->str + text->length);
  448. // Drop trailing newline characters.
  449. while (!output.empty() && output.back() == '\n') output.pop_back();
  450. }
  451. spvTextDestroy(text);
  452. spvContextDestroy(context);
  453. return output;
  454. }