runtime.cc 62.2 KB
Newer Older
Elliott Hughes's avatar
Elliott Hughes committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
/*
 * Copyright (C) 2011 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
16

17
#include "runtime.h"
18

19 20
// sys/mount.h has to come before linux/fs.h due to redefinition of MS_RDONLY, MS_BIND, etc
#include <sys/mount.h>
21
#ifdef __linux__
22
#include <linux/fs.h>
23
#endif
24

25 26
#define ATRACE_TAG ATRACE_TAG_DALVIK
#include <cutils/trace.h>
27
#include <signal.h>
28
#include <sys/syscall.h>
29
#include <valgrind.h>
30

31 32
#include <cstdio>
#include <cstdlib>
33
#include <limits>
34
#include <memory_representation.h>
35
#include <vector>
36
#include <fcntl.h>
37

38 39
#include "JniConstants.h"
#include "ScopedLocalRef.h"
40
#include "arch/arm/quick_method_frame_info_arm.h"
41
#include "arch/arm/registers_arm.h"
42
#include "arch/arm64/quick_method_frame_info_arm64.h"
43
#include "arch/arm64/registers_arm64.h"
44
#include "arch/instruction_set_features.h"
45
#include "arch/mips/quick_method_frame_info_mips.h"
46
#include "arch/mips/registers_mips.h"
47 48
#include "arch/mips64/quick_method_frame_info_mips64.h"
#include "arch/mips64/registers_mips64.h"
49
#include "arch/x86/quick_method_frame_info_x86.h"
50
#include "arch/x86/registers_x86.h"
51
#include "arch/x86_64/quick_method_frame_info_x86_64.h"
52
#include "arch/x86_64/registers_x86_64.h"
Mathieu Chartier's avatar
Mathieu Chartier committed
53
#include "art_field-inl.h"
54
#include "art_method-inl.h"
Ian Rogers's avatar
Ian Rogers committed
55
#include "asm_support.h"
56
#include "atomic.h"
Andreas Gampe's avatar
Andreas Gampe committed
57
#include "base/arena_allocator.h"
Ian Rogers's avatar
Ian Rogers committed
58
#include "base/dumpable.h"
Ian Rogers's avatar
Ian Rogers committed
59
#include "base/unix_file/fd_file.h"
Vladimir Marko's avatar
Vladimir Marko committed
60
#include "class_linker-inl.h"
Andreas Gampe's avatar
Andreas Gampe committed
61
#include "compiler_callbacks.h"
Elliott Hughes's avatar
Elliott Hughes committed
62
#include "debugger.h"
63
#include "elf_file.h"
64
#include "entrypoints/runtime_asm_entrypoints.h"
65
#include "fault_handler.h"
Ian Rogers's avatar
Ian Rogers committed
66 67
#include "gc/accounting/card_table-inl.h"
#include "gc/heap.h"
Ian Rogers's avatar
Ian Rogers committed
68
#include "gc/space/image_space.h"
Mathieu Chartier's avatar
Mathieu Chartier committed
69
#include "gc/space/space-inl.h"
70
#include "handle_scope-inl.h"
Brian Carlstrom's avatar
Brian Carlstrom committed
71
#include "image.h"
72
#include "instrumentation.h"
73
#include "intern_table.h"
Mathieu Chartier's avatar
Mathieu Chartier committed
74 75
#include "interpreter/interpreter.h"
#include "jit/jit.h"
76
#include "jni_internal.h"
Mathieu Chartier's avatar
Mathieu Chartier committed
77
#include "linear_alloc.h"
78
#include "mirror/array.h"
79
#include "mirror/class-inl.h"
80
#include "mirror/class_loader.h"
81
#include "mirror/field.h"
82
#include "mirror/method.h"
Mathieu Chartier's avatar
Mathieu Chartier committed
83
#include "mirror/stack_trace_element.h"
84
#include "mirror/throwable.h"
85
#include "monitor.h"
Andreas Gampe's avatar
Andreas Gampe committed
86 87 88 89 90 91 92 93 94 95
#include "native/dalvik_system_DexFile.h"
#include "native/dalvik_system_VMDebug.h"
#include "native/dalvik_system_VMRuntime.h"
#include "native/dalvik_system_VMStack.h"
#include "native/dalvik_system_ZygoteHooks.h"
#include "native/java_lang_Class.h"
#include "native/java_lang_DexCache.h"
#include "native/java_lang_Object.h"
#include "native/java_lang_Runtime.h"
#include "native/java_lang_String.h"
96
#include "native/java_lang_StringFactory.h"
Andreas Gampe's avatar
Andreas Gampe committed
97 98 99 100
#include "native/java_lang_System.h"
#include "native/java_lang_Thread.h"
#include "native/java_lang_Throwable.h"
#include "native/java_lang_VMClassLoader.h"
101 102 103 104 105 106 107
#include "native/java_lang_ref_FinalizerReference.h"
#include "native/java_lang_ref_Reference.h"
#include "native/java_lang_reflect_Array.h"
#include "native/java_lang_reflect_Constructor.h"
#include "native/java_lang_reflect_Field.h"
#include "native/java_lang_reflect_Method.h"
#include "native/java_lang_reflect_Proxy.h"
Andreas Gampe's avatar
Andreas Gampe committed
108
#include "native/java_util_concurrent_atomic_AtomicLong.h"
109
#include "native/libcore_util_CharsetUtils.h"
Andreas Gampe's avatar
Andreas Gampe committed
110 111 112
#include "native/org_apache_harmony_dalvik_ddmc_DdmServer.h"
#include "native/org_apache_harmony_dalvik_ddmc_DdmVmInternal.h"
#include "native/sun_misc_Unsafe.h"
113
#include "native_bridge_art_interface.h"
Brian Carlstrom's avatar
Brian Carlstrom committed
114
#include "oat_file.h"
115
#include "os.h"
116 117
#include "parsed_options.h"
#include "profiler.h"
118
#include "quick/quick_method_frame_info.h"
119
#include "reflection.h"
120 121
#include "runtime_options.h"
#include "ScopedLocalRef.h"
Ian Rogers's avatar
Ian Rogers committed
122
#include "scoped_thread_state_change.h"
123
#include "sigchain.h"
124
#include "signal_catcher.h"
125
#include "signal_set.h"
126
#include "thread.h"
Elliott Hughes's avatar
Elliott Hughes committed
127
#include "thread_list.h"
128
#include "trace.h"
Sebastien Hertz's avatar
Sebastien Hertz committed
129
#include "transaction.h"
130
#include "verifier/method_verifier.h"
131
#include "well_known_classes.h"
132

133
namespace art {
134

135
// If a signal isn't handled properly, enable a handler that attempts to dump the Java stack.
136
static constexpr bool kEnableJavaStackTraceHandler = false;
137
Runtime* Runtime::instance_ = nullptr;
138

139 140 141 142 143 144 145
struct TraceConfig {
  Trace::TraceMode trace_mode;
  Trace::TraceOutputMode trace_output_mode;
  std::string trace_file;
  size_t trace_file_size;
};

146
Runtime::Runtime()
147
    : instruction_set_(kNone),
148
      compiler_callbacks_(nullptr),
Elliott Hughes's avatar
Elliott Hughes committed
149
      is_zygote_(false),
150
      must_relocate_(false),
151
      is_concurrent_gc_enabled_(true),
152
      is_explicit_gc_disabled_(false),
153
      dex2oat_enabled_(true),
154
      image_dex2oat_enabled_(true),
155
      default_stack_size_(0),
156
      heap_(nullptr),
157
      max_spins_before_thin_lock_inflation_(Monitor::kDefaultMaxSpinsBeforeThinLockInflation),
158 159 160 161 162 163 164
      monitor_list_(nullptr),
      monitor_pool_(nullptr),
      thread_list_(nullptr),
      intern_table_(nullptr),
      class_linker_(nullptr),
      signal_catcher_(nullptr),
      java_vm_(nullptr),
165 166
      fault_message_lock_("Fault message lock"),
      fault_message_(""),
167
      threads_being_born_(0),
168
      shutdown_cond_(new ConditionVariable("Runtime shutdown", *Locks::runtime_shutdown_lock_)),
169
      shutting_down_(false),
170
      shutting_down_started_(false),
171
      started_(false),
172
      finished_starting_(false),
173 174 175
      vfprintf_(nullptr),
      exit_(nullptr),
      abort_(nullptr),
176
      stats_enabled_(false),
177
      running_on_valgrind_(RUNNING_ON_VALGRIND > 0),
178
      profiler_started_(false),
179
      instrumentation_(),
180 181 182
      main_thread_group_(nullptr),
      system_thread_group_(nullptr),
      system_class_loader_(nullptr),
Sebastien Hertz's avatar
Sebastien Hertz committed
183
      dump_gc_performance_on_shutdown_(false),
Sebastien Hertz's avatar
Sebastien Hertz committed
184
      preinitialization_transaction_(nullptr),
185
      verify_(false),
186
      allow_dex_file_fallback_(true),
187 188 189
      target_sdk_version_(0),
      implicit_null_checks_(false),
      implicit_so_checks_(false),
190
      implicit_suspend_checks_(false),
191 192
      is_native_bridge_loaded_(false),
      zygote_max_failed_boots_(0) {
Ian Rogers's avatar
Ian Rogers committed
193
  CheckAsmSupportOffsetsAndSizes();
194
  std::fill(callee_save_methods_, callee_save_methods_ + arraysize(callee_save_methods_), 0u);
195 196
}

197
Runtime::~Runtime() {
198 199 200
  if (is_native_bridge_loaded_) {
    UnloadNativeBridge();
  }
201 202 203 204 205 206 207
  if (dump_gc_performance_on_shutdown_) {
    // This can't be called from the Heap destructor below because it
    // could call RosAlloc::InspectAll() which needs the thread_list
    // to be still alive.
    heap_->DumpGcPerformanceInfo(LOG(INFO));
  }

208
  Thread* self = Thread::Current();
209 210
  const bool attach_shutdown_thread = self == nullptr;
  if (attach_shutdown_thread) {
211 212 213 214 215 216
    CHECK(AttachCurrentThread("Shutdown thread", false, nullptr, false));
    self = Thread::Current();
  } else {
    LOG(WARNING) << "Current thread not detached in Runtime shutdown";
  }

217 218 219 220
  {
    MutexLock mu(self, *Locks::runtime_shutdown_lock_);
    shutting_down_started_ = true;
    while (threads_being_born_ > 0) {
221
      shutdown_cond_->Wait(self);
222 223 224
    }
    shutting_down_ = true;
  }
225 226 227 228 229 230 231
  // Shutdown and wait for the daemons.
  CHECK(self != nullptr);
  if (IsFinishedStarting()) {
    self->ClearException();
    self->GetJniEnv()->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
                                            WellKnownClasses::java_lang_Daemons_stop);
  }
232 233 234 235
  if (attach_shutdown_thread) {
    DetachCurrentThread();
    self = nullptr;
  }
236

237
  // Shut down background profiler before the runtime exits.
238
  if (profiler_started_) {
239 240
    BackgroundMethodSamplingProfiler::Shutdown();
  }
241

242
  Trace::Shutdown();
243

Mathieu Chartier's avatar
Mathieu Chartier committed
244
  // Make sure to let the GC complete if it is running.
245
  heap_->WaitForGcToComplete(gc::kGcCauseBackground, self);
246
  heap_->DeleteThreadPool();
Mathieu Chartier's avatar
Mathieu Chartier committed
247 248 249 250 251 252
  if (jit_.get() != nullptr) {
    VLOG(jit) << "Deleting jit thread pool";
    // Delete thread pool before the thread list since we don't want to wait forever on the
    // JIT compiler threads.
    jit_->DeleteThreadPool();
  }
Mathieu Chartier's avatar
Mathieu Chartier committed
253

254
  // Make sure our internal threads are dead before we start tearing down things they're using.
255
  Dbg::StopJdwp();
256 257
  delete signal_catcher_;

258
  // Make sure all other non-daemon threads have terminated, and all daemon threads are suspended.
259
  delete thread_list_;
260

Mathieu Chartier's avatar
Mathieu Chartier committed
261 262 263 264 265 266
  // Delete the JIT after thread list to ensure that there is no remaining threads which could be
  // accessing the instrumentation when we delete it.
  if (jit_.get() != nullptr) {
    VLOG(jit) << "Deleting jit";
    jit_.reset(nullptr);
  }
Mathieu Chartier's avatar
Mathieu Chartier committed
267
  linear_alloc_.reset();
Mathieu Chartier's avatar
Mathieu Chartier committed
268
  arena_pool_.reset();
Mathieu Chartier's avatar
Mathieu Chartier committed
269
  low_4gb_arena_pool_.reset();
Mathieu Chartier's avatar
Mathieu Chartier committed
270

271 272 273
  // Shutdown the fault manager if it was initialized.
  fault_manager.Shutdown();

Elliott Hughes's avatar
Elliott Hughes committed
274
  delete monitor_list_;
275
  delete monitor_pool_;
276
  delete class_linker_;
277
  delete heap_;
278
  delete intern_table_;
279
  delete java_vm_;
280
  Thread::Shutdown();
281
  QuasiAtomic::Shutdown();
282
  verifier::MethodVerifier::Shutdown();
283
  MemMap::Shutdown();
284
  // TODO: acquire a static mutex on Runtime to avoid racing.
285 286
  CHECK(instance_ == nullptr || instance_ == this);
  instance_ = nullptr;
287 288
}

289
struct AbortState {
Ian Rogers's avatar
Ian Rogers committed
290
  void Dump(std::ostream& os) const {
Nicolas Geoffray's avatar
Nicolas Geoffray committed
291 292 293 294 295
    if (gAborting > 1) {
      os << "Runtime aborting --- recursively, so no thread-specific detail!\n";
      return;
    }
    gAborting++;
296
    os << "Runtime aborting...\n";
Mathieu Chartier's avatar
Mathieu Chartier committed
297
    if (Runtime::Current() == nullptr) {
298 299 300
      os << "(Runtime does not yet exist!)\n";
      return;
    }
301
    Thread* self = Thread::Current();
302
    if (self == nullptr) {
303
      os << "(Aborting thread was not attached to runtime!)\n";
304 305
      DumpKernelStack(os, GetTid(), "  kernel: ", false);
      DumpNativeStack(os, GetTid(), "  native: ", nullptr);
306
    } else {
307
      os << "Aborting thread:\n";
308 309 310 311 312 313 314
      if (Locks::mutator_lock_->IsExclusiveHeld(self) || Locks::mutator_lock_->IsSharedHeld(self)) {
        DumpThread(os, self);
      } else {
        if (Locks::mutator_lock_->SharedTryLock(self)) {
          DumpThread(os, self);
          Locks::mutator_lock_->SharedUnlock(self);
        }
315
      }
316
    }
317 318 319
    DumpAllThreads(os, self);
  }

320
  // No thread-safety analysis as we do explicitly test for holding the mutator lock.
Ian Rogers's avatar
Ian Rogers committed
321
  void DumpThread(std::ostream& os, Thread* self) const NO_THREAD_SAFETY_ANALYSIS {
322
    DCHECK(Locks::mutator_lock_->IsExclusiveHeld(self) || Locks::mutator_lock_->IsSharedHeld(self));
323 324
    self->Dump(os);
    if (self->IsExceptionPending()) {
325 326
      mirror::Throwable* exception = self->GetException();
      os << "Pending exception " << exception->Dump();
327 328 329
    }
  }

Ian Rogers's avatar
Ian Rogers committed
330
  void DumpAllThreads(std::ostream& os, Thread* self) const {
331 332 333 334 335 336 337 338 339 340 341 342 343
    Runtime* runtime = Runtime::Current();
    if (runtime != nullptr) {
      ThreadList* thread_list = runtime->GetThreadList();
      if (thread_list != nullptr) {
        bool tll_already_held = Locks::thread_list_lock_->IsExclusiveHeld(self);
        bool ml_already_held = Locks::mutator_lock_->IsSharedHeld(self);
        if (!tll_already_held || !ml_already_held) {
          os << "Dumping all threads without appropriate locks held:"
              << (!tll_already_held ? " thread list lock" : "")
              << (!ml_already_held ? " mutator lock" : "")
              << "\n";
        }
        os << "All threads:\n";
344
        thread_list->Dump(os);
345
      }
346
    }
347 348 349
  }
};

350
void Runtime::Abort() {
Ian Rogers's avatar
Ian Rogers committed
351
  gAborting++;  // set before taking any locks
352

353 354
  // Ensure that we don't have multiple threads trying to abort at once,
  // which would result in significantly worse diagnostics.
355
  MutexLock mu(Thread::Current(), *Locks::abort_lock_);
356

357
  // Get any pending output out of the way.
Mathieu Chartier's avatar
Mathieu Chartier committed
358
  fflush(nullptr);
359 360 361

  // Many people have difficulty distinguish aborts from crashes,
  // so be explicit.
362
  AbortState state;
363
  LOG(INTERNAL_FATAL) << Dumpable<AbortState>(state);
364

365
  // Call the abort hook if we have one.
Mathieu Chartier's avatar
Mathieu Chartier committed
366
  if (Runtime::Current() != nullptr && Runtime::Current()->abort_ != nullptr) {
367
    LOG(INTERNAL_FATAL) << "Calling abort hook...";
Brian Carlstrom's avatar
Brian Carlstrom committed
368 369
    Runtime::Current()->abort_();
    // notreached
370
    LOG(INTERNAL_FATAL) << "Unexpectedly returned from abort hook!";
Brian Carlstrom's avatar
Brian Carlstrom committed
371 372
  }

373
#if defined(__GLIBC__)
374 375 376 377 378 379
  // TODO: we ought to be able to use pthread_kill(3) here (or abort(3),
  // which POSIX defines in terms of raise(3), which POSIX defines in terms
  // of pthread_kill(3)). On Linux, though, libcorkscrew can't unwind through
  // libpthread, which means the stacks we dump would be useless. Calling
  // tgkill(2) directly avoids that.
  syscall(__NR_tgkill, getpid(), GetTid(), SIGABRT);
380 381
  // TODO: LLVM installs it's own SIGABRT handler so exit to be safe... Can we disable that in LLVM?
  // If not, we could use sigaction(3) before calling tgkill(2) and lose this call to exit(3).
382
  exit(1);
383 384
#else
  abort();
385
#endif
386 387 388
  // notreached
}

389
void Runtime::PreZygoteFork() {
390 391 392
  heap_->PreZygoteFork();
}

393
void Runtime::CallExitHook(jint status) {
Mathieu Chartier's avatar
Mathieu Chartier committed
394
  if (exit_ != nullptr) {
395
    ScopedThreadStateChange tsc(Thread::Current(), kNative);
396 397 398 399 400
    exit_(status);
    LOG(WARNING) << "Exit hook returned instead of exiting!";
  }
}

401
void Runtime::SweepSystemWeaks(IsMarkedCallback* visitor, void* arg) {
402 403 404
  GetInternTable()->SweepInternTableWeaks(visitor, arg);
  GetMonitorList()->SweepMonitorList(visitor, arg);
  GetJavaVM()->SweepJniWeakGlobals(visitor, arg);
405
  GetHeap()->SweepAllocationRecords(visitor, arg);
406 407
}

Ian Rogers's avatar
Ian Rogers committed
408
bool Runtime::Create(const RuntimeOptions& options, bool ignore_unrecognized) {
409
  // TODO: acquire a static mutex on Runtime to avoid racing.
Mathieu Chartier's avatar
Mathieu Chartier committed
410
  if (Runtime::instance_ != nullptr) {
Ian Rogers's avatar
Ian Rogers committed
411
    return false;
412
  }
Mathieu Chartier's avatar
Mathieu Chartier committed
413
  InitLogging(nullptr);  // Calls Locks::Init() as a side effect.
414 415
  instance_ = new Runtime;
  if (!instance_->Init(options, ignore_unrecognized)) {
416 417 418
    // TODO: Currently deleting the instance will abort the runtime on destruction. Now This will
    // leak memory, instead. Fix the destructor. b/19100793.
    // delete instance_;
Mathieu Chartier's avatar
Mathieu Chartier committed
419
    instance_ = nullptr;
Ian Rogers's avatar
Ian Rogers committed
420
    return false;
421
  }
Ian Rogers's avatar
Ian Rogers committed
422
  return true;
Brian Carlstrom's avatar
Brian Carlstrom committed
423
}
424

425 426 427
static jobject CreateSystemClassLoader(Runtime* runtime) {
  if (runtime->IsAotCompiler() && !runtime->GetCompilerCallbacks()->IsBootImage()) {
    return nullptr;
Brian Carlstrom's avatar
Brian Carlstrom committed
428 429
  }

Ian Rogers's avatar
Ian Rogers committed
430
  ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier's avatar
Mathieu Chartier committed
431
  ClassLinker* cl = Runtime::Current()->GetClassLinker();
432
  auto pointer_size = cl->GetImagePointerSize();
Brian Carlstrom's avatar
Brian Carlstrom committed
433

434
  StackHandleScope<2> hs(soa.Self());
435 436
  Handle<mirror::Class> class_loader_class(
      hs.NewHandle(soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_ClassLoader)));
437
  CHECK(cl->EnsureInitialized(soa.Self(), class_loader_class, true, true));
Brian Carlstrom's avatar
Brian Carlstrom committed
438

439 440
  ArtMethod* getSystemClassLoader = class_loader_class->FindDirectMethod(
      "getSystemClassLoader", "()Ljava/lang/ClassLoader;", pointer_size);
Mathieu Chartier's avatar
Mathieu Chartier committed
441
  CHECK(getSystemClassLoader != nullptr);
442

443
  JValue result = InvokeWithJValues(soa, nullptr, soa.EncodeMethod(getSystemClassLoader), nullptr);
444
  JNIEnv* env = soa.Self()->GetJniEnv();
445
  ScopedLocalRef<jobject> system_class_loader(env, soa.AddLocalReference<jobject>(result.GetL()));
Mathieu Chartier's avatar
Mathieu Chartier committed
446
  CHECK(system_class_loader.get() != nullptr);
447

448
  soa.Self()->SetClassLoaderOverride(system_class_loader.get());
449

450 451
  Handle<mirror::Class> thread_class(
      hs.NewHandle(soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_Thread)));
452
  CHECK(cl->EnsureInitialized(soa.Self(), thread_class, true, true));
453

Mathieu Chartier's avatar
Mathieu Chartier committed
454
  ArtField* contextClassLoader =
Mathieu Chartier's avatar
Mathieu Chartier committed
455
      thread_class->FindDeclaredInstanceField("contextClassLoader", "Ljava/lang/ClassLoader;");
Mathieu Chartier's avatar
Mathieu Chartier committed
456
  CHECK(contextClassLoader != nullptr);
457

Sebastien Hertz's avatar
Sebastien Hertz committed
458
  // We can't run in a transaction yet.
459 460
  contextClassLoader->SetObject<false>(soa.Self()->GetPeer(),
                                       soa.Decode<mirror::ClassLoader*>(system_class_loader.get()));
461 462

  return env->NewGlobalRef(system_class_loader.get());
Brian Carlstrom's avatar
Brian Carlstrom committed
463 464
}

465 466 467 468
std::string Runtime::GetPatchoatExecutable() const {
  if (!patchoat_executable_.empty()) {
    return patchoat_executable_;
  }
Andreas Gampe's avatar
Andreas Gampe committed
469 470 471
  std::string patchoat_executable(GetAndroidRoot());
  patchoat_executable += (kIsDebugBuild ? "/bin/patchoatd" : "/bin/patchoat");
  return patchoat_executable;
472 473
}

474 475 476 477 478 479 480 481 482
std::string Runtime::GetCompilerExecutable() const {
  if (!compiler_executable_.empty()) {
    return compiler_executable_;
  }
  std::string compiler_executable(GetAndroidRoot());
  compiler_executable += (kIsDebugBuild ? "/bin/dex2oatd" : "/bin/dex2oat");
  return compiler_executable;
}

483
bool Runtime::Start() {
Elliott Hughes's avatar
Elliott Hughes committed
484
  VLOG(startup) << "Runtime::Start entering";
485

Ian Rogers's avatar
Ian Rogers committed
486
  // Restore main thread state to kNative as expected by native code.
487
  Thread* self = Thread::Current();
488

Ian Rogers's avatar
Ian Rogers committed
489 490
  self->TransitionFromRunnableToSuspended(kNative);

491 492
  started_ = true;

Mathieu Chartier's avatar
Mathieu Chartier committed
493 494
  // Use !IsAotCompiler so that we get test coverage, tests are never the zygote.
  if (!IsAotCompiler()) {
495
    ScopedObjectAccess soa(self);
496 497
    gc::space::ImageSpace* image_space = heap_->GetImageSpace();
    if (image_space != nullptr) {
498
      ATRACE_BEGIN("AddImageStringsToTable");
Mathieu Chartier's avatar
Mathieu Chartier committed
499
      GetInternTable()->AddImageStringsToTable(image_space);
500 501
      ATRACE_END();
      ATRACE_BEGIN("MoveImageClassesToClassTable");
Mathieu Chartier's avatar
Mathieu Chartier committed
502
      GetClassLinker()->MoveImageClassesToClassTable();
503
      ATRACE_END();
504
    }
505 506
  }

507 508 509 510
  // If we are the zygote then we need to wait until after forking to create the code cache
  // due to SELinux restrictions on r/w/x memory regions.
  if (!IsZygote() && jit_options_->UseJIT()) {
    CreateJit();
Mathieu Chartier's avatar
Mathieu Chartier committed
511 512 513
  }

  if (!IsImageDex2OatEnabled() || !GetHeap()->HasImageSpace()) {
514
    ScopedObjectAccess soa(self);
515 516
    StackHandleScope<1> hs(soa.Self());
    auto klass(hs.NewHandle<mirror::Class>(mirror::Class::GetJavaLangClass()));
517
    class_linker_->EnsureInitialized(soa.Self(), klass, true, true);
518 519
  }

520 521
  // InitNativeMethods needs to be after started_ so that the classes
  // it touches will have methods linked to the oat file if necessary.
522
  ATRACE_BEGIN("InitNativeMethods");
523
  InitNativeMethods();
524
  ATRACE_END();
525

526 527 528
  // Initialize well known thread group values that may be accessed threads while attaching.
  InitThreadGroups(self);

529 530
  Thread::FinishStartup();

531
  system_class_loader_ = CreateSystemClassLoader(this);
532

533 534 535 536 537
  if (is_zygote_) {
    if (!InitZygote()) {
      return false;
    }
  } else {
538
    if (is_native_bridge_loaded_) {
539 540
      PreInitializeNativeBridge(".");
    }
541 542
    DidForkFromZygote(self->GetJniEnv(), NativeBridgeAction::kInitialize,
                      GetInstructionSetString(kRuntimeISA));
543
  }
544

545
  ATRACE_BEGIN("StartDaemonThreads");
Elliott Hughes's avatar
Elliott Hughes committed
546
  StartDaemonThreads();
547
  ATRACE_END();
Brian Carlstrom's avatar
Brian Carlstrom committed
548

549 550 551 552
  {
    ScopedObjectAccess soa(self);
    self->GetJniEnv()->locals.AssertEmpty();
  }
553

Elliott Hughes's avatar
Elliott Hughes committed
554
  VLOG(startup) << "Runtime::Start exiting";
555
  finished_starting_ = true;
556

557 558
  if (profiler_options_.IsEnabled() && !profile_output_filename_.empty()) {
    // User has asked for a profile using -Xenable-profiler.
559 560 561 562
    // Create the profile file if it doesn't exist.
    int fd = open(profile_output_filename_.c_str(), O_RDWR|O_CREAT|O_EXCL, 0660);
    if (fd >= 0) {
      close(fd);
563 564 565
    } else if (errno != EEXIST) {
      LOG(INFO) << "Failed to access the profile file. Profiler disabled.";
      return true;
566
    }
567
    StartProfiler(profile_output_filename_.c_str());
Dave Allison's avatar
Dave Allison committed
568 569
  }

Andreas Gampe's avatar
Andreas Gampe committed
570 571 572 573 574 575 576 577 578 579 580
  if (trace_config_.get() != nullptr && trace_config_->trace_file != "") {
    ScopedThreadStateChange tsc(self, kWaitingForMethodTracingStart);
    Trace::Start(trace_config_->trace_file.c_str(),
                 -1,
                 static_cast<int>(trace_config_->trace_file_size),
                 0,
                 trace_config_->trace_output_mode,
                 trace_config_->trace_mode,
                 0);
  }

581
  return true;
Elliott Hughes's avatar
Elliott Hughes committed
582 583
}

584 585 586 587
void Runtime::EndThreadBirth() EXCLUSIVE_LOCKS_REQUIRED(Locks::runtime_shutdown_lock_) {
  DCHECK_GT(threads_being_born_, 0U);
  threads_being_born_--;
  if (shutting_down_started_ && threads_being_born_ == 0) {
588
    shutdown_cond_->Broadcast(Thread::Current());
589 590 591
  }
}

592 593
// Do zygote-mode-only initialization.
bool Runtime::InitZygote() {
594
#ifdef __linux__
595
  // zygote goes into its own process group
596
  setpgid(0, 0);
597 598 599 600 601 602 603 604 605 606

  // See storage config details at http://source.android.com/tech/storage/
  // Create private mount namespace shared by all children
  if (unshare(CLONE_NEWNS) == -1) {
    PLOG(WARNING) << "Failed to unshare()";
    return false;
  }

  // Mark rootfs as being a slave so that changes from default
  // namespace only flow into our children.
Mathieu Chartier's avatar
Mathieu Chartier committed
607
  if (mount("rootfs", "/", nullptr, (MS_SLAVE | MS_REC), nullptr) == -1) {
608 609 610 611 612 613 614 615
    PLOG(WARNING) << "Failed to mount() rootfs as MS_SLAVE";
    return false;
  }

  // Create a staging tmpfs that is shared by our children; they will
  // bind mount storage into their respective private namespaces, which
  // are isolated from each other.
  const char* target_base = getenv("EMULATED_STORAGE_TARGET");
Mathieu Chartier's avatar
Mathieu Chartier committed
616
  if (target_base != nullptr) {
617
    if (mount("tmpfs", target_base, "tmpfs", MS_NOSUID | MS_NODEV,
618
              "uid=0,gid=1028,mode=0751") == -1) {
619 620 621 622 623 624
      LOG(WARNING) << "Failed to mount tmpfs to " << target_base;
      return false;
    }
  }

  return true;
625 626 627 628
#else
  UNIMPLEMENTED(FATAL);
  return false;
#endif
629 630
}

631
void Runtime::DidForkFromZygote(JNIEnv* env, NativeBridgeAction action, const char* isa) {
632
  is_zygote_ = false;
633

634 635 636 637 638 639
  if (is_native_bridge_loaded_) {
    switch (action) {
      case NativeBridgeAction::kUnload:
        UnloadNativeBridge();
        is_native_bridge_loaded_ = false;
        break;
640

641 642 643 644
      case NativeBridgeAction::kInitialize:
        InitializeNativeBridge(env, isa);
        break;
    }
645 646
  }

Mathieu Chartier's avatar
Mathieu Chartier committed
647
  // Create the thread pools.
648
  heap_->CreateThreadPool();
649
  if (jit_.get() == nullptr && jit_options_->UseJIT()) {
Mathieu Chartier's avatar
Mathieu Chartier committed
650 651 652
    // Create the JIT if the flag is set and we haven't already create it (happens for run-tests).
    CreateJit();
  }
653

654
  StartSignalCatcher();
655 656 657

  // Start the JDWP thread. If the command-line debugger flags specified "suspend=y",
  // this will pause the runtime, so we probably want this to come last.
Sebastien Hertz's avatar
Sebastien Hertz committed
658
  Dbg::StartJdwp();
659 660 661 662
}

void Runtime::StartSignalCatcher() {
  if (!is_zygote_) {
Elliott Hughes's avatar
Elliott Hughes committed
663
    signal_catcher_ = new SignalCatcher(stack_trace_file_);
664 665 666
  }
}

Mathieu Chartier's avatar
Mathieu Chartier committed
667 668 669 670 671
bool Runtime::IsShuttingDown(Thread* self) {
  MutexLock mu(self, *Locks::runtime_shutdown_lock_);
  return IsShuttingDownLocked();
}

Elliott Hughes's avatar
Elliott Hughes committed
672
void Runtime::StartDaemonThreads() {
Elliott Hughes's avatar
Elliott Hughes committed
673
  VLOG(startup) << "Runtime::StartDaemonThreads entering";
Elliott Hughes's avatar
Elliott Hughes committed
674

675
  Thread* self = Thread::Current();
Brian Carlstrom's avatar
Brian Carlstrom committed
676 677

  // Must be in the kNative state for calling native methods.
678
  CHECK_EQ(self->GetState(), kNative);
Brian Carlstrom's avatar
Brian Carlstrom committed
679

680
  JNIEnv* env = self->GetJniEnv();
Ian Rogers's avatar
Ian Rogers committed
681 682 683 684 685 686
  env->CallStaticVoidMethod(WellKnownClasses::java_lang_Daemons,
                            WellKnownClasses::java_lang_Daemons_start);
  if (env->ExceptionCheck()) {
    env->ExceptionDescribe();
    LOG(FATAL) << "Error starting java.lang.Daemons";
  }
687

Elliott Hughes's avatar
Elliott Hughes committed
688
  VLOG(startup) << "Runtime::StartDaemonThreads exiting";
689 690
}

691
static bool OpenDexFilesFromImage(const std::string& image_location,
692
                                  std::vector<std::unique_ptr<const DexFile>>* dex_files,
693
                                  size_t* failures) {
Mathieu Chartier's avatar
Mathieu Chartier committed
694
  DCHECK(dex_files != nullptr) << "OpenDexFilesFromImage: out-param is nullptr";
695 696 697 698 699
  std::string system_filename;
  bool has_system = false;
  std::string cache_filename_unused;
  bool dalvik_cache_exists_unused;
  bool has_cache_unused;
700
  bool is_global_cache_unused;
701 702 703 704 705 706
  bool found_image = gc::space::ImageSpace::FindImageFilename(image_location.c_str(),
                                                              kRuntimeISA,
                                                              &system_filename,
                                                              &has_system,
                                                              &cache_filename_unused,
                                                              &dalvik_cache_exists_unused,
707 708
                                                              &has_cache_unused,
                                                              &is_global_cache_unused);
709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726
  *failures = 0;
  if (!found_image || !has_system) {
    return false;
  }
  std::string error_msg;
  // We are falling back to non-executable use of the oat file because patching failed, presumably
  // due to lack of space.
  std::string oat_filename = ImageHeader::GetOatLocationFromImageLocation(system_filename.c_str());
  std::string oat_location = ImageHeader::GetOatLocationFromImageLocation(image_location.c_str());
  std::unique_ptr<File> file(OS::OpenFileForReading(oat_filename.c_str()));
  if (file.get() == nullptr) {
    return false;
  }
  std::unique_ptr<ElfFile> elf_file(ElfFile::Open(file.release(), false, false, &error_msg));
  if (elf_file.get() == nullptr) {
    return false;
  }
  std::unique_ptr<OatFile> oat_file(OatFile::OpenWithElfFile(elf_file.release(), oat_location,
727
                                                             nullptr, &error_msg));
728 729 730 731 732
  if (oat_file.get() == nullptr) {
    LOG(INFO) << "Unable to use '" << oat_filename << "' because " << error_msg;
    return false;
  }

733
  for (const OatFile::OatDexFile* oat_dex_file : oat_file->GetOatDexFiles()) {
734 735 736 737
    if (oat_dex_file == nullptr) {
      *failures += 1;
      continue;
    }
738 739
    std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
    if (dex_file.get() == nullptr) {
740 741
      *failures += 1;
    } else {
742
      dex_files->push_back(std::move(dex_file));
743 744 745 746 747 748 749
    }
  }
  Runtime::Current()->GetClassLinker()->RegisterOatFile(oat_file.release());
  return true;
}


750
static size_t OpenDexFiles(const std::vector<std::string>& dex_filenames,
751
                           const std::vector<std::string>& dex_locations,
752
                           const std::string& image_location,
753
                           std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier's avatar
Mathieu Chartier committed
754
  DCHECK(dex_files != nullptr) << "OpenDexFiles: out-param is nullptr";
755
  size_t failure_count = 0;
756
  if (!image_location.empty() && OpenDexFilesFromImage(image_location, dex_files, &failure_count)) {
757 758 759
    return failure_count;
  }
  failure_count = 0;
760 761
  for (size_t i = 0; i < dex_filenames.size(); i++) {
    const char* dex_filename = dex_filenames[i].c_str();
762
    const char* dex_location = dex_locations[i].c_str();
763 764 765 766 767
    std::string error_msg;
    if (!OS::FileExists(dex_filename)) {
      LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'";
      continue;
    }
768
    if (!DexFile::Open(dex_filename, dex_location, &error_msg, dex_files)) {
769 770 771 772 773 774 775
      LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg;
      ++failure_count;
    }
  }
  return failure_count;
}

Ian Rogers's avatar
Ian Rogers committed
776
bool Runtime::Init(const RuntimeOptions& raw_options, bool ignore_unrecognized) {
777
  ATRACE_BEGIN("Runtime::Init");
778
  CHECK_EQ(sysconf(_SC_PAGE_SIZE), kPageSize);
Brian Carlstrom's avatar
Brian Carlstrom committed
779

780 781
  MemMap::Init();

782 783 784 785 786
  using Opt = RuntimeArgumentMap;
  RuntimeArgumentMap runtime_options;
  std::unique_ptr<ParsedOptions> parsed_options(
      ParsedOptions::Create(raw_options, ignore_unrecognized, &runtime_options));
  if (parsed_options.get() == nullptr) {
Brian Carlstrom's avatar
Brian Carlstrom committed
787
    LOG(ERROR) << "Failed to parse options";
788
    ATRACE_END();
Brian Carlstrom's avatar
Brian Carlstrom committed
789 790
    return false;
  }
Elliott Hughes's avatar
Elliott Hughes committed
791
  VLOG(startup) << "Runtime::Init -verbose:startup enabled";
Elliott Hughes's avatar
Elliott Hughes committed
792

793 794
  QuasiAtomic::Startup();

795 796
  Monitor::Init(runtime_options.GetOrDefault(Opt::LockProfThreshold),
                runtime_options.GetOrDefault(Opt::HookIsSensitiveThread));
797

798 799 800
  boot_class_path_string_ = runtime_options.ReleaseOrDefault(Opt::BootClassPath);
  class_path_string_ = runtime_options.ReleaseOrDefault(Opt::ClassPath);
  properties_ = runtime_options.ReleaseOrDefault(Opt::PropertiesList);
Elliott Hughes's avatar
Elliott Hughes committed
801

802 803 804 805 806 807 808
  compiler_callbacks_ = runtime_options.GetOrDefault(Opt::CompilerCallbacksPtr);
  patchoat_executable_ = runtime_options.ReleaseOrDefault(Opt::PatchOat);
  must_relocate_ = runtime_options.GetOrDefault(Opt::Relocate);
  is_zygote_ = runtime_options.Exists(Opt::Zygote);
  is_explicit_gc_disabled_ = runtime_options.Exists(Opt::DisableExplicitGC);
  dex2oat_enabled_ = runtime_options.GetOrDefault(Opt::Dex2Oat);
  image_dex2oat_enabled_ = runtime_options.GetOrDefault(Opt::ImageDex2Oat);
809

810 811 812
  vfprintf_ = runtime_options.GetOrDefault(Opt::HookVfprintf);
  exit_ = runtime_options.GetOrDefault(Opt::HookExit);
  abort_ = runtime_options.GetOrDefault(Opt::HookAbort);
Brian Carlstrom's avatar
Brian Carlstrom committed
813

814 815
  default_stack_size_ = runtime_options.GetOrDefault(Opt::StackSize);
  stack_trace_file_ = runtime_options.ReleaseOrDefault(Opt::StackTraceFile);
Brian Carlstrom's avatar
Brian Carlstrom committed
816

817 818 819 820
  compiler_executable_ = runtime_options.ReleaseOrDefault(Opt::Compiler);
  compiler_options_ = runtime_options.ReleaseOrDefault(Opt::CompilerOptions);
  image_compiler_options_ = runtime_options.ReleaseOrDefault(Opt::ImageCompilerOptions);
  image_location_ = runtime_options.GetOrDefault(Opt::Image);
821

822 823
  max_spins_before_thin_lock_inflation_ =
      runtime_options.GetOrDefault(Opt::MaxSpinsBeforeThinLockInflation);
824

Elliott Hughes's avatar
Elliott Hughes committed
825
  monitor_list_ = new MonitorList;
826
  monitor_pool_ = MonitorPool::Create();
Elliott Hughes's avatar
Elliott Hughes committed
827
  thread_list_ = new ThreadList;
828 829
  intern_table_ = new InternTable;

830
  verify_ = runtime_options.GetOrDefault(Opt::Verify);
831
  allow_dex_file_fallback_ = !runtime_options.Exists(Opt::NoDexFileFallback);
832

833 834
  Split(runtime_options.GetOrDefault(Opt::CpuAbiList), ',', &cpu_abilist_);

835
  if (runtime_options.GetOrDefault(Opt::Interpret)) {
836 837 838
    GetInstrumentation()->ForceInterpretOnly();
  }

839 840
  zygote_max_failed_boots_ = runtime_options.GetOrDefault(Opt::ZygoteMaxFailedBoots);

841
  XGcOption xgc_option = runtime_options.GetOrDefault(Opt::GcOption);
842
  ATRACE_BEGIN("CreateHeap");
843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862
  heap_ = new gc::Heap(runtime_options.GetOrDefault(Opt::MemoryInitialSize),
                       runtime_options.GetOrDefault(Opt::HeapGrowthLimit),
                       runtime_options.GetOrDefault(Opt::HeapMinFree),
                       runtime_options.GetOrDefault(Opt::HeapMaxFree),
                       runtime_options.GetOrDefault(Opt::HeapTargetUtilization),
                       runtime_options.GetOrDefault(Opt::ForegroundHeapGrowthMultiplier),
                       runtime_options.GetOrDefault(Opt::MemoryMaximumSize),
                       runtime_options.GetOrDefault(Opt::NonMovingSpaceCapacity),
                       runtime_options.GetOrDefault(Opt::Image),
                       runtime_options.GetOrDefault(Opt::ImageInstructionSet),
                       xgc_option.collector_type_,
                       runtime_options.GetOrDefault(Opt::BackgroundGc),
                       runtime_options.GetOrDefault(Opt::LargeObjectSpace),
                       runtime_options.GetOrDefault(Opt::LargeObjectThreshold),
                       runtime_options.GetOrDefault(Opt::ParallelGCThreads),
                       runtime_options.GetOrDefault(Opt::ConcGCThreads),
                       runtime_options.Exists(Opt::LowMemoryMode),
                       runtime_options.GetOrDefault(Opt::LongPauseLogThreshold),
                       runtime_options.GetOrDefault(Opt::LongGCLogThreshold),
                       runtime_options.Exists(Opt::IgnoreMaxFootprint),
Hiroshi Yamauchi's avatar
Hiroshi Yamauchi committed
863
                       runtime_options.GetOrDefault(Opt::UseTLAB),
864 865 866 867 868 869 870 871
                       xgc_option.verify_pre_gc_heap_,
                       xgc_option.verify_pre_sweeping_heap_,
                       xgc_option.verify_post_gc_heap_,
                       xgc_option.verify_pre_gc_rosalloc_,
                       xgc_option.verify_pre_sweeping_rosalloc_,
                       xgc_option.verify_post_gc_rosalloc_,
                       runtime_options.GetOrDefault(Opt::EnableHSpaceCompactForOOM),
                       runtime_options.GetOrDefault(Opt::HSpaceCompactForOOMMinIntervalsMs));
872
  ATRACE_END();
873

874 875
  if (heap_->GetImageSpace() == nullptr && !allow_dex_file_fallback_) {
    LOG(ERROR) << "Dex file fallback disabled, cannot continue without image.";
876
    ATRACE_END();
877 878 879
    return false;
  }

880
  dump_gc_performance_on_shutdown_ = runtime_options.Exists(Opt::DumpGCPerformanceOnShutdown);
881

882
  if (runtime_options.Exists(Opt::JdwpOptions)) {
Sebastien Hertz's avatar
Sebastien Hertz committed
883
    Dbg::ConfigureJdwp(runtime_options.GetOrDefault(Opt::JdwpOptions));
884 885
  }

886 887
  jit_options_.reset(jit::JitOptions::CreateFromRuntimeArguments(runtime_options));
  if (IsAotCompiler()) {
Mathieu Chartier's avatar
Mathieu Chartier committed
888 889 890
    // If we are already the compiler at this point, we must be dex2oat. Don't create the jit in
    // this case.
    // If runtime_options doesn't have UseJIT set to true then CreateFromRuntimeArguments returns
Mathieu Chartier's avatar
Mathieu Chartier committed
891
    // null and we don't create the jit.
892
    jit_options_->SetUseJIT(false);
Mathieu Chartier's avatar
Mathieu Chartier committed
893 894
  }

895 896
  // Use MemMap arena pool for jit, malloc otherwise. Malloc arenas are faster to allocate but
  // can't be trimmed as easily.
897
  const bool use_malloc = IsAotCompiler();
Mathieu Chartier's avatar
Mathieu Chartier committed
898 899 900 901 902 903 904 905
  arena_pool_.reset(new ArenaPool(use_malloc, false));
  if (IsCompiler() && Is64BitInstructionSet(kRuntimeISA)) {
    // 4gb, no malloc. Explanation in header.
    low_4gb_arena_pool_.reset(new ArenaPool(false, true));
    linear_alloc_.reset(new LinearAlloc(low_4gb_arena_pool_.get()));
  } else {
    linear_alloc_.reset(new LinearAlloc(arena_pool_.get()));
  }
906

907 908 909
  BlockSignals();
  InitPlatformSignalHandlers();

910 911 912 913 914
  // Change the implicit checks flags based on runtime architecture.
  switch (kRuntimeISA) {
    case kArm:
    case kThumb2:
    case kX86:
915
    case kArm64:
916
    case kX86_64:
917
      implicit_null_checks_ = true;
Andreas Gampe's avatar
Andreas Gampe committed
918 919
      // Installing stack protection does not play well with valgrind.
      implicit_so_checks_ = (RUNNING_ON_VALGRIND == 0);
920 921 922 923 924 925
      break;
    default:
      // Keep the defaults.
      break;
  }

926 927 928 929 930
  // Always initialize the signal chain so that any calls to sigaction get
  // correctly routed to the next in the chain regardless of whether we
  // have claimed the signal or not.
  InitializeSignalChain();

931
  if (implicit_null_checks_ || implicit_so_checks_ || implicit_suspend_checks_) {
932 933 934 935
    fault_manager.Init();

    // These need to be in a specific order.  The null point check handler must be
    // after the suspend check and stack overflow check handlers.
Andreas Gampe's avatar
Andreas Gampe committed
936 937 938
    //
    // Note: the instances attach themselves to the fault manager and are handled by it. The manager
    //       will delete the instance on Shutdown().
939
    if (implicit_suspend_checks_) {
Andreas Gampe's avatar
Andreas Gampe committed
940
      new SuspensionHandler(&fault_manager);
941 942 943
    }

    if (implicit_so_checks_) {
Andreas Gampe's avatar
Andreas Gampe committed
944
      new StackOverflowHandler(&fault_manager);
945 946 947
    }

    if (implicit_null_checks_) {
Andreas Gampe's avatar
Andreas Gampe committed
948
      new NullPointerHandler(&fault_manager);
949 950 951 952 953 954 955
    }

    if (kEnableJavaStackTraceHandler) {
      new JavaStackTraceHandler(&fault_manager);
    }
  }

956
  java_vm_ = new JavaVMExt(this, runtime_options);
Elliott Hughes's avatar
Elliott Hughes committed
957

958
  Thread::Startup();
959

960 961 962
  // ClassLinker needs an attached thread, but we can't fully attach a thread without creating
  // objects. We can't supply a thread group yet; it will be fixed later. Since we are the main
  // thread, we do not get a java peer.
963
  Thread* self = Thread::Attach("main", false, nullptr, false);
964
  CHECK_EQ(self->GetThreadId(), ThreadList::kMainThreadId);
965
  CHECK(self != nullptr);
Brian Carlstrom's avatar
Brian Carlstrom committed
966

967
  // Set us to runnable so tools using a runtime can allocate and GC by default
968
  self->TransitionFromSuspendedToRunnable();
969

970
  // Now we're attached, we can take the heap locks and validate the heap.
Ian Rogers's avatar
Ian Rogers committed
971 972
  GetHeap()->EnableObjectValidation();

Ian Rogers's avatar
Ian Rogers committed
973
  CHECK_GE(GetHeap()->GetContinuousSpaces().size(), 1U);
Mathieu Chartier's avatar
Mathieu Chartier committed
974 975
  class_linker_ = new ClassLinker(intern_table_);
  if (GetHeap()->HasImageSpace()) {
976
    ATRACE_BEGIN("InitFromImage");
Mathieu Chartier's avatar
Mathieu Chartier committed
977
    class_linker_->InitFromImage();
978
    ATRACE_END();
979 980 981
    if (kIsDebugBuild) {
      GetHeap()->GetImageSpace()->VerifyImageAllocations();
    }
982 983 984 985 986 987 988 989 990 991
    if (boot_class_path_string_.empty()) {
      // The bootclasspath is not explicitly specified: construct it from the loaded dex files.
      const std::vector<const DexFile*>& boot_class_path = GetClassLinker()->GetBootClassPath();
      std::vector<std::string> dex_locations;
      dex_locations.reserve(boot_class_path.size());
      for (const DexFile* dex_file : boot_class_path) {
        dex_locations.push_back(dex_file->GetLocation());
      }
      boot_class_path_string_ = Join(dex_locations, ':');
    }
992
  } else {
993
    std::vector<std::string> dex_filenames;
994
    Split(boot_class_path_string_, ':', &dex_filenames);
995 996

    std::vector<std::string> dex_locations;
997
    if (!runtime_options.Exists(Opt::BootClassPathLocations)) {
998 999
      dex_locations = dex_filenames;
    } else {
1000
      dex_locations = runtime_options.GetOrDefault(Opt::BootClassPathLocations);
1001 1002 1003
      CHECK_EQ(dex_filenames.size(), dex_locations.size());
    }

1004
    std::vector<std::unique_ptr<const DexFile>> boot_class_path;
1005 1006 1007 1008
    OpenDexFiles(dex_filenames,
                 dex_locations,
                 runtime_options.GetOrDefault(Opt::Image),
                 &boot_class_path);
1009
    instruction_set_ = runtime_options.GetOrDefault(Opt::ImageInstructionSet);
1010
    class_linker_->InitWithoutImage(std::move(boot_class_path));
1011

1012
    // TODO: Should we move the following to InitWithoutImage?
1013
    SetInstructionSet(instruction_set_);
1014 1015 1016
    for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
      Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
      if (!HasCalleeSaveMethod(type)) {
1017
        SetCalleeSaveMethod(CreateCalleeSaveMethod(), type);
1018 1019
      }
    }
1020 1021
  }

1022
  CHECK(class_linker_ != nullptr);
1023 1024 1025

  // Initialize the special sentinel_ value early.
  sentinel_ = GcRoot<mirror::Object>(class_linker_->AllocObject(self));
1026
  CHECK(sentinel_.Read() != nullptr);
1027

1028
  verifier::MethodVerifier::Init();
Brian Carlstrom's avatar
Brian Carlstrom committed
1029

1030 1031 1032 1033 1034
  if (runtime_options.Exists(Opt::MethodTrace)) {
    trace_config_.reset(new TraceConfig());
    trace_config_->trace_file = runtime_options.ReleaseOrDefault(Opt::MethodTraceFile);
    trace_config_->trace_file_size = runtime_options.ReleaseOrDefault(Opt::MethodTraceFileSize);
    trace_config_->trace_mode = Trace::TraceMode::kMethodTracing;
Andreas Gampe's avatar
Andreas Gampe committed
1035 1036 1037
    trace_config_->trace_output_mode = runtime_options.Exists(Opt::MethodTraceStreaming) ?
        Trace::TraceOutputMode::kStreaming :
        Trace::TraceOutputMode::kFile;
1038
  }
1039

1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
  {
    auto&& profiler_options = runtime_options.ReleaseOrDefault(Opt::ProfilerOpts);
    profile_output_filename_ = profiler_options.output_file_name_;

    // TODO: Don't do this, just change ProfilerOptions to include the output file name?
    ProfilerOptions other_options(
        profiler_options.enabled_,
        profiler_options.period_s_,
        profiler_options.duration_s_,
        profiler_options.interval_us_,
        profiler_options.backoff_coefficient_,
        profiler_options.start_immediately_,
        profiler_options.top_k_threshold_,
        profiler_options.top_k_change_threshold_,
        profiler_options.profile_type_,
        profiler_options.max_stack_depth_);

    profiler_options_ = other_options;
  }
1059

1060
  // TODO: move this to just be an Trace::Start argument
1061
  Trace::SetDefaultClockSource(runtime_options.GetOrDefault(Opt::ProfileClock));
Dave Allison's avatar
Dave Allison committed
1062

1063
  // Pre-allocate an OutOfMemoryError for the double-OOME case.
Nicolas Geoffray's avatar
Nicolas Geoffray committed
1064
  self->ThrowNewException("Ljava/lang/OutOfMemoryError;",
1065
                          "OutOfMemoryError thrown while trying to throw OutOfMemoryError; "
1066
                          "no stack trace available");
1067
  pre_allocated_OutOfMemoryError_ = GcRoot<mirror::Throwable>(self->GetException());
1068 1069
  self->ClearException();

1070 1071
  // Pre-allocate a NoClassDefFoundError for the common case of failing to find a system class
  // ahead of checking the application's class loader.
Nicolas Geoffray's avatar
Nicolas Geoffray committed
1072
  self->ThrowNewException("Ljava/lang/NoClassDefFoundError;",
1073
                          "Class not found using the boot class loader; no stack trace available");
1074
  pre_allocated_NoClassDefFoundError_ = GcRoot<mirror::Throwable>(self->GetException());
1075 1076
  self->ClearException();

1077
  // Look for a native bridge.
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103
  //
  // The intended flow here is, in the case of a running system:
  //
  // Runtime::Init() (zygote):
  //   LoadNativeBridge -> dlopen from cmd line parameter.
  //  |
  //  V
  // Runtime::Start() (zygote):
  //   No-op wrt native bridge.
  //  |
  //  | start app
  //  V
  // DidForkFromZygote(action)
  //   action = kUnload -> dlclose native bridge.
  //   action = kInitialize -> initialize library
  //
  //
  // The intended flow here is, in the case of a simple dalvikvm call:
  //
  // Runtime::Init():
  //   LoadNativeBridge -> dlopen from cmd line parameter.
  //  |
  //  V
  // Runtime::Start():
  //   DidForkFromZygote(kInitialize) -> try to initialize any native bridge given.
  //   No-op wrt native bridge.
1104 1105 1106 1107
  {
    std::string native_bridge_file_name = runtime_options.ReleaseOrDefault(Opt::NativeBridge);
    is_native_bridge_loaded_ = LoadNativeBridge(native_bridge_file_name);
  }
1108

Elliott Hughes's avatar
Elliott Hughes committed
1109
  VLOG(startup) << "Runtime::Init exiting";
1110

1111 1112
  ATRACE_END();

1113 1114 1115
  return true;
}

1116
void Runtime::InitNativeMethods() {
Elliott Hughes's avatar
Elliott Hughes committed
1117
  VLOG(startup) << "Runtime::InitNativeMethods entering";
1118 1119 1120
  Thread* self = Thread::Current();
  JNIEnv* env = self->GetJniEnv();

1121
  // Must be in the kNative state for calling native methods (JNI_OnLoad code).
1122
  CHECK_EQ(self->GetState(), kNative);
1123

1124 1125
  // First set up JniConstants, which is used by both the runtime's built-in native
  // methods and libcore.
1126
  JniConstants::init(env);
1127
  WellKnownClasses::Init(env);
1128

1129
  // Then set up the native methods provided by the runtime itself.
1130 1131
  RegisterRuntimeNativeMethods(env);

1132 1133 1134
  // Then set up libcore, which is just a regular JNI library with a regular JNI_OnLoad.
  // Most JNI libraries can just use System.loadLibrary, but libcore can't because it's
  // the library that implements System.loadLibrary!
Ian Rogers's avatar
Ian Rogers committed
1135 1136
  {
    std::string reason;
1137 1138
    if (!java_vm_->LoadNativeLibrary(env, "libjavacore.so", nullptr, &reason)) {
      LOG(FATAL) << "LoadNativeLibrary failed for \"libjavacore.so\": " << reason;
Ian Rogers's avatar
Ian Rogers committed
1139 1140
    }
  }
1141 1142 1143 1144

  // Initialize well known classes that may invoke runtime native methods.
  WellKnownClasses::LateInit(env);

Elliott Hughes's avatar
Elliott Hughes committed
1145
  VLOG(startup) << "Runtime::InitNativeMethods exiting";
1146 1147
}

1148 1149 1150 1151
void Runtime::InitThreadGroups(Thread* self) {
  JNIEnvExt* env = self->GetJniEnv();
  ScopedJniEnvLocalRefState env_state(env);
  main_thread_group_ =
1152 1153 1154
      env->NewGlobalRef(env->GetStaticObjectField(
          WellKnownClasses::java_lang_ThreadGroup,
          WellKnownClasses::java_lang_ThreadGroup_mainThreadGroup));
Mathieu Chartier's avatar
Mathieu Chartier committed
1155
  CHECK(main_thread_group_ != nullptr || IsAotCompiler());
1156
  system_thread_group_ =
1157 1158 1159
      env->NewGlobalRef(env->GetStaticObjectField(
          WellKnownClasses::java_lang_ThreadGroup,
          WellKnownClasses::java_lang_ThreadGroup_systemThreadGroup));
Mathieu Chartier's avatar
Mathieu Chartier committed
1160
  CHECK(system_thread_group_ != nullptr || IsAotCompiler());
1161 1162 1163
}

jobject Runtime::GetMainThreadGroup() const {
Mathieu Chartier's avatar
Mathieu Chartier committed
1164
  CHECK(main_thread_group_ != nullptr || IsAotCompiler());
1165 1166 1167 1168
  return main_thread_group_;
}

jobject Runtime::GetSystemThreadGroup() const {
Mathieu Chartier's avatar
Mathieu Chartier committed
1169
  CHECK(system_thread_group_ != nullptr || IsAotCompiler());
1170
  return system_thread_group_;
1171 1172
}

1173
jobject Runtime::GetSystemClassLoader() const {
Mathieu Chartier's avatar
Mathieu Chartier committed
1174
  CHECK(system_class_loader_ != nullptr || IsAotCompiler());
1175 1176 1177
  return system_class_loader_;
}

1178
void Runtime::RegisterRuntimeNativeMethods(JNIEnv* env) {
Andreas Gampe's avatar
Andreas Gampe committed
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195
  register_dalvik_system_DexFile(env);
  register_dalvik_system_VMDebug(env);
  register_dalvik_system_VMRuntime(env);
  register_dalvik_system_VMStack(env);
  register_dalvik_system_ZygoteHooks(env);
  register_java_lang_Class(env);
  register_java_lang_DexCache(env);
  register_java_lang_Object(env);
  register_java_lang_ref_FinalizerReference(env);
  register_java_lang_reflect_Array(env);
  register_java_lang_reflect_Constructor(env);
  register_java_lang_reflect_Field(env);
  register_java_lang_reflect_Method(env);
  register_java_lang_reflect_Proxy(env);
  register_java_lang_ref_Reference(env);
  register_java_lang_Runtime(env);
  register_java_lang_String(env);
1196
  register_java_lang_StringFactory(env);
Andreas Gampe's avatar
Andreas Gampe committed
1197 1198 1199 1200 1201
  register_java_lang_System(env);
  register_java_lang_Thread(env);
  register_java_lang_Throwable(env);
  register_java_lang_VMClassLoader(env);
  register_java_util_concurrent_atomic_AtomicLong(env);
1202
  register_libcore_util_CharsetUtils(env);
Andreas Gampe's avatar
Andreas Gampe committed
1203 1204 1205
  register_org_apache_harmony_dalvik_ddmc_DdmServer(env);
  register_org_apache_harmony_dalvik_ddmc_DdmVmInternal(env);
  register_sun_misc_Unsafe(env);
1206 1207
}

1208
void Runtime::DumpForSigQuit(std::ostream& os) {
1209 1210
  GetClassLinker()->DumpForSigQuit(os);
  GetInternTable()->DumpForSigQuit(os);
1211
  GetJavaVM()->DumpForSigQuit(os);
1212
  GetHeap()->DumpForSigQuit(os);
1213
  TrackedAllocators::Dump(os);
1214
  os << "\n";
Elliott Hughes's avatar
Elliott Hughes committed
1215

1216
  thread_list_->DumpForSigQuit(os);
1217
  BaseMutex::DumpAll(os);
1218 1219
}

1220
void Runtime::DumpLockHolders(std::ostream& os) {
1221
  uint64_t mutator_lock_owner = Locks::mutator_lock_->GetExclusiveOwnerTid();
1222 1223 1224
  pid_t thread_list_lock_owner = GetThreadList()->GetLockOwner();
  pid_t classes_lock_owner = GetClassLinker()->GetClassesLockOwner();
  pid_t dex_lock_owner = GetClassLinker()->GetDexLockOwner();
Ian Rogers's avatar
Ian Rogers committed
1225 1226
  if ((thread_list_lock_owner | classes_lock_owner | dex_lock_owner) != 0) {
    os << "Mutator lock exclusive owner tid: " << mutator_lock_owner << "\n"
1227 1228 1229 1230 1231 1232
       << "ThreadList lock owner tid: " << thread_list_lock_owner << "\n"
       << "ClassLinker classes lock owner tid: " << classes_lock_owner << "\n"
       << "ClassLinker dex lock owner tid: " << dex_lock_owner << "\n";
  }
}

1233 1234 1235
void Runtime::SetStatsEnabled(bool new_state) {
  Thread* self = Thread::Current();
  MutexLock mu(self, *Locks::instrument_entrypoints_lock_);
1236 1237 1238
  if (new_state == true) {
    GetStats()->Clear(~0);
    // TODO: wouldn't it make more sense to clear _all_ threads' stats?
1239 1240 1241 1242 1243 1244
    self->GetStats()->Clear(~0);
    if (stats_enabled_ != new_state) {
      GetInstrumentation()->InstrumentQuickAllocEntryPointsLocked();
    }
  } else if (stats_enabled_ != new_state) {
    GetInstrumentation()->UninstrumentQuickAllocEntryPointsLocked();
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277
  }
  stats_enabled_ = new_state;
}

void Runtime::ResetStats(int kinds) {
  GetStats()->Clear(kinds & 0xffff);
  // TODO: wouldn't it make more sense to clear _all_ threads' stats?
  Thread::Current()->GetStats()->Clear(kinds >> 16);
}

int32_t Runtime::GetStat(int kind) {
  RuntimeStats* stats;
  if (kind < (1<<16)) {
    stats = GetStats();
  } else {
    stats = Thread::Current()->GetStats();
    kind >>= 16;
  }
  switch (kind) {
  case KIND_ALLOCATED_OBJECTS:
    return stats->allocated_objects;
  case KIND_ALLOCATED_BYTES:
    return stats->allocated_bytes;
  case KIND_FREED_OBJECTS:
    return stats->freed_objects;
  case KIND_FREED_BYTES:
    return stats->freed_bytes;
  case KIND_GC_INVOCATIONS:
    return stats->gc_for_alloc_count;
  case KIND_CLASS_INIT_COUNT:
    return stats->class_init_count;
  case KIND_CLASS_INIT_TIME:
    // Convert ns to us, reduce to 32 bits.
1278
    return static_cast<int>(stats->class_init_time_ns / 1000);
1279 1280 1281 1282 1283 1284
  case KIND_EXT_ALLOCATED_OBJECTS:
  case KIND_EXT_ALLOCATED_BYTES:
  case KIND_EXT_FREED_OBJECTS:
  case KIND_EXT_FREED_BYTES:
    return 0;  // backward compatibility
  default:
Elliott Hughes's avatar
Elliott Hughes committed
1285
    LOG(FATAL) << "Unknown statistic " << kind;
1286
    return -1;  // unreachable
1287 1288 1289
  }
}

1290
void Runtime::BlockSignals() {
1291 1292
  SignalSet signals;
  signals.Add(SIGPIPE);
1293
  // SIGQUIT is used to dump the runtime's state (including stack traces).
1294
  signals.Add(SIGQUIT);
Elliott Hughes's avatar
Elliott Hughes committed
1295
  // SIGUSR1 is used to initiate a GC.
1296 1297
  signals.Add(SIGUSR1);
  signals.Block();
1298 1299
}

1300 1301
bool Runtime::AttachCurrentThread(const char* thread_name, bool as_daemon, jobject thread_group,
                                  bool create_peer) {
Mathieu Chartier's avatar
Mathieu Chartier committed
1302
  return Thread::Attach(thread_name, as_daemon, thread_group, create_peer) != nullptr;
1303 1304
}

1305
void Runtime::DetachCurrentThread() {
1306
  Thread* self = Thread::Current();
Mathieu Chartier's avatar
Mathieu Chartier committed
1307
  if (self == nullptr) {
1308 1309
    LOG(FATAL) << "attempting to detach thread that is not attached";
  }
1310
  if (self->HasManagedStack()) {
1311 1312
    LOG(FATAL) << *Thread::Current() << " attempting to detach while still running code";
  }
Ian Rogers's avatar
Ian Rogers committed
1313
  thread_list_->Unregister(self);
1314 1315
}

1316
mirror::Throwable* Runtime::GetPreAllocatedOutOfMemoryError() {
1317
  mirror::Throwable* oome = pre_allocated_OutOfMemoryError_.Read();
1318
  if (oome == nullptr) {
1319 1320
    LOG(ERROR) << "Failed to return pre-allocated OOME";
  }
1321
  return oome;
1322 1323
}

1324 1325 1326 1327 1328 1329 1330 1331
mirror::Throwable* Runtime::GetPreAllocatedNoClassDefFoundError() {
  mirror::Throwable* ncdfe = pre_allocated_NoClassDefFoundError_.Read();
  if (ncdfe == nullptr) {
    LOG(ERROR) << "Failed to return pre-allocated NoClassDefFoundError";
  }
  return ncdfe;
}

1332
void Runtime::VisitConstantRoots(RootVisitor* visitor) {
1333
  // Visit the classes held as static in mirror classes, these can be visited concurrently and only
1334
  // need to be visited once per GC since they never change.
1335
  mirror::Class::VisitRoots(visitor);
1336
  mirror::Constructor::VisitRoots(visitor);
1337
  mirror::Reference::VisitRoots(visitor);
1338
  mirror::Method::VisitRoots(visitor);
1339 1340 1341 1342
  mirror::StackTraceElement::VisitRoots(visitor);
  mirror::String::VisitRoots(visitor);
  mirror::Throwable::VisitRoots(visitor);
  mirror::Field::VisitRoots(visitor);
Mathieu Chartier's avatar
Mathieu Chartier committed
1343
  // Visit all the primitive array types classes.
1344 1345 1346 1347 1348 1349 1350 1351
  mirror::PrimitiveArray<uint8_t>::VisitRoots(visitor);   // BooleanArray
  mirror::PrimitiveArray<int8_t>::VisitRoots(visitor);    // ByteArray
  mirror::PrimitiveArray<uint16_t>::VisitRoots(visitor);  // CharArray
  mirror::PrimitiveArray<double>::VisitRoots(visitor);    // DoubleArray
  mirror::PrimitiveArray<float>::VisitRoots(visitor);     // FloatArray
  mirror::PrimitiveArray<int32_t>::VisitRoots(visitor);   // IntArray
  mirror::PrimitiveArray<int64_t>::VisitRoots(visitor);   // LongArray
  mirror::PrimitiveArray<int16_t>::VisitRoots(visitor);   // ShortArray
1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369
  // Visiting the roots of these ArtMethods is not currently required since all the GcRoots are
  // null.
  BufferedRootVisitor<16> buffered_visitor(visitor, RootInfo(kRootVMInternal));
  if (HasResolutionMethod()) {
    resolution_method_->VisitRoots(buffered_visitor);
  }
  if (HasImtConflictMethod()) {
    imt_conflict_method_->VisitRoots(buffered_visitor);
  }
  if (imt_unimplemented_method_ != nullptr) {
    imt_unimplemented_method_->VisitRoots(buffered_visitor);
  }
  for (size_t i = 0; i < kLastCalleeSaveType; ++i) {
    auto* m = reinterpret_cast<ArtMethod*>(callee_save_methods_[i]);
    if (m != nullptr) {
      m->VisitRoots(buffered_visitor);
    }
  }
1370 1371
}

1372 1373 1374
void Runtime::VisitConcurrentRoots(RootVisitor* visitor, VisitRootFlags flags) {
  intern_table_->VisitRoots(visitor, flags);
  class_linker_->VisitRoots(visitor, flags);
1375 1376
  if ((flags & kVisitRootFlagNewRoots) == 0) {
    // Guaranteed to have no new roots in the constant roots.
1377
    VisitConstantRoots(visitor);
1378 1379 1380
  }
}

1381
void Runtime::VisitTransactionRoots(RootVisitor* visitor) {
1382
  if (preinitialization_transaction_ != nullptr) {
1383
    preinitialization_transaction_->VisitRoots(visitor);
1384 1385 1386
  }
}

1387 1388 1389 1390 1391 1392 1393
void Runtime::VisitNonThreadRoots(RootVisitor* visitor) {
  java_vm_->VisitRoots(visitor);
  sentinel_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
  pre_allocated_OutOfMemoryError_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
  pre_allocated_NoClassDefFoundError_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
  verifier::MethodVerifier::VisitStaticRoots(visitor);
  VisitTransactionRoots(visitor);
Brian Carlstrom's avatar
Brian Carlstrom committed
1394 1395
}

1396 1397 1398
void Runtime::VisitNonConcurrentRoots(RootVisitor* visitor) {
  thread_list_->VisitRoots(visitor);
  VisitNonThreadRoots(visitor);
Mathieu Chartier's avatar
Mathieu Chartier committed
1399 1400
}

1401 1402
void Runtime::VisitThreadRoots(RootVisitor* visitor) {
  thread_list_->VisitRoots(visitor);
1403 1404 1405 1406 1407 1408 1409
}

size_t Runtime::FlipThreadRoots(Closure* thread_flip_visitor, Closure* flip_callback,
                                gc::collector::GarbageCollector* collector) {
  return thread_list_->FlipThreadRoots(thread_flip_visitor, flip_callback, collector);
}

1410 1411 1412
void Runtime::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
  VisitNonConcurrentRoots(visitor);
  VisitConcurrentRoots(visitor, flags);
1413 1414
}

1415
void Runtime::VisitImageRoots(RootVisitor* visitor) {
Mathieu Chartier's avatar
Mathieu Chartier committed
1416 1417 1418 1419 1420 1421 1422 1423
  for (auto* space : GetHeap()->GetContinuousSpaces()) {
    if (space->IsImageSpace()) {
      auto* image_space = space->AsImageSpace();
      const auto& image_header = image_space->GetImageHeader();
      for (size_t i = 0; i < ImageHeader::kImageRootsMax; ++i) {
        auto* obj = image_header.GetImageRoot(static_cast<ImageHeader::ImageRoot>(i));
        if (obj != nullptr) {
          auto* after_obj = obj;
1424
          visitor->VisitRoot(&after_obj, RootInfo(kRootStickyClass));
Mathieu Chartier's avatar
Mathieu Chartier committed
1425 1426 1427 1428 1429 1430 1431
          CHECK_EQ(after_obj, obj);
        }
      }
    }
  }
}

1432 1433
ArtMethod* Runtime::CreateImtConflictMethod() {
  auto* method = Runtime::Current()->GetClassLinker()->CreateRuntimeMethod();
1434
  // When compiling, the code pointer will get set later when the image is loaded.
1435
  if (IsAotCompiler()) {
1436 1437
    size_t pointer_size = GetInstructionSetPointerSize(instruction_set_);
    method->SetEntryPointFromQuickCompiledCodePtrSize(nullptr, pointer_size);
1438
  } else {
1439
    method->SetEntryPointFromQuickCompiledCode(GetQuickImtConflictStub());
1440
  }
1441
  return method;
1442 1443
}

1444 1445 1446 1447
void Runtime::SetImtConflictMethod(ArtMethod* method) {
  CHECK(method != nullptr);
  CHECK(method->IsRuntimeMethod());
  imt_conflict_method_ = method;
Mathieu Chartier's avatar
Mathieu Chartier committed
1448 1449
}

1450 1451
ArtMethod* Runtime::CreateResolutionMethod() {
  auto* method = Runtime::Current()->GetClassLinker()->CreateRuntimeMethod();
1452
  // When compiling, the code pointer will get set later when the image is loaded.
1453
  if (IsAotCompiler()) {
1454 1455
    size_t pointer_size = GetInstructionSetPointerSize(instruction_set_);
    method->SetEntryPointFromQuickCompiledCodePtrSize(nullptr, pointer_size);
1456
  } else {
1457
    method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
1458
  }
1459
  return method;
1460 1461
}

1462 1463
ArtMethod* Runtime::CreateCalleeSaveMethod() {
  auto* method = Runtime::Current()->GetClassLinker()->CreateRuntimeMethod();
1464 1465
  size_t pointer_size = GetInstructionSetPointerSize(instruction_set_);
  method->SetEntryPointFromQuickCompiledCodePtrSize(nullptr, pointer_size);
1466
  DCHECK_NE(instruction_set_, kNone);
1467 1468
  DCHECK(method->IsRuntimeMethod());
  return method;
1469 1470
}

1471 1472 1473 1474
void Runtime::DisallowNewSystemWeaks() {
  monitor_list_->DisallowNewMonitors();
  intern_table_->DisallowNewInterns();
  java_vm_->DisallowNewWeakGlobals();
1475 1476 1477 1478 1479
  // TODO: add a similar call for heap.allocation_records_, otherwise some of the newly allocated
  // objects that are not marked might be swept from the records, making the records incomplete.
  // It is safe for now since the only effect is that those objects do not have allocation records.
  // The number of such objects should be small, and current allocation tracker cannot collect
  // allocation records for all objects anyway.
1480 1481 1482 1483 1484 1485 1486 1487
}

void Runtime::AllowNewSystemWeaks() {
  monitor_list_->AllowNewMonitors();
  intern_table_->AllowNewInterns();
  java_vm_->AllowNewWeakGlobals();
}

1488 1489 1490 1491 1492 1493 1494 1495
void Runtime::EnsureNewSystemWeaksDisallowed() {
  // Lock and unlock the system weak locks once to ensure that no
  // threads are still in the middle of adding new system weaks.
  monitor_list_->EnsureNewMonitorsDisallowed();
  intern_table_->EnsureNewInternsDisallowed();
  java_vm_->EnsureNewWeakGlobalsDisallowed();
}

1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506
void Runtime::SetInstructionSet(InstructionSet instruction_set) {
  instruction_set_ = instruction_set;
  if ((instruction_set_ == kThumb2) || (instruction_set_ == kArm)) {
    for (int i = 0; i != kLastCalleeSaveType; ++i) {
      CalleeSaveType type = static_cast<CalleeSaveType>(i);
      callee_save_method_frame_infos_[i] = arm::ArmCalleeSaveMethodFrameInfo(type);
    }
  } else if (instruction_set_ == kMips) {
    for (int i = 0; i != kLastCalleeSaveType; ++i) {
      CalleeSaveType type = static_cast<CalleeSaveType>(i);
      callee_save_method_frame_infos_[i] = mips::MipsCalleeSaveMethodFrameInfo(type);
1507 1508 1509 1510 1511
    }
  } else if (instruction_set_ == kMips64) {
    for (int i = 0; i != kLastCalleeSaveType; ++i) {
      CalleeSaveType type = static_cast<CalleeSaveType>(i);
      callee_save_method_frame_infos_[i] = mips64::Mips64CalleeSaveMethodFrameInfo(type);
1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532
    }
  } else if (instruction_set_ == kX86) {
    for (int i = 0; i != kLastCalleeSaveType; ++i) {
      CalleeSaveType type = static_cast<CalleeSaveType>(i);
      callee_save_method_frame_infos_[i] = x86::X86CalleeSaveMethodFrameInfo(type);
    }
  } else if (instruction_set_ == kX86_64) {
    for (int i = 0; i != kLastCalleeSaveType; ++i) {
      CalleeSaveType type = static_cast<CalleeSaveType>(i);
      callee_save_method_frame_infos_[i] = x86_64::X86_64CalleeSaveMethodFrameInfo(type);
    }
  } else if (instruction_set_ == kArm64) {
    for (int i = 0; i != kLastCalleeSaveType; ++i) {
      CalleeSaveType type = static_cast<CalleeSaveType>(i);
      callee_save_method_frame_infos_[i] = arm64::Arm64CalleeSaveMethodFrameInfo(type);
    }
  } else {
    UNIMPLEMENTED(FATAL) << instruction_set_;
  }
}

1533
void Runtime::SetCalleeSaveMethod(ArtMethod* method, CalleeSaveType type) {
1534
  DCHECK_LT(static_cast<int>(type), static_cast<int>(kLastCalleeSaveType));
1535 1536
  CHECK(method != nullptr);
  callee_save_methods_[type] = reinterpret_cast<uintptr_t>(method);
Brian Carlstrom's avatar
Brian Carlstrom committed
1537 1538
}

1539 1540 1541
void Runtime::StartProfiler(const char* profile_output_filename) {
  profile_output_filename_ = profile_output_filename;
  profiler_started_ =
1542
      BackgroundMethodSamplingProfiler::Start(profile_output_filename_, profiler_options_);
Dave Allison's avatar
Dave Allison committed
1543
}
Sebastien Hertz's avatar
Sebastien Hertz committed
1544 1545 1546

// Transaction support.
void Runtime::EnterTransactionMode(Transaction* transaction) {
Mathieu Chartier's avatar
Mathieu Chartier committed
1547
  DCHECK(IsAotCompiler());
Sebastien Hertz's avatar
Sebastien Hertz committed
1548 1549
  DCHECK(transaction != nullptr);
  DCHECK(!IsActiveTransaction());
Sebastien Hertz's avatar
Sebastien Hertz committed
1550
  preinitialization_transaction_ = transaction;
Sebastien Hertz's avatar
Sebastien Hertz committed
1551 1552 1553
}

void Runtime::ExitTransactionMode() {
Mathieu Chartier's avatar
Mathieu Chartier committed
1554
  DCHECK(IsAotCompiler());
Sebastien Hertz's avatar
Sebastien Hertz committed
1555
  DCHECK(IsActiveTransaction());
Sebastien Hertz's avatar
Sebastien Hertz committed
1556
  preinitialization_transaction_ = nullptr;
Sebastien Hertz's avatar
Sebastien Hertz committed
1557 1558
}

Sebastien Hertz's avatar
Sebastien Hertz committed
1559 1560 1561 1562
bool Runtime::IsTransactionAborted() const {
  if (!IsActiveTransaction()) {
    return false;
  } else {
1563
    DCHECK(IsAotCompiler());
Sebastien Hertz's avatar
Sebastien Hertz committed
1564 1565 1566 1567
    return preinitialization_transaction_->IsAborted();
  }
}

1568
void Runtime::AbortTransactionAndThrowAbortError(Thread* self, const std::string& abort_message) {
1569
  DCHECK(IsAotCompiler());
Sebastien Hertz's avatar
Sebastien Hertz committed
1570
  DCHECK(IsActiveTransaction());
Sebastien Hertz's avatar
Sebastien Hertz committed
1571 1572 1573
  // Throwing an exception may cause its class initialization. If we mark the transaction
  // aborted before that, we may warn with a false alarm. Throwing the exception before
  // marking the transaction aborted avoids that.
1574
  preinitialization_transaction_->ThrowAbortError(self, &abort_message);
Sebastien Hertz's avatar
Sebastien Hertz committed
1575 1576 1577
  preinitialization_transaction_->Abort(abort_message);
}

1578
void Runtime::ThrowTransactionAbortError(Thread* self) {
1579
  DCHECK(IsAotCompiler());
Sebastien Hertz's avatar
Sebastien Hertz committed
1580
  DCHECK(IsActiveTransaction());
1581 1582
  // Passing nullptr means we rethrow an exception with the earlier transaction abort message.
  preinitialization_transaction_->ThrowAbortError(self, nullptr);
Sebastien Hertz's avatar
Sebastien Hertz committed
1583 1584
}

1585 1586
void Runtime::RecordWriteFieldBoolean(mirror::Object* obj, MemberOffset field_offset,
                                      uint8_t value, bool is_volatile) const {
1587
  DCHECK(IsAotCompiler());
1588 1589 1590 1591 1592 1593
  DCHECK(IsActiveTransaction());
  preinitialization_transaction_->RecordWriteFieldBoolean(obj, field_offset, value, is_volatile);
}

void Runtime::RecordWriteFieldByte(mirror::Object* obj, MemberOffset field_offset,
                                   int8_t value, bool is_volatile) const {
1594
  DCHECK(IsAotCompiler());
1595 1596 1597 1598 1599 1600
  DCHECK(IsActiveTransaction());
  preinitialization_transaction_->RecordWriteFieldByte(obj, field_offset, value, is_volatile);
}

void Runtime::RecordWriteFieldChar(mirror::Object* obj, MemberOffset field_offset,
                                   uint16_t value, bool is_volatile) const {
1601
  DCHECK(IsAotCompiler());
1602 1603 1604 1605 1606 1607
  DCHECK(IsActiveTransaction());
  preinitialization_transaction_->RecordWriteFieldChar(obj, field_offset, value, is_volatile);
}

void Runtime::RecordWriteFieldShort(mirror::Object* obj, MemberOffset field_offset,
                                    int16_t value, bool is_volatile) const {
1608
  DCHECK(IsAotCompiler());
1609 1610 1611 1612
  DCHECK(IsActiveTransaction());
  preinitialization_transaction_->RecordWriteFieldShort(obj, field_offset, value, is_volatile);
}

Sebastien Hertz's avatar
Sebastien Hertz committed
1613 1614
void Runtime::RecordWriteField32(mirror::Object* obj, MemberOffset field_offset,
                                 uint32_t value, bool is_volatile) const {
Mathieu Chartier's avatar
Mathieu Chartier committed
1615
  DCHECK(IsAotCompiler());
Sebastien Hertz's avatar
Sebastien Hertz committed
1616
  DCHECK(IsActiveTransaction());
Sebastien Hertz's avatar
Sebastien Hertz committed
1617
  preinitialization_transaction_->RecordWriteField32(obj, field_offset, value, is_volatile);
Sebastien Hertz's avatar
Sebastien Hertz committed
1618 1619 1620 1621
}

void Runtime::RecordWriteField64(mirror::Object* obj, MemberOffset field_offset,
                                 uint64_t value, bool is_volatile) const {
Mathieu Chartier's avatar
Mathieu Chartier committed
1622
  DCHECK(IsAotCompiler());
Sebastien Hertz's avatar
Sebastien Hertz committed
1623
  DCHECK(IsActiveTransaction());
Sebastien Hertz's avatar
Sebastien Hertz committed
1624
  preinitialization_transaction_->RecordWriteField64(obj, field_offset, value, is_volatile);
Sebastien Hertz's avatar
Sebastien Hertz committed
1625 1626 1627 1628
}

void Runtime::RecordWriteFieldReference(mirror::Object* obj, MemberOffset field_offset,
                                        mirror::Object* value, bool is_volatile) const {
Mathieu Chartier's avatar
Mathieu Chartier committed
1629
  DCHECK(IsAotCompiler());
Sebastien Hertz's avatar
Sebastien Hertz committed
1630
  DCHECK(IsActiveTransaction());
Sebastien Hertz's avatar
Sebastien Hertz committed
1631
  preinitialization_transaction_->RecordWriteFieldReference(obj, field_offset, value, is_volatile);
Sebastien Hertz's avatar
Sebastien Hertz committed
1632 1633 1634
}

void Runtime::RecordWriteArray(mirror::Array* array, size_t index, uint64_t value) const {
Mathieu Chartier's avatar
Mathieu Chartier committed
1635
  DCHECK(IsAotCompiler());
Sebastien Hertz's avatar
Sebastien Hertz committed
1636
  DCHECK(IsActiveTransaction());
Sebastien Hertz's avatar
Sebastien Hertz committed
1637
  preinitialization_transaction_->RecordWriteArray(array, index, value);
Sebastien Hertz's avatar
Sebastien Hertz committed
1638 1639
}

1640
void Runtime::RecordStrongStringInsertion(mirror::String* s) const {
Mathieu Chartier's avatar
Mathieu Chartier committed
1641
  DCHECK(IsAotCompiler());
Sebastien Hertz's avatar
Sebastien Hertz committed
1642
  DCHECK(IsActiveTransaction());
1643
  preinitialization_transaction_->RecordStrongStringInsertion(s);
Sebastien Hertz's avatar
Sebastien Hertz committed
1644 1645
}

1646
void Runtime::RecordWeakStringInsertion(mirror::String* s) const {
Mathieu Chartier's avatar
Mathieu Chartier committed
1647
  DCHECK(IsAotCompiler());
Sebastien Hertz's avatar
Sebastien Hertz committed
1648
  DCHECK(IsActiveTransaction());
1649
  preinitialization_transaction_->RecordWeakStringInsertion(s);
Sebastien Hertz's avatar
Sebastien Hertz committed
1650 1651
}

1652
void Runtime::RecordStrongStringRemoval(mirror::String* s) const {
Mathieu Chartier's avatar
Mathieu Chartier committed
1653
  DCHECK(IsAotCompiler());
Sebastien Hertz's avatar
Sebastien Hertz committed
1654
  DCHECK(IsActiveTransaction());
1655
  preinitialization_transaction_->RecordStrongStringRemoval(s);
Sebastien Hertz's avatar
Sebastien Hertz committed
1656 1657
}

1658
void Runtime::RecordWeakStringRemoval(mirror::String* s) const {
Mathieu Chartier's avatar
Mathieu Chartier committed
1659
  DCHECK(IsAotCompiler());
Sebastien Hertz's avatar
Sebastien Hertz committed
1660
  DCHECK(IsActiveTransaction());
1661
  preinitialization_transaction_->RecordWeakStringRemoval(s);
Sebastien Hertz's avatar
Sebastien Hertz committed
1662
}
1663 1664 1665 1666 1667

void Runtime::SetFaultMessage(const std::string& message) {
  MutexLock mu(Thread::Current(), fault_message_lock_);
  fault_message_ = message;
}
1668

1669 1670
void Runtime::AddCurrentRuntimeFeaturesAsDex2OatArguments(std::vector<std::string>* argv)
    const {
1671
  if (GetInstrumentation()->InterpretOnly() || UseJit()) {
1672 1673 1674
    argv->push_back("--compiler-filter=interpret-only");
  }

1675 1676 1677
  // Make the dex2oat instruction set match that of the launching runtime. If we have multiple
  // architecture support, dex2oat may be compiled as a different instruction-set than that
  // currently being executed.
Ian Rogers's avatar
Ian Rogers committed
1678 1679 1680
  std::string instruction_set("--instruction-set=");
  instruction_set += GetInstructionSetString(kRuntimeISA);
  argv->push_back(instruction_set);
1681

1682 1683 1684 1685
  std::unique_ptr<const InstructionSetFeatures> features(InstructionSetFeatures::FromCppDefines());
  std::string feature_string("--instruction-set-features=");
  feature_string += features->GetFeatureString();
  argv->push_back(feature_string);
1686 1687
}

1688
void Runtime::UpdateProfilerState(int state) {
1689
  VLOG(profiler) << "Profiler state updated to " << state;
1690
}
Mathieu Chartier's avatar
Mathieu Chartier committed
1691 1692

void Runtime::CreateJit() {
1693
  CHECK(!IsAotCompiler());
1694 1695 1696 1697
  if (GetInstrumentation()->IsForcedInterpretOnly()) {
    // Don't create JIT if forced interpret only.
    return;
  }
Mathieu Chartier's avatar
Mathieu Chartier committed
1698 1699 1700 1701
  std::string error_msg;
  jit_.reset(jit::Jit::Create(jit_options_.get(), &error_msg));
  if (jit_.get() != nullptr) {
    compiler_callbacks_ = jit_->GetCompilerCallbacks();
1702 1703
    jit_->CreateInstrumentationCache(jit_options_->GetCompileThreshold());
    jit_->CreateThreadPool();
Mathieu Chartier's avatar
Mathieu Chartier committed
1704 1705 1706 1707 1708
  } else {
    LOG(WARNING) << "Failed to create JIT " << error_msg;
  }
}

Andreas Gampe's avatar
Andreas Gampe committed
1709 1710 1711 1712 1713 1714 1715 1716
bool Runtime::CanRelocate() const {
  return !IsAotCompiler() || compiler_callbacks_->IsRelocationPossible();
}

bool Runtime::IsCompilingBootImage() const {
  return IsCompiler() && compiler_callbacks_->IsBootImage();
}

1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728
void Runtime::SetResolutionMethod(ArtMethod* method) {
  CHECK(method != nullptr);
  CHECK(method->IsRuntimeMethod()) << method;
  resolution_method_ = method;
}

void Runtime::SetImtUnimplementedMethod(ArtMethod* method) {
  CHECK(method != nullptr);
  CHECK(method->IsRuntimeMethod());
  imt_unimplemented_method_ = method;
}

1729
}  // namespace art