xref: /freebsd/cddl/contrib/opensolaris/lib/libdtrace/common/dt_link.c (revision 87e886953f538edaf48c20214f619c3796617dee)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 #define	ELF_TARGET_ALL
30 #include <elf.h>
31 
32 #include <sys/types.h>
33 #ifdef illumos
34 #include <sys/sysmacros.h>
35 #else
36 #define	P2ROUNDUP(x, align)		(-(-(x) & -(align)))
37 #endif
38 
39 #include <unistd.h>
40 #include <strings.h>
41 #ifdef illumos
42 #include <alloca.h>
43 #endif
44 #include <limits.h>
45 #include <stddef.h>
46 #include <stdlib.h>
47 #include <stdio.h>
48 #include <fcntl.h>
49 #include <errno.h>
50 #ifdef illumos
51 #include <wait.h>
52 #else
53 #include <sys/wait.h>
54 #include <libelf.h>
55 #include <gelf.h>
56 #include <sys/mman.h>
57 #endif
58 #include <assert.h>
59 #include <sys/ipc.h>
60 
61 #include <dt_impl.h>
62 #include <dt_provider.h>
63 #include <dt_program.h>
64 #include <dt_string.h>
65 
66 #define	ESHDR_NULL	0
67 #define	ESHDR_SHSTRTAB	1
68 #define	ESHDR_DOF	2
69 #define	ESHDR_STRTAB	3
70 #define	ESHDR_SYMTAB	4
71 #define	ESHDR_REL	5
72 #define	ESHDR_NUM	6
73 
74 #define	PWRITE_SCN(index, data) \
75 	(lseek64(fd, (off64_t)elf_file.shdr[(index)].sh_offset, SEEK_SET) != \
76 	(off64_t)elf_file.shdr[(index)].sh_offset || \
77 	dt_write(dtp, fd, (data), elf_file.shdr[(index)].sh_size) != \
78 	elf_file.shdr[(index)].sh_size)
79 
80 static const char DTRACE_SHSTRTAB32[] = "\0"
81 ".shstrtab\0"		/* 1 */
82 ".SUNW_dof\0"		/* 11 */
83 ".strtab\0"		/* 21 */
84 ".symtab\0"		/* 29 */
85 #ifdef __sparc
86 ".rela.SUNW_dof";	/* 37 */
87 #else
88 ".rel.SUNW_dof";	/* 37 */
89 #endif
90 
91 static const char DTRACE_SHSTRTAB64[] = "\0"
92 ".shstrtab\0"		/* 1 */
93 ".SUNW_dof\0"		/* 11 */
94 ".strtab\0"		/* 21 */
95 ".symtab\0"		/* 29 */
96 ".rela.SUNW_dof";	/* 37 */
97 
98 static const char DOFSTR[] = "__SUNW_dof";
99 static const char DOFLAZYSTR[] = "___SUNW_dof";
100 
101 typedef struct dt_link_pair {
102 	struct dt_link_pair *dlp_next;	/* next pair in linked list */
103 	void *dlp_str;			/* buffer for string table */
104 	void *dlp_sym;			/* buffer for symbol table */
105 } dt_link_pair_t;
106 
107 typedef struct dof_elf32 {
108 	uint32_t de_nrel;		/* relocation count */
109 #ifdef __sparc
110 	Elf32_Rela *de_rel;		/* array of relocations for sparc */
111 #else
112 	Elf32_Rel *de_rel;		/* array of relocations for x86 */
113 #endif
114 	uint32_t de_nsym;		/* symbol count */
115 	Elf32_Sym *de_sym;		/* array of symbols */
116 	uint32_t de_strlen;		/* size of of string table */
117 	char *de_strtab;		/* string table */
118 	uint32_t de_global;		/* index of the first global symbol */
119 } dof_elf32_t;
120 
121 static int
122 prepare_elf32(dtrace_hdl_t *dtp, const dof_hdr_t *dof, dof_elf32_t *dep)
123 {
124 	dof_sec_t *dofs, *s;
125 	dof_relohdr_t *dofrh;
126 	dof_relodesc_t *dofr;
127 	char *strtab;
128 	int i, j, nrel;
129 	size_t strtabsz = 1;
130 	uint32_t count = 0;
131 	size_t base;
132 	Elf32_Sym *sym;
133 #ifdef __sparc
134 	Elf32_Rela *rel;
135 #else
136 	Elf32_Rel *rel;
137 #endif
138 
139 	/*LINTED*/
140 	dofs = (dof_sec_t *)((char *)dof + dof->dofh_secoff);
141 
142 	/*
143 	 * First compute the size of the string table and the number of
144 	 * relocations present in the DOF.
145 	 */
146 	for (i = 0; i < dof->dofh_secnum; i++) {
147 		if (dofs[i].dofs_type != DOF_SECT_URELHDR)
148 			continue;
149 
150 		/*LINTED*/
151 		dofrh = (dof_relohdr_t *)((char *)dof + dofs[i].dofs_offset);
152 
153 		s = &dofs[dofrh->dofr_strtab];
154 		strtab = (char *)dof + s->dofs_offset;
155 		assert(strtab[0] == '\0');
156 		strtabsz += s->dofs_size - 1;
157 
158 		s = &dofs[dofrh->dofr_relsec];
159 		/*LINTED*/
160 		dofr = (dof_relodesc_t *)((char *)dof + s->dofs_offset);
161 		count += s->dofs_size / s->dofs_entsize;
162 	}
163 
164 	dep->de_strlen = strtabsz;
165 	dep->de_nrel = count;
166 	dep->de_nsym = count + 1; /* the first symbol is always null */
167 
168 	if (dtp->dt_lazyload) {
169 		dep->de_strlen += sizeof (DOFLAZYSTR);
170 		dep->de_nsym++;
171 	} else {
172 		dep->de_strlen += sizeof (DOFSTR);
173 		dep->de_nsym++;
174 	}
175 
176 	if ((dep->de_rel = calloc(dep->de_nrel,
177 	    sizeof (dep->de_rel[0]))) == NULL) {
178 		return (dt_set_errno(dtp, EDT_NOMEM));
179 	}
180 
181 	if ((dep->de_sym = calloc(dep->de_nsym, sizeof (Elf32_Sym))) == NULL) {
182 		free(dep->de_rel);
183 		return (dt_set_errno(dtp, EDT_NOMEM));
184 	}
185 
186 	if ((dep->de_strtab = calloc(dep->de_strlen, 1)) == NULL) {
187 		free(dep->de_rel);
188 		free(dep->de_sym);
189 		return (dt_set_errno(dtp, EDT_NOMEM));
190 	}
191 
192 	count = 0;
193 	strtabsz = 1;
194 	dep->de_strtab[0] = '\0';
195 	rel = dep->de_rel;
196 	sym = dep->de_sym;
197 	dep->de_global = 1;
198 
199 	/*
200 	 * The first symbol table entry must be zeroed and is always ignored.
201 	 */
202 	bzero(sym, sizeof (Elf32_Sym));
203 	sym++;
204 
205 	/*
206 	 * Take a second pass through the DOF sections filling in the
207 	 * memory we allocated.
208 	 */
209 	for (i = 0; i < dof->dofh_secnum; i++) {
210 		if (dofs[i].dofs_type != DOF_SECT_URELHDR)
211 			continue;
212 
213 		/*LINTED*/
214 		dofrh = (dof_relohdr_t *)((char *)dof + dofs[i].dofs_offset);
215 
216 		s = &dofs[dofrh->dofr_strtab];
217 		strtab = (char *)dof + s->dofs_offset;
218 		bcopy(strtab + 1, dep->de_strtab + strtabsz, s->dofs_size);
219 		base = strtabsz;
220 		strtabsz += s->dofs_size - 1;
221 
222 		s = &dofs[dofrh->dofr_relsec];
223 		/*LINTED*/
224 		dofr = (dof_relodesc_t *)((char *)dof + s->dofs_offset);
225 		nrel = s->dofs_size / s->dofs_entsize;
226 
227 		s = &dofs[dofrh->dofr_tgtsec];
228 
229 		for (j = 0; j < nrel; j++) {
230 #if defined(__aarch64__)
231 /* XXX */
232 printf("%s:%s(%d): DOODAD\n",__FUNCTION__,__FILE__,__LINE__);
233 #elif defined(__arm__)
234 /* XXX */
235 printf("%s:%s(%d): DOODAD\n",__FUNCTION__,__FILE__,__LINE__);
236 #elif defined(__i386) || defined(__amd64)
237 			rel->r_offset = s->dofs_offset +
238 			    dofr[j].dofr_offset;
239 			rel->r_info = ELF32_R_INFO(count + dep->de_global,
240 			    R_386_PC32);
241 #elif defined(__mips__)
242 /* XXX */
243 printf("%s:%s(%d): DOODAD\n",__FUNCTION__,__FILE__,__LINE__);
244 #elif defined(__powerpc__)
245 			/*
246 			 * Add 4 bytes to hit the low half of this 64-bit
247 			 * big-endian address.
248 			 */
249 			rel->r_offset = s->dofs_offset +
250 			    dofr[j].dofr_offset + 4;
251 			rel->r_info = ELF32_R_INFO(count + dep->de_global,
252 			    R_PPC_REL32);
253 #elif defined(__riscv__)
254 /* XXX */
255 printf("%s:%s(%d): DOODAD\n",__FUNCTION__,__FILE__,__LINE__);
256 #else
257 #error unknown ISA
258 #endif
259 
260 			sym->st_name = base + dofr[j].dofr_name - 1;
261 			sym->st_value = 0;
262 			sym->st_size = 0;
263 			sym->st_info = ELF32_ST_INFO(STB_GLOBAL, STT_FUNC);
264 			sym->st_other = ELF32_ST_VISIBILITY(STV_HIDDEN);
265 			sym->st_shndx = SHN_UNDEF;
266 
267 			rel++;
268 			sym++;
269 			count++;
270 		}
271 	}
272 
273 	/*
274 	 * Add a symbol for the DOF itself. We use a different symbol for
275 	 * lazily and actively loaded DOF to make them easy to distinguish.
276 	 */
277 	sym->st_name = strtabsz;
278 	sym->st_value = 0;
279 	sym->st_size = dof->dofh_filesz;
280 	sym->st_info = ELF32_ST_INFO(STB_GLOBAL, STT_OBJECT);
281 	sym->st_other = ELF32_ST_VISIBILITY(STV_HIDDEN);
282 	sym->st_shndx = ESHDR_DOF;
283 	sym++;
284 
285 	if (dtp->dt_lazyload) {
286 		bcopy(DOFLAZYSTR, dep->de_strtab + strtabsz,
287 		    sizeof (DOFLAZYSTR));
288 		strtabsz += sizeof (DOFLAZYSTR);
289 	} else {
290 		bcopy(DOFSTR, dep->de_strtab + strtabsz, sizeof (DOFSTR));
291 		strtabsz += sizeof (DOFSTR);
292 	}
293 
294 	assert(count == dep->de_nrel);
295 	assert(strtabsz == dep->de_strlen);
296 
297 	return (0);
298 }
299 
300 
301 typedef struct dof_elf64 {
302 	uint32_t de_nrel;
303 	Elf64_Rela *de_rel;
304 	uint32_t de_nsym;
305 	Elf64_Sym *de_sym;
306 
307 	uint32_t de_strlen;
308 	char *de_strtab;
309 
310 	uint32_t de_global;
311 } dof_elf64_t;
312 
313 static int
314 prepare_elf64(dtrace_hdl_t *dtp, const dof_hdr_t *dof, dof_elf64_t *dep)
315 {
316 	dof_sec_t *dofs, *s;
317 	dof_relohdr_t *dofrh;
318 	dof_relodesc_t *dofr;
319 	char *strtab;
320 	int i, j, nrel;
321 	size_t strtabsz = 1;
322 #ifdef illumos
323 	uint32_t count = 0;
324 #else
325 	uint64_t count = 0;
326 #endif
327 	size_t base;
328 	Elf64_Sym *sym;
329 	Elf64_Rela *rel;
330 
331 	/*LINTED*/
332 	dofs = (dof_sec_t *)((char *)dof + dof->dofh_secoff);
333 
334 	/*
335 	 * First compute the size of the string table and the number of
336 	 * relocations present in the DOF.
337 	 */
338 	for (i = 0; i < dof->dofh_secnum; i++) {
339 		if (dofs[i].dofs_type != DOF_SECT_URELHDR)
340 			continue;
341 
342 		/*LINTED*/
343 		dofrh = (dof_relohdr_t *)((char *)dof + dofs[i].dofs_offset);
344 
345 		s = &dofs[dofrh->dofr_strtab];
346 		strtab = (char *)dof + s->dofs_offset;
347 		assert(strtab[0] == '\0');
348 		strtabsz += s->dofs_size - 1;
349 
350 		s = &dofs[dofrh->dofr_relsec];
351 		/*LINTED*/
352 		dofr = (dof_relodesc_t *)((char *)dof + s->dofs_offset);
353 		count += s->dofs_size / s->dofs_entsize;
354 	}
355 
356 	dep->de_strlen = strtabsz;
357 	dep->de_nrel = count;
358 	dep->de_nsym = count + 1; /* the first symbol is always null */
359 
360 	if (dtp->dt_lazyload) {
361 		dep->de_strlen += sizeof (DOFLAZYSTR);
362 		dep->de_nsym++;
363 	} else {
364 		dep->de_strlen += sizeof (DOFSTR);
365 		dep->de_nsym++;
366 	}
367 
368 	if ((dep->de_rel = calloc(dep->de_nrel,
369 	    sizeof (dep->de_rel[0]))) == NULL) {
370 		return (dt_set_errno(dtp, EDT_NOMEM));
371 	}
372 
373 	if ((dep->de_sym = calloc(dep->de_nsym, sizeof (Elf64_Sym))) == NULL) {
374 		free(dep->de_rel);
375 		return (dt_set_errno(dtp, EDT_NOMEM));
376 	}
377 
378 	if ((dep->de_strtab = calloc(dep->de_strlen, 1)) == NULL) {
379 		free(dep->de_rel);
380 		free(dep->de_sym);
381 		return (dt_set_errno(dtp, EDT_NOMEM));
382 	}
383 
384 	count = 0;
385 	strtabsz = 1;
386 	dep->de_strtab[0] = '\0';
387 	rel = dep->de_rel;
388 	sym = dep->de_sym;
389 	dep->de_global = 1;
390 
391 	/*
392 	 * The first symbol table entry must be zeroed and is always ignored.
393 	 */
394 	bzero(sym, sizeof (Elf64_Sym));
395 	sym++;
396 
397 	/*
398 	 * Take a second pass through the DOF sections filling in the
399 	 * memory we allocated.
400 	 */
401 	for (i = 0; i < dof->dofh_secnum; i++) {
402 		if (dofs[i].dofs_type != DOF_SECT_URELHDR)
403 			continue;
404 
405 		/*LINTED*/
406 		dofrh = (dof_relohdr_t *)((char *)dof + dofs[i].dofs_offset);
407 
408 		s = &dofs[dofrh->dofr_strtab];
409 		strtab = (char *)dof + s->dofs_offset;
410 		bcopy(strtab + 1, dep->de_strtab + strtabsz, s->dofs_size);
411 		base = strtabsz;
412 		strtabsz += s->dofs_size - 1;
413 
414 		s = &dofs[dofrh->dofr_relsec];
415 		/*LINTED*/
416 		dofr = (dof_relodesc_t *)((char *)dof + s->dofs_offset);
417 		nrel = s->dofs_size / s->dofs_entsize;
418 
419 		s = &dofs[dofrh->dofr_tgtsec];
420 
421 		for (j = 0; j < nrel; j++) {
422 #if defined(__aarch64__)
423 /* XXX */
424 #elif defined(__arm__)
425 /* XXX */
426 #elif defined(__mips__)
427 /* XXX */
428 #elif defined(__powerpc__)
429 			rel->r_offset = s->dofs_offset +
430 			    dofr[j].dofr_offset;
431 			rel->r_info = ELF64_R_INFO(count + dep->de_global,
432 			    R_PPC64_REL64);
433 #elif defined(__riscv__)
434 /* XXX */
435 #elif defined(__i386) || defined(__amd64)
436 			rel->r_offset = s->dofs_offset +
437 			    dofr[j].dofr_offset;
438 			rel->r_info = ELF64_R_INFO(count + dep->de_global,
439 			    R_X86_64_PC64);
440 #else
441 #error unknown ISA
442 #endif
443 
444 			sym->st_name = base + dofr[j].dofr_name - 1;
445 			sym->st_value = 0;
446 			sym->st_size = 0;
447 			sym->st_info = GELF_ST_INFO(STB_GLOBAL, STT_FUNC);
448 			sym->st_other = ELF64_ST_VISIBILITY(STV_HIDDEN);
449 			sym->st_shndx = SHN_UNDEF;
450 
451 			rel++;
452 			sym++;
453 			count++;
454 		}
455 	}
456 
457 	/*
458 	 * Add a symbol for the DOF itself. We use a different symbol for
459 	 * lazily and actively loaded DOF to make them easy to distinguish.
460 	 */
461 	sym->st_name = strtabsz;
462 	sym->st_value = 0;
463 	sym->st_size = dof->dofh_filesz;
464 	sym->st_info = GELF_ST_INFO(STB_GLOBAL, STT_OBJECT);
465 	sym->st_other = ELF64_ST_VISIBILITY(STV_HIDDEN);
466 	sym->st_shndx = ESHDR_DOF;
467 	sym++;
468 
469 	if (dtp->dt_lazyload) {
470 		bcopy(DOFLAZYSTR, dep->de_strtab + strtabsz,
471 		    sizeof (DOFLAZYSTR));
472 		strtabsz += sizeof (DOFLAZYSTR);
473 	} else {
474 		bcopy(DOFSTR, dep->de_strtab + strtabsz, sizeof (DOFSTR));
475 		strtabsz += sizeof (DOFSTR);
476 	}
477 
478 	assert(count == dep->de_nrel);
479 	assert(strtabsz == dep->de_strlen);
480 
481 	return (0);
482 }
483 
484 /*
485  * Write out an ELF32 file prologue consisting of a header, section headers,
486  * and a section header string table.  The DOF data will follow this prologue
487  * and complete the contents of the given ELF file.
488  */
489 static int
490 dump_elf32(dtrace_hdl_t *dtp, const dof_hdr_t *dof, int fd)
491 {
492 	struct {
493 		Elf32_Ehdr ehdr;
494 		Elf32_Shdr shdr[ESHDR_NUM];
495 	} elf_file;
496 
497 	Elf32_Shdr *shp;
498 	Elf32_Off off;
499 	dof_elf32_t de;
500 	int ret = 0;
501 	uint_t nshdr;
502 
503 	if (prepare_elf32(dtp, dof, &de) != 0)
504 		return (-1); /* errno is set for us */
505 
506 	/*
507 	 * If there are no relocations, we only need enough sections for
508 	 * the shstrtab and the DOF.
509 	 */
510 	nshdr = de.de_nrel == 0 ? ESHDR_SYMTAB + 1 : ESHDR_NUM;
511 
512 	bzero(&elf_file, sizeof (elf_file));
513 
514 	elf_file.ehdr.e_ident[EI_MAG0] = ELFMAG0;
515 	elf_file.ehdr.e_ident[EI_MAG1] = ELFMAG1;
516 	elf_file.ehdr.e_ident[EI_MAG2] = ELFMAG2;
517 	elf_file.ehdr.e_ident[EI_MAG3] = ELFMAG3;
518 	elf_file.ehdr.e_ident[EI_VERSION] = EV_CURRENT;
519 	elf_file.ehdr.e_ident[EI_CLASS] = ELFCLASS32;
520 #if BYTE_ORDER == _BIG_ENDIAN
521 	elf_file.ehdr.e_ident[EI_DATA] = ELFDATA2MSB;
522 #else
523 	elf_file.ehdr.e_ident[EI_DATA] = ELFDATA2LSB;
524 #endif
525 #if defined(__FreeBSD__)
526 	elf_file.ehdr.e_ident[EI_OSABI] = ELFOSABI_FREEBSD;
527 #endif
528 	elf_file.ehdr.e_type = ET_REL;
529 #if defined(__arm__)
530 	elf_file.ehdr.e_machine = EM_ARM;
531 #elif defined(__mips__)
532 	elf_file.ehdr.e_machine = EM_MIPS;
533 #elif defined(__powerpc__)
534 	elf_file.ehdr.e_machine = EM_PPC;
535 #elif defined(__sparc)
536 	elf_file.ehdr.e_machine = EM_SPARC;
537 #elif defined(__i386) || defined(__amd64)
538 	elf_file.ehdr.e_machine = EM_386;
539 #endif
540 	elf_file.ehdr.e_version = EV_CURRENT;
541 	elf_file.ehdr.e_shoff = sizeof (Elf32_Ehdr);
542 	elf_file.ehdr.e_ehsize = sizeof (Elf32_Ehdr);
543 	elf_file.ehdr.e_phentsize = sizeof (Elf32_Phdr);
544 	elf_file.ehdr.e_shentsize = sizeof (Elf32_Shdr);
545 	elf_file.ehdr.e_shnum = nshdr;
546 	elf_file.ehdr.e_shstrndx = ESHDR_SHSTRTAB;
547 	off = sizeof (elf_file) + nshdr * sizeof (Elf32_Shdr);
548 
549 	shp = &elf_file.shdr[ESHDR_SHSTRTAB];
550 	shp->sh_name = 1; /* DTRACE_SHSTRTAB32[1] = ".shstrtab" */
551 	shp->sh_type = SHT_STRTAB;
552 	shp->sh_offset = off;
553 	shp->sh_size = sizeof (DTRACE_SHSTRTAB32);
554 	shp->sh_addralign = sizeof (char);
555 	off = P2ROUNDUP(shp->sh_offset + shp->sh_size, 8);
556 
557 	shp = &elf_file.shdr[ESHDR_DOF];
558 	shp->sh_name = 11; /* DTRACE_SHSTRTAB32[11] = ".SUNW_dof" */
559 	shp->sh_flags = SHF_ALLOC;
560 	shp->sh_type = SHT_SUNW_dof;
561 	shp->sh_offset = off;
562 	shp->sh_size = dof->dofh_filesz;
563 	shp->sh_addralign = 8;
564 	off = shp->sh_offset + shp->sh_size;
565 
566 	shp = &elf_file.shdr[ESHDR_STRTAB];
567 	shp->sh_name = 21; /* DTRACE_SHSTRTAB32[21] = ".strtab" */
568 	shp->sh_flags = SHF_ALLOC;
569 	shp->sh_type = SHT_STRTAB;
570 	shp->sh_offset = off;
571 	shp->sh_size = de.de_strlen;
572 	shp->sh_addralign = sizeof (char);
573 	off = P2ROUNDUP(shp->sh_offset + shp->sh_size, 4);
574 
575 	shp = &elf_file.shdr[ESHDR_SYMTAB];
576 	shp->sh_name = 29; /* DTRACE_SHSTRTAB32[29] = ".symtab" */
577 	shp->sh_flags = SHF_ALLOC;
578 	shp->sh_type = SHT_SYMTAB;
579 	shp->sh_entsize = sizeof (Elf32_Sym);
580 	shp->sh_link = ESHDR_STRTAB;
581 	shp->sh_offset = off;
582 	shp->sh_info = de.de_global;
583 	shp->sh_size = de.de_nsym * sizeof (Elf32_Sym);
584 	shp->sh_addralign = 4;
585 	off = P2ROUNDUP(shp->sh_offset + shp->sh_size, 4);
586 
587 	if (de.de_nrel == 0) {
588 		if (dt_write(dtp, fd, &elf_file,
589 		    sizeof (elf_file)) != sizeof (elf_file) ||
590 		    PWRITE_SCN(ESHDR_SHSTRTAB, DTRACE_SHSTRTAB32) ||
591 		    PWRITE_SCN(ESHDR_STRTAB, de.de_strtab) ||
592 		    PWRITE_SCN(ESHDR_SYMTAB, de.de_sym) ||
593 		    PWRITE_SCN(ESHDR_DOF, dof)) {
594 			ret = dt_set_errno(dtp, errno);
595 		}
596 	} else {
597 		shp = &elf_file.shdr[ESHDR_REL];
598 		shp->sh_name = 37; /* DTRACE_SHSTRTAB32[37] = ".rel.SUNW_dof" */
599 		shp->sh_flags = SHF_ALLOC;
600 #ifdef __sparc
601 		shp->sh_type = SHT_RELA;
602 #else
603 		shp->sh_type = SHT_REL;
604 #endif
605 		shp->sh_entsize = sizeof (de.de_rel[0]);
606 		shp->sh_link = ESHDR_SYMTAB;
607 		shp->sh_info = ESHDR_DOF;
608 		shp->sh_offset = off;
609 		shp->sh_size = de.de_nrel * sizeof (de.de_rel[0]);
610 		shp->sh_addralign = 4;
611 
612 		if (dt_write(dtp, fd, &elf_file,
613 		    sizeof (elf_file)) != sizeof (elf_file) ||
614 		    PWRITE_SCN(ESHDR_SHSTRTAB, DTRACE_SHSTRTAB32) ||
615 		    PWRITE_SCN(ESHDR_STRTAB, de.de_strtab) ||
616 		    PWRITE_SCN(ESHDR_SYMTAB, de.de_sym) ||
617 		    PWRITE_SCN(ESHDR_REL, de.de_rel) ||
618 		    PWRITE_SCN(ESHDR_DOF, dof)) {
619 			ret = dt_set_errno(dtp, errno);
620 		}
621 	}
622 
623 	free(de.de_strtab);
624 	free(de.de_sym);
625 	free(de.de_rel);
626 
627 	return (ret);
628 }
629 
630 /*
631  * Write out an ELF64 file prologue consisting of a header, section headers,
632  * and a section header string table.  The DOF data will follow this prologue
633  * and complete the contents of the given ELF file.
634  */
635 static int
636 dump_elf64(dtrace_hdl_t *dtp, const dof_hdr_t *dof, int fd)
637 {
638 	struct {
639 		Elf64_Ehdr ehdr;
640 		Elf64_Shdr shdr[ESHDR_NUM];
641 	} elf_file;
642 
643 	Elf64_Shdr *shp;
644 	Elf64_Off off;
645 	dof_elf64_t de;
646 	int ret = 0;
647 	uint_t nshdr;
648 
649 	if (prepare_elf64(dtp, dof, &de) != 0)
650 		return (-1); /* errno is set for us */
651 
652 	/*
653 	 * If there are no relocations, we only need enough sections for
654 	 * the shstrtab and the DOF.
655 	 */
656 	nshdr = de.de_nrel == 0 ? ESHDR_SYMTAB + 1 : ESHDR_NUM;
657 
658 	bzero(&elf_file, sizeof (elf_file));
659 
660 	elf_file.ehdr.e_ident[EI_MAG0] = ELFMAG0;
661 	elf_file.ehdr.e_ident[EI_MAG1] = ELFMAG1;
662 	elf_file.ehdr.e_ident[EI_MAG2] = ELFMAG2;
663 	elf_file.ehdr.e_ident[EI_MAG3] = ELFMAG3;
664 	elf_file.ehdr.e_ident[EI_VERSION] = EV_CURRENT;
665 	elf_file.ehdr.e_ident[EI_CLASS] = ELFCLASS64;
666 #if BYTE_ORDER == _BIG_ENDIAN
667 	elf_file.ehdr.e_ident[EI_DATA] = ELFDATA2MSB;
668 #else
669 	elf_file.ehdr.e_ident[EI_DATA] = ELFDATA2LSB;
670 #endif
671 #if defined(__FreeBSD__)
672 	elf_file.ehdr.e_ident[EI_OSABI] = ELFOSABI_FREEBSD;
673 #endif
674 	elf_file.ehdr.e_type = ET_REL;
675 #if defined(__arm__)
676 	elf_file.ehdr.e_machine = EM_ARM;
677 #elif defined(__mips__)
678 	elf_file.ehdr.e_machine = EM_MIPS;
679 #elif defined(__powerpc64__)
680 	elf_file.ehdr.e_machine = EM_PPC64;
681 #elif defined(__sparc)
682 	elf_file.ehdr.e_machine = EM_SPARCV9;
683 #elif defined(__i386) || defined(__amd64)
684 	elf_file.ehdr.e_machine = EM_AMD64;
685 #endif
686 	elf_file.ehdr.e_version = EV_CURRENT;
687 	elf_file.ehdr.e_shoff = sizeof (Elf64_Ehdr);
688 	elf_file.ehdr.e_ehsize = sizeof (Elf64_Ehdr);
689 	elf_file.ehdr.e_phentsize = sizeof (Elf64_Phdr);
690 	elf_file.ehdr.e_shentsize = sizeof (Elf64_Shdr);
691 	elf_file.ehdr.e_shnum = nshdr;
692 	elf_file.ehdr.e_shstrndx = ESHDR_SHSTRTAB;
693 	off = sizeof (elf_file) + nshdr * sizeof (Elf64_Shdr);
694 
695 	shp = &elf_file.shdr[ESHDR_SHSTRTAB];
696 	shp->sh_name = 1; /* DTRACE_SHSTRTAB64[1] = ".shstrtab" */
697 	shp->sh_type = SHT_STRTAB;
698 	shp->sh_offset = off;
699 	shp->sh_size = sizeof (DTRACE_SHSTRTAB64);
700 	shp->sh_addralign = sizeof (char);
701 	off = P2ROUNDUP(shp->sh_offset + shp->sh_size, 8);
702 
703 	shp = &elf_file.shdr[ESHDR_DOF];
704 	shp->sh_name = 11; /* DTRACE_SHSTRTAB64[11] = ".SUNW_dof" */
705 	shp->sh_flags = SHF_ALLOC;
706 	shp->sh_type = SHT_SUNW_dof;
707 	shp->sh_offset = off;
708 	shp->sh_size = dof->dofh_filesz;
709 	shp->sh_addralign = 8;
710 	off = shp->sh_offset + shp->sh_size;
711 
712 	shp = &elf_file.shdr[ESHDR_STRTAB];
713 	shp->sh_name = 21; /* DTRACE_SHSTRTAB64[21] = ".strtab" */
714 	shp->sh_flags = SHF_ALLOC;
715 	shp->sh_type = SHT_STRTAB;
716 	shp->sh_offset = off;
717 	shp->sh_size = de.de_strlen;
718 	shp->sh_addralign = sizeof (char);
719 	off = P2ROUNDUP(shp->sh_offset + shp->sh_size, 8);
720 
721 	shp = &elf_file.shdr[ESHDR_SYMTAB];
722 	shp->sh_name = 29; /* DTRACE_SHSTRTAB64[29] = ".symtab" */
723 	shp->sh_flags = SHF_ALLOC;
724 	shp->sh_type = SHT_SYMTAB;
725 	shp->sh_entsize = sizeof (Elf64_Sym);
726 	shp->sh_link = ESHDR_STRTAB;
727 	shp->sh_offset = off;
728 	shp->sh_info = de.de_global;
729 	shp->sh_size = de.de_nsym * sizeof (Elf64_Sym);
730 	shp->sh_addralign = 8;
731 	off = P2ROUNDUP(shp->sh_offset + shp->sh_size, 8);
732 
733 	if (de.de_nrel == 0) {
734 		if (dt_write(dtp, fd, &elf_file,
735 		    sizeof (elf_file)) != sizeof (elf_file) ||
736 		    PWRITE_SCN(ESHDR_SHSTRTAB, DTRACE_SHSTRTAB64) ||
737 		    PWRITE_SCN(ESHDR_STRTAB, de.de_strtab) ||
738 		    PWRITE_SCN(ESHDR_SYMTAB, de.de_sym) ||
739 		    PWRITE_SCN(ESHDR_DOF, dof)) {
740 			ret = dt_set_errno(dtp, errno);
741 		}
742 	} else {
743 		shp = &elf_file.shdr[ESHDR_REL];
744 		shp->sh_name = 37; /* DTRACE_SHSTRTAB64[37] = ".rel.SUNW_dof" */
745 		shp->sh_flags = SHF_ALLOC;
746 		shp->sh_type = SHT_RELA;
747 		shp->sh_entsize = sizeof (de.de_rel[0]);
748 		shp->sh_link = ESHDR_SYMTAB;
749 		shp->sh_info = ESHDR_DOF;
750 		shp->sh_offset = off;
751 		shp->sh_size = de.de_nrel * sizeof (de.de_rel[0]);
752 		shp->sh_addralign = 8;
753 
754 		if (dt_write(dtp, fd, &elf_file,
755 		    sizeof (elf_file)) != sizeof (elf_file) ||
756 		    PWRITE_SCN(ESHDR_SHSTRTAB, DTRACE_SHSTRTAB64) ||
757 		    PWRITE_SCN(ESHDR_STRTAB, de.de_strtab) ||
758 		    PWRITE_SCN(ESHDR_SYMTAB, de.de_sym) ||
759 		    PWRITE_SCN(ESHDR_REL, de.de_rel) ||
760 		    PWRITE_SCN(ESHDR_DOF, dof)) {
761 			ret = dt_set_errno(dtp, errno);
762 		}
763 	}
764 
765 	free(de.de_strtab);
766 	free(de.de_sym);
767 	free(de.de_rel);
768 
769 	return (ret);
770 }
771 
772 static int
773 dt_symtab_lookup(Elf_Data *data_sym, int start, int end, uintptr_t addr,
774     uint_t shn, GElf_Sym *sym, int uses_funcdesc, Elf *elf)
775 {
776 	Elf64_Addr symval;
777 	Elf_Scn *opd_scn;
778 	Elf_Data *opd_desc;
779 	int i;
780 
781 	for (i = start; i < end && gelf_getsym(data_sym, i, sym) != NULL; i++) {
782 		if (GELF_ST_TYPE(sym->st_info) == STT_FUNC) {
783 			symval = sym->st_value;
784 			if (uses_funcdesc) {
785 				opd_scn = elf_getscn(elf, sym->st_shndx);
786 				opd_desc = elf_rawdata(opd_scn, NULL);
787 				symval =
788 				    *(uint64_t*)((char *)opd_desc->d_buf + symval);
789 			}
790 			if ((uses_funcdesc || shn == sym->st_shndx) &&
791 			    symval <= addr && addr < symval + sym->st_size)
792 				return (0);
793 		}
794 	}
795 
796 	return (-1);
797 }
798 
799 #if defined(__aarch64__)
800 /* XXX */
801 static int
802 dt_modtext(dtrace_hdl_t *dtp, char *p, int isenabled, GElf_Rela *rela,
803     uint32_t *off)
804 {
805 printf("%s:%s(%d): DOODAD\n",__FUNCTION__,__FILE__,__LINE__);
806 	return (0);
807 }
808 #elif defined(__arm__)
809 /* XXX */
810 static int
811 dt_modtext(dtrace_hdl_t *dtp, char *p, int isenabled, GElf_Rela *rela,
812     uint32_t *off)
813 {
814 printf("%s:%s(%d): DOODAD\n",__FUNCTION__,__FILE__,__LINE__);
815 	return (0);
816 }
817 #elif defined(__mips__)
818 /* XXX */
819 static int
820 dt_modtext(dtrace_hdl_t *dtp, char *p, int isenabled, GElf_Rela *rela,
821     uint32_t *off)
822 {
823 printf("%s:%s(%d): DOODAD\n",__FUNCTION__,__FILE__,__LINE__);
824 	return (0);
825 }
826 #elif defined(__powerpc__)
827 /* The sentinel is 'xor r3,r3,r3'. */
828 #define DT_OP_XOR_R3	0x7c631a78
829 
830 #define DT_OP_NOP		0x60000000
831 #define DT_OP_BLR		0x4e800020
832 
833 /* This captures all forms of branching to address. */
834 #define DT_IS_BRANCH(inst)	((inst & 0xfc000000) == 0x48000000)
835 #define DT_IS_BL(inst)	(DT_IS_BRANCH(inst) && (inst & 0x01))
836 
837 /* XXX */
838 static int
839 dt_modtext(dtrace_hdl_t *dtp, char *p, int isenabled, GElf_Rela *rela,
840     uint32_t *off)
841 {
842 	uint32_t *ip;
843 
844 	if ((rela->r_offset & (sizeof (uint32_t) - 1)) != 0)
845 		return (-1);
846 
847 	/*LINTED*/
848 	ip = (uint32_t *)(p + rela->r_offset);
849 
850 	/*
851 	 * We only know about some specific relocation types.
852 	 */
853 	if (GELF_R_TYPE(rela->r_info) != R_PPC_REL24 &&
854 	    GELF_R_TYPE(rela->r_info) != R_PPC_PLTREL24)
855 		return (-1);
856 
857 	/*
858 	 * We may have already processed this object file in an earlier linker
859 	 * invocation. Check to see if the present instruction sequence matches
860 	 * the one we would install below.
861 	 */
862 	if (isenabled) {
863 		if (ip[0] == DT_OP_XOR_R3) {
864 			(*off) += sizeof (ip[0]);
865 			return (0);
866 		}
867 	} else {
868 		if (ip[0] == DT_OP_NOP) {
869 			(*off) += sizeof (ip[0]);
870 			return (0);
871 		}
872 	}
873 
874 	/*
875 	 * We only expect branch to address instructions.
876 	 */
877 	if (!DT_IS_BRANCH(ip[0])) {
878 		dt_dprintf("found %x instead of a branch instruction at %llx\n",
879 		    ip[0], (u_longlong_t)rela->r_offset);
880 		return (-1);
881 	}
882 
883 	if (isenabled) {
884 		/*
885 		 * It would necessarily indicate incorrect usage if an is-
886 		 * enabled probe were tail-called so flag that as an error.
887 		 * It's also potentially (very) tricky to handle gracefully,
888 		 * but could be done if this were a desired use scenario.
889 		 */
890 		if (!DT_IS_BL(ip[0])) {
891 			dt_dprintf("tail call to is-enabled probe at %llx\n",
892 			    (u_longlong_t)rela->r_offset);
893 			return (-1);
894 		}
895 
896 		ip[0] = DT_OP_XOR_R3;
897 		(*off) += sizeof (ip[0]);
898 	} else {
899 		if (DT_IS_BL(ip[0]))
900 			ip[0] = DT_OP_NOP;
901 		else
902 			ip[0] = DT_OP_BLR;
903 	}
904 
905 	return (0);
906 }
907 #elif defined(__riscv__)
908 /* XXX */
909 static int
910 dt_modtext(dtrace_hdl_t *dtp, char *p, int isenabled, GElf_Rela *rela,
911     uint32_t *off)
912 {
913 printf("%s:%s(%d): DOODAD\n",__FUNCTION__,__FILE__,__LINE__);
914 	return (0);
915 }
916 #elif defined(__sparc)
917 
918 #define	DT_OP_RET		0x81c7e008
919 #define	DT_OP_NOP		0x01000000
920 #define	DT_OP_CALL		0x40000000
921 #define	DT_OP_CLR_O0		0x90102000
922 
923 #define	DT_IS_MOV_O7(inst)	(((inst) & 0xffffe000) == 0x9e100000)
924 #define	DT_IS_RESTORE(inst)	(((inst) & 0xc1f80000) == 0x81e80000)
925 #define	DT_IS_RETL(inst)	(((inst) & 0xfff83fff) == 0x81c02008)
926 
927 #define	DT_RS2(inst)		((inst) & 0x1f)
928 #define	DT_MAKE_RETL(reg)	(0x81c02008 | ((reg) << 14))
929 
930 /*ARGSUSED*/
931 static int
932 dt_modtext(dtrace_hdl_t *dtp, char *p, int isenabled, GElf_Rela *rela,
933     uint32_t *off)
934 {
935 	uint32_t *ip;
936 
937 	if ((rela->r_offset & (sizeof (uint32_t) - 1)) != 0)
938 		return (-1);
939 
940 	/*LINTED*/
941 	ip = (uint32_t *)(p + rela->r_offset);
942 
943 	/*
944 	 * We only know about some specific relocation types.
945 	 */
946 	if (GELF_R_TYPE(rela->r_info) != R_SPARC_WDISP30 &&
947 	    GELF_R_TYPE(rela->r_info) != R_SPARC_WPLT30)
948 		return (-1);
949 
950 	/*
951 	 * We may have already processed this object file in an earlier linker
952 	 * invocation. Check to see if the present instruction sequence matches
953 	 * the one we would install below.
954 	 */
955 	if (isenabled) {
956 		if (ip[0] == DT_OP_NOP) {
957 			(*off) += sizeof (ip[0]);
958 			return (0);
959 		}
960 	} else {
961 		if (DT_IS_RESTORE(ip[1])) {
962 			if (ip[0] == DT_OP_RET) {
963 				(*off) += sizeof (ip[0]);
964 				return (0);
965 			}
966 		} else if (DT_IS_MOV_O7(ip[1])) {
967 			if (DT_IS_RETL(ip[0]))
968 				return (0);
969 		} else {
970 			if (ip[0] == DT_OP_NOP) {
971 				(*off) += sizeof (ip[0]);
972 				return (0);
973 			}
974 		}
975 	}
976 
977 	/*
978 	 * We only expect call instructions with a displacement of 0.
979 	 */
980 	if (ip[0] != DT_OP_CALL) {
981 		dt_dprintf("found %x instead of a call instruction at %llx\n",
982 		    ip[0], (u_longlong_t)rela->r_offset);
983 		return (-1);
984 	}
985 
986 	if (isenabled) {
987 		/*
988 		 * It would necessarily indicate incorrect usage if an is-
989 		 * enabled probe were tail-called so flag that as an error.
990 		 * It's also potentially (very) tricky to handle gracefully,
991 		 * but could be done if this were a desired use scenario.
992 		 */
993 		if (DT_IS_RESTORE(ip[1]) || DT_IS_MOV_O7(ip[1])) {
994 			dt_dprintf("tail call to is-enabled probe at %llx\n",
995 			    (u_longlong_t)rela->r_offset);
996 			return (-1);
997 		}
998 
999 
1000 		/*
1001 		 * On SPARC, we take advantage of the fact that the first
1002 		 * argument shares the same register as for the return value.
1003 		 * The macro handles the work of zeroing that register so we
1004 		 * don't need to do anything special here. We instrument the
1005 		 * instruction in the delay slot as we'll need to modify the
1006 		 * return register after that instruction has been emulated.
1007 		 */
1008 		ip[0] = DT_OP_NOP;
1009 		(*off) += sizeof (ip[0]);
1010 	} else {
1011 		/*
1012 		 * If the call is followed by a restore, it's a tail call so
1013 		 * change the call to a ret. If the call if followed by a mov
1014 		 * of a register into %o7, it's a tail call in leaf context
1015 		 * so change the call to a retl-like instruction that returns
1016 		 * to that register value + 8 (rather than the typical %o7 +
1017 		 * 8); the delay slot instruction is left, but should have no
1018 		 * effect. Otherwise we change the call to be a nop. We
1019 		 * identify the subsequent instruction as the probe point in
1020 		 * all but the leaf tail-call case to ensure that arguments to
1021 		 * the probe are complete and consistent. An astute, though
1022 		 * largely hypothetical, observer would note that there is the
1023 		 * possibility of a false-positive probe firing if the function
1024 		 * contained a branch to the instruction in the delay slot of
1025 		 * the call. Fixing this would require significant in-kernel
1026 		 * modifications, and isn't worth doing until we see it in the
1027 		 * wild.
1028 		 */
1029 		if (DT_IS_RESTORE(ip[1])) {
1030 			ip[0] = DT_OP_RET;
1031 			(*off) += sizeof (ip[0]);
1032 		} else if (DT_IS_MOV_O7(ip[1])) {
1033 			ip[0] = DT_MAKE_RETL(DT_RS2(ip[1]));
1034 		} else {
1035 			ip[0] = DT_OP_NOP;
1036 			(*off) += sizeof (ip[0]);
1037 		}
1038 	}
1039 
1040 	return (0);
1041 }
1042 
1043 #elif defined(__i386) || defined(__amd64)
1044 
1045 #define	DT_OP_NOP		0x90
1046 #define	DT_OP_RET		0xc3
1047 #define	DT_OP_CALL		0xe8
1048 #define	DT_OP_JMP32		0xe9
1049 #define	DT_OP_REX_RAX		0x48
1050 #define	DT_OP_XOR_EAX_0		0x33
1051 #define	DT_OP_XOR_EAX_1		0xc0
1052 
1053 static int
1054 dt_modtext(dtrace_hdl_t *dtp, char *p, int isenabled, GElf_Rela *rela,
1055     uint32_t *off)
1056 {
1057 	uint8_t *ip = (uint8_t *)(p + rela->r_offset - 1);
1058 	uint8_t ret;
1059 
1060 	/*
1061 	 * On x86, the first byte of the instruction is the call opcode and
1062 	 * the next four bytes are the 32-bit address; the relocation is for
1063 	 * the address operand. We back up the offset to the first byte of
1064 	 * the instruction. For is-enabled probes, we later advance the offset
1065 	 * so that it hits the first nop in the instruction sequence.
1066 	 */
1067 	(*off) -= 1;
1068 
1069 	/*
1070 	 * We only know about some specific relocation types. Luckily
1071 	 * these types have the same values on both 32-bit and 64-bit
1072 	 * x86 architectures.
1073 	 */
1074 	if (GELF_R_TYPE(rela->r_info) != R_386_PC32 &&
1075 	    GELF_R_TYPE(rela->r_info) != R_386_PLT32)
1076 		return (-1);
1077 
1078 	/*
1079 	 * We may have already processed this object file in an earlier linker
1080 	 * invocation. Check to see if the present instruction sequence matches
1081 	 * the one we would install. For is-enabled probes, we advance the
1082 	 * offset to the first nop instruction in the sequence to match the
1083 	 * text modification code below.
1084 	 */
1085 	if (!isenabled) {
1086 		if ((ip[0] == DT_OP_NOP || ip[0] == DT_OP_RET) &&
1087 		    ip[1] == DT_OP_NOP && ip[2] == DT_OP_NOP &&
1088 		    ip[3] == DT_OP_NOP && ip[4] == DT_OP_NOP)
1089 			return (0);
1090 	} else if (dtp->dt_oflags & DTRACE_O_LP64) {
1091 		if (ip[0] == DT_OP_REX_RAX &&
1092 		    ip[1] == DT_OP_XOR_EAX_0 && ip[2] == DT_OP_XOR_EAX_1 &&
1093 		    (ip[3] == DT_OP_NOP || ip[3] == DT_OP_RET) &&
1094 		    ip[4] == DT_OP_NOP) {
1095 			(*off) += 3;
1096 			return (0);
1097 		}
1098 	} else {
1099 		if (ip[0] == DT_OP_XOR_EAX_0 && ip[1] == DT_OP_XOR_EAX_1 &&
1100 		    (ip[2] == DT_OP_NOP || ip[2] == DT_OP_RET) &&
1101 		    ip[3] == DT_OP_NOP && ip[4] == DT_OP_NOP) {
1102 			(*off) += 2;
1103 			return (0);
1104 		}
1105 	}
1106 
1107 	/*
1108 	 * We expect either a call instrution with a 32-bit displacement or a
1109 	 * jmp instruction with a 32-bit displacement acting as a tail-call.
1110 	 */
1111 	if (ip[0] != DT_OP_CALL && ip[0] != DT_OP_JMP32) {
1112 		dt_dprintf("found %x instead of a call or jmp instruction at "
1113 		    "%llx\n", ip[0], (u_longlong_t)rela->r_offset);
1114 		return (-1);
1115 	}
1116 
1117 	ret = (ip[0] == DT_OP_JMP32) ? DT_OP_RET : DT_OP_NOP;
1118 
1119 	/*
1120 	 * Establish the instruction sequence -- all nops for probes, and an
1121 	 * instruction to clear the return value register (%eax/%rax) followed
1122 	 * by nops for is-enabled probes. For is-enabled probes, we advance
1123 	 * the offset to the first nop. This isn't stricly necessary but makes
1124 	 * for more readable disassembly when the probe is enabled.
1125 	 */
1126 	if (!isenabled) {
1127 		ip[0] = ret;
1128 		ip[1] = DT_OP_NOP;
1129 		ip[2] = DT_OP_NOP;
1130 		ip[3] = DT_OP_NOP;
1131 		ip[4] = DT_OP_NOP;
1132 	} else if (dtp->dt_oflags & DTRACE_O_LP64) {
1133 		ip[0] = DT_OP_REX_RAX;
1134 		ip[1] = DT_OP_XOR_EAX_0;
1135 		ip[2] = DT_OP_XOR_EAX_1;
1136 		ip[3] = ret;
1137 		ip[4] = DT_OP_NOP;
1138 		(*off) += 3;
1139 	} else {
1140 		ip[0] = DT_OP_XOR_EAX_0;
1141 		ip[1] = DT_OP_XOR_EAX_1;
1142 		ip[2] = ret;
1143 		ip[3] = DT_OP_NOP;
1144 		ip[4] = DT_OP_NOP;
1145 		(*off) += 2;
1146 	}
1147 
1148 	return (0);
1149 }
1150 
1151 #else
1152 #error unknown ISA
1153 #endif
1154 
1155 /*PRINTFLIKE5*/
1156 static int
1157 dt_link_error(dtrace_hdl_t *dtp, Elf *elf, int fd, dt_link_pair_t *bufs,
1158     const char *format, ...)
1159 {
1160 	va_list ap;
1161 	dt_link_pair_t *pair;
1162 
1163 	va_start(ap, format);
1164 	dt_set_errmsg(dtp, NULL, NULL, NULL, 0, format, ap);
1165 	va_end(ap);
1166 
1167 	if (elf != NULL)
1168 		(void) elf_end(elf);
1169 
1170 	if (fd >= 0)
1171 		(void) close(fd);
1172 
1173 	while ((pair = bufs) != NULL) {
1174 		bufs = pair->dlp_next;
1175 		dt_free(dtp, pair->dlp_str);
1176 		dt_free(dtp, pair->dlp_sym);
1177 		dt_free(dtp, pair);
1178 	}
1179 
1180 	return (dt_set_errno(dtp, EDT_COMPILER));
1181 }
1182 
1183 static int
1184 process_obj(dtrace_hdl_t *dtp, const char *obj, int *eprobesp)
1185 {
1186 	static const char dt_prefix[] = "__dtrace";
1187 	static const char dt_enabled[] = "enabled";
1188 	static const char dt_symprefix[] = "$dtrace";
1189 	static const char dt_symfmt[] = "%s%ld.%s";
1190 	char probename[DTRACE_NAMELEN];
1191 	int fd, i, ndx, eprobe, mod = 0;
1192 	Elf *elf = NULL;
1193 	GElf_Ehdr ehdr;
1194 	Elf_Scn *scn_rel, *scn_sym, *scn_str, *scn_tgt;
1195 	Elf_Data *data_rel, *data_sym, *data_str, *data_tgt;
1196 	GElf_Shdr shdr_rel, shdr_sym, shdr_str, shdr_tgt;
1197 	GElf_Sym rsym, fsym, dsym;
1198 	GElf_Rela rela;
1199 	char *s, *p, *r;
1200 	char pname[DTRACE_PROVNAMELEN];
1201 	dt_provider_t *pvp;
1202 	dt_probe_t *prp;
1203 	uint32_t off, eclass, emachine1, emachine2;
1204 	size_t symsize, osym, nsym, isym, istr, len;
1205 	key_t objkey;
1206 	dt_link_pair_t *pair, *bufs = NULL;
1207 	dt_strtab_t *strtab;
1208 	void *tmp;
1209 
1210 	if ((fd = open64(obj, O_RDWR)) == -1) {
1211 		return (dt_link_error(dtp, elf, fd, bufs,
1212 		    "failed to open %s: %s", obj, strerror(errno)));
1213 	}
1214 
1215 	if ((elf = elf_begin(fd, ELF_C_RDWR, NULL)) == NULL) {
1216 		return (dt_link_error(dtp, elf, fd, bufs,
1217 		    "failed to process %s: %s", obj, elf_errmsg(elf_errno())));
1218 	}
1219 
1220 	switch (elf_kind(elf)) {
1221 	case ELF_K_ELF:
1222 		break;
1223 	case ELF_K_AR:
1224 		return (dt_link_error(dtp, elf, fd, bufs, "archives are not "
1225 		    "permitted; use the contents of the archive instead: %s",
1226 		    obj));
1227 	default:
1228 		return (dt_link_error(dtp, elf, fd, bufs,
1229 		    "invalid file type: %s", obj));
1230 	}
1231 
1232 	if (gelf_getehdr(elf, &ehdr) == NULL) {
1233 		return (dt_link_error(dtp, elf, fd, bufs, "corrupt file: %s",
1234 		    obj));
1235 	}
1236 
1237 	if (dtp->dt_oflags & DTRACE_O_LP64) {
1238 		eclass = ELFCLASS64;
1239 #if defined(__mips__)
1240 		emachine1 = emachine2 = EM_MIPS;
1241 #elif defined(__powerpc__)
1242 		emachine1 = emachine2 = EM_PPC64;
1243 #elif defined(__sparc)
1244 		emachine1 = emachine2 = EM_SPARCV9;
1245 #elif defined(__i386) || defined(__amd64)
1246 		emachine1 = emachine2 = EM_AMD64;
1247 #endif
1248 		symsize = sizeof (Elf64_Sym);
1249 	} else {
1250 		eclass = ELFCLASS32;
1251 #if defined(__arm__)
1252 		emachine1 = emachine2 = EM_ARM;
1253 #elif defined(__mips__)
1254 		emachine1 = emachine2 = EM_MIPS;
1255 #elif defined(__powerpc__)
1256 		emachine1 = emachine2 = EM_PPC;
1257 #elif defined(__sparc)
1258 		emachine1 = EM_SPARC;
1259 		emachine2 = EM_SPARC32PLUS;
1260 #elif defined(__i386) || defined(__amd64)
1261 		emachine1 = emachine2 = EM_386;
1262 #endif
1263 		symsize = sizeof (Elf32_Sym);
1264 	}
1265 
1266 	if (ehdr.e_ident[EI_CLASS] != eclass) {
1267 		return (dt_link_error(dtp, elf, fd, bufs,
1268 		    "incorrect ELF class for object file: %s", obj));
1269 	}
1270 
1271 	if (ehdr.e_machine != emachine1 && ehdr.e_machine != emachine2) {
1272 		return (dt_link_error(dtp, elf, fd, bufs,
1273 		    "incorrect ELF machine type for object file: %s", obj));
1274 	}
1275 
1276 	/*
1277 	 * We use this token as a relatively unique handle for this file on the
1278 	 * system in order to disambiguate potential conflicts between files of
1279 	 * the same name which contain identially named local symbols.
1280 	 */
1281 	if ((objkey = ftok(obj, 0)) == (key_t)-1) {
1282 		return (dt_link_error(dtp, elf, fd, bufs,
1283 		    "failed to generate unique key for object file: %s", obj));
1284 	}
1285 
1286 	scn_rel = NULL;
1287 	while ((scn_rel = elf_nextscn(elf, scn_rel)) != NULL) {
1288 		if (gelf_getshdr(scn_rel, &shdr_rel) == NULL)
1289 			goto err;
1290 
1291 		/*
1292 		 * Skip any non-relocation sections.
1293 		 */
1294 		if (shdr_rel.sh_type != SHT_RELA && shdr_rel.sh_type != SHT_REL)
1295 			continue;
1296 
1297 		if ((data_rel = elf_getdata(scn_rel, NULL)) == NULL)
1298 			goto err;
1299 
1300 		/*
1301 		 * Grab the section, section header and section data for the
1302 		 * symbol table that this relocation section references.
1303 		 */
1304 		if ((scn_sym = elf_getscn(elf, shdr_rel.sh_link)) == NULL ||
1305 		    gelf_getshdr(scn_sym, &shdr_sym) == NULL ||
1306 		    (data_sym = elf_getdata(scn_sym, NULL)) == NULL)
1307 			goto err;
1308 
1309 		/*
1310 		 * Ditto for that symbol table's string table.
1311 		 */
1312 		if ((scn_str = elf_getscn(elf, shdr_sym.sh_link)) == NULL ||
1313 		    gelf_getshdr(scn_str, &shdr_str) == NULL ||
1314 		    (data_str = elf_getdata(scn_str, NULL)) == NULL)
1315 			goto err;
1316 
1317 		/*
1318 		 * Grab the section, section header and section data for the
1319 		 * target section for the relocations. For the relocations
1320 		 * we're looking for -- this will typically be the text of the
1321 		 * object file.
1322 		 */
1323 		if ((scn_tgt = elf_getscn(elf, shdr_rel.sh_info)) == NULL ||
1324 		    gelf_getshdr(scn_tgt, &shdr_tgt) == NULL ||
1325 		    (data_tgt = elf_getdata(scn_tgt, NULL)) == NULL)
1326 			goto err;
1327 
1328 		/*
1329 		 * We're looking for relocations to symbols matching this form:
1330 		 *
1331 		 *   __dtrace[enabled]_<prov>___<probe>
1332 		 *
1333 		 * For the generated object, we need to record the location
1334 		 * identified by the relocation, and create a new relocation
1335 		 * in the generated object that will be resolved at link time
1336 		 * to the location of the function in which the probe is
1337 		 * embedded. In the target object, we change the matched symbol
1338 		 * so that it will be ignored at link time, and we modify the
1339 		 * target (text) section to replace the call instruction with
1340 		 * one or more nops.
1341 		 *
1342 		 * To avoid runtime overhead, the relocations added to the
1343 		 * generated object should be resolved at static link time. We
1344 		 * therefore create aliases for the functions that contain
1345 		 * probes. An alias is global (so that the relocation from the
1346 		 * generated object can be resolved), and hidden (so that its
1347 		 * address is known at static link time). Such aliases have this
1348 		 * form:
1349 		 *
1350 		 *   $dtrace<key>.<function>
1351 		 *
1352 		 * We take a first pass through all the relocations to
1353 		 * populate our string table and count the number of extra
1354 		 * symbols we'll require.
1355 		 */
1356 		strtab = dt_strtab_create(1);
1357 		nsym = 0;
1358 		isym = data_sym->d_size / symsize;
1359 		istr = data_str->d_size;
1360 
1361 		for (i = 0; i < shdr_rel.sh_size / shdr_rel.sh_entsize; i++) {
1362 
1363 			if (shdr_rel.sh_type == SHT_RELA) {
1364 				if (gelf_getrela(data_rel, i, &rela) == NULL)
1365 					continue;
1366 			} else {
1367 				GElf_Rel rel;
1368 				if (gelf_getrel(data_rel, i, &rel) == NULL)
1369 					continue;
1370 				rela.r_offset = rel.r_offset;
1371 				rela.r_info = rel.r_info;
1372 				rela.r_addend = 0;
1373 			}
1374 
1375 			if (gelf_getsym(data_sym, GELF_R_SYM(rela.r_info),
1376 			    &rsym) == NULL) {
1377 				dt_strtab_destroy(strtab);
1378 				goto err;
1379 			}
1380 
1381 			s = (char *)data_str->d_buf + rsym.st_name;
1382 
1383 			if (strncmp(s, dt_prefix, sizeof (dt_prefix) - 1) != 0)
1384 				continue;
1385 
1386 			if (dt_symtab_lookup(data_sym, 0, isym, rela.r_offset,
1387 			    shdr_rel.sh_info, &fsym, (emachine1 == EM_PPC64),
1388 			    elf) != 0) {
1389 				dt_strtab_destroy(strtab);
1390 				goto err;
1391 			}
1392 
1393 			if (fsym.st_name > data_str->d_size) {
1394 				dt_strtab_destroy(strtab);
1395 				goto err;
1396 			}
1397 
1398 			s = (char *)data_str->d_buf + fsym.st_name;
1399 
1400 			/*
1401 			 * If this symbol isn't of type function, we've really
1402 			 * driven off the rails or the object file is corrupt.
1403 			 */
1404 			if (GELF_ST_TYPE(fsym.st_info) != STT_FUNC) {
1405 				dt_strtab_destroy(strtab);
1406 				return (dt_link_error(dtp, elf, fd, bufs,
1407 				    "expected %s to be of type function", s));
1408 			}
1409 
1410 			len = snprintf(NULL, 0, dt_symfmt, dt_symprefix,
1411 			    objkey, s) + 1;
1412 			if ((p = dt_alloc(dtp, len)) == NULL) {
1413 				dt_strtab_destroy(strtab);
1414 				goto err;
1415 			}
1416 			(void) snprintf(p, len, dt_symfmt, dt_symprefix,
1417 			    objkey, s);
1418 
1419 			if (dt_strtab_index(strtab, p) == -1) {
1420 				nsym++;
1421 				(void) dt_strtab_insert(strtab, p);
1422 			}
1423 
1424 			dt_free(dtp, p);
1425 		}
1426 
1427 		/*
1428 		 * If any probes were found, allocate the additional space for
1429 		 * the symbol table and string table, copying the old data into
1430 		 * the new buffers, and marking the buffers as dirty. We inject
1431 		 * those newly allocated buffers into the libelf data
1432 		 * structures, but are still responsible for freeing them once
1433 		 * we're done with the elf handle.
1434 		 */
1435 		if (nsym > 0) {
1436 			/*
1437 			 * The first byte of the string table is reserved for
1438 			 * the \0 entry.
1439 			 */
1440 			len = dt_strtab_size(strtab) - 1;
1441 
1442 			assert(len > 0);
1443 			assert(dt_strtab_index(strtab, "") == 0);
1444 
1445 			dt_strtab_destroy(strtab);
1446 
1447 			if ((pair = dt_alloc(dtp, sizeof (*pair))) == NULL)
1448 				goto err;
1449 
1450 			if ((pair->dlp_str = dt_alloc(dtp, data_str->d_size +
1451 			    len)) == NULL) {
1452 				dt_free(dtp, pair);
1453 				goto err;
1454 			}
1455 
1456 			if ((pair->dlp_sym = dt_alloc(dtp, data_sym->d_size +
1457 			    nsym * symsize)) == NULL) {
1458 				dt_free(dtp, pair->dlp_str);
1459 				dt_free(dtp, pair);
1460 				goto err;
1461 			}
1462 
1463 			pair->dlp_next = bufs;
1464 			bufs = pair;
1465 
1466 			bcopy(data_str->d_buf, pair->dlp_str, data_str->d_size);
1467 			tmp = data_str->d_buf;
1468 			data_str->d_buf = pair->dlp_str;
1469 			pair->dlp_str = tmp;
1470 			data_str->d_size += len;
1471 			(void) elf_flagdata(data_str, ELF_C_SET, ELF_F_DIRTY);
1472 
1473 			shdr_str.sh_size += len;
1474 			(void) gelf_update_shdr(scn_str, &shdr_str);
1475 
1476 			bcopy(data_sym->d_buf, pair->dlp_sym, data_sym->d_size);
1477 			tmp = data_sym->d_buf;
1478 			data_sym->d_buf = pair->dlp_sym;
1479 			pair->dlp_sym = tmp;
1480 			data_sym->d_size += nsym * symsize;
1481 			(void) elf_flagdata(data_sym, ELF_C_SET, ELF_F_DIRTY);
1482 
1483 			shdr_sym.sh_size += nsym * symsize;
1484 			(void) gelf_update_shdr(scn_sym, &shdr_sym);
1485 
1486 			osym = isym;
1487 			nsym += isym;
1488 		} else {
1489 			dt_strtab_destroy(strtab);
1490 			continue;
1491 		}
1492 
1493 		/*
1494 		 * Now that the tables have been allocated, perform the
1495 		 * modifications described above.
1496 		 */
1497 		for (i = 0; i < shdr_rel.sh_size / shdr_rel.sh_entsize; i++) {
1498 
1499 			if (shdr_rel.sh_type == SHT_RELA) {
1500 				if (gelf_getrela(data_rel, i, &rela) == NULL)
1501 					continue;
1502 			} else {
1503 				GElf_Rel rel;
1504 				if (gelf_getrel(data_rel, i, &rel) == NULL)
1505 					continue;
1506 				rela.r_offset = rel.r_offset;
1507 				rela.r_info = rel.r_info;
1508 				rela.r_addend = 0;
1509 			}
1510 
1511 			ndx = GELF_R_SYM(rela.r_info);
1512 
1513 			if (gelf_getsym(data_sym, ndx, &rsym) == NULL ||
1514 			    rsym.st_name > data_str->d_size)
1515 				goto err;
1516 
1517 			s = (char *)data_str->d_buf + rsym.st_name;
1518 
1519 			if (strncmp(s, dt_prefix, sizeof (dt_prefix) - 1) != 0)
1520 				continue;
1521 
1522 			s += sizeof (dt_prefix) - 1;
1523 
1524 			/*
1525 			 * Check to see if this is an 'is-enabled' check as
1526 			 * opposed to a normal probe.
1527 			 */
1528 			if (strncmp(s, dt_enabled,
1529 			    sizeof (dt_enabled) - 1) == 0) {
1530 				s += sizeof (dt_enabled) - 1;
1531 				eprobe = 1;
1532 				*eprobesp = 1;
1533 				dt_dprintf("is-enabled probe\n");
1534 			} else {
1535 				eprobe = 0;
1536 				dt_dprintf("normal probe\n");
1537 			}
1538 
1539 			if (*s++ != '_')
1540 				goto err;
1541 
1542 			if ((p = strstr(s, "___")) == NULL ||
1543 			    p - s >= sizeof (pname))
1544 				goto err;
1545 
1546 			bcopy(s, pname, p - s);
1547 			pname[p - s] = '\0';
1548 
1549 			if (dt_symtab_lookup(data_sym, osym, isym,
1550 			    rela.r_offset, shdr_rel.sh_info, &fsym,
1551 			    (emachine1 == EM_PPC64), elf) != 0 &&
1552 			    dt_symtab_lookup(data_sym, 0, osym,
1553 			    rela.r_offset, shdr_rel.sh_info, &fsym,
1554 			    (emachine1 == EM_PPC64), elf) != 0)
1555 				goto err;
1556 
1557 			if (fsym.st_name > data_str->d_size)
1558 				goto err;
1559 
1560 			assert(GELF_ST_TYPE(fsym.st_info) == STT_FUNC);
1561 
1562 			/*
1563 			 * If this is our first time encountering this symbol,
1564 			 * emit an alias.
1565 			 */
1566 			s = (char *)data_str->d_buf + fsym.st_name;
1567 
1568 			if (strncmp(s, dt_symprefix,
1569 			    sizeof (dt_symprefix) - 1) != 0) {
1570 				u_int bind = GELF_ST_BIND(fsym.st_info);
1571 
1572 				dsym = fsym;
1573 				dsym.st_name = istr;
1574 				dsym.st_info = GELF_ST_INFO(bind == STB_LOCAL ?
1575 				    STB_GLOBAL : bind, STT_FUNC);
1576 				dsym.st_other = GELF_ST_VISIBILITY(STV_HIDDEN);
1577 				(void) gelf_update_sym(data_sym, isym, &dsym);
1578 				r = (char *) data_str->d_buf + istr;
1579 				istr += 1 + sprintf(r, dt_symfmt, dt_symprefix, objkey,
1580 				    s);
1581 				isym++;
1582 				assert(isym <= nsym);
1583 			} else {
1584 				r = s;
1585 				s = strchr(s, '.');
1586 				assert(s != NULL);
1587 				s++;
1588 			}
1589 
1590 			if ((pvp = dt_provider_lookup(dtp, pname)) == NULL) {
1591 				return (dt_link_error(dtp, elf, fd, bufs,
1592 				    "no such provider %s", pname));
1593 			}
1594 
1595 			if (strlcpy(probename, p + 3, sizeof (probename)) >=
1596 			    sizeof (probename))
1597 				return (dt_link_error(dtp, elf, fd, bufs,
1598 				    "invalid probe name %s", probename));
1599 			(void) strhyphenate(probename);
1600 			if ((prp = dt_probe_lookup(pvp, probename)) == NULL)
1601 				return (dt_link_error(dtp, elf, fd, bufs,
1602 				    "no such probe %s", probename));
1603 
1604 			assert(fsym.st_value <= rela.r_offset);
1605 
1606 			off = rela.r_offset - fsym.st_value;
1607 			if (dt_modtext(dtp, data_tgt->d_buf, eprobe,
1608 			    &rela, &off) != 0)
1609 				goto err;
1610 
1611 			if (dt_probe_define(pvp, prp, s, r, off, eprobe) != 0) {
1612 				return (dt_link_error(dtp, elf, fd, bufs,
1613 				    "failed to allocate space for probe"));
1614 			}
1615 #ifndef illumos
1616 			/*
1617 			 * Our linker doesn't understand the SUNW_IGNORE ndx and
1618 			 * will try to use this relocation when we build the
1619 			 * final executable. Since we are done processing this
1620 			 * relocation, mark it as inexistant and let libelf
1621 			 * remove it from the file.
1622 			 * If this wasn't done, we would have garbage added to
1623 			 * the executable file as the symbol is going to be
1624 			 * change from UND to ABS.
1625 			 */
1626 			if (shdr_rel.sh_type == SHT_RELA) {
1627 				rela.r_offset = 0;
1628 				rela.r_info  = 0;
1629 				rela.r_addend = 0;
1630 				(void) gelf_update_rela(data_rel, i, &rela);
1631 			} else {
1632 				GElf_Rel rel;
1633 				rel.r_offset = 0;
1634 				rel.r_info = 0;
1635 				(void) gelf_update_rel(data_rel, i, &rel);
1636 			}
1637 #endif
1638 
1639 			mod = 1;
1640 			(void) elf_flagdata(data_tgt, ELF_C_SET, ELF_F_DIRTY);
1641 
1642 			/*
1643 			 * This symbol may already have been marked to
1644 			 * be ignored by another relocation referencing
1645 			 * the same symbol or if this object file has
1646 			 * already been processed by an earlier link
1647 			 * invocation.
1648 			 */
1649 #ifndef illumos
1650 #define SHN_SUNW_IGNORE	SHN_ABS
1651 #endif
1652 			if (rsym.st_shndx != SHN_SUNW_IGNORE) {
1653 				rsym.st_shndx = SHN_SUNW_IGNORE;
1654 				(void) gelf_update_sym(data_sym, ndx, &rsym);
1655 			}
1656 		}
1657 	}
1658 
1659 	if (mod && elf_update(elf, ELF_C_WRITE) == -1)
1660 		goto err;
1661 
1662 	(void) elf_end(elf);
1663 	(void) close(fd);
1664 
1665 	while ((pair = bufs) != NULL) {
1666 		bufs = pair->dlp_next;
1667 		dt_free(dtp, pair->dlp_str);
1668 		dt_free(dtp, pair->dlp_sym);
1669 		dt_free(dtp, pair);
1670 	}
1671 
1672 	return (0);
1673 
1674 err:
1675 	return (dt_link_error(dtp, elf, fd, bufs,
1676 	    "an error was encountered while processing %s", obj));
1677 }
1678 
1679 int
1680 dtrace_program_link(dtrace_hdl_t *dtp, dtrace_prog_t *pgp, uint_t dflags,
1681     const char *file, int objc, char *const objv[])
1682 {
1683 #ifndef illumos
1684 	char tfile[PATH_MAX];
1685 #endif
1686 	char drti[PATH_MAX];
1687 	dof_hdr_t *dof;
1688 	int fd, status, i, cur;
1689 	char *cmd, tmp;
1690 	size_t len;
1691 	int eprobes = 0, ret = 0;
1692 
1693 #ifndef illumos
1694 	if (access(file, R_OK) == 0) {
1695 		fprintf(stderr, "dtrace: target object (%s) already exists. "
1696 		    "Please remove the target\ndtrace: object and rebuild all "
1697 		    "the source objects if you wish to run the DTrace\n"
1698 		    "dtrace: linking process again\n", file);
1699 		/*
1700 		 * Several build infrastructures run DTrace twice (e.g.
1701 		 * postgres) and we don't want the build to fail. Return
1702 		 * 0 here since this isn't really a fatal error.
1703 		 */
1704 		return (0);
1705 	}
1706 #endif
1707 
1708 	/*
1709 	 * A NULL program indicates a special use in which we just link
1710 	 * together a bunch of object files specified in objv and then
1711 	 * unlink(2) those object files.
1712 	 */
1713 	if (pgp == NULL) {
1714 		const char *fmt = "%s -o %s -r";
1715 
1716 		len = snprintf(&tmp, 1, fmt, dtp->dt_ld_path, file) + 1;
1717 
1718 		for (i = 0; i < objc; i++)
1719 			len += strlen(objv[i]) + 1;
1720 
1721 		cmd = alloca(len);
1722 
1723 		cur = snprintf(cmd, len, fmt, dtp->dt_ld_path, file);
1724 
1725 		for (i = 0; i < objc; i++)
1726 			cur += snprintf(cmd + cur, len - cur, " %s", objv[i]);
1727 
1728 		if ((status = system(cmd)) == -1) {
1729 			return (dt_link_error(dtp, NULL, -1, NULL,
1730 			    "failed to run %s: %s", dtp->dt_ld_path,
1731 			    strerror(errno)));
1732 		}
1733 
1734 		if (WIFSIGNALED(status)) {
1735 			return (dt_link_error(dtp, NULL, -1, NULL,
1736 			    "failed to link %s: %s failed due to signal %d",
1737 			    file, dtp->dt_ld_path, WTERMSIG(status)));
1738 		}
1739 
1740 		if (WEXITSTATUS(status) != 0) {
1741 			return (dt_link_error(dtp, NULL, -1, NULL,
1742 			    "failed to link %s: %s exited with status %d\n",
1743 			    file, dtp->dt_ld_path, WEXITSTATUS(status)));
1744 		}
1745 
1746 		for (i = 0; i < objc; i++) {
1747 			if (strcmp(objv[i], file) != 0)
1748 				(void) unlink(objv[i]);
1749 		}
1750 
1751 		return (0);
1752 	}
1753 
1754 	for (i = 0; i < objc; i++) {
1755 		if (process_obj(dtp, objv[i], &eprobes) != 0)
1756 			return (-1); /* errno is set for us */
1757 	}
1758 
1759 	/*
1760 	 * If there are is-enabled probes then we need to force use of DOF
1761 	 * version 2.
1762 	 */
1763 	if (eprobes && pgp->dp_dofversion < DOF_VERSION_2)
1764 		pgp->dp_dofversion = DOF_VERSION_2;
1765 
1766 	if ((dof = dtrace_dof_create(dtp, pgp, dflags)) == NULL)
1767 		return (-1); /* errno is set for us */
1768 
1769 #ifdef illumos
1770 	/*
1771 	 * Create a temporary file and then unlink it if we're going to
1772 	 * combine it with drti.o later.  We can still refer to it in child
1773 	 * processes as /dev/fd/<fd>.
1774 	 */
1775 	if ((fd = open64(file, O_RDWR | O_CREAT | O_TRUNC, 0666)) == -1) {
1776 		return (dt_link_error(dtp, NULL, -1, NULL,
1777 		    "failed to open %s: %s", file, strerror(errno)));
1778 	}
1779 #else
1780 	snprintf(tfile, sizeof(tfile), "%s.XXXXXX", file);
1781 	if ((fd = mkostemp(tfile, O_CLOEXEC)) == -1)
1782 		return (dt_link_error(dtp, NULL, -1, NULL,
1783 		    "failed to create temporary file %s: %s",
1784 		    tfile, strerror(errno)));
1785 #endif
1786 
1787 	/*
1788 	 * If -xlinktype=DOF has been selected, just write out the DOF.
1789 	 * Otherwise proceed to the default of generating and linking ELF.
1790 	 */
1791 	switch (dtp->dt_linktype) {
1792 	case DT_LTYP_DOF:
1793 		if (dt_write(dtp, fd, dof, dof->dofh_filesz) < dof->dofh_filesz)
1794 			ret = errno;
1795 
1796 		if (close(fd) != 0 && ret == 0)
1797 			ret = errno;
1798 
1799 		if (ret != 0) {
1800 			return (dt_link_error(dtp, NULL, -1, NULL,
1801 			    "failed to write %s: %s", file, strerror(ret)));
1802 		}
1803 
1804 		return (0);
1805 
1806 	case DT_LTYP_ELF:
1807 		break; /* fall through to the rest of dtrace_program_link() */
1808 
1809 	default:
1810 		return (dt_link_error(dtp, NULL, -1, NULL,
1811 		    "invalid link type %u\n", dtp->dt_linktype));
1812 	}
1813 
1814 
1815 #ifdef illumos
1816 	if (!dtp->dt_lazyload)
1817 		(void) unlink(file);
1818 #endif
1819 
1820 	if (dtp->dt_oflags & DTRACE_O_LP64)
1821 		status = dump_elf64(dtp, dof, fd);
1822 	else
1823 		status = dump_elf32(dtp, dof, fd);
1824 
1825 #ifdef illumos
1826 	if (status != 0 || lseek(fd, 0, SEEK_SET) != 0) {
1827 		return (dt_link_error(dtp, NULL, -1, NULL,
1828 		    "failed to write %s: %s", file, strerror(errno)));
1829 	}
1830 #else
1831 	if (status != 0)
1832 		return (dt_link_error(dtp, NULL, -1, NULL,
1833 		    "failed to write %s: %s", tfile,
1834 		    strerror(dtrace_errno(dtp))));
1835 #endif
1836 
1837 	if (!dtp->dt_lazyload) {
1838 #ifdef illumos
1839 		const char *fmt = "%s -o %s -r -Blocal -Breduce /dev/fd/%d %s";
1840 
1841 		if (dtp->dt_oflags & DTRACE_O_LP64) {
1842 			(void) snprintf(drti, sizeof (drti),
1843 			    "%s/64/drti.o", _dtrace_libdir);
1844 		} else {
1845 			(void) snprintf(drti, sizeof (drti),
1846 			    "%s/drti.o", _dtrace_libdir);
1847 		}
1848 
1849 		len = snprintf(&tmp, 1, fmt, dtp->dt_ld_path, file, fd,
1850 		    drti) + 1;
1851 
1852 		cmd = alloca(len);
1853 
1854 		(void) snprintf(cmd, len, fmt, dtp->dt_ld_path, file, fd, drti);
1855 #else
1856 		const char *fmt = "%s -o %s -r %s %s";
1857 		dt_dirpath_t *dp = dt_list_next(&dtp->dt_lib_path);
1858 
1859 		(void) snprintf(drti, sizeof (drti), "%s/drti.o", dp->dir_path);
1860 
1861 		len = snprintf(&tmp, 1, fmt, dtp->dt_ld_path, file, tfile,
1862 		    drti) + 1;
1863 
1864 		cmd = alloca(len);
1865 
1866 		(void) snprintf(cmd, len, fmt, dtp->dt_ld_path, file, tfile,
1867 		    drti);
1868 #endif
1869 		if ((status = system(cmd)) == -1) {
1870 			ret = dt_link_error(dtp, NULL, fd, NULL,
1871 			    "failed to run %s: %s", dtp->dt_ld_path,
1872 			    strerror(errno));
1873 			goto done;
1874 		}
1875 
1876 		if (WIFSIGNALED(status)) {
1877 			ret = dt_link_error(dtp, NULL, fd, NULL,
1878 			    "failed to link %s: %s failed due to signal %d",
1879 			    file, dtp->dt_ld_path, WTERMSIG(status));
1880 			goto done;
1881 		}
1882 
1883 		if (WEXITSTATUS(status) != 0) {
1884 			ret = dt_link_error(dtp, NULL, fd, NULL,
1885 			    "failed to link %s: %s exited with status %d\n",
1886 			    file, dtp->dt_ld_path, WEXITSTATUS(status));
1887 			goto done;
1888 		}
1889 		(void) close(fd); /* release temporary file */
1890 
1891 #ifdef __FreeBSD__
1892 		/*
1893 		 * Now that we've linked drti.o, reduce the global __SUNW_dof
1894 		 * symbol to a local symbol. This is needed to so that multiple
1895 		 * generated object files (for different providers, for
1896 		 * instance) can be linked together. This is accomplished using
1897 		 * the -Blocal flag with Sun's linker, but GNU ld doesn't appear
1898 		 * to have an equivalent option.
1899 		 */
1900 		asprintf(&cmd, "%s --localize-hidden %s", dtp->dt_objcopy_path,
1901 		    file);
1902 		if ((status = system(cmd)) == -1) {
1903 			ret = dt_link_error(dtp, NULL, -1, NULL,
1904 			    "failed to run %s: %s", dtp->dt_objcopy_path,
1905 			    strerror(errno));
1906 			free(cmd);
1907 			goto done;
1908 		}
1909 		free(cmd);
1910 
1911 		if (WIFSIGNALED(status)) {
1912 			ret = dt_link_error(dtp, NULL, -1, NULL,
1913 			    "failed to link %s: %s failed due to signal %d",
1914 			    file, dtp->dt_objcopy_path, WTERMSIG(status));
1915 			goto done;
1916 		}
1917 
1918 		if (WEXITSTATUS(status) != 0) {
1919 			ret = dt_link_error(dtp, NULL, -1, NULL,
1920 			    "failed to link %s: %s exited with status %d\n",
1921 			    file, dtp->dt_objcopy_path, WEXITSTATUS(status));
1922 			goto done;
1923 		}
1924 #endif
1925 	} else {
1926 #ifdef __FreeBSD__
1927 		if (rename(tfile, file) != 0) {
1928 			ret = dt_link_error(dtp, NULL, fd, NULL,
1929 			    "failed to rename %s to %s: %s", tfile, file,
1930 			    strerror(errno));
1931 			goto done;
1932 		}
1933 #endif
1934 		(void) close(fd);
1935 	}
1936 
1937 done:
1938 	dtrace_dof_destroy(dtp, dof);
1939 
1940 #ifdef __FreeBSD__
1941 	if (!dtp->dt_lazyload)
1942 		(void) unlink(tfile);
1943 #endif
1944 	return (ret);
1945 }
1946