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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
|
#include "types.h"
#include "Process.h"
#include "kmalloc.h"
#include "VGA.h"
#include "StdLib.h"
#include "i386.h"
#include "system.h"
#include <VirtualFileSystem/FileDescriptor.h>
#include <VirtualFileSystem/VirtualFileSystem.h>
#include <ELFLoader/ELFLoader.h>
#include "MemoryManager.h"
#include "errno.h"
#include "i8253.h"
#include "RTC.h"
#include "ProcFileSystem.h"
#include <AK/StdLib.h>
#include <LibC/signal_numbers.h>
#include "Syscall.h"
//#define DEBUG_IO
//#define TASK_DEBUG
//#define FORK_DEBUG
//#define SCHEDULER_DEBUG
#define COOL_GLOBALS
#define MAX_PROCESS_GIDS 32
static const dword scheduler_time_slice = 5; // *10 = 50ms
#ifdef COOL_GLOBALS
struct CoolGlobals {
dword current_pid;
};
CoolGlobals* g_cool_globals;
#endif
// FIXME: Only do a single validation for accesses that don't span multiple pages.
// FIXME: Some places pass strlen(arg1) as arg2. This doesn't seem entirely perfect..
#define VALIDATE_USER_READ(b, s) \
do { \
LinearAddress laddr((dword)(b)); \
if (!validate_user_read(laddr) || !validate_user_read(laddr.offset((s) - 1))) \
return -EFAULT; \
} while(0)
#define VALIDATE_USER_WRITE(b, s) \
do { \
LinearAddress laddr((dword)(b)); \
if (!validate_user_write(laddr) || !validate_user_write(laddr.offset((s) - 1))) \
return -EFAULT; \
} while(0)
static const DWORD defaultStackSize = 16384;
Process* current;
Process* s_kernelProcess;
static pid_t next_pid;
static InlineLinkedList<Process>* s_processes;
static InlineLinkedList<Process>* s_deadProcesses;
static String* s_hostname;
static String& hostnameStorage(InterruptDisabler&)
{
ASSERT(s_hostname);
return *s_hostname;
}
static String getHostname()
{
InterruptDisabler disabler;
return hostnameStorage(disabler).isolatedCopy();
}
static bool contextSwitch(Process*);
static void redoKernelProcessTSS()
{
if (!s_kernelProcess->selector())
s_kernelProcess->setSelector(gdt_alloc_entry());
auto& tssDescriptor = getGDTEntry(s_kernelProcess->selector());
tssDescriptor.setBase(&s_kernelProcess->tss());
tssDescriptor.setLimit(0xffff);
tssDescriptor.dpl = 0;
tssDescriptor.segment_present = 1;
tssDescriptor.granularity = 1;
tssDescriptor.zero = 0;
tssDescriptor.operation_size = 1;
tssDescriptor.descriptor_type = 0;
tssDescriptor.type = 9;
flushGDT();
}
void Process::prepForIRETToNewProcess()
{
redoKernelProcessTSS();
s_kernelProcess->tss().backlink = current->selector();
loadTaskRegister(s_kernelProcess->selector());
}
static void hlt_loop()
{
for (;;) {
asm volatile("hlt");
}
}
void Process::initialize()
{
#ifdef COOL_GLOBALS
g_cool_globals = (CoolGlobals*)0x1000;
#endif
current = nullptr;
next_pid = 0;
s_processes = new InlineLinkedList<Process>;
s_deadProcesses = new InlineLinkedList<Process>;
s_kernelProcess = Process::createKernelProcess(hlt_loop, "colonel");
s_hostname = new String("birx");
redoKernelProcessTSS();
loadTaskRegister(s_kernelProcess->selector());
}
template<typename Callback>
static void forEachProcess(Callback callback)
{
ASSERT_INTERRUPTS_DISABLED();
for (auto* process = s_processes->head(); process; process = process->next()) {
if (!callback(*process))
break;
}
}
void Process::for_each_in_pgrp(pid_t pgid, Function<void(Process&)> callback)
{
ASSERT_INTERRUPTS_DISABLED();
for (auto* process = s_processes->head(); process; process = process->next()) {
if (process->pgid() == pgid)
callback(*process);
}
}
Vector<Process*> Process::allProcesses()
{
InterruptDisabler disabler;
Vector<Process*> processes;
processes.ensureCapacity(s_processes->sizeSlow());
for (auto* process = s_processes->head(); process; process = process->next())
processes.append(process);
return processes;
}
Region* Process::allocate_region(LinearAddress laddr, size_t size, String&& name, bool is_readable, bool is_writable)
{
// FIXME: This needs sanity checks. What if this overlaps existing regions?
if (laddr.is_null()) {
laddr = m_nextRegion;
m_nextRegion = m_nextRegion.offset(size).offset(PAGE_SIZE);
}
laddr.mask(0xfffff000);
unsigned page_count = ceilDiv(size, PAGE_SIZE);
auto physical_pages = MM.allocate_physical_pages(page_count);
ASSERT(physical_pages.size() == page_count);
m_regions.append(adopt(*new Region(laddr, size, move(physical_pages), move(name), is_readable, is_writable)));
MM.mapRegion(*this, *m_regions.last());
return m_regions.last().ptr();
}
bool Process::deallocate_region(Region& region)
{
InterruptDisabler disabler;
for (size_t i = 0; i < m_regions.size(); ++i) {
if (m_regions[i].ptr() == ®ion) {
MM.unmapRegion(*this, region);
m_regions.remove(i);
return true;
}
}
return false;
}
Region* Process::regionFromRange(LinearAddress laddr, size_t size)
{
for (auto& region : m_regions) {
if (region->linearAddress == laddr && region->size == size)
return region.ptr();
}
return nullptr;
}
int Process::sys$set_mmap_name(void* addr, size_t size, const char* name)
{
VALIDATE_USER_READ(name, strlen(name));
auto* region = regionFromRange(LinearAddress((dword)addr), size);
if (!region)
return -EINVAL;
region->name = name;
return 0;
}
void* Process::sys$mmap(void* addr, size_t size)
{
InterruptDisabler disabler;
// FIXME: Implement mapping at a client-preferred address.
ASSERT(addr == nullptr);
auto* region = allocate_region(LinearAddress(), size, "mmap");
if (!region)
return (void*)-1;
MM.mapRegion(*this, *region);
return (void*)region->linearAddress.get();
}
int Process::sys$munmap(void* addr, size_t size)
{
InterruptDisabler disabler;
auto* region = regionFromRange(LinearAddress((dword)addr), size);
if (!region)
return -1;
if (!deallocate_region(*region))
return -1;
return 0;
}
int Process::sys$gethostname(char* buffer, size_t size)
{
VALIDATE_USER_WRITE(buffer, size);
auto hostname = getHostname();
if (size < (hostname.length() + 1))
return -ENAMETOOLONG;
memcpy(buffer, hostname.characters(), size);
return 0;
}
Process* Process::fork(RegisterDump& regs)
{
auto* child = new Process(String(m_name), m_uid, m_gid, m_pid, m_ring, m_cwd.copyRef(), m_executable.copyRef(), m_tty, this);
#ifdef FORK_DEBUG
dbgprintf("fork: child=%p\n", child);
#endif
#if 0
// FIXME: An honest fork() would copy these. Needs a Vector copy ctor.
child->m_arguments = m_arguments;
child->m_initialEnvironment = m_initialEnvironment;
#endif
for (auto& region : m_regions) {
#ifdef FORK_DEBUG
dbgprintf("fork: cloning Region{%p}\n", region.ptr());
#endif
auto cloned_region = region->clone();
child->m_regions.append(move(cloned_region));
MM.mapRegion(*child, *child->m_regions.last());
}
child->m_tss.eax = 0; // fork() returns 0 in the child :^)
child->m_tss.ebx = regs.ebx;
child->m_tss.ecx = regs.ecx;
child->m_tss.edx = regs.edx;
child->m_tss.ebp = regs.ebp;
child->m_tss.esp = regs.esp_if_crossRing;
child->m_tss.esi = regs.esi;
child->m_tss.edi = regs.edi;
child->m_tss.eflags = regs.eflags;
child->m_tss.eip = regs.eip;
child->m_tss.cs = regs.cs;
child->m_tss.ds = regs.ds;
child->m_tss.es = regs.es;
child->m_tss.fs = regs.fs;
child->m_tss.gs = regs.gs;
child->m_tss.ss = regs.ss_if_crossRing;
#ifdef FORK_DEBUG
dbgprintf("fork: child will begin executing at %w:%x with stack %w:%x\n", child->m_tss.cs, child->m_tss.eip, child->m_tss.ss, child->m_tss.esp);
#endif
ProcFileSystem::the().addProcess(*child);
s_processes->prepend(child);
system.nprocess++;
#ifdef TASK_DEBUG
kprintf("Process %u (%s) forked from %u @ %p\n", child->pid(), child->name().characters(), m_pid, child->m_tss.eip);
#endif
return child;
}
pid_t Process::sys$fork(RegisterDump& regs)
{
auto* child = fork(regs);
ASSERT(child);
return child->pid();
}
int Process::exec(const String& path, Vector<String>&& arguments, Vector<String>&& environment)
{
auto parts = path.split('/');
if (parts.isEmpty())
return -ENOENT;
int error;
auto descriptor = VirtualFileSystem::the().open(path, error, 0, m_cwd ? m_cwd->inode : InodeIdentifier());
if (!descriptor) {
ASSERT(error != 0);
return error;
}
if (!descriptor->metadata().mayExecute(m_euid, m_gids))
return -EACCES;
auto elfData = descriptor->readEntireFile();
if (!elfData)
return -EIO; // FIXME: Get a more detailed error from VFS.
dword entry_eip = 0;
PageDirectory* old_page_directory;
PageDirectory* new_page_directory;
{
InterruptDisabler disabler;
// Okay, here comes the sleight of hand, pay close attention..
auto old_regions = move(m_regions);
old_page_directory = m_page_directory;
new_page_directory = reinterpret_cast<PageDirectory*>(kmalloc_page_aligned(sizeof(PageDirectory)));
MM.populate_page_directory(*new_page_directory);
m_page_directory = new_page_directory;
MM.enter_process_paging_scope(*this);
ELFLoader loader(move(elfData));
loader.alloc_section_hook = [&] (LinearAddress laddr, size_t size, size_t alignment, bool is_readable, bool is_writable, const String& name) {
ASSERT(size);
size = ((size / 4096) + 1) * 4096; // FIXME: Use ceil_div?
(void) allocate_region(laddr, size, String(name), is_readable, is_writable);
return laddr.asPtr();
};
bool success = loader.load();
if (!success) {
m_page_directory = old_page_directory;
MM.enter_process_paging_scope(*this);
MM.release_page_directory(*new_page_directory);
m_regions = move(old_regions);
kprintf("sys$execve: Failure loading %s\n", path.characters());
return -ENOEXEC;
}
entry_eip = (dword)loader.symbol_ptr("_start");
if (!entry_eip) {
m_page_directory = old_page_directory;
MM.enter_process_paging_scope(*this);
MM.release_page_directory(*new_page_directory);
m_regions = move(old_regions);
return -ENOEXEC;
}
}
InterruptDisabler disabler;
if (current == this)
loadTaskRegister(s_kernelProcess->selector());
m_name = parts.takeLast();
dword old_esp0 = m_tss.esp0;
memset(&m_tss, 0, sizeof(m_tss));
m_tss.eflags = 0x0202;
m_tss.eip = entry_eip;
m_tss.cs = 0x1b;
m_tss.ds = 0x23;
m_tss.es = 0x23;
m_tss.fs = 0x23;
m_tss.gs = 0x23;
m_tss.ss = 0x23;
m_tss.cr3 = (dword)m_page_directory;
m_stack_region = allocate_region(LinearAddress(), defaultStackSize, "stack");
ASSERT(m_stack_region);
m_stackTop3 = m_stack_region->linearAddress.offset(defaultStackSize).get() & 0xfffffff8;
m_tss.esp = m_stackTop3;
m_tss.ss0 = 0x10;
m_tss.esp0 = old_esp0;
m_tss.ss2 = m_pid;
MM.release_page_directory(*old_page_directory);
m_executable = descriptor->vnode();
m_arguments = move(arguments);
m_initialEnvironment = move(environment);
#ifdef TASK_DEBUG
kprintf("Process %u (%s) exec'd %s @ %p\n", pid(), name().characters(), filename, m_tss.eip);
#endif
if (current == this)
sched_yield();
return 0;
}
int Process::sys$execve(const char* filename, const char** argv, const char** envp)
{
VALIDATE_USER_READ(filename, strlen(filename));
if (argv) {
for (size_t i = 0; argv[i]; ++i) {
VALIDATE_USER_READ(argv[i], strlen(argv[i]));
}
}
if (envp) {
for (size_t i = 0; envp[i]; ++i) {
VALIDATE_USER_READ(envp[i], strlen(envp[i]));
}
}
String path(filename);
auto parts = path.split('/');
Vector<String> arguments;
if (argv) {
for (size_t i = 0; argv[i]; ++i) {
arguments.append(argv[i]);
}
} else {
arguments.append(parts.last());
}
Vector<String> environment;
if (envp) {
for (size_t i = 0; envp[i]; ++i) {
environment.append(envp[i]);
}
}
int rc = exec(path, move(arguments), move(environment));
ASSERT(rc < 0);
return rc;
}
pid_t Process::sys$spawn(const char* filename, const char** argv, const char** envp)
{
VALIDATE_USER_READ(filename, strlen(filename));
if (argv) {
for (size_t i = 0; argv[i]; ++i) {
VALIDATE_USER_READ(argv[i], strlen(argv[i]));
}
}
if (envp) {
for (size_t i = 0; envp[i]; ++i) {
VALIDATE_USER_READ(envp[i], strlen(envp[i]));
}
}
String path(filename);
auto parts = path.split('/');
Vector<String> arguments;
if (argv) {
for (size_t i = 0; argv[i]; ++i) {
arguments.append(argv[i]);
}
} else {
arguments.append(parts.last());
}
Vector<String> environment;
if (envp) {
for (size_t i = 0; envp[i]; ++i) {
environment.append(envp[i]);
}
}
int error;
auto* child = create_user_process(path, m_uid, m_gid, m_pid, error, move(arguments), move(environment), m_tty);
if (child)
return child->pid();
return error;
}
Process* Process::create_user_process(const String& path, uid_t uid, gid_t gid, pid_t parent_pid, int& error, Vector<String>&& arguments, Vector<String>&& environment, TTY* tty)
{
// FIXME: Don't split() the path twice (sys$spawn also does it...)
auto parts = path.split('/');
if (arguments.isEmpty()) {
arguments.append(parts.last());
}
RetainPtr<VirtualFileSystem::Node> cwd;
{
InterruptDisabler disabler;
if (auto* parent = Process::fromPID(parent_pid))
cwd = parent->m_cwd.copyRef();
}
if (!cwd)
cwd = VirtualFileSystem::the().root();
auto* process = new Process(parts.takeLast(), uid, gid, parent_pid, Ring3, move(cwd), nullptr, tty);
error = process->exec(path, move(arguments), move(environment));
if (error != 0)
return nullptr;
ProcFileSystem::the().addProcess(*process);
s_processes->prepend(process);
system.nprocess++;
#ifdef TASK_DEBUG
kprintf("Process %u (%s) spawned @ %p\n", process->pid(), process->name().characters(), process->m_tss.eip);
#endif
error = 0;
return process;
}
int Process::sys$get_environment(char*** environ)
{
auto* region = allocate_region(LinearAddress(), PAGE_SIZE, "environ");
if (!region)
return -ENOMEM;
MM.mapRegion(*this, *region);
char* envpage = (char*)region->linearAddress.get();
*environ = (char**)envpage;
char* bufptr = envpage + (sizeof(char*) * (m_initialEnvironment.size() + 1));
for (size_t i = 0; i < m_initialEnvironment.size(); ++i) {
(*environ)[i] = bufptr;
memcpy(bufptr, m_initialEnvironment[i].characters(), m_initialEnvironment[i].length());
bufptr += m_initialEnvironment[i].length();
*(bufptr++) = '\0';
}
(*environ)[m_initialEnvironment.size()] = nullptr;
return 0;
}
int Process::sys$get_arguments(int* argc, char*** argv)
{
auto* region = allocate_region(LinearAddress(), PAGE_SIZE, "argv");
if (!region)
return -ENOMEM;
MM.mapRegion(*this, *region);
char* argpage = (char*)region->linearAddress.get();
*argc = m_arguments.size();
*argv = (char**)argpage;
char* bufptr = argpage + (sizeof(char*) * m_arguments.size());
for (size_t i = 0; i < m_arguments.size(); ++i) {
(*argv)[i] = bufptr;
memcpy(bufptr, m_arguments[i].characters(), m_arguments[i].length());
bufptr += m_arguments[i].length();
*(bufptr++) = '\0';
}
return 0;
}
Process* Process::createKernelProcess(void (*e)(), String&& name)
{
auto* process = new Process(move(name), (uid_t)0, (gid_t)0, (pid_t)0, Ring0);
process->m_tss.eip = (dword)e;
if (process->pid() != 0) {
InterruptDisabler disabler;
s_processes->prepend(process);
system.nprocess++;
ProcFileSystem::the().addProcess(*process);
#ifdef TASK_DEBUG
kprintf("Kernel process %u (%s) spawned @ %p\n", process->pid(), process->name().characters(), process->m_tss.eip);
#endif
}
return process;
}
Process::Process(String&& name, uid_t uid, gid_t gid, pid_t ppid, RingLevel ring, RetainPtr<VirtualFileSystem::Node>&& cwd, RetainPtr<VirtualFileSystem::Node>&& executable, TTY* tty, Process* fork_parent)
: m_name(move(name))
, m_pid(next_pid++) // FIXME: RACE: This variable looks racy!
, m_uid(uid)
, m_gid(gid)
, m_euid(uid)
, m_egid(gid)
, m_state(Runnable)
, m_ring(ring)
, m_cwd(move(cwd))
, m_executable(move(executable))
, m_tty(tty)
, m_ppid(ppid)
{
m_gids.set(m_gid);
if (fork_parent) {
m_sid = fork_parent->m_sid;
m_pgid = fork_parent->m_pgid;
} else {
// FIXME: Use a ProcessHandle? Presumably we're executing *IN* the parent right now though..
InterruptDisabler disabler;
if (auto* parent = Process::fromPID(m_ppid)) {
m_sid = parent->m_sid;
m_pgid = parent->m_pgid;
}
}
m_page_directory = (PageDirectory*)kmalloc_page_aligned(sizeof(PageDirectory));
MM.populate_page_directory(*m_page_directory);
if (fork_parent) {
m_file_descriptors.resize(fork_parent->m_file_descriptors.size());
for (size_t i = 0; i < fork_parent->m_file_descriptors.size(); ++i) {
if (!fork_parent->m_file_descriptors[i])
continue;
#ifdef FORK_DEBUG
dbgprintf("fork: cloning fd %u... (%p) istty? %um\n", i, fork_parent->m_file_descriptors[i].ptr(), fork_parent->m_file_descriptors[i]->isTTY());
#endif
m_file_descriptors[i] = fork_parent->m_file_descriptors[i]->clone();
}
} else {
m_file_descriptors.resize(m_max_open_file_descriptors);
if (tty) {
m_file_descriptors[0] = tty->open(O_RDONLY);
m_file_descriptors[1] = tty->open(O_WRONLY);
m_file_descriptors[2] = tty->open(O_WRONLY);
}
}
if (fork_parent)
m_nextRegion = fork_parent->m_nextRegion;
else
m_nextRegion = LinearAddress(0x10000000);
if (fork_parent) {
memcpy(&m_tss, &fork_parent->m_tss, sizeof(m_tss));
} else {
memset(&m_tss, 0, sizeof(m_tss));
// Only IF is set when a process boots.
m_tss.eflags = 0x0202;
word cs, ds, ss;
if (isRing0()) {
cs = 0x08;
ds = 0x10;
ss = 0x10;
} else {
cs = 0x1b;
ds = 0x23;
ss = 0x23;
}
m_tss.ds = ds;
m_tss.es = ds;
m_tss.fs = ds;
m_tss.gs = ds;
m_tss.ss = ss;
m_tss.cs = cs;
}
m_tss.cr3 = (dword)m_page_directory;
if (isRing0()) {
// FIXME: This memory is leaked.
// But uh, there's also no kernel process termination, so I guess it's not technically leaked...
dword stackBottom = (dword)kmalloc_eternal(defaultStackSize);
m_stackTop0 = (stackBottom + defaultStackSize) & 0xffffff8;
m_tss.esp = m_stackTop0;
} else {
if (fork_parent) {
m_stackTop3 = fork_parent->m_stackTop3;
} else {
auto* region = allocate_region(LinearAddress(), defaultStackSize, "stack");
ASSERT(region);
m_stackTop3 = region->linearAddress.offset(defaultStackSize).get() & 0xfffffff8;
m_tss.esp = m_stackTop3;
}
}
if (isRing3()) {
// Ring3 processes need a separate stack for Ring0.
m_kernelStack = kmalloc(defaultStackSize);
m_stackTop0 = ((DWORD)m_kernelStack + defaultStackSize) & 0xffffff8;
m_tss.ss0 = 0x10;
m_tss.esp0 = m_stackTop0;
}
// HACK: Ring2 SS in the TSS is the current PID.
m_tss.ss2 = m_pid;
m_farPtr.offset = 0x98765432;
}
Process::~Process()
{
InterruptDisabler disabler;
ProcFileSystem::the().removeProcess(*this);
system.nprocess--;
gdt_free_entry(selector());
if (m_kernelStack) {
kfree(m_kernelStack);
m_kernelStack = nullptr;
}
MM.release_page_directory(*m_page_directory);
}
void Process::dumpRegions()
{
kprintf("Process %s(%u) regions:\n", name().characters(), pid());
kprintf("BEGIN END SIZE NAME\n");
for (auto& region : m_regions) {
kprintf("%x -- %x %x %s\n",
region->linearAddress.get(),
region->linearAddress.offset(region->size - 1).get(),
region->size,
region->name.characters());
}
}
void Process::sys$exit(int status)
{
cli();
#ifdef TASK_DEBUG
kprintf("sys$exit: %s(%u) exit with status %d\n", name().characters(), pid(), status);
#endif
set_state(Dead);
m_termination_status = status;
m_termination_signal = 0;
if (!scheduleNewProcess()) {
kprintf("Process::sys$exit: Failed to schedule a new process :(\n");
HANG;
}
switchNow();
}
void Process::terminate_due_to_signal(byte signal)
{
ASSERT_INTERRUPTS_DISABLED();
ASSERT(signal < 32);
dbgprintf("terminate_due_to_signal %s(%u) <- %u\n", name().characters(), pid(), signal);
m_termination_status = 0;
m_termination_signal = signal;
set_state(Dead);
}
void Process::send_signal(byte signal, Process* sender)
{
ASSERT_INTERRUPTS_DISABLED();
ASSERT(signal < 32);
m_pending_signals |= 1 << signal;
if (sender)
dbgprintf("signal: %s(%u) sent %d to %s(%u)\n", sender->name().characters(), sender->pid(), signal, name().characters(), pid());
else
dbgprintf("signal: kernel sent %d to %s(%u)\n", signal, name().characters(), pid());
}
bool Process::has_unmasked_pending_signals() const
{
return m_pending_signals & ~m_signal_mask;
}
void Process::dispatch_one_pending_signal()
{
ASSERT_INTERRUPTS_DISABLED();
dword signal_candidates = m_pending_signals & ~m_signal_mask;
ASSERT(signal_candidates);
byte signal = 0;
for (; signal < 32; ++signal) {
if (signal_candidates & (1 << signal)) {
break;
}
}
dispatch_signal(signal);
}
void Process::dispatch_signal(byte signal)
{
ASSERT_INTERRUPTS_DISABLED();
ASSERT(signal < 32);
dbgprintf("dispatch_signal %s(%u) <- %u\n", name().characters(), pid(), signal);
auto& action = m_signal_action_data[signal];
// FIXME: Implement SA_SIGINFO signal handlers.
ASSERT(!(action.flags & SA_SIGINFO));
auto handler_laddr = action.handler_or_sigaction;
if (handler_laddr.is_null()) {
// FIXME: Is termination really always the appropriate action?
return terminate_due_to_signal(signal);
}
m_tss_to_resume_kernel = m_tss;
#ifdef SIGNAL_DEBUG
kprintf("resume tss pc: %w:%x\n", m_tss_to_resume_kernel.cs, m_tss_to_resume_kernel.eip);
#endif
word ret_ss = m_tss.ss;
dword ret_esp = m_tss.esp;
word ret_cs = m_tss.cs;
dword ret_eip = m_tss.eip;
dword ret_eflags = m_tss.eflags;
bool interrupting_in_kernel = (ret_cs & 3) == 0;
if ((ret_cs & 3) == 0) {
// FIXME: Handle send_signal to process currently in kernel code.
dbgprintf("dispatch_signal to %s(%u) in state=%s with return to %w:%x\n", name().characters(), pid(), toString(state()), ret_cs, ret_eip);
ASSERT(is_blocked());
}
ProcessPagingScope pagingScope(*this);
if (interrupting_in_kernel) {
if (!m_signal_stack_user_region) {
m_signal_stack_user_region = allocate_region(LinearAddress(), defaultStackSize, "signal stack (user)");
ASSERT(m_signal_stack_user_region);
m_signal_stack_kernel_region = allocate_region(LinearAddress(), defaultStackSize, "signal stack (kernel)");
ASSERT(m_signal_stack_user_region);
}
m_tss.ss = 0x23;
m_tss.esp = m_signal_stack_user_region->linearAddress.offset(defaultStackSize).get() & 0xfffffff8;
m_tss.ss0 = 0x10;
m_tss.esp0 = m_signal_stack_kernel_region->linearAddress.offset(defaultStackSize).get() & 0xfffffff8;
push_value_on_stack(ret_eflags);
push_value_on_stack(ret_cs);
push_value_on_stack(ret_eip);
} else {
push_value_on_stack(ret_cs);
push_value_on_stack(ret_eip);
push_value_on_stack(ret_eflags);
}
// PUSHA
dword old_esp = m_tss.esp;
push_value_on_stack(m_tss.eax);
push_value_on_stack(m_tss.ecx);
push_value_on_stack(m_tss.edx);
push_value_on_stack(m_tss.ebx);
push_value_on_stack(old_esp);
push_value_on_stack(m_tss.ebp);
push_value_on_stack(m_tss.esi);
push_value_on_stack(m_tss.edi);
m_tss.eax = (dword)signal;
m_tss.cs = 0x1b;
m_tss.ds = 0x23;
m_tss.es = 0x23;
m_tss.fs = 0x23;
m_tss.gs = 0x23;
m_tss.eip = handler_laddr.get();
if (m_return_to_ring3_from_signal_trampoline.is_null()) {
// FIXME: This should be a global trampoline shared by all processes, not one created per process!
// FIXME: Remap as read-only after setup.
auto* region = allocate_region(LinearAddress(), PAGE_SIZE, "signal_trampoline", true, true);
m_return_to_ring3_from_signal_trampoline = region->linearAddress;
byte* code_ptr = m_return_to_ring3_from_signal_trampoline.asPtr();
*code_ptr++ = 0x61; // popa
*code_ptr++ = 0x9d; // popf
*code_ptr++ = 0xc3; // ret
*code_ptr++ = 0x0f; // ud2
*code_ptr++ = 0x0b;
m_return_to_ring0_from_signal_trampoline = LinearAddress((dword)code_ptr);
*code_ptr++ = 0x61; // popa
*code_ptr++ = 0xb8; // mov eax, <dword>
*(dword*)code_ptr = Syscall::SC_sigreturn;
code_ptr += sizeof(dword);
*code_ptr++ = 0xcd; // int 0x80
*code_ptr++ = 0x80;
*code_ptr++ = 0x0f; // ud2
*code_ptr++ = 0x0b;
// FIXME: For !SA_NODEFER, maybe we could do something like emitting an int 0x80 syscall here that
// unmasks the signal so it can be received again? I guess then I would need one trampoline
// per signal number if it's hard-coded, but it's just a few bytes per each.
}
if (interrupting_in_kernel)
push_value_on_stack(m_return_to_ring0_from_signal_trampoline.get());
else
push_value_on_stack(m_return_to_ring3_from_signal_trampoline.get());
m_pending_signals &= ~(1 << signal);
#ifdef SIGNAL_DEBUG
dbgprintf("signal: Okay, %s(%u) has been primed\n", name().characters(), pid());
#endif
}
void Process::sys$sigreturn()
{
InterruptDisabler disabler;
m_tss = m_tss_to_resume_kernel;
#ifdef SIGNAL_DEBUG
dbgprintf("sys$sigreturn in %s(%u)\n", name().characters(), pid());
dbgprintf(" -> resuming execution at %w:%x\n", m_tss.cs, m_tss.eip);
#endif
loadTaskRegister(s_kernelProcess->selector());
sched_yield();
kprintf("sys$sigreturn failed in %s(%u)\n", name().characters(), pid());
ASSERT_NOT_REACHED();
}
void Process::push_value_on_stack(dword value)
{
m_tss.esp -= 4;
dword* stack_ptr = (dword*)m_tss.esp;
*stack_ptr = value;
}
void Process::crash()
{
ASSERT_INTERRUPTS_DISABLED();
ASSERT(state() != Dead);
m_termination_signal = SIGSEGV;
set_state(Dead);
dumpRegions();
if (!scheduleNewProcess()) {
kprintf("Process::crash: Failed to schedule a new process :(\n");
HANG;
}
switchNow();
}
void Process::doHouseKeeping()
{
if (s_deadProcesses->isEmpty())
return;
InterruptDisabler disabler;
Process* next = nullptr;
for (auto* deadProcess = s_deadProcesses->head(); deadProcess; deadProcess = next) {
next = deadProcess->next();
delete deadProcess;
}
s_deadProcesses->clear();
}
int sched_yield()
{
if (!current) {
kprintf("PANIC: sched_yield() with !current");
HANG;
}
//kprintf("%s<%u> yield()\n", current->name().characters(), current->pid());
InterruptDisabler disabler;
if (!scheduleNewProcess())
return 1;
//kprintf("yield() jumping to new process: %x (%s)\n", current->farPtr().selector, current->name().characters());
switchNow();
return 0;
}
void switchNow()
{
Descriptor& descriptor = getGDTEntry(current->selector());
descriptor.type = 9;
flushGDT();
asm("sti\n"
"ljmp *(%%eax)\n"
::"a"(¤t->farPtr())
);
}
template<typename Callback>
static void for_each_process_in_state(Process::State state, Callback callback)
{
ASSERT_INTERRUPTS_DISABLED();
for (auto* process = s_processes->head(); process;) {
auto* next_process = process->next();
if (process->state() == state)
callback(*process);
process = next_process;
}
}
template<typename Callback>
static void for_each_process_not_in_state(Process::State state, Callback callback)
{
ASSERT_INTERRUPTS_DISABLED();
for (auto* process = s_processes->head(); process;) {
auto* next_process = process->next();
if (process->state() != state)
callback(*process);
process = next_process;
}
}
template<typename Callback>
static void for_each_blocked_process(Callback callback)
{
ASSERT_INTERRUPTS_DISABLED();
for (auto* process = s_processes->head(); process;) {
auto* next_process = process->next();
if (process->is_blocked())
callback(*process);
process = next_process;
}
}
bool scheduleNewProcess()
{
ASSERT_INTERRUPTS_DISABLED();
if (!current) {
// XXX: The first ever context_switch() goes to the idle process.
// This to setup a reliable place we can return to.
return contextSwitch(Process::kernelProcess());
}
// Check and unblock processes whose wait conditions have been met.
for (auto* process = s_processes->head(); process; process = process->next()) {
if (process->state() == Process::BlockedSleep) {
if (process->wakeupTime() <= system.uptime)
process->unblock();
continue;
}
if (process->state() == Process::BlockedWait) {
auto* waitee = Process::fromPID(process->waitee());
if (!waitee) {
kprintf("waitee %u of %s(%u) reaped before I could wait?\n", process->waitee(), process->name().characters(), process->pid());
ASSERT_NOT_REACHED();
}
if (waitee->state() == Process::Dead) {
process->m_waitee_status = (waitee->m_termination_status << 8) | waitee->m_termination_signal;
process->unblock();
waitee->set_state(Process::Forgiven);
}
continue;
}
if (process->state() == Process::BlockedRead) {
ASSERT(process->m_fdBlockedOnRead != -1);
// FIXME: Block until the amount of data wanted is available.
if (process->m_file_descriptors[process->m_fdBlockedOnRead]->hasDataAvailableForRead())
process->unblock();
continue;
}
}
// Forgive dead orphans.
// FIXME: Does this really make sense?
for_each_process_in_state(Process::Dead, [] (auto& process) {
if (!Process::fromPID(process.ppid()))
process.set_state(Process::Forgiven);
});
// Clean up forgiven processes.
// FIXME: Do we really need this to be a separate pass over the process list?
for_each_process_in_state(Process::Forgiven, [] (auto& process) {
s_processes->remove(&process);
s_deadProcesses->append(&process);
});
// Dispatch any pending signals.
// FIXME: Do we really need this to be a separate pass over the process list?
for_each_process_not_in_state(Process::Dead, [] (auto& process) {
if (!process.has_unmasked_pending_signals())
return;
// We know how to interrupt blocked processes, but if they are just executing
// at some random point in the kernel, let them continue. They'll be in userspace
// sooner or later and we can deliver the signal then.
// FIXME: Maybe we could check when returning from a syscall if there's a pending
// signal and dispatch it then and there? Would that be doable without the
// syscall effectively being "interrupted" despite having completed?
if (process.in_kernel() && !process.is_blocked())
return;
process.dispatch_one_pending_signal();
if (process.is_blocked()) {
process.m_was_interrupted_while_blocked = true;
process.unblock();
}
});
#ifdef SCHEDULER_DEBUG
dbgprintf("Scheduler choices:\n");
for (auto* process = s_processes->head(); process; process = process->next()) {
//if (process->state() == Process::BlockedWait || process->state() == Process::BlockedSleep)
// continue;
dbgprintf("% 12s %s(%u) @ %w:%x\n", toString(process->state()), process->name().characters(), process->pid(), process->tss().cs, process->tss().eip);
}
#endif
auto* prevHead = s_processes->head();
for (;;) {
// Move head to tail.
s_processes->append(s_processes->removeHead());
auto* process = s_processes->head();
if (process->state() == Process::Runnable || process->state() == Process::Running) {
#ifdef SCHEDULER_DEBUG
dbgprintf("switch to %s(%u)\n", process->name().characters(), process->pid());
#endif
return contextSwitch(process);
}
if (process == prevHead) {
// Back at process_head, nothing wants to run.
kprintf("Nothing wants to run!\n");
kprintf("PID OWNER STATE NSCHED NAME\n");
for (auto* process = s_processes->head(); process; process = process->next()) {
kprintf("%w %w:%w %b %w %s\n",
process->pid(),
process->uid(),
process->gid(),
process->state(),
process->timesScheduled(),
process->name().characters());
}
kprintf("Switch to kernel process @ %w:%x\n", s_kernelProcess->tss().cs, s_kernelProcess->tss().eip);
return contextSwitch(Process::kernelProcess());
}
}
}
static bool contextSwitch(Process* t)
{
t->setTicksLeft(scheduler_time_slice);
t->didSchedule();
if (current == t)
return false;
#ifdef SCHEDULER_DEBUG
// Some sanity checking to force a crash earlier.
auto csRPL = t->tss().cs & 3;
auto ssRPL = t->tss().ss & 3;
if (csRPL != ssRPL) {
kprintf("Fuckup! Switching from %s(%u) to %s(%u) has RPL mismatch\n",
current->name().characters(), current->pid(),
t->name().characters(), t->pid()
);
kprintf("code: %w:%x\n", t->tss().cs, t->tss().eip);
kprintf(" stk: %w:%x\n", t->tss().ss, t->tss().esp);
ASSERT(csRPL == ssRPL);
}
#endif
if (current) {
// If the last process hasn't blocked (still marked as running),
// mark it as runnable for the next round.
if (current->state() == Process::Running)
current->set_state(Process::Runnable);
}
current = t;
t->set_state(Process::Running);
#ifdef COOL_GLOBALS
g_cool_globals->current_pid = t->pid();
#endif
if (!t->selector()) {
t->setSelector(gdt_alloc_entry());
auto& descriptor = getGDTEntry(t->selector());
descriptor.setBase(&t->tss());
descriptor.setLimit(0xffff);
descriptor.dpl = 0;
descriptor.segment_present = 1;
descriptor.granularity = 1;
descriptor.zero = 0;
descriptor.operation_size = 1;
descriptor.descriptor_type = 0;
}
auto& descriptor = getGDTEntry(t->selector());
descriptor.type = 11; // Busy TSS
flushGDT();
return true;
}
Process* Process::fromPID(pid_t pid)
{
ASSERT_INTERRUPTS_DISABLED();
for (auto* process = s_processes->head(); process; process = process->next()) {
if (process->pid() == pid)
return process;
}
return nullptr;
}
FileDescriptor* Process::file_descriptor(int fd)
{
if (fd < 0)
return nullptr;
if ((size_t)fd < m_file_descriptors.size())
return m_file_descriptors[fd].ptr();
return nullptr;
}
const FileDescriptor* Process::file_descriptor(int fd) const
{
if (fd < 0)
return nullptr;
if ((size_t)fd < m_file_descriptors.size())
return m_file_descriptors[fd].ptr();
return nullptr;
}
ssize_t Process::sys$get_dir_entries(int fd, void* buffer, size_t size)
{
VALIDATE_USER_WRITE(buffer, size);
auto* descriptor = file_descriptor(fd);
if (!descriptor)
return -EBADF;
return descriptor->get_dir_entries((byte*)buffer, size);
}
int Process::sys$lseek(int fd, off_t offset, int whence)
{
auto* descriptor = file_descriptor(fd);
if (!descriptor)
return -EBADF;
return descriptor->seek(offset, whence);
}
int Process::sys$ttyname_r(int fd, char* buffer, size_t size)
{
VALIDATE_USER_WRITE(buffer, size);
auto* descriptor = file_descriptor(fd);
if (!descriptor)
return -EBADF;
if (!descriptor->isTTY())
return -ENOTTY;
auto ttyName = descriptor->tty()->ttyName();
if (size < ttyName.length() + 1)
return -ERANGE;
strcpy(buffer, ttyName.characters());
return 0;
}
ssize_t Process::sys$write(int fd, const void* data, size_t size)
{
VALIDATE_USER_READ(data, size);
#ifdef DEBUG_IO
kprintf("Process::sys$write: called(%d, %p, %u)\n", fd, data, size);
#endif
auto* descriptor = file_descriptor(fd);
#ifdef DEBUG_IO
kprintf("Process::sys$write: handle=%p\n", descriptor);
#endif
if (!descriptor)
return -EBADF;
auto nwritten = descriptor->write((const byte*)data, size);
#ifdef DEBUG_IO
kprintf("Process::sys$write: nwritten=%u\n", nwritten);
#endif
return nwritten;
}
ssize_t Process::sys$read(int fd, void* outbuf, size_t nread)
{
VALIDATE_USER_WRITE(outbuf, nread);
#ifdef DEBUG_IO
kprintf("Process::sys$read: called(%d, %p, %u)\n", fd, outbuf, nread);
#endif
auto* descriptor = file_descriptor(fd);
#ifdef DEBUG_IO
kprintf("Process::sys$read: handle=%p\n", descriptor);
#endif
if (!descriptor)
return -EBADF;
if (descriptor->isBlocking()) {
if (!descriptor->hasDataAvailableForRead()) {
m_fdBlockedOnRead = fd;
block(BlockedRead);
sched_yield();
if (m_was_interrupted_while_blocked)
return -EINTR;
}
}
nread = descriptor->read((byte*)outbuf, nread);
#ifdef DEBUG_IO
kprintf("Process::sys$read: nread=%u\n", nread);
#endif
return nread;
}
int Process::sys$close(int fd)
{
auto* descriptor = file_descriptor(fd);
if (!descriptor)
return -EBADF;
int rc = descriptor->close();
m_file_descriptors[fd] = nullptr;
return rc;
}
int Process::sys$lstat(const char* path, Unix::stat* statbuf)
{
VALIDATE_USER_WRITE(statbuf, sizeof(Unix::stat));
int error;
auto descriptor = VirtualFileSystem::the().open(move(path), error, O_NOFOLLOW_NOERROR, cwdInode());
if (!descriptor)
return error;
descriptor->stat(statbuf);
return 0;
}
int Process::sys$stat(const char* path, Unix::stat* statbuf)
{
VALIDATE_USER_WRITE(statbuf, sizeof(Unix::stat));
int error;
auto descriptor = VirtualFileSystem::the().open(move(path), error, 0, cwdInode());
if (!descriptor)
return error;
descriptor->stat(statbuf);
return 0;
}
int Process::sys$readlink(const char* path, char* buffer, size_t size)
{
VALIDATE_USER_READ(path, strlen(path));
VALIDATE_USER_WRITE(buffer, size);
int error;
auto descriptor = VirtualFileSystem::the().open(path, error, O_RDONLY | O_NOFOLLOW_NOERROR, cwdInode());
if (!descriptor)
return error;
if (!descriptor->metadata().isSymbolicLink())
return -EINVAL;
auto contents = descriptor->readEntireFile();
if (!contents)
return -EIO; // FIXME: Get a more detailed error from VFS.
memcpy(buffer, contents.pointer(), min(size, contents.size()));
if (contents.size() + 1 < size)
buffer[contents.size()] = '\0';
return 0;
}
int Process::sys$chdir(const char* path)
{
VALIDATE_USER_READ(path, strlen(path));
int error;
auto descriptor = VirtualFileSystem::the().open(path, error, 0, cwdInode());
if (!descriptor)
return error;
if (!descriptor->isDirectory())
return -ENOTDIR;
m_cwd = descriptor->vnode();
return 0;
}
int Process::sys$getcwd(char* buffer, size_t size)
{
VALIDATE_USER_WRITE(buffer, size);
auto path = VirtualFileSystem::the().absolutePath(cwdInode());
if (path.isNull())
return -EINVAL;
if (size < path.length() + 1)
return -ERANGE;
strcpy(buffer, path.characters());
return -ENOTIMPL;
}
size_t Process::number_of_open_file_descriptors() const
{
size_t count = 0;
for (auto& descriptor : m_file_descriptors) {
if (descriptor)
++count;
}
return count;
}
int Process::sys$open(const char* path, int options)
{
#ifdef DEBUG_IO
kprintf("Process::sys$open(): PID=%u, path=%s {%u}\n", m_pid, path, pathLength);
#endif
VALIDATE_USER_READ(path, strlen(path));
if (number_of_open_file_descriptors() >= m_max_open_file_descriptors)
return -EMFILE;
int error;
auto descriptor = VirtualFileSystem::the().open(path, error, options, cwdInode());
if (!descriptor)
return error;
if (options & O_DIRECTORY && !descriptor->isDirectory())
return -ENOTDIR; // FIXME: This should be handled by VFS::open.
int fd = 0;
for (; fd < m_max_open_file_descriptors; ++fd) {
if (!m_file_descriptors[fd])
break;
}
m_file_descriptors[fd] = move(descriptor);
return fd;
}
int Process::sys$uname(utsname* buf)
{
VALIDATE_USER_WRITE(buf, sizeof(utsname));
strcpy(buf->sysname, "Serenity");
strcpy(buf->release, "1.0-dev");
strcpy(buf->version, "FIXME");
strcpy(buf->machine, "i386");
strcpy(buf->nodename, getHostname().characters());
return 0;
}
int Process::sys$isatty(int fd)
{
auto* descriptor = file_descriptor(fd);
if (!descriptor)
return -EBADF;
if (!descriptor->isTTY())
return -ENOTTY;
return 1;
}
int Process::sys$kill(pid_t pid, int signal)
{
if (pid == 0) {
// FIXME: Send to same-group processes.
ASSERT(pid != 0);
}
if (pid == -1) {
// FIXME: Send to all processes.
ASSERT(pid != -1);
}
ASSERT(pid != current->pid()); // FIXME: Support this scenario.
InterruptDisabler disabler;
auto* peer = Process::fromPID(pid);
if (!peer)
return -ESRCH;
peer->send_signal(signal, this);
return 0;
}
int Process::sys$sleep(unsigned seconds)
{
if (!seconds)
return 0;
sleep(seconds * TICKS_PER_SECOND);
if (m_wakeupTime > system.uptime) {
ASSERT(m_was_interrupted_while_blocked);
dword ticks_left_until_original_wakeup_time = m_wakeupTime - system.uptime;
return ticks_left_until_original_wakeup_time / TICKS_PER_SECOND;
}
return 0;
}
int Process::sys$gettimeofday(timeval* tv)
{
VALIDATE_USER_WRITE(tv, sizeof(tv));
InterruptDisabler disabler;
auto now = RTC::now();
tv->tv_sec = now;
tv->tv_usec = 0;
return 0;
}
uid_t Process::sys$getuid()
{
return m_uid;
}
gid_t Process::sys$getgid()
{
return m_gid;
}
uid_t Process::sys$geteuid()
{
return m_euid;
}
gid_t Process::sys$getegid()
{
return m_egid;
}
pid_t Process::sys$getpid()
{
return m_pid;
}
pid_t Process::sys$getppid()
{
return m_ppid;
}
mode_t Process::sys$umask(mode_t mask)
{
auto old_mask = m_umask;
m_umask = mask;
return old_mask;
}
pid_t Process::sys$waitpid(pid_t waitee, int* wstatus, int options)
{
if (wstatus)
VALIDATE_USER_WRITE(wstatus, sizeof(int));
InterruptDisabler disabler;
if (!Process::fromPID(waitee))
return -1;
m_waitee = waitee;
m_waitee_status = 0;
block(BlockedWait);
sched_yield();
if (m_was_interrupted_while_blocked)
return -EINTR;
if (wstatus)
*wstatus = m_waitee_status;
return m_waitee;
}
void Process::unblock()
{
ASSERT(m_state != Process::Runnable && m_state != Process::Running);
system.nblocked--;
m_state = Process::Runnable;
}
void Process::block(Process::State state)
{
ASSERT(current->state() == Process::Running);
system.nblocked++;
m_was_interrupted_while_blocked = false;
set_state(state);
}
void block(Process::State state)
{
current->block(state);
sched_yield();
}
void sleep(DWORD ticks)
{
ASSERT(current->state() == Process::Running);
current->setWakeupTime(system.uptime + ticks);
current->block(Process::BlockedSleep);
sched_yield();
}
Process* Process::kernelProcess()
{
ASSERT(s_kernelProcess);
return s_kernelProcess;
}
bool Process::isValidAddressForKernel(LinearAddress laddr) const
{
// We check extra carefully here since the first 4MB of the address space is identity-mapped.
// This code allows access outside of the known used address ranges to get caught.
InterruptDisabler disabler;
if (laddr.get() >= ksyms().first().address && laddr.get() <= ksyms().last().address)
return true;
if (is_kmalloc_address((void*)laddr.get()))
return true;
return validate_user_read(laddr);
}
bool Process::validate_user_read(LinearAddress laddr) const
{
InterruptDisabler disabler;
return MM.validate_user_read(*this, laddr);
}
bool Process::validate_user_write(LinearAddress laddr) const
{
InterruptDisabler disabler;
return MM.validate_user_write(*this, laddr);
}
pid_t Process::sys$getsid(pid_t pid)
{
if (pid == 0)
return m_sid;
InterruptDisabler disabler;
auto* process = Process::fromPID(pid);
if (!process)
return -ESRCH;
if (m_sid != process->m_sid)
return -EPERM;
return process->m_sid;
}
pid_t Process::sys$setsid()
{
InterruptDisabler disabler;
bool found_process_with_same_pgid_as_my_pid = false;
forEachProcess([&] (auto& process) {
if (process.pgid() == pid()) {
found_process_with_same_pgid_as_my_pid = true;
return false;
}
return true;
});
if (found_process_with_same_pgid_as_my_pid)
return -EPERM;
m_sid = m_pid;
m_pgid = m_pid;
return m_sid;
}
pid_t Process::sys$getpgid(pid_t pid)
{
if (pid == 0)
return m_pgid;
InterruptDisabler disabler; // FIXME: Use a ProcessHandle
auto* process = Process::fromPID(pid);
if (!process)
return -ESRCH;
return process->m_pgid;
}
pid_t Process::sys$getpgrp()
{
return m_pgid;
}
static pid_t get_sid_from_pgid(pid_t pgid)
{
InterruptDisabler disabler;
auto* group_leader = Process::fromPID(pgid);
if (!group_leader)
return -1;
return group_leader->sid();
}
int Process::sys$setpgid(pid_t specified_pid, pid_t specified_pgid)
{
InterruptDisabler disabler; // FIXME: Use a ProcessHandle
pid_t pid = specified_pid ? specified_pid : m_pid;
if (specified_pgid < 0)
return -EINVAL;
auto* process = Process::fromPID(pid);
if (!process)
return -ESRCH;
pid_t new_pgid = specified_pgid ? specified_pgid : process->m_pid;
pid_t current_sid = get_sid_from_pgid(process->m_pgid);
pid_t new_sid = get_sid_from_pgid(new_pgid);
if (current_sid != new_sid) {
// Can't move a process between sessions.
return -EPERM;
}
// FIXME: There are more EPERM conditions to check for here..
process->m_pgid = new_pgid;
return 0;
}
pid_t Process::sys$tcgetpgrp(int fd)
{
auto* descriptor = file_descriptor(fd);
if (!descriptor)
return -EBADF;
if (!descriptor->isTTY())
return -ENOTTY;
auto& tty = *descriptor->tty();
if (&tty != m_tty)
return -ENOTTY;
return tty.pgid();
}
int Process::sys$tcsetpgrp(int fd, pid_t pgid)
{
if (pgid < 0)
return -EINVAL;
if (get_sid_from_pgid(pgid) != m_sid)
return -EINVAL;
auto* descriptor = file_descriptor(fd);
if (!descriptor)
return -EBADF;
if (!descriptor->isTTY())
return -ENOTTY;
auto& tty = *descriptor->tty();
if (&tty != m_tty)
return -ENOTTY;
tty.set_pgid(pgid);
return 0;
}
int Process::sys$getdtablesize()
{
return m_max_open_file_descriptors;
}
int Process::sys$dup(int old_fd)
{
auto* descriptor = file_descriptor(old_fd);
if (!descriptor)
return -EBADF;
if (number_of_open_file_descriptors() == m_max_open_file_descriptors)
return -EMFILE;
int new_fd = 0;
for (; new_fd < m_max_open_file_descriptors; ++new_fd) {
if (!m_file_descriptors[new_fd])
break;
}
m_file_descriptors[new_fd] = descriptor;
return new_fd;
}
int Process::sys$dup2(int old_fd, int new_fd)
{
auto* descriptor = file_descriptor(old_fd);
if (!descriptor)
return -EBADF;
if (number_of_open_file_descriptors() == m_max_open_file_descriptors)
return -EMFILE;
m_file_descriptors[new_fd] = descriptor;
return new_fd;
}
Unix::sighandler_t Process::sys$signal(int signum, Unix::sighandler_t handler)
{
// FIXME: Fail with -EINVAL if attepmting to catch or ignore SIGKILL or SIGSTOP.
if (signum >= 32)
return (Unix::sighandler_t)-EINVAL;
dbgprintf("sys$signal: %d => L%x\n", signum, handler);
return nullptr;
}
int Process::sys$sigaction(int signum, const Unix::sigaction* act, Unix::sigaction* old_act)
{
// FIXME: Fail with -EINVAL if attepmting to change action for SIGKILL or SIGSTOP.
if (signum >= 32)
return -EINVAL;
VALIDATE_USER_READ(act, sizeof(Unix::sigaction));
InterruptDisabler disabler; // FIXME: This should use a narrower lock.
auto& action = m_signal_action_data[signum];
if (old_act) {
VALIDATE_USER_WRITE(old_act, sizeof(Unix::sigaction));
old_act->sa_flags = action.flags;
old_act->sa_restorer = (decltype(old_act->sa_restorer))action.restorer.get();
old_act->sa_sigaction = (decltype(old_act->sa_sigaction))action.handler_or_sigaction.get();
}
action.restorer = LinearAddress((dword)act->sa_restorer);
action.flags = act->sa_flags;
action.handler_or_sigaction = LinearAddress((dword)act->sa_sigaction);
return 0;
}
int Process::sys$getgroups(int count, gid_t* gids)
{
if (count < 0)
return -EINVAL;
ASSERT(m_gids.size() < MAX_PROCESS_GIDS);
if (!count)
return m_gids.size();
if (count != m_gids.size())
return -EINVAL;
VALIDATE_USER_WRITE(gids, sizeof(gid_t) * count);
size_t i = 0;
for (auto gid : m_gids)
gids[i++] = gid;
return 0;
}
int Process::sys$setgroups(size_t count, const gid_t* gids)
{
if (!is_root())
return -EPERM;
if (count >= MAX_PROCESS_GIDS)
return -EINVAL;
VALIDATE_USER_READ(gids, sizeof(gid_t) * count);
m_gids.clear();
m_gids.set(m_gid);
for (size_t i = 0; i < count; ++i)
m_gids.set(gids[i]);
return 0;
}
|