blob: 3924e77fab5912e57265a168ac45cdabe119d646 [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
Eric Holk5c6a1a52019-09-17 13:28:34 -0700143// Represents an allocated register returned by MethodBuilder::AllocRegister
144class LiveRegister {
145 friend class MethodBuilder;
146
147 public:
148 LiveRegister(LiveRegister&& other) : liveness_{other.liveness_}, index_{other.index_} {
149 other.index_ = {};
150 };
151 ~LiveRegister() {
152 if (index_.has_value()) {
153 (*liveness_)[*index_] = false;
154 }
155 };
156
157 operator const Value() const { return Value::Local(*index_); }
158
159 private:
160 LiveRegister(std::vector<bool>* liveness, size_t index) : liveness_{liveness}, index_{index} {}
161
162 std::vector<bool>* const liveness_;
163 std::optional<size_t> index_;
164};
165
Eric Holkfaefd4f2018-10-11 16:25:57 -0700166// A virtual instruction. We convert these to real instructions in MethodBuilder::Encode.
167// Virtual instructions are needed to keep track of information that is not known until all of the
168// code is generated. This information includes things like how many local registers are created and
169// branch target locations.
170class Instruction {
171 public:
172 // The operation performed by this instruction. These are virtual instructions that do not
173 // correspond exactly to DEX instructions.
Eric Holkb3927582018-11-08 16:40:16 -0800174 enum class Op {
Eric Holkb3927582018-11-08 16:40:16 -0800175 kBindLabel,
176 kBranchEqz,
Eric Holkc69449d2018-12-13 11:35:58 -0800177 kBranchNEqz,
Eric Holk44d8cdf2018-12-17 13:35:34 -0800178 kCheckCast,
Eric Holkf3b95892019-07-30 14:47:06 -0700179 kGetInstanceField,
Eric Holk3092f992019-07-25 15:14:01 -0700180 kGetStaticField,
Eric Holk44d8cdf2018-12-17 13:35:34 -0800181 kInvokeDirect,
182 kInvokeInterface,
183 kInvokeStatic,
184 kInvokeVirtual,
185 kMove,
Eric Holkd1b43832019-01-29 08:32:42 -0800186 kMoveObject,
Eric Holk44d8cdf2018-12-17 13:35:34 -0800187 kNew,
188 kReturn,
189 kReturnObject,
Eric Holkf3b95892019-07-30 14:47:06 -0700190 kSetInstanceField,
Eric Holk70445d02019-07-26 09:37:46 -0700191 kSetStaticField
Eric Holkb3927582018-11-08 16:40:16 -0800192 };
Eric Holkfaefd4f2018-10-11 16:25:57 -0700193
194 ////////////////////////
195 // Named Constructors //
196 ////////////////////////
197
198 // For instructions with no return value and no arguments.
199 static inline Instruction OpNoArgs(Op opcode) {
Eric Holk3092f992019-07-25 15:14:01 -0700200 return Instruction{opcode, /*index_argument*/ 0, /*dest*/ {}};
Eric Holkfaefd4f2018-10-11 16:25:57 -0700201 }
202 // For most instructions, which take some number of arguments and have an optional return value.
203 template <typename... T>
Eric Holk5c6a1a52019-09-17 13:28:34 -0700204 static inline Instruction OpWithArgs(Op opcode, std::optional<const Value> dest,
205 const T&... args) {
Eric Holk3092f992019-07-25 15:14:01 -0700206 return Instruction{opcode, /*index_argument=*/0, /*result_is_object=*/false, dest, args...};
Eric Holkfaefd4f2018-10-11 16:25:57 -0700207 }
Eric Holk44d8cdf2018-12-17 13:35:34 -0800208
209 // A cast instruction. Basically, `(type)val`
210 static inline Instruction Cast(Value val, Value type) {
Eric Holkd1b43832019-01-29 08:32:42 -0800211 CHECK(type.is_type());
Eric Holk44d8cdf2018-12-17 13:35:34 -0800212 return OpWithArgs(Op::kCheckCast, val, type);
213 }
214
Eric Holkfaefd4f2018-10-11 16:25:57 -0700215 // For method calls.
216 template <typename... T>
Eric Holk3092f992019-07-25 15:14:01 -0700217 static inline Instruction InvokeVirtual(size_t index_argument, std::optional<const Value> dest,
Eric Holkfaefd4f2018-10-11 16:25:57 -0700218 Value this_arg, T... args) {
Eric Holkc69449d2018-12-13 11:35:58 -0800219 return Instruction{
Eric Holk3092f992019-07-25 15:14:01 -0700220 Op::kInvokeVirtual, index_argument, /*result_is_object=*/false, dest, this_arg, args...};
Eric Holkc69449d2018-12-13 11:35:58 -0800221 }
222 // Returns an object
223 template <typename... T>
Eric Holkf3b95892019-07-30 14:47:06 -0700224 static inline Instruction InvokeVirtualObject(size_t index_argument,
225 std::optional<const Value> dest, Value this_arg,
Eric Holk5c6a1a52019-09-17 13:28:34 -0700226 const T&... args) {
Eric Holkc69449d2018-12-13 11:35:58 -0800227 return Instruction{
Eric Holk3092f992019-07-25 15:14:01 -0700228 Op::kInvokeVirtual, index_argument, /*result_is_object=*/true, dest, this_arg, args...};
Eric Holkfaefd4f2018-10-11 16:25:57 -0700229 }
Eric Holkb3927582018-11-08 16:40:16 -0800230 // For direct calls (basically, constructors).
231 template <typename... T>
Eric Holk3092f992019-07-25 15:14:01 -0700232 static inline Instruction InvokeDirect(size_t index_argument, std::optional<const Value> dest,
Eric Holk5c6a1a52019-09-17 13:28:34 -0700233 Value this_arg, const T&... args) {
Eric Holkc69449d2018-12-13 11:35:58 -0800234 return Instruction{
Eric Holk3092f992019-07-25 15:14:01 -0700235 Op::kInvokeDirect, index_argument, /*result_is_object=*/false, dest, this_arg, args...};
Eric Holkc69449d2018-12-13 11:35:58 -0800236 }
237 // Returns an object
238 template <typename... T>
Eric Holkf3b95892019-07-30 14:47:06 -0700239 static inline Instruction InvokeDirectObject(size_t index_argument,
240 std::optional<const Value> dest, Value this_arg,
241 T... args) {
Eric Holkc69449d2018-12-13 11:35:58 -0800242 return Instruction{
Eric Holk3092f992019-07-25 15:14:01 -0700243 Op::kInvokeDirect, index_argument, /*result_is_object=*/true, dest, this_arg, args...};
Eric Holkc69449d2018-12-13 11:35:58 -0800244 }
245 // For static calls.
246 template <typename... T>
Eric Holk3092f992019-07-25 15:14:01 -0700247 static inline Instruction InvokeStatic(size_t index_argument, std::optional<const Value> dest,
Eric Holkc69449d2018-12-13 11:35:58 -0800248 T... args) {
Eric Holkf3b95892019-07-30 14:47:06 -0700249 return Instruction{
250 Op::kInvokeStatic, index_argument, /*result_is_object=*/false, dest, args...};
Eric Holkc69449d2018-12-13 11:35:58 -0800251 }
252 // Returns an object
253 template <typename... T>
Eric Holkf3b95892019-07-30 14:47:06 -0700254 static inline Instruction InvokeStaticObject(size_t index_argument,
255 std::optional<const Value> dest, T... args) {
Eric Holk3092f992019-07-25 15:14:01 -0700256 return Instruction{Op::kInvokeStatic, index_argument, /*result_is_object=*/true, dest, args...};
Eric Holkc69449d2018-12-13 11:35:58 -0800257 }
258 // For static calls.
259 template <typename... T>
Eric Holk3092f992019-07-25 15:14:01 -0700260 static inline Instruction InvokeInterface(size_t index_argument, std::optional<const Value> dest,
Eric Holk5c6a1a52019-09-17 13:28:34 -0700261 const T&... args) {
Eric Holkf3b95892019-07-30 14:47:06 -0700262 return Instruction{
263 Op::kInvokeInterface, index_argument, /*result_is_object=*/false, dest, args...};
Eric Holk3092f992019-07-25 15:14:01 -0700264 }
265
266 static inline Instruction GetStaticField(size_t field_id, Value dest) {
267 return Instruction{Op::kGetStaticField, field_id, dest};
Eric Holkb3927582018-11-08 16:40:16 -0800268 }
Eric Holkfaefd4f2018-10-11 16:25:57 -0700269
Eric Holk70445d02019-07-26 09:37:46 -0700270 static inline Instruction SetStaticField(size_t field_id, Value value) {
Eric Holkf3b95892019-07-30 14:47:06 -0700271 return Instruction{
272 Op::kSetStaticField, field_id, /*result_is_object=*/false, /*dest=*/{}, value};
Eric Holk70445d02019-07-26 09:37:46 -0700273 }
274
Eric Holkf3b95892019-07-30 14:47:06 -0700275 static inline Instruction GetField(size_t field_id, Value dest, Value object) {
276 return Instruction{Op::kGetInstanceField, field_id, /*result_is_object=*/false, dest, object};
277 }
278
279 static inline Instruction SetField(size_t field_id, Value object, Value value) {
280 return Instruction{
281 Op::kSetInstanceField, field_id, /*result_is_object=*/false, /*dest=*/{}, object, value};
282 }
Eric Holk70445d02019-07-26 09:37:46 -0700283
Eric Holkfaefd4f2018-10-11 16:25:57 -0700284 ///////////////
285 // Accessors //
286 ///////////////
287
288 Op opcode() const { return opcode_; }
Eric Holk3092f992019-07-25 15:14:01 -0700289 size_t index_argument() const { return index_argument_; }
Eric Holkc69449d2018-12-13 11:35:58 -0800290 bool result_is_object() const { return result_is_object_; }
Eric Holkfaefd4f2018-10-11 16:25:57 -0700291 const std::optional<const Value>& dest() const { return dest_; }
292 const std::vector<const Value>& args() const { return args_; }
293
294 private:
Eric Holk3092f992019-07-25 15:14:01 -0700295 inline Instruction(Op opcode, size_t index_argument, std::optional<const Value> dest)
Eric Holkf3b95892019-07-30 14:47:06 -0700296 : opcode_{opcode},
297 index_argument_{index_argument},
298 result_is_object_{false},
299 dest_{dest},
300 args_{} {}
Eric Holkfaefd4f2018-10-11 16:25:57 -0700301
302 template <typename... T>
Eric Holkf3b95892019-07-30 14:47:06 -0700303 inline Instruction(Op opcode, size_t index_argument, bool result_is_object,
Eric Holk5c6a1a52019-09-17 13:28:34 -0700304 std::optional<const Value> dest, const T&... args)
Eric Holkc69449d2018-12-13 11:35:58 -0800305 : opcode_{opcode},
Eric Holk3092f992019-07-25 15:14:01 -0700306 index_argument_{index_argument},
Eric Holkc69449d2018-12-13 11:35:58 -0800307 result_is_object_{result_is_object},
308 dest_{dest},
309 args_{args...} {}
Eric Holkfaefd4f2018-10-11 16:25:57 -0700310
311 const Op opcode_;
312 // The index of the method to invoke, for kInvokeVirtual and similar opcodes.
Eric Holk3092f992019-07-25 15:14:01 -0700313 const size_t index_argument_{0};
Eric Holkc69449d2018-12-13 11:35:58 -0800314 const bool result_is_object_;
Eric Holkfaefd4f2018-10-11 16:25:57 -0700315 const std::optional<const Value> dest_;
316 const std::vector<const Value> args_;
317};
318
319// Needed for CHECK_EQ, DCHECK_EQ, etc.
320std::ostream& operator<<(std::ostream& out, const Instruction::Op& opcode);
321
Eric Holkb3927582018-11-08 16:40:16 -0800322// Keeps track of information needed to manipulate or call a method.
323struct MethodDeclData {
324 size_t id;
325 ir::MethodDecl* decl;
326};
327
Eric Holkdbc36e22018-09-20 12:03:10 -0700328// Tools to help build methods and their bodies.
329class MethodBuilder {
330 public:
331 MethodBuilder(DexBuilder* dex, ir::Class* class_def, ir::MethodDecl* decl);
332
333 // Encode the method into DEX format.
334 ir::EncodedMethod* Encode();
335
Eric Holk5c6a1a52019-09-17 13:28:34 -0700336 // Create a new register to be used to storing values.
337 LiveRegister AllocRegister();
Eric Holkdbc36e22018-09-20 12:03:10 -0700338
Eric Holkd62c5aa2018-11-01 15:50:24 -0700339 Value MakeLabel();
340
Eric Holkdbc36e22018-09-20 12:03:10 -0700341 /////////////////////////////////
342 // Instruction builder methods //
343 /////////////////////////////////
344
Eric Holkfaefd4f2018-10-11 16:25:57 -0700345 void AddInstruction(Instruction instruction);
346
Eric Holkdbc36e22018-09-20 12:03:10 -0700347 // return-void
348 void BuildReturn();
Eric Holk3cc4afc2018-11-08 14:16:20 -0800349 void BuildReturn(Value src, bool is_object = false);
Eric Holkdbc36e22018-09-20 12:03:10 -0700350 // const/4
Eric Holkfaefd4f2018-10-11 16:25:57 -0700351 void BuildConst4(Value target, int value);
Eric Holk3cc4afc2018-11-08 14:16:20 -0800352 void BuildConstString(Value target, const std::string& value);
Eric Holkb3927582018-11-08 16:40:16 -0800353 template <typename... T>
Eric Holk5c6a1a52019-09-17 13:28:34 -0700354 void BuildNew(Value target, TypeDescriptor type, Prototype constructor, const T&... args);
Eric Holkdbc36e22018-09-20 12:03:10 -0700355
356 // TODO: add builders for more instructions
357
Eric Holkc69449d2018-12-13 11:35:58 -0800358 DexBuilder* dex_file() const { return dex_; }
359
Eric Holkdbc36e22018-09-20 12:03:10 -0700360 private:
Eric Holkfaefd4f2018-10-11 16:25:57 -0700361 void EncodeInstructions();
362 void EncodeInstruction(const Instruction& instruction);
Eric Holk3cc4afc2018-11-08 14:16:20 -0800363
364 // Encodes a return instruction. For instructions with no return value, the opcode field is
365 // ignored. Otherwise, this specifies which return instruction will be used (return,
366 // return-object, etc.)
367 void EncodeReturn(const Instruction& instruction, ::art::Instruction::Code opcode);
368
Eric Holkfaefd4f2018-10-11 16:25:57 -0700369 void EncodeMove(const Instruction& instruction);
Eric Holkb3927582018-11-08 16:40:16 -0800370 void EncodeInvoke(const Instruction& instruction, ::art::Instruction::Code opcode);
Eric Holkd62c5aa2018-11-01 15:50:24 -0700371 void EncodeBranch(art::Instruction::Code op, const Instruction& instruction);
Eric Holkb3927582018-11-08 16:40:16 -0800372 void EncodeNew(const Instruction& instruction);
Eric Holk44d8cdf2018-12-17 13:35:34 -0800373 void EncodeCast(const Instruction& instruction);
Eric Holkf3b95892019-07-30 14:47:06 -0700374 void EncodeFieldOp(const Instruction& instruction);
Eric Holkfaefd4f2018-10-11 16:25:57 -0700375
Eric Holk1c0f3f02018-11-09 13:48:59 -0800376 // Low-level instruction format encoding. See
377 // https://source.android.com/devices/tech/dalvik/instruction-formats for documentation of
378 // formats.
379
380 inline void Encode10x(art::Instruction::Code opcode) {
381 // 00|op
382 buffer_.push_back(opcode);
383 }
384
385 inline void Encode11x(art::Instruction::Code opcode, uint8_t a) {
386 // aa|op
387 buffer_.push_back((a << 8) | opcode);
388 }
389
390 inline void Encode11n(art::Instruction::Code opcode, uint8_t a, int8_t b) {
391 // b|a|op
392
393 // Make sure the fields are in bounds (4 bits for a, 4 bits for b).
394 CHECK_LT(a, 16);
395 CHECK_LE(-8, b);
396 CHECK_LT(b, 8);
397
398 buffer_.push_back(((b & 0xf) << 12) | (a << 8) | opcode);
399 }
400
401 inline void Encode21c(art::Instruction::Code opcode, uint8_t a, uint16_t b) {
402 // aa|op|bbbb
403 buffer_.push_back((a << 8) | opcode);
404 buffer_.push_back(b);
405 }
406
Eric Holkf3b95892019-07-30 14:47:06 -0700407 inline void Encode22c(art::Instruction::Code opcode, uint8_t a, uint8_t b, uint16_t c) {
408 // b|a|op|bbbb
409 CHECK(IsShortRegister(a));
410 CHECK(IsShortRegister(b));
411 buffer_.push_back((b << 12) | (a << 8) | opcode);
412 buffer_.push_back(c);
413 }
414
Eric Holkd1b43832019-01-29 08:32:42 -0800415 inline void Encode32x(art::Instruction::Code opcode, uint16_t a, uint16_t b) {
416 buffer_.push_back(opcode);
417 buffer_.push_back(a);
418 buffer_.push_back(b);
419 }
420
Eric Holk1c0f3f02018-11-09 13:48:59 -0800421 inline void Encode35c(art::Instruction::Code opcode, size_t a, uint16_t b, uint8_t c, uint8_t d,
422 uint8_t e, uint8_t f, uint8_t g) {
423 // a|g|op|bbbb|f|e|d|c
424
425 CHECK_LE(a, 5);
Eric Holkd1b43832019-01-29 08:32:42 -0800426 CHECK(IsShortRegister(c));
427 CHECK(IsShortRegister(d));
428 CHECK(IsShortRegister(e));
429 CHECK(IsShortRegister(f));
430 CHECK(IsShortRegister(g));
Eric Holk1c0f3f02018-11-09 13:48:59 -0800431 buffer_.push_back((a << 12) | (g << 8) | opcode);
432 buffer_.push_back(b);
433 buffer_.push_back((f << 12) | (e << 8) | (d << 4) | c);
434 }
435
Eric Holkd1b43832019-01-29 08:32:42 -0800436 inline void Encode3rc(art::Instruction::Code opcode, size_t a, uint16_t b, uint16_t c) {
437 CHECK_LE(a, 255);
438 buffer_.push_back((a << 8) | opcode);
439 buffer_.push_back(b);
440 buffer_.push_back(c);
441 }
442
443 static constexpr bool IsShortRegister(size_t register_value) { return register_value < 16; }
444
445 // Returns an array of num_regs scratch registers. These are guaranteed to be
446 // contiguous, so they are suitable for the invoke-*/range instructions.
447 template <int num_regs>
448 std::array<Value, num_regs> GetScratchRegisters() const {
449 static_assert(num_regs <= kMaxScratchRegisters);
450 std::array<Value, num_regs> regs;
451 for (size_t i = 0; i < num_regs; ++i) {
Eric Holk5c6a1a52019-09-17 13:28:34 -0700452 regs[i] = std::move(Value::Local(NumRegisters() + i));
Eric Holkd1b43832019-01-29 08:32:42 -0800453 }
454 return regs;
455 }
456
Eric Holkfaefd4f2018-10-11 16:25:57 -0700457 // Converts a register or parameter to its DEX register number.
Eric Holkd62c5aa2018-11-01 15:50:24 -0700458 size_t RegisterValue(const Value& value) const;
459
460 // Sets a label's address to the current position in the instruction buffer. If there are any
461 // forward references to the label, this function will back-patch them.
462 void BindLabel(const Value& label);
463
464 // Returns the offset of the label relative to the given instruction offset. If the label is not
465 // bound, a reference will be saved and it will automatically be patched when the label is bound.
466 ::dex::u2 LabelValue(const Value& label, size_t instruction_offset, size_t field_offset);
Eric Holkfaefd4f2018-10-11 16:25:57 -0700467
Eric Holkdbc36e22018-09-20 12:03:10 -0700468 DexBuilder* dex_;
469 ir::Class* class_;
470 ir::MethodDecl* decl_;
471
Eric Holkfaefd4f2018-10-11 16:25:57 -0700472 // A list of the instructions we will eventually encode.
473 std::vector<Instruction> instructions_;
474
475 // A buffer to hold instructions that have been encoded.
Eric Holkdbc36e22018-09-20 12:03:10 -0700476 std::vector<::dex::u2> buffer_;
477
Eric Holkd1b43832019-01-29 08:32:42 -0800478 // We create some scratch registers for when we have to shuffle registers
479 // around to make legal DEX code.
480 static constexpr size_t kMaxScratchRegisters = 5;
481
Eric Holk5c6a1a52019-09-17 13:28:34 -0700482 size_t NumRegisters() const {
483 return register_liveness_.size();
484 }
Eric Holkd62c5aa2018-11-01 15:50:24 -0700485
486 // Stores information needed to back-patch a label once it is bound. We need to know the start of
487 // the instruction that refers to the label, and the offset to where the actual label value should
488 // go.
489 struct LabelReference {
490 size_t instruction_offset;
491 size_t field_offset;
492 };
493
494 struct LabelData {
495 std::optional<size_t> bound_address;
496 std::forward_list<LabelReference> references;
497 };
498
499 std::vector<LabelData> labels_;
Eric Holkb3927582018-11-08 16:40:16 -0800500
501 // During encoding, keep track of the largest number of arguments needed, so we can use it for our
502 // outs count
503 size_t max_args_{0};
Eric Holk5c6a1a52019-09-17 13:28:34 -0700504
505 std::vector<bool> register_liveness_;
Eric Holkdbc36e22018-09-20 12:03:10 -0700506};
507
508// A helper to build class definitions.
509class ClassBuilder {
510 public:
Eric Holkfaefd4f2018-10-11 16:25:57 -0700511 ClassBuilder(DexBuilder* parent, const std::string& name, ir::Class* class_def);
Eric Holkdbc36e22018-09-20 12:03:10 -0700512
513 void set_source_file(const std::string& source);
514
515 // Create a method with the given name and prototype. The returned MethodBuilder can be used to
516 // fill in the method body.
517 MethodBuilder CreateMethod(const std::string& name, Prototype prototype);
518
519 private:
Eric Holkfaefd4f2018-10-11 16:25:57 -0700520 DexBuilder* const parent_;
521 const TypeDescriptor type_descriptor_;
522 ir::Class* const class_;
523};
524
Eric Holkdbc36e22018-09-20 12:03:10 -0700525// Builds Dex files from scratch.
526class DexBuilder {
527 public:
528 DexBuilder();
529
530 // Create an in-memory image of the DEX file that can either be loaded directly or written to a
531 // file.
532 slicer::MemView CreateImage();
533
534 template <typename T>
535 T* Alloc() {
536 return dex_file_->Alloc<T>();
537 }
538
539 // Find the ir::String that matches the given string, creating it if it does not exist.
540 ir::String* GetOrAddString(const std::string& string);
541 // Create a new class of the given name.
542 ClassBuilder MakeClass(const std::string& name);
543
544 // Add a type for the given descriptor, or return the existing one if it already exists.
Eric Holkfaefd4f2018-10-11 16:25:57 -0700545 // See the TypeDescriptor class for help generating these. GetOrAddType can be used to declare
546 // imported classes.
Eric Holkdbc36e22018-09-20 12:03:10 -0700547 ir::Type* GetOrAddType(const std::string& descriptor);
Eric Holk3092f992019-07-25 15:14:01 -0700548 inline ir::Type* GetOrAddType(TypeDescriptor descriptor) {
549 return GetOrAddType(descriptor.descriptor());
550 }
551
552 ir::FieldDecl* GetOrAddField(TypeDescriptor parent, const std::string& name, TypeDescriptor type);
Eric Holkdbc36e22018-09-20 12:03:10 -0700553
Eric Holkfaefd4f2018-10-11 16:25:57 -0700554 // Returns the method id for the method, creating it if it has not been created yet.
555 const MethodDeclData& GetOrDeclareMethod(TypeDescriptor type, const std::string& name,
556 Prototype prototype);
557
Eric Holkd1b43832019-01-29 08:32:42 -0800558 std::optional<const Prototype> GetPrototypeByMethodId(size_t method_id) const;
559
Eric Holkdbc36e22018-09-20 12:03:10 -0700560 private:
Eric Holkfaefd4f2018-10-11 16:25:57 -0700561 // Looks up the ir::Proto* corresponding to this given prototype, or creates one if it does not
562 // exist.
563 ir::Proto* GetOrEncodeProto(Prototype prototype);
564
Eric Holkdbc36e22018-09-20 12:03:10 -0700565 std::shared_ptr<ir::DexFile> dex_file_;
566
567 // allocator_ is needed to be able to encode the image.
568 TrackingAllocator allocator_;
569
570 // We'll need to allocate buffers for all of the encoded strings we create. This is where we store
571 // all of them.
572 std::vector<std::unique_ptr<uint8_t[]>> string_data_;
573
574 // Keep track of what types we've defined so we can look them up later.
Eric Holkfaefd4f2018-10-11 16:25:57 -0700575 std::unordered_map<std::string, ir::Type*> types_by_descriptor_;
576
577 struct MethodDescriptor {
578 TypeDescriptor type;
579 std::string name;
580 Prototype prototype;
581
582 inline bool operator<(const MethodDescriptor& rhs) const {
583 return std::make_tuple(type, name, prototype) <
584 std::make_tuple(rhs.type, rhs.name, rhs.prototype);
585 }
586 };
587
588 // Maps method declarations to their method index. This is needed to encode references to them.
589 // When we go to actually write the DEX file, slicer will re-assign these after correctly sorting
590 // the methods list.
591 std::map<MethodDescriptor, MethodDeclData> method_id_map_;
Eric Holkdbc36e22018-09-20 12:03:10 -0700592
593 // Keep track of what strings we've defined so we can look them up later.
Eric Holkfaefd4f2018-10-11 16:25:57 -0700594 std::unordered_map<std::string, ir::String*> strings_;
595
596 // Keep track of already-encoded protos.
597 std::map<Prototype, ir::Proto*> proto_map_;
Eric Holk3092f992019-07-25 15:14:01 -0700598
599 // Keep track of fields that have been declared
600 std::map<std::tuple<TypeDescriptor, std::string>, ir::FieldDecl*> field_decls_by_key_;
Eric Holkdbc36e22018-09-20 12:03:10 -0700601};
602
Eric Holkb3927582018-11-08 16:40:16 -0800603template <typename... T>
Eric Holk5c6a1a52019-09-17 13:28:34 -0700604void MethodBuilder::BuildNew(Value target, TypeDescriptor type, Prototype constructor,
605 const T&... args) {
Eric Holkb3927582018-11-08 16:40:16 -0800606 MethodDeclData constructor_data{dex_->GetOrDeclareMethod(type, "<init>", constructor)};
607 // allocate the object
608 ir::Type* type_def = dex_->GetOrAddType(type.descriptor());
609 AddInstruction(
610 Instruction::OpWithArgs(Instruction::Op::kNew, target, Value::Type(type_def->orig_index)));
611 // call the constructor
612 AddInstruction(Instruction::InvokeDirect(constructor_data.id, /*dest=*/{}, target, args...));
613};
614
Eric Holkdbc36e22018-09-20 12:03:10 -0700615} // namespace dex
616} // namespace startop
617
618#endif // DEX_BUILDER_H_