blob: 541d80077bd32fd0d43e422d3a0609cbb85a530f [file] [log] [blame]
Eric Holkdbc36e22018-09-20 12:03:10 -07001/*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16#ifndef DEX_BUILDER_H_
17#define DEX_BUILDER_H_
18
Eric Holkd1b43832019-01-29 08:32:42 -080019#include <array>
Eric Holkd62c5aa2018-11-01 15:50:24 -070020#include <forward_list>
Eric Holkdbc36e22018-09-20 12:03:10 -070021#include <map>
Eric Holkfaefd4f2018-10-11 16:25:57 -070022#include <optional>
Eric Holkdbc36e22018-09-20 12:03:10 -070023#include <string>
Eric Holkfaefd4f2018-10-11 16:25:57 -070024#include <unordered_map>
Eric Holkdbc36e22018-09-20 12:03:10 -070025#include <vector>
26
Eric Holkd62c5aa2018-11-01 15:50:24 -070027#include "dex/dex_instruction.h"
Eric Holkdbc36e22018-09-20 12:03:10 -070028#include "slicer/dex_ir.h"
29#include "slicer/writer.h"
30
31namespace startop {
32namespace dex {
33
34// TODO: remove this once the dex generation code is complete.
35void WriteTestDexFile(const std::string& filename);
36
37//////////////////////////
38// Forward declarations //
39//////////////////////////
40class DexBuilder;
41
42// Our custom allocator for dex::Writer
43//
44// This keeps track of all allocations and ensures they are freed when
45// TrackingAllocator is destroyed. Pointers to memory allocated by this
46// allocator must not outlive the allocator.
47class TrackingAllocator : public ::dex::Writer::Allocator {
48 public:
49 virtual void* Allocate(size_t size);
50 virtual void Free(void* ptr);
51
52 private:
Eric Holkfaefd4f2018-10-11 16:25:57 -070053 std::unordered_map<void*, std::unique_ptr<uint8_t[]>> allocations_;
Eric Holkdbc36e22018-09-20 12:03:10 -070054};
55
56// Represents a DEX type descriptor.
57//
58// TODO: add a way to create a descriptor for a reference of a class type.
59class TypeDescriptor {
60 public:
61 // Named constructors for base type descriptors.
62 static const TypeDescriptor Int();
63 static const TypeDescriptor Void();
64
Eric Holkfaefd4f2018-10-11 16:25:57 -070065 // Creates a type descriptor from a fully-qualified class name. For example, it turns the class
66 // name java.lang.Object into the descriptor Ljava/lang/Object.
67 static TypeDescriptor FromClassname(const std::string& name);
68
Eric Holkdbc36e22018-09-20 12:03:10 -070069 // Return the full descriptor, such as I or Ljava/lang/Object
70 const std::string& descriptor() const { return descriptor_; }
71 // Return the shorty descriptor, such as I or L
72 std::string short_descriptor() const { return descriptor().substr(0, 1); }
73
Eric Holkd1b43832019-01-29 08:32:42 -080074 bool is_object() const { return short_descriptor() == "L"; }
75
Eric Holkfaefd4f2018-10-11 16:25:57 -070076 bool operator<(const TypeDescriptor& rhs) const { return descriptor_ < rhs.descriptor_; }
77
Eric Holkdbc36e22018-09-20 12:03:10 -070078 private:
Chih-Hung Hsieh81aff0f2018-12-20 13:53:28 -080079 explicit TypeDescriptor(std::string descriptor) : descriptor_{descriptor} {}
Eric Holkdbc36e22018-09-20 12:03:10 -070080
81 const std::string descriptor_;
82};
83
84// Defines a function signature. For example, Prototype{TypeDescriptor::VOID, TypeDescriptor::Int}
85// represents the function type (Int) -> Void.
86class Prototype {
87 public:
88 template <typename... TypeDescriptors>
Chih-Hung Hsieh81aff0f2018-12-20 13:53:28 -080089 explicit Prototype(TypeDescriptor return_type, TypeDescriptors... param_types)
Eric Holkdbc36e22018-09-20 12:03:10 -070090 : return_type_{return_type}, param_types_{param_types...} {}
91
92 // Encode this prototype into the dex file.
93 ir::Proto* Encode(DexBuilder* dex) const;
94
95 // Get the shorty descriptor, such as VII for (Int, Int) -> Void
96 std::string Shorty() const;
97
Eric Holkd1b43832019-01-29 08:32:42 -080098 const TypeDescriptor& ArgType(size_t index) const;
99
Eric Holkfaefd4f2018-10-11 16:25:57 -0700100 bool operator<(const Prototype& rhs) const {
101 return std::make_tuple(return_type_, param_types_) <
102 std::make_tuple(rhs.return_type_, rhs.param_types_);
103 }
104
Eric Holkdbc36e22018-09-20 12:03:10 -0700105 private:
106 const TypeDescriptor return_type_;
107 const std::vector<TypeDescriptor> param_types_;
108};
109
Eric Holkfaefd4f2018-10-11 16:25:57 -0700110// Represents a DEX register or constant. We separate regular registers and parameters
111// because we will not know the real parameter id until after all instructions
112// have been generated.
113class Value {
114 public:
115 static constexpr Value Local(size_t id) { return Value{id, Kind::kLocalRegister}; }
116 static constexpr Value Parameter(size_t id) { return Value{id, Kind::kParameter}; }
117 static constexpr Value Immediate(size_t value) { return Value{value, Kind::kImmediate}; }
Eric Holk3cc4afc2018-11-08 14:16:20 -0800118 static constexpr Value String(size_t value) { return Value{value, Kind::kString}; }
Eric Holkd62c5aa2018-11-01 15:50:24 -0700119 static constexpr Value Label(size_t id) { return Value{id, Kind::kLabel}; }
Eric Holkb3927582018-11-08 16:40:16 -0800120 static constexpr Value Type(size_t id) { return Value{id, Kind::kType}; }
Eric Holkfaefd4f2018-10-11 16:25:57 -0700121
122 bool is_register() const { return kind_ == Kind::kLocalRegister; }
123 bool is_parameter() const { return kind_ == Kind::kParameter; }
Eric Holkd62c5aa2018-11-01 15:50:24 -0700124 bool is_variable() const { return is_register() || is_parameter(); }
Eric Holkfaefd4f2018-10-11 16:25:57 -0700125 bool is_immediate() const { return kind_ == Kind::kImmediate; }
Eric Holk3cc4afc2018-11-08 14:16:20 -0800126 bool is_string() const { return kind_ == Kind::kString; }
Eric Holkd62c5aa2018-11-01 15:50:24 -0700127 bool is_label() const { return kind_ == Kind::kLabel; }
Eric Holkb3927582018-11-08 16:40:16 -0800128 bool is_type() const { return kind_ == Kind::kType; }
Eric Holkfaefd4f2018-10-11 16:25:57 -0700129
130 size_t value() const { return value_; }
131
Eric Holkd1b43832019-01-29 08:32:42 -0800132 constexpr Value() : value_{0}, kind_{Kind::kInvalid} {}
Eric Holkfaefd4f2018-10-11 16:25:57 -0700133
Eric Holkd1b43832019-01-29 08:32:42 -0800134 private:
135 enum class Kind { kInvalid, kLocalRegister, kParameter, kImmediate, kString, kLabel, kType };
136
137 size_t value_;
138 Kind kind_;
Eric Holkfaefd4f2018-10-11 16:25:57 -0700139
140 constexpr Value(size_t value, Kind kind) : value_{value}, kind_{kind} {}
141};
142
143// A virtual instruction. We convert these to real instructions in MethodBuilder::Encode.
144// Virtual instructions are needed to keep track of information that is not known until all of the
145// code is generated. This information includes things like how many local registers are created and
146// branch target locations.
147class Instruction {
148 public:
149 // The operation performed by this instruction. These are virtual instructions that do not
150 // correspond exactly to DEX instructions.
Eric Holkb3927582018-11-08 16:40:16 -0800151 enum class Op {
Eric Holkb3927582018-11-08 16:40:16 -0800152 kBindLabel,
153 kBranchEqz,
Eric Holkc69449d2018-12-13 11:35:58 -0800154 kBranchNEqz,
Eric Holk44d8cdf2018-12-17 13:35:34 -0800155 kCheckCast,
156 kInvokeDirect,
157 kInvokeInterface,
158 kInvokeStatic,
159 kInvokeVirtual,
160 kMove,
Eric Holkd1b43832019-01-29 08:32:42 -0800161 kMoveObject,
Eric Holk44d8cdf2018-12-17 13:35:34 -0800162 kNew,
163 kReturn,
164 kReturnObject,
Eric Holkb3927582018-11-08 16:40:16 -0800165 };
Eric Holkfaefd4f2018-10-11 16:25:57 -0700166
167 ////////////////////////
168 // Named Constructors //
169 ////////////////////////
170
171 // For instructions with no return value and no arguments.
172 static inline Instruction OpNoArgs(Op opcode) {
173 return Instruction{opcode, /*method_id*/ 0, /*dest*/ {}};
174 }
175 // For most instructions, which take some number of arguments and have an optional return value.
176 template <typename... T>
177 static inline Instruction OpWithArgs(Op opcode, std::optional<const Value> dest, T... args) {
Eric Holkc69449d2018-12-13 11:35:58 -0800178 return Instruction{opcode, /*method_id=*/0, /*result_is_object=*/false, dest, args...};
Eric Holkfaefd4f2018-10-11 16:25:57 -0700179 }
Eric Holk44d8cdf2018-12-17 13:35:34 -0800180
181 // A cast instruction. Basically, `(type)val`
182 static inline Instruction Cast(Value val, Value type) {
Eric Holkd1b43832019-01-29 08:32:42 -0800183 CHECK(type.is_type());
Eric Holk44d8cdf2018-12-17 13:35:34 -0800184 return OpWithArgs(Op::kCheckCast, val, type);
185 }
186
Eric Holkfaefd4f2018-10-11 16:25:57 -0700187 // For method calls.
188 template <typename... T>
189 static inline Instruction InvokeVirtual(size_t method_id, std::optional<const Value> dest,
190 Value this_arg, T... args) {
Eric Holkc69449d2018-12-13 11:35:58 -0800191 return Instruction{
192 Op::kInvokeVirtual, method_id, /*result_is_object=*/false, dest, this_arg, args...};
193 }
194 // Returns an object
195 template <typename... T>
196 static inline Instruction InvokeVirtualObject(size_t method_id, std::optional<const Value> dest,
197 Value this_arg, T... args) {
198 return Instruction{
199 Op::kInvokeVirtual, method_id, /*result_is_object=*/true, dest, this_arg, args...};
Eric Holkfaefd4f2018-10-11 16:25:57 -0700200 }
Eric Holkb3927582018-11-08 16:40:16 -0800201 // For direct calls (basically, constructors).
202 template <typename... T>
203 static inline Instruction InvokeDirect(size_t method_id, std::optional<const Value> dest,
204 Value this_arg, T... args) {
Eric Holkc69449d2018-12-13 11:35:58 -0800205 return Instruction{
206 Op::kInvokeDirect, method_id, /*result_is_object=*/false, dest, this_arg, args...};
207 }
208 // Returns an object
209 template <typename... T>
210 static inline Instruction InvokeDirectObject(size_t method_id, std::optional<const Value> dest,
211 Value this_arg, T... args) {
212 return Instruction{
213 Op::kInvokeDirect, method_id, /*result_is_object=*/true, dest, this_arg, args...};
214 }
215 // For static calls.
216 template <typename... T>
217 static inline Instruction InvokeStatic(size_t method_id, std::optional<const Value> dest,
218 T... args) {
219 return Instruction{Op::kInvokeStatic, method_id, /*result_is_object=*/false, dest, args...};
220 }
221 // Returns an object
222 template <typename... T>
223 static inline Instruction InvokeStaticObject(size_t method_id, std::optional<const Value> dest,
224 T... args) {
225 return Instruction{Op::kInvokeStatic, method_id, /*result_is_object=*/true, dest, args...};
226 }
227 // For static calls.
228 template <typename... T>
229 static inline Instruction InvokeInterface(size_t method_id, std::optional<const Value> dest,
230 T... args) {
231 return Instruction{Op::kInvokeInterface, method_id, /*result_is_object=*/false, dest, args...};
Eric Holkb3927582018-11-08 16:40:16 -0800232 }
Eric Holkfaefd4f2018-10-11 16:25:57 -0700233
234 ///////////////
235 // Accessors //
236 ///////////////
237
238 Op opcode() const { return opcode_; }
239 size_t method_id() const { return method_id_; }
Eric Holkc69449d2018-12-13 11:35:58 -0800240 bool result_is_object() const { return result_is_object_; }
Eric Holkfaefd4f2018-10-11 16:25:57 -0700241 const std::optional<const Value>& dest() const { return dest_; }
242 const std::vector<const Value>& args() const { return args_; }
243
244 private:
245 inline Instruction(Op opcode, size_t method_id, std::optional<const Value> dest)
Eric Holkc69449d2018-12-13 11:35:58 -0800246 : opcode_{opcode}, method_id_{method_id}, result_is_object_{false}, dest_{dest}, args_{} {}
Eric Holkfaefd4f2018-10-11 16:25:57 -0700247
248 template <typename... T>
Eric Holkc69449d2018-12-13 11:35:58 -0800249 inline constexpr Instruction(Op opcode, size_t method_id, bool result_is_object,
250 std::optional<const Value> dest, T... args)
251 : opcode_{opcode},
252 method_id_{method_id},
253 result_is_object_{result_is_object},
254 dest_{dest},
255 args_{args...} {}
Eric Holkfaefd4f2018-10-11 16:25:57 -0700256
257 const Op opcode_;
258 // The index of the method to invoke, for kInvokeVirtual and similar opcodes.
259 const size_t method_id_{0};
Eric Holkc69449d2018-12-13 11:35:58 -0800260 const bool result_is_object_;
Eric Holkfaefd4f2018-10-11 16:25:57 -0700261 const std::optional<const Value> dest_;
262 const std::vector<const Value> args_;
263};
264
265// Needed for CHECK_EQ, DCHECK_EQ, etc.
266std::ostream& operator<<(std::ostream& out, const Instruction::Op& opcode);
267
Eric Holkb3927582018-11-08 16:40:16 -0800268// Keeps track of information needed to manipulate or call a method.
269struct MethodDeclData {
270 size_t id;
271 ir::MethodDecl* decl;
272};
273
Eric Holkdbc36e22018-09-20 12:03:10 -0700274// Tools to help build methods and their bodies.
275class MethodBuilder {
276 public:
277 MethodBuilder(DexBuilder* dex, ir::Class* class_def, ir::MethodDecl* decl);
278
279 // Encode the method into DEX format.
280 ir::EncodedMethod* Encode();
281
Eric Holkdbc36e22018-09-20 12:03:10 -0700282 // Create a new register to be used to storing values. Note that these are not SSA registers, like
283 // might be expected in similar code generators. This does no liveness tracking or anything, so
284 // it's up to the caller to reuse registers as appropriate.
Eric Holkfaefd4f2018-10-11 16:25:57 -0700285 Value MakeRegister();
Eric Holkdbc36e22018-09-20 12:03:10 -0700286
Eric Holkd62c5aa2018-11-01 15:50:24 -0700287 Value MakeLabel();
288
Eric Holkdbc36e22018-09-20 12:03:10 -0700289 /////////////////////////////////
290 // Instruction builder methods //
291 /////////////////////////////////
292
Eric Holkfaefd4f2018-10-11 16:25:57 -0700293 void AddInstruction(Instruction instruction);
294
Eric Holkdbc36e22018-09-20 12:03:10 -0700295 // return-void
296 void BuildReturn();
Eric Holk3cc4afc2018-11-08 14:16:20 -0800297 void BuildReturn(Value src, bool is_object = false);
Eric Holkdbc36e22018-09-20 12:03:10 -0700298 // const/4
Eric Holkfaefd4f2018-10-11 16:25:57 -0700299 void BuildConst4(Value target, int value);
Eric Holk3cc4afc2018-11-08 14:16:20 -0800300 void BuildConstString(Value target, const std::string& value);
Eric Holkb3927582018-11-08 16:40:16 -0800301 template <typename... T>
302 void BuildNew(Value target, TypeDescriptor type, Prototype constructor, T... args);
Eric Holkdbc36e22018-09-20 12:03:10 -0700303
304 // TODO: add builders for more instructions
305
Eric Holkc69449d2018-12-13 11:35:58 -0800306 DexBuilder* dex_file() const { return dex_; }
307
Eric Holkdbc36e22018-09-20 12:03:10 -0700308 private:
Eric Holkfaefd4f2018-10-11 16:25:57 -0700309 void EncodeInstructions();
310 void EncodeInstruction(const Instruction& instruction);
Eric Holk3cc4afc2018-11-08 14:16:20 -0800311
312 // Encodes a return instruction. For instructions with no return value, the opcode field is
313 // ignored. Otherwise, this specifies which return instruction will be used (return,
314 // return-object, etc.)
315 void EncodeReturn(const Instruction& instruction, ::art::Instruction::Code opcode);
316
Eric Holkfaefd4f2018-10-11 16:25:57 -0700317 void EncodeMove(const Instruction& instruction);
Eric Holkb3927582018-11-08 16:40:16 -0800318 void EncodeInvoke(const Instruction& instruction, ::art::Instruction::Code opcode);
Eric Holkd62c5aa2018-11-01 15:50:24 -0700319 void EncodeBranch(art::Instruction::Code op, const Instruction& instruction);
Eric Holkb3927582018-11-08 16:40:16 -0800320 void EncodeNew(const Instruction& instruction);
Eric Holk44d8cdf2018-12-17 13:35:34 -0800321 void EncodeCast(const Instruction& instruction);
Eric Holkfaefd4f2018-10-11 16:25:57 -0700322
Eric Holk1c0f3f02018-11-09 13:48:59 -0800323 // Low-level instruction format encoding. See
324 // https://source.android.com/devices/tech/dalvik/instruction-formats for documentation of
325 // formats.
326
327 inline void Encode10x(art::Instruction::Code opcode) {
328 // 00|op
329 buffer_.push_back(opcode);
330 }
331
332 inline void Encode11x(art::Instruction::Code opcode, uint8_t a) {
333 // aa|op
334 buffer_.push_back((a << 8) | opcode);
335 }
336
337 inline void Encode11n(art::Instruction::Code opcode, uint8_t a, int8_t b) {
338 // b|a|op
339
340 // Make sure the fields are in bounds (4 bits for a, 4 bits for b).
341 CHECK_LT(a, 16);
342 CHECK_LE(-8, b);
343 CHECK_LT(b, 8);
344
345 buffer_.push_back(((b & 0xf) << 12) | (a << 8) | opcode);
346 }
347
348 inline void Encode21c(art::Instruction::Code opcode, uint8_t a, uint16_t b) {
349 // aa|op|bbbb
350 buffer_.push_back((a << 8) | opcode);
351 buffer_.push_back(b);
352 }
353
Eric Holkd1b43832019-01-29 08:32:42 -0800354 inline void Encode32x(art::Instruction::Code opcode, uint16_t a, uint16_t b) {
355 buffer_.push_back(opcode);
356 buffer_.push_back(a);
357 buffer_.push_back(b);
358 }
359
Eric Holk1c0f3f02018-11-09 13:48:59 -0800360 inline void Encode35c(art::Instruction::Code opcode, size_t a, uint16_t b, uint8_t c, uint8_t d,
361 uint8_t e, uint8_t f, uint8_t g) {
362 // a|g|op|bbbb|f|e|d|c
363
364 CHECK_LE(a, 5);
Eric Holkd1b43832019-01-29 08:32:42 -0800365 CHECK(IsShortRegister(c));
366 CHECK(IsShortRegister(d));
367 CHECK(IsShortRegister(e));
368 CHECK(IsShortRegister(f));
369 CHECK(IsShortRegister(g));
Eric Holk1c0f3f02018-11-09 13:48:59 -0800370 buffer_.push_back((a << 12) | (g << 8) | opcode);
371 buffer_.push_back(b);
372 buffer_.push_back((f << 12) | (e << 8) | (d << 4) | c);
373 }
374
Eric Holkd1b43832019-01-29 08:32:42 -0800375 inline void Encode3rc(art::Instruction::Code opcode, size_t a, uint16_t b, uint16_t c) {
376 CHECK_LE(a, 255);
377 buffer_.push_back((a << 8) | opcode);
378 buffer_.push_back(b);
379 buffer_.push_back(c);
380 }
381
382 static constexpr bool IsShortRegister(size_t register_value) { return register_value < 16; }
383
384 // Returns an array of num_regs scratch registers. These are guaranteed to be
385 // contiguous, so they are suitable for the invoke-*/range instructions.
386 template <int num_regs>
387 std::array<Value, num_regs> GetScratchRegisters() const {
388 static_assert(num_regs <= kMaxScratchRegisters);
389 std::array<Value, num_regs> regs;
390 for (size_t i = 0; i < num_regs; ++i) {
391 regs[i] = std::move(Value::Local(num_registers_ + i));
392 }
393 return regs;
394 }
395
Eric Holkfaefd4f2018-10-11 16:25:57 -0700396 // Converts a register or parameter to its DEX register number.
Eric Holkd62c5aa2018-11-01 15:50:24 -0700397 size_t RegisterValue(const Value& value) const;
398
399 // Sets a label's address to the current position in the instruction buffer. If there are any
400 // forward references to the label, this function will back-patch them.
401 void BindLabel(const Value& label);
402
403 // Returns the offset of the label relative to the given instruction offset. If the label is not
404 // bound, a reference will be saved and it will automatically be patched when the label is bound.
405 ::dex::u2 LabelValue(const Value& label, size_t instruction_offset, size_t field_offset);
Eric Holkfaefd4f2018-10-11 16:25:57 -0700406
Eric Holkdbc36e22018-09-20 12:03:10 -0700407 DexBuilder* dex_;
408 ir::Class* class_;
409 ir::MethodDecl* decl_;
410
Eric Holkfaefd4f2018-10-11 16:25:57 -0700411 // A list of the instructions we will eventually encode.
412 std::vector<Instruction> instructions_;
413
414 // A buffer to hold instructions that have been encoded.
Eric Holkdbc36e22018-09-20 12:03:10 -0700415 std::vector<::dex::u2> buffer_;
416
Eric Holkd1b43832019-01-29 08:32:42 -0800417 // We create some scratch registers for when we have to shuffle registers
418 // around to make legal DEX code.
419 static constexpr size_t kMaxScratchRegisters = 5;
420
Eric Holkdbc36e22018-09-20 12:03:10 -0700421 // How many registers we've allocated
Eric Holkfaefd4f2018-10-11 16:25:57 -0700422 size_t num_registers_{0};
Eric Holkd62c5aa2018-11-01 15:50:24 -0700423
424 // Stores information needed to back-patch a label once it is bound. We need to know the start of
425 // the instruction that refers to the label, and the offset to where the actual label value should
426 // go.
427 struct LabelReference {
428 size_t instruction_offset;
429 size_t field_offset;
430 };
431
432 struct LabelData {
433 std::optional<size_t> bound_address;
434 std::forward_list<LabelReference> references;
435 };
436
437 std::vector<LabelData> labels_;
Eric Holkb3927582018-11-08 16:40:16 -0800438
439 // During encoding, keep track of the largest number of arguments needed, so we can use it for our
440 // outs count
441 size_t max_args_{0};
Eric Holkdbc36e22018-09-20 12:03:10 -0700442};
443
444// A helper to build class definitions.
445class ClassBuilder {
446 public:
Eric Holkfaefd4f2018-10-11 16:25:57 -0700447 ClassBuilder(DexBuilder* parent, const std::string& name, ir::Class* class_def);
Eric Holkdbc36e22018-09-20 12:03:10 -0700448
449 void set_source_file(const std::string& source);
450
451 // Create a method with the given name and prototype. The returned MethodBuilder can be used to
452 // fill in the method body.
453 MethodBuilder CreateMethod(const std::string& name, Prototype prototype);
454
455 private:
Eric Holkfaefd4f2018-10-11 16:25:57 -0700456 DexBuilder* const parent_;
457 const TypeDescriptor type_descriptor_;
458 ir::Class* const class_;
459};
460
Eric Holkdbc36e22018-09-20 12:03:10 -0700461// Builds Dex files from scratch.
462class DexBuilder {
463 public:
464 DexBuilder();
465
466 // Create an in-memory image of the DEX file that can either be loaded directly or written to a
467 // file.
468 slicer::MemView CreateImage();
469
470 template <typename T>
471 T* Alloc() {
472 return dex_file_->Alloc<T>();
473 }
474
475 // Find the ir::String that matches the given string, creating it if it does not exist.
476 ir::String* GetOrAddString(const std::string& string);
477 // Create a new class of the given name.
478 ClassBuilder MakeClass(const std::string& name);
479
480 // Add a type for the given descriptor, or return the existing one if it already exists.
Eric Holkfaefd4f2018-10-11 16:25:57 -0700481 // See the TypeDescriptor class for help generating these. GetOrAddType can be used to declare
482 // imported classes.
Eric Holkdbc36e22018-09-20 12:03:10 -0700483 ir::Type* GetOrAddType(const std::string& descriptor);
484
Eric Holkfaefd4f2018-10-11 16:25:57 -0700485 // Returns the method id for the method, creating it if it has not been created yet.
486 const MethodDeclData& GetOrDeclareMethod(TypeDescriptor type, const std::string& name,
487 Prototype prototype);
488
Eric Holkd1b43832019-01-29 08:32:42 -0800489 std::optional<const Prototype> GetPrototypeByMethodId(size_t method_id) const;
490
Eric Holkdbc36e22018-09-20 12:03:10 -0700491 private:
Eric Holkfaefd4f2018-10-11 16:25:57 -0700492 // Looks up the ir::Proto* corresponding to this given prototype, or creates one if it does not
493 // exist.
494 ir::Proto* GetOrEncodeProto(Prototype prototype);
495
Eric Holkdbc36e22018-09-20 12:03:10 -0700496 std::shared_ptr<ir::DexFile> dex_file_;
497
498 // allocator_ is needed to be able to encode the image.
499 TrackingAllocator allocator_;
500
501 // We'll need to allocate buffers for all of the encoded strings we create. This is where we store
502 // all of them.
503 std::vector<std::unique_ptr<uint8_t[]>> string_data_;
504
505 // Keep track of what types we've defined so we can look them up later.
Eric Holkfaefd4f2018-10-11 16:25:57 -0700506 std::unordered_map<std::string, ir::Type*> types_by_descriptor_;
507
508 struct MethodDescriptor {
509 TypeDescriptor type;
510 std::string name;
511 Prototype prototype;
512
513 inline bool operator<(const MethodDescriptor& rhs) const {
514 return std::make_tuple(type, name, prototype) <
515 std::make_tuple(rhs.type, rhs.name, rhs.prototype);
516 }
517 };
518
519 // Maps method declarations to their method index. This is needed to encode references to them.
520 // When we go to actually write the DEX file, slicer will re-assign these after correctly sorting
521 // the methods list.
522 std::map<MethodDescriptor, MethodDeclData> method_id_map_;
Eric Holkdbc36e22018-09-20 12:03:10 -0700523
524 // Keep track of what strings we've defined so we can look them up later.
Eric Holkfaefd4f2018-10-11 16:25:57 -0700525 std::unordered_map<std::string, ir::String*> strings_;
526
527 // Keep track of already-encoded protos.
528 std::map<Prototype, ir::Proto*> proto_map_;
Eric Holkdbc36e22018-09-20 12:03:10 -0700529};
530
Eric Holkb3927582018-11-08 16:40:16 -0800531template <typename... T>
532void MethodBuilder::BuildNew(Value target, TypeDescriptor type, Prototype constructor, T... args) {
533 MethodDeclData constructor_data{dex_->GetOrDeclareMethod(type, "<init>", constructor)};
534 // allocate the object
535 ir::Type* type_def = dex_->GetOrAddType(type.descriptor());
536 AddInstruction(
537 Instruction::OpWithArgs(Instruction::Op::kNew, target, Value::Type(type_def->orig_index)));
538 // call the constructor
539 AddInstruction(Instruction::InvokeDirect(constructor_data.id, /*dest=*/{}, target, args...));
540};
541
Eric Holkdbc36e22018-09-20 12:03:10 -0700542} // namespace dex
543} // namespace startop
544
545#endif // DEX_BUILDER_H_