blob: a5730f12ba6148577086c72ceb3150975ce7099b [file] [log] [blame]
Aaron Durbin4fde5a62014-03-07 15:11:53 -06001/*
2 ;* Copyright (C) 2014 Google, Inc.
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; version 2 of the License.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License
14 * along with this program; if not, write to the Free Software
15 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA, 02110-1301 USA
16 */
17
18#include <stdio.h>
19#include <stdlib.h>
20#include <string.h>
21
22#include "elfparsing.h"
23#include "rmodule.h"
24#include "../../src/include/rmodule-defs.h"
25
26struct rmod_context;
27
28struct arch_ops {
29 int arch;
30 /* Determine if relocation is a valid type for the architecture. */
31 int (*valid_type)(struct rmod_context *ctx, Elf64_Rela *rel);
32 /* Determine if relocation should be emitted. */
33 int (*should_emit)(struct rmod_context *ctx, Elf64_Rela *rel);
34};
35
36struct rmod_context {
37 /* Ops to process relocations. */
38 struct arch_ops *ops;
39
40 /* endian conversion ops */
41 struct xdr *xdr;
42
43 /* Parsed ELF sturcture. */
44 struct parsed_elf pelf;
45 /* Program segment. */
46 Elf64_Phdr *phdr;
47
48 /* Collection of relocation addresses fixup in the module. */
49 Elf64_Xword nrelocs;
50 Elf64_Addr *emitted_relocs;
51
52 /* The following fields are addresses within the linked program. */
53 Elf64_Addr link_addr;
54 Elf64_Addr entry;
55 Elf64_Addr parameters_begin;
56 Elf64_Addr parameters_end;
57 Elf64_Addr bss_begin;
58 Elf64_Addr bss_end;
59 Elf64_Xword size;
60};
61
62/*
63 * Architecture specific support operations.
64 */
65static int valid_reloc_386(struct rmod_context *ctx, Elf64_Rela *rel)
66{
67 int type;
68
69 type = ELF64_R_TYPE(rel->r_info);
70
71 /* Only these 2 relocations are expected to be found. */
72 return (type == R_386_32 || type == R_386_PC32);
73}
74
75static int should_emit_386(struct rmod_context *ctx, Elf64_Rela *rel)
76{
77 int type;
78
79 type = ELF64_R_TYPE(rel->r_info);
80
81 /* R_386_32 relocations are absolute. Must emit these. */
82 return (type == R_386_32);
83}
84
85static struct arch_ops reloc_ops[] = {
86 {
87 .arch = EM_386,
88 .valid_type = valid_reloc_386,
89 .should_emit = should_emit_386,
90 },
91};
92
93/*
94 * Relocation processing loops.
95 */
96
97static int for_each_reloc(struct rmod_context *ctx, int do_emit)
98{
99 Elf64_Half i;
100 struct parsed_elf *pelf = &ctx->pelf;
101
102 for (i = 0; i < pelf->ehdr.e_shnum; i++) {
103 Elf64_Shdr *shdr;
104 Elf64_Rela *relocs;
105 Elf64_Xword nrelocs;
106 Elf64_Xword j;
107
108 relocs = pelf->relocs[i];
109
110 /* No relocations in this section. */
111 if (relocs == NULL)
112 continue;
113
114 shdr = &pelf->shdr[i];
115 nrelocs = shdr->sh_size / shdr->sh_entsize;
116
117 for (j = 0; j < nrelocs; j++) {
118 Elf64_Rela *r = &relocs[j];
119
120 if (!ctx->ops->valid_type(ctx, r)) {
121 ERROR("Invalid reloc type: %u\n",
122 (unsigned int)ELF64_R_TYPE(r->r_info));
123 return -1;
124 }
125
126 if (ctx->ops->should_emit(ctx, r)) {
127 int n = ctx->nrelocs;
128 if (do_emit)
129 ctx->emitted_relocs[n] = r->r_offset;
130 ctx->nrelocs++;
131 }
132 }
133 }
134
135 return 0;
136}
137
138static int find_program_segment(struct rmod_context *ctx)
139{
140 int i;
141 int nsegments;
142 struct parsed_elf *pelf;
143 Elf64_Phdr *phdr;
144
145 pelf = &ctx->pelf;
146
147 /* There should only be a single loadable segment. */
148 nsegments = 0;
149 for (i = 0; i < pelf->ehdr.e_phnum; i++) {
150 if (pelf->phdr[i].p_type != PT_LOAD)
151 continue;
152 phdr = &pelf->phdr[i];
153 nsegments++;
154 }
155
156 if (nsegments != 1) {
157 ERROR("Unexepcted number of loadable segments: %d.\n",
158 nsegments);
159 return -1;
160 }
161
162 INFO("Segment at 0x%0llx, file size 0x%0llx, mem size 0x%0llx.\n",
163 (long long)phdr->p_vaddr, (long long)phdr->p_filesz,
164 (long long)phdr->p_memsz);
165
166 ctx->phdr = phdr;
167
168 return 0;
169}
170
171static int
172filter_relocation_sections(struct rmod_context *ctx)
173{
174 int i;
175 const char *shstrtab;
176 struct parsed_elf *pelf;
177 const Elf64_Phdr *phdr;
178
179 pelf = &ctx->pelf;
180 phdr = ctx->phdr;
181 shstrtab = buffer_get(pelf->strtabs[pelf->ehdr.e_shstrndx]);
182
183 /*
184 * Find all relocation sections that contain relocation entries
185 * for sections that fall within the bounds of the segment. For
186 * easier processing the pointer to the relocation array for the
187 * sections that don't fall within the loadable program are NULL'd
188 * out.
189 */
190 for (i = 0; i < pelf->ehdr.e_shnum; i++) {
191 Elf64_Shdr *shdr;
192 Elf64_Word sh_info;
193 const char *section_name;
194
195 shdr = &pelf->shdr[i];
196
197 /* Ignore non-relocation sections. */
198 if (shdr->sh_type != SHT_RELA && shdr->sh_type != SHT_REL)
199 continue;
200
201 /* Obtain section which relocations apply. */
202 sh_info = shdr->sh_info;
203 shdr = &pelf->shdr[sh_info];
204
205 section_name = &shstrtab[shdr->sh_name];
206 DEBUG("Relocation section found for '%s' section.\n",
207 section_name);
208
209 /* Do not process relocations for debug sections. */
210 if (strstr(section_name, ".debug") != NULL) {
211 pelf->relocs[i] = NULL;
212 continue;
213 }
214
215 /*
216 * If relocations apply to a non program section ignore the
217 * relocations for future processing.
218 */
219 if (shdr->sh_type != SHT_PROGBITS) {
220 pelf->relocs[i] = NULL;
221 continue;
222 }
223
224 if (shdr->sh_addr < phdr->p_vaddr ||
225 ((shdr->sh_addr + shdr->sh_size) >
226 (phdr->p_vaddr + phdr->p_memsz))) {
227 ERROR("Relocations being applied to section %d not "
228 "within segment region.\n", sh_info);
229 return -1;
230 }
231 }
232
233 return 0;
234}
235
236static int vaddr_cmp(const void *a, const void *b)
237{
238 const Elf64_Addr *pa = a;
239 const Elf64_Addr *pb = b;
240
241 if (*pa < *pb)
242 return -1;
243 if (*pa > *pb)
244 return 1;
245 return 0;
246}
247
248static int collect_relocations(struct rmod_context *ctx)
249{
250 int nrelocs;
251
252 /*
253 * The relocs array in the pelf should only contain relocations that
254 * apply to the program. Count the number relocations. Then collect
255 * them into the allocated buffer.
256 */
257 if (for_each_reloc(ctx, 0))
258 return -1;
259
260 nrelocs = ctx->nrelocs;
261 INFO("%d relocations to be emitted.\n", nrelocs);
262 if (!nrelocs) {
263 ERROR("No valid relocations in file.\n");
264 return -1;
265 }
266
267 /* Reset the counter for indexing into the array. */
268 ctx->nrelocs = 0;
269 ctx->emitted_relocs = calloc(nrelocs, sizeof(Elf64_Addr));
270 /* Write out the relocations into the emitted_relocs array. */
271 if (for_each_reloc(ctx, 1))
272 return -1;
273
274 if (ctx->nrelocs != nrelocs) {
275 ERROR("Mismatch counted and emitted relocations: %zu vs %zu.\n",
276 (size_t)nrelocs, (size_t)ctx->nrelocs);
277 return -1;
278 }
279
280 /* Sort the relocations by their address. */
281 qsort(ctx->emitted_relocs, nrelocs, sizeof(Elf64_Addr), vaddr_cmp);
282
283 return 0;
284}
285
286static int
287populate_sym(struct rmod_context *ctx, const char *sym_name, Elf64_Addr *addr,
288 int nsyms, const char *strtab)
289{
290 int i;
291 Elf64_Sym *syms;
292
293 syms = ctx->pelf.syms;
294
295 for (i = 0; i < nsyms; i++) {
296 if (syms[i].st_name == 0)
297 continue;
298 if (strcmp(sym_name, &strtab[syms[i].st_name]))
299 continue;
300 DEBUG("%s -> 0x%llx\n", sym_name, (long long)syms[i].st_value);
301 *addr = syms[i].st_value;
302 return 0;
303 }
304 ERROR("symbol '%s' not found.\n", sym_name);
305 return -1;
306}
307
308static int populate_program_info(struct rmod_context *ctx)
309{
310 int i;
311 const char *strtab;
312 struct parsed_elf *pelf;
313 Elf64_Ehdr *ehdr;
314 int nsyms;
315
316 pelf = &ctx->pelf;
317 ehdr = &pelf->ehdr;
318
319 /* Obtain the string table. */
320 strtab = NULL;
321 for (i = 0; i < ehdr->e_shnum; i++) {
322 if (ctx->pelf.strtabs[i] == NULL)
323 continue;
324 /* Don't use the section headers' string table. */
325 if (i == ehdr->e_shstrndx)
326 continue;
327 strtab = buffer_get(ctx->pelf.strtabs[i]);
328 break;
329 }
330
331 if (strtab == NULL) {
332 ERROR("No string table found.\n");
333 return -1;
334 }
335
336 /* Determine number of symbols. */
337 nsyms = 0;
338 for (i = 0; i < ehdr->e_shnum; i++) {
339 if (pelf->shdr[i].sh_type != SHT_SYMTAB)
340 continue;
341
342 nsyms = pelf->shdr[i].sh_size / pelf->shdr[i].sh_entsize;
343 break;
344 }
345
346 if (populate_sym(ctx, "_module_params_begin", &ctx->parameters_begin,
347 nsyms, strtab))
348 return -1;
349
350 if (populate_sym(ctx, "_module_params_end", &ctx->parameters_end,
351 nsyms, strtab))
352 return -1;
353
354 if (populate_sym(ctx, "_bss", &ctx->bss_begin, nsyms, strtab))
355 return -1;
356
357 if (populate_sym(ctx, "_ebss", &ctx->bss_end, nsyms, strtab))
358 return -1;
359
360 if (populate_sym(ctx, "__rmodule_entry", &ctx->entry, nsyms, strtab))
361 return -1;
362
363 /* Link address is the virtual address of the program segment. */
364 ctx->link_addr = ctx->phdr->p_vaddr;
365
366 /* The program size is the memsz of the program segment. */
367 ctx->size = ctx->phdr->p_memsz;
368
369 return 0;
370}
371
372static int
373add_section(struct elf_writer *ew, struct buffer *data, const char *name,
374 Elf64_Addr addr, Elf64_Word size)
375{
376 Elf64_Shdr shdr;
377 int ret;
378
379 memset(&shdr, 0, sizeof(shdr));
380 if (data != NULL) {
381 shdr.sh_type = SHT_PROGBITS;
382 shdr.sh_flags = SHF_ALLOC | SHF_WRITE | SHF_EXECINSTR;
383 } else {
384 shdr.sh_type = SHT_NOBITS;
385 shdr.sh_flags = SHF_ALLOC;
386 }
387 shdr.sh_addr = addr;
388 shdr.sh_offset = addr;
389 shdr.sh_size = size;
390
391 ret = elf_writer_add_section(ew, &shdr, data, name);
392
393 if (ret)
394 ERROR("Could not add '%s' section.\n", name);
395
396 return ret;
397}
398
399static int
400write_elf(const struct rmod_context *ctx, const struct buffer *in,
401 struct buffer *out)
402{
403 int i;
404 int ret;
405 int bit64;
406 size_t loc;
407 size_t rmod_data_size;
408 struct elf_writer *ew;
409 struct buffer rmod_data;
410 struct buffer rmod_header;
411 struct buffer program;
412 struct buffer relocs;
413 Elf64_Xword total_size;
414 Elf64_Addr addr;
415 Elf64_Ehdr ehdr;
416
417 bit64 = ctx->pelf.ehdr.e_ident[EI_CLASS] == ELFCLASS64;
418
419 /*
420 * 3 sections will be added to the ELF file.
421 * +------------------+
422 * | rmodule header |
423 * +------------------+
424 * | program |
425 * +------------------+
426 * | relocations |
427 * +------------------+
428 */
429
430 /* Create buffer for header and relocations. */
431 rmod_data_size = sizeof(struct rmodule_header);
432 if (bit64)
433 rmod_data_size += ctx->nrelocs * sizeof(Elf64_Addr);
434 else
435 rmod_data_size += ctx->nrelocs * sizeof(Elf32_Addr);
436
437 if (buffer_create(&rmod_data, rmod_data_size, "rmod"))
438 return -1;
439
440 buffer_splice(&rmod_header, &rmod_data,
441 0, sizeof(struct rmodule_header));
442 buffer_clone(&relocs, &rmod_data);
443 buffer_seek(&relocs, sizeof(struct rmodule_header));
444
445 /* Reset current location. */
446 buffer_set_size(&rmod_header, 0);
447 buffer_set_size(&relocs, 0);
448
449 /* Program contents. */
450 buffer_splice(&program, in, ctx->phdr->p_offset, ctx->phdr->p_filesz);
451
452 /* Create ELF writer with modified entry point. */
453 memcpy(&ehdr, &ctx->pelf.ehdr, sizeof(ehdr));
454 ehdr.e_entry = ctx->entry;
455 ew = elf_writer_init(&ehdr);
456
457 if (ew == NULL) {
458 ERROR("Failed to create ELF writer.\n");
459 buffer_delete(&rmod_data);
460 return -1;
461 }
462
463 /* Write out rmodule_header. */
464 ctx->xdr->put16(&rmod_header, RMODULE_MAGIC);
465 ctx->xdr->put8(&rmod_header, RMODULE_VERSION_1);
466 ctx->xdr->put8(&rmod_header, 0);
467 /* payload_begin_offset */
468 loc = sizeof(struct rmodule_header);
469 ctx->xdr->put32(&rmod_header, loc);
470 /* payload_end_offset */
471 loc += ctx->phdr->p_filesz;
472 ctx->xdr->put32(&rmod_header, loc);
473 /* relocations_begin_offset */
474 ctx->xdr->put32(&rmod_header, loc);
475 /* relocations_end_offset */
476 if (bit64)
477 loc += ctx->nrelocs * sizeof(Elf64_Addr);
478 else
479 loc += ctx->nrelocs * sizeof(Elf32_Addr);
480 ctx->xdr->put32(&rmod_header, loc);
481 /* module_link_start_address */
482 ctx->xdr->put32(&rmod_header, ctx->link_addr);
483 /* module_program_size */
484 ctx->xdr->put32(&rmod_header, ctx->size);
485 /* module_entry_point */
486 ctx->xdr->put32(&rmod_header, ctx->entry);
487 /* parameters_begin */
488 ctx->xdr->put32(&rmod_header, ctx->parameters_begin);
489 /* parameters_end */
490 ctx->xdr->put32(&rmod_header, ctx->parameters_end);
491 /* bss_begin */
492 ctx->xdr->put32(&rmod_header, ctx->bss_begin);
493 /* bss_end */
494 ctx->xdr->put32(&rmod_header, ctx->bss_end);
495 /* padding[4] */
496 ctx->xdr->put32(&rmod_header, 0);
497 ctx->xdr->put32(&rmod_header, 0);
498 ctx->xdr->put32(&rmod_header, 0);
499 ctx->xdr->put32(&rmod_header, 0);
500
501 /* Write the relocations. */
502 for (i = 0; i < ctx->nrelocs; i++) {
503 if (bit64)
504 ctx->xdr->put64(&relocs, ctx->emitted_relocs[i]);
505 else
506 ctx->xdr->put32(&relocs, ctx->emitted_relocs[i]);
507 }
508
509 total_size = 0;
510 addr = 0;
511
512 /*
513 * There are 2 cases to deal with. The program has a large NOBITS
514 * section and the relocations can fit entirely within occupied memory
515 * region for the program. The other is that the relocations increase
516 * the memory footprint of the program if it was loaded directly into
517 * the region it would run. The rmdoule header is a fixed cost that
518 * is considered a part of the program.
519 */
520 total_size += buffer_size(&rmod_header);
521 total_size += ctx->phdr->p_memsz;
522 if (buffer_size(&relocs) + ctx->phdr->p_filesz > total_size) {
523 total_size -= ctx->phdr->p_memsz;
524 total_size += buffer_size(&relocs);
525 total_size += ctx->phdr->p_filesz;
526 }
527
528 ret = add_section(ew, &rmod_header, ".header", addr,
529 buffer_size(&rmod_header));
530 if (ret < 0)
531 goto out;
532 addr += buffer_size(&rmod_header);
533
534 ret = add_section(ew, &program, ".program", addr, ctx->phdr->p_filesz);
535 if (ret < 0)
536 goto out;
537 addr += ctx->phdr->p_filesz;
538
539 ret = add_section(ew, &relocs, ".relocs", addr, buffer_size(&relocs));
540 if (ret < 0)
541 goto out;
542 addr += buffer_size(&relocs);
543
544 if (total_size != addr) {
545 ret = add_section(ew, NULL, ".empty", addr, total_size - addr);
546 if (ret < 0)
547 goto out;
548 }
549
550 /*
551 * Ensure last section has a memory usage that meets the required
552 * total size of the program in memory.
553 */
554
555 ret = elf_writer_serialize(ew, out);
556 if (ret < 0)
557 ERROR("Failed to serialize ELF to buffer.\n");
558
559out:
560 buffer_delete(&rmod_data);
561 elf_writer_destroy(ew);
562
563 return ret;
564}
565
566int rmodule_create(const struct buffer *elfin, struct buffer *elfout)
567{
568 struct rmod_context ctx;
569 struct parsed_elf *pelf;
570 int i;
571 int ret;
572
573 ret = -1;
574 memset(&ctx, 0, sizeof(ctx));
575 pelf = &ctx.pelf;
576
577 if (parse_elf(elfin, pelf, ELF_PARSE_ALL)) {
578 ERROR("Couldn't parse ELF!\n");
579 return -1;
580 }
581
582 /* Only allow executables to be turned into rmodules. */
583 if (pelf->ehdr.e_type != ET_EXEC) {
584 ERROR("ELF is not an executable: %u.\n", pelf->ehdr.e_type);
585 goto out;
586 }
587
588 /* Determine if architecture is supported. */
589 for (i = 0; i < ARRAY_SIZE(reloc_ops); i++) {
590 if (reloc_ops[i].arch == pelf->ehdr.e_machine) {
591 ctx.ops = &reloc_ops[i];
592 break;
593 }
594 }
595
596 if (ctx.ops == NULL) {
597 ERROR("ELF is unsupported arch: %u.\n", pelf->ehdr.e_machine);
598 goto out;
599 }
600
601 /* Set the endian ops. */
602 if (ctx.pelf.ehdr.e_ident[EI_DATA] == ELFDATA2MSB)
603 ctx.xdr = &xdr_be;
604 else
605 ctx.xdr = &xdr_le;
606
607 if (find_program_segment(&ctx))
608 goto out;
609
610 if (filter_relocation_sections(&ctx))
611 goto out;
612
613 if (collect_relocations(&ctx))
614 goto out;
615
616 if (populate_program_info(&ctx))
617 goto out;
618
619 if (write_elf(&ctx, elfin, elfout))
620 goto out;
621
622 ret = 0;
623
624out:
625 free(ctx.emitted_relocs);
626 parsed_elf_destroy(pelf);
627 return ret;
628}