1 /*
2  * Copyright (C) 2008 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 "dalvik_system_ZygoteHooks.h"
18 
19 #include <stdlib.h>
20 
21 #include <android-base/logging.h>
22 #include <android-base/stringprintf.h>
23 
24 #include "arch/instruction_set.h"
25 #include "art_method-inl.h"
26 #include "base/macros.h"
27 #include "base/mutex.h"
28 #include "base/runtime_debug.h"
29 #include "debugger.h"
30 #include "hidden_api.h"
31 #include "jit/jit.h"
32 #include "jit/jit_code_cache.h"
33 #include "jni/java_vm_ext.h"
34 #include "jni/jni_internal.h"
35 #include "native_util.h"
36 #include "nativehelper/jni_macros.h"
37 #include "nativehelper/scoped_utf_chars.h"
38 #include "non_debuggable_classes.h"
39 #include "oat_file.h"
40 #include "oat_file_manager.h"
41 #include "scoped_thread_state_change-inl.h"
42 #include "stack.h"
43 #include "thread-current-inl.h"
44 #include "thread_list.h"
45 #include "trace.h"
46 
47 #include <sys/resource.h>
48 
49 namespace art {
50 
51 // Set to true to always determine the non-debuggable classes even if we would not allow a debugger
52 // to actually attach.
53 static bool kAlwaysCollectNonDebuggableClasses =
54     RegisterRuntimeDebugFlag(&kAlwaysCollectNonDebuggableClasses);
55 
56 using android::base::StringPrintf;
57 
58 class ClassSet {
59  public:
60   // The number of classes we reasonably expect to have to look at. Realistically the number is more
61   // ~10 but there is little harm in having some extra.
62   static constexpr int kClassSetCapacity = 100;
63 
ClassSet(Thread * const self)64   explicit ClassSet(Thread* const self) : self_(self) {
65     self_->GetJniEnv()->PushFrame(kClassSetCapacity);
66   }
67 
~ClassSet()68   ~ClassSet() {
69     self_->GetJniEnv()->PopFrame();
70   }
71 
AddClass(ObjPtr<mirror::Class> klass)72   void AddClass(ObjPtr<mirror::Class> klass) REQUIRES(Locks::mutator_lock_) {
73     class_set_.insert(self_->GetJniEnv()->AddLocalReference<jclass>(klass));
74   }
75 
GetClasses() const76   const std::unordered_set<jclass>& GetClasses() const {
77     return class_set_;
78   }
79 
80  private:
81   Thread* const self_;
82   std::unordered_set<jclass> class_set_;
83 };
84 
DoCollectNonDebuggableCallback(Thread * thread,void * data)85 static void DoCollectNonDebuggableCallback(Thread* thread, void* data)
86     REQUIRES(Locks::mutator_lock_) {
87   class NonDebuggableStacksVisitor : public StackVisitor {
88    public:
89     NonDebuggableStacksVisitor(Thread* t, ClassSet* class_set)
90         : StackVisitor(t, nullptr, StackVisitor::StackWalkKind::kIncludeInlinedFrames),
91           class_set_(class_set) {}
92 
93     ~NonDebuggableStacksVisitor() override {}
94 
95     bool VisitFrame() override REQUIRES(Locks::mutator_lock_) {
96       if (GetMethod()->IsRuntimeMethod()) {
97         return true;
98       }
99       class_set_->AddClass(GetMethod()->GetDeclaringClass());
100       if (kIsDebugBuild) {
101         LOG(INFO) << GetMethod()->GetDeclaringClass()->PrettyClass()
102                   << " might not be fully debuggable/deoptimizable due to "
103                   << GetMethod()->PrettyMethod() << " appearing on the stack during zygote fork.";
104       }
105       return true;
106     }
107 
108    private:
109     ClassSet* class_set_;
110   };
111   NonDebuggableStacksVisitor visitor(thread, reinterpret_cast<ClassSet*>(data));
112   visitor.WalkStack();
113 }
114 
CollectNonDebuggableClasses()115 static void CollectNonDebuggableClasses() REQUIRES(!Locks::mutator_lock_) {
116   Runtime* const runtime = Runtime::Current();
117   Thread* const self = Thread::Current();
118   // Get the mutator lock.
119   ScopedObjectAccess soa(self);
120   ClassSet classes(self);
121   {
122     // Drop the shared mutator lock.
123     ScopedThreadSuspension sts(self, art::ThreadState::kNative);
124     // Get exclusive mutator lock with suspend all.
125     ScopedSuspendAll suspend("Checking stacks for non-obsoletable methods!",
126                              /*long_suspend=*/false);
127     MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
128     runtime->GetThreadList()->ForEach(DoCollectNonDebuggableCallback, &classes);
129   }
130   for (jclass klass : classes.GetClasses()) {
131     NonDebuggableClasses::AddNonDebuggableClass(klass);
132   }
133 }
134 
135 // Must match values in com.android.internal.os.Zygote.
136 enum {
137   DEBUG_ENABLE_JDWP                   = 1,
138   DEBUG_ENABLE_CHECKJNI               = 1 << 1,
139   DEBUG_ENABLE_ASSERT                 = 1 << 2,
140   DEBUG_ENABLE_SAFEMODE               = 1 << 3,
141   DEBUG_ENABLE_JNI_LOGGING            = 1 << 4,
142   DEBUG_GENERATE_DEBUG_INFO           = 1 << 5,
143   DEBUG_ALWAYS_JIT                    = 1 << 6,
144   DEBUG_NATIVE_DEBUGGABLE             = 1 << 7,
145   DEBUG_JAVA_DEBUGGABLE               = 1 << 8,
146   DISABLE_VERIFIER                    = 1 << 9,
147   ONLY_USE_SYSTEM_OAT_FILES           = 1 << 10,
148   DEBUG_GENERATE_MINI_DEBUG_INFO      = 1 << 11,
149   HIDDEN_API_ENFORCEMENT_POLICY_MASK  = (1 << 12)
150                                       | (1 << 13),
151   PROFILE_SYSTEM_SERVER               = 1 << 14,
152   PROFILE_FROM_SHELL                  = 1 << 15,
153   USE_APP_IMAGE_STARTUP_CACHE         = 1 << 16,
154   DEBUG_IGNORE_APP_SIGNAL_HANDLER     = 1 << 17,
155   DISABLE_TEST_API_ENFORCEMENT_POLICY = 1 << 18,
156 
157   // bits to shift (flags & HIDDEN_API_ENFORCEMENT_POLICY_MASK) by to get a value
158   // corresponding to hiddenapi::EnforcementPolicy
159   API_ENFORCEMENT_POLICY_SHIFT = CTZ(HIDDEN_API_ENFORCEMENT_POLICY_MASK),
160 };
161 
EnableDebugFeatures(uint32_t runtime_flags)162 static uint32_t EnableDebugFeatures(uint32_t runtime_flags) {
163   Runtime* const runtime = Runtime::Current();
164   if ((runtime_flags & DEBUG_ENABLE_CHECKJNI) != 0) {
165     JavaVMExt* vm = runtime->GetJavaVM();
166     if (!vm->IsCheckJniEnabled()) {
167       LOG(INFO) << "Late-enabling -Xcheck:jni";
168       vm->SetCheckJniEnabled(true);
169       // There's only one thread running at this point, so only one JNIEnv to fix up.
170       Thread::Current()->GetJniEnv()->SetCheckJniEnabled(true);
171     } else {
172       LOG(INFO) << "Not late-enabling -Xcheck:jni (already on)";
173     }
174     runtime_flags &= ~DEBUG_ENABLE_CHECKJNI;
175   }
176 
177   if ((runtime_flags & DEBUG_ENABLE_JNI_LOGGING) != 0) {
178     gLogVerbosity.third_party_jni = true;
179     runtime_flags &= ~DEBUG_ENABLE_JNI_LOGGING;
180   }
181 
182   Dbg::SetJdwpAllowed((runtime_flags & DEBUG_ENABLE_JDWP) != 0);
183   runtime_flags &= ~DEBUG_ENABLE_JDWP;
184 
185   const bool safe_mode = (runtime_flags & DEBUG_ENABLE_SAFEMODE) != 0;
186   if (safe_mode) {
187     // Only quicken oat files.
188     runtime->AddCompilerOption("--compiler-filter=quicken");
189     runtime->SetSafeMode(true);
190     runtime_flags &= ~DEBUG_ENABLE_SAFEMODE;
191   }
192 
193   // This is for backwards compatibility with Dalvik.
194   runtime_flags &= ~DEBUG_ENABLE_ASSERT;
195 
196   if ((runtime_flags & DEBUG_ALWAYS_JIT) != 0) {
197     jit::JitOptions* jit_options = runtime->GetJITOptions();
198     CHECK(jit_options != nullptr);
199     Runtime::Current()->DoAndMaybeSwitchInterpreter([=]() {
200         jit_options->SetJitAtFirstUse();
201     });
202     runtime_flags &= ~DEBUG_ALWAYS_JIT;
203   }
204 
205   bool needs_non_debuggable_classes = false;
206   if ((runtime_flags & DEBUG_JAVA_DEBUGGABLE) != 0) {
207     runtime->AddCompilerOption("--debuggable");
208     runtime_flags |= DEBUG_GENERATE_MINI_DEBUG_INFO;
209     runtime->SetJavaDebuggable(true);
210     {
211       // Deoptimize the boot image as it may be non-debuggable.
212       ScopedSuspendAll ssa(__FUNCTION__);
213       runtime->DeoptimizeBootImage();
214     }
215     runtime_flags &= ~DEBUG_JAVA_DEBUGGABLE;
216     needs_non_debuggable_classes = true;
217   }
218   if (needs_non_debuggable_classes || kAlwaysCollectNonDebuggableClasses) {
219     CollectNonDebuggableClasses();
220   }
221 
222   if ((runtime_flags & DEBUG_NATIVE_DEBUGGABLE) != 0) {
223     runtime->AddCompilerOption("--debuggable");
224     runtime_flags |= DEBUG_GENERATE_DEBUG_INFO;
225     runtime->SetNativeDebuggable(true);
226     runtime_flags &= ~DEBUG_NATIVE_DEBUGGABLE;
227   }
228 
229   if ((runtime_flags & DEBUG_GENERATE_MINI_DEBUG_INFO) != 0) {
230     // Generate native minimal debug information to allow backtracing.
231     runtime->AddCompilerOption("--generate-mini-debug-info");
232     runtime_flags &= ~DEBUG_GENERATE_MINI_DEBUG_INFO;
233   }
234 
235   if ((runtime_flags & DEBUG_GENERATE_DEBUG_INFO) != 0) {
236     // Generate all native debug information we can (e.g. line-numbers).
237     runtime->AddCompilerOption("--generate-debug-info");
238     runtime_flags &= ~DEBUG_GENERATE_DEBUG_INFO;
239   }
240 
241   if ((runtime_flags & DEBUG_IGNORE_APP_SIGNAL_HANDLER) != 0) {
242     runtime->SetSignalHookDebuggable(true);
243     runtime_flags &= ~DEBUG_IGNORE_APP_SIGNAL_HANDLER;
244   }
245 
246   runtime->SetProfileableFromShell((runtime_flags & PROFILE_FROM_SHELL) != 0);
247   runtime_flags &= ~PROFILE_FROM_SHELL;
248 
249   return runtime_flags;
250 }
251 
ZygoteHooks_nativePreFork(JNIEnv * env,jclass)252 static jlong ZygoteHooks_nativePreFork(JNIEnv* env, jclass) {
253   Runtime* runtime = Runtime::Current();
254   CHECK(runtime->IsZygote()) << "runtime instance not started with -Xzygote";
255 
256   runtime->PreZygoteFork();
257 
258   // Grab thread before fork potentially makes Thread::pthread_key_self_ unusable.
259   return reinterpret_cast<jlong>(ThreadForEnv(env));
260 }
261 
ZygoteHooks_nativePostZygoteFork(JNIEnv *,jclass)262 static void ZygoteHooks_nativePostZygoteFork(JNIEnv*, jclass) {
263   Runtime::Current()->PostZygoteFork();
264 }
265 
ZygoteHooks_nativePostForkSystemServer(JNIEnv * env ATTRIBUTE_UNUSED,jclass klass ATTRIBUTE_UNUSED,jint runtime_flags)266 static void ZygoteHooks_nativePostForkSystemServer(JNIEnv* env ATTRIBUTE_UNUSED,
267                                                    jclass klass ATTRIBUTE_UNUSED,
268                                                    jint runtime_flags) {
269   // Set the runtime state as the first thing, in case JIT and other services
270   // start querying it.
271   Runtime::Current()->SetAsSystemServer();
272 
273   // This JIT code cache for system server is created whilst the runtime is still single threaded.
274   // System server has a window where it can create executable pages for this purpose, but this is
275   // turned off after this hook. Consequently, the only JIT mode supported is the dual-view JIT
276   // where one mapping is R->RW and the other is RX. Single view requires RX->RWX->RX.
277   if (Runtime::Current()->GetJit() != nullptr) {
278     Runtime::Current()->GetJit()->GetCodeCache()->PostForkChildAction(
279         /* is_system_server= */ true, /* is_zygote= */ false);
280   }
281   // Enable profiling if required based on the flags. This is done here instead of in
282   // nativePostForkChild since nativePostForkChild is called after loading the system server oat
283   // files.
284   bool profile_system_server = (runtime_flags & PROFILE_SYSTEM_SERVER) == PROFILE_SYSTEM_SERVER;
285   Runtime::Current()->GetJITOptions()->SetSaveProfilingInfo(profile_system_server);
286 }
287 
ZygoteHooks_nativePostForkChild(JNIEnv * env,jclass,jlong token,jint runtime_flags,jboolean is_system_server,jboolean is_zygote,jstring instruction_set)288 static void ZygoteHooks_nativePostForkChild(JNIEnv* env,
289                                             jclass,
290                                             jlong token,
291                                             jint runtime_flags,
292                                             jboolean is_system_server,
293                                             jboolean is_zygote,
294                                             jstring instruction_set) {
295   DCHECK(!(is_system_server && is_zygote));
296   // Set the runtime state as the first thing, in case JIT and other services
297   // start querying it.
298   Runtime::Current()->SetAsZygoteChild(is_system_server, is_zygote);
299 
300   Thread* thread = reinterpret_cast<Thread*>(token);
301   // Our system thread ID, etc, has changed so reset Thread state.
302   thread->InitAfterFork();
303   runtime_flags = EnableDebugFeatures(runtime_flags);
304   hiddenapi::EnforcementPolicy api_enforcement_policy = hiddenapi::EnforcementPolicy::kDisabled;
305 
306   Runtime* runtime = Runtime::Current();
307 
308   if ((runtime_flags & DISABLE_VERIFIER) != 0) {
309     runtime->DisableVerifier();
310     runtime_flags &= ~DISABLE_VERIFIER;
311   }
312 
313   if ((runtime_flags & ONLY_USE_SYSTEM_OAT_FILES) != 0 || is_system_server) {
314     runtime->GetOatFileManager().SetOnlyUseSystemOatFiles();
315     runtime_flags &= ~ONLY_USE_SYSTEM_OAT_FILES;
316   }
317 
318   api_enforcement_policy = hiddenapi::EnforcementPolicyFromInt(
319       (runtime_flags & HIDDEN_API_ENFORCEMENT_POLICY_MASK) >> API_ENFORCEMENT_POLICY_SHIFT);
320   runtime_flags &= ~HIDDEN_API_ENFORCEMENT_POLICY_MASK;
321 
322   if ((runtime_flags & DISABLE_TEST_API_ENFORCEMENT_POLICY) != 0u) {
323     runtime->SetTestApiEnforcementPolicy(hiddenapi::EnforcementPolicy::kDisabled);
324   } else {
325     runtime->SetTestApiEnforcementPolicy(hiddenapi::EnforcementPolicy::kEnabled);
326   }
327   runtime_flags &= ~DISABLE_TEST_API_ENFORCEMENT_POLICY;
328 
329   bool profile_system_server = (runtime_flags & PROFILE_SYSTEM_SERVER) == PROFILE_SYSTEM_SERVER;
330   runtime_flags &= ~PROFILE_SYSTEM_SERVER;
331 
332   runtime->SetLoadAppImageStartupCacheEnabled(
333       (runtime_flags & USE_APP_IMAGE_STARTUP_CACHE) != 0u);
334   runtime_flags &= ~USE_APP_IMAGE_STARTUP_CACHE;
335 
336   if (runtime_flags != 0) {
337     LOG(ERROR) << StringPrintf("Unknown bits set in runtime_flags: %#x", runtime_flags);
338   }
339 
340   runtime->GetHeap()->PostForkChildAction(thread);
341   if (runtime->GetJit() != nullptr) {
342     if (!is_system_server) {
343       // System server already called the JIT cache post fork action in `nativePostForkSystemServer`.
344       runtime->GetJit()->GetCodeCache()->PostForkChildAction(
345           /* is_system_server= */ false, is_zygote);
346     }
347     // This must be called after EnableDebugFeatures.
348     runtime->GetJit()->PostForkChildAction(is_system_server, is_zygote);
349   }
350 
351   // Update tracing.
352   if (Trace::GetMethodTracingMode() != TracingMode::kTracingInactive) {
353     Trace::TraceOutputMode output_mode = Trace::GetOutputMode();
354     Trace::TraceMode trace_mode = Trace::GetMode();
355     size_t buffer_size = Trace::GetBufferSize();
356 
357     // Just drop it.
358     Trace::Abort();
359 
360     // Only restart if it was streaming mode.
361     // TODO: Expose buffer size, so we can also do file mode.
362     if (output_mode == Trace::TraceOutputMode::kStreaming) {
363       static constexpr size_t kMaxProcessNameLength = 100;
364       char name_buf[kMaxProcessNameLength] = {};
365       int rc = pthread_getname_np(pthread_self(), name_buf, kMaxProcessNameLength);
366       std::string proc_name;
367 
368       if (rc == 0) {
369           // On success use the pthread name.
370           proc_name = name_buf;
371       }
372 
373       if (proc_name.empty() || proc_name == "zygote" || proc_name == "zygote64") {
374         // Either no process name, or the name hasn't been changed, yet. Just use pid.
375         pid_t pid = getpid();
376         proc_name = StringPrintf("%u", static_cast<uint32_t>(pid));
377       }
378 
379       std::string trace_file = StringPrintf("/data/misc/trace/%s.trace.bin", proc_name.c_str());
380       Trace::Start(trace_file.c_str(),
381                    buffer_size,
382                    0,   // TODO: Expose flags.
383                    output_mode,
384                    trace_mode,
385                    0);  // TODO: Expose interval.
386       if (thread->IsExceptionPending()) {
387         ScopedObjectAccess soa(env);
388         thread->ClearException();
389       }
390     }
391   }
392 
393   bool do_hidden_api_checks = api_enforcement_policy != hiddenapi::EnforcementPolicy::kDisabled;
394   DCHECK(!(is_system_server && do_hidden_api_checks))
395       << "SystemServer should be forked with EnforcementPolicy::kDisable";
396   DCHECK(!(is_zygote && do_hidden_api_checks))
397       << "Child zygote processes should be forked with EnforcementPolicy::kDisable";
398   runtime->SetHiddenApiEnforcementPolicy(api_enforcement_policy);
399   runtime->SetDedupeHiddenApiWarnings(true);
400   if (api_enforcement_policy != hiddenapi::EnforcementPolicy::kDisabled &&
401       runtime->GetHiddenApiEventLogSampleRate() != 0) {
402     // Hidden API checks are enabled, and we are sampling access for the event log. Initialize the
403     // random seed, to ensure the sampling is actually random. We do this post-fork, as doing it
404     // pre-fork would result in the same sequence for every forked process.
405     std::srand(static_cast<uint32_t>(NanoTime()));
406   }
407 
408   if (instruction_set != nullptr && !is_system_server) {
409     ScopedUtfChars isa_string(env, instruction_set);
410     InstructionSet isa = GetInstructionSetFromString(isa_string.c_str());
411     Runtime::NativeBridgeAction action = Runtime::NativeBridgeAction::kUnload;
412     if (isa != InstructionSet::kNone && isa != kRuntimeISA) {
413       action = Runtime::NativeBridgeAction::kInitialize;
414     }
415     runtime->InitNonZygoteOrPostFork(env, is_system_server, is_zygote, action, isa_string.c_str());
416   } else {
417     runtime->InitNonZygoteOrPostFork(
418         env,
419         is_system_server,
420         is_zygote,
421         Runtime::NativeBridgeAction::kUnload,
422         /*isa=*/ nullptr,
423         profile_system_server);
424   }
425 }
426 
ZygoteHooks_startZygoteNoThreadCreation(JNIEnv * env ATTRIBUTE_UNUSED,jclass klass ATTRIBUTE_UNUSED)427 static void ZygoteHooks_startZygoteNoThreadCreation(JNIEnv* env ATTRIBUTE_UNUSED,
428                                                     jclass klass ATTRIBUTE_UNUSED) {
429   Runtime::Current()->SetZygoteNoThreadSection(true);
430 }
431 
ZygoteHooks_stopZygoteNoThreadCreation(JNIEnv * env ATTRIBUTE_UNUSED,jclass klass ATTRIBUTE_UNUSED)432 static void ZygoteHooks_stopZygoteNoThreadCreation(JNIEnv* env ATTRIBUTE_UNUSED,
433                                                    jclass klass ATTRIBUTE_UNUSED) {
434   Runtime::Current()->SetZygoteNoThreadSection(false);
435 }
436 
437 static JNINativeMethod gMethods[] = {
438   NATIVE_METHOD(ZygoteHooks, nativePreFork, "()J"),
439   NATIVE_METHOD(ZygoteHooks, nativePostZygoteFork, "()V"),
440   NATIVE_METHOD(ZygoteHooks, nativePostForkSystemServer, "(I)V"),
441   NATIVE_METHOD(ZygoteHooks, nativePostForkChild, "(JIZZLjava/lang/String;)V"),
442   NATIVE_METHOD(ZygoteHooks, startZygoteNoThreadCreation, "()V"),
443   NATIVE_METHOD(ZygoteHooks, stopZygoteNoThreadCreation, "()V"),
444 };
445 
register_dalvik_system_ZygoteHooks(JNIEnv * env)446 void register_dalvik_system_ZygoteHooks(JNIEnv* env) {
447   REGISTER_NATIVE_METHODS("dalvik/system/ZygoteHooks");
448 }
449 
450 }  // namespace art
451