DragonFlyBSD Kernel Audit
sys/kern/kern_exec.c
← back
   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
/*
 * Copyright (c) 1993, David Greenman
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * $FreeBSD: src/sys/kern/kern_exec.c,v 1.107.2.15 2002/07/30 15:40:46 nectar Exp $
 */

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/sysmsg.h>
#include <sys/kernel.h>
#include <sys/mount.h>
#include <sys/filedesc.h>
#include <sys/fcntl.h>
#include <sys/acct.h>
#include <sys/exec.h>
#include <sys/imgact.h>
#include <sys/imgact_elf.h>
#include <sys/kern_syscall.h>
#include <sys/wait.h>
#include <sys/malloc.h>
#include <sys/proc.h>
#include <sys/caps.h>
#include <sys/ktrace.h>
#include <sys/signalvar.h>
#include <sys/pioctl.h>
#include <sys/nlookup.h>
#include <sys/sysent.h>
#include <sys/shm.h>
#include <sys/sysctl.h>
#include <sys/vnode.h>
#include <sys/vmmeter.h>
#include <sys/libkern.h>

#include <cpu/lwbuf.h>

#include <vm/vm.h>
#include <vm/vm_param.h>
#include <sys/lock.h>
#include <vm/pmap.h>
#include <vm/vm_page.h>
#include <vm/vm_map.h>
#include <vm/vm_kern.h>
#include <vm/vm_extern.h>
#include <vm/vm_object.h>
#include <vm/vnode_pager.h>
#include <vm/vm_pager.h>

#include <sys/reg.h>

#include <sys/objcache.h>
#include <sys/refcount.h>
#include <sys/thread2.h>
#include <vm/vm_page2.h>

MALLOC_DEFINE(M_PARGS, "proc-args", "Process arguments");
MALLOC_DEFINE(M_EXECARGS, "exec-args", "Exec arguments");

enum exec_path_segflg {
	PATH_SYSSPACE,
	PATH_USERSPACE,
};

static register_t *exec_copyout_strings(struct image_params *);
static int	exec_copyin_args(struct image_args *, char *,
				 enum exec_path_segflg, char **, char **);
static void	exec_free_args(struct image_args *);
static void	print_execve_args(struct image_args *args);

/* XXX This should be vm_size_t. */
__read_mostly static u_long ps_strings = PS_STRINGS;
SYSCTL_ULONG(_kern, KERN_PS_STRINGS, ps_strings, CTLFLAG_RD, &ps_strings, 0, "");

/* XXX This should be vm_size_t. */
__read_mostly static u_long usrstack = USRSTACK;
SYSCTL_ULONG(_kern, KERN_USRSTACK, usrstack, CTLFLAG_RD, &usrstack, 0, "");

__read_mostly u_long ps_arg_cache_limit = PAGE_SIZE / 16;
SYSCTL_LONG(_kern, OID_AUTO, ps_arg_cache_limit, CTLFLAG_RW,
    &ps_arg_cache_limit, 0, "");

__read_mostly int ps_argsopen = 1;
SYSCTL_INT(_kern, OID_AUTO, ps_argsopen, CTLFLAG_RW, &ps_argsopen, 0, "");

__read_mostly static int ktrace_suid = 0;
SYSCTL_INT(_kern, OID_AUTO, ktrace_suid, CTLFLAG_RW, &ktrace_suid, 0, "");

__read_mostly static int debug_execve_args = 0;
SYSCTL_INT(_kern, OID_AUTO, debug_execve_args, CTLFLAG_RW, &debug_execve_args,
    0, "");

/*
 * Exec arguments object cache
 */
__read_mostly static struct objcache *exec_objcache;

static
void
exec_objcache_init(void *arg __unused)
{
	int cluster_limit;
	size_t limsize;

	/*
	 * Maximum number of concurrent execs.  This can be limiting on
	 * systems with a lot of cpu cores but it also eats a significant
	 * amount of memory.
	 */
	cluster_limit = (ncpus < 16) ? 16 : ncpus;
	limsize = kmem_lim_size();
	if (limsize > 7 * 1024)
		cluster_limit *= 2;
	if (limsize > 15 * 1024)
		cluster_limit *= 2;

	exec_objcache = objcache_create_mbacked(
					M_EXECARGS, PATH_MAX + ARG_MAX,
					cluster_limit, 8,
					NULL, NULL, NULL);
}
SYSINIT(exec_objcache, SI_BOOT2_MACHDEP, SI_ORDER_ANY, exec_objcache_init, 0);

/*
 * stackgap_random specifies if the stackgap should have a random size added
 * to it.  It must be a power of 2.  If non-zero, the stack gap will be
 * calculated as: ALIGN(karc4random() & (stackgap_random - 1)).
 */
__read_mostly static int stackgap_random = 1024;

static int
sysctl_kern_stackgap(SYSCTL_HANDLER_ARGS)
{
	int error, new_val;
	new_val = stackgap_random;
	error = sysctl_handle_int(oidp, &new_val, 0, req);
	if (error != 0 || req->newptr == NULL)
		return (error);
	if (new_val > 0 && ((new_val > 16 * PAGE_SIZE) || !powerof2(new_val)))
		return (EINVAL);
	stackgap_random = new_val;

	return(0);
}

SYSCTL_PROC(_kern, OID_AUTO, stackgap_random, CTLFLAG_RW|CTLTYPE_INT,
	0, 0, sysctl_kern_stackgap, "I",
	"Max random stack gap (power of 2), static gap if negative");

static void
print_execve_args(struct image_args *args)
{
	char *cp;
	int ndx;

	cp = args->begin_argv;
	for (ndx = 0; ndx < args->argc; ndx++) {
		kprintf("\targv[%d]: %s\n", ndx, cp);
		while (*cp++ != '\0');
	}
	for (ndx = 0; ndx < args->envc; ndx++) {
		kprintf("\tenvv[%d]: %s\n", ndx, cp);
		while (*cp++ != '\0');
	}
}

/*
 * Each of the items is a pointer to a `const struct execsw', hence the
 * double pointer here.
 */
__read_mostly static const struct execsw **execsw;

/*
 * Replace current vmspace with a new binary.
 * Returns 0 on success, > 0 on recoverable error (use as errno).
 * Returns -1 on lethal error which demands killing of the current
 * process!
 */
int
kern_execve(struct nlookupdata *nd, struct file *fp, char fileflags,
	    struct image_args *args)
{
	static const char *proctitle = "(execve)";
	register_t *stack_base;
	struct thread *td = curthread;
	struct lwp *lp = td->td_lwp;
	struct proc *p = td->td_proc;
	struct vnode *ovp;
	struct pargs *pa;
	struct sigacts *ops;
	struct sigacts *nps;
	struct image_params image_params, *imgp;
	struct filedesc *fds;
	struct nchandle *nch;
	struct nlookupdata nd_interpreter;
	struct vattr_lite lva;
	int error, len, i;
	int (*img_first) (struct image_params *);

	if (debug_execve_args) {
		kprintf("%s()\n", __func__);
		print_execve_args(args);
	}

	KKASSERT(p);
	lwkt_gettoken(&p->p_token);
	imgp = &image_params;

	/*
	 * NOTE: P_INEXEC is handled by exec_new_vmspace() now.  We make
	 * no modifications to the process at all until we get there.
	 *
	 * Note that multiple threads may be trying to exec at the same
	 * time.  exec_new_vmspace() handles that too.
	 */

	/*
	 * Initialize part of the common data
	 */
	imgp->proc = p;
	imgp->args = args;
	imgp->lvap = &lva;
	imgp->entry_addr = 0;
	imgp->resident = 0;
	imgp->vmspace_destroyed = 0;
	imgp->interpreted = 0;
	imgp->interpreter_name[0] = 0;
	imgp->auxargs = NULL;
	imgp->vp = NULL;
	imgp->firstpage = NULL;
	imgp->ps_strings = 0;
	imgp->execpath = imgp->freepath = NULL;
	imgp->execpathp = 0;
	imgp->image_header = NULL;

interpret:

	if (nd) {
		/*
		 * Translate the file name to a vnode.  Unlock the cache
		 * entry to improve parallelism for programs exec'd in
		 * parallel.
		 */
		nch = &nd->nl_nch;
		nd->nl_flags |= NLC_SHAREDLOCK;
		if ((error = nlookup(nd)) != 0)
			goto failed;

		error = cache_vget(nch, nd->nl_cred, LK_SHARED, &imgp->vp);
		KKASSERT(nd->nl_flags & NLC_NCPISLOCKED);
		nd->nl_flags &= ~NLC_NCPISLOCKED;
		cache_unlock(nch);
	} else {
		nch = &fp->f_nchandle;
		imgp->vp = fp->f_data;
		error = vget(imgp->vp, LK_SHARED);
	}
	if (error) {
		imgp->vp = NULL;
		goto failed;
	}

	/*
	 * Check file permissions (also 'opens' file).
	 * Include also the top level mount in the check.
	 */
	error = exec_check_permissions(imgp, nch->mount);
	if (error) {
		vn_unlock(imgp->vp);
		goto failed;
	}

	error = exec_map_first_page(imgp);
	vn_unlock(imgp->vp);
	if (error)
		goto failed;

	imgp->proc->p_osrel = 0;

	if (debug_execve_args && imgp->interpreted) {
		kprintf("    target is interpreted -- recursive pass\n");
		kprintf("    interpreter: %s\n", imgp->interpreter_name);
		print_execve_args(args);
	}

	/*
	 *	If the current process has a special image activator it
	 *	wants to try first, call it.  For example, emulating shell
	 *	scripts differently.
	 */
	error = -1;
	if ((img_first = imgp->proc->p_sysent->sv_imgact_try) != NULL)
		error = img_first(imgp);

	/*
	 *	If the vnode has a registered vmspace, exec the vmspace
	 */
	if (error == -1 && imgp->vp->v_resident)
		error = exec_resident_imgact(imgp);

	/*
	 *	Loop through the list of image activators, calling each one.
	 *	An activator returns -1 if there is no match, 0 on success,
	 *	and an error otherwise.
	 */
	for (i = 0; error == -1 && execsw[i]; ++i) {
		if (execsw[i]->ex_imgact == NULL ||
		    execsw[i]->ex_imgact == img_first) {
			continue;
		}
		error = (*execsw[i]->ex_imgact)(imgp);
	}

	if (error) {
		if (error == -1)
			error = ENOEXEC;
		goto failed;
	}

	/*
	 * Special interpreter operation, cleanup and loop up to try to
	 * activate the interpreter.
	 */
	if (imgp->interpreted) {
		exec_unmap_first_page(imgp);
		vrele(imgp->vp);
		imgp->vp = NULL;

		nd = &nd_interpreter;
		error = nlookup_init(nd, imgp->interpreter_name,
				     UIO_SYSSPACE, NLC_FOLLOW);
		if (error)
			goto failed;

		if (fp && (fileflags & UF_EXCLOSE)) {
			/*
			 * Fexecve'ing an interpreted file opened with
			 * O_CLOEXEC flag, return ENOENT.
			 */
			error = ENOENT;
			goto failed;
		}

		goto interpret;
	}

	/*
	 * Do the best to calculate the full path to the image file
	 */
	if (imgp->auxargs != NULL &&
	    ((args->fname != NULL && args->fname[0] == '/') ||
	     vn_fullpath(imgp->proc, imgp->vp, &imgp->execpath,
			 &imgp->freepath, 0) != 0))
	{
		imgp->execpath = args->fname;
	}

	/*
	 * Copy out strings (args and env) and initialize stack base
	 */
	stack_base = exec_copyout_strings(imgp);
	p->p_vmspace->vm_minsaddr = (char *)stack_base;

	/*
	 * If custom stack fixup routine present for this process
	 * let it do the stack setup.  If we are running a resident
	 * image there is no auxinfo or other image activator context
	 * so don't try to add fixups to the stack.
	 *
	 * Else stuff argument count as first item on stack
	 */
	if (p->p_sysent->sv_fixup && imgp->resident == 0)
		(*p->p_sysent->sv_fixup)(&stack_base, imgp);
	else
		suword64(--stack_base, imgp->args->argc);

	/*
	 * For security and other reasons, the file descriptor table cannot
	 * be shared after an exec.
	 */
	if (p->p_fd->fd_refcnt > 1) {
		if ((error = fdcopy(p, &fds)) != 0)
			goto failed;

		fdfree(p, fds);
	}

	/*
	 * For security and other reasons, signal handlers cannot
	 * be shared after an exec. The new proces gets a copy of the old
	 * handlers. In execsigs(), the new process will have its signals
	 * reset.
	 */
	ops = p->p_sigacts;
	if (ops->ps_refcnt > 1) {
		nps = kmalloc(sizeof(*nps), M_SUBPROC, M_WAITOK);
		bcopy(ops, nps, sizeof(*nps));
		refcount_init(&nps->ps_refcnt, 1);
		p->p_sigacts = nps;
		if (refcount_release(&ops->ps_refcnt)) {
			kfree(ops, M_SUBPROC);
			ops = NULL;
		}
	}

	/*
	 * Clean up shared pages, the new program will allocate fresh
	 * copies as needed.  This is also for security purposes and
	 * to ensure (for example) that things like sys_lpmap->blockallsigs
	 * state is properly reset on exec.
	 */
	lwp_userunmap(lp);
	proc_userunmap(p);

	/*
	 * For security and other reasons virtual kernels cannot be
	 * inherited by an exec.  This also allows a virtual kernel
	 * to fork/exec unrelated applications.
	 */
	if (p->p_vkernel)
		vkernel_exit(p);

	/* Stop profiling */
	stopprofclock(p);

	/* close files on exec */
	fdcloseexec(p);

	/* reset caught signals */
	execsigs(p);

	/* name this process */
	if (nch->ncp) {
		len = min(nch->ncp->nc_nlen, MAXCOMLEN);
		bcopy(nch->ncp->nc_name, p->p_comm, len);
	} else {
		len = sizeof(proctitle) - 1;
		bcopy(proctitle, p->p_comm, len);
	}
	p->p_comm[len] = 0;
	bcopy(p->p_comm, lp->lwp_thread->td_comm, MAXCOMLEN+1);

	/*
	 * mark as execed, wakeup the process that vforked (if any) and tell
	 * it that it now has its own resources back
	 *
	 * We are using the P_PPWAIT as an interlock so an atomic op is
	 * necessary to synchronize with the parent's cpu.
	 */
	p->p_flags |= P_EXEC;
	if (p->p_pptr && (p->p_flags & P_PPWAIT)) {
		if (p->p_pptr->p_upmap)
			atomic_add_int(&p->p_pptr->p_upmap->invfork, -1);
		atomic_clear_int(&p->p_flags, P_PPWAIT);
		wakeup(p->p_pptr);
	}

	/*
	 * Implement image setuid/setgid.
	 *
	 * Don't honor setuid/setgid if the filesystem prohibits it or if
	 * the process is being traced.
	 */
	if ((((lva.va_mode & VSUID) && p->p_ucred->cr_uid != lva.va_uid) ||
	     ((lva.va_mode & VSGID) && p->p_ucred->cr_gid != lva.va_gid)) &&
	    (imgp->vp->v_mount->mnt_flag & MNT_NOSUID) == 0 &&
	    (p->p_flags & P_TRACED) == 0) {
		/*
		 * Turn off syscall tracing for set-id programs, except for
		 * root.  Record any set-id flags first to make sure that
		 * we do not regain any tracing during a possible block.
		 */
		setsugid();
		if (p->p_tracenode && ktrace_suid == 0 &&
		    caps_priv_check_td(td, SYSCAP_RESTRICTEDROOT) != 0)
		{
			ktrdestroy(&p->p_tracenode);
			p->p_traceflag = 0;
		}

		/* Clear any PROC_PDEATHSIG_CTL setting */
		p->p_deathsig = 0;

		/* Close any file descriptors 0..2 that reference procfs */
		setugidsafety(p);
		/* Make sure file descriptors 0..2 are in use. */
		error = fdcheckstd(lp);
		if (error != 0)
			goto failed;

		/*
		 * Set the new credentials.
		 */
		cratom_proc(p);
		if (lva.va_mode & VSUID)
			change_euid(lva.va_uid);
		if (lva.va_mode & VSGID)
			p->p_ucred->cr_gid = lva.va_gid;

		/* Clear local varsym variables */
		varsymset_clean(&p->p_varsymset);
	} else {
		if (p->p_ucred->cr_uid == p->p_ucred->cr_ruid &&
		    p->p_ucred->cr_gid == p->p_ucred->cr_rgid)
			p->p_flags &= ~P_SUGID;
	}

	/*
	 * Implement correct POSIX saved-id behavior.
	 */
	if (p->p_ucred->cr_svuid != p->p_ucred->cr_uid ||
	    p->p_ucred->cr_svgid != p->p_ucred->cr_gid) {
		cratom_proc(p);
		p->p_ucred->cr_svuid = p->p_ucred->cr_uid;
		p->p_ucred->cr_svgid = p->p_ucred->cr_gid;
	}

	/*
	 * Store the vp for use in procfs.  Be sure to keep p_textvp
	 * consistent if we block during the switch-over.
	 */
	ovp = p->p_textvp;
	vref(imgp->vp);			/* ref new vp */
	p->p_textvp = imgp->vp;
	if (ovp)			/* release old vp */
		vrele(ovp);

	/* Release old namecache handle to text file */
	if (p->p_textnch.ncp)
		cache_drop(&p->p_textnch);
	if (nch->mount)
		cache_copy(nch, &p->p_textnch);

	/*
	 * Adjust capabilities in ucred if necessasry
	 */
	caps_exec(p);

        /*
         * Notify others that we exec'd, and clear the P_INEXEC flag
         * as we're now a bona fide freshly-execed process.
         */
	KNOTE(&p->p_klist, NOTE_EXEC);
	p->p_flags &= ~P_INEXEC;
	if (p->p_stops)
		wakeup(&p->p_stype);

	/*
	 * If tracing the process, trap to debugger so breakpoints
	 * 	can be set before the program executes.
	 */
	STOPEVENT(p, S_EXEC, 0);

	if (p->p_flags & P_TRACED)
		ksignal(p, SIGTRAP);

	/* clear "fork but no exec" flag, as we _are_ execing */
	p->p_acflag &= ~AFORK;

	/* Set values passed into the program in registers. */
	exec_setregs(imgp->entry_addr, (u_long)(uintptr_t)stack_base,
		     imgp->ps_strings);

	/* Set the access time on the vnode */
	vn_mark_atime(imgp->vp, td);

	/*
	 * Free any previous argument cache
	 */
	pa = p->p_args;
	p->p_args = NULL;
	if (pa && refcount_release(&pa->ar_ref)) {
		kfree(pa, M_PARGS);
		pa = NULL;
	}

	/*
	 * Cache arguments if they fit inside our allowance
	 */
	i = imgp->args->begin_envv - imgp->args->begin_argv;
	if (sizeof(struct pargs) + i <= ps_arg_cache_limit) {
		pa = kmalloc(sizeof(struct pargs) + i, M_PARGS, M_WAITOK);
		refcount_init(&pa->ar_ref, 1);
		pa->ar_length = i;
		bcopy(imgp->args->begin_argv, pa->ar_args, i);
		KKASSERT(p->p_args == NULL);
		p->p_args = pa;
	}

failed:

	/*
	 * free various allocated resources
	 */
	if (imgp->firstpage)
		exec_unmap_first_page(imgp);
	if (imgp->vp)
		vrele(imgp->vp);
	if (imgp->freepath)
		kfree(imgp->freepath, M_TEMP);
	if (nd == &nd_interpreter)
		nlookup_done(nd);

	if (error == 0) {
		++mycpu->gd_cnt.v_exec;
		lwkt_reltoken(&p->p_token);
		return (0);
	}

	/*
	 * we're done here, clear P_INEXEC if we were the ones that
	 * set it.  Otherwise if vmspace_destroyed is still set we
	 * raced another thread and that thread is responsible for
	 * clearing it.
	 */
	if (imgp->vmspace_destroyed & 2) {
		p->p_flags &= ~P_INEXEC;
		if (p->p_stops)
			wakeup(&p->p_stype);
	}
	lwkt_reltoken(&p->p_token);
	if (imgp->vmspace_destroyed) {
		/*
		 * Sorry, no more process anymore. exit gracefully.
		 * However we can't die right here, because our
		 * caller might have to clean up, so indicate a
		 * lethal error by returning -1.
		 */
		return (-1);
	} else {
		return (error);
	}
}

/*
 * execve() system call.
 */
int
sys_execve(struct sysmsg *sysmsg, const struct execve_args *uap)
{
	struct nlookupdata nd;
	struct image_args args;
	int error;

	/*
	 * General exec ok?
	 */
	if (caps_priv_check_self(SYSCAP_NOEXEC | __SYSCAP_NOROOTTEST))
		return EACCES;

	/*
	 * Exec path
	 */
	bzero(&args, sizeof(args));

	error = nlookup_init(&nd, uap->fname, UIO_USERSPACE, NLC_FOLLOW);
	if (error == 0) {
		error = exec_copyin_args(&args, uap->fname, PATH_USERSPACE,
					 uap->argv, uap->envv);
	}
	if (error == 0)
		error = kern_execve(&nd, NULL, 0, &args);
	nlookup_done(&nd);
	exec_free_args(&args);

	if (error < 0) {
		/* We hit a lethal error condition.  Let's die now. */
		exit1(W_EXITCODE(0, SIGABRT));
		/* NOTREACHED */
	}

	/*
	 * The syscall result is returned in registers to the new program.
	 * Linux will register %edx as an atexit function and we must be
	 * sure to set it to 0.  XXX
	 */
	if (error == 0)
		sysmsg->sysmsg_result64 = 0;

	return (error);
}

/*
 * fexecve() system call.
 */
int
sys_fexecve(struct sysmsg *sysmsg, const struct fexecve_args *uap)
{
	struct image_args args;
	struct thread *td = curthread;
	struct file *fp;
	char fileflags;
	char fname[32]; /* "/dev/fd/xxx" */
	int error;

	/*
	 * General exec ok?
	 */
	if (caps_priv_check_self(SYSCAP_NOEXEC | __SYSCAP_NOROOTTEST))
		return EACCES;

	/*
	 * Exec descriptor
	 */
	if ((error = holdvnode2(td, uap->fd, &fp, &fileflags)) != 0)
		return (error);

	/*
	 * Require a descriptor opened only with O_RDONLY or O_EXEC.
	 * XXX: missing O_EXEC support
	 */
	if ((fp->f_flag & FWRITE) != 0 || (fp->f_flag & FREAD) == 0) {
		error = EBADF;
		goto done;
	}

	/*
	 * The 'fname' argument is required when executing an
	 * interpreted program because the interpreter must know
	 * the script path.  Supply it with '/dev/fd/xxx'.
	 */
	ksnprintf(fname, sizeof(fname), "/dev/fd/%d", uap->fd);
	bzero(&args, sizeof(args));
	error = exec_copyin_args(&args, fname, PATH_SYSSPACE,
				 uap->argv, uap->envv);
	if (error == 0)
		error = kern_execve(NULL, fp, fileflags, &args);
	exec_free_args(&args);

	if (error < 0) {
		/* We hit a lethal error condition.  Let's die now. */
		exit1(W_EXITCODE(0, SIGABRT));
		/* NOTREACHED */
	}

	/*
	 * The syscall result is returned in registers to the new program.
	 * Linux will register %edx as an atexit function and we must be
	 * sure to set it to 0.  XXX
	 */
	if (error == 0)
		sysmsg->sysmsg_result64 = 0;

done:
	fdrop(fp);
	return (error);
}

int
exec_map_page(struct image_params *imgp, vm_pindex_t pageno,
	      struct lwbuf **plwb, const char **pdata)
{
	int rv;
	vm_page_t ma;
	vm_page_t m;
	vm_object_t object;

	/*
	 * The file has to be mappable.
	 */
	if ((object = imgp->vp->v_object) == NULL)
		return (EIO);

	if (pageno >= object->size)
		return (EIO);

	/*
	 * Shortcut using shared locks, improve concurrent execs.
	 */
	vm_object_hold_shared(object);
	m = vm_page_lookup(object, pageno);
	if (m) {
		if ((m->valid & VM_PAGE_BITS_ALL) == VM_PAGE_BITS_ALL) {
			vm_page_hold(m);
			vm_page_sleep_busy(m, FALSE, "execpg");
			if ((m->valid & VM_PAGE_BITS_ALL) == VM_PAGE_BITS_ALL &&
			    m->object == object && m->pindex == pageno) {
				vm_object_drop(object);
				goto done;
			}
			vm_page_unhold(m);
		}
	}
	vm_object_drop(object);

	/*
	 * Do it the hard way
	 */
	vm_object_hold(object);
	m = vm_page_grab(object, pageno, VM_ALLOC_NORMAL | VM_ALLOC_RETRY);
	while ((m->valid & VM_PAGE_BITS_ALL) != VM_PAGE_BITS_ALL) {
		ma = m;

		/*
		 * get_pages unbusies all the requested pages except the
		 * primary page (at index 0 in this case).  The primary
		 * page may have been wired during the pagein (e.g. by
		 * the buffer cache) so vnode_pager_freepage() must be
		 * used to properly release it.
		 */
		rv = vm_pager_get_page(object, pageno, &ma, 1);
		m = vm_page_lookup(object, pageno);

		if (rv != VM_PAGER_OK || m == NULL || m->valid == 0) {
			if (m) {
				vm_page_protect(m, VM_PROT_NONE);
				vnode_pager_freepage(m);
			}
			vm_object_drop(object);
			return EIO;
		}
	}
	vm_page_hold(m);
	vm_page_wakeup(m);	/* unbusy the page */
	vm_object_drop(object);

done:
	*plwb = lwbuf_alloc(m, *plwb);
	*pdata = (void *)lwbuf_kva(*plwb);

	return (0);
}

/*
 * Map the first page of an executable image.
 *
 * NOTE: If the mapping fails we have to NULL-out firstpage which may
 *	 still be pointing to our supplied lwp structure.
 */
int
exec_map_first_page(struct image_params *imgp)
{
	int err;

	if (imgp->firstpage)
		exec_unmap_first_page(imgp);

	imgp->firstpage = &imgp->firstpage_cache;
	err = exec_map_page(imgp, 0, &imgp->firstpage, &imgp->image_header);

	if (err) {
		imgp->firstpage = NULL;
		return err;
	}

	return 0;
}

void
exec_unmap_page(struct lwbuf *lwb)
{
	vm_page_t m;

	crit_enter();
	if (lwb != NULL) {
		m = lwbuf_page(lwb);
		lwbuf_free(lwb);
		vm_page_unhold(m);
	}
	crit_exit();
}

void
exec_unmap_first_page(struct image_params *imgp)
{
	exec_unmap_page(imgp->firstpage);
	imgp->firstpage = NULL;
	imgp->image_header = NULL;
}

/*
 * Destroy old address space, and allocate a new stack
 *	The new stack is only SGROWSIZ large because it is grown
 *	automatically in trap.c.
 *
 * This is the point of no return.
 */
int
exec_new_vmspace(struct image_params *imgp, struct vmspace *vmcopy)
{
	struct vmspace *vmspace = imgp->proc->p_vmspace;
	vm_offset_t stack_addr = USRSTACK - maxssiz;
	struct lwp *lp;
	struct proc *p;
	vm_map_t map;
	int error;

	/*
	 * Indicate that we cannot gracefully error out any more, kill
	 * any other threads present, and set P_INEXEC to indicate that
	 * we are now messing with the process structure proper.
	 *
	 * If killalllwps() races return an error which coupled with
	 * vmspace_destroyed will cause us to exit.  This is what we
	 * want since another thread is patiently waiting for us to exit
	 * in that case.
	 */
	lp = curthread->td_lwp;
	p = lp->lwp_proc;
	imgp->vmspace_destroyed = 1;

	if (curthread->td_proc->p_nthreads > 1) {
		error = killalllwps(1);
		if (error)
			return (error);
	}
	imgp->vmspace_destroyed |= 2;	/* we are responsible for P_INEXEC */
	p->p_flags |= P_INEXEC;

	/*
	 * Tell procfs to release its hold on the process.  It
	 * will return EAGAIN.
	 */
	if (p->p_stops)
		wakeup(&p->p_stype);

	/*
	 * After setting P_INEXEC wait for any remaining references to
	 * the process (p) to go away.
	 *
	 * In particular, a vfork/exec sequence will replace p->p_vmspace
	 * and we must interlock anyone trying to access the space (aka
	 * procfs or sys_process.c calling procfs_domem()).
	 *
	 * If P_PPWAIT is set the parent vfork()'d and has a PHOLD() on us.
	 */
	PSTALL(p, "exec1", ((p->p_flags & P_PPWAIT) ? 1 : 0));

	/*
	 * Blow away entire process VM, if address space not shared,
	 * otherwise, create a new VM space so that other threads are
	 * not disrupted.  If we are execing a resident vmspace we
	 * create a duplicate of it and remap the stack.
	 */
	map = &vmspace->vm_map;
	if (vmcopy) {
		vmspace_exec(imgp->proc, vmcopy);
		vmspace = imgp->proc->p_vmspace;
		pmap_remove_pages(vmspace_pmap(vmspace), stack_addr, USRSTACK);
		map = &vmspace->vm_map;
	} else if (vmspace_getrefs(vmspace) == 1) {
		shmexit(vmspace);
		pmap_remove_pages(vmspace_pmap(vmspace),
				  0, VM_MAX_USER_ADDRESS);
		vm_map_remove(map, 0, VM_MAX_USER_ADDRESS);
	} else {
		vmspace_exec(imgp->proc, NULL);
		vmspace = imgp->proc->p_vmspace;
		map = &vmspace->vm_map;
	}

	/*
	 * Really make sure lwp-specific and process-specific mappings
	 * are gone.
	 *
	 * Once we've done that, and because we are the only LWP left, with
	 * no TID-dependent mappings, we can reset the TID to 1 (the RB tree
	 * will remain consistent since it has only one entry).  This way
	 * the exec'd program gets a nice deterministic tid of 1.
	 */
	lwp_userunmap(lp);
	proc_userunmap(p);
	lp->lwp_tid = 1;
	p->p_lasttid = 1;

	/*
	 * Allocate a new stack, generally make the stack non-executable
	 * but allow the program to adjust that (the program may desire to
	 * use areas of the stack for executable code).
	 */
	error = vm_map_stack(&vmspace->vm_map, &stack_addr, (vm_size_t)maxssiz,
			     0,
			     VM_PROT_READ|VM_PROT_WRITE,
			     VM_PROT_READ|VM_PROT_WRITE|VM_PROT_EXECUTE,
			     0);
	if (error)
		return (error);

	/*
	 * vm_ssize and vm_maxsaddr are somewhat antiquated concepts in the
	 * VM_STACK case, but they are still used to monitor the size of the
	 * process stack so we can check the stack rlimit.
	 */
	vmspace->vm_ssize = sgrowsiz;		/* in bytes */
	vmspace->vm_maxsaddr = (char *)USRSTACK - maxssiz;

	return(0);
}

/*
 * Copy out argument and environment strings from the old process
 *	address space into the temporary string buffer.
 */
static int
exec_copyin_args(struct image_args *args, char *fname,
		 enum exec_path_segflg segflg, char **argv, char **envv)
{
	char	*argp, *envp;
	int	error = 0;
	size_t	length;

	args->buf = objcache_get(exec_objcache, M_WAITOK);
	if (args->buf == NULL)
		return (ENOMEM);

	args->begin_argv = args->buf;
	args->endp = args->begin_argv;
	args->space = ARG_MAX;

	args->fname = args->buf + ARG_MAX;

	/*
	 * Copy the file name.
	 */
	if (segflg == PATH_SYSSPACE)
		error = copystr(fname, args->fname, PATH_MAX, &length);
	else
		error = copyinstr(fname, args->fname, PATH_MAX, &length);
	if (error)
		return (error);

	/*
	 * Extract argument strings.  argv may not be NULL.  The argv
	 * array is terminated by a NULL entry.  We special-case the
	 * situation where argv[0] is NULL by passing { filename, NULL }
	 * to the new program to guarentee that the interpreter knows what
	 * file to open in case we exec an interpreted file.   Note that
	 * a NULL argv[0] terminates the argv[] array.
	 *
	 * XXX the special-casing of argv[0] is historical and needs to be
	 * revisited.
	 */
	if (argv == NULL)
		error = EFAULT;
	if (error == 0) {
		while ((argp = (caddr_t)(intptr_t)
			       fuword64((uintptr_t *)argv++)) != NULL) {
			if (argp == (caddr_t)-1) {
				error = EFAULT;
				break;
			}
			error = copyinstr(argp, args->endp,
					  args->space, &length);
			if (error) {
				if (error == ENAMETOOLONG)
					error = E2BIG;
				break;
			}
			args->space -= length;
			args->endp += length;
			args->argc++;
		}
		if (args->argc == 0 && error == 0) {
			length = strlen(args->fname) + 1;
			if (length > args->space) {
				error = E2BIG;
			} else {
				bcopy(args->fname, args->endp, length);
				args->space -= length;
				args->endp += length;
				args->argc++;
			}
		}
	}

	args->begin_envv = args->endp;

	/*
	 * extract environment strings.  envv may be NULL.
	 */
	if (envv && error == 0) {
		while ((envp = (caddr_t)(intptr_t)
			       fuword64((uintptr_t *)envv++))) {
			if (envp == (caddr_t) -1) {
				error = EFAULT;
				break;
			}
			error = copyinstr(envp, args->endp,
					  args->space, &length);
			if (error) {
				if (error == ENAMETOOLONG)
					error = E2BIG;
				break;
			}
			args->space -= length;
			args->endp += length;
			args->envc++;
		}
	}

	return (error);
}

static void
exec_free_args(struct image_args *args)
{
	if (args->buf) {
		objcache_put(exec_objcache, args->buf);
		args->buf = NULL;
	}
}

/*
 * Copy strings out to the new process address space, constructing
 * new arg and env vector tables. Return a pointer to the base
 * so that it can be used as the initial stack pointer.
 *
 * The format is, roughly:
 *
 *	[argv[]]			<-- vectp
 *	[envp[]]
 *	[ELF_Auxargs]
 *
 *	[args & env]			<-- destp
 *	[sgap]
 *	[SPARE_USRSPACE]
 *	[execpath]
 *	[szsigcode]   RO|NX
 *	[ps_strings]  RO|NX		Top of user stack
 *
 */
static register_t *
exec_copyout_strings(struct image_params *imgp)
{
	int argc, envc, sgap;
	int gap;
	int argsenvspace;
	char **vectp;
	char *stringp, *destp, *szsigbase;
	register_t *stack_base;
	struct ps_strings *arginfo;
	size_t execpath_len;
	int szsigcode;

	/*
	 * Calculate string base and vector table pointers.
	 * Also deal with signal trampoline code for this exec type.
	 */
	if (imgp->execpath != NULL && imgp->auxargs != NULL)
		execpath_len = strlen(imgp->execpath) + 1;
	else
		execpath_len = 0;
	arginfo = (struct ps_strings *)PS_STRINGS;
	szsigcode = *(imgp->proc->p_sysent->sv_szsigcode);

	argsenvspace = roundup((ARG_MAX - imgp->args->space), sizeof(char *));
	gap = stackgap_random;
	cpu_ccfence();
	if (gap != 0) {
		if (gap < 0)
			sgap = ALIGN(-gap);
		else
			sgap = ALIGN(karc4random() & (gap - 1));
	} else {
		sgap = 0;
	}

	/*
	 * Calculate destp, which points to [args & env] and above.
	 */
	szsigbase = (char *)(intptr_t)
		    trunc_page64((intptr_t)arginfo - szsigcode);
	szsigbase -= SZSIGCODE_EXTRA_BYTES;
	destp = szsigbase -
		roundup(execpath_len, sizeof(char *)) -
		SPARE_USRSPACE -
		sgap -
		argsenvspace;

	/*
	 * install sigcode
	 */
	if (szsigcode)
		copyout(imgp->proc->p_sysent->sv_sigcode, szsigbase, szsigcode);

	/*
	 * Copy the image path for the rtld
	 */
	if (execpath_len) {
		imgp->execpathp = (uintptr_t)szsigbase -
				  roundup(execpath_len, sizeof(char *));
		copyout(imgp->execpath, (void *)imgp->execpathp, execpath_len);
	}

	/*
	 * Calculate base for argv[], envp[], and ELF_Auxargs.
	 */
	vectp = (char **)destp - (AT_COUNT * 2);
	vectp -= imgp->args->argc + imgp->args->envc + 2;

	stack_base = (register_t *)vectp;

	stringp = imgp->args->begin_argv;
	argc = imgp->args->argc;
	envc = imgp->args->envc;

	/*
	 * Copy out strings - arguments and environment (at destp)
	 */
	copyout(stringp, destp, ARG_MAX - imgp->args->space);

	/*
	 * Fill in "ps_strings" struct for ps, w, etc.
	 */
	suword64((void *)&arginfo->ps_argvstr, (uint64_t)(intptr_t)vectp);
	suword32((void *)&arginfo->ps_nargvstr, argc);

	/*
	 * Fill in argument portion of vector table.
	 */
	for (; argc > 0; --argc) {
		suword64((void *)vectp++, (uintptr_t)destp);
		while (*stringp++ != 0)
			destp++;
		destp++;
	}

	/* a null vector table pointer separates the argp's from the envp's */
	suword64((void *)vectp++, 0);

	suword64((void *)&arginfo->ps_envstr, (uintptr_t)vectp);
	suword32((void *)&arginfo->ps_nenvstr, envc);

	/*
	 * Fill in environment portion of vector table.
	 */
	for (; envc > 0; --envc) {
		suword64((void *)vectp++, (uintptr_t)destp);
		while (*stringp++ != 0)
			destp++;
		destp++;
	}

	/* end of vector table is a null pointer */
	suword64((void *)vectp, 0);

	/*
	 * Make the signal trampoline executable and read-only.
	 */
	vm_map_protect(&imgp->proc->p_vmspace->vm_map,
		       (vm_offset_t)szsigbase,
		       (vm_offset_t)szsigbase + PAGE_SIZE,
		       VM_PROT_READ|VM_PROT_EXECUTE, FALSE);

	return (stack_base);
}

/*
 * Check permissions of file to execute.
 *	Return 0 for success or error code on failure.
 */
int
exec_check_permissions(struct image_params *imgp, struct mount *topmnt)
{
	struct proc *p = imgp->proc;
	struct vnode *vp = imgp->vp;
	struct vattr_lite *lvap = imgp->lvap;
	int error;

	/* Get file attributes */
	error = VOP_GETATTR_LITE(vp, lvap);
	if (error)
		return (error);

	/*
	 * 1) Check if file execution is disabled for the filesystem that this
	 *	file resides on.
	 * 2) Insure that at least one execute bit is on - otherwise root
	 *	will always succeed, and we don't want to happen unless the
	 *	file really is executable.
	 * 3) Insure that the file is a regular file.
	 */
	if ((vp->v_mount->mnt_flag & MNT_NOEXEC) ||
	    ((topmnt != NULL) && (topmnt->mnt_flag & MNT_NOEXEC)) ||
	    ((lvap->va_mode & 0111) == 0) ||
	    (lvap->va_type != VREG)) {
		return (EACCES);
	}

	/*
	 * Capability restrictions on suid or sgid exec?
	 */
	if ((lvap->va_mode & VSUID) && caps_priv_check_self(SYSCAP_NOEXEC_SUID | __SYSCAP_NOROOTTEST))
		return EACCES;
	if ((lvap->va_mode & VSGID) && caps_priv_check_self(SYSCAP_NOEXEC_SGID | __SYSCAP_NOROOTTEST))
		return EACCES;

	/*
	 * Zero length files can't be exec'd
	 */
	if (lvap->va_size == 0)
		return (ENOEXEC);

	/*
	 *  Check for execute permission to file based on current credentials.
	 */
	error = VOP_EACCESS(vp, VEXEC, p->p_ucred);
	if (error)
		return (error);

	/*
	 * Check number of open-for-writes on the file and deny execution
	 * if there are any.
	 */
	if (vp->v_writecount)
		return (ETXTBSY);

	/*
	 * Call filesystem specific open routine, which allows us to read,
	 * write, and mmap the file.  Without the VOP_OPEN we can only
	 * stat the file.
	 */
	error = VOP_OPEN(vp, FREAD, p->p_ucred, NULL);
	if (error)
		return (error);

	return (0);
}

/*
 * Exec handler registration
 */
int
exec_register(const struct execsw *execsw_arg)
{
	const struct execsw **es, **xs, **newexecsw;
	int count = 2;	/* New slot and trailing NULL */

	if (execsw)
		for (es = execsw; *es; es++)
			count++;
	newexecsw = kmalloc(count * sizeof(*es), M_TEMP, M_WAITOK);
	xs = newexecsw;
	if (execsw)
		for (es = execsw; *es; es++)
			*xs++ = *es;
	*xs++ = execsw_arg;
	*xs = NULL;
	if (execsw)
		kfree(execsw, M_TEMP);
	execsw = newexecsw;
	return 0;
}

int
exec_unregister(const struct execsw *execsw_arg)
{
	const struct execsw **es, **xs, **newexecsw;
	int count = 1;

	if (execsw == NULL)
		panic("unregister with no handlers left?");

	for (es = execsw; *es; es++) {
		if (*es == execsw_arg)
			break;
	}
	if (*es == NULL)
		return ENOENT;
	for (es = execsw; *es; es++)
		if (*es != execsw_arg)
			count++;
	newexecsw = kmalloc(count * sizeof(*es), M_TEMP, M_WAITOK);
	xs = newexecsw;
	for (es = execsw; *es; es++)
		if (*es != execsw_arg)
			*xs++ = *es;
	*xs = NULL;
	if (execsw)
		kfree(execsw, M_TEMP);
	execsw = newexecsw;
	return 0;
}