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 // The stack depth we observe here will be determined by the stack of
177 // whichever caller enters this code first. In practice this means that we may
178 // miss some root-most frames, which hopefully shouldn't ruin profiling.
179 int stackBase = 5;
180 mozilla::baseprofiler::profiler_init(&stackBase);
181 sInitialized = true;
182 }
183
loadGeckoLibs()184 static LoadGeckoLibsResult loadGeckoLibs() {
185 TimeStamp t0 = TimeStamp::Now();
186 struct rusage usage1_thread, usage1;
187 getrusage(RUSAGE_THREAD, &usage1_thread);
188 getrusage(RUSAGE_SELF, &usage1);
189
190 static const char* libxul = getenv("MOZ_ANDROID_LIBDIR_OVERRIDE");
191 MOZ_TRY_VAR(
192 gBootstrap,
193 GetBootstrap(libxul ? libxul : getUnpackedLibraryName("libxul.so").get(),
194 LibLoadingStrategy::ReadAhead));
195
196 TimeStamp t1 = TimeStamp::Now();
197 struct rusage usage2_thread, usage2;
198 getrusage(RUSAGE_THREAD, &usage2_thread);
199 getrusage(RUSAGE_SELF, &usage2);
200
201 #define RUSAGE_TIMEDIFF(u1, u2, field) \
202 ((u2.ru_##field.tv_sec - u1.ru_##field.tv_sec) * 1000 + \
203 (u2.ru_##field.tv_usec - u1.ru_##field.tv_usec) / 1000)
204
205 __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad",
206 "Loaded libs in %fms total, %ldms(%ldms) user, "
207 "%ldms(%ldms) system, %ld(%ld) faults",
208 (t1 - t0).ToMilliseconds(),
209 RUSAGE_TIMEDIFF(usage1_thread, usage2_thread, utime),
210 RUSAGE_TIMEDIFF(usage1, usage2, utime),
211 RUSAGE_TIMEDIFF(usage1_thread, usage2_thread, stime),
212 RUSAGE_TIMEDIFF(usage1, usage2, stime),
213 usage2_thread.ru_majflt - usage1_thread.ru_majflt,
214 usage2.ru_majflt - usage1.ru_majflt);
215
216 gBootstrap->XRE_StartupTimelineRecord(LINKER_INITIALIZED, t0);
217 gBootstrap->XRE_StartupTimelineRecord(LIBRARIES_LOADED, t1);
218 return Ok();
219 }
220
221 static mozglueresult loadNSSLibs();
222
loadSQLiteLibs()223 static mozglueresult loadSQLiteLibs() {
224 if (sqlite_handle) return SUCCESS;
225
226 #ifdef MOZ_FOLD_LIBS
227 if (loadNSSLibs() != SUCCESS) return FAILURE;
228 #else
229
230 sqlite_handle = dlopenLibrary("libmozsqlite3.so");
231 if (!sqlite_handle) {
232 __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad",
233 "Couldn't get a handle to libmozsqlite3!");
234 return FAILURE;
235 }
236 #endif
237
238 return SUCCESS;
239 }
240
loadNSSLibs()241 static mozglueresult loadNSSLibs() {
242 if (nss_handle && nspr_handle && plc_handle) return SUCCESS;
243
244 nss_handle = dlopenLibrary("libnss3.so");
245
246 #ifndef MOZ_FOLD_LIBS
247 nspr_handle = dlopenLibrary("libnspr4.so");
248
249 plc_handle = dlopenLibrary("libplc4.so");
250 #endif
251
252 if (!nss_handle) {
253 __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad",
254 "Couldn't get a handle to libnss3!");
255 return FAILURE;
256 }
257
258 #ifndef MOZ_FOLD_LIBS
259 if (!nspr_handle) {
260 __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad",
261 "Couldn't get a handle to libnspr4!");
262 return FAILURE;
263 }
264
265 if (!plc_handle) {
266 __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad",
267 "Couldn't get a handle to libplc4!");
268 return FAILURE;
269 }
270 #endif
271
272 return SUCCESS;
273 }
274
275 extern "C" APKOPEN_EXPORT void MOZ_JNICALL
Java_org_mozilla_gecko_mozglue_GeckoLoader_loadGeckoLibsNative(JNIEnv * jenv,jclass jGeckoAppShellClass)276 Java_org_mozilla_gecko_mozglue_GeckoLoader_loadGeckoLibsNative(
277 JNIEnv* jenv, jclass jGeckoAppShellClass) {
278 EnsureBaseProfilerInitialized();
279
280 jenv->GetJavaVM(&sJavaVM);
281
282 LoadGeckoLibsResult res = loadGeckoLibs();
283 if (res.isOk()) {
284 return;
285 }
286
287 const BootstrapError& errorInfo = res.inspectErr();
288
289 auto msg = errorInfo.match(
290 [](const nsresult& aRv) {
291 return Smprintf("Error loading Gecko libraries: nsresult 0x%08X", aRv);
292 },
293 [](const DLErrorType& aErr) {
294 return Smprintf("Error loading Gecko libraries: %s", aErr.get());
295 });
296
297 JNI_Throw(jenv, "java/lang/Exception", msg.get());
298 }
299
300 extern "C" APKOPEN_EXPORT void MOZ_JNICALL
Java_org_mozilla_gecko_mozglue_GeckoLoader_loadSQLiteLibsNative(JNIEnv * jenv,jclass jGeckoAppShellClass)301 Java_org_mozilla_gecko_mozglue_GeckoLoader_loadSQLiteLibsNative(
302 JNIEnv* jenv, jclass jGeckoAppShellClass) {
303 EnsureBaseProfilerInitialized();
304
305 __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad", "Load sqlite start\n");
306 mozglueresult rv = loadSQLiteLibs();
307 if (rv != SUCCESS) {
308 JNI_Throw(jenv, "java/lang/Exception", "Error loading sqlite libraries");
309 }
310 __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad", "Load sqlite done\n");
311 }
312
313 extern "C" APKOPEN_EXPORT void MOZ_JNICALL
Java_org_mozilla_gecko_mozglue_GeckoLoader_loadNSSLibsNative(JNIEnv * jenv,jclass jGeckoAppShellClass)314 Java_org_mozilla_gecko_mozglue_GeckoLoader_loadNSSLibsNative(
315 JNIEnv* jenv, jclass jGeckoAppShellClass) {
316 EnsureBaseProfilerInitialized();
317
318 __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad", "Load nss start\n");
319 mozglueresult rv = loadNSSLibs();
320 if (rv != SUCCESS) {
321 JNI_Throw(jenv, "java/lang/Exception", "Error loading nss libraries");
322 }
323 __android_log_print(ANDROID_LOG_ERROR, "GeckoLibLoad", "Load nss done\n");
324 }
325
CreateArgvFromObjectArray(JNIEnv * jenv,jobjectArray jargs,int * length)326 static char** CreateArgvFromObjectArray(JNIEnv* jenv, jobjectArray jargs,
327 int* length) {
328 size_t stringCount = jenv->GetArrayLength(jargs);
329
330 if (length) {
331 *length = stringCount;
332 }
333
334 if (!stringCount) {
335 return nullptr;
336 }
337
338 char** argv = new char*[stringCount + 1];
339
340 argv[stringCount] = nullptr;
341
342 for (size_t ix = 0; ix < stringCount; ix++) {
343 jstring string = (jstring)(jenv->GetObjectArrayElement(jargs, ix));
344 const char* rawString = jenv->GetStringUTFChars(string, nullptr);
345 const int strLength = jenv->GetStringUTFLength(string);
346 argv[ix] = strndup(rawString, strLength);
347 jenv->ReleaseStringUTFChars(string, rawString);
348 jenv->DeleteLocalRef(string);
349 }
350
351 return argv;
352 }
353
FreeArgv(char ** argv,int argc)354 static void FreeArgv(char** argv, int argc) {
355 for (int ix = 0; ix < argc; ix++) {
356 // String was allocated with strndup, so need to use free to deallocate.
357 free(argv[ix]);
358 }
359 delete[](argv);
360 }
361
362 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)363 Java_org_mozilla_gecko_mozglue_GeckoLoader_nativeRun(
364 JNIEnv* jenv, jclass jc, jobjectArray jargs, int prefsFd, int prefMapFd,
365 int ipcFd, int crashFd, int crashAnnotationFd, bool xpcshell,
366 jstring outFilePath) {
367 EnsureBaseProfilerInitialized();
368
369 int argc = 0;
370 char** argv = CreateArgvFromObjectArray(jenv, jargs, &argc);
371
372 if (ipcFd < 0) {
373 if (gBootstrap == nullptr) {
374 FreeArgv(argv, argc);
375 return;
376 }
377
378 #ifdef MOZ_LINKER
379 ElfLoader::Singleton.ExpectShutdown(false);
380 #endif
381 const char* outFilePathRaw = nullptr;
382 if (xpcshell) {
383 MOZ_ASSERT(outFilePath);
384 outFilePathRaw = jenv->GetStringUTFChars(outFilePath, nullptr);
385 }
386 gBootstrap->GeckoStart(jenv, argv, argc, sAppData, xpcshell,
387 outFilePathRaw);
388 if (outFilePathRaw) {
389 jenv->ReleaseStringUTFChars(outFilePath, outFilePathRaw);
390 }
391 #ifdef MOZ_LINKER
392 ElfLoader::Singleton.ExpectShutdown(true);
393 #endif
394 } else {
395 gBootstrap->XRE_SetAndroidChildFds(
396 jenv, {prefsFd, prefMapFd, ipcFd, crashFd, crashAnnotationFd});
397 gBootstrap->XRE_SetProcessType(argv[argc - 1]);
398
399 XREChildData childData;
400 gBootstrap->XRE_InitChildProcess(argc - 1, argv, &childData);
401 }
402
403 #ifdef MOZ_WIDGET_ANDROID
404 # ifdef MOZ_PROFILE_GENERATE
405 gBootstrap->XRE_WriteLLVMProfData();
406 # endif
407 #endif
408 gBootstrap.reset();
409 FreeArgv(argv, argc);
410 }
411
ChildProcessInit(int argc,char * argv[])412 extern "C" APKOPEN_EXPORT mozglueresult ChildProcessInit(int argc,
413 char* argv[]) {
414 EnsureBaseProfilerInitialized();
415
416 if (loadNSSLibs() != SUCCESS) {
417 return FAILURE;
418 }
419 if (loadSQLiteLibs() != SUCCESS) {
420 return FAILURE;
421 }
422 if (loadGeckoLibs().isErr()) {
423 return FAILURE;
424 }
425
426 gBootstrap->XRE_SetProcessType(argv[--argc]);
427
428 XREChildData childData;
429 return NS_FAILED(gBootstrap->XRE_InitChildProcess(argc, argv, &childData));
430 }
431
432 // Does current process name end with ':media'?
IsMediaProcess()433 static bool IsMediaProcess() {
434 pid_t pid = getpid();
435 char str[256];
436 SprintfLiteral(str, "/proc/%d/cmdline", pid);
437 FILE* f = fopen(str, "r");
438 if (f) {
439 fgets(str, sizeof(str), f);
440 fclose(f);
441 const size_t strLen = strlen(str);
442 const char suffix[] = ":media";
443 const size_t suffixLen = sizeof(suffix) - 1;
444 if (strLen >= suffixLen &&
445 !strncmp(str + strLen - suffixLen, suffix, suffixLen)) {
446 return true;
447 }
448 }
449 return false;
450 }
451
452 #ifndef SYS_rt_tgsigqueueinfo
453 # define SYS_rt_tgsigqueueinfo __NR_rt_tgsigqueueinfo
454 #endif
455 /* Copy of http://androidxref.com/7.1.1_r6/xref/bionic/linker/debugger.cpp#262,
456 * with debuggerd related code stripped.
457 *
458 * Copyright (C) 2008 The Android Open Source Project
459 * All rights reserved.
460 *
461 * Redistribution and use in source and binary forms, with or without
462 * modification, are permitted provided that the following conditions
463 * are met:
464 * * Redistributions of source code must retain the above copyright
465 * notice, this list of conditions and the following disclaimer.
466 * * Redistributions in binary form must reproduce the above copyright
467 * notice, this list of conditions and the following disclaimer in
468 * the documentation and/or other materials provided with the
469 * distribution.
470 *
471 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
472 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
473 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
474 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
475 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
476 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
477 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
478 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
479 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
480 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
481 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
482 * SUCH DAMAGE.
483 */
CatchFatalSignals(int num,siginfo_t * info,void * context)484 static void CatchFatalSignals(int num, siginfo_t* info, void* context) {
485 // It's possible somebody cleared the SA_SIGINFO flag, which would mean
486 // our "info" arg holds an undefined value.
487 struct sigaction action = {};
488 if ((sigaction(num, nullptr, &action) < 0) ||
489 !(action.sa_flags & SA_SIGINFO)) {
490 info = nullptr;
491 }
492
493 // We need to return from the signal handler so that debuggerd can dump the
494 // thread that crashed, but returning here does not guarantee that the signal
495 // will be thrown again, even for SIGSEGV and friends, since the signal could
496 // have been sent manually. Resend the signal with rt_tgsigqueueinfo(2) to
497 // preserve the SA_SIGINFO contents.
498 signal(num, SIG_DFL);
499
500 struct siginfo si;
501 if (!info) {
502 memset(&si, 0, sizeof(si));
503 si.si_code = SI_USER;
504 si.si_pid = getpid();
505 si.si_uid = getuid();
506 info = &si;
507 } else if (info->si_code >= 0 || info->si_code == SI_TKILL) {
508 // rt_tgsigqueueinfo(2)'s documentation appears to be incorrect on kernels
509 // that contain commit 66dd34a (3.9+). The manpage claims to only allow
510 // negative si_code values that are not SI_TKILL, but 66dd34a changed the
511 // check to allow all si_code values in calls coming from inside the house.
512 }
513
514 int rc = syscall(SYS_rt_tgsigqueueinfo, getpid(), gettid(), num, info);
515 if (rc != 0) {
516 __android_log_print(ANDROID_LOG_FATAL, "mozglue",
517 "failed to resend signal during crash: %s",
518 strerror(errno));
519 _exit(0);
520 }
521 }
522
523 extern "C" APKOPEN_EXPORT void MOZ_JNICALL
Java_org_mozilla_gecko_mozglue_GeckoLoader_suppressCrashDialog(JNIEnv * jenv,jclass jc)524 Java_org_mozilla_gecko_mozglue_GeckoLoader_suppressCrashDialog(JNIEnv* jenv,
525 jclass jc) {
526 MOZ_RELEASE_ASSERT(IsMediaProcess(),
527 "Suppress crash dialog only for media process");
528 // Restoring to SIG_DFL will crash on x86/Android M devices (see bug 1374556)
529 // so copy Android code
530 // (http://androidxref.com/7.1.1_r6/xref/bionic/linker/debugger.cpp#302). See
531 // comments above CatchFatalSignals() for copyright notice.
532 struct sigaction action;
533 memset(&action, 0, sizeof(action));
534 sigemptyset(&action.sa_mask);
535 action.sa_sigaction = &CatchFatalSignals;
536 action.sa_flags = SA_RESTART | SA_SIGINFO;
537
538 // Use the alternate signal stack if available so we can catch stack
539 // overflows.
540 action.sa_flags |= SA_ONSTACK;
541
542 sigaction(SIGABRT, &action, nullptr);
543 sigaction(SIGBUS, &action, nullptr);
544 sigaction(SIGFPE, &action, nullptr);
545 sigaction(SIGILL, &action, nullptr);
546 sigaction(SIGSEGV, &action, nullptr);
547 #if defined(SIGSTKFLT)
548 sigaction(SIGSTKFLT, &action, nullptr);
549 #endif
550 sigaction(SIGTRAP, &action, nullptr);
551 }
552