/
Nuwa.cpp
2104 lines (1814 loc) · 62.4 KB
/
Nuwa.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
#include <map>
#include <memory>
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <setjmp.h>
#include <signal.h>
#include <poll.h>
#include <pthread.h>
#include <alloca.h>
#include <sys/epoll.h>
#include <sys/mman.h>
#include <sys/prctl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <vector>
#include "mozilla/Alignment.h"
#include "mozilla/LinkedList.h"
#include "mozilla/TaggedAnonymousMemory.h"
#include "Nuwa.h"
/* Support for telling Valgrind about the stack pointer changes that
Nuwa makes. Without this, Valgrind is unusable in Nuwa child
processes due to the large number of false positives resulting from
Nuwa's stack pointer changes. See bug 1125091.
*/
#if defined(MOZ_VALGRIND)
# include <valgrind/memcheck.h>
#endif
#define DEBUG_VALGRIND_ANNOTATIONS 1
/* Call this as soon as possible after a setjmp() that has returned
non-locally (that is, it is restoring some previous context). This
paints a small area -- half a page -- above SP as containing
defined data in any area which is currently marked accessible.
Note that in fact there are a few memory references to the stack
after the setjmp but before the use of this macro, even when they
appear consecutively in the source code. But those accesses all
appear to be stores, and since that part of the stack -- before we
get to the VALGRIND_MAKE_MEM_DEFINED_IF_ADDRESSABLE client request
-- is marked as accessible-but-undefined, Memcheck doesn't
complain. Of course, once we get past the client request then even
reading from the stack is "safe".
VALGRIND_MAKE_MEM_DEFINED_IF_ADDRESSABLE and VALGRIND_PRINTF each
require 6 words of stack space. In the worst case, in which the
compiler allocates two different pieces of stack, the required
extra stack is therefore 12 words, that is, 48 bytes on arm32.
*/
#if defined(MOZ_VALGRIND) && defined(VALGRIND_MAKE_MEM_DEFINED_IF_ADDRESSABLE) \
&& defined(__arm__) && !defined(__aarch64__)
# define POST_SETJMP_RESTORE(_who) \
do { \
/* setjmp returned 1 (meaning "restored"). Paint the area */ \
/* immediately above SP as "defined where it is accessible". */ \
register unsigned long int sp; \
__asm__ __volatile__("mov %0, sp" : "=r"(sp)); \
unsigned long int len = 1024*2; \
VALGRIND_MAKE_MEM_DEFINED_IF_ADDRESSABLE(sp, len); \
if (DEBUG_VALGRIND_ANNOTATIONS) { \
VALGRIND_PRINTF("Nuwa: POST_SETJMP_RESTORE: marking [0x%lx, +%ld) as " \
"Defined-if-Addressible, called by %s\n", \
sp, len, (_who)); \
} \
} while (0)
#else
# define POST_SETJMP_RESTORE(_who) /* */
#endif
using namespace mozilla;
/**
* Provides the wrappers to a selected set of pthread and system-level functions
* as the basis for implementing Zygote-like preforking mechanism.
*/
/**
* Real functions for the wrappers.
*/
extern "C" {
#pragma GCC visibility push(default)
int __real_pthread_create(pthread_t *thread,
const pthread_attr_t *attr,
void *(*start_routine) (void *),
void *arg);
int __real_pthread_key_create(pthread_key_t *key, void (*destructor)(void*));
int __real_pthread_key_delete(pthread_key_t key);
pthread_t __real_pthread_self();
int __real_pthread_join(pthread_t thread, void **retval);
int __real_epoll_wait(int epfd,
struct epoll_event *events,
int maxevents,
int timeout);
int __real_pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mtx);
int __real_pthread_cond_timedwait(pthread_cond_t *cond,
pthread_mutex_t *mtx,
const struct timespec *abstime);
int __real_pthread_mutex_lock(pthread_mutex_t *mtx);
int __real_pthread_mutex_trylock(pthread_mutex_t *mtx);
int __real_poll(struct pollfd *fds, nfds_t nfds, int timeout);
int __real_epoll_create(int size);
int __real_socketpair(int domain, int type, int protocol, int sv[2]);
int __real_pipe2(int __pipedes[2], int flags);
int __real_pipe(int __pipedes[2]);
int __real_epoll_ctl(int aEpollFd, int aOp, int aFd, struct epoll_event *aEvent);
int __real_close(int aFd);
#pragma GCC visibility pop
}
#define REAL(s) __real_##s
/**
* A Nuwa process is started by preparing. After preparing, it waits
* for all threads becoming frozen. Then, it is ready while all
* threads are frozen.
*/
static bool sIsNuwaProcess = false; // This process is a Nuwa process.
static bool sIsNuwaChildProcess = false; // This process is spawned from Nuwa.
static bool sIsFreezing = false; // Waiting for all threads getting frozen.
static bool sNuwaReady = false; // Nuwa process is ready.
static bool sNuwaPendingSpawn = false; // Are there any pending spawn requests?
static bool sNuwaForking = false;
// Fds of transports of top level protocols.
static NuwaProtoFdInfo sProtoFdInfos[NUWA_TOPLEVEL_MAX];
static int sProtoFdInfosSize = 0;
typedef std::vector<std::pair<pthread_key_t, void *> >
TLSInfoList;
/**
* Return the system's page size
*/
static size_t getPageSize(void) {
#ifdef HAVE_GETPAGESIZE
return getpagesize();
#elif defined(_SC_PAGESIZE)
return sysconf(_SC_PAGESIZE);
#elif defined(PAGE_SIZE)
return PAGE_SIZE;
#else
#warning "Hard-coding page size to 4096 bytes"
return 4096
#endif
}
/**
* Use 1 MiB stack size as Android does.
*/
#ifndef NUWA_STACK_SIZE
#define NUWA_STACK_SIZE (1024 * 1024)
#endif
#define NATIVE_THREAD_NAME_LENGTH 16
typedef struct nuwa_construct {
typedef void(*construct_t)(void*);
construct_t construct;
void *arg;
nuwa_construct(construct_t aConstruct, void *aArg)
: construct(aConstruct)
, arg(aArg)
{ }
nuwa_construct(const nuwa_construct&) = default;
nuwa_construct& operator=(const nuwa_construct&) = default;
} nuwa_construct_t;
struct thread_info : public mozilla::LinkedListElement<thread_info> {
pthread_t origThreadID;
pthread_t recreatedThreadID;
pthread_attr_t threadAttr;
jmp_buf jmpEnv;
jmp_buf retEnv;
int flags;
void *(*startupFunc)(void *arg);
void *startupArg;
// The thread specific function to recreate the new thread. It's executed
// after the thread is recreated.
std::vector<nuwa_construct_t> *recrFunctions;
void addThreadConstructor(const nuwa_construct_t *construct) {
if (!recrFunctions) {
recrFunctions = new std::vector<nuwa_construct_t>();
}
recrFunctions->push_back(*construct);
}
TLSInfoList tlsInfo;
/**
* We must ensure that the recreated thread has entered pthread_cond_wait() or
* similar functions before proceeding to recreate the next one. Otherwise, if
* the next thread depends on the same mutex, it may be used in an incorrect
* state. To do this, the main thread must unconditionally acquire the mutex.
* The mutex is unconditionally released when the recreated thread enters
* pthread_cond_wait(). The recreated thread may have locked the mutex itself
* (if the pthread_mutex_trylock succeeded) or another thread may have already
* held the lock. If the recreated thread did lock the mutex we must balance
* that with another unlock on the main thread, which is signaled by
* condMutexNeedsBalancing.
*/
pthread_mutex_t *condMutex;
bool condMutexNeedsBalancing;
size_t stackSize;
size_t guardSize;
void *stk;
pid_t origNativeThreadID;
pid_t recreatedNativeThreadID;
char nativeThreadName[NATIVE_THREAD_NAME_LENGTH];
};
typedef struct thread_info thread_info_t;
static thread_info_t *sCurrentRecreatingThread = nullptr;
/**
* This function runs the custom recreation function registered when calling
* NuwaMarkCurrentThread() after thread stack is restored.
*/
static void
RunCustomRecreation() {
thread_info_t *tinfo = sCurrentRecreatingThread;
if (tinfo->recrFunctions) {
for (auto iter = tinfo->recrFunctions->begin();
iter != tinfo->recrFunctions->end();
iter++) {
iter->construct(iter->arg);
}
}
}
/**
* Every thread should be marked as either TINFO_FLAG_NUWA_SUPPORT or
* TINFO_FLAG_NUWA_SKIP, or it means a potential error. We force
* Gecko code to mark every single thread to make sure there are no accidents
* when recreating threads with Nuwa.
*
* Threads marked as TINFO_FLAG_NUWA_SUPPORT can be checkpointed explicitly, by
* calling NuwaCheckpointCurrentThread(), or implicitly when they call into wrapped
* functions like pthread_mutex_lock(), epoll_wait(), etc.
* TINFO_FLAG_NUWA_EXPLICIT_CHECKPOINT denotes the explicitly checkpointed thread.
*/
#define TINFO_FLAG_NUWA_SUPPORT 0x1
#define TINFO_FLAG_NUWA_SKIP 0x2
#define TINFO_FLAG_NUWA_EXPLICIT_CHECKPOINT 0x4
static std::vector<nuwa_construct_t> sConstructors;
static std::vector<nuwa_construct_t> sFinalConstructors;
class TLSKey
: public std::pair<pthread_key_t, void (*)(void*)>
, public LinkedListElement<TLSKey>
{
public:
TLSKey() {}
TLSKey(pthread_key_t aKey, void (*aDestructor)(void*))
: std::pair<pthread_key_t, void (*)(void*)>(aKey, aDestructor)
{}
static void* operator new(size_t size) {
if (sUsed)
return ::operator new(size);
sUsed = true;
return sFirstElement.addr();
}
static void operator delete(void* ptr) {
if (ptr == sFirstElement.addr()) {
sUsed = false;
return;
}
::operator delete(ptr);
}
private:
static bool sUsed;
static AlignedStorage2<TLSKey> sFirstElement;
};
bool TLSKey::sUsed = false;
AlignedStorage2<TLSKey> TLSKey::sFirstElement;
static AutoCleanLinkedList<TLSKey> sTLSKeys;
/**
* This mutex is used to block the running threads and freeze their contexts.
* PrepareNuwaProcess() is the first one to acquire the lock. Further attempts
* to acquire this mutex (in the freeze point macros) will block and freeze the
* calling thread.
*/
static pthread_mutex_t sThreadFreezeLock = PTHREAD_MUTEX_INITIALIZER;
static thread_info_t sMainThread;
static int sThreadCount = 0;
static int sThreadFreezeCount = 0;
// Bug 1008254: LinkedList's destructor asserts that the list is empty.
// But here, on exit, when the global sAllThreads list
// is destroyed, it may or may not be empty. Bug 1008254 comment 395 has a log
// when there were 8 threads remaining on exit. So this assertion was
// intermittently (almost every second time) failing.
// As a work-around to avoid this intermittent failure, we clear the list on
// exit just before it gets destroyed. This is the only purpose of that
// AllThreadsListType subclass.
struct AllThreadsListType : public AutoCleanLinkedList<thread_info_t>
{
~AllThreadsListType()
{
if (!isEmpty()) {
__android_log_print(ANDROID_LOG_WARN, "Nuwa",
"Threads remaining at exit:\n");
int n = 0;
for (const thread_info_t* t = getFirst(); t; t = t->getNext()) {
__android_log_print(ANDROID_LOG_WARN, "Nuwa",
" %.*s (origNativeThreadID=%d recreatedNativeThreadID=%d)\n",
NATIVE_THREAD_NAME_LENGTH,
t->nativeThreadName,
t->origNativeThreadID,
t->recreatedNativeThreadID);
n++;
}
__android_log_print(ANDROID_LOG_WARN, "Nuwa",
"total: %d outstanding threads. "
"Please fix them so they're destroyed before this point!\n", n);
__android_log_print(ANDROID_LOG_WARN, "Nuwa",
"note: sThreadCount=%d, sThreadFreezeCount=%d\n",
sThreadCount,
sThreadFreezeCount);
}
}
};
static AllThreadsListType sAllThreads;
static AllThreadsListType sExitingThreads;
/**
* This mutex protects the access to thread info:
* sAllThreads, sThreadCount, sThreadFreezeCount, sRecreateVIPCount.
*/
static pthread_mutex_t sThreadCountLock = PTHREAD_MUTEX_INITIALIZER;
/**
* This condition variable lets MakeNuwaProcess() wait until all recreated
* threads are frozen.
*/
static pthread_cond_t sThreadChangeCond = PTHREAD_COND_INITIALIZER;
/**
* This mutex and condition variable is used to serialize the fork requests
* from the parent process.
*/
static pthread_mutex_t sForkLock = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t sForkWaitCond = PTHREAD_COND_INITIALIZER;
/**
* sForkWaitCondChanged will be reset to false on the IPC thread before
* and will be changed to true on the main thread to indicate that the condition
* that the IPC thread is waiting for has already changed.
*/
static bool sForkWaitCondChanged = false;
/**
* This mutex protects the access to sTLSKeys, which keeps track of existing
* TLS Keys.
*/
static pthread_mutex_t sTLSKeyLock = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER;
static int sThreadSkipCount = 0;
static thread_info_t *
GetThreadInfoInner(pthread_t threadID) {
for (thread_info_t *tinfo = sAllThreads.getFirst();
tinfo;
tinfo = tinfo->getNext()) {
if (pthread_equal(tinfo->origThreadID, threadID)) {
return tinfo;
}
}
for (thread_info_t *tinfo = sExitingThreads.getFirst();
tinfo;
tinfo = tinfo->getNext()) {
if (pthread_equal(tinfo->origThreadID, threadID)) {
return tinfo;
}
}
return nullptr;
}
/**
* Get thread info using the specified thread ID.
*
* @return thread_info_t which has threadID == specified threadID
*/
static thread_info_t *
GetThreadInfo(pthread_t threadID) {
REAL(pthread_mutex_lock)(&sThreadCountLock);
thread_info_t *tinfo = GetThreadInfoInner(threadID);
pthread_mutex_unlock(&sThreadCountLock);
return tinfo;
}
#if !defined(HAVE_THREAD_TLS_KEYWORD)
/**
* Get thread info of the current thread.
*
* @return thread_info_t for the current thread.
*/
static thread_info_t *
GetCurThreadInfo() {
pthread_t threadID = REAL(pthread_self)();
pthread_t thread_info_t::*threadIDptr =
(sIsNuwaProcess ?
&thread_info_t::origThreadID :
&thread_info_t::recreatedThreadID);
REAL(pthread_mutex_lock)(&sThreadCountLock);
thread_info_t *tinfo;
for (tinfo = sAllThreads.getFirst();
tinfo;
tinfo = tinfo->getNext()) {
if (pthread_equal(tinfo->*threadIDptr, threadID)) {
break;
}
}
pthread_mutex_unlock(&sThreadCountLock);
return tinfo;
}
#define CUR_THREAD_INFO GetCurThreadInfo()
#define SET_THREAD_INFO(x) /* Nothing to do. */
#else
// Is not nullptr only for threads created by pthread_create() in an Nuwa process.
// It is always nullptr for the main thread.
static __thread thread_info_t *sCurThreadInfo = nullptr;
#define CUR_THREAD_INFO sCurThreadInfo
#define SET_THREAD_INFO(x) do { sCurThreadInfo = (x); } while(0)
#endif // HAVE_THREAD_TLS_KEYWORD
/*
* Track all epoll fds and handling events.
*/
class EpollManager {
public:
class EpollInfo {
public:
typedef struct epoll_event Events;
typedef std::map<int, Events> EpollEventsMap;
typedef EpollEventsMap::iterator iterator;
typedef EpollEventsMap::const_iterator const_iterator;
EpollInfo(): mBackSize(0) {}
EpollInfo(int aBackSize): mBackSize(aBackSize) {}
EpollInfo(const EpollInfo &aOther): mEvents(aOther.mEvents)
, mBackSize(aOther.mBackSize) {
}
~EpollInfo() {
mEvents.clear();
}
void AddEvents(int aFd, Events &aEvents) {
std::pair<iterator, bool> pair =
mEvents.insert(std::make_pair(aFd, aEvents));
if (!pair.second) {
abort();
}
}
void RemoveEvents(int aFd) {
if (!mEvents.erase(aFd)) {
abort();
}
}
void ModifyEvents(int aFd, Events &aEvents) {
iterator it = mEvents.find(aFd);
if (it == mEvents.end()) {
abort();
}
it->second = aEvents;
}
const Events &FindEvents(int aFd) const {
const_iterator it = mEvents.find(aFd);
if (it == mEvents.end()) {
abort();
}
return it->second;
}
int Size() const { return mEvents.size(); }
// Iterator with values of <fd, Events> pairs.
const_iterator begin() const { return mEvents.begin(); }
const_iterator end() const { return mEvents.end(); }
int BackSize() const { return mBackSize; }
private:
EpollEventsMap mEvents;
int mBackSize;
friend class EpollManager;
};
typedef std::map<int, EpollInfo> EpollInfoMap;
typedef EpollInfoMap::iterator iterator;
typedef EpollInfoMap::const_iterator const_iterator;
public:
void AddEpollInfo(int aEpollFd, int aBackSize) {
EpollInfo *oldinfo = FindEpollInfo(aEpollFd);
if (oldinfo != nullptr) {
abort();
}
mEpollFdsInfo[aEpollFd] = EpollInfo(aBackSize);
}
EpollInfo *FindEpollInfo(int aEpollFd) {
iterator it = mEpollFdsInfo.find(aEpollFd);
if (it == mEpollFdsInfo.end()) {
return nullptr;
}
return &it->second;
}
void RemoveEpollInfo(int aEpollFd) {
if (!mEpollFdsInfo.erase(aEpollFd)) {
abort();
}
}
int Size() const { return mEpollFdsInfo.size(); }
// Iterator of <epollfd, EpollInfo> pairs.
const_iterator begin() const { return mEpollFdsInfo.begin(); }
const_iterator end() const { return mEpollFdsInfo.end(); }
static EpollManager *Singleton() {
if (!sInstance) {
sInstance = new EpollManager();
}
return sInstance;
}
static void Shutdown() {
if (!sInstance) {
abort();
}
delete sInstance;
sInstance = nullptr;
}
private:
static EpollManager *sInstance;
~EpollManager() {
mEpollFdsInfo.clear();
}
EpollInfoMap mEpollFdsInfo;
EpollManager() {}
};
EpollManager* EpollManager::sInstance;
static thread_info_t *
thread_info_new(void) {
/* link tinfo to sAllThreads */
thread_info_t *tinfo = new thread_info_t();
tinfo->flags = 0;
tinfo->recrFunctions = nullptr;
tinfo->recreatedThreadID = 0;
tinfo->recreatedNativeThreadID = 0;
tinfo->condMutex = nullptr;
tinfo->condMutexNeedsBalancing = false;
// Default stack and guard size.
tinfo->stackSize = NUWA_STACK_SIZE;
tinfo->guardSize = getPageSize();
REAL(pthread_mutex_lock)(&sThreadCountLock);
// Insert to the tail.
sAllThreads.insertBack(tinfo);
sThreadCount++;
pthread_cond_signal(&sThreadChangeCond);
pthread_mutex_unlock(&sThreadCountLock);
return tinfo;
}
static void
thread_attr_init(thread_info_t *tinfo, const pthread_attr_t *tattr)
{
pthread_attr_init(&tinfo->threadAttr);
if (tattr) {
// Override default thread stack and guard size with tattr.
pthread_attr_getstacksize(tattr, &tinfo->stackSize);
pthread_attr_getguardsize(tattr, &tinfo->guardSize);
size_t pageSize = getPageSize();
tinfo->stackSize = (tinfo->stackSize + pageSize - 1) % pageSize;
tinfo->guardSize = (tinfo->guardSize + pageSize - 1) % pageSize;
int detachState = 0;
pthread_attr_getdetachstate(tattr, &detachState);
pthread_attr_setdetachstate(&tinfo->threadAttr, detachState);
}
tinfo->stk = MozTaggedAnonymousMmap(nullptr,
tinfo->stackSize + tinfo->guardSize,
PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS,
/* fd */ -1,
/* offset */ 0,
"nuwa-thread-stack");
// Add protection to stack overflow: mprotect() stack top (the page at the
// lowest address) so we crash instead of corrupt other content that is
// malloc()'d.
mprotect(tinfo->stk, tinfo->guardSize, PROT_NONE);
pthread_attr_setstack(&tinfo->threadAttr,
(char*)tinfo->stk + tinfo->guardSize,
tinfo->stackSize);
}
static void
thread_info_cleanup(void *arg) {
if (sNuwaForking) {
// We shouldn't have any thread exiting when we are forking a new process.
abort();
}
thread_info_t *tinfo = (thread_info_t *)arg;
pthread_attr_destroy(&tinfo->threadAttr);
munmap(tinfo->stk, tinfo->stackSize + tinfo->guardSize);
REAL(pthread_mutex_lock)(&sThreadCountLock);
/* unlink tinfo from sAllThreads */
tinfo->remove();
pthread_mutex_unlock(&sThreadCountLock);
if (tinfo->recrFunctions) {
delete tinfo->recrFunctions;
}
// while sThreadCountLock is held, since delete calls wrapped functions
// which try to lock sThreadCountLock. This results in deadlock. And we
// need to delete |tinfo| before decreasing sThreadCount, so Nuwa won't
// get ready before tinfo is cleaned.
delete tinfo;
REAL(pthread_mutex_lock)(&sThreadCountLock);
sThreadCount--;
pthread_cond_signal(&sThreadChangeCond);
pthread_mutex_unlock(&sThreadCountLock);
}
static void
EnsureThreadExited(thread_info_t *tinfo) {
pid_t thread = sIsNuwaProcess ? tinfo->origNativeThreadID
: tinfo->recreatedNativeThreadID;
// Wait until the target thread exits. Note that we use tgkill() instead of
// pthread_kill() because of:
// 1. Use after free inside pthread implementation.
// 2. Race due to pthread_t reuse when a thread is created.
while (!syscall(__NR_tgkill, getpid(), thread, 0)) {
sched_yield();
}
}
static void*
safe_thread_info_cleanup(void *arg)
{
thread_info_t *tinfo = (thread_info_t *)arg;
// We need to ensure the thread is really dead before cleaning up tinfo.
EnsureThreadExited(tinfo);
thread_info_cleanup(tinfo);
return nullptr;
}
static void
MaybeCleanUpDetachedThread(thread_info_t *tinfo)
{
if (pthread_getattr_np(REAL(pthread_self()), &tinfo->threadAttr)) {
return;
}
int detachState = 0;
if (pthread_attr_getdetachstate(&tinfo->threadAttr, &detachState) ||
detachState == PTHREAD_CREATE_JOINABLE) {
// We only clean up tinfo of a detached thread. A joinable thread
// will be cleaned up in __wrap_pthread_join().
return;
}
// Create a detached thread to safely clean up the current thread.
pthread_t thread;
if (!REAL(pthread_create)(&thread,
nullptr,
safe_thread_info_cleanup,
tinfo)) {
pthread_detach(thread);
}
}
static void
invalidate_thread_info(void *arg) {
REAL(pthread_mutex_lock)(&sThreadCountLock);
// Unlink tinfo from sAllThreads to make it invisible from CUR_THREAD_INFO so
// it won't be misused by a newly created thread.
thread_info_t *tinfo = (thread_info_t*) arg;
tinfo->remove();
sExitingThreads.insertBack(tinfo);
pthread_mutex_unlock(&sThreadCountLock);
MaybeCleanUpDetachedThread(tinfo);
}
static void *
_thread_create_startup(void *arg) {
thread_info_t *tinfo = (thread_info_t *)arg;
void *r;
// Save thread info; especially, stackaddr & stacksize.
// Reuse the stack in the new thread.
pthread_getattr_np(REAL(pthread_self)(), &tinfo->threadAttr);
SET_THREAD_INFO(tinfo);
tinfo->origThreadID = REAL(pthread_self)();
tinfo->origNativeThreadID = gettid();
r = tinfo->startupFunc(tinfo->startupArg);
return r;
}
// reserve STACK_RESERVED_SZ * 4 bytes for thread_recreate_startup().
#define STACK_RESERVED_SZ 96
#define STACK_SENTINEL(v) ((v)[0])
#define STACK_SENTINEL_VALUE(v) ((uint32_t)(v) ^ 0xdeadbeef)
static void *
thread_create_startup(void *arg) {
/*
* Dark Art!! Never try to do the same unless you are ABSOLUTELY sure of
* what you are doing!
*
* This function is here for reserving stack space before calling
* _thread_create_startup(). see also thread_create_startup();
*/
void *r;
volatile uint32_t reserved[STACK_RESERVED_SZ];
// Reserve stack space.
STACK_SENTINEL(reserved) = STACK_SENTINEL_VALUE(reserved);
r = _thread_create_startup(arg);
// Check if the reservation is enough.
if (STACK_SENTINEL(reserved) != STACK_SENTINEL_VALUE(reserved)) {
abort(); // Did not reserve enough stack space.
}
// Get tinfo before invalidating it. Note that we cannot use arg directly here
// because thread_recreate_startup() also runs on the same stack area and
// could corrupt the value.
thread_info_t *tinfo = CUR_THREAD_INFO;
invalidate_thread_info(tinfo);
if (!sIsNuwaProcess) {
longjmp(tinfo->retEnv, 1);
// Never go here!
abort();
}
return r;
}
extern "C" MFBT_API int
__wrap_pthread_create(pthread_t *thread,
const pthread_attr_t *attr,
void *(*start_routine) (void *),
void *arg) {
if (!sIsNuwaProcess) {
return REAL(pthread_create)(thread, attr, start_routine, arg);
}
thread_info_t *tinfo = thread_info_new();
thread_attr_init(tinfo, attr);
tinfo->startupFunc = start_routine;
tinfo->startupArg = arg;
int rv = REAL(pthread_create)(thread,
&tinfo->threadAttr,
thread_create_startup,
tinfo);
if (rv) {
thread_info_cleanup(tinfo);
} else {
tinfo->origThreadID = *thread;
}
return rv;
}
// TLS related
/**
* Iterates over the existing TLS keys and store the TLS data for the current
* thread in tinfo.
*/
static void
SaveTLSInfo(thread_info_t *tinfo) {
MOZ_RELEASE_ASSERT(REAL(pthread_mutex_lock)(&sTLSKeyLock) == 0);
tinfo->tlsInfo.clear();
for (TLSKey *it = sTLSKeys.getFirst(); it != nullptr; it = it->getNext()) {
void *value = pthread_getspecific(it->first);
if (value == nullptr) {
continue;
}
pthread_key_t key = it->first;
tinfo->tlsInfo.push_back(TLSInfoList::value_type(key, value));
}
MOZ_RELEASE_ASSERT(pthread_mutex_unlock(&sTLSKeyLock) == 0);
}
/**
* Restores the TLS data for the current thread from tinfo.
*/
static void
RestoreTLSInfo(thread_info_t *tinfo) {
for (TLSInfoList::const_iterator it = tinfo->tlsInfo.begin();
it != tinfo->tlsInfo.end();
it++) {
pthread_key_t key = it->first;
const void *value = it->second;
if (pthread_setspecific(key, value)) {
abort();
}
}
SET_THREAD_INFO(tinfo);
tinfo->recreatedThreadID = REAL(pthread_self)();
tinfo->recreatedNativeThreadID = gettid();
}
extern "C" MFBT_API int
__wrap_pthread_key_create(pthread_key_t *key, void (*destructor)(void*)) {
int rv = REAL(pthread_key_create)(key, destructor);
if (rv != 0) {
return rv;
}
MOZ_RELEASE_ASSERT(REAL(pthread_mutex_lock)(&sTLSKeyLock) == 0);
sTLSKeys.insertBack(new TLSKey(*key, destructor));
MOZ_RELEASE_ASSERT(pthread_mutex_unlock(&sTLSKeyLock) == 0);
return 0;
}
extern "C" MFBT_API int
__wrap_pthread_key_delete(pthread_key_t key) {
// Don't call pthread_key_delete() for Nuwa-forked processes because bionic's
// pthread_key_delete() implementation can touch the thread stack that was
// freed in thread_info_cleanup().
int rv = sIsNuwaChildProcess ?
0 : REAL(pthread_key_delete)(key);
if (rv != 0) {
return rv;
}
MOZ_RELEASE_ASSERT(REAL(pthread_mutex_lock)(&sTLSKeyLock) == 0);
for (TLSKey *it = sTLSKeys.getFirst(); it != nullptr; it = it->getNext()) {
if (key == it->first) {
delete it;
break;
}
}
MOZ_RELEASE_ASSERT(pthread_mutex_unlock(&sTLSKeyLock) == 0);
return 0;
}
extern "C" MFBT_API pthread_t
__wrap_pthread_self() {
thread_info_t *tinfo = CUR_THREAD_INFO;
if (tinfo) {
// For recreated thread, masquerade as the original thread in the Nuwa
// process.
return tinfo->origThreadID;
}
return REAL(pthread_self)();
}
extern "C" MFBT_API int
__wrap_pthread_join(pthread_t thread, void **retval) {
thread_info_t *tinfo = GetThreadInfo(thread);
if (tinfo == nullptr) {
return REAL(pthread_join)(thread, retval);
}
pthread_t thread_info_t::*threadIDptr =
(sIsNuwaProcess ?
&thread_info_t::origThreadID :
&thread_info_t::recreatedThreadID);
// pthread_join() uses the origThreadID or recreatedThreadID depending on
// whether we are in Nuwa or forked processes.
int rc = REAL(pthread_join)(tinfo->*threadIDptr, retval);
// Before Android L, bionic wakes up the caller of pthread_join() with
// pthread_cond_signal() so the thread can still use the stack for some while.
// Call safe_thread_info_cleanup() to destroy tinfo after the thread really
// exits.
safe_thread_info_cleanup(tinfo);
return rc;
}
/**
* The following are used to synchronize between the main thread and the
* thread being recreated. The main thread will wait until the thread is woken
* up from the freeze points or the blocking intercepted functions and then
* proceed to recreate the next frozen thread.
*
* In thread recreation, the main thread recreates the frozen threads one by
* one. The recreated threads will be "gated" until the main thread "opens the
* gate" to let them run freely as if they were created from scratch. The VIP
* threads gets the chance to run first after their thread stacks are recreated
* (using longjmp()) so they can adjust their contexts to a valid, consistent
* state. The threads frozen waiting for pthread condition variables are VIP
* threads. After woken up they need to run first to make the associated mutex
* in a valid state to maintain the semantics of the intercepted function calls
* (like pthread_cond_wait()).
*/
// Used to synchronize the main thread and the thread being recreated so that
// only one thread is allowed to be recreated at a time.
static pthread_mutex_t sRecreateWaitLock = PTHREAD_MUTEX_INITIALIZER;
// Used to block recreated threads until the main thread "opens the gate".
static pthread_mutex_t sRecreateGateLock = PTHREAD_MUTEX_INITIALIZER;
// Used to block the main thread from "opening the gate" until all VIP threads
// have been recreated.
static pthread_mutex_t sRecreateVIPGateLock = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t sRecreateVIPCond = PTHREAD_COND_INITIALIZER;
static int sRecreateVIPCount = 0;
static int sRecreateGatePassed = 0;
/**
* Thread recreation macros.
*
* The following macros are used in the forked process to synchronize and
* control the progress of thread recreation.
*
* 1. RECREATE_START() is first called in the beginning of thread
* recreation to set sRecreateWaitLock and sRecreateGateLock in locked
* state.
* 2. For each frozen thread:
* 2.1. RECREATE_BEFORE() to set the thread being recreated.
* 2.2. thread_recreate() to recreate the frozen thread.
* 2.3. Main thread calls RECREATE_WAIT() to wait on sRecreateWaitLock until
* the thread is recreated from the freeze point and calls
* RECREATE_CONTINUE() to release sRecreateWaitLock.
* 2.3. Non-VIP threads are blocked on RECREATE_GATE(). VIP threads calls
* RECREATE_PASS_VIP() to mark that a VIP thread is successfully
* recreated and then is blocked by calling RECREATE_GATE_VIP().
* 3. RECREATE_WAIT_ALL_VIP() to wait until all VIP threads passed, that is,