/
Nuwa.cpp
1935 lines (1685 loc) · 56.5 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/LinkedList.h"
#include "mozilla/TaggedAnonymousMemory.h"
#include "Nuwa.h"
using namespace mozilla;
extern "C" MFBT_API int tgkill(pid_t tgid, pid_t tid, int signalno) {
return syscall(__NR_tgkill, tgid, tid, signalno);
}
/**
* 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_cond_timedwait(pthread_cond_t *cond,
pthread_mutex_t *mtx,
const struct timespec *abstime,
clockid_t clock);
int __real_pthread_mutex_lock(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 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
}
/**
* The stack size is chosen carefully so the frozen threads doesn't consume too
* much memory in the Nuwa process. The threads shouldn't run deep recursive
* methods or do large allocations on the stack to avoid stack overflow.
*/
#ifndef NUWA_STACK_SIZE
#define NUWA_STACK_SIZE (1024 * 128)
#endif
#define NATIVE_THREAD_NAME_LENGTH 16
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.
void (*recrFunc)(void *arg);
void *recrArg;
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;
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->recrFunc != nullptr) {
tinfo->recrFunc(tinfo->recrArg);
}
}
/**
* 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
typedef struct nuwa_construct {
void (*construct)(void *);
void *arg;
} nuwa_construct_t;
static std::vector<nuwa_construct_t> sConstructors;
static std::vector<nuwa_construct_t> sFinalConstructors;
typedef std::map<pthread_key_t, void (*)(void *)> TLSKeySet;
static TLSKeySet 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 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 LinkedList<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);
}
clear();
}
};
static AllThreadsListType sAllThreads;
/**
* 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_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;
}
}
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) {
if (sIsNuwaProcess) {
REAL(pthread_mutex_lock)(&sThreadCountLock);
}
thread_info_t *tinfo = GetThreadInfoInner(threadID);
if (sIsNuwaProcess) {
pthread_mutex_unlock(&sThreadCountLock);
}
return tinfo;
}
/**
* Get thread info using the specified native thread ID.
*
* @return thread_info_t with nativeThreadID == specified threadID
*/
static thread_info_t*
GetThreadInfo(pid_t threadID) {
if (sIsNuwaProcess) {
REAL(pthread_mutex_lock)(&sThreadCountLock);
}
thread_info_t *thrinfo = nullptr;
for (thread_info_t *tinfo = sAllThreads.getFirst();
tinfo;
tinfo = tinfo->getNext()) {
if (tinfo->origNativeThreadID == threadID) {
thrinfo = tinfo;
break;
}
}
if (sIsNuwaProcess) {
pthread_mutex_unlock(&sThreadCountLock);
}
return thrinfo;
}
#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->recrFunc = nullptr;
tinfo->recrArg = nullptr;
tinfo->recreatedThreadID = 0;
tinfo->recreatedNativeThreadID = 0;
tinfo->condMutex = nullptr;
tinfo->condMutexNeedsBalancing = false;
tinfo->stk = MozTaggedAnonymousMmap(nullptr,
NUWA_STACK_SIZE + getPageSize(),
PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS,
/* fd */ -1,
/* offset */ 0,
"nuwa-thread-stack");
// We use a smaller stack size. 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, getPageSize(), PROT_NONE);
pthread_attr_init(&tinfo->threadAttr);
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_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, NUWA_STACK_SIZE + getPageSize());
REAL(pthread_mutex_lock)(&sThreadCountLock);
/* unlink tinfo from sAllThreads */
tinfo->remove();
pthread_mutex_unlock(&sThreadCountLock);
// 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*
cleaner_thread(void *arg) {
thread_info_t *tinfo = (thread_info_t *)arg;
pthread_t *thread = sIsNuwaProcess ? &tinfo->origThreadID
: &tinfo->recreatedThreadID;
// Wait until target thread end.
while (!pthread_kill(*thread, 0)) {
sched_yield();
}
thread_info_cleanup(tinfo);
return nullptr;
}
static void
thread_cleanup(void *arg) {
pthread_t thread;
REAL(pthread_create)(&thread, nullptr, &cleaner_thread, arg);
pthread_detach(thread);
}
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();
pthread_cleanup_push(thread_cleanup, tinfo);
r = tinfo->startupFunc(tinfo->startupArg);
if (!sIsNuwaProcess) {
return r;
}
pthread_cleanup_pop(1);
return r;
}
// reserve STACK_RESERVED_SZ * 4 bytes for thread_recreate_startup().
#define STACK_RESERVED_SZ 64
#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.
}
thread_info_t *tinfo = CUR_THREAD_INFO;
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();
tinfo->startupFunc = start_routine;
tinfo->startupArg = arg;
pthread_attr_setstack(&tinfo->threadAttr,
(char*)tinfo->stk + getPageSize(),
NUWA_STACK_SIZE);
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) {
REAL(pthread_mutex_lock)(&sTLSKeyLock);
tinfo->tlsInfo.clear();
for (TLSKeySet::const_iterator it = sTLSKeys.begin();
it != sTLSKeys.end();
it++) {
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));
}
pthread_mutex_unlock(&sTLSKeyLock);
}
/**
* 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;
}
REAL(pthread_mutex_lock)(&sTLSKeyLock);
sTLSKeys.insert(TLSKeySet::value_type(*key, destructor));
pthread_mutex_unlock(&sTLSKeyLock);
return 0;
}
extern "C" MFBT_API int
__wrap_pthread_key_delete(pthread_key_t key) {
if (!sIsNuwaProcess) {
return REAL(pthread_key_delete)(key);
}
int rv = REAL(pthread_key_delete)(key);
if (rv != 0) {
return rv;
}
REAL(pthread_mutex_lock)(&sTLSKeyLock);
sTLSKeys.erase(key);
pthread_mutex_unlock(&sTLSKeyLock);
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_join() need to use the real thread ID in the spawned process.
return REAL(pthread_join)(tinfo->recreatedThreadID, retval);
}
/**
* 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,
* VIP threads already has their contexts (mainly pthread mutex) in a valid
* state.
* 4. RECREATE_OPEN_GATE() to unblock threads blocked by sRecreateGateLock.
* 5. RECREATE_FINISH() to complete thread recreation.
*/
#define RECREATE_START() \
do { \
REAL(pthread_mutex_lock)(&sRecreateWaitLock); \
REAL(pthread_mutex_lock)(&sRecreateGateLock); \
} while(0)
#define RECREATE_BEFORE(info) do { sCurrentRecreatingThread = info; } while(0)
#define RECREATE_WAIT() REAL(pthread_mutex_lock)(&sRecreateWaitLock)
#define RECREATE_CONTINUE() do { \
RunCustomRecreation(); \
pthread_mutex_unlock(&sRecreateWaitLock); \
} while(0)
#define RECREATE_FINISH() pthread_mutex_unlock(&sRecreateWaitLock)
#define RECREATE_GATE() \
do { \
REAL(pthread_mutex_lock)(&sRecreateGateLock); \
sRecreateGatePassed++; \
pthread_mutex_unlock(&sRecreateGateLock); \
} while(0)
#define RECREATE_OPEN_GATE() pthread_mutex_unlock(&sRecreateGateLock)
#define RECREATE_GATE_VIP() \
do { \
REAL(pthread_mutex_lock)(&sRecreateGateLock); \
pthread_mutex_unlock(&sRecreateGateLock); \
} while(0)
#define RECREATE_PASS_VIP() \
do { \
REAL(pthread_mutex_lock)(&sRecreateVIPGateLock); \
sRecreateGatePassed++; \
pthread_cond_signal(&sRecreateVIPCond); \
pthread_mutex_unlock(&sRecreateVIPGateLock); \
} while(0)
#define RECREATE_WAIT_ALL_VIP() \
do { \
REAL(pthread_mutex_lock)(&sRecreateVIPGateLock); \
while(sRecreateGatePassed < sRecreateVIPCount) { \
REAL(pthread_cond_wait)(&sRecreateVIPCond, \
&sRecreateVIPGateLock); \
} \
pthread_mutex_unlock(&sRecreateVIPGateLock); \
} while(0)
/**
* Thread freeze points. Note that the freeze points are implemented as macros
* so as not to garble the content of the stack after setjmp().
*
* In the nuwa process, when a thread supporting nuwa calls a wrapper
* function, freeze point 1 setjmp()s to save the state. We only allow the
* thread to be frozen in the wrapper functions. If thread freezing is not
* enabled yet, the wrapper functions act like their wrapped counterparts,
* except for the extra actions in the freeze points. If thread freezing is
* enabled, the thread will be frozen by calling one of the wrapper functions.
* The threads can be frozen in any of the following points:
*
* 1) Freeze point 1: this is the point where we setjmp() in the nuwa process
* and longjmp() in the spawned process. If freezing is enabled, then the
* current thread blocks by acquiring an already locked mutex,
* sThreadFreezeLock.
* 2) The wrapped function: the function that might block waiting for some
* resource or condition.
* 3) Freeze point 2: blocks the current thread by acquiring sThreadFreezeLock.
* If freezing is not enabled then revert the counter change in freeze
* point 1.
*/
#define THREAD_FREEZE_POINT1() \
bool freezeCountChg = false; \
bool recreated = false; \
volatile bool freezePoint2 = false; \
thread_info_t *tinfo; \
if (sIsNuwaProcess && \
(tinfo = CUR_THREAD_INFO) && \
(tinfo->flags & TINFO_FLAG_NUWA_SUPPORT) && \
!(tinfo->flags & TINFO_FLAG_NUWA_EXPLICIT_CHECKPOINT)) { \
if (!setjmp(tinfo->jmpEnv)) { \
REAL(pthread_mutex_lock)(&sThreadCountLock); \
SaveTLSInfo(tinfo); \
sThreadFreezeCount++; \
freezeCountChg = true; \
pthread_cond_signal(&sThreadChangeCond); \
pthread_mutex_unlock(&sThreadCountLock); \
\
if (sIsFreezing) { \
REAL(pthread_mutex_lock)(&sThreadFreezeLock); \
/* Never return from the pthread_mutex_lock() call. */ \
abort(); \
} \
} else { \
RECREATE_CONTINUE(); \
RECREATE_GATE(); \
freezeCountChg = false; \
recreated = true; \
} \
}
#define THREAD_FREEZE_POINT1_VIP() \
bool freezeCountChg = false; \
bool recreated = false; \
volatile bool freezePoint1 = false; \
volatile bool freezePoint2 = false; \
thread_info_t *tinfo; \
if (sIsNuwaProcess && \
(tinfo = CUR_THREAD_INFO) && \
(tinfo->flags & TINFO_FLAG_NUWA_SUPPORT) && \
!(tinfo->flags & TINFO_FLAG_NUWA_EXPLICIT_CHECKPOINT)) { \
if (!setjmp(tinfo->jmpEnv)) { \
REAL(pthread_mutex_lock)(&sThreadCountLock); \
SaveTLSInfo(tinfo); \
sThreadFreezeCount++; \
sRecreateVIPCount++; \
freezeCountChg = true; \
pthread_cond_signal(&sThreadChangeCond); \
pthread_mutex_unlock(&sThreadCountLock); \
\
if (sIsFreezing) { \
freezePoint1 = true; \
REAL(pthread_mutex_lock)(&sThreadFreezeLock); \
/* Never return from the pthread_mutex_lock() call. */ \
abort(); \
} \
} else { \
freezeCountChg = false; \
recreated = true; \
} \
}
#define THREAD_FREEZE_POINT2() \
if (freezeCountChg) { \
REAL(pthread_mutex_lock)(&sThreadCountLock); \
if (sNuwaReady && sIsNuwaProcess) { \
pthread_mutex_unlock(&sThreadCountLock); \
freezePoint2 = true; \
REAL(pthread_mutex_lock)(&sThreadFreezeLock); \
/* Never return from the pthread_mutex_lock() call. */ \
abort(); \
} \
sThreadFreezeCount--; \
pthread_cond_signal(&sThreadChangeCond); \
pthread_mutex_unlock(&sThreadCountLock); \
}
#define THREAD_FREEZE_POINT2_VIP() \
if (freezeCountChg) { \
REAL(pthread_mutex_lock)(&sThreadCountLock); \
if (sNuwaReady && sIsNuwaProcess) { \
pthread_mutex_unlock(&sThreadCountLock); \
freezePoint2 = true; \
REAL(pthread_mutex_lock)(&sThreadFreezeLock); \
/* Never return from the pthread_mutex_lock() call. */ \
abort(); \
} \
sThreadFreezeCount--; \
sRecreateVIPCount--; \
pthread_cond_signal(&sThreadChangeCond); \
pthread_mutex_unlock(&sThreadCountLock); \
}
/**
* Wrapping the blocking functions: epoll_wait(), poll(), pthread_mutex_lock(),
* pthread_cond_wait() and pthread_cond_timedwait():
*
* These functions are wrapped by the above freeze point macros. Once a new
* process is forked, the recreated thread will be blocked in one of the wrapper
* functions. When recreating the thread, we longjmp() to
* THREAD_FREEZE_POINT1() to recover the thread stack. Care must be taken to
* maintain the semantics of the wrapped function:
*
* - epoll_wait() and poll(): just retry the function.
* - pthread_mutex_lock(): don't lock if frozen at freeze point 2 (lock is
* already acquired).