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