blob: 292d6599c1155171ce75af5478c0b36bbd83647d [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,
Eric Holkf3b95892019-07-30 14:47:06 -0700156 kGetInstanceField,
Eric Holk3092f992019-07-25 15:14:01 -0700157 kGetStaticField,
Eric Holk44d8cdf2018-12-17 13:35:34 -0800158 kInvokeDirect,
159 kInvokeInterface,
160 kInvokeStatic,
161 kInvokeVirtual,
162 kMove,
Eric Holkd1b43832019-01-29 08:32:42 -0800163 kMoveObject,
Eric Holk44d8cdf2018-12-17 13:35:34 -0800164 kNew,
165 kReturn,
166 kReturnObject,
Eric Holkf3b95892019-07-30 14:47:06 -0700167 kSetInstanceField,
Eric Holk70445d02019-07-26 09:37:46 -0700168 kSetStaticField
Eric Holkb3927582018-11-08 16:40:16 -0800169 };
Eric Holkfaefd4f2018-10-11 16:25:57 -0700170
171 ////////////////////////
172 // Named Constructors //
173 ////////////////////////
174
175 // For instructions with no return value and no arguments.
176 static inline Instruction OpNoArgs(Op opcode) {
Eric Holk3092f992019-07-25 15:14:01 -0700177 return Instruction{opcode, /*index_argument*/ 0, /*dest*/ {}};
Eric Holkfaefd4f2018-10-11 16:25:57 -0700178 }
179 // For most instructions, which take some number of arguments and have an optional return value.
180 template <typename... T>
181 static inline Instruction OpWithArgs(Op opcode, std::optional<const Value> dest, T... args) {
Eric Holk3092f992019-07-25 15:14:01 -0700182 return Instruction{opcode, /*index_argument=*/0, /*result_is_object=*/false, dest, args...};
Eric Holkfaefd4f2018-10-11 16:25:57 -0700183 }
Eric Holk44d8cdf2018-12-17 13:35:34 -0800184
185 // A cast instruction. Basically, `(type)val`
186 static inline Instruction Cast(Value val, Value type) {
Eric Holkd1b43832019-01-29 08:32:42 -0800187 CHECK(type.is_type());
Eric Holk44d8cdf2018-12-17 13:35:34 -0800188 return OpWithArgs(Op::kCheckCast, val, type);
189 }
190
Eric Holkfaefd4f2018-10-11 16:25:57 -0700191 // For method calls.
192 template <typename... T>
Eric Holk3092f992019-07-25 15:14:01 -0700193 static inline Instruction InvokeVirtual(size_t index_argument, std::optional<const Value> dest,
Eric Holkfaefd4f2018-10-11 16:25:57 -0700194 Value this_arg, T... args) {
Eric Holkc69449d2018-12-13 11:35:58 -0800195 return Instruction{
Eric Holk3092f992019-07-25 15:14:01 -0700196 Op::kInvokeVirtual, index_argument, /*result_is_object=*/false, dest, this_arg, args...};
Eric Holkc69449d2018-12-13 11:35:58 -0800197 }
198 // Returns an object
199 template <typename... T>
Eric Holkf3b95892019-07-30 14:47:06 -0700200 static inline Instruction InvokeVirtualObject(size_t index_argument,
201 std::optional<const Value> dest, Value this_arg,
202 T... args) {
Eric Holkc69449d2018-12-13 11:35:58 -0800203 return Instruction{
Eric Holk3092f992019-07-25 15:14:01 -0700204 Op::kInvokeVirtual, index_argument, /*result_is_object=*/true, dest, this_arg, args...};
Eric Holkfaefd4f2018-10-11 16:25:57 -0700205 }
Eric Holkb3927582018-11-08 16:40:16 -0800206 // For direct calls (basically, constructors).
207 template <typename... T>
Eric Holk3092f992019-07-25 15:14:01 -0700208 static inline Instruction InvokeDirect(size_t index_argument, std::optional<const Value> dest,
Eric Holkb3927582018-11-08 16:40:16 -0800209 Value this_arg, T... args) {
Eric Holkc69449d2018-12-13 11:35:58 -0800210 return Instruction{
Eric Holk3092f992019-07-25 15:14:01 -0700211 Op::kInvokeDirect, index_argument, /*result_is_object=*/false, dest, this_arg, args...};
Eric Holkc69449d2018-12-13 11:35:58 -0800212 }
213 // Returns an object
214 template <typename... T>
Eric Holkf3b95892019-07-30 14:47:06 -0700215 static inline Instruction InvokeDirectObject(size_t index_argument,
216 std::optional<const Value> dest, Value this_arg,
217 T... args) {
Eric Holkc69449d2018-12-13 11:35:58 -0800218 return Instruction{
Eric Holk3092f992019-07-25 15:14:01 -0700219 Op::kInvokeDirect, index_argument, /*result_is_object=*/true, dest, this_arg, args...};
Eric Holkc69449d2018-12-13 11:35:58 -0800220 }
221 // For static calls.
222 template <typename... T>
Eric Holk3092f992019-07-25 15:14:01 -0700223 static inline Instruction InvokeStatic(size_t index_argument, std::optional<const Value> dest,
Eric Holkc69449d2018-12-13 11:35:58 -0800224 T... args) {
Eric Holkf3b95892019-07-30 14:47:06 -0700225 return Instruction{
226 Op::kInvokeStatic, index_argument, /*result_is_object=*/false, dest, args...};
Eric Holkc69449d2018-12-13 11:35:58 -0800227 }
228 // Returns an object
229 template <typename... T>
Eric Holkf3b95892019-07-30 14:47:06 -0700230 static inline Instruction InvokeStaticObject(size_t index_argument,
231 std::optional<const Value> dest, T... args) {
Eric Holk3092f992019-07-25 15:14:01 -0700232 return Instruction{Op::kInvokeStatic, index_argument, /*result_is_object=*/true, dest, args...};
Eric Holkc69449d2018-12-13 11:35:58 -0800233 }
234 // For static calls.
235 template <typename... T>
Eric Holk3092f992019-07-25 15:14:01 -0700236 static inline Instruction InvokeInterface(size_t index_argument, std::optional<const Value> dest,
Eric Holkc69449d2018-12-13 11:35:58 -0800237 T... args) {
Eric Holkf3b95892019-07-30 14:47:06 -0700238 return Instruction{
239 Op::kInvokeInterface, index_argument, /*result_is_object=*/false, dest, args...};
Eric Holk3092f992019-07-25 15:14:01 -0700240 }
241
242 static inline Instruction GetStaticField(size_t field_id, Value dest) {
243 return Instruction{Op::kGetStaticField, field_id, dest};
Eric Holkb3927582018-11-08 16:40:16 -0800244 }
Eric Holkfaefd4f2018-10-11 16:25:57 -0700245
Eric Holk70445d02019-07-26 09:37:46 -0700246 static inline Instruction SetStaticField(size_t field_id, Value value) {
Eric Holkf3b95892019-07-30 14:47:06 -0700247 return Instruction{
248 Op::kSetStaticField, field_id, /*result_is_object=*/false, /*dest=*/{}, value};
Eric Holk70445d02019-07-26 09:37:46 -0700249 }
250
Eric Holkf3b95892019-07-30 14:47:06 -0700251 static inline Instruction GetField(size_t field_id, Value dest, Value object) {
252 return Instruction{Op::kGetInstanceField, field_id, /*result_is_object=*/false, dest, object};
253 }
254
255 static inline Instruction SetField(size_t field_id, Value object, Value value) {
256 return Instruction{
257 Op::kSetInstanceField, field_id, /*result_is_object=*/false, /*dest=*/{}, object, value};
258 }
Eric Holk70445d02019-07-26 09:37:46 -0700259
Eric Holkfaefd4f2018-10-11 16:25:57 -0700260 ///////////////
261 // Accessors //
262 ///////////////
263
264 Op opcode() const { return opcode_; }
Eric Holk3092f992019-07-25 15:14:01 -0700265 size_t index_argument() const { return index_argument_; }
Eric Holkc69449d2018-12-13 11:35:58 -0800266 bool result_is_object() const { return result_is_object_; }
Eric Holkfaefd4f2018-10-11 16:25:57 -0700267 const std::optional<const Value>& dest() const { return dest_; }
268 const std::vector<const Value>& args() const { return args_; }
269
270 private:
Eric Holk3092f992019-07-25 15:14:01 -0700271 inline Instruction(Op opcode, size_t index_argument, std::optional<const Value> dest)
Eric Holkf3b95892019-07-30 14:47:06 -0700272 : opcode_{opcode},
273 index_argument_{index_argument},
274 result_is_object_{false},
275 dest_{dest},
276 args_{} {}
Eric Holkfaefd4f2018-10-11 16:25:57 -0700277
278 template <typename... T>
Eric Holkf3b95892019-07-30 14:47:06 -0700279 inline Instruction(Op opcode, size_t index_argument, bool result_is_object,
Eric Holkc69449d2018-12-13 11:35:58 -0800280 std::optional<const Value> dest, T... args)
281 : opcode_{opcode},
Eric Holk3092f992019-07-25 15:14:01 -0700282 index_argument_{index_argument},
Eric Holkc69449d2018-12-13 11:35:58 -0800283 result_is_object_{result_is_object},
284 dest_{dest},
285 args_{args...} {}
Eric Holkfaefd4f2018-10-11 16:25:57 -0700286
287 const Op opcode_;
288 // The index of the method to invoke, for kInvokeVirtual and similar opcodes.
Eric Holk3092f992019-07-25 15:14:01 -0700289 const size_t index_argument_{0};
Eric Holkc69449d2018-12-13 11:35:58 -0800290 const bool result_is_object_;
Eric Holkfaefd4f2018-10-11 16:25:57 -0700291 const std::optional<const Value> dest_;
292 const std::vector<const Value> args_;
293};
294
295// Needed for CHECK_EQ, DCHECK_EQ, etc.
296std::ostream& operator<<(std::ostream& out, const Instruction::Op& opcode);
297
Eric Holkb3927582018-11-08 16:40:16 -0800298// Keeps track of information needed to manipulate or call a method.
299struct MethodDeclData {
300 size_t id;
301 ir::MethodDecl* decl;
302};
303
Eric Holkdbc36e22018-09-20 12:03:10 -0700304// Tools to help build methods and their bodies.
305class MethodBuilder {
306 public:
307 MethodBuilder(DexBuilder* dex, ir::Class* class_def, ir::MethodDecl* decl);
308
309 // Encode the method into DEX format.
310 ir::EncodedMethod* Encode();
311
Eric Holkdbc36e22018-09-20 12:03:10 -0700312 // Create a new register to be used to storing values. Note that these are not SSA registers, like
313 // might be expected in similar code generators. This does no liveness tracking or anything, so
314 // it's up to the caller to reuse registers as appropriate.
Eric Holkfaefd4f2018-10-11 16:25:57 -0700315 Value MakeRegister();
Eric Holkdbc36e22018-09-20 12:03:10 -0700316
Eric Holkd62c5aa2018-11-01 15:50:24 -0700317 Value MakeLabel();
318
Eric Holkdbc36e22018-09-20 12:03:10 -0700319 /////////////////////////////////
320 // Instruction builder methods //
321 /////////////////////////////////
322
Eric Holkfaefd4f2018-10-11 16:25:57 -0700323 void AddInstruction(Instruction instruction);
324
Eric Holkdbc36e22018-09-20 12:03:10 -0700325 // return-void
326 void BuildReturn();
Eric Holk3cc4afc2018-11-08 14:16:20 -0800327 void BuildReturn(Value src, bool is_object = false);
Eric Holkdbc36e22018-09-20 12:03:10 -0700328 // const/4
Eric Holkfaefd4f2018-10-11 16:25:57 -0700329 void BuildConst4(Value target, int value);
Eric Holk3cc4afc2018-11-08 14:16:20 -0800330 void BuildConstString(Value target, const std::string& value);
Eric Holkb3927582018-11-08 16:40:16 -0800331 template <typename... T>
332 void BuildNew(Value target, TypeDescriptor type, Prototype constructor, T... args);
Eric Holkdbc36e22018-09-20 12:03:10 -0700333
334 // TODO: add builders for more instructions
335
Eric Holkc69449d2018-12-13 11:35:58 -0800336 DexBuilder* dex_file() const { return dex_; }
337
Eric Holkdbc36e22018-09-20 12:03:10 -0700338 private:
Eric Holkfaefd4f2018-10-11 16:25:57 -0700339 void EncodeInstructions();
340 void EncodeInstruction(const Instruction& instruction);
Eric Holk3cc4afc2018-11-08 14:16:20 -0800341
342 // Encodes a return instruction. For instructions with no return value, the opcode field is
343 // ignored. Otherwise, this specifies which return instruction will be used (return,
344 // return-object, etc.)
345 void EncodeReturn(const Instruction& instruction, ::art::Instruction::Code opcode);
346
Eric Holkfaefd4f2018-10-11 16:25:57 -0700347 void EncodeMove(const Instruction& instruction);
Eric Holkb3927582018-11-08 16:40:16 -0800348 void EncodeInvoke(const Instruction& instruction, ::art::Instruction::Code opcode);
Eric Holkd62c5aa2018-11-01 15:50:24 -0700349 void EncodeBranch(art::Instruction::Code op, const Instruction& instruction);
Eric Holkb3927582018-11-08 16:40:16 -0800350 void EncodeNew(const Instruction& instruction);
Eric Holk44d8cdf2018-12-17 13:35:34 -0800351 void EncodeCast(const Instruction& instruction);
Eric Holkf3b95892019-07-30 14:47:06 -0700352 void EncodeFieldOp(const Instruction& instruction);
Eric Holkfaefd4f2018-10-11 16:25:57 -0700353
Eric Holk1c0f3f02018-11-09 13:48:59 -0800354 // Low-level instruction format encoding. See
355 // https://source.android.com/devices/tech/dalvik/instruction-formats for documentation of
356 // formats.
357
358 inline void Encode10x(art::Instruction::Code opcode) {
359 // 00|op
360 buffer_.push_back(opcode);
361 }
362
363 inline void Encode11x(art::Instruction::Code opcode, uint8_t a) {
364 // aa|op
365 buffer_.push_back((a << 8) | opcode);
366 }
367
368 inline void Encode11n(art::Instruction::Code opcode, uint8_t a, int8_t b) {
369 // b|a|op
370
371 // Make sure the fields are in bounds (4 bits for a, 4 bits for b).
372 CHECK_LT(a, 16);
373 CHECK_LE(-8, b);
374 CHECK_LT(b, 8);
375
376 buffer_.push_back(((b & 0xf) << 12) | (a << 8) | opcode);
377 }
378
379 inline void Encode21c(art::Instruction::Code opcode, uint8_t a, uint16_t b) {
380 // aa|op|bbbb
381 buffer_.push_back((a << 8) | opcode);
382 buffer_.push_back(b);
383 }
384
Eric Holkf3b95892019-07-30 14:47:06 -0700385 inline void Encode22c(art::Instruction::Code opcode, uint8_t a, uint8_t b, uint16_t c) {
386 // b|a|op|bbbb
387 CHECK(IsShortRegister(a));
388 CHECK(IsShortRegister(b));
389 buffer_.push_back((b << 12) | (a << 8) | opcode);
390 buffer_.push_back(c);
391 }
392
Eric Holkd1b43832019-01-29 08:32:42 -0800393 inline void Encode32x(art::Instruction::Code opcode, uint16_t a, uint16_t b) {
394 buffer_.push_back(opcode);
395 buffer_.push_back(a);
396 buffer_.push_back(b);
397 }
398
Eric Holk1c0f3f02018-11-09 13:48:59 -0800399 inline void Encode35c(art::Instruction::Code opcode, size_t a, uint16_t b, uint8_t c, uint8_t d,
400 uint8_t e, uint8_t f, uint8_t g) {
401 // a|g|op|bbbb|f|e|d|c
402
403 CHECK_LE(a, 5);
Eric Holkd1b43832019-01-29 08:32:42 -0800404 CHECK(IsShortRegister(c));
405 CHECK(IsShortRegister(d));
406 CHECK(IsShortRegister(e));
407 CHECK(IsShortRegister(f));
408 CHECK(IsShortRegister(g));
Eric Holk1c0f3f02018-11-09 13:48:59 -0800409 buffer_.push_back((a << 12) | (g << 8) | opcode);
410 buffer_.push_back(b);
411 buffer_.push_back((f << 12) | (e << 8) | (d << 4) | c);
412 }
413
Eric Holkd1b43832019-01-29 08:32:42 -0800414 inline void Encode3rc(art::Instruction::Code opcode, size_t a, uint16_t b, uint16_t c) {
415 CHECK_LE(a, 255);
416 buffer_.push_back((a << 8) | opcode);
417 buffer_.push_back(b);
418 buffer_.push_back(c);
419 }
420
421 static constexpr bool IsShortRegister(size_t register_value) { return register_value < 16; }
422
423 // Returns an array of num_regs scratch registers. These are guaranteed to be
424 // contiguous, so they are suitable for the invoke-*/range instructions.
425 template <int num_regs>
426 std::array<Value, num_regs> GetScratchRegisters() const {
427 static_assert(num_regs <= kMaxScratchRegisters);
428 std::array<Value, num_regs> regs;
429 for (size_t i = 0; i < num_regs; ++i) {
430 regs[i] = std::move(Value::Local(num_registers_ + i));
431 }
432 return regs;
433 }
434
Eric Holkfaefd4f2018-10-11 16:25:57 -0700435 // Converts a register or parameter to its DEX register number.
Eric Holkd62c5aa2018-11-01 15:50:24 -0700436 size_t RegisterValue(const Value& value) const;
437
438 // Sets a label's address to the current position in the instruction buffer. If there are any
439 // forward references to the label, this function will back-patch them.
440 void BindLabel(const Value& label);
441
442 // Returns the offset of the label relative to the given instruction offset. If the label is not
443 // bound, a reference will be saved and it will automatically be patched when the label is bound.
444 ::dex::u2 LabelValue(const Value& label, size_t instruction_offset, size_t field_offset);
Eric Holkfaefd4f2018-10-11 16:25:57 -0700445
Eric Holkdbc36e22018-09-20 12:03:10 -0700446 DexBuilder* dex_;
447 ir::Class* class_;
448 ir::MethodDecl* decl_;
449
Eric Holkfaefd4f2018-10-11 16:25:57 -0700450 // A list of the instructions we will eventually encode.
451 std::vector<Instruction> instructions_;
452
453 // A buffer to hold instructions that have been encoded.
Eric Holkdbc36e22018-09-20 12:03:10 -0700454 std::vector<::dex::u2> buffer_;
455
Eric Holkd1b43832019-01-29 08:32:42 -0800456 // We create some scratch registers for when we have to shuffle registers
457 // around to make legal DEX code.
458 static constexpr size_t kMaxScratchRegisters = 5;
459
Eric Holkdbc36e22018-09-20 12:03:10 -0700460 // How many registers we've allocated
Eric Holkfaefd4f2018-10-11 16:25:57 -0700461 size_t num_registers_{0};
Eric Holkd62c5aa2018-11-01 15:50:24 -0700462
463 // Stores information needed to back-patch a label once it is bound. We need to know the start of
464 // the instruction that refers to the label, and the offset to where the actual label value should
465 // go.
466 struct LabelReference {
467 size_t instruction_offset;
468 size_t field_offset;
469 };
470
471 struct LabelData {
472 std::optional<size_t> bound_address;
473 std::forward_list<LabelReference> references;
474 };
475
476 std::vector<LabelData> labels_;
Eric Holkb3927582018-11-08 16:40:16 -0800477
478 // During encoding, keep track of the largest number of arguments needed, so we can use it for our
479 // outs count
480 size_t max_args_{0};
Eric Holkdbc36e22018-09-20 12:03:10 -0700481};
482
483// A helper to build class definitions.
484class ClassBuilder {
485 public:
Eric Holkfaefd4f2018-10-11 16:25:57 -0700486 ClassBuilder(DexBuilder* parent, const std::string& name, ir::Class* class_def);
Eric Holkdbc36e22018-09-20 12:03:10 -0700487
488 void set_source_file(const std::string& source);
489
490 // Create a method with the given name and prototype. The returned MethodBuilder can be used to
491 // fill in the method body.
492 MethodBuilder CreateMethod(const std::string& name, Prototype prototype);
493
494 private:
Eric Holkfaefd4f2018-10-11 16:25:57 -0700495 DexBuilder* const parent_;
496 const TypeDescriptor type_descriptor_;
497 ir::Class* const class_;
498};
499
Eric Holkdbc36e22018-09-20 12:03:10 -0700500// Builds Dex files from scratch.
501class DexBuilder {
502 public:
503 DexBuilder();
504
505 // Create an in-memory image of the DEX file that can either be loaded directly or written to a
506 // file.
507 slicer::MemView CreateImage();
508
509 template <typename T>
510 T* Alloc() {
511 return dex_file_->Alloc<T>();
512 }
513
514 // Find the ir::String that matches the given string, creating it if it does not exist.
515 ir::String* GetOrAddString(const std::string& string);
516 // Create a new class of the given name.
517 ClassBuilder MakeClass(const std::string& name);
518
519 // Add a type for the given descriptor, or return the existing one if it already exists.
Eric Holkfaefd4f2018-10-11 16:25:57 -0700520 // See the TypeDescriptor class for help generating these. GetOrAddType can be used to declare
521 // imported classes.
Eric Holkdbc36e22018-09-20 12:03:10 -0700522 ir::Type* GetOrAddType(const std::string& descriptor);
Eric Holk3092f992019-07-25 15:14:01 -0700523 inline ir::Type* GetOrAddType(TypeDescriptor descriptor) {
524 return GetOrAddType(descriptor.descriptor());
525 }
526
527 ir::FieldDecl* GetOrAddField(TypeDescriptor parent, const std::string& name, TypeDescriptor type);
Eric Holkdbc36e22018-09-20 12:03:10 -0700528
Eric Holkfaefd4f2018-10-11 16:25:57 -0700529 // Returns the method id for the method, creating it if it has not been created yet.
530 const MethodDeclData& GetOrDeclareMethod(TypeDescriptor type, const std::string& name,
531 Prototype prototype);
532
Eric Holkd1b43832019-01-29 08:32:42 -0800533 std::optional<const Prototype> GetPrototypeByMethodId(size_t method_id) const;
534
Eric Holkdbc36e22018-09-20 12:03:10 -0700535 private:
Eric Holkfaefd4f2018-10-11 16:25:57 -0700536 // Looks up the ir::Proto* corresponding to this given prototype, or creates one if it does not
537 // exist.
538 ir::Proto* GetOrEncodeProto(Prototype prototype);
539
Eric Holkdbc36e22018-09-20 12:03:10 -0700540 std::shared_ptr<ir::DexFile> dex_file_;
541
542 // allocator_ is needed to be able to encode the image.
543 TrackingAllocator allocator_;
544
545 // We'll need to allocate buffers for all of the encoded strings we create. This is where we store
546 // all of them.
547 std::vector<std::unique_ptr<uint8_t[]>> string_data_;
548
549 // Keep track of what types we've defined so we can look them up later.
Eric Holkfaefd4f2018-10-11 16:25:57 -0700550 std::unordered_map<std::string, ir::Type*> types_by_descriptor_;
551
552 struct MethodDescriptor {
553 TypeDescriptor type;
554 std::string name;
555 Prototype prototype;
556
557 inline bool operator<(const MethodDescriptor& rhs) const {
558 return std::make_tuple(type, name, prototype) <
559 std::make_tuple(rhs.type, rhs.name, rhs.prototype);
560 }
561 };
562
563 // Maps method declarations to their method index. This is needed to encode references to them.
564 // When we go to actually write the DEX file, slicer will re-assign these after correctly sorting
565 // the methods list.
566 std::map<MethodDescriptor, MethodDeclData> method_id_map_;
Eric Holkdbc36e22018-09-20 12:03:10 -0700567
568 // Keep track of what strings we've defined so we can look them up later.
Eric Holkfaefd4f2018-10-11 16:25:57 -0700569 std::unordered_map<std::string, ir::String*> strings_;
570
571 // Keep track of already-encoded protos.
572 std::map<Prototype, ir::Proto*> proto_map_;
Eric Holk3092f992019-07-25 15:14:01 -0700573
574 // Keep track of fields that have been declared
575 std::map<std::tuple<TypeDescriptor, std::string>, ir::FieldDecl*> field_decls_by_key_;
Eric Holkdbc36e22018-09-20 12:03:10 -0700576};
577
Eric Holkb3927582018-11-08 16:40:16 -0800578template <typename... T>
579void MethodBuilder::BuildNew(Value target, TypeDescriptor type, Prototype constructor, T... args) {
580 MethodDeclData constructor_data{dex_->GetOrDeclareMethod(type, "<init>", constructor)};
581 // allocate the object
582 ir::Type* type_def = dex_->GetOrAddType(type.descriptor());
583 AddInstruction(
584 Instruction::OpWithArgs(Instruction::Op::kNew, target, Value::Type(type_def->orig_index)));
585 // call the constructor
586 AddInstruction(Instruction::InvokeDirect(constructor_data.id, /*dest=*/{}, target, args...));
587};
588
Eric Holkdbc36e22018-09-20 12:03:10 -0700589} // namespace dex
590} // namespace startop
591
592#endif // DEX_BUILDER_H_