374813eafa52f63a38ff9079c6db3aef8ce6063b
[linux-2.6-microblaze.git] / tools / objtool / elf.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * elf.c - ELF access library
4  *
5  * Adapted from kpatch (https://github.com/dynup/kpatch):
6  * Copyright (C) 2013-2015 Josh Poimboeuf <jpoimboe@redhat.com>
7  * Copyright (C) 2014 Seth Jennings <sjenning@redhat.com>
8  */
9
10 #include <sys/types.h>
11 #include <sys/stat.h>
12 #include <fcntl.h>
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <string.h>
16 #include <unistd.h>
17 #include <errno.h>
18 #include <objtool/builtin.h>
19
20 #include <objtool/elf.h>
21 #include <objtool/warn.h>
22
23 #define MAX_NAME_LEN 128
24
25 static inline u32 str_hash(const char *str)
26 {
27         return jhash(str, strlen(str), 0);
28 }
29
30 static inline int elf_hash_bits(void)
31 {
32         return vmlinux ? ELF_HASH_BITS : 16;
33 }
34
35 #define elf_hash_add(hashtable, node, key) \
36         hlist_add_head(node, &hashtable[hash_min(key, elf_hash_bits())])
37
38 static void elf_hash_init(struct hlist_head *table)
39 {
40         __hash_init(table, 1U << elf_hash_bits());
41 }
42
43 #define elf_hash_for_each_possible(name, obj, member, key)                      \
44         hlist_for_each_entry(obj, &name[hash_min(key, elf_hash_bits())], member)
45
46 static bool symbol_to_offset(struct rb_node *a, const struct rb_node *b)
47 {
48         struct symbol *sa = rb_entry(a, struct symbol, node);
49         struct symbol *sb = rb_entry(b, struct symbol, node);
50
51         if (sa->offset < sb->offset)
52                 return true;
53         if (sa->offset > sb->offset)
54                 return false;
55
56         if (sa->len < sb->len)
57                 return true;
58         if (sa->len > sb->len)
59                 return false;
60
61         sa->alias = sb;
62
63         return false;
64 }
65
66 static int symbol_by_offset(const void *key, const struct rb_node *node)
67 {
68         const struct symbol *s = rb_entry(node, struct symbol, node);
69         const unsigned long *o = key;
70
71         if (*o < s->offset)
72                 return -1;
73         if (*o >= s->offset + s->len)
74                 return 1;
75
76         return 0;
77 }
78
79 struct section *find_section_by_name(const struct elf *elf, const char *name)
80 {
81         struct section *sec;
82
83         elf_hash_for_each_possible(elf->section_name_hash, sec, name_hash, str_hash(name))
84                 if (!strcmp(sec->name, name))
85                         return sec;
86
87         return NULL;
88 }
89
90 static struct section *find_section_by_index(struct elf *elf,
91                                              unsigned int idx)
92 {
93         struct section *sec;
94
95         elf_hash_for_each_possible(elf->section_hash, sec, hash, idx)
96                 if (sec->idx == idx)
97                         return sec;
98
99         return NULL;
100 }
101
102 static struct symbol *find_symbol_by_index(struct elf *elf, unsigned int idx)
103 {
104         struct symbol *sym;
105
106         elf_hash_for_each_possible(elf->symbol_hash, sym, hash, idx)
107                 if (sym->idx == idx)
108                         return sym;
109
110         return NULL;
111 }
112
113 struct symbol *find_symbol_by_offset(struct section *sec, unsigned long offset)
114 {
115         struct rb_node *node;
116
117         rb_for_each(node, &offset, &sec->symbol_tree, symbol_by_offset) {
118                 struct symbol *s = rb_entry(node, struct symbol, node);
119
120                 if (s->offset == offset && s->type != STT_SECTION)
121                         return s;
122         }
123
124         return NULL;
125 }
126
127 struct symbol *find_func_by_offset(struct section *sec, unsigned long offset)
128 {
129         struct rb_node *node;
130
131         rb_for_each(node, &offset, &sec->symbol_tree, symbol_by_offset) {
132                 struct symbol *s = rb_entry(node, struct symbol, node);
133
134                 if (s->offset == offset && s->type == STT_FUNC)
135                         return s;
136         }
137
138         return NULL;
139 }
140
141 struct symbol *find_symbol_containing(const struct section *sec, unsigned long offset)
142 {
143         struct rb_node *node;
144
145         rb_for_each(node, &offset, &sec->symbol_tree, symbol_by_offset) {
146                 struct symbol *s = rb_entry(node, struct symbol, node);
147
148                 if (s->type != STT_SECTION)
149                         return s;
150         }
151
152         return NULL;
153 }
154
155 struct symbol *find_func_containing(struct section *sec, unsigned long offset)
156 {
157         struct rb_node *node;
158
159         rb_for_each(node, &offset, &sec->symbol_tree, symbol_by_offset) {
160                 struct symbol *s = rb_entry(node, struct symbol, node);
161
162                 if (s->type == STT_FUNC)
163                         return s;
164         }
165
166         return NULL;
167 }
168
169 struct symbol *find_symbol_by_name(const struct elf *elf, const char *name)
170 {
171         struct symbol *sym;
172
173         elf_hash_for_each_possible(elf->symbol_name_hash, sym, name_hash, str_hash(name))
174                 if (!strcmp(sym->name, name))
175                         return sym;
176
177         return NULL;
178 }
179
180 struct reloc *find_reloc_by_dest_range(const struct elf *elf, struct section *sec,
181                                      unsigned long offset, unsigned int len)
182 {
183         struct reloc *reloc, *r = NULL;
184         unsigned long o;
185
186         if (!sec->reloc)
187                 return NULL;
188
189         sec = sec->reloc;
190
191         for_offset_range(o, offset, offset + len) {
192                 elf_hash_for_each_possible(elf->reloc_hash, reloc, hash,
193                                        sec_offset_hash(sec, o)) {
194                         if (reloc->sec != sec)
195                                 continue;
196
197                         if (reloc->offset >= offset && reloc->offset < offset + len) {
198                                 if (!r || reloc->offset < r->offset)
199                                         r = reloc;
200                         }
201                 }
202                 if (r)
203                         return r;
204         }
205
206         return NULL;
207 }
208
209 struct reloc *find_reloc_by_dest(const struct elf *elf, struct section *sec, unsigned long offset)
210 {
211         return find_reloc_by_dest_range(elf, sec, offset, 1);
212 }
213
214 void insn_to_reloc_sym_addend(struct section *sec, unsigned long offset,
215                               struct reloc *reloc)
216 {
217         if (sec->sym) {
218                 reloc->sym = sec->sym;
219                 reloc->addend = offset;
220                 return;
221         }
222
223         /*
224          * The Clang assembler strips section symbols, so we have to reference
225          * the function symbol instead:
226          */
227         reloc->sym = find_symbol_containing(sec, offset);
228         if (!reloc->sym) {
229                 /*
230                  * Hack alert.  This happens when we need to reference the NOP
231                  * pad insn immediately after the function.
232                  */
233                 reloc->sym = find_symbol_containing(sec, offset - 1);
234         }
235
236         if (reloc->sym)
237                 reloc->addend = offset - reloc->sym->offset;
238 }
239
240 static int read_sections(struct elf *elf)
241 {
242         Elf_Scn *s = NULL;
243         struct section *sec;
244         size_t shstrndx, sections_nr;
245         int i;
246
247         if (elf_getshdrnum(elf->elf, &sections_nr)) {
248                 WARN_ELF("elf_getshdrnum");
249                 return -1;
250         }
251
252         if (elf_getshdrstrndx(elf->elf, &shstrndx)) {
253                 WARN_ELF("elf_getshdrstrndx");
254                 return -1;
255         }
256
257         for (i = 0; i < sections_nr; i++) {
258                 sec = malloc(sizeof(*sec));
259                 if (!sec) {
260                         perror("malloc");
261                         return -1;
262                 }
263                 memset(sec, 0, sizeof(*sec));
264
265                 INIT_LIST_HEAD(&sec->symbol_list);
266                 INIT_LIST_HEAD(&sec->reloc_list);
267
268                 s = elf_getscn(elf->elf, i);
269                 if (!s) {
270                         WARN_ELF("elf_getscn");
271                         return -1;
272                 }
273
274                 sec->idx = elf_ndxscn(s);
275
276                 if (!gelf_getshdr(s, &sec->sh)) {
277                         WARN_ELF("gelf_getshdr");
278                         return -1;
279                 }
280
281                 sec->name = elf_strptr(elf->elf, shstrndx, sec->sh.sh_name);
282                 if (!sec->name) {
283                         WARN_ELF("elf_strptr");
284                         return -1;
285                 }
286
287                 if (sec->sh.sh_size != 0) {
288                         sec->data = elf_getdata(s, NULL);
289                         if (!sec->data) {
290                                 WARN_ELF("elf_getdata");
291                                 return -1;
292                         }
293                         if (sec->data->d_off != 0 ||
294                             sec->data->d_size != sec->sh.sh_size) {
295                                 WARN("unexpected data attributes for %s",
296                                      sec->name);
297                                 return -1;
298                         }
299                 }
300                 sec->len = sec->sh.sh_size;
301
302                 list_add_tail(&sec->list, &elf->sections);
303                 elf_hash_add(elf->section_hash, &sec->hash, sec->idx);
304                 elf_hash_add(elf->section_name_hash, &sec->name_hash, str_hash(sec->name));
305         }
306
307         if (stats)
308                 printf("nr_sections: %lu\n", (unsigned long)sections_nr);
309
310         /* sanity check, one more call to elf_nextscn() should return NULL */
311         if (elf_nextscn(elf->elf, s)) {
312                 WARN("section entry mismatch");
313                 return -1;
314         }
315
316         return 0;
317 }
318
319 static int read_symbols(struct elf *elf)
320 {
321         struct section *symtab, *symtab_shndx, *sec;
322         struct symbol *sym, *pfunc;
323         struct list_head *entry;
324         struct rb_node *pnode;
325         int symbols_nr, i;
326         char *coldstr;
327         Elf_Data *shndx_data = NULL;
328         Elf32_Word shndx;
329
330         symtab = find_section_by_name(elf, ".symtab");
331         if (!symtab) {
332                 /*
333                  * A missing symbol table is actually possible if it's an empty
334                  * .o file.  This can happen for thunk_64.o.
335                  */
336                 return 0;
337         }
338
339         symtab_shndx = find_section_by_name(elf, ".symtab_shndx");
340         if (symtab_shndx)
341                 shndx_data = symtab_shndx->data;
342
343         symbols_nr = symtab->sh.sh_size / symtab->sh.sh_entsize;
344
345         for (i = 0; i < symbols_nr; i++) {
346                 sym = malloc(sizeof(*sym));
347                 if (!sym) {
348                         perror("malloc");
349                         return -1;
350                 }
351                 memset(sym, 0, sizeof(*sym));
352                 sym->alias = sym;
353
354                 sym->idx = i;
355
356                 if (!gelf_getsymshndx(symtab->data, shndx_data, i, &sym->sym,
357                                       &shndx)) {
358                         WARN_ELF("gelf_getsymshndx");
359                         goto err;
360                 }
361
362                 sym->name = elf_strptr(elf->elf, symtab->sh.sh_link,
363                                        sym->sym.st_name);
364                 if (!sym->name) {
365                         WARN_ELF("elf_strptr");
366                         goto err;
367                 }
368
369                 sym->type = GELF_ST_TYPE(sym->sym.st_info);
370                 sym->bind = GELF_ST_BIND(sym->sym.st_info);
371
372                 if ((sym->sym.st_shndx > SHN_UNDEF &&
373                      sym->sym.st_shndx < SHN_LORESERVE) ||
374                     (shndx_data && sym->sym.st_shndx == SHN_XINDEX)) {
375                         if (sym->sym.st_shndx != SHN_XINDEX)
376                                 shndx = sym->sym.st_shndx;
377
378                         sym->sec = find_section_by_index(elf, shndx);
379                         if (!sym->sec) {
380                                 WARN("couldn't find section for symbol %s",
381                                      sym->name);
382                                 goto err;
383                         }
384                         if (sym->type == STT_SECTION) {
385                                 sym->name = sym->sec->name;
386                                 sym->sec->sym = sym;
387                         }
388                 } else
389                         sym->sec = find_section_by_index(elf, 0);
390
391                 sym->offset = sym->sym.st_value;
392                 sym->len = sym->sym.st_size;
393
394                 rb_add(&sym->node, &sym->sec->symbol_tree, symbol_to_offset);
395                 pnode = rb_prev(&sym->node);
396                 if (pnode)
397                         entry = &rb_entry(pnode, struct symbol, node)->list;
398                 else
399                         entry = &sym->sec->symbol_list;
400                 list_add(&sym->list, entry);
401                 elf_hash_add(elf->symbol_hash, &sym->hash, sym->idx);
402                 elf_hash_add(elf->symbol_name_hash, &sym->name_hash, str_hash(sym->name));
403
404                 /*
405                  * Don't store empty STT_NOTYPE symbols in the rbtree.  They
406                  * can exist within a function, confusing the sorting.
407                  */
408                 if (!sym->len)
409                         rb_erase(&sym->node, &sym->sec->symbol_tree);
410         }
411
412         if (stats)
413                 printf("nr_symbols: %lu\n", (unsigned long)symbols_nr);
414
415         /* Create parent/child links for any cold subfunctions */
416         list_for_each_entry(sec, &elf->sections, list) {
417                 list_for_each_entry(sym, &sec->symbol_list, list) {
418                         char pname[MAX_NAME_LEN + 1];
419                         size_t pnamelen;
420                         if (sym->type != STT_FUNC)
421                                 continue;
422
423                         if (sym->pfunc == NULL)
424                                 sym->pfunc = sym;
425
426                         if (sym->cfunc == NULL)
427                                 sym->cfunc = sym;
428
429                         coldstr = strstr(sym->name, ".cold");
430                         if (!coldstr)
431                                 continue;
432
433                         pnamelen = coldstr - sym->name;
434                         if (pnamelen > MAX_NAME_LEN) {
435                                 WARN("%s(): parent function name exceeds maximum length of %d characters",
436                                      sym->name, MAX_NAME_LEN);
437                                 return -1;
438                         }
439
440                         strncpy(pname, sym->name, pnamelen);
441                         pname[pnamelen] = '\0';
442                         pfunc = find_symbol_by_name(elf, pname);
443
444                         if (!pfunc) {
445                                 WARN("%s(): can't find parent function",
446                                      sym->name);
447                                 return -1;
448                         }
449
450                         sym->pfunc = pfunc;
451                         pfunc->cfunc = sym;
452
453                         /*
454                          * Unfortunately, -fnoreorder-functions puts the child
455                          * inside the parent.  Remove the overlap so we can
456                          * have sane assumptions.
457                          *
458                          * Note that pfunc->len now no longer matches
459                          * pfunc->sym.st_size.
460                          */
461                         if (sym->sec == pfunc->sec &&
462                             sym->offset >= pfunc->offset &&
463                             sym->offset + sym->len == pfunc->offset + pfunc->len) {
464                                 pfunc->len -= sym->len;
465                         }
466                 }
467         }
468
469         return 0;
470
471 err:
472         free(sym);
473         return -1;
474 }
475
476 void elf_add_reloc(struct elf *elf, struct reloc *reloc)
477 {
478         struct section *sec = reloc->sec;
479
480         list_add_tail(&reloc->list, &sec->reloc_list);
481         elf_hash_add(elf->reloc_hash, &reloc->hash, reloc_hash(reloc));
482
483         sec->changed = true;
484 }
485
486 static int read_rel_reloc(struct section *sec, int i, struct reloc *reloc, unsigned int *symndx)
487 {
488         if (!gelf_getrel(sec->data, i, &reloc->rel)) {
489                 WARN_ELF("gelf_getrel");
490                 return -1;
491         }
492         reloc->type = GELF_R_TYPE(reloc->rel.r_info);
493         reloc->addend = 0;
494         reloc->offset = reloc->rel.r_offset;
495         *symndx = GELF_R_SYM(reloc->rel.r_info);
496         return 0;
497 }
498
499 static int read_rela_reloc(struct section *sec, int i, struct reloc *reloc, unsigned int *symndx)
500 {
501         if (!gelf_getrela(sec->data, i, &reloc->rela)) {
502                 WARN_ELF("gelf_getrela");
503                 return -1;
504         }
505         reloc->type = GELF_R_TYPE(reloc->rela.r_info);
506         reloc->addend = reloc->rela.r_addend;
507         reloc->offset = reloc->rela.r_offset;
508         *symndx = GELF_R_SYM(reloc->rela.r_info);
509         return 0;
510 }
511
512 static int read_relocs(struct elf *elf)
513 {
514         struct section *sec;
515         struct reloc *reloc;
516         int i;
517         unsigned int symndx;
518         unsigned long nr_reloc, max_reloc = 0, tot_reloc = 0;
519
520         list_for_each_entry(sec, &elf->sections, list) {
521                 if ((sec->sh.sh_type != SHT_RELA) &&
522                     (sec->sh.sh_type != SHT_REL))
523                         continue;
524
525                 sec->base = find_section_by_index(elf, sec->sh.sh_info);
526                 if (!sec->base) {
527                         WARN("can't find base section for reloc section %s",
528                              sec->name);
529                         return -1;
530                 }
531
532                 sec->base->reloc = sec;
533
534                 nr_reloc = 0;
535                 for (i = 0; i < sec->sh.sh_size / sec->sh.sh_entsize; i++) {
536                         reloc = malloc(sizeof(*reloc));
537                         if (!reloc) {
538                                 perror("malloc");
539                                 return -1;
540                         }
541                         memset(reloc, 0, sizeof(*reloc));
542                         switch (sec->sh.sh_type) {
543                         case SHT_REL:
544                                 if (read_rel_reloc(sec, i, reloc, &symndx))
545                                         return -1;
546                                 break;
547                         case SHT_RELA:
548                                 if (read_rela_reloc(sec, i, reloc, &symndx))
549                                         return -1;
550                                 break;
551                         default: return -1;
552                         }
553
554                         reloc->sec = sec;
555                         reloc->idx = i;
556                         reloc->sym = find_symbol_by_index(elf, symndx);
557                         if (!reloc->sym) {
558                                 WARN("can't find reloc entry symbol %d for %s",
559                                      symndx, sec->name);
560                                 return -1;
561                         }
562
563                         list_add_tail(&reloc->list, &sec->reloc_list);
564                         elf_hash_add(elf->reloc_hash, &reloc->hash, reloc_hash(reloc));
565
566                         nr_reloc++;
567                 }
568                 max_reloc = max(max_reloc, nr_reloc);
569                 tot_reloc += nr_reloc;
570         }
571
572         if (stats) {
573                 printf("max_reloc: %lu\n", max_reloc);
574                 printf("tot_reloc: %lu\n", tot_reloc);
575         }
576
577         return 0;
578 }
579
580 struct elf *elf_open_read(const char *name, int flags)
581 {
582         struct elf *elf;
583         Elf_Cmd cmd;
584
585         elf_version(EV_CURRENT);
586
587         elf = malloc(sizeof(*elf));
588         if (!elf) {
589                 perror("malloc");
590                 return NULL;
591         }
592         memset(elf, 0, offsetof(struct elf, sections));
593
594         INIT_LIST_HEAD(&elf->sections);
595
596         elf_hash_init(elf->symbol_hash);
597         elf_hash_init(elf->symbol_name_hash);
598         elf_hash_init(elf->section_hash);
599         elf_hash_init(elf->section_name_hash);
600         elf_hash_init(elf->reloc_hash);
601
602         elf->fd = open(name, flags);
603         if (elf->fd == -1) {
604                 fprintf(stderr, "objtool: Can't open '%s': %s\n",
605                         name, strerror(errno));
606                 goto err;
607         }
608
609         if ((flags & O_ACCMODE) == O_RDONLY)
610                 cmd = ELF_C_READ_MMAP;
611         else if ((flags & O_ACCMODE) == O_RDWR)
612                 cmd = ELF_C_RDWR;
613         else /* O_WRONLY */
614                 cmd = ELF_C_WRITE;
615
616         elf->elf = elf_begin(elf->fd, cmd, NULL);
617         if (!elf->elf) {
618                 WARN_ELF("elf_begin");
619                 goto err;
620         }
621
622         if (!gelf_getehdr(elf->elf, &elf->ehdr)) {
623                 WARN_ELF("gelf_getehdr");
624                 goto err;
625         }
626
627         if (read_sections(elf))
628                 goto err;
629
630         if (read_symbols(elf))
631                 goto err;
632
633         if (read_relocs(elf))
634                 goto err;
635
636         return elf;
637
638 err:
639         elf_close(elf);
640         return NULL;
641 }
642
643 struct section *elf_create_section(struct elf *elf, const char *name,
644                                    unsigned int sh_flags, size_t entsize, int nr)
645 {
646         struct section *sec, *shstrtab;
647         size_t size = entsize * nr;
648         Elf_Scn *s;
649         Elf_Data *data;
650
651         sec = malloc(sizeof(*sec));
652         if (!sec) {
653                 perror("malloc");
654                 return NULL;
655         }
656         memset(sec, 0, sizeof(*sec));
657
658         INIT_LIST_HEAD(&sec->symbol_list);
659         INIT_LIST_HEAD(&sec->reloc_list);
660
661         s = elf_newscn(elf->elf);
662         if (!s) {
663                 WARN_ELF("elf_newscn");
664                 return NULL;
665         }
666
667         sec->name = strdup(name);
668         if (!sec->name) {
669                 perror("strdup");
670                 return NULL;
671         }
672
673         sec->idx = elf_ndxscn(s);
674         sec->len = size;
675         sec->changed = true;
676
677         sec->data = elf_newdata(s);
678         if (!sec->data) {
679                 WARN_ELF("elf_newdata");
680                 return NULL;
681         }
682
683         sec->data->d_size = size;
684         sec->data->d_align = 1;
685
686         if (size) {
687                 sec->data->d_buf = malloc(size);
688                 if (!sec->data->d_buf) {
689                         perror("malloc");
690                         return NULL;
691                 }
692                 memset(sec->data->d_buf, 0, size);
693         }
694
695         if (!gelf_getshdr(s, &sec->sh)) {
696                 WARN_ELF("gelf_getshdr");
697                 return NULL;
698         }
699
700         sec->sh.sh_size = size;
701         sec->sh.sh_entsize = entsize;
702         sec->sh.sh_type = SHT_PROGBITS;
703         sec->sh.sh_addralign = 1;
704         sec->sh.sh_flags = SHF_ALLOC | sh_flags;
705
706
707         /* Add section name to .shstrtab (or .strtab for Clang) */
708         shstrtab = find_section_by_name(elf, ".shstrtab");
709         if (!shstrtab)
710                 shstrtab = find_section_by_name(elf, ".strtab");
711         if (!shstrtab) {
712                 WARN("can't find .shstrtab or .strtab section");
713                 return NULL;
714         }
715
716         s = elf_getscn(elf->elf, shstrtab->idx);
717         if (!s) {
718                 WARN_ELF("elf_getscn");
719                 return NULL;
720         }
721
722         data = elf_newdata(s);
723         if (!data) {
724                 WARN_ELF("elf_newdata");
725                 return NULL;
726         }
727
728         data->d_buf = sec->name;
729         data->d_size = strlen(name) + 1;
730         data->d_align = 1;
731
732         sec->sh.sh_name = shstrtab->len;
733
734         shstrtab->len += strlen(name) + 1;
735         shstrtab->changed = true;
736
737         list_add_tail(&sec->list, &elf->sections);
738         elf_hash_add(elf->section_hash, &sec->hash, sec->idx);
739         elf_hash_add(elf->section_name_hash, &sec->name_hash, str_hash(sec->name));
740
741         elf->changed = true;
742
743         return sec;
744 }
745
746 static struct section *elf_create_rel_reloc_section(struct elf *elf, struct section *base)
747 {
748         char *relocname;
749         struct section *sec;
750
751         relocname = malloc(strlen(base->name) + strlen(".rel") + 1);
752         if (!relocname) {
753                 perror("malloc");
754                 return NULL;
755         }
756         strcpy(relocname, ".rel");
757         strcat(relocname, base->name);
758
759         sec = elf_create_section(elf, relocname, 0, sizeof(GElf_Rel), 0);
760         free(relocname);
761         if (!sec)
762                 return NULL;
763
764         base->reloc = sec;
765         sec->base = base;
766
767         sec->sh.sh_type = SHT_REL;
768         sec->sh.sh_addralign = 8;
769         sec->sh.sh_link = find_section_by_name(elf, ".symtab")->idx;
770         sec->sh.sh_info = base->idx;
771         sec->sh.sh_flags = SHF_INFO_LINK;
772
773         return sec;
774 }
775
776 static struct section *elf_create_rela_reloc_section(struct elf *elf, struct section *base)
777 {
778         char *relocname;
779         struct section *sec;
780
781         relocname = malloc(strlen(base->name) + strlen(".rela") + 1);
782         if (!relocname) {
783                 perror("malloc");
784                 return NULL;
785         }
786         strcpy(relocname, ".rela");
787         strcat(relocname, base->name);
788
789         sec = elf_create_section(elf, relocname, 0, sizeof(GElf_Rela), 0);
790         free(relocname);
791         if (!sec)
792                 return NULL;
793
794         base->reloc = sec;
795         sec->base = base;
796
797         sec->sh.sh_type = SHT_RELA;
798         sec->sh.sh_addralign = 8;
799         sec->sh.sh_link = find_section_by_name(elf, ".symtab")->idx;
800         sec->sh.sh_info = base->idx;
801         sec->sh.sh_flags = SHF_INFO_LINK;
802
803         return sec;
804 }
805
806 struct section *elf_create_reloc_section(struct elf *elf,
807                                          struct section *base,
808                                          int reltype)
809 {
810         switch (reltype) {
811         case SHT_REL:  return elf_create_rel_reloc_section(elf, base);
812         case SHT_RELA: return elf_create_rela_reloc_section(elf, base);
813         default:       return NULL;
814         }
815 }
816
817 static int elf_rebuild_rel_reloc_section(struct section *sec, int nr)
818 {
819         struct reloc *reloc;
820         int idx = 0, size;
821         void *buf;
822
823         /* Allocate a buffer for relocations */
824         size = nr * sizeof(GElf_Rel);
825         buf = malloc(size);
826         if (!buf) {
827                 perror("malloc");
828                 return -1;
829         }
830
831         sec->data->d_buf = buf;
832         sec->data->d_size = size;
833         sec->data->d_type = ELF_T_REL;
834
835         sec->sh.sh_size = size;
836
837         idx = 0;
838         list_for_each_entry(reloc, &sec->reloc_list, list) {
839                 reloc->rel.r_offset = reloc->offset;
840                 reloc->rel.r_info = GELF_R_INFO(reloc->sym->idx, reloc->type);
841                 gelf_update_rel(sec->data, idx, &reloc->rel);
842                 idx++;
843         }
844
845         return 0;
846 }
847
848 static int elf_rebuild_rela_reloc_section(struct section *sec, int nr)
849 {
850         struct reloc *reloc;
851         int idx = 0, size;
852         void *buf;
853
854         /* Allocate a buffer for relocations with addends */
855         size = nr * sizeof(GElf_Rela);
856         buf = malloc(size);
857         if (!buf) {
858                 perror("malloc");
859                 return -1;
860         }
861
862         sec->data->d_buf = buf;
863         sec->data->d_size = size;
864         sec->data->d_type = ELF_T_RELA;
865
866         sec->sh.sh_size = size;
867
868         idx = 0;
869         list_for_each_entry(reloc, &sec->reloc_list, list) {
870                 reloc->rela.r_offset = reloc->offset;
871                 reloc->rela.r_addend = reloc->addend;
872                 reloc->rela.r_info = GELF_R_INFO(reloc->sym->idx, reloc->type);
873                 gelf_update_rela(sec->data, idx, &reloc->rela);
874                 idx++;
875         }
876
877         return 0;
878 }
879
880 static int elf_rebuild_reloc_section(struct elf *elf, struct section *sec)
881 {
882         struct reloc *reloc;
883         int nr;
884
885         nr = 0;
886         list_for_each_entry(reloc, &sec->reloc_list, list)
887                 nr++;
888
889         switch (sec->sh.sh_type) {
890         case SHT_REL:  return elf_rebuild_rel_reloc_section(sec, nr);
891         case SHT_RELA: return elf_rebuild_rela_reloc_section(sec, nr);
892         default:       return -1;
893         }
894 }
895
896 int elf_write_insn(struct elf *elf, struct section *sec,
897                    unsigned long offset, unsigned int len,
898                    const char *insn)
899 {
900         Elf_Data *data = sec->data;
901
902         if (data->d_type != ELF_T_BYTE || data->d_off) {
903                 WARN("write to unexpected data for section: %s", sec->name);
904                 return -1;
905         }
906
907         memcpy(data->d_buf + offset, insn, len);
908         elf_flagdata(data, ELF_C_SET, ELF_F_DIRTY);
909
910         elf->changed = true;
911
912         return 0;
913 }
914
915 int elf_write_reloc(struct elf *elf, struct reloc *reloc)
916 {
917         struct section *sec = reloc->sec;
918
919         if (sec->sh.sh_type == SHT_REL) {
920                 reloc->rel.r_info = GELF_R_INFO(reloc->sym->idx, reloc->type);
921                 reloc->rel.r_offset = reloc->offset;
922
923                 if (!gelf_update_rel(sec->data, reloc->idx, &reloc->rel)) {
924                         WARN_ELF("gelf_update_rel");
925                         return -1;
926                 }
927         } else {
928                 reloc->rela.r_info = GELF_R_INFO(reloc->sym->idx, reloc->type);
929                 reloc->rela.r_addend = reloc->addend;
930                 reloc->rela.r_offset = reloc->offset;
931
932                 if (!gelf_update_rela(sec->data, reloc->idx, &reloc->rela)) {
933                         WARN_ELF("gelf_update_rela");
934                         return -1;
935                 }
936         }
937
938         elf->changed = true;
939
940         return 0;
941 }
942
943 int elf_write(struct elf *elf)
944 {
945         struct section *sec;
946         Elf_Scn *s;
947
948         /* Update changed relocation sections and section headers: */
949         list_for_each_entry(sec, &elf->sections, list) {
950                 if (sec->changed) {
951                         if (sec->base &&
952                             elf_rebuild_reloc_section(elf, sec)) {
953                                 WARN("elf_rebuild_reloc_section");
954                                 return -1;
955                         }
956
957                         s = elf_getscn(elf->elf, sec->idx);
958                         if (!s) {
959                                 WARN_ELF("elf_getscn");
960                                 return -1;
961                         }
962                         if (!gelf_update_shdr(s, &sec->sh)) {
963                                 WARN_ELF("gelf_update_shdr");
964                                 return -1;
965                         }
966
967                         sec->changed = false;
968                         elf->changed = true;
969                 }
970         }
971
972         /* Make sure the new section header entries get updated properly. */
973         elf_flagelf(elf->elf, ELF_C_SET, ELF_F_DIRTY);
974
975         /* Write all changes to the file. */
976         if (elf_update(elf->elf, ELF_C_WRITE) < 0) {
977                 WARN_ELF("elf_update");
978                 return -1;
979         }
980
981         elf->changed = false;
982
983         return 0;
984 }
985
986 void elf_close(struct elf *elf)
987 {
988         struct section *sec, *tmpsec;
989         struct symbol *sym, *tmpsym;
990         struct reloc *reloc, *tmpreloc;
991
992         if (elf->elf)
993                 elf_end(elf->elf);
994
995         if (elf->fd > 0)
996                 close(elf->fd);
997
998         list_for_each_entry_safe(sec, tmpsec, &elf->sections, list) {
999                 list_for_each_entry_safe(sym, tmpsym, &sec->symbol_list, list) {
1000                         list_del(&sym->list);
1001                         hash_del(&sym->hash);
1002                         free(sym);
1003                 }
1004                 list_for_each_entry_safe(reloc, tmpreloc, &sec->reloc_list, list) {
1005                         list_del(&reloc->list);
1006                         hash_del(&reloc->hash);
1007                         free(reloc);
1008                 }
1009                 list_del(&sec->list);
1010                 free(sec);
1011         }
1012
1013         free(elf);
1014 }