blob: 3f80260a289ce64838d17323e5102309df94d9d0 [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 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 */
Carl Shapiro1fb86202011-06-27 17:43:13 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "runtime.h"
Carl Shapiro1fb86202011-06-27 17:43:13 -070018
Brian Carlstromdbf05b72011-12-15 00:55:24 -080019#include <signal.h>
20
Elliott Hughesffe67362011-07-17 12:09:27 -070021#include <cstdio>
22#include <cstdlib>
Brian Carlstrom8a436592011-08-15 21:27:23 -070023#include <limits>
Carl Shapiro2ed144c2011-07-26 16:52:08 -070024#include <vector>
TDYa127b92bcab2012-04-08 00:09:51 -070025#include <fstream>
Elliott Hughesffe67362011-07-17 12:09:27 -070026
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070027#include "class_linker.h"
Brian Carlstromaded5f72011-10-07 17:15:04 -070028#include "class_loader.h"
Elliott Hughes0f3c5532012-03-30 14:51:51 -070029#include "constants_arm.h"
30#include "constants_x86.h"
Elliott Hughes3bb81562011-10-21 18:52:59 -070031#include "debugger.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070032#include "heap.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070033#include "image.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070034#include "intern_table.h"
Elliott Hughesc5f7c912011-08-18 14:00:42 -070035#include "jni_internal.h"
Elliott Hughes32d6e1e2011-10-11 14:47:44 -070036#include "monitor.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070037#include "oat_file.h"
Elliott Hughes726079d2011-10-07 18:43:44 -070038#include "ScopedLocalRef.h"
Elliott Hughese27955c2011-08-26 15:21:24 -070039#include "signal_catcher.h"
Elliott Hughes457005c2012-04-16 13:54:25 -070040#include "signal_set.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070041#include "space.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070042#include "thread.h"
Elliott Hughes8daa0922011-09-11 13:46:25 -070043#include "thread_list.h"
jeffhaob5e81852012-03-12 11:15:45 -070044#include "trace.h"
Elliott Hughes3bb81562011-10-21 18:52:59 -070045#include "UniquePtr.h"
Ian Rogers776ac1f2012-04-13 23:36:36 -070046#include "verifier/method_verifier.h"
Carl Shapiro61e019d2011-07-14 16:53:09 -070047
Elliott Hughes90a33692011-08-30 13:27:07 -070048// TODO: this drags in cutil/log.h, which conflicts with our logging.h.
49#include "JniConstants.h"
50
Carl Shapiro1fb86202011-06-27 17:43:13 -070051namespace art {
52
Carl Shapiro2ed144c2011-07-26 16:52:08 -070053Runtime* Runtime::instance_ = NULL;
54
Elliott Hughesdcc24742011-09-07 14:02:44 -070055Runtime::Runtime()
Elliott Hughesd9c67be2012-02-02 19:54:06 -080056 : is_compiler_(false),
57 is_zygote_(false),
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -070058 default_stack_size_(Thread::kDefaultStackSize),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080059 heap_(NULL),
Elliott Hughesc33a32b2011-10-11 18:18:07 -070060 monitor_list_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -070061 thread_list_(NULL),
62 intern_table_(NULL),
63 class_linker_(NULL),
64 signal_catcher_(NULL),
65 java_vm_(NULL),
Brian Carlstrom16192862011-09-12 17:50:06 -070066 jni_stub_array_(NULL),
Brian Carlstrome24fa612011-09-29 00:53:55 -070067 abstract_method_error_stub_array_(NULL),
Ian Rogers19846512012-02-24 11:42:47 -080068 resolution_method_(NULL),
Ian Rogers7c3757f2012-02-15 17:18:53 -080069 system_class_loader_(NULL),
Elliott Hughes6b355752012-01-13 16:49:08 -080070 shutting_down_(false),
Elliott Hughesdcc24742011-09-07 14:02:44 -070071 started_(false),
72 vfprintf_(NULL),
73 exit_(NULL),
Elliott Hughes9d5ccec2011-09-19 13:19:50 -070074 abort_(NULL),
jeffhao2692b572011-12-16 15:42:28 -080075 stats_enabled_(false),
Ian Rogers776ac1f2012-04-13 23:36:36 -070076 method_trace_(0),
77 method_trace_file_size_(0),
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080078 tracer_(NULL),
79 use_compile_time_class_path_(false) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -070080 for (int i = 0; i < Runtime::kLastTrampolineMethodType; i++) {
81 resolution_stub_array_[i] = NULL;
82 }
83 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
84 callee_save_method_[i] = NULL;
85 }
Elliott Hughesdcc24742011-09-07 14:02:44 -070086}
87
Carl Shapiro61e019d2011-07-14 16:53:09 -070088Runtime::~Runtime() {
Elliott Hughes6b355752012-01-13 16:49:08 -080089 shutting_down_ = true;
90
jeffhaob5e81852012-03-12 11:15:45 -070091 if (IsMethodTracingActive()) {
92 Trace::Shutdown();
93 }
94
Elliott Hughes5fe594f2011-09-08 12:33:17 -070095 // Make sure our internal threads are dead before we start tearing down things they're using.
Elliott Hughese52e49b2012-04-02 16:05:44 -070096 Dbg::StopJdwp();
Elliott Hughes5fe594f2011-09-08 12:33:17 -070097 delete signal_catcher_;
98
Elliott Hughes038a8062011-09-18 14:12:41 -070099 // Make sure all other non-daemon threads have terminated, and all daemon threads are suspended.
Elliott Hughes93e74e82011-09-13 11:07:03 -0700100 delete thread_list_;
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700101 delete monitor_list_;
Elliott Hughes93e74e82011-09-13 11:07:03 -0700102
Carl Shapiro61e019d2011-07-14 16:53:09 -0700103 delete class_linker_;
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800104 delete heap_;
Logan Chiendd361c92012-04-10 23:40:37 +0800105#if defined(ART_USE_LLVM_COMPILER)
Ian Rogers776ac1f2012-04-13 23:36:36 -0700106 verifier::MethodVerifier::DeleteInferredRegCategoryMaps();
Logan Chiendd361c92012-04-10 23:40:37 +0800107#endif
Ian Rogers776ac1f2012-04-13 23:36:36 -0700108 verifier::MethodVerifier::DeleteGcMaps();
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700109 delete intern_table_;
Elliott Hughesc5f7c912011-08-18 14:00:42 -0700110 delete java_vm_;
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700111 Thread::Shutdown();
Carl Shapiro4acf4642011-07-26 18:54:13 -0700112 // TODO: acquire a static mutex on Runtime to avoid racing.
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700113 CHECK(instance_ == NULL || instance_ == this);
Carl Shapiro4acf4642011-07-26 18:54:13 -0700114 instance_ = NULL;
Carl Shapiro61e019d2011-07-14 16:53:09 -0700115}
116
Elliott Hughescac6cc72011-11-03 20:31:21 -0700117static bool gAborting = false;
118
Elliott Hughese0918552011-10-28 17:18:29 -0700119struct AbortState {
120 void Dump(std::ostream& os) {
Elliott Hughescac6cc72011-11-03 20:31:21 -0700121 if (gAborting) {
122 os << "Runtime aborting --- recursively, so no thread-specific detail!\n";
123 return;
124 }
125 gAborting = true;
Elliott Hughese0918552011-10-28 17:18:29 -0700126 os << "Runtime aborting...\n";
Elliott Hughes6c7d2442012-02-01 18:40:47 -0800127 if (Runtime::Current() == NULL) {
128 os << "(Runtime does not yet exist!)\n";
129 return;
130 }
Elliott Hughese0918552011-10-28 17:18:29 -0700131 Thread* self = Thread::Current();
132 if (self == NULL) {
133 os << "(Aborting thread was not attached to runtime!)\n";
134 } else {
Elliott Hughes899e7892012-01-24 14:57:32 -0800135 self->Dump(os);
136 if (self->IsExceptionPending()) {
137 os << "Pending " << PrettyTypeOf(self->GetException()) << " on thread:\n"
138 << self->GetException()->Dump();
139 }
Elliott Hughese0918552011-10-28 17:18:29 -0700140 }
141 }
142};
143
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800144static Mutex& GetAbortLock() {
145 static Mutex abort_lock("abort lock");
146 return abort_lock;
147}
148
Elliott Hughes8593fdb2012-04-21 20:53:44 -0700149void Runtime::Abort() {
Elliott Hughes131aef82012-01-27 11:53:35 -0800150 // Ensure that we don't have multiple threads trying to abort at once,
151 // which would result in significantly worse diagnostics.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800152 MutexLock mu(GetAbortLock());
Elliott Hughes131aef82012-01-27 11:53:35 -0800153
Elliott Hughesffe67362011-07-17 12:09:27 -0700154 // Get any pending output out of the way.
155 fflush(NULL);
156
157 // Many people have difficulty distinguish aborts from crashes,
158 // so be explicit.
Elliott Hughese0918552011-10-28 17:18:29 -0700159 AbortState state;
Elliott Hughes9ee5f9c2012-02-03 18:33:16 -0800160 LOG(INTERNAL_FATAL) << Dumpable<AbortState>(state);
Elliott Hughesffe67362011-07-17 12:09:27 -0700161
Elliott Hughes8593fdb2012-04-21 20:53:44 -0700162 // Call the abort hook if we have one.
Brian Carlstrom6ea095a2011-08-16 15:26:54 -0700163 if (Runtime::Current() != NULL && Runtime::Current()->abort_ != NULL) {
164 Runtime::Current()->abort_();
165 // notreached
166 }
167
Elliott Hughesffe67362011-07-17 12:09:27 -0700168 // If we call abort(3) on a device, all threads in the process
Carl Shapiro69759ea2011-07-21 18:13:35 -0700169 // receive SIGABRT. debuggerd dumps the stack trace of the main
170 // thread, whether or not that was the thread that failed. By
171 // stuffing a value into a bogus address, we cause a segmentation
Elliott Hughesffe67362011-07-17 12:09:27 -0700172 // fault in the current thread, and get a useful log from debuggerd.
Elliott Hughes81ff3182012-03-23 20:35:56 -0700173 // We can also trivially tell the difference between a crash and
Elliott Hughesffe67362011-07-17 12:09:27 -0700174 // a deliberate abort by looking at the fault address.
175 *reinterpret_cast<char*>(0xdeadd00d) = 38;
176 abort();
Elliott Hughesffe67362011-07-17 12:09:27 -0700177 // notreached
178}
179
Elliott Hughesbf86d042011-08-31 17:53:14 -0700180void Runtime::CallExitHook(jint status) {
181 if (exit_ != NULL) {
Elliott Hughes34e06962012-04-09 13:55:55 -0700182 ScopedThreadStateChange tsc(Thread::Current(), kNative);
Elliott Hughesbf86d042011-08-31 17:53:14 -0700183 exit_(status);
184 LOG(WARNING) << "Exit hook returned instead of exiting!";
185 }
186}
187
Brian Carlstrom8a436592011-08-15 21:27:23 -0700188// Parse a string of the form /[0-9]+[kKmMgG]?/, which is used to specify
189// memory sizes. [kK] indicates kilobytes, [mM] megabytes, and
190// [gG] gigabytes.
191//
192// "s" should point just past the "-Xm?" part of the string.
Brian Carlstrom8a436592011-08-15 21:27:23 -0700193// "div" specifies a divisor, e.g. 1024 if the value must be a multiple
194// of 1024.
195//
196// The spec says the -Xmx and -Xms options must be multiples of 1024. It
197// doesn't say anything about -Xss.
198//
199// Returns 0 (a useless size) if "s" is malformed or specifies a low or
200// non-evenly-divisible value.
201//
Elliott Hughesc1f143d2011-12-01 17:31:10 -0800202size_t ParseMemoryOption(const char* s, size_t div) {
Brian Carlstrom8a436592011-08-15 21:27:23 -0700203 // strtoul accepts a leading [+-], which we don't want,
204 // so make sure our string starts with a decimal digit.
205 if (isdigit(*s)) {
Elliott Hughes398f64b2012-03-26 18:05:48 -0700206 char* s2;
207 size_t val = strtoul(s, &s2, 10);
Brian Carlstrom8a436592011-08-15 21:27:23 -0700208 if (s2 != s) {
209 // s2 should be pointing just after the number.
210 // If this is the end of the string, the user
211 // has specified a number of bytes. Otherwise,
212 // there should be exactly one more character
213 // that specifies a multiplier.
214 if (*s2 != '\0') {
Brian Carlstromf734cf52011-08-17 16:28:14 -0700215 // The remainder of the string is either a single multiplier
216 // character, or nothing to indicate that the value is in
217 // bytes.
218 char c = *s2++;
219 if (*s2 == '\0') {
220 size_t mul;
221 if (c == '\0') {
222 mul = 1;
223 } else if (c == 'k' || c == 'K') {
224 mul = KB;
225 } else if (c == 'm' || c == 'M') {
226 mul = MB;
227 } else if (c == 'g' || c == 'G') {
228 mul = GB;
Brian Carlstrom8a436592011-08-15 21:27:23 -0700229 } else {
Brian Carlstromf734cf52011-08-17 16:28:14 -0700230 // Unknown multiplier character.
Brian Carlstrom8a436592011-08-15 21:27:23 -0700231 return 0;
232 }
Brian Carlstromf734cf52011-08-17 16:28:14 -0700233
234 if (val <= std::numeric_limits<size_t>::max() / mul) {
235 val *= mul;
236 } else {
237 // Clamp to a multiple of 1024.
238 val = std::numeric_limits<size_t>::max() & ~(1024-1);
239 }
240 } else {
241 // There's more than one character after the numeric part.
242 return 0;
243 }
Brian Carlstrom8a436592011-08-15 21:27:23 -0700244 }
245 // The man page says that a -Xm value must be a multiple of 1024.
246 if (val % div == 0) {
247 return val;
248 }
Carl Shapirofc322c72011-07-27 00:20:01 -0700249 }
250 }
Brian Carlstrom8a436592011-08-15 21:27:23 -0700251 return 0;
Carl Shapirofc322c72011-07-27 00:20:01 -0700252}
253
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800254size_t ParseIntegerOrDie(const std::string& s) {
255 std::string::size_type colon = s.find(':');
256 if (colon == std::string::npos) {
Elliott Hughesbb1e8f02011-10-18 14:14:25 -0700257 LOG(FATAL) << "Missing integer: " << s;
258 }
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800259 const char* begin = &s[colon + 1];
Elliott Hughesbb1e8f02011-10-18 14:14:25 -0700260 char* end;
261 size_t result = strtoul(begin, &end, 10);
262 if (begin == end || *end != '\0') {
263 LOG(FATAL) << "Failed to parse integer in: " << s;
264 }
265 return result;
266}
267
Elliott Hughes0af55432011-08-17 18:37:28 -0700268void LoadJniLibrary(JavaVMExt* vm, const char* name) {
Elliott Hughes6cc332e2012-01-20 22:59:20 -0800269 std::string mapped_name(StringPrintf(OS_SHARED_LIB_FORMAT_STR, name));
Elliott Hughes75770752011-08-24 17:52:38 -0700270 std::string reason;
271 if (!vm->LoadNativeLibrary(mapped_name, NULL, reason)) {
Elliott Hughes0af55432011-08-17 18:37:28 -0700272 LOG(FATAL) << "LoadNativeLibrary failed for \"" << mapped_name << "\": "
273 << reason;
274 }
275}
276
Brian Carlstrom6ea095a2011-08-16 15:26:54 -0700277Runtime::ParsedOptions* Runtime::ParsedOptions::Create(const Options& options, bool ignore_unrecognized) {
Elliott Hughes90a33692011-08-30 13:27:07 -0700278 UniquePtr<ParsedOptions> parsed(new ParsedOptions());
Brian Carlstroma004aa92012-02-08 18:05:09 -0800279 const char* boot_class_path_string = getenv("BOOTCLASSPATH");
280 if (boot_class_path_string != NULL) {
281 parsed->boot_class_path_string_ = boot_class_path_string;
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700282 }
Brian Carlstroma004aa92012-02-08 18:05:09 -0800283 const char* class_path_string = getenv("CLASSPATH");
284 if (class_path_string != NULL) {
285 parsed->class_path_string_ = class_path_string;
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700286 }
Elliott Hughes67d92002012-03-26 15:08:51 -0700287 // -Xcheck:jni is off by default for regular builds but on by default in debug builds.
288 parsed->check_jni_ = kIsDebugBuild;
Elliott Hughes85d15452011-09-16 17:33:01 -0700289
Brian Carlstrom6ea095a2011-08-16 15:26:54 -0700290 parsed->heap_initial_size_ = Heap::kInitialSize;
291 parsed->heap_maximum_size_ = Heap::kMaximumSize;
jeffhaoc1160702011-10-27 15:48:45 -0700292 parsed->heap_growth_limit_ = 0; // 0 means no growth limit
Brian Carlstromf734cf52011-08-17 16:28:14 -0700293 parsed->stack_size_ = Thread::kDefaultStackSize;
294
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800295 parsed->is_compiler_ = false;
Elliott Hughes9ca7a1f2011-10-11 14:29:52 -0700296 parsed->is_zygote_ = false;
297
Elliott Hughesbb1e8f02011-10-18 14:14:25 -0700298 parsed->jni_globals_max_ = 0;
Elliott Hughesfc861622011-10-17 17:57:47 -0700299 parsed->lock_profiling_threshold_ = 0;
300 parsed->hook_is_sensitive_thread_ = NULL;
301
Brian Carlstrom6ea095a2011-08-16 15:26:54 -0700302 parsed->hook_vfprintf_ = vfprintf;
303 parsed->hook_exit_ = exit;
304 parsed->hook_abort_ = abort;
Brian Carlstrom8a436592011-08-15 21:27:23 -0700305
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800306// gLogVerbosity.class_linker = true; // TODO: don't check this in!
307// gLogVerbosity.compiler = true; // TODO: don't check this in!
308// gLogVerbosity.heap = true; // TODO: don't check this in!
309// gLogVerbosity.gc = true; // TODO: don't check this in!
310// gLogVerbosity.jdwp = true; // TODO: don't check this in!
311// gLogVerbosity.jni = true; // TODO: don't check this in!
312// gLogVerbosity.monitor = true; // TODO: don't check this in!
313// gLogVerbosity.startup = true; // TODO: don't check this in!
314// gLogVerbosity.third_party_jni = true; // TODO: don't check this in!
315// gLogVerbosity.threads = true; // TODO: don't check this in!
316
jeffhaob5e81852012-03-12 11:15:45 -0700317 parsed->method_trace_ = false;
318 parsed->method_trace_file_ = "/data/method-trace-file.bin";
319 parsed->method_trace_file_size_ = 10 * MB;
320
Brian Carlstrom8a436592011-08-15 21:27:23 -0700321 for (size_t i = 0; i < options.size(); ++i) {
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800322 const std::string option(options[i].first);
Brian Carlstrom0796af02011-10-12 14:31:45 -0700323 if (true && options[0].first == "-Xzygote") {
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700324 LOG(INFO) << "option[" << i << "]=" << option;
325 }
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800326 if (StartsWith(option, "-Xbootclasspath:")) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800327 parsed->boot_class_path_string_ = option.substr(strlen("-Xbootclasspath:")).data();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700328 } else if (option == "-classpath" || option == "-cp") {
329 // TODO: support -Djava.class.path
330 i++;
331 if (i == options.size()) {
332 // TODO: usage
333 LOG(FATAL) << "Missing required class path value for " << option;
334 return NULL;
335 }
Brian Carlstroma004aa92012-02-08 18:05:09 -0800336 const StringPiece& value = options[i].first;
337 parsed->class_path_string_ = value.data();
338 } else if (option == "bootclasspath") {
339 parsed->boot_class_path_
340 = reinterpret_cast<const std::vector<const DexFile*>*>(options[i].second);
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800341 } else if (StartsWith(option, "-Ximage:")) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800342 parsed->image_ = option.substr(strlen("-Ximage:")).data();
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800343 } else if (StartsWith(option, "-Xcheck:jni")) {
Elliott Hughes515a5bc2011-08-17 11:08:34 -0700344 parsed->check_jni_ = true;
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800345 } else if (StartsWith(option, "-Xrunjdwp:") || StartsWith(option, "-agentlib:jdwp=")) {
346 std::string tail(option.substr(option[1] == 'X' ? 10 : 15));
Elliott Hughes3bb81562011-10-21 18:52:59 -0700347 if (tail == "help" || !Dbg::ParseJdwpOptions(tail)) {
348 LOG(FATAL) << "Example: -Xrunjdwp:transport=dt_socket,address=8000,server=y\n"
349 << "Example: -Xrunjdwp:transport=dt_socket,address=localhost:6500,server=n";
350 return NULL;
351 }
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800352 } else if (StartsWith(option, "-Xms")) {
353 size_t size = ParseMemoryOption(option.substr(strlen("-Xms")).c_str(), 1024);
Brian Carlstromf734cf52011-08-17 16:28:14 -0700354 if (size == 0) {
355 if (ignore_unrecognized) {
356 continue;
357 }
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700358 // TODO: usage
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700359 LOG(FATAL) << "Failed to parse " << option;
Brian Carlstromf734cf52011-08-17 16:28:14 -0700360 return NULL;
361 }
362 parsed->heap_initial_size_ = size;
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800363 } else if (StartsWith(option, "-Xmx")) {
364 size_t size = ParseMemoryOption(option.substr(strlen("-Xmx")).c_str(), 1024);
Brian Carlstromf734cf52011-08-17 16:28:14 -0700365 if (size == 0) {
366 if (ignore_unrecognized) {
367 continue;
368 }
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700369 // TODO: usage
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700370 LOG(FATAL) << "Failed to parse " << option;
Brian Carlstromf734cf52011-08-17 16:28:14 -0700371 return NULL;
372 }
373 parsed->heap_maximum_size_ = size;
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800374 } else if (StartsWith(option, "-XX:HeapGrowthLimit=")) {
375 size_t size = ParseMemoryOption(option.substr(strlen("-XX:HeapGrowthLimit=")).c_str(), 1024);
jeffhaoc1160702011-10-27 15:48:45 -0700376 if (size == 0) {
377 if (ignore_unrecognized) {
378 continue;
379 }
380 // TODO: usage
381 LOG(FATAL) << "Failed to parse " << option;
382 return NULL;
383 }
384 parsed->heap_growth_limit_ = size;
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800385 } else if (StartsWith(option, "-Xss")) {
386 size_t size = ParseMemoryOption(option.substr(strlen("-Xss")).c_str(), 1);
Brian Carlstromf734cf52011-08-17 16:28:14 -0700387 if (size == 0) {
388 if (ignore_unrecognized) {
389 continue;
390 }
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700391 // TODO: usage
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700392 LOG(FATAL) << "Failed to parse " << option;
Brian Carlstromf734cf52011-08-17 16:28:14 -0700393 return NULL;
394 }
395 parsed->stack_size_ = size;
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800396 } else if (StartsWith(option, "-D")) {
397 parsed->properties_.push_back(option.substr(strlen("-D")));
398 } else if (StartsWith(option, "-Xjnitrace:")) {
399 parsed->jni_trace_ = option.substr(strlen("-Xjnitrace:"));
Brian Carlstrom5de8fe52011-10-16 14:10:09 -0700400 } else if (option == "compiler") {
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800401 parsed->is_compiler_ = true;
Elliott Hughes9ca7a1f2011-10-11 14:29:52 -0700402 } else if (option == "-Xzygote") {
403 parsed->is_zygote_ = true;
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800404 } else if (StartsWith(option, "-verbose:")) {
Elliott Hughes0af55432011-08-17 18:37:28 -0700405 std::vector<std::string> verbose_options;
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800406 Split(option.substr(strlen("-verbose:")), ',', verbose_options);
Elliott Hughes0af55432011-08-17 18:37:28 -0700407 for (size_t i = 0; i < verbose_options.size(); ++i) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800408 if (verbose_options[i] == "class") {
409 gLogVerbosity.class_linker = true;
410 } else if (verbose_options[i] == "compiler") {
411 gLogVerbosity.compiler = true;
412 } else if (verbose_options[i] == "heap") {
413 gLogVerbosity.heap = true;
414 } else if (verbose_options[i] == "gc") {
415 gLogVerbosity.gc = true;
416 } else if (verbose_options[i] == "jdwp") {
417 gLogVerbosity.jdwp = true;
418 } else if (verbose_options[i] == "jni") {
419 gLogVerbosity.jni = true;
420 } else if (verbose_options[i] == "monitor") {
421 gLogVerbosity.monitor = true;
422 } else if (verbose_options[i] == "startup") {
423 gLogVerbosity.startup = true;
424 } else if (verbose_options[i] == "third-party-jni") {
425 gLogVerbosity.third_party_jni = true;
426 } else if (verbose_options[i] == "threads") {
427 gLogVerbosity.threads = true;
TDYa127b92bcab2012-04-08 00:09:51 -0700428 } else if (StartsWith(verbose_options[i], "log-to=")) {
429 std::string log_file_name(verbose_options[i].substr(strlen("log-to=")));
430 std::ofstream* log_file = new std::ofstream(log_file_name.c_str());
431 if (log_file->is_open() && log_file->good()) {
432 gLogVerbosity.SetLoggingStream(log_file);
433 } else {
434 LOG(ERROR) << "Fail to open log file: \"" << log_file_name << "\","
435 << " use default logging stream.";
436 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800437 } else {
438 LOG(WARNING) << "Ignoring unknown -verbose option: " << verbose_options[i];
439 }
Elliott Hughes0af55432011-08-17 18:37:28 -0700440 }
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800441 } else if (StartsWith(option, "-Xjnigreflimit:")) {
Elliott Hughesbb1e8f02011-10-18 14:14:25 -0700442 parsed->jni_globals_max_ = ParseIntegerOrDie(option);
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800443 } else if (StartsWith(option, "-Xlockprofthreshold:")) {
Elliott Hughesbb1e8f02011-10-18 14:14:25 -0700444 parsed->lock_profiling_threshold_ = ParseIntegerOrDie(option);
Elliott Hughesf1a5adc2012-02-10 18:09:35 -0800445 } else if (StartsWith(option, "-Xstacktracefile:")) {
Elliott Hughes67d92002012-03-26 15:08:51 -0700446 if (kIsDebugBuild) {
447 // Ignore the zygote and always show stack traces in debug builds.
448 } else {
449 parsed->stack_trace_file_ = option.substr(strlen("-Xstacktracefile:"));
450 }
Elliott Hughesfc861622011-10-17 17:57:47 -0700451 } else if (option == "sensitiveThread") {
452 parsed->hook_is_sensitive_thread_ = reinterpret_cast<bool (*)()>(options[i].second);
Brian Carlstrom6ea095a2011-08-16 15:26:54 -0700453 } else if (option == "vfprintf") {
454 parsed->hook_vfprintf_ = reinterpret_cast<int (*)(FILE *, const char*, va_list)>(options[i].second);
455 } else if (option == "exit") {
456 parsed->hook_exit_ = reinterpret_cast<void(*)(jint)>(options[i].second);
457 } else if (option == "abort") {
458 parsed->hook_abort_ = reinterpret_cast<void(*)()>(options[i].second);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700459 } else if (option == "host-prefix") {
460 parsed->host_prefix_ = reinterpret_cast<const char*>(options[i].second);
Elliott Hughesb3e66df2012-01-12 14:49:18 -0800461 } else if (option == "-Xgenregmap" || option == "-Xgc:precise") {
462 // We silently ignore these for backwards compatibility.
jeffhaob5e81852012-03-12 11:15:45 -0700463 } else if (option == "-Xmethod-trace") {
464 parsed->method_trace_ = true;
465 } else if (StartsWith(option, "-Xmethod-trace-file:")) {
466 parsed->method_trace_file_ = option.substr(strlen("-Xmethod-trace-file:"));
467 } else if (StartsWith(option, "-Xmethod-trace-file-size:")) {
468 parsed->method_trace_file_size_ = ParseIntegerOrDie(option);
Brian Carlstrom8a436592011-08-15 21:27:23 -0700469 } else {
470 if (!ignore_unrecognized) {
Brian Carlstrom6ea095a2011-08-16 15:26:54 -0700471 // TODO: print usage via vfprintf
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700472 LOG(ERROR) << "Unrecognized option " << option;
473 // TODO: this should exit, but for now tolerate unknown options
474 //return NULL;
Brian Carlstrom8a436592011-08-15 21:27:23 -0700475 }
476 }
477 }
478
Brian Carlstrom223f20f2012-02-04 23:06:55 -0800479 if (!parsed->is_compiler_ && parsed->image_.empty()) {
480 parsed->image_ += GetAndroidRoot();
481 parsed->image_ += "/framework/boot.art";
Brian Carlstrom5de8fe52011-10-16 14:10:09 -0700482 }
jeffhaoc1160702011-10-27 15:48:45 -0700483 if (parsed->heap_growth_limit_ == 0) {
484 parsed->heap_growth_limit_ = parsed->heap_maximum_size_;
485 }
Brian Carlstrom5de8fe52011-10-16 14:10:09 -0700486
Elliott Hughescac6cc72011-11-03 20:31:21 -0700487 LOG(INFO) << "Build type: "
Elliott Hughes67d92002012-03-26 15:08:51 -0700488 << (kIsDebugBuild ? "debug" : "optimized")
Elliott Hughescac6cc72011-11-03 20:31:21 -0700489 << "; CheckJNI: " << (parsed->check_jni_ ? "on" : "off");
Elliott Hughes85d15452011-09-16 17:33:01 -0700490
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700491 return parsed.release();
Brian Carlstrom8a436592011-08-15 21:27:23 -0700492}
493
494Runtime* Runtime::Create(const Options& options, bool ignore_unrecognized) {
Carl Shapiro2ed144c2011-07-26 16:52:08 -0700495 // TODO: acquire a static mutex on Runtime to avoid racing.
496 if (Runtime::instance_ != NULL) {
497 return NULL;
498 }
Elliott Hughesdcc24742011-09-07 14:02:44 -0700499 instance_ = new Runtime;
500 if (!instance_->Init(options, ignore_unrecognized)) {
501 delete instance_;
502 instance_ = NULL;
Carl Shapiro61e019d2011-07-14 16:53:09 -0700503 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700504 return instance_;
505}
Elliott Hughes0af55432011-08-17 18:37:28 -0700506
Brian Carlstromaded5f72011-10-07 17:15:04 -0700507void CreateSystemClassLoader() {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800508 if (Runtime::Current()->UseCompileTimeClassPath()) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700509 return;
510 }
511
512 Thread* self = Thread::Current();
513
514 // Must be in the kNative state for calling native methods.
Elliott Hughes34e06962012-04-09 13:55:55 -0700515 CHECK_EQ(self->GetState(), kNative);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700516
517 JNIEnv* env = self->GetJniEnv();
Brian Carlstromdf143242011-10-10 18:05:34 -0700518 ScopedLocalRef<jclass> ClassLoader_class(env, env->FindClass("java/lang/ClassLoader"));
519 CHECK(ClassLoader_class.get() != NULL);
520 jmethodID getSystemClassLoader = env->GetStaticMethodID(ClassLoader_class.get(),
521 "getSystemClassLoader",
522 "()Ljava/lang/ClassLoader;");
523 CHECK(getSystemClassLoader != NULL);
524 ScopedLocalRef<jobject> class_loader(env, env->CallStaticObjectMethod(ClassLoader_class.get(),
525 getSystemClassLoader));
526 CHECK(class_loader.get() != NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700527
Brian Carlstromdf143242011-10-10 18:05:34 -0700528 Thread::Current()->SetClassLoaderOverride(Decode<ClassLoader*>(env, class_loader.get()));
Jesse Wilson1b2b2f22011-11-22 11:47:44 -0500529
530 ScopedLocalRef<jclass> Thread_class(env, env->FindClass("java/lang/Thread"));
531 CHECK(Thread_class.get() != NULL);
532 jfieldID contextClassLoader = env->GetFieldID(Thread_class.get(),
533 "contextClassLoader",
534 "Ljava/lang/ClassLoader;");
535 CHECK(contextClassLoader != NULL);
536 ScopedLocalRef<jobject> self_jobject(env, AddLocalReference<jobject>(env, self->GetPeer()));
537 env->SetObjectField(self_jobject.get(), contextClassLoader, class_loader.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -0700538}
539
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700540void Runtime::Start() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800541 VLOG(startup) << "Runtime::Start entering";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700542
543 CHECK(host_prefix_.empty()) << host_prefix_;
544
Logan Chien0c717dd2012-03-28 18:31:07 +0800545 // Relocate the OatFiles (ELF images)
546 class_linker_->RelocateExecutable();
547
Brian Carlstromf28bc5b2011-10-26 01:15:03 -0700548 // Restore main thread state to kNative as expected by native code
Elliott Hughes34e06962012-04-09 13:55:55 -0700549 Thread::Current()->SetState(kNative);
Brian Carlstromf28bc5b2011-10-26 01:15:03 -0700550
Brian Carlstrom5d40f182011-09-26 22:29:18 -0700551 started_ = true;
552
Brian Carlstromae826982011-11-09 01:33:42 -0800553 // InitNativeMethods needs to be after started_ so that the classes
554 // it touches will have methods linked to the oat file if necessary.
555 InitNativeMethods();
556
Jesse Wilson9a6bae82011-11-14 14:57:30 -0500557 Thread::FinishStartup();
558
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700559 if (!is_zygote_) {
560 DidForkFromZygote();
561 }
Elliott Hughes9ca7a1f2011-10-11 14:29:52 -0700562
Elliott Hughes85d15452011-09-16 17:33:01 -0700563 StartDaemonThreads();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700564
Brian Carlstromaded5f72011-10-07 17:15:04 -0700565 CreateSystemClassLoader();
566
Elliott Hughes726079d2011-10-07 18:43:44 -0700567 Thread::Current()->GetJniEnv()->locals.AssertEmpty();
568
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800569 VLOG(startup) << "Runtime::Start exiting";
Elliott Hughes85d15452011-09-16 17:33:01 -0700570}
571
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700572void Runtime::DidForkFromZygote() {
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700573 is_zygote_ = false;
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700574
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700575 StartSignalCatcher();
Elliott Hughesd1cc8362011-10-24 16:58:50 -0700576
577 // Start the JDWP thread. If the command-line debugger flags specified "suspend=y",
578 // this will pause the runtime, so we probably want this to come last.
579 Dbg::StartJdwp();
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700580}
581
582void Runtime::StartSignalCatcher() {
583 if (!is_zygote_) {
Elliott Hughes94ce37a2011-10-18 15:07:48 -0700584 signal_catcher_ = new SignalCatcher(stack_trace_file_);
Brian Carlstromcaabb1b2011-10-11 18:09:13 -0700585 }
586}
587
Elliott Hughes85d15452011-09-16 17:33:01 -0700588void Runtime::StartDaemonThreads() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800589 VLOG(startup) << "Runtime::StartDaemonThreads entering";
Elliott Hughes85d15452011-09-16 17:33:01 -0700590
Elliott Hughes719b3232011-09-25 17:42:19 -0700591 Thread* self = Thread::Current();
Brian Carlstromaded5f72011-10-07 17:15:04 -0700592
593 // Must be in the kNative state for calling native methods.
Elliott Hughes34e06962012-04-09 13:55:55 -0700594 CHECK_EQ(self->GetState(), kNative);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700595
Elliott Hughes719b3232011-09-25 17:42:19 -0700596 JNIEnv* env = self->GetJniEnv();
Elliott Hughes726079d2011-10-07 18:43:44 -0700597 ScopedLocalRef<jclass> c(env, env->FindClass("java/lang/Daemons"));
598 CHECK(c.get() != NULL);
599 jmethodID mid = env->GetStaticMethodID(c.get(), "start", "()V");
Elliott Hughes719b3232011-09-25 17:42:19 -0700600 CHECK(mid != NULL);
Elliott Hughes726079d2011-10-07 18:43:44 -0700601 env->CallStaticVoidMethod(c.get(), mid);
Elliott Hughes8cf5bc02012-02-02 16:32:16 -0800602 CHECK(!env->ExceptionCheck());
Elliott Hughes9ca7a1f2011-10-11 14:29:52 -0700603
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800604 VLOG(startup) << "Runtime::StartDaemonThreads exiting";
Carl Shapiro61e019d2011-07-14 16:53:09 -0700605}
606
Elliott Hughes6b355752012-01-13 16:49:08 -0800607bool Runtime::IsShuttingDown() const {
608 return shutting_down_;
609}
610
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700611bool Runtime::IsStarted() const {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700612 return started_;
613}
614
Elliott Hughes0af55432011-08-17 18:37:28 -0700615bool Runtime::Init(const Options& raw_options, bool ignore_unrecognized) {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700616 CHECK_EQ(sysconf(_SC_PAGE_SIZE), kPageSize);
Brian Carlstrom6ea095a2011-08-16 15:26:54 -0700617
Elliott Hughes90a33692011-08-30 13:27:07 -0700618 UniquePtr<ParsedOptions> options(ParsedOptions::Create(raw_options, ignore_unrecognized));
619 if (options.get() == NULL) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700620 LOG(ERROR) << "Failed to parse options";
Brian Carlstrom6ea095a2011-08-16 15:26:54 -0700621 return false;
622 }
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800623 VLOG(startup) << "Runtime::Init -verbose:startup enabled";
Elliott Hughes7ede61e2011-09-14 18:18:06 -0700624
Elliott Hughesbb1e8f02011-10-18 14:14:25 -0700625 SetJniGlobalsMax(options->jni_globals_max_);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800626 Monitor::Init(options->lock_profiling_threshold_, options->hook_is_sensitive_thread_);
Elliott Hughes32d6e1e2011-10-11 14:47:44 -0700627
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700628 host_prefix_ = options->host_prefix_;
Brian Carlstroma004aa92012-02-08 18:05:09 -0800629 boot_class_path_string_ = options->boot_class_path_string_;
630 class_path_string_ = options->class_path_string_;
Elliott Hughes7ede61e2011-09-14 18:18:06 -0700631 properties_ = options->properties_;
632
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800633 is_compiler_ = options->is_compiler_;
Elliott Hughes9ca7a1f2011-10-11 14:29:52 -0700634 is_zygote_ = options->is_zygote_;
635
Elliott Hughes0af55432011-08-17 18:37:28 -0700636 vfprintf_ = options->hook_vfprintf_;
637 exit_ = options->hook_exit_;
638 abort_ = options->hook_abort_;
Brian Carlstrom6ea095a2011-08-16 15:26:54 -0700639
Elliott Hughesbe759c62011-09-08 19:38:21 -0700640 default_stack_size_ = options->stack_size_;
Elliott Hughes94ce37a2011-10-18 15:07:48 -0700641 stack_trace_file_ = options->stack_trace_file_;
Brian Carlstrom6ea095a2011-08-16 15:26:54 -0700642
Elliott Hughesc33a32b2011-10-11 18:18:07 -0700643 monitor_list_ = new MonitorList;
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800644 thread_list_ = new ThreadList;
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700645 intern_table_ = new InternTable;
646
Ian Rogers776ac1f2012-04-13 23:36:36 -0700647 verifier::MethodVerifier::InitGcMaps();
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800648
Logan Chiendd361c92012-04-10 23:40:37 +0800649#if defined(ART_USE_LLVM_COMPILER)
Ian Rogers776ac1f2012-04-13 23:36:36 -0700650 verifier::MethodVerifier::InitInferredRegCategoryMaps();
Logan Chiendd361c92012-04-10 23:40:37 +0800651#endif
652
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800653 heap_ = new Heap(options->heap_initial_size_,
654 options->heap_growth_limit_,
655 options->heap_maximum_size_,
656 options->image_);
Brian Carlstrom6ea095a2011-08-16 15:26:54 -0700657
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700658 BlockSignals();
Elliott Hughes457005c2012-04-16 13:54:25 -0700659 InitPlatformSignalHandlers();
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700660
Elliott Hughesa0957642011-09-02 14:27:33 -0700661 java_vm_ = new JavaVMExt(this, options.get());
Elliott Hughes515a5bc2011-08-17 11:08:34 -0700662
Elliott Hughesbe759c62011-09-08 19:38:21 -0700663 Thread::Startup();
Elliott Hughesd92bec42011-09-02 17:04:36 -0700664
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700665 // ClassLinker needs an attached thread, but we can't fully attach a thread
Elliott Hughes462c9442012-03-23 18:47:50 -0700666 // without creating objects. We can't supply a thread group yet; it will be fixed later.
667 Thread::Attach("main", false, NULL);
Brian Carlstrom6ea095a2011-08-16 15:26:54 -0700668
Brian Carlstromf28bc5b2011-10-26 01:15:03 -0700669 // Set us to runnable so tools using a runtime can allocate and GC by default
Elliott Hughes34e06962012-04-09 13:55:55 -0700670 Thread::Current()->SetState(kRunnable);
Brian Carlstromf28bc5b2011-10-26 01:15:03 -0700671
Ian Rogers141d6222012-04-05 12:23:06 -0700672 // Now we're attached, we can take the heap lock and validate the heap.
673 GetHeap()->EnableObjectValidation();
674
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800675 CHECK_GE(GetHeap()->GetSpaces().size(), 1U);
676 if (GetHeap()->GetSpaces()[0]->IsImageSpace()) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800677 class_linker_ = ClassLinker::CreateFromImage(intern_table_);
678 } else {
679 CHECK(options->boot_class_path_ != NULL);
680 CHECK_NE(options->boot_class_path_->size(), 0U);
681 class_linker_ = ClassLinker::CreateFromCompiler(*options->boot_class_path_, intern_table_);
682 }
683 CHECK(class_linker_ != NULL);
Brian Carlstrom6ea095a2011-08-16 15:26:54 -0700684
jeffhaob5e81852012-03-12 11:15:45 -0700685 method_trace_ = options->method_trace_;
686 method_trace_file_ = options->method_trace_file_;
687 method_trace_file_size_ = options->method_trace_file_size_;
688
689 if (options->method_trace_) {
690 Trace::Start(options->method_trace_file_.c_str(), -1, options->method_trace_file_size_, 0, false);
691 }
692
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800693 VLOG(startup) << "Runtime::Init exiting";
Carl Shapiro1fb86202011-06-27 17:43:13 -0700694 return true;
695}
696
Elliott Hughes038a8062011-09-18 14:12:41 -0700697void Runtime::InitNativeMethods() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800698 VLOG(startup) << "Runtime::InitNativeMethods entering";
Elliott Hughesad7c2a32011-08-31 11:58:10 -0700699 Thread* self = Thread::Current();
700 JNIEnv* env = self->GetJniEnv();
701
Elliott Hughes418d20f2011-09-22 14:00:39 -0700702 // Must be in the kNative state for calling native methods (JNI_OnLoad code).
Elliott Hughes34e06962012-04-09 13:55:55 -0700703 CHECK_EQ(self->GetState(), kNative);
Elliott Hughesad7c2a32011-08-31 11:58:10 -0700704
Elliott Hughes418d20f2011-09-22 14:00:39 -0700705 // First set up JniConstants, which is used by both the runtime's built-in native
706 // methods and libcore.
Elliott Hughesfea966e2011-09-22 10:26:20 -0700707 JniConstants::init(env);
708
Elliott Hughes418d20f2011-09-22 14:00:39 -0700709 // Then set up the native methods provided by the runtime itself.
Elliott Hughesad7c2a32011-08-31 11:58:10 -0700710 RegisterRuntimeNativeMethods(env);
711
Elliott Hughes418d20f2011-09-22 14:00:39 -0700712 // Then set up libcore, which is just a regular JNI library with a regular JNI_OnLoad.
713 // Most JNI libraries can just use System.loadLibrary, but libcore can't because it's
714 // the library that implements System.loadLibrary!
Elliott Hughesad7c2a32011-08-31 11:58:10 -0700715 LoadJniLibrary(instance_->GetJavaVM(), "javacore");
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800716 VLOG(startup) << "Runtime::InitNativeMethods exiting";
Elliott Hughesad7c2a32011-08-31 11:58:10 -0700717}
718
719void Runtime::RegisterRuntimeNativeMethods(JNIEnv* env) {
720#define REGISTER(FN) extern void FN(JNIEnv*); FN(env)
Ian Rogers5167c972012-02-03 10:41:20 -0800721 // Register Throwable first so that registration of other native methods can throw exceptions
722 REGISTER(register_java_lang_Throwable);
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700723 REGISTER(register_dalvik_system_DexFile);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700724 REGISTER(register_dalvik_system_VMDebug);
Elliott Hughes7ede61e2011-09-14 18:18:06 -0700725 REGISTER(register_dalvik_system_VMRuntime);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700726 REGISTER(register_dalvik_system_VMStack);
Elliott Hughes01158d72011-09-19 19:47:10 -0700727 REGISTER(register_dalvik_system_Zygote);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700728 REGISTER(register_java_lang_Class);
Elliott Hughesbf86d042011-08-31 17:53:14 -0700729 REGISTER(register_java_lang_Object);
730 REGISTER(register_java_lang_Runtime);
731 REGISTER(register_java_lang_String);
732 REGISTER(register_java_lang_System);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700733 REGISTER(register_java_lang_Thread);
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700734 REGISTER(register_java_lang_VMClassLoader);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700735 REGISTER(register_java_lang_reflect_Array);
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700736 REGISTER(register_java_lang_reflect_Constructor);
Brian Carlstromf867b6f2011-09-16 12:17:25 -0700737 REGISTER(register_java_lang_reflect_Field);
738 REGISTER(register_java_lang_reflect_Method);
Jesse Wilson95caa792011-10-12 18:14:17 -0400739 REGISTER(register_java_lang_reflect_Proxy);
Elliott Hughesbf86d042011-08-31 17:53:14 -0700740 REGISTER(register_java_util_concurrent_atomic_AtomicLong);
Brian Carlstrom395520e2011-09-25 19:35:00 -0700741 REGISTER(register_org_apache_harmony_dalvik_ddmc_DdmServer);
Elliott Hughesf6a1e1e2011-10-25 16:28:04 -0700742 REGISTER(register_org_apache_harmony_dalvik_ddmc_DdmVmInternal);
Elliott Hughes5ee7a8b2011-09-13 16:40:07 -0700743 REGISTER(register_sun_misc_Unsafe);
Elliott Hughesad7c2a32011-08-31 11:58:10 -0700744#undef REGISTER
745}
746
Elliott Hughesc967f782012-04-16 10:23:15 -0700747void Runtime::DumpForSigQuit(std::ostream& os) {
Elliott Hughescac6cc72011-11-03 20:31:21 -0700748 GetClassLinker()->DumpForSigQuit(os);
749 GetInternTable()->DumpForSigQuit(os);
Elliott Hughesc967f782012-04-16 10:23:15 -0700750 GetHeap()->DumpForSigQuit(os);
Elliott Hughes42ee1422011-09-06 12:33:32 -0700751 os << "\n";
Elliott Hughes8daa0922011-09-11 13:46:25 -0700752
Elliott Hughesc967f782012-04-16 10:23:15 -0700753 thread_list_->DumpForSigQuit(os);
Elliott Hughese27955c2011-08-26 15:21:24 -0700754}
755
Elliott Hughes21a5bf22011-12-07 14:35:20 -0800756void Runtime::DumpLockHolders(std::ostream& os) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800757 pid_t heap_lock_owner = GetHeap()->GetLockOwner();
Elliott Hughes21a5bf22011-12-07 14:35:20 -0800758 pid_t thread_list_lock_owner = GetThreadList()->GetLockOwner();
759 pid_t classes_lock_owner = GetClassLinker()->GetClassesLockOwner();
760 pid_t dex_lock_owner = GetClassLinker()->GetDexLockOwner();
761 if ((heap_lock_owner | thread_list_lock_owner | classes_lock_owner | dex_lock_owner) != 0) {
762 os << "Heap lock owner tid: " << heap_lock_owner << "\n"
763 << "ThreadList lock owner tid: " << thread_list_lock_owner << "\n"
764 << "ClassLinker classes lock owner tid: " << classes_lock_owner << "\n"
765 << "ClassLinker dex lock owner tid: " << dex_lock_owner << "\n";
766 }
767}
768
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700769void Runtime::SetStatsEnabled(bool new_state) {
770 if (new_state == true) {
771 GetStats()->Clear(~0);
772 // TODO: wouldn't it make more sense to clear _all_ threads' stats?
773 Thread::Current()->GetStats()->Clear(~0);
774 }
775 stats_enabled_ = new_state;
776}
777
778void Runtime::ResetStats(int kinds) {
779 GetStats()->Clear(kinds & 0xffff);
780 // TODO: wouldn't it make more sense to clear _all_ threads' stats?
781 Thread::Current()->GetStats()->Clear(kinds >> 16);
782}
783
784RuntimeStats* Runtime::GetStats() {
785 return &stats_;
786}
787
788int32_t Runtime::GetStat(int kind) {
789 RuntimeStats* stats;
790 if (kind < (1<<16)) {
791 stats = GetStats();
792 } else {
793 stats = Thread::Current()->GetStats();
794 kind >>= 16;
795 }
796 switch (kind) {
797 case KIND_ALLOCATED_OBJECTS:
798 return stats->allocated_objects;
799 case KIND_ALLOCATED_BYTES:
800 return stats->allocated_bytes;
801 case KIND_FREED_OBJECTS:
802 return stats->freed_objects;
803 case KIND_FREED_BYTES:
804 return stats->freed_bytes;
805 case KIND_GC_INVOCATIONS:
806 return stats->gc_for_alloc_count;
807 case KIND_CLASS_INIT_COUNT:
808 return stats->class_init_count;
809 case KIND_CLASS_INIT_TIME:
810 // Convert ns to us, reduce to 32 bits.
Elliott Hughes398f64b2012-03-26 18:05:48 -0700811 return static_cast<int>(stats->class_init_time_ns / 1000);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700812 case KIND_EXT_ALLOCATED_OBJECTS:
813 case KIND_EXT_ALLOCATED_BYTES:
814 case KIND_EXT_FREED_OBJECTS:
815 case KIND_EXT_FREED_BYTES:
816 return 0; // backward compatibility
817 default:
Elliott Hughes7b9d9962012-04-20 18:48:18 -0700818 LOG(FATAL) << "Unknown statistic " << kind;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700819 return -1; // unreachable
820 }
821}
822
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700823void Runtime::BlockSignals() {
Elliott Hughes457005c2012-04-16 13:54:25 -0700824 SignalSet signals;
825 signals.Add(SIGPIPE);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700826 // SIGQUIT is used to dump the runtime's state (including stack traces).
Elliott Hughes457005c2012-04-16 13:54:25 -0700827 signals.Add(SIGQUIT);
Elliott Hughes08795042012-04-03 14:48:52 -0700828 // SIGUSR1 is used to initiate a GC.
Elliott Hughes457005c2012-04-16 13:54:25 -0700829 signals.Add(SIGUSR1);
830 signals.Block();
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700831}
832
Elliott Hughes462c9442012-03-23 18:47:50 -0700833void Runtime::AttachCurrentThread(const char* thread_name, bool as_daemon, Object* thread_group) {
834 Thread::Attach(thread_name, as_daemon, thread_group);
Elliott Hughes22869a92012-03-27 14:08:24 -0700835 if (thread_name == NULL) {
836 LOG(WARNING) << *Thread::Current() << " attached without supplying a name";
837 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700838}
839
Elliott Hughesd92bec42011-09-02 17:04:36 -0700840void Runtime::DetachCurrentThread() {
Elliott Hughes22869a92012-03-27 14:08:24 -0700841 if (Thread::Current()->GetTopOfStack().GetSP() != NULL) {
842 LOG(FATAL) << *Thread::Current() << " attempting to detach while still running code";
843 }
Elliott Hughes02b48d12011-09-07 17:15:51 -0700844 thread_list_->Unregister();
Carl Shapiro1fb86202011-06-27 17:43:13 -0700845}
846
Brian Carlstrome24fa612011-09-29 00:53:55 -0700847void Runtime::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
Elliott Hughesbfe487b2011-10-26 15:48:55 -0700848 Dbg::VisitRoots(visitor, arg);
Brian Carlstrome24fa612011-09-29 00:53:55 -0700849 class_linker_->VisitRoots(visitor, arg);
850 intern_table_->VisitRoots(visitor, arg);
851 java_vm_->VisitRoots(visitor, arg);
852 thread_list_->VisitRoots(visitor, arg);
853 visitor(jni_stub_array_, arg);
854 visitor(abstract_method_error_stub_array_, arg);
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700855 for (int i = 0; i < Runtime::kLastTrampolineMethodType; i++) {
856 visitor(resolution_stub_array_[i], arg);
857 }
Ian Rogers19846512012-02-24 11:42:47 -0800858 visitor(resolution_method_, arg);
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700859 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
860 visitor(callee_save_method_[i], arg);
861 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700862}
863
Ian Rogers169c9a72011-11-13 20:13:17 -0800864bool Runtime::HasJniDlsymLookupStub() const {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700865 return jni_stub_array_ != NULL;
866}
867
Ian Rogers169c9a72011-11-13 20:13:17 -0800868ByteArray* Runtime::GetJniDlsymLookupStub() const {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700869 CHECK(jni_stub_array_ != NULL);
870 return jni_stub_array_;
871}
872
Ian Rogers169c9a72011-11-13 20:13:17 -0800873void Runtime::SetJniDlsymLookupStub(ByteArray* jni_stub_array) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700874 CHECK(jni_stub_array != NULL) << " jni_stub_array=" << jni_stub_array;
875 CHECK(jni_stub_array_ == NULL || jni_stub_array_ == jni_stub_array)
876 << "jni_stub_array_=" << jni_stub_array_ << " jni_stub_array=" << jni_stub_array;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700877 jni_stub_array_ = jni_stub_array;
878}
879
880bool Runtime::HasAbstractMethodErrorStubArray() const {
881 return abstract_method_error_stub_array_ != NULL;
882}
883
884ByteArray* Runtime::GetAbstractMethodErrorStubArray() const {
885 CHECK(abstract_method_error_stub_array_ != NULL);
886 return abstract_method_error_stub_array_;
887}
888
889void Runtime::SetAbstractMethodErrorStubArray(ByteArray* abstract_method_error_stub_array) {
890 CHECK(abstract_method_error_stub_array != NULL);
891 CHECK(abstract_method_error_stub_array_ == NULL || abstract_method_error_stub_array_ == abstract_method_error_stub_array);
892 abstract_method_error_stub_array_ = abstract_method_error_stub_array;
893}
894
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700895
896Runtime::TrampolineType Runtime::GetTrampolineType(Method* method) {
897 if (method == NULL) {
898 return Runtime::kUnknownMethod;
899 } else if (method->IsStatic()) {
900 return Runtime::kStaticMethod;
901 } else {
Ian Rogersfb6adba2012-03-04 21:51:51 -0800902 return Runtime::kUnknownMethod;
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700903 }
Ian Rogersad25ac52011-10-04 19:13:33 -0700904}
905
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700906bool Runtime::HasResolutionStubArray(TrampolineType type) const {
907 return resolution_stub_array_[type] != NULL;
Ian Rogersad25ac52011-10-04 19:13:33 -0700908}
909
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700910ByteArray* Runtime::GetResolutionStubArray(TrampolineType type) const {
911 CHECK(HasResolutionStubArray(type));
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700912 DCHECK_LT(static_cast<int>(type), static_cast<int>(kLastTrampolineMethodType));
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700913 return resolution_stub_array_[type];
914}
915
916void Runtime::SetResolutionStubArray(ByteArray* resolution_stub_array, TrampolineType type) {
Ian Rogersad25ac52011-10-04 19:13:33 -0700917 CHECK(resolution_stub_array != NULL);
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700918 CHECK(!HasResolutionStubArray(type) || resolution_stub_array_[type] == resolution_stub_array);
919 resolution_stub_array_[type] = resolution_stub_array;
Ian Rogersad25ac52011-10-04 19:13:33 -0700920}
921
Ian Rogers19846512012-02-24 11:42:47 -0800922Method* Runtime::CreateResolutionMethod() {
923 Class* method_class = Method::GetMethodClass();
924 SirtRef<Method> method(down_cast<Method*>(method_class->AllocObject()));
925 method->SetDeclaringClass(method_class);
926 // TODO: use a special method for resolution method saves
927 method->SetDexMethodIndex(DexFile::kDexNoIndex16);
928 ByteArray* unknown_resolution_stub = GetResolutionStubArray(kUnknownMethod);
929 CHECK(unknown_resolution_stub != NULL);
930 method->SetCode(unknown_resolution_stub->GetData());
931 return method.get();
932}
933
934bool Runtime::HasResolutionMethod() const {
935 return resolution_method_ != NULL;
936}
937
938// Returns a special method that calls into a trampoline for runtime method resolution
939Method* Runtime::GetResolutionMethod() const {
940 CHECK(HasResolutionMethod());
941 return resolution_method_;
942}
943
944void Runtime::SetResolutionMethod(Method* method) {
945 resolution_method_ = method;
946}
947
Brian Carlstromae826982011-11-09 01:33:42 -0800948Method* Runtime::CreateCalleeSaveMethod(InstructionSet instruction_set, CalleeSaveType type) {
Ian Rogersff1ed472011-09-20 13:46:24 -0700949 Class* method_class = Method::GetMethodClass();
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700950 SirtRef<Method> method(down_cast<Method*>(method_class->AllocObject()));
Ian Rogersff1ed472011-09-20 13:46:24 -0700951 method->SetDeclaringClass(method_class);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800952 // TODO: use a special method for callee saves
Ian Rogers19846512012-02-24 11:42:47 -0800953 method->SetDexMethodIndex(DexFile::kDexNoIndex16);
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700954 method->SetCode(NULL);
Brian Carlstromae826982011-11-09 01:33:42 -0800955 if ((instruction_set == kThumb2) || (instruction_set == kArm)) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700956 uint32_t ref_spills = (1 << art::arm::R5) | (1 << art::arm::R6) | (1 << art::arm::R7) |
957 (1 << art::arm::R8) | (1 << art::arm::R10) | (1 << art::arm::R11);
958 uint32_t arg_spills = (1 << art::arm::R1) | (1 << art::arm::R2) | (1 << art::arm::R3);
959 uint32_t all_spills = (1 << art::arm::R4) | (1 << art::arm::R9);
960 uint32_t core_spills = ref_spills | (type == kRefsAndArgs ? arg_spills :0) |
961 (type == kSaveAll ? all_spills :0) | (1 << art::arm::LR);
962 uint32_t fp_all_spills = (1 << art::arm::S0) | (1 << art::arm::S1) | (1 << art::arm::S2) |
963 (1 << art::arm::S3) | (1 << art::arm::S4) | (1 << art::arm::S5) |
964 (1 << art::arm::S6) | (1 << art::arm::S7) | (1 << art::arm::S8) |
965 (1 << art::arm::S9) | (1 << art::arm::S10) | (1 << art::arm::S11) |
966 (1 << art::arm::S12) | (1 << art::arm::S13) | (1 << art::arm::S14) |
967 (1 << art::arm::S15) | (1 << art::arm::S16) | (1 << art::arm::S17) |
968 (1 << art::arm::S18) | (1 << art::arm::S19) | (1 << art::arm::S20) |
969 (1 << art::arm::S21) | (1 << art::arm::S22) | (1 << art::arm::S23) |
970 (1 << art::arm::S24) | (1 << art::arm::S25) | (1 << art::arm::S26) |
971 (1 << art::arm::S27) | (1 << art::arm::S28) | (1 << art::arm::S29) |
972 (1 << art::arm::S30) | (1 << art::arm::S31);
973 uint32_t fp_spills = type == kSaveAll ? fp_all_spills : 0;
974 size_t frame_size = RoundUp((__builtin_popcount(core_spills) /* gprs */ +
975 __builtin_popcount(fp_spills) /* fprs */ +
976 1 /* Method* */) * kPointerSize, kStackAlignment);
Ian Rogers15fdb8c2011-09-25 15:45:07 -0700977 method->SetFrameSizeInBytes(frame_size);
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700978 method->SetCoreSpillMask(core_spills);
979 method->SetFpSpillMask(fp_spills);
Brian Carlstromae826982011-11-09 01:33:42 -0800980 } else if (instruction_set == kX86) {
Ian Rogers7caad772012-03-30 01:07:54 -0700981 uint32_t ref_spills = (1 << art::x86::EBP) | (1 << art::x86::ESI) | (1 << art::x86::EDI);
982 uint32_t arg_spills = (1 << art::x86::ECX) | (1 << art::x86::EDX) | (1 << art::x86::EBX);
983 uint32_t core_spills = ref_spills | (type == kRefsAndArgs ? arg_spills : 0) |
984 (1 << art::x86::kNumberOfCpuRegisters); // fake return address callee save
985 size_t frame_size = RoundUp((__builtin_popcount(core_spills) /* gprs */ +
986 1 /* Method* */) * kPointerSize, kStackAlignment);
987 method->SetFrameSizeInBytes(frame_size);
988 method->SetCoreSpillMask(core_spills);
Ian Rogersff1ed472011-09-20 13:46:24 -0700989 method->SetFpSpillMask(0);
990 } else {
991 UNIMPLEMENTED(FATAL);
992 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700993 return method.get();
Ian Rogersff1ed472011-09-20 13:46:24 -0700994}
995
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700996bool Runtime::HasCalleeSaveMethod(CalleeSaveType type) const {
997 return callee_save_method_[type] != NULL;
Brian Carlstrom1f870082011-08-23 16:02:11 -0700998}
999
Brian Carlstrome24fa612011-09-29 00:53:55 -07001000// Returns a special method that describes all callee saves being spilled to the stack.
Ian Rogers4f0d07c2011-10-06 23:38:47 -07001001Method* Runtime::GetCalleeSaveMethod(CalleeSaveType type) const {
1002 CHECK(HasCalleeSaveMethod(type));
1003 return callee_save_method_[type];
Brian Carlstrome24fa612011-09-29 00:53:55 -07001004}
1005
Ian Rogers4f0d07c2011-10-06 23:38:47 -07001006void Runtime::SetCalleeSaveMethod(Method* method, CalleeSaveType type) {
1007 DCHECK_LT(static_cast<int>(type), static_cast<int>(kLastCalleeSaveType));
1008 callee_save_method_[type] = method;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001009}
1010
jeffhao2692b572011-12-16 15:42:28 -08001011void Runtime::EnableMethodTracing(Trace* tracer) {
1012 CHECK(!IsMethodTracingActive());
1013 tracer_ = tracer;
1014}
1015
1016void Runtime::DisableMethodTracing() {
1017 CHECK(IsMethodTracingActive());
1018 delete tracer_;
1019 tracer_ = NULL;
1020}
1021
1022bool Runtime::IsMethodTracingActive() const {
1023 return (tracer_ != NULL);
1024}
1025
1026Trace* Runtime::GetTracer() const {
1027 CHECK(IsMethodTracingActive());
1028 return tracer_;
1029}
1030
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001031const std::vector<const DexFile*>& Runtime::GetCompileTimeClassPath(const ClassLoader* class_loader) {
1032 if (class_loader == NULL) {
1033 return GetClassLinker()->GetBootClassPath();
1034 }
1035 CHECK(UseCompileTimeClassPath());
1036 CompileTimeClassPaths::const_iterator it = compile_time_class_paths_.find(class_loader);
1037 CHECK(it != compile_time_class_paths_.end());
1038 return it->second;
1039}
1040
1041void Runtime::SetCompileTimeClassPath(const ClassLoader* class_loader, std::vector<const DexFile*>& class_path) {
1042 CHECK(!IsStarted());
1043 use_compile_time_class_path_ = true;
Elliott Hughesa0e18062012-04-13 15:59:59 -07001044 compile_time_class_paths_.Put(class_loader, class_path);
Elliott Hughesb3bd5f02012-03-08 21:05:27 -08001045}
1046
Carl Shapiro1fb86202011-06-27 17:43:13 -07001047} // namespace art