summaryrefslogtreecommitdiff
path: root/exec/exec.c
blob: 7ff998266d3f51ba37169e6eab956d83904869ea (plain)
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
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
/* GNU Hurd standard exec server.
   Copyright (C) 1992, 1993, 1994, 1995 Free Software Foundation, Inc.
   Written by Roland McGrath.

   #ifdef BFD
   Can exec any executable format the BFD library understands
   to be for this flavor of machine.
   #endif
   #ifdef AOUT
   Can exec a.out format.
   #endif

This file is part of the GNU Hurd.

The GNU Hurd 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, or (at your option)
any later version.

The GNU Hurd 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 the GNU Hurd; see the file COPYING.  If not, write to
the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */

#include <errno.h>
#include <mach.h>
#include <mach/notify.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/stat.h>
#include <hurd.h>
#include <hurd/startup.h>
#include <hurd/shared.h>
#include <hurd/fsys.h>
#include <hurd/exec.h>
#include <hurd/paths.h>
#include <fcntl.h>
#include "exec_S.h"
#include "fsys_S.h"
#include "notify_S.h"

/* Default: BFD or a.out?  */
#if	!defined (BFD) && !defined (AOUT)
#define	AOUT
#endif


#ifdef	BFD
#include <bfd.h>

extern error_t bfd_mach_host_arch_mach (host_t host,
					enum bfd_architecture *arch,
					long int *machine);
#else
#include A_OUT_H

extern error_t aout_mach_host_machine (host_t host, int *host_machine);
#endif


/* Data shared between check, check_section,
   load, load_section, and finish.  */
struct execdata
  {
    /* Passed out to caller.  */
    error_t error;

    /* Set by check.  */
    vm_address_t entry;
    FILE stream;
    file_t file;
#ifdef	BFD
    bfd *bfd;
#else
    struct exec *header, headbuf;
#endif
    memory_object_t filemap, cntlmap;
    struct shared_io *cntl;
    char *file_data;		/* File data if already copied in core.  */
    off_t file_size;
    size_t optimal_block;	/* Optimal size for io_read from file.  */

    /* Set by caller of load.  */
    task_t task;

#ifdef	BFD
    /* Vector indexed by section index,
       information passed from check_section to load_section.
       Set by caller of check_section and load.  */
    vm_offset_t *locations;
#endif
  };

#ifdef	BFD
/* A BFD whose architecture and machine type are those of the host system.  */
static bfd_arch_info_type host_bfd_arch_info;
static bfd host_bfd = { arch_info: &host_bfd_arch_info };
#else
static enum machine_type host_machine; /* a.out machine_type of the host.  */
#endif

static file_t realnode;
static mach_port_t execserver;	/* Port doing exec protocol.  */
static mach_port_t fsys;	/* Port doing fsys protocol.  */
static mach_port_t request_portset; /* Portset we receive on.  */
static mach_port_t procserver;	/* our proc port */
char *exec_version = "0.0 pre-alpha";
char **save_argv;

/* Standard exec data for secure execs.  */
static mach_port_t *std_ports;
static int *std_ints;
static size_t std_nports, std_nints;


#ifdef	BFD
/* Return a Hurd error code corresponding to the most recent BFD error.  */
static error_t
b2he (error_t deflt)
{
  switch (bfd_get_error ())
    {
    case bfd_error_system_call:
      return errno;

    case bfd_error_no_memory:
      return ENOMEM;

    default:
      return deflt;
    }
}
#else
#define	b2he()	a2he (errno)
#endif

static void check_gzip (struct execdata *);

#ifdef	BFD

/* Check a section, updating the `locations' vector [BFD].  */
static void
check_section (bfd *bfd, asection *sec, void *userdata)
{
  struct execdata *u = userdata;
  vm_address_t addr;

  if (u->error)
    return;

  if (!(sec->flags & (SEC_ALLOC|SEC_LOAD)) ||
      (sec->flags & SEC_NEVER_LOAD))
    /* Nothing to do for this section.  */
    return;

  addr = (vm_address_t) sec->vma;

  if (sec->flags & SEC_LOAD)
    {
      u->locations[sec->index] = sec->filepos;
      if ((off_t) sec->filepos < 0 || (off_t) sec->filepos > u->file_size)
	u->error = EINVAL;
    }
}
#endif

enum section { text, data, bss };

/* Load or allocate a section.  */
static void
#ifdef	BFD
load_section (bfd *bfd, asection *sec, void *userdata)
#else
load_section (enum section section, struct execdata *u)
#endif
{
#ifdef	BFD
  struct execdata *u = userdata;
#endif
  vm_address_t addr = 0;
  vm_offset_t filepos = 0;
  vm_size_t secsize = 0;
  vm_prot_t vm_prot;

  if (u->error)
    return;

#ifdef	BFD
  if (sec->flags & SEC_NEVER_LOAD)
    /* Nothing to do for this section.  */
    return;
#endif

  vm_prot = VM_PROT_READ | VM_PROT_WRITE | VM_PROT_EXECUTE;

#ifdef	BFD
  addr = (vm_address_t) sec->vma;
  filepos = u->locations[sec->index];
  secsize = sec->_raw_size;
  if (sec->flags & (SEC_READONLY|SEC_ROM))
    vm_prot &= ~VM_PROT_WRITE;
#else
  switch (section)
    {
    case text:
      addr = (vm_address_t) N_TXTADDR (*u->header);
      filepos = (vm_offset_t) N_TXTOFF (*u->header);
      secsize = N_TXTLEN (*u->header);
      vm_prot &= ~VM_PROT_WRITE;
      break;
    case data:
      addr = (vm_address_t) N_DATADDR (*u->header);
      filepos = (vm_offset_t) N_DATOFF (*u->header);
      secsize = N_DATLEN (*u->header);
      break;
    case bss:
      addr = (vm_address_t) N_BSSADDR (*u->header);
      secsize = N_BSSLEN (*u->header);
      break;
    }
#endif

  if (
#ifdef	BFD
      sec->flags & SEC_LOAD
#else
      section != bss
#endif
      )
    {
      vm_address_t mapstart = round_page (addr);

      /* Allocate space in the task and write CONTENTS into it.  */
      void write_to_task (vm_address_t mapstart, vm_size_t size,
			  vm_prot_t vm_prot, vm_address_t contents)
	{
	  vm_size_t off = size % vm_page_size;
	  /* Allocate with vm_map to set max protections.  */
	  u->error = vm_map (u->task,
			     &mapstart, size, 0, 0,
			     MACH_PORT_NULL, 0, 1,
			     vm_prot|VM_PROT_WRITE,
			     VM_PROT_READ|VM_PROT_WRITE|VM_PROT_EXECUTE,
			     VM_INHERIT_COPY);
	  if (! u->error && size >= vm_page_size)
	    u->error = vm_write (u->task, mapstart, contents, size - off);
	  if (! u->error && off != 0)
	    {
	      vm_address_t page = 0;
	      u->error = vm_allocate (mach_task_self (),
				      &page, vm_page_size, 1);
	      if (! u->error)
		{
		  memcpy ((void *) page,
			  (void *) (contents + (size - off)),
			  off);
		  u->error = vm_write (u->task, mapstart + (size - off),
				       page, vm_page_size);
		  vm_deallocate (mach_task_self (), page, vm_page_size);
		}
	    }
	  /* Reset the current protections to the desired state.  */
	  if (! u->error && (vm_prot & VM_PROT_WRITE) == 0)
	    u->error = vm_protect (u->task, mapstart, size, 0, vm_prot);
	}

      if (mapstart - addr < secsize)
	{
	  /* MAPSTART is the first page that starts inside the section.
	     Map all the pages that start inside the section.  */

#ifdef	BFD
#define SECTION_IN_MEMORY_P	(sec->flags & SEC_IN_MEMORY)
#define SECTION_CONTENTS	sec->contents
#else
#define SECTION_IN_MEMORY_P	(u->file_data != NULL)
#define SECTION_CONTENTS	(u->file_data + filepos)
#endif
	  if (SECTION_IN_MEMORY_P)
	    /* Data is already in memory; write it into the task.  */
	    write_to_task (mapstart, secsize - (mapstart - addr), vm_prot,
			   (vm_address_t) SECTION_CONTENTS
			   + (mapstart - addr));
	  else if (u->filemap != MACH_PORT_NULL)
	    /* Map the data into the task directly from the file.  */
	    u->error = vm_map (u->task,
			       &mapstart, secsize - (mapstart - addr), 0, 0,
			       u->filemap, filepos + (mapstart - addr), 1, 
			       vm_prot,
			       VM_PROT_READ|VM_PROT_WRITE|VM_PROT_EXECUTE,
			       VM_INHERIT_COPY);
	  else
	    {
	      /* Cannot map the data.  Read it into a buffer and vm_write
		 it into the task.  */
	      void *buf;
	      const vm_size_t size = secsize - (mapstart - addr);
	      u->error = vm_allocate (mach_task_self (),
				      (vm_address_t *) &buf, size, 1);
	      if (! u->error)
		{
		  if (fseek (&u->stream,
			     filepos + (mapstart - addr), SEEK_SET) ||
		      fread (buf, size, 1, &u->stream) != 1)
		    u->error = errno;
		  else
		    write_to_task (mapstart, size, vm_prot,
				   (vm_address_t) buf);
		  vm_deallocate (mach_task_self (), (vm_address_t) buf, size);
		}
	    }
	  if (u->error)
	    return;
	}

      if (mapstart > addr)
	{
	  /* We must read and copy in the space in the section before the
             first page boundary.  */
	  vm_address_t overlap_page = trunc_page (addr);
	  vm_address_t ourpage = 0;
	  vm_size_t size = 0;
	  void *readaddr;
	  size_t readsize;

#ifdef	AOUT
	  if (N_MAGIC (*u->header) == NMAGIC || N_MAGIC (*u->header) == ZMAGIC)
	    {
	      u->error = ENOEXEC;
	      goto maplose;
	    }
#endif

	  if (u->error = vm_read (u->task, overlap_page, vm_page_size,
				  &ourpage, &size))
	    {
	      if (u->error == KERN_INVALID_ADDRESS)
		{
		  /* The space is unallocated.  */
		  u->error = vm_allocate (u->task,
					  &overlap_page, vm_page_size, 0);
		  size = vm_page_size;
		  if (!u->error)
		    u->error = vm_allocate (mach_task_self (),
					    &ourpage, vm_page_size, 1);
		}
	      if (u->error)
		{
		maplose:
		  vm_deallocate (u->task, mapstart, secsize);
		  return;
		}
	    }

	  readaddr = (void *) (ourpage + (addr - overlap_page));
	  readsize = size - (addr - overlap_page);

	  if (SECTION_IN_MEMORY_P)
	    bcopy (SECTION_CONTENTS, readaddr, readsize);
	  else
	    if (fseek (&u->stream, filepos, SEEK_SET) ||
		fread (readaddr, readsize, 1, &u->stream) != 1)
	      {
		u->error = errno;
		goto maplose;
	      }
	  u->error = vm_write (u->task, overlap_page, ourpage, size);
	  if (u->error == KERN_PROTECTION_FAILURE)
	    {
	      /* The overlap page is not writable; the section
		 that appears in preceding memory is read-only.
		 Change the page's protection so we can write it.  */
	      u->error = vm_protect (u->task, overlap_page, size,
				     0, vm_prot | VM_PROT_WRITE);
	      if (!u->error)
		u->error = vm_write (u->task, overlap_page, ourpage, size);
	      /* If this section is not supposed to be writable either,
		 restore the page's protection to read-only.  */
	      if (!u->error && !(vm_prot & VM_PROT_WRITE))
		u->error = vm_protect (u->task, overlap_page, size,
				       0, vm_prot);
	    }
	  vm_deallocate (mach_task_self (), ourpage, size);
	  if (u->error)
	    goto maplose;
	}

      if (u->cntl)
	u->cntl->accessed = 1;
    }
#ifdef	BFD
  else if (sec->flags & SEC_ALLOC)
#else
  else
#endif
    {
      /* SEC_ALLOC: Allocate zero-filled memory for the section.  */

      vm_address_t mapstart = round_page (addr);

      if (mapstart - addr < secsize)
	{
	  /* MAPSTART is the first page that starts inside the section.
	     Allocate all the pages that start inside the section.  */

	  if (u->error = vm_allocate (u->task, &mapstart, 
				      secsize - (mapstart - addr), 0))
	    return;
	}

      if (mapstart > addr)
	{
	  /* Zero space in the section before the first page boundary.  */
	  vm_address_t overlap_page = trunc_page (addr);
	  vm_address_t ourpage = 0;
	  vm_size_t size = 0;
	  if (u->error = vm_read (u->task, overlap_page, vm_page_size,
				  &ourpage, &size))
	    {
	      vm_deallocate (u->task, mapstart, secsize);
	      return;
	    }
	  bzero ((void *) (ourpage + (addr - overlap_page)),
		 size - (addr - overlap_page));
	  u->error = vm_write (u->task, overlap_page, ourpage, size);
	  vm_deallocate (mach_task_self (), ourpage, size);
	}
    }
}

/* Do post-loading processing for a section.  This consists of peeking the
   pages of non-demand-paged executables.  */

static void
#ifdef	BFD
postload_section (bfd *bfd, asection *sec, void *userdata)
#else
postload_section (enum section section, struct execdata *u)
#endif
{
#ifdef	BFD
  struct execdata *u = userdata;
#endif
  vm_address_t addr = 0;
  vm_size_t secsize = 0;

#ifdef	BFD
  addr = (vm_address_t) sec->vma;
  secsize = sec->_raw_size;
#else
  switch (section)
    {
    case text:
      addr = (vm_address_t) N_TXTADDR (*u->header);
      secsize = N_TXTLEN (*u->header);
      break;
    case data:
      addr = (vm_address_t) N_DATADDR (*u->header);
      secsize = N_DATLEN (*u->header);
      break;
    case bss:
      addr = (vm_address_t) N_BSSADDR (*u->header);
      secsize = N_BSSLEN (*u->header);
      break;
    }
#endif

  if (
#ifdef	AOUT
      section != bss && N_MAGIC (*u->header) == NMAGIC
#else
      (sec->flags & SEC_LOAD) && !(bfd->flags & D_PAGED)
#endif
      )
    {
      /* Pre-load the section by peeking every mapped page.  */
      vm_address_t myaddr, a;
      vm_size_t mysize;
      myaddr = 0;
	  
      /* We have already mapped the file into the task in load_section.
	 Now read from the task's memory into our own address space so we
	 can peek each page and cause it to be paged in.  */
      if (u->error = vm_read (u->task, trunc_page (addr), round_page (secsize),
			      &myaddr, &mysize))
	return;

      /* Peek at the first word of each page.  */
      for (a = ((myaddr + mysize) & ~(vm_page_size - 1));
	   a >= myaddr; a -= vm_page_size)
	/* Force it to be paged in.  */
	(void) *(volatile int *) a;

      vm_deallocate (mach_task_self (), myaddr, mysize);
    }
}



/* stdio input-room function.  */
static int
input_room (FILE *f)
{
  struct execdata *e = f->__cookie;
  const size_t size = e->file_size;
  size_t offset = 0;

  if (f->__target >= size)
    {
      f->__eof = 1;
      return EOF;
    }

  if (e->filemap == MACH_PORT_NULL)
    {
      mach_msg_type_number_t nread = f->__bufsize;
      char *buffer = f->__buffer;
      if (e->error = io_read (e->file, &buffer, &nread,
			      f->__target, e->optimal_block))
	{
	  errno = e->error;
	  f->__error = 1;
	  return EOF;
	}
      if (buffer != f->__buffer)
	{
	  /* The data was returned out of line.  Discard the old buffer.  */
	  vm_deallocate (mach_task_self (), (vm_address_t) f->__buffer,
			 f->__bufsize);
	  f->__buffer = buffer;
	  f->__bufsize = round_page (nread);
	}

      f->__get_limit = f->__buffer + nread;
    }
  else
    {
      /* Deallocate the old mapping area.  */
      if (f->__buffer != NULL)
	vm_deallocate (mach_task_self (), (vm_address_t) f->__buffer,
		       f->__bufsize);
      f->__buffer = NULL;

      /* Make sure our mapping is page-aligned in the file.  */
      offset = f->__target % vm_page_size;
      if (offset != 0)
	f->__target -= offset;

      /* Map the data from the file.  */
      if (vm_map (mach_task_self (),
		  (vm_address_t *) &f->__buffer, vm_page_size, 0, 1,
		  e->filemap, f->__target, 1, VM_PROT_READ, VM_PROT_READ,
		  VM_INHERIT_NONE))
	{
	  errno = EIO;
	  f->__error = 1;
	  return EOF;
	}
      f->__bufsize = vm_page_size;

      if (e->cntl)
	e->cntl->accessed = 1;

      if (f->__target + f->__bufsize > size)
	f->__get_limit = f->__buffer + (size - f->__target);
      else
	f->__get_limit = f->__buffer + f->__bufsize;
    }

  f->__offset = f->__target;
  f->__bufp = f->__buffer + offset;

  if (f->__get_limit == f->__buffer)
    {
      f->__eof = 1;
      return EOF;
    }

  return (unsigned char) *f->__bufp++;
}

static int
close_exec_stream (void *cookie)
{
  struct execdata *e = cookie;

  if (e->stream.__buffer != NULL)
    vm_deallocate (mach_task_self (), (vm_address_t) e->stream.__buffer,
		   e->stream.__bufsize);

  return 0;
}


/* Prepare to check and load FILE.  */
static inline void
prepare (file_t file, struct execdata *e)
{
  e->file = file;

#ifdef	BFD
  e->bfd = NULL;
#endif
  e->file_data = NULL;
  e->cntl = NULL;
  e->filemap = MACH_PORT_NULL;
  e->cntlmap = MACH_PORT_NULL;

  {
    memory_object_t rd, wr;
    if (e->error = io_map (file, &rd, &wr))
      return;
    if (wr != MACH_PORT_NULL)
      mach_port_deallocate (mach_task_self (), wr);
    if (rd == MACH_PORT_NULL)
      {
	e->error = EBADF;	/* ? XXX */
	return;
      }
    e->filemap = rd;

    e->error = /* io_map_cntl (file, &e->cntlmap) */ EOPNOTSUPP; /* XXX */
    if (e->error)
      {
	/* No shared page.  Do a stat to find the file size.  */
	struct stat st;
	if (e->error = io_stat (file, &st))
	  return;
	e->file_size = st.st_size;
	e->optimal_block = st.st_blksize;
      }
    else
      e->error = vm_map (mach_task_self (), (vm_address_t *) &e->cntl,
			 vm_page_size, 0, 1, e->cntlmap, 0, 0,
			 VM_PROT_READ|VM_PROT_WRITE, 
			 VM_PROT_READ|VM_PROT_WRITE, VM_INHERIT_NONE);

    if (e->cntl)
      while (1)
	{
	  spin_lock (&e->cntl->lock);
	  switch (e->cntl->conch_status)
	    {
	    case USER_COULD_HAVE_CONCH:
	      e->cntl->conch_status = USER_HAS_CONCH;
	    case USER_HAS_CONCH:
	      spin_unlock (&e->cntl->lock);
	      /* Break out of the loop.  */
	      break;
	    case USER_RELEASE_CONCH:
	    case USER_HAS_NOT_CONCH:
	    default:		/* Oops.  */
	      spin_unlock (&e->cntl->lock);
	      if (e->error = io_get_conch (e->file))
		return;
	      /* Continue the loop.  */
	      continue;
	    }

	  /* Get here if we are now IT.  */
	  e->file_size = 0;
	  if (e->cntl->use_file_size)
	    e->file_size = e->cntl->file_size;
	  if (e->cntl->use_read_size && e->cntl->read_size > e->file_size)
	    e->file_size = e->cntl->read_size;
	  break;
	}
  }

  /* Open a stdio stream to do mapped i/o to the file.  */
  memset (&e->stream, 0, sizeof (e->stream));
  e->stream.__magic = _IOMAGIC;
  e->stream.__mode.__read = 1;
  e->stream.__userbuf = 1;
  e->stream.__room_funcs.__input = input_room;
  /* This never gets called, but fseek returns ESPIPE if it's null.  */
  e->stream.__io_funcs.seek = __default_io_functions.seek;
  e->stream.__io_funcs.close = close_exec_stream;
  e->stream.__cookie = e;
  e->stream.__seen = 1;

#ifdef BFD
  e->bfd = bfd_openstreamr (NULL, NULL, &e->stream);
  if (e->bfd == NULL)
    {
      e->error = b2he (ENOEXEC);
      return;
    }
#endif
}

/* Check the magic number, etc. of the file.
   On successful return, the caller must allocate the
   E->locations vector, and map check_section over the BFD.  */

static void
check (struct execdata *e)
{
#ifdef	BFD
  bfd_set_error (bfd_error_no_error);
  if (!bfd_check_format (e->bfd, bfd_object))
    {
      e->error = b2he (ENOEXEC);
      return;
    }
  else if (/* !(e->bfd->flags & EXEC_P) || XXX */
	   (host_bfd.arch_info->compatible = e->bfd->arch_info->compatible,
	    bfd_arch_get_compatible (&host_bfd, e->bfd)) != host_bfd.arch_info)
    {
      /* This file is of a recognized binary file format, but it is not
	 executable on this machine.  */
      e->error = b2he (EINVAL);
      return;
    }

  e->entry = e->bfd->start_address;
#else
  /* Map in the a.out header.  */
  if (e->file_size < sizeof (*e->header))
    {
      e->error = EINVAL;
      return;
    }
  e->header = NULL;
  if (e->file_data)
    /* Data already in core.  Just use it.  */
    e->header = (void *) e->file_data;
  else if (e->filemap == MACH_PORT_NULL)
    {
      /* Cannot map the file.  Read the header into a buffer.  */
      if (fread (&e->headbuf, sizeof e->headbuf, 1, &e->stream) != 1)
	{
	  e->error = errno;
	  return;
	}
      e->header = &e->headbuf;
    }
  else
    if (e->error = vm_map (mach_task_self (),
			   (vm_address_t *) &e->header, sizeof (*e->header),
			   0, 1, e->filemap, 0, 1, VM_PROT_READ, VM_PROT_READ,
			   VM_INHERIT_NONE))
      return;
  if (N_BADMAG (*e->header))
    {
      e->error = ENOEXEC;
      return;
    }
  if (N_MACHTYPE (*e->header) && N_MACHTYPE (*e->header) != host_machine)
    {
      e->error = EINVAL;
      return;
    }

  e->entry = e->header->a_entry;
#endif
}


/* Load the file.  */
static void
load (task_t usertask, struct execdata *e)
{
  if (e->error)
    return;

  e->task = usertask;
#ifdef	BFD
  bfd_map_over_sections (e->bfd, load_section, e);
#else
  load_section (text, e);
  load_section (data, e);
  load_section (bss, e);
#endif
}

/* Do post-loading processing on the task.  */
static void
postload (struct execdata *e)
{
  if (e->error)
    return;

#ifdef	BFD
  bfd_map_over_sections (e->bfd, postload_section, e);
#else
  postload_section (text, e);
  postload_section (data, e);
  postload_section (bss, e);
#endif
}


/* Release the conch and clean up mapping the file and control page.  */
static void
finish_mapping (struct execdata *e)
{
  if (e->cntl != NULL)
    {
      spin_lock (&e->cntl->lock);
      if (e->cntl->conch_status == USER_RELEASE_CONCH)
	{
	  spin_unlock (&e->cntl->lock);
	  io_release_conch (e->file);
	}
      else
	{
	  e->cntl->conch_status = USER_HAS_NOT_CONCH;
	  spin_unlock (&e->cntl->lock);
	}
      vm_deallocate (mach_task_self (), (vm_address_t) e->cntl, vm_page_size);
      e->cntl = NULL;
    }
  if (e->filemap != MACH_PORT_NULL)
    {
      mach_port_deallocate (mach_task_self (), e->filemap);
      e->filemap = MACH_PORT_NULL;
    }
  if (e->cntlmap != MACH_PORT_NULL)
    {
      mach_port_deallocate (mach_task_self (), e->cntlmap);
      e->cntlmap = MACH_PORT_NULL;
    }
}
      
/* Clean up after reading the file (need not be completed).  */
static void
finish (struct execdata *e)
{
  finish_mapping (e);
#ifdef	BFD
  if (e->bfd != NULL)
    bfd_close (e->bfd);
  else
    fclose (&e->stream);
#else
  fclose (&e->stream);
  if (e->header != NULL && e->header != &e->headbuf &&
      e->header != (void *) e->file_data)
    vm_deallocate (mach_task_self (),
		   (vm_address_t) e->header, sizeof (*e->header));
  e->header = NULL;
#endif
  if (e->file != MACH_PORT_NULL)
    {
      mach_port_deallocate (mach_task_self (), e->file);
      e->file = MACH_PORT_NULL;
    }
}

/* Check the file for being a gzip'd image.  Return with ENOEXEC means not
   a valid gzip file; return with another error means lossage in decoding;
   return with zero means the file was uncompressed into memory which E now
   points to, and `check' can be run again.  */

static void
check_gzip (struct execdata *earg)
{
  struct execdata *e = earg;
  /* Entry points to unzip engine.  */
  int get_method (int);
  void unzip (int, int);
  extern long int bytes_out;
  /* Callbacks from unzip for I/O and error interface.  */
  extern int (*unzip_read) (char *buf, size_t maxread);
  extern void (*unzip_write) (const char *buf, size_t nwrite);
  extern void (*unzip_read_error) (void);
  extern void (*unzip_error) (const char *msg);

  char *zipdata = NULL;
  size_t zipdatasz = 0;
  FILE *zipout = NULL;
  jmp_buf ziperr;
  int zipread (char *buf, size_t maxread)
    {
      return fread (buf, 1, maxread, &e->stream);
    }
  void zipwrite (const char *buf, size_t nwrite)
    {
      if (fwrite (buf, nwrite, 1, zipout) != 1)
	longjmp (ziperr, 1);
    }
  void ziprderr (void)
    {
      longjmp (ziperr, 2);
    }
  void ziperror (const char *msg)
    {
      errno = ENOEXEC;
      longjmp (ziperr, 2);
    }

  unzip_read = zipread;
  unzip_write = zipwrite;
  unzip_read_error = ziprderr;
  unzip_error = ziperror;

  if (setjmp (ziperr))
    {
      /* Error in unzipping jumped out.  */
      if (zipout)
	{
	  fclose (zipout);
	  free (zipdata);
	}
      e->error = errno;
      return;
    }

  if (get_method (0) != 0)
    {
      /* Not a happy gzip file.  */
      e->error = ENOEXEC;
      return;
    }

  /* Matched gzip magic number.  Ready to unzip.
     Set up the output stream and let 'er rip.  */

  zipout = open_memstream (&zipdata, &zipdatasz);
  if (! zipout)
    {
      e->error = errno;
      return;
    }

  /* Call the gunzip engine.  */
  bytes_out = 0;
  unzip (17, 23);		/* Arguments ignored.  */

  /* The output is complete.  Clean up the stream and store its resultant
     buffer and size in the execdata as the file contents.  */
  fclose (zipout);
  e->file_data = zipdata;
  e->file_size = zipdatasz;

  /* Clean up the old exec file stream's state.  */
  finish (e);

  /* Point the stream at the buffer of file data.  */
  memset (&e->stream, 0, sizeof (e->stream));
  e->stream.__magic = _IOMAGIC;
  e->stream.__mode.__read = 1;
  e->stream.__buffer = e->file_data;
  e->stream.__bufsize = e->file_size;
  e->stream.__get_limit = e->stream.__buffer + e->stream.__bufsize;
  e->stream.__bufp = e->stream.__buffer;
  e->stream.__seen = 1;

  e->error = 0;
}


static int
request_server (mach_msg_header_t *inp,
		mach_msg_header_t *outp)
{
  extern int notify_server (), exec_server (), fsys_server ();

  return (notify_server (inp, outp) ||
	  exec_server (inp, outp) ||
	  fsys_server (inp, outp));
}


/* Allocate SIZE bytes of storage, and make the
   resulting pointer a name for a new receive right.  */
static void *
alloc_recv (size_t size)
{
  void *obj = malloc (size);
  if (obj == NULL)
    return NULL;

  if (mach_port_allocate_name (mach_task_self (),
			       MACH_PORT_RIGHT_RECEIVE,
			       (mach_port_t) obj)
      == KERN_NAME_EXISTS)
    {
      void *new = alloc_recv (size); /* Bletch.  */
      free (obj);
      return new;
    }

  return obj;
}

/* Information kept around to be given to a new task
   in response to a message on the task's bootstrap port.  */
struct bootinfo
  {
    vm_address_t stack_base;
    vm_size_t stack_size;
    int flags;
    char *argv, *envp;
    size_t argvlen, envplen, dtablesize, nports, nints;
    mach_port_t *dtable, *portarray;
    int *intarray;
  };

static inline error_t
servercopy (void **arg, u_int argsize, boolean_t argcopy)
{
  if (argcopy)
    {
      /* ARG came in-line, so we must copy it.  */
      error_t error;
      void *copy;
      if (error = vm_allocate (mach_task_self (),
			       (vm_address_t *) &copy, argsize, 1))
	return error;
      bcopy (*arg, copy, argsize);
      *arg = copy;
    }
  return 0;
}

/* Put PORT into *SLOT.  If *SLOT isn't already null, then 
   mach_port_deallocate it first.  If AUTHENTICATE is not null, then
   do an io_reauthenticate transaction to determine the port to put in
   *SLOT.  If CONSUME is set, then don't create a new send right;
   otherwise do.  (It is an error for both CONSUME and AUTHENTICATE to be 
   set.) */
static void
set_init_port (mach_port_t port, mach_port_t *slot, auth_t authenticate,
	       int consume)
{
  mach_port_t ref;

  if (*slot != MACH_PORT_NULL)
    mach_port_deallocate (mach_task_self (), *slot);
  if (authenticate != MACH_PORT_NULL && port != MACH_PORT_NULL)
    {
      ref = mach_reply_port ();
      io_reauthenticate (port, ref, MACH_MSG_TYPE_MAKE_SEND);
      auth_user_authenticate (authenticate, port, 
			      ref, MACH_MSG_TYPE_MAKE_SEND, slot);
      mach_port_destroy (mach_task_self (), ref);
    }
  else
    {
      *slot = port;
      if (!consume && port != MACH_PORT_NULL)
	mach_port_mod_refs (mach_task_self (), port, MACH_PORT_RIGHT_SEND, 1);
    }
}

static error_t
do_exec (mach_port_t execserver,
	 file_t file,
	 task_t oldtask,
	 int flags,
	 char *argv, u_int argvlen, boolean_t argv_copy,
	 char *envp, u_int envplen, boolean_t envp_copy,
	 mach_port_t *dtable, u_int dtablesize, boolean_t dtable_copy,
	 mach_port_t *portarray, u_int nports, boolean_t portarray_copy,
	 int *intarray, u_int nints, boolean_t intarray_copy,
	 mach_port_t *deallocnames, u_int ndeallocnames,
	 mach_port_t *destroynames, u_int ndestroynames)
{
  struct execdata e;
  int finished = 0;
  task_t newtask = MACH_PORT_NULL;
  thread_t thread = MACH_PORT_NULL;
  struct bootinfo *boot = 0;
  int secure, defaults;

  /* Catch this error now, rather than later.  */
  if ((!std_ports || !std_ints) && (flags & (EXEC_SECURE|EXEC_DEFAULTS)))
    return EIEIO;

  /* Prepare E to read the file.  */
  prepare (file, &e);

  /* Check the file for validity first.  */
  check (&e);
  if (e.error == ENOEXEC)
    {
      /* See if it is a compressed image.  */
      check_gzip (&e);
      if (e.error == 0)
	/* The file was uncompressed into memory, and now E describes the
	   uncompressed image rather than the actual file.  Check it again
	   for a valid magic number.  */
	check (&e);
    }
#if 0
  if (e.error == ENOEXEC)
    /* Check for a #! executable file.  */
    check_hashbang (&e, replyport,
		    file, oldtask, flags,
		    argv, argvlen, argv_copy,
		    envp, envplen, envp_copy,
		    dtable, dtablesize, dtable_copy,
		    portarray, nports, portarray_copy,
		    intarray, nints, intarray_copy,
		    deallocnames, ndeallocnames,
		    destroynames, ndestroynames);
#endif
#ifdef	BFD
  if (! e.error)
    {
      e.locations = alloca (e.bfd->section_count * sizeof (vm_offset_t));
      bfd_map_over_sections (e.bfd, check_section, &e);
    }
#endif
  if (e.error)
    {
      finish (&e);
      return e.error;
    }

  /* Suspend the existing task before frobnicating it.  */
  if (oldtask != MACH_PORT_NULL && (e.error = task_suspend (oldtask)))
    return e.error;

  if (oldtask == MACH_PORT_NULL)
    flags |= EXEC_NEWTASK;

  if (flags & (EXEC_NEWTASK|EXEC_SECURE))
    {
      /* Create the new task.  If we are not being secure, then use OLDTASK
	 for the task_create RPC, in case it is something magical.  */	 
      if (e.error = task_create (flags & EXEC_SECURE || !oldtask ?
				 mach_task_self () : oldtask,
				 0, &newtask))
	goto out;
    }
  else
    {
      thread_array_t threads;
      mach_msg_type_number_t nthreads, i;

      /* Terminate all the threads of the old task.  */

      if (e.error = task_threads (oldtask, &threads, &nthreads))
	goto out;
      for (i = 0; i < nthreads; ++i)
	{
	  thread_terminate (threads[i]);
	  mach_port_deallocate (mach_task_self (), threads[i]);
	}
      vm_deallocate (mach_task_self (),
		     (vm_address_t) threads, nthreads * sizeof (thread_t));

      /* Deallocate the entire virtual address space of the task.  */

      vm_deallocate (oldtask,
		     VM_MIN_ADDRESS, VM_MAX_ADDRESS - VM_MIN_ADDRESS);

      /* Deallocate and destroy the ports requested by the caller.
	 These are ports the task wants not to lose if the exec call
	 fails, but wants removed from the new program task.  */

      for (i = 0; i < ndeallocnames; ++i)
	mach_port_deallocate (oldtask, deallocnames[i]);

      for (i = 0; i < ndestroynames; ++i)
	mach_port_destroy (oldtask, destroynames[i]);

      newtask = oldtask;
    }

  /* Load the file into the task.  */
  load (newtask, &e);
  if (e.error)
    goto out;

  /* Release the conch for the file.  */
  finish_mapping (&e);

  /* Further frobnicate the task after loading from the file.  */
  postload (&e);
  if (e.error)
    goto out;

  /* Clean up.  */
  finish (&e);
  finished = 1;

  /* Create the initial thread.  */
  if (e.error = thread_create (newtask, &thread))
    goto out;

  /* Store the data that we will give in response
     to the RPC on the new task's bootstrap port.  */

  boot = alloc_recv (sizeof (*boot));
  if (boot == NULL)
    {
      e.error = ENOMEM;
      goto out;
    }

  if (nports <= INIT_PORT_BOOTSTRAP)
    {
      mach_port_t *new;
      vm_allocate (mach_task_self (),
		   (vm_address_t *) &new,
		   INIT_PORT_MAX * sizeof (mach_port_t), 1);
      memcpy (new, portarray, nports * sizeof (mach_port_t));
      bzero (&new[nports], (INIT_PORT_MAX - nports) * sizeof (mach_port_t));
    }
  if (portarray[INIT_PORT_BOOTSTRAP] == MACH_PORT_NULL &&
      oldtask != MACH_PORT_NULL)
    task_get_bootstrap_port (oldtask, &portarray[INIT_PORT_BOOTSTRAP]);

  if (e.error = mach_port_insert_right (mach_task_self (),
					(mach_port_t) boot,
					(mach_port_t) boot,
					MACH_MSG_TYPE_MAKE_SEND))
    goto out;
  if (e.error = task_set_bootstrap_port (newtask, (mach_port_t) boot))
    goto out;
  mach_port_deallocate (mach_task_self (), (mach_port_t) boot);

  if (e.error = servercopy ((void **) &argv, argvlen, argv_copy))
    goto bootout;
  boot->argv = argv;
  boot->argvlen = argvlen;
  if (e.error = servercopy ((void **) &envp, envplen, envp_copy))
    goto bootout;
  boot->envp = envp;
  boot->envplen = envplen;
  if (e.error = servercopy ((void **) &dtable,
			    dtablesize * sizeof (mach_port_t),
			    dtable_copy))
    goto bootout;
  boot->dtable = dtable;
  boot->dtablesize = dtablesize;
  if (e.error = servercopy ((void **) &portarray,
			    nports * sizeof (mach_port_t),
			    portarray_copy))
    goto bootout;
  boot->portarray = portarray;
  boot->nports = nports;
  if (e.error = servercopy ((void **) &intarray,
			    nints * sizeof (mach_port_t),
			    intarray_copy))
    goto bootout;
  boot->intarray = intarray;
  boot->nints = nints;
  boot->flags = flags;

  {
    mach_port_t unused;
    mach_port_request_notification (mach_task_self (),
				    (mach_port_t) boot,
				    MACH_NOTIFY_NO_SENDERS, 0,
				    (mach_port_t) boot,
				    MACH_MSG_TYPE_MAKE_SEND_ONCE,
				    &unused);
  }

  secure = (flags & EXEC_SECURE);
  
  defaults = (flags & EXEC_DEFAULTS);
  
  if ((secure || defaults) && nports < INIT_PORT_MAX)
    {
      /* Allocate a new vector that is big enough.  */
      vm_allocate (mach_task_self (),
		   (vm_address_t *) &boot->portarray,
		   INIT_PORT_MAX * sizeof (mach_port_t),
		   1);
      memcpy (boot->portarray, portarray,
	      nports * sizeof (mach_port_t));
      vm_deallocate (mach_task_self (), (vm_address_t) portarray,
		     nports * sizeof (mach_port_t));
      nports = INIT_PORT_MAX;
    }

  /* Note that the paretheses on this first test are different from the others
     below it. */
  if ((secure || defaults)
      && boot->portarray[INIT_PORT_AUTH] == MACH_PORT_NULL)
    /* Q: Doesn't this let anyone run a program and make it
       get a root auth port? 
       A: No; the standard port for INIT_PORT_AUTH has no UID's at all.
       See init.trim/init.c (init_stdarrays).  */
    set_init_port (std_ports[INIT_PORT_AUTH], 
		   &boot->portarray[INIT_PORT_AUTH], 0, 0);
  if (secure || (defaults 
		 && boot->portarray[INIT_PORT_PROC] == MACH_PORT_NULL))
    {
      mach_port_t new;
      if (e.error = proc_task2proc (procserver, newtask, &new))
	goto bootout;

      set_init_port (new, &boot->portarray[INIT_PORT_PROC], 0, 1);

      /* XXX We should also call proc_setowner at this point. */
    }
  else if (oldtask != newtask && oldtask != MACH_PORT_NULL 
	   && nports > INIT_PORT_PROC
	   && boot->portarray[INIT_PORT_PROC] != MACH_PORT_NULL)
    {
      mach_port_t new;
      /* This task port refers to the old task; use it to fetch a new
	 one for the new task.  */
      if (e.error = proc_task2proc (boot->portarray[INIT_PORT_PROC], 
				    newtask, &new))
	goto bootout;
      set_init_port (new, &boot->portarray[INIT_PORT_PROC], 0, 1);
    }
  if (secure || (defaults
		 && boot->portarray[INIT_PORT_CRDIR] == MACH_PORT_NULL))
    set_init_port (std_ports[INIT_PORT_CRDIR],
		   &boot->portarray[INIT_PORT_CRDIR], 
		   boot->portarray[INIT_PORT_AUTH], 0);
  if (secure || (defaults && 
		 boot->portarray[INIT_PORT_CWDIR] == MACH_PORT_NULL))
    set_init_port (std_ports[INIT_PORT_CWDIR],
		   &boot->portarray[INIT_PORT_CWDIR],
		   boot->portarray[INIT_PORT_AUTH], 0);
  
  if ((secure || defaults) && nints < INIT_INT_MAX)
    {
      /* Allocate a new vector that is big enough.  */
      vm_allocate (mach_task_self (),
		   (vm_address_t *) &boot->intarray,
		   INIT_INT_MAX * sizeof (int),
		   1);
      memcpy (boot->intarray, intarray, nints * sizeof (int));
      vm_deallocate (mach_task_self (), (vm_address_t) intarray,
		     nints * sizeof (int));
      nints = INIT_INT_MAX;
    }

  if (secure)
    boot->intarray[INIT_UMASK] = std_ints ? std_ints[INIT_UMASK] : CMASK;
      
  if (nports > INIT_PORT_PROC)
    proc_mark_exec (boot->portarray[INIT_PORT_PROC]);

  /* Start up the initial thread at the entry point.  */
  boot->stack_base = 0, boot->stack_size = 0; /* Don't care about values.  */
  if (e.error = mach_setup_thread (newtask, thread, (void *) e.entry,
				   &boot->stack_base, &boot->stack_size))
    goto bootout;

  if (oldtask != newtask && oldtask != MACH_PORT_NULL)
    {
      /* The program is on its way.  The old task can be nuked.  */
      process_t proc;
      process_t psrv;

      /* Use the canonical proc server if secure, or there is none other.
	 When not secure, it is nice to let processes associate with
	 whatever proc server turns them on, regardless of which exec
	 itself is using.  */
      if ((flags & EXEC_SECURE)
	  || nports <= INIT_PORT_PROC
	  || boot->portarray[INIT_PORT_PROC] == MACH_PORT_NULL)
	psrv = procserver;
      else
	psrv = boot->portarray[INIT_PORT_PROC];

      /* XXX there is a race here for SIGKILLing the process. -roland
         I don't think it matters.  -mib */
      if (! proc_task2proc (psrv, oldtask, &proc))
	{
	  proc_reassign (proc, newtask);
	  mach_port_deallocate (mach_task_self (), proc);
	}
    }

  newtask = MACH_PORT_NULL;

 bootout:
  if (e.error)
    {
      mach_port_deallocate (mach_task_self (), (vm_address_t) boot);
      if (boot->portarray != portarray)
	vm_deallocate (mach_task_self (),
		       (vm_address_t) boot->portarray,
		       boot->nports * sizeof (mach_port_t));
      free (boot);
    }

 out:
  if (newtask != MACH_PORT_NULL)
    {
      task_terminate (newtask);
      mach_port_deallocate (mach_task_self (), newtask);
    }
  if (!finished)
    finish (&e);
  
  task_resume (oldtask);
  thread_resume (thread);

  if (thread != MACH_PORT_NULL)
    mach_port_deallocate (mach_task_self (), thread);

  mach_port_deallocate (mach_task_self (), oldtask);
  
  mach_port_move_member (mach_task_self (),
			 (mach_port_t) boot, request_portset);

  return e.error;
}

kern_return_t
S_exec_exec (mach_port_t execserver,
	     file_t file,
	     task_t oldtask,
	     int flags,
	     char *argv, u_int argvlen, boolean_t argv_copy,
	     char *envp, u_int envplen, boolean_t envp_copy,
	     mach_port_t *dtable, u_int dtablesize, boolean_t dtable_copy,
	     mach_port_t *portarray, u_int nports, boolean_t portarray_copy,
	     int *intarray, u_int nints, boolean_t intarray_copy,
	     mach_port_t *deallocnames, u_int ndeallocnames,
	     mach_port_t *destroynames, u_int ndestroynames)
{
  if (!(flags & EXEC_SECURE))
    {
      const char envar[] = "\0EXECSERVERS=";
      char *p = NULL;
      if (envplen >= sizeof (envar) &&
	  !memcmp (&envar[1], envp, sizeof (envar) - 2))
	p = envp - 1;
      else
	p = memmem (envp, envplen, envar, sizeof (envar) - 1);
      if (p != NULL)
	{
	  size_t len;
	  char *list;
	  int tried = 0;
	  p += sizeof (envar) - 1;
	  len = strlen (p) + 1;
	  list = alloca (len);
	  memcpy (list, p, len);
	  while (p = strsep (&list, ":"))
	    {
	      file_t server;
	      if (!hurd_file_name_lookup (portarray[INIT_PORT_CRDIR],
					  portarray[INIT_PORT_CWDIR],
					  p, 0, 0, &server))
		{
		  error_t err = (server == execserver ?
				 do_exec (server, file, oldtask, 0,
					  argv, argvlen, argv_copy,
					  envp, envplen, envp_copy,
					  dtable, dtablesize, dtable_copy,
					  portarray, nports, portarray_copy,
					  intarray, nints, intarray_copy,
					  deallocnames, ndeallocnames,
					  destroynames, ndestroynames) :
				 exec_exec (server,
					    file, MACH_MSG_TYPE_MOVE_SEND,
					    oldtask, 0,
					    argv, argvlen,
					    envp, envplen,
					    dtable, MACH_MSG_TYPE_MOVE_SEND,
					    dtablesize,
					    portarray, MACH_MSG_TYPE_MOVE_SEND,
					    nports,
					    intarray, nints,
					    deallocnames, ndeallocnames,
					    destroynames, ndestroynames));
		  mach_port_deallocate (mach_task_self (), server);
		  if (err != ENOEXEC)
		    return err;
		  tried = 1;
		}
	    }
	  if (tried)
	    /* At least one exec server got a crack at it and gave up.  */
	    return ENOEXEC;
	}
    }

  /* There were no user-specified exec servers,
     or none of them could be found.  */

  return do_exec (execserver, file, oldtask, flags,
		  argv, argvlen, argv_copy,
		  envp, envplen, envp_copy,
		  dtable, dtablesize, dtable_copy,
		  portarray, nports, portarray_copy,
		  intarray, nints, intarray_copy,
		  deallocnames, ndeallocnames,
		  destroynames, ndestroynames);
}

kern_return_t
S_exec_setexecdata (mach_port_t me,
		    mach_port_t *ports, u_int nports, int ports_copy,
		    int *ints, u_int nints, int ints_copy)
{
  error_t err;

  /* XXX needs authentication */

  if (nports < INIT_PORT_MAX || nints < INIT_INT_MAX)
    return EINVAL;

  if (std_ports)
    vm_deallocate (mach_task_self (), (vm_address_t)std_ports, 
		   std_nports * sizeof (mach_port_t));
  if (err = servercopy ((void **) &ports, nports * sizeof (mach_port_t),
			ports_copy))
    return err;

  std_ports = ports;
  std_nports = nports;

  if (std_ints)
    vm_deallocate (mach_task_self (), (vm_address_t)std_ints,
		   std_nints * sizeof (int));
  if (err = servercopy ((void **) &ints, nints * sizeof (int), ints_copy))
    return err;

  std_ints = ints;
  std_nints = nints;

  return 0;
}



/* fsys server.  */

kern_return_t
S_fsys_getroot (fsys_t fsys,
		mach_port_t dotdot,
		uid_t *uids, u_int nuids,
		gid_t *gids, u_int ngids,
		int flags,
		retry_type *retry,
		char *retry_name,
		file_t *rootfile,
		mach_msg_type_name_t *rootfilePoly)
{
  /* XXX eventually this should return a user-specific port which has an
     associated access-restricted realnode port which file ops get
     forwarded to.  */



  *rootfile = execserver;
  *rootfilePoly = MACH_MSG_TYPE_MAKE_SEND;

  *retry = FS_RETRY_NORMAL;
  *retry_name = '\0';
  return 0;
}

kern_return_t
S_fsys_goaway (fsys_t fsys, int flags)
{
  if (!(flags & FSYS_GOAWAY_FORCE))
    {
      mach_port_t *serving;
      mach_msg_type_number_t nserving, i;
      mach_port_get_set_status (mach_task_self (), request_portset,
				&serving, &nserving);
      for (i = 0; i < nserving; ++i)
	mach_port_deallocate (mach_task_self (), serving[i]);
      if (nserving > 2)
	/* Not just fsys and execserver.
	   We are also waiting on some bootstrap ports.  */
	return EBUSY;
    }
  mach_port_mod_refs (mach_task_self (), request_portset,
		      MACH_PORT_TYPE_RECEIVE, -1);
  return 0;
}

kern_return_t
S_fsys_startup (mach_port_t bootstrap,
		fsys_t control,
		mach_port_t *node,
		mach_msg_type_name_t *realnodePoly)
{
  return EOPNOTSUPP;
}

kern_return_t
S_fsys_syncfs (fsys_t fsys,
	       int wait,
	       int dochildren)
{
  return EOPNOTSUPP;
}

kern_return_t
S_fsys_mod_readonly (fsys_t fsys,
		     int readonly,
		     int force)
{
  return EOPNOTSUPP;
}

kern_return_t
S_fsys_getfile (fsys_t fsys,
		uid_t *uids,
		u_int nuids,
		uid_t *gids,
		u_int ngids,
		char *filehandle,
		u_int filehandlelen,
		mach_port_t *file,
		mach_msg_type_name_t *filetype)
{
  return EOPNOTSUPP;
}

kern_return_t
S_fsys_getpriv (fsys_t fsys,
		mach_port_t *hp,
		mach_port_t *dm,
		mach_port_t *tk)
{
  return EOPNOTSUPP;
}

kern_return_t
S_fsys_init (fsys_t fsys,
	     mach_port_t reply, mach_msg_type_name_t replytype,
	     mach_port_t ps,
	     mach_port_t ah)
{
  return EOPNOTSUPP;
}




/* RPC sent on the bootstrap port.  */

kern_return_t
S_exec_startup (mach_port_t port,
		vm_address_t *stack_base, vm_size_t *stack_size,
		int *flags,
		char **argvp, u_int *argvlen,
		char **envpp, u_int *envplen,
		mach_port_t **dtable, mach_msg_type_name_t *dtablepoly,
		u_int *dtablesize,
		mach_port_t **portarray, mach_msg_type_name_t *portpoly,
		u_int *nports,
		int **intarray, u_int *nints)
{
  struct bootinfo *boot = (struct bootinfo *)port;
  if ((mach_port_t) boot == execserver || (mach_port_t) boot == fsys)
    return EOPNOTSUPP;

  *stack_base = boot->stack_base;
  *stack_size = boot->stack_size;

  *argvp = boot->argv;
  *argvlen = boot->argvlen;

  *envpp = boot->envp;
  *envplen = boot->envplen;

  *dtable = boot->dtable;
  *dtablesize = boot->dtablesize;
  *dtablepoly = MACH_MSG_TYPE_MOVE_SEND;

  *intarray = boot->intarray;
  *nints = boot->nints;

  *portarray = boot->portarray;
  *nports = boot->nports;
  *portpoly = MACH_MSG_TYPE_MOVE_SEND;

  *flags = boot->flags;

  mach_port_move_member (mach_task_self (), (mach_port_t) boot, 
			 MACH_PORT_NULL); /* XXX what is this XXX here for? */
  
  mach_port_mod_refs (mach_task_self (), (mach_port_t) boot,
		      MACH_PORT_TYPE_RECEIVE, -1);
  free (boot);

  return 0;
}

/* Notice when a receive right has no senders.  Either this is the
   bootstrap port of a stillborn task, or it is the execserver port itself. */

kern_return_t
do_mach_notify_no_senders (mach_port_t port, mach_port_mscount_t mscount)
{
  if (port != execserver && port != fsys)
    {
      /* Free the resources we were saving to give the task
	 which can no longer ask for them.  */

      struct bootinfo *boot = (struct bootinfo *) port;
      size_t i;

      vm_deallocate (mach_task_self (),
		     (vm_address_t) boot->argv, boot->argvlen);
      vm_deallocate (mach_task_self (),
		     (vm_address_t) boot->envp, boot->envplen);

      for (i = 0; i < boot->dtablesize; ++i)
	mach_port_deallocate (mach_task_self (), boot->dtable[i]);
      for (i = 0; i < boot->nports; ++i)
	mach_port_deallocate (mach_task_self (), boot->portarray[i]);
      vm_deallocate (mach_task_self (),
		     (vm_address_t) boot->portarray,
		     boot->nports * sizeof (mach_port_t));
      vm_deallocate (mach_task_self (),
		     (vm_address_t) boot->intarray,
		     boot->nints * sizeof (int));

      free (boot);
    }

  /* Deallocate the request port.  */
  mach_port_mod_refs (mach_task_self (), port, MACH_PORT_TYPE_RECEIVE, -1);

  mach_port_mod_refs (mach_task_self (), request_portset,
		      MACH_PORT_TYPE_RECEIVE, -1);

  return KERN_SUCCESS;
}

/* Attempt to set the active translator for the exec server so that
   filesystems other than the bootstrap can find it. */
void
set_active_trans ()
{
  file_t execnode;
  
  execnode = file_name_lookup (_SERVERS_EXEC, O_NOTRANS | O_CREAT, 0666);
  if (execnode == MACH_PORT_NULL)
    return;
  
  file_set_translator (execnode, 0, FS_TRANS_SET, 0, 0, 0, fsys,
		       MACH_MSG_TYPE_MAKE_SEND);
  /* Don't deallocate EXECNODE here.  If we drop the last reference,
     a bug in ufs might throw away the active translator. XXX */
}


/* Sent by the bootstrap filesystem after the other essential
   servers have been started up.  */

kern_return_t
S_exec_init (mach_port_t server, auth_t auth, process_t proc)
{
  mach_port_t host_priv, dev_master, startup;
  error_t err;

  if (_hurd_ports[INIT_PORT_PROC].port != MACH_PORT_NULL)
    /* Can only be done once.  */
    return EPERM;

  mach_port_mod_refs (mach_task_self (), proc, MACH_PORT_RIGHT_SEND, 1);
  procserver = proc;
  _hurd_port_set (&_hurd_ports[INIT_PORT_PROC], proc);
  _hurd_port_set (&_hurd_ports[INIT_PORT_AUTH], auth);

  /* Do initial setup with the proc server.  */
  _hurd_proc_init (save_argv);

  /* Set the active translator on /hurd/exec. */
  set_active_trans ();

  err = get_privileged_ports (&host_priv, &dev_master);
  if (!err)
    {
      proc_register_version (proc, host_priv, "exec", HURD_RELEASE,
			     exec_version);
      mach_port_deallocate (mach_task_self (), dev_master);
      err = proc_getmsgport (proc, 1, &startup);
      if (err)
	{
	  mach_port_deallocate (mach_task_self (), host_priv);
	  host_priv = MACH_PORT_NULL;
	}
    }
  else
    host_priv = MACH_PORT_NULL;
      
  /* Have the proc server notify us when the canonical ints and ports change.
     The notification comes as a normal RPC on the message port, which
     the C library's signal thread handles.  */
  proc_execdata_notify (procserver, execserver, MACH_MSG_TYPE_MAKE_SEND);

  /* Call startup_essential task last; init assumes we are ready to
     run once we call it. */
  if (host_priv != MACH_PORT_NULL)
    {
      startup_essential_task (startup, mach_task_self (), MACH_PORT_NULL,
			      "exec", host_priv);
      mach_port_deallocate (mach_task_self (), startup);
      mach_port_deallocate (mach_task_self (), host_priv);
    }
  
  return 0;
}


int
main (int argc, char **argv)
{
  error_t err;
  mach_port_t boot;

  /* XXX */
  stdout = mach_open_devstream (getdport (1), "w");
  stderr = mach_open_devstream (getdport (2), "w");
  /* End XXX */

  save_argv = argv;

#ifdef	BFD
  /* Put the Mach kernel's idea of what flavor of machine this is into the
     fake BFD against which architecture compatibility checks are made.  */
  err = bfd_mach_host_arch_mach (mach_host_self (),
				 &host_bfd.arch_info->arch,
				 &host_bfd.arch_info->mach);
#else
  err = aout_mach_host_machine (mach_host_self (), (int *)&host_machine);
#endif
  if (err)
    return err;

  mach_port_allocate (mach_task_self (), MACH_PORT_RIGHT_RECEIVE, &fsys);
  mach_port_allocate (mach_task_self (), MACH_PORT_RIGHT_RECEIVE, &execserver);

  task_get_bootstrap_port (mach_task_self (), &boot);
  fsys_startup (boot, fsys, MACH_MSG_TYPE_MAKE_SEND, &realnode);

  mach_port_allocate (mach_task_self (),
		      MACH_PORT_RIGHT_PORT_SET, &request_portset);
  mach_port_move_member (mach_task_self (), fsys, request_portset);
  mach_port_move_member (mach_task_self (), execserver, request_portset);

  while (1)
    {
      err = mach_msg_server (request_server, vm_page_size, request_portset);
      fprintf (stderr, "%s: mach_msg_server: %s\n",
	       (argv && argv[0]) ? argv[0] : "exec server",
	       strerror (err));
    }
}

/* Nops */
kern_return_t 
do_mach_notify_port_deleted (mach_port_t notify,
			     mach_port_t name)
{
  return EOPNOTSUPP;
}

kern_return_t
do_mach_notify_msg_accepted (mach_port_t notify,
			     mach_port_t name)
{
  return EOPNOTSUPP;
}

kern_return_t
do_mach_notify_port_destroyed (mach_port_t notify,
			       mach_port_t rights)
{
  return EOPNOTSUPP;
}

kern_return_t
do_mach_notify_send_once (mach_port_t notify)
{
  return EOPNOTSUPP;
}

kern_return_t
do_mach_notify_dead_name (mach_port_t notify,
			  mach_port_t name)
{
  return EOPNOTSUPP;
}