xref: /freebsd/contrib/elftoolchain/elfcopy/segments.c (revision 1f4bcc459a76b7aa664f3fd557684cd0ba6da352)
1 /*-
2  * Copyright (c) 2007-2010,2012 Kai Wang
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 #include <sys/queue.h>
28 #include <err.h>
29 #include <gelf.h>
30 #include <stdint.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 
35 #include "elfcopy.h"
36 
37 ELFTC_VCSID("$Id: segments.c 3269 2015-12-11 18:38:43Z kaiwang27 $");
38 
39 static void	insert_to_inseg_list(struct segment *seg, struct section *sec);
40 
41 /*
42  * elfcopy's segment handling is relatively simpler and less powerful than
43  * libbfd. Program headers are modified or copied from input to output objects,
44  * but never re-generated. As a result, if the input object has incorrect
45  * program headers, the output object's program headers will remain incorrect
46  * or become even worse.
47  */
48 
49 /*
50  * Check whether a section is "loadable". If so, add it to the
51  * corresponding segment list(s) and return 1.
52  */
53 int
54 add_to_inseg_list(struct elfcopy *ecp, struct section *s)
55 {
56 	struct segment	*seg;
57 	int		 loadable;
58 
59 	if (ecp->ophnum == 0)
60 		return (0);
61 
62 	/*
63 	 * Segment is a different view of an ELF object. One segment can
64 	 * contain one or more sections, and one section can be included
65 	 * in one or more segments, or not included in any segment at all.
66 	 * We call those sections which can be found in one or more segments
67 	 * "loadable" sections, and call the rest "unloadable" sections.
68 	 * We keep track of "loadable" sections in their containing
69 	 * segment(s)' v_sec queue. These information are later used to
70 	 * recalculate the extents of segments, when sections are removed,
71 	 * for example.
72 	 */
73 	loadable = 0;
74 	STAILQ_FOREACH(seg, &ecp->v_seg, seg_list) {
75 		if (s->off < seg->off || (s->vma < seg->addr && !s->pseudo))
76 			continue;
77 		if (s->off + s->sz > seg->off + seg->fsz &&
78 		    s->type != SHT_NOBITS)
79 			continue;
80 		if (s->vma + s->sz > seg->addr + seg->msz)
81 			continue;
82 
83 		insert_to_inseg_list(seg, s);
84 		if (seg->type == PT_LOAD)
85 			s->seg = seg;
86 		else if (seg->type == PT_TLS)
87 			s->seg_tls = seg;
88 		s->lma = seg->addr + (s->off - seg->off);
89 		loadable = 1;
90 	}
91 
92 	return (loadable);
93 }
94 
95 void
96 adjust_addr(struct elfcopy *ecp)
97 {
98 	struct section *s, *s0;
99 	struct segment *seg;
100 	struct sec_action *sac;
101 	uint64_t dl, lma, start, end;
102 	int found, i;
103 
104 	/*
105 	 * Apply VMA and global LMA changes in the first iteration.
106 	 */
107 	TAILQ_FOREACH(s, &ecp->v_sec, sec_list) {
108 
109 		/* Only adjust loadable section's address. */
110 		if (!s->loadable || s->seg == NULL)
111 			continue;
112 
113 		/* Apply global LMA adjustment. */
114 		if (ecp->change_addr != 0)
115 			s->lma += ecp->change_addr;
116 
117 		if (!s->pseudo) {
118 			/* Apply global VMA adjustment. */
119 			if (ecp->change_addr != 0)
120 				s->vma += ecp->change_addr;
121 
122 			/* Apply section VMA adjustment. */
123 			sac = lookup_sec_act(ecp, s->name, 0);
124 			if (sac == NULL)
125 				continue;
126 			if (sac->setvma)
127 				s->vma = sac->vma;
128 			if (sac->vma_adjust != 0)
129 				s->vma += sac->vma_adjust;
130 		}
131 	}
132 
133 	/*
134 	 * Apply sections LMA change in the second iteration.
135 	 */
136 	TAILQ_FOREACH(s, &ecp->v_sec, sec_list) {
137 
138 		/* Only adjust loadable section's LMA. */
139 		if (!s->loadable || s->seg == NULL)
140 			continue;
141 
142 		/*
143 		 * Check if there is a LMA change request for this
144 		 * section.
145 		 */
146 		sac = lookup_sec_act(ecp, s->name, 0);
147 		if (sac == NULL)
148 			continue;
149 		if (!sac->setlma && sac->lma_adjust == 0)
150 			continue;
151 		lma = s->lma;
152 		if (sac->setlma)
153 			lma = sac->lma;
154 		if (sac->lma_adjust != 0)
155 			lma += sac->lma_adjust;
156 		if (lma == s->lma)
157 			continue;
158 
159 		/*
160 		 * Check if the LMA change is viable.
161 		 *
162 		 * 1. Check if the new LMA is properly aligned accroding to
163 		 *    section alignment.
164 		 *
165 		 * 2. Compute the new extent of segment that contains this
166 		 *    section, make sure it doesn't overlap with other
167 		 *    segments.
168 		 */
169 #ifdef	DEBUG
170 		printf("LMA for section %s: %#jx\n", s->name, lma);
171 #endif
172 
173 		if (lma % s->align != 0)
174 			errx(EXIT_FAILURE, "The load address %#jx for "
175 			    "section %s is not aligned to %ju",
176 			    (uintmax_t) lma, s->name, s->align);
177 
178 		if (lma < s->lma) {
179 			/* Move section to lower address. */
180 			if (lma < s->lma - s->seg->addr)
181 				errx(EXIT_FAILURE, "Not enough space to move "
182 				    "section %s load address to %#jx", s->name,
183 				    (uintmax_t) lma);
184 			start = lma - (s->lma - s->seg->addr);
185 			if (s == s->seg->v_sec[s->seg->nsec - 1])
186 				end = start + s->seg->msz;
187 			else
188 				end = s->seg->addr + s->seg->msz;
189 
190 		} else {
191 			/* Move section to upper address. */
192 			if (s == s->seg->v_sec[0])
193 				start = lma;
194 			else
195 				start = s->seg->addr;
196 			end = lma + (s->seg->addr + s->seg->msz - s->lma);
197 			if (end < start)
198 				errx(EXIT_FAILURE, "Not enough space to move "
199 				    "section %s load address to %#jx", s->name,
200 				    (uintmax_t) lma);
201 		}
202 
203 #ifdef	DEBUG
204 		printf("new extent for segment containing %s: (%#jx,%#jx)\n",
205 		    s->name, start, end);
206 #endif
207 
208 		STAILQ_FOREACH(seg, &ecp->v_seg, seg_list) {
209 			if (seg == s->seg || seg->type != PT_LOAD)
210 				continue;
211 			if (start > seg->addr + seg->msz)
212 				continue;
213 			if (end < seg->addr)
214 				continue;
215 			errx(EXIT_FAILURE, "The extent of segment containing "
216 			    "section %s overlaps with segment(%#jx,%#jx)",
217 			    s->name, seg->addr, seg->addr + seg->msz);
218 		}
219 
220 		/*
221 		 * Update section LMA and file offset.
222 		 */
223 
224 		if (lma < s->lma) {
225 			/*
226 			 * To move a section to lower load address, we decrease
227 			 * the load addresses of the section and all the
228 			 * sections that are before it, and we increase the
229 			 * file offsets of all the sections that are after it.
230 			 */
231 			dl = s->lma - lma;
232 			for (i = 0; i < s->seg->nsec; i++) {
233 				s0 = s->seg->v_sec[i];
234 				s0->lma -= dl;
235 #ifdef	DEBUG
236 				printf("section %s LMA set to %#jx\n",
237 				    s0->name, (uintmax_t) s0->lma);
238 #endif
239 				if (s0 == s)
240 					break;
241 			}
242 			for (i = i + 1; i < s->seg->nsec; i++) {
243 				s0 = s->seg->v_sec[i];
244 				s0->off += dl;
245 #ifdef	DEBUG
246 				printf("section %s offset set to %#jx\n",
247 				    s0->name, (uintmax_t) s0->off);
248 #endif
249 			}
250 		} else {
251 			/*
252 			 * To move a section to upper load address, we increase
253 			 * the load addresses of the section and all the
254 			 * sections that are after it, and we increase the
255 			 * their file offsets too unless the section in question
256 			 * is the first in its containing segment.
257 			 */
258 			dl = lma - s->lma;
259 			for (i = 0; i < s->seg->nsec; i++)
260 				if (s->seg->v_sec[i] == s)
261 					break;
262 			if (i >= s->seg->nsec)
263 				errx(EXIT_FAILURE, "Internal: section `%s' not"
264 				    " found in its containing segement",
265 				    s->name);
266 			for (; i < s->seg->nsec; i++) {
267 				s0 = s->seg->v_sec[i];
268 				s0->lma += dl;
269 #ifdef	DEBUG
270 				printf("section %s LMA set to %#jx\n",
271 				    s0->name, (uintmax_t) s0->lma);
272 #endif
273 				if (s != s->seg->v_sec[0]) {
274 					s0->off += dl;
275 #ifdef	DEBUG
276 					printf("section %s offset set to %#jx\n",
277 					    s0->name, (uintmax_t) s0->off);
278 #endif
279 				}
280 			}
281 		}
282 	}
283 
284 	/*
285 	 * Apply load address padding.
286 	 */
287 
288 	if (ecp->pad_to != 0) {
289 
290 		/*
291 		 * Find the section with highest load address.
292 		 */
293 
294 		s = NULL;
295 		STAILQ_FOREACH(seg, &ecp->v_seg, seg_list) {
296 			if (seg->type != PT_LOAD)
297 				continue;
298 			for (i = seg->nsec - 1; i >= 0; i--)
299 				if (seg->v_sec[i]->type != SHT_NOBITS)
300 					break;
301 			if (i < 0)
302 				continue;
303 			if (s == NULL)
304 				s = seg->v_sec[i];
305 			else {
306 				s0 = seg->v_sec[i];
307 				if (s0->lma > s->lma)
308 					s = s0;
309 			}
310 		}
311 
312 		if (s == NULL)
313 			goto issue_warn;
314 
315 		/* No need to pad if the pad_to address is lower. */
316 		if (ecp->pad_to <= s->lma + s->sz)
317 			goto issue_warn;
318 
319 		s->pad_sz = ecp->pad_to - (s->lma + s->sz);
320 #ifdef	DEBUG
321 		printf("pad section %s load to address %#jx by %#jx\n", s->name,
322 		    (uintmax_t) ecp->pad_to, (uintmax_t) s->pad_sz);
323 #endif
324 	}
325 
326 issue_warn:
327 
328 	/*
329 	 * Issue a warning if there are VMA/LMA adjust requests for
330 	 * some nonexistent sections.
331 	 */
332 	if ((ecp->flags & NO_CHANGE_WARN) == 0) {
333 		STAILQ_FOREACH(sac, &ecp->v_sac, sac_list) {
334 			if (!sac->setvma && !sac->setlma &&
335 			    !sac->vma_adjust && !sac->lma_adjust)
336 				continue;
337 			found = 0;
338 			TAILQ_FOREACH(s, &ecp->v_sec, sec_list) {
339 				if (s->pseudo || s->name == NULL)
340 					continue;
341 				if (!strcmp(s->name, sac->name)) {
342 					found = 1;
343 					break;
344 				}
345 			}
346 			if (!found)
347 				warnx("cannot find section `%s'", sac->name);
348 		}
349 	}
350 }
351 
352 static void
353 insert_to_inseg_list(struct segment *seg, struct section *sec)
354 {
355 	struct section *s;
356 	int i;
357 
358 	seg->nsec++;
359 	seg->v_sec = realloc(seg->v_sec, seg->nsec * sizeof(*seg->v_sec));
360 	if (seg->v_sec == NULL)
361 		err(EXIT_FAILURE, "realloc failed");
362 
363 	/*
364 	 * Sort the section in order of offset.
365 	 */
366 
367 	for (i = seg->nsec - 1; i > 0; i--) {
368 		s = seg->v_sec[i - 1];
369 		if (sec->off >= s->off) {
370 			seg->v_sec[i] = sec;
371 			break;
372 		} else
373 			seg->v_sec[i] = s;
374 	}
375 	if (i == 0)
376 		seg->v_sec[0] = sec;
377 }
378 
379 void
380 setup_phdr(struct elfcopy *ecp)
381 {
382 	struct segment	*seg;
383 	GElf_Phdr	 iphdr;
384 	size_t		 iphnum;
385 	int		 i;
386 
387 	if (elf_getphnum(ecp->ein, &iphnum) == 0)
388 		errx(EXIT_FAILURE, "elf_getphnum failed: %s",
389 		    elf_errmsg(-1));
390 
391 	ecp->ophnum = ecp->iphnum = iphnum;
392 	if (iphnum == 0)
393 		return;
394 
395 	/* If --only-keep-debug is specified, discard all program headers. */
396 	if (ecp->strip == STRIP_NONDEBUG) {
397 		ecp->ophnum = 0;
398 		return;
399 	}
400 
401 	for (i = 0; (size_t)i < iphnum; i++) {
402 		if (gelf_getphdr(ecp->ein, i, &iphdr) != &iphdr)
403 			errx(EXIT_FAILURE, "gelf_getphdr failed: %s",
404 			    elf_errmsg(-1));
405 		if ((seg = calloc(1, sizeof(*seg))) == NULL)
406 			err(EXIT_FAILURE, "calloc failed");
407 		seg->addr	= iphdr.p_vaddr;
408 		seg->off	= iphdr.p_offset;
409 		seg->fsz	= iphdr.p_filesz;
410 		seg->msz	= iphdr.p_memsz;
411 		seg->type	= iphdr.p_type;
412 		STAILQ_INSERT_TAIL(&ecp->v_seg, seg, seg_list);
413 	}
414 }
415 
416 void
417 copy_phdr(struct elfcopy *ecp)
418 {
419 	struct segment	*seg;
420 	struct section	*s;
421 	GElf_Phdr	 iphdr, ophdr;
422 	int		 i;
423 
424 	STAILQ_FOREACH(seg, &ecp->v_seg, seg_list) {
425 		if (seg->type == PT_PHDR) {
426 			if (!TAILQ_EMPTY(&ecp->v_sec)) {
427 				s = TAILQ_FIRST(&ecp->v_sec);
428 				if (s->pseudo)
429 					seg->addr = s->lma +
430 					    gelf_fsize(ecp->eout, ELF_T_EHDR,
431 						1, EV_CURRENT);
432 			}
433 			seg->fsz = seg->msz = gelf_fsize(ecp->eout, ELF_T_PHDR,
434 			    ecp->ophnum, EV_CURRENT);
435 			continue;
436 		}
437 
438 		seg->fsz = seg->msz = 0;
439 		for (i = 0; i < seg->nsec; i++) {
440 			s = seg->v_sec[i];
441 			seg->msz = s->vma + s->sz - seg->addr;
442 			if (s->type != SHT_NOBITS)
443 				seg->fsz = s->off + s->sz - seg->off;
444 		}
445 	}
446 
447 	/*
448 	 * Allocate space for program headers, note that libelf keep
449 	 * track of the number in internal variable, and a call to
450 	 * elf_update is needed to update e_phnum of ehdr.
451 	 */
452 	if (gelf_newphdr(ecp->eout, ecp->ophnum) == NULL)
453 		errx(EXIT_FAILURE, "gelf_newphdr() failed: %s",
454 		    elf_errmsg(-1));
455 
456 	/*
457 	 * This elf_update() call is to update the e_phnum field in
458 	 * ehdr. It's necessary because later we will call gelf_getphdr(),
459 	 * which does sanity check by comparing ndx argument with e_phnum.
460 	 */
461 	if (elf_update(ecp->eout, ELF_C_NULL) < 0)
462 		errx(EXIT_FAILURE, "elf_update() failed: %s", elf_errmsg(-1));
463 
464 	/*
465 	 * iphnum == ophnum, since we don't remove program headers even if
466 	 * they no longer contain sections.
467 	 */
468 	i = 0;
469 	STAILQ_FOREACH(seg, &ecp->v_seg, seg_list) {
470 		if (i >= ecp->iphnum)
471 			break;
472 		if (gelf_getphdr(ecp->ein, i, &iphdr) != &iphdr)
473 			errx(EXIT_FAILURE, "gelf_getphdr failed: %s",
474 			    elf_errmsg(-1));
475 		if (gelf_getphdr(ecp->eout, i, &ophdr) != &ophdr)
476 			errx(EXIT_FAILURE, "gelf_getphdr failed: %s",
477 			    elf_errmsg(-1));
478 
479 		ophdr.p_type = iphdr.p_type;
480 		ophdr.p_vaddr = seg->addr;
481 		ophdr.p_paddr = seg->addr;
482 		ophdr.p_flags = iphdr.p_flags;
483 		ophdr.p_align = iphdr.p_align;
484 		ophdr.p_offset = seg->off;
485 		ophdr.p_filesz = seg->fsz;
486 		ophdr.p_memsz = seg->msz;
487 		if (!gelf_update_phdr(ecp->eout, i, &ophdr))
488 			err(EXIT_FAILURE, "gelf_update_phdr failed :%s",
489 			    elf_errmsg(-1));
490 
491 		i++;
492 	}
493 }
494