-
Notifications
You must be signed in to change notification settings - Fork 70
/
kthread.cpp
1512 lines (1361 loc) · 53.5 KB
/
kthread.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
/*
* Copyright (C) 2016 The BoxedWine Team
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "boxedwine.h"
#include "kscheduler.h"
#include "ksignal.h"
#include "kscheduler.h"
#include "ksignal.h"
#include <string.h>
#include "../io/fsfilenode.h"
#include "bufferaccess.h"
#include "kstat.h"
thread_local KThread* KThread::runningThread;
BOXEDWINE_MUTEX KThread::futexesMutex;
KThread::~KThread() {
for (auto& callback : callbacksOnExit) {
callback(id);
}
this->cleanup();
CPU* cpu = this->cpu;
this->cpu = nullptr;
delete cpu;
}
void KThread::cleanup() {
{
BOXEDWINE_CRITICAL_SECTION_WITH_CONDITION(this->waitingForSignalToEndCond);
BOXEDWINE_CONDITION_SIGNAL_ALL(this->waitingForSignalToEndCond);
}
if (!KSystem::shutingDown && this->clear_child_tid && this->process && memory->canWrite(this->clear_child_tid, 4)) {
memory->writed(this->clear_child_tid, 0);
this->futex(this->clear_child_tid, 1, 0xffffffff, 0, 0, 0, false);
}
this->clear_child_tid = 0;
#ifndef BOXEDWINE_MULTI_THREADED
if (this->waitingCond) {
BOXEDWINE_CRITICAL_SECTION_WITH_CONDITION(*this->waitingCond);
this->waitThreadNode.remove();
this->waitingCond = nullptr;
}
#endif
this->clearFutexes();
this->exitRobustList();
this->robustList = 0;
if (this->process) {
this->process->removeThread(this);
}
unscheduleThread(this);
}
void KThread::reset() {
this->clearFutexes();
this->cpu->reset();
this->alternateStack = 0;
this->alternateStackSize = 0;
this->setupStack();
}
void KThread::setupStack() {
U32 stack = memory->mmap(this, 0, MAX_STACK_SIZE, K_PROT_NONE, K_MAP_ANONYMOUS|K_MAP_PRIVATE, -1, 0);
// will all by on demand
memory->mprotect(this, stack + K_PAGE_SIZE, MAX_STACK_SIZE - 2 * K_PAGE_SIZE, K_PROT_READ | K_PROT_WRITE);
U32 stackPageCount = MAX_STACK_SIZE >> K_PAGE_SHIFT;
U32 stackPageStart = stack >> K_PAGE_SHIFT;
this->cpu->reg[4].u32 = (stackPageStart + stackPageCount - 1) << K_PAGE_SHIFT;
// touch the first 16 pages now so that they are ready
for (int i = 1; i < 17; i++) {
memory->readd(this->cpu->reg[4].u32 - K_PAGE_SIZE * i);
}
}
KThread::KThread(U32 id, const KProcessPtr& process) :
id(id),
process(process),
memory(process->memory),
waitingForSignalToEndCond(std::make_shared<BoxedWineCondition>(B("KThread::waitingForSignalToEndCond"))),
sigWaitCond(std::make_shared<BoxedWineCondition>(B("KThread::sigWaitCond"))),
pollCond(std::make_shared<BoxedWineCondition>(B("KThread::pollCond"))),
#ifndef BOXEDWINE_MULTI_THREADED
scheduledThreadNode(this),
waitThreadNode(this),
#endif
sleepCond(std::make_shared<BoxedWineCondition>(B("KThread::sleepCond")))
{
this->sigMask = 0;
for (int i=0;i<TLS_ENTRIES;i++) {
this->tls[i].seg_not_present = 1;
this->tls[i].read_exec_only = 1;
}
this->cpu = CPU::allocCPU(memory);
this->cpu->thread = this;
if (process->name=="services.exe") {
this->log=true;
}
this->name = BString::valueOf(id);
if (process->taskNode) {
this->threadNode = Fs::addFileNode(process->taskNode->path + B("/") + BString::valueOf(id), B(""), B(""), true, process->taskNode);
this->commNode = Fs::addVirtualFile(threadNode->path + B("/comm"), [this](const std::shared_ptr<FsNode>& node, U32 flags, U32 data) {
return new BufferAccess(node, flags, &this->name);
}, K__S_IREAD | K__S_IWRITE, k_mdev(0, 0), threadNode);
}
//BString tmp = BString::valueOf(id);
//tmp += ".txt";
//if (id==0x1c)
//this->cpu->logFile = fopen(tmp.c_str(), "w");
}
bool KThread::isLdtEmpty(struct user_desc* desc) {
return (!desc || (desc->seg_not_present==1 && desc->read_exec_only==1));
}
struct user_desc* KThread::getLDT(U32 index) {
if (index>=TLS_ENTRY_START_INDEX && index<TLS_ENTRIES+TLS_ENTRY_START_INDEX) {
BOXEDWINE_CRITICAL_SECTION_WITH_MUTEX(tlsMutex);
return &this->tls[index-TLS_ENTRY_START_INDEX];
} else if (index<LDT_ENTRIES) {
return this->process->getLDT(index);
}
return nullptr;
}
void KThread::setTLS(struct user_desc* desc) {
BOXEDWINE_CRITICAL_SECTION_WITH_MUTEX(tlsMutex);
this->tls[desc->entry_number-TLS_ENTRY_START_INDEX] = *desc;
}
bool KThread::readyForSignal(U32 signal) {
return (((U64)1 << (signal - 1)) & ~(this->inSignal ? this->inSigMask : this->sigMask)) != 0;
}
U32 KThread::signal(U32 signal, bool wait) {
if (signal==0) {
return 0;
}
BOXEDWINE_CRITICAL_SECTION_WITH_CONDITION(this->sigWaitCond);
if (this->sigWaitMask & signal) {
this->foundWaitSignal = signal;
BOXEDWINE_CONDITION_SIGNAL(this->sigWaitCond);
return 0;
}
memset(process->sigActions[signal].sigInfo, 0, sizeof(process->sigActions[signal].sigInfo));
process->sigActions[signal].sigInfo[0] = signal;
process->sigActions[signal].sigInfo[2] = K_SI_USER;
process->sigActions[signal].sigInfo[3] = process->id;
process->sigActions[signal].sigInfo[4] = process->userId;
if (signal == K_SIGKILL || signal == K_SIGSTOP || readyForSignal(signal)) {
// don't return -K_WAIT, we don't want to re-enter tgkill, instead we will return 0 once the thread wakes up
// must set CPU state before runSignal since it will be stored
if (this==KThread::currentThread()) {
this->cpu->reg[0].u32 = 0;
this->cpu->eip.u32+=2;
}
#ifdef BOXEDWINE_MULTI_THREADED
else {
// :TODO: how to interrupt the thread (the current approache assumes the thread will yield to the signal)
{
bool handled = false;
BOXEDWINE_CONDITION cond = waitingCond;
if (signal == K_SIGQUIT && cond) {
BOXEDWINE_CRITICAL_SECTION_WITH_CONDITION(cond);
if (waitingCond) {
this->startSignal = true;
this->runSignal(K_SIGQUIT, -1, 0);
BOXEDWINE_CONDITION_SIGNAL(cond);
handled = true;
}
}
if (!handled) {
BOXEDWINE_CRITICAL_SECTION_WITH_MUTEX(this->pendingSignalsMutex);
this->pendingSignals |= ((U64)1 << (signal - 1));
}
}
if (wait && !this->terminating) {
BOXEDWINE_CONDITION c = this->waitingCond;
if (c) {
BOXEDWINE_CRITICAL_SECTION_WITH_CONDITION(c);
BOXEDWINE_CONDITION_SIGNAL_ALL(c);
}
BOXEDWINE_CRITICAL_SECTION_WITH_CONDITION(this->waitingForSignalToEndCond);
BOXEDWINE_CONDITION_WAIT_TIMEOUT(this->waitingForSignalToEndCond, 1000);
}
return 0;
}
#endif
this->runSignal(signal, -1, 0);
if (wait && KThread::currentThread()!=this) {
BOXEDWINE_CRITICAL_SECTION_WITH_CONDITION(this->waitingForSignalToEndCond);
BOXEDWINE_CONDITION_WAIT_TIMEOUT(this->waitingForSignalToEndCond, 1000);
}
} else {
BOXEDWINE_CRITICAL_SECTION_WITH_MUTEX(this->pendingSignalsMutex);
this->pendingSignals |= ((U64)1 << (signal-1));
this->process->signalFd(this, signal);
}
return 0;
}
#define FUTEX_WAIT 0
#define FUTEX_WAKE 1
#define FUTEX_FD 2
#define FUTEX_REQUEUE 3
#define FUTEX_CMP_REQUEUE 4
#define FUTEX_WAKE_OP 5
#define FUTEX_LOCK_PI 6
#define FUTEX_UNLOCK_PI 7
#define FUTEX_TRYLOCK_PI 8
#define FUTEX_WAIT_BITSET 9
#define FUTEX_WAKE_BITSET 10
#define FUTEX_WAIT_REQUEUE_PI 11
#define FUTEX_CMP_REQUEUE_PI 12
#define FUTEX_PRIVATE_FLAG 128
#define FUTEX_CLOCK_REALTIME 256
#define FUTEX_CMD_MASK ~(FUTEX_PRIVATE_FLAG | FUTEX_CLOCK_REALTIME)
struct futex {
public:
futex() : cond(std::make_shared<BoxedWineCondition>(B("futex"))) {}
KThread* thread = nullptr;
U64 address = 0;
U32 expireTimeInMillies = 0;
U32 mask = 0;
bool wake = false;
BOXEDWINE_CONDITION cond;
};
#define MAX_FUTEXES 128
struct futex system_futex[MAX_FUTEXES];
struct futex* getFutex(KThread* thread, U64 address) {
int i=0;
for (i=0;i<MAX_FUTEXES;i++) {
if (system_futex[i].address == address && system_futex[i].thread==thread) {
return &system_futex[i];
}
}
return nullptr;
}
struct futex* allocFutex(KThread* thread, U64 address, U32 millies) {
BOXEDWINE_CRITICAL_SECTION;
int i=0;
for (i=0;i<MAX_FUTEXES;i++) {
if (system_futex[i].thread== nullptr) {
system_futex[i].thread = thread;
system_futex[i].address = address;
system_futex[i].expireTimeInMillies = millies;
system_futex[i].wake = false;
system_futex[i].mask = 0;
return &system_futex[i];
}
}
kpanic("ran out of futexes");
return nullptr;
}
void freeFutex(struct futex* f) {
f->thread = nullptr;
f->address = 0;
}
void KThread::clearFutexes() {
U32 i;
BOXEDWINE_CRITICAL_SECTION_WITH_MUTEX(KThread::futexesMutex);
for (i=0;i<MAX_FUTEXES;i++) {
if (system_futex[i].thread == this) {
freeFutex(&system_futex[i]);
}
}
}
U32 KThread::futex(U32 addr, U32 op, U32 value, U32 pTime, U32 val2, U32 val3, bool time64) {
U64 ramAddress = 0;
U32 cmd = (op & FUTEX_CMD_MASK);
bool isPrivate = (op & FUTEX_PRIVATE_FLAG) != 0;
if (isPrivate) {
ramAddress = addr;
} else {
ramAddress = (U64)memory->getPtrForFutex(addr);
}
if (ramAddress == 0) {
kpanic("Could not find futex address: %0.8X", addr);
}
/*
* from kernel source, if I ever implement one of these I need to note pTime actually contains val2
if (cmd == FUTEX_REQUEUE || cmd == FUTEX_CMP_REQUEUE ||
cmd == FUTEX_CMP_REQUEUE_PI || cmd == FUTEX_WAKE_OP)
val2 = (u32)(unsigned long)utime;
*/
if (cmd ==FUTEX_WAIT || cmd == FUTEX_WAIT_BITSET) {
//klog("%x/%x futux WAIT addr=%x op=%x val=%x ram=%x", id, process->id, addr, op, value, (U32)ramAddress);
struct futex* f=getFutex(this, ramAddress);
U32 expireTime = 0xFFFFFFFF;
if (pTime != 0) {
if (time64) {
U64 seconds = memory->readq(pTime);
U32 nano = memory->readd(pTime + 8);
if (cmd == FUTEX_WAIT) {
// FUTEX_WAIT timeout is relative
expireTime = (U32)(seconds * 1000 + nano / 1000000);
} else {
expireTime = (U32)((seconds * 1000 + nano / 1000000) - KSystem::getSystemTimeAsMicroSeconds() / 1000);
}
} else {
U32 seconds = memory->readd(pTime);
U32 nano = memory->readd(pTime + 4);
if (cmd == FUTEX_WAIT) {
// FUTEX_WAIT timeout is relative
expireTime = seconds * 1000 + nano / 1000000;
} else {
expireTime = (U32)((seconds * 1000 + nano / 1000000) - KSystem::getSystemTimeAsMicroSeconds() / 1000);
}
}
expireTime += KSystem::getMilliesSinceStart();
}
if (!f) {
BOXEDWINE_CRITICAL_SECTION_WITH_MUTEX(KThread::futexesMutex);
U32 currentValue = memory->readd(addr);
if (currentValue != value) {
//klog(" %x/%x futux addr=%x op=%x val=%x ram=%x NEW VALUE %x", id, process->id, addr, op, value, (U32)ramAddress, currentValue);
return -K_EWOULDBLOCK;
}
f = allocFutex(this, ramAddress, expireTime);
if (cmd == FUTEX_WAIT_BITSET) {
f->mask = val3;
}
} else {
int ii = 0;
}
while (true) {
BOXEDWINE_CRITICAL_SECTION_WITH_CONDITION(f->cond);
if (this->pendingSignals) {
// I know this is a nested if statement, but it makes setting a break point easier
if (runSignals()) {
//klog(" %x/%x futux addr=%x op=%x val=%x ram=%x RAN SIGNAL", id, process->id, addr, op, value, (U32)ramAddress);
return -K_CONTINUE;
}
}
if (f->wake) {
#ifdef BOXEDWINE_MULTI_THREADED
// need to unlock before getting futexesMutex since FUTEX_WAKE will get futexesMutex then try to signal f->cond
boxedWineCriticalSection.unlock();
#endif
BOXEDWINE_CRITICAL_SECTION_WITH_MUTEX(KThread::futexesMutex);
freeFutex(f);
return 0;
}
if (f->expireTimeInMillies<0x7FFFFFFF) {
S32 diff = f->expireTimeInMillies - KSystem::getMilliesSinceStart();
if (diff<=0) {
#ifdef BOXEDWINE_MULTI_THREADED
// need to unlock before getting futexesMutex since FUTEX_WAKE will get futexesMutex then try to signal f->cond
boxedWineCriticalSection.unlock();
#endif
BOXEDWINE_CRITICAL_SECTION_WITH_MUTEX(KThread::futexesMutex);
freeFutex(f);
return -K_ETIMEDOUT;
}
//klog(" %x/%x futux SLEEPING %x addr=%x op=%x val=%x ram=%x", id, process->id, (U32)diff, addr, op, value, (U32)ramAddress);
BOXEDWINE_CONDITION_WAIT_TIMEOUT(f->cond, (U32)diff);
//klog(" %x/%x futux DONE SLEEPING %x addr=%x op=%x val=%x ram=%x", id, process->id, (U32)diff, addr, op, value, (U32)ramAddress);
} else {
BOXEDWINE_CONDITION_WAIT(f->cond);
}
#ifdef BOXEDWINE_MULTI_THREADED
if (this->terminating) {
return -K_EINTR;
}
if (KThread::currentThread()->startSignal) {
KThread::currentThread()->startSignal = false;
return -K_CONTINUE;
}
#endif
}
} else if (cmd ==FUTEX_WAKE || cmd == FUTEX_WAKE_BITSET) {
U32 count = 0;
//klog("%x/%x futux wake addr=%x op=%x val=%x ram=%x", id, process->id, addr, op, value, (U32)ramAddress);
{
BOXEDWINE_CRITICAL_SECTION_WITH_MUTEX(KThread::futexesMutex);
for (int i = 0; i < MAX_FUTEXES && count < value; i++) {
if (!system_futex[i].thread) {
continue;
}
bool processCheck = (!isPrivate || system_futex[i].thread->process->id == this->process->id);
bool addressCheck = system_futex[i].address == ramAddress;
bool maskCheck = ((cmd != FUTEX_WAKE_BITSET) || (system_futex[i].mask & val3));
if (processCheck && addressCheck && !system_futex[i].wake && maskCheck) {
BOXEDWINE_CRITICAL_SECTION_WITH_CONDITION(system_futex[i].cond);
system_futex[i].wake = true;
BOXEDWINE_CONDITION_SIGNAL(system_futex[i].cond);
count++;
}
}
}
//klog(" %x/%x futux wake finished addr=%x op=%x val=%x ram=%x", id, process->id, addr, op, value, (U32)ramAddress);
return count;
} else {
kwarn("syscall __NR_futex op %d not implemented", op);
return -1;
}
}
/*
struct robust_list {
struct robust_list* next;
};
struct robust_list_head {
struct robust_list list;
U32 futex_offset;
struct robust_list __user* list_op_pending;
};
*/
struct k_robust_list_head {
U32 next;
U32 futex_offset;
U32 list_op_pending;
U32 address;
};
// copied/ported from https://cregit.linuxsources.org/code/5.18/kernel/futex/core.c.html
static U32 fetch_robust_entry(KThread* thread, struct k_robust_list_head* entry, U32 headAddress, U32* pi) {
*pi = headAddress & 1;
headAddress &= ~1;
entry->address = headAddress;
if (!thread->memory->canRead(headAddress, 12)) {
return -K_EFAULT;
}
thread->memory->memcpy(entry, headAddress, 12);
return 0;
}
/* Constants for the pending_op argument of handle_futex_death */
#define HANDLE_DEATH_PENDING true
#define HANDLE_DEATH_LIST false
/*
* Are there any waiters for this robust futex:
*/
#define K_FUTEX_WAITERS 0x80000000
/*
* The kernel signals via this bit that a thread holding a futex
* has exited without unlocking the futex. The kernel also does
* a FUTEX_WAKE on such futexes, after setting the bit, to wake
* up any possible waiters:
*/
#define K_FUTEX_OWNER_DIED 0x40000000
#define K_FUTEX_TID_MASK 0x3fffffff
/*
* Process a futex-list entry, check whether it's owned by the
* dying task, and do notification if so:
*/
U32 KThread::handleFutexDeath(U32 uaddr, bool pi, bool pending_op) {
U32 uval, nval, mval;
/* Futex address must be 32bit aligned */
if ((((unsigned long)uaddr) % 4) != 0)
return -1;
retry:
uval = memory->readd(uaddr);
/*
* Special case for regular (non PI) futexes. The unlock path in
* user space has two race scenarios:
*
* 1. The unlock path releases the user space futex value and
* before it can execute the futex() syscall to wake up
* waiters it is killed.
*
* 2. A woken up waiter is killed before it can acquire the
* futex in user space.
*
* In both cases the TID validation below prevents a wakeup of
* potential waiters which can cause these waiters to block
* forever.
*
* In both cases the following conditions are met:
*
* 1) task->robust_list->list_op_pending != NULL
* @pending_op == true
* 2) User space futex value == 0
* 3) Regular futex: @pi == false
*
* If these conditions are met, it is safe to attempt waking up a
* potential waiter without touching the user space futex value and
* trying to set the OWNER_DIED bit. The user space futex value is
* uncontended and the rest of the user space mutex state is
* consistent, so a woken waiter will just take over the
* uncontended futex. Setting the OWNER_DIED bit would create
* inconsistent state and malfunction of the user space owner died
* handling.
*/
if (pending_op && !pi && !uval) {
// extern int futex_wake(u32 __user * uaddr, unsigned int flags, int nr_wake, u32 bitset);
// is the flag FLAGS_SHARED?
// futex_wake(uaddr, 1, 1, FUTEX_BITSET_MATCH_ANY);
futex(uaddr, FUTEX_WAIT, 1, 0, 0, 0, false);
return 0;
}
if ((uval & K_FUTEX_TID_MASK) != id) {
return 0;
}
/*
* Ok, this dying thread is truly holding a futex
* of interest. Set the OWNER_DIED bit atomically
* via cmpxchg, and if the value had FUTEX_WAITERS
* set, wake up a waiter (if any). (We have to do a
* futex_wake() even if OWNER_DIED is already set -
* to handle the rare but possible case of recursive
* thread-death.) The rest of the cleanup is done in
* userspace.
*/
mval = (uval & K_FUTEX_WAITERS) | K_FUTEX_OWNER_DIED;
// futex_cmpxchg_value_locked
U32 val = memory->readd(uaddr);
if (val == uval) {
memory->writed(uaddr, mval);
}
nval = val;
if (nval != uval)
goto retry;
/*
* Wake robust non-PI futexes here. The wakeup of
* PI futexes happens in exit_pi_state():
*/
if (!pi && (uval & K_FUTEX_WAITERS)) {
// futex_wake(uaddr, 1, 1, FUTEX_BITSET_MATCH_ANY);
futex(uaddr, FUTEX_WAIT, 1, 0, 0, 0, false);
}
return 0;
}
/*
* Walk curr->robust_list (very carefully, it's a userspace list!)
* and mark any locks found there dead, and notify any waiters.
*
* We silently return on any sign of list-walking problem.
*/
#define ROBUST_LIST_LIMIT 2048
void KThread::exitRobustList()
{
BOXEDWINE_CRITICAL_SECTION;
struct k_robust_list_head head;
struct k_robust_list_head entry;
struct k_robust_list_head next_entry;
struct k_robust_list_head pending;
unsigned int limit = ROBUST_LIST_LIMIT, pi, pip;
unsigned int next_pi;
U32 futex_offset = 0;
int rc;
if (!this->robustList || !memory->canRead(this->robustList, 12)) {
return;
}
memory->memcpy(&head, this->robustList, 12);
head.address = this->robustList;
/*
* Fetch the list head (which was registered earlier, via
* sys_set_robust_list()):
*/
if (fetch_robust_entry(this, &entry, head.next, &pi)) {
return;
}
/*
* Fetch the relative futex offset:
*/
U32 futexOffset = head.futex_offset;
/*
* Fetch any possibly pending lock-add first, and handle it
* if it exists:
*/
if (fetch_robust_entry(this, &pending, head.list_op_pending, &pip))
return;
next_entry.address = 0; /* avoid warning with gcc */
while (entry.address != head.next) {
/*
* Fetch the next entry in the list before calling
* handle_futex_death:
*/
rc = fetch_robust_entry(this, &next_entry, entry.next, &next_pi);
/*
* A pending lock might already be on the list, so
* don't process it twice:
*/
if (entry.address != pending.address) {
if (handleFutexDeath(entry.address + futex_offset, pi, HANDLE_DEATH_LIST)) {
return;
}
}
if (rc) {
return;
}
entry = next_entry;
pi = next_pi;
/*
* Avoid excessively long or circular lists:
*/
if (!--limit) {
break;
}
// cond_resched(); // give the scheduler a chance to run a higher-priority process
}
if (pending.address) {
handleFutexDeath(pending.address + futex_offset, pip, HANDLE_DEATH_PENDING);
}
}
static U8 fetchByte(void* data, U32* eip) {
KMemory* memory = (KMemory*)data;
return memory->readb((*eip)++);
}
void KThread::signalTrap(U32 code) {
KSigAction* action = &this->process->sigActions[K_SIGTRAP];
if (action->handlerAndSigAction == K_SIG_DFL) {
DecodedBlock block;
decodeBlock(fetchByte, memory, cpu->eip.u32 + cpu->seg[CS].address, cpu->isBig(), 1, K_PAGE_SIZE, 0, &block);
#ifdef BOXEDWINE_BINARY_TRANSLATOR
kpanic("%s tid=%04X eip=%08X Illegal instruction but no signal handler set up for it: %s: (%X)", process->name.c_str(), cpu->thread->id, cpu->eip.u32, block.op->name(), block.op->originalOp);
#else
kpanic("%s tid=%04X eip=%08X Illegal instruction but no signal handler set up for it: %s (%X)", process->name.c_str(), cpu->thread->id, cpu->eip.u32, block.op->name(), block.op->inst);
#endif
}
memset(this->process->sigActions[K_SIGTRAP].sigInfo, 0, sizeof(this->process->sigActions[K_SIGTRAP].sigInfo));
this->process->sigActions[K_SIGTRAP].sigInfo[0] = K_SIGTRAP;
this->process->sigActions[K_SIGTRAP].sigInfo[2] = code;
this->process->sigActions[K_SIGTRAP].sigInfo[3] = cpu->eip.u32;
this->runSignal(K_SIGTRAP, 3, 0);
}
void KThread::signalIllegalInstruction(int code) {
KSigAction* action = &this->process->sigActions[K_SIGILL];
if (action->handlerAndSigAction == K_SIG_DFL) {
DecodedBlock block;
decodeBlock(fetchByte, memory, cpu->eip.u32 + cpu->seg[CS].address, cpu->isBig(), 1, K_PAGE_SIZE, 0, &block);
#ifdef BOXEDWINE_BINARY_TRANSLATOR
kpanic("%s tid=%04X eip=%08X Illegal instruction but no signal handler set up for it: %s: (%X)", process->name.c_str(), cpu->thread->id, cpu->eip.u32, block.op->name(), block.op->originalOp);
#else
kpanic("%s tid=%04X eip=%08X Illegal instruction but no signal handler set up for it: %s (%X)", process->name.c_str(), cpu->thread->id, cpu->eip.u32, block.op->name(), block.op->inst);
#endif
}
memset(this->process->sigActions[K_SIGILL].sigInfo, 0, sizeof(this->process->sigActions[K_SIGILL].sigInfo));
this->process->sigActions[K_SIGILL].sigInfo[0] = K_SIGILL;
this->process->sigActions[K_SIGILL].sigInfo[2] = code;
this->process->sigActions[K_SIGILL].sigInfo[3] = cpu->eip.u32;
this->runSignal(K_SIGILL, 13, 0); // blocking signal, signalfd can't handle this
}
bool KThread::runSignals() {
U64 mask = this->inSignal ? this->inSigMask : this->sigMask;
U64 todoProcess = this->process->pendingSignals & ~mask;
U64 todoThread = this->pendingSignals & ~mask;
// It seems like linux (tiny core 13, maybe libc) sets the sigprocmask to 0x10012A03 K_SIGIO|K_SIGCHLD|K_SIGALRM|K_SIGUSR2|K_SIGUSR1|K_SIGINT|K_SIGHUP
// then it grabs a pthread mutex via compare exchange
// then wine sends a K_SIGQUIT signal to that thread
// the thread dies/exits because of handling SIGKILL without releasing the pthread mutex
// the next thread in the process that asks for the mutex hangs
//
// I only noticed this on multi-thread normal core with win32, I wonder if this is a race condition that normally doesn't happen under faster circumstances
//
// for now I will add this hack
//
// hopefully it won't have any bad side effects and cause other bugs
if ((todoThread & ((U64)1 << (K_SIGQUIT-1))) && (mask & ((U64)1 << (K_SIGIO-1)))) {
todoThread &= ~((U64)1 << (K_SIGQUIT-1)); // don't process SIGKILL now
}
if (todoProcess!=0 || todoThread!=0) {
U32 i;
for (i=0;i<32;i++) {
if ((todoProcess & ((U64)1 << i))!=0) {
BOXEDWINE_CRITICAL_SECTION_WITH_MUTEX(this->process->pendingSignalsMutex);
if ((this->process->pendingSignals & ((U64)1 << i))!=0 || i + 1 == K_SIGKILL) { // SIGKILL can't be ignored
this->process->pendingSignals &= ~(1 << i);
this->runSignal(i+1, -1, 0);
return true;
}
}
if ((todoThread & ((U64)1 << i))!=0) {
BOXEDWINE_CRITICAL_SECTION_WITH_MUTEX(this->pendingSignalsMutex);
if ((this->pendingSignals & ((U64)1 << i))!=0 || i+1 == K_SIGKILL) { // SIGKILL can't be ignored
this->pendingSignals &= ~(1 << i);
this->runSignal(i+1, -1, 0);
return true;
}
}
}
}
return false;
}
/*
typedef union compat_sigval {
S32 sival_int;
U32 sival_ptr;
} compat_sigval_t;
typedef struct compat_siginfo {
S32 si_signo;
S32 si_errno;
S32 si_code;
union {
S32 _pad[29];
// kill()
struct {
U32 _pid; // sender's pid
U32 _uid; // sender's uid
} _kill;
// POSIX.1b timers
struct {
S32 _tid; // timer id
S32 _overrun; // overrun count
compat_sigval_t _sigval; // same as below
S32 _sys_private; // not to be passed to user
S32 _overrun_incr; // amount to add to overrun
} _timer;
// POSIX.1b signals
struct {
U32 _pid; // sender's pid
U32 _uid; // sender's uid
compat_sigval_t _sigval;
} _rt;
// SIGCHLD
struct {
U32 _pid; // which child
U32 _uid; // sender's uid
S32 _status; // exit code
S32 _utime;
S32 _stime;
} _sigchld;
// SIGCHLD (x32 version)
struct {
U32 _pid; // which child
U32 _uid; // sender's uid
S32 _status; // exit code
S64 _utime;
S64 _stime;
} _sigchld_x32;
// SIGILL, SIGFPE, SIGSEGV, SIGBUS
struct {
U32 _addr; // faulting insn/memory ref.
} _sigfault;
// SIGPOLL
struct {
S32 _band; // POLL_IN, POLL_OUT, POLL_MSG
S32 _fd;
} _sigpoll;
struct {
U32 _call_addr; // calling insn
S32 _syscall; // triggering system call number
U32 _arch; // AUDIT_ARCH_* of syscall
} _sigsys;
} _sifields;
} compat_siginfo_t;
typedef struct fpregset
{
union
{
struct fpchip_state
{
int state[27];
int status;
} fpchip_state;
struct fp_emul_space
{
char fp_emul[246];
char fp_epad[2];
} fp_emul_space;
int f_fpregs[62];
} fp_reg_set;
long int f_wregs[33];
} fpregset_t;
// Number of general registers.
#define NGREG 19
enum
{
REG_GS = 0,
#define REG_GS REG_GS
REG_FS,
#define REG_FS REG_FS
REG_ES,
#define REG_ES REG_ES
REG_DS,
#define REG_DS REG_DS
REG_EDI,
#define REG_EDI REG_EDI
REG_ESI,
#define REG_ESI REG_ESI
REG_EBP,
#define REG_EBP REG_EBP
REG_ESP,
#define REG_ESP REG_ESP
REG_EBX,
#define REG_EBX REG_EBX
REG_EDX,
#define REG_EDX REG_EDX
REG_ECX,
#define REG_ECX REG_ECX
REG_EAX,
#define REG_EAX REG_EAX
REG_TRAPNO,
#define REG_TRAPNO REG_TRAPNO
REG_ERR,
#define REG_ERR REG_ERR
REG_EIP,
#define REG_EIP REG_EIP
REG_CS,
#define REG_CS REG_CS
REG_EFL,
#define REG_EFL REG_EFL
REG_UESP,
#define REG_UESP REG_UESP
REG_SS
#define REG_SS REG_SS
};
// Container for all general registers.
typedef S32 gregset_t[NGREG];
// Context to describe whole processor state.
typedef struct
{
gregset_t gregs;
fpregset_t fpregs;
} mcontext_tt;
typedef struct sigaltstack {
void *ss_sp;
int ss_flags;
S32 ss_size;
} stack_tt;
# define K_SIGSET_NWORDS (1024 / 32)
typedef struct
{
unsigned long int __val[K_SIGSET_NWORDS];
} k__sigset_t;
// Userlevel context.
struct ucontext_ia32 {
unsigned int uc_flags; // 0
unsigned int uc_link; // 4
stack_tt uc_stack; // 8
mcontext_tt uc_mcontext; // 20
k__sigset_t uc_sigmask; // mask last for extensibility
};
*/
#define INFO_SIZE 128
#define CONTEXT_SIZE 128
void writeToContext(KThread* thread, U32 stack, U32 context, bool altStack, U32 trapNo, U32 errorNo) {
CPU* cpu = thread->cpu;
KMemory* memory = thread->memory;
if (altStack) {
memory->writed(context+0x8, thread->alternateStack);
memory->writed(context+0xC, K_SS_ONSTACK);
memory->writed(context+0x10, thread->alternateStackSize);
} else {
memory->writed(context+0x8, thread->alternateStack);
memory->writed(context+0xC, K_SS_DISABLE);
memory->writed(context+0x10, 0);
}
memory->writed(context+0x14, cpu->seg[GS].value);
memory->writed(context+0x18, cpu->seg[FS].value);
memory->writed(context+0x1C, cpu->seg[ES].value);
memory->writed(context+0x20, cpu->seg[DS].value);
memory->writed(context+0x24, cpu->reg[7].u32); // EDI
memory->writed(context+0x28, cpu->reg[6].u32); // ESI
memory->writed(context+0x2C, cpu->reg[5].u32); // EBP
memory->writed(context+0x30, stack); // ESP
memory->writed(context+0x34, cpu->reg[3].u32); // EBX
memory->writed(context+0x38, cpu->reg[2].u32); // EDX
memory->writed(context+0x3C, cpu->reg[1].u32); // ECX
memory->writed(context+0x40, cpu->reg[0].u32); // EAX
memory->writed(context+0x44, trapNo); // REG_TRAPNO
memory->writed(context+0x48, errorNo); // REG_ERR
memory->writed(context+0x4C, cpu->isBig()?cpu->eip.u32:cpu->eip.u16);
memory->writed(context+0x50, cpu->seg[CS].value);
memory->writed(context+0x54, cpu->flags);
memory->writed(context+0x58, 0); // REG_UESP
memory->writed(context+0x5C, cpu->seg[SS].value);
memory->writed(context+0x60, 0); // fpu save state
}
void readFromContext(CPU* cpu, U32 context) {
KMemory* memory = (KMemory*)cpu->memory;
cpu->setSegment(GS, memory->readd(context+0x14));
cpu->setSegment(FS, memory->readd(context+0x18));
cpu->setSegment(ES, memory->readd(context+0x1C));
cpu->setSegment(DS, memory->readd(context+0x20));
cpu->reg[7].u32 = memory->readd(context+0x24); // EDI
cpu->reg[6].u32 = memory->readd(context+0x28); // ESI
cpu->reg[5].u32 = memory->readd(context+0x2C); // EBP
cpu->reg[4].u32 = memory->readd(context+0x30); // ESP
cpu->reg[3].u32 = memory->readd(context+0x34); // EBX
cpu->reg[2].u32 = memory->readd(context+0x38); // EDX
cpu->reg[1].u32 = memory->readd(context+0x3C); // ECX
cpu->reg[0].u32 = memory->readd(context+0x40); // EAX
cpu->eip.u32 = memory->readd(context+0x4C);
cpu->setSegment(CS, memory->readd(context+0x50));
cpu->flags = memory->readd(context+0x54);
cpu->setSegment(SS, memory->readd(context+0x5C));
}
U32 KThread::sigreturn() {
kpanic("KThread::sigreturn This code seems wrong, we never did a memcpy to memory of CPU, should this be readContext. Debug this after finding a program that triggers it");
memory->memcpy(&this->cpu, this->cpu->reg[4].u32, sizeof(CPU));
//klog("signal return (threadId=%d)", thread->id);
return -K_CONTINUE;
}
// https://github.com/torvalds/linux/blob/master/kernel/rseq.c
/*
struct rseq {
U32 cpu_id_start;
U32 cpu_id;
U32 rseq_cs;
U32 padding;
U32 flags;
};
*/