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