disassemble.cpp 18 KB

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