fuzzer_pass_construct_composites.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. // Copyright (c) 2019 Google LLC
  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/fuzz/fuzzer_pass_construct_composites.h"
  15. #include <cmath>
  16. #include <memory>
  17. #include "source/fuzz/fuzzer_util.h"
  18. #include "source/fuzz/transformation_composite_construct.h"
  19. #include "source/util/make_unique.h"
  20. namespace spvtools {
  21. namespace fuzz {
  22. FuzzerPassConstructComposites::FuzzerPassConstructComposites(
  23. opt::IRContext* ir_context, FactManager* fact_manager,
  24. FuzzerContext* fuzzer_context,
  25. protobufs::TransformationSequence* transformations)
  26. : FuzzerPass(ir_context, fact_manager, fuzzer_context, transformations) {}
  27. FuzzerPassConstructComposites::~FuzzerPassConstructComposites() = default;
  28. void FuzzerPassConstructComposites::Apply() {
  29. // Gather up the ids of all composite types.
  30. std::vector<uint32_t> composite_type_ids;
  31. for (auto& inst : GetIRContext()->types_values()) {
  32. if (fuzzerutil::IsCompositeType(
  33. GetIRContext()->get_type_mgr()->GetType(inst.result_id()))) {
  34. composite_type_ids.push_back(inst.result_id());
  35. }
  36. }
  37. MaybeAddTransformationBeforeEachInstruction(
  38. [this, &composite_type_ids](
  39. const opt::Function& function, opt::BasicBlock* block,
  40. opt::BasicBlock::iterator inst_it,
  41. const protobufs::InstructionDescriptor& instruction_descriptor)
  42. -> void {
  43. // Check whether it is legitimate to insert a composite construction
  44. // before the instruction.
  45. if (!fuzzerutil::CanInsertOpcodeBeforeInstruction(
  46. SpvOpCompositeConstruct, inst_it)) {
  47. return;
  48. }
  49. // Randomly decide whether to try inserting an object copy here.
  50. if (!GetFuzzerContext()->ChoosePercentage(
  51. GetFuzzerContext()->GetChanceOfConstructingComposite())) {
  52. return;
  53. }
  54. // For each instruction that is available at this program point (i.e. an
  55. // instruction that is global or whose definition strictly dominates the
  56. // program point) and suitable for making a synonym of, associate it
  57. // with the id of its result type.
  58. TypeIdToInstructions type_id_to_available_instructions;
  59. for (auto instruction : FindAvailableInstructions(
  60. function, block, inst_it, fuzzerutil::CanMakeSynonymOf)) {
  61. RecordAvailableInstruction(instruction,
  62. &type_id_to_available_instructions);
  63. }
  64. // At this point, |composite_type_ids| captures all the composite types
  65. // we could try to create, while |type_id_to_available_instructions|
  66. // captures all the available result ids we might use, organized by
  67. // type.
  68. // Now we try to find a composite that we can construct. We might not
  69. // manage, if there is a paucity of available ingredients in the module
  70. // (e.g. if our only available composite was a boolean vector and we had
  71. // no instructions generating boolean result types available).
  72. //
  73. // If we succeed, |chosen_composite_type| will end up being non-zero,
  74. // and |constructor_arguments| will end up giving us result ids suitable
  75. // for constructing a composite of that type. Otherwise these variables
  76. // will remain 0 and null respectively.
  77. uint32_t chosen_composite_type = 0;
  78. std::unique_ptr<std::vector<uint32_t>> constructor_arguments = nullptr;
  79. // Initially, all composite type ids are available for us to try. Keep
  80. // trying until we run out of options.
  81. auto composites_to_try_constructing = composite_type_ids;
  82. while (!composites_to_try_constructing.empty()) {
  83. // Remove a composite type from the composite types left for us to
  84. // try.
  85. auto index =
  86. GetFuzzerContext()->RandomIndex(composites_to_try_constructing);
  87. auto next_composite_to_try_constructing =
  88. composites_to_try_constructing[index];
  89. composites_to_try_constructing.erase(
  90. composites_to_try_constructing.begin() + index);
  91. // Now try to construct a composite of this type, using an appropriate
  92. // helper method depending on the kind of composite type.
  93. auto composite_type = GetIRContext()->get_type_mgr()->GetType(
  94. next_composite_to_try_constructing);
  95. if (auto array_type = composite_type->AsArray()) {
  96. constructor_arguments = TryConstructingArrayComposite(
  97. *array_type, type_id_to_available_instructions);
  98. } else if (auto matrix_type = composite_type->AsMatrix()) {
  99. constructor_arguments = TryConstructingMatrixComposite(
  100. *matrix_type, type_id_to_available_instructions);
  101. } else if (auto struct_type = composite_type->AsStruct()) {
  102. constructor_arguments = TryConstructingStructComposite(
  103. *struct_type, type_id_to_available_instructions);
  104. } else {
  105. auto vector_type = composite_type->AsVector();
  106. assert(vector_type &&
  107. "The space of possible composite types should be covered by "
  108. "the above cases.");
  109. constructor_arguments = TryConstructingVectorComposite(
  110. *vector_type, type_id_to_available_instructions);
  111. }
  112. if (constructor_arguments != nullptr) {
  113. // We succeeded! Note the composite type we finally settled on, and
  114. // exit from the loop.
  115. chosen_composite_type = next_composite_to_try_constructing;
  116. break;
  117. }
  118. }
  119. if (!chosen_composite_type) {
  120. // We did not manage to make a composite; return 0 to indicate that no
  121. // instructions were added.
  122. assert(constructor_arguments == nullptr);
  123. return;
  124. }
  125. assert(constructor_arguments != nullptr);
  126. // Make and apply a transformation.
  127. TransformationCompositeConstruct transformation(
  128. chosen_composite_type, *constructor_arguments,
  129. instruction_descriptor, GetFuzzerContext()->GetFreshId());
  130. assert(transformation.IsApplicable(GetIRContext(), *GetFactManager()) &&
  131. "This transformation should be applicable by construction.");
  132. transformation.Apply(GetIRContext(), GetFactManager());
  133. *GetTransformations()->add_transformation() =
  134. transformation.ToMessage();
  135. // Indicate that one instruction was added.
  136. });
  137. }
  138. void FuzzerPassConstructComposites::RecordAvailableInstruction(
  139. opt::Instruction* inst,
  140. TypeIdToInstructions* type_id_to_available_instructions) {
  141. if (type_id_to_available_instructions->count(inst->type_id()) == 0) {
  142. (*type_id_to_available_instructions)[inst->type_id()] = {};
  143. }
  144. type_id_to_available_instructions->at(inst->type_id()).push_back(inst);
  145. }
  146. std::unique_ptr<std::vector<uint32_t>>
  147. FuzzerPassConstructComposites::TryConstructingArrayComposite(
  148. const opt::analysis::Array& array_type,
  149. const TypeIdToInstructions& type_id_to_available_instructions) {
  150. // At present we assume arrays have a constant size.
  151. assert(array_type.length_info().words.size() == 2);
  152. assert(array_type.length_info().words[0] ==
  153. opt::analysis::Array::LengthInfo::kConstant);
  154. auto result = MakeUnique<std::vector<uint32_t>>();
  155. // Get the element type for the array.
  156. auto element_type_id =
  157. GetIRContext()->get_type_mgr()->GetId(array_type.element_type());
  158. // Get all instructions at our disposal that compute something of this element
  159. // type.
  160. auto available_instructions =
  161. type_id_to_available_instructions.find(element_type_id);
  162. if (available_instructions == type_id_to_available_instructions.cend()) {
  163. // If there are not any instructions available that compute the element type
  164. // of the array then we are not in a position to construct a composite with
  165. // this array type.
  166. return nullptr;
  167. }
  168. for (uint32_t index = 0; index < array_type.length_info().words[1]; index++) {
  169. result->push_back(available_instructions
  170. ->second[GetFuzzerContext()->RandomIndex(
  171. available_instructions->second)]
  172. ->result_id());
  173. }
  174. return result;
  175. }
  176. std::unique_ptr<std::vector<uint32_t>>
  177. FuzzerPassConstructComposites::TryConstructingMatrixComposite(
  178. const opt::analysis::Matrix& matrix_type,
  179. const TypeIdToInstructions& type_id_to_available_instructions) {
  180. auto result = MakeUnique<std::vector<uint32_t>>();
  181. // Get the element type for the matrix.
  182. auto element_type_id =
  183. GetIRContext()->get_type_mgr()->GetId(matrix_type.element_type());
  184. // Get all instructions at our disposal that compute something of this element
  185. // type.
  186. auto available_instructions =
  187. type_id_to_available_instructions.find(element_type_id);
  188. if (available_instructions == type_id_to_available_instructions.cend()) {
  189. // If there are not any instructions available that compute the element type
  190. // of the matrix then we are not in a position to construct a composite with
  191. // this matrix type.
  192. return nullptr;
  193. }
  194. for (uint32_t index = 0; index < matrix_type.element_count(); index++) {
  195. result->push_back(available_instructions
  196. ->second[GetFuzzerContext()->RandomIndex(
  197. available_instructions->second)]
  198. ->result_id());
  199. }
  200. return result;
  201. }
  202. std::unique_ptr<std::vector<uint32_t>>
  203. FuzzerPassConstructComposites::TryConstructingStructComposite(
  204. const opt::analysis::Struct& struct_type,
  205. const TypeIdToInstructions& type_id_to_available_instructions) {
  206. auto result = MakeUnique<std::vector<uint32_t>>();
  207. // Consider the type of each field of the struct.
  208. for (auto element_type : struct_type.element_types()) {
  209. auto element_type_id = GetIRContext()->get_type_mgr()->GetId(element_type);
  210. // Find the instructions at our disposal that compute something of the field
  211. // type.
  212. auto available_instructions =
  213. type_id_to_available_instructions.find(element_type_id);
  214. if (available_instructions == type_id_to_available_instructions.cend()) {
  215. // If there are no such instructions, we cannot construct a composite of
  216. // this struct type.
  217. return nullptr;
  218. }
  219. result->push_back(available_instructions
  220. ->second[GetFuzzerContext()->RandomIndex(
  221. available_instructions->second)]
  222. ->result_id());
  223. }
  224. return result;
  225. }
  226. std::unique_ptr<std::vector<uint32_t>>
  227. FuzzerPassConstructComposites::TryConstructingVectorComposite(
  228. const opt::analysis::Vector& vector_type,
  229. const TypeIdToInstructions& type_id_to_available_instructions) {
  230. // Get details of the type underlying the vector, and the width of the vector,
  231. // for convenience.
  232. auto element_type = vector_type.element_type();
  233. auto element_count = vector_type.element_count();
  234. // Collect a mapping, from type id to width, for scalar/vector types that are
  235. // smaller in width than |vector_type|, but that have the same underlying
  236. // type. For example, if |vector_type| is vec4, the mapping will be:
  237. // { float -> 1, vec2 -> 2, vec3 -> 3 }
  238. // The mapping will have missing entries if some of these types do not exist.
  239. std::map<uint32_t, uint32_t> smaller_vector_type_id_to_width;
  240. // Add the underlying type. This id must exist, in order for |vector_type| to
  241. // exist.
  242. auto scalar_type_id = GetIRContext()->get_type_mgr()->GetId(element_type);
  243. smaller_vector_type_id_to_width[scalar_type_id] = 1;
  244. // Now add every vector type with width at least 2, and less than the width of
  245. // |vector_type|.
  246. for (uint32_t width = 2; width < element_count; width++) {
  247. opt::analysis::Vector smaller_vector_type(vector_type.element_type(),
  248. width);
  249. auto smaller_vector_type_id =
  250. GetIRContext()->get_type_mgr()->GetId(&smaller_vector_type);
  251. // We might find that there is no declared type of this smaller width.
  252. // For example, a module can declare vec4 without having declared vec2 or
  253. // vec3.
  254. if (smaller_vector_type_id) {
  255. smaller_vector_type_id_to_width[smaller_vector_type_id] = width;
  256. }
  257. }
  258. // Now we know the types that are available to us, we set about populating a
  259. // vector of the right length. We do this by deciding, with no order in mind,
  260. // which instructions we will use to populate the vector, and subsequently
  261. // randomly choosing an order. This is to avoid biasing construction of
  262. // vectors with smaller vectors to the left and scalars to the right. That is
  263. // a concern because, e.g. in the case of populating a vec4, if we populate
  264. // the constructor instructions left-to-right, we can always choose a vec3 to
  265. // construct the first three elements, but can only choose a vec3 to construct
  266. // the last three elements if we chose a float to construct the first element
  267. // (otherwise there will not be space left for a vec3).
  268. uint32_t vector_slots_used = 0;
  269. // The instructions we will use to construct the vector, in no particular
  270. // order at this stage.
  271. std::vector<opt::Instruction*> instructions_to_use;
  272. while (vector_slots_used < vector_type.element_count()) {
  273. std::vector<opt::Instruction*> instructions_to_choose_from;
  274. for (auto& entry : smaller_vector_type_id_to_width) {
  275. if (entry.second >
  276. std::min(vector_type.element_count() - 1,
  277. vector_type.element_count() - vector_slots_used)) {
  278. continue;
  279. }
  280. auto available_instructions =
  281. type_id_to_available_instructions.find(entry.first);
  282. if (available_instructions == type_id_to_available_instructions.cend()) {
  283. continue;
  284. }
  285. instructions_to_choose_from.insert(instructions_to_choose_from.end(),
  286. available_instructions->second.begin(),
  287. available_instructions->second.end());
  288. }
  289. if (instructions_to_choose_from.empty()) {
  290. // We may get unlucky and find that there are not any instructions to
  291. // choose from. In this case we give up constructing a composite of this
  292. // vector type. It might be that we could construct the composite in
  293. // another manner, so we could opt to retry a few times here, but it is
  294. // simpler to just give up on the basis that this will not happen
  295. // frequently.
  296. return nullptr;
  297. }
  298. auto instruction_to_use =
  299. instructions_to_choose_from[GetFuzzerContext()->RandomIndex(
  300. instructions_to_choose_from)];
  301. instructions_to_use.push_back(instruction_to_use);
  302. auto chosen_type =
  303. GetIRContext()->get_type_mgr()->GetType(instruction_to_use->type_id());
  304. if (chosen_type->AsVector()) {
  305. assert(chosen_type->AsVector()->element_type() == element_type);
  306. assert(chosen_type->AsVector()->element_count() < element_count);
  307. assert(chosen_type->AsVector()->element_count() <=
  308. element_count - vector_slots_used);
  309. vector_slots_used += chosen_type->AsVector()->element_count();
  310. } else {
  311. assert(chosen_type == element_type);
  312. vector_slots_used += 1;
  313. }
  314. }
  315. assert(vector_slots_used == vector_type.element_count());
  316. auto result = MakeUnique<std::vector<uint32_t>>();
  317. std::vector<uint32_t> operands;
  318. while (!instructions_to_use.empty()) {
  319. auto index = GetFuzzerContext()->RandomIndex(instructions_to_use);
  320. result->push_back(instructions_to_use[index]->result_id());
  321. instructions_to_use.erase(instructions_to_use.begin() + index);
  322. }
  323. assert(result->size() > 1);
  324. return result;
  325. }
  326. } // namespace fuzz
  327. } // namespace spvtools