insmod: fix build warnings. By Cristian Ionescu-Idbohrn
[platform/upstream/busybox.git] / modutils / insmod.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Mini insmod implementation for busybox
4  *
5  * This version of insmod supports ARM, CRIS, H8/300, x86, ia64, x86_64,
6  * m68k, MIPS, PowerPC, S390, SH3/4/5, Sparc, v850e, and x86_64.
7  *
8  * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
9  * and Ron Alder <alder@lineo.com>
10  *
11  * Rodney Radford <rradford@mindspring.com> 17-Aug-2004.
12  *   Added x86_64 support.
13  *
14  * Miles Bader <miles@gnu.org> added NEC V850E support.
15  *
16  * Modified by Bryan Rittmeyer <bryan@ixiacom.com> to support SH4
17  * and (theoretically) SH3. I have only tested SH4 in little endian mode.
18  *
19  * Modified by Alcove, Julien Gaulmin <julien.gaulmin@alcove.fr> and
20  * Nicolas Ferre <nicolas.ferre@alcove.fr> to support ARM7TDMI.  Only
21  * very minor changes required to also work with StrongArm and presumably
22  * all ARM based systems.
23  *
24  * Yoshinori Sato <ysato@users.sourceforge.jp> 19-May-2004.
25  *   added Renesas H8/300 support.
26  *
27  * Paul Mundt <lethal@linux-sh.org> 08-Aug-2003.
28  *   Integrated support for sh64 (SH-5), from preliminary modutils
29  *   patches from Benedict Gaster <benedict.gaster@superh.com>.
30  *   Currently limited to support for 32bit ABI.
31  *
32  * Magnus Damm <damm@opensource.se> 22-May-2002.
33  *   The plt and got code are now using the same structs.
34  *   Added generic linked list code to fully support PowerPC.
35  *   Replaced the mess in arch_apply_relocation() with architecture blocks.
36  *   The arch_create_got() function got cleaned up with architecture blocks.
37  *   These blocks should be easy maintain and sync with obj_xxx.c in modutils.
38  *
39  * Magnus Damm <damm@opensource.se> added PowerPC support 20-Feb-2001.
40  *   PowerPC specific code stolen from modutils-2.3.16,
41  *   written by Paul Mackerras, Copyright 1996, 1997 Linux International.
42  *   I've only tested the code on mpc8xx platforms in big-endian mode.
43  *   Did some cleanup and added USE_xxx_ENTRIES...
44  *
45  * Quinn Jensen <jensenq@lineo.com> added MIPS support 23-Feb-2001.
46  *   based on modutils-2.4.2
47  *   MIPS specific support for Elf loading and relocation.
48  *   Copyright 1996, 1997 Linux International.
49  *   Contributed by Ralf Baechle <ralf@gnu.ai.mit.edu>
50  *
51  * Based almost entirely on the Linux modutils-2.3.11 implementation.
52  *   Copyright 1996, 1997 Linux International.
53  *   New implementation contributed by Richard Henderson <rth@tamu.edu>
54  *   Based on original work by Bjorn Ekwall <bj0rn@blox.se>
55  *   Restructured (and partly rewritten) by:
56  *   Björn Ekwall <bj0rn@blox.se> February 1999
57  *
58  * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
59  */
60
61 #include "libbb.h"
62 #include <libgen.h>
63 #include <sys/utsname.h>
64
65 #if !ENABLE_FEATURE_2_4_MODULES && !ENABLE_FEATURE_2_6_MODULES
66 #undef ENABLE_FEATURE_2_4_MODULES
67 #define ENABLE_FEATURE_2_4_MODULES 1
68 #endif
69
70 /*
71  * Big piece of 2.4-specific code
72  */
73 #if ENABLE_FEATURE_2_4_MODULES
74
75 #if ENABLE_FEATURE_2_6_MODULES
76 static int insmod_ng_main(int argc, char **argv);
77 #endif
78
79 #if ENABLE_FEATURE_INSMOD_LOADINKMEM
80 #define LOADBITS 0
81 #else
82 #define LOADBITS 1
83 #endif
84
85 /* Alpha */
86 #if defined(__alpha__)
87 #define MATCH_MACHINE(x) (x == EM_ALPHA)
88 #define SHT_RELM       SHT_RELA
89 #define Elf64_RelM     Elf64_Rela
90 #define ELFCLASSM      ELFCLASS64
91 #endif
92
93 /* ARM support */
94 #if defined(__arm__)
95 #define MATCH_MACHINE(x) (x == EM_ARM)
96 #define SHT_RELM        SHT_REL
97 #define Elf32_RelM      Elf32_Rel
98 #define ELFCLASSM       ELFCLASS32
99 #define USE_PLT_ENTRIES
100 #define PLT_ENTRY_SIZE 8
101 #define USE_GOT_ENTRIES
102 #define GOT_ENTRY_SIZE 8
103 #define USE_SINGLE
104 #endif
105
106 /* blackfin */
107 #if defined(BFIN)
108 #define MATCH_MACHINE(x) (x == EM_BLACKFIN)
109 #define SHT_RELM        SHT_RELA
110 #define Elf32_RelM      Elf32_Rela
111 #define ELFCLASSM       ELFCLASS32
112 #endif
113
114 /* CRIS */
115 #if defined(__cris__)
116 #define MATCH_MACHINE(x) (x == EM_CRIS)
117 #define SHT_RELM        SHT_RELA
118 #define Elf32_RelM      Elf32_Rela
119 #define ELFCLASSM       ELFCLASS32
120 #ifndef EM_CRIS
121 #define EM_CRIS 76
122 #define R_CRIS_NONE 0
123 #define R_CRIS_32   3
124 #endif
125 #endif
126
127 /* H8/300 */
128 #if defined(__H8300H__) || defined(__H8300S__)
129 #define MATCH_MACHINE(x) (x == EM_H8_300)
130 #define SHT_RELM        SHT_RELA
131 #define Elf32_RelM      Elf32_Rela
132 #define ELFCLASSM       ELFCLASS32
133 #define USE_SINGLE
134 #define SYMBOL_PREFIX   "_"
135 #endif
136
137 /* PA-RISC / HP-PA */
138 #if defined(__hppa__)
139 #define MATCH_MACHINE(x) (x == EM_PARISC)
140 #define SHT_RELM       SHT_RELA
141 #if defined(__LP64__)
142 #define Elf64_RelM     Elf64_Rela
143 #define ELFCLASSM      ELFCLASS64
144 #else
145 #define Elf32_RelM     Elf32_Rela
146 #define ELFCLASSM      ELFCLASS32
147 #endif
148 #endif
149
150 /* x86 */
151 #if defined(__i386__)
152 #ifndef EM_486
153 #define MATCH_MACHINE(x) (x == EM_386)
154 #else
155 #define MATCH_MACHINE(x) (x == EM_386 || x == EM_486)
156 #endif
157 #define SHT_RELM        SHT_REL
158 #define Elf32_RelM      Elf32_Rel
159 #define ELFCLASSM       ELFCLASS32
160 #define USE_GOT_ENTRIES
161 #define GOT_ENTRY_SIZE 4
162 #define USE_SINGLE
163 #endif
164
165 /* IA64, aka Itanium */
166 #if defined(__ia64__)
167 #define MATCH_MACHINE(x) (x == EM_IA_64)
168 #define SHT_RELM       SHT_RELA
169 #define Elf64_RelM     Elf64_Rela
170 #define ELFCLASSM      ELFCLASS64
171 #endif
172
173 /* m68k */
174 #if defined(__mc68000__)
175 #define MATCH_MACHINE(x) (x == EM_68K)
176 #define SHT_RELM        SHT_RELA
177 #define Elf32_RelM      Elf32_Rela
178 #define ELFCLASSM       ELFCLASS32
179 #define USE_GOT_ENTRIES
180 #define GOT_ENTRY_SIZE 4
181 #define USE_SINGLE
182 #endif
183
184 /* Microblaze */
185 #if defined(__microblaze__)
186 #define USE_SINGLE
187 #define MATCH_MACHINE(x) (x == EM_XILINX_MICROBLAZE)
188 #define SHT_RELM        SHT_RELA
189 #define Elf32_RelM      Elf32_Rela
190 #define ELFCLASSM       ELFCLASS32
191 #endif
192
193 /* MIPS */
194 #if defined(__mips__)
195 #define MATCH_MACHINE(x) (x == EM_MIPS || x == EM_MIPS_RS3_LE)
196 #define SHT_RELM        SHT_REL
197 #define Elf32_RelM      Elf32_Rel
198 #define ELFCLASSM       ELFCLASS32
199 /* Account for ELF spec changes.  */
200 #ifndef EM_MIPS_RS3_LE
201 #ifdef EM_MIPS_RS4_BE
202 #define EM_MIPS_RS3_LE  EM_MIPS_RS4_BE
203 #else
204 #define EM_MIPS_RS3_LE  10
205 #endif
206 #endif /* !EM_MIPS_RS3_LE */
207 #define ARCHDATAM       "__dbe_table"
208 #endif
209
210 /* Nios II */
211 #if defined(__nios2__)
212 #define MATCH_MACHINE(x) (x == EM_ALTERA_NIOS2)
213 #define SHT_RELM        SHT_RELA
214 #define Elf32_RelM      Elf32_Rela
215 #define ELFCLASSM       ELFCLASS32
216 #endif
217
218 /* PowerPC */
219 #if defined(__powerpc64__)
220 #define MATCH_MACHINE(x) (x == EM_PPC64)
221 #define SHT_RELM        SHT_RELA
222 #define Elf64_RelM      Elf64_Rela
223 #define ELFCLASSM       ELFCLASS64
224 #elif defined(__powerpc__)
225 #define MATCH_MACHINE(x) (x == EM_PPC)
226 #define SHT_RELM        SHT_RELA
227 #define Elf32_RelM      Elf32_Rela
228 #define ELFCLASSM       ELFCLASS32
229 #define USE_PLT_ENTRIES
230 #define PLT_ENTRY_SIZE 16
231 #define USE_PLT_LIST
232 #define LIST_ARCHTYPE ElfW(Addr)
233 #define USE_LIST
234 #define ARCHDATAM       "__ftr_fixup"
235 #endif
236
237 /* S390 */
238 #if defined(__s390__)
239 #define MATCH_MACHINE(x) (x == EM_S390)
240 #define SHT_RELM        SHT_RELA
241 #define Elf32_RelM      Elf32_Rela
242 #define ELFCLASSM       ELFCLASS32
243 #define USE_PLT_ENTRIES
244 #define PLT_ENTRY_SIZE 8
245 #define USE_GOT_ENTRIES
246 #define GOT_ENTRY_SIZE 8
247 #define USE_SINGLE
248 #endif
249
250 /* SuperH */
251 #if defined(__sh__)
252 #define MATCH_MACHINE(x) (x == EM_SH)
253 #define SHT_RELM        SHT_RELA
254 #define Elf32_RelM      Elf32_Rela
255 #define ELFCLASSM       ELFCLASS32
256 #define USE_GOT_ENTRIES
257 #define GOT_ENTRY_SIZE 4
258 #define USE_SINGLE
259 /* the SH changes have only been tested in =little endian= mode */
260 /* I'm not sure about big endian, so let's warn: */
261 #if defined(__sh__) && BB_BIG_ENDIAN
262 # error insmod.c may require changes for use on big endian SH
263 #endif
264 /* it may or may not work on the SH1/SH2... Error on those also */
265 #if ((!(defined(__SH3__) || defined(__SH4__) || defined(__SH5__)))) && (defined(__sh__))
266 #error insmod.c may require changes for SH1 or SH2 use
267 #endif
268 #endif
269
270 /* Sparc */
271 #if defined(__sparc__)
272 #define MATCH_MACHINE(x) (x == EM_SPARC)
273 #define SHT_RELM       SHT_RELA
274 #define Elf32_RelM     Elf32_Rela
275 #define ELFCLASSM      ELFCLASS32
276 #endif
277
278 /* v850e */
279 #if defined(__v850e__)
280 #define MATCH_MACHINE(x) ((x) == EM_V850 || (x) == EM_CYGNUS_V850)
281 #define SHT_RELM        SHT_RELA
282 #define Elf32_RelM      Elf32_Rela
283 #define ELFCLASSM       ELFCLASS32
284 #define USE_PLT_ENTRIES
285 #define PLT_ENTRY_SIZE 8
286 #define USE_SINGLE
287 #ifndef EM_CYGNUS_V850  /* grumble */
288 #define EM_CYGNUS_V850  0x9080
289 #endif
290 #define SYMBOL_PREFIX   "_"
291 #endif
292
293 /* X86_64  */
294 #if defined(__x86_64__)
295 #define MATCH_MACHINE(x) (x == EM_X86_64)
296 #define SHT_RELM        SHT_RELA
297 #define USE_GOT_ENTRIES
298 #define GOT_ENTRY_SIZE 8
299 #define USE_SINGLE
300 #define Elf64_RelM      Elf64_Rela
301 #define ELFCLASSM       ELFCLASS64
302 #endif
303
304 #ifndef SHT_RELM
305 #error Sorry, but insmod.c does not yet support this architecture...
306 #endif
307
308
309 //----------------------------------------------------------------------------
310 //--------modutils module.h, lines 45-242
311 //----------------------------------------------------------------------------
312
313 /* Definitions for the Linux module syscall interface.
314    Copyright 1996, 1997 Linux International.
315
316    Contributed by Richard Henderson <rth@tamu.edu>
317
318    This file is part of the Linux modutils.
319
320    This program is free software; you can redistribute it and/or modify it
321    under the terms of the GNU General Public License as published by the
322    Free Software Foundation; either version 2 of the License, or (at your
323    option) any later version.
324
325    This program is distributed in the hope that it will be useful, but
326    WITHOUT ANY WARRANTY; without even the implied warranty of
327    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
328    General Public License for more details.
329
330    You should have received a copy of the GNU General Public License
331    along with this program; if not, write to the Free Software Foundation,
332    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
333
334
335 #ifndef MODUTILS_MODULE_H
336
337 /*======================================================================*/
338 /* For sizeof() which are related to the module platform and not to the
339    environment isnmod is running in, use sizeof_xx instead of sizeof(xx).  */
340
341 #define tgt_sizeof_char         sizeof(char)
342 #define tgt_sizeof_short        sizeof(short)
343 #define tgt_sizeof_int          sizeof(int)
344 #define tgt_sizeof_long         sizeof(long)
345 #define tgt_sizeof_char_p       sizeof(char *)
346 #define tgt_sizeof_void_p       sizeof(void *)
347 #define tgt_long                long
348
349 #if defined(__sparc__) && !defined(__sparc_v9__) && defined(ARCH_sparc64)
350 #undef tgt_sizeof_long
351 #undef tgt_sizeof_char_p
352 #undef tgt_sizeof_void_p
353 #undef tgt_long
354 enum {
355         tgt_sizeof_long = 8,
356         tgt_sizeof_char_p = 8,
357         tgt_sizeof_void_p = 8
358 };
359 #define tgt_long                long long
360 #endif
361
362 /*======================================================================*/
363 /* The structures used in Linux 2.1.  */
364
365 /* Note: new_module_symbol does not use tgt_long intentionally */
366 struct new_module_symbol {
367         unsigned long value;
368         unsigned long name;
369 };
370
371 struct new_module_persist;
372
373 struct new_module_ref {
374         unsigned tgt_long dep;          /* kernel addresses */
375         unsigned tgt_long ref;
376         unsigned tgt_long next_ref;
377 };
378
379 struct new_module {
380         unsigned tgt_long size_of_struct;       /* == sizeof(module) */
381         unsigned tgt_long next;
382         unsigned tgt_long name;
383         unsigned tgt_long size;
384
385         tgt_long usecount;
386         unsigned tgt_long flags;                /* AUTOCLEAN et al */
387
388         unsigned nsyms;
389         unsigned ndeps;
390
391         unsigned tgt_long syms;
392         unsigned tgt_long deps;
393         unsigned tgt_long refs;
394         unsigned tgt_long init;
395         unsigned tgt_long cleanup;
396         unsigned tgt_long ex_table_start;
397         unsigned tgt_long ex_table_end;
398 #ifdef __alpha__
399         unsigned tgt_long gp;
400 #endif
401         /* Everything after here is extension.  */
402         unsigned tgt_long persist_start;
403         unsigned tgt_long persist_end;
404         unsigned tgt_long can_unload;
405         unsigned tgt_long runsize;
406         const char *kallsyms_start;     /* All symbols for kernel debugging */
407         const char *kallsyms_end;
408         const char *archdata_start;     /* arch specific data for module */
409         const char *archdata_end;
410         const char *kernel_data;        /* Reserved for kernel internal use */
411 };
412
413 #ifdef ARCHDATAM
414 #define ARCHDATA_SEC_NAME ARCHDATAM
415 #else
416 #define ARCHDATA_SEC_NAME "__archdata"
417 #endif
418 #define KALLSYMS_SEC_NAME "__kallsyms"
419
420
421 struct new_module_info {
422         unsigned long addr;
423         unsigned long size;
424         unsigned long flags;
425         long usecount;
426 };
427
428 /* Bits of module.flags.  */
429 enum {
430         NEW_MOD_RUNNING = 1,
431         NEW_MOD_DELETED = 2,
432         NEW_MOD_AUTOCLEAN = 4,
433         NEW_MOD_VISITED = 8,
434         NEW_MOD_USED_ONCE = 16
435 };
436
437 int init_module(const char *name, const struct new_module *);
438 int query_module(const char *name, int which, void *buf,
439                 size_t bufsize, size_t *ret);
440
441 /* Values for query_module's which.  */
442 enum {
443         QM_MODULES = 1,
444         QM_DEPS = 2,
445         QM_REFS = 3,
446         QM_SYMBOLS = 4,
447         QM_INFO = 5
448 };
449
450 /*======================================================================*/
451 /* The system calls unchanged between 2.0 and 2.1.  */
452
453 unsigned long create_module(const char *, size_t);
454 int delete_module(const char *);
455
456
457 #endif /* module.h */
458
459 //----------------------------------------------------------------------------
460 //--------end of modutils module.h
461 //----------------------------------------------------------------------------
462
463
464
465 //----------------------------------------------------------------------------
466 //--------modutils obj.h, lines 253-462
467 //----------------------------------------------------------------------------
468
469 /* Elf object file loading and relocation routines.
470    Copyright 1996, 1997 Linux International.
471
472    Contributed by Richard Henderson <rth@tamu.edu>
473
474    This file is part of the Linux modutils.
475
476    This program is free software; you can redistribute it and/or modify it
477    under the terms of the GNU General Public License as published by the
478    Free Software Foundation; either version 2 of the License, or (at your
479    option) any later version.
480
481    This program is distributed in the hope that it will be useful, but
482    WITHOUT ANY WARRANTY; without even the implied warranty of
483    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
484    General Public License for more details.
485
486    You should have received a copy of the GNU General Public License
487    along with this program; if not, write to the Free Software Foundation,
488    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
489
490
491 #ifndef MODUTILS_OBJ_H
492
493 /* The relocatable object is manipulated using elfin types.  */
494
495 #include <elf.h>
496 #include <endian.h>
497
498 #ifndef ElfW
499 # if ELFCLASSM == ELFCLASS32
500 #  define ElfW(x)  Elf32_ ## x
501 #  define ELFW(x)  ELF32_ ## x
502 # else
503 #  define ElfW(x)  Elf64_ ## x
504 #  define ELFW(x)  ELF64_ ## x
505 # endif
506 #endif
507
508 /* For some reason this is missing from some ancient C libraries....  */
509 #ifndef ELF32_ST_INFO
510 # define ELF32_ST_INFO(bind, type)       (((bind) << 4) + ((type) & 0xf))
511 #endif
512
513 #ifndef ELF64_ST_INFO
514 # define ELF64_ST_INFO(bind, type)       (((bind) << 4) + ((type) & 0xf))
515 #endif
516
517 #define ELF_ST_BIND(info) ELFW(ST_BIND)(info)
518 #define ELF_ST_TYPE(info) ELFW(ST_TYPE)(info)
519 #define ELF_ST_INFO(bind, type) ELFW(ST_INFO)(bind, type)
520 #define ELF_R_TYPE(val) ELFW(R_TYPE)(val)
521 #define ELF_R_SYM(val) ELFW(R_SYM)(val)
522
523 struct obj_string_patch;
524 struct obj_symbol_patch;
525
526 struct obj_section
527 {
528         ElfW(Shdr) header;
529         const char *name;
530         char *contents;
531         struct obj_section *load_next;
532         int idx;
533 };
534
535 struct obj_symbol
536 {
537         struct obj_symbol *next;        /* hash table link */
538         const char *name;
539         unsigned long value;
540         unsigned long size;
541         int secidx;                     /* the defining section index/module */
542         int info;
543         int ksymidx;                    /* for export to the kernel symtab */
544         int referenced;         /* actually used in the link */
545 };
546
547 /* Hardcode the hash table size.  We shouldn't be needing so many
548    symbols that we begin to degrade performance, and we get a big win
549    by giving the compiler a constant divisor.  */
550
551 #define HASH_BUCKETS  521
552
553 struct obj_file {
554         ElfW(Ehdr) header;
555         ElfW(Addr) baseaddr;
556         struct obj_section **sections;
557         struct obj_section *load_order;
558         struct obj_section **load_order_search_start;
559         struct obj_string_patch *string_patches;
560         struct obj_symbol_patch *symbol_patches;
561         int (*symbol_cmp)(const char *, const char *);
562         unsigned long (*symbol_hash)(const char *);
563         unsigned long local_symtab_size;
564         struct obj_symbol **local_symtab;
565         struct obj_symbol *symtab[HASH_BUCKETS];
566 };
567
568 enum obj_reloc {
569         obj_reloc_ok,
570         obj_reloc_overflow,
571         obj_reloc_dangerous,
572         obj_reloc_unhandled
573 };
574
575 struct obj_string_patch {
576         struct obj_string_patch *next;
577         int reloc_secidx;
578         ElfW(Addr) reloc_offset;
579         ElfW(Addr) string_offset;
580 };
581
582 struct obj_symbol_patch {
583         struct obj_symbol_patch *next;
584         int reloc_secidx;
585         ElfW(Addr) reloc_offset;
586         struct obj_symbol *sym;
587 };
588
589
590 /* Generic object manipulation routines.  */
591
592 static unsigned long obj_elf_hash(const char *);
593
594 static unsigned long obj_elf_hash_n(const char *, unsigned long len);
595
596 static struct obj_symbol *obj_find_symbol(struct obj_file *f,
597                                          const char *name);
598
599 static ElfW(Addr) obj_symbol_final_value(struct obj_file *f,
600                                   struct obj_symbol *sym);
601
602 #if ENABLE_FEATURE_INSMOD_VERSION_CHECKING
603 static void obj_set_symbol_compare(struct obj_file *f,
604                             int (*cmp)(const char *, const char *),
605                             unsigned long (*hash)(const char *));
606 #endif
607
608 static struct obj_section *obj_find_section(struct obj_file *f,
609                                            const char *name);
610
611 static void obj_insert_section_load_order(struct obj_file *f,
612                                     struct obj_section *sec);
613
614 static struct obj_section *obj_create_alloced_section(struct obj_file *f,
615                                                 const char *name,
616                                                 unsigned long align,
617                                                 unsigned long size);
618
619 static struct obj_section *obj_create_alloced_section_first(struct obj_file *f,
620                                                       const char *name,
621                                                       unsigned long align,
622                                                       unsigned long size);
623
624 static void *obj_extend_section(struct obj_section *sec, unsigned long more);
625
626 static void obj_string_patch(struct obj_file *f, int secidx, ElfW(Addr) offset,
627                      const char *string);
628
629 static void obj_symbol_patch(struct obj_file *f, int secidx, ElfW(Addr) offset,
630                      struct obj_symbol *sym);
631
632 static void obj_check_undefineds(struct obj_file *f);
633
634 static void obj_allocate_commons(struct obj_file *f);
635
636 static unsigned long obj_load_size(struct obj_file *f);
637
638 static int obj_relocate(struct obj_file *f, ElfW(Addr) base);
639
640 static struct obj_file *obj_load(FILE *f, int loadprogbits);
641
642 static int obj_create_image(struct obj_file *f, char *image);
643
644 /* Architecture specific manipulation routines.  */
645
646 static struct obj_file *arch_new_file(void);
647
648 static struct obj_section *arch_new_section(void);
649
650 static struct obj_symbol *arch_new_symbol(void);
651
652 static enum obj_reloc arch_apply_relocation(struct obj_file *f,
653                                       struct obj_section *targsec,
654                                       /*struct obj_section *symsec,*/
655                                       struct obj_symbol *sym,
656                                       ElfW(RelM) *rel, ElfW(Addr) value);
657
658 static void arch_create_got(struct obj_file *f);
659 #if ENABLE_FEATURE_CHECK_TAINTED_MODULE
660 static int obj_gpl_license(struct obj_file *f, const char **license);
661 #endif /* FEATURE_CHECK_TAINTED_MODULE */
662 #endif /* obj.h */
663 //----------------------------------------------------------------------------
664 //--------end of modutils obj.h
665 //----------------------------------------------------------------------------
666
667
668 /* SPFX is always a string, so it can be concatenated to string constants.  */
669 #ifdef SYMBOL_PREFIX
670 #define SPFX    SYMBOL_PREFIX
671 #else
672 #define SPFX    ""
673 #endif
674
675
676 #define _PATH_MODULES   "/lib/modules"
677 enum { STRVERSIONLEN = 64 };
678
679 /*======================================================================*/
680
681 #define OPTION_STR "sLo:fkvqx" USE_FEATURE_INSMOD_LOAD_MAP("m")
682 enum {
683         OPT_s = 0x1, // -s /* log to syslog */
684                 /* Not supported but kernel needs this for request_module(),
685                    as this calls: modprobe -k -s -- <module>
686                    so silently ignore this flag */
687         OPT_L = 0x2, // -L /* Stub warning */
688                 /* Compatibility with modprobe.
689                    In theory, this does locking, but we don't do
690                    that.  So be careful and plan your life around not
691                    loading the same module 50 times concurrently. */
692         OPT_o = 0x4, // -o /* name the output module */
693         OPT_f = 0x8, // -f /* force loading */
694         OPT_k = 0x10, // -k /* module loaded by kerneld, auto-cleanable */
695         OPT_v = 0x20, // -v /* verbose output */
696         OPT_q = 0x40, // -q /* silent */
697         OPT_x = 0x80, // -x /* do not export externs */
698         OPT_m = 0x100, // -m /* print module load map */
699 };
700 #define flag_force_load (option_mask32 & OPT_f)
701 #define flag_autoclean (option_mask32 & OPT_k)
702 #define flag_verbose (option_mask32 & OPT_v)
703 #define flag_quiet (option_mask32 & OPT_q)
704 #define flag_noexport (option_mask32 & OPT_x)
705 #if ENABLE_FEATURE_INSMOD_LOAD_MAP
706 #define flag_print_load_map (option_mask32 & OPT_m)
707 #else
708 #define flag_print_load_map 0
709 #endif
710
711 /*======================================================================*/
712
713 #if defined(USE_LIST)
714
715 struct arch_list_entry
716 {
717         struct arch_list_entry *next;
718         LIST_ARCHTYPE addend;
719         int offset;
720         int inited : 1;
721 };
722
723 #endif
724
725 #if defined(USE_SINGLE)
726
727 struct arch_single_entry
728 {
729         int offset;
730         int inited : 1;
731         int allocated : 1;
732 };
733
734 #endif
735
736 #if defined(__mips__)
737 struct mips_hi16
738 {
739         struct mips_hi16 *next;
740         ElfW(Addr) *addr;
741         ElfW(Addr) value;
742 };
743 #endif
744
745 struct arch_file {
746         struct obj_file root;
747 #if defined(USE_PLT_ENTRIES)
748         struct obj_section *plt;
749 #endif
750 #if defined(USE_GOT_ENTRIES)
751         struct obj_section *got;
752 #endif
753 #if defined(__mips__)
754         struct mips_hi16 *mips_hi16_list;
755 #endif
756 };
757
758 struct arch_symbol {
759         struct obj_symbol root;
760 #if defined(USE_PLT_ENTRIES)
761 #if defined(USE_PLT_LIST)
762         struct arch_list_entry *pltent;
763 #else
764         struct arch_single_entry pltent;
765 #endif
766 #endif
767 #if defined(USE_GOT_ENTRIES)
768         struct arch_single_entry gotent;
769 #endif
770 };
771
772
773 struct external_module {
774         const char *name;
775         ElfW(Addr) addr;
776         int used;
777         size_t nsyms;
778         struct new_module_symbol *syms;
779 };
780
781 static struct new_module_symbol *ksyms;
782 static size_t nksyms;
783
784 static struct external_module *ext_modules;
785 static int n_ext_modules;
786 static int n_ext_modules_used;
787
788 static char *m_filename;
789 static char *m_fullName;
790
791
792 /*======================================================================*/
793
794
795 static int check_module_name_match(const char *filename,
796                 struct stat *statbuf ATTRIBUTE_UNUSED,
797                 void *userdata, int depth ATTRIBUTE_UNUSED)
798 {
799         char *fullname = (char *) userdata;
800         char *tmp;
801
802         if (fullname[0] == '\0')
803                 return FALSE;
804
805         tmp = bb_get_last_path_component_nostrip(filename);
806         if (strcmp(tmp, fullname) == 0) {
807                 /* Stop searching if we find a match */
808                 m_filename = xstrdup(filename);
809                 return FALSE;
810         }
811         return TRUE;
812 }
813
814
815 /*======================================================================*/
816
817 static struct obj_file *arch_new_file(void)
818 {
819         struct arch_file *f;
820         f = xzalloc(sizeof(*f));
821         return &f->root; /* it's a first member */
822 }
823
824 static struct obj_section *arch_new_section(void)
825 {
826         return xzalloc(sizeof(struct obj_section));
827 }
828
829 static struct obj_symbol *arch_new_symbol(void)
830 {
831         struct arch_symbol *sym;
832         sym = xzalloc(sizeof(*sym));
833         return &sym->root;
834 }
835
836 static enum obj_reloc
837 arch_apply_relocation(struct obj_file *f,
838                                 struct obj_section *targsec,
839                                 /*struct obj_section *symsec,*/
840                                 struct obj_symbol *sym,
841                                 ElfW(RelM) *rel, ElfW(Addr) v)
842 {
843 #if defined(__arm__) || defined(__i386__) || defined(__mc68000__) \
844  || defined(__sh__) || defined(__s390__)
845         struct arch_file *ifile = (struct arch_file *) f;
846 #endif
847         enum obj_reloc ret = obj_reloc_ok;
848         ElfW(Addr) *loc = (ElfW(Addr) *) (targsec->contents + rel->r_offset);
849 #if defined(__arm__) || defined(__H8300H__) || defined(__H8300S__) \
850  || defined(__i386__) || defined(__mc68000__) || defined(__microblaze__) \
851  || defined(__mips__) || defined(__nios2__) || defined(__powerpc__) \
852  || defined(__s390__) || defined(__sh__) || defined(__x86_64__)
853         ElfW(Addr) dot = targsec->header.sh_addr + rel->r_offset;
854 #endif
855 #if defined(USE_GOT_ENTRIES) || defined(USE_PLT_ENTRIES)
856         struct arch_symbol *isym = (struct arch_symbol *) sym;
857 #endif
858 #if defined(__arm__) || defined(__i386__) || defined(__mc68000__) \
859  || defined(__sh__) || defined(__s390__)
860 #if defined(USE_GOT_ENTRIES)
861         ElfW(Addr) got = ifile->got ? ifile->got->header.sh_addr : 0;
862 #endif
863 #endif
864 #if defined(USE_PLT_ENTRIES)
865         ElfW(Addr) plt = ifile->plt ? ifile->plt->header.sh_addr : 0;
866         unsigned long *ip;
867 # if defined(USE_PLT_LIST)
868         struct arch_list_entry *pe;
869 # else
870         struct arch_single_entry *pe;
871 # endif
872 #endif
873
874         switch (ELF_R_TYPE(rel->r_info)) {
875
876 #if defined(__arm__)
877
878                 case R_ARM_NONE:
879                         break;
880
881                 case R_ARM_ABS32:
882                         *loc += v;
883                         break;
884
885                 case R_ARM_GOT32:
886                         goto bb_use_got;
887
888                 case R_ARM_GOTPC:
889                         /* relative reloc, always to _GLOBAL_OFFSET_TABLE_
890                          * (which is .got) similar to branch,
891                          * but is full 32 bits relative */
892
893                         *loc += got - dot;
894                         break;
895
896                 case R_ARM_PC24:
897                 case R_ARM_PLT32:
898                         goto bb_use_plt;
899
900                 case R_ARM_GOTOFF: /* address relative to the got */
901                         *loc += v - got;
902                         break;
903
904 #elif defined(__cris__)
905
906                 case R_CRIS_NONE:
907                         break;
908
909                 case R_CRIS_32:
910                         /* CRIS keeps the relocation value in the r_addend field and
911                          * should not use whats in *loc at all
912                          */
913                         *loc = v;
914                         break;
915
916 #elif defined(__H8300H__) || defined(__H8300S__)
917
918                 case R_H8_DIR24R8:
919                         loc = (ElfW(Addr) *)((ElfW(Addr))loc - 1);
920                         *loc = (*loc & 0xff000000) | ((*loc & 0xffffff) + v);
921                         break;
922                 case R_H8_DIR24A8:
923                         *loc += v;
924                         break;
925                 case R_H8_DIR32:
926                 case R_H8_DIR32A16:
927                         *loc += v;
928                         break;
929                 case R_H8_PCREL16:
930                         v -= dot + 2;
931                         if ((ElfW(Sword))v > 0x7fff ||
932                             (ElfW(Sword))v < -(ElfW(Sword))0x8000)
933                                 ret = obj_reloc_overflow;
934                         else
935                                 *(unsigned short *)loc = v;
936                         break;
937                 case R_H8_PCREL8:
938                         v -= dot + 1;
939                         if ((ElfW(Sword))v > 0x7f ||
940                             (ElfW(Sword))v < -(ElfW(Sword))0x80)
941                                 ret = obj_reloc_overflow;
942                         else
943                                 *(unsigned char *)loc = v;
944                         break;
945
946 #elif defined(__i386__)
947
948                 case R_386_NONE:
949                         break;
950
951                 case R_386_32:
952                         *loc += v;
953                         break;
954
955                 case R_386_PLT32:
956                 case R_386_PC32:
957                         *loc += v - dot;
958                         break;
959
960                 case R_386_GLOB_DAT:
961                 case R_386_JMP_SLOT:
962                         *loc = v;
963                         break;
964
965                 case R_386_RELATIVE:
966                         *loc += f->baseaddr;
967                         break;
968
969                 case R_386_GOTPC:
970                         *loc += got - dot;
971                         break;
972
973                 case R_386_GOT32:
974                         goto bb_use_got;
975
976                 case R_386_GOTOFF:
977                         *loc += v - got;
978                         break;
979
980 #elif defined(__microblaze__)
981                 case R_MICROBLAZE_NONE:
982                 case R_MICROBLAZE_64_NONE:
983                 case R_MICROBLAZE_32_SYM_OP_SYM:
984                 case R_MICROBLAZE_32_PCREL:
985                         break;
986
987                 case R_MICROBLAZE_64_PCREL: {
988                         /* dot is the address of the current instruction.
989                          * v is the target symbol address.
990                          * So we need to extract the offset in the code,
991                          * adding v, then subtrating the current address
992                          * of this instruction.
993                          * Ex: "IMM 0xFFFE  bralid 0x0000" = "bralid 0xFFFE0000"
994                          */
995
996                         /* Get split offset stored in code */
997                         unsigned int temp = (loc[0] & 0xFFFF) << 16 |
998                                                 (loc[1] & 0xFFFF);
999
1000                         /* Adjust relative offset. -4 adjustment required
1001                          * because dot points to the IMM insn, but branch
1002                          * is computed relative to the branch instruction itself.
1003                          */
1004                         temp += v - dot - 4;
1005
1006                         /* Store back into code */
1007                         loc[0] = (loc[0] & 0xFFFF0000) | temp >> 16;
1008                         loc[1] = (loc[1] & 0xFFFF0000) | (temp & 0xFFFF);
1009
1010                         break;
1011                 }
1012
1013                 case R_MICROBLAZE_32:
1014                         *loc += v;
1015                         break;
1016
1017                 case R_MICROBLAZE_64: {
1018                         /* Get split pointer stored in code */
1019                         unsigned int temp1 = (loc[0] & 0xFFFF) << 16 |
1020                                                 (loc[1] & 0xFFFF);
1021
1022                         /* Add reloc offset */
1023                         temp1+=v;
1024
1025                         /* Store back into code */
1026                         loc[0] = (loc[0] & 0xFFFF0000) | temp1 >> 16;
1027                         loc[1] = (loc[1] & 0xFFFF0000) | (temp1 & 0xFFFF);
1028
1029                         break;
1030                 }
1031
1032                 case R_MICROBLAZE_32_PCREL_LO:
1033                 case R_MICROBLAZE_32_LO:
1034                 case R_MICROBLAZE_SRO32:
1035                 case R_MICROBLAZE_SRW32:
1036                         ret = obj_reloc_unhandled;
1037                         break;
1038
1039 #elif defined(__mc68000__)
1040
1041                 case R_68K_NONE:
1042                         break;
1043
1044                 case R_68K_32:
1045                         *loc += v;
1046                         break;
1047
1048                 case R_68K_8:
1049                         if (v > 0xff) {
1050                                 ret = obj_reloc_overflow;
1051                         }
1052                         *(char *)loc = v;
1053                         break;
1054
1055                 case R_68K_16:
1056                         if (v > 0xffff) {
1057                                 ret = obj_reloc_overflow;
1058                         }
1059                         *(short *)loc = v;
1060                         break;
1061
1062                 case R_68K_PC8:
1063                         v -= dot;
1064                         if ((ElfW(Sword))v > 0x7f ||
1065                                         (ElfW(Sword))v < -(ElfW(Sword))0x80) {
1066                                 ret = obj_reloc_overflow;
1067                         }
1068                         *(char *)loc = v;
1069                         break;
1070
1071                 case R_68K_PC16:
1072                         v -= dot;
1073                         if ((ElfW(Sword))v > 0x7fff ||
1074                                         (ElfW(Sword))v < -(ElfW(Sword))0x8000) {
1075                                 ret = obj_reloc_overflow;
1076                         }
1077                         *(short *)loc = v;
1078                         break;
1079
1080                 case R_68K_PC32:
1081                         *(int *)loc = v - dot;
1082                         break;
1083
1084                 case R_68K_GLOB_DAT:
1085                 case R_68K_JMP_SLOT:
1086                         *loc = v;
1087                         break;
1088
1089                 case R_68K_RELATIVE:
1090                         *(int *)loc += f->baseaddr;
1091                         break;
1092
1093                 case R_68K_GOT32:
1094                         goto bb_use_got;
1095
1096 # ifdef R_68K_GOTOFF
1097                 case R_68K_GOTOFF:
1098                         *loc += v - got;
1099                         break;
1100 # endif
1101
1102 #elif defined(__mips__)
1103
1104                 case R_MIPS_NONE:
1105                         break;
1106
1107                 case R_MIPS_32:
1108                         *loc += v;
1109                         break;
1110
1111                 case R_MIPS_26:
1112                         if (v % 4)
1113                                 ret = obj_reloc_dangerous;
1114                         if ((v & 0xf0000000) != ((dot + 4) & 0xf0000000))
1115                                 ret = obj_reloc_overflow;
1116                         *loc =
1117                                 (*loc & ~0x03ffffff) | ((*loc + (v >> 2)) &
1118                                                                                 0x03ffffff);
1119                         break;
1120
1121                 case R_MIPS_HI16:
1122                         {
1123                                 struct mips_hi16 *n;
1124
1125                                 /* We cannot relocate this one now because we don't know the value
1126                                    of the carry we need to add.  Save the information, and let LO16
1127                                    do the actual relocation.  */
1128                                 n = xmalloc(sizeof *n);
1129                                 n->addr = loc;
1130                                 n->value = v;
1131                                 n->next = ifile->mips_hi16_list;
1132                                 ifile->mips_hi16_list = n;
1133                                 break;
1134                         }
1135
1136                 case R_MIPS_LO16:
1137                         {
1138                                 unsigned long insnlo = *loc;
1139                                 ElfW(Addr) val, vallo;
1140
1141                                 /* Sign extend the addend we extract from the lo insn.  */
1142                                 vallo = ((insnlo & 0xffff) ^ 0x8000) - 0x8000;
1143
1144                                 if (ifile->mips_hi16_list != NULL) {
1145                                         struct mips_hi16 *l;
1146
1147                                         l = ifile->mips_hi16_list;
1148                                         while (l != NULL) {
1149                                                 struct mips_hi16 *next;
1150                                                 unsigned long insn;
1151
1152                                                 /* Do the HI16 relocation.  Note that we actually don't
1153                                                    need to know anything about the LO16 itself, except where
1154                                                    to find the low 16 bits of the addend needed by the LO16.  */
1155                                                 insn = *l->addr;
1156                                                 val =
1157                                                         ((insn & 0xffff) << 16) +
1158                                                         vallo;
1159                                                 val += v;
1160
1161                                                 /* Account for the sign extension that will happen in the
1162                                                    low bits.  */
1163                                                 val =
1164                                                         ((val >> 16) +
1165                                                          ((val & 0x8000) !=
1166                                                           0)) & 0xffff;
1167
1168                                                 insn = (insn & ~0xffff) | val;
1169                                                 *l->addr = insn;
1170
1171                                                 next = l->next;
1172                                                 free(l);
1173                                                 l = next;
1174                                         }
1175
1176                                         ifile->mips_hi16_list = NULL;
1177                                 }
1178
1179                                 /* Ok, we're done with the HI16 relocs.  Now deal with the LO16.  */
1180                                 val = v + vallo;
1181                                 insnlo = (insnlo & ~0xffff) | (val & 0xffff);
1182                                 *loc = insnlo;
1183                                 break;
1184                         }
1185
1186 #elif defined(__nios2__)
1187
1188                 case R_NIOS2_NONE:
1189                         break;
1190
1191                 case R_NIOS2_BFD_RELOC_32:
1192                         *loc += v;
1193                         break;
1194
1195                 case R_NIOS2_BFD_RELOC_16:
1196                         if (v > 0xffff) {
1197                                 ret = obj_reloc_overflow;
1198                         }
1199                         *(short *)loc = v;
1200                         break;
1201
1202                 case R_NIOS2_BFD_RELOC_8:
1203                         if (v > 0xff) {
1204                                 ret = obj_reloc_overflow;
1205                         }
1206                         *(char *)loc = v;
1207                         break;
1208
1209                 case R_NIOS2_S16:
1210                         {
1211                                 Elf32_Addr word;
1212
1213                                 if ((Elf32_Sword)v > 0x7fff ||
1214                                     (Elf32_Sword)v < -(Elf32_Sword)0x8000) {
1215                                         ret = obj_reloc_overflow;
1216                                 }
1217
1218                                 word = *loc;
1219                                 *loc = ((((word >> 22) << 16) | (v & 0xffff)) << 6) |
1220                                        (word & 0x3f);
1221                         }
1222                         break;
1223
1224                 case R_NIOS2_U16:
1225                         {
1226                                 Elf32_Addr word;
1227
1228                                 if (v > 0xffff) {
1229                                         ret = obj_reloc_overflow;
1230                                 }
1231
1232                                 word = *loc;
1233                                 *loc = ((((word >> 22) << 16) | (v & 0xffff)) << 6) |
1234                                        (word & 0x3f);
1235                         }
1236                         break;
1237
1238                 case R_NIOS2_PCREL16:
1239                         {
1240                                 Elf32_Addr word;
1241
1242                                 v -= dot + 4;
1243                                 if ((Elf32_Sword)v > 0x7fff ||
1244                                     (Elf32_Sword)v < -(Elf32_Sword)0x8000) {
1245                                         ret = obj_reloc_overflow;
1246                                 }
1247
1248                                 word = *loc;
1249                                 *loc = ((((word >> 22) << 16) | (v & 0xffff)) << 6) | (word & 0x3f);
1250                         }
1251                         break;
1252
1253                 case R_NIOS2_GPREL:
1254                         {
1255                                 Elf32_Addr word, gp;
1256                                 /* get _gp */
1257                                 gp = obj_symbol_final_value(f, obj_find_symbol(f, SPFX "_gp"));
1258                                 v-=gp;
1259                                 if ((Elf32_Sword)v > 0x7fff ||
1260                                                 (Elf32_Sword)v < -(Elf32_Sword)0x8000) {
1261                                         ret = obj_reloc_overflow;
1262                                 }
1263
1264                                 word = *loc;
1265                                 *loc = ((((word >> 22) << 16) | (v & 0xffff)) << 6) | (word & 0x3f);
1266                         }
1267                         break;
1268
1269                 case R_NIOS2_CALL26:
1270                         if (v & 3)
1271                                 ret = obj_reloc_dangerous;
1272                         if ((v >> 28) != (dot >> 28))
1273                                 ret = obj_reloc_overflow;
1274                         *loc = (*loc & 0x3f) | ((v >> 2) << 6);
1275                         break;
1276
1277                 case R_NIOS2_IMM5:
1278                         {
1279                                 Elf32_Addr word;
1280
1281                                 if (v > 0x1f) {
1282                                         ret = obj_reloc_overflow;
1283                                 }
1284
1285                                 word = *loc & ~0x7c0;
1286                                 *loc = word | ((v & 0x1f) << 6);
1287                         }
1288                         break;
1289
1290                 case R_NIOS2_IMM6:
1291                         {
1292                                 Elf32_Addr word;
1293
1294                                 if (v > 0x3f) {
1295                                         ret = obj_reloc_overflow;
1296                                 }
1297
1298                                 word = *loc & ~0xfc0;
1299                                 *loc = word | ((v & 0x3f) << 6);
1300                         }
1301                         break;
1302
1303                 case R_NIOS2_IMM8:
1304                         {
1305                                 Elf32_Addr word;
1306
1307                                 if (v > 0xff) {
1308                                         ret = obj_reloc_overflow;
1309                                 }
1310
1311                                 word = *loc & ~0x3fc0;
1312                                 *loc = word | ((v & 0xff) << 6);
1313                         }
1314                         break;
1315
1316                 case R_NIOS2_HI16:
1317                         {
1318                                 Elf32_Addr word;
1319
1320                                 word = *loc;
1321                                 *loc = ((((word >> 22) << 16) | ((v >>16) & 0xffff)) << 6) |
1322                                        (word & 0x3f);
1323                         }
1324                         break;
1325
1326                 case R_NIOS2_LO16:
1327                         {
1328                                 Elf32_Addr word;
1329
1330                                 word = *loc;
1331                                 *loc = ((((word >> 22) << 16) | (v & 0xffff)) << 6) |
1332                                        (word & 0x3f);
1333                         }
1334                         break;
1335
1336                 case R_NIOS2_HIADJ16:
1337                         {
1338                                 Elf32_Addr word1, word2;
1339
1340                                 word1 = *loc;
1341                                 word2 = ((v >> 16) + ((v >> 15) & 1)) & 0xffff;
1342                                 *loc = ((((word1 >> 22) << 16) | word2) << 6) |
1343                                        (word1 & 0x3f);
1344                         }
1345                         break;
1346
1347 #elif defined(__powerpc64__)
1348                 /* PPC64 needs a 2.6 kernel, 2.4 module relocation irrelevant */
1349
1350 #elif defined(__powerpc__)
1351
1352                 case R_PPC_ADDR16_HA:
1353                         *(unsigned short *)loc = (v + 0x8000) >> 16;
1354                         break;
1355
1356                 case R_PPC_ADDR16_HI:
1357                         *(unsigned short *)loc = v >> 16;
1358                         break;
1359
1360                 case R_PPC_ADDR16_LO:
1361                         *(unsigned short *)loc = v;
1362                         break;
1363
1364                 case R_PPC_REL24:
1365                         goto bb_use_plt;
1366
1367                 case R_PPC_REL32:
1368                         *loc = v - dot;
1369                         break;
1370
1371                 case R_PPC_ADDR32:
1372                         *loc = v;
1373                         break;
1374
1375 #elif defined(__s390__)
1376
1377                 case R_390_32:
1378                         *(unsigned int *) loc += v;
1379                         break;
1380                 case R_390_16:
1381                         *(unsigned short *) loc += v;
1382                         break;
1383                 case R_390_8:
1384                         *(unsigned char *) loc += v;
1385                         break;
1386
1387                 case R_390_PC32:
1388                         *(unsigned int *) loc += v - dot;
1389                         break;
1390                 case R_390_PC16DBL:
1391                         *(unsigned short *) loc += (v - dot) >> 1;
1392                         break;
1393                 case R_390_PC16:
1394                         *(unsigned short *) loc += v - dot;
1395                         break;
1396
1397                 case R_390_PLT32:
1398                 case R_390_PLT16DBL:
1399                         /* find the plt entry and initialize it.  */
1400                         pe = (struct arch_single_entry *) &isym->pltent;
1401                         if (pe->inited == 0) {
1402                                 ip = (unsigned long *)(ifile->plt->contents + pe->offset);
1403                                 ip[0] = 0x0d105810; /* basr 1,0; lg 1,10(1); br 1 */
1404                                 ip[1] = 0x100607f1;
1405                                 if (ELF_R_TYPE(rel->r_info) == R_390_PLT16DBL)
1406                                         ip[2] = v - 2;
1407                                 else
1408                                         ip[2] = v;
1409                                 pe->inited = 1;
1410                         }
1411
1412                         /* Insert relative distance to target.  */
1413                         v = plt + pe->offset - dot;
1414                         if (ELF_R_TYPE(rel->r_info) == R_390_PLT32)
1415                                 *(unsigned int *) loc = (unsigned int) v;
1416                         else if (ELF_R_TYPE(rel->r_info) == R_390_PLT16DBL)
1417                                 *(unsigned short *) loc = (unsigned short) ((v + 2) >> 1);
1418                         break;
1419
1420                 case R_390_GLOB_DAT:
1421                 case R_390_JMP_SLOT:
1422                         *loc = v;
1423                         break;
1424
1425                 case R_390_RELATIVE:
1426                         *loc += f->baseaddr;
1427                         break;
1428
1429                 case R_390_GOTPC:
1430                         *(unsigned long *) loc += got - dot;
1431                         break;
1432
1433                 case R_390_GOT12:
1434                 case R_390_GOT16:
1435                 case R_390_GOT32:
1436                         if (!isym->gotent.inited)
1437                         {
1438                                 isym->gotent.inited = 1;
1439                                 *(ElfW(Addr) *)(ifile->got->contents + isym->gotent.offset) = v;
1440                         }
1441                         if (ELF_R_TYPE(rel->r_info) == R_390_GOT12)
1442                                 *(unsigned short *) loc |= (*(unsigned short *) loc + isym->gotent.offset) & 0xfff;
1443                         else if (ELF_R_TYPE(rel->r_info) == R_390_GOT16)
1444                                 *(unsigned short *) loc += isym->gotent.offset;
1445                         else if (ELF_R_TYPE(rel->r_info) == R_390_GOT32)
1446                                 *(unsigned int *) loc += isym->gotent.offset;
1447                         break;
1448
1449 # ifndef R_390_GOTOFF32
1450 #  define R_390_GOTOFF32 R_390_GOTOFF
1451 # endif
1452                 case R_390_GOTOFF32:
1453                         *loc += v - got;
1454                         break;
1455
1456 #elif defined(__sh__)
1457
1458                 case R_SH_NONE:
1459                         break;
1460
1461                 case R_SH_DIR32:
1462                         *loc += v;
1463                         break;
1464
1465                 case R_SH_REL32:
1466                         *loc += v - dot;
1467                         break;
1468
1469                 case R_SH_PLT32:
1470                         *loc = v - dot;
1471                         break;
1472
1473                 case R_SH_GLOB_DAT:
1474                 case R_SH_JMP_SLOT:
1475                         *loc = v;
1476                         break;
1477
1478                 case R_SH_RELATIVE:
1479                         *loc = f->baseaddr + rel->r_addend;
1480                         break;
1481
1482                 case R_SH_GOTPC:
1483                         *loc = got - dot + rel->r_addend;
1484                         break;
1485
1486                 case R_SH_GOT32:
1487                         goto bb_use_got;
1488
1489                 case R_SH_GOTOFF:
1490                         *loc = v - got;
1491                         break;
1492
1493 # if defined(__SH5__)
1494                 case R_SH_IMM_MEDLOW16:
1495                 case R_SH_IMM_LOW16:
1496                         {
1497                                 ElfW(Addr) word;
1498
1499                                 if (ELF_R_TYPE(rel->r_info) == R_SH_IMM_MEDLOW16)
1500                                         v >>= 16;
1501
1502                                 /*
1503                                  *  movi and shori have the format:
1504                                  *
1505                                  *  |  op  | imm  | reg | reserved |
1506                                  *   31..26 25..10 9.. 4 3   ..   0
1507                                  *
1508                                  * so we simply mask and or in imm.
1509                                  */
1510                                 word = *loc & ~0x3fffc00;
1511                                 word |= (v & 0xffff) << 10;
1512
1513                                 *loc = word;
1514
1515                                 break;
1516                         }
1517
1518                 case R_SH_IMM_MEDLOW16_PCREL:
1519                 case R_SH_IMM_LOW16_PCREL:
1520                         {
1521                                 ElfW(Addr) word;
1522
1523                                 word = *loc & ~0x3fffc00;
1524
1525                                 v -= dot;
1526
1527                                 if (ELF_R_TYPE(rel->r_info) == R_SH_IMM_MEDLOW16_PCREL)
1528                                         v >>= 16;
1529
1530                                 word |= (v & 0xffff) << 10;
1531
1532                                 *loc = word;
1533
1534                                 break;
1535                         }
1536 # endif /* __SH5__ */
1537
1538 #elif defined(__v850e__)
1539
1540                 case R_V850_NONE:
1541                         break;
1542
1543                 case R_V850_32:
1544                         /* We write two shorts instead of a long because even
1545                            32-bit insns only need half-word alignment, but
1546                            32-bit data needs to be long-word aligned.  */
1547                         v += ((unsigned short *)loc)[0];
1548                         v += ((unsigned short *)loc)[1] << 16;
1549                         ((unsigned short *)loc)[0] = v & 0xffff;
1550                         ((unsigned short *)loc)[1] = (v >> 16) & 0xffff;
1551                         break;
1552
1553                 case R_V850_22_PCREL:
1554                         goto bb_use_plt;
1555
1556 #elif defined(__x86_64__)
1557
1558                 case R_X86_64_NONE:
1559                         break;
1560
1561                 case R_X86_64_64:
1562                         *loc += v;
1563                         break;
1564
1565                 case R_X86_64_32:
1566                         *(unsigned int *) loc += v;
1567                         if (v > 0xffffffff)
1568                         {
1569                                 ret = obj_reloc_overflow; /* Kernel module compiled without -mcmodel=kernel. */
1570                                 /* error("Possibly is module compiled without -mcmodel=kernel!"); */
1571                         }
1572                         break;
1573
1574                 case R_X86_64_32S:
1575                         *(signed int *) loc += v;
1576                         break;
1577
1578                 case R_X86_64_16:
1579                         *(unsigned short *) loc += v;
1580                         break;
1581
1582                 case R_X86_64_8:
1583                         *(unsigned char *) loc += v;
1584                         break;
1585
1586                 case R_X86_64_PC32:
1587                         *(unsigned int *) loc += v - dot;
1588                         break;
1589
1590                 case R_X86_64_PC16:
1591                         *(unsigned short *) loc += v - dot;
1592                         break;
1593
1594                 case R_X86_64_PC8:
1595                         *(unsigned char *) loc += v - dot;
1596                         break;
1597
1598                 case R_X86_64_GLOB_DAT:
1599                 case R_X86_64_JUMP_SLOT:
1600                         *loc = v;
1601                         break;
1602
1603                 case R_X86_64_RELATIVE:
1604                         *loc += f->baseaddr;
1605                         break;
1606
1607                 case R_X86_64_GOT32:
1608                 case R_X86_64_GOTPCREL:
1609                         goto bb_use_got;
1610 # if 0
1611                         if (!isym->gotent.reloc_done)
1612                         {
1613                                 isym->gotent.reloc_done = 1;
1614                                 *(Elf64_Addr *)(ifile->got->contents + isym->gotent.offset) = v;
1615                         }
1616                         /* XXX are these really correct?  */
1617                         if (ELF64_R_TYPE(rel->r_info) == R_X86_64_GOTPCREL)
1618                                 *(unsigned int *) loc += v + isym->gotent.offset;
1619                         else
1620                                 *loc += isym->gotent.offset;
1621                         break;
1622 # endif
1623
1624 #else
1625 # warning "no idea how to handle relocations on your arch"
1626 #endif
1627
1628                 default:
1629                         printf("Warning: unhandled reloc %d\n",(int)ELF_R_TYPE(rel->r_info));
1630                         ret = obj_reloc_unhandled;
1631                         break;
1632
1633 #if defined(USE_PLT_ENTRIES)
1634
1635 bb_use_plt:
1636
1637                         /* find the plt entry and initialize it if necessary */
1638
1639 #if defined(USE_PLT_LIST)
1640                         for (pe = isym->pltent; pe != NULL && pe->addend != rel->r_addend;)
1641                                 pe = pe->next;
1642 #else
1643                         pe = &isym->pltent;
1644 #endif
1645
1646                         if (! pe->inited) {
1647                                 ip = (unsigned long *) (ifile->plt->contents + pe->offset);
1648
1649                                 /* generate some machine code */
1650
1651 #if defined(__arm__)
1652                                 ip[0] = 0xe51ff004;                     /* ldr pc,[pc,#-4] */
1653                                 ip[1] = v;                              /* sym@ */
1654 #endif
1655 #if defined(__powerpc__)
1656                                 ip[0] = 0x3d600000 + ((v + 0x8000) >> 16);  /* lis r11,sym@ha */
1657                                 ip[1] = 0x396b0000 + (v & 0xffff);          /* addi r11,r11,sym@l */
1658                                 ip[2] = 0x7d6903a6;                           /* mtctr r11 */
1659                                 ip[3] = 0x4e800420;                           /* bctr */
1660 #endif
1661 #if defined(__v850e__)
1662                                 /* We have to trash a register, so we assume that any control
1663                                    transfer more than 21-bits away must be a function call
1664                                    (so we can use a call-clobbered register).  */
1665                                 ip[0] = 0x0621 + ((v & 0xffff) << 16);   /* mov sym, r1 ... */
1666                                 ip[1] = ((v >> 16) & 0xffff) + 0x610000; /* ...; jmp r1 */
1667 #endif
1668                                 pe->inited = 1;
1669                         }
1670
1671                         /* relative distance to target */
1672                         v -= dot;
1673                         /* if the target is too far away.... */
1674 #if defined(__arm__) || defined(__powerpc__)
1675                         if ((int)v < -0x02000000 || (int)v >= 0x02000000)
1676 #elif defined(__v850e__)
1677                                 if ((ElfW(Sword))v > 0x1fffff || (ElfW(Sword))v < (ElfW(Sword))-0x200000)
1678 #endif
1679                                         /* go via the plt */
1680                                         v = plt + pe->offset - dot;
1681
1682 #if defined(__v850e__)
1683                         if (v & 1)
1684 #else
1685                                 if (v & 3)
1686 #endif
1687                                         ret = obj_reloc_dangerous;
1688
1689                         /* merge the offset into the instruction. */
1690 #if defined(__arm__)
1691                         /* Convert to words. */
1692                         v >>= 2;
1693
1694                         *loc = (*loc & ~0x00ffffff) | ((v + *loc) & 0x00ffffff);
1695 #endif
1696 #if defined(__powerpc__)
1697                         *loc = (*loc & ~0x03fffffc) | (v & 0x03fffffc);
1698 #endif
1699 #if defined(__v850e__)
1700                         /* We write two shorts instead of a long because even 32-bit insns
1701                            only need half-word alignment, but the 32-bit data write needs
1702                            to be long-word aligned.  */
1703                         ((unsigned short *)loc)[0] =
1704                                 (*(unsigned short *)loc & 0xffc0) /* opcode + reg */
1705                                 | ((v >> 16) & 0x3f);             /* offs high part */
1706                         ((unsigned short *)loc)[1] =
1707                                 (v & 0xffff);                    /* offs low part */
1708 #endif
1709                         break;
1710 #endif /* USE_PLT_ENTRIES */
1711
1712 #if defined(USE_GOT_ENTRIES)
1713 bb_use_got:
1714
1715                         /* needs an entry in the .got: set it, once */
1716                         if (!isym->gotent.inited) {
1717                                 isym->gotent.inited = 1;
1718                                 *(ElfW(Addr) *) (ifile->got->contents + isym->gotent.offset) = v;
1719                         }
1720                         /* make the reloc with_respect_to_.got */
1721 #if defined(__sh__)
1722                         *loc += isym->gotent.offset + rel->r_addend;
1723 #elif defined(__i386__) || defined(__arm__) || defined(__mc68000__)
1724                         *loc += isym->gotent.offset;
1725 #endif
1726                         break;
1727
1728 #endif /* USE_GOT_ENTRIES */
1729         }
1730
1731         return ret;
1732 }
1733
1734
1735 #if defined(USE_LIST)
1736
1737 static int arch_list_add(ElfW(RelM) *rel, struct arch_list_entry **list,
1738                           int offset, int size)
1739 {
1740         struct arch_list_entry *pe;
1741
1742         for (pe = *list; pe != NULL; pe = pe->next) {
1743                 if (pe->addend == rel->r_addend) {
1744                         break;
1745                 }
1746         }
1747
1748         if (pe == NULL) {
1749                 pe = xmalloc(sizeof(struct arch_list_entry));
1750                 pe->next = *list;
1751                 pe->addend = rel->r_addend;
1752                 pe->offset = offset;
1753                 pe->inited = 0;
1754                 *list = pe;
1755                 return size;
1756         }
1757         return 0;
1758 }
1759
1760 #endif
1761
1762 #if defined(USE_SINGLE)
1763
1764 static int arch_single_init(/*ElfW(RelM) *rel,*/ struct arch_single_entry *single,
1765                              int offset, int size)
1766 {
1767         if (single->allocated == 0) {
1768                 single->allocated = 1;
1769                 single->offset = offset;
1770                 single->inited = 0;
1771                 return size;
1772         }
1773         return 0;
1774 }
1775
1776 #endif
1777
1778 #if defined(USE_GOT_ENTRIES) || defined(USE_PLT_ENTRIES)
1779
1780 static struct obj_section *arch_xsect_init(struct obj_file *f, const char *name,
1781                                            int offset, int size)
1782 {
1783         struct obj_section *myrelsec = obj_find_section(f, name);
1784
1785         if (offset == 0) {
1786                 offset += size;
1787         }
1788
1789         if (myrelsec) {
1790                 obj_extend_section(myrelsec, offset);
1791         } else {
1792                 myrelsec = obj_create_alloced_section(f, name,
1793                                 size, offset);
1794         }
1795
1796         return myrelsec;
1797 }
1798
1799 #endif
1800
1801 static void arch_create_got(struct obj_file *f)
1802 {
1803 #if defined(USE_GOT_ENTRIES) || defined(USE_PLT_ENTRIES)
1804         struct arch_file *ifile = (struct arch_file *) f;
1805         int i;
1806 #if defined(USE_GOT_ENTRIES)
1807         int got_offset = 0, got_needed = 0, got_allocate;
1808 #endif
1809 #if defined(USE_PLT_ENTRIES)
1810         int plt_offset = 0, plt_needed = 0, plt_allocate;
1811 #endif
1812         struct obj_section *relsec, *symsec, *strsec;
1813         ElfW(RelM) *rel, *relend;
1814         ElfW(Sym) *symtab, *extsym;
1815         const char *strtab, *name;
1816         struct arch_symbol *intsym;
1817
1818         for (i = 0; i < f->header.e_shnum; ++i) {
1819                 relsec = f->sections[i];
1820                 if (relsec->header.sh_type != SHT_RELM)
1821                         continue;
1822
1823                 symsec = f->sections[relsec->header.sh_link];
1824                 strsec = f->sections[symsec->header.sh_link];
1825
1826                 rel = (ElfW(RelM) *) relsec->contents;
1827                 relend = rel + (relsec->header.sh_size / sizeof(ElfW(RelM)));
1828                 symtab = (ElfW(Sym) *) symsec->contents;
1829                 strtab = (const char *) strsec->contents;
1830
1831                 for (; rel < relend; ++rel) {
1832                         extsym = &symtab[ELF_R_SYM(rel->r_info)];
1833
1834 #if defined(USE_GOT_ENTRIES)
1835                         got_allocate = 0;
1836 #endif
1837 #if defined(USE_PLT_ENTRIES)
1838                         plt_allocate = 0;
1839 #endif
1840
1841                         switch (ELF_R_TYPE(rel->r_info)) {
1842 #if defined(__arm__)
1843                         case R_ARM_PC24:
1844                         case R_ARM_PLT32:
1845                                 plt_allocate = 1;
1846                                 break;
1847
1848                         case R_ARM_GOTOFF:
1849                         case R_ARM_GOTPC:
1850                                 got_needed = 1;
1851                                 continue;
1852
1853                         case R_ARM_GOT32:
1854                                 got_allocate = 1;
1855                                 break;
1856
1857 #elif defined(__i386__)
1858                         case R_386_GOTPC:
1859                         case R_386_GOTOFF:
1860                                 got_needed = 1;
1861                                 continue;
1862
1863                         case R_386_GOT32:
1864                                 got_allocate = 1;
1865                                 break;
1866
1867 #elif defined(__powerpc__)
1868                         case R_PPC_REL24:
1869                                 plt_allocate = 1;
1870                                 break;
1871
1872 #elif defined(__mc68000__)
1873                         case R_68K_GOT32:
1874                                 got_allocate = 1;
1875                                 break;
1876
1877 #ifdef R_68K_GOTOFF
1878                         case R_68K_GOTOFF:
1879                                 got_needed = 1;
1880                                 continue;
1881 #endif
1882
1883 #elif defined(__sh__)
1884                         case R_SH_GOT32:
1885                                 got_allocate = 1;
1886                                 break;
1887
1888                         case R_SH_GOTPC:
1889                         case R_SH_GOTOFF:
1890                                 got_needed = 1;
1891                                 continue;
1892
1893 #elif defined(__v850e__)
1894                         case R_V850_22_PCREL:
1895                                 plt_needed = 1;
1896                                 break;
1897
1898 #endif
1899                         default:
1900                                 continue;
1901                         }
1902
1903                         if (extsym->st_name != 0) {
1904                                 name = strtab + extsym->st_name;
1905                         } else {
1906                                 name = f->sections[extsym->st_shndx]->name;
1907                         }
1908                         intsym = (struct arch_symbol *) obj_find_symbol(f, name);
1909 #if defined(USE_GOT_ENTRIES)
1910                         if (got_allocate) {
1911                                 got_offset += arch_single_init(
1912                                                 /*rel,*/ &intsym->gotent,
1913                                                 got_offset, GOT_ENTRY_SIZE);
1914
1915                                 got_needed = 1;
1916                         }
1917 #endif
1918 #if defined(USE_PLT_ENTRIES)
1919                         if (plt_allocate) {
1920 #if defined(USE_PLT_LIST)
1921                                 plt_offset += arch_list_add(
1922                                                 rel, &intsym->pltent,
1923                                                 plt_offset, PLT_ENTRY_SIZE);
1924 #else
1925                                 plt_offset += arch_single_init(
1926                                                 /*rel,*/ &intsym->pltent,
1927                                                 plt_offset, PLT_ENTRY_SIZE);
1928 #endif
1929                                 plt_needed = 1;
1930                         }
1931 #endif
1932                 }
1933         }
1934
1935 #if defined(USE_GOT_ENTRIES)
1936         if (got_needed) {
1937                 ifile->got = arch_xsect_init(f, ".got", got_offset,
1938                                 GOT_ENTRY_SIZE);
1939         }
1940 #endif
1941
1942 #if defined(USE_PLT_ENTRIES)
1943         if (plt_needed) {
1944                 ifile->plt = arch_xsect_init(f, ".plt", plt_offset,
1945                                 PLT_ENTRY_SIZE);
1946         }
1947 #endif
1948
1949 #endif /* defined(USE_GOT_ENTRIES) || defined(USE_PLT_ENTRIES) */
1950 }
1951
1952 /*======================================================================*/
1953
1954 /* Standard ELF hash function.  */
1955 static unsigned long obj_elf_hash_n(const char *name, unsigned long n)
1956 {
1957         unsigned long h = 0;
1958         unsigned long g;
1959         unsigned char ch;
1960
1961         while (n > 0) {
1962                 ch = *name++;
1963                 h = (h << 4) + ch;
1964                 g = (h & 0xf0000000);
1965                 if (g != 0) {
1966                         h ^= g >> 24;
1967                         h &= ~g;
1968                 }
1969                 n--;
1970         }
1971         return h;
1972 }
1973
1974 static unsigned long obj_elf_hash(const char *name)
1975 {
1976         return obj_elf_hash_n(name, strlen(name));
1977 }
1978
1979 #if ENABLE_FEATURE_INSMOD_VERSION_CHECKING
1980 /* String comparison for non-co-versioned kernel and module.  */
1981
1982 static int ncv_strcmp(const char *a, const char *b)
1983 {
1984         size_t alen = strlen(a), blen = strlen(b);
1985
1986         if (blen == alen + 10 && b[alen] == '_' && b[alen + 1] == 'R')
1987                 return strncmp(a, b, alen);
1988         else if (alen == blen + 10 && a[blen] == '_' && a[blen + 1] == 'R')
1989                 return strncmp(a, b, blen);
1990         else
1991                 return strcmp(a, b);
1992 }
1993
1994 /* String hashing for non-co-versioned kernel and module.  Here
1995    we are simply forced to drop the crc from the hash.  */
1996
1997 static unsigned long ncv_symbol_hash(const char *str)
1998 {
1999         size_t len = strlen(str);
2000         if (len > 10 && str[len - 10] == '_' && str[len - 9] == 'R')
2001                 len -= 10;
2002         return obj_elf_hash_n(str, len);
2003 }
2004
2005 static void
2006 obj_set_symbol_compare(struct obj_file *f,
2007                                            int (*cmp) (const char *, const char *),
2008                                            unsigned long (*hash) (const char *))
2009 {
2010         if (cmp)
2011                 f->symbol_cmp = cmp;
2012         if (hash) {
2013                 struct obj_symbol *tmptab[HASH_BUCKETS], *sym, *next;
2014                 int i;
2015
2016                 f->symbol_hash = hash;
2017
2018                 memcpy(tmptab, f->symtab, sizeof(tmptab));
2019                 memset(f->symtab, 0, sizeof(f->symtab));
2020
2021                 for (i = 0; i < HASH_BUCKETS; ++i)
2022                         for (sym = tmptab[i]; sym; sym = next) {
2023                                 unsigned long h = hash(sym->name) % HASH_BUCKETS;
2024                                 next = sym->next;
2025                                 sym->next = f->symtab[h];
2026                                 f->symtab[h] = sym;
2027                         }
2028         }
2029 }
2030
2031 #endif /* FEATURE_INSMOD_VERSION_CHECKING */
2032
2033 static struct obj_symbol *
2034 obj_add_symbol(struct obj_file *f, const char *name,
2035                                 unsigned long symidx, int info,
2036                                 int secidx, ElfW(Addr) value,
2037                                 unsigned long size)
2038 {
2039         struct obj_symbol *sym;
2040         unsigned long hash = f->symbol_hash(name) % HASH_BUCKETS;
2041         int n_type = ELF_ST_TYPE(info);
2042         int n_binding = ELF_ST_BIND(info);
2043
2044         for (sym = f->symtab[hash]; sym; sym = sym->next)
2045                 if (f->symbol_cmp(sym->name, name) == 0) {
2046                         int o_secidx = sym->secidx;
2047                         int o_info = sym->info;
2048                         int o_type = ELF_ST_TYPE(o_info);
2049                         int o_binding = ELF_ST_BIND(o_info);
2050
2051                         /* A redefinition!  Is it legal?  */
2052
2053                         if (secidx == SHN_UNDEF)
2054                                 return sym;
2055                         else if (o_secidx == SHN_UNDEF)
2056                                 goto found;
2057                         else if (n_binding == STB_GLOBAL && o_binding == STB_LOCAL) {
2058                                 /* Cope with local and global symbols of the same name
2059                                    in the same object file, as might have been created
2060                                    by ld -r.  The only reason locals are now seen at this
2061                                    level at all is so that we can do semi-sensible things
2062                                    with parameters.  */
2063
2064                                 struct obj_symbol *nsym, **p;
2065
2066                                 nsym = arch_new_symbol();
2067                                 nsym->next = sym->next;
2068                                 nsym->ksymidx = -1;
2069
2070                                 /* Excise the old (local) symbol from the hash chain.  */
2071                                 for (p = &f->symtab[hash]; *p != sym; p = &(*p)->next)
2072                                         continue;
2073                                 *p = sym = nsym;
2074                                 goto found;
2075                         } else if (n_binding == STB_LOCAL) {
2076                                 /* Another symbol of the same name has already been defined.
2077                                    Just add this to the local table.  */
2078                                 sym = arch_new_symbol();
2079                                 sym->next = NULL;
2080                                 sym->ksymidx = -1;
2081                                 f->local_symtab[symidx] = sym;
2082                                 goto found;
2083                         } else if (n_binding == STB_WEAK)
2084                                 return sym;
2085                         else if (o_binding == STB_WEAK)
2086                                 goto found;
2087                         /* Don't unify COMMON symbols with object types the programmer
2088                            doesn't expect.  */
2089                         else if (secidx == SHN_COMMON
2090                                         && (o_type == STT_NOTYPE || o_type == STT_OBJECT))
2091                                 return sym;
2092                         else if (o_secidx == SHN_COMMON
2093                                         && (n_type == STT_NOTYPE || n_type == STT_OBJECT))
2094                                 goto found;
2095                         else {
2096                                 /* Don't report an error if the symbol is coming from
2097                                    the kernel or some external module.  */
2098                                 if (secidx <= SHN_HIRESERVE)
2099                                         bb_error_msg("%s multiply defined", name);
2100                                 return sym;
2101                         }
2102                 }
2103
2104         /* Completely new symbol.  */
2105         sym = arch_new_symbol();
2106         sym->next = f->symtab[hash];
2107         f->symtab[hash] = sym;
2108         sym->ksymidx = -1;
2109
2110         if (ELF_ST_BIND(info) == STB_LOCAL && symidx != -1) {
2111                 if (symidx >= f->local_symtab_size)
2112                         bb_error_msg("local symbol %s with index %ld exceeds local_symtab_size %ld",
2113                                         name, (long) symidx, (long) f->local_symtab_size);
2114                 else
2115                         f->local_symtab[symidx] = sym;
2116         }
2117
2118 found:
2119         sym->name = name;
2120         sym->value = value;
2121         sym->size = size;
2122         sym->secidx = secidx;
2123         sym->info = info;
2124
2125         return sym;
2126 }
2127
2128 static struct obj_symbol *
2129 obj_find_symbol(struct obj_file *f, const char *name)
2130 {
2131         struct obj_symbol *sym;
2132         unsigned long hash = f->symbol_hash(name) % HASH_BUCKETS;
2133
2134         for (sym = f->symtab[hash]; sym; sym = sym->next)
2135                 if (f->symbol_cmp(sym->name, name) == 0)
2136                         return sym;
2137
2138         return NULL;
2139 }
2140
2141 static ElfW(Addr) obj_symbol_final_value(struct obj_file * f, struct obj_symbol * sym)
2142 {
2143         if (sym) {
2144                 if (sym->secidx >= SHN_LORESERVE)
2145                         return sym->value;
2146
2147                 return sym->value + f->sections[sym->secidx]->header.sh_addr;
2148         } else {
2149                 /* As a special case, a NULL sym has value zero.  */
2150                 return 0;
2151         }
2152 }
2153
2154 static struct obj_section *obj_find_section(struct obj_file *f, const char *name)
2155 {
2156         int i, n = f->header.e_shnum;
2157
2158         for (i = 0; i < n; ++i)
2159                 if (strcmp(f->sections[i]->name, name) == 0)
2160                         return f->sections[i];
2161
2162         return NULL;
2163 }
2164
2165 static int obj_load_order_prio(struct obj_section *a)
2166 {
2167         unsigned long af, ac;
2168
2169         af = a->header.sh_flags;
2170
2171         ac = 0;
2172         if (a->name[0] != '.' || strlen(a->name) != 10 ||
2173                         strcmp(a->name + 5, ".init"))
2174                 ac |= 32;
2175         if (af & SHF_ALLOC)
2176                 ac |= 16;
2177         if (!(af & SHF_WRITE))
2178                 ac |= 8;
2179         if (af & SHF_EXECINSTR)
2180                 ac |= 4;
2181         if (a->header.sh_type != SHT_NOBITS)
2182                 ac |= 2;
2183
2184         return ac;
2185 }
2186
2187 static void
2188 obj_insert_section_load_order(struct obj_file *f, struct obj_section *sec)
2189 {
2190         struct obj_section **p;
2191         int prio = obj_load_order_prio(sec);
2192         for (p = f->load_order_search_start; *p; p = &(*p)->load_next)
2193                 if (obj_load_order_prio(*p) < prio)
2194                         break;
2195         sec->load_next = *p;
2196         *p = sec;
2197 }
2198
2199 static struct obj_section *obj_create_alloced_section(struct obj_file *f,
2200                                 const char *name,
2201                                 unsigned long align,
2202                                 unsigned long size)
2203 {
2204         int newidx = f->header.e_shnum++;
2205         struct obj_section *sec;
2206
2207         f->sections = xrealloc(f->sections, (newidx + 1) * sizeof(sec));
2208         f->sections[newidx] = sec = arch_new_section();
2209
2210         sec->header.sh_type = SHT_PROGBITS;
2211         sec->header.sh_flags = SHF_WRITE | SHF_ALLOC;
2212         sec->header.sh_size = size;
2213         sec->header.sh_addralign = align;
2214         sec->name = name;
2215         sec->idx = newidx;
2216         if (size)
2217                 sec->contents = xmalloc(size);
2218
2219         obj_insert_section_load_order(f, sec);
2220
2221         return sec;
2222 }
2223
2224 static struct obj_section *obj_create_alloced_section_first(struct obj_file *f,
2225                                 const char *name,
2226                                 unsigned long align,
2227                                 unsigned long size)
2228 {
2229         int newidx = f->header.e_shnum++;
2230         struct obj_section *sec;
2231
2232         f->sections = xrealloc(f->sections, (newidx + 1) * sizeof(sec));
2233         f->sections[newidx] = sec = arch_new_section();
2234
2235         sec->header.sh_type = SHT_PROGBITS;
2236         sec->header.sh_flags = SHF_WRITE | SHF_ALLOC;
2237         sec->header.sh_size = size;
2238         sec->header.sh_addralign = align;
2239         sec->name = name;
2240         sec->idx = newidx;
2241         if (size)
2242                 sec->contents = xmalloc(size);
2243
2244         sec->load_next = f->load_order;
2245         f->load_order = sec;
2246         if (f->load_order_search_start == &f->load_order)
2247                 f->load_order_search_start = &sec->load_next;
2248
2249         return sec;
2250 }
2251
2252 static void *obj_extend_section(struct obj_section *sec, unsigned long more)
2253 {
2254         unsigned long oldsize = sec->header.sh_size;
2255         if (more) {
2256                 sec->contents = xrealloc(sec->contents, sec->header.sh_size += more);
2257         }
2258         return sec->contents + oldsize;
2259 }
2260
2261
2262 /* Conditionally add the symbols from the given symbol set to the
2263    new module.  */
2264
2265 static int
2266 add_symbols_from( struct obj_file *f,
2267                                  int idx, struct new_module_symbol *syms, size_t nsyms)
2268 {
2269         struct new_module_symbol *s;
2270         size_t i;
2271         int used = 0;
2272 #ifdef SYMBOL_PREFIX
2273         char *name_buf = 0;
2274         size_t name_alloced_size = 0;
2275 #endif
2276 #if ENABLE_FEATURE_CHECK_TAINTED_MODULE
2277         int gpl;
2278
2279         gpl = obj_gpl_license(f, NULL) == 0;
2280 #endif
2281         for (i = 0, s = syms; i < nsyms; ++i, ++s) {
2282                 /* Only add symbols that are already marked external.
2283                    If we override locals we may cause problems for
2284                    argument initialization.  We will also create a false
2285                    dependency on the module.  */
2286                 struct obj_symbol *sym;
2287                 char *name;
2288
2289                 /* GPL licensed modules can use symbols exported with
2290                  * EXPORT_SYMBOL_GPL, so ignore any GPLONLY_ prefix on the
2291                  * exported names.  Non-GPL modules never see any GPLONLY_
2292                  * symbols so they cannot fudge it by adding the prefix on
2293                  * their references.
2294                  */
2295                 if (strncmp((char *)s->name, "GPLONLY_", 8) == 0) {
2296 #if ENABLE_FEATURE_CHECK_TAINTED_MODULE
2297                         if (gpl)
2298                                 s->name += 8;
2299                         else
2300 #endif
2301                                 continue;
2302                 }
2303                 name = (char *)s->name;
2304
2305 #ifdef SYMBOL_PREFIX
2306                 /* Prepend SYMBOL_PREFIX to the symbol's name (the
2307                    kernel exports `C names', but module object files
2308                    reference `linker names').  */
2309                 size_t extra = sizeof SYMBOL_PREFIX;
2310                 size_t name_size = strlen(name) + extra;
2311                 if (name_size > name_alloced_size) {
2312                         name_alloced_size = name_size * 2;
2313                         name_buf = alloca(name_alloced_size);
2314                 }
2315                 strcpy(name_buf, SYMBOL_PREFIX);
2316                 strcpy(name_buf + extra - 1, name);
2317                 name = name_buf;
2318 #endif /* SYMBOL_PREFIX */
2319
2320                 sym = obj_find_symbol(f, name);
2321                 if (sym && !(ELF_ST_BIND(sym->info) == STB_LOCAL)) {
2322 #ifdef SYMBOL_PREFIX
2323                         /* Put NAME_BUF into more permanent storage.  */
2324                         name = xmalloc(name_size);
2325                         strcpy(name, name_buf);
2326 #endif
2327                         sym = obj_add_symbol(f, name, -1,
2328                                         ELF_ST_INFO(STB_GLOBAL,
2329                                                 STT_NOTYPE),
2330                                         idx, s->value, 0);
2331                         /* Did our symbol just get installed?  If so, mark the
2332                            module as "used".  */
2333                         if (sym->secidx == idx)
2334                                 used = 1;
2335                 }
2336         }
2337
2338         return used;
2339 }
2340
2341 static void add_kernel_symbols(struct obj_file *f)
2342 {
2343         struct external_module *m;
2344         int i, nused = 0;
2345
2346         /* Add module symbols first.  */
2347
2348         for (i = 0, m = ext_modules; i < n_ext_modules; ++i, ++m) {
2349                 if (m->nsyms
2350                  && add_symbols_from(f, SHN_HIRESERVE + 2 + i, m->syms, m->nsyms)
2351                 ) {
2352                         m->used = 1;
2353                         ++nused;
2354                 }
2355         }
2356
2357         n_ext_modules_used = nused;
2358
2359         /* And finally the symbols from the kernel proper.  */
2360
2361         if (nksyms)
2362                 add_symbols_from(f, SHN_HIRESERVE + 1, ksyms, nksyms);
2363 }
2364
2365 static char *get_modinfo_value(struct obj_file *f, const char *key)
2366 {
2367         struct obj_section *sec;
2368         char *p, *v, *n, *ep;
2369         size_t klen = strlen(key);
2370
2371         sec = obj_find_section(f, ".modinfo");
2372         if (sec == NULL)
2373                 return NULL;
2374         p = sec->contents;
2375         ep = p + sec->header.sh_size;
2376         while (p < ep) {
2377                 v = strchr(p, '=');
2378                 n = strchr(p, '\0');
2379                 if (v) {
2380                         if (p + klen == v && strncmp(p, key, klen) == 0)
2381                                 return v + 1;
2382                 } else {
2383                         if (p + klen == n && strcmp(p, key) == 0)
2384                                 return n;
2385                 }
2386                 p = n + 1;
2387         }
2388
2389         return NULL;
2390 }
2391
2392
2393 /*======================================================================*/
2394 /* Functions relating to module loading after 2.1.18.  */
2395
2396 static void
2397 new_process_module_arguments(struct obj_file *f, int argc, char **argv)
2398 {
2399         while (argc > 0) {
2400                 char *p, *q, *key, *sym_name;
2401                 struct obj_symbol *sym;
2402                 char *contents, *loc;
2403                 int min, max, n;
2404
2405                 p = *argv;
2406                 q = strchr(p, '=');
2407                 if (q == NULL) {
2408                         argc--;
2409                         continue;
2410                 }
2411
2412                 key = alloca(q - p + 6);
2413                 memcpy(key, "parm_", 5);
2414                 memcpy(key + 5, p, q - p);
2415                 key[q - p + 5] = 0;
2416
2417                 p = get_modinfo_value(f, key);
2418                 key += 5;
2419                 if (p == NULL) {
2420                         bb_error_msg_and_die("invalid parameter %s", key);
2421                 }
2422
2423 #ifdef SYMBOL_PREFIX
2424                 sym_name = alloca(strlen(key) + sizeof SYMBOL_PREFIX);
2425                 strcpy(sym_name, SYMBOL_PREFIX);
2426                 strcat(sym_name, key);
2427 #else
2428                 sym_name = key;
2429 #endif
2430                 sym = obj_find_symbol(f, sym_name);
2431
2432                 /* Also check that the parameter was not resolved from the kernel.  */
2433                 if (sym == NULL || sym->secidx > SHN_HIRESERVE) {
2434                         bb_error_msg_and_die("symbol for parameter %s not found", key);
2435                 }
2436
2437                 if (isdigit(*p)) {
2438                         min = strtoul(p, &p, 10);
2439                         if (*p == '-')
2440                                 max = strtoul(p + 1, &p, 10);
2441                         else
2442                                 max = min;
2443                 } else
2444                         min = max = 1;
2445
2446                 contents = f->sections[sym->secidx]->contents;
2447                 loc = contents + sym->value;
2448                 n = (*++q != '\0');
2449
2450                 while (1) {
2451                         if ((*p == 's') || (*p == 'c')) {
2452                                 char *str;
2453
2454                                 /* Do C quoting if we begin with a ", else slurp the lot.  */
2455                                 if (*q == '"') {
2456                                         char *r;
2457
2458                                         str = alloca(strlen(q));
2459                                         for (r = str, q++; *q != '"'; ++q, ++r) {
2460                                                 if (*q == '\0')
2461                                                         bb_error_msg_and_die("improperly terminated string argument for %s",
2462                                                                         key);
2463                                                 if (*q == '\\')
2464                                                         switch (*++q) {
2465                                                         case 'a':
2466                                                                 *r = '\a';
2467                                                                 break;
2468                                                         case 'b':
2469                                                                 *r = '\b';
2470                                                                 break;
2471                                                         case 'e':
2472                                                                 *r = '\033';
2473                                                                 break;
2474                                                         case 'f':
2475                                                                 *r = '\f';
2476                                                                 break;
2477                                                         case 'n':
2478                                                                 *r = '\n';
2479                                                                 break;
2480                                                         case 'r':
2481                                                                 *r = '\r';
2482                                                                 break;
2483                                                         case 't':
2484                                                                 *r = '\t';
2485                                                                 break;
2486
2487                                                         case '0':
2488                                                         case '1':
2489                                                         case '2':
2490                                                         case '3':
2491                                                         case '4':
2492                                                         case '5':
2493                                                         case '6':
2494                                                         case '7':
2495                                                                 {
2496                                                                         int c = *q - '0';
2497                                                                         if (q[1] >= '0' && q[1] <= '7') {
2498                                                                                 c = (c * 8) + *++q - '0';
2499                                                                                 if (q[1] >= '0' && q[1] <= '7')
2500                                                                                         c = (c * 8) + *++q - '0';
2501                                                                         }
2502                                                                         *r = c;
2503                                                                 }
2504                                                                 break;
2505
2506                                                         default:
2507                                                                 *r = *q;
2508                                                                 break;
2509                                                         }
2510                                                 else
2511                                                         *r = *q;
2512                                         }
2513                                         *r = '\0';
2514                                         ++q;
2515                                 } else {
2516                                         char *r;
2517
2518                                         /* In this case, the string is not quoted. We will break
2519                                            it using the coma (like for ints). If the user wants to
2520                                            include comas in a string, he just has to quote it */
2521
2522                                         /* Search the next coma */
2523                                         r = strchr(q, ',');
2524
2525                                         /* Found ? */
2526                                         if (r != (char *) NULL) {
2527                                                 /* Recopy the current field */
2528                                                 str = alloca(r - q + 1);
2529                                                 memcpy(str, q, r - q);
2530
2531                                                 /* I don't know if it is useful, as the previous case
2532                                                    doesn't nul terminate the string ??? */
2533                                                 str[r - q] = '\0';
2534
2535                                                 /* Keep next fields */
2536                                                 q = r;
2537                                         } else {
2538                                                 /* last string */
2539                                                 str = q;
2540                                                 q = (char*)"";
2541                                         }
2542                                 }
2543
2544                                 if (*p == 's') {
2545                                         /* Normal string */
2546                                         obj_string_patch(f, sym->secidx, loc - contents, str);
2547                                         loc += tgt_sizeof_char_p;
2548                                 } else {
2549                                         /* Array of chars (in fact, matrix!) */
2550                                         unsigned long charssize;        /* size of each member */
2551
2552                                         /* Get the size of each member */
2553                                         /* Probably we should do that outside the loop ? */
2554                                         if (!isdigit(*(p + 1))) {
2555                                                 bb_error_msg_and_die("parameter type 'c' for %s must be followed by"
2556                                                                 " the maximum size", key);
2557                                         }
2558                                         charssize = strtoul(p + 1, (char **) NULL, 10);
2559
2560                                         /* Check length */
2561                                         if (strlen(str) >= charssize) {
2562                                                 bb_error_msg_and_die("string too long for %s (max %ld)", key,
2563                                                                 charssize - 1);
2564                                         }
2565
2566                                         /* Copy to location */
2567                                         strcpy((char *) loc, str);
2568                                         loc += charssize;
2569                                 }
2570                         } else {
2571                                 long v = strtoul(q, &q, 0);
2572                                 switch (*p) {
2573                                 case 'b':
2574                                         *loc++ = v;
2575                                         break;
2576                                 case 'h':
2577                                         *(short *) loc = v;
2578                                         loc += tgt_sizeof_short;
2579                                         break;
2580                                 case 'i':
2581                                         *(int *) loc = v;
2582                                         loc += tgt_sizeof_int;
2583                                         break;
2584                                 case 'l':
2585                                         *(long *) loc = v;
2586                                         loc += tgt_sizeof_long;
2587                                         break;
2588
2589                                 default:
2590                                         bb_error_msg_and_die("unknown parameter type '%c' for %s", *p, key);
2591                                 }
2592                         }
2593  retry_end_of_value:
2594                         switch (*q) {
2595                         case '\0':
2596                                 goto end_of_arg;
2597
2598                         case ' ':
2599                         case '\t':
2600                         case '\n':
2601                         case '\r':
2602                                 ++q;
2603                                 goto retry_end_of_value;
2604
2605                         case ',':
2606                                 if (++n > max) {
2607                                         bb_error_msg_and_die("too many values for %s (max %d)", key, max);
2608                                 }
2609                                 ++q;
2610                                 break;
2611
2612                         default:
2613                                 bb_error_msg_and_die("invalid argument syntax for %s", key);
2614                         }
2615                 }
2616  end_of_arg:
2617                 if (n < min) {
2618                         bb_error_msg_and_die("too few values for %s (min %d)", key, min);
2619                 }
2620
2621                 argc--;
2622                 argv++;
2623         }
2624 }
2625
2626 #if ENABLE_FEATURE_INSMOD_VERSION_CHECKING
2627 static int new_is_module_checksummed(struct obj_file *f)
2628 {
2629         const char *p = get_modinfo_value(f, "using_checksums");
2630         if (p)
2631                 return xatoi(p);
2632         return 0;
2633 }
2634
2635 /* Get the module's kernel version in the canonical integer form.  */
2636
2637 static int
2638 new_get_module_version(struct obj_file *f, char str[STRVERSIONLEN])
2639 {
2640         char *p, *q;
2641         int a, b, c;
2642
2643         p = get_modinfo_value(f, "kernel_version");
2644         if (p == NULL)
2645                 return -1;
2646         safe_strncpy(str, p, STRVERSIONLEN);
2647
2648         a = strtoul(p, &p, 10);
2649         if (*p != '.')
2650                 return -1;
2651         b = strtoul(p + 1, &p, 10);
2652         if (*p != '.')
2653                 return -1;
2654         c = strtoul(p + 1, &q, 10);
2655         if (p + 1 == q)
2656                 return -1;
2657
2658         return a << 16 | b << 8 | c;
2659 }
2660
2661 #endif   /* FEATURE_INSMOD_VERSION_CHECKING */
2662
2663
2664 /* Fetch the loaded modules, and all currently exported symbols.  */
2665
2666 static void new_get_kernel_symbols(void)
2667 {
2668         char *module_names, *mn;
2669         struct external_module *modules, *m;
2670         struct new_module_symbol *syms, *s;
2671         size_t ret, bufsize, nmod, nsyms, i, j;
2672
2673         /* Collect the loaded modules.  */
2674
2675         bufsize = 256;
2676         module_names = xmalloc(bufsize);
2677
2678  retry_modules_load:
2679         if (query_module(NULL, QM_MODULES, module_names, bufsize, &ret)) {
2680                 if (errno == ENOSPC && bufsize < ret) {
2681                         bufsize = ret;
2682                         module_names = xrealloc(module_names, bufsize);
2683                         goto retry_modules_load;
2684                 }
2685                 bb_perror_msg_and_die("QM_MODULES");
2686         }
2687
2688         n_ext_modules = nmod = ret;
2689
2690         /* Collect the modules' symbols.  */
2691
2692         if (nmod) {
2693                 ext_modules = modules = xmalloc(nmod * sizeof(*modules));
2694                 memset(modules, 0, nmod * sizeof(*modules));
2695                 for (i = 0, mn = module_names, m = modules;
2696                                 i < nmod; ++i, ++m, mn += strlen(mn) + 1) {
2697                         struct new_module_info info;
2698
2699                         if (query_module(mn, QM_INFO, &info, sizeof(info), &ret)) {
2700                                 if (errno == ENOENT) {
2701                                         /* The module was removed out from underneath us.  */
2702                                         continue;
2703                                 }
2704                                 bb_perror_msg_and_die("query_module: QM_INFO: %s", mn);
2705                         }
2706
2707                         bufsize = 1024;
2708                         syms = xmalloc(bufsize);
2709  retry_mod_sym_load:
2710                         if (query_module(mn, QM_SYMBOLS, syms, bufsize, &ret)) {
2711                                 switch (errno) {
2712                                         case ENOSPC:
2713                                                 bufsize = ret;
2714                                                 syms = xrealloc(syms, bufsize);
2715                                                 goto retry_mod_sym_load;
2716                                         case ENOENT:
2717                                                 /* The module was removed out from underneath us.  */
2718                                                 continue;
2719                                         default:
2720                                                 bb_perror_msg_and_die("query_module: QM_SYMBOLS: %s", mn);
2721                                 }
2722                         }
2723                         nsyms = ret;
2724
2725                         m->name = mn;
2726                         m->addr = info.addr;
2727                         m->nsyms = nsyms;
2728                         m->syms = syms;
2729
2730                         for (j = 0, s = syms; j < nsyms; ++j, ++s) {
2731                                 s->name += (unsigned long) syms;
2732                         }
2733                 }
2734         }
2735
2736         /* Collect the kernel's symbols.  */
2737
2738         syms = xmalloc(bufsize = 16 * 1024);
2739  retry_kern_sym_load:
2740         if (query_module(NULL, QM_SYMBOLS, syms, bufsize, &ret)) {
2741                 if (errno == ENOSPC && bufsize < ret) {
2742                         syms = xrealloc(syms, bufsize = ret);
2743                         goto retry_kern_sym_load;
2744                 }
2745                 bb_perror_msg_and_die("kernel: QM_SYMBOLS");
2746         }
2747         nksyms = nsyms = ret;
2748         ksyms = syms;
2749
2750         for (j = 0, s = syms; j < nsyms; ++j, ++s) {
2751                 s->name += (unsigned long) syms;
2752         }
2753 }
2754
2755
2756 /* Return the kernel symbol checksum version, or zero if not used.  */
2757
2758 static int new_is_kernel_checksummed(void)
2759 {
2760         struct new_module_symbol *s;
2761         size_t i;
2762
2763         /* Using_Versions is not the first symbol, but it should be in there.  */
2764
2765         for (i = 0, s = ksyms; i < nksyms; ++i, ++s)
2766                 if (strcmp((char *) s->name, "Using_Versions") == 0)
2767                         return s->value;
2768
2769         return 0;
2770 }
2771
2772
2773 static void  new_create_this_module(struct obj_file *f, const char *m_name)
2774 {
2775         struct obj_section *sec;
2776
2777         sec = obj_create_alloced_section_first(f, ".this", tgt_sizeof_long,
2778                         sizeof(struct new_module));
2779         memset(sec->contents, 0, sizeof(struct new_module));
2780
2781         obj_add_symbol(f, SPFX "__this_module", -1,
2782                         ELF_ST_INFO(STB_LOCAL, STT_OBJECT), sec->idx, 0,
2783                         sizeof(struct new_module));
2784
2785         obj_string_patch(f, sec->idx, offsetof(struct new_module, name),
2786                         m_name);
2787 }
2788
2789 #if ENABLE_FEATURE_INSMOD_KSYMOOPS_SYMBOLS
2790 /* add an entry to the __ksymtab section, creating it if necessary */
2791 static void new_add_ksymtab(struct obj_file *f, struct obj_symbol *sym)
2792 {
2793         struct obj_section *sec;
2794         ElfW(Addr) ofs;
2795
2796         /* ensure __ksymtab is allocated, EXPORT_NOSYMBOLS creates a non-alloc section.
2797          * If __ksymtab is defined but not marked alloc, x out the first character
2798          * (no obj_delete routine) and create a new __ksymtab with the correct
2799          * characteristics.
2800          */
2801         sec = obj_find_section(f, "__ksymtab");
2802         if (sec && !(sec->header.sh_flags & SHF_ALLOC)) {
2803                 *((char *)(sec->name)) = 'x';   /* override const */
2804                 sec = NULL;
2805         }
2806         if (!sec)
2807                 sec = obj_create_alloced_section(f, "__ksymtab",
2808                                 tgt_sizeof_void_p, 0);
2809         if (!sec)
2810                 return;
2811         sec->header.sh_flags |= SHF_ALLOC;
2812         /* Empty section might be byte-aligned */
2813         sec->header.sh_addralign = tgt_sizeof_void_p;
2814         ofs = sec->header.sh_size;
2815         obj_symbol_patch(f, sec->idx, ofs, sym);
2816         obj_string_patch(f, sec->idx, ofs + tgt_sizeof_void_p, sym->name);
2817         obj_extend_section(sec, 2 * tgt_sizeof_char_p);
2818 }
2819 #endif /* FEATURE_INSMOD_KSYMOOPS_SYMBOLS */
2820
2821 static int new_create_module_ksymtab(struct obj_file *f)
2822 {
2823         struct obj_section *sec;
2824         int i;
2825
2826         /* We must always add the module references.  */
2827
2828         if (n_ext_modules_used) {
2829                 struct new_module_ref *dep;
2830                 struct obj_symbol *tm;
2831
2832                 sec = obj_create_alloced_section(f, ".kmodtab", tgt_sizeof_void_p,
2833                                 (sizeof(struct new_module_ref)
2834                                  * n_ext_modules_used));
2835                 if (!sec)
2836                         return 0;
2837
2838                 tm = obj_find_symbol(f, SPFX "__this_module");
2839                 dep = (struct new_module_ref *) sec->contents;
2840                 for (i = 0; i < n_ext_modules; ++i)
2841                         if (ext_modules[i].used) {
2842                                 dep->dep = ext_modules[i].addr;
2843                                 obj_symbol_patch(f, sec->idx,
2844                                                 (char *) &dep->ref - sec->contents, tm);
2845                                 dep->next_ref = 0;
2846                                 ++dep;
2847                         }
2848         }
2849
2850         if (!flag_noexport && !obj_find_section(f, "__ksymtab")) {
2851                 size_t nsyms;
2852                 int *loaded;
2853
2854                 sec = obj_create_alloced_section(f, "__ksymtab", tgt_sizeof_void_p, 0);
2855
2856                 /* We don't want to export symbols residing in sections that
2857                    aren't loaded.  There are a number of these created so that
2858                    we make sure certain module options don't appear twice.  */
2859
2860                 loaded = alloca(sizeof(int) * (i = f->header.e_shnum));
2861                 while (--i >= 0)
2862                         loaded[i] = (f->sections[i]->header.sh_flags & SHF_ALLOC) != 0;
2863
2864                 for (nsyms = i = 0; i < HASH_BUCKETS; ++i) {
2865                         struct obj_symbol *sym;
2866                         for (sym = f->symtab[i]; sym; sym = sym->next)
2867                                 if (ELF_ST_BIND(sym->info) != STB_LOCAL
2868                                                 && sym->secidx <= SHN_HIRESERVE
2869                                                 && (sym->secidx >= SHN_LORESERVE
2870                                                         || loaded[sym->secidx])) {
2871                                         ElfW(Addr) ofs = nsyms * 2 * tgt_sizeof_void_p;
2872
2873                                         obj_symbol_patch(f, sec->idx, ofs, sym);
2874                                         obj_string_patch(f, sec->idx, ofs + tgt_sizeof_void_p,
2875                                                         sym->name);
2876
2877                                         nsyms++;
2878                                 }
2879                 }
2880
2881                 obj_extend_section(sec, nsyms * 2 * tgt_sizeof_char_p);
2882         }
2883
2884         return 1;
2885 }
2886
2887
2888 static int
2889 new_init_module(const char *m_name, struct obj_file *f, unsigned long m_size)
2890 {
2891         struct new_module *module;
2892         struct obj_section *sec;
2893         void *image;
2894         int ret;
2895         tgt_long m_addr;
2896
2897         sec = obj_find_section(f, ".this");
2898         if (!sec || !sec->contents) {
2899                 bb_perror_msg_and_die("corrupt module %s?",m_name);
2900         }
2901         module = (struct new_module *) sec->contents;
2902         m_addr = sec->header.sh_addr;
2903
2904         module->size_of_struct = sizeof(*module);
2905         module->size = m_size;
2906         module->flags = flag_autoclean ? NEW_MOD_AUTOCLEAN : 0;
2907
2908         sec = obj_find_section(f, "__ksymtab");
2909         if (sec && sec->header.sh_size) {
2910                 module->syms = sec->header.sh_addr;
2911                 module->nsyms = sec->header.sh_size / (2 * tgt_sizeof_char_p);
2912         }
2913
2914         if (n_ext_modules_used) {
2915                 sec = obj_find_section(f, ".kmodtab");
2916                 module->deps = sec->header.sh_addr;
2917                 module->ndeps = n_ext_modules_used;
2918         }
2919
2920         module->init =
2921                 obj_symbol_final_value(f, obj_find_symbol(f, SPFX "init_module"));
2922         module->cleanup =
2923                 obj_symbol_final_value(f, obj_find_symbol(f, SPFX "cleanup_module"));
2924
2925         sec = obj_find_section(f, "__ex_table");
2926         if (sec) {
2927                 module->ex_table_start = sec->header.sh_addr;
2928                 module->ex_table_end = sec->header.sh_addr + sec->header.sh_size;
2929         }
2930
2931         sec = obj_find_section(f, ".text.init");
2932         if (sec) {
2933                 module->runsize = sec->header.sh_addr - m_addr;
2934         }
2935         sec = obj_find_section(f, ".data.init");
2936         if (sec) {
2937                 if (!module->runsize ||
2938                                 module->runsize > sec->header.sh_addr - m_addr)
2939                         module->runsize = sec->header.sh_addr - m_addr;
2940         }
2941         sec = obj_find_section(f, ARCHDATA_SEC_NAME);
2942         if (sec && sec->header.sh_size) {
2943                 module->archdata_start = (void*)sec->header.sh_addr;
2944                 module->archdata_end = module->archdata_start + sec->header.sh_size;
2945         }
2946         sec = obj_find_section(f, KALLSYMS_SEC_NAME);
2947         if (sec && sec->header.sh_size) {
2948                 module->kallsyms_start = (void*)sec->header.sh_addr;
2949                 module->kallsyms_end = module->kallsyms_start + sec->header.sh_size;
2950         }
2951
2952         /* Whew!  All of the initialization is complete.  Collect the final
2953            module image and give it to the kernel.  */
2954
2955         image = xmalloc(m_size);
2956         obj_create_image(f, image);
2957
2958         ret = init_module(m_name, (struct new_module *) image);
2959         if (ret)
2960                 bb_perror_msg("init_module: %s", m_name);
2961
2962         free(image);
2963
2964         return ret == 0;
2965 }
2966
2967
2968 /*======================================================================*/
2969
2970 static void
2971 obj_string_patch(struct obj_file *f, int secidx, ElfW(Addr) offset,
2972                                  const char *string)
2973 {
2974         struct obj_string_patch *p;
2975         struct obj_section *strsec;
2976         size_t len = strlen(string) + 1;
2977         char *loc;
2978
2979         p = xmalloc(sizeof(*p));
2980         p->next = f->string_patches;
2981         p->reloc_secidx = secidx;
2982         p->reloc_offset = offset;
2983         f->string_patches = p;
2984
2985         strsec = obj_find_section(f, ".kstrtab");
2986         if (strsec == NULL) {
2987                 strsec = obj_create_alloced_section(f, ".kstrtab", 1, len);
2988                 p->string_offset = 0;
2989                 loc = strsec->contents;
2990         } else {
2991                 p->string_offset = strsec->header.sh_size;
2992                 loc = obj_extend_section(strsec, len);
2993         }
2994         memcpy(loc, string, len);
2995 }
2996
2997 static void
2998 obj_symbol_patch(struct obj_file *f, int secidx, ElfW(Addr) offset,
2999                                  struct obj_symbol *sym)
3000 {
3001         struct obj_symbol_patch *p;
3002
3003         p = xmalloc(sizeof(*p));
3004         p->next = f->symbol_patches;
3005         p->reloc_secidx = secidx;
3006         p->reloc_offset = offset;
3007         p->sym = sym;
3008         f->symbol_patches = p;
3009 }
3010
3011 static void obj_check_undefineds(struct obj_file *f)
3012 {
3013         unsigned i;
3014
3015         for (i = 0; i < HASH_BUCKETS; ++i) {
3016                 struct obj_symbol *sym;
3017                 for (sym = f->symtab[i]; sym; sym = sym->next)
3018                         if (sym->secidx == SHN_UNDEF) {
3019                                 if (ELF_ST_BIND(sym->info) == STB_WEAK) {
3020                                         sym->secidx = SHN_ABS;
3021                                         sym->value = 0;
3022                                 } else {
3023                                         if (!flag_quiet)
3024                                                 bb_error_msg_and_die("unresolved symbol %s", sym->name);
3025                                 }
3026                         }
3027         }
3028 }
3029
3030 static void obj_allocate_commons(struct obj_file *f)
3031 {
3032         struct common_entry {
3033                 struct common_entry *next;
3034                 struct obj_symbol *sym;
3035         } *common_head = NULL;
3036
3037         unsigned long i;
3038
3039         for (i = 0; i < HASH_BUCKETS; ++i) {
3040                 struct obj_symbol *sym;
3041                 for (sym = f->symtab[i]; sym; sym = sym->next)
3042                         if (sym->secidx == SHN_COMMON) {
3043                                 /* Collect all COMMON symbols and sort them by size so as to
3044                                    minimize space wasted by alignment requirements.  */
3045                                 {
3046                                         struct common_entry **p, *n;
3047                                         for (p = &common_head; *p; p = &(*p)->next)
3048                                                 if (sym->size <= (*p)->sym->size)
3049                                                         break;
3050
3051                                         n = alloca(sizeof(*n));
3052                                         n->next = *p;
3053                                         n->sym = sym;
3054                                         *p = n;
3055                                 }
3056                         }
3057         }
3058
3059         for (i = 1; i < f->local_symtab_size; ++i) {
3060                 struct obj_symbol *sym = f->local_symtab[i];
3061                 if (sym && sym->secidx == SHN_COMMON) {
3062                         struct common_entry **p, *n;
3063                         for (p = &common_head; *p; p = &(*p)->next)
3064                                 if (sym == (*p)->sym)
3065                                         break;
3066                                 else if (sym->size < (*p)->sym->size) {
3067                                         n = alloca(sizeof(*n));
3068                                         n->next = *p;
3069                                         n->sym = sym;
3070                                         *p = n;
3071                                         break;
3072                                 }
3073                 }
3074         }
3075
3076         if (common_head) {
3077                 /* Find the bss section.  */
3078                 for (i = 0; i < f->header.e_shnum; ++i)
3079                         if (f->sections[i]->header.sh_type == SHT_NOBITS)
3080                                 break;
3081
3082                 /* If for some reason there hadn't been one, create one.  */
3083                 if (i == f->header.e_shnum) {
3084                         struct obj_section *sec;
3085
3086                         f->sections = xrealloc(f->sections, (i + 1) * sizeof(sec));
3087                         f->sections[i] = sec = arch_new_section();
3088                         f->header.e_shnum = i + 1;
3089
3090                         sec->header.sh_type = SHT_PROGBITS;
3091                         sec->header.sh_flags = SHF_WRITE | SHF_ALLOC;
3092                         sec->name = ".bss";
3093                         sec->idx = i;
3094                 }
3095
3096                 /* Allocate the COMMONS.  */
3097                 {
3098                         ElfW(Addr) bss_size = f->sections[i]->header.sh_size;
3099                         ElfW(Addr) max_align = f->sections[i]->header.sh_addralign;
3100                         struct common_entry *c;
3101
3102                         for (c = common_head; c; c = c->next) {
3103                                 ElfW(Addr) align = c->sym->value;
3104
3105                                 if (align > max_align)
3106                                         max_align = align;
3107                                 if (bss_size & (align - 1))
3108                                         bss_size = (bss_size | (align - 1)) + 1;
3109
3110                                 c->sym->secidx = i;
3111                                 c->sym->value = bss_size;
3112
3113                                 bss_size += c->sym->size;
3114                         }
3115
3116                         f->sections[i]->header.sh_size = bss_size;
3117                         f->sections[i]->header.sh_addralign = max_align;
3118                 }
3119         }
3120
3121         /* For the sake of patch relocation and parameter initialization,
3122            allocate zeroed data for NOBITS sections now.  Note that after
3123            this we cannot assume NOBITS are really empty.  */
3124         for (i = 0; i < f->header.e_shnum; ++i) {
3125                 struct obj_section *s = f->sections[i];
3126                 if (s->header.sh_type == SHT_NOBITS) {
3127                         if (s->header.sh_size != 0)
3128                                 s->contents = memset(xmalloc(s->header.sh_size),
3129                                                 0, s->header.sh_size);
3130                         else
3131                                 s->contents = NULL;
3132
3133                         s->header.sh_type = SHT_PROGBITS;
3134                 }
3135         }
3136 }
3137
3138 static unsigned long obj_load_size(struct obj_file *f)
3139 {
3140         unsigned long dot = 0;
3141         struct obj_section *sec;
3142
3143         /* Finalize the positions of the sections relative to one another.  */
3144
3145         for (sec = f->load_order; sec; sec = sec->load_next) {
3146                 ElfW(Addr) align;
3147
3148                 align = sec->header.sh_addralign;
3149                 if (align && (dot & (align - 1)))
3150                         dot = (dot | (align - 1)) + 1;
3151
3152                 sec->header.sh_addr = dot;
3153                 dot += sec->header.sh_size;
3154         }
3155
3156         return dot;
3157 }
3158
3159 static int obj_relocate(struct obj_file *f, ElfW(Addr) base)
3160 {
3161         int i, n = f->header.e_shnum;
3162         int ret = 1;
3163
3164         /* Finalize the addresses of the sections.  */
3165
3166         f->baseaddr = base;
3167         for (i = 0; i < n; ++i)
3168                 f->sections[i]->header.sh_addr += base;
3169
3170         /* And iterate over all of the relocations.  */
3171
3172         for (i = 0; i < n; ++i) {
3173                 struct obj_section *relsec, *symsec, *targsec, *strsec;
3174                 ElfW(RelM) * rel, *relend;
3175                 ElfW(Sym) * symtab;
3176                 const char *strtab;
3177
3178                 relsec = f->sections[i];
3179                 if (relsec->header.sh_type != SHT_RELM)
3180                         continue;
3181
3182                 symsec = f->sections[relsec->header.sh_link];
3183                 targsec = f->sections[relsec->header.sh_info];
3184                 strsec = f->sections[symsec->header.sh_link];
3185
3186                 rel = (ElfW(RelM) *) relsec->contents;
3187                 relend = rel + (relsec->header.sh_size / sizeof(ElfW(RelM)));
3188                 symtab = (ElfW(Sym) *) symsec->contents;
3189                 strtab = (const char *) strsec->contents;
3190
3191                 for (; rel < relend; ++rel) {
3192                         ElfW(Addr) value = 0;
3193                         struct obj_symbol *intsym = NULL;
3194                         unsigned long symndx;
3195                         ElfW(Sym) * extsym = 0;
3196                         const char *errmsg;
3197
3198                         /* Attempt to find a value to use for this relocation.  */
3199
3200                         symndx = ELF_R_SYM(rel->r_info);
3201                         if (symndx) {
3202                                 /* Note we've already checked for undefined symbols.  */
3203
3204                                 extsym = &symtab[symndx];
3205                                 if (ELF_ST_BIND(extsym->st_info) == STB_LOCAL) {
3206                                         /* Local symbols we look up in the local table to be sure
3207                                            we get the one that is really intended.  */
3208                                         intsym = f->local_symtab[symndx];
3209                                 } else {
3210                                         /* Others we look up in the hash table.  */
3211                                         const char *name;
3212                                         if (extsym->st_name)
3213                                                 name = strtab + extsym->st_name;
3214                                         else
3215                                                 name = f->sections[extsym->st_shndx]->name;
3216                                         intsym = obj_find_symbol(f, name);
3217                                 }
3218
3219                                 value = obj_symbol_final_value(f, intsym);
3220                                 intsym->referenced = 1;
3221                         }
3222 #if SHT_RELM == SHT_RELA
3223 #if defined(__alpha__) && defined(AXP_BROKEN_GAS)
3224                         /* Work around a nasty GAS bug, that is fixed as of 2.7.0.9.  */
3225                         if (!extsym || !extsym->st_name ||
3226                                         ELF_ST_BIND(extsym->st_info) != STB_LOCAL)
3227 #endif
3228                                 value += rel->r_addend;
3229 #endif
3230
3231                         /* Do it! */
3232                         switch (arch_apply_relocation
3233                                         (f, targsec, /*symsec,*/ intsym, rel, value)
3234                         ) {
3235                         case obj_reloc_ok:
3236                                 break;
3237
3238                         case obj_reloc_overflow:
3239                                 errmsg = "Relocation overflow";
3240                                 goto bad_reloc;
3241                         case obj_reloc_dangerous:
3242                                 errmsg = "Dangerous relocation";
3243                                 goto bad_reloc;
3244                         case obj_reloc_unhandled:
3245                                 errmsg = "Unhandled relocation";
3246 bad_reloc:
3247                                 if (extsym) {
3248                                         bb_error_msg("%s of type %ld for %s", errmsg,
3249                                                         (long) ELF_R_TYPE(rel->r_info),
3250                                                         strtab + extsym->st_name);
3251                                 } else {
3252                                         bb_error_msg("%s of type %ld", errmsg,
3253                                                         (long) ELF_R_TYPE(rel->r_info));
3254                                 }
3255                                 ret = 0;
3256                                 break;
3257                         }
3258                 }
3259         }
3260
3261         /* Finally, take care of the patches.  */
3262
3263         if (f->string_patches) {
3264                 struct obj_string_patch *p;
3265                 struct obj_section *strsec;
3266                 ElfW(Addr) strsec_base;
3267                 strsec = obj_find_section(f, ".kstrtab");
3268                 strsec_base = strsec->header.sh_addr;
3269
3270                 for (p = f->string_patches; p; p = p->next) {
3271                         struct obj_section *targsec = f->sections[p->reloc_secidx];
3272                         *(ElfW(Addr) *) (targsec->contents + p->reloc_offset)
3273                                 = strsec_base + p->string_offset;
3274                 }
3275         }
3276
3277         if (f->symbol_patches) {
3278                 struct obj_symbol_patch *p;
3279
3280                 for (p = f->symbol_patches; p; p = p->next) {
3281                         struct obj_section *targsec = f->sections[p->reloc_secidx];
3282                         *(ElfW(Addr) *) (targsec->contents + p->reloc_offset)
3283                                 = obj_symbol_final_value(f, p->sym);
3284                 }
3285         }
3286
3287         return ret;
3288 }
3289
3290 static int obj_create_image(struct obj_file *f, char *image)
3291 {
3292         struct obj_section *sec;
3293         ElfW(Addr) base = f->baseaddr;
3294
3295         for (sec = f->load_order; sec; sec = sec->load_next) {
3296                 char *secimg;
3297
3298                 if (sec->contents == 0 || sec->header.sh_size == 0)
3299                         continue;
3300
3301                 secimg = image + (sec->header.sh_addr - base);
3302
3303                 /* Note that we allocated data for NOBITS sections earlier.  */
3304                 memcpy(secimg, sec->contents, sec->header.sh_size);
3305         }
3306
3307         return 1;
3308 }
3309
3310 /*======================================================================*/
3311
3312 static struct obj_file *obj_load(FILE * fp, int loadprogbits ATTRIBUTE_UNUSED)
3313 {
3314         struct obj_file *f;
3315         ElfW(Shdr) * section_headers;
3316         int shnum, i;
3317         char *shstrtab;
3318
3319         /* Read the file header.  */
3320
3321         f = arch_new_file();
3322         f->symbol_cmp = strcmp;
3323         f->symbol_hash = obj_elf_hash;
3324         f->load_order_search_start = &f->load_order;
3325
3326         fseek(fp, 0, SEEK_SET);
3327         if (fread(&f->header, sizeof(f->header), 1, fp) != 1) {
3328                 bb_perror_msg_and_die("error reading ELF header");
3329         }
3330
3331         if (f->header.e_ident[EI_MAG0] != ELFMAG0
3332                         || f->header.e_ident[EI_MAG1] != ELFMAG1
3333                         || f->header.e_ident[EI_MAG2] != ELFMAG2
3334                         || f->header.e_ident[EI_MAG3] != ELFMAG3) {
3335                 bb_error_msg_and_die("not an ELF file");
3336         }
3337         if (f->header.e_ident[EI_CLASS] != ELFCLASSM
3338                         || f->header.e_ident[EI_DATA] != (BB_BIG_ENDIAN
3339                                 ? ELFDATA2MSB : ELFDATA2LSB)
3340                         || f->header.e_ident[EI_VERSION] != EV_CURRENT
3341                         || !MATCH_MACHINE(f->header.e_machine)) {
3342                 bb_error_msg_and_die("ELF file not for this architecture");
3343         }
3344         if (f->header.e_type != ET_REL) {
3345                 bb_error_msg_and_die("ELF file not a relocatable object");
3346         }
3347
3348         /* Read the section headers.  */
3349
3350         if (f->header.e_shentsize != sizeof(ElfW(Shdr))) {
3351                 bb_error_msg_and_die("section header size mismatch: %lu != %lu",
3352                                 (unsigned long) f->header.e_shentsize,
3353                                 (unsigned long) sizeof(ElfW(Shdr)));
3354         }
3355
3356         shnum = f->header.e_shnum;
3357         f->sections = xmalloc(sizeof(struct obj_section *) * shnum);
3358         memset(f->sections, 0, sizeof(struct obj_section *) * shnum);
3359
3360         section_headers = alloca(sizeof(ElfW(Shdr)) * shnum);
3361         fseek(fp, f->header.e_shoff, SEEK_SET);
3362         if (fread(section_headers, sizeof(ElfW(Shdr)), shnum, fp) != shnum) {
3363                 bb_perror_msg_and_die("error reading ELF section headers");
3364         }
3365
3366         /* Read the section data.  */
3367
3368         for (i = 0; i < shnum; ++i) {
3369                 struct obj_section *sec;
3370
3371                 f->sections[i] = sec = arch_new_section();
3372
3373                 sec->header = section_headers[i];
3374                 sec->idx = i;
3375
3376                 if (sec->header.sh_size) {
3377                         switch (sec->header.sh_type) {
3378                         case SHT_NULL:
3379                         case SHT_NOTE:
3380                         case SHT_NOBITS:
3381                                 /* ignore */
3382                                 break;
3383
3384                         case SHT_PROGBITS:
3385 #if LOADBITS
3386                                 if (!loadprogbits) {
3387                                         sec->contents = NULL;
3388                                         break;
3389                                 }
3390 #endif
3391                         case SHT_SYMTAB:
3392                         case SHT_STRTAB:
3393                         case SHT_RELM:
3394                                 if (sec->header.sh_size > 0) {
3395                                         sec->contents = xmalloc(sec->header.sh_size);
3396                                         fseek(fp, sec->header.sh_offset, SEEK_SET);
3397                                         if (fread(sec->contents, sec->header.sh_size, 1, fp) != 1) {
3398                                                 bb_perror_msg_and_die("error reading ELF section data");
3399                                         }
3400                                 } else {
3401                                         sec->contents = NULL;
3402                                 }
3403                                 break;
3404
3405 #if SHT_RELM == SHT_REL
3406                         case SHT_RELA:
3407                                 bb_error_msg_and_die("RELA relocations not supported on this architecture");
3408 #else
3409                         case SHT_REL:
3410                                 bb_error_msg_and_die("REL relocations not supported on this architecture");
3411 #endif
3412                         default:
3413                                 if (sec->header.sh_type >= SHT_LOPROC) {
3414                                         /* Assume processor specific section types are debug
3415                                            info and can safely be ignored.  If this is ever not
3416                                            the case (Hello MIPS?), don't put ifdefs here but
3417                                            create an arch_load_proc_section().  */
3418                                         break;
3419                                 }
3420
3421                                 bb_error_msg_and_die("can't handle sections of type %ld",
3422                                                 (long) sec->header.sh_type);
3423                         }
3424                 }
3425         }
3426
3427         /* Do what sort of interpretation as needed by each section.  */
3428
3429         shstrtab = f->sections[f->header.e_shstrndx]->contents;
3430
3431         for (i = 0; i < shnum; ++i) {
3432                 struct obj_section *sec = f->sections[i];
3433                 sec->name = shstrtab + sec->header.sh_name;
3434         }
3435
3436         for (i = 0; i < shnum; ++i) {
3437                 struct obj_section *sec = f->sections[i];
3438
3439                 /* .modinfo should be contents only but gcc has no attribute for that.
3440                  * The kernel may have marked .modinfo as ALLOC, ignore this bit.
3441                  */
3442                 if (strcmp(sec->name, ".modinfo") == 0)
3443                         sec->header.sh_flags &= ~SHF_ALLOC;
3444
3445                 if (sec->header.sh_flags & SHF_ALLOC)
3446                         obj_insert_section_load_order(f, sec);
3447
3448                 switch (sec->header.sh_type) {
3449                 case SHT_SYMTAB:
3450                         {
3451                                 unsigned long nsym, j;
3452                                 char *strtab;
3453                                 ElfW(Sym) * sym;
3454
3455                                 if (sec->header.sh_entsize != sizeof(ElfW(Sym))) {
3456                                         bb_error_msg_and_die("symbol size mismatch: %lu != %lu",
3457                                                         (unsigned long) sec->header.sh_entsize,
3458                                                         (unsigned long) sizeof(ElfW(Sym)));
3459                                 }
3460
3461                                 nsym = sec->header.sh_size / sizeof(ElfW(Sym));
3462                                 strtab = f->sections[sec->header.sh_link]->contents;
3463                                 sym = (ElfW(Sym) *) sec->contents;
3464
3465                                 /* Allocate space for a table of local symbols.  */
3466                                 j = f->local_symtab_size = sec->header.sh_info;
3467                                 f->local_symtab = xzalloc(j * sizeof(struct obj_symbol *));
3468
3469                                 /* Insert all symbols into the hash table.  */
3470                                 for (j = 1, ++sym; j < nsym; ++j, ++sym) {
3471                                         ElfW(Addr) val = sym->st_value;
3472                                         const char *name;
3473                                         if (sym->st_name)
3474                                                 name = strtab + sym->st_name;
3475                                         else if (sym->st_shndx < shnum)
3476                                                 name = f->sections[sym->st_shndx]->name;
3477                                         else
3478                                                 continue;
3479 #if defined(__SH5__)
3480                                         /*
3481                                          * For sh64 it is possible that the target of a branch
3482                                          * requires a mode switch (32 to 16 and back again).
3483                                          *
3484                                          * This is implied by the lsb being set in the target
3485                                          * address for SHmedia mode and clear for SHcompact.
3486                                          */
3487                                         val |= sym->st_other & 4;
3488 #endif
3489                                         obj_add_symbol(f, name, j, sym->st_info, sym->st_shndx,
3490                                                         val, sym->st_size);
3491                                 }
3492                         }
3493                         break;
3494
3495                 case SHT_RELM:
3496                         if (sec->header.sh_entsize != sizeof(ElfW(RelM))) {
3497                                 bb_error_msg_and_die("relocation entry size mismatch: %lu != %lu",
3498                                                 (unsigned long) sec->header.sh_entsize,
3499                                                 (unsigned long) sizeof(ElfW(RelM)));
3500                         }
3501                         break;
3502                         /* XXX  Relocation code from modutils-2.3.19 is not here.
3503                          * Why?  That's about 20 lines of code from obj/obj_load.c,
3504                          * which gets done in a second pass through the sections.
3505                          * This BusyBox insmod does similar work in obj_relocate(). */
3506                 }
3507         }
3508
3509         return f;
3510 }
3511
3512 #if ENABLE_FEATURE_INSMOD_LOADINKMEM
3513 /*
3514  * load the unloaded sections directly into the memory allocated by
3515  * kernel for the module
3516  */
3517
3518 static int obj_load_progbits(FILE * fp, struct obj_file* f, char* imagebase)
3519 {
3520         ElfW(Addr) base = f->baseaddr;
3521         struct obj_section* sec;
3522
3523         for (sec = f->load_order; sec; sec = sec->load_next) {
3524
3525                 /* section already loaded? */
3526                 if (sec->contents != NULL)
3527                         continue;
3528
3529                 if (sec->header.sh_size == 0)
3530                         continue;
3531
3532                 sec->contents = imagebase + (sec->header.sh_addr - base);
3533                 fseek(fp, sec->header.sh_offset, SEEK_SET);
3534                 if (fread(sec->contents, sec->header.sh_size, 1, fp) != 1) {
3535                         bb_perror_msg("error reading ELF section data");
3536                         return 0;
3537                 }
3538
3539         }
3540         return 1;
3541 }
3542 #endif
3543
3544 static void hide_special_symbols(struct obj_file *f)
3545 {
3546         static const char *const specials[] = {
3547                 SPFX "cleanup_module",
3548                 SPFX "init_module",
3549                 SPFX "kernel_version",
3550                 NULL
3551         };
3552
3553         struct obj_symbol *sym;
3554         const char *const *p;
3555
3556         for (p = specials; *p; ++p) {
3557                 sym = obj_find_symbol(f, *p);
3558                 if (sym != NULL)
3559                         sym->info = ELF_ST_INFO(STB_LOCAL, ELF_ST_TYPE(sym->info));
3560         }
3561 }
3562
3563
3564 #if ENABLE_FEATURE_CHECK_TAINTED_MODULE
3565 static int obj_gpl_license(struct obj_file *f, const char **license)
3566 {
3567         struct obj_section *sec;
3568         /* This list must match *exactly* the list of allowable licenses in
3569          * linux/include/linux/module.h.  Checking for leading "GPL" will not
3570          * work, somebody will use "GPL sucks, this is proprietary".
3571          */
3572         static const char *const gpl_licenses[] = {
3573                 "GPL",
3574                 "GPL v2",
3575                 "GPL and additional rights",
3576                 "Dual BSD/GPL",
3577                 "Dual MPL/GPL"
3578         };
3579
3580         sec = obj_find_section(f, ".modinfo");
3581         if (sec) {
3582                 const char *value, *ptr, *endptr;
3583                 ptr = sec->contents;
3584                 endptr = ptr + sec->header.sh_size;
3585                 while (ptr < endptr) {
3586                         value = strchr(ptr, '=');
3587                         if (value && strncmp(ptr, "license", value-ptr) == 0) {
3588                                 int i;
3589                                 if (license)
3590                                         *license = value+1;
3591                                 for (i = 0; i < ARRAY_SIZE(gpl_licenses); ++i) {
3592                                         if (strcmp(value+1, gpl_licenses[i]) == 0)
3593                                                 return 0;
3594                                 }
3595                                 return 2;
3596                         }
3597                         ptr = strchr(ptr, '\0');
3598                         if (ptr)
3599                                 ptr++;
3600                         else
3601                                 ptr = endptr;
3602                 }
3603         }
3604         return 1;
3605 }
3606
3607 #define TAINT_FILENAME                  "/proc/sys/kernel/tainted"
3608 #define TAINT_PROPRIETORY_MODULE        (1 << 0)
3609 #define TAINT_FORCED_MODULE             (1 << 1)
3610 #define TAINT_UNSAFE_SMP                (1 << 2)
3611 #define TAINT_URL                       "http://www.tux.org/lkml/#export-tainted"
3612
3613 static void set_tainted(int fd, char *m_name,
3614                 int kernel_has_tainted, int taint, const char *text1, const char *text2)
3615 {
3616         static smallint printed_info;
3617
3618         char buf[80];
3619         int oldval;
3620
3621         if (fd < 0 && !kernel_has_tainted)
3622                 return;         /* New modutils on old kernel */
3623         printf("Warning: loading %s will taint the kernel: %s%s\n",
3624                         m_name, text1, text2);
3625         if (!printed_info) {
3626                 printf("  See %s for information about tainted modules\n", TAINT_URL);
3627                 printed_info = 1;
3628         }
3629         if (fd >= 0) {
3630                 read(fd, buf, sizeof(buf)-1);
3631                 buf[sizeof(buf)-1] = '\0';
3632                 oldval = strtoul(buf, NULL, 10);
3633                 sprintf(buf, "%d\n", oldval | taint);
3634                 write(fd, buf, strlen(buf));
3635         }
3636 }
3637
3638 /* Check if loading this module will taint the kernel. */
3639 static void check_tainted_module(struct obj_file *f, char *m_name)
3640 {
3641         static const char tainted_file[] ALIGN1 = TAINT_FILENAME;
3642
3643         int fd, kernel_has_tainted;
3644         const char *ptr;
3645
3646         kernel_has_tainted = 1;
3647         fd = open(tainted_file, O_RDWR);
3648         if (fd < 0) {
3649                 if (errno == ENOENT)
3650                         kernel_has_tainted = 0;
3651                 else if (errno == EACCES)
3652                         kernel_has_tainted = 1;
3653                 else {
3654                         perror(tainted_file);
3655                         kernel_has_tainted = 0;
3656                 }
3657         }
3658
3659         switch (obj_gpl_license(f, &ptr)) {
3660                 case 0:
3661                         break;
3662                 case 1:
3663                         set_tainted(fd, m_name, kernel_has_tainted, TAINT_PROPRIETORY_MODULE, "no license", "");
3664                         break;
3665                 case 2:
3666                         /* The module has a non-GPL license so we pretend that the
3667                          * kernel always has a taint flag to get a warning even on
3668                          * kernels without the proc flag.
3669                          */
3670                         set_tainted(fd, m_name, 1, TAINT_PROPRIETORY_MODULE, "non-GPL license - ", ptr);
3671                         break;
3672                 default:
3673                         set_tainted(fd, m_name, 1, TAINT_PROPRIETORY_MODULE, "Unexpected return from obj_gpl_license", "");
3674                         break;
3675         }
3676
3677         if (flag_force_load)
3678                 set_tainted(fd, m_name, 1, TAINT_FORCED_MODULE, "forced load", "");
3679
3680         if (fd >= 0)
3681                 close(fd);
3682 }
3683 #else /* FEATURE_CHECK_TAINTED_MODULE */
3684 #define check_tainted_module(x, y) do { } while (0);
3685 #endif /* FEATURE_CHECK_TAINTED_MODULE */
3686
3687 #if ENABLE_FEATURE_INSMOD_KSYMOOPS_SYMBOLS
3688 /* add module source, timestamp, kernel version and a symbol for the
3689  * start of some sections.  this info is used by ksymoops to do better
3690  * debugging.
3691  */
3692 #if !ENABLE_FEATURE_INSMOD_VERSION_CHECKING
3693 #define get_module_version(f, str) get_module_version(str)
3694 #endif
3695 static int
3696 get_module_version(struct obj_file *f, char str[STRVERSIONLEN])
3697 {
3698 #if ENABLE_FEATURE_INSMOD_VERSION_CHECKING
3699         return new_get_module_version(f, str);
3700 #else  /* FEATURE_INSMOD_VERSION_CHECKING */
3701         strncpy(str, "???", sizeof(str));
3702         return -1;
3703 #endif /* FEATURE_INSMOD_VERSION_CHECKING */
3704 }
3705
3706 /* add module source, timestamp, kernel version and a symbol for the
3707  * start of some sections.  this info is used by ksymoops to do better
3708  * debugging.
3709  */
3710 static void
3711 add_ksymoops_symbols(struct obj_file *f, const char *filename,
3712                                  const char *m_name)
3713 {
3714         static const char symprefix[] ALIGN1 = "__insmod_";
3715         static const char section_names[][8] = {
3716                 ".text",
3717                 ".rodata",
3718                 ".data",
3719                 ".bss",
3720                 ".sbss"
3721         };
3722
3723         struct obj_section *sec;
3724         struct obj_symbol *sym;
3725         char *name, *absolute_filename;
3726         char str[STRVERSIONLEN];
3727         int i, l, lm_name, lfilename, use_ksymtab, version;
3728         struct stat statbuf;
3729
3730         /* WARNING: was using realpath, but replaced by readlink to stop using
3731          * lots of stack. But here it seems to be able to cause problems? */
3732         absolute_filename = xmalloc_readlink(filename);
3733         if (!absolute_filename)
3734                 absolute_filename = xstrdup(filename);
3735
3736         lm_name = strlen(m_name);
3737         lfilename = strlen(absolute_filename);
3738
3739         /* add to ksymtab if it already exists or there is no ksymtab and other symbols
3740          * are not to be exported.  otherwise leave ksymtab alone for now, the
3741          * "export all symbols" compatibility code will export these symbols later.
3742          */
3743         use_ksymtab = obj_find_section(f, "__ksymtab") || flag_noexport;
3744
3745         sec = obj_find_section(f, ".this");
3746         if (sec) {
3747                 /* tag the module header with the object name, last modified
3748                  * timestamp and module version.  worst case for module version
3749                  * is 0xffffff, decimal 16777215.  putting all three fields in
3750                  * one symbol is less readable but saves kernel space.
3751                  */
3752                 l = sizeof(symprefix) +                 /* "__insmod_" */
3753                         lm_name +                       /* module name */
3754                         2 +                             /* "_O" */
3755                         lfilename +                     /* object filename */
3756                         2 +                             /* "_M" */
3757                         2 * sizeof(statbuf.st_mtime) +  /* mtime in hex */
3758                         2 +                             /* "_V" */
3759                         8 +                             /* version in dec */
3760                         1;                              /* nul */
3761                 name = xmalloc(l);
3762                 if (stat(absolute_filename, &statbuf) != 0)
3763                         statbuf.st_mtime = 0;
3764                 version = get_module_version(f, str);   /* -1 if not found */
3765                 snprintf(name, l, "%s%s_O%s_M%0*lX_V%d",
3766                                 symprefix, m_name, absolute_filename,
3767                                 (int)(2 * sizeof(statbuf.st_mtime)), statbuf.st_mtime,
3768                                 version);
3769                 sym = obj_add_symbol(f, name, -1,
3770                                 ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE),
3771                                 sec->idx, sec->header.sh_addr, 0);
3772                 if (use_ksymtab)
3773                         new_add_ksymtab(f, sym);
3774         }
3775         free(absolute_filename);
3776 #ifdef _NOT_SUPPORTED_
3777         /* record where the persistent data is going, same address as previous symbol */
3778
3779         if (f->persist) {
3780                 l = sizeof(symprefix) +         /* "__insmod_" */
3781                         lm_name +               /* module name */
3782                         2 +                     /* "_P" */
3783                         strlen(f->persist) +    /* data store */
3784                         1;                      /* nul */
3785                 name = xmalloc(l);
3786                 snprintf(name, l, "%s%s_P%s",
3787                                 symprefix, m_name, f->persist);
3788                 sym = obj_add_symbol(f, name, -1, ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE),
3789                                 sec->idx, sec->header.sh_addr, 0);
3790                 if (use_ksymtab)
3791                         new_add_ksymtab(f, sym);
3792         }
3793 #endif /* _NOT_SUPPORTED_ */
3794         /* tag the desired sections if size is non-zero */
3795
3796         for (i = 0; i < ARRAY_SIZE(section_names); ++i) {
3797                 sec = obj_find_section(f, section_names[i]);
3798                 if (sec && sec->header.sh_size) {
3799                         l = sizeof(symprefix) +         /* "__insmod_" */
3800                                 lm_name +               /* module name */
3801                                 2 +                     /* "_S" */
3802                                 strlen(sec->name) +     /* section name */
3803                                 2 +                     /* "_L" */
3804                                 8 +                     /* length in dec */
3805                                 1;                      /* nul */
3806                         name = xmalloc(l);
3807                         snprintf(name, l, "%s%s_S%s_L%ld",
3808                                         symprefix, m_name, sec->name,
3809                                         (long)sec->header.sh_size);
3810                         sym = obj_add_symbol(f, name, -1, ELF_ST_INFO(STB_GLOBAL, STT_NOTYPE),
3811                                         sec->idx, sec->header.sh_addr, 0);
3812                         if (use_ksymtab)
3813                                 new_add_ksymtab(f, sym);
3814                 }
3815         }
3816 }
3817 #endif /* FEATURE_INSMOD_KSYMOOPS_SYMBOLS */
3818
3819 #if ENABLE_FEATURE_INSMOD_LOAD_MAP
3820 static void print_load_map(struct obj_file *f)
3821 {
3822         struct obj_section *sec;
3823 #if ENABLE_FEATURE_INSMOD_LOAD_MAP_FULL
3824         struct obj_symbol **all, **p;
3825         int i, nsyms, *loaded;
3826         struct obj_symbol *sym;
3827 #endif
3828         /* Report on the section layout.  */
3829
3830         printf("Sections:       Size      %-*s  Align\n",
3831                         (int) (2 * sizeof(void *)), "Address");
3832
3833         for (sec = f->load_order; sec; sec = sec->load_next) {
3834                 int a;
3835                 unsigned long tmp;
3836
3837                 for (a = -1, tmp = sec->header.sh_addralign; tmp; ++a)
3838                         tmp >>= 1;
3839                 if (a == -1)
3840                         a = 0;
3841
3842                 printf("%-15s %08lx  %0*lx  2**%d\n",
3843                                 sec->name,
3844                                 (long)sec->header.sh_size,
3845                                 (int) (2 * sizeof(void *)),
3846                                 (long)sec->header.sh_addr,
3847                                 a);
3848         }
3849 #if ENABLE_FEATURE_INSMOD_LOAD_MAP_FULL
3850         /* Quick reference which section indicies are loaded.  */
3851
3852         i = f->header.e_shnum;
3853         loaded = alloca(sizeof(int) * i);
3854         while (--i >= 0)
3855                 loaded[i] = ((f->sections[i]->header.sh_flags & SHF_ALLOC) != 0);
3856
3857         /* Collect the symbols we'll be listing.  */
3858
3859         for (nsyms = i = 0; i < HASH_BUCKETS; ++i)
3860                 for (sym = f->symtab[i]; sym; sym = sym->next)
3861                         if (sym->secidx <= SHN_HIRESERVE
3862                                         && (sym->secidx >= SHN_LORESERVE || loaded[sym->secidx]))
3863                                 ++nsyms;
3864
3865         all = alloca(nsyms * sizeof(struct obj_symbol *));
3866
3867         for (i = 0, p = all; i < HASH_BUCKETS; ++i)
3868                 for (sym = f->symtab[i]; sym; sym = sym->next)
3869                         if (sym->secidx <= SHN_HIRESERVE
3870                                         && (sym->secidx >= SHN_LORESERVE || loaded[sym->secidx]))
3871                                 *p++ = sym;
3872
3873         /* And list them.  */
3874         printf("\nSymbols:\n");
3875         for (p = all; p < all + nsyms; ++p) {
3876                 char type = '?';
3877                 unsigned long value;
3878
3879                 sym = *p;
3880                 if (sym->secidx == SHN_ABS) {
3881                         type = 'A';
3882                         value = sym->value;
3883                 } else if (sym->secidx == SHN_UNDEF) {
3884                         type = 'U';
3885                         value = 0;
3886                 } else {
3887                         sec = f->sections[sym->secidx];
3888
3889                         if (sec->header.sh_type == SHT_NOBITS)
3890                                 type = 'B';
3891                         else if (sec->header.sh_flags & SHF_ALLOC) {
3892                                 if (sec->header.sh_flags & SHF_EXECINSTR)
3893                                         type = 'T';
3894                                 else if (sec->header.sh_flags & SHF_WRITE)
3895                                         type = 'D';
3896                                 else
3897                                         type = 'R';
3898                         }
3899                         value = sym->value + sec->header.sh_addr;
3900                 }
3901
3902                 if (ELF_ST_BIND(sym->info) == STB_LOCAL)
3903                         type = tolower(type);
3904
3905                 printf("%0*lx %c %s\n", (int) (2 * sizeof(void *)), value,
3906                                 type, sym->name);
3907         }
3908 #endif
3909 }
3910 #else /* !FEATURE_INSMOD_LOAD_MAP */
3911 void print_load_map(struct obj_file *f);
3912 #endif
3913
3914 int insmod_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
3915 int insmod_main(int argc, char **argv)
3916 {
3917         char *opt_o, *arg1;
3918         int len;
3919         int k_crcs;
3920         char *tmp, *tmp1;
3921         unsigned long m_size;
3922         ElfW(Addr) m_addr;
3923         struct obj_file *f;
3924         struct stat st;
3925         char *m_name = NULL;
3926         int exit_status = EXIT_FAILURE;
3927         int m_has_modinfo;
3928 #if ENABLE_FEATURE_INSMOD_VERSION_CHECKING
3929         struct utsname uts_info;
3930         char m_strversion[STRVERSIONLEN];
3931         int m_version, m_crcs;
3932 #endif
3933 #if ENABLE_FEATURE_CLEAN_UP
3934         FILE *fp = NULL;
3935 #else
3936         FILE *fp;
3937 #endif
3938         int k_version = 0;
3939         struct utsname myuname;
3940
3941         /* Parse any options */
3942         getopt32(argv, OPTION_STR, &opt_o);
3943         arg1 = argv[optind];
3944         if (option_mask32 & OPT_o) { // -o /* name the output module */
3945                 free(m_name);
3946                 m_name = xstrdup(opt_o);
3947         }
3948
3949         if (arg1 == NULL) {
3950                 bb_show_usage();
3951         }
3952
3953         /* Grab the module name */
3954         tmp1 = xstrdup(arg1);
3955         tmp = basename(tmp1);
3956         len = strlen(tmp);
3957
3958         if (uname(&myuname) == 0) {
3959                 if (myuname.release[0] == '2') {
3960                         k_version = myuname.release[2] - '0';
3961                 }
3962         }
3963
3964 #if ENABLE_FEATURE_2_6_MODULES
3965         if (k_version > 4 && len > 3 && tmp[len - 3] == '.'
3966          && tmp[len - 2] == 'k' && tmp[len - 1] == 'o'
3967         ) {
3968                 len -= 3;
3969                 tmp[len] = '\0';
3970         } else
3971 #endif
3972                 if (len > 2 && tmp[len - 2] == '.' && tmp[len - 1] == 'o') {
3973                         len -= 2;
3974                         tmp[len] = '\0';
3975                 }
3976
3977
3978 #if ENABLE_FEATURE_2_6_MODULES
3979         if (k_version > 4)
3980                 m_fullName = xasprintf("%s.ko", tmp);
3981         else
3982 #endif
3983                 m_fullName = xasprintf("%s.o", tmp);
3984
3985         if (!m_name) {
3986                 m_name = tmp;
3987         } else {
3988                 free(tmp1);
3989                 tmp1 = NULL;       /* flag for free(m_name) before exit() */
3990         }
3991
3992         /* Get a filedesc for the module.  Check that we have a complete path */
3993         if (stat(arg1, &st) < 0 || !S_ISREG(st.st_mode)
3994          || (fp = fopen(arg1, "r")) == NULL
3995         ) {
3996                 /* Hmm.  Could not open it.  First search under /lib/modules/`uname -r`,
3997                  * but do not error out yet if we fail to find it... */
3998                 if (k_version) {        /* uname succeedd */
3999                         char *module_dir;
4000                         char *tmdn;
4001
4002                         tmdn = concat_path_file(_PATH_MODULES, myuname.release);
4003                         /* Jump through hoops in case /lib/modules/`uname -r`
4004                          * is a symlink.  We do not want recursive_action to
4005                          * follow symlinks, but we do want to follow the
4006                          * /lib/modules/`uname -r` dir, So resolve it ourselves
4007                          * if it is a link... */
4008                         module_dir = xmalloc_readlink(tmdn);
4009                         if (!module_dir)
4010                                 module_dir = xstrdup(tmdn);
4011                         recursive_action(module_dir, ACTION_RECURSE,
4012                                         check_module_name_match, NULL, m_fullName, 0);
4013                         free(module_dir);
4014                         free(tmdn);
4015                 }
4016
4017                 /* Check if we have found anything yet */
4018                 if (!m_filename || ((fp = fopen(m_filename, "r")) == NULL)) {
4019                         int r;
4020                         char *module_dir;
4021
4022                         free(m_filename);
4023                         m_filename = NULL;
4024                         module_dir = xmalloc_readlink(_PATH_MODULES);
4025                         if (!module_dir)
4026                                 module_dir = xstrdup(_PATH_MODULES);
4027                         /* No module found under /lib/modules/`uname -r`, this
4028                          * time cast the net a bit wider.  Search /lib/modules/ */
4029                         r = recursive_action(module_dir, ACTION_RECURSE,
4030                                         check_module_name_match, NULL, m_fullName, 0);
4031                         if (r)
4032                                 bb_error_msg_and_die("%s: module not found", m_fullName);
4033                         free(module_dir);
4034                         if (m_filename == NULL
4035                          || ((fp = fopen(m_filename, "r")) == NULL)
4036                         ) {
4037                                 bb_error_msg_and_die("%s: module not found", m_fullName);
4038                         }
4039                 }
4040         } else
4041                 m_filename = xstrdup(arg1);
4042
4043         if (flag_verbose)
4044                 printf("Using %s\n", m_filename);
4045
4046 #if ENABLE_FEATURE_2_6_MODULES
4047         if (k_version > 4) {
4048                 argv[optind] = m_filename;
4049                 optind--;
4050                 return insmod_ng_main(argc - optind, argv + optind);
4051         }
4052 #endif
4053
4054         f = obj_load(fp, LOADBITS);
4055
4056         if (get_modinfo_value(f, "kernel_version") == NULL)
4057                 m_has_modinfo = 0;
4058         else
4059                 m_has_modinfo = 1;
4060
4061 #if ENABLE_FEATURE_INSMOD_VERSION_CHECKING
4062         /* Version correspondence?  */
4063         if (!flag_quiet) {
4064                 if (uname(&uts_info) < 0)
4065                         uts_info.release[0] = '\0';
4066                 if (m_has_modinfo) {
4067                         m_version = new_get_module_version(f, m_strversion);
4068                         if (m_version == -1) {
4069                                 bb_error_msg_and_die("cannot find the kernel version the module was "
4070                                                 "compiled for");
4071                         }
4072                 }
4073
4074                 if (strncmp(uts_info.release, m_strversion, STRVERSIONLEN) != 0) {
4075                         bb_error_msg("%skernel-module version mismatch\n"
4076                                 "\t%s was compiled for kernel version %s\n"
4077                                 "\twhile this kernel is version %s",
4078                                 flag_force_load ? "warning: " : "",
4079                                 m_filename, m_strversion, uts_info.release);
4080                         if (!flag_force_load)
4081                                 goto out;
4082                 }
4083         }
4084         k_crcs = 0;
4085 #endif /* FEATURE_INSMOD_VERSION_CHECKING */
4086
4087         if (query_module(NULL, 0, NULL, 0, NULL))
4088                 bb_error_msg_and_die("not configured to support old kernels");
4089         new_get_kernel_symbols();
4090         k_crcs = new_is_kernel_checksummed();
4091
4092 #if ENABLE_FEATURE_INSMOD_VERSION_CHECKING
4093         m_crcs = 0;
4094         if (m_has_modinfo)
4095                 m_crcs = new_is_module_checksummed(f);
4096
4097         if (m_crcs != k_crcs)
4098                 obj_set_symbol_compare(f, ncv_strcmp, ncv_symbol_hash);
4099 #endif /* FEATURE_INSMOD_VERSION_CHECKING */
4100
4101         /* Let the module know about the kernel symbols.  */
4102         add_kernel_symbols(f);
4103
4104         /* Allocate common symbols, symbol tables, and string tables.  */
4105
4106         new_create_this_module(f, m_name);
4107         obj_check_undefineds(f);
4108         obj_allocate_commons(f);
4109         check_tainted_module(f, m_name);
4110
4111         /* done with the module name, on to the optional var=value arguments */
4112         ++optind;
4113         if (optind < argc) {
4114                 new_process_module_arguments(f, argc - optind, argv + optind);
4115         }
4116
4117         arch_create_got(f);
4118         hide_special_symbols(f);
4119
4120 #if ENABLE_FEATURE_INSMOD_KSYMOOPS_SYMBOLS
4121         add_ksymoops_symbols(f, m_filename, m_name);
4122 #endif /* FEATURE_INSMOD_KSYMOOPS_SYMBOLS */
4123
4124         new_create_module_ksymtab(f);
4125
4126         /* Find current size of the module */
4127         m_size = obj_load_size(f);
4128
4129         m_addr = create_module(m_name, m_size);
4130         if (m_addr == -1) switch (errno) {
4131                 case EEXIST:
4132                         bb_error_msg_and_die("a module named %s already exists", m_name);
4133                 case ENOMEM:
4134                         bb_error_msg_and_die("can't allocate kernel memory for module; needed %lu bytes",
4135                                         m_size);
4136                 default:
4137                         bb_perror_msg_and_die("create_module: %s", m_name);
4138         }
4139
4140 #if !LOADBITS
4141         /*
4142          * the PROGBITS section was not loaded by the obj_load
4143          * now we can load them directly into the kernel memory
4144          */
4145         if (!obj_load_progbits(fp, f, (char*)m_addr)) {
4146                 delete_module(m_name);
4147                 goto out;
4148         }
4149 #endif
4150
4151         if (!obj_relocate(f, m_addr)) {
4152                 delete_module(m_name);
4153                 goto out;
4154         }
4155
4156         if (!new_init_module(m_name, f, m_size)) {
4157                 delete_module(m_name);
4158                 goto out;
4159         }
4160
4161         if (flag_print_load_map)
4162                 print_load_map(f);
4163
4164         exit_status = EXIT_SUCCESS;
4165
4166  out:
4167 #if ENABLE_FEATURE_CLEAN_UP
4168         if (fp)
4169                 fclose(fp);
4170         free(tmp1);
4171         if (!tmp1)
4172                 free(m_name);
4173         free(m_filename);
4174 #endif
4175         return exit_status;
4176 }
4177
4178 #endif /* ENABLE_FEATURE_2_4_MODULES */
4179 /*
4180  * End of big piece of 2.4-specific code
4181  */
4182
4183
4184 #if ENABLE_FEATURE_2_6_MODULES
4185
4186 #include <sys/mman.h>
4187 #include <asm/unistd.h>
4188 #include <sys/syscall.h>
4189
4190 /* We use error numbers in a loose translation... */
4191 static const char *moderror(int err)
4192 {
4193         switch (err) {
4194         case ENOEXEC:
4195                 return "invalid module format";
4196         case ENOENT:
4197                 return "unknown symbol in module";
4198         case ESRCH:
4199                 return "module has wrong symbol version";
4200         case EINVAL:
4201                 return "invalid parameters";
4202         default:
4203                 return strerror(err);
4204         }
4205 }
4206
4207 #if !ENABLE_FEATURE_2_4_MODULES
4208 int insmod_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
4209 int insmod_main(int argc ATTRIBUTE_UNUSED, char **argv)
4210 #else
4211 static int insmod_ng_main(int argc ATTRIBUTE_UNUSED, char **argv)
4212 #endif
4213 {
4214         long ret;
4215         size_t len;
4216         int optlen;
4217         void *map;
4218         char *filename, *options;
4219
4220         filename = *++argv;
4221         if (!filename)
4222                 bb_show_usage();
4223
4224         /* Rest is options */
4225         options = xzalloc(1);
4226         optlen = 0;
4227         while (*++argv) {
4228                 options = xrealloc(options, optlen + 2 + strlen(*argv) + 2);
4229                 /* Spaces handled by "" pairs, but no way of escaping quotes */
4230                 optlen += sprintf(options + optlen, (strchr(*argv,' ') ? "\"%s\" " : "%s "), *argv);
4231         }
4232
4233 #if 0
4234         /* Any special reason why mmap? It isn't performace critical... */
4235         int fd;
4236         struct stat st;
4237         unsigned long len;
4238         fd = xopen(filename, O_RDONLY);
4239         fstat(fd, &st);
4240         len = st.st_size;
4241         map = mmap(NULL, len, PROT_READ, MAP_PRIVATE, fd, 0);
4242         if (map == MAP_FAILED) {
4243                 bb_perror_msg_and_die("cannot mmap '%s'", filename);
4244         }
4245
4246         /* map == NULL on Blackfin, probably on other MMU-less systems too. Workaround. */
4247         if (map == NULL) {
4248                 map = xmalloc(len);
4249                 xread(fd, map, len);
4250         }
4251 #else
4252         len = MAXINT(ssize_t);
4253         map = xmalloc_open_read_close(filename, &len);
4254 #endif
4255
4256         ret = syscall(__NR_init_module, map, len, options);
4257         if (ret != 0) {
4258                 bb_error_msg_and_die("cannot insert '%s': %s",
4259                                 filename, moderror(errno));
4260         }
4261
4262         return 0;
4263 }
4264
4265 #endif