blob: c639427e645e5c840774598d28fdcff2ef399b79 [file] [log] [blame]
Andreas Gampe72ede722019-03-04 14:15:18 -08001/*
2 * Copyright (C) 2019 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
17#include <cstring>
18#include <iostream>
19#include <memory>
20#include <sstream>
21
Andreas Gampe5e2a8842019-06-18 12:35:20 -070022#include <unistd.h>
23
Andreas Gampe72ede722019-03-04 14:15:18 -080024#include <jni.h>
25
26#include <jvmti.h>
27
28#include <android-base/file.h>
29#include <android-base/logging.h>
30#include <android-base/macros.h>
Andreas Gampe5e2a8842019-06-18 12:35:20 -070031#include <android-base/strings.h>
Andreas Gampe72ede722019-03-04 14:15:18 -080032#include <android-base/unique_fd.h>
33
34#include <fcntl.h>
35#include <sys/stat.h>
Andreas Gampe5e2a8842019-06-18 12:35:20 -070036#include <sys/wait.h>
37
38#include <nativehelper/scoped_utf_chars.h>
Andreas Gampe72ede722019-03-04 14:15:18 -080039
40// We need dladdr.
41#if !defined(__APPLE__) && !defined(_WIN32)
42#ifndef _GNU_SOURCE
43#define _GNU_SOURCE
44#define DEFINED_GNU_SOURCE
45#endif
46#include <dlfcn.h>
47#ifdef DEFINED_GNU_SOURCE
48#undef _GNU_SOURCE
49#undef DEFINED_GNU_SOURCE
50#endif
51#endif
52
53// Slicer's headers have code that triggers these warnings. b/65298177
54#pragma clang diagnostic push
55#pragma clang diagnostic ignored "-Wunused-parameter"
56#pragma clang diagnostic ignored "-Wsign-compare"
57
58#include <slicer/dex_ir.h>
59#include <slicer/code_ir.h>
60#include <slicer/dex_bytecode.h>
61#include <slicer/dex_ir_builder.h>
62#include <slicer/writer.h>
63#include <slicer/reader.h>
64
65#pragma clang diagnostic pop
66
67namespace {
68
69JavaVM* gJavaVM = nullptr;
Andreas Gampe5e2a8842019-06-18 12:35:20 -070070bool gForkCrash = false;
Andreas Gampe8695b402019-06-18 12:36:46 -070071bool gJavaCrash = false;
Andreas Gampe72ede722019-03-04 14:15:18 -080072
73// Converts a class name to a type descriptor
74// (ex. "java.lang.String" to "Ljava/lang/String;")
75std::string classNameToDescriptor(const char* className) {
76 std::stringstream ss;
77 ss << "L";
78 for (auto p = className; *p != '\0'; ++p) {
79 ss << (*p == '.' ? '/' : *p);
80 }
81 ss << ";";
82 return ss.str();
83}
84
85using namespace dex;
86using namespace lir;
87
88bool transform(std::shared_ptr<ir::DexFile> dexIr) {
89 bool modified = false;
90
91 std::unique_ptr<ir::Builder> builder;
92
93 for (auto& method : dexIr->encoded_methods) {
94 // Do not look into abstract/bridge/native/synthetic methods.
95 if ((method->access_flags & (kAccAbstract | kAccBridge | kAccNative | kAccSynthetic))
96 != 0) {
97 continue;
98 }
99
100 struct HookVisitor: public Visitor {
101 HookVisitor(std::unique_ptr<ir::Builder>* b, std::shared_ptr<ir::DexFile> d_ir,
102 CodeIr* c_ir) :
103 b(b), dIr(d_ir), cIr(c_ir) {
104 }
105
106 bool Visit(Bytecode* bytecode) override {
107 if (bytecode->opcode == OP_MONITOR_ENTER) {
108 prepare();
109 addCall(bytecode, OP_INVOKE_STATIC_RANGE, hookType, "preLock", voidType,
110 objectType, reinterpret_cast<VReg*>(bytecode->operands[0])->reg);
111 myModified = true;
112 return true;
113 }
114 if (bytecode->opcode == OP_MONITOR_EXIT) {
115 prepare();
116 addCall(bytecode, OP_INVOKE_STATIC_RANGE, hookType, "postLock", voidType,
117 objectType, reinterpret_cast<VReg*>(bytecode->operands[0])->reg);
118 myModified = true;
119 return true;
120 }
121 return false;
122 }
123
124 void prepare() {
125 if (*b == nullptr) {
126 *b = std::unique_ptr<ir::Builder>(new ir::Builder(dIr));
127 }
128 if (voidType == nullptr) {
129 voidType = (*b)->GetType("V");
130 hookType = (*b)->GetType("Lcom/android/lock_checker/LockHook;");
131 objectType = (*b)->GetType("Ljava/lang/Object;");
132 }
133 }
134
135 void addInst(lir::Instruction* instructionAfter, Opcode opcode,
136 const std::list<Operand*>& operands) {
137 auto instruction = cIr->Alloc<Bytecode>();
138
139 instruction->opcode = opcode;
140
141 for (auto it = operands.begin(); it != operands.end(); it++) {
142 instruction->operands.push_back(*it);
143 }
144
145 cIr->instructions.InsertBefore(instructionAfter, instruction);
146 }
147
148 void addCall(lir::Instruction* instructionAfter, Opcode opcode, ir::Type* type,
149 const char* methodName, ir::Type* returnType,
150 const std::vector<ir::Type*>& types, const std::list<int>& regs) {
151 auto proto = (*b)->GetProto(returnType, (*b)->GetTypeList(types));
152 auto method = (*b)->GetMethodDecl((*b)->GetAsciiString(methodName), proto, type);
153
154 VRegList* paramRegs = cIr->Alloc<VRegList>();
155 for (auto it = regs.begin(); it != regs.end(); it++) {
156 paramRegs->registers.push_back(*it);
157 }
158
159 addInst(instructionAfter, opcode,
160 { paramRegs, cIr->Alloc<Method>(method, method->orig_index) });
161 }
162
163 void addCall(lir::Instruction* instructionAfter, Opcode opcode, ir::Type* type,
164 const char* methodName, ir::Type* returnType, ir::Type* paramType,
165 u4 paramVReg) {
166 auto proto = (*b)->GetProto(returnType, (*b)->GetTypeList( { paramType }));
167 auto method = (*b)->GetMethodDecl((*b)->GetAsciiString(methodName), proto, type);
168
169 VRegRange* args = cIr->Alloc<VRegRange>(paramVReg, 1);
170
171 addInst(instructionAfter, opcode,
172 { args, cIr->Alloc<Method>(method, method->orig_index) });
173 }
174
175 std::unique_ptr<ir::Builder>* b;
176 std::shared_ptr<ir::DexFile> dIr;
177 CodeIr* cIr;
178 ir::Type* voidType = nullptr;
179 ir::Type* hookType = nullptr;
180 ir::Type* objectType = nullptr;
181 bool myModified = false;
182 };
183
184 CodeIr c(method.get(), dexIr);
185 HookVisitor visitor(&builder, dexIr, &c);
186
187 for (auto it = c.instructions.begin(); it != c.instructions.end(); ++it) {
188 lir::Instruction* fi = *it;
189 fi->Accept(&visitor);
190 }
191
192 if (visitor.myModified) {
193 modified = true;
194 c.Assemble();
195 }
196 }
197
198 return modified;
199}
200
201std::pair<dex::u1*, size_t> maybeTransform(const char* name, size_t classDataLen,
202 const unsigned char* classData, dex::Writer::Allocator* allocator) {
203 // Isolate byte code of class class. This is needed as Android usually gives us more
204 // than the class we need.
205 dex::Reader reader(classData, classDataLen);
206
207 dex::u4 index = reader.FindClassIndex(classNameToDescriptor(name).c_str());
208 CHECK_NE(index, kNoIndex);
209 reader.CreateClassIr(index);
210 std::shared_ptr<ir::DexFile> ir = reader.GetIr();
211
212 if (!transform(ir)) {
213 return std::make_pair(nullptr, 0);
214 }
215
216 size_t new_size;
217 dex::Writer writer(ir);
218 dex::u1* newClassData = writer.CreateImage(allocator, &new_size);
219 return std::make_pair(newClassData, new_size);
220}
221
222void transformHook(jvmtiEnv* jvmtiEnv, JNIEnv* env ATTRIBUTE_UNUSED,
223 jclass classBeingRedefined ATTRIBUTE_UNUSED, jobject loader, const char* name,
224 jobject protectionDomain ATTRIBUTE_UNUSED, jint classDataLen,
225 const unsigned char* classData, jint* newClassDataLen, unsigned char** newClassData) {
226 // Even reading the classData array is expensive as the data is only generated when the
227 // memory is touched. Hence call JvmtiAgent#shouldTransform to check if we need to transform
228 // the class.
229
230 // Skip bootclasspath classes. TODO: Make this configurable.
231 if (loader == nullptr) {
232 return;
233 }
234
235 // Do not look into java.* classes. Should technically be filtered by above, but when that's
236 // configurable have this.
237 if (strncmp("java", name, 4) == 0) {
238 return;
239 }
240
241 // Do not look into our Java classes.
242 if (strncmp("com/android/lock_checker", name, 24) == 0) {
243 return;
244 }
245
246 class JvmtiAllocator: public dex::Writer::Allocator {
247 public:
248 explicit JvmtiAllocator(::jvmtiEnv* jvmti) :
249 jvmti_(jvmti) {
250 }
251
252 void* Allocate(size_t size) override {
253 unsigned char* res = nullptr;
254 jvmti_->Allocate(size, &res);
255 return res;
256 }
257
258 void Free(void* ptr) override {
259 jvmti_->Deallocate(reinterpret_cast<unsigned char*>(ptr));
260 }
261
262 private:
263 ::jvmtiEnv* jvmti_;
264 };
265 JvmtiAllocator allocator(jvmtiEnv);
266 std::pair<dex::u1*, size_t> result = maybeTransform(name, classDataLen, classData,
267 &allocator);
268
269 if (result.second > 0) {
270 *newClassData = result.first;
271 *newClassDataLen = static_cast<jint>(result.second);
272 }
273}
274
275void dataDumpRequestHook(jvmtiEnv* jvmtiEnv ATTRIBUTE_UNUSED) {
276 if (gJavaVM == nullptr) {
277 LOG(ERROR) << "No JavaVM for dump";
278 return;
279 }
280 JNIEnv* env;
281 if (gJavaVM->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_6) != JNI_OK) {
282 LOG(ERROR) << "Could not get env for dump";
283 return;
284 }
285 jclass lockHookClass = env->FindClass("com/android/lock_checker/LockHook");
286 if (lockHookClass == nullptr) {
287 env->ExceptionClear();
288 LOG(ERROR) << "Could not find LockHook class";
289 return;
290 }
291 jmethodID dumpId = env->GetStaticMethodID(lockHookClass, "dump", "()V");
292 if (dumpId == nullptr) {
293 env->ExceptionClear();
294 LOG(ERROR) << "Could not find LockHook.dump";
295 return;
296 }
297 env->CallStaticVoidMethod(lockHookClass, dumpId);
298 env->ExceptionClear();
299}
300
301// A function for dladdr to search.
302extern "C" __attribute__ ((visibility ("default"))) void lock_agent_tag_fn() {
303}
304
305bool fileExists(const std::string& path) {
306 struct stat statBuf;
307 int rc = stat(path.c_str(), &statBuf);
308 return rc == 0;
309}
310
311std::string findLockAgentJar() {
312 // Check whether the jar is located next to the agent's so.
313#ifndef __APPLE__
314 {
315 Dl_info info;
316 if (dladdr(reinterpret_cast<const void*>(&lock_agent_tag_fn), /* out */ &info) != 0) {
317 std::string lockAgentSoPath = info.dli_fname;
318 std::string dir = android::base::Dirname(lockAgentSoPath);
319 std::string lockAgentJarPath = dir + "/" + "lockagent.jar";
320 if (fileExists(lockAgentJarPath)) {
321 return lockAgentJarPath;
322 }
323 } else {
324 LOG(ERROR) << "dladdr failed";
325 }
326 }
327#endif
328
329 std::string sysFrameworkPath = "/system/framework/lockagent.jar";
330 if (fileExists(sysFrameworkPath)) {
331 return sysFrameworkPath;
332 }
333
334 std::string relPath = "lockagent.jar";
335 if (fileExists(relPath)) {
336 return relPath;
337 }
338
339 return "";
340}
341
342void prepareHook(jvmtiEnv* env) {
343 // Inject the agent Java code.
344 {
345 std::string path = findLockAgentJar();
346 if (path.empty()) {
347 LOG(FATAL) << "Could not find lockagent.jar";
348 }
349 LOG(INFO) << "Will load Java parts from " << path;
350 jvmtiError res = env->AddToBootstrapClassLoaderSearch(path.c_str());
351 if (res != JVMTI_ERROR_NONE) {
352 LOG(FATAL) << "Could not add lockagent from " << path << " to boot classpath: " << res;
353 }
354 }
355
356 jvmtiCapabilities caps;
357 memset(&caps, 0, sizeof(caps));
358 caps.can_retransform_classes = 1;
359
360 if (env->AddCapabilities(&caps) != JVMTI_ERROR_NONE) {
361 LOG(FATAL) << "Could not add caps";
362 }
363
364 jvmtiEventCallbacks cb;
365 memset(&cb, 0, sizeof(cb));
366 cb.ClassFileLoadHook = transformHook;
367 cb.DataDumpRequest = dataDumpRequestHook;
368
369 if (env->SetEventCallbacks(&cb, sizeof(cb)) != JVMTI_ERROR_NONE) {
370 LOG(FATAL) << "Could not set cb";
371 }
372
373 if (env->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_CLASS_FILE_LOAD_HOOK, nullptr)
374 != JVMTI_ERROR_NONE) {
375 LOG(FATAL) << "Could not enable events";
376 }
377 if (env->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_DATA_DUMP_REQUEST, nullptr)
378 != JVMTI_ERROR_NONE) {
379 LOG(FATAL) << "Could not enable events";
380 }
381}
382
Andreas Gampe5e2a8842019-06-18 12:35:20 -0700383jint attach(JavaVM* vm, char* options, void* reserved ATTRIBUTE_UNUSED) {
Andreas Gampe72ede722019-03-04 14:15:18 -0800384 gJavaVM = vm;
385
386 jvmtiEnv* env;
387 jint jvmError = vm->GetEnv(reinterpret_cast<void**>(&env), JVMTI_VERSION_1_2);
388 if (jvmError != JNI_OK) {
389 return jvmError;
390 }
391
392 prepareHook(env);
393
Andreas Gampe5e2a8842019-06-18 12:35:20 -0700394 std::vector<std::string> config = android::base::Split(options, ",");
395 for (const std::string& c : config) {
396 if (c == "native_crash") {
397 gForkCrash = true;
Andreas Gampe8695b402019-06-18 12:36:46 -0700398 } else if (c == "java_crash") {
399 gJavaCrash = true;
Andreas Gampe5e2a8842019-06-18 12:35:20 -0700400 }
401 }
402
Andreas Gampe72ede722019-03-04 14:15:18 -0800403 return JVMTI_ERROR_NONE;
404}
405
Andreas Gampe5e2a8842019-06-18 12:35:20 -0700406extern "C" JNIEXPORT
407jboolean JNICALL Java_com_android_lock_1checker_LockHook_getNativeHandlingConfig(JNIEnv*, jclass) {
408 return gForkCrash ? JNI_TRUE : JNI_FALSE;
409}
410
Andreas Gampe8695b402019-06-18 12:36:46 -0700411extern "C" JNIEXPORT jboolean JNICALL
412Java_com_android_lock_1checker_LockHook_getSimulateCrashConfig(JNIEnv*, jclass) {
413 return gJavaCrash ? JNI_TRUE : JNI_FALSE;
414}
415
Andreas Gampe5e2a8842019-06-18 12:35:20 -0700416extern "C" JNIEXPORT void JNICALL Java_com_android_lock_1checker_LockHook_nWtf(JNIEnv* env, jclass,
417 jstring msg) {
418 if (!gForkCrash || msg == nullptr) {
419 return;
420 }
421
422 // Create a native crash with the given message. Decouple from the current crash to create a
423 // tombstone but continue on.
424 //
425 // TODO: Once there are not so many reports, consider making this fatal for the calling process.
426 ScopedUtfChars utf(env, msg);
427 if (utf.c_str() == nullptr) {
428 return;
429 }
430 const char* args[] = {
431 "/system/bin/lockagent_crasher",
432 utf.c_str(),
433 nullptr
434 };
435 pid_t pid = fork();
436 if (pid < 0) {
437 return;
438 }
439 if (pid == 0) {
440 // Double fork so we return quickly. Leave init to deal with the zombie.
441 pid_t pid2 = fork();
442 if (pid2 == 0) {
443 execv(args[0], const_cast<char* const*>(args));
444 _exit(1);
445 __builtin_unreachable();
446 }
447 _exit(0);
448 __builtin_unreachable();
449 }
450 int status;
451 waitpid(pid, &status, 0); // Ignore any results.
452}
453
Andreas Gampe72ede722019-03-04 14:15:18 -0800454extern "C" JNIEXPORT jint JNICALL Agent_OnAttach(JavaVM* vm, char* options, void* reserved) {
455 return attach(vm, options, reserved);
456}
457
458extern "C" JNIEXPORT jint JNICALL Agent_OnLoad(JavaVM* vm, char* options, void* reserved) {
459 return attach(vm, options, reserved);
460}
461
462int locktest_main(int argc, char *argv[]) {
463 if (argc != 3) {
464 LOG(FATAL) << "Need two arguments: dex-file class-name";
465 }
466 struct stat statBuf;
467 int rc = stat(argv[1], &statBuf);
468 if (rc != 0) {
469 PLOG(FATAL) << "Could not get file size for " << argv[1];
470 }
471 std::unique_ptr<char[]> data(new char[statBuf.st_size]);
472 {
473 android::base::unique_fd fd(open(argv[1], O_RDONLY));
474 if (fd.get() == -1) {
475 PLOG(FATAL) << "Could not open file " << argv[1];
476 }
477 if (!android::base::ReadFully(fd.get(), data.get(), statBuf.st_size)) {
478 PLOG(FATAL) << "Could not read file " << argv[1];
479 }
480 }
481
482 class NewDeleteAllocator: public dex::Writer::Allocator {
483 public:
484 explicit NewDeleteAllocator() {
485 }
486
487 void* Allocate(size_t size) override {
488 return new char[size];
489 }
490
491 void Free(void* ptr) override {
492 delete[] reinterpret_cast<char*>(ptr);
493 }
494 };
495 NewDeleteAllocator allocator;
496
497 std::pair<dex::u1*, size_t> result = maybeTransform(argv[2], statBuf.st_size,
498 reinterpret_cast<unsigned char*>(data.get()), &allocator);
499
500 if (result.second == 0) {
501 LOG(INFO) << "No transformation";
502 return 0;
503 }
504
505 std::string newName(argv[1]);
506 newName.append(".new");
507
508 {
509 android::base::unique_fd fd(
510 open(newName.c_str(), O_CREAT | O_TRUNC | O_WRONLY, S_IRUSR | S_IWUSR));
511 if (fd.get() == -1) {
512 PLOG(FATAL) << "Could not open file " << newName;
513 }
514 if (!android::base::WriteFully(fd.get(), result.first, result.second)) {
515 PLOG(FATAL) << "Could not write file " << newName;
516 }
517 }
518 LOG(INFO) << "Transformed file written to " << newName;
519
520 return 0;
521}
522
523} // namespace
524
525int main(int argc, char *argv[]) {
526 return locktest_main(argc, argv);
527}