blob: 366374575950319715a7092f9d82f66bc64094e2 [file] [log] [blame]
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/*
18 * Dalvik initialization, shutdown, and command-line argument processing.
19 */
20#include "Dalvik.h"
21#include "test/Test.h"
22#include "mterp/Mterp.h"
Ben Chengba4fc8b2009-06-01 13:00:29 -070023#include "Hash.h"
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080024
25#include <stdlib.h>
26#include <stdio.h>
27#include <signal.h>
28#include <limits.h>
29#include <ctype.h>
30#include <sys/wait.h>
31#include <unistd.h>
32
33#define kMinHeapStartSize (1*1024*1024)
34#define kMinHeapSize (2*1024*1024)
35#define kMaxHeapSize (1*1024*1024*1024)
36
37/*
38 * Register VM-agnostic native methods for system classes.
39 *
40 * Currently defined in ../include/nativehelper/AndroidSystemNatives.h
41 */
42extern int jniRegisterSystemMethods(JNIEnv* env);
43
44/* fwd */
45static bool registerSystemNatives(JNIEnv* pEnv);
46static bool dvmInitJDWP(void);
47static bool dvmInitZygote(void);
48
49
50/* global state */
51struct DvmGlobals gDvm;
52
Ben Chengba4fc8b2009-06-01 13:00:29 -070053/* JIT-specific global state */
54#if defined(WITH_JIT)
55struct DvmJitGlobals gDvmJit;
56#endif
57
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080058/*
59 * Show usage.
60 *
61 * We follow the tradition of unhyphenated compound words.
62 */
63static void dvmUsage(const char* progName)
64{
65 dvmFprintf(stderr, "%s: [options] class [argument ...]\n", progName);
66 dvmFprintf(stderr, "%s: [options] -jar file.jar [argument ...]\n",progName);
67 dvmFprintf(stderr, "\n");
68 dvmFprintf(stderr, "The following standard options are recognized:\n");
69 dvmFprintf(stderr, " -classpath classpath\n");
70 dvmFprintf(stderr, " -Dproperty=value\n");
71 dvmFprintf(stderr, " -verbose:tag ('gc', 'jni', or 'class')\n");
72 dvmFprintf(stderr, " -ea[:<package name>... |:<class name>]\n");
73 dvmFprintf(stderr, " -da[:<package name>... |:<class name>]\n");
74 dvmFprintf(stderr, " (-enableassertions, -disableassertions)\n");
75 dvmFprintf(stderr, " -esa\n");
76 dvmFprintf(stderr, " -dsa\n");
77 dvmFprintf(stderr,
78 " (-enablesystemassertions, -disablesystemassertions)\n");
79 dvmFprintf(stderr, " -showversion\n");
80 dvmFprintf(stderr, " -help\n");
81 dvmFprintf(stderr, "\n");
82 dvmFprintf(stderr, "The following extended options are recognized:\n");
83 dvmFprintf(stderr, " -Xrunjdwp:<options>\n");
84 dvmFprintf(stderr, " -Xbootclasspath:bootclasspath\n");
85 dvmFprintf(stderr, " -Xcheck:tag (e.g. 'jni')\n");
86 dvmFprintf(stderr, " -XmsN (min heap, must be multiple of 1K, >= 1MB)\n");
87 dvmFprintf(stderr, " -XmxN (max heap, must be multiple of 1K, >= 2MB)\n");
88 dvmFprintf(stderr, " -XssN (stack size, >= %dKB, <= %dKB)\n",
89 kMinStackSize / 1024, kMaxStackSize / 1024);
90 dvmFprintf(stderr, " -Xverify:{none,remote,all}\n");
91 dvmFprintf(stderr, " -Xrs\n");
Ben Chengba4fc8b2009-06-01 13:00:29 -070092#if defined(WITH_JIT)
93 dvmFprintf(stderr,
94 " -Xint (extended to accept ':portable', ':fast' and ':jit')\n");
95#else
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080096 dvmFprintf(stderr,
97 " -Xint (extended to accept ':portable' and ':fast')\n");
Ben Chengba4fc8b2009-06-01 13:00:29 -070098#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -080099 dvmFprintf(stderr, "\n");
100 dvmFprintf(stderr, "These are unique to Dalvik:\n");
101 dvmFprintf(stderr, " -Xzygote\n");
102 dvmFprintf(stderr, " -Xdexopt:{none,verified,all}\n");
103 dvmFprintf(stderr, " -Xnoquithandler\n");
104 dvmFprintf(stderr,
105 " -Xjnigreflimit:N (must be multiple of 100, >= 200)\n");
106 dvmFprintf(stderr, " -Xjniopts:{warnonly,forcecopy}\n");
107 dvmFprintf(stderr, " -Xdeadlockpredict:{off,warn,err,abort}\n");
108 dvmFprintf(stderr, " -Xstacktracefile:<filename>\n");
The Android Open Source Project99409882009-03-18 22:20:24 -0700109 dvmFprintf(stderr, " -Xgc:[no]precise\n");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800110 dvmFprintf(stderr, " -Xgenregmap\n");
111 dvmFprintf(stderr, " -Xcheckdexsum\n");
Ben Chengba4fc8b2009-06-01 13:00:29 -0700112#if defined(WITH_JIT)
113 dvmFprintf(stderr, " -Xincludeselectedop\n");
114 dvmFprintf(stderr, " -Xjitop:hexopvalue[-endvalue]"
115 "[,hexopvalue[-endvalue]]*\n");
116 dvmFprintf(stderr, " -Xincludeselectedmethod\n");
117 dvmFprintf(stderr, " -Xthreshold:decimalvalue\n");
118 dvmFprintf(stderr, " -Xblocking\n");
119 dvmFprintf(stderr, " -Xjitmethod:signture[,signature]* "
120 "(eg Ljava/lang/String\\;replace)\n");
121 dvmFprintf(stderr, " -Xjitverbose\n");
Bill Buzbee6e963e12009-06-17 16:56:19 -0700122 dvmFprintf(stderr, " -Xjitprofile\n");
Ben Chengba4fc8b2009-06-01 13:00:29 -0700123#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800124 dvmFprintf(stderr, "\n");
125 dvmFprintf(stderr, "Configured with:"
126#ifdef WITH_DEBUGGER
127 " debugger"
128#endif
129#ifdef WITH_PROFILER
130 " profiler"
131#endif
132#ifdef WITH_MONITOR_TRACKING
133 " monitor_tracking"
134#endif
135#ifdef WITH_DEADLOCK_PREDICTION
136 " deadlock_prediction"
137#endif
138#ifdef WITH_HPROF
139 " hprof"
140#endif
141#ifdef WITH_HPROF_STACK
142 " hprof_stack"
143#endif
144#ifdef WITH_HPROF_STACK_UNREACHABLE
145 " hprof_stack_unreachable"
146#endif
147#ifdef WITH_ALLOC_LIMITS
148 " alloc_limits"
149#endif
150#ifdef WITH_TRACKREF_CHECKS
151 " trackref_checks"
152#endif
153#ifdef WITH_INSTR_CHECKS
154 " instr_checks"
155#endif
156#ifdef WITH_EXTRA_OBJECT_VALIDATION
157 " extra_object_validation"
158#endif
The Android Open Source Project99409882009-03-18 22:20:24 -0700159#ifdef WITH_EXTRA_GC_CHECKS
160 " extra_gc_checks"
161#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800162#ifdef WITH_DALVIK_ASSERT
163 " dalvik_assert"
164#endif
165#ifdef WITH_JNI_STACK_CHECK
166 " jni_stack_check"
167#endif
168#ifdef EASY_GDB
169 " easy_gdb"
170#endif
171#ifdef CHECK_MUTEX
172 " check_mutex"
173#endif
174#ifdef PROFILE_FIELD_ACCESS
175 " profile_field_access"
176#endif
177#ifdef DVM_TRACK_HEAP_MARKING
178 " track_heap_marking"
179#endif
180#if DVM_RESOLVER_CACHE == DVM_RC_REDUCING
181 " resolver_cache_reducing"
182#elif DVM_RESOLVER_CACHE == DVM_RC_EXPANDING
183 " resolver_cache_expanding"
184#elif DVM_RESOLVER_CACHE == DVM_RC_NO_CACHE
185 " resolver_cache_disabled"
186#endif
Ben Chengba4fc8b2009-06-01 13:00:29 -0700187#if defined(WITH_JIT)
188 " with_jit"
189#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800190 );
191#ifdef DVM_SHOW_EXCEPTION
192 dvmFprintf(stderr, " show_exception=%d", DVM_SHOW_EXCEPTION);
193#endif
194 dvmFprintf(stderr, "\n\n");
195}
196
197/*
198 * Show helpful information on JDWP options.
199 */
200static void showJdwpHelp(void)
201{
202 dvmFprintf(stderr,
203 "Example: -Xrunjdwp:transport=dt_socket,address=8000,server=y\n");
204 dvmFprintf(stderr,
205 "Example: -Xrunjdwp:transport=dt_socket,address=localhost:6500,server=n\n");
206}
207
208/*
209 * Show version and copyright info.
210 */
211static void showVersion(void)
212{
213 dvmFprintf(stdout, "DalvikVM version %d.%d.%d\n",
214 DALVIK_MAJOR_VERSION, DALVIK_MINOR_VERSION, DALVIK_BUG_VERSION);
215 dvmFprintf(stdout,
216 "Copyright (C) 2007 The Android Open Source Project\n\n"
217 "This software is built from source code licensed under the "
218 "Apache License,\n"
219 "Version 2.0 (the \"License\"). You may obtain a copy of the "
220 "License at\n\n"
221 " http://www.apache.org/licenses/LICENSE-2.0\n\n"
222 "See the associated NOTICE file for this software for further "
223 "details.\n");
224}
225
226/*
227 * Parse a string of the form /[0-9]+[kKmMgG]?/, which is used to specify
228 * memory sizes. [kK] indicates kilobytes, [mM] megabytes, and
229 * [gG] gigabytes.
230 *
231 * "s" should point just past the "-Xm?" part of the string.
232 * "min" specifies the lowest acceptable value described by "s".
233 * "div" specifies a divisor, e.g. 1024 if the value must be a multiple
234 * of 1024.
235 *
236 * The spec says the -Xmx and -Xms options must be multiples of 1024. It
237 * doesn't say anything about -Xss.
238 *
239 * Returns 0 (a useless size) if "s" is malformed or specifies a low or
240 * non-evenly-divisible value.
241 */
242static unsigned int dvmParseMemOption(const char *s, unsigned int div)
243{
244 /* strtoul accepts a leading [+-], which we don't want,
245 * so make sure our string starts with a decimal digit.
246 */
247 if (isdigit(*s)) {
248 const char *s2;
249 unsigned int val;
250
251 val = (unsigned int)strtoul(s, (char **)&s2, 10);
252 if (s2 != s) {
253 /* s2 should be pointing just after the number.
254 * If this is the end of the string, the user
255 * has specified a number of bytes. Otherwise,
256 * there should be exactly one more character
257 * that specifies a multiplier.
258 */
259 if (*s2 != '\0') {
260 char c;
261
262 /* The remainder of the string is either a single multiplier
263 * character, or nothing to indicate that the value is in
264 * bytes.
265 */
266 c = *s2++;
267 if (*s2 == '\0') {
268 unsigned int mul;
269
270 if (c == '\0') {
271 mul = 1;
272 } else if (c == 'k' || c == 'K') {
273 mul = 1024;
274 } else if (c == 'm' || c == 'M') {
275 mul = 1024 * 1024;
276 } else if (c == 'g' || c == 'G') {
277 mul = 1024 * 1024 * 1024;
278 } else {
279 /* Unknown multiplier character.
280 */
281 return 0;
282 }
283
284 if (val <= UINT_MAX / mul) {
285 val *= mul;
286 } else {
287 /* Clamp to a multiple of 1024.
288 */
289 val = UINT_MAX & ~(1024-1);
290 }
291 } else {
292 /* There's more than one character after the
293 * numeric part.
294 */
295 return 0;
296 }
297 }
298
299 /* The man page says that a -Xm value must be
300 * a multiple of 1024.
301 */
302 if (val % div == 0) {
303 return val;
304 }
305 }
306 }
307
308 return 0;
309}
310
311/*
312 * Handle one of the JDWP name/value pairs.
313 *
314 * JDWP options are:
315 * help: if specified, show help message and bail
316 * transport: may be dt_socket or dt_shmem
317 * address: for dt_socket, "host:port", or just "port" when listening
318 * server: if "y", wait for debugger to attach; if "n", attach to debugger
319 * timeout: how long to wait for debugger to connect / listen
320 *
321 * Useful with server=n (these aren't supported yet):
322 * onthrow=<exception-name>: connect to debugger when exception thrown
323 * onuncaught=y|n: connect to debugger when uncaught exception thrown
324 * launch=<command-line>: launch the debugger itself
325 *
326 * The "transport" option is required, as is "address" if server=n.
327 */
328static bool handleJdwpOption(const char* name, const char* value)
329{
330 if (strcmp(name, "transport") == 0) {
331 if (strcmp(value, "dt_socket") == 0) {
332 gDvm.jdwpTransport = kJdwpTransportSocket;
333 } else if (strcmp(value, "dt_android_adb") == 0) {
334 gDvm.jdwpTransport = kJdwpTransportAndroidAdb;
335 } else {
336 LOGE("JDWP transport '%s' not supported\n", value);
337 return false;
338 }
339 } else if (strcmp(name, "server") == 0) {
340 if (*value == 'n')
341 gDvm.jdwpServer = false;
342 else if (*value == 'y')
343 gDvm.jdwpServer = true;
344 else {
345 LOGE("JDWP option 'server' must be 'y' or 'n'\n");
346 return false;
347 }
348 } else if (strcmp(name, "suspend") == 0) {
349 if (*value == 'n')
350 gDvm.jdwpSuspend = false;
351 else if (*value == 'y')
352 gDvm.jdwpSuspend = true;
353 else {
354 LOGE("JDWP option 'suspend' must be 'y' or 'n'\n");
355 return false;
356 }
357 } else if (strcmp(name, "address") == 0) {
358 /* this is either <port> or <host>:<port> */
359 const char* colon = strchr(value, ':');
360 char* end;
361 long port;
362
363 if (colon != NULL) {
364 free(gDvm.jdwpHost);
365 gDvm.jdwpHost = (char*) malloc(colon - value +1);
366 strncpy(gDvm.jdwpHost, value, colon - value +1);
367 gDvm.jdwpHost[colon-value] = '\0';
368 value = colon + 1;
369 }
370 if (*value == '\0') {
371 LOGE("JDWP address missing port\n");
372 return false;
373 }
374 port = strtol(value, &end, 10);
375 if (*end != '\0') {
376 LOGE("JDWP address has junk in port field '%s'\n", value);
377 return false;
378 }
379 gDvm.jdwpPort = port;
380 } else if (strcmp(name, "launch") == 0 ||
381 strcmp(name, "onthrow") == 0 ||
382 strcmp(name, "oncaught") == 0 ||
383 strcmp(name, "timeout") == 0)
384 {
385 /* valid but unsupported */
386 LOGI("Ignoring JDWP option '%s'='%s'\n", name, value);
387 } else {
388 LOGI("Ignoring unrecognized JDWP option '%s'='%s'\n", name, value);
389 }
390
391 return true;
392}
393
394/*
395 * Parse the latter half of a -Xrunjdwp/-agentlib:jdwp= string, e.g.:
396 * "transport=dt_socket,address=8000,server=y,suspend=n"
397 */
398static bool parseJdwpOptions(const char* str)
399{
400 char* mangle = strdup(str);
401 char* name = mangle;
402 bool result = false;
403
404 /*
405 * Process all of the name=value pairs.
406 */
407 while (true) {
408 char* value;
409 char* comma;
410
411 value = strchr(name, '=');
412 if (value == NULL) {
413 LOGE("JDWP opts: garbage at '%s'\n", name);
414 goto bail;
415 }
416
417 comma = strchr(name, ','); // use name, not value, for safety
418 if (comma != NULL) {
419 if (comma < value) {
420 LOGE("JDWP opts: found comma before '=' in '%s'\n", mangle);
421 goto bail;
422 }
423 *comma = '\0';
424 }
425
426 *value++ = '\0'; // stomp the '='
427
428 if (!handleJdwpOption(name, value))
429 goto bail;
430
431 if (comma == NULL) {
432 /* out of options */
433 break;
434 }
435 name = comma+1;
436 }
437
438 /*
439 * Make sure the combination of arguments makes sense.
440 */
441 if (gDvm.jdwpTransport == kJdwpTransportUnknown) {
442 LOGE("JDWP opts: must specify transport\n");
443 goto bail;
444 }
445 if (!gDvm.jdwpServer && (gDvm.jdwpHost == NULL || gDvm.jdwpPort == 0)) {
446 LOGE("JDWP opts: when server=n, must specify host and port\n");
447 goto bail;
448 }
449 // transport mandatory
450 // outbound server address
451
452 gDvm.jdwpConfigured = true;
453 result = true;
454
455bail:
456 free(mangle);
457 return result;
458}
459
460/*
461 * Handle one of the four kinds of assertion arguments.
462 *
463 * "pkgOrClass" is the last part of an enable/disable line. For a package
464 * the arg looks like "-ea:com.google.fubar...", for a class it looks
465 * like "-ea:com.google.fubar.Wahoo". The string we get starts at the ':'.
466 *
467 * For system assertions (-esa/-dsa), "pkgOrClass" is NULL.
468 *
469 * Multiple instances of these arguments can be specified, e.g. you can
470 * enable assertions for a package and then disable them for one class in
471 * the package.
472 */
473static bool enableAssertions(const char* pkgOrClass, bool enable)
474{
475 AssertionControl* pCtrl = &gDvm.assertionCtrl[gDvm.assertionCtrlCount++];
476 pCtrl->enable = enable;
477
478 if (pkgOrClass == NULL) {
479 /* enable or disable for all system classes */
480 pCtrl->isPackage = false;
481 pCtrl->pkgOrClass = NULL;
482 pCtrl->pkgOrClassLen = 0;
483 } else {
484 if (*pkgOrClass == '\0') {
485 /* global enable/disable for all but system */
486 pCtrl->isPackage = false;
487 pCtrl->pkgOrClass = strdup("");
488 pCtrl->pkgOrClassLen = 0;
489 } else {
490 pCtrl->pkgOrClass = dvmDotToSlash(pkgOrClass+1); // skip ':'
491 if (pCtrl->pkgOrClass == NULL) {
492 /* can happen if class name includes an illegal '/' */
493 LOGW("Unable to process assertion arg '%s'\n", pkgOrClass);
494 return false;
495 }
496
497 int len = strlen(pCtrl->pkgOrClass);
498 if (len >= 3 && strcmp(pCtrl->pkgOrClass + len-3, "///") == 0) {
499 /* mark as package, truncate two of the three slashes */
500 pCtrl->isPackage = true;
501 *(pCtrl->pkgOrClass + len-2) = '\0';
502 pCtrl->pkgOrClassLen = len - 2;
503 } else {
504 /* just a class */
505 pCtrl->isPackage = false;
506 pCtrl->pkgOrClassLen = len;
507 }
508 }
509 }
510
511 return true;
512}
513
514/*
515 * Turn assertions on when requested to do so by the Zygote.
516 *
517 * This is a bit sketchy. We can't (easily) go back and fiddle with all
518 * of the classes that have already been initialized, so this only
519 * affects classes that have yet to be loaded. If some or all assertions
520 * have been enabled through some other means, we don't want to mess with
521 * it here, so we do nothing. Finally, we assume that there's room in
522 * "assertionCtrl" to hold at least one entry; this is guaranteed by the
523 * allocator.
524 *
525 * This must only be called from the main thread during zygote init.
526 */
527void dvmLateEnableAssertions(void)
528{
529 if (gDvm.assertionCtrl == NULL) {
530 LOGD("Not late-enabling assertions: no assertionCtrl array\n");
531 return;
532 } else if (gDvm.assertionCtrlCount != 0) {
533 LOGD("Not late-enabling assertions: some asserts already configured\n");
534 return;
535 }
536 LOGD("Late-enabling assertions\n");
537
538 /* global enable for all but system */
539 AssertionControl* pCtrl = gDvm.assertionCtrl;
540 pCtrl->pkgOrClass = strdup("");
541 pCtrl->pkgOrClassLen = 0;
542 pCtrl->isPackage = false;
543 pCtrl->enable = true;
544 gDvm.assertionCtrlCount = 1;
545}
546
547
548/*
549 * Release memory associated with the AssertionCtrl array.
550 */
551static void freeAssertionCtrl(void)
552{
553 int i;
554
555 for (i = 0; i < gDvm.assertionCtrlCount; i++)
556 free(gDvm.assertionCtrl[i].pkgOrClass);
557 free(gDvm.assertionCtrl);
558}
559
Ben Chengba4fc8b2009-06-01 13:00:29 -0700560#if defined(WITH_JIT)
561/* Parse -Xjitop to selectively turn on/off certain opcodes for JIT */
562static void processXjitop(const char *opt)
563{
564 if (opt[7] == ':') {
565 const char *startPtr = &opt[8];
566 char *endPtr = NULL;
567
568 do {
569 long startValue, endValue;
570
571 startValue = strtol(startPtr, &endPtr, 16);
572 if (startPtr != endPtr) {
573 /* Just in case value is out of range */
574 startValue &= 0xff;
575
576 if (*endPtr == '-') {
577 endValue = strtol(endPtr+1, &endPtr, 16);
578 endValue &= 0xff;
579 } else {
580 endValue = startValue;
581 }
582
583 for (; startValue <= endValue; startValue++) {
584 LOGW("Dalvik opcode %x is selected for debugging",
585 (unsigned int) startValue);
586 /* Mark the corresponding bit to 1 */
587 gDvmJit.opList[startValue >> 3] |=
588 1 << (startValue & 0x7);
589 }
590
591 if (*endPtr == 0) {
592 break;
593 }
594
595 startPtr = endPtr + 1;
596
597 continue;
598 } else {
599 if (*endPtr != 0) {
600 dvmFprintf(stderr,
601 "Warning: Unrecognized opcode value substring "
602 "%s\n", endPtr);
603 }
604 break;
605 }
606 } while (1);
607 } else {
608 int i;
609 for (i = 0; i < 32; i++) {
610 gDvmJit.opList[i] = 0xff;
611 }
612 dvmFprintf(stderr, "Warning: select all opcodes\n");
613 }
614}
615
616/* Parse -Xjitmethod to selectively turn on/off certain methods for JIT */
617static void processXjitmethod(const char *opt)
618{
619 char *buf = strdup(&opt[12]);
620 char *start, *end;
621
622 gDvmJit.methodTable = dvmHashTableCreate(8, NULL);
623
624 start = buf;
625 /*
626 * Break comma-separated method signatures and enter them into the hash
627 * table individually.
628 */
629 do {
630 int hashValue;
631
632 end = strchr(start, ',');
633 if (end) {
634 *end = 0;
635 }
636
637 hashValue = dvmComputeUtf8Hash(start);
638
639 dvmHashTableLookup(gDvmJit.methodTable, hashValue,
640 strdup(start),
641 (HashCompareFunc) strcmp, true);
642 if (end) {
643 start = end + 1;
644 } else {
645 break;
646 }
647 } while (1);
648 free(buf);
649}
650#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800651
652/*
653 * Process an argument vector full of options. Unlike standard C programs,
654 * argv[0] does not contain the name of the program.
655 *
656 * If "ignoreUnrecognized" is set, we ignore options starting with "-X" or "_"
657 * that we don't recognize. Otherwise, we return with an error as soon as
658 * we see anything we can't identify.
659 *
660 * Returns 0 on success, -1 on failure, and 1 for the special case of
661 * "-version" where we want to stop without showing an error message.
662 */
663static int dvmProcessOptions(int argc, const char* const argv[],
664 bool ignoreUnrecognized)
665{
666 int i;
667
668 LOGV("VM options (%d):\n", argc);
669 for (i = 0; i < argc; i++)
670 LOGV(" %d: '%s'\n", i, argv[i]);
671
672 /*
673 * Over-allocate AssertionControl array for convenience. If allocated,
674 * the array must be able to hold at least one entry, so that the
675 * zygote-time activation can do its business.
676 */
677 assert(gDvm.assertionCtrl == NULL);
678 if (argc > 0) {
679 gDvm.assertionCtrl =
680 (AssertionControl*) malloc(sizeof(AssertionControl) * argc);
681 if (gDvm.assertionCtrl == NULL)
682 return -1;
683 assert(gDvm.assertionCtrlCount == 0);
684 }
685
686 for (i = 0; i < argc; i++) {
687 if (strcmp(argv[i], "-help") == 0) {
688 /* show usage and stop */
689 return -1;
690
691 } else if (strcmp(argv[i], "-version") == 0) {
692 /* show version and stop */
693 showVersion();
694 return 1;
695 } else if (strcmp(argv[i], "-showversion") == 0) {
696 /* show version and continue */
697 showVersion();
698
699 } else if (strcmp(argv[i], "-classpath") == 0 ||
700 strcmp(argv[i], "-cp") == 0)
701 {
702 /* set classpath */
703 if (i == argc-1) {
704 dvmFprintf(stderr, "Missing classpath path list\n");
705 return -1;
706 }
707 free(gDvm.classPathStr); /* in case we have compiled-in default */
708 gDvm.classPathStr = strdup(argv[++i]);
709
710 } else if (strncmp(argv[i], "-Xbootclasspath:",
711 sizeof("-Xbootclasspath:")-1) == 0)
712 {
713 /* set bootclasspath */
714 const char* path = argv[i] + sizeof("-Xbootclasspath:")-1;
715
716 if (*path == '\0') {
717 dvmFprintf(stderr, "Missing bootclasspath path list\n");
718 return -1;
719 }
720 free(gDvm.bootClassPathStr);
721 gDvm.bootClassPathStr = strdup(path);
722
723 /*
724 * TODO: support -Xbootclasspath/a and /p, which append or
725 * prepend to the default bootclasspath. We set the default
726 * path earlier.
727 */
728
729 } else if (strncmp(argv[i], "-D", 2) == 0) {
730 /* set property */
731 dvmAddCommandLineProperty(argv[i] + 2);
732
733 } else if (strcmp(argv[i], "-jar") == 0) {
734 // TODO: handle this; name of jar should be in argv[i+1]
735 dvmFprintf(stderr, "-jar not yet handled\n");
736 assert(false);
737
738 } else if (strncmp(argv[i], "-Xms", 4) == 0) {
739 unsigned int val = dvmParseMemOption(argv[i]+4, 1024);
740 if (val != 0) {
741 if (val >= kMinHeapStartSize && val <= kMaxHeapSize) {
742 gDvm.heapSizeStart = val;
743 } else {
744 dvmFprintf(stderr,
745 "Invalid -Xms '%s', range is %dKB to %dKB\n",
746 argv[i], kMinHeapStartSize/1024, kMaxHeapSize/1024);
747 return -1;
748 }
749 } else {
750 dvmFprintf(stderr, "Invalid -Xms option '%s'\n", argv[i]);
751 return -1;
752 }
753 } else if (strncmp(argv[i], "-Xmx", 4) == 0) {
754 unsigned int val = dvmParseMemOption(argv[i]+4, 1024);
755 if (val != 0) {
756 if (val >= kMinHeapSize && val <= kMaxHeapSize) {
757 gDvm.heapSizeMax = val;
758 } else {
759 dvmFprintf(stderr,
760 "Invalid -Xmx '%s', range is %dKB to %dKB\n",
761 argv[i], kMinHeapSize/1024, kMaxHeapSize/1024);
762 return -1;
763 }
764 } else {
765 dvmFprintf(stderr, "Invalid -Xmx option '%s'\n", argv[i]);
766 return -1;
767 }
768 } else if (strncmp(argv[i], "-Xss", 4) == 0) {
769 unsigned int val = dvmParseMemOption(argv[i]+4, 1);
770 if (val != 0) {
771 if (val >= kMinStackSize && val <= kMaxStackSize) {
772 gDvm.stackSize = val;
773 } else {
774 dvmFprintf(stderr, "Invalid -Xss '%s', range is %d to %d\n",
775 argv[i], kMinStackSize, kMaxStackSize);
776 return -1;
777 }
778 } else {
779 dvmFprintf(stderr, "Invalid -Xss option '%s'\n", argv[i]);
780 return -1;
781 }
782
783 } else if (strcmp(argv[i], "-verbose") == 0 ||
784 strcmp(argv[i], "-verbose:class") == 0)
785 {
786 // JNI spec says "-verbose:gc,class" is valid, but cmd line
787 // doesn't work that way; may want to support.
788 gDvm.verboseClass = true;
789 } else if (strcmp(argv[i], "-verbose:jni") == 0) {
790 gDvm.verboseJni = true;
791 } else if (strcmp(argv[i], "-verbose:gc") == 0) {
792 gDvm.verboseGc = true;
793
794 } else if (strncmp(argv[i], "-enableassertions", 17) == 0) {
795 enableAssertions(argv[i] + 17, true);
796 } else if (strncmp(argv[i], "-ea", 3) == 0) {
797 enableAssertions(argv[i] + 3, true);
798 } else if (strncmp(argv[i], "-disableassertions", 18) == 0) {
799 enableAssertions(argv[i] + 18, false);
800 } else if (strncmp(argv[i], "-da", 3) == 0) {
801 enableAssertions(argv[i] + 3, false);
802 } else if (strcmp(argv[i], "-enablesystemassertions") == 0 ||
803 strcmp(argv[i], "-esa") == 0)
804 {
805 enableAssertions(NULL, true);
806 } else if (strcmp(argv[i], "-disablesystemassertions") == 0 ||
807 strcmp(argv[i], "-dsa") == 0)
808 {
809 enableAssertions(NULL, false);
810
811 } else if (strncmp(argv[i], "-Xcheck:jni", 11) == 0) {
812 /* nothing to do now -- was handled during JNI init */
813
814 } else if (strcmp(argv[i], "-Xdebug") == 0) {
815 /* accept but ignore */
816
817 } else if (strncmp(argv[i], "-Xrunjdwp:", 10) == 0 ||
818 strncmp(argv[i], "-agentlib:jdwp=", 15) == 0)
819 {
820 const char* tail;
821 bool result = false;
822
823 if (argv[i][1] == 'X')
824 tail = argv[i] + 10;
825 else
826 tail = argv[i] + 15;
827
828 if (strncmp(tail, "help", 4) == 0 || !parseJdwpOptions(tail)) {
829 showJdwpHelp();
830 return 1;
831 }
832 } else if (strcmp(argv[i], "-Xrs") == 0) {
833 gDvm.reduceSignals = true;
834 } else if (strcmp(argv[i], "-Xnoquithandler") == 0) {
835 /* disables SIGQUIT handler thread while still blocking SIGQUIT */
836 /* (useful if we don't want thread but system still signals us) */
837 gDvm.noQuitHandler = true;
838 } else if (strcmp(argv[i], "-Xzygote") == 0) {
839 gDvm.zygote = true;
840 } else if (strncmp(argv[i], "-Xdexopt:", 9) == 0) {
841 if (strcmp(argv[i] + 9, "none") == 0)
842 gDvm.dexOptMode = OPTIMIZE_MODE_NONE;
843 else if (strcmp(argv[i] + 9, "verified") == 0)
844 gDvm.dexOptMode = OPTIMIZE_MODE_VERIFIED;
845 else if (strcmp(argv[i] + 9, "all") == 0)
846 gDvm.dexOptMode = OPTIMIZE_MODE_ALL;
847 else {
848 dvmFprintf(stderr, "Unrecognized dexopt option '%s'\n",argv[i]);
849 return -1;
850 }
851 } else if (strncmp(argv[i], "-Xverify:", 9) == 0) {
852 if (strcmp(argv[i] + 9, "none") == 0)
853 gDvm.classVerifyMode = VERIFY_MODE_NONE;
854 else if (strcmp(argv[i] + 9, "remote") == 0)
855 gDvm.classVerifyMode = VERIFY_MODE_REMOTE;
856 else if (strcmp(argv[i] + 9, "all") == 0)
857 gDvm.classVerifyMode = VERIFY_MODE_ALL;
858 else {
859 dvmFprintf(stderr, "Unrecognized verify option '%s'\n",argv[i]);
860 return -1;
861 }
862 } else if (strncmp(argv[i], "-Xjnigreflimit:", 15) == 0) {
863 int lim = atoi(argv[i] + 15);
864 if (lim < 200 || (lim % 100) != 0) {
865 dvmFprintf(stderr, "Bad value for -Xjnigreflimit: '%s'\n",
866 argv[i]+15);
867 return -1;
868 }
869 gDvm.jniGrefLimit = lim;
870
871 } else if (strcmp(argv[i], "-Xlog-stdio") == 0) {
872 gDvm.logStdio = true;
873
874 } else if (strncmp(argv[i], "-Xint", 5) == 0) {
875 if (argv[i][5] == ':') {
876 if (strcmp(argv[i] + 6, "portable") == 0)
877 gDvm.executionMode = kExecutionModeInterpPortable;
878 else if (strcmp(argv[i] + 6, "fast") == 0)
879 gDvm.executionMode = kExecutionModeInterpFast;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700880#ifdef WITH_JIT
881 else if (strcmp(argv[i] + 6, "jit") == 0)
882 gDvm.executionMode = kExecutionModeJit;
883#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800884 else {
885 dvmFprintf(stderr,
886 "Warning: Unrecognized interpreter mode %s\n",argv[i]);
887 /* keep going */
888 }
889 } else {
890 /* disable JIT -- nothing to do here for now */
891 }
892
Ben Chengba4fc8b2009-06-01 13:00:29 -0700893#ifdef WITH_JIT
894 } else if (strncmp(argv[i], "-Xjitop", 7) == 0) {
895 processXjitop(argv[i]);
896 } else if (strncmp(argv[i], "-Xjitmethod", 11) == 0) {
897 processXjitmethod(argv[i]);
898 } else if (strncmp(argv[i], "-Xblocking", 10) == 0) {
899 gDvmJit.blockingMode = true;
900 } else if (strncmp(argv[i], "-Xthreshold:", 12) == 0) {
901 gDvmJit.threshold = atoi(argv[i] + 12);
902 } else if (strncmp(argv[i], "-Xincludeselectedop", 19) == 0) {
903 gDvmJit.includeSelectedOp = true;
904 } else if (strncmp(argv[i], "-Xincludeselectedmethod", 23) == 0) {
905 gDvmJit.includeSelectedMethod = true;
906 } else if (strncmp(argv[i], "-Xjitverbose", 12) == 0) {
907 gDvmJit.printMe = true;
Bill Buzbee6e963e12009-06-17 16:56:19 -0700908 } else if (strncmp(argv[i], "-Xjitprofile", 12) == 0) {
909 gDvmJit.profile = true;
Ben Chengba4fc8b2009-06-01 13:00:29 -0700910#endif
911
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800912 } else if (strncmp(argv[i], "-Xdeadlockpredict:", 18) == 0) {
913#ifdef WITH_DEADLOCK_PREDICTION
914 if (strcmp(argv[i] + 18, "off") == 0)
915 gDvm.deadlockPredictMode = kDPOff;
916 else if (strcmp(argv[i] + 18, "warn") == 0)
917 gDvm.deadlockPredictMode = kDPWarn;
918 else if (strcmp(argv[i] + 18, "err") == 0)
919 gDvm.deadlockPredictMode = kDPErr;
920 else if (strcmp(argv[i] + 18, "abort") == 0)
921 gDvm.deadlockPredictMode = kDPAbort;
922 else {
923 dvmFprintf(stderr, "Bad value for -Xdeadlockpredict");
924 return -1;
925 }
926 if (gDvm.deadlockPredictMode != kDPOff)
927 LOGD("Deadlock prediction enabled (%s)\n", argv[i]+18);
928#endif
929
930 } else if (strncmp(argv[i], "-Xstacktracefile:", 17) == 0) {
931 gDvm.stackTraceFile = strdup(argv[i]+17);
932
933 } else if (strcmp(argv[i], "-Xgenregmap") == 0) {
934 gDvm.generateRegisterMaps = true;
The Android Open Source Project99409882009-03-18 22:20:24 -0700935 LOGD("Register maps will be generated during verification\n");
936
937 } else if (strncmp(argv[i], "-Xgc:", 5) == 0) {
938 if (strcmp(argv[i] + 5, "precise") == 0)
939 gDvm.preciseGc = true;
940 else if (strcmp(argv[i] + 5, "noprecise") == 0)
941 gDvm.preciseGc = false;
942 else {
943 dvmFprintf(stderr, "Bad value for -Xgc");
944 return -1;
945 }
946 LOGD("Precise GC configured %s\n", gDvm.preciseGc ? "ON" : "OFF");
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800947
948 } else if (strcmp(argv[i], "-Xcheckdexsum") == 0) {
949 gDvm.verifyDexChecksum = true;
950
951 } else {
952 if (!ignoreUnrecognized) {
953 dvmFprintf(stderr, "Unrecognized option '%s'\n", argv[i]);
954 return -1;
955 }
956 }
957 }
958
959 if (gDvm.heapSizeStart > gDvm.heapSizeMax) {
960 dvmFprintf(stderr, "Heap start size must be <= heap max size\n");
961 return -1;
962 }
963
964 return 0;
965}
966
967/*
968 * Set defaults for fields altered or modified by arguments.
The Android Open Source Project99409882009-03-18 22:20:24 -0700969 *
970 * Globals are initialized to 0 (a/k/a NULL or false).
The Android Open Source Projectf6c38712009-03-03 19:28:47 -0800971 */
972static void setCommandLineDefaults()
973{
974 const char* envStr;
975
976 envStr = getenv("CLASSPATH");
977 if (envStr != NULL)
978 gDvm.classPathStr = strdup(envStr);
979 else
980 gDvm.classPathStr = strdup(".");
981 envStr = getenv("BOOTCLASSPATH");
982 if (envStr != NULL)
983 gDvm.bootClassPathStr = strdup(envStr);
984 else
985 gDvm.bootClassPathStr = strdup(".");
986
987 /* Defaults overridden by -Xms and -Xmx.
988 * TODO: base these on a system or application-specific default
989 */
990 gDvm.heapSizeStart = 2 * 1024 * 1024; // Spec says 16MB; too big for us.
991 gDvm.heapSizeMax = 16 * 1024 * 1024; // Spec says 75% physical mem
992 gDvm.stackSize = kDefaultStackSize;
993
994 /* gDvm.jdwpSuspend = true; */
995
996 /* allowed unless zygote config doesn't allow it */
997 gDvm.jdwpAllowed = true;
998
999 /* default verification and optimization modes */
1000 gDvm.classVerifyMode = VERIFY_MODE_ALL;
1001 gDvm.dexOptMode = OPTIMIZE_MODE_VERIFIED;
1002
1003 /*
1004 * Default execution mode.
1005 *
1006 * This should probably interact with the mterp code somehow, e.g. if
1007 * we know we're using the "desktop" build we should probably be
1008 * using "portable" rather than "fast".
1009 */
Ben Chengba4fc8b2009-06-01 13:00:29 -07001010#if defined(WITH_JIT)
1011 gDvm.executionMode = kExecutionModeJit;
1012 /*
1013 * TODO - check system property and insert command-line options in
1014 * frameworks/base/core/jni/AndroidRuntime.cpp
1015 */
1016 gDvmJit.blockingMode = false;
Bill Buzbee27176222009-06-09 09:20:16 -07001017 gDvmJit.jitTableSize = 512;
1018 gDvmJit.jitTableMask = gDvmJit.jitTableSize - 1;
Ben Chengba4fc8b2009-06-01 13:00:29 -07001019 gDvmJit.threshold = 200;
1020#else
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001021 gDvm.executionMode = kExecutionModeInterpFast;
Ben Chengba4fc8b2009-06-01 13:00:29 -07001022#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001023}
1024
1025
1026/*
1027 * Handle a SIGBUS, which frequently occurs because somebody replaced an
1028 * optimized DEX file out from under us.
1029 */
1030static void busCatcher(int signum, siginfo_t* info, void* context)
1031{
1032 void* addr = info->si_addr;
1033
1034 LOGE("Caught a SIGBUS (%d), addr=%p\n", signum, addr);
1035
1036 /*
1037 * If we return at this point the SIGBUS just keeps happening, so we
1038 * remove the signal handler and allow it to kill us. TODO: restore
1039 * the original, which points to a debuggerd stub; if we don't then
1040 * debuggerd won't be notified.
1041 */
1042 signal(SIGBUS, SIG_DFL);
1043}
1044
1045/*
1046 * Configure signals. We need to block SIGQUIT so that the signal only
1047 * reaches the dump-stack-trace thread.
1048 *
1049 * This can be disabled with the "-Xrs" flag.
1050 */
1051static void blockSignals()
1052{
1053 sigset_t mask;
1054 int cc;
1055
1056 sigemptyset(&mask);
1057 sigaddset(&mask, SIGQUIT);
1058 sigaddset(&mask, SIGUSR1); // used to initiate heap dump
Ben Chengba4fc8b2009-06-01 13:00:29 -07001059#if defined(WITH_JIT) && defined(WITH_JIT_TUNING)
1060 sigaddset(&mask, SIGUSR2); // used to investigate JIT internals
1061#endif
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001062 //sigaddset(&mask, SIGPIPE);
1063 cc = sigprocmask(SIG_BLOCK, &mask, NULL);
1064 assert(cc == 0);
1065
1066 if (false) {
1067 /* TODO: save the old sigaction in a global */
1068 struct sigaction sa;
1069 memset(&sa, 0, sizeof(sa));
1070 sa.sa_sigaction = busCatcher;
1071 sa.sa_flags = SA_SIGINFO;
1072 cc = sigaction(SIGBUS, &sa, NULL);
1073 assert(cc == 0);
1074 }
1075}
1076
1077/*
1078 * VM initialization. Pass in any options provided on the command line.
1079 * Do not pass in the class name or the options for the class.
1080 *
1081 * Returns 0 on success.
1082 */
1083int dvmStartup(int argc, const char* const argv[], bool ignoreUnrecognized,
1084 JNIEnv* pEnv)
1085{
1086 int i, cc;
1087
1088 assert(gDvm.initializing);
1089
1090 LOGV("VM init args (%d):\n", argc);
1091 for (i = 0; i < argc; i++)
1092 LOGV(" %d: '%s'\n", i, argv[i]);
1093
1094 setCommandLineDefaults();
1095
1096 /* prep properties storage */
1097 if (!dvmPropertiesStartup(argc))
1098 goto fail;
1099
1100 /*
1101 * Process the option flags (if any).
1102 */
1103 cc = dvmProcessOptions(argc, argv, ignoreUnrecognized);
1104 if (cc != 0) {
1105 if (cc < 0) {
1106 dvmFprintf(stderr, "\n");
1107 dvmUsage("dalvikvm");
1108 }
1109 goto fail;
1110 }
1111
The Android Open Source Project99409882009-03-18 22:20:24 -07001112#if WITH_EXTRA_GC_CHECKS > 1
1113 /* only "portable" interp has the extra goodies */
1114 if (gDvm.executionMode != kExecutionModeInterpPortable) {
1115 LOGI("Switching to 'portable' interpreter for GC checks\n");
1116 gDvm.executionMode = kExecutionModeInterpPortable;
1117 }
1118#endif
1119
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001120 /* configure signal handling */
1121 if (!gDvm.reduceSignals)
1122 blockSignals();
1123
1124 /* mterp setup */
1125 LOGV("Using executionMode %d\n", gDvm.executionMode);
1126 dvmCheckAsmConstants();
1127
1128 /*
1129 * Initialize components.
1130 */
1131 if (!dvmAllocTrackerStartup())
1132 goto fail;
1133 if (!dvmGcStartup())
1134 goto fail;
1135 if (!dvmThreadStartup())
1136 goto fail;
1137 if (!dvmInlineNativeStartup())
1138 goto fail;
1139 if (!dvmVerificationStartup())
1140 goto fail;
The Android Open Source Project99409882009-03-18 22:20:24 -07001141 if (!dvmRegisterMapStartup())
1142 goto fail;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001143 if (!dvmInstanceofStartup())
1144 goto fail;
1145 if (!dvmClassStartup())
1146 goto fail;
1147 if (!dvmThreadObjStartup())
1148 goto fail;
1149 if (!dvmExceptionStartup())
1150 goto fail;
1151 if (!dvmStringInternStartup())
1152 goto fail;
1153 if (!dvmNativeStartup())
1154 goto fail;
1155 if (!dvmInternalNativeStartup())
1156 goto fail;
1157 if (!dvmJniStartup())
1158 goto fail;
1159 if (!dvmReflectStartup())
1160 goto fail;
1161#ifdef WITH_PROFILER
1162 if (!dvmProfilingStartup())
1163 goto fail;
1164#endif
1165
1166 /* make sure we got these [can this go away?] */
1167 assert(gDvm.classJavaLangClass != NULL);
1168 assert(gDvm.classJavaLangObject != NULL);
1169 //assert(gDvm.classJavaLangString != NULL);
1170 assert(gDvm.classJavaLangThread != NULL);
1171 assert(gDvm.classJavaLangVMThread != NULL);
1172 assert(gDvm.classJavaLangThreadGroup != NULL);
1173
1174 /*
1175 * Make sure these exist. If they don't, we can return a failure out
1176 * of main and nip the whole thing in the bud.
1177 */
1178 static const char* earlyClasses[] = {
1179 "Ljava/lang/InternalError;",
1180 "Ljava/lang/StackOverflowError;",
1181 "Ljava/lang/UnsatisfiedLinkError;",
1182 "Ljava/lang/NoClassDefFoundError;",
1183 NULL
1184 };
1185 const char** pClassName;
1186 for (pClassName = earlyClasses; *pClassName != NULL; pClassName++) {
1187 if (dvmFindSystemClassNoInit(*pClassName) == NULL)
1188 goto fail;
1189 }
1190
1191 /*
1192 * Miscellaneous class library validation.
1193 */
1194 if (!dvmValidateBoxClasses())
1195 goto fail;
1196
1197 /*
1198 * Do the last bits of Thread struct initialization we need to allow
1199 * JNI calls to work.
1200 */
1201 if (!dvmPrepMainForJni(pEnv))
1202 goto fail;
1203
1204 /*
1205 * Register the system native methods, which are registered through JNI.
1206 */
1207 if (!registerSystemNatives(pEnv))
1208 goto fail;
1209
1210 /*
1211 * Do some "late" initialization for the memory allocator. This may
1212 * allocate storage and initialize classes.
1213 */
1214 if (!dvmGcLateInit())
1215 goto fail;
1216
1217 /*
1218 * At this point, the VM is in a pretty good state. Finish prep on
1219 * the main thread (specifically, create a java.lang.Thread object to go
1220 * along with our Thread struct). Note we will probably be executing
1221 * some interpreted class initializer code in here.
1222 */
1223 if (!dvmPrepMainThread())
1224 goto fail;
1225
1226 /* general debugging setup */
1227 if (!dvmDebuggerStartup())
1228 goto fail;
1229
1230 /*
1231 * Init for either zygote mode or non-zygote mode. The key difference
1232 * is that we don't start any additional threads in Zygote mode.
1233 */
1234 if (gDvm.zygote) {
1235 if (!dvmInitZygote())
1236 goto fail;
1237 } else {
1238 if (!dvmInitAfterZygote())
1239 goto fail;
1240 }
1241
1242
1243#ifndef NDEBUG
1244 dvmTestHash();
1245#endif
1246
1247 assert(!dvmCheckException(dvmThreadSelf()));
1248 gDvm.initExceptionCount = 0;
1249
1250 return 0;
1251
1252fail:
1253 dvmShutdown();
1254 return 1;
1255}
1256
1257/*
1258 * Register java.* natives from our class libraries. We need to do
1259 * this after we're ready for JNI registration calls, but before we
1260 * do any class initialization.
1261 *
1262 * If we get this wrong, we will blow up in the ThreadGroup class init if
1263 * interpreted code makes any reference to System. It will likely do this
1264 * since it wants to do some java.io.File setup (e.g. for static in/out/err).
1265 *
1266 * We need to have gDvm.initializing raised here so that JNI FindClass
1267 * won't try to use the system/application class loader.
1268 */
1269static bool registerSystemNatives(JNIEnv* pEnv)
1270{
1271 Thread* self;
1272
1273 /* main thread is always first in list */
1274 self = gDvm.threadList;
1275
1276 /* must set this before allowing JNI-based method registration */
1277 self->status = THREAD_NATIVE;
1278
1279 if (jniRegisterSystemMethods(pEnv) < 0) {
1280 LOGW("jniRegisterSystemMethods failed\n");
1281 return false;
1282 }
1283
1284 /* back to run mode */
1285 self->status = THREAD_RUNNING;
1286
1287 return true;
1288}
1289
1290
1291/*
1292 * Do zygote-mode-only initialization.
1293 */
1294static bool dvmInitZygote(void)
1295{
1296 /* zygote goes into its own process group */
1297 setpgid(0,0);
1298
1299 return true;
1300}
1301
1302/*
1303 * Do non-zygote-mode initialization. This is done during VM init for
1304 * standard startup, or after a "zygote fork" when creating a new process.
1305 */
1306bool dvmInitAfterZygote(void)
1307{
1308 u8 startHeap, startQuit, startJdwp;
1309 u8 endHeap, endQuit, endJdwp;
1310
1311 startHeap = dvmGetRelativeTimeUsec();
1312
1313 /*
1314 * Post-zygote heap initialization, including starting
1315 * the HeapWorker thread.
1316 */
1317 if (!dvmGcStartupAfterZygote())
1318 return false;
1319
1320 endHeap = dvmGetRelativeTimeUsec();
1321 startQuit = dvmGetRelativeTimeUsec();
1322
1323 /* start signal catcher thread that dumps stacks on SIGQUIT */
1324 if (!gDvm.reduceSignals && !gDvm.noQuitHandler) {
1325 if (!dvmSignalCatcherStartup())
1326 return false;
1327 }
1328
1329 /* start stdout/stderr copier, if requested */
1330 if (gDvm.logStdio) {
1331 if (!dvmStdioConverterStartup())
1332 return false;
1333 }
1334
1335 endQuit = dvmGetRelativeTimeUsec();
1336 startJdwp = dvmGetRelativeTimeUsec();
1337
1338 /*
1339 * Start JDWP thread. If the command-line debugger flags specified
1340 * "suspend=y", this will pause the VM. We probably want this to
1341 * come last.
1342 */
1343 if (!dvmInitJDWP()) {
1344 LOGD("JDWP init failed; continuing anyway\n");
1345 }
1346
1347 endJdwp = dvmGetRelativeTimeUsec();
1348
1349 LOGV("thread-start heap=%d quit=%d jdwp=%d total=%d usec\n",
1350 (int)(endHeap-startHeap), (int)(endQuit-startQuit),
1351 (int)(endJdwp-startJdwp), (int)(endJdwp-startHeap));
1352
Ben Chengba4fc8b2009-06-01 13:00:29 -07001353#ifdef WITH_JIT
1354 if (!dvmJitStartup())
1355 return false;
1356#endif
1357
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001358 return true;
1359}
1360
1361/*
1362 * Prepare for a connection to a JDWP-compliant debugger.
1363 *
1364 * Note this needs to happen fairly late in the startup process, because
1365 * we need to have all of the java.* native methods registered (which in
1366 * turn requires JNI to be fully prepped).
1367 *
1368 * There are several ways to initialize:
1369 * server=n
1370 * We immediately try to connect to host:port. Bail on failure. On
1371 * success, send VM_START (suspending the VM if "suspend=y").
1372 * server=y suspend=n
1373 * Passively listen for a debugger to connect. Return immediately.
1374 * server=y suspend=y
1375 * Wait until debugger connects. Send VM_START ASAP, suspending the
1376 * VM after the message is sent.
1377 *
1378 * This gets more complicated with a nonzero value for "timeout".
1379 */
1380static bool dvmInitJDWP(void)
1381{
1382 assert(!gDvm.zygote);
1383
1384#ifndef WITH_DEBUGGER
1385 LOGI("Debugger support not compiled into VM\n");
1386 return false;
1387#endif
1388
1389 /*
1390 * Init JDWP if the debugger is enabled. This may connect out to a
1391 * debugger, passively listen for a debugger, or block waiting for a
1392 * debugger.
1393 */
1394 if (gDvm.jdwpAllowed && gDvm.jdwpConfigured) {
1395 JdwpStartupParams params;
1396
1397 if (gDvm.jdwpHost != NULL) {
1398 if (strlen(gDvm.jdwpHost) >= sizeof(params.host)-1) {
1399 LOGE("ERROR: hostname too long: '%s'\n", gDvm.jdwpHost);
1400 return false;
1401 }
1402 strcpy(params.host, gDvm.jdwpHost);
1403 } else {
1404 params.host[0] = '\0';
1405 }
1406 params.transport = gDvm.jdwpTransport;
1407 params.server = gDvm.jdwpServer;
1408 params.suspend = gDvm.jdwpSuspend;
1409 params.port = gDvm.jdwpPort;
1410
1411 gDvm.jdwpState = dvmJdwpStartup(&params);
1412 if (gDvm.jdwpState == NULL) {
1413 LOGW("WARNING: debugger thread failed to initialize\n");
1414 /* TODO: ignore? fail? need to mimic "expected" behavior */
1415 }
1416 }
1417
1418 /*
1419 * If a debugger has already attached, send the "welcome" message. This
1420 * may cause us to suspend all threads.
1421 */
1422 if (dvmJdwpIsActive(gDvm.jdwpState)) {
1423 //dvmChangeStatus(NULL, THREAD_RUNNING);
1424 if (!dvmJdwpPostVMStart(gDvm.jdwpState, gDvm.jdwpSuspend)) {
1425 LOGW("WARNING: failed to post 'start' message to debugger\n");
1426 /* keep going */
1427 }
1428 //dvmChangeStatus(NULL, THREAD_NATIVE);
1429 }
1430
1431 return true;
1432}
1433
1434/*
1435 * An alternative to JNI_CreateJavaVM/dvmStartup that does the first bit
1436 * of initialization and then returns with "initializing" still set. (Used
1437 * by DexOpt command-line utility.)
1438 *
1439 * Attempting to use JNI or internal natives will fail. It's best if
1440 * no bytecode gets executed, which means no <clinit>, which means no
1441 * exception-throwing. We check the "initializing" flag anyway when
1442 * throwing an exception, so we can insert some code that avoids chucking
1443 * an exception when we're optimizing stuff.
1444 *
1445 * Returns 0 on success.
1446 */
1447int dvmPrepForDexOpt(const char* bootClassPath, DexOptimizerMode dexOptMode,
1448 DexClassVerifyMode verifyMode, int dexoptFlags)
1449{
1450 gDvm.initializing = true;
1451 gDvm.optimizing = true;
1452
1453 /* configure signal handling */
1454 blockSignals();
1455
1456 /* set some defaults */
1457 setCommandLineDefaults();
1458 free(gDvm.bootClassPathStr);
1459 gDvm.bootClassPathStr = strdup(bootClassPath);
1460
1461 /* set opt/verify modes */
1462 gDvm.dexOptMode = dexOptMode;
1463 gDvm.classVerifyMode = verifyMode;
1464 gDvm.generateRegisterMaps = (dexoptFlags & DEXOPT_GEN_REGISTER_MAPS) != 0;
1465
1466 /*
1467 * Initialize the heap, some basic thread control mutexes, and
1468 * get the bootclasspath prepped.
1469 *
1470 * We can't load any classes yet because we may not yet have a source
1471 * for things like java.lang.Object and java.lang.Class.
1472 */
1473 if (!dvmGcStartup())
1474 goto fail;
1475 if (!dvmThreadStartup())
1476 goto fail;
1477 if (!dvmInlineNativeStartup())
1478 goto fail;
1479 if (!dvmVerificationStartup())
1480 goto fail;
The Android Open Source Project99409882009-03-18 22:20:24 -07001481 if (!dvmRegisterMapStartup())
1482 goto fail;
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001483 if (!dvmInstanceofStartup())
1484 goto fail;
1485 if (!dvmClassStartup())
1486 goto fail;
1487
1488 /*
1489 * We leave gDvm.initializing set to "true" so that, if we're not
1490 * able to process the "core" classes, we don't go into a death-spin
1491 * trying to throw a "class not found" exception.
1492 */
1493
1494 return 0;
1495
1496fail:
1497 dvmShutdown();
1498 return 1;
1499}
1500
1501
1502/*
1503 * All threads have stopped. Finish the shutdown procedure.
1504 *
1505 * We can also be called if startup fails partway through, so be prepared
1506 * to deal with partially initialized data.
1507 *
1508 * Free any storage allocated in gGlobals.
1509 *
1510 * We can't dlclose() shared libs we've loaded, because it's possible a
1511 * thread not associated with the VM is running code in one.
1512 *
1513 * This is called from the JNI DestroyJavaVM function, which can be
1514 * called from any thread. (In practice, this will usually run in the
1515 * same thread that started the VM, a/k/a the main thread, but we don't
1516 * want to assume that.)
1517 */
1518void dvmShutdown(void)
1519{
1520 LOGV("VM shutting down\n");
1521
1522 if (CALC_CACHE_STATS)
1523 dvmDumpAtomicCacheStats(gDvm.instanceofCache);
1524
1525 /*
1526 * Stop our internal threads.
1527 */
1528 dvmHeapWorkerShutdown();
1529
1530 if (gDvm.jdwpState != NULL)
1531 dvmJdwpShutdown(gDvm.jdwpState);
1532 free(gDvm.jdwpHost);
1533 gDvm.jdwpHost = NULL;
1534 free(gDvm.stackTraceFile);
1535 gDvm.stackTraceFile = NULL;
1536
1537 /* tell signal catcher to shut down if it was started */
1538 dvmSignalCatcherShutdown();
1539
1540 /* shut down stdout/stderr conversion */
1541 dvmStdioConverterShutdown();
1542
Ben Chengef00a852009-06-22 22:53:35 -07001543#ifdef WITH_JIT
1544 /* tell the compiler to shut down if it was started */
1545 dvmJitShutdown();
1546#endif
1547
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001548 /*
1549 * Kill any daemon threads that still exist. Actively-running threads
1550 * are likely to crash the process if they continue to execute while
1551 * the VM shuts down.
1552 */
1553 dvmSlayDaemons();
1554
1555 LOGD("VM cleaning up\n");
1556
1557 dvmDebuggerShutdown();
1558 dvmReflectShutdown();
1559#ifdef WITH_PROFILER
1560 dvmProfilingShutdown();
1561#endif
1562 dvmJniShutdown();
1563 dvmStringInternShutdown();
1564 dvmExceptionShutdown();
1565 dvmThreadShutdown();
1566 dvmClassShutdown();
1567 dvmVerificationShutdown();
The Android Open Source Project99409882009-03-18 22:20:24 -07001568 dvmRegisterMapShutdown();
The Android Open Source Projectf6c38712009-03-03 19:28:47 -08001569 dvmInstanceofShutdown();
1570 dvmInlineNativeShutdown();
1571 dvmGcShutdown();
1572 dvmAllocTrackerShutdown();
1573 dvmPropertiesShutdown();
1574
1575 /* these must happen AFTER dvmClassShutdown has walked through class data */
1576 dvmNativeShutdown();
1577 dvmInternalNativeShutdown();
1578
1579 free(gDvm.bootClassPathStr);
1580 free(gDvm.classPathStr);
1581
1582 freeAssertionCtrl();
1583
1584 /*
1585 * We want valgrind to report anything we forget to free as "definitely
1586 * lost". If there's a pointer in the global chunk, it would be reported
1587 * as "still reachable". Erasing the memory fixes this.
1588 *
1589 * This must be erased to zero if we want to restart the VM within this
1590 * process.
1591 */
1592 memset(&gDvm, 0xcd, sizeof(gDvm));
1593}
1594
1595
1596/*
1597 * fprintf() wrapper that calls through the JNI-specified vfprintf hook if
1598 * one was specified.
1599 */
1600int dvmFprintf(FILE* fp, const char* format, ...)
1601{
1602 va_list args;
1603 int result;
1604
1605 va_start(args, format);
1606 if (gDvm.vfprintfHook != NULL)
1607 result = (*gDvm.vfprintfHook)(fp, format, args);
1608 else
1609 result = vfprintf(fp, format, args);
1610 va_end(args);
1611
1612 return result;
1613}
1614
1615/*
1616 * Abort the VM. We get here on fatal errors. Try very hard not to use
1617 * this; whenever possible, return an error to somebody responsible.
1618 */
1619void dvmAbort(void)
1620{
1621 LOGE("VM aborting\n");
1622
1623 fflush(NULL); // flush all open file buffers
1624
1625 /* JNI-supplied abort hook gets right of first refusal */
1626 if (gDvm.abortHook != NULL)
1627 (*gDvm.abortHook)();
1628
1629 /*
1630 * If we call abort(), all threads in the process receives a SIBABRT.
1631 * debuggerd dumps the stack trace of the main thread, whether or not
1632 * that was the thread that failed.
1633 *
1634 * By stuffing a value into a bogus address, we cause a segmentation
1635 * fault in the current thread, and get a useful log from debuggerd.
1636 * We can also trivially tell the difference between a VM crash and
1637 * a deliberate abort by looking at the fault address.
1638 */
1639 *((char*)0xdeadd00d) = 38;
1640 abort();
1641
1642 /* notreached */
1643}