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