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