blob: c733bfed11aff1b3ebce345d4fb7ac9ef0a597fd [file] [log] [blame]
Carl Shapiro1fb86202011-06-27 17:43:13 -07001// Copyright 2011 Google Inc. All Rights Reserved.
2
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003#include "runtime.h"
Carl Shapiro1fb86202011-06-27 17:43:13 -07004
Elliott Hughesffe67362011-07-17 12:09:27 -07005#include <cstdio>
6#include <cstdlib>
Brian Carlstrom8a436592011-08-15 21:27:23 -07007#include <limits>
Carl Shapiro2ed144c2011-07-26 16:52:08 -07008#include <vector>
Elliott Hughesffe67362011-07-17 12:09:27 -07009
Brian Carlstromaded5f72011-10-07 17:15:04 -070010#include "ScopedLocalRef.h"
Elliott Hughes90a33692011-08-30 13:27:07 -070011#include "UniquePtr.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070012#include "class_linker.h"
Brian Carlstromaded5f72011-10-07 17:15:04 -070013#include "class_loader.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070014#include "heap.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070015#include "image.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070016#include "intern_table.h"
Elliott Hughesc5f7c912011-08-18 14:00:42 -070017#include "jni_internal.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070018#include "oat_file.h"
Elliott Hughes726079d2011-10-07 18:43:44 -070019#include "ScopedLocalRef.h"
Elliott Hughese27955c2011-08-26 15:21:24 -070020#include "signal_catcher.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070021#include "space.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070022#include "thread.h"
Elliott Hughes8daa0922011-09-11 13:46:25 -070023#include "thread_list.h"
Carl Shapiro61e019d2011-07-14 16:53:09 -070024
Elliott Hughes90a33692011-08-30 13:27:07 -070025// TODO: this drags in cutil/log.h, which conflicts with our logging.h.
26#include "JniConstants.h"
27
Carl Shapiro1fb86202011-06-27 17:43:13 -070028namespace art {
29
Carl Shapiro2ed144c2011-07-26 16:52:08 -070030Runtime* Runtime::instance_ = NULL;
31
Elliott Hughesdcc24742011-09-07 14:02:44 -070032Runtime::Runtime()
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -070033 : verbose_startup_(false),
34 default_stack_size_(Thread::kDefaultStackSize),
Elliott Hughesdcc24742011-09-07 14:02:44 -070035 thread_list_(NULL),
36 intern_table_(NULL),
37 class_linker_(NULL),
38 signal_catcher_(NULL),
39 java_vm_(NULL),
Brian Carlstrom16192862011-09-12 17:50:06 -070040 jni_stub_array_(NULL),
Brian Carlstrome24fa612011-09-29 00:53:55 -070041 abstract_method_error_stub_array_(NULL),
Elliott Hughesdcc24742011-09-07 14:02:44 -070042 started_(false),
43 vfprintf_(NULL),
44 exit_(NULL),
Elliott Hughes9d5ccec2011-09-19 13:19:50 -070045 abort_(NULL),
46 stats_enabled_(false) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -070047 for (int i = 0; i < Runtime::kLastTrampolineMethodType; i++) {
48 resolution_stub_array_[i] = NULL;
49 }
50 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
51 callee_save_method_[i] = NULL;
52 }
Elliott Hughesdcc24742011-09-07 14:02:44 -070053}
54
Carl Shapiro61e019d2011-07-14 16:53:09 -070055Runtime::~Runtime() {
Elliott Hughes5fe594f2011-09-08 12:33:17 -070056 // Make sure our internal threads are dead before we start tearing down things they're using.
57 delete signal_catcher_;
Elliott Hughes038a8062011-09-18 14:12:41 -070058 // TODO: GC thread.
Elliott Hughes5fe594f2011-09-08 12:33:17 -070059
Elliott Hughes038a8062011-09-18 14:12:41 -070060 // Make sure all other non-daemon threads have terminated, and all daemon threads are suspended.
Elliott Hughes93e74e82011-09-13 11:07:03 -070061 delete thread_list_;
62
Carl Shapiro61e019d2011-07-14 16:53:09 -070063 delete class_linker_;
Carl Shapiro69759ea2011-07-21 18:13:35 -070064 Heap::Destroy();
Elliott Hughescf4c6c42011-09-01 15:16:42 -070065 delete intern_table_;
Elliott Hughesc5f7c912011-08-18 14:00:42 -070066 delete java_vm_;
Elliott Hughesc1674ed2011-08-25 18:09:09 -070067 Thread::Shutdown();
Carl Shapiro4acf4642011-07-26 18:54:13 -070068 // TODO: acquire a static mutex on Runtime to avoid racing.
Brian Carlstrom4a289ed2011-08-16 17:17:49 -070069 CHECK(instance_ == NULL || instance_ == this);
Carl Shapiro4acf4642011-07-26 18:54:13 -070070 instance_ = NULL;
Carl Shapiro61e019d2011-07-14 16:53:09 -070071}
72
Elliott Hughesffe67362011-07-17 12:09:27 -070073void Runtime::Abort(const char* file, int line) {
74 // Get any pending output out of the way.
75 fflush(NULL);
76
77 // Many people have difficulty distinguish aborts from crashes,
78 // so be explicit.
79 LogMessage(file, line, ERROR, -1).stream() << "Runtime aborting...";
80
Elliott Hughesffe67362011-07-17 12:09:27 -070081 // Perform any platform-specific pre-abort actions.
82 PlatformAbort(file, line);
83
Brian Carlstrom6ea095a2011-08-16 15:26:54 -070084 // use abort hook if we have one
85 if (Runtime::Current() != NULL && Runtime::Current()->abort_ != NULL) {
86 Runtime::Current()->abort_();
87 // notreached
88 }
89
Elliott Hughesffe67362011-07-17 12:09:27 -070090 // If we call abort(3) on a device, all threads in the process
Carl Shapiro69759ea2011-07-21 18:13:35 -070091 // receive SIGABRT. debuggerd dumps the stack trace of the main
92 // thread, whether or not that was the thread that failed. By
93 // stuffing a value into a bogus address, we cause a segmentation
Elliott Hughesffe67362011-07-17 12:09:27 -070094 // fault in the current thread, and get a useful log from debuggerd.
95 // We can also trivially tell the difference between a VM crash and
96 // a deliberate abort by looking at the fault address.
97 *reinterpret_cast<char*>(0xdeadd00d) = 38;
98 abort();
Elliott Hughesffe67362011-07-17 12:09:27 -070099 // notreached
100}
101
Elliott Hughesbf86d042011-08-31 17:53:14 -0700102void Runtime::CallExitHook(jint status) {
103 if (exit_ != NULL) {
104 ScopedThreadStateChange tsc(Thread::Current(), Thread::kNative);
105 exit_(status);
106 LOG(WARNING) << "Exit hook returned instead of exiting!";
107 }
108}
109
Brian Carlstrom8a436592011-08-15 21:27:23 -0700110// Parse a string of the form /[0-9]+[kKmMgG]?/, which is used to specify
111// memory sizes. [kK] indicates kilobytes, [mM] megabytes, and
112// [gG] gigabytes.
113//
114// "s" should point just past the "-Xm?" part of the string.
Brian Carlstrom8a436592011-08-15 21:27:23 -0700115// "div" specifies a divisor, e.g. 1024 if the value must be a multiple
116// of 1024.
117//
118// The spec says the -Xmx and -Xms options must be multiples of 1024. It
119// doesn't say anything about -Xss.
120//
121// Returns 0 (a useless size) if "s" is malformed or specifies a low or
122// non-evenly-divisible value.
123//
124size_t ParseMemoryOption(const char *s, size_t div) {
125 // strtoul accepts a leading [+-], which we don't want,
126 // so make sure our string starts with a decimal digit.
127 if (isdigit(*s)) {
128 const char *s2;
129 size_t val = strtoul(s, (char **)&s2, 10);
130 if (s2 != s) {
131 // s2 should be pointing just after the number.
132 // If this is the end of the string, the user
133 // has specified a number of bytes. Otherwise,
134 // there should be exactly one more character
135 // that specifies a multiplier.
136 if (*s2 != '\0') {
Brian Carlstromf734cf52011-08-17 16:28:14 -0700137 // The remainder of the string is either a single multiplier
138 // character, or nothing to indicate that the value is in
139 // bytes.
140 char c = *s2++;
141 if (*s2 == '\0') {
142 size_t mul;
143 if (c == '\0') {
144 mul = 1;
145 } else if (c == 'k' || c == 'K') {
146 mul = KB;
147 } else if (c == 'm' || c == 'M') {
148 mul = MB;
149 } else if (c == 'g' || c == 'G') {
150 mul = GB;
Brian Carlstrom8a436592011-08-15 21:27:23 -0700151 } else {
Brian Carlstromf734cf52011-08-17 16:28:14 -0700152 // Unknown multiplier character.
Brian Carlstrom8a436592011-08-15 21:27:23 -0700153 return 0;
154 }
Brian Carlstromf734cf52011-08-17 16:28:14 -0700155
156 if (val <= std::numeric_limits<size_t>::max() / mul) {
157 val *= mul;
158 } else {
159 // Clamp to a multiple of 1024.
160 val = std::numeric_limits<size_t>::max() & ~(1024-1);
161 }
162 } else {
163 // There's more than one character after the numeric part.
164 return 0;
165 }
Brian Carlstrom8a436592011-08-15 21:27:23 -0700166 }
167 // The man page says that a -Xm value must be a multiple of 1024.
168 if (val % div == 0) {
169 return val;
170 }
Carl Shapirofc322c72011-07-27 00:20:01 -0700171 }
172 }
Brian Carlstrom8a436592011-08-15 21:27:23 -0700173 return 0;
Carl Shapirofc322c72011-07-27 00:20:01 -0700174}
175
Elliott Hughes0af55432011-08-17 18:37:28 -0700176void LoadJniLibrary(JavaVMExt* vm, const char* name) {
177 // TODO: OS_SHARED_LIB_FORMAT_STR
178 std::string mapped_name(StringPrintf("lib%s.so", name));
Elliott Hughes75770752011-08-24 17:52:38 -0700179 std::string reason;
180 if (!vm->LoadNativeLibrary(mapped_name, NULL, reason)) {
Elliott Hughes0af55432011-08-17 18:37:28 -0700181 LOG(FATAL) << "LoadNativeLibrary failed for \"" << mapped_name << "\": "
182 << reason;
183 }
184}
185
Brian Carlstrom6ea095a2011-08-16 15:26:54 -0700186Runtime::ParsedOptions* Runtime::ParsedOptions::Create(const Options& options, bool ignore_unrecognized) {
Elliott Hughes90a33692011-08-30 13:27:07 -0700187 UniquePtr<ParsedOptions> parsed(new ParsedOptions());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700188 const char* boot_class_path = getenv("BOOTCLASSPATH");
189 if (boot_class_path != NULL) {
190 parsed->boot_class_path_ = getenv("BOOTCLASSPATH");
191 }
192 const char* class_path = getenv("CLASSPATH");
193 if (class_path != NULL) {
194 parsed->class_path_ = getenv("CLASSPATH");
195 }
Elliott Hughes515a5bc2011-08-17 11:08:34 -0700196#ifdef NDEBUG
Elliott Hughes5174fe62011-08-23 15:12:35 -0700197 // -Xcheck:jni is off by default for regular builds...
Elliott Hughes515a5bc2011-08-17 11:08:34 -0700198 parsed->check_jni_ = false;
199#else
200 // ...but on by default in debug builds.
201 parsed->check_jni_ = true;
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700202#endif
Elliott Hughes85d15452011-09-16 17:33:01 -0700203
Brian Carlstrom6ea095a2011-08-16 15:26:54 -0700204 parsed->heap_initial_size_ = Heap::kInitialSize;
205 parsed->heap_maximum_size_ = Heap::kMaximumSize;
Brian Carlstromf734cf52011-08-17 16:28:14 -0700206 parsed->stack_size_ = Thread::kDefaultStackSize;
207
Brian Carlstrom6ea095a2011-08-16 15:26:54 -0700208 parsed->hook_vfprintf_ = vfprintf;
209 parsed->hook_exit_ = exit;
210 parsed->hook_abort_ = abort;
Brian Carlstrom8a436592011-08-15 21:27:23 -0700211
212 for (size_t i = 0; i < options.size(); ++i) {
213 const StringPiece& option = options[i].first;
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700214 if (false) {
215 LOG(INFO) << "option[" << i << "]=" << option;
216 }
Brian Carlstrom8a436592011-08-15 21:27:23 -0700217 if (option.starts_with("-Xbootclasspath:")) {
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700218 parsed->boot_class_path_ = option.substr(strlen("-Xbootclasspath:")).data();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700219 } else if (option == "-classpath" || option == "-cp") {
220 // TODO: support -Djava.class.path
221 i++;
222 if (i == options.size()) {
223 // TODO: usage
224 LOG(FATAL) << "Missing required class path value for " << option;
225 return NULL;
226 }
227 const StringPiece& value = options[i].first;
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700228 parsed->class_path_ = value.data();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700229 } else if (option.starts_with("-Ximage:")) {
230 parsed->images_.push_back(option.substr(strlen("-Ximage:")).data());
Elliott Hughes515a5bc2011-08-17 11:08:34 -0700231 } else if (option.starts_with("-Xcheck:jni")) {
232 parsed->check_jni_ = true;
Brian Carlstrom8a436592011-08-15 21:27:23 -0700233 } else if (option.starts_with("-Xms")) {
Brian Carlstromf734cf52011-08-17 16:28:14 -0700234 size_t size = ParseMemoryOption(option.substr(strlen("-Xms")).data(), 1024);
235 if (size == 0) {
236 if (ignore_unrecognized) {
237 continue;
238 }
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700239 // TODO: usage
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700240 LOG(FATAL) << "Failed to parse " << option;
Brian Carlstromf734cf52011-08-17 16:28:14 -0700241 return NULL;
242 }
243 parsed->heap_initial_size_ = size;
Brian Carlstrom8a436592011-08-15 21:27:23 -0700244 } else if (option.starts_with("-Xmx")) {
Brian Carlstromf734cf52011-08-17 16:28:14 -0700245 size_t size = ParseMemoryOption(option.substr(strlen("-Xmx")).data(), 1024);
246 if (size == 0) {
247 if (ignore_unrecognized) {
248 continue;
249 }
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700250 // TODO: usage
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700251 LOG(FATAL) << "Failed to parse " << option;
Brian Carlstromf734cf52011-08-17 16:28:14 -0700252 return NULL;
253 }
254 parsed->heap_maximum_size_ = size;
255 } else if (option.starts_with("-Xss")) {
256 size_t size = ParseMemoryOption(option.substr(strlen("-Xss")).data(), 1);
257 if (size == 0) {
258 if (ignore_unrecognized) {
259 continue;
260 }
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700261 // TODO: usage
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700262 LOG(FATAL) << "Failed to parse " << option;
Brian Carlstromf734cf52011-08-17 16:28:14 -0700263 return NULL;
264 }
265 parsed->stack_size_ = size;
Brian Carlstrom6ea095a2011-08-16 15:26:54 -0700266 } else if (option.starts_with("-D")) {
267 parsed->properties_.push_back(option.substr(strlen("-D")).data());
Elliott Hughesa0957642011-09-02 14:27:33 -0700268 } else if (option.starts_with("-Xjnitrace:")) {
269 parsed->jni_trace_ = option.substr(strlen("-Xjnitrace:")).data();
Brian Carlstrom6ea095a2011-08-16 15:26:54 -0700270 } else if (option.starts_with("-verbose:")) {
Elliott Hughes0af55432011-08-17 18:37:28 -0700271 std::vector<std::string> verbose_options;
Elliott Hughes34023802011-08-30 12:06:17 -0700272 Split(option.substr(strlen("-verbose:")).data(), ',', verbose_options);
Elliott Hughes0af55432011-08-17 18:37:28 -0700273 for (size_t i = 0; i < verbose_options.size(); ++i) {
274 parsed->verbose_.insert(verbose_options[i]);
275 }
Brian Carlstrom6ea095a2011-08-16 15:26:54 -0700276 } else if (option == "vfprintf") {
277 parsed->hook_vfprintf_ = reinterpret_cast<int (*)(FILE *, const char*, va_list)>(options[i].second);
278 } else if (option == "exit") {
279 parsed->hook_exit_ = reinterpret_cast<void(*)(jint)>(options[i].second);
280 } else if (option == "abort") {
281 parsed->hook_abort_ = reinterpret_cast<void(*)()>(options[i].second);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700282 } else if (option == "host-prefix") {
283 parsed->host_prefix_ = reinterpret_cast<const char*>(options[i].second);
Brian Carlstrom8a436592011-08-15 21:27:23 -0700284 } else {
285 if (!ignore_unrecognized) {
Brian Carlstrom6ea095a2011-08-16 15:26:54 -0700286 // TODO: print usage via vfprintf
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700287 LOG(ERROR) << "Unrecognized option " << option;
288 // TODO: this should exit, but for now tolerate unknown options
289 //return NULL;
Brian Carlstrom8a436592011-08-15 21:27:23 -0700290 }
291 }
292 }
293
Elliott Hughes85d15452011-09-16 17:33:01 -0700294 LOG(INFO) << "CheckJNI is " << (parsed->check_jni_ ? "on" : "off");
295
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700296 return parsed.release();
Brian Carlstrom8a436592011-08-15 21:27:23 -0700297}
298
299Runtime* Runtime::Create(const Options& options, bool ignore_unrecognized) {
Carl Shapiro2ed144c2011-07-26 16:52:08 -0700300 // TODO: acquire a static mutex on Runtime to avoid racing.
301 if (Runtime::instance_ != NULL) {
302 return NULL;
303 }
Elliott Hughesdcc24742011-09-07 14:02:44 -0700304 instance_ = new Runtime;
305 if (!instance_->Init(options, ignore_unrecognized)) {
306 delete instance_;
307 instance_ = NULL;
Carl Shapiro61e019d2011-07-14 16:53:09 -0700308 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700309 return instance_;
310}
Elliott Hughes0af55432011-08-17 18:37:28 -0700311
Brian Carlstromaded5f72011-10-07 17:15:04 -0700312void CreateSystemClassLoader() {
313 if (ClassLoader::UseCompileTimeClassPath()) {
314 return;
315 }
316
317 Thread* self = Thread::Current();
318
319 // Must be in the kNative state for calling native methods.
320 CHECK_EQ(self->GetState(), Thread::kNative);
321
322 JNIEnv* env = self->GetJniEnv();
323 ScopedLocalRef<jclass> c(env, env->FindClass("java/lang/ClassLoader"));
324 CHECK(c.get() != NULL);
325 jmethodID mid = env->GetStaticMethodID(c.get(),
326 "getSystemClassLoader", "()Ljava/lang/ClassLoader;");
327 CHECK(mid != NULL);
328 ScopedLocalRef<jobject> result(env, env->CallStaticObjectMethod(c.get(), mid));
329 CHECK(result.get() != NULL);
330
331 ClassLoader* class_loader = Decode<ClassLoader*>(env, result.get());
332 Thread::Current()->SetClassLoaderOverride(class_loader);
333}
334
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700335void Runtime::Start() {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700336 if (IsVerboseStartup()) {
337 LOG(INFO) << "Runtime::Start entering";
338 }
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700339
340 CHECK(host_prefix_.empty()) << host_prefix_;
341
Elliott Hughes038a8062011-09-18 14:12:41 -0700342 InitNativeMethods();
Elliott Hughes85d15452011-09-16 17:33:01 -0700343
Elliott Hughes038a8062011-09-18 14:12:41 -0700344 Thread::FinishStartup();
Elliott Hughes85d15452011-09-16 17:33:01 -0700345
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700346 class_linker_->RunRootClinits();
Brian Carlstromf867b6f2011-09-16 12:17:25 -0700347
Brian Carlstrom5d40f182011-09-26 22:29:18 -0700348 // Class::AllocObject asserts that all objects allocated better be
349 // initialized after Runtime::IsStarted is true, so this needs to
350 // come after ClassLinker::RunRootClinits.
351 started_ = true;
352
Elliott Hughes85d15452011-09-16 17:33:01 -0700353 StartDaemonThreads();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700354
Brian Carlstromaded5f72011-10-07 17:15:04 -0700355 CreateSystemClassLoader();
356
Elliott Hughes726079d2011-10-07 18:43:44 -0700357 Thread::Current()->GetJniEnv()->locals.AssertEmpty();
358
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700359 if (IsVerboseStartup()) {
360 LOG(INFO) << "Runtime::Start exiting";
361 }
Elliott Hughes85d15452011-09-16 17:33:01 -0700362}
363
364void Runtime::StartDaemonThreads() {
365 signal_catcher_ = new SignalCatcher;
366
Elliott Hughes719b3232011-09-25 17:42:19 -0700367 Thread* self = Thread::Current();
Brian Carlstromaded5f72011-10-07 17:15:04 -0700368
369 // Must be in the kNative state for calling native methods.
370 CHECK_EQ(self->GetState(), Thread::kNative);
371
Elliott Hughes719b3232011-09-25 17:42:19 -0700372 JNIEnv* env = self->GetJniEnv();
Elliott Hughes726079d2011-10-07 18:43:44 -0700373 ScopedLocalRef<jclass> c(env, env->FindClass("java/lang/Daemons"));
374 CHECK(c.get() != NULL);
375 jmethodID mid = env->GetStaticMethodID(c.get(), "start", "()V");
Elliott Hughes719b3232011-09-25 17:42:19 -0700376 CHECK(mid != NULL);
Elliott Hughes726079d2011-10-07 18:43:44 -0700377 env->CallStaticVoidMethod(c.get(), mid);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700378}
379
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700380bool Runtime::IsStarted() const {
Elliott Hughesdcc24742011-09-07 14:02:44 -0700381 return started_;
382}
383
Elliott Hughes0af55432011-08-17 18:37:28 -0700384bool Runtime::Init(const Options& raw_options, bool ignore_unrecognized) {
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700385 CHECK_EQ(sysconf(_SC_PAGE_SIZE), kPageSize);
Brian Carlstrom6ea095a2011-08-16 15:26:54 -0700386
Elliott Hughes90a33692011-08-30 13:27:07 -0700387 UniquePtr<ParsedOptions> options(ParsedOptions::Create(raw_options, ignore_unrecognized));
388 if (options.get() == NULL) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700389 LOG(ERROR) << "Failed to parse options";
Brian Carlstrom6ea095a2011-08-16 15:26:54 -0700390 return false;
391 }
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700392 verbose_startup_ = options->IsVerbose("startup");
393 if (IsVerboseStartup()) {
394 LOG(INFO) << "Runtime::Init -verbose:startup enabled";
395 }
Elliott Hughes7ede61e2011-09-14 18:18:06 -0700396
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700397 host_prefix_ = options->host_prefix_;
398 boot_class_path_ = options->boot_class_path_;
399 class_path_ = options->class_path_;
Elliott Hughes7ede61e2011-09-14 18:18:06 -0700400 properties_ = options->properties_;
401
Elliott Hughes0af55432011-08-17 18:37:28 -0700402 vfprintf_ = options->hook_vfprintf_;
403 exit_ = options->hook_exit_;
404 abort_ = options->hook_abort_;
Brian Carlstrom6ea095a2011-08-16 15:26:54 -0700405
Elliott Hughesbe759c62011-09-08 19:38:21 -0700406 default_stack_size_ = options->stack_size_;
Brian Carlstrom6ea095a2011-08-16 15:26:54 -0700407
Elliott Hughes14357e82011-09-26 10:42:15 -0700408 thread_list_ = new ThreadList(options->IsVerbose("thread"));
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700409 intern_table_ = new InternTable;
410
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700411 Heap::Init(options->heap_initial_size_, options->heap_maximum_size_, options->images_);
Brian Carlstrom6ea095a2011-08-16 15:26:54 -0700412
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700413 BlockSignals();
414
Elliott Hughesa0957642011-09-02 14:27:33 -0700415 java_vm_ = new JavaVMExt(this, options.get());
Elliott Hughes515a5bc2011-08-17 11:08:34 -0700416
Elliott Hughesbe759c62011-09-08 19:38:21 -0700417 Thread::Startup();
Elliott Hughesd92bec42011-09-02 17:04:36 -0700418
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700419 // ClassLinker needs an attached thread, but we can't fully attach a thread
420 // without creating objects.
421 Thread::Attach(this, "main", false);
Brian Carlstrom6ea095a2011-08-16 15:26:54 -0700422
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700423 CHECK_GE(Heap::GetSpaces().size(), 1U);
424 class_linker_ = ((Heap::GetSpaces()[0]->IsImageSpace())
425 ? ClassLinker::Create(intern_table_)
426 : ClassLinker::Create(options->boot_class_path_, intern_table_));
Brian Carlstrom6ea095a2011-08-16 15:26:54 -0700427
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700428 if (IsVerboseStartup()) {
429 LOG(INFO) << "Runtime::Init exiting";
430 }
Carl Shapiro1fb86202011-06-27 17:43:13 -0700431 return true;
432}
433
Elliott Hughes038a8062011-09-18 14:12:41 -0700434void Runtime::InitNativeMethods() {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700435 if (IsVerboseStartup()) {
436 LOG(INFO) << "Runtime::InitNativeMethods entering";
437 }
Elliott Hughesad7c2a32011-08-31 11:58:10 -0700438 Thread* self = Thread::Current();
439 JNIEnv* env = self->GetJniEnv();
440
Elliott Hughes418d20f2011-09-22 14:00:39 -0700441 // Must be in the kNative state for calling native methods (JNI_OnLoad code).
Brian Carlstromaded5f72011-10-07 17:15:04 -0700442 CHECK_EQ(self->GetState(), Thread::kNative);
Elliott Hughesad7c2a32011-08-31 11:58:10 -0700443
Elliott Hughes418d20f2011-09-22 14:00:39 -0700444 // First set up JniConstants, which is used by both the runtime's built-in native
445 // methods and libcore.
Elliott Hughesfea966e2011-09-22 10:26:20 -0700446 JniConstants::init(env);
447
Elliott Hughes418d20f2011-09-22 14:00:39 -0700448 // Then set up the native methods provided by the runtime itself.
Elliott Hughesad7c2a32011-08-31 11:58:10 -0700449 RegisterRuntimeNativeMethods(env);
450
Elliott Hughes418d20f2011-09-22 14:00:39 -0700451 // Then set up libcore, which is just a regular JNI library with a regular JNI_OnLoad.
452 // Most JNI libraries can just use System.loadLibrary, but libcore can't because it's
453 // the library that implements System.loadLibrary!
Elliott Hughesad7c2a32011-08-31 11:58:10 -0700454 LoadJniLibrary(instance_->GetJavaVM(), "javacore");
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700455 if (IsVerboseStartup()) {
456 LOG(INFO) << "Runtime::InitNativeMethods exiting";
457 }
Elliott Hughesad7c2a32011-08-31 11:58:10 -0700458}
459
460void Runtime::RegisterRuntimeNativeMethods(JNIEnv* env) {
461#define REGISTER(FN) extern void FN(JNIEnv*); FN(env)
Brian Carlstromf91c8c32011-09-21 17:30:34 -0700462 REGISTER(register_dalvik_system_DexFile);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700463 REGISTER(register_dalvik_system_VMDebug);
Elliott Hughes7ede61e2011-09-14 18:18:06 -0700464 REGISTER(register_dalvik_system_VMRuntime);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700465 REGISTER(register_dalvik_system_VMStack);
Elliott Hughes01158d72011-09-19 19:47:10 -0700466 REGISTER(register_dalvik_system_Zygote);
Elliott Hughesd369bb72011-09-12 14:41:14 -0700467 REGISTER(register_java_lang_Class);
Elliott Hughesbf86d042011-08-31 17:53:14 -0700468 REGISTER(register_java_lang_Object);
469 REGISTER(register_java_lang_Runtime);
470 REGISTER(register_java_lang_String);
471 REGISTER(register_java_lang_System);
Elliott Hughes8daa0922011-09-11 13:46:25 -0700472 REGISTER(register_java_lang_Thread);
Elliott Hughes1240dad2011-09-09 16:24:50 -0700473 REGISTER(register_java_lang_Throwable);
Elliott Hughes64bf5a32011-09-20 14:43:12 -0700474 REGISTER(register_java_lang_VMClassLoader);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700475 REGISTER(register_java_lang_reflect_Array);
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700476 REGISTER(register_java_lang_reflect_Constructor);
Brian Carlstromf867b6f2011-09-16 12:17:25 -0700477 REGISTER(register_java_lang_reflect_Field);
478 REGISTER(register_java_lang_reflect_Method);
Elliott Hughesad7c2a32011-08-31 11:58:10 -0700479 //REGISTER(register_java_lang_reflect_Proxy);
Elliott Hughesbf86d042011-08-31 17:53:14 -0700480 REGISTER(register_java_util_concurrent_atomic_AtomicLong);
Brian Carlstrom395520e2011-09-25 19:35:00 -0700481 REGISTER(register_org_apache_harmony_dalvik_ddmc_DdmServer);
Elliott Hughesad7c2a32011-08-31 11:58:10 -0700482 //REGISTER(register_org_apache_harmony_dalvik_ddmc_DdmVmInternal);
Elliott Hughes5ee7a8b2011-09-13 16:40:07 -0700483 REGISTER(register_sun_misc_Unsafe);
Elliott Hughesad7c2a32011-08-31 11:58:10 -0700484#undef REGISTER
485}
486
Elliott Hughes8daa0922011-09-11 13:46:25 -0700487void Runtime::Dump(std::ostream& os) {
Elliott Hughese27955c2011-08-26 15:21:24 -0700488 // TODO: dump other runtime statistics?
489 os << "Loaded classes: " << class_linker_->NumLoadedClasses() << "\n";
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700490 os << "Intern table size: " << GetInternTable()->Size() << "\n";
Elliott Hughese27955c2011-08-26 15:21:24 -0700491 // LOGV("VM stats: meth=%d ifld=%d sfld=%d linear=%d",
492 // gDvm.numDeclaredMethods,
493 // gDvm.numDeclaredInstFields,
494 // gDvm.numDeclaredStaticFields,
495 // gDvm.pBootLoaderAlloc->curOffset);
496 // LOGI("GC precise methods: %d", dvmPointerSetGetCount(gDvm.preciseMethods));
Elliott Hughes42ee1422011-09-06 12:33:32 -0700497 os << "\n";
Elliott Hughes8daa0922011-09-11 13:46:25 -0700498
499 thread_list_->Dump(os);
Elliott Hughese27955c2011-08-26 15:21:24 -0700500}
501
Elliott Hughes9d5ccec2011-09-19 13:19:50 -0700502void Runtime::SetStatsEnabled(bool new_state) {
503 if (new_state == true) {
504 GetStats()->Clear(~0);
505 // TODO: wouldn't it make more sense to clear _all_ threads' stats?
506 Thread::Current()->GetStats()->Clear(~0);
507 }
508 stats_enabled_ = new_state;
509}
510
511void Runtime::ResetStats(int kinds) {
512 GetStats()->Clear(kinds & 0xffff);
513 // TODO: wouldn't it make more sense to clear _all_ threads' stats?
514 Thread::Current()->GetStats()->Clear(kinds >> 16);
515}
516
517RuntimeStats* Runtime::GetStats() {
518 return &stats_;
519}
520
521int32_t Runtime::GetStat(int kind) {
522 RuntimeStats* stats;
523 if (kind < (1<<16)) {
524 stats = GetStats();
525 } else {
526 stats = Thread::Current()->GetStats();
527 kind >>= 16;
528 }
529 switch (kind) {
530 case KIND_ALLOCATED_OBJECTS:
531 return stats->allocated_objects;
532 case KIND_ALLOCATED_BYTES:
533 return stats->allocated_bytes;
534 case KIND_FREED_OBJECTS:
535 return stats->freed_objects;
536 case KIND_FREED_BYTES:
537 return stats->freed_bytes;
538 case KIND_GC_INVOCATIONS:
539 return stats->gc_for_alloc_count;
540 case KIND_CLASS_INIT_COUNT:
541 return stats->class_init_count;
542 case KIND_CLASS_INIT_TIME:
543 // Convert ns to us, reduce to 32 bits.
544 return (int) (stats->class_init_time_ns / 1000);
545 case KIND_EXT_ALLOCATED_OBJECTS:
546 case KIND_EXT_ALLOCATED_BYTES:
547 case KIND_EXT_FREED_OBJECTS:
548 case KIND_EXT_FREED_BYTES:
549 return 0; // backward compatibility
550 default:
551 CHECK(false);
552 return -1; // unreachable
553 }
554}
555
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700556void Runtime::BlockSignals() {
557 sigset_t sigset;
558 if (sigemptyset(&sigset) == -1) {
559 PLOG(FATAL) << "sigemptyset failed";
560 }
561 if (sigaddset(&sigset, SIGPIPE) == -1) {
562 PLOG(ERROR) << "sigaddset SIGPIPE failed";
563 }
564 // SIGQUIT is used to dump the runtime's state (including stack traces).
565 if (sigaddset(&sigset, SIGQUIT) == -1) {
566 PLOG(ERROR) << "sigaddset SIGQUIT failed";
567 }
568 // SIGUSR1 is used to initiate a heap dump.
569 if (sigaddset(&sigset, SIGUSR1) == -1) {
570 PLOG(ERROR) << "sigaddset SIGUSR1 failed";
571 }
572 CHECK_EQ(sigprocmask(SIG_BLOCK, &sigset, NULL), 0);
573}
574
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700575void Runtime::AttachCurrentThread(const char* name, bool as_daemon) {
576 Thread::Attach(instance_, name, as_daemon);
Carl Shapiro61e019d2011-07-14 16:53:09 -0700577}
578
Elliott Hughesd92bec42011-09-02 17:04:36 -0700579void Runtime::DetachCurrentThread() {
Elliott Hughes038a8062011-09-18 14:12:41 -0700580 // TODO: check we're not calling DetachCurrentThread from a call stack that
581 // includes managed frames. (It's only valid if the stack is all-native.)
Elliott Hughes02b48d12011-09-07 17:15:51 -0700582 thread_list_->Unregister();
Carl Shapiro1fb86202011-06-27 17:43:13 -0700583}
584
Brian Carlstrome24fa612011-09-29 00:53:55 -0700585void Runtime::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
586 class_linker_->VisitRoots(visitor, arg);
587 intern_table_->VisitRoots(visitor, arg);
588 java_vm_->VisitRoots(visitor, arg);
589 thread_list_->VisitRoots(visitor, arg);
590 visitor(jni_stub_array_, arg);
591 visitor(abstract_method_error_stub_array_, arg);
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700592 for (int i = 0; i < Runtime::kLastTrampolineMethodType; i++) {
593 visitor(resolution_stub_array_[i], arg);
594 }
595 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
596 visitor(callee_save_method_[i], arg);
597 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700598
599 //(*visitor)(&gDvm.outOfMemoryObj, 0, ROOT_VM_INTERNAL, arg);
600 //(*visitor)(&gDvm.internalErrorObj, 0, ROOT_VM_INTERNAL, arg);
601 //(*visitor)(&gDvm.noClassDefFoundErrorObj, 0, ROOT_VM_INTERNAL, arg);
602 UNIMPLEMENTED(WARNING) << "some roots not marked";
603}
604
605bool Runtime::HasJniStubArray() const {
606 return jni_stub_array_ != NULL;
607}
608
609ByteArray* Runtime::GetJniStubArray() const {
610 CHECK(jni_stub_array_ != NULL);
611 return jni_stub_array_;
612}
613
614void Runtime::SetJniStubArray(ByteArray* jni_stub_array) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700615 CHECK(jni_stub_array != NULL) << " jni_stub_array=" << jni_stub_array;
616 CHECK(jni_stub_array_ == NULL || jni_stub_array_ == jni_stub_array)
617 << "jni_stub_array_=" << jni_stub_array_ << " jni_stub_array=" << jni_stub_array;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700618 jni_stub_array_ = jni_stub_array;
619}
620
621bool Runtime::HasAbstractMethodErrorStubArray() const {
622 return abstract_method_error_stub_array_ != NULL;
623}
624
625ByteArray* Runtime::GetAbstractMethodErrorStubArray() const {
626 CHECK(abstract_method_error_stub_array_ != NULL);
627 return abstract_method_error_stub_array_;
628}
629
630void Runtime::SetAbstractMethodErrorStubArray(ByteArray* abstract_method_error_stub_array) {
631 CHECK(abstract_method_error_stub_array != NULL);
632 CHECK(abstract_method_error_stub_array_ == NULL || abstract_method_error_stub_array_ == abstract_method_error_stub_array);
633 abstract_method_error_stub_array_ = abstract_method_error_stub_array;
634}
635
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700636
637Runtime::TrampolineType Runtime::GetTrampolineType(Method* method) {
638 if (method == NULL) {
639 return Runtime::kUnknownMethod;
640 } else if (method->IsStatic()) {
641 return Runtime::kStaticMethod;
642 } else {
643 return Runtime::kInstanceMethod;
644 }
Ian Rogersad25ac52011-10-04 19:13:33 -0700645}
646
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700647bool Runtime::HasResolutionStubArray(TrampolineType type) const {
648 return resolution_stub_array_[type] != NULL;
Ian Rogersad25ac52011-10-04 19:13:33 -0700649}
650
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700651ByteArray* Runtime::GetResolutionStubArray(TrampolineType type) const {
652 CHECK(HasResolutionStubArray(type));
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700653 DCHECK_LT(static_cast<int>(type), static_cast<int>(kLastTrampolineMethodType));
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700654 return resolution_stub_array_[type];
655}
656
657void Runtime::SetResolutionStubArray(ByteArray* resolution_stub_array, TrampolineType type) {
Ian Rogersad25ac52011-10-04 19:13:33 -0700658 CHECK(resolution_stub_array != NULL);
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700659 CHECK(!HasResolutionStubArray(type) || resolution_stub_array_[type] == resolution_stub_array);
660 resolution_stub_array_[type] = resolution_stub_array;
Ian Rogersad25ac52011-10-04 19:13:33 -0700661}
662
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700663Method* Runtime::CreateCalleeSaveMethod(InstructionSet insns, CalleeSaveType type) {
Ian Rogersff1ed472011-09-20 13:46:24 -0700664 Class* method_class = Method::GetMethodClass();
665 Method* method = down_cast<Method*>(method_class->AllocObject());
666 method->SetDeclaringClass(method_class);
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700667 const char* name;
668 if (type == kSaveAll) {
669 name = "$$$callee_save_method$$$";
670 } else if (type == kRefsOnly) {
671 name = "$$$refs_only_callee_save_method$$$";
672 } else {
673 DCHECK(type == kRefsAndArgs);
674 name = "$$$refs_and_args_callee_save_method$$$";
675 }
676 method->SetName(intern_table_->InternStrong(name));
Ian Rogersff1ed472011-09-20 13:46:24 -0700677 method->SetSignature(intern_table_->InternStrong("()V"));
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700678 method->SetCode(NULL);
Ian Rogersff1ed472011-09-20 13:46:24 -0700679 if ((insns == kThumb2) || (insns == kArm)) {
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700680 uint32_t ref_spills = (1 << art::arm::R5) | (1 << art::arm::R6) | (1 << art::arm::R7) |
681 (1 << art::arm::R8) | (1 << art::arm::R10) | (1 << art::arm::R11);
682 uint32_t arg_spills = (1 << art::arm::R1) | (1 << art::arm::R2) | (1 << art::arm::R3);
683 uint32_t all_spills = (1 << art::arm::R4) | (1 << art::arm::R9);
684 uint32_t core_spills = ref_spills | (type == kRefsAndArgs ? arg_spills :0) |
685 (type == kSaveAll ? all_spills :0) | (1 << art::arm::LR);
686 uint32_t fp_all_spills = (1 << art::arm::S0) | (1 << art::arm::S1) | (1 << art::arm::S2) |
687 (1 << art::arm::S3) | (1 << art::arm::S4) | (1 << art::arm::S5) |
688 (1 << art::arm::S6) | (1 << art::arm::S7) | (1 << art::arm::S8) |
689 (1 << art::arm::S9) | (1 << art::arm::S10) | (1 << art::arm::S11) |
690 (1 << art::arm::S12) | (1 << art::arm::S13) | (1 << art::arm::S14) |
691 (1 << art::arm::S15) | (1 << art::arm::S16) | (1 << art::arm::S17) |
692 (1 << art::arm::S18) | (1 << art::arm::S19) | (1 << art::arm::S20) |
693 (1 << art::arm::S21) | (1 << art::arm::S22) | (1 << art::arm::S23) |
694 (1 << art::arm::S24) | (1 << art::arm::S25) | (1 << art::arm::S26) |
695 (1 << art::arm::S27) | (1 << art::arm::S28) | (1 << art::arm::S29) |
696 (1 << art::arm::S30) | (1 << art::arm::S31);
697 uint32_t fp_spills = type == kSaveAll ? fp_all_spills : 0;
698 size_t frame_size = RoundUp((__builtin_popcount(core_spills) /* gprs */ +
699 __builtin_popcount(fp_spills) /* fprs */ +
700 1 /* Method* */) * kPointerSize, kStackAlignment);
Ian Rogers15fdb8c2011-09-25 15:45:07 -0700701 method->SetFrameSizeInBytes(frame_size);
702 method->SetReturnPcOffsetInBytes(frame_size - kPointerSize);
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700703 method->SetCoreSpillMask(core_spills);
704 method->SetFpSpillMask(fp_spills);
Ian Rogersff1ed472011-09-20 13:46:24 -0700705 } else if (insns == kX86) {
706 method->SetFrameSizeInBytes(32);
707 method->SetReturnPcOffsetInBytes(28);
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700708 method->SetCoreSpillMask((1 << art::x86::EBX) | (1 << art::x86::EBP) | (1 << art::x86::ESI) |
Ian Rogersff1ed472011-09-20 13:46:24 -0700709 (1 << art::x86::EDI));
710 method->SetFpSpillMask(0);
711 } else {
712 UNIMPLEMENTED(FATAL);
713 }
714 return method;
715}
716
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700717bool Runtime::HasCalleeSaveMethod(CalleeSaveType type) const {
718 return callee_save_method_[type] != NULL;
Brian Carlstrom1f870082011-08-23 16:02:11 -0700719}
720
Brian Carlstrome24fa612011-09-29 00:53:55 -0700721// Returns a special method that describes all callee saves being spilled to the stack.
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700722Method* Runtime::GetCalleeSaveMethod(CalleeSaveType type) const {
723 CHECK(HasCalleeSaveMethod(type));
724 return callee_save_method_[type];
Brian Carlstrome24fa612011-09-29 00:53:55 -0700725}
726
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700727void Runtime::SetCalleeSaveMethod(Method* method, CalleeSaveType type) {
728 DCHECK_LT(static_cast<int>(type), static_cast<int>(kLastCalleeSaveType));
729 callee_save_method_[type] = method;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700730}
731
Carl Shapiro1fb86202011-06-27 17:43:13 -0700732} // namespace art