blob: eb2dc88835d46507f127288ca68ceb7bb3b73679 [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
Orion Hodson59d07202019-10-31 15:25:33 +000027#include "android-base/logging.h"
28
29#include "slicer/dex_bytecode.h"
Eric Holkdbc36e22018-09-20 12:03:10 -070030#include "slicer/dex_ir.h"
31#include "slicer/writer.h"
32
33namespace startop {
34namespace dex {
35
36// TODO: remove this once the dex generation code is complete.
37void WriteTestDexFile(const std::string& filename);
38
39//////////////////////////
40// Forward declarations //
41//////////////////////////
42class DexBuilder;
43
44// Our custom allocator for dex::Writer
45//
46// This keeps track of all allocations and ensures they are freed when
47// TrackingAllocator is destroyed. Pointers to memory allocated by this
48// allocator must not outlive the allocator.
49class TrackingAllocator : public ::dex::Writer::Allocator {
50 public:
51 virtual void* Allocate(size_t size);
52 virtual void Free(void* ptr);
53
54 private:
Eric Holkfaefd4f2018-10-11 16:25:57 -070055 std::unordered_map<void*, std::unique_ptr<uint8_t[]>> allocations_;
Eric Holkdbc36e22018-09-20 12:03:10 -070056};
57
58// Represents a DEX type descriptor.
59//
60// TODO: add a way to create a descriptor for a reference of a class type.
61class TypeDescriptor {
62 public:
63 // Named constructors for base type descriptors.
64 static const TypeDescriptor Int();
65 static const TypeDescriptor Void();
66
Eric Holkfaefd4f2018-10-11 16:25:57 -070067 // Creates a type descriptor from a fully-qualified class name. For example, it turns the class
68 // name java.lang.Object into the descriptor Ljava/lang/Object.
69 static TypeDescriptor FromClassname(const std::string& name);
70
Eric Holkdbc36e22018-09-20 12:03:10 -070071 // Return the full descriptor, such as I or Ljava/lang/Object
72 const std::string& descriptor() const { return descriptor_; }
73 // Return the shorty descriptor, such as I or L
74 std::string short_descriptor() const { return descriptor().substr(0, 1); }
75
Eric Holkd1b43832019-01-29 08:32:42 -080076 bool is_object() const { return short_descriptor() == "L"; }
77
Eric Holkfaefd4f2018-10-11 16:25:57 -070078 bool operator<(const TypeDescriptor& rhs) const { return descriptor_ < rhs.descriptor_; }
79
Eric Holkdbc36e22018-09-20 12:03:10 -070080 private:
Chih-Hung Hsieh81aff0f2018-12-20 13:53:28 -080081 explicit TypeDescriptor(std::string descriptor) : descriptor_{descriptor} {}
Eric Holkdbc36e22018-09-20 12:03:10 -070082
83 const std::string descriptor_;
84};
85
86// Defines a function signature. For example, Prototype{TypeDescriptor::VOID, TypeDescriptor::Int}
87// represents the function type (Int) -> Void.
88class Prototype {
89 public:
90 template <typename... TypeDescriptors>
Chih-Hung Hsieh81aff0f2018-12-20 13:53:28 -080091 explicit Prototype(TypeDescriptor return_type, TypeDescriptors... param_types)
Eric Holkdbc36e22018-09-20 12:03:10 -070092 : return_type_{return_type}, param_types_{param_types...} {}
93
94 // Encode this prototype into the dex file.
95 ir::Proto* Encode(DexBuilder* dex) const;
96
97 // Get the shorty descriptor, such as VII for (Int, Int) -> Void
98 std::string Shorty() const;
99
Eric Holkd1b43832019-01-29 08:32:42 -0800100 const TypeDescriptor& ArgType(size_t index) const;
101
Eric Holkfaefd4f2018-10-11 16:25:57 -0700102 bool operator<(const Prototype& rhs) const {
103 return std::make_tuple(return_type_, param_types_) <
104 std::make_tuple(rhs.return_type_, rhs.param_types_);
105 }
106
Eric Holkdbc36e22018-09-20 12:03:10 -0700107 private:
108 const TypeDescriptor return_type_;
109 const std::vector<TypeDescriptor> param_types_;
110};
111
Eric Holkfaefd4f2018-10-11 16:25:57 -0700112// Represents a DEX register or constant. We separate regular registers and parameters
113// because we will not know the real parameter id until after all instructions
114// have been generated.
115class Value {
116 public:
117 static constexpr Value Local(size_t id) { return Value{id, Kind::kLocalRegister}; }
118 static constexpr Value Parameter(size_t id) { return Value{id, Kind::kParameter}; }
119 static constexpr Value Immediate(size_t value) { return Value{value, Kind::kImmediate}; }
Eric Holk3cc4afc2018-11-08 14:16:20 -0800120 static constexpr Value String(size_t value) { return Value{value, Kind::kString}; }
Eric Holkd62c5aa2018-11-01 15:50:24 -0700121 static constexpr Value Label(size_t id) { return Value{id, Kind::kLabel}; }
Eric Holkb3927582018-11-08 16:40:16 -0800122 static constexpr Value Type(size_t id) { return Value{id, Kind::kType}; }
Eric Holkfaefd4f2018-10-11 16:25:57 -0700123
124 bool is_register() const { return kind_ == Kind::kLocalRegister; }
125 bool is_parameter() const { return kind_ == Kind::kParameter; }
Eric Holkd62c5aa2018-11-01 15:50:24 -0700126 bool is_variable() const { return is_register() || is_parameter(); }
Eric Holkfaefd4f2018-10-11 16:25:57 -0700127 bool is_immediate() const { return kind_ == Kind::kImmediate; }
Eric Holk3cc4afc2018-11-08 14:16:20 -0800128 bool is_string() const { return kind_ == Kind::kString; }
Eric Holkd62c5aa2018-11-01 15:50:24 -0700129 bool is_label() const { return kind_ == Kind::kLabel; }
Eric Holkb3927582018-11-08 16:40:16 -0800130 bool is_type() const { return kind_ == Kind::kType; }
Eric Holkfaefd4f2018-10-11 16:25:57 -0700131
132 size_t value() const { return value_; }
133
Eric Holkd1b43832019-01-29 08:32:42 -0800134 constexpr Value() : value_{0}, kind_{Kind::kInvalid} {}
Eric Holkfaefd4f2018-10-11 16:25:57 -0700135
Eric Holkd1b43832019-01-29 08:32:42 -0800136 private:
137 enum class Kind { kInvalid, kLocalRegister, kParameter, kImmediate, kString, kLabel, kType };
138
139 size_t value_;
140 Kind kind_;
Eric Holkfaefd4f2018-10-11 16:25:57 -0700141
142 constexpr Value(size_t value, Kind kind) : value_{value}, kind_{kind} {}
143};
144
Eric Holk5c6a1a52019-09-17 13:28:34 -0700145// Represents an allocated register returned by MethodBuilder::AllocRegister
146class LiveRegister {
147 friend class MethodBuilder;
148
149 public:
150 LiveRegister(LiveRegister&& other) : liveness_{other.liveness_}, index_{other.index_} {
151 other.index_ = {};
152 };
153 ~LiveRegister() {
154 if (index_.has_value()) {
155 (*liveness_)[*index_] = false;
156 }
157 };
158
159 operator const Value() const { return Value::Local(*index_); }
160
161 private:
162 LiveRegister(std::vector<bool>* liveness, size_t index) : liveness_{liveness}, index_{index} {}
163
164 std::vector<bool>* const liveness_;
165 std::optional<size_t> index_;
166};
167
Eric Holkfaefd4f2018-10-11 16:25:57 -0700168// A virtual instruction. We convert these to real instructions in MethodBuilder::Encode.
169// Virtual instructions are needed to keep track of information that is not known until all of the
170// code is generated. This information includes things like how many local registers are created and
171// branch target locations.
172class Instruction {
173 public:
174 // The operation performed by this instruction. These are virtual instructions that do not
175 // correspond exactly to DEX instructions.
Eric Holkb3927582018-11-08 16:40:16 -0800176 enum class Op {
Eric Holkb3927582018-11-08 16:40:16 -0800177 kBindLabel,
178 kBranchEqz,
Eric Holkc69449d2018-12-13 11:35:58 -0800179 kBranchNEqz,
Eric Holk44d8cdf2018-12-17 13:35:34 -0800180 kCheckCast,
Eric Holkf3b95892019-07-30 14:47:06 -0700181 kGetInstanceField,
Eric Holk3092f992019-07-25 15:14:01 -0700182 kGetStaticField,
Eric Holk44d8cdf2018-12-17 13:35:34 -0800183 kInvokeDirect,
184 kInvokeInterface,
185 kInvokeStatic,
186 kInvokeVirtual,
187 kMove,
Eric Holkd1b43832019-01-29 08:32:42 -0800188 kMoveObject,
Eric Holk44d8cdf2018-12-17 13:35:34 -0800189 kNew,
190 kReturn,
191 kReturnObject,
Eric Holkf3b95892019-07-30 14:47:06 -0700192 kSetInstanceField,
Eric Holk70445d02019-07-26 09:37:46 -0700193 kSetStaticField
Eric Holkb3927582018-11-08 16:40:16 -0800194 };
Eric Holkfaefd4f2018-10-11 16:25:57 -0700195
196 ////////////////////////
197 // Named Constructors //
198 ////////////////////////
199
200 // For instructions with no return value and no arguments.
201 static inline Instruction OpNoArgs(Op opcode) {
Eric Holk3092f992019-07-25 15:14:01 -0700202 return Instruction{opcode, /*index_argument*/ 0, /*dest*/ {}};
Eric Holkfaefd4f2018-10-11 16:25:57 -0700203 }
204 // For most instructions, which take some number of arguments and have an optional return value.
205 template <typename... T>
Eric Holk5c6a1a52019-09-17 13:28:34 -0700206 static inline Instruction OpWithArgs(Op opcode, std::optional<const Value> dest,
207 const T&... args) {
Eric Holk3092f992019-07-25 15:14:01 -0700208 return Instruction{opcode, /*index_argument=*/0, /*result_is_object=*/false, dest, args...};
Eric Holkfaefd4f2018-10-11 16:25:57 -0700209 }
Eric Holk44d8cdf2018-12-17 13:35:34 -0800210
211 // A cast instruction. Basically, `(type)val`
212 static inline Instruction Cast(Value val, Value type) {
Eric Holkd1b43832019-01-29 08:32:42 -0800213 CHECK(type.is_type());
Eric Holk44d8cdf2018-12-17 13:35:34 -0800214 return OpWithArgs(Op::kCheckCast, val, type);
215 }
216
Eric Holkfaefd4f2018-10-11 16:25:57 -0700217 // For method calls.
218 template <typename... T>
Eric Holk3092f992019-07-25 15:14:01 -0700219 static inline Instruction InvokeVirtual(size_t index_argument, std::optional<const Value> dest,
Eric Holkfaefd4f2018-10-11 16:25:57 -0700220 Value this_arg, T... args) {
Eric Holkc69449d2018-12-13 11:35:58 -0800221 return Instruction{
Eric Holk3092f992019-07-25 15:14:01 -0700222 Op::kInvokeVirtual, index_argument, /*result_is_object=*/false, dest, this_arg, args...};
Eric Holkc69449d2018-12-13 11:35:58 -0800223 }
224 // Returns an object
225 template <typename... T>
Eric Holkf3b95892019-07-30 14:47:06 -0700226 static inline Instruction InvokeVirtualObject(size_t index_argument,
227 std::optional<const Value> dest, Value this_arg,
Eric Holk5c6a1a52019-09-17 13:28:34 -0700228 const T&... args) {
Eric Holkc69449d2018-12-13 11:35:58 -0800229 return Instruction{
Eric Holk3092f992019-07-25 15:14:01 -0700230 Op::kInvokeVirtual, index_argument, /*result_is_object=*/true, dest, this_arg, args...};
Eric Holkfaefd4f2018-10-11 16:25:57 -0700231 }
Eric Holkb3927582018-11-08 16:40:16 -0800232 // For direct calls (basically, constructors).
233 template <typename... T>
Eric Holk3092f992019-07-25 15:14:01 -0700234 static inline Instruction InvokeDirect(size_t index_argument, std::optional<const Value> dest,
Eric Holk5c6a1a52019-09-17 13:28:34 -0700235 Value this_arg, const T&... args) {
Eric Holkc69449d2018-12-13 11:35:58 -0800236 return Instruction{
Eric Holk3092f992019-07-25 15:14:01 -0700237 Op::kInvokeDirect, index_argument, /*result_is_object=*/false, dest, this_arg, args...};
Eric Holkc69449d2018-12-13 11:35:58 -0800238 }
239 // Returns an object
240 template <typename... T>
Eric Holkf3b95892019-07-30 14:47:06 -0700241 static inline Instruction InvokeDirectObject(size_t index_argument,
242 std::optional<const Value> dest, Value this_arg,
243 T... args) {
Eric Holkc69449d2018-12-13 11:35:58 -0800244 return Instruction{
Eric Holk3092f992019-07-25 15:14:01 -0700245 Op::kInvokeDirect, index_argument, /*result_is_object=*/true, dest, this_arg, args...};
Eric Holkc69449d2018-12-13 11:35:58 -0800246 }
247 // For static calls.
248 template <typename... T>
Eric Holk3092f992019-07-25 15:14:01 -0700249 static inline Instruction InvokeStatic(size_t index_argument, std::optional<const Value> dest,
Eric Holkc69449d2018-12-13 11:35:58 -0800250 T... args) {
Eric Holkf3b95892019-07-30 14:47:06 -0700251 return Instruction{
252 Op::kInvokeStatic, index_argument, /*result_is_object=*/false, dest, args...};
Eric Holkc69449d2018-12-13 11:35:58 -0800253 }
254 // Returns an object
255 template <typename... T>
Eric Holkf3b95892019-07-30 14:47:06 -0700256 static inline Instruction InvokeStaticObject(size_t index_argument,
257 std::optional<const Value> dest, T... args) {
Eric Holk3092f992019-07-25 15:14:01 -0700258 return Instruction{Op::kInvokeStatic, index_argument, /*result_is_object=*/true, dest, args...};
Eric Holkc69449d2018-12-13 11:35:58 -0800259 }
260 // For static calls.
261 template <typename... T>
Eric Holk3092f992019-07-25 15:14:01 -0700262 static inline Instruction InvokeInterface(size_t index_argument, std::optional<const Value> dest,
Eric Holk5c6a1a52019-09-17 13:28:34 -0700263 const T&... args) {
Eric Holkf3b95892019-07-30 14:47:06 -0700264 return Instruction{
265 Op::kInvokeInterface, index_argument, /*result_is_object=*/false, dest, args...};
Eric Holk3092f992019-07-25 15:14:01 -0700266 }
267
268 static inline Instruction GetStaticField(size_t field_id, Value dest) {
269 return Instruction{Op::kGetStaticField, field_id, dest};
Eric Holkb3927582018-11-08 16:40:16 -0800270 }
Eric Holkfaefd4f2018-10-11 16:25:57 -0700271
Eric Holk70445d02019-07-26 09:37:46 -0700272 static inline Instruction SetStaticField(size_t field_id, Value value) {
Eric Holkf3b95892019-07-30 14:47:06 -0700273 return Instruction{
274 Op::kSetStaticField, field_id, /*result_is_object=*/false, /*dest=*/{}, value};
Eric Holk70445d02019-07-26 09:37:46 -0700275 }
276
Eric Holkf3b95892019-07-30 14:47:06 -0700277 static inline Instruction GetField(size_t field_id, Value dest, Value object) {
278 return Instruction{Op::kGetInstanceField, field_id, /*result_is_object=*/false, dest, object};
279 }
280
281 static inline Instruction SetField(size_t field_id, Value object, Value value) {
282 return Instruction{
283 Op::kSetInstanceField, field_id, /*result_is_object=*/false, /*dest=*/{}, object, value};
284 }
Eric Holk70445d02019-07-26 09:37:46 -0700285
Eric Holkfaefd4f2018-10-11 16:25:57 -0700286 ///////////////
287 // Accessors //
288 ///////////////
289
290 Op opcode() const { return opcode_; }
Eric Holk3092f992019-07-25 15:14:01 -0700291 size_t index_argument() const { return index_argument_; }
Eric Holkc69449d2018-12-13 11:35:58 -0800292 bool result_is_object() const { return result_is_object_; }
Eric Holkfaefd4f2018-10-11 16:25:57 -0700293 const std::optional<const Value>& dest() const { return dest_; }
294 const std::vector<const Value>& args() const { return args_; }
295
296 private:
Eric Holk3092f992019-07-25 15:14:01 -0700297 inline Instruction(Op opcode, size_t index_argument, std::optional<const Value> dest)
Eric Holkf3b95892019-07-30 14:47:06 -0700298 : opcode_{opcode},
299 index_argument_{index_argument},
300 result_is_object_{false},
301 dest_{dest},
302 args_{} {}
Eric Holkfaefd4f2018-10-11 16:25:57 -0700303
304 template <typename... T>
Eric Holkf3b95892019-07-30 14:47:06 -0700305 inline Instruction(Op opcode, size_t index_argument, bool result_is_object,
Eric Holk5c6a1a52019-09-17 13:28:34 -0700306 std::optional<const Value> dest, const T&... args)
Eric Holkc69449d2018-12-13 11:35:58 -0800307 : opcode_{opcode},
Eric Holk3092f992019-07-25 15:14:01 -0700308 index_argument_{index_argument},
Eric Holkc69449d2018-12-13 11:35:58 -0800309 result_is_object_{result_is_object},
310 dest_{dest},
311 args_{args...} {}
Eric Holkfaefd4f2018-10-11 16:25:57 -0700312
313 const Op opcode_;
314 // The index of the method to invoke, for kInvokeVirtual and similar opcodes.
Eric Holk3092f992019-07-25 15:14:01 -0700315 const size_t index_argument_{0};
Eric Holkc69449d2018-12-13 11:35:58 -0800316 const bool result_is_object_;
Eric Holkfaefd4f2018-10-11 16:25:57 -0700317 const std::optional<const Value> dest_;
318 const std::vector<const Value> args_;
319};
320
321// Needed for CHECK_EQ, DCHECK_EQ, etc.
322std::ostream& operator<<(std::ostream& out, const Instruction::Op& opcode);
323
Eric Holkb3927582018-11-08 16:40:16 -0800324// Keeps track of information needed to manipulate or call a method.
325struct MethodDeclData {
326 size_t id;
327 ir::MethodDecl* decl;
328};
329
Eric Holkdbc36e22018-09-20 12:03:10 -0700330// Tools to help build methods and their bodies.
331class MethodBuilder {
332 public:
333 MethodBuilder(DexBuilder* dex, ir::Class* class_def, ir::MethodDecl* decl);
334
335 // Encode the method into DEX format.
336 ir::EncodedMethod* Encode();
337
Eric Holk5c6a1a52019-09-17 13:28:34 -0700338 // Create a new register to be used to storing values.
339 LiveRegister AllocRegister();
Eric Holkdbc36e22018-09-20 12:03:10 -0700340
Eric Holkd62c5aa2018-11-01 15:50:24 -0700341 Value MakeLabel();
342
Eric Holkdbc36e22018-09-20 12:03:10 -0700343 /////////////////////////////////
344 // Instruction builder methods //
345 /////////////////////////////////
346
Eric Holkfaefd4f2018-10-11 16:25:57 -0700347 void AddInstruction(Instruction instruction);
348
Eric Holkdbc36e22018-09-20 12:03:10 -0700349 // return-void
350 void BuildReturn();
Eric Holk3cc4afc2018-11-08 14:16:20 -0800351 void BuildReturn(Value src, bool is_object = false);
Eric Holkdbc36e22018-09-20 12:03:10 -0700352 // const/4
Eric Holkfaefd4f2018-10-11 16:25:57 -0700353 void BuildConst4(Value target, int value);
Eric Holk3cc4afc2018-11-08 14:16:20 -0800354 void BuildConstString(Value target, const std::string& value);
Eric Holkb3927582018-11-08 16:40:16 -0800355 template <typename... T>
Eric Holk5c6a1a52019-09-17 13:28:34 -0700356 void BuildNew(Value target, TypeDescriptor type, Prototype constructor, const T&... args);
Eric Holkdbc36e22018-09-20 12:03:10 -0700357
358 // TODO: add builders for more instructions
359
Eric Holkc69449d2018-12-13 11:35:58 -0800360 DexBuilder* dex_file() const { return dex_; }
361
Eric Holkdbc36e22018-09-20 12:03:10 -0700362 private:
Eric Holkfaefd4f2018-10-11 16:25:57 -0700363 void EncodeInstructions();
364 void EncodeInstruction(const Instruction& instruction);
Eric Holk3cc4afc2018-11-08 14:16:20 -0800365
366 // Encodes a return instruction. For instructions with no return value, the opcode field is
367 // ignored. Otherwise, this specifies which return instruction will be used (return,
368 // return-object, etc.)
Orion Hodson59d07202019-10-31 15:25:33 +0000369 void EncodeReturn(const Instruction& instruction, ::dex::Opcode opcode);
Eric Holk3cc4afc2018-11-08 14:16:20 -0800370
Eric Holkfaefd4f2018-10-11 16:25:57 -0700371 void EncodeMove(const Instruction& instruction);
Orion Hodson59d07202019-10-31 15:25:33 +0000372 void EncodeInvoke(const Instruction& instruction, ::dex::Opcode opcode);
373 void EncodeBranch(::dex::Opcode op, const Instruction& instruction);
Eric Holkb3927582018-11-08 16:40:16 -0800374 void EncodeNew(const Instruction& instruction);
Eric Holk44d8cdf2018-12-17 13:35:34 -0800375 void EncodeCast(const Instruction& instruction);
Eric Holkf3b95892019-07-30 14:47:06 -0700376 void EncodeFieldOp(const Instruction& instruction);
Eric Holkfaefd4f2018-10-11 16:25:57 -0700377
Eric Holk1c0f3f02018-11-09 13:48:59 -0800378 // Low-level instruction format encoding. See
379 // https://source.android.com/devices/tech/dalvik/instruction-formats for documentation of
380 // formats.
381
Orion Hodsoncc8b8ca2019-11-04 16:58:26 +0000382 inline uint8_t ToBits(::dex::Opcode opcode) {
383 static_assert(sizeof(uint8_t) == sizeof(::dex::Opcode));
384 return static_cast<uint8_t>(opcode);
385 }
386
Orion Hodson59d07202019-10-31 15:25:33 +0000387 inline void Encode10x(::dex::Opcode opcode) {
Eric Holk1c0f3f02018-11-09 13:48:59 -0800388 // 00|op
Orion Hodson59d07202019-10-31 15:25:33 +0000389 static_assert(sizeof(uint8_t) == sizeof(::dex::Opcode));
Orion Hodsoncc8b8ca2019-11-04 16:58:26 +0000390 buffer_.push_back(ToBits(opcode));
Eric Holk1c0f3f02018-11-09 13:48:59 -0800391 }
392
Orion Hodson59d07202019-10-31 15:25:33 +0000393 inline void Encode11x(::dex::Opcode opcode, uint8_t a) {
Eric Holk1c0f3f02018-11-09 13:48:59 -0800394 // aa|op
Orion Hodsoncc8b8ca2019-11-04 16:58:26 +0000395 buffer_.push_back((a << 8) | ToBits(opcode));
Eric Holk1c0f3f02018-11-09 13:48:59 -0800396 }
397
Orion Hodson59d07202019-10-31 15:25:33 +0000398 inline void Encode11n(::dex::Opcode opcode, uint8_t a, int8_t b) {
Eric Holk1c0f3f02018-11-09 13:48:59 -0800399 // b|a|op
400
401 // Make sure the fields are in bounds (4 bits for a, 4 bits for b).
402 CHECK_LT(a, 16);
403 CHECK_LE(-8, b);
404 CHECK_LT(b, 8);
405
Orion Hodsoncc8b8ca2019-11-04 16:58:26 +0000406 buffer_.push_back(((b & 0xf) << 12) | (a << 8) | ToBits(opcode));
Eric Holk1c0f3f02018-11-09 13:48:59 -0800407 }
408
Orion Hodson59d07202019-10-31 15:25:33 +0000409 inline void Encode21c(::dex::Opcode opcode, uint8_t a, uint16_t b) {
Eric Holk1c0f3f02018-11-09 13:48:59 -0800410 // aa|op|bbbb
Orion Hodsoncc8b8ca2019-11-04 16:58:26 +0000411 buffer_.push_back((a << 8) | ToBits(opcode));
Eric Holk1c0f3f02018-11-09 13:48:59 -0800412 buffer_.push_back(b);
413 }
414
Orion Hodson59d07202019-10-31 15:25:33 +0000415 inline void Encode22c(::dex::Opcode opcode, uint8_t a, uint8_t b, uint16_t c) {
Eric Holkf3b95892019-07-30 14:47:06 -0700416 // b|a|op|bbbb
417 CHECK(IsShortRegister(a));
418 CHECK(IsShortRegister(b));
Orion Hodsoncc8b8ca2019-11-04 16:58:26 +0000419 buffer_.push_back((b << 12) | (a << 8) | ToBits(opcode));
Eric Holkf3b95892019-07-30 14:47:06 -0700420 buffer_.push_back(c);
421 }
422
Orion Hodson59d07202019-10-31 15:25:33 +0000423 inline void Encode32x(::dex::Opcode opcode, uint16_t a, uint16_t b) {
Orion Hodsoncc8b8ca2019-11-04 16:58:26 +0000424 buffer_.push_back(ToBits(opcode));
Eric Holkd1b43832019-01-29 08:32:42 -0800425 buffer_.push_back(a);
426 buffer_.push_back(b);
427 }
428
Orion Hodson59d07202019-10-31 15:25:33 +0000429 inline void Encode35c(::dex::Opcode opcode, size_t a, uint16_t b, uint8_t c, uint8_t d,
Eric Holk1c0f3f02018-11-09 13:48:59 -0800430 uint8_t e, uint8_t f, uint8_t g) {
431 // a|g|op|bbbb|f|e|d|c
432
433 CHECK_LE(a, 5);
Eric Holkd1b43832019-01-29 08:32:42 -0800434 CHECK(IsShortRegister(c));
435 CHECK(IsShortRegister(d));
436 CHECK(IsShortRegister(e));
437 CHECK(IsShortRegister(f));
438 CHECK(IsShortRegister(g));
Orion Hodsoncc8b8ca2019-11-04 16:58:26 +0000439 buffer_.push_back((a << 12) | (g << 8) | ToBits(opcode));
Eric Holk1c0f3f02018-11-09 13:48:59 -0800440 buffer_.push_back(b);
441 buffer_.push_back((f << 12) | (e << 8) | (d << 4) | c);
442 }
443
Orion Hodson59d07202019-10-31 15:25:33 +0000444 inline void Encode3rc(::dex::Opcode opcode, size_t a, uint16_t b, uint16_t c) {
Eric Holkd1b43832019-01-29 08:32:42 -0800445 CHECK_LE(a, 255);
Orion Hodsoncc8b8ca2019-11-04 16:58:26 +0000446 buffer_.push_back((a << 8) | ToBits(opcode));
Eric Holkd1b43832019-01-29 08:32:42 -0800447 buffer_.push_back(b);
448 buffer_.push_back(c);
449 }
450
451 static constexpr bool IsShortRegister(size_t register_value) { return register_value < 16; }
452
453 // Returns an array of num_regs scratch registers. These are guaranteed to be
454 // contiguous, so they are suitable for the invoke-*/range instructions.
455 template <int num_regs>
456 std::array<Value, num_regs> GetScratchRegisters() const {
457 static_assert(num_regs <= kMaxScratchRegisters);
458 std::array<Value, num_regs> regs;
459 for (size_t i = 0; i < num_regs; ++i) {
Eric Holk5c6a1a52019-09-17 13:28:34 -0700460 regs[i] = std::move(Value::Local(NumRegisters() + i));
Eric Holkd1b43832019-01-29 08:32:42 -0800461 }
462 return regs;
463 }
464
Eric Holkfaefd4f2018-10-11 16:25:57 -0700465 // Converts a register or parameter to its DEX register number.
Eric Holkd62c5aa2018-11-01 15:50:24 -0700466 size_t RegisterValue(const Value& value) const;
467
468 // Sets a label's address to the current position in the instruction buffer. If there are any
469 // forward references to the label, this function will back-patch them.
470 void BindLabel(const Value& label);
471
472 // Returns the offset of the label relative to the given instruction offset. If the label is not
473 // bound, a reference will be saved and it will automatically be patched when the label is bound.
474 ::dex::u2 LabelValue(const Value& label, size_t instruction_offset, size_t field_offset);
Eric Holkfaefd4f2018-10-11 16:25:57 -0700475
Eric Holkdbc36e22018-09-20 12:03:10 -0700476 DexBuilder* dex_;
477 ir::Class* class_;
478 ir::MethodDecl* decl_;
479
Eric Holkfaefd4f2018-10-11 16:25:57 -0700480 // A list of the instructions we will eventually encode.
481 std::vector<Instruction> instructions_;
482
483 // A buffer to hold instructions that have been encoded.
Eric Holkdbc36e22018-09-20 12:03:10 -0700484 std::vector<::dex::u2> buffer_;
485
Eric Holkd1b43832019-01-29 08:32:42 -0800486 // We create some scratch registers for when we have to shuffle registers
487 // around to make legal DEX code.
488 static constexpr size_t kMaxScratchRegisters = 5;
489
Eric Holk5c6a1a52019-09-17 13:28:34 -0700490 size_t NumRegisters() const {
491 return register_liveness_.size();
492 }
Eric Holkd62c5aa2018-11-01 15:50:24 -0700493
494 // Stores information needed to back-patch a label once it is bound. We need to know the start of
495 // the instruction that refers to the label, and the offset to where the actual label value should
496 // go.
497 struct LabelReference {
498 size_t instruction_offset;
499 size_t field_offset;
500 };
501
502 struct LabelData {
503 std::optional<size_t> bound_address;
504 std::forward_list<LabelReference> references;
505 };
506
507 std::vector<LabelData> labels_;
Eric Holkb3927582018-11-08 16:40:16 -0800508
509 // During encoding, keep track of the largest number of arguments needed, so we can use it for our
510 // outs count
511 size_t max_args_{0};
Eric Holk5c6a1a52019-09-17 13:28:34 -0700512
513 std::vector<bool> register_liveness_;
Eric Holkdbc36e22018-09-20 12:03:10 -0700514};
515
516// A helper to build class definitions.
517class ClassBuilder {
518 public:
Eric Holkfaefd4f2018-10-11 16:25:57 -0700519 ClassBuilder(DexBuilder* parent, const std::string& name, ir::Class* class_def);
Eric Holkdbc36e22018-09-20 12:03:10 -0700520
521 void set_source_file(const std::string& source);
522
523 // Create a method with the given name and prototype. The returned MethodBuilder can be used to
524 // fill in the method body.
525 MethodBuilder CreateMethod(const std::string& name, Prototype prototype);
526
527 private:
Eric Holkfaefd4f2018-10-11 16:25:57 -0700528 DexBuilder* const parent_;
529 const TypeDescriptor type_descriptor_;
530 ir::Class* const class_;
531};
532
Eric Holkdbc36e22018-09-20 12:03:10 -0700533// Builds Dex files from scratch.
534class DexBuilder {
535 public:
536 DexBuilder();
537
538 // Create an in-memory image of the DEX file that can either be loaded directly or written to a
539 // file.
540 slicer::MemView CreateImage();
541
542 template <typename T>
543 T* Alloc() {
544 return dex_file_->Alloc<T>();
545 }
546
547 // Find the ir::String that matches the given string, creating it if it does not exist.
548 ir::String* GetOrAddString(const std::string& string);
549 // Create a new class of the given name.
550 ClassBuilder MakeClass(const std::string& name);
551
552 // Add a type for the given descriptor, or return the existing one if it already exists.
Eric Holkfaefd4f2018-10-11 16:25:57 -0700553 // See the TypeDescriptor class for help generating these. GetOrAddType can be used to declare
554 // imported classes.
Eric Holkdbc36e22018-09-20 12:03:10 -0700555 ir::Type* GetOrAddType(const std::string& descriptor);
Eric Holk3092f992019-07-25 15:14:01 -0700556 inline ir::Type* GetOrAddType(TypeDescriptor descriptor) {
557 return GetOrAddType(descriptor.descriptor());
558 }
559
560 ir::FieldDecl* GetOrAddField(TypeDescriptor parent, const std::string& name, TypeDescriptor type);
Eric Holkdbc36e22018-09-20 12:03:10 -0700561
Eric Holkfaefd4f2018-10-11 16:25:57 -0700562 // Returns the method id for the method, creating it if it has not been created yet.
563 const MethodDeclData& GetOrDeclareMethod(TypeDescriptor type, const std::string& name,
564 Prototype prototype);
565
Eric Holkd1b43832019-01-29 08:32:42 -0800566 std::optional<const Prototype> GetPrototypeByMethodId(size_t method_id) const;
567
Eric Holkdbc36e22018-09-20 12:03:10 -0700568 private:
Eric Holkfaefd4f2018-10-11 16:25:57 -0700569 // Looks up the ir::Proto* corresponding to this given prototype, or creates one if it does not
570 // exist.
571 ir::Proto* GetOrEncodeProto(Prototype prototype);
572
Eric Holkdbc36e22018-09-20 12:03:10 -0700573 std::shared_ptr<ir::DexFile> dex_file_;
574
575 // allocator_ is needed to be able to encode the image.
576 TrackingAllocator allocator_;
577
578 // We'll need to allocate buffers for all of the encoded strings we create. This is where we store
579 // all of them.
580 std::vector<std::unique_ptr<uint8_t[]>> string_data_;
581
582 // Keep track of what types we've defined so we can look them up later.
Eric Holkfaefd4f2018-10-11 16:25:57 -0700583 std::unordered_map<std::string, ir::Type*> types_by_descriptor_;
584
585 struct MethodDescriptor {
586 TypeDescriptor type;
587 std::string name;
588 Prototype prototype;
589
590 inline bool operator<(const MethodDescriptor& rhs) const {
591 return std::make_tuple(type, name, prototype) <
592 std::make_tuple(rhs.type, rhs.name, rhs.prototype);
593 }
594 };
595
596 // Maps method declarations to their method index. This is needed to encode references to them.
597 // When we go to actually write the DEX file, slicer will re-assign these after correctly sorting
598 // the methods list.
599 std::map<MethodDescriptor, MethodDeclData> method_id_map_;
Eric Holkdbc36e22018-09-20 12:03:10 -0700600
601 // Keep track of what strings we've defined so we can look them up later.
Eric Holkfaefd4f2018-10-11 16:25:57 -0700602 std::unordered_map<std::string, ir::String*> strings_;
603
604 // Keep track of already-encoded protos.
605 std::map<Prototype, ir::Proto*> proto_map_;
Eric Holk3092f992019-07-25 15:14:01 -0700606
607 // Keep track of fields that have been declared
608 std::map<std::tuple<TypeDescriptor, std::string>, ir::FieldDecl*> field_decls_by_key_;
Eric Holkdbc36e22018-09-20 12:03:10 -0700609};
610
Eric Holkb3927582018-11-08 16:40:16 -0800611template <typename... T>
Eric Holk5c6a1a52019-09-17 13:28:34 -0700612void MethodBuilder::BuildNew(Value target, TypeDescriptor type, Prototype constructor,
613 const T&... args) {
Eric Holkb3927582018-11-08 16:40:16 -0800614 MethodDeclData constructor_data{dex_->GetOrDeclareMethod(type, "<init>", constructor)};
615 // allocate the object
616 ir::Type* type_def = dex_->GetOrAddType(type.descriptor());
617 AddInstruction(
618 Instruction::OpWithArgs(Instruction::Op::kNew, target, Value::Type(type_def->orig_index)));
619 // call the constructor
620 AddInstruction(Instruction::InvokeDirect(constructor_data.id, /*dest=*/{}, target, args...));
621};
622
Eric Holkdbc36e22018-09-20 12:03:10 -0700623} // namespace dex
624} // namespace startop
625
626#endif // DEX_BUILDER_H_