1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 /*
6 * This custom library loading code is only meant to be called
7 * during initialization. As a result, it takes no special
8 * precautions to be threadsafe. Any of the library loading functions
9 * like mozload should not be available to other code.
10 */
11
12 #include <jni.h>
13 #include <android/log.h>
14 #include <sys/types.h>
15 #include <sys/stat.h>
16 #include <sys/mman.h>
17 #include <sys/limits.h>
18 #include <errno.h>
19 #include <string.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <fcntl.h>
23 #include <unistd.h>
24 #include <zlib.h>
25 #include "dlfcn.h"
26 #include "APKOpen.h"
27 #include <sys/time.h>
28 #include <sys/syscall.h>
29 #include <sys/resource.h>
30 #include <sys/prctl.h>
31 #include "sqlite3.h"
32 #include "Linker.h"
33 #include "BaseProfiler.h"
34 #include "application.ini.h"
35
36 #include "mozilla/arm.h"
37 #include "mozilla/Bootstrap.h"
38 #include "mozilla/Printf.h"
39 #include "mozilla/Sprintf.h"
40 #include "mozilla/TimeStamp.h"
41 #include "mozilla/UniquePtr.h"
42 #include "XREChildData.h"
43
44 /* Android headers don't define RUSAGE_THREAD */
45 #ifndef RUSAGE_THREAD
46 # define RUSAGE_THREAD 1
47 #endif
48
49 #ifndef RELEASE_OR_BETA
50 /* Official builds have the debuggable flag set to false, which disables
51 * the backtrace dumper from bionic. However, as it is useful for native
52 * crashes happening before the crash reporter is registered, re-enable
53 * it on non release builds (i.e. nightly and aurora).
54 * Using a constructor so that it is re-enabled as soon as libmozglue.so
55 * is loaded.
56 */
make_dumpable()57 __attribute__((constructor)) void make_dumpable() { prctl(PR_SET_DUMPABLE, 1); }
58 #endif
59
60 typedef int mozglueresult;
61
62 using LoadGeckoLibsResult =
63 mozilla::Result<mozilla::Ok, mozilla::BootstrapError>;
64
65 enum StartupEvent {
66 #define mozilla_StartupTimeline_Event(ev, z) ev,
67 #include "StartupTimeline.h"
68 #undef mozilla_StartupTimeline_Event
69 MAX_STARTUP_EVENT_ID
70 };
71
72 using namespace mozilla;
73
JNI_Throw(JNIEnv * jenv,const char * classname,const char * msg)74 void JNI_Throw(JNIEnv* jenv, const char* classname, const char* msg) {
75 __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad", "Throw\n");
76 jclass cls = jenv->FindClass(classname);
77 if (cls == nullptr) {
78 __android_log_print(
79 ANDROID_LOG_ERROR, "GeckoLibLoad",
80 "Couldn't find exception class (or exception pending) %s\n", classname);
81 exit(FAILURE);
82 }
83 int rc = jenv->ThrowNew(cls, msg);
84 if (rc < 0) {
85 __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad",
86 "Error throwing exception %s\n", msg);
87 exit(FAILURE);
88 }
89 jenv->DeleteLocalRef(cls);
90 }
91
92 namespace {
93 JavaVM* sJavaVM;
94 }
95
abortThroughJava(const char * msg)96 void abortThroughJava(const char* msg) {
97 struct sigaction sigact = {};
98 if (__wrap_sigaction(SIGSEGV, nullptr, &sigact)) {
99 return; // sigaction call failed.
100 }
101
102 Dl_info info = {};
103 if ((sigact.sa_flags & SA_SIGINFO) &&
104 __wrap_dladdr(reinterpret_cast<void*>(sigact.sa_sigaction), &info) &&
105 info.dli_fname && strstr(info.dli_fname, "libxul.so")) {
106 return; // Existing signal handler is in libxul (i.e. we have crash
107 // reporter).
108 }
109
110 JNIEnv* env = nullptr;
111 if (!sJavaVM ||
112 sJavaVM->AttachCurrentThreadAsDaemon(&env, nullptr) != JNI_OK) {
113 return;
114 }
115
116 if (!env || env->PushLocalFrame(2) != JNI_OK) {
117 return;
118 }
119
120 jclass loader = env->FindClass("org/mozilla/gecko/mozglue/GeckoLoader");
121 if (!loader) {
122 return;
123 }
124
125 jmethodID method =
126 env->GetStaticMethodID(loader, "abort", "(Ljava/lang/String;)V");
127 jstring str = env->NewStringUTF(msg);
128
129 if (method && str) {
130 env->CallStaticVoidMethod(loader, method, str);
131 }
132
133 env->PopLocalFrame(nullptr);
134 }
135
136 Bootstrap::UniquePtr gBootstrap;
137 #ifndef MOZ_FOLD_LIBS
138 static void* sqlite_handle = nullptr;
139 static void* nspr_handle = nullptr;
140 static void* plc_handle = nullptr;
141 #else
142 # define sqlite_handle nss_handle
143 # define nspr_handle nss_handle
144 # define plc_handle nss_handle
145 #endif
146 static void* nss_handle = nullptr;
147
getUnpackedLibraryName(const char * libraryName)148 static UniquePtr<char[]> getUnpackedLibraryName(const char* libraryName) {
149 static const char* libdir = getenv("MOZ_ANDROID_LIBDIR");
150
151 size_t len = strlen(libdir) + 1 /* path separator */ + strlen(libraryName) +
152 1; /* null terminator */
153 auto file = MakeUnique<char[]>(len);
154 snprintf(file.get(), len, "%s/%s", libdir, libraryName);
155 return file;
156 }
157
dlopenLibrary(const char * libraryName)158 static void* dlopenLibrary(const char* libraryName) {
159 return __wrap_dlopen(getUnpackedLibraryName(libraryName).get(),
160 RTLD_GLOBAL | RTLD_LAZY);
161 }
162
EnsureBaseProfilerInitialized()163 static void EnsureBaseProfilerInitialized() {
164 // There is no single entry-point into C++ code on Android.
165 // Instead, GeckoThread and GeckoLibLoader call various functions to load
166 // libraries one-by-one.
167 // We want to capture all that library loading in the profiler, so we need to
168 // kick off the base profiler at the beginning of whichever function is called
169 // first.
170 // We currently assume that all these functions are called on the same thread.
171 static bool sInitialized = false;
172 if (sInitialized) {
173 return;
174 }
175
176 #ifdef MOZ_GECKO_PROFILER
177 // The stack depth we observe here will be determined by the stack of
178 // whichever caller enters this code first. In practice this means that we may
179 // miss some root-most frames, which hopefully shouldn't ruin profiling.
180 int stackBase = 5;
181 mozilla::baseprofiler::profiler_init(&stackBase);
182 #endif
183 sInitialized = true;
184 }
185
loadGeckoLibs()186 static LoadGeckoLibsResult loadGeckoLibs() {
187 TimeStamp t0 = TimeStamp::Now();
188 struct rusage usage1_thread, usage1;
189 getrusage(RUSAGE_THREAD, &usage1_thread);
190 getrusage(RUSAGE_SELF, &usage1);
191
192 static const char* libxul = getenv("MOZ_ANDROID_LIBDIR_OVERRIDE");
193 MOZ_TRY_VAR(
194 gBootstrap,
195 GetBootstrap(libxul ? libxul : getUnpackedLibraryName("libxul.so").get(),
196 LibLoadingStrategy::ReadAhead));
197
198 TimeStamp t1 = TimeStamp::Now();
199 struct rusage usage2_thread, usage2;
200 getrusage(RUSAGE_THREAD, &usage2_thread);
201 getrusage(RUSAGE_SELF, &usage2);
202
203 #define RUSAGE_TIMEDIFF(u1, u2, field) \
204 ((u2.ru_##field.tv_sec - u1.ru_##field.tv_sec) * 1000 + \
205 (u2.ru_##field.tv_usec - u1.ru_##field.tv_usec) / 1000)
206
207 __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad",
208 "Loaded libs in %fms total, %ldms(%ldms) user, "
209 "%ldms(%ldms) system, %ld(%ld) faults",
210 (t1 - t0).ToMilliseconds(),
211 RUSAGE_TIMEDIFF(usage1_thread, usage2_thread, utime),
212 RUSAGE_TIMEDIFF(usage1, usage2, utime),
213 RUSAGE_TIMEDIFF(usage1_thread, usage2_thread, stime),
214 RUSAGE_TIMEDIFF(usage1, usage2, stime),
215 usage2_thread.ru_majflt - usage1_thread.ru_majflt,
216 usage2.ru_majflt - usage1.ru_majflt);
217
218 gBootstrap->XRE_StartupTimelineRecord(LINKER_INITIALIZED, t0);
219 gBootstrap->XRE_StartupTimelineRecord(LIBRARIES_LOADED, t1);
220 return Ok();
221 }
222
223 static mozglueresult loadNSSLibs();
224
loadSQLiteLibs()225 static mozglueresult loadSQLiteLibs() {
226 if (sqlite_handle) return SUCCESS;
227
228 #ifdef MOZ_FOLD_LIBS
229 if (loadNSSLibs() != SUCCESS) return FAILURE;
230 #else
231
232 sqlite_handle = dlopenLibrary("libmozsqlite3.so");
233 if (!sqlite_handle) {
234 __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad",
235 "Couldn't get a handle to libmozsqlite3!");
236 return FAILURE;
237 }
238 #endif
239
240 return SUCCESS;
241 }
242
loadNSSLibs()243 static mozglueresult loadNSSLibs() {
244 if (nss_handle && nspr_handle && plc_handle) return SUCCESS;
245
246 nss_handle = dlopenLibrary("libnss3.so");
247
248 #ifndef MOZ_FOLD_LIBS
249 nspr_handle = dlopenLibrary("libnspr4.so");
250
251 plc_handle = dlopenLibrary("libplc4.so");
252 #endif
253
254 if (!nss_handle) {
255 __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad",
256 "Couldn't get a handle to libnss3!");
257 return FAILURE;
258 }
259
260 #ifndef MOZ_FOLD_LIBS
261 if (!nspr_handle) {
262 __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad",
263 "Couldn't get a handle to libnspr4!");
264 return FAILURE;
265 }
266
267 if (!plc_handle) {
268 __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad",
269 "Couldn't get a handle to libplc4!");
270 return FAILURE;
271 }
272 #endif
273
274 return SUCCESS;
275 }
276
277 extern "C" APKOPEN_EXPORT void MOZ_JNICALL
Java_org_mozilla_gecko_mozglue_GeckoLoader_loadGeckoLibsNative(JNIEnv * jenv,jclass jGeckoAppShellClass)278 Java_org_mozilla_gecko_mozglue_GeckoLoader_loadGeckoLibsNative(
279 JNIEnv* jenv, jclass jGeckoAppShellClass) {
280 EnsureBaseProfilerInitialized();
281
282 jenv->GetJavaVM(&sJavaVM);
283
284 LoadGeckoLibsResult res = loadGeckoLibs();
285 if (res.isOk()) {
286 return;
287 }
288
289 const BootstrapError& errorInfo = res.inspectErr();
290
291 auto msg = errorInfo.match(
292 [](const nsresult& aRv) {
293 return Smprintf("Error loading Gecko libraries: nsresult 0x%08X", aRv);
294 },
295 [](const DLErrorType& aErr) {
296 return Smprintf("Error loading Gecko libraries: %s", aErr.get());
297 });
298
299 JNI_Throw(jenv, "java/lang/Exception", msg.get());
300 }
301
302 extern "C" APKOPEN_EXPORT void MOZ_JNICALL
Java_org_mozilla_gecko_mozglue_GeckoLoader_loadSQLiteLibsNative(JNIEnv * jenv,jclass jGeckoAppShellClass)303 Java_org_mozilla_gecko_mozglue_GeckoLoader_loadSQLiteLibsNative(
304 JNIEnv* jenv, jclass jGeckoAppShellClass) {
305 EnsureBaseProfilerInitialized();
306
307 __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad", "Load sqlite start\n");
308 mozglueresult rv = loadSQLiteLibs();
309 if (rv != SUCCESS) {
310 JNI_Throw(jenv, "java/lang/Exception", "Error loading sqlite libraries");
311 }
312 __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad", "Load sqlite done\n");
313 }
314
315 extern "C" APKOPEN_EXPORT void MOZ_JNICALL
Java_org_mozilla_gecko_mozglue_GeckoLoader_loadNSSLibsNative(JNIEnv * jenv,jclass jGeckoAppShellClass)316 Java_org_mozilla_gecko_mozglue_GeckoLoader_loadNSSLibsNative(
317 JNIEnv* jenv, jclass jGeckoAppShellClass) {
318 EnsureBaseProfilerInitialized();
319
320 __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad", "Load nss start\n");
321 mozglueresult rv = loadNSSLibs();
322 if (rv != SUCCESS) {
323 JNI_Throw(jenv, "java/lang/Exception", "Error loading nss libraries");
324 }
325 __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad", "Load nss done\n");
326 }
327
CreateArgvFromObjectArray(JNIEnv * jenv,jobjectArray jargs,int * length)328 static char** CreateArgvFromObjectArray(JNIEnv* jenv, jobjectArray jargs,
329 int* length) {
330 size_t stringCount = jenv->GetArrayLength(jargs);
331
332 if (length) {
333 *length = stringCount;
334 }
335
336 if (!stringCount) {
337 return nullptr;
338 }
339
340 char** argv = new char*[stringCount + 1];
341
342 argv[stringCount] = nullptr;
343
344 for (size_t ix = 0; ix < stringCount; ix++) {
345 jstring string = (jstring)(jenv->GetObjectArrayElement(jargs, ix));
346 const char* rawString = jenv->GetStringUTFChars(string, nullptr);
347 const int strLength = jenv->GetStringUTFLength(string);
348 argv[ix] = strndup(rawString, strLength);
349 jenv->ReleaseStringUTFChars(string, rawString);
350 jenv->DeleteLocalRef(string);
351 }
352
353 return argv;
354 }
355
FreeArgv(char ** argv,int argc)356 static void FreeArgv(char** argv, int argc) {
357 for (int ix = 0; ix < argc; ix++) {
358 // String was allocated with strndup, so need to use free to deallocate.
359 free(argv[ix]);
360 }
361 delete[](argv);
362 }
363
364 extern "C" APKOPEN_EXPORT void MOZ_JNICALL
Java_org_mozilla_gecko_mozglue_GeckoLoader_nativeRun(JNIEnv * jenv,jclass jc,jobjectArray jargs,int prefsFd,int prefMapFd,int ipcFd,int crashFd,int crashAnnotationFd,bool xpcshell,jstring outFilePath)365 Java_org_mozilla_gecko_mozglue_GeckoLoader_nativeRun(
366 JNIEnv* jenv, jclass jc, jobjectArray jargs, int prefsFd, int prefMapFd,
367 int ipcFd, int crashFd, int crashAnnotationFd, bool xpcshell,
368 jstring outFilePath) {
369 EnsureBaseProfilerInitialized();
370
371 int argc = 0;
372 char** argv = CreateArgvFromObjectArray(jenv, jargs, &argc);
373
374 if (ipcFd < 0) {
375 if (gBootstrap == nullptr) {
376 FreeArgv(argv, argc);
377 return;
378 }
379
380 #ifdef MOZ_LINKER
381 ElfLoader::Singleton.ExpectShutdown(false);
382 #endif
383 const char* outFilePathRaw = nullptr;
384 if (xpcshell) {
385 MOZ_ASSERT(outFilePath);
386 outFilePathRaw = jenv->GetStringUTFChars(outFilePath, nullptr);
387 }
388 gBootstrap->GeckoStart(jenv, argv, argc, sAppData, xpcshell,
389 outFilePathRaw);
390 if (outFilePathRaw) {
391 jenv->ReleaseStringUTFChars(outFilePath, outFilePathRaw);
392 }
393 #ifdef MOZ_LINKER
394 ElfLoader::Singleton.ExpectShutdown(true);
395 #endif
396 } else {
397 gBootstrap->XRE_SetAndroidChildFds(
398 jenv, {prefsFd, prefMapFd, ipcFd, crashFd, crashAnnotationFd});
399 gBootstrap->XRE_SetProcessType(argv[argc - 1]);
400
401 XREChildData childData;
402 gBootstrap->XRE_InitChildProcess(argc - 1, argv, &childData);
403 }
404
405 #ifdef MOZ_WIDGET_ANDROID
406 # ifdef MOZ_PROFILE_GENERATE
407 gBootstrap->XRE_WriteLLVMProfData();
408 # endif
409 #endif
410 gBootstrap.reset();
411 FreeArgv(argv, argc);
412 }
413
ChildProcessInit(int argc,char * argv[])414 extern "C" APKOPEN_EXPORT mozglueresult ChildProcessInit(int argc,
415 char* argv[]) {
416 EnsureBaseProfilerInitialized();
417
418 if (loadNSSLibs() != SUCCESS) {
419 return FAILURE;
420 }
421 if (loadSQLiteLibs() != SUCCESS) {
422 return FAILURE;
423 }
424 if (loadGeckoLibs().isErr()) {
425 return FAILURE;
426 }
427
428 gBootstrap->XRE_SetProcessType(argv[--argc]);
429
430 XREChildData childData;
431 return NS_FAILED(gBootstrap->XRE_InitChildProcess(argc, argv, &childData));
432 }
433
434 // Does current process name end with ':media'?
IsMediaProcess()435 static bool IsMediaProcess() {
436 pid_t pid = getpid();
437 char str[256];
438 SprintfLiteral(str, "/proc/%d/cmdline", pid);
439 FILE* f = fopen(str, "r");
440 if (f) {
441 fgets(str, sizeof(str), f);
442 fclose(f);
443 const size_t strLen = strlen(str);
444 const char suffix[] = ":media";
445 const size_t suffixLen = sizeof(suffix) - 1;
446 if (strLen >= suffixLen &&
447 !strncmp(str + strLen - suffixLen, suffix, suffixLen)) {
448 return true;
449 }
450 }
451 return false;
452 }
453
454 #ifndef SYS_rt_tgsigqueueinfo
455 # define SYS_rt_tgsigqueueinfo __NR_rt_tgsigqueueinfo
456 #endif
457 /* Copy of http://androidxref.com/7.1.1_r6/xref/bionic/linker/debugger.cpp#262,
458 * with debuggerd related code stripped.
459 *
460 * Copyright (C) 2008 The Android Open Source Project
461 * All rights reserved.
462 *
463 * Redistribution and use in source and binary forms, with or without
464 * modification, are permitted provided that the following conditions
465 * are met:
466 * * Redistributions of source code must retain the above copyright
467 * notice, this list of conditions and the following disclaimer.
468 * * Redistributions in binary form must reproduce the above copyright
469 * notice, this list of conditions and the following disclaimer in
470 * the documentation and/or other materials provided with the
471 * distribution.
472 *
473 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
474 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
475 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
476 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
477 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
478 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
479 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
480 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
481 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
482 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
483 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
484 * SUCH DAMAGE.
485 */
CatchFatalSignals(int num,siginfo_t * info,void * context)486 static void CatchFatalSignals(int num, siginfo_t* info, void* context) {
487 // It's possible somebody cleared the SA_SIGINFO flag, which would mean
488 // our "info" arg holds an undefined value.
489 struct sigaction action = {};
490 if ((sigaction(num, nullptr, &action) < 0) ||
491 !(action.sa_flags & SA_SIGINFO)) {
492 info = nullptr;
493 }
494
495 // We need to return from the signal handler so that debuggerd can dump the
496 // thread that crashed, but returning here does not guarantee that the signal
497 // will be thrown again, even for SIGSEGV and friends, since the signal could
498 // have been sent manually. Resend the signal with rt_tgsigqueueinfo(2) to
499 // preserve the SA_SIGINFO contents.
500 signal(num, SIG_DFL);
501
502 struct siginfo si;
503 if (!info) {
504 memset(&si, 0, sizeof(si));
505 si.si_code = SI_USER;
506 si.si_pid = getpid();
507 si.si_uid = getuid();
508 info = &si;
509 } else if (info->si_code >= 0 || info->si_code == SI_TKILL) {
510 // rt_tgsigqueueinfo(2)'s documentation appears to be incorrect on kernels
511 // that contain commit 66dd34a (3.9+). The manpage claims to only allow
512 // negative si_code values that are not SI_TKILL, but 66dd34a changed the
513 // check to allow all si_code values in calls coming from inside the house.
514 }
515
516 int rc = syscall(SYS_rt_tgsigqueueinfo, getpid(), gettid(), num, info);
517 if (rc != 0) {
518 __android_log_print(ANDROID_LOG_FATAL, "mozglue",
519 "failed to resend signal during crash: %s",
520 strerror(errno));
521 _exit(0);
522 }
523 }
524
525 extern "C" APKOPEN_EXPORT void MOZ_JNICALL
Java_org_mozilla_gecko_mozglue_GeckoLoader_suppressCrashDialog(JNIEnv * jenv,jclass jc)526 Java_org_mozilla_gecko_mozglue_GeckoLoader_suppressCrashDialog(JNIEnv* jenv,
527 jclass jc) {
528 MOZ_RELEASE_ASSERT(IsMediaProcess(),
529 "Suppress crash dialog only for media process");
530 // Restoring to SIG_DFL will crash on x86/Android M devices (see bug 1374556)
531 // so copy Android code
532 // (http://androidxref.com/7.1.1_r6/xref/bionic/linker/debugger.cpp#302). See
533 // comments above CatchFatalSignals() for copyright notice.
534 struct sigaction action;
535 memset(&action, 0, sizeof(action));
536 sigemptyset(&action.sa_mask);
537 action.sa_sigaction = &CatchFatalSignals;
538 action.sa_flags = SA_RESTART | SA_SIGINFO;
539
540 // Use the alternate signal stack if available so we can catch stack
541 // overflows.
542 action.sa_flags |= SA_ONSTACK;
543
544 sigaction(SIGABRT, &action, nullptr);
545 sigaction(SIGBUS, &action, nullptr);
546 sigaction(SIGFPE, &action, nullptr);
547 sigaction(SIGILL, &action, nullptr);
548 sigaction(SIGSEGV, &action, nullptr);
549 #if defined(SIGSTKFLT)
550 sigaction(SIGSTKFLT, &action, nullptr);
551 #endif
552 sigaction(SIGTRAP, &action, nullptr);
553 }
554