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