zoukankan      html  css  js  c++  java
  • insmod模块加载过程代码分析1【转】

    转自:http://blog.chinaunix.net/uid-27717694-id-3966290.html

    一、概述
    模块是作为ELF对象文件存放在文件系统中的,并通过执行insmod程序链接到内核中。对于每个模块,系统都要分配一个包含以下数据结构的内存区。
    一个module对象,表示模块名的一个以null结束的字符串,实现模块功能的代码。在2.6内核以前,insmod模块过程主要是通过modutils中的insmod加载,大量工作都是在用户空间完成。但在2.6内核以后,系统使用busybox的insmod指令,把大量工作移到内核代码处理,参见模块加载过程代码分析2.
    二、相关数据结构
    1.module对象描述一个模块。一个双向循环链表存放所有module对象,链表头部存放在modules变量中,而指向相邻单元的指针存放在每个module对象的list字段中。
    struct module
    {
     /*state 表示该模块的当前状态。 
     enum module_state 
     { 
         MODULE_STATE_LIVE, 
         MODULE_STATE_COMING, 
         MODULE_STATE_GOING, 
     }; 
     在装载期间,状态为 MODULE_STATE_COMING; 
     正常运行(完成所有初始化任务之后)时,状态为 MODULE_STATE_LIVE; 
     在模块正在卸载移除时,状态为 MODULE_STATE_GOING. 
     */
     enum module_state state;//模块内部状态
     //模块链表指针,将所有加载模块保存到一个双链表中,链表的表头是定义在 的全局变量 modules。 
     struct list_head list;
     char name[MODULE_NAME_LEN];//模块名
     /* Sysfs stuff. */
     struct module_kobject mkobj;//包含一个kobject数据结构
     struct module_attribute *modinfo_attrs;
     const char *version;
     const char *srcversion;
     struct kobject *holders_dir;
     /*syms,num_syms,crcs 用于管理模块导出的符号。syms是一个数组,有 num_syms 个数组项, 
     数组项类型为 kernel_symbol,负责将标识符(name)分配到内存地址(value): 
     struct kernel_symbol 
     { 
         unsigned long value; 
         const char *name; 
     }; 
     crcs 也是一个 num_syms 个数组项的数组,存储了导出符号的校验和,用于实现版本控制 
     */
     const struct kernel_symbol *syms;//指向导出符号数组的指针
     const unsigned long *crcs;//指向导出符号CRC值数组的指针
     unsigned int num_syms;//导出符号数
     struct kernel_param *kp;//内核参数
     unsigned int num_kp;//内核参数个数 
     /*在导出符号时,内核不仅考虑了可以有所有模块(不考虑许可证类型)使用的符号,还要考虑只能由 GPL 兼容模块使用的符号。 第三类的符号当前仍然可以有任意许可证的模块使用,但在不久的将来也会转变为只适用于 GPL 模块。gpl_syms,num_gpl_syms,gpl_crcs 成员用于只提供给 GPL 模块的符号;gpl_future_syms,num_gpl_future_syms,gpl_future_crcs 用于将来只提供给 GPL 模块的符号。unused_gpl_syms 和 unused_syms 以及对应的计数器和校验和成员描述。 这两个数组用于存储(只适用于 GPL)已经导出, 但 in-tree 模块未使用的符号。在out-of-tree 模块使用此类型符号时,内核将输出一个警告消息。 
    */ 
     unsigned int num_gpl_syms;//GPL格式导出符号数
     const struct kernel_symbol *gpl_syms;//指向GPL格式导出符号数组的指针
     const unsigned long *gpl_crcs;//指向GPL格式导出符号CRC值数组的指针
     
    #ifdef CONFIG_MODULE_SIG  
     bool sig_ok;/* Signature was verified. */
    #endif
      /* symbols that will be GPL-only in the near future. */
     const struct kernel_symbol *gpl_future_syms;
     const unsigned long *gpl_future_crcs;
     unsigned int num_gpl_future_syms;
      
     /*如果模块定义了新的异常,异常的描述保存在 extable数组中。 num_exentries 指定了数组的长度。 */
     unsigned int num_exentries;
     struct exception_table_entry *extable;
      
      /*模块的二进制数据分为两个部分;初始化部分和核心部分。 
     前者包含的数据在转载结束后都可以丢弃(例如:初始化函数),后者包含了正常运行期间需要的所有数据。   
     初始化部分的起始地址保存在 module_init,长度为 init_size 字节; 
     核心部分有 module_core 和 core_size 描述。 
     */
     int (*init)(void);//模块初始化方法,指向一个在模块初始化时调用的函数
     void *module_init;//用于模块初始化的动态内存区指针
     void *module_core;//用于模块核心函数与数据结构的动态内存区指针
     //用于模块初始化的动态内存区大小和用于模块核心函数与数据结构的动态内存区指针
     unsigned int init_size, core_size;
     //模块初始化的可执行代码大小,模块核心可执行代码大小,只当模块链接时使用
     unsigned int init_text_size, core_text_size;
     /* Size of RO sections of the module (text+rodata) */
     unsigned int init_ro_size, core_ro_size;
     struct mod_arch_specific arch;//依赖于体系结构的字段
     /*如果模块会污染内核,则设置 taints.污染意味着内核怀疑该模块做了一个有害的事情,可能妨碍内核的正常运作。 
     如果发生内核恐慌(在发生致命的内部错误,无法恢复正常运作时,将触发内核恐慌),那么错误诊断也会包含为什么内核被污染的有关信息。 
     这有助于开发者区分来自正常运行系统的错误报告和包含某些可疑因素的系统错误。 
     add_taint_module 函数用来设置 struct module 的给定实例的 taints 成员。 
      
     模块可能因两个原因污染内核: 
     1,如果模块的许可证是专有的,或不兼容 GPL,那么在模块载入内核时,会使用 TAINT_PROPRIETARY_MODULE. 
       由于专有模块的源码可能弄不到,模块在内核中作的任何事情都无法跟踪,因此,bug 很可能是由模块引入的。 
      
       内核提供了函数 license_is_gpl_compatible 来判断给定的许可证是否与 GPL 兼容。 
     2,TAINT_FORCED_MODULE 表示该模块是强制装载的。如果模块中没有提供版本信息,也称为版本魔术(version magic), 
       或模块和内核某些符号的版本不一致,那么可以请求强制装载。  
     */
     unsigned int taints;    /* same bits as kernel:tainted */
     char *args;//模块链接时使用的命令行参数
     
    #ifdef CONFIG_SMP/
     void __percpu *percpu;/*percpu 指向属于模块的各 CPU 数据。它在模块装载时初始化*/   
     unsigned int percpu_size;
    #endif
     
    #ifdef CONFIG_TRACEPOINTS
     unsigned int num_tracepoints;
     struct tracepoint * const *tracepoints_ptrs;
    #endif
    #ifdef HAVE_JUMP_LABEL
     struct jump_entry *jump_entries;
     unsigned int num_jump_entries;
    #endif
    #ifdef CONFIG_TRACING
      unsigned int num_trace_bprintk_fmt;
     const char **trace_bprintk_fmt_start;
    #endif
    #ifdef CONFIG_EVENT_TRACING
     struct ftrace_event_call **trace_events;
     unsigned int num_trace_events;
    #endif
    #ifdef CONFIG_FTRACE_MCOUNT_RECORD
     unsigned int num_ftrace_callsites;
     unsigned long *ftrace_callsites;
    #endif
     
    #ifdef CONFIG_MODULE_UNLOAD
     /* What modules depend on me? */
     struct list_head source_list;
     /* What modules do I depend on? */
     struct list_head target_list;
     struct task_struct *waiter;//正卸载模块的进程
     void (*exit)(void);//模块退出方法
     /*module_ref 用于引用计数。系统中的每个 CPU,都对应到该数组中的数组项。该项指定了系统中有多少地方使用了该模块。 
    内核提供了 try_module_get 和 module_put 函数,用对引用计数器加1或减1,如果调用者确信相关模块当前没有被卸载, 
    也可以使用 __module_get 对引用计数加 1.相反,try_module_get 会确认模块确实已经加载。
     struct module_ref { 
       unsigned int incs; 
       unsigned int decs; 
      } 
    */ 
     struct module_ref __percpu *refptr;//模块计数器,每个cpu一个
     #endif

    #ifdef CONFIG_CONSTRUCTORS
     /* Constructor functions. */
     ctor_fn_t *ctors;
     unsigned int num_ctors;
    #endif
    };

    三、模块链接过程
    用户可以通过执行insmod外部程序把一个模块链接到正在运行的内核中。该过程执行以下操作:
    1.从命令行中读取要链接的模块名
    2.确定模块对象代码所在的文件在系统目录树中的位置。
    3.从磁盘读入存有模块目标代码的文件。
    4.调用init_module()系统调用。函数将模块二进制文件复制到内核,然后由内核完成剩余的任务。
    5.init_module函数通过系统调用层,进入内核到达内核函数 sys_init_module,这是加载模块的主要函数。
    6.结束。

    四、insmod过程解析
    1.obj_file记录模块信息
    struct obj_file
    {
      ElfW(Ehdr) header;//指向elf header
      ElfW(Addr) baseaddr;//模块的基址
      struct obj_section **sections;//指向节区头部表,包含每个节区头部
      struct obj_section *load_order;//节区load顺序
      struct obj_section **load_order_search_start;//
      struct obj_string_patch_struct *string_patches;//patch的字符串
      struct obj_symbol_patch_struct *symbol_patches;//patch的符号
      int (*symbol_cmp)(const char *, const char *);//指向strcmp函数
      unsigned long (*symbol_hash)(const char *);//指向obj_elf_hash函数
      unsigned long local_symtab_size;//局部符号表大小
      struct obj_symbol **local_symtab;//局部符号表
      struct obj_symbol *symtab[HASH_BUCKETS];//符号hash表
      const char *filename;//模块名
      char *persist;
    };

    2.obj_section记录模块节区信息
    struct obj_section
    {
      ElfW(Shdr) header;//指向本节区头结构
      const char *name;//节区名
      char *contents;//从节区头内容偏移处获得的节区内容
      struct obj_section *load_next;//指向下一个节区
      int idx;//该节区索引值
    };

    3.module_stat结构记录每一个模块的信息
    struct module_stat {
     char *name;//模块名称
     unsigned long addr;//模块地址
     unsigned long modstruct; /* COMPAT_2_0! *//* depends on architecture? */
     unsigned long size;//模块大小
     unsigned long flags;//标志
     long usecount;//模块计数
     size_t nsyms;//模块中的符号个数
     struct module_symbol *syms;//指向模块符号
     size_t nrefs;//模块依赖其他模块的个数
     struct module_stat **refs;//依赖的模块数组
     unsigned long status;//模块状态
    };

    4.
    struct load_info {
     Elf_Ehdr *hdr;//指向elf头
     unsigned long len;
     Elf_Shdr *sechdrs;//指向节区头
     char *secstrings;//指向节区名称的字符串节区
     char *strtab;//指向符号节区
     unsigned long symoffs, stroffs;
     struct _ddebug *debug;
     unsigned int num_debug;
     bool sig_ok;
     struct {
      unsigned int sym, str, mod, vers, info, pcpu;
     } index;
    };

    5.代码分析

    1. int main(int argc, char **argv)
    2. {
    3.     /* List of possible program names and the corresponding mainline routines */
    4.     static struct { char *name; int (*handler)(int, char **); } mains[] =
    5.     {
    6.         { "insmod", &insmod_main },
    7. #ifdef COMBINE_modprobe
    8.         { "modprobe", &modprobe_main },
    9. #endif
    10. #ifdef COMBINE_rmmod
    11.     { "rmmod", &rmmod_main },
    12. #endif
    13. #ifdef COMBINE_ksyms
    14.     { "ksyms", &ksyms_main },
    15. #endif
    16. #ifdef COMBINE_lsmod
    17.     { "lsmod", &lsmod_main },
    18. #endif
    19. #ifdef COMBINE_kallsyms
    20.     { "kallsyms", &kallsyms_main },
    21. #endif
    22.     };
    23.     #define MAINS_NO (sizeof(mains)/sizeof(mains[0]))
    24.     static int mains_match;
    25.     static int mains_which;
    26.     
    27.     char *p = strrchr(argv[0], '/');//查找‘/’字符出现的位置
    28.     char error_id1[2048] = "The ";        /* Way oversized */
    29.     char error_id2[2048] = "";        /* Way oversized */
    30.     int i;
    31.     
    32.     p = p ? p + 1 : argv[0];//得到命令符,这里是insmod命令
    33.     
    34.     for (i = 0; i < MAINS_NO; ++i) {
    35.      if (i) {
    36.      xstrcat(error_id1, "/", sizeof(error_id1));//字符串连接函数
    37.      if (i == MAINS_NO-1)
    38.          xstrcat(error_id2, " or ", sizeof(error_id2));
    39.      else
    40.          xstrcat(error_id2, ", ", sizeof(error_id2));
    41.      }
    42.      xstrcat(error_id1, mains[i].name, sizeof(error_id1));
    43.      xstrcat(error_id2, mains[i].name, sizeof(error_id2));
    44.      if (strstr(p, mains[i].name)) {//命令跟数组的数据比较
    45.          ++mains_match;//insmod命令时,mains_match=1
    46.          mains_which = i;//得到insmod命令所在数组的位置,insmod命令为0
    47.      }
    48.     }
    49.     
    50.     /* Finish the error identifiers */
    51.     if (MAINS_NO != 1)
    52.         xstrcat(error_id1, " combined", sizeof(error_id1));
    53.     xstrcat(error_id1, " binary", sizeof(error_id1));
    54.     
    55.     if (mains_match == 0 && MAINS_NO == 1)
    56.         ++mains_match;        /* Not combined, any name will do */
    57.         
    58.     if (mains_match == 0) {
    59.         error("%s does not have a recognisable name, ""the name must contain one of %s.",error_id1, error_id2);
    60.         return(1);
    61.     }
    62.     else if (mains_match > 1) {
    63.         error("%s has an ambiguous name, it must contain %s%s.", error_id1, MAINS_NO == 1 ? "" : "exactly one of ", error_id2);
    64.         return(1);
    65.     }
    66.     else//mains_match=1,表示在数组中找到对应的指令
    67.         return((mains[mains_which].handler)(argc, argv));//调用insmod_main()函数
    68. }
    69. int insmod_main(int argc, char **argv)
    70. {
    71.     if (arch64())
    72.         return insmod_main_64(argc, argv);
    73.     else
    74.       return insmod_main_32(argc, argv);
    75. }
    76. #if defined(COMMON_3264) && defined(ONLY_32)
    77. #define INSMOD_MAIN insmod_main_32    /* 32 bit version */
    78. #elif defined(COMMON_3264) && defined(ONLY_64)
    79. #define INSMOD_MAIN insmod_main_64    /* 64 bit version */
    80. #else
    81. #define INSMOD_MAIN insmod_main        /* Not common code */
    82. #endif
    83. int INSMOD_MAIN(int argc, char **argv)
    84. {
    85.     int k_version;
    86.     int k_crcs;
    87.     char k_strversion[STRVERSIONLEN];
    88.     struct option long_opts[] = {
    89.      {"force", 0, 0, 'f'},
    90.      {"help", 0, 0, 'h'},
    91.      {"autoclean", 0, 0, 'k'},
    92.      {"lock", 0, 0, 'L'},
    93.      {"map", 0, 0, 'm'},
    94.      {"noload", 0, 0, 'n'},
    95.      {"probe", 0, 0, 'p'},
    96.      {"poll", 0, 0, 'p'},    /* poll is deprecated, remove in 2.5 */
    97.      {"quiet", 0, 0, 'q'},
    98.      {"root", 0, 0, 'r'},
    99.      {"syslog", 0, 0, 's'},
    100.      {"kallsyms", 0, 0, 'S'},
    101.      {"verbose", 0, 0, 'v'},
    102.      {"version", 0, 0, 'V'},
    103.      {"noexport", 0, 0, 'x'},
    104.      {"export", 0, 0, 'X'},
    105.      {"noksymoops", 0, 0, 'y'},
    106.      {"ksymoops", 0, 0, 'Y'},
    107.      {"persist", 1, 0, 'e'},
    108.      {"numeric-only", 1, 0, 'N'},
    109.      {"name", 1, 0, 'o'},
    110.      {"blob", 1, 0, 'O'},
    111.      {"prefix", 1, 0, 'P'},
    112.      {0, 0, 0, 0}
    113.     };
    114.     char *m_name = NULL;
    115.     char *blob_name = NULL;        /* Save object as binary blob */
    116.     int m_version;
    117.     ElfW(Addr) m_addr;
    118.     unsigned long m_size;
    119.     int m_crcs;
    120.     char m_strversion[STRVERSIONLEN];
    121.     char *filename;
    122.     char *persist_name = NULL;    /* filename to hold any persistent data */
    123.     int fp;
    124.     struct obj_file *f;
    125.     struct obj_section *kallsyms = NULL, *archdata = NULL;
    126.     int o;
    127.     int noload = 0;
    128.     int dolock = 1; /*Note: was: 0; */
    129.     int quiet = 0;
    130.     int exit_status = 1;
    131.     int force_kallsyms = 0;
    132.     int persist_parms = 0;    /* does module have persistent parms? */
    133.     int i;
    134.     int gpl;
    135.     
    136.     error_file = "insmod";
    137.     
    138.     /* To handle repeated calls from combined modprobe */
    139.     errors = optind = 0;
    140.     
    141.     /* Process the command line. */
    142.     while ((o = getopt_long(argc, argv, "fhkLmnpqrsSvVxXyYNe:o:O:P:R:",&long_opts[0], NULL)) != EOF)
    143.      switch (o) {
    144.      case 'f':    /* force loading */
    145.      flag_force_load = 1;
    146.      break;
    147.      case 'h': /* Print the usage message. */
    148.      insmod_usage();
    149.      break;
    150.      case 'k':    /* module loaded by kerneld, auto-cleanable */
    151.      flag_autoclean = 1;
    152.      break;
    153.      case 'L':    /* protect against recursion. */
    154.      dolock = 1;
    155.      break;
    156.      case 'm':    /* generate load map */
    157.      flag_load_map = 1;
    158.      break;
    159.      case 'n':    /* don't load, just check */
    160.      noload = 1;
    161.      break;
    162.      case 'p':    /* silent probe mode */
    163.      flag_silent_probe = 1;
    164.      break;
    165.      case 'q':    /* Don't print unresolved symbols */
    166.      quiet = 1;
    167.      break;
    168.      case 'r':    /* allow root to load non-root modules */
    169.      root_check_off = !root_check_off;
    170.      break;
    171.      case 's':    /* start syslog */
    172.      setsyslog("insmod");
    173.      break;
    174.      case 'S':    /* Force kallsyms */
    175.      force_kallsyms = 1;
    176.      break;
    177.      case 'v':    /* verbose output */
    178.      flag_verbose = 1;
    179.      break;
    180.      case 'V':
    181.      fputs("insmod version " MODUTILS_VERSION " ", stderr);
    182.      break;
    183.      case 'x':    /* do not export externs */
    184.      flag_export = 0;
    185.      break;
    186.      case 'X':    /* do export externs */
    187.     #ifdef HAS_FUNCTION_DESCRIPTORS
    188.      fputs("This architecture has function descriptors, exporting everything is unsafe "
    189.      "You must explicitly export the desired symbols with EXPORT_SYMBOL() ", stderr);
    190.     #else
    191.      flag_export = 1;
    192.     #endif
    193.      break;
    194.      case 'y':    /* do not define ksymoops symbols */
    195.      flag_ksymoops = 0;
    196.      break;
    197.      case 'Y':    /* do define ksymoops symbols */
    198.      flag_ksymoops = 1;
    199.      break;
    200.      case 'N':    /* only check numeric part of kernel version */
    201.      flag_numeric_only = 1;
    202.      break;
    203.     
    204.      case 'e':    /* persistent data filename */
    205.      free(persist_name);
    206.      persist_name = xstrdup(optarg);
    207.      break;
    208.      case 'o':    /* name the output module */
    209.      m_name = optarg;
    210.      break;
    211.      case 'O':    /* save the output module object */
    212.      blob_name = optarg;
    213.      break;
    214.      case 'P':    /* use prefix on crc */
    215.      set_ncv_prefix(optarg);
    216.      break;
    217.     
    218.      default:
    219.      insmod_usage();
    220.      break;
    221.      }
    222.     
    223.     if (optind >= argc) {//参数为0,则输出insmod用法介绍
    224.         insmod_usage();
    225.     }
    226.     filename = argv[optind++];//获得要加载的模块路径名
    227.     
    228.     if (config_read(0, NULL, "", NULL) < 0) {//modutil配置相关???
    229.         error("Failed handle configuration");
    230.   }
    231.     //清空persist_name 
    232.   if (persist_name && !*persist_name &&(!persistdir || !*persistdir)) {
    233.     free(persist_name);
    234.     persist_name = NULL;
    235.     if (flag_verbose) {
    236.         lprintf("insmod: -e "" ignored, no persistdir");
    237.       ++warnings;
    238.     }
    239.   }
    240.   if (m_name == NULL) {
    241.      size_t len;
    242.      char *p;
    243.         
    244.         //根据模块的路径名获取模块的名称
    245.      if ((p = strrchr(filename, '/')) != NULL)//找到最后一个'/'的位置
    246.          p++;
    247.      else
    248.          p = filename;
    249.          
    250.      len = strlen(p);
    251.      //去除模块名的后缀,保存在m_name中
    252.      if (len > 2 && p[len - 2] == '.' && p[len - 1] == 'o')
    253.          len -= 2;
    254.      else if (len > 4 && p[len - 4] == '.' && p[len - 3] == 'm'&& p[len - 2] == 'o' && p[len - 1] == 'd')
    255.          len -= 4;
    256. #ifdef CONFIG_USE_ZLIB
    257.      else if (len > 5 && !strcmp(p + len - 5, ".o.gz"))
    258.          len -= 5;
    259. #endif
    260.     
    261.      m_name = xmalloc(len + 1);
    262.      memcpy(m_name, p, len);//模块名称拷贝到m_name[]中
    263.      m_name[len] = '';
    264.   }
    265.   //根据模块路径,检查模块是否存在
    266.   if (!strchr(filename, '/') && !strchr(filename, '.')) {
    267.      char *tmp = search_module_path(filename);//查找模块路径???
    268.      if (tmp == NULL) {
    269.          error("%s: no module by that name found", filename);
    270.          return 1;
    271.      }
    272.      filename = tmp;
    273.      lprintf("Using %s", filename);
    274.   } else if (flag_verbose)
    275.       lprintf("Using %s", filename);
    276.   //打开要加载的模块文件
    277.   if ((fp = gzf_open(filename, O_RDONLY)) == -1) {
    278.       error("%s: %m", filename);
    279.       return 1;
    280.   }
    281.   /* Try to prevent multiple simultaneous loads. */
    282.   if (dolock)
    283.       flock(fp, LOCK_EX);
    284.   /*
    285.   type的三种类型,影响get_kernle_info的流程。
    286.   #define K_SYMBOLS 1 //Want info about symbols
    287.   #define K_INFO 2 Want extended module info
    288.   #define K_REFS 4 Want info about references
    289.   */
    290.   //负责取得kernel中先以注册的modules,放入module_stat中,并将kernel实现的各个symbol放入ksyms中,个数为ksyms。get_kernel_info最终调用new_get_kernel_info
    291.   if (!get_kernel_info(K_SYMBOLS))
    292.       goto out;
    293.   set_ncv_prefix(NULL);//判断symbol name中是否有前缀,象_smp之类,这里没有。
    294.   for (i = 0; !noload && i < n_module_stat; ++i) {//判断是否有同名的模块存在
    295.         if (strcmp(module_stat[i].name, m_name) == 0) {//遍历kernel中所有的模块,比较名称
    296.             error("a module named %s already exists", m_name);
    297.             goto out;
    298.         }
    299.   }
    300.   error_file = filename;
    301.   if ((f = obj_load(fp, ET_REL, filename)) == NULL)//将模块文件读入到struct obj_file结构f
    302.       goto out;
    303.   if (check_gcc_mismatch(f, filename))//检查编译器版本
    304.       goto out;
    305.   //检查内核和module的版本信息
    306.   k_version = get_kernel_version(k_strversion);
    307.   m_version = get_module_version(f, m_strversion);
    308.   if (m_version == -1) {
    309.         error("couldn't find the kernel version the module was compiled for");
    310.       goto out;
    311.   }
    312.     
    313.     //接下来还要测试内核和模块是否使用了版本的附加信息
    314.   k_crcs = is_kernel_checksummed();
    315.   m_crcs = is_module_checksummed(f);
    316.   if ((m_crcs == 0 || k_crcs == 0) &&strncmp(k_strversion, m_strversion, STRVERSIONLEN) != 0) {
    317.     if (flag_force_load) {
    318.         lprintf("Warning: kernel-module version mismatch "
    319.           " %s was compiled for kernel version %s "
    320.           " while this kernel is version %s",
    321.           filename, m_strversion, k_strversion);
    322.         ++warnings;
    323.     } else {
    324.         if (!quiet)
    325.           error("kernel-module version mismatch "
    326.             " %s was compiled for kernel version %s "
    327.             " while this kernel is version %s.",
    328.             filename, m_strversion, k_strversion);
    329.         goto out;
    330.     }
    331.   }
    332.   if (m_crcs != k_crcs)//设置新的符号比较函数和hash函数,重构hash表(即symtab表)。
    333.         obj_set_symbol_compare(f, ncv_strcmp, ncv_symbol_hash);
    334.   //检查GPL license
    335.   gpl = obj_gpl_license(f, NULL) == 0;
    336.   
    337.   //替换模块中的symbol值为其他已经存在的模块中相同符号的值
    338.   //如果内核模块中有该符号,则将该符号的value该为内核中(ksyms[])的符号值
    339.   //修改的是hash符号表中或者局部符号表中的符号值
    340.   add_kernel_symbols(f, gpl);
    341. #ifdef COMPAT_2_0//linux 内核2.0版本以前
    342.   if (k_new_syscalls ? !create_this_module(f, m_name): !old_create_mod_use_count(f))
    343.         goto out;
    344. #else
    345.   if (!create_this_module(f, m_name))//创建.this节区,添加一个"__this_module"符号
    346.         goto out;
    347. #endif
    348.     
    349.     //这个函数的作用是创建文件的.GOT段,.GOT全称是global offset table。在这个节区里保存的是绝对地址,这些地址不受重定位的影响。如果程序需要直接引用符号的绝对地址,这些符号就必须在.GOT段中出现
    350.   arch_create_got(f);
    351.   if (!obj_check_undefineds(f, quiet)) {//检查是否还有未解析的symbol
    352.     if (!gpl && !quiet) {
    353.       if (gplonly_seen)
    354.           error(" "
    355.                     "Hint: You are trying to load a module without a GPL compatible license "
    356.                     " and it has unresolved symbols. The module may be trying to access "
    357.                     " GPLONLY symbols but the problem is more likely to be a coding or "
    358.                     " user error. Contact the module supplier for assistance, only they "
    359.                     " can help you. ");
    360.       else
    361.           error(" "
    362.                     "Hint: You are trying to load a module without a GPL compatible license "
    363.                     " and it has unresolved symbols. Contact the module supplier for "
    364.                     " assistance, only they can help you. ");
    365.     }
    366.     goto out;
    367.   }
    368.   obj_allocate_commons(f);//处理未分配资源的符号
    369.     
    370.     //检查模块参数,即检查那些模块通过module_param(type, charp, S_IRUGO);声明的参数
    371.   check_module_parameters(f, &persist_parms);
    372.   check_tainted_module(f, noload);//???
    373.   if (optind < argc) {//如果命令行里带了参数,处理命令行参数
    374.         if (!process_module_arguments(f, argc - optind, argv + optind, 1))
    375.             goto out;
    376.   }
    377.   //将符号“cleanup_module”,“init_module”,“kernel_version”的属性改为local(局部),从而使其外部不可见
    378.   hide_special_symbols(f);
    379.     
    380.     //如果命令行参数来自文件,将文件名保存好,下面要从那里读出参数值
    381.   if (persist_parms && persist_name && *persist_name) {
    382.         f->persist = persist_name;
    383.         persist_name = NULL;
    384.   }
    385.     //防止-e""这样的恶作剧
    386.   if (persist_parms &&persist_name && !*persist_name) {
    387.     int j, l = strlen(filename);
    388.     char *relative = NULL;
    389.     char *p;
    390.     for (i = 0; i < nmodpath; ++i) {
    391.      p = modpath[i].path;
    392.      j = strlen(p);
    393.      while (j && p[j] == '/')
    394.          --j;
    395.      if (j < l && strncmp(filename, p, j) == 0 && filename[j] == '/') {
    396.          while (filename[j] == '/')
    397.          ++j;
    398.          relative = xstrdup(filename+j);
    399.          break;
    400.      }
    401.     }
    402.     if (relative) {
    403.       i = strlen(relative);
    404.       if (i > 3 && strcmp(relative+i-3, ".gz") == 0)
    405.           relative[i -= 3] = '';
    406.       if (i > 2 && strcmp(relative+i-2, ".o") == 0)
    407.           relative[i -= 2] = '';
    408.       else if (i > 4 && strcmp(relative+i-4, ".mod") == 0)
    409.           relative[i -= 4] = '';
    410.       f->persist = xmalloc(strlen(persistdir) + 1 + i + 1);
    411.       strcpy(f->persist, persistdir);    /* safe, xmalloc */
    412.       strcat(f->persist, "/");    /* safe, xmalloc */
    413.       strcat(f->persist, relative);    /* safe, xmalloc */
    414.       free(relative);
    415.     }
    416.     else
    417.             error("Cannot calculate persistent filename");
    418.   }
    419.     //接下来是一些健康检查
    420.   if (f->persist && *(f->persist) != '/') {
    421.      error("Persistent filenames must be absolute, ignoring '%s'", f->persist);
    422.      free(f->persist);
    423.      f->persist = NULL;
    424.   }
    425.   if (f->persist && !flag_ksymoops) {
    426.     error("has persistent data but ksymoops symbols are not available");
    427.     free(f->persist);
    428.     f->persist = NULL;
    429.   }
    430.   if (f->persist && !k_new_syscalls) {
    431.     error("has persistent data but the kernel is too old to support it");
    432.     free(f->persist);
    433.     f->persist = NULL;
    434.   }
    435.   if (persist_parms && flag_verbose) {
    436.     if (f->persist)
    437.         lprintf("Persist filename '%s'", f->persist);
    438.     else
    439.         lprintf("No persistent filename available");
    440.   }
    441.   if (f->persist) {
    442.      FILE *fp = fopen(f->persist, "r");
    443.      if (!fp) {
    444.      if (flag_verbose)
    445.      lprintf("Cannot open persist file '%s' %m", f->persist);
    446.      }
    447.      else {
    448.      int pargc = 0;
    449.      char *pargv[1000];    /* hard coded but big enough */
    450.      char line[3000];    /* hard coded but big enough */
    451.      char *p;
    452.      while (fgets(line, sizeof(line), fp)) {
    453.      p = strchr(line, ' ');
    454.      if (!p) {
    455.      error("Persistent data line is too long %s", line);
    456.      break;
    457.      }
    458.      *p = '';
    459.      p = line;
    460.      while (isspace(*p))
    461.      ++p;
    462.      if (!*p || *p == '#')
    463.      continue;
    464.      if (pargc == sizeof(pargv)/sizeof(pargv[0])) {
    465.      error("More than %d persistent parameters", pargc);
    466.      break;
    467.      }
    468.      pargv[pargc++] = xstrdup(p);
    469.      }
    470.      fclose(fp);
    471.      if (!process_module_arguments(f, pargc, pargv, 0))
    472.      goto out;
    473.      while (pargc--)
    474.      free(pargv[pargc]);
    475.      }
    476.   }
    477.     
    478.     //ksymoops 是一个调试辅助工具,它将试图将代码转换为指令并将堆栈值映射到内核符号。
    479.   if (flag_ksymoops)
    480.         add_ksymoops_symbols(f, filename, m_name);
    481.   if (k_new_syscalls)//k_new_syscalls标志用于测试内核版本
    482.         create_module_ksymtab(f);//创建模块要导出的符号节区ksymtab,并将要导出的符号加入该节区
    483.   //创建名为“__archdata” (宏 ARCH_SEC_NAME 的定义)的段
    484.   if (add_archdata(f, &archdata))
    485.         goto out;
    486.  //如果symbol使用的都是kernel提供的,就添加一个.kallsyms节区
    487.  //这个函数主要是处理内核导出符号。
    488.   if (add_kallsyms(f, &kallsyms, force_kallsyms))
    489.         goto out;
    490.   /**** No symbols or sections to be changed after kallsyms above ***/
    491.   if (errors)
    492.         goto out;
    493.   //如果flag_slient_probe已经设置,说明我们不想真正安装模块,只是想测试一下,那么到这里测试已经完成了,模块一切正常.
    494.   if (flag_silent_probe) {
    495.         exit_status = 0;
    496.         goto out;
    497.   }
    498.   
    499.   //计算载入模块所需的大小,即各个节区的大小和
    500.   m_size = obj_load_size(f);
    501.   
    502.   //如果noload设置了,那么我们选择不真正加载模块。随便给加载地址就完了.
    503.   if (noload) {
    504.        m_addr = 0x12340000;
    505.   } else {
    506.     errno = 0;
    507.     //调用sys_create_module系统调用创建模块,分配module的空间,返回模块在内核空间的地址.这里的module结构不是内核使用的那个,它定义在./modutilst-2.4.0/include/module.h中。函数最终会调用系统调用sys_create_module,生成一个模块对象,并链入模块的内核链表
    508.     //模块对象的大小就是各个节区大小的和,这里为什么分配的空间m_size不是sizeof(module)+各个节区大小的和?因为第一个节区.this的大小正好就是sizeof(module),所以第一个节区就是struct module结构。
    509.     //注意:区分后边还有一次在用户空间为模块分配空间,然后先把模块section拷贝到用户空间的模块影像中,然后再由sys_init_module()函数将用户空间的模块映像拷贝到内核空间的模块地址,即这里的m_addr。
    510.     m_addr = create_module(m_name, m_size);
    511.     m_addr |= arch_module_base (f);//#define arch_module_base(m) ((ElfW(Addr))0)
    512.     //检查是否成功创建module结构
    513.     switch (errno) {
    514.     case 0:
    515.         break;
    516.     case EEXIST:
    517.       if (dolock) {
    518.           exit_status = 0;
    519.           goto out;
    520.       }
    521.       error("a module named %s already exists", m_name);
    522.       goto out;
    523.     case ENOMEM:
    524.         error("can't allocate kernel memory for module; needed %lu bytes",m_size);
    525.       goto out;
    526.     default:
    527.       error("create_module: %m");
    528.       goto out;
    529.     }
    530.   }
    531.     //如果模块运行时参数使用了文件,而且需要真正加载
    532.   if (f->persist && !noload) {
    533.     struct {
    534.         struct module m;
    535.         int data;
    536.     } test_read;
    537.     memset(&test_read, 0, sizeof(test_read));
    538.     test_read.m.size_of_struct = -sizeof(test_read.m); /* -ve size => read, not write */
    539.     test_read.m.read_start = m_addr + sizeof(struct module);
    540.     test_read.m.read_end = test_read.m.read_start + sizeof(test_read.data);
    541.     if (sys_init_module(m_name, (struct module *) &test_read)) {
    542.      int old_errors = errors;
    543.      error("has persistent data but the kernel is too old to support it."
    544.      " Expect errors during rmmod as well");
    545.      errors = old_errors;
    546.     }
    547.   }
    548.     
    549.     //模块在内核的地址.而在模块elf文件里,节区在内存的位置是假设文件从0地址加载而得出的,现在就要根据base值调整。base就是create_module时分配的地址m_addr
    550.   if (!obj_relocate(f, m_addr)) {
    551.       if (!noload)
    552.         delete_module(m_name);
    553.       goto out;
    554.   }
    555.     //至此相当于磁盘中的elf文件格式的.ko文件的内容,已经全部加载到内存中,需要重定位的符号已经进行了重定位,符号地址变成了真正的在内存中的地址,即绝对地址。
    556.     
    557.   /* Do archdata again, this time we have the final addresses */
    558.   if (add_archdata(f, &archdata))
    559.           goto out;
    560.   //用绝对地址重新生成kallsyms段的内容
    561.   if (add_kallsyms(f, &kallsyms, force_kallsyms))
    562.           goto out;
    563. #ifdef COMPAT_2_0//2.0以前的版本
    564.   if (k_new_syscalls)
    565.       init_module(m_name, f, m_size, blob_name, noload, flag_load_map);
    566.   else if (!noload)
    567.       old_init_module(m_name, f, m_size);
    568. #else
    569.   init_module(m_name, f, m_size, blob_name, noload, flag_load_map);
    570. #endif
    571.   if (errors) {
    572.       if (!noload)
    573.         delete_module(m_name);
    574.       goto out;
    575.   }
    576.   if (warnings && !noload)
    577.       lprintf("Module %s loaded, with warnings", m_name);
    578.   exit_status = 0;
    579. out:
    580.   if (dolock)
    581.           flock(fp, LOCK_UN);
    582.   close(fp);
    583.   if (!noload)
    584.           snap_shot(NULL, 0);
    585.   return exit_status;
    586. }
    587. static int new_get_kernel_info(int type)
    588. {
    589.   struct module_stat *modules;
    590.   struct module_stat *m;
    591.   struct module_symbol *syms;
    592.   struct module_symbol *s;
    593.   size_t ret;
    594.   size_t bufsize;
    595.   size_t nmod;
    596.   size_t nsyms;
    597.   size_t i;
    598.   size_t j;
    599.   char *module_names;
    600.   char *mn;
    601.   drop();//首先清除module_stat内容,module_stat是个全局变量,保存模块信息
    602.     //指针分配空间
    603.   module_names = xmalloc(bufsize = 256);
    604.   //取得系统中现有所有的module名称,ret返回个数,module_names返回各个module名称,字符0分割
    605.   while (query_module(NULL, QM_MODULES, module_names, bufsize, &ret)) {
    606.      if (errno != ENOSPC) {
    607.      error("QM_MODULES: %m ");
    608.      return 0;
    609.      }
    610.      /*
    611.      会调用realloc(void *mem_address, unsigned int newsize)函数,此先判断当前的指针是否有足够的连续空间,如果有,扩大mem_address指向的地址,并且将mem_address返回,如果空间不够,先按照newsize指定的大小分配空间,将原有数据从头到尾拷贝到新分配的内存区域,而后释放原来mem_address所指内存区域(注意:原来指针是自动释放,不需要使用free),同时返回新分配的内存区域的首地址。即重新分配存储器块的地址。
    612.      */
    613.     module_names = xrealloc(module_names, bufsize = ret);
    614.   }
    615.   module_name_list = module_names;//指向系统中所有模块名称的起始地址
    616.   l_module_name_list = bufsize;//所有模块名称的大小,即module_names大小
    617.   n_module_stat = nmod = ret;//返回模块个数
    618.   //分配空间,地址付给全局变量module_stat
    619.   module_stat = modules = xmalloc(nmod * sizeof(struct module_stat));
    620.   memset(modules, 0, nmod * sizeof(struct module_stat));
    621.   //循环取得各个module的信息,QM_INFO的使用。
    622.   for (i = 0, mn = module_names, m = modules;i < nmod;++i, ++m, mn += strlen(mn) + 1) {
    623.       struct module_info info;
    624.       //info包括module的地址,大小,flag和使用计数器。
    625.       m->name = mn;//模块名称给module_stat结构
    626.       if (query_module(mn, QM_INFO, &info, sizeof(info), &ret)) {
    627.           if (errno == ENOENT) {
    628.               m->flags = NEW_MOD_DELETED;
    629.               continue;
    630.           }
    631.           error("module %s: QM_INFO: %m", mn);
    632.           return 0;
    633.       }
    634.       m->addr = info.addr;//模块地址给module_stat结构
    635.       if (type & K_INFO) {//取得module的信息
    636.           m->size = info.size;
    637.           m->flags = info.flags;
    638.           m->usecount = info.usecount;
    639.           m->modstruct = info.addr;
    640.       }//将info值传给module_stat结构
    641.       if (type & K_REFS) {//取得module的引用关系
    642.           int mm;
    643.           char *mrefs;
    644.           char *mr;
    645.           mrefs = xmalloc(bufsize = 64);
    646.           while (query_module(mn, QM_REFS, mrefs, bufsize, &ret)) {//查找mn模块引用的模块名
    647.               if (errno != ENOSPC) {
    648.                   error("QM_REFS: %m");
    649.                   return 1;
    650.               }
    651.               mrefs = xrealloc(mrefs, bufsize = ret);
    652.           }
    653.           for (j = 0, mr = mrefs;j < ret;++j, mr += strlen(mr) + 1) {
    654.               for (mm = 0; mm < i; ++mm) {
    655.                   if (strcmp(mr, module_stat[mm].name) == 0) {
    656.                       m->nrefs += 1;
    657.                       m->refs = xrealloc(m->refs, m->nrefs * sizeof(struct module_stat **));
    658.                       m->refs[m->nrefs - 1] = module_stat + mm;//引用的模块名
    659.                       break;
    660.                   }
    661.               }
    662.           }
    663.           free(mrefs);
    664.       }
    665.             
    666.             //这里是遍历内核中其他模块的所有符号
    667.       if (type & K_SYMBOLS) { /* 取得symbol信息,正是我们要得*/
    668.         syms = xmalloc(bufsize = 1024);
    669.         //取得mn模块的符号信息,保存在syms数组中
    670.         while (query_module(mn, QM_SYMBOLS, syms, bufsize, &ret)) {
    671.           if (errno == ENOSPC) {
    672.               syms = xrealloc(syms, bufsize = ret);
    673.               continue;
    674.           }
    675.           if (errno == ENOENT) {
    676.               m->flags = NEW_MOD_DELETED;
    677.               free(syms);
    678.               goto next;
    679.           } else {
    680.               error("module %s: QM_SYMBOLS: %m", mn);
    681.               return 0;
    682.           }
    683.         }
    684.         nsyms = ret;
    685.         //syms是module_symbol结构,ret返回symbol个数
    686.         m->nsyms = nsyms;//符号个数
    687.         m->syms = syms;//符号信息
    688.         //name原来只是一个结构内的偏移,加上结构地址为真正的字符串地址
    689.         for (j = 0, s = syms; j < nsyms; ++j, ++s)
    690.             s->name += (unsigned long) syms;
    691.       }
    692.       next:
    693.   }
    694.     //这里是取得内核符号
    695.   if (type & K_SYMBOLS) { /* Want info about symbols */
    696.       syms = xmalloc(bufsize = 16 * 1024);
    697.       //name为NULL,返回内核符号信息
    698.       while (query_module(NULL, QM_SYMBOLS, syms, bufsize, &ret)) {
    699.         if (errno != ENOSPC) {
    700.             error("kernel: QM_SYMBOLS: %m");
    701.             return 0;
    702.         }
    703.         syms = xrealloc(syms, bufsize = ret);//扩展空间
    704.       }
    705.       //将值返回给nksyms和ksyms两个全局变量存储。
    706.       nksyms = nsyms = ret;//内核符号个数
    707.       ksyms = syms;//内核符号
    708.       /* name原来只是一个结构内的偏移,加上结构地址为真正的字符串地址 */
    709.       for (j = 0, s = syms; j < nsyms; ++j, ++s)
    710.           s->name += (unsigned long) syms;
    711.   }
    712.   return 1;
    713. }
    714. struct obj_file *obj_load (int fp, Elf32_Half e_type, const char *filename)
    715. {
    716.   struct obj_file *f;
    717.   ElfW(Shdr) *section_headers;
    718.   int shnum, i;
    719.   char *shstrtab;
    720.   f = arch_new_file();//创建一个新的obj_file结构
    721.   memset(f, 0, sizeof(*f));
    722.   f->symbol_cmp = strcmp;//设置symbol名的比较函数就是strcmp
    723.   f->symbol_hash = obj_elf_hash;//设置计算symbol hash值的函数
    724.   f->load_order_search_start = &f->load_order;//??
    725.   gzf_lseek(fp, 0, SEEK_SET);//文件指针设置到文件头
    726.   //取得object文件的ELF头结构。
    727.   if (gzf_read(fp, &f->header, sizeof(f->header)) != sizeof(f->header))
    728.   {
    729.     error("cannot read ELF header from %s", filename);
    730.     return NULL;
    731.   }
    732.     
    733.     //判断ELF的magic,是否是ELF文件格式
    734.   if (f->header.e_ident[EI_MAG0] != ELFMAG0
    735.       || f->header.e_ident[EI_MAG1] != ELFMAG1
    736.       || f->header.e_ident[EI_MAG2] != ELFMAG2
    737.       || f->header.e_ident[EI_MAG3] != ELFMAG3)
    738.   {
    739.       error("%s is not an ELF file", filename);
    740.       return NULL;
    741.   }
    742.   //检查architecture
    743.   if (f->header.e_ident[EI_CLASS] != ELFCLASSM//i386的机器上为ELFCLASS32,表示32bit
    744.       || f->header.e_ident[EI_DATA] != ELFDATAM//此处值为ELFDATA2LSB,表示编码方式
    745.       || f->header.e_ident[EI_VERSION] != EV_CURRENT//此值固定,表示版本
    746.       || !MATCH_MACHINE(f->header.e_machine))//机器类型
    747.   {
    748.       error("ELF file %s not for this architecture", filename);
    749.       return NULL;
    750.   }
    751.   //判断目标文件类型
    752.   if (f->header.e_type != e_type && e_type != ET_NONE)//.ko文件类型必为ET_REL
    753.   {
    754.     switch (e_type) {
    755.      case ET_REL:
    756.              error("ELF file %s not a relocatable object", filename);
    757.              break;
    758.      case ET_EXEC:
    759.          error("ELF file %s not an executable object", filename);
    760.          break;
    761.      default:
    762.              error("ELF file %s has wrong type, expecting %d got %d",
    763.      filename, e_type, f->header.e_type);
    764.              break;
    765.     }
    766.     return NULL;
    767.   }
    768.     
    769.     //检查elf文件头指定的节区头的大小是否一致
    770.   if (f->header.e_shentsize != sizeof(ElfW(Shdr)))
    771.   {
    772.     error("section header size mismatch %s: %lu != %lu",filename,
    773.       (unsigned long)f->header.e_shentsize,
    774.       (unsigned long)sizeof(ElfW(Shdr)));
    775.     return NULL;
    776.   }
    777.   shnum = f->header.e_shnum;//文件中节区个数
    778.   f->sections = xmalloc(sizeof(struct obj_section *) * shnum);//为section开辟空间
    779.   memset(f->sections, 0, sizeof(struct obj_section *) * shnum);
    780.     
    781.     //每个节区都有一个节区头部表,为shnum个节区头部表分配空间
    782.   section_headers = alloca(sizeof(ElfW(Shdr)) * shnum);
    783.   gzf_lseek(fp, f->header.e_shoff, SEEK_SET);//指针移到节区头部表开始位置
    784.   //读取shnum个节区头部表(每个节区都有一个节区头部表)内容保存在section_headers中
    785.   if (gzf_read(fp, section_headers, sizeof(ElfW(Shdr))*shnum) != sizeof(ElfW(Shdr))*shnum)
    786.   {
    787.     error("error reading ELF section headers %s: %m", filename);
    788.     return NULL;
    789.   }
    790.   for (i = 0; i < shnum; ++i)//遍历所有的节区
    791.   {
    792.     struct obj_section *sec;
    793.     f->sections[i] = sec = arch_new_section();//分配内存给每个section
    794.     memset(sec, 0, sizeof(*sec));
    795.     sec->header = section_headers[i];//设置obj_section结构的sec的header指向本节区的节区头部表
    796.     sec->idx = i;//节区索引
    797.     switch (sec->header.sh_type)//section的类型
    798.      {
    799.          case SHT_NULL:
    800.          case SHT_NOTE:
    801.          case SHT_NOBITS:/* ignore */
    802.          break;        
    803.          case SHT_PROGBITS:
    804.          case SHT_SYMTAB:
    805.          case SHT_STRTAB:
    806.          case SHT_RELM://将以上各种类型的section内容读到sec->contents结构中。
    807.          if (sec->header.sh_size > 0)
    808.      {
    809.      sec->contents = xmalloc(sec->header.sh_size);
    810.      //指针移到节区的第一个字节与文件头之间的偏移
    811.      gzf_lseek(fp, sec->header.sh_offset, SEEK_SET);
    812.      //读取节区中内容
    813.      if (gzf_read(fp, sec->contents, sec->header.sh_size) != sec->header.sh_size)
    814.          {
    815.          error("error reading ELF section data %s: %m", filename);
    816.          return NULL;
    817.          }
    818.      }
    819.          else
    820.          sec->contents = NULL;
    821.          break;
    822.          //描述relocation的section
    823. #if SHT_RELM == SHT_REL
    824.          case SHT_RELA:
    825.          if (sec->header.sh_size) {
    826.          error("RELA relocations not supported on this architecture %s", filename);
    827.          return NULL;
    828.          }
    829.          break;
    830. #else
    831.          case SHT_REL:
    832.          if (sec->header.sh_size) {
    833.          error("REL relocations not supported on this architecture %s", filename);
    834.          return NULL;
    835.          }
    836.          break;
    837. #endif
    838.          default:
    839.          if (sec->header.sh_type >= SHT_LOPROC)
    840.      {
    841.      if (arch_load_proc_section(sec, fp) < 0)
    842.              return NULL;
    843.      break;
    844.      }
    845.         
    846.          error("can't handle sections of type %ld %s",(long)sec->header.sh_type, filename);
    847.          return NULL;
    848.       }
    849.   }
    850. //shstrndx存的是section字符串表的索引值,就是第几个section
    851. //shstrtab就是那个section了。找到节区名字符串节区,把字符串节区内容地址付给shstrtab指针
    852.   shstrtab = f->sections[f->header.e_shstrndx]->contents;
    853.   for (i = 0; i < shnum; ++i)
    854.   {
    855.     struct obj_section *sec = f->sections[i];
    856.     sec->name = shstrtab + sec->header.sh_name;//sh_name字段是节区头部字符串表节区的索引
    857.   }//根据strtab,取得每个section的名字
    858.     //遍历节区查找符号表
    859.   for (i = 0; i < shnum; ++i)
    860.   {
    861.     struct obj_section *sec = f->sections[i];
    862.     //也就是说即使modinfo和modstring有此标志位,也去掉。
    863.     if (strcmp(sec->name, ".modinfo") == 0 ||strcmp(sec->name, ".modstring") == 0)
    864.           sec->header.sh_flags &= ~SHF_ALLOC;//ALLOC表示此section是否占用内存,这两个节区不占用内存
    865.     if (sec->header.sh_flags & SHF_ALLOC)//此节区在进程执行过程中占用内存
    866.              obj_insert_section_load_order(f, sec);//确定section load的顺序,根据的是flag的类型加权得到优先级
    867.     switch (sec->header.sh_type)
    868.      {
    869.          case SHT_SYMTAB://符号表节区,就是.symtab节区
    870.          {
    871.      unsigned long nsym, j;
    872.      char *strtab;
    873.      ElfW(Sym) *sym;
    874.                 
    875.                 //节区的大小若不等于符号表结构的大小,则出错
    876.      if (sec->header.sh_entsize != sizeof(ElfW(Sym)))
    877.      {
    878.          error("symbol size mismatch %s: %lu != %lu",filename,(unsigned long)sec->header.sh_entsize,(unsigned long)sizeof(ElfW(Sym)));
    879.          return NULL;
    880.      }
    881.      
    882.      //计算符号表表项个数,nsym也就是symbol个数,我的fedcore有560个符号(结构)
    883.      nsym = sec->header.sh_size / sizeof(ElfW(Sym));
    884.      //sh_link是符号字符串表的索引值,f->sections[sec->header.sh_link]就是.strtab节区
    885.      strtab = f->sections[sec->header.sh_link]->contents;//符号字符串表节区的内容
    886.      sym = (ElfW(Sym) *) sec->contents;//符号表节区的内容Elf32_sym结构
    887.     
    888.      j = f->local_symtab_size = sec->header.sh_info;//本模块局部符号的size
    889.      f->local_symtab = xmalloc(j *= sizeof(struct obj_symbol *));//为本模块局部符号分配空间
    890.      memset(f->local_symtab, 0, j);
    891.     
    892.      //遍历要加载模块的符号表节区内容的符号Elf32_sym结构
    893.      for (j = 1, ++sym; j < nsym; ++j, ++sym)
    894.      {
    895.          const char *name;
    896.          if (sym->st_name)//有值就是符号字符串表strtab的索引值
    897.          name = strtab+sym->st_name;
    898.          else//如果为零,此symbol name是一个section的name,比如.rodata之类的
    899.          name = f->sections[sym->st_shndx]->name;
    900.          //obj_add_symbol将符号加入到f->symbab这个hash表中,sym->st_shndx是相关节区头部表索引。如果一个符号的取值引用了某个节区中的特定位置,那么它的节区索引成员(st_shndx)包含了其在节区头部表中的索引。(比如说符号“function_x”定义在节区.rodata中,则sym->st_shndx是节区.rodata的索引值,sym->st_value是指在该节区中的到符号位置的偏移,即符号“function_x”在模块中的地址由节区.rodata->contens+sym->st_value位置处的数值指定)
    901.          //局部符号会添加到f->local_symtab表中,其余符号会添加到hash表f->symtab中(),注意:局部符号也可能添加到hash表中
    902.          obj_add_symbol(f, name, j, sym->st_info, sym->st_shndx,sym->st_value, sym->st_size);
    903.          }
    904.          }
    905.              break;
    906.         }
    907.   }
    908.   //重定位是将符号引用与符号定义进行连接的过程。例如,当程序调用了一个函数时,相关的调用指令必须把控制传输到适当的目标执行地址。
    909.   for (i = 0; i < shnum; ++i)
    910.   {
    911.     struct obj_section *sec = f->sections[i];
    912.     switch (sec->header.sh_type)
    913.     {
    914.      case SHT_RELM://找到描述重定位的section
    915.       {
    916.         unsigned long nrel, j;
    917.         ElfW(RelM) *rel;
    918.         struct obj_section *symtab;
    919.         char *strtab;
    920.         if (sec->header.sh_entsize != sizeof(ElfW(RelM)))
    921.         {
    922.             error("relocation entry size mismatch %s: %lu != %lu",
    923.               filename,(unsigned long)sec->header.sh_entsize,
    924.               (unsigned long)sizeof(ElfW(RelM)));
    925.             return NULL;
    926.         }
    927.             //算出rel有几项,存到nrel中
    928.         nrel = sec->header.sh_size / sizeof(ElfW(RelM));
    929.         rel = (ElfW(RelM) *) sec->contents;
    930.         //rel的section中sh_link相关值是符号section的索引值,即.symtab符号节区
    931.         symtab = f->sections[sec->header.sh_link];
    932.         //而符号section中sh_link是符号字符串section的索引值,即找到.strtab节区
    933.         strtab = f->sections[symtab->header.sh_link]->contents;
    934.         //存储需要relocate的符号的rel的类型
    935.         for (j = 0; j < nrel; ++j, ++rel)
    936.         {
    937.      ElfW(Sym) *extsym;
    938.      struct obj_symbol *intsym;
    939.      unsigned long symndx;
    940.      symndx = ELFW(R_SYM)(rel->r_info);//取得要进行重定位的符号表索引
    941.      if(symndx)
    942.           {
    943.               //取得要进行重定位的符号(Elf32_sym结构)
    944.             extsym = ((ElfW(Sym) *) symtab->contents) + symndx;
    945.             //符号信息是局部的,别的文件不可见
    946.             if (ELFW(ST_BIND)(extsym->st_info) == STB_LOCAL)
    947.             {
    948.                 intsym = f->local_symtab[symndx];//要从局部符号表中获取
    949.             }
    950.             else//其他类型,从hash表中取
    951.             {
    952.      const char *name;
    953.      if (extsym->st_name)//有值就是符号字符串表.strtab的索引值
    954.      name = strtab + extsym->st_name;
    955.      else//如果为零,此symbol name是一个section的name,比如.rodata之类的
    956.      name = f->sections[extsym->st_shndx]->name;
    957.      //因为前边已添加到hash表中,从hash表中获取该要重定位的符号
    958.      intsym = obj_find_symbol(f, name);
    959.             }
    960.             intsym->r_type = ELFW(R_TYPE)(rel->r_info);//设置该符号的重定位类型,为以后进行符号重定位时使用
    961.           }
    962.         }
    963.       }
    964.      break;
    965.      }
    966.   }
    967.   f->filename = xstrdup(filename);
    968.   return f;
    969. }
    970. struct obj_symbol *obj_add_symbol (struct obj_file *f, const char *name, unsigned long symidx,int info, int secidx, ElfW(Addr) value, unsigned long size)
    971. {
    972.     //参数:name符号名,symidx符号索引值(在此模块中),secidx节区索引值,value符号值
    973.   struct obj_symbol *sym;
    974.   unsigned long hash = f->symbol_hash(name) % HASH_BUCKETS;//计算出hash值
    975.   int n_type = ELFW(ST_TYPE)(info);//要添加的符号类型
    976.   int n_binding = ELFW(ST_BIND)(info);//要添加的符号绑定类型,例如:STB_LOCAL或STB_GLOBAL
    977.     //遍历hash表中是否已添加了此符号,根据符号类型做不同处理
    978.   for (sym = f->symtab[hash]; sym; sym = sym->next)
    979.     if (f->symbol_cmp(sym->name, name) == 0)
    980.     {
    981.             int o_secidx = sym->secidx;
    982.             int o_info = sym->info;
    983.             int o_type = ELFW(ST_TYPE)(o_info);
    984.             int o_binding = ELFW(ST_BIND)(o_info);
    985.             
    986.             if (secidx == SHN_UNDEF)//如果要加入的符号的属性是SHN_UNDEF,即未定义,不用处理
    987.              return sym;
    988.             else if (o_secidx == SHN_UNDEF)//如果已加入的符号属性是SHN_UNDEF,则用新的符号替换。
    989.              goto found;
    990.             else if (n_binding == STB_GLOBAL && o_binding == STB_LOCAL)//新添加的符号是global,而old符号是局部符号,那么就将STB_GLOBAL符号替换掉STB_LOCAL 符号。
    991.             {    
    992.          struct obj_symbol *nsym, **p;
    993.     
    994.          nsym = arch_new_symbol();
    995.          nsym->next = sym->next;
    996.          nsym->ksymidx = -1;
    997.     
    998.          //从链表中删除旧的符号
    999.          for (p = &f->symtab[hash]; *p != sym; p = &(*p)->next)
    1000.          continue;
    1001.          *p = sym = nsym;//新的符号替换旧的符号
    1002.          goto found;
    1003.             }
    1004.             else if (n_binding == STB_LOCAL)//新添加的符号是局部符号,则加入到local_symtab表中,不加入 symtab
    1005.          {
    1006.          sym = arch_new_symbol();
    1007.          sym->next = NULL;
    1008.          sym->ksymidx = -1;
    1009.          f->local_symtab[symidx] = sym;
    1010.          goto found;
    1011.          }
    1012.             else if (n_binding == STB_WEAK)//新加入的符号是weak属性,则不需处理
    1013.              return sym;
    1014.             else if (o_binding == STB_WEAK)//如果已加入的符号属性是STB_WEAK,则用新的符号替换。
    1015.              goto found;
    1016.             else if (secidx == SHN_COMMON&& (o_type == STT_NOTYPE || o_type == STT_OBJECT))
    1017.              return sym;
    1018.             else if (o_secidx == SHN_COMMON&& (n_type == STT_NOTYPE || n_type == STT_OBJECT))
    1019.              goto found;
    1020.             else
    1021.          {
    1022.          if (secidx <= SHN_HIRESERVE)
    1023.          error("%s multiply defined", name);
    1024.          return sym;
    1025.          }
    1026.     }
    1027.     
    1028.     //该符号没有在hash符号表中添加过,所以有可能一个局部符号添加到了hash表中
    1029.   sym = arch_new_symbol();//分配一个新的符号结构体
    1030.   sym->next = f->symtab[hash];//链入hash数组中f->symtab[hash]
    1031.   f->symtab[hash] = sym;
    1032.   sym->ksymidx = -1;
    1033.     //若是局部符号(别的文件不可见),则将该符号添加到f->local_symtab[]数组中
    1034.   if (ELFW(ST_BIND)(info) == STB_LOCAL && symidx != -1) {
    1035.     if (symidx >= f->local_symtab_size)
    1036.       error("local symbol %s with index %ld exceeds local_symtab_size %ld",
    1037.         name, (long) symidx, (long) f->local_symtab_size);
    1038.     else
    1039.       f->local_symtab[symidx] = sym;
    1040.   }
    1041. found:
    1042.   sym->name = name;//符号名
    1043.   sym->value = value;//符号值
    1044.   sym->size = size;//符号大小
    1045.   sym->secidx = secidx;//节区索引值
    1046.   sym->info = info;//符号类型和绑定信息
    1047.   sym->r_type = 0;//重定位类型初始为0
    1048.   return sym;
    1049. }
    1050. void obj_set_symbol_compare (struct obj_file *f,int (*cmp)(const char *, const char *),
    1051.             unsigned long (*hash)(const char *))
    1052. {
    1053.   if (cmp)
    1054.     f->symbol_cmp = cmp;//符号比较函数
    1055.   if (hash)
    1056.   {
    1057.     struct obj_symbol *tmptab[HASH_BUCKETS], *sym, *next;
    1058.     int i;
    1059.     f->symbol_hash = hash;//hash函数
    1060.     memcpy(tmptab, f->symtab, sizeof(tmptab));//先将符号信息保存在临时数组tmptab
    1061.     memset(f->symtab, 0, sizeof(f->symtab));//清空hash表
    1062.         
    1063.         //重新使用hash函数将符号添加到符号表f->symtab中
    1064.     for (i = 0; i < HASH_BUCKETS; ++i)
    1065.             for (sym = tmptab[i]; sym ; sym = next)
    1066.           {
    1067.          unsigned long h = hash(sym->name) % HASH_BUCKETS;
    1068.          next = sym->next;
    1069.          sym->next = f->symtab[h];
    1070.          f->symtab[h] = sym;
    1071.           }
    1072.   }
    1073. }
    1074. static const char *gpl_licenses[] = {
    1075.     "GPL",
    1076.     "GPL v2",
    1077.     "GPL and additional rights",
    1078.     "Dual BSD/GPL",
    1079.     "Dual MPL/GPL",
    1080. };
    1081. int obj_gpl_license(struct obj_file *f, const char **license)
    1082. {
    1083.     struct obj_section *sec;
    1084.     //找到.modinfo节区
    1085.     if ((sec = obj_find_section(f, ".modinfo"))) {
    1086.         const char *value, *ptr, *endptr;
    1087.         ptr = sec->contents;//指向该节区内容其实地址
    1088.         endptr = ptr + sec->header.sh_size;//节区内容结束地址
    1089.         
    1090.         while (ptr < endptr) {
    1091.             //找到以”license=“起始的字符串
    1092.             if ((value = strchr(ptr, '=')) && strncmp(ptr, "license", value-ptr) == 0) {
    1093.                 int i;
    1094.                 if (license)
    1095.                     *license = value+1;
    1096.                 for (i = 0; i < sizeof(gpl_licenses)/sizeof(gpl_licenses[0]); ++i) {
    1097.                     if (strcmp(value+1, gpl_licenses[i]) == 0)//比较是否与以上数组相同的license
    1098.                         return(0);
    1099.                 }
    1100.                 return(2);
    1101.             }
    1102.             //否则从下一个字符串开始再查找
    1103.             if (strchr(ptr, ''))
    1104.                 ptr = strchr(ptr, '') + 1;
    1105.             else
    1106.                 ptr = endptr;
    1107.         }
    1108.     }
    1109.     return(1);
    1110. }
    1111. static void add_kernel_symbols(struct obj_file *f)
    1112. {
    1113.     struct module_stat *m;
    1114.     size_t i, nused = 0;
    1115.     //注意:此处虽然将模块的全局符号用内核和其他模块的符号替换过了,而且符号结构obj_symbol的secidx字段被重新写成了SHN_HIRESERVE以上的数值。对于一些全局的未定义符号(原来的secidx为SHN_UNDEF),现在这些未定义符号的secidx字段也被重新写成了SHN_HIRESERVE以上的数值。但是这些未定义符号对于elf文件格式的符号结构Elf32_sym中的字段st_shndx的取值并未改变,仍是SHN_UNDEF。这样做的原因是:在模块的编译过程中会生成一个__versions节区,该节区中存放的都是该模块中使用到,但没被定义的符号,也就是所谓的 unresolved symbol,它们或在基本内核中定义,或在其他模块中定义,内核使用它们来做 Module versioning。注意其中的 module_layout 符号,这是一个 dummy symbol。内核使用它来跟踪不同内核版本关于模块处理的相关数据结构的变化。所以该节区的未定义的符号虽然在这里被内核符号或其他模块符号已替换,但是它本身的SHN_UNDEF性质没有改变,用来对之后模块加载时的crc校验。因为crc校验时就是检查这些SHN_UNDEF性质的符号的crc值。参见内核函数simplify_symbols()。
    1116.     //而且__versions节区的未定义的符号必须是内核或内核其他模块用到的符号,这样在此系统下编译的模块安装到另一个系统上时,根据这些全局符号的crc值就能知道此模块是不是在此系统上编译的。还有这些符号虽然被设置为未定义的,但是通过符号替换,仍能得到符号的绝对地址,从而被模块引用。
    1117.     /* 使用系统中已有的module中的symbol,更新symbol的值,重新写入hash表或者局部符号表。注意:要加载的模块还没有加入到module_stat数组中 */
    1118.     for (i = 0, m = module_stat; i < n_module_stat; ++i, ++m)
    1119.         //遍历每个模块的符号表,符号对应的节区是SHN_LORESERVE以上的节区号。节区序号大于SHN_LORESERVE的符号,是没有对应的节区的。因此,符号里的值就认为是绝对地址。内核和已加载模块导出符号就处在这个区段。
    1120.       if (m->nsyms && add_symbols_from(f, SHN_HIRESERVE + 2 + i, m->syms, m->nsyms))
    1121.       {
    1122.           m->status = 1;//表示此模块被引用了
    1123.           ++nused;
    1124.       }
    1125.     n_ext_modules_used = nused;//该模块依赖的内核其余模块的个数
    1126.     //使用kernel导出的symbol,更新symbol的值,重新写入hash表或者局部符号表.SHN_HIRESERVE对应系统保留节区的上限,使用SHN_HIRESERVE以上的节区来保存已加载模块的符号和内核符号。
    1127.     if (nksyms)
    1128.         add_symbols_from(f, SHN_HIRESERVE + 1, ksyms, nksyms);
    1129. }
    1130. static int add_symbols_from(struct obj_file *f, int idx,struct module_symbol *syms, size_t nsyms)
    1131. {
    1132.     struct module_symbol *s;
    1133.     size_t i;
    1134.     int used = 0;
    1135.         
    1136.         //遍历该模块的所有符号
    1137.     for (i = 0, s = syms; i < nsyms; ++i, ++s) {
    1138.         struct obj_symbol *sym;
    1139.         //从hash表中是否有需要此名字的的symbol,局部符号表中的符号不需要内核符号替换
    1140.         sym = obj_find_symbol(f, (char *) s->name);
    1141.         //从要加载模块的hash表中找到该符号(必须为非局部符号),表示要加载模块需要改符号
    1142.         if (sym && !ELFW(ST_BIND) (sym->info) == STB_LOCAL) {
    1143.                 /*将hash表中的待解析的symbol的value添成正确的值s->value*/
    1144.             sym = obj_add_symbol(f, (char *) s->name, -1,ELFW(ST_INFO) (STB_GLOBAL, STT_NOTYPE),idx, s->value, 0);
    1145.             if (sym->secidx == idx)
    1146.                 used = 1;//表示发生了符号替换
    1147.         }
    1148.     }
    1149.     return used;
    1150. }
    1151. static int create_this_module(struct obj_file *f, const char *m_name)
    1152. {
    1153.     struct obj_section *sec;
    1154.     //创建一个.this节区,显然准备在这个节区里存放module结构。注意:这个节区是load时的首个节区,即起始节区
    1155.     sec = obj_create_alloced_section_first(f, ".this", tgt_sizeof_long,sizeof(struct module));
    1156.     memset(sec->contents, 0, sizeof(struct module));
    1157.     //添加一个"__this_module"符号,所在节区是.this,属性是 STB_LOCAL,类型是 STT_OBJECT,symidx 为-1,所以这个符号不加入 local_symtab 中(因为这个符号不是文件原有的)
    1158.     obj_add_symbol(f, "__this_module", -1, ELFW(ST_INFO) (STB_LOCAL, STT_OBJECT),sec->idx, 0, sizeof(struct module));
    1159.     
    1160.     /*为了能在obj_file里引用模块名(回忆一下,每个字符串要么与节区名对应,要么对应于一个符号,而在这里,模块名没有对应的符号或节区),因此obj_file通过obj_string_patch_struct结构收留这些孤独的字符串*/
    1161.     //创建.kstrtab节区,若存在该节区则扩展该节区,给该节区内容赋值为m_name,这里即”fedcore.ko“
    1162.     obj_string_patch(f, sec->idx, offsetof(struct module, name), m_name);
    1163.     return 1;
    1164. }
    1165. struct obj_section *obj_create_alloced_section_first (struct obj_file *f, const char *name,
    1166.                  unsigned long align, unsigned long size)
    1167. {
    1168.   int newidx = f->header.e_shnum++;//elf文件头中的节区头数量加1
    1169.   struct obj_section *sec;
    1170.     //为节区头分配空间
    1171.   f->sections = xrealloc(f->sections, (newidx+1) * sizeof(sec));
    1172.   f->sections[newidx] = sec = arch_new_section();
    1173.   memset(sec, 0, sizeof(*sec));//.this节区的偏移地址是0,sec->header.sh_addr=0
    1174.   sec->header.sh_type = SHT_PROGBITS;
    1175.   sec->header.sh_flags = SHF_WRITE|SHF_ALLOC;
    1176.   sec->header.sh_size = size;
    1177.   sec->header.sh_addralign = align;
    1178.   sec->name = name;
    1179.   sec->idx = newidx;
    1180.   if (size)
    1181.     sec->contents = xmalloc(size);//节区内容分配空间
    1182.   sec->load_next = f->load_order;
    1183.   f->load_order = sec;
    1184.   if (f->load_order_search_start == &f->load_order)
    1185.     f->load_order_search_start = &sec->load_next;
    1186.   return sec;
    1187. }
    1188. int obj_string_patch(struct obj_file *f, int secidx, ElfW(Addr) offset,const char *string)
    1189. {
    1190.   struct obj_string_patch_struct *p;
    1191.   struct obj_section *strsec;
    1192.   size_t len = strlen(string)+1;
    1193.   char *loc;
    1194.   p = xmalloc(sizeof(*p));
    1195.   p->next = f->string_patches;
    1196.   p->reloc_secidx = secidx;
    1197.   p->reloc_offset = offset;
    1198.   f->string_patches = p;//patch 字符串
    1199.     
    1200.     //查找.kstrtab节区
    1201.   strsec = obj_find_section(f, ".kstrtab");
    1202.   if (strsec == NULL)
    1203.   {
    1204.       //该节区不存在则创建该节区
    1205.     strsec = obj_create_alloced_section(f, ".kstrtab", 1, len, 0);
    1206.     p->string_offset = 0;
    1207.     loc = strsec->contents;
    1208.   }
    1209.   else
    1210.   {
    1211.     p->string_offset = strsec->header.sh_size;//字符串偏移地址
    1212.     loc = obj_extend_section(strsec, len);//扩展该节区内容的地址大小
    1213.   }
    1214.   memcpy(loc, string, len);//赋值给节区内容
    1215.   return 1;
    1216. }
    1217. int obj_check_undefineds(struct obj_file *f, int quiet)
    1218. {
    1219.   unsigned long i;
    1220.   int ret = 1;
    1221.     //遍历模块的hash表的所有符号,检查是否还有未定义的符号
    1222.   for (i = 0; i < HASH_BUCKETS; ++i)
    1223.   {
    1224.       struct obj_symbol *sym;
    1225.       //一般来说此处不会有未定义的符号,因为前边经过了一次内核符号和其他模块符号的替换操作add_kernel_symbols,但是在模块的编译
    1226.       for (sym = f->symtab[i]; sym ; sym = sym->next)
    1227.             if (sym->secidx == SHN_UNDEF)//如果有未定义的符号
    1228.          {
    1229.              //对于属性为weak的符号,如果未能解析,链接器只是将它置0完事
    1230.              if (ELFW(ST_BIND)(sym->info) == STB_WEAK)
    1231.              {
    1232.                     sym->secidx = SHN_ABS;//符号具有绝对取值,不会因为重定位而发生变化。
    1233.                     sym->value = 0;
    1234.              }
    1235.          else if (sym->r_type) /* assumes R_arch_NONE is 0 on all arch */
    1236.              {//如果不是weak属性,而且受重定位影响那就出错了
    1237.                     if (!quiet)
    1238.                         error("%s: unresolved symbol %s",f->filename, sym->name);
    1239.                     ret = 0;
    1240.          }
    1241.          }
    1242.   }
    1243.   return ret;
    1244. }
    1245. void obj_allocate_commons(struct obj_file *f)
    1246. {
    1247.   struct common_entry
    1248.   {
    1249.     struct common_entry *next;
    1250.     struct obj_symbol *sym;
    1251.   } *common_head = NULL;
    1252.   unsigned long i;
    1253.   for (i = 0; i < HASH_BUCKETS; ++i)
    1254.   {
    1255.     struct obj_symbol *sym;
    1256.     //遍历该模块的hash符号表
    1257.     for (sym = f->symtab[i]; sym ; sym = sym->next)
    1258.     //若设置了该标志SHN_COMMON,则表示符号标注了一个尚未分配的公共块,例如未分配的C外部变量。就是说,链接编辑器将为符号分配存储空间,地址位于 st_value 的倍数处。符号的大小给出了所需要的字节数。
    1259.     //找出所有SHN_COMMON的符号,并按符号大小排序,链入到common_head链表中
    1260.         if (sym->secidx == SHN_COMMON)
    1261.       {
    1262.      {
    1263.      struct common_entry **p, *n;
    1264.      for (p = &common_head; *p ; p = &(*p)->next)
    1265.                 if (sym->size <= (*p)->sym->size)
    1266.                  break;
    1267.      n = alloca(sizeof(*n));
    1268.      n->next = *p;
    1269.      n->sym = sym;
    1270.      *p = n;
    1271.      }
    1272.       }
    1273.   }
    1274.     //遍历该模块的局部符号表local_symtab,找出所有SHN_COMMON的符号,并按符号大小排序,链入到common_head链表中
    1275.   for (i = 1; i < f->local_symtab_size; ++i)
    1276.   {
    1277.       struct obj_symbol *sym = f->local_symtab[i];
    1278.       if (sym && sym->secidx == SHN_COMMON)
    1279.         {
    1280.          struct common_entry **p, *n;
    1281.          for (p = &common_head; *p ; p = &(*p)->next)
    1282.          if (sym == (*p)->sym)
    1283.          break;
    1284.          else if (sym->size < (*p)->sym->size)
    1285.          {
    1286.                     n = alloca(sizeof(*n));
    1287.                     n->next = *p;
    1288.                     n->sym = sym;
    1289.                     *p = n;
    1290.                     break;
    1291.          }
    1292.         }
    1293.   }
    1294.   if (common_head)
    1295.   {
    1296.       for (i = 0; i < f->header.e_shnum; ++i)
    1297.           //SHT_NOBITS表明这个节区不占据文件空间,这正是.bss节区的类型,这里就是为了查找.bss节区
    1298.             if (f->sections[i]->header.sh_type == SHT_NOBITS)
    1299.                  break;
    1300.     //如果没有找到.bss节区,则就创建一个.bss节区
    1301.     //.bss 含义:包含将出现在程序的内存映像中的为初始化数据。根据定义,当程序开始执行,系统将把这些数据初始化为 0。此节区不占用文件空间。
    1302.       if (i == f->header.e_shnum)
    1303.         {
    1304.          struct obj_section *sec;
    1305.     
    1306.          f->sections = xrealloc(f->sections, (i+1) * sizeof(sec));
    1307.          f->sections[i] = sec = arch_new_section();//分配节区结构obj_section
    1308.          f->header.e_shnum = i+1;//节区数量加1
    1309.     
    1310.          memset(sec, 0, sizeof(*sec));
    1311.          sec->header.sh_type = SHT_PROGBITS;//节区类型
    1312.          sec->header.sh_flags = SHF_WRITE|SHF_ALLOC;
    1313.          sec->name = ".bss";//节区名称
    1314.          sec->idx = i;//节区索引值
    1315.         }
    1316.     {
    1317.             ElfW(Addr) bss_size = f->sections[i]->header.sh_size;//节区大小
    1318.             ElfW(Addr) max_align = f->sections[i]->header.sh_addralign;//对齐边界
    1319.             struct common_entry *c;
    1320.     
    1321.             //根据SHN_COMMON的符号重新计算该.bss节区大小和对齐边界
    1322.             for (c = common_head; c ; c = c->next)
    1323.          {
    1324.          ElfW(Addr) align = c->sym->value;
    1325.     
    1326.          if (align > max_align)
    1327.          max_align = align;
    1328.          if (bss_size & (align - 1))
    1329.          bss_size = (bss_size | (align - 1)) + 1;
    1330.     
    1331.          c->sym->secidx = i;//该符号的节区索引值也改变了,即是.bss节区
    1332.          c->sym->value = bss_size;//符号值也变了,变成.bss节区符号偏移量
    1333.     
    1334.          bss_size += c->sym->size;
    1335.          }
    1336.     
    1337.             f->sections[i]->header.sh_size = bss_size;
    1338.             f->sections[i]->header.sh_addralign = max_align;
    1339.     }
    1340.   }
    1341.   //为SHT_NOBITS节区分配资源,并将它设为SHT_PROGBITS。从这里可以看到,文件定义的静态、全局变量,还有引用的外部变量,最终放在了.bss节区中
    1342.   for (i = 0; i < f->header.e_shnum; ++i)
    1343.   {
    1344.       struct obj_section *s = f->sections[i];
    1345.       if (s->header.sh_type == SHT_NOBITS)//找到.bss节区
    1346.         {
    1347.          if (s->header.sh_size)
    1348.              //节区内容都初始化为0,即.bss节区中符号对应的文件定义的静态、全局变量,还有引用的外部变量都初始化为0
    1349.          s->contents = memset(xmalloc(s->header.sh_size),0, s->header.sh_size);
    1350.          else
    1351.          s->contents = NULL;
    1352.          s->header.sh_type = SHT_PROGBITS;
    1353.         }
    1354.   }
    1355. }
    1356. static void check_module_parameters(struct obj_file *f, int *persist_flag)
    1357. {
    1358.     struct obj_section *sec;
    1359.     char *ptr, *value, *n, *endptr;
    1360.     int namelen, err = 0;
    1361.     //查找 ".modinfo"节区
    1362.     sec = obj_find_section(f, ".modinfo");
    1363.     if (sec == NULL) {
    1364.         return;
    1365.     }
    1366.     ptr = sec->contents;//节区内容起始地址
    1367.     endptr = ptr + sec->header.sh_size;//节区内容结束地址
    1368.     
    1369.     while (ptr < endptr && !err) {
    1370.         value = strchr(ptr, '=');//定位到该字符串的”=“位置出
    1371.         n = strchr(ptr, '');
    1372.         if (value) {
    1373.             namelen = value - ptr;//找到该字符串的名称
    1374.             //查找相对应的"parm_"或"parm_desc_"开头的字符串
    1375.             if (namelen >= 5 && strncmp(ptr, "parm_", 5) == 0
    1376.              && !(namelen > 10 && strncmp(ptr, "parm_desc_", 10) == 0)) {
    1377.                 char *pname = xmalloc(namelen + 1);
    1378.                 strncpy(pname, ptr + 5, namelen - 5);//取得该字符串名
    1379.                 pname[namelen - 5] = '';
    1380.                 //检查该参数字符串的内容
    1381.                 err = check_module_parameter(f, pname, value+1, persist_flag);
    1382.                 free(pname);
    1383.             }
    1384.         } else {
    1385.             if (n - ptr >= 5 && strncmp(ptr, "parm_", 5) == 0) {
    1386.                 error("parameter %s found with no value", ptr);
    1387.                 err = 1;
    1388.             }
    1389.         }
    1390.         ptr = n + 1;//下一个字符串
    1391.     }
    1392.     if (err)
    1393.         *persist_flag = 0;
    1394.     return;
    1395. }
    1396. static int check_module_parameter(struct obj_file *f, char *key, char *value, int *persist_flag)
    1397. {
    1398.     struct obj_symbol *sym;
    1399.     int min, max;
    1400.     char *p = value;
    1401.     
    1402.     //确定该符号是否存在
    1403.     sym = obj_find_symbol(f, key);
    1404.     if (sym == NULL) {
    1405.         lprintf("Warning: %s symbol for parameter %s not found", error_file, key);
    1406.         ++warnings;
    1407.         return(1);
    1408.     }
    1409.     //解析参数值个数的声明,如果没有参数值个数的取值声明就默认为1
    1410.     if (isdigit(*p)) {
    1411.         min = strtoul(p, &p, 10);
    1412.         if (*p == '-')
    1413.             max = strtoul(p + 1, &p, 10);
    1414.         else
    1415.             max = min;
    1416.     } else
    1417.         min = max = 1;
    1418.     if (max < min) {
    1419.         lprintf("Warning: %s parameter %s has max < min!", error_file, key);
    1420.         ++warnings;
    1421.         return(1);
    1422.     }
    1423.     //处理变量类型
    1424.     switch (*p) {
    1425.     case 'c':
    1426.         if (!isdigit(p[1])) {
    1427.             lprintf("%s parameter %s has no size after 'c'!", error_file, key);
    1428.             ++warnings;
    1429.             return(1);
    1430.         }
    1431.         while (isdigit(p[1]))
    1432.             ++p;    /* swallow c array size */
    1433.         break;
    1434.     case 'b':    /* drop through */
    1435.     case 'h':    /* drop through */
    1436.     case 'i':    /* drop through */
    1437.     case 'l':    /* drop through */
    1438.     case 's':
    1439.         break;
    1440.     case '':
    1441.         lprintf("%s parameter %s has no format character!", error_file, key);
    1442.         ++warnings;
    1443.         return(1);
    1444.     default:
    1445.         lprintf("%s parameter %s has unknown format character '%c'", error_file, key, *p);
    1446.         ++warnings;
    1447.         return(1);
    1448.     }
    1449.     
    1450.     switch (*++p) {
    1451.     case 'p':
    1452.         if (*(p-1) == 's') {
    1453.             error("parameter %s is invalid persistent string", key);
    1454.             return(1);
    1455.         }
    1456.         *persist_flag = 1;
    1457.         break;
    1458.     case '':
    1459.         break;
    1460.     default:
    1461.         lprintf("%s parameter %s has unknown format modifier '%c'", error_file, key, *p);
    1462.         ++warnings;
    1463.         return(1);
    1464.     }
    1465.     return(0);
    1466. }
    1467. static int process_module_arguments(struct obj_file *f, int argc, char **argv, int required)
    1468. {
    1469.     //遍历命令行参数
    1470.     for (; argc > 0; ++argv, --argc) {
    1471.         struct obj_symbol *sym;
    1472.         int c;
    1473.         int min, max;
    1474.         int n;
    1475.         char *contents;
    1476.         char *input;
    1477.         char *fmt;
    1478.         char *key;
    1479.         char *loc;
    1480.         //因为使用命令行参数时,一定是param=value这样的形式
    1481.         if ((input = strchr(*argv, '=')) == NULL)
    1482.             continue;
    1483.         n = input - *argv;//参数长度
    1484.         input += 1; /* skip '=' */
    1485.         key = alloca(n + 6);
    1486.         if (m_has_modinfo) {
    1487.             //将该参数组合成参数符号格式”parm_xxx“
    1488.             memcpy(key, "parm_", 5);
    1489.             memcpy(key + 5, *argv, n);
    1490.             key[n + 5] = '';
    1491.             
    1492.             //从节区.modinfo中查找该模块参数
    1493.             if ((fmt = get_modinfo_value(f, key)) == NULL) {
    1494.                 if (required || flag_verbose) {
    1495.                     lprintf("Warning: ignoring %s, no such parameter in this module", *argv);
    1496.                     ++warnings;
    1497.                     continue;
    1498.                 }
    1499.             }
    1500.             key += 5;
    1501.             
    1502.             //解析参数值个数的声明,如果没有参数值个数的取值声明就默认为1
    1503.             if (isdigit(*fmt)) {
    1504.                 min = strtoul(fmt, &fmt, 10);
    1505.                 if (*fmt == '-')
    1506.                     max = strtoul(fmt + 1, &fmt, 10);
    1507.                 else
    1508.                     max = min;
    1509.             } else
    1510.                 min = max = 1;
    1511.                 
    1512.         } else { /* not m_has_modinfo */
    1513.             memcpy(key, *argv, n);
    1514.             key[n] = '';
    1515.             if (isdigit(*input))
    1516.                 fmt = "i";
    1517.             else
    1518.                 fmt = "s";
    1519.             min = max = 0;
    1520.         }
    1521.         //到hash符号表中查找该参数符号
    1522.         sym = obj_find_symbol(f, key);
    1523.         if (sym == NULL || sym->secidx > SHN_HIRESERVE) {
    1524.             error("symbol for parameter %s not found", key);
    1525.             return 0;
    1526.         }
    1527.         //找到符号,读取该符号所在节区的内容
    1528.         contents = f->sections[sym->secidx]->contents;
    1529.         loc = contents + sym->value;//存储该参数符号的值地址付给loc指针,下边就会给参数符号重新赋值
    1530.         n = 1;
    1531.         while (*input) {
    1532.             char *str;
    1533.             switch (*fmt) {
    1534.             case 's':
    1535.             case 'c':
    1536.                 if (*input == '"') {
    1537.                     char *r;
    1538.                     str = alloca(strlen(input));
    1539.                     for (r = str, input++; *input != '"'; ++input, ++r) {
    1540.                         if (*input == '') {
    1541.                             error("improperly terminated string argument for %s", key);
    1542.                             return 0;
    1543.                         }
    1544.                         /* else */
    1545.                         if (*input != '\') {
    1546.                             *r = *input;
    1547.                             continue;
    1548.                         }
    1549.                         /* else handle */
    1550.                         switch (*++input) {
    1551.                         case 'a': *r = 'a'; break;
    1552.                         case 'b': *r = ''; break;
    1553.                         case 'e': *r = '33'; break;
    1554.                         case 'f': *r = 'f'; break;
    1555.                         case 'n': *r = ' '; break;
    1556.                         case 'r': *r = ' '; break;
    1557.                         case 't': *r = ' '; break;
    1558.                         case '0':
    1559.                         case '1':
    1560.                         case '2':
    1561.                         case '3':
    1562.                         case '4':
    1563.                         case '5':
    1564.                         case '6':
    1565.                         case '7':
    1566.                             c = *input - '0';
    1567.                             if ('0' <= input[1] && input[1] <= '7') {
    1568.                                 c = (c * 8) + *++input - '0';
    1569.                                 if ('0' <= input[1] && input[1] <= '7')
    1570.                                     c = (c * 8) + *++input - '0';
    1571.                             }
    1572.                             *r = c;
    1573.                             break;
    1574.                         default: *r = *input; break;
    1575.                         }
    1576.                     }
    1577.                     *r = '';
    1578.                     ++input;
    1579.                 } else {
    1580.                     /*
    1581.                      * The string is not quoted.
    1582.                      * We will break it using the comma
    1583.                      * (like for ints).
    1584.                      * If the user wants to include commas
    1585.                      * in a string, he just has to quote it
    1586.                      */
    1587.                     char *r;
    1588.                     /* Search the next comma */
    1589.                     if ((r = strchr(input, ',')) != NULL) {
    1590.                         /*
    1591.                          * Found a comma
    1592.                          * Recopy the current field
    1593.                          */
    1594.                         str = alloca(r - input + 1);
    1595.                         memcpy(str, input, r - input);
    1596.                         str[r - input] = '';
    1597.                         /* Keep next fields */
    1598.                         input = r;
    1599.                     } else {
    1600.                         /* last string */
    1601.                         str = input;
    1602.                         input = "";
    1603.                     }
    1604.                 }
    1605.                 if (*fmt == 's') {
    1606.                     /* Normal string */
    1607.                     obj_string_patch(f, sym->secidx, loc - contents, str);
    1608.                     loc += tgt_sizeof_char_p;
    1609.                 } else {
    1610.                     /* Array of chars (in fact, matrix !) */
    1611.                     long charssize;    /* size of each member */
    1612.                     /* Get the size of each member */
    1613.                     /* Probably we should do that outside the loop ? */
    1614.                     if (!isdigit(*(fmt + 1))) {
    1615.                         error("parameter type 'c' for %s must be followed by the maximum size", key);
    1616.                         return 0;
    1617.                     }
    1618.                     charssize = strtoul(fmt + 1, (char **) NULL, 10);
    1619.                     /* Check length */
    1620.                     if (strlen(str) >= charssize-1) {
    1621.                         error("string too long for %s (max %ld)",key, charssize - 1);
    1622.                         return 0;
    1623.                     }
    1624.                     /* Copy to location */
    1625.                     strcpy((char *) loc, str);    /* safe, see check above */
    1626.                     loc += charssize;
    1627.                 }
    1628.                 /*
    1629.                  * End of 's' and 'c'
    1630.                  */
    1631.                 break;
    1632.             case 'b':
    1633.                 *loc++ = strtoul(input, &input, 0);
    1634.                 break;
    1635.             case 'h':
    1636.                 *(short *) loc = strtoul(input, &input, 0);
    1637.                 loc += tgt_sizeof_short;
    1638.                 break;
    1639.             case 'i':
    1640.                 *(int *) loc = strtoul(input, &input, 0);
    1641.                 loc += tgt_sizeof_int;
    1642.                 break;
    1643.             case 'l':
    1644.                 *(tgt_long *) loc = tgt_strtoul(input, &input, 0);
    1645.                 loc += tgt_sizeof_long;
    1646.                 break;
    1647.             default:
    1648.                 error("unknown parameter type '%c' for %s",*fmt, key);
    1649.                 return 0;
    1650.             }
    1651.             /*
    1652.              * end of switch (*fmt)
    1653.              */
    1654.             while (*input && isspace(*input))
    1655.                 ++input;
    1656.             if (*input == '')
    1657.                 break; /* while (*input) */
    1658.             /* else */
    1659.             if (*input == ',') {
    1660.                 if (max && (++n > max)) {
    1661.                     error("too many values for %s (max %d)", key, max);
    1662.                     return 0;
    1663.                 }
    1664.                 ++input;
    1665.                 /* continue with while (*input) */
    1666.             } else {
    1667.                 error("invalid argument syntax for %s: '%c'",key, *input);
    1668.                 return 0;
    1669.             }
    1670.         } /* end of while (*input) */
    1671.         if (min && (n < min)) {
    1672.             error("too few values for %s (min %d)", key, min);
    1673.             return 0;
    1674.         }
    1675.     } /* end of for (;argc > 0;) */
    1676.     return 1;
    1677. }
    1678. static void hide_special_symbols(struct obj_file *f)
    1679. {
    1680.     struct obj_symbol *sym;
    1681.     const char *const *p;
    1682.     static const char *const specials[] =
    1683.     {
    1684.         "cleanup_module",
    1685.         "init_module",
    1686.         "kernel_version",
    1687.         NULL
    1688.     };
    1689.     //查找数组中的几个符号,找到后类型改为STB_LOCAL(局部)
    1690.     for (p = specials; *p; ++p)
    1691.         if ((sym = obj_find_symbol(f, *p)) != NULL)
    1692.             sym->info = ELFW(ST_INFO) (STB_LOCAL, ELFW(ST_TYPE) (sym->info));
    1693. }
    1694. static void add_ksymoops_symbols(struct obj_file *f, const char *filename,const char *m_name)
    1695. {
    1696.     struct obj_section *sec;
    1697.     struct obj_symbol *sym;
    1698.     char *name, *absolute_filename;
    1699.     char str[STRVERSIONLEN], real[PATH_MAX];
    1700.     int i, l, lm_name, lfilename, use_ksymtab, version;
    1701.     struct stat statbuf;
    1702.     static const char *section_names[] = {
    1703.         ".text",
    1704.         ".rodata",
    1705.         ".data",
    1706.         ".bss"
    1707.         ".sbss"
    1708.     };
    1709.     
    1710.     //找到模块所在的完整路径名
    1711.     if (realpath(filename, real)) {
    1712.         absolute_filename = xstrdup(real);
    1713.     }
    1714.     else {
    1715.         int save_errno = errno;
    1716.         error("cannot get realpath for %s", filename);
    1717.         errno = save_errno;
    1718.         perror("");
    1719.         absolute_filename = xstrdup(filename);
    1720.     }
    1721.     lm_name = strlen(m_name);
    1722.     lfilename = strlen(absolute_filename);
    1723.     //查找"__ksymtab"节区是否存在或者模块符号是否需要导出
    1724.     use_ksymtab = obj_find_section(f, "__ksymtab") || !flag_export;
    1725.     //找到.this节区,记录经过修饰的模块名和经过修饰的长度不为0的节区。在这里修饰的目的,应该是为了唯一确定所使用的模块。
    1726.     if ((sec = obj_find_section(f, ".this"))) {
    1727.         l = sizeof(symprefix)+            /* "__insmod_" */
    1728.          lm_name+                /* module name */
    1729.          2+                    /* "_O" */
    1730.          lfilename+                /* object filename */
    1731.          2+                    /* "_M" */
    1732.          2*sizeof(statbuf.st_mtime)+        /* mtime in hex */
    1733.          2+                    /* "_V" */
    1734.          8+                    /* version in dec */
    1735.          1;                    /* nul */
    1736.         name = xmalloc(l);
    1737.         if (stat(absolute_filename, &statbuf) != 0)
    1738.             statbuf.st_mtime = 0;
    1739.         version = get_module_version(f, str);    /* -1 if not found */
    1740.         snprintf(name, l, "%s%s_O%s_M%0*lX_V%d",symprefix, m_name, absolute_filename,
    1741.              (int)(2*sizeof(statbuf.st_mtime)), statbuf.st_mtime,version);
    1742.         //添加一个符号,该符号所在节区是.this节区,符号value给出该符号的地址在节区sec->header.sh_addr(值为0)的偏移地址处
    1743.         sym = obj_add_symbol(f, name, -1,ELFW(ST_INFO) (STB_GLOBAL, STT_NOTYPE),sec->idx, sec->header.sh_addr, 0);
    1744.         if (use_ksymtab)
    1745.             add_ksymtab(f, sym);//该符号添加到__ksymtab节区中
    1746.     }
    1747.     free(absolute_filename);
    1748.     //参数若是通过文件传入的,也要修饰记录这个文件名
    1749.     if (f->persist) {
    1750.         l = sizeof(symprefix)+        /* "__insmod_" */
    1751.             lm_name+        /* module name */
    1752.             2+            /* "_P" */
    1753.             strlen(f->persist)+    /* data store */
    1754.             1;            /* nul */
    1755.         name = xmalloc(l);
    1756.         snprintf(name, l, "%s%s_P%s",symprefix, m_name, f->persist);
    1757.         sym = obj_add_symbol(f, name, -1, ELFW(ST_INFO) (STB_GLOBAL, STT_NOTYPE),sec->idx, sec->header.sh_addr, 0);
    1758.         if (use_ksymtab)
    1759.             add_ksymtab(f, sym);//该符号添加到__ksymtab节区中,要导出的符号加入该节区"__ksymtab"
    1760.     }
    1761.     /* tag the desired sections if size is non-zero */
    1762.     for (i = 0; i < sizeof(section_names)/sizeof(section_names[0]); ++i) {
    1763.         if ((sec = obj_find_section(f, section_names[i])) &&sec->header.sh_size) {
    1764.             l = sizeof(symprefix)+        /* "__insmod_" */
    1765.                 lm_name+        /* module name */
    1766.                 2+            /* "_S" */
    1767.                 strlen(sec->name)+    /* section name */
    1768.                 2+            /* "_L" */
    1769.                 8+            /* length in dec */
    1770.                 1;            /* nul */
    1771.             name = xmalloc(l);
    1772.             snprintf(name, l, "%s%s_S%s_L%ld",symprefix, m_name, sec->name,(long)sec->header.sh_size);
    1773.             sym = obj_add_symbol(f, name, -1, ELFW(ST_INFO) (STB_GLOBAL, STT_NOTYPE),sec->idx, sec->header.sh_addr, 0);
    1774.             if (use_ksymtab)
    1775.                 add_ksymtab(f, sym);//该符号添加到__ksymtab节区中,要导出的符号加入该节区"__ksymtab"
    1776.         }
    1777.     }
    1778. }
    1779. static int create_module_ksymtab(struct obj_file *f)
    1780. {
    1781.     struct obj_section *sec;
    1782.     int i;
    1783.     //n_ext_modules_used是该模块引用的模块的数量
    1784.     if (n_ext_modules_used) {
    1785.         struct module_ref *dep;
    1786.         struct obj_symbol *tm;
    1787.         //创建一个.kmodtab节区保存该模块所引用的模块信息
    1788.         sec = obj_create_alloced_section(f, ".kmodtab",tgt_sizeof_void_p,sizeof(struct module_ref) * n_ext_modules_used, 0);
    1789.         if (!sec)
    1790.             return 0;
    1791.         tm = obj_find_symbol(f, "__this_module");
    1792.         dep = (struct module_ref *) sec->contents;
    1793.         //
    1794.         for (i = 0; i < n_module_stat; ++i)
    1795.             if (module_stat[i].status) {//模块若被引用,则status为1
    1796.                 dep->dep = module_stat[i].addr;
    1797.                 dep->dep |= arch_module_base (f);
    1798.                 obj_symbol_patch(f, sec->idx, (char *) &dep->ref - sec->contents, tm);
    1799.                 dep->next_ref = 0;
    1800.                 ++dep;
    1801.             }
    1802.     }
    1803.     
    1804.     // 在存在__ksymtab节区或者不存在这个节区,而且其他符号都不导出的情况下,还要将这些符号添加入__symtab节区
    1805.     //如果需要导出外部(extern)符号,而__ksymtab段不存在(这种情况下,add_ksymoops_symbols里是不会创建__ksymtab段的。而实际上,模块一般是不会不包含__ksymtab段的,因为模块的导出符号都位于这个段里。),那么通过add_ksymtab创建__ksymtab段,并加入模块要导出的符号。在这里可以发现,如果模块需要导出符号,那么经过修饰的模块名、模块文件名,甚至参数文件名会在这里加入__ksymtab段(因为在前面的add_ksymoops_symbols函数里,这些符号被设为STB_GLOBOL了,段序号指向.this段)。
    1806.     //注意,在不存在__ksymtab段的情况下(这时模块没有定义任何需要导出的参数),直接导出序号在SHN_LORESERVE~SHN_HIRESERVE的符号,以及其他已分配资源段的非local符号。(根据elf规范里,位于SHN_LORESERVE~SHN_HIRESERVE区的已定义序号有SHN_LOPROC、SHN_HIPROC、SHN_ABS、SHN_COMMON。经过前面的处理,到这里SHN_COMMON对应的符号已经不存在了。这些序号的节区实际上是不存在的,存在的是持有这些序号的符号。其中SHN_ABS是不受重定位影响的符号,其他2个则是与处理器有关的。至于为什么模块不需要导出符号时,要导出这些区的符号,我也不太清楚,可以肯定的是,这和GCC有关,谁知道它放了什么进来?!)。
    1807.     if (flag_export && !obj_find_section(f, "__ksymtab")) {
    1808.         int *loaded;
    1809.         loaded = alloca(sizeof(int) * (i = f->header.e_shnum));
    1810.         while (--i >= 0)
    1811.             loaded[i] = (f->sections[i]->header.sh_flags & SHF_ALLOC) != 0;//节区是否占用内存
    1812.         for (i = 0; i < HASH_BUCKETS; ++i) {
    1813.             struct obj_symbol *sym;
    1814.             for (sym = f->symtab[i]; sym; sym = sym->next) 
    1815.             {
    1816.                 
    1817.                 if (ELFW(ST_BIND) (sym->info) != STB_LOCAL && sym->secidx <= SHN_HIRESERVE&& (sym->secidx >= SHN_LORESERVE || loaded[sym->secidx])) {
    1818.                     add_ksymtab(f, sym);//要导出的符号加入该节区"__ksymtab"
    1819.                 }
    1820.             }
    1821.         }
    1822.     }
    1823.     return 1;
    1824. }
    1825. static void add_ksymtab(struct obj_file *f, struct obj_symbol *sym)
    1826. {
    1827.     struct obj_section *sec;
    1828.     ElfW(Addr) ofs;
    1829.     //查找是否已经存在"__ksymtab"节区
    1830.     sec = obj_find_section(f, "__ksymtab");
    1831.     //如果存在这个节区,但是没有标示SHF_ALLOC,则直接将该节区的名字修改掉,标示删除
    1832.     if (sec && !(sec->header.sh_flags & SHF_ALLOC)) {
    1833.         *((char *)(sec->name)) = 'x';    /* override const */
    1834.         sec = NULL;
    1835.     }
    1836.     if (!sec)
    1837.         sec = obj_create_alloced_section(f, "__ksymtab",tgt_sizeof_void_p, 0, 0);
    1838.     if (!sec)
    1839.         return;
    1840.         
    1841.     sec->header.sh_flags |= SHF_ALLOC;
    1842.     sec->header.sh_addralign = tgt_sizeof_void_p;    /* Empty section mightbe byte-aligned */
    1843.     ofs = sec->header.sh_size;
    1844.     obj_symbol_patch(f, sec->idx, ofs, sym);//使用f->sybol_ptches保存这些符号
    1845.     obj_string_patch(f, sec->idx, ofs + tgt_sizeof_void_p, sym->name);//使用f->string_patches保存符号名
    1846.     obj_extend_section(sec, 2 * tgt_sizeof_char_p);//扩展"__ksymtab"节区
    1847. }
    1848. static int add_archdata(struct obj_file *f,struct obj_section **sec)
    1849. {
    1850.     size_t i;
    1851.     *sec = NULL;
    1852.     
    1853.     //查找是否有ARCHDATA_SEC_NAME=“__archdata”节区,没有则创建该节区
    1854.     for (i = 0; i < f->header.e_shnum; ++i) {
    1855.         if (strcmp(f->sections[i]->name, ARCHDATA_SEC_NAME) == 0) {
    1856.             *sec = f->sections[i];
    1857.             break;
    1858.         }
    1859.     }
    1860.     if (!*sec)
    1861.         *sec = obj_create_alloced_section(f, ARCHDATA_SEC_NAME, 16, 0, 0);
    1862.     //x86体系下是空函数
    1863.     if (arch_archdata(f, *sec))
    1864.         return(1);
    1865.     return 0;
    1866. }
    1867. static int add_kallsyms(struct obj_file *f,struct obj_section **module_kallsyms, int force_kallsyms)
    1868. {
    1869.     struct module_symbol *s;
    1870.     struct obj_file *f_kallsyms;
    1871.     struct obj_section *sec_kallsyms;
    1872.     size_t i;
    1873.     int l;
    1874.     const char *p, *pt_R;
    1875.     unsigned long start = 0, stop = 0;
    1876.     //遍历所有内核符号,内核符号都保存在全局变量ksyms中
    1877.     for (i = 0, s = ksyms; i < nksyms; ++i, ++s) {
    1878.         p = (char *)s->name;
    1879.         pt_R = strstr(p, "_R");//查找符号中是否有 "_R",计算符号长度是,去掉这两个字符
    1880.         if (pt_R)
    1881.             l = pt_R - p;
    1882.         else
    1883.             l = strlen(p);
    1884.             
    1885.         //内核导出符号位于“__start_kallsyms”和“__stop_kallsyms”符号所指向的地址之间
    1886.         if (strncmp(p, "__start_" KALLSYMS_SEC_NAME, l) == 0)
    1887.             start = s->value;
    1888.         else if (strncmp(p, "__stop_" KALLSYMS_SEC_NAME, l) == 0)
    1889.             stop = s->value;
    1890.     }
    1891.     if (start >= stop && !force_kallsyms)
    1892.         return(0);
    1893.     /* The kernel contains all symbols, do the same for this module. */
    1894.     //找到该模块的“kallsyms”节区
    1895.     for (i = 0; i < f->header.e_shnum; ++i) {
    1896.         if (strcmp(f->sections[i]->name, KALLSYMS_SEC_NAME) == 0) {
    1897.             *module_kallsyms = f->sections[i];
    1898.             break;
    1899.         }
    1900.     }
    1901.     //如果没有找到,则创建一个kallsyms节区
    1902.     if (!*module_kallsyms)
    1903.         *module_kallsyms = obj_create_alloced_section(f, KALLSYMS_SEC_NAME, 0, 0, 0);
    1904.     //这个函数的作用是将输入obj_file里的符号提取出来,忽略不用于调试的符号.构建出obj_file只包含kallsyms节区。这个段可以任意定位,因为不包含重定位信息。
    1905.     //实际上,f_kallsyms这个文件就是将输入文件里的信息整理整理,更方便使用(记住__kallsyms节区是用作辅助内核调试),整个输出文件只是临时的调试仓库。
    1906.     if (obj_kallsyms(f, &f_kallsyms))//???
    1907.         return(1);
    1908.     sec_kallsyms = f_kallsyms->sections[KALLSYMS_IDX];//临时创建obj_file里的kallsyms节区
    1909.     (*module_kallsyms)->header.sh_addralign = sec_kallsyms->header.sh_addralign;//节区对齐大小
    1910.     (*module_kallsyms)->header.sh_size = sec_kallsyms->header.sh_size;//节区大小
    1911.     free((*module_kallsyms)->contents);
    1912.     (*module_kallsyms)->contents = sec_kallsyms->contents;//内容赋值给kallsyms节区
    1913.     sec_kallsyms->contents = NULL;
    1914.     obj_free(f_kallsyms);
    1915.     return 0;
    1916. }
    1917. unsigned long obj_load_size (struct obj_file *f)
    1918. {
    1919.   unsigned long dot = 0;
    1920.   struct obj_section *sec;
    1921.     //前面提到段按对其边界大小排序,可以减少空间占用,就是体现在这里。
    1922.   for (sec = f->load_order; sec ; sec = sec->load_next)
    1923.   {
    1924.     ElfW(Addr) align;
    1925.     align = sec->header.sh_addralign;
    1926.     if (align && (dot & (align - 1)))
    1927.             dot = (dot | (align - 1)) + 1;
    1928.     sec->header.sh_addr = dot;
    1929.     dot += sec->header.sh_size;//各个节区大小累加
    1930.   }
    1931.   return dot;
    1932. }
    1933. asmlinkage unsigned long sys_create_module(const char *name_user, size_t size)
    1934. {
    1935.     char *name;
    1936.     long namelen, error;
    1937.     struct module *mod;
    1938.     if (!capable(CAP_SYS_MODULE))//是否具有创建模块的特权
    1939.         return EPERM;
    1940.     lock_kernel();
    1941.     if ((namelen = get_mod_name(name_user, &name)) < 0) {//模块名拷贝到内核空间
    1942.         error = namelen;
    1943.         goto err0;
    1944.     }
    1945.     if (size < sizeof(struct module)+namelen) {//检查模块名的大小
    1946.         error = EINVAL;
    1947.         goto err1;
    1948.     }
    1949.     if (find_module(name) != NULL) {//在内存中查找是否模块已经安装
    1950.         error = EEXIST;
    1951.         goto err1;
    1952.     }
    1953.     //分配module空间 #define module_map(x) vmalloc(x)
    1954.     if ((mod = (struct module *)module_map(size)) == NULL) {
    1955.         error = ENOMEM;
    1956.         goto err1;
    1957.     }
    1958.     memset(mod, 0, sizeof(*mod));
    1959.     mod->size_of_struct = sizeof(*mod);
    1960.     mod->next = module_list;//挂入链表
    1961.     mod->name = (char *)(mod + 1);//module结构下边用来存储模块名
    1962.     mod->size = size;
    1963.     memcpy((char*)(mod+1), name, namelen+1);//拷贝模块名
    1964.     put_mod_name(name);//释放name的空间
    1965.     module_list = mod;//挂入链表
    1966.     error = (long) mod;
    1967.     goto err0;
    1968. err1:
    1969.     put_mod_name(name);
    1970. err0:
    1971.     unlock_kernel();
    1972.     return error;
    1973. }
    1974. //base是模块在内核空间的起始地址,也是.this节区的偏移地址
    1975. int obj_relocate (struct obj_file *f, ElfW(Addr) base)
    1976. {
    1977.   int i, n = f->header.e_shnum;
    1978.   int ret = 1;
    1979.     
    1980.     //节区在内存的位置是假设文件从0地址加载而得出的,现在就要根据base值调整
    1981.   arch_finalize_section_address(f, base);
    1982.     //处理重定位符号,遍历每一个节区
    1983.   for (i = 0; i < n; ++i)
    1984.   {
    1985.     struct obj_section *relsec, *symsec, *targsec, *strsec;
    1986.     ElfW(RelM) *rel, *relend;
    1987.     ElfW(Sym) *symtab;
    1988.     const char *strtab;
    1989.     unsigned long nsyms;
    1990.     relsec = f->sections[i];
    1991.     if (relsec->header.sh_type != SHT_RELM)//如果该节区不是重定位类型,则继续查找
    1992.             continue;
    1993.             
    1994.         //重定位节区会引用两个其它节区:符号表、要修改的节区。符号表是symsec,要修改的节区是targsec节区.例如重定位节区(relsec).rel.text是对节区是.text(targsec)的进行重定位.原来重定位的目标节区(.text)的内容contents只是读入到内存中,这块内存是系统在堆上malloc的,内容中对应的地址不是真正的符号所在的地址。现在符号的真正的地址已经计算出,就要修改contents区的符号对应的地址,从而将符号链接到正确的地址。
    1995.         
    1996.         //重定位节区的sh_link表示相关符号表的节区头部索引,即.symtab符号节区
    1997.     symsec = f->sections[relsec->header.sh_link];
    1998.     //重定位节区的sh_info表示重定位所适用的节区的节区头部索引,像.text等节区
    1999.     targsec = f->sections[relsec->header.sh_info];
    2000.     //找到重定位节区相关符号表字符串的节区,即.strtab
    2001.     strsec = f->sections[symsec->header.sh_link];
    2002.     if (!(targsec->header.sh_flags & SHF_ALLOC))
    2003.             continue;
    2004.         //读出该节区重定位信息开始地址
    2005.     rel = (ElfW(RelM) *)relsec->contents;
    2006.     //重定位信息结束地址
    2007.     relend = rel + (relsec->header.sh_size / sizeof(ElfW(RelM)));
    2008.     //找到重定位节区相关符号表的内容
    2009.     symtab = (ElfW(Sym) *)symsec->contents;
    2010.     nsyms = symsec->header.sh_size / symsec->header.sh_entsize;
    2011.     strtab = (const char *)strsec->contents;//找到重定位节区相关符号表字符串的节区的内容
    2012.     for (; rel < relend; ++rel)
    2013.         {
    2014.          ElfW(Addr) value = 0;
    2015.          struct obj_symbol *intsym = NULL;
    2016.          unsigned long symndx;
    2017.          const char *errmsg;
    2018.     
    2019.          //给出要重定位的符号表索引
    2020.          symndx = ELFW(R_SYM)(rel->r_info);
    2021.          if (symndx)
    2022.          {
    2023.          /* Note we've already checked for undefined symbols. */
    2024.              if (symndx >= nsyms)
    2025.                 {
    2026.                  error("%s: Bad symbol index: %08lx >= %08lx",f->filename, symndx, nsyms);
    2027.                  continue;
    2028.                 }
    2029.                 
    2030.                 //这些要重定位的符号就是重定位目标节区(例如.text节区)里的符号,然后把该符号的绝对地址在覆盖这个节区的(例如.text节区)对应符号的地址
    2031.              obj_find_relsym(intsym, f, f, rel, symtab, strtab);//返回要找的重定位符号intsym
    2032.              value = obj_symbol_final_value(f, intsym);//计算符号的绝对地址(是内核空间的绝对地址,因为base就是内核空间的一个地址)
    2033.          }
    2034.     
    2035.     #if SHT_RELM == SHT_RELA
    2036.          value += rel->r_addend;
    2037.     #endif
    2038.     
    2039.          //获得了绝对地址,可以进行操作了
    2040.          //注意:这里虽然重新定义了符号的绝对地址,但是节区的内容还没有拷贝到分配模块返回的内核空间地址处。后边会进行这项操作。先将节区内容拷贝的用户空间中,再从用户空间拷贝到内核空间地址处,即base处。
    2041.          //f:objfile结构,targsec:.text节,symsec:.symtab节,rel:.rel结构,value:绝对地址 
    2042.          switch (arch_apply_relocation(f,targsec,symsec,intsym,rel,value))
    2043.      {
    2044.          case obj_reloc_ok:
    2045.          break;
    2046.          case obj_reloc_overflow:
    2047.          errmsg = "Relocation overflow";
    2048.          goto bad_reloc;
    2049.          case obj_reloc_dangerous:
    2050.          errmsg = "Dangerous relocation";
    2051.          goto bad_reloc;
    2052.          case obj_reloc_unhandled:
    2053.          errmsg = "Unhandled relocation";
    2054.          goto bad_reloc;
    2055.          case obj_reloc_constant_gp:
    2056.          errmsg = "Modules compiled with -mconstant-gp cannot be loaded";
    2057.          goto bad_reloc;
    2058.          bad_reloc:
    2059.          error("%s: %s of type %ld for %s", f->filename, errmsg,
    2060.              (long)ELFW(R_TYPE)(rel->r_info), intsym->name);
    2061.          ret = 0;
    2062.          break;
    2063.      }
    2064.         }
    2065.     }
    2066.   /* Finally, take care of the patches. */
    2067.   if (f->string_patches)
    2068.   {
    2069.     struct obj_string_patch_struct *p;
    2070.     struct obj_section *strsec;
    2071.     ElfW(Addr) strsec_base;
    2072.     strsec = obj_find_section(f, ".kstrtab");
    2073.     strsec_base = strsec->header.sh_addr;
    2074.     for (p = f->string_patches; p ; p = p->next)
    2075.         {
    2076.          struct obj_section *targsec = f->sections[p->reloc_secidx];
    2077.          *(ElfW(Addr) *)(targsec->contents + p->reloc_offset)= strsec_base + p->string_offset;
    2078.         }
    2079.   }
    2080.   if (f->symbol_patches)
    2081.   {
    2082.     struct obj_symbol_patch_struct *p;
    2083.     for (p = f->symbol_patches; p; p = p->next)
    2084.         {
    2085.          struct obj_section *targsec = f->sections[p->reloc_secidx];
    2086.          *(ElfW(Addr) *)(targsec->contents + p->reloc_offset)= obj_symbol_final_value(f, p->sym);
    2087.         }
    2088.   }
    2089.   return ret;
    2090. }
    2091. int arch_finalize_section_address(struct obj_file *f, Elf32_Addr base)
    2092. {
    2093.   int i, n = f->header.e_shnum;
    2094.     //每个节区的起始地址都要加上模块在内核的起始地址
    2095.   f->baseaddr = base;//模块在内核的起始地址
    2096.   for (i = 0; i < n; ++i)
    2097.     f->sections[i]->header.sh_addr += base;
    2098.   return 1;
    2099. }
    2100. #define obj_find_relsym(isym, f, find, rel, symtab, strtab)
    2101.     {
    2102.         unsigned long symndx = ELFW(R_SYM)((rel)->r_info);
    2103.         ElfW(Sym) *extsym = (symtab)+symndx; //在符号表节区的内容中根据索引值找到相关符号
    2104.         if (ELFW(ST_BIND)(extsym->st_info) == STB_LOCAL) { //若是局部符号
    2105.             isym = (typeof(isym)) (f)->local_symtab[symndx]; //直接在局部符号表中返回要找的重定位符号
    2106.         }
    2107.         else {
    2108.             const char *name;
    2109.             if (extsym->st_name) //有值的话,就是strtab字符串节区内容的索引值
    2110.                 name = (strtab) + extsym->st_name; //找到符号名
    2111.             else //否则就是节区名
    2112.                 name = (f)->sections[extsym->st_shndx]->name;
    2113.             isym = (typeof(isym)) obj_find_symbol((find), name); //在符号hash表中找到该重定位符号
    2114.         }
    2115.     }
    2116.     
    2117. ElfW(Addr) obj_symbol_final_value (struct obj_file *f, struct obj_symbol *sym)
    2118. {
    2119.   if (sym)
    2120.   {
    2121.       //在保留区内直接返回符号值,即符号绝对地址(一般是内核符号,因为前边将模块内的符号用内核中或已存在的模块中相同符号的value更写过了,并且节区索引值设置高于SHN_HIRESERVE,所以这些符号的value保存的就是符号的实际地址)
    2122.     if (sym->secidx >= SHN_LORESERVE)
    2123.             return sym->value;
    2124.         
    2125.         //其余节区内的符号value要加上现在节区的偏移地址,才是符号指向的实际地址(因为节区的偏移地址已经更改了)
    2126.     return sym->value + f->sections[sym->secidx]->header.sh_addr;//符号值加上节区头偏移地址
    2127.   }
    2128.   else
    2129.   {
    2130.     /* As a special case, a NULL sym has value zero. */
    2131.     return 0;
    2132.   }
    2133. }
    2134. //x86架构
    2135. /*
    2136. 。“重定位表”记录的是每个需要重定位的地方(即有了重定位表,就可知道哪个段、偏移多少的地方的地址或值是需要修改的)、重定位的类型、符号的名字(即重定位的地方属于哪个符号)。(静态)链接器在链接目标文件的时候,会扫描每个目标文件,为每个目标文件中的段分配运行时的地址(这个地址就是进程地址空间的地址,因为每个操作系统都会位应用程序指定装载地址、如eos和windows的0x00400000,linux的0x0804800,通过用操作系统指定的地址配置链接器,链接器根据每个段的属性、大小和对齐属性等,就可得到每个段运行时的地址了),这样每个段的地址就确定下来了,从而,每个符号的地址都确定了,然后把符号表中符号的值修改为正确的地址。然后连接器就会把所有目标文件的符号表合并为一个全局的符号表(主要是为了定位的方便)。接下来,连接器就读取每个目标文件,通过重定位表找到需要重定位的地方和这个符号的名字,然后用这个符号去检索全局符号表,得到符号的地址,再用个这个地址填入需要修正的地方(对于相对跳转指令是用这个地址和修正处的地址和修正处存放的值参运算计算出正确的跳转偏移,然后填入),最后把所有经过了重定位的目标文件中相同段名和属性的段合并,输出到最终的可执行文件中并建立相应的数据结构,可执行文件也是有格式的,linux 常见的elf,windows和eos的pe格式。
    2137. */
    2138. //重定位结构(Elf32_Rel)中的字段r_info指定重定位地址属于哪个符号,r_offset字段指定重定位的地方。然后把这个符号的绝对地址写到重定位的地方
    2139. enum obj_reloc arch_apply_relocation (struct obj_file *f,
    2140.          struct obj_section *targsec,
    2141.          struct obj_section *symsec,
    2142.          struct obj_symbol *sym,
    2143.          Elf32_Rel *rel,
    2144.          Elf32_Addr v)
    2145. {
    2146.   struct i386_file *ifile = (struct i386_file *)f;
    2147.   struct i386_symbol *isym = (struct i386_symbol *)sym;
    2148.     ////找到重定位的地方,下边在这个地方写入符号的绝对地址
    2149.   Elf32_Addr *loc = (Elf32_Addr *)(targsec->contents + rel->r_offset);
    2150.   Elf32_Addr dot = targsec->header.sh_addr + rel->r_offset;
    2151.   Elf32_Addr got = ifile->got ? ifile->got->header.sh_addr : 0;
    2152.   enum obj_reloc ret = obj_reloc_ok;
    2153.   switch (ELF32_R_TYPE(rel->r_info))//重定位类型
    2154.     {
    2155.     case R_386_NONE:
    2156.       break;
    2157.     case R_386_32:
    2158.       *loc += v;
    2159.       break;
    2160.     case R_386_PLT32:
    2161.     case R_386_PC32:
    2162.       *loc += v - dot;
    2163.       break;
    2164.     case R_386_GLOB_DAT:
    2165.     case R_386_JMP_SLOT:
    2166.       *loc = v;
    2167.       break;
    2168.     case R_386_RELATIVE:
    2169.       *loc += f->baseaddr;
    2170.       break;
    2171.     case R_386_GOTPC:
    2172.       assert(got != 0);
    2173.       *loc += got - dot;
    2174.       break;
    2175.     case R_386_GOT32:
    2176.       assert(isym != NULL);
    2177.       if (!isym->gotent.reloc_done)
    2178.             {
    2179.              isym->gotent.reloc_done = 1;
    2180.              *(Elf32_Addr *)(ifile->got->contents + isym->gotent.offset) = v;
    2181.             }
    2182.       *loc += isym->gotent.offset;
    2183.       break;
    2184.     case R_386_GOTOFF:
    2185.       assert(got != 0);
    2186.       *loc += v - got;
    2187.       break;
    2188.     default:
    2189.       ret = obj_reloc_unhandled;
    2190.       break;
    2191.     }
    2192.   return ret;
    2193. }
    2194. //insmod包含在modutils包里。我们感兴趣的东西是insmod.c文件里的init_module()函数。
    2195. static int init_module(const char *m_name, struct obj_file *f,unsigned long m_size, const char *blob_name,unsigned int noload, unsigned int flag_load_map)
    2196. {
    2197.     //传入的参数m_name是模块名称,obj_file *f已经将模块的节区信息添加到该结构中,m_size是模块大小
    2198.     struct module *module;
    2199.     struct obj_section *sec;
    2200.     void *image;
    2201.     int ret = 0;
    2202.     tgt_long m_addr;
    2203.     //从节区数组中查找.this节区
    2204.     sec = obj_find_section(f, ".this");
    2205.     module = (struct module *) sec->contents;//取得本节区的内容,是一个module结构
    2206.     //下边的操作就是初始化module结构,都保存在.this节区的contents中。
    2207.     
    2208.     //.this节区的偏移地址地址就是module结构的在内核空间的起始地址,因为.this节区是首节区,前边该节区的偏移地址根据内核空间的模块起始地址做了一个偏移即sec->header.sh_addr+m_addr,又因为.this节区的sh_addr初始值是0,所以加了这个偏移,就正好指向模块在内核空间的起始地址。
    2209.     m_addr = sec->header.sh_addr;
    2210.     
    2211.     module->size_of_struct = sizeof(*module);//模块结构大小
    2212.     module->size = m_size;//模块大小
    2213.     module->flags = flag_autoclean ? NEW_MOD_AUTOCLEAN : 0;
    2214.     //查找__ksymtab节表,保存的是该模块导出的符号
    2215.     sec = obj_find_section(f, "__ksymtab");
    2216.     if (sec && sec->header.sh_size) {
    2217.         module->syms = sec->header.sh_addr;
    2218.         module->nsyms = sec->header.sh_size / (2 * tgt_sizeof_char_p);
    2219.     }
    2220.     
    2221.     //查找.kmodtab节表,module的依赖对象对应于.kmodtab节区
    2222.     if (n_ext_modules_used) {
    2223.         sec = obj_find_section(f, ".kmodtab");
    2224.         module->deps = sec->header.sh_addr;
    2225.         module->ndeps = n_ext_modules_used;
    2226.     }
    2227.     
    2228.     //obj_find_symbol()函数遍历符号列表查找名字为init_module的符号,然后提取这个结构体符号(struct symbol)并把它传递给 obj_symbol_final_value()。后者从这个结构体符号提取出init_module函数的地址。
    2229.     module->init = obj_symbol_final_value(f, obj_find_symbol(f, "init_module"));
    2230.     module->cleanup = obj_symbol_final_value(f,obj_find_symbol(f, "cleanup_module"));
    2231.     //查找__ex_table节表
    2232.     sec = obj_find_section(f, "__ex_table");
    2233.     if (sec) {
    2234.         module->ex_table_start = sec->header.sh_addr;
    2235.         module->ex_table_end = sec->header.sh_addr + sec->header.sh_size;
    2236.     }
    2237.     
    2238.     //查找.text.init节表
    2239.     sec = obj_find_section(f, ".text.init");
    2240.     if (sec) {
    2241.         module->runsize = sec->header.sh_addr - m_addr;
    2242.     }
    2243.     //查找.data.init节表
    2244.     sec = obj_find_section(f, ".data.init");
    2245.     if (sec) {
    2246.         if (!module->runsize || module->runsize > sec->header.sh_addr - m_addr)
    2247.             module->runsize = sec->header.sh_addr - m_addr;
    2248.     }
    2249.     
    2250.     sec = obj_find_section(f, ARCHDATA_SEC_NAME);
    2251.     if (sec && sec->header.sh_size) {
    2252.         module->archdata_start = sec->header.sh_addr;
    2253.         module->archdata_end = module->archdata_start + sec->header.sh_size;
    2254.     }
    2255.     
    2256.     //查找kallsyms节区
    2257.     sec = obj_find_section(f, KALLSYMS_SEC_NAME);
    2258.     if (sec && sec->header.sh_size) {
    2259.         module->kallsyms_start = sec->header.sh_addr;//符号开始地址
    2260.         module->kallsyms_end = module->kallsyms_start + sec->header.sh_size;//符号结束地址
    2261.     }
    2262.     if (!arch_init_module(f, module))//x86下什么也不干
    2263.         return 0;
    2264.     //在用户空间分配module的image的内存,返回模块起始地址
    2265.     image = xmalloc(m_size);
    2266.     //各个section的内容拷入image中,包括原文件中的section和后来构造的section 
    2267.     obj_create_image(f, image);//模块内容从f结构指定的地址中拷贝到image中,构建模块映像
    2268.     if (flag_load_map)
    2269.         print_load_map(f);
    2270.     if (blob_name) {//是否指定了要输出模块到指定的文件blob_name
    2271.         int fd, l;
    2272.         fd = open(blob_name, O_WRONLY|O_CREAT|O_TRUNC, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
    2273.         if (fd < 0) {
    2274.             error("open %s failed %m", blob_name);
    2275.             ret = -1;
    2276.         }
    2277.         else {
    2278.             if ((l = write(fd, image, m_size)) != m_size) {
    2279.                 error("write %s failed %m", blob_name);
    2280.                 ret = -1;
    2281.             }
    2282.             close(fd);
    2283.         }
    2284.     }
    2285.     if (ret == 0 && !noload) {
    2286.         fflush(stdout);        /* Flush any debugging output */
    2287.         //sys_init_module() 这个系统调用通知内核加载相应模块,这个函数的代码可以在 /usr/src/linux/kernel/module.c 
    2288.         //在此函数中把在用户空间的module映像复制到前边由create_module创建地内核空间中。 
    2289.         ret = sys_init_module(m_name, (struct module *) image);
    2290.         if (ret) {
    2291.             error("init_module: %m");
    2292.             lprintf("Hint: insmod errors can be caused by incorrect module parameters, "
    2293.                 "including invalid IO or IRQ parameters.You may find more information in syslog or the output from dmesg

    1. }
    2.     }
    3.     free(image);
    4.     return ret == 0;
    5. }
    6. int obj_create_image (struct obj_file *f, char *image)
    7. {
    8.   struct obj_section *sec;
    9.   ElfW(Addr) base = f->baseaddr;
    10.     //注意:首个load的节区是.this节区
    11.   for (sec = f->load_order; sec ; sec = sec->load_next)
    12.   {
    13.     char *secimg;
    14.     if (sec->contents == 0)
    15.             continue;
    16.     secimg = image + (sec->header.sh_addr - base);
    17.     //所有的节区内容拷贝到以image地址开始的地方,当然第一个节区的内容恰好是struct module结构
    18.     memcpy(secimg, sec->contents, sec->header.sh_size);
    19.   }
    20.   return 1;

      1. int sys_init_module(const char *name, const struct module *info)
      2. {
      3.  //调用系统调用init_module(),系统调用init_module()在内核中的实现是sys_init_module(),这是由内核提供的,全内核只有这一个函数。注意,这是linux V2.6以前的调用。
      4.   return init_module(name, info);
      5. }
      6. asmlinkage long sys_init_module(const char *name_user, struct module *mod_user)
      7. {
      8.  struct module mod_tmp, *mod;
      9.  char *name, *n_name, *name_tmp = NULL;
      10.  long namelen, n_namelen, i, error;
      11.  unsigned long mod_user_size;
      12.  struct module_ref *dep;
      13.  
      14.  //检查模块加载的权限
      15.  if (!capable(CAP_SYS_MODULE))
      16.   return EPERM;
      17.  lock_kernel();
      18.  //复制模块名到内核空间name中
      19.  if ((namelen = get_mod_name(name_user, &name)) < 0) {
      20.   error = namelen;
      21.   goto err0;
      22.  }
      23.  //从module_list中找到之前通过creat_module()在内核空间创建的module结构,创建模块时已经将模块结构链入module_list
      24.  if ((mod = find_module(name)) == NULL) {
      25.   error = ENOENT;
      26.   goto err1;
      27.  }
      28.  //把用户空间的module结构的size_of_struct复制到内核中加以检查,将模块结构的大小size_of_struct赋值给mod_user_size,即sizeof(struct module)
      29.  if ((error = get_user(mod_user_size, &mod_user->size_of_struct)) != 0)
      30.   goto err1;
      31.   
      32.  //对用户空间和内核空间的module结构的大小进行检查
      33.  //如果申请的模块头部长度小于旧版的模块头长度或者大于将来可能的模块头长度
      34.  if (mod_user_size < (unsigned long)&((struct module *)0L)->persist_start
      35.      || mod_user_size > sizeof(struct module) + 16*sizeof(void*)) {
      36.   printk(KERN_ERR "init_module: Invalid module header size. "
      37.           KERN_ERR "A new version of the modutils is likely ""needed. ");
      38.   error = EINVAL;
      39.   goto err1;
      40.  }
      41.  mod_tmp = *mod;//内核中的module结构先保存到堆栈中
      42.  //分配保存内核空间模块名的空间
      43.  name_tmp = kmalloc(strlen(mod->name) + 1, GFP_KERNEL); /* Where's kstrdup()? */
      44.  if (name_tmp == NULL) {
      45.   error = ENOMEM;
      46.   goto err1;
      47.  }
      48.  strcpy(name_tmp, mod->name);//将内核中module的name复制给name_tmp,在堆栈中先保存起来
      49.  
      50.  //将用户空间的模块结构到内核空间原来的module地址处(即将用户空间的模块映像覆盖掉在内核空间模块映像的所在地址,这样前边设置的符号地址就不需要改变了,正好就是我们在前边按照内核空间的模块起始地址设置的),mod_user_size是模块结构的大小,即sizeof(struct module)
      51.  error = copy_from_user(mod, mod_user, mod_user_size);
      52.  if (error) {
      53.   error = EFAULT;
      54.   goto err2;
      55.  }
      56.  error = EINVAL; 
      57.  
      58.  //比较内核空间和用户空间模块大小,若在insmod用户空间创建的module结构大小大于内核空间的module大小,就出错退出 
      59.  if (mod->size > mod_tmp.size) {
      60.   printk(KERN_ERR "init_module: Size of initialized module ""exceeds size of created module. ");
      61.   goto err2;
      62.  } 
      63.  if (!mod_bound(mod->name, namelen, mod)) {//用来检查用户指针所指的对象是否落在模块的边界内
      64.   printk(KERN_ERR "init_module: mod->name out of bounds. ");
      65.   goto err2;
      66.  }
      67.  if (mod->nsyms && !mod_bound(mod->syms, mod->nsyms, mod)) {// 符号表的区域是否在模块体中
      68.   printk(KERN_ERR "init_module: mod->syms out of bounds. ");
      69.   goto err2;
      70.  }
      71.  if (mod->ndeps && !mod_bound(mod->deps, mod->ndeps, mod)) {//依赖关系表是否在模块体中
      72.   printk(KERN_ERR "init_module: mod->deps out of bounds. ");
      73.   goto err2;
      74.  }
      75.  if (mod->init && !mod_bound(mod->init, 0, mod)) {//init函数是否是模块体中
      76.   printk(KERN_ERR "init_module: mod->init out of bounds. ");
      77.   goto err2;
      78.  }
      79.  if (mod->cleanup && !mod_bound(mod->cleanup, 0, mod)) {//cleanup函数是否是模块体中
      80.   printk(KERN_ERR "init_module: mod->cleanup out of bounds. ");
      81.   goto err2;
      82.  }
      83.  //检查模块的异常描述表是否在模块影像内
      84.  if (mod->ex_table_start > mod->ex_table_end|| (mod->ex_table_start 
      85.  &&!((unsigned long)mod->ex_table_start >= ((unsigned long)mod + mod->size_of_struct)
      86.  && ((unsigned long)mod->ex_table_end< (unsigned long)mod + mod->size)))|| 
      87.  (((unsigned long)mod->ex_table_start-(unsigned long)mod->ex_table_end)% sizeof(struct exception_table_entry))) {
      88.   printk(KERN_ERR "init_module: mod->ex_table_* invalid. ");
      89.   goto err2;
      90.  }
      91.  if (mod->flags & ~MOD_AUTOCLEAN) {
      92.   printk(KERN_ERR "init_module: mod->flags invalid. ");
      93.   goto err2;
      94.  }
      95.  if (mod_member_present(mod, can_unload)//检查结构的大小,看用户模块是否包含can_unload字段
      96.  && mod->can_unload && !mod_bound(mod->can_unload, 0, mod)) {//若包含can_unload字段,就检查其边界
      97.   printk(KERN_ERR "init_module: mod->can_unload out of bounds. ");
      98.   goto err2;
      99.  }
      100.  if (mod_member_present(mod, kallsyms_end)) {
      101.     if (mod->kallsyms_end &&(!mod_bound(mod->kallsyms_start, 0, mod) ||!mod_bound(mod->kallsyms_end, 0, mod))) {
      102.       printk(KERN_ERR "init_module: mod->kallsyms out of bounds. ");
      103.       goto err2;
      104.     }
      105.     if (mod->kallsyms_start > mod->kallsyms_end) {
      106.       printk(KERN_ERR "init_module: mod->kallsyms invalid. ");
      107.       goto err2;
      108.     }
      109.  }
      110.  if (mod_member_present(mod, archdata_end)) {
      111.     if (mod->archdata_end &&(!mod_bound(mod->archdata_start, 0, mod) ||
      112.     !mod_bound(mod->archdata_end, 0, mod))) {
      113.       printk(KERN_ERR "init_module: mod->archdata out of bounds. ");
      114.       goto err2;
      115.     }
      116.     if (mod->archdata_start > mod->archdata_end) {
      117.       printk(KERN_ERR "init_module: mod->archdata invalid. ");
      118.       goto err2;
      119.     }
      120.  }
      121.  if (mod_member_present(mod, kernel_data) && mod->kernel_data) {
      122.      printk(KERN_ERR "init_module: mod->kernel_data must be zero. ");
      123.      goto err2;
      124.  }
      125.  
      126.  //在把用户空间的模块名从用户空间拷贝进来
      127.  if ((n_namelen = get_mod_name(mod->name-(unsigned long)mod+ (unsigned long)mod_user,&n_name)) < 0) {
      128.     printk(KERN_ERR "init_module: get_mod_name failure. ");
      129.     error = n_namelen;
      130.     goto err2;
      131.  }
      132.  //比较内核空间中和用户空间中模块名是否相同
      133.  if (namelen != n_namelen || strcmp(n_name, mod_tmp.name) != 0) {
      134.   printk(KERN_ERR "init_module: changed module name to ""`%s' from `%s' ",n_name, mod_tmp.name);
      135.   goto err3;
      136.  }
      137.  
      138.  //拷贝除module结构本身以外的其它section到内核空间中,就是拷贝模块映像
      139.  if (copy_from_user((char *)mod+mod_user_size,(char *)mod_user+mod_user_size,mod->size-mod_user_size)) {
      140.   error = EFAULT;
      141.   goto err3;
      142.  }
      143.  
      144.  if (module_arch_init(mod))//空操作
      145.   goto err3;
      146.  
      147.  flush_icache_range((unsigned long)mod, (unsigned long)mod + mod->size);
      148.  mod->next = mod_tmp.next;//mod->next在拷贝模块头时被覆盖了
      149.  mod->refs = NULL;//由于是新加载的,还没有别的模块引用我
      150.  
      151.  //检查模块的依赖关系,依赖的模块仍在内核中
      152.  for (i = 0, dep = mod->deps; i < mod->ndeps; ++i, ++dep) {
      153.   struct module *o, *d = dep->dep;
      154.   if (d == mod) {//依赖的模块不能使自身
      155.    printk(KERN_ERR "init_module: selfreferential""dependency in mod->deps. ");
      156.    goto err3;
      157.   }
      158.   //若依赖的模块已经不在module_list中,则系统调用失败
      159.   for (o = module_list; o != &kernel_module && o != d; o = o->next);
      160.   if (o != d) {
      161.    printk(KERN_ERR "init_module: found dependency that is ""(no longer?) a module. ");
      162.    goto err3;
      163.   }
      164.  }
      165.  //再扫描,将每个module_ref结构链入到所依赖模块的refs队列中,并将结构中的ref指针指向正在安装的nodule结构。这样每个module_ref结构既存在于所属模块的deps[]数组中,又出现于该模块所依赖的某个模块的refs队列中。
      166.  for (i = 0, dep = mod->deps; i < mod->ndeps; ++i, ++dep) {
      167.   struct module *d = dep->dep;
      168.   dep->ref = mod;
      169.   dep->next_ref = d->refs;
      170.   d->refs = dep;
      171.   d->flags |= MOD_USED_ONCE;
      172.  }
      173.  
      174.  put_mod_name(n_name);//释放空间
      175.  put_mod_name(name);//释放空间
      176.  mod->flags |= MOD_INITIALIZING;//设置模块初始化标志
      177.  atomic_set(&mod->uc.usecount,1);//用户计数设为1
      178.  
      179.   //检查模块的init_module()函数,然后执行模块的init_module()函数,注意此函数与内核中的
      180.   //init_module()函数是不一样的,内核中的调用sys_init_module()
      181.  if (mod->init && (error = mod->init()) != 0) {
      182.   atomic_set(&mod->uc.usecount,0);//模块的计数加1
      183.   mod->flags &= ~MOD_INITIALIZING;//初始化标志清零
      184.   if (error > 0) /* Buggy module */
      185.    error = EBUSY;
      186.   goto err0;
      187.  }
      188.  atomic_dec(&mod->uc.usecount);//递减计数
      189.  //初始化标志清零,标志设置为MOD_RUNNING
      190.  mod->flags = (mod->flags | MOD_RUNNING) & ~MOD_INITIALIZING;
      191.  error = 0;
      192.  goto err0;
      193. err3:
      194.  put_mod_name(n_name);
      195. err2:
      196.  *mod = mod_tmp;
      197.  strcpy((char *)mod->name, name_tmp); /* We know there is room for this */
      198. err1:
      199.  put_mod_name(name);
      200. err0:
      201.  unlock_kernel();
      202.  kfree(name_tmp);
      203.  return error;
      204. }

    ---恢复内容结束---

    一、概述
    模块是作为ELF对象文件存放在文件系统中的,并通过执行insmod程序链接到内核中。对于每个模块,系统都要分配一个包含以下数据结构的内存区。
    一个module对象,表示模块名的一个以null结束的字符串,实现模块功能的代码。在2.6内核以前,insmod模块过程主要是通过modutils中的insmod加载,大量工作都是在用户空间完成。但在2.6内核以后,系统使用busybox的insmod指令,把大量工作移到内核代码处理,参见模块加载过程代码分析2.
    二、相关数据结构
    1.module对象描述一个模块。一个双向循环链表存放所有module对象,链表头部存放在modules变量中,而指向相邻单元的指针存放在每个module对象的list字段中。
    struct module
    {
     /*state 表示该模块的当前状态。 
     enum module_state 
     { 
         MODULE_STATE_LIVE, 
         MODULE_STATE_COMING, 
         MODULE_STATE_GOING, 
     }; 
     在装载期间,状态为 MODULE_STATE_COMING; 
     正常运行(完成所有初始化任务之后)时,状态为 MODULE_STATE_LIVE; 
     在模块正在卸载移除时,状态为 MODULE_STATE_GOING. 
     */
     enum module_state state;//模块内部状态
     //模块链表指针,将所有加载模块保存到一个双链表中,链表的表头是定义在 的全局变量 modules。 
     struct list_head list;
     char name[MODULE_NAME_LEN];//模块名
     /* Sysfs stuff. */
     struct module_kobject mkobj;//包含一个kobject数据结构
     struct module_attribute *modinfo_attrs;
     const char *version;
     const char *srcversion;
     struct kobject *holders_dir;
     /*syms,num_syms,crcs 用于管理模块导出的符号。syms是一个数组,有 num_syms 个数组项, 
     数组项类型为 kernel_symbol,负责将标识符(name)分配到内存地址(value): 
     struct kernel_symbol 
     { 
         unsigned long value; 
         const char *name; 
     }; 
     crcs 也是一个 num_syms 个数组项的数组,存储了导出符号的校验和,用于实现版本控制 
     */
     const struct kernel_symbol *syms;//指向导出符号数组的指针
     const unsigned long *crcs;//指向导出符号CRC值数组的指针
     unsigned int num_syms;//导出符号数
     struct kernel_param *kp;//内核参数
     unsigned int num_kp;//内核参数个数 
     /*在导出符号时,内核不仅考虑了可以有所有模块(不考虑许可证类型)使用的符号,还要考虑只能由 GPL 兼容模块使用的符号。 第三类的符号当前仍然可以有任意许可证的模块使用,但在不久的将来也会转变为只适用于 GPL 模块。gpl_syms,num_gpl_syms,gpl_crcs 成员用于只提供给 GPL 模块的符号;gpl_future_syms,num_gpl_future_syms,gpl_future_crcs 用于将来只提供给 GPL 模块的符号。unused_gpl_syms 和 unused_syms 以及对应的计数器和校验和成员描述。 这两个数组用于存储(只适用于 GPL)已经导出, 但 in-tree 模块未使用的符号。在out-of-tree 模块使用此类型符号时,内核将输出一个警告消息。 
    */ 
     unsigned int num_gpl_syms;//GPL格式导出符号数
     const struct kernel_symbol *gpl_syms;//指向GPL格式导出符号数组的指针
     const unsigned long *gpl_crcs;//指向GPL格式导出符号CRC值数组的指针
     
    #ifdef CONFIG_MODULE_SIG  
     bool sig_ok;/* Signature was verified. */
    #endif
      /* symbols that will be GPL-only in the near future. */
     const struct kernel_symbol *gpl_future_syms;
     const unsigned long *gpl_future_crcs;
     unsigned int num_gpl_future_syms;
      
     /*如果模块定义了新的异常,异常的描述保存在 extable数组中。 num_exentries 指定了数组的长度。 */
     unsigned int num_exentries;
     struct exception_table_entry *extable;
      
      /*模块的二进制数据分为两个部分;初始化部分和核心部分。 
     前者包含的数据在转载结束后都可以丢弃(例如:初始化函数),后者包含了正常运行期间需要的所有数据。   
     初始化部分的起始地址保存在 module_init,长度为 init_size 字节; 
     核心部分有 module_core 和 core_size 描述。 
     */
     int (*init)(void);//模块初始化方法,指向一个在模块初始化时调用的函数
     void *module_init;//用于模块初始化的动态内存区指针
     void *module_core;//用于模块核心函数与数据结构的动态内存区指针
     //用于模块初始化的动态内存区大小和用于模块核心函数与数据结构的动态内存区指针
     unsigned int init_size, core_size;
     //模块初始化的可执行代码大小,模块核心可执行代码大小,只当模块链接时使用
     unsigned int init_text_size, core_text_size;
     /* Size of RO sections of the module (text+rodata) */
     unsigned int init_ro_size, core_ro_size;
     struct mod_arch_specific arch;//依赖于体系结构的字段
     /*如果模块会污染内核,则设置 taints.污染意味着内核怀疑该模块做了一个有害的事情,可能妨碍内核的正常运作。 
     如果发生内核恐慌(在发生致命的内部错误,无法恢复正常运作时,将触发内核恐慌),那么错误诊断也会包含为什么内核被污染的有关信息。 
     这有助于开发者区分来自正常运行系统的错误报告和包含某些可疑因素的系统错误。 
     add_taint_module 函数用来设置 struct module 的给定实例的 taints 成员。 
      
     模块可能因两个原因污染内核: 
     1,如果模块的许可证是专有的,或不兼容 GPL,那么在模块载入内核时,会使用 TAINT_PROPRIETARY_MODULE. 
       由于专有模块的源码可能弄不到,模块在内核中作的任何事情都无法跟踪,因此,bug 很可能是由模块引入的。 
      
       内核提供了函数 license_is_gpl_compatible 来判断给定的许可证是否与 GPL 兼容。 
     2,TAINT_FORCED_MODULE 表示该模块是强制装载的。如果模块中没有提供版本信息,也称为版本魔术(version magic), 
       或模块和内核某些符号的版本不一致,那么可以请求强制装载。  
     */
     unsigned int taints;    /* same bits as kernel:tainted */
     char *args;//模块链接时使用的命令行参数
     
    #ifdef CONFIG_SMP/
     void __percpu *percpu;/*percpu 指向属于模块的各 CPU 数据。它在模块装载时初始化*/   
     unsigned int percpu_size;
    #endif
     
    #ifdef CONFIG_TRACEPOINTS
     unsigned int num_tracepoints;
     struct tracepoint * const *tracepoints_ptrs;
    #endif
    #ifdef HAVE_JUMP_LABEL
     struct jump_entry *jump_entries;
     unsigned int num_jump_entries;
    #endif
    #ifdef CONFIG_TRACING
      unsigned int num_trace_bprintk_fmt;
     const char **trace_bprintk_fmt_start;
    #endif
    #ifdef CONFIG_EVENT_TRACING
     struct ftrace_event_call **trace_events;
     unsigned int num_trace_events;
    #endif
    #ifdef CONFIG_FTRACE_MCOUNT_RECORD
     unsigned int num_ftrace_callsites;
     unsigned long *ftrace_callsites;
    #endif
     
    #ifdef CONFIG_MODULE_UNLOAD
     /* What modules depend on me? */
     struct list_head source_list;
     /* What modules do I depend on? */
     struct list_head target_list;
     struct task_struct *waiter;//正卸载模块的进程
     void (*exit)(void);//模块退出方法
     /*module_ref 用于引用计数。系统中的每个 CPU,都对应到该数组中的数组项。该项指定了系统中有多少地方使用了该模块。 
    内核提供了 try_module_get 和 module_put 函数,用对引用计数器加1或减1,如果调用者确信相关模块当前没有被卸载, 
    也可以使用 __module_get 对引用计数加 1.相反,try_module_get 会确认模块确实已经加载。
     struct module_ref { 
       unsigned int incs; 
       unsigned int decs; 
      } 
    */ 
     struct module_ref __percpu *refptr;//模块计数器,每个cpu一个
     #endif

    #ifdef CONFIG_CONSTRUCTORS
     /* Constructor functions. */
     ctor_fn_t *ctors;
     unsigned int num_ctors;
    #endif
    };

    三、模块链接过程
    用户可以通过执行insmod外部程序把一个模块链接到正在运行的内核中。该过程执行以下操作:
    1.从命令行中读取要链接的模块名
    2.确定模块对象代码所在的文件在系统目录树中的位置。
    3.从磁盘读入存有模块目标代码的文件。
    4.调用init_module()系统调用。函数将模块二进制文件复制到内核,然后由内核完成剩余的任务。
    5.init_module函数通过系统调用层,进入内核到达内核函数 sys_init_module,这是加载模块的主要函数。
    6.结束。

    四、insmod过程解析
    1.obj_file记录模块信息
    struct obj_file
    {
      ElfW(Ehdr) header;//指向elf header
      ElfW(Addr) baseaddr;//模块的基址
      struct obj_section **sections;//指向节区头部表,包含每个节区头部
      struct obj_section *load_order;//节区load顺序
      struct obj_section **load_order_search_start;//
      struct obj_string_patch_struct *string_patches;//patch的字符串
      struct obj_symbol_patch_struct *symbol_patches;//patch的符号
      int (*symbol_cmp)(const char *, const char *);//指向strcmp函数
      unsigned long (*symbol_hash)(const char *);//指向obj_elf_hash函数
      unsigned long local_symtab_size;//局部符号表大小
      struct obj_symbol **local_symtab;//局部符号表
      struct obj_symbol *symtab[HASH_BUCKETS];//符号hash表
      const char *filename;//模块名
      char *persist;
    };

    2.obj_section记录模块节区信息
    struct obj_section
    {
      ElfW(Shdr) header;//指向本节区头结构
      const char *name;//节区名
      char *contents;//从节区头内容偏移处获得的节区内容
      struct obj_section *load_next;//指向下一个节区
      int idx;//该节区索引值
    };

    3.module_stat结构记录每一个模块的信息
    struct module_stat {
     char *name;//模块名称
     unsigned long addr;//模块地址
     unsigned long modstruct; /* COMPAT_2_0! *//* depends on architecture? */
     unsigned long size;//模块大小
     unsigned long flags;//标志
     long usecount;//模块计数
     size_t nsyms;//模块中的符号个数
     struct module_symbol *syms;//指向模块符号
     size_t nrefs;//模块依赖其他模块的个数
     struct module_stat **refs;//依赖的模块数组
     unsigned long status;//模块状态
    };

    4.
    struct load_info {
     Elf_Ehdr *hdr;//指向elf头
     unsigned long len;
     Elf_Shdr *sechdrs;//指向节区头
     char *secstrings;//指向节区名称的字符串节区
     char *strtab;//指向符号节区
     unsigned long symoffs, stroffs;
     struct _ddebug *debug;
     unsigned int num_debug;
     bool sig_ok;
     struct {
      unsigned int sym, str, mod, vers, info, pcpu;
     } index;
    };

    5.代码分析

    1. int main(int argc, char **argv)
    2. {
    3.     /* List of possible program names and the corresponding mainline routines */
    4.     static struct { char *name; int (*handler)(int, char **); } mains[] =
    5.     {
    6.         { "insmod", &insmod_main },
    7. #ifdef COMBINE_modprobe
    8.         { "modprobe", &modprobe_main },
    9. #endif
    10. #ifdef COMBINE_rmmod
    11.     { "rmmod", &rmmod_main },
    12. #endif
    13. #ifdef COMBINE_ksyms
    14.     { "ksyms", &ksyms_main },
    15. #endif
    16. #ifdef COMBINE_lsmod
    17.     { "lsmod", &lsmod_main },
    18. #endif
    19. #ifdef COMBINE_kallsyms
    20.     { "kallsyms", &kallsyms_main },
    21. #endif
    22.     };
    23.     #define MAINS_NO (sizeof(mains)/sizeof(mains[0]))
    24.     static int mains_match;
    25.     static int mains_which;
    26.     
    27.     char *p = strrchr(argv[0], '/');//查找‘/’字符出现的位置
    28.     char error_id1[2048] = "The ";        /* Way oversized */
    29.     char error_id2[2048] = "";        /* Way oversized */
    30.     int i;
    31.     
    32.     p = p ? p + 1 : argv[0];//得到命令符,这里是insmod命令
    33.     
    34.     for (i = 0; i < MAINS_NO; ++i) {
    35.      if (i) {
    36.      xstrcat(error_id1, "/", sizeof(error_id1));//字符串连接函数
    37.      if (i == MAINS_NO-1)
    38.          xstrcat(error_id2, " or ", sizeof(error_id2));
    39.      else
    40.          xstrcat(error_id2, ", ", sizeof(error_id2));
    41.      }
    42.      xstrcat(error_id1, mains[i].name, sizeof(error_id1));
    43.      xstrcat(error_id2, mains[i].name, sizeof(error_id2));
    44.      if (strstr(p, mains[i].name)) {//命令跟数组的数据比较
    45.          ++mains_match;//insmod命令时,mains_match=1
    46.          mains_which = i;//得到insmod命令所在数组的位置,insmod命令为0
    47.      }
    48.     }
    49.     
    50.     /* Finish the error identifiers */
    51.     if (MAINS_NO != 1)
    52.         xstrcat(error_id1, " combined", sizeof(error_id1));
    53.     xstrcat(error_id1, " binary", sizeof(error_id1));
    54.     
    55.     if (mains_match == 0 && MAINS_NO == 1)
    56.         ++mains_match;        /* Not combined, any name will do */
    57.         
    58.     if (mains_match == 0) {
    59.         error("%s does not have a recognisable name, ""the name must contain one of %s.",error_id1, error_id2);
    60.         return(1);
    61.     }
    62.     else if (mains_match > 1) {
    63.         error("%s has an ambiguous name, it must contain %s%s.", error_id1, MAINS_NO == 1 ? "" : "exactly one of ", error_id2);
    64.         return(1);
    65.     }
    66.     else//mains_match=1,表示在数组中找到对应的指令
    67.         return((mains[mains_which].handler)(argc, argv));//调用insmod_main()函数
    68. }
    69. int insmod_main(int argc, char **argv)
    70. {
    71.     if (arch64())
    72.         return insmod_main_64(argc, argv);
    73.     else
    74.       return insmod_main_32(argc, argv);
    75. }
    76. #if defined(COMMON_3264) && defined(ONLY_32)
    77. #define INSMOD_MAIN insmod_main_32    /* 32 bit version */
    78. #elif defined(COMMON_3264) && defined(ONLY_64)
    79. #define INSMOD_MAIN insmod_main_64    /* 64 bit version */
    80. #else
    81. #define INSMOD_MAIN insmod_main        /* Not common code */
    82. #endif
    83. int INSMOD_MAIN(int argc, char **argv)
    84. {
    85.     int k_version;
    86.     int k_crcs;
    87.     char k_strversion[STRVERSIONLEN];
    88.     struct option long_opts[] = {
    89.      {"force", 0, 0, 'f'},
    90.      {"help", 0, 0, 'h'},
    91.      {"autoclean", 0, 0, 'k'},
    92.      {"lock", 0, 0, 'L'},
    93.      {"map", 0, 0, 'm'},
    94.      {"noload", 0, 0, 'n'},
    95.      {"probe", 0, 0, 'p'},
    96.      {"poll", 0, 0, 'p'},    /* poll is deprecated, remove in 2.5 */
    97.      {"quiet", 0, 0, 'q'},
    98.      {"root", 0, 0, 'r'},
    99.      {"syslog", 0, 0, 's'},
    100.      {"kallsyms", 0, 0, 'S'},
    101.      {"verbose", 0, 0, 'v'},
    102.      {"version", 0, 0, 'V'},
    103.      {"noexport", 0, 0, 'x'},
    104.      {"export", 0, 0, 'X'},
    105.      {"noksymoops", 0, 0, 'y'},
    106.      {"ksymoops", 0, 0, 'Y'},
    107.      {"persist", 1, 0, 'e'},
    108.      {"numeric-only", 1, 0, 'N'},
    109.      {"name", 1, 0, 'o'},
    110.      {"blob", 1, 0, 'O'},
    111.      {"prefix", 1, 0, 'P'},
    112.      {0, 0, 0, 0}
    113.     };
    114.     char *m_name = NULL;
    115.     char *blob_name = NULL;        /* Save object as binary blob */
    116.     int m_version;
    117.     ElfW(Addr) m_addr;
    118.     unsigned long m_size;
    119.     int m_crcs;
    120.     char m_strversion[STRVERSIONLEN];
    121.     char *filename;
    122.     char *persist_name = NULL;    /* filename to hold any persistent data */
    123.     int fp;
    124.     struct obj_file *f;
    125.     struct obj_section *kallsyms = NULL, *archdata = NULL;
    126.     int o;
    127.     int noload = 0;
    128.     int dolock = 1; /*Note: was: 0; */
    129.     int quiet = 0;
    130.     int exit_status = 1;
    131.     int force_kallsyms = 0;
    132.     int persist_parms = 0;    /* does module have persistent parms? */
    133.     int i;
    134.     int gpl;
    135.     
    136.     error_file = "insmod";
    137.     
    138.     /* To handle repeated calls from combined modprobe */
    139.     errors = optind = 0;
    140.     
    141.     /* Process the command line. */
    142.     while ((o = getopt_long(argc, argv, "fhkLmnpqrsSvVxXyYNe:o:O:P:R:",&long_opts[0], NULL)) != EOF)
    143.      switch (o) {
    144.      case 'f':    /* force loading */
    145.      flag_force_load = 1;
    146.      break;
    147.      case 'h': /* Print the usage message. */
    148.      insmod_usage();
    149.      break;
    150.      case 'k':    /* module loaded by kerneld, auto-cleanable */
    151.      flag_autoclean = 1;
    152.      break;
    153.      case 'L':    /* protect against recursion. */
    154.      dolock = 1;
    155.      break;
    156.      case 'm':    /* generate load map */
    157.      flag_load_map = 1;
    158.      break;
    159.      case 'n':    /* don't load, just check */
    160.      noload = 1;
    161.      break;
    162.      case 'p':    /* silent probe mode */
    163.      flag_silent_probe = 1;
    164.      break;
    165.      case 'q':    /* Don't print unresolved symbols */
    166.      quiet = 1;
    167.      break;
    168.      case 'r':    /* allow root to load non-root modules */
    169.      root_check_off = !root_check_off;
    170.      break;
    171.      case 's':    /* start syslog */
    172.      setsyslog("insmod");
    173.      break;
    174.      case 'S':    /* Force kallsyms */
    175.      force_kallsyms = 1;
    176.      break;
    177.      case 'v':    /* verbose output */
    178.      flag_verbose = 1;
    179.      break;
    180.      case 'V':
    181.      fputs("insmod version " MODUTILS_VERSION " ", stderr);
    182.      break;
    183.      case 'x':    /* do not export externs */
    184.      flag_export = 0;
    185.      break;
    186.      case 'X':    /* do export externs */
    187.     #ifdef HAS_FUNCTION_DESCRIPTORS
    188.      fputs("This architecture has function descriptors, exporting everything is unsafe "
    189.      "You must explicitly export the desired symbols with EXPORT_SYMBOL() ", stderr);
    190.     #else
    191.      flag_export = 1;
    192.     #endif
    193.      break;
    194.      case 'y':    /* do not define ksymoops symbols */
    195.      flag_ksymoops = 0;
    196.      break;
    197.      case 'Y':    /* do define ksymoops symbols */
    198.      flag_ksymoops = 1;
    199.      break;
    200.      case 'N':    /* only check numeric part of kernel version */
    201.      flag_numeric_only = 1;
    202.      break;
    203.     
    204.      case 'e':    /* persistent data filename */
    205.      free(persist_name);
    206.      persist_name = xstrdup(optarg);
    207.      break;
    208.      case 'o':    /* name the output module */
    209.      m_name = optarg;
    210.      break;
    211.      case 'O':    /* save the output module object */
    212.      blob_name = optarg;
    213.      break;
    214.      case 'P':    /* use prefix on crc */
    215.      set_ncv_prefix(optarg);
    216.      break;
    217.     
    218.      default:
    219.      insmod_usage();
    220.      break;
    221.      }
    222.     
    223.     if (optind >= argc) {//参数为0,则输出insmod用法介绍
    224.         insmod_usage();
    225.     }
    226.     filename = argv[optind++];//获得要加载的模块路径名
    227.     
    228.     if (config_read(0, NULL, "", NULL) < 0) {//modutil配置相关???
    229.         error("Failed handle configuration");
    230.   }
    231.     //清空persist_name 
    232.   if (persist_name && !*persist_name &&(!persistdir || !*persistdir)) {
    233.     free(persist_name);
    234.     persist_name = NULL;
    235.     if (flag_verbose) {
    236.         lprintf("insmod: -e "" ignored, no persistdir");
    237.       ++warnings;
    238.     }
    239.   }
    240.   if (m_name == NULL) {
    241.      size_t len;
    242.      char *p;
    243.         
    244.         //根据模块的路径名获取模块的名称
    245.      if ((p = strrchr(filename, '/')) != NULL)//找到最后一个'/'的位置
    246.          p++;
    247.      else
    248.          p = filename;
    249.          
    250.      len = strlen(p);
    251.      //去除模块名的后缀,保存在m_name中
    252.      if (len > 2 && p[len - 2] == '.' && p[len - 1] == 'o')
    253.          len -= 2;
    254.      else if (len > 4 && p[len - 4] == '.' && p[len - 3] == 'm'&& p[len - 2] == 'o' && p[len - 1] == 'd')
    255.          len -= 4;
    256. #ifdef CONFIG_USE_ZLIB
    257.      else if (len > 5 && !strcmp(p + len - 5, ".o.gz"))
    258.          len -= 5;
    259. #endif
    260.     
    261.      m_name = xmalloc(len + 1);
    262.      memcpy(m_name, p, len);//模块名称拷贝到m_name[]中
    263.      m_name[len] = '';
    264.   }
    265.   //根据模块路径,检查模块是否存在
    266.   if (!strchr(filename, '/') && !strchr(filename, '.')) {
    267.      char *tmp = search_module_path(filename);//查找模块路径???
    268.      if (tmp == NULL) {
    269.          error("%s: no module by that name found", filename);
    270.          return 1;
    271.      }
    272.      filename = tmp;
    273.      lprintf("Using %s", filename);
    274.   } else if (flag_verbose)
    275.       lprintf("Using %s", filename);
    276.   //打开要加载的模块文件
    277.   if ((fp = gzf_open(filename, O_RDONLY)) == -1) {
    278.       error("%s: %m", filename);
    279.       return 1;
    280.   }
    281.   /* Try to prevent multiple simultaneous loads. */
    282.   if (dolock)
    283.       flock(fp, LOCK_EX);
    284.   /*
    285.   type的三种类型,影响get_kernle_info的流程。
    286.   #define K_SYMBOLS 1 //Want info about symbols
    287.   #define K_INFO 2 Want extended module info
    288.   #define K_REFS 4 Want info about references
    289.   */
    290.   //负责取得kernel中先以注册的modules,放入module_stat中,并将kernel实现的各个symbol放入ksyms中,个数为ksyms。get_kernel_info最终调用new_get_kernel_info
    291.   if (!get_kernel_info(K_SYMBOLS))
    292.       goto out;
    293.   set_ncv_prefix(NULL);//判断symbol name中是否有前缀,象_smp之类,这里没有。
    294.   for (i = 0; !noload && i < n_module_stat; ++i) {//判断是否有同名的模块存在
    295.         if (strcmp(module_stat[i].name, m_name) == 0) {//遍历kernel中所有的模块,比较名称
    296.             error("a module named %s already exists", m_name);
    297.             goto out;
    298.         }
    299.   }
    300.   error_file = filename;
    301.   if ((f = obj_load(fp, ET_REL, filename)) == NULL)//将模块文件读入到struct obj_file结构f
    302.       goto out;
    303.   if (check_gcc_mismatch(f, filename))//检查编译器版本
    304.       goto out;
    305.   //检查内核和module的版本信息
    306.   k_version = get_kernel_version(k_strversion);
    307.   m_version = get_module_version(f, m_strversion);
    308.   if (m_version == -1) {
    309.         error("couldn't find the kernel version the module was compiled for");
    310.       goto out;
    311.   }
    312.     
    313.     //接下来还要测试内核和模块是否使用了版本的附加信息
    314.   k_crcs = is_kernel_checksummed();
    315.   m_crcs = is_module_checksummed(f);
    316.   if ((m_crcs == 0 || k_crcs == 0) &&strncmp(k_strversion, m_strversion, STRVERSIONLEN) != 0) {
    317.     if (flag_force_load) {
    318.         lprintf("Warning: kernel-module version mismatch "
    319.           " %s was compiled for kernel version %s "
    320.           " while this kernel is version %s",
    321.           filename, m_strversion, k_strversion);
    322.         ++warnings;
    323.     } else {
    324.         if (!quiet)
    325.           error("kernel-module version mismatch "
    326.             " %s was compiled for kernel version %s "
    327.             " while this kernel is version %s.",
    328.             filename, m_strversion, k_strversion);
    329.         goto out;
    330.     }
    331.   }
    332.   if (m_crcs != k_crcs)//设置新的符号比较函数和hash函数,重构hash表(即symtab表)。
    333.         obj_set_symbol_compare(f, ncv_strcmp, ncv_symbol_hash);
    334.   //检查GPL license
    335.   gpl = obj_gpl_license(f, NULL) == 0;
    336.   
    337.   //替换模块中的symbol值为其他已经存在的模块中相同符号的值
    338.   //如果内核模块中有该符号,则将该符号的value该为内核中(ksyms[])的符号值
    339.   //修改的是hash符号表中或者局部符号表中的符号值
    340.   add_kernel_symbols(f, gpl);
    341. #ifdef COMPAT_2_0//linux 内核2.0版本以前
    342.   if (k_new_syscalls ? !create_this_module(f, m_name): !old_create_mod_use_count(f))
    343.         goto out;
    344. #else
    345.   if (!create_this_module(f, m_name))//创建.this节区,添加一个"__this_module"符号
    346.         goto out;
    347. #endif
    348.     
    349.     //这个函数的作用是创建文件的.GOT段,.GOT全称是global offset table。在这个节区里保存的是绝对地址,这些地址不受重定位的影响。如果程序需要直接引用符号的绝对地址,这些符号就必须在.GOT段中出现
    350.   arch_create_got(f);
    351.   if (!obj_check_undefineds(f, quiet)) {//检查是否还有未解析的symbol
    352.     if (!gpl && !quiet) {
    353.       if (gplonly_seen)
    354.           error(" "
    355.                     "Hint: You are trying to load a module without a GPL compatible license "
    356.                     " and it has unresolved symbols. The module may be trying to access "
    357.                     " GPLONLY symbols but the problem is more likely to be a coding or "
    358.                     " user error. Contact the module supplier for assistance, only they "
    359.                     " can help you. ");
    360.       else
    361.           error(" "
    362.                     "Hint: You are trying to load a module without a GPL compatible license "
    363.                     " and it has unresolved symbols. Contact the module supplier for "
    364.                     " assistance, only they can help you. ");
    365.     }
    366.     goto out;
    367.   }
    368.   obj_allocate_commons(f);//处理未分配资源的符号
    369.     
    370.     //检查模块参数,即检查那些模块通过module_param(type, charp, S_IRUGO);声明的参数
    371.   check_module_parameters(f, &persist_parms);
    372.   check_tainted_module(f, noload);//???
    373.   if (optind < argc) {//如果命令行里带了参数,处理命令行参数
    374.         if (!process_module_arguments(f, argc - optind, argv + optind, 1))
    375.             goto out;
    376.   }
    377.   //将符号“cleanup_module”,“init_module”,“kernel_version”的属性改为local(局部),从而使其外部不可见
    378.   hide_special_symbols(f);
    379.     
    380.     //如果命令行参数来自文件,将文件名保存好,下面要从那里读出参数值
    381.   if (persist_parms && persist_name && *persist_name) {
    382.         f->persist = persist_name;
    383.         persist_name = NULL;
    384.   }
    385.     //防止-e""这样的恶作剧
    386.   if (persist_parms &&persist_name && !*persist_name) {
    387.     int j, l = strlen(filename);
    388.     char *relative = NULL;
    389.     char *p;
    390.     for (i = 0; i < nmodpath; ++i) {
    391.      p = modpath[i].path;
    392.      j = strlen(p);
    393.      while (j && p[j] == '/')
    394.          --j;
    395.      if (j < l && strncmp(filename, p, j) == 0 && filename[j] == '/') {
    396.          while (filename[j] == '/')
    397.          ++j;
    398.          relative = xstrdup(filename+j);
    399.          break;
    400.      }
    401.     }
    402.     if (relative) {
    403.       i = strlen(relative);
    404.       if (i > 3 && strcmp(relative+i-3, ".gz") == 0)
    405.           relative[i -= 3] = '';
    406.       if (i > 2 && strcmp(relative+i-2, ".o") == 0)
    407.           relative[i -= 2] = '';
    408.       else if (i > 4 && strcmp(relative+i-4, ".mod") == 0)
    409.           relative[i -= 4] = '';
    410.       f->persist = xmalloc(strlen(persistdir) + 1 + i + 1);
    411.       strcpy(f->persist, persistdir);    /* safe, xmalloc */
    412.       strcat(f->persist, "/");    /* safe, xmalloc */
    413.       strcat(f->persist, relative);    /* safe, xmalloc */
    414.       free(relative);
    415.     }
    416.     else
    417.             error("Cannot calculate persistent filename");
    418.   }
    419.     //接下来是一些健康检查
    420.   if (f->persist && *(f->persist) != '/') {
    421.      error("Persistent filenames must be absolute, ignoring '%s'", f->persist);
    422.      free(f->persist);
    423.      f->persist = NULL;
    424.   }
    425.   if (f->persist && !flag_ksymoops) {
    426.     error("has persistent data but ksymoops symbols are not available");
    427.     free(f->persist);
    428.     f->persist = NULL;
    429.   }
    430.   if (f->persist && !k_new_syscalls) {
    431.     error("has persistent data but the kernel is too old to support it");
    432.     free(f->persist);
    433.     f->persist = NULL;
    434.   }
    435.   if (persist_parms && flag_verbose) {
    436.     if (f->persist)
    437.         lprintf("Persist filename '%s'", f->persist);
    438.     else
    439.         lprintf("No persistent filename available");
    440.   }
    441.   if (f->persist) {
    442.      FILE *fp = fopen(f->persist, "r");
    443.      if (!fp) {
    444.      if (flag_verbose)
    445.      lprintf("Cannot open persist file '%s' %m", f->persist);
    446.      }
    447.      else {
    448.      int pargc = 0;
    449.      char *pargv[1000];    /* hard coded but big enough */
    450.      char line[3000];    /* hard coded but big enough */
    451.      char *p;
    452.      while (fgets(line, sizeof(line), fp)) {
    453.      p = strchr(line, ' ');
    454.      if (!p) {
    455.      error("Persistent data line is too long %s", line);
    456.      break;
    457.      }
    458.      *p = '';
    459.      p = line;
    460.      while (isspace(*p))
    461.      ++p;
    462.      if (!*p || *p == '#')
    463.      continue;
    464.      if (pargc == sizeof(pargv)/sizeof(pargv[0])) {
    465.      error("More than %d persistent parameters", pargc);
    466.      break;
    467.      }
    468.      pargv[pargc++] = xstrdup(p);
    469.      }
    470.      fclose(fp);
    471.      if (!process_module_arguments(f, pargc, pargv, 0))
    472.      goto out;
    473.      while (pargc--)
    474.      free(pargv[pargc]);
    475.      }
    476.   }
    477.     
    478.     //ksymoops 是一个调试辅助工具,它将试图将代码转换为指令并将堆栈值映射到内核符号。
    479.   if (flag_ksymoops)
    480.         add_ksymoops_symbols(f, filename, m_name);
    481.   if (k_new_syscalls)//k_new_syscalls标志用于测试内核版本
    482.         create_module_ksymtab(f);//创建模块要导出的符号节区ksymtab,并将要导出的符号加入该节区
    483.   //创建名为“__archdata” (宏 ARCH_SEC_NAME 的定义)的段
    484.   if (add_archdata(f, &archdata))
    485.         goto out;
    486.  //如果symbol使用的都是kernel提供的,就添加一个.kallsyms节区
    487.  //这个函数主要是处理内核导出符号。
    488.   if (add_kallsyms(f, &kallsyms, force_kallsyms))
    489.         goto out;
    490.   /**** No symbols or sections to be changed after kallsyms above ***/
    491.   if (errors)
    492.         goto out;
    493.   //如果flag_slient_probe已经设置,说明我们不想真正安装模块,只是想测试一下,那么到这里测试已经完成了,模块一切正常.
    494.   if (flag_silent_probe) {
    495.         exit_status = 0;
    496.         goto out;
    497.   }
    498.   
    499.   //计算载入模块所需的大小,即各个节区的大小和
    500.   m_size = obj_load_size(f);
    501.   
    502.   //如果noload设置了,那么我们选择不真正加载模块。随便给加载地址就完了.
    503.   if (noload) {
    504.        m_addr = 0x12340000;
    505.   } else {
    506.     errno = 0;
    507.     //调用sys_create_module系统调用创建模块,分配module的空间,返回模块在内核空间的地址.这里的module结构不是内核使用的那个,它定义在./modutilst-2.4.0/include/module.h中。函数最终会调用系统调用sys_create_module,生成一个模块对象,并链入模块的内核链表
    508.     //模块对象的大小就是各个节区大小的和,这里为什么分配的空间m_size不是sizeof(module)+各个节区大小的和?因为第一个节区.this的大小正好就是sizeof(module),所以第一个节区就是struct module结构。
    509.     //注意:区分后边还有一次在用户空间为模块分配空间,然后先把模块section拷贝到用户空间的模块影像中,然后再由sys_init_module()函数将用户空间的模块映像拷贝到内核空间的模块地址,即这里的m_addr。
    510.     m_addr = create_module(m_name, m_size);
    511.     m_addr |= arch_module_base (f);//#define arch_module_base(m) ((ElfW(Addr))0)
    512.     //检查是否成功创建module结构
    513.     switch (errno) {
    514.     case 0:
    515.         break;
    516.     case EEXIST:
    517.       if (dolock) {
    518.           exit_status = 0;
    519.           goto out;
    520.       }
    521.       error("a module named %s already exists", m_name);
    522.       goto out;
    523.     case ENOMEM:
    524.         error("can't allocate kernel memory for module; needed %lu bytes",m_size);
    525.       goto out;
    526.     default:
    527.       error("create_module: %m");
    528.       goto out;
    529.     }
    530.   }
    531.     //如果模块运行时参数使用了文件,而且需要真正加载
    532.   if (f->persist && !noload) {
    533.     struct {
    534.         struct module m;
    535.         int data;
    536.     } test_read;
    537.     memset(&test_read, 0, sizeof(test_read));
    538.     test_read.m.size_of_struct = -sizeof(test_read.m); /* -ve size => read, not write */
    539.     test_read.m.read_start = m_addr + sizeof(struct module);
    540.     test_read.m.read_end = test_read.m.read_start + sizeof(test_read.data);
    541.     if (sys_init_module(m_name, (struct module *) &test_read)) {
    542.      int old_errors = errors;
    543.      error("has persistent data but the kernel is too old to support it."
    544.      " Expect errors during rmmod as well");
    545.      errors = old_errors;
    546.     }
    547.   }
    548.     
    549.     //模块在内核的地址.而在模块elf文件里,节区在内存的位置是假设文件从0地址加载而得出的,现在就要根据base值调整。base就是create_module时分配的地址m_addr
    550.   if (!obj_relocate(f, m_addr)) {
    551.       if (!noload)
    552.         delete_module(m_name);
    553.       goto out;
    554.   }
    555.     //至此相当于磁盘中的elf文件格式的.ko文件的内容,已经全部加载到内存中,需要重定位的符号已经进行了重定位,符号地址变成了真正的在内存中的地址,即绝对地址。
    556.     
    557.   /* Do archdata again, this time we have the final addresses */
    558.   if (add_archdata(f, &archdata))
    559.           goto out;
    560.   //用绝对地址重新生成kallsyms段的内容
    561.   if (add_kallsyms(f, &kallsyms, force_kallsyms))
    562.           goto out;
    563. #ifdef COMPAT_2_0//2.0以前的版本
    564.   if (k_new_syscalls)
    565.       init_module(m_name, f, m_size, blob_name, noload, flag_load_map);
    566.   else if (!noload)
    567.       old_init_module(m_name, f, m_size);
    568. #else
    569.   init_module(m_name, f, m_size, blob_name, noload, flag_load_map);
    570. #endif
    571.   if (errors) {
    572.       if (!noload)
    573.         delete_module(m_name);
    574.       goto out;
    575.   }
    576.   if (warnings && !noload)
    577.       lprintf("Module %s loaded, with warnings", m_name);
    578.   exit_status = 0;
    579. out:
    580.   if (dolock)
    581.           flock(fp, LOCK_UN);
    582.   close(fp);
    583.   if (!noload)
    584.           snap_shot(NULL, 0);
    585.   return exit_status;
    586. }
    587. static int new_get_kernel_info(int type)
    588. {
    589.   struct module_stat *modules;
    590.   struct module_stat *m;
    591.   struct module_symbol *syms;
    592.   struct module_symbol *s;
    593.   size_t ret;
    594.   size_t bufsize;
    595.   size_t nmod;
    596.   size_t nsyms;
    597.   size_t i;
    598.   size_t j;
    599.   char *module_names;
    600.   char *mn;
    601.   drop();//首先清除module_stat内容,module_stat是个全局变量,保存模块信息
    602.     //指针分配空间
    603.   module_names = xmalloc(bufsize = 256);
    604.   //取得系统中现有所有的module名称,ret返回个数,module_names返回各个module名称,字符0分割
    605.   while (query_module(NULL, QM_MODULES, module_names, bufsize, &ret)) {
    606.      if (errno != ENOSPC) {
    607.      error("QM_MODULES: %m ");
    608.      return 0;
    609.      }
    610.      /*
    611.      会调用realloc(void *mem_address, unsigned int newsize)函数,此先判断当前的指针是否有足够的连续空间,如果有,扩大mem_address指向的地址,并且将mem_address返回,如果空间不够,先按照newsize指定的大小分配空间,将原有数据从头到尾拷贝到新分配的内存区域,而后释放原来mem_address所指内存区域(注意:原来指针是自动释放,不需要使用free),同时返回新分配的内存区域的首地址。即重新分配存储器块的地址。
    612.      */
    613.     module_names = xrealloc(module_names, bufsize = ret);
    614.   }
    615.   module_name_list = module_names;//指向系统中所有模块名称的起始地址
    616.   l_module_name_list = bufsize;//所有模块名称的大小,即module_names大小
    617.   n_module_stat = nmod = ret;//返回模块个数
    618.   //分配空间,地址付给全局变量module_stat
    619.   module_stat = modules = xmalloc(nmod * sizeof(struct module_stat));
    620.   memset(modules, 0, nmod * sizeof(struct module_stat));
    621.   //循环取得各个module的信息,QM_INFO的使用。
    622.   for (i = 0, mn = module_names, m = modules;i < nmod;++i, ++m, mn += strlen(mn) + 1) {
    623.       struct module_info info;
    624.       //info包括module的地址,大小,flag和使用计数器。
    625.       m->name = mn;//模块名称给module_stat结构
    626.       if (query_module(mn, QM_INFO, &info, sizeof(info), &ret)) {
    627.           if (errno == ENOENT) {
    628.               m->flags = NEW_MOD_DELETED;
    629.               continue;
    630.           }
    631.           error("module %s: QM_INFO: %m", mn);
    632.           return 0;
    633.       }
    634.       m->addr = info.addr;//模块地址给module_stat结构
    635.       if (type & K_INFO) {//取得module的信息
    636.           m->size = info.size;
    637.           m->flags = info.flags;
    638.           m->usecount = info.usecount;
    639.           m->modstruct = info.addr;
    640.       }//将info值传给module_stat结构
    641.       if (type & K_REFS) {//取得module的引用关系
    642.           int mm;
    643.           char *mrefs;
    644.           char *mr;
    645.           mrefs = xmalloc(bufsize = 64);
    646.           while (query_module(mn, QM_REFS, mrefs, bufsize, &ret)) {//查找mn模块引用的模块名
    647.               if (errno != ENOSPC) {
    648.                   error("QM_REFS: %m");
    649.                   return 1;
    650.               }
    651.               mrefs = xrealloc(mrefs, bufsize = ret);
    652.           }
    653.           for (j = 0, mr = mrefs;j < ret;++j, mr += strlen(mr) + 1) {
    654.               for (mm = 0; mm < i; ++mm) {
    655.                   if (strcmp(mr, module_stat[mm].name) == 0) {
    656.                       m->nrefs += 1;
    657.                       m->refs = xrealloc(m->refs, m->nrefs * sizeof(struct module_stat **));
    658.                       m->refs[m->nrefs - 1] = module_stat + mm;//引用的模块名
    659.                       break;
    660.                   }
    661.               }
    662.           }
    663.           free(mrefs);
    664.       }
    665.             
    666.             //这里是遍历内核中其他模块的所有符号
    667.       if (type & K_SYMBOLS) { /* 取得symbol信息,正是我们要得*/
    668.         syms = xmalloc(bufsize = 1024);
    669.         //取得mn模块的符号信息,保存在syms数组中
    670.         while (query_module(mn, QM_SYMBOLS, syms, bufsize, &ret)) {
    671.           if (errno == ENOSPC) {
    672.               syms = xrealloc(syms, bufsize = ret);
    673.               continue;
    674.           }
    675.           if (errno == ENOENT) {
    676.               m->flags = NEW_MOD_DELETED;
    677.               free(syms);
    678.               goto next;
    679.           } else {
    680.               error("module %s: QM_SYMBOLS: %m", mn);
    681.               return 0;
    682.           }
    683.         }
    684.         nsyms = ret;
    685.         //syms是module_symbol结构,ret返回symbol个数
    686.         m->nsyms = nsyms;//符号个数
    687.         m->syms = syms;//符号信息
    688.         //name原来只是一个结构内的偏移,加上结构地址为真正的字符串地址
    689.         for (j = 0, s = syms; j < nsyms; ++j, ++s)
    690.             s->name += (unsigned long) syms;
    691.       }
    692.       next:
    693.   }
    694.     //这里是取得内核符号
    695.   if (type & K_SYMBOLS) { /* Want info about symbols */
    696.       syms = xmalloc(bufsize = 16 * 1024);
    697.       //name为NULL,返回内核符号信息
    698.       while (query_module(NULL, QM_SYMBOLS, syms, bufsize, &ret)) {
    699.         if (errno != ENOSPC) {
    700.             error("kernel: QM_SYMBOLS: %m");
    701.             return 0;
    702.         }
    703.         syms = xrealloc(syms, bufsize = ret);//扩展空间
    704.       }
    705.       //将值返回给nksyms和ksyms两个全局变量存储。
    706.       nksyms = nsyms = ret;//内核符号个数
    707.       ksyms = syms;//内核符号
    708.       /* name原来只是一个结构内的偏移,加上结构地址为真正的字符串地址 */
    709.       for (j = 0, s = syms; j < nsyms; ++j, ++s)
    710.           s->name += (unsigned long) syms;
    711.   }
    712.   return 1;
    713. }
    714. struct obj_file *obj_load (int fp, Elf32_Half e_type, const char *filename)
    715. {
    716.   struct obj_file *f;
    717.   ElfW(Shdr) *section_headers;
    718.   int shnum, i;
    719.   char *shstrtab;
    720.   f = arch_new_file();//创建一个新的obj_file结构
    721.   memset(f, 0, sizeof(*f));
    722.   f->symbol_cmp = strcmp;//设置symbol名的比较函数就是strcmp
    723.   f->symbol_hash = obj_elf_hash;//设置计算symbol hash值的函数
    724.   f->load_order_search_start = &f->load_order;//??
    725.   gzf_lseek(fp, 0, SEEK_SET);//文件指针设置到文件头
    726.   //取得object文件的ELF头结构。
    727.   if (gzf_read(fp, &f->header, sizeof(f->header)) != sizeof(f->header))
    728.   {
    729.     error("cannot read ELF header from %s", filename);
    730.     return NULL;
    731.   }
    732.     
    733.     //判断ELF的magic,是否是ELF文件格式
    734.   if (f->header.e_ident[EI_MAG0] != ELFMAG0
    735.       || f->header.e_ident[EI_MAG1] != ELFMAG1
    736.       || f->header.e_ident[EI_MAG2] != ELFMAG2
    737.       || f->header.e_ident[EI_MAG3] != ELFMAG3)
    738.   {
    739.       error("%s is not an ELF file", filename);
    740.       return NULL;
    741.   }
    742.   //检查architecture
    743.   if (f->header.e_ident[EI_CLASS] != ELFCLASSM//i386的机器上为ELFCLASS32,表示32bit
    744.       || f->header.e_ident[EI_DATA] != ELFDATAM//此处值为ELFDATA2LSB,表示编码方式
    745.       || f->header.e_ident[EI_VERSION] != EV_CURRENT//此值固定,表示版本
    746.       || !MATCH_MACHINE(f->header.e_machine))//机器类型
    747.   {
    748.       error("ELF file %s not for this architecture", filename);
    749.       return NULL;
    750.   }
    751.   //判断目标文件类型
    752.   if (f->header.e_type != e_type && e_type != ET_NONE)//.ko文件类型必为ET_REL
    753.   {
    754.     switch (e_type) {
    755.      case ET_REL:
    756.              error("ELF file %s not a relocatable object", filename);
    757.              break;
    758.      case ET_EXEC:
    759.          error("ELF file %s not an executable object", filename);
    760.          break;
    761.      default:
    762.              error("ELF file %s has wrong type, expecting %d got %d",
    763.      filename, e_type, f->header.e_type);
    764.              break;
    765.     }
    766.     return NULL;
    767.   }
    768.     
    769.     //检查elf文件头指定的节区头的大小是否一致
    770.   if (f->header.e_shentsize != sizeof(ElfW(Shdr)))
    771.   {
    772.     error("section header size mismatch %s: %lu != %lu",filename,
    773.       (unsigned long)f->header.e_shentsize,
    774.       (unsigned long)sizeof(ElfW(Shdr)));
    775.     return NULL;
    776.   }
    777.   shnum = f->header.e_shnum;//文件中节区个数
    778.   f->sections = xmalloc(sizeof(struct obj_section *) * shnum);//为section开辟空间
    779.   memset(f->sections, 0, sizeof(struct obj_section *) * shnum);
    780.     
    781.     //每个节区都有一个节区头部表,为shnum个节区头部表分配空间
    782.   section_headers = alloca(sizeof(ElfW(Shdr)) * shnum);
    783.   gzf_lseek(fp, f->header.e_shoff, SEEK_SET);//指针移到节区头部表开始位置
    784.   //读取shnum个节区头部表(每个节区都有一个节区头部表)内容保存在section_headers中
    785.   if (gzf_read(fp, section_headers, sizeof(ElfW(Shdr))*shnum) != sizeof(ElfW(Shdr))*shnum)
    786.   {
    787.     error("error reading ELF section headers %s: %m", filename);
    788.     return NULL;
    789.   }
    790.   for (i = 0; i < shnum; ++i)//遍历所有的节区
    791.   {
    792.     struct obj_section *sec;
    793.     f->sections[i] = sec = arch_new_section();//分配内存给每个section
    794.     memset(sec, 0, sizeof(*sec));
    795.     sec->header = section_headers[i];//设置obj_section结构的sec的header指向本节区的节区头部表
    796.     sec->idx = i;//节区索引
    797.     switch (sec->header.sh_type)//section的类型
    798.      {
    799.          case SHT_NULL:
    800.          case SHT_NOTE:
    801.          case SHT_NOBITS:/* ignore */
    802.          break;        
    803.          case SHT_PROGBITS:
    804.          case SHT_SYMTAB:
    805.          case SHT_STRTAB:
    806.          case SHT_RELM://将以上各种类型的section内容读到sec->contents结构中。
    807.          if (sec->header.sh_size > 0)
    808.      {
    809.      sec->contents = xmalloc(sec->header.sh_size);
    810.      //指针移到节区的第一个字节与文件头之间的偏移
    811.      gzf_lseek(fp, sec->header.sh_offset, SEEK_SET);
    812.      //读取节区中内容
    813.      if (gzf_read(fp, sec->contents, sec->header.sh_size) != sec->header.sh_size)
    814.          {
    815.          error("error reading ELF section data %s: %m", filename);
    816.          return NULL;
    817.          }
    818.      }
    819.          else
    820.          sec->contents = NULL;
    821.          break;
    822.          //描述relocation的section
    823. #if SHT_RELM == SHT_REL
    824.          case SHT_RELA:
    825.          if (sec->header.sh_size) {
    826.          error("RELA relocations not supported on this architecture %s", filename);
    827.          return NULL;
    828.          }
    829.          break;
    830. #else
    831.          case SHT_REL:
    832.          if (sec->header.sh_size) {
    833.          error("REL relocations not supported on this architecture %s", filename);
    834.          return NULL;
    835.          }
    836.          break;
    837. #endif
    838.          default:
    839.          if (sec->header.sh_type >= SHT_LOPROC)
    840.      {
    841.      if (arch_load_proc_section(sec, fp) < 0)
    842.              return NULL;
    843.      break;
    844.      }
    845.         
    846.          error("can't handle sections of type %ld %s",(long)sec->header.sh_type, filename);
    847.          return NULL;
    848.       }
    849.   }
    850. //shstrndx存的是section字符串表的索引值,就是第几个section
    851. //shstrtab就是那个section了。找到节区名字符串节区,把字符串节区内容地址付给shstrtab指针
    852.   shstrtab = f->sections[f->header.e_shstrndx]->contents;
    853.   for (i = 0; i < shnum; ++i)
    854.   {
    855.     struct obj_section *sec = f->sections[i];
    856.     sec->name = shstrtab + sec->header.sh_name;//sh_name字段是节区头部字符串表节区的索引
    857.   }//根据strtab,取得每个section的名字
    858.     //遍历节区查找符号表
    859.   for (i = 0; i < shnum; ++i)
    860.   {
    861.     struct obj_section *sec = f->sections[i];
    862.     //也就是说即使modinfo和modstring有此标志位,也去掉。
    863.     if (strcmp(sec->name, ".modinfo") == 0 ||strcmp(sec->name, ".modstring") == 0)
    864.           sec->header.sh_flags &= ~SHF_ALLOC;//ALLOC表示此section是否占用内存,这两个节区不占用内存
    865.     if (sec->header.sh_flags & SHF_ALLOC)//此节区在进程执行过程中占用内存
    866.              obj_insert_section_load_order(f, sec);//确定section load的顺序,根据的是flag的类型加权得到优先级
    867.     switch (sec->header.sh_type)
    868.      {
    869.          case SHT_SYMTAB://符号表节区,就是.symtab节区
    870.          {
    871.      unsigned long nsym, j;
    872.      char *strtab;
    873.      ElfW(Sym) *sym;
    874.                 
    875.                 //节区的大小若不等于符号表结构的大小,则出错
    876.      if (sec->header.sh_entsize != sizeof(ElfW(Sym)))
    877.      {
    878.          error("symbol size mismatch %s: %lu != %lu",filename,(unsigned long)sec->header.sh_entsize,(unsigned long)sizeof(ElfW(Sym)));
    879.          return NULL;
    880.      }
    881.      
    882.      //计算符号表表项个数,nsym也就是symbol个数,我的fedcore有560个符号(结构)
    883.      nsym = sec->header.sh_size / sizeof(ElfW(Sym));
    884.      //sh_link是符号字符串表的索引值,f->sections[sec->header.sh_link]就是.strtab节区
    885.      strtab = f->sections[sec->header.sh_link]->contents;//符号字符串表节区的内容
    886.      sym = (ElfW(Sym) *) sec->contents;//符号表节区的内容Elf32_sym结构
    887.     
    888.      j = f->local_symtab_size = sec->header.sh_info;//本模块局部符号的size
    889.      f->local_symtab = xmalloc(j *= sizeof(struct obj_symbol *));//为本模块局部符号分配空间
    890.      memset(f->local_symtab, 0, j);
    891.     
    892.      //遍历要加载模块的符号表节区内容的符号Elf32_sym结构
    893.      for (j = 1, ++sym; j < nsym; ++j, ++sym)
    894.      {
    895.          const char *name;
    896.          if (sym->st_name)//有值就是符号字符串表strtab的索引值
    897.          name = strtab+sym->st_name;
    898.          else//如果为零,此symbol name是一个section的name,比如.rodata之类的
    899.          name = f->sections[sym->st_shndx]->name;
    900.          //obj_add_symbol将符号加入到f->symbab这个hash表中,sym->st_shndx是相关节区头部表索引。如果一个符号的取值引用了某个节区中的特定位置,那么它的节区索引成员(st_shndx)包含了其在节区头部表中的索引。(比如说符号“function_x”定义在节区.rodata中,则sym->st_shndx是节区.rodata的索引值,sym->st_value是指在该节区中的到符号位置的偏移,即符号“function_x”在模块中的地址由节区.rodata->contens+sym->st_value位置处的数值指定)
    901.          //局部符号会添加到f->local_symtab表中,其余符号会添加到hash表f->symtab中(),注意:局部符号也可能添加到hash表中
    902.          obj_add_symbol(f, name, j, sym->st_info, sym->st_shndx,sym->st_value, sym->st_size);
    903.          }
    904.          }
    905.              break;
    906.         }
    907.   }
    908.   //重定位是将符号引用与符号定义进行连接的过程。例如,当程序调用了一个函数时,相关的调用指令必须把控制传输到适当的目标执行地址。
    909.   for (i = 0; i < shnum; ++i)
    910.   {
    911.     struct obj_section *sec = f->sections[i];
    912.     switch (sec->header.sh_type)
    913.     {
    914.      case SHT_RELM://找到描述重定位的section
    915.       {
    916.         unsigned long nrel, j;
    917.         ElfW(RelM) *rel;
    918.         struct obj_section *symtab;
    919.         char *strtab;
    920.         if (sec->header.sh_entsize != sizeof(ElfW(RelM)))
    921.         {
    922.             error("relocation entry size mismatch %s: %lu != %lu",
    923.               filename,(unsigned long)sec->header.sh_entsize,
    924.               (unsigned long)sizeof(ElfW(RelM)));
    925.             return NULL;
    926.         }
    927.             //算出rel有几项,存到nrel中
    928.         nrel = sec->header.sh_size / sizeof(ElfW(RelM));
    929.         rel = (ElfW(RelM) *) sec->contents;
    930.         //rel的section中sh_link相关值是符号section的索引值,即.symtab符号节区
    931.         symtab = f->sections[sec->header.sh_link];
    932.         //而符号section中sh_link是符号字符串section的索引值,即找到.strtab节区
    933.         strtab = f->sections[symtab->header.sh_link]->contents;
    934.         //存储需要relocate的符号的rel的类型
    935.         for (j = 0; j < nrel; ++j, ++rel)
    936.         {
    937.      ElfW(Sym) *extsym;
    938.      struct obj_symbol *intsym;
    939.      unsigned long symndx;
    940.      symndx = ELFW(R_SYM)(rel->r_info);//取得要进行重定位的符号表索引
    941.      if(symndx)
    942.           {
    943.               //取得要进行重定位的符号(Elf32_sym结构)
    944.             extsym = ((ElfW(Sym) *) symtab->contents) + symndx;
    945.             //符号信息是局部的,别的文件不可见
    946.             if (ELFW(ST_BIND)(extsym->st_info) == STB_LOCAL)
    947.             {
    948.                 intsym = f->local_symtab[symndx];//要从局部符号表中获取
    949.             }
    950.             else//其他类型,从hash表中取
    951.             {
    952.      const char *name;
    953.      if (extsym->st_name)//有值就是符号字符串表.strtab的索引值
    954.      name = strtab + extsym->st_name;
    955.      else//如果为零,此symbol name是一个section的name,比如.rodata之类的
    956.      name = f->sections[extsym->st_shndx]->name;
    957.      //因为前边已添加到hash表中,从hash表中获取该要重定位的符号
    958.      intsym = obj_find_symbol(f, name);
    959.             }
    960.             intsym->r_type = ELFW(R_TYPE)(rel->r_info);//设置该符号的重定位类型,为以后进行符号重定位时使用
    961.           }
    962.         }
    963.       }
    964.      break;
    965.      }
    966.   }
    967.   f->filename = xstrdup(filename);
    968.   return f;
    969. }
    970. struct obj_symbol *obj_add_symbol (struct obj_file *f, const char *name, unsigned long symidx,int info, int secidx, ElfW(Addr) value, unsigned long size)
    971. {
    972.     //参数:name符号名,symidx符号索引值(在此模块中),secidx节区索引值,value符号值
    973.   struct obj_symbol *sym;
    974.   unsigned long hash = f->symbol_hash(name) % HASH_BUCKETS;//计算出hash值
    975.   int n_type = ELFW(ST_TYPE)(info);//要添加的符号类型
    976.   int n_binding = ELFW(ST_BIND)(info);//要添加的符号绑定类型,例如:STB_LOCAL或STB_GLOBAL
    977.     //遍历hash表中是否已添加了此符号,根据符号类型做不同处理
    978.   for (sym = f->symtab[hash]; sym; sym = sym->next)
    979.     if (f->symbol_cmp(sym->name, name) == 0)
    980.     {
    981.             int o_secidx = sym->secidx;
    982.             int o_info = sym->info;
    983.             int o_type = ELFW(ST_TYPE)(o_info);
    984.             int o_binding = ELFW(ST_BIND)(o_info);
    985.             
    986.             if (secidx == SHN_UNDEF)//如果要加入的符号的属性是SHN_UNDEF,即未定义,不用处理
    987.              return sym;
    988.             else if (o_secidx == SHN_UNDEF)//如果已加入的符号属性是SHN_UNDEF,则用新的符号替换。
    989.              goto found;
    990.             else if (n_binding == STB_GLOBAL && o_binding == STB_LOCAL)//新添加的符号是global,而old符号是局部符号,那么就将STB_GLOBAL符号替换掉STB_LOCAL 符号。
    991.             {    
    992.          struct obj_symbol *nsym, **p;
    993.     
    994.          nsym = arch_new_symbol();
    995.          nsym->next = sym->next;
    996.          nsym->ksymidx = -1;
    997.     
    998.          //从链表中删除旧的符号
    999.          for (p = &f->symtab[hash]; *p != sym; p = &(*p)->next)
    1000.          continue;
    1001.          *p = sym = nsym;//新的符号替换旧的符号
    1002.          goto found;
    1003.             }
    1004.             else if (n_binding == STB_LOCAL)//新添加的符号是局部符号,则加入到local_symtab表中,不加入 symtab
    1005.          {
    1006.          sym = arch_new_symbol();
    1007.          sym->next = NULL;
    1008.          sym->ksymidx = -1;
    1009.          f->local_symtab[symidx] = sym;
    1010.          goto found;
    1011.          }
    1012.             else if (n_binding == STB_WEAK)//新加入的符号是weak属性,则不需处理
    1013.              return sym;
    1014.             else if (o_binding == STB_WEAK)//如果已加入的符号属性是STB_WEAK,则用新的符号替换。
    1015.              goto found;
    1016.             else if (secidx == SHN_COMMON&& (o_type == STT_NOTYPE || o_type == STT_OBJECT))
    1017.              return sym;
    1018.             else if (o_secidx == SHN_COMMON&& (n_type == STT_NOTYPE || n_type == STT_OBJECT))
    1019.              goto found;
    1020.             else
    1021.          {
    1022.          if (secidx <= SHN_HIRESERVE)
    1023.          error("%s multiply defined", name);
    1024.          return sym;
    1025.          }
    1026.     }
    1027.     
    1028.     //该符号没有在hash符号表中添加过,所以有可能一个局部符号添加到了hash表中
    1029.   sym = arch_new_symbol();//分配一个新的符号结构体
    1030.   sym->next = f->symtab[hash];//链入hash数组中f->symtab[hash]
    1031.   f->symtab[hash] = sym;
    1032.   sym->ksymidx = -1;
    1033.     //若是局部符号(别的文件不可见),则将该符号添加到f->local_symtab[]数组中
    1034.   if (ELFW(ST_BIND)(info) == STB_LOCAL && symidx != -1) {
    1035.     if (symidx >= f->local_symtab_size)
    1036.       error("local symbol %s with index %ld exceeds local_symtab_size %ld",
    1037.         name, (long) symidx, (long) f->local_symtab_size);
    1038.     else
    1039.       f->local_symtab[symidx] = sym;
    1040.   }
    1041. found:
    1042.   sym->name = name;//符号名
    1043.   sym->value = value;//符号值
    1044.   sym->size = size;//符号大小
    1045.   sym->secidx = secidx;//节区索引值
    1046.   sym->info = info;//符号类型和绑定信息
    1047.   sym->r_type = 0;//重定位类型初始为0
    1048.   return sym;
    1049. }
    1050. void obj_set_symbol_compare (struct obj_file *f,int (*cmp)(const char *, const char *),
    1051.             unsigned long (*hash)(const char *))
    1052. {
    1053.   if (cmp)
    1054.     f->symbol_cmp = cmp;//符号比较函数
    1055.   if (hash)
    1056.   {
    1057.     struct obj_symbol *tmptab[HASH_BUCKETS], *sym, *next;
    1058.     int i;
    1059.     f->symbol_hash = hash;//hash函数
    1060.     memcpy(tmptab, f->symtab, sizeof(tmptab));//先将符号信息保存在临时数组tmptab
    1061.     memset(f->symtab, 0, sizeof(f->symtab));//清空hash表
    1062.         
    1063.         //重新使用hash函数将符号添加到符号表f->symtab中
    1064.     for (i = 0; i < HASH_BUCKETS; ++i)
    1065.             for (sym = tmptab[i]; sym ; sym = next)
    1066.           {
    1067.          unsigned long h = hash(sym->name) % HASH_BUCKETS;
    1068.          next = sym->next;
    1069.          sym->next = f->symtab[h];
    1070.          f->symtab[h] = sym;
    1071.           }
    1072.   }
    1073. }
    1074. static const char *gpl_licenses[] = {
    1075.     "GPL",
    1076.     "GPL v2",
    1077.     "GPL and additional rights",
    1078.     "Dual BSD/GPL",
    1079.     "Dual MPL/GPL",
    1080. };
    1081. int obj_gpl_license(struct obj_file *f, const char **license)
    1082. {
    1083.     struct obj_section *sec;
    1084.     //找到.modinfo节区
    1085.     if ((sec = obj_find_section(f, ".modinfo"))) {
    1086.         const char *value, *ptr, *endptr;
    1087.         ptr = sec->contents;//指向该节区内容其实地址
    1088.         endptr = ptr + sec->header.sh_size;//节区内容结束地址
    1089.         
    1090.         while (ptr < endptr) {
    1091.             //找到以”license=“起始的字符串
    1092.             if ((value = strchr(ptr, '=')) && strncmp(ptr, "license", value-ptr) == 0) {
    1093.                 int i;
    1094.                 if (license)
    1095.                     *license = value+1;
    1096.                 for (i = 0; i < sizeof(gpl_licenses)/sizeof(gpl_licenses[0]); ++i) {
    1097.                     if (strcmp(value+1, gpl_licenses[i]) == 0)//比较是否与以上数组相同的license
    1098.                         return(0);
    1099.                 }
    1100.                 return(2);
    1101.             }
    1102.             //否则从下一个字符串开始再查找
    1103.             if (strchr(ptr, ''))
    1104.                 ptr = strchr(ptr, '') + 1;
    1105.             else
    1106.                 ptr = endptr;
    1107.         }
    1108.     }
    1109.     return(1);
    1110. }
    1111. static void add_kernel_symbols(struct obj_file *f)
    1112. {
    1113.     struct module_stat *m;
    1114.     size_t i, nused = 0;
    1115.     //注意:此处虽然将模块的全局符号用内核和其他模块的符号替换过了,而且符号结构obj_symbol的secidx字段被重新写成了SHN_HIRESERVE以上的数值。对于一些全局的未定义符号(原来的secidx为SHN_UNDEF),现在这些未定义符号的secidx字段也被重新写成了SHN_HIRESERVE以上的数值。但是这些未定义符号对于elf文件格式的符号结构Elf32_sym中的字段st_shndx的取值并未改变,仍是SHN_UNDEF。这样做的原因是:在模块的编译过程中会生成一个__versions节区,该节区中存放的都是该模块中使用到,但没被定义的符号,也就是所谓的 unresolved symbol,它们或在基本内核中定义,或在其他模块中定义,内核使用它们来做 Module versioning。注意其中的 module_layout 符号,这是一个 dummy symbol。内核使用它来跟踪不同内核版本关于模块处理的相关数据结构的变化。所以该节区的未定义的符号虽然在这里被内核符号或其他模块符号已替换,但是它本身的SHN_UNDEF性质没有改变,用来对之后模块加载时的crc校验。因为crc校验时就是检查这些SHN_UNDEF性质的符号的crc值。参见内核函数simplify_symbols()。
    1116.     //而且__versions节区的未定义的符号必须是内核或内核其他模块用到的符号,这样在此系统下编译的模块安装到另一个系统上时,根据这些全局符号的crc值就能知道此模块是不是在此系统上编译的。还有这些符号虽然被设置为未定义的,但是通过符号替换,仍能得到符号的绝对地址,从而被模块引用。
    1117.     /* 使用系统中已有的module中的symbol,更新symbol的值,重新写入hash表或者局部符号表。注意:要加载的模块还没有加入到module_stat数组中 */
    1118.     for (i = 0, m = module_stat; i < n_module_stat; ++i, ++m)
    1119.         //遍历每个模块的符号表,符号对应的节区是SHN_LORESERVE以上的节区号。节区序号大于SHN_LORESERVE的符号,是没有对应的节区的。因此,符号里的值就认为是绝对地址。内核和已加载模块导出符号就处在这个区段。
    1120.       if (m->nsyms && add_symbols_from(f, SHN_HIRESERVE + 2 + i, m->syms, m->nsyms))
    1121.       {
    1122.           m->status = 1;//表示此模块被引用了
    1123.           ++nused;
    1124.       }
    1125.     n_ext_modules_used = nused;//该模块依赖的内核其余模块的个数
    1126.     //使用kernel导出的symbol,更新symbol的值,重新写入hash表或者局部符号表.SHN_HIRESERVE对应系统保留节区的上限,使用SHN_HIRESERVE以上的节区来保存已加载模块的符号和内核符号。
    1127.     if (nksyms)
    1128.         add_symbols_from(f, SHN_HIRESERVE + 1, ksyms, nksyms);
    1129. }
    1130. static int add_symbols_from(struct obj_file *f, int idx,struct module_symbol *syms, size_t nsyms)
    1131. {
    1132.     struct module_symbol *s;
    1133.     size_t i;
    1134.     int used = 0;
    1135.         
    1136.         //遍历该模块的所有符号
    1137.     for (i = 0, s = syms; i < nsyms; ++i, ++s) {
    1138.         struct obj_symbol *sym;
    1139.         //从hash表中是否有需要此名字的的symbol,局部符号表中的符号不需要内核符号替换
    1140.         sym = obj_find_symbol(f, (char *) s->name);
    1141.         //从要加载模块的hash表中找到该符号(必须为非局部符号),表示要加载模块需要改符号
    1142.         if (sym && !ELFW(ST_BIND) (sym->info) == STB_LOCAL) {
    1143.                 /*将hash表中的待解析的symbol的value添成正确的值s->value*/
    1144.             sym = obj_add_symbol(f, (char *) s->name, -1,ELFW(ST_INFO) (STB_GLOBAL, STT_NOTYPE),idx, s->value, 0);
    1145.             if (sym->secidx == idx)
    1146.                 used = 1;//表示发生了符号替换
    1147.         }
    1148.     }
    1149.     return used;
    1150. }
    1151. static int create_this_module(struct obj_file *f, const char *m_name)
    1152. {
    1153.     struct obj_section *sec;
    1154.     //创建一个.this节区,显然准备在这个节区里存放module结构。注意:这个节区是load时的首个节区,即起始节区
    1155.     sec = obj_create_alloced_section_first(f, ".this", tgt_sizeof_long,sizeof(struct module));
    1156.     memset(sec->contents, 0, sizeof(struct module));
    1157.     //添加一个"__this_module"符号,所在节区是.this,属性是 STB_LOCAL,类型是 STT_OBJECT,symidx 为-1,所以这个符号不加入 local_symtab 中(因为这个符号不是文件原有的)
    1158.     obj_add_symbol(f, "__this_module", -1, ELFW(ST_INFO) (STB_LOCAL, STT_OBJECT),sec->idx, 0, sizeof(struct module));
    1159.     
    1160.     /*为了能在obj_file里引用模块名(回忆一下,每个字符串要么与节区名对应,要么对应于一个符号,而在这里,模块名没有对应的符号或节区),因此obj_file通过obj_string_patch_struct结构收留这些孤独的字符串*/
    1161.     //创建.kstrtab节区,若存在该节区则扩展该节区,给该节区内容赋值为m_name,这里即”fedcore.ko“
    1162.     obj_string_patch(f, sec->idx, offsetof(struct module, name), m_name);
    1163.     return 1;
    1164. }
    1165. struct obj_section *obj_create_alloced_section_first (struct obj_file *f, const char *name,
    1166.                  unsigned long align, unsigned long size)
    1167. {
    1168.   int newidx = f->header.e_shnum++;//elf文件头中的节区头数量加1
    1169.   struct obj_section *sec;
    1170.     //为节区头分配空间
    1171.   f->sections = xrealloc(f->sections, (newidx+1) * sizeof(sec));
    1172.   f->sections[newidx] = sec = arch_new_section();
    1173.   memset(sec, 0, sizeof(*sec));//.this节区的偏移地址是0,sec->header.sh_addr=0
    1174.   sec->header.sh_type = SHT_PROGBITS;
    1175.   sec->header.sh_flags = SHF_WRITE|SHF_ALLOC;
    1176.   sec->header.sh_size = size;
    1177.   sec->header.sh_addralign = align;
    1178.   sec->name = name;
    1179.   sec->idx = newidx;
    1180.   if (size)
    1181.     sec->contents = xmalloc(size);//节区内容分配空间
    1182.   sec->load_next = f->load_order;
    1183.   f->load_order = sec;
    1184.   if (f->load_order_search_start == &f->load_order)
    1185.     f->load_order_search_start = &sec->load_next;
    1186.   return sec;
    1187. }
    1188. int obj_string_patch(struct obj_file *f, int secidx, ElfW(Addr) offset,const char *string)
    1189. {
    1190.   struct obj_string_patch_struct *p;
    1191.   struct obj_section *strsec;
    1192.   size_t len = strlen(string)+1;
    1193.   char *loc;
    1194.   p = xmalloc(sizeof(*p));
    1195.   p->next = f->string_patches;
    1196.   p->reloc_secidx = secidx;
    1197.   p->reloc_offset = offset;
    1198.   f->string_patches = p;//patch 字符串
    1199.     
    1200.     //查找.kstrtab节区
    1201.   strsec = obj_find_section(f, ".kstrtab");
    1202.   if (strsec == NULL)
    1203.   {
    1204.       //该节区不存在则创建该节区
    1205.     strsec = obj_create_alloced_section(f, ".kstrtab", 1, len, 0);
    1206.     p->string_offset = 0;
    1207.     loc = strsec->contents;
    1208.   }
    1209.   else
    1210.   {
    1211.     p->string_offset = strsec->header.sh_size;//字符串偏移地址
    1212.     loc = obj_extend_section(strsec, len);//扩展该节区内容的地址大小
    1213.   }
    1214.   memcpy(loc, string, len);//赋值给节区内容
    1215.   return 1;
    1216. }
    1217. int obj_check_undefineds(struct obj_file *f, int quiet)
    1218. {
    1219.   unsigned long i;
    1220.   int ret = 1;
    1221.     //遍历模块的hash表的所有符号,检查是否还有未定义的符号
    1222.   for (i = 0; i < HASH_BUCKETS; ++i)
    1223.   {
    1224.       struct obj_symbol *sym;
    1225.       //一般来说此处不会有未定义的符号,因为前边经过了一次内核符号和其他模块符号的替换操作add_kernel_symbols,但是在模块的编译
    1226.       for (sym = f->symtab[i]; sym ; sym = sym->next)
    1227.             if (sym->secidx == SHN_UNDEF)//如果有未定义的符号
    1228.          {
    1229.              //对于属性为weak的符号,如果未能解析,链接器只是将它置0完事
    1230.              if (ELFW(ST_BIND)(sym->info) == STB_WEAK)
    1231.              {
    1232.                     sym->secidx = SHN_ABS;//符号具有绝对取值,不会因为重定位而发生变化。
    1233.                     sym->value = 0;
    1234.              }
    1235.          else if (sym->r_type) /* assumes R_arch_NONE is 0 on all arch */
    1236.              {//如果不是weak属性,而且受重定位影响那就出错了
    1237.                     if (!quiet)
    1238.                         error("%s: unresolved symbol %s",f->filename, sym->name);
    1239.                     ret = 0;
    1240.          }
    1241.          }
    1242.   }
    1243.   return ret;
    1244. }
    1245. void obj_allocate_commons(struct obj_file *f)
    1246. {
    1247.   struct common_entry
    1248.   {
    1249.     struct common_entry *next;
    1250.     struct obj_symbol *sym;
    1251.   } *common_head = NULL;
    1252.   unsigned long i;
    1253.   for (i = 0; i < HASH_BUCKETS; ++i)
    1254.   {
    1255.     struct obj_symbol *sym;
    1256.     //遍历该模块的hash符号表
    1257.     for (sym = f->symtab[i]; sym ; sym = sym->next)
    1258.     //若设置了该标志SHN_COMMON,则表示符号标注了一个尚未分配的公共块,例如未分配的C外部变量。就是说,链接编辑器将为符号分配存储空间,地址位于 st_value 的倍数处。符号的大小给出了所需要的字节数。
    1259.     //找出所有SHN_COMMON的符号,并按符号大小排序,链入到common_head链表中
    1260.         if (sym->secidx == SHN_COMMON)
    1261.       {
    1262.      {
    1263.      struct common_entry **p, *n;
    1264.      for (p = &common_head; *p ; p = &(*p)->next)
    1265.                 if (sym->size <= (*p)->sym->size)
    1266.                  break;
    1267.      n = alloca(sizeof(*n));
    1268.      n->next = *p;
    1269.      n->sym = sym;
    1270.      *p = n;
    1271.      }
    1272.       }
    1273.   }
    1274.     //遍历该模块的局部符号表local_symtab,找出所有SHN_COMMON的符号,并按符号大小排序,链入到common_head链表中
    1275.   for (i = 1; i < f->local_symtab_size; ++i)
    1276.   {
    1277.       struct obj_symbol *sym = f->local_symtab[i];
    1278.       if (sym && sym->secidx == SHN_COMMON)
    1279.         {
    1280.          struct common_entry **p, *n;
    1281.          for (p = &common_head; *p ; p = &(*p)->next)
    1282.          if (sym == (*p)->sym)
    1283.          break;
    1284.          else if (sym->size < (*p)->sym->size)
    1285.          {
    1286.                     n = alloca(sizeof(*n));
    1287.                     n->next = *p;
    1288.                     n->sym = sym;
    1289.                     *p = n;
    1290.                     break;
    1291.          }
    1292.         }
    1293.   }
    1294.   if (common_head)
    1295.   {
    1296.       for (i = 0; i < f->header.e_shnum; ++i)
    1297.           //SHT_NOBITS表明这个节区不占据文件空间,这正是.bss节区的类型,这里就是为了查找.bss节区
    1298.             if (f->sections[i]->header.sh_type == SHT_NOBITS)
    1299.                  break;
    1300.     //如果没有找到.bss节区,则就创建一个.bss节区
    1301.     //.bss 含义:包含将出现在程序的内存映像中的为初始化数据。根据定义,当程序开始执行,系统将把这些数据初始化为 0。此节区不占用文件空间。
    1302.       if (i == f->header.e_shnum)
    1303.         {
    1304.          struct obj_section *sec;
    1305.     
    1306.          f->sections = xrealloc(f->sections, (i+1) * sizeof(sec));
    1307.          f->sections[i] = sec = arch_new_section();//分配节区结构obj_section
    1308.          f->header.e_shnum = i+1;//节区数量加1
    1309.     
    1310.          memset(sec, 0, sizeof(*sec));
    1311.          sec->header.sh_type = SHT_PROGBITS;//节区类型
    1312.          sec->header.sh_flags = SHF_WRITE|SHF_ALLOC;
    1313.          sec->name = ".bss";//节区名称
    1314.          sec->idx = i;//节区索引值
    1315.         }
    1316.     {
    1317.             ElfW(Addr) bss_size = f->sections[i]->header.sh_size;//节区大小
    1318.             ElfW(Addr) max_align = f->sections[i]->header.sh_addralign;//对齐边界
    1319.             struct common_entry *c;
    1320.     
    1321.             //根据SHN_COMMON的符号重新计算该.bss节区大小和对齐边界
    1322.             for (c = common_head; c ; c = c->next)
    1323.          {
    1324.          ElfW(Addr) align = c->sym->value;
    1325.     
    1326.          if (align > max_align)
    1327.          max_align = align;
    1328.          if (bss_size & (align - 1))
    1329.          bss_size = (bss_size | (align - 1)) + 1;
    1330.     
    1331.          c->sym->secidx = i;//该符号的节区索引值也改变了,即是.bss节区
    1332.          c->sym->value = bss_size;//符号值也变了,变成.bss节区符号偏移量
    1333.     
    1334.          bss_size += c->sym->size;
    1335.          }
    1336.     
    1337.             f->sections[i]->header.sh_size = bss_size;
    1338.             f->sections[i]->header.sh_addralign = max_align;
    1339.     }
    1340.   }
    1341.   //为SHT_NOBITS节区分配资源,并将它设为SHT_PROGBITS。从这里可以看到,文件定义的静态、全局变量,还有引用的外部变量,最终放在了.bss节区中
    1342.   for (i = 0; i < f->header.e_shnum; ++i)
    1343.   {
    1344.       struct obj_section *s = f->sections[i];
    1345.       if (s->header.sh_type == SHT_NOBITS)//找到.bss节区
    1346.         {
    1347.          if (s->header.sh_size)
    1348.              //节区内容都初始化为0,即.bss节区中符号对应的文件定义的静态、全局变量,还有引用的外部变量都初始化为0
    1349.          s->contents = memset(xmalloc(s->header.sh_size),0, s->header.sh_size);
    1350.          else
    1351.          s->contents = NULL;
    1352.          s->header.sh_type = SHT_PROGBITS;
    1353.         }
    1354.   }
    1355. }
    1356. static void check_module_parameters(struct obj_file *f, int *persist_flag)
    1357. {
    1358.     struct obj_section *sec;
    1359.     char *ptr, *value, *n, *endptr;
    1360.     int namelen, err = 0;
    1361.     //查找 ".modinfo"节区
    1362.     sec = obj_find_section(f, ".modinfo");
    1363.     if (sec == NULL) {
    1364.         return;
    1365.     }
    1366.     ptr = sec->contents;//节区内容起始地址
    1367.     endptr = ptr + sec->header.sh_size;//节区内容结束地址
    1368.     
    1369.     while (ptr < endptr && !err) {
    1370.         value = strchr(ptr, '=');//定位到该字符串的”=“位置出
    1371.         n = strchr(ptr, '');
    1372.         if (value) {
    1373.             namelen = value - ptr;//找到该字符串的名称
    1374.             //查找相对应的"parm_"或"parm_desc_"开头的字符串
    1375.             if (namelen >= 5 && strncmp(ptr, "parm_", 5) == 0
    1376.              && !(namelen > 10 && strncmp(ptr, "parm_desc_", 10) == 0)) {
    1377.                 char *pname = xmalloc(namelen + 1);
    1378.                 strncpy(pname, ptr + 5, namelen - 5);//取得该字符串名
    1379.                 pname[namelen - 5] = '';
    1380.                 //检查该参数字符串的内容
    1381.                 err = check_module_parameter(f, pname, value+1, persist_flag);
    1382.                 free(pname);
    1383.             }
    1384.         } else {
    1385.             if (n - ptr >= 5 && strncmp(ptr, "parm_", 5) == 0) {
    1386.                 error("parameter %s found with no value", ptr);
    1387.                 err = 1;
    1388.             }
    1389.         }
    1390.         ptr = n + 1;//下一个字符串
    1391.     }
    1392.     if (err)
    1393.         *persist_flag = 0;
    1394.     return;
    1395. }
    1396. static int check_module_parameter(struct obj_file *f, char *key, char *value, int *persist_flag)
    1397. {
    1398.     struct obj_symbol *sym;
    1399.     int min, max;
    1400.     char *p = value;
    1401.     
    1402.     //确定该符号是否存在
    1403.     sym = obj_find_symbol(f, key);
    1404.     if (sym == NULL) {
    1405.         lprintf("Warning: %s symbol for parameter %s not found", error_file, key);
    1406.         ++warnings;
    1407.         return(1);
    1408.     }
    1409.     //解析参数值个数的声明,如果没有参数值个数的取值声明就默认为1
    1410.     if (isdigit(*p)) {
    1411.         min = strtoul(p, &p, 10);
    1412.         if (*p == '-')
    1413.             max = strtoul(p + 1, &p, 10);
    1414.         else
    1415.             max = min;
    1416.     } else
    1417.         min = max = 1;
    1418.     if (max < min) {
    1419.         lprintf("Warning: %s parameter %s has max < min!", error_file, key);
    1420.         ++warnings;
    1421.         return(1);
    1422.     }
    1423.     //处理变量类型
    1424.     switch (*p) {
    1425.     case 'c':
    1426.         if (!isdigit(p[1])) {
    1427.             lprintf("%s parameter %s has no size after 'c'!", error_file, key);
    1428.             ++warnings;
    1429.             return(1);
    1430.         }
    1431.         while (isdigit(p[1]))
    1432.             ++p;    /* swallow c array size */
    1433.         break;
    1434.     case 'b':    /* drop through */
    1435.     case 'h':    /* drop through */
    1436.     case 'i':    /* drop through */
    1437.     case 'l':    /* drop through */
    1438.     case 's':
    1439.         break;
    1440.     case '':
    1441.         lprintf("%s parameter %s has no format character!", error_file, key);
    1442.         ++warnings;
    1443.         return(1);
    1444.     default:
    1445.         lprintf("%s parameter %s has unknown format character '%c'", error_file, key, *p);
    1446.         ++warnings;
    1447.         return(1);
    1448.     }
    1449.     
    1450.     switch (*++p) {
    1451.     case 'p':
    1452.         if (*(p-1) == 's') {
    1453.             error("parameter %s is invalid persistent string", key);
    1454.             return(1);
    1455.         }
    1456.         *persist_flag = 1;
    1457.         break;
    1458.     case '':
    1459.         break;
    1460.     default:
    1461.         lprintf("%s parameter %s has unknown format modifier '%c'", error_file, key, *p);
    1462.         ++warnings;
    1463.         return(1);
    1464.     }
    1465.     return(0);
    1466. }
    1467. static int process_module_arguments(struct obj_file *f, int argc, char **argv, int required)
    1468. {
    1469.     //遍历命令行参数
    1470.     for (; argc > 0; ++argv, --argc) {
    1471.         struct obj_symbol *sym;
    1472.         int c;
    1473.         int min, max;
    1474.         int n;
    1475.         char *contents;
    1476.         char *input;
    1477.         char *fmt;
    1478.         char *key;
    1479.         char *loc;
    1480.         //因为使用命令行参数时,一定是param=value这样的形式
    1481.         if ((input = strchr(*argv, '=')) == NULL)
    1482.             continue;
    1483.         n = input - *argv;//参数长度
    1484.         input += 1; /* skip '=' */
    1485.         key = alloca(n + 6);
    1486.         if (m_has_modinfo) {
    1487.             //将该参数组合成参数符号格式”parm_xxx“
    1488.             memcpy(key, "parm_", 5);
    1489.             memcpy(key + 5, *argv, n);
    1490.             key[n + 5] = '';
    1491.             
    1492.             //从节区.modinfo中查找该模块参数
    1493.             if ((fmt = get_modinfo_value(f, key)) == NULL) {
    1494.                 if (required || flag_verbose) {
    1495.                     lprintf("Warning: ignoring %s, no such parameter in this module", *argv);
    1496.                     ++warnings;
    1497.                     continue;
    1498.                 }
    1499.             }
    1500.             key += 5;
    1501.             
    1502.             //解析参数值个数的声明,如果没有参数值个数的取值声明就默认为1
    1503.             if (isdigit(*fmt)) {
    1504.                 min = strtoul(fmt, &fmt, 10);
    1505.                 if (*fmt == '-')
    1506.                     max = strtoul(fmt + 1, &fmt, 10);
    1507.                 else
    1508.                     max = min;
    1509.             } else
    1510.                 min = max = 1;
    1511.                 
    1512.         } else { /* not m_has_modinfo */
    1513.             memcpy(key, *argv, n);
    1514.             key[n] = '';
    1515.             if (isdigit(*input))
    1516.                 fmt = "i";
    1517.             else
    1518.                 fmt = "s";
    1519.             min = max = 0;
    1520.         }
    1521.         //到hash符号表中查找该参数符号
    1522.         sym = obj_find_symbol(f, key);
    1523.         if (sym == NULL || sym->secidx > SHN_HIRESERVE) {
    1524.             error("symbol for parameter %s not found", key);
    1525.             return 0;
    1526.         }
    1527.         //找到符号,读取该符号所在节区的内容
    1528.         contents = f->sections[sym->secidx]->contents;
    1529.         loc = contents + sym->value;//存储该参数符号的值地址付给loc指针,下边就会给参数符号重新赋值
    1530.         n = 1;
    1531.         while (*input) {
    1532.             char *str;
    1533.             switch (*fmt) {
    1534.             case 's':
    1535.             case 'c':
    1536.                 if (*input == '"') {
    1537.                     char *r;
    1538.                     str = alloca(strlen(input));
    1539.                     for (r = str, input++; *input != '"'; ++input, ++r) {
    1540.                         if (*input == '') {
    1541.                             error("improperly terminated string argument for %s", key);
    1542.                             return 0;
    1543.                         }
    1544.                         /* else */
    1545.                         if (*input != '\') {
    1546.                             *r = *input;
    1547.                             continue;
    1548.                         }
    1549.                         /* else handle */
    1550.                         switch (*++input) {
    1551.                         case 'a': *r = 'a'; break;
    1552.                         case 'b': *r = ''; break;
    1553.                         case 'e': *r = '33'; break;
    1554.                         case 'f': *r = 'f'; break;
    1555.                         case 'n': *r = ' '; break;
    1556.                         case 'r': *r = ' '; break;
    1557.                         case 't': *r = ' '; break;
    1558.                         case '0':
    1559.                         case '1':
    1560.                         case '2':
    1561.                         case '3':
    1562.                         case '4':
    1563.                         case '5':
    1564.                         case '6':
    1565.                         case '7':
    1566.                             c = *input - '0';
    1567.                             if ('0' <= input[1] && input[1] <= '7') {
    1568.                                 c = (c * 8) + *++input - '0';
    1569.                                 if ('0' <= input[1] && input[1] <= '7')
    1570.                                     c = (c * 8) + *++input - '0';
    1571.                             }
    1572.                             *r = c;
    1573.                             break;
    1574.                         default: *r = *input; break;
    1575.                         }
    1576.                     }
    1577.                     *r = '';
    1578.                     ++input;
    1579.                 } else {
    1580.                     /*
    1581.                      * The string is not quoted.
    1582.                      * We will break it using the comma
    1583.                      * (like for ints).
    1584.                      * If the user wants to include commas
    1585.                      * in a string, he just has to quote it
    1586.                      */
    1587.                     char *r;
    1588.                     /* Search the next comma */
    1589.                     if ((r = strchr(input, ',')) != NULL) {
    1590.                         /*
    1591.                          * Found a comma
    1592.                          * Recopy the current field
    1593.                          */
    1594.                         str = alloca(r - input + 1);
    1595.                         memcpy(str, input, r - input);
    1596.                         str[r - input] = '';
    1597.                         /* Keep next fields */
    1598.                         input = r;
    1599.                     } else {
    1600.                         /* last string */
    1601.                         str = input;
    1602.                         input = "";
    1603.                     }
    1604.                 }
    1605.                 if (*fmt == 's') {
    1606.                     /* Normal string */
    1607.                     obj_string_patch(f, sym->secidx, loc - contents, str);
    1608.                     loc += tgt_sizeof_char_p;
    1609.                 } else {
    1610.                     /* Array of chars (in fact, matrix !) */
    1611.                     long charssize;    /* size of each member */
    1612.                     /* Get the size of each member */
    1613.                     /* Probably we should do that outside the loop ? */
    1614.                     if (!isdigit(*(fmt + 1))) {
    1615.                         error("parameter type 'c' for %s must be followed by the maximum size", key);
    1616.                         return 0;
    1617.                     }
    1618.                     charssize = strtoul(fmt + 1, (char **) NULL, 10);
    1619.                     /* Check length */
    1620.                     if (strlen(str) >= charssize-1) {
    1621.                         error("string too long for %s (max %ld)",key, charssize - 1);
    1622.                         return 0;
    1623.                     }
    1624.                     /* Copy to location */
    1625.                     strcpy((char *) loc, str);    /* safe, see check above */
    1626.                     loc += charssize;
    1627.                 }
    1628.                 /*
    1629.                  * End of 's' and 'c'
    1630.                  */
    1631.                 break;
    1632.             case 'b':
    1633.                 *loc++ = strtoul(input, &input, 0);
    1634.                 break;
    1635.             case 'h':
    1636.                 *(short *) loc = strtoul(input, &input, 0);
    1637.                 loc += tgt_sizeof_short;
    1638.                 break;
    1639.             case 'i':
    1640.                 *(int *) loc = strtoul(input, &input, 0);
    1641.                 loc += tgt_sizeof_int;
    1642.                 break;
    1643.             case 'l':
    1644.                 *(tgt_long *) loc = tgt_strtoul(input, &input, 0);
    1645.                 loc += tgt_sizeof_long;
    1646.                 break;
    1647.             default:
    1648.                 error("unknown parameter type '%c' for %s",*fmt, key);
    1649.                 return 0;
    1650.             }
    1651.             /*
    1652.              * end of switch (*fmt)
    1653.              */
    1654.             while (*input && isspace(*input))
    1655.                 ++input;
    1656.             if (*input == '')
    1657.                 break; /* while (*input) */
    1658.             /* else */
    1659.             if (*input == ',') {
    1660.                 if (max && (++n > max)) {
    1661.                     error("too many values for %s (max %d)", key, max);
    1662.                     return 0;
    1663.                 }
    1664.                 ++input;
    1665.                 /* continue with while (*input) */
    1666.             } else {
    1667.                 error("invalid argument syntax for %s: '%c'",key, *input);
    1668.                 return 0;
    1669.             }
    1670.         } /* end of while (*input) */
    1671.         if (min && (n < min)) {
    1672.             error("too few values for %s (min %d)", key, min);
    1673.             return 0;
    1674.         }
    1675.     } /* end of for (;argc > 0;) */
    1676.     return 1;
    1677. }
    1678. static void hide_special_symbols(struct obj_file *f)
    1679. {
    1680.     struct obj_symbol *sym;
    1681.     const char *const *p;
    1682.     static const char *const specials[] =
    1683.     {
    1684.         "cleanup_module",
    1685.         "init_module",
    1686.         "kernel_version",
    1687.         NULL
    1688.     };
    1689.     //查找数组中的几个符号,找到后类型改为STB_LOCAL(局部)
    1690.     for (p = specials; *p; ++p)
    1691.         if ((sym = obj_find_symbol(f, *p)) != NULL)
    1692.             sym->info = ELFW(ST_INFO) (STB_LOCAL, ELFW(ST_TYPE) (sym->info));
    1693. }
    1694. static void add_ksymoops_symbols(struct obj_file *f, const char *filename,const char *m_name)
    1695. {
    1696.     struct obj_section *sec;
    1697.     struct obj_symbol *sym;
    1698.     char *name, *absolute_filename;
    1699.     char str[STRVERSIONLEN], real[PATH_MAX];
    1700.     int i, l, lm_name, lfilename, use_ksymtab, version;
    1701.     struct stat statbuf;
    1702.     static const char *section_names[] = {
    1703.         ".text",
    1704.         ".rodata",
    1705.         ".data",
    1706.         ".bss"
    1707.         ".sbss"
    1708.     };
    1709.     
    1710.     //找到模块所在的完整路径名
    1711.     if (realpath(filename, real)) {
    1712.         absolute_filename = xstrdup(real);
    1713.     }
    1714.     else {
    1715.         int save_errno = errno;
    1716.         error("cannot get realpath for %s", filename);
    1717.         errno = save_errno;
    1718.         perror("");
    1719.         absolute_filename = xstrdup(filename);
    1720.     }
    1721.     lm_name = strlen(m_name);
    1722.     lfilename = strlen(absolute_filename);
    1723.     //查找"__ksymtab"节区是否存在或者模块符号是否需要导出
    1724.     use_ksymtab = obj_find_section(f, "__ksymtab") || !flag_export;
    1725.     //找到.this节区,记录经过修饰的模块名和经过修饰的长度不为0的节区。在这里修饰的目的,应该是为了唯一确定所使用的模块。
    1726.     if ((sec = obj_find_section(f, ".this"))) {
    1727.         l = sizeof(symprefix)+            /* "__insmod_" */
    1728.          lm_name+                /* module name */
    1729.          2+                    /* "_O" */
    1730.          lfilename+                /* object filename */
    1731.          2+                    /* "_M" */
    1732.          2*sizeof(statbuf.st_mtime)+        /* mtime in hex */
    1733.          2+                    /* "_V" */
    1734.          8+                    /* version in dec */
    1735.          1;                    /* nul */
    1736.         name = xmalloc(l);
    1737.         if (stat(absolute_filename, &statbuf) != 0)
    1738.             statbuf.st_mtime = 0;
    1739.         version = get_module_version(f, str);    /* -1 if not found */
    1740.         snprintf(name, l, "%s%s_O%s_M%0*lX_V%d",symprefix, m_name, absolute_filename,
    1741.              (int)(2*sizeof(statbuf.st_mtime)), statbuf.st_mtime,version);
    1742.         //添加一个符号,该符号所在节区是.this节区,符号value给出该符号的地址在节区sec->header.sh_addr(值为0)的偏移地址处
    1743.         sym = obj_add_symbol(f, name, -1,ELFW(ST_INFO) (STB_GLOBAL, STT_NOTYPE),sec->idx, sec->header.sh_addr, 0);
    1744.         if (use_ksymtab)
    1745.             add_ksymtab(f, sym);//该符号添加到__ksymtab节区中
    1746.     }
    1747.     free(absolute_filename);
    1748.     //参数若是通过文件传入的,也要修饰记录这个文件名
    1749.     if (f->persist) {
    1750.         l = sizeof(symprefix)+        /* "__insmod_" */
    1751.             lm_name+        /* module name */
    1752.             2+            /* "_P" */
    1753.             strlen(f->persist)+    /* data store */
    1754.             1;            /* nul */
    1755.         name = xmalloc(l);
    1756.         snprintf(name, l, "%s%s_P%s",symprefix, m_name, f->persist);
    1757.         sym = obj_add_symbol(f, name, -1, ELFW(ST_INFO) (STB_GLOBAL, STT_NOTYPE),sec->idx, sec->header.sh_addr, 0);
    1758.         if (use_ksymtab)
    1759.             add_ksymtab(f, sym);//该符号添加到__ksymtab节区中,要导出的符号加入该节区"__ksymtab"
    1760.     }
    1761.     /* tag the desired sections if size is non-zero */
    1762.     for (i = 0; i < sizeof(section_names)/sizeof(section_names[0]); ++i) {
    1763.         if ((sec = obj_find_section(f, section_names[i])) &&sec->header.sh_size) {
    1764.             l = sizeof(symprefix)+        /* "__insmod_" */
    1765.                 lm_name+        /* module name */
    1766.                 2+            /* "_S" */
    1767.                 strlen(sec->name)+    /* section name */
    1768.                 2+            /* "_L" */
    1769.                 8+            /* length in dec */
    1770.                 1;            /* nul */
    1771.             name = xmalloc(l);
    1772.             snprintf(name, l, "%s%s_S%s_L%ld",symprefix, m_name, sec->name,(long)sec->header.sh_size);
    1773.             sym = obj_add_symbol(f, name, -1, ELFW(ST_INFO) (STB_GLOBAL, STT_NOTYPE),sec->idx, sec->header.sh_addr, 0);
    1774.             if (use_ksymtab)
    1775.                 add_ksymtab(f, sym);//该符号添加到__ksymtab节区中,要导出的符号加入该节区"__ksymtab"
    1776.         }
    1777.     }
    1778. }
    1779. static int create_module_ksymtab(struct obj_file *f)
    1780. {
    1781.     struct obj_section *sec;
    1782.     int i;
    1783.     //n_ext_modules_used是该模块引用的模块的数量
    1784.     if (n_ext_modules_used) {
    1785.         struct module_ref *dep;
    1786.         struct obj_symbol *tm;
    1787.         //创建一个.kmodtab节区保存该模块所引用的模块信息
    1788.         sec = obj_create_alloced_section(f, ".kmodtab",tgt_sizeof_void_p,sizeof(struct module_ref) * n_ext_modules_used, 0);
    1789.         if (!sec)
    1790.             return 0;
    1791.         tm = obj_find_symbol(f, "__this_module");
    1792.         dep = (struct module_ref *) sec->contents;
    1793.         //
    1794.         for (i = 0; i < n_module_stat; ++i)
    1795.             if (module_stat[i].status) {//模块若被引用,则status为1
    1796.                 dep->dep = module_stat[i].addr;
    1797.                 dep->dep |= arch_module_base (f);
    1798.                 obj_symbol_patch(f, sec->idx, (char *) &dep->ref - sec->contents, tm);
    1799.                 dep->next_ref = 0;
    1800.                 ++dep;
    1801.             }
    1802.     }
    1803.     
    1804.     // 在存在__ksymtab节区或者不存在这个节区,而且其他符号都不导出的情况下,还要将这些符号添加入__symtab节区
    1805.     //如果需要导出外部(extern)符号,而__ksymtab段不存在(这种情况下,add_ksymoops_symbols里是不会创建__ksymtab段的。而实际上,模块一般是不会不包含__ksymtab段的,因为模块的导出符号都位于这个段里。),那么通过add_ksymtab创建__ksymtab段,并加入模块要导出的符号。在这里可以发现,如果模块需要导出符号,那么经过修饰的模块名、模块文件名,甚至参数文件名会在这里加入__ksymtab段(因为在前面的add_ksymoops_symbols函数里,这些符号被设为STB_GLOBOL了,段序号指向.this段)。
    1806.     //注意,在不存在__ksymtab段的情况下(这时模块没有定义任何需要导出的参数),直接导出序号在SHN_LORESERVE~SHN_HIRESERVE的符号,以及其他已分配资源段的非local符号。(根据elf规范里,位于SHN_LORESERVE~SHN_HIRESERVE区的已定义序号有SHN_LOPROC、SHN_HIPROC、SHN_ABS、SHN_COMMON。经过前面的处理,到这里SHN_COMMON对应的符号已经不存在了。这些序号的节区实际上是不存在的,存在的是持有这些序号的符号。其中SHN_ABS是不受重定位影响的符号,其他2个则是与处理器有关的。至于为什么模块不需要导出符号时,要导出这些区的符号,我也不太清楚,可以肯定的是,这和GCC有关,谁知道它放了什么进来?!)。
    1807.     if (flag_export && !obj_find_section(f, "__ksymtab")) {
    1808.         int *loaded;
    1809.         loaded = alloca(sizeof(int) * (i = f->header.e_shnum));
    1810.         while (--i >= 0)
    1811.             loaded[i] = (f->sections[i]->header.sh_flags & SHF_ALLOC) != 0;//节区是否占用内存
    1812.         for (i = 0; i < HASH_BUCKETS; ++i) {
    1813.             struct obj_symbol *sym;
    1814.             for (sym = f->symtab[i]; sym; sym = sym->next) 
    1815.             {
    1816.                 
    1817.                 if (ELFW(ST_BIND) (sym->info) != STB_LOCAL && sym->secidx <= SHN_HIRESERVE&& (sym->secidx >= SHN_LORESERVE || loaded[sym->secidx])) {
    1818.                     add_ksymtab(f, sym);//要导出的符号加入该节区"__ksymtab"
    1819.                 }
    1820.             }
    1821.         }
    1822.     }
    1823.     return 1;
    1824. }
    1825. static void add_ksymtab(struct obj_file *f, struct obj_symbol *sym)
    1826. {
    1827.     struct obj_section *sec;
    1828.     ElfW(Addr) ofs;
    1829.     //查找是否已经存在"__ksymtab"节区
    1830.     sec = obj_find_section(f, "__ksymtab");
    1831.     //如果存在这个节区,但是没有标示SHF_ALLOC,则直接将该节区的名字修改掉,标示删除
    1832.     if (sec && !(sec->header.sh_flags & SHF_ALLOC)) {
    1833.         *((char *)(sec->name)) = 'x';    /* override const */
    1834.         sec = NULL;
    1835.     }
    1836.     if (!sec)
    1837.         sec = obj_create_alloced_section(f, "__ksymtab",tgt_sizeof_void_p, 0, 0);
    1838.     if (!sec)
    1839.         return;
    1840.         
    1841.     sec->header.sh_flags |= SHF_ALLOC;
    1842.     sec->header.sh_addralign = tgt_sizeof_void_p;    /* Empty section mightbe byte-aligned */
    1843.     ofs = sec->header.sh_size;
    1844.     obj_symbol_patch(f, sec->idx, ofs, sym);//使用f->sybol_ptches保存这些符号
    1845.     obj_string_patch(f, sec->idx, ofs + tgt_sizeof_void_p, sym->name);//使用f->string_patches保存符号名
    1846.     obj_extend_section(sec, 2 * tgt_sizeof_char_p);//扩展"__ksymtab"节区
    1847. }
    1848. static int add_archdata(struct obj_file *f,struct obj_section **sec)
    1849. {
    1850.     size_t i;
    1851.     *sec = NULL;
    1852.     
    1853.     //查找是否有ARCHDATA_SEC_NAME=“__archdata”节区,没有则创建该节区
    1854.     for (i = 0; i < f->header.e_shnum; ++i) {
    1855.         if (strcmp(f->sections[i]->name, ARCHDATA_SEC_NAME) == 0) {
    1856.             *sec = f->sections[i];
    1857.             break;
    1858.         }
    1859.     }
    1860.     if (!*sec)
    1861.         *sec = obj_create_alloced_section(f, ARCHDATA_SEC_NAME, 16, 0, 0);
    1862.     //x86体系下是空函数
    1863.     if (arch_archdata(f, *sec))
    1864.         return(1);
    1865.     return 0;
    1866. }
    1867. static int add_kallsyms(struct obj_file *f,struct obj_section **module_kallsyms, int force_kallsyms)
    1868. {
    1869.     struct module_symbol *s;
    1870.     struct obj_file *f_kallsyms;
    1871.     struct obj_section *sec_kallsyms;
    1872.     size_t i;
    1873.     int l;
    1874.     const char *p, *pt_R;
    1875.     unsigned long start = 0, stop = 0;
    1876.     //遍历所有内核符号,内核符号都保存在全局变量ksyms中
    1877.     for (i = 0, s = ksyms; i < nksyms; ++i, ++s) {
    1878.         p = (char *)s->name;
    1879.         pt_R = strstr(p, "_R");//查找符号中是否有 "_R",计算符号长度是,去掉这两个字符
    1880.         if (pt_R)
    1881.             l = pt_R - p;
    1882.         else
    1883.             l = strlen(p);
    1884.             
    1885.         //内核导出符号位于“__start_kallsyms”和“__stop_kallsyms”符号所指向的地址之间
    1886.         if (strncmp(p, "__start_" KALLSYMS_SEC_NAME, l) == 0)
    1887.             start = s->value;
    1888.         else if (strncmp(p, "__stop_" KALLSYMS_SEC_NAME, l) == 0)
    1889.             stop = s->value;
    1890.     }
    1891.     if (start >= stop && !force_kallsyms)
    1892.         return(0);
    1893.     /* The kernel contains all symbols, do the same for this module. */
    1894.     //找到该模块的“kallsyms”节区
    1895.     for (i = 0; i < f->header.e_shnum; ++i) {
    1896.         if (strcmp(f->sections[i]->name, KALLSYMS_SEC_NAME) == 0) {
    1897.             *module_kallsyms = f->sections[i];
    1898.             break;
    1899.         }
    1900.     }
    1901.     //如果没有找到,则创建一个kallsyms节区
    1902.     if (!*module_kallsyms)
    1903.         *module_kallsyms = obj_create_alloced_section(f, KALLSYMS_SEC_NAME, 0, 0, 0);
    1904.     //这个函数的作用是将输入obj_file里的符号提取出来,忽略不用于调试的符号.构建出obj_file只包含kallsyms节区。这个段可以任意定位,因为不包含重定位信息。
    1905.     //实际上,f_kallsyms这个文件就是将输入文件里的信息整理整理,更方便使用(记住__kallsyms节区是用作辅助内核调试),整个输出文件只是临时的调试仓库。
    1906.     if (obj_kallsyms(f, &f_kallsyms))//???
    1907.         return(1);
    1908.     sec_kallsyms = f_kallsyms->sections[KALLSYMS_IDX];//临时创建obj_file里的kallsyms节区
    1909.     (*module_kallsyms)->header.sh_addralign = sec_kallsyms->header.sh_addralign;//节区对齐大小
    1910.     (*module_kallsyms)->header.sh_size = sec_kallsyms->header.sh_size;//节区大小
    1911.     free((*module_kallsyms)->contents);
    1912.     (*module_kallsyms)->contents = sec_kallsyms->contents;//内容赋值给kallsyms节区
    1913.     sec_kallsyms->contents = NULL;
    1914.     obj_free(f_kallsyms);
    1915.     return 0;
    1916. }
    1917. unsigned long obj_load_size (struct obj_file *f)
    1918. {
    1919.   unsigned long dot = 0;
    1920.   struct obj_section *sec;
    1921.     //前面提到段按对其边界大小排序,可以减少空间占用,就是体现在这里。
    1922.   for (sec = f->load_order; sec ; sec = sec->load_next)
    1923.   {
    1924.     ElfW(Addr) align;
    1925.     align = sec->header.sh_addralign;
    1926.     if (align && (dot & (align - 1)))
    1927.             dot = (dot | (align - 1)) + 1;
    1928.     sec->header.sh_addr = dot;
    1929.     dot += sec->header.sh_size;//各个节区大小累加
    1930.   }
    1931.   return dot;
    1932. }
    1933. asmlinkage unsigned long sys_create_module(const char *name_user, size_t size)
    1934. {
    1935.     char *name;
    1936.     long namelen, error;
    1937.     struct module *mod;
    1938.     if (!capable(CAP_SYS_MODULE))//是否具有创建模块的特权
    1939.         return EPERM;
    1940.     lock_kernel();
    1941.     if ((namelen = get_mod_name(name_user, &name)) < 0) {//模块名拷贝到内核空间
    1942.         error = namelen;
    1943.         goto err0;
    1944.     }
    1945.     if (size < sizeof(struct module)+namelen) {//检查模块名的大小
    1946.         error = EINVAL;
    1947.         goto err1;
    1948.     }
    1949.     if (find_module(name) != NULL) {//在内存中查找是否模块已经安装
    1950.         error = EEXIST;
    1951.         goto err1;
    1952.     }
    1953.     //分配module空间 #define module_map(x) vmalloc(x)
    1954.     if ((mod = (struct module *)module_map(size)) == NULL) {
    1955.         error = ENOMEM;
    1956.         goto err1;
    1957.     }
    1958.     memset(mod, 0, sizeof(*mod));
    1959.     mod->size_of_struct = sizeof(*mod);
    1960.     mod->next = module_list;//挂入链表
    1961.     mod->name = (char *)(mod + 1);//module结构下边用来存储模块名
    1962.     mod->size = size;
    1963.     memcpy((char*)(mod+1), name, namelen+1);//拷贝模块名
    1964.     put_mod_name(name);//释放name的空间
    1965.     module_list = mod;//挂入链表
    1966.     error = (long) mod;
    1967.     goto err0;
    1968. err1:
    1969.     put_mod_name(name);
    1970. err0:
    1971.     unlock_kernel();
    1972.     return error;
    1973. }
    1974. //base是模块在内核空间的起始地址,也是.this节区的偏移地址
    1975. int obj_relocate (struct obj_file *f, ElfW(Addr) base)
    1976. {
    1977.   int i, n = f->header.e_shnum;
    1978.   int ret = 1;
    1979.     
    1980.     //节区在内存的位置是假设文件从0地址加载而得出的,现在就要根据base值调整
    1981.   arch_finalize_section_address(f, base);
    1982.     //处理重定位符号,遍历每一个节区
    1983.   for (i = 0; i < n; ++i)
    1984.   {
    1985.     struct obj_section *relsec, *symsec, *targsec, *strsec;
    1986.     ElfW(RelM) *rel, *relend;
    1987.     ElfW(Sym) *symtab;
    1988.     const char *strtab;
    1989.     unsigned long nsyms;
    1990.     relsec = f->sections[i];
    1991.     if (relsec->header.sh_type != SHT_RELM)//如果该节区不是重定位类型,则继续查找
    1992.             continue;
    1993.             
    1994.         //重定位节区会引用两个其它节区:符号表、要修改的节区。符号表是symsec,要修改的节区是targsec节区.例如重定位节区(relsec).rel.text是对节区是.text(targsec)的进行重定位.原来重定位的目标节区(.text)的内容contents只是读入到内存中,这块内存是系统在堆上malloc的,内容中对应的地址不是真正的符号所在的地址。现在符号的真正的地址已经计算出,就要修改contents区的符号对应的地址,从而将符号链接到正确的地址。
    1995.         
    1996.         //重定位节区的sh_link表示相关符号表的节区头部索引,即.symtab符号节区
    1997.     symsec = f->sections[relsec->header.sh_link];
    1998.     //重定位节区的sh_info表示重定位所适用的节区的节区头部索引,像.text等节区
    1999.     targsec = f->sections[relsec->header.sh_info];
    2000.     //找到重定位节区相关符号表字符串的节区,即.strtab
    2001.     strsec = f->sections[symsec->header.sh_link];
    2002.     if (!(targsec->header.sh_flags & SHF_ALLOC))
    2003.             continue;
    2004.         //读出该节区重定位信息开始地址
    2005.     rel = (ElfW(RelM) *)relsec->contents;
    2006.     //重定位信息结束地址
    2007.     relend = rel + (relsec->header.sh_size / sizeof(ElfW(RelM)));
    2008.     //找到重定位节区相关符号表的内容
    2009.     symtab = (ElfW(Sym) *)symsec->contents;
    2010.     nsyms = symsec->header.sh_size / symsec->header.sh_entsize;
    2011.     strtab = (const char *)strsec->contents;//找到重定位节区相关符号表字符串的节区的内容
    2012.     for (; rel < relend; ++rel)
    2013.         {
    2014.          ElfW(Addr) value = 0;
    2015.          struct obj_symbol *intsym = NULL;
    2016.          unsigned long symndx;
    2017.          const char *errmsg;
    2018.     
    2019.          //给出要重定位的符号表索引
    2020.          symndx = ELFW(R_SYM)(rel->r_info);
    2021.          if (symndx)
    2022.          {
    2023.          /* Note we've already checked for undefined symbols. */
    2024.              if (symndx >= nsyms)
    2025.                 {
    2026.                  error("%s: Bad symbol index: %08lx >= %08lx",f->filename, symndx, nsyms);
    2027.                  continue;
    2028.                 }
    2029.                 
    2030.                 //这些要重定位的符号就是重定位目标节区(例如.text节区)里的符号,然后把该符号的绝对地址在覆盖这个节区的(例如.text节区)对应符号的地址
    2031.              obj_find_relsym(intsym, f, f, rel, symtab, strtab);//返回要找的重定位符号intsym
    2032.              value = obj_symbol_final_value(f, intsym);//计算符号的绝对地址(是内核空间的绝对地址,因为base就是内核空间的一个地址)
    2033.          }
    2034.     
    2035.     #if SHT_RELM == SHT_RELA
    2036.          value += rel->r_addend;
    2037.     #endif
    2038.     
    2039.          //获得了绝对地址,可以进行操作了
    2040.          //注意:这里虽然重新定义了符号的绝对地址,但是节区的内容还没有拷贝到分配模块返回的内核空间地址处。后边会进行这项操作。先将节区内容拷贝的用户空间中,再从用户空间拷贝到内核空间地址处,即base处。
    2041.          //f:objfile结构,targsec:.text节,symsec:.symtab节,rel:.rel结构,value:绝对地址 
    2042.          switch (arch_apply_relocation(f,targsec,symsec,intsym,rel,value))
    2043.      {
    2044.          case obj_reloc_ok:
    2045.          break;
    2046.          case obj_reloc_overflow:
    2047.          errmsg = "Relocation overflow";
    2048.          goto bad_reloc;
    2049.          case obj_reloc_dangerous:
    2050.          errmsg = "Dangerous relocation";
    2051.          goto bad_reloc;
    2052.          case obj_reloc_unhandled:
    2053.          errmsg = "Unhandled relocation";
    2054.          goto bad_reloc;
    2055.          case obj_reloc_constant_gp:
    2056.          errmsg = "Modules compiled with -mconstant-gp cannot be loaded";
    2057.          goto bad_reloc;
    2058.          bad_reloc:
    2059.          error("%s: %s of type %ld for %s", f->filename, errmsg,
    2060.              (long)ELFW(R_TYPE)(rel->r_info), intsym->name);
    2061.          ret = 0;
    2062.          break;
    2063.      }
    2064.         }
    2065.     }
    2066.   /* Finally, take care of the patches. */
    2067.   if (f->string_patches)
    2068.   {
    2069.     struct obj_string_patch_struct *p;
    2070.     struct obj_section *strsec;
    2071.     ElfW(Addr) strsec_base;
    2072.     strsec = obj_find_section(f, ".kstrtab");
    2073.     strsec_base = strsec->header.sh_addr;
    2074.     for (p = f->string_patches; p ; p = p->next)
    2075.         {
    2076.          struct obj_section *targsec = f->sections[p->reloc_secidx];
    2077.          *(ElfW(Addr) *)(targsec->contents + p->reloc_offset)= strsec_base + p->string_offset;
    2078.         }
    2079.   }
    2080.   if (f->symbol_patches)
    2081.   {
    2082.     struct obj_symbol_patch_struct *p;
    2083.     for (p = f->symbol_patches; p; p = p->next)
    2084.         {
    2085.          struct obj_section *targsec = f->sections[p->reloc_secidx];
    2086.          *(ElfW(Addr) *)(targsec->contents + p->reloc_offset)= obj_symbol_final_value(f, p->sym);
    2087.         }
    2088.   }
    2089.   return ret;
    2090. }
    2091. int arch_finalize_section_address(struct obj_file *f, Elf32_Addr base)
    2092. {
    2093.   int i, n = f->header.e_shnum;
    2094.     //每个节区的起始地址都要加上模块在内核的起始地址
    2095.   f->baseaddr = base;//模块在内核的起始地址
    2096.   for (i = 0; i < n; ++i)
    2097.     f->sections[i]->header.sh_addr += base;
    2098.   return 1;
    2099. }
    2100. #define obj_find_relsym(isym, f, find, rel, symtab, strtab)
    2101.     {
    2102.         unsigned long symndx = ELFW(R_SYM)((rel)->r_info);
    2103.         ElfW(Sym) *extsym = (symtab)+symndx; //在符号表节区的内容中根据索引值找到相关符号
    2104.         if (ELFW(ST_BIND)(extsym->st_info) == STB_LOCAL) { //若是局部符号
    2105.             isym = (typeof(isym)) (f)->local_symtab[symndx]; //直接在局部符号表中返回要找的重定位符号
    2106.         }
    2107.         else {
    2108.             const char *name;
    2109.             if (extsym->st_name) //有值的话,就是strtab字符串节区内容的索引值
    2110.                 name = (strtab) + extsym->st_name; //找到符号名
    2111.             else //否则就是节区名
    2112.                 name = (f)->sections[extsym->st_shndx]->name;
    2113.             isym = (typeof(isym)) obj_find_symbol((find), name); //在符号hash表中找到该重定位符号
    2114.         }
    2115.     }
    2116.     
    2117. ElfW(Addr) obj_symbol_final_value (struct obj_file *f, struct obj_symbol *sym)
    2118. {
    2119.   if (sym)
    2120.   {
    2121.       //在保留区内直接返回符号值,即符号绝对地址(一般是内核符号,因为前边将模块内的符号用内核中或已存在的模块中相同符号的value更写过了,并且节区索引值设置高于SHN_HIRESERVE,所以这些符号的value保存的就是符号的实际地址)
    2122.     if (sym->secidx >= SHN_LORESERVE)
    2123.             return sym->value;
    2124.         
    2125.         //其余节区内的符号value要加上现在节区的偏移地址,才是符号指向的实际地址(因为节区的偏移地址已经更改了)
    2126.     return sym->value + f->sections[sym->secidx]->header.sh_addr;//符号值加上节区头偏移地址
    2127.   }
    2128.   else
    2129.   {
    2130.     /* As a special case, a NULL sym has value zero. */
    2131.     return 0;
    2132.   }
    2133. }
    2134. //x86架构
    2135. /*
    2136. 。“重定位表”记录的是每个需要重定位的地方(即有了重定位表,就可知道哪个段、偏移多少的地方的地址或值是需要修改的)、重定位的类型、符号的名字(即重定位的地方属于哪个符号)。(静态)链接器在链接目标文件的时候,会扫描每个目标文件,为每个目标文件中的段分配运行时的地址(这个地址就是进程地址空间的地址,因为每个操作系统都会位应用程序指定装载地址、如eos和windows的0x00400000,linux的0x0804800,通过用操作系统指定的地址配置链接器,链接器根据每个段的属性、大小和对齐属性等,就可得到每个段运行时的地址了),这样每个段的地址就确定下来了,从而,每个符号的地址都确定了,然后把符号表中符号的值修改为正确的地址。然后连接器就会把所有目标文件的符号表合并为一个全局的符号表(主要是为了定位的方便)。接下来,连接器就读取每个目标文件,通过重定位表找到需要重定位的地方和这个符号的名字,然后用这个符号去检索全局符号表,得到符号的地址,再用个这个地址填入需要修正的地方(对于相对跳转指令是用这个地址和修正处的地址和修正处存放的值参运算计算出正确的跳转偏移,然后填入),最后把所有经过了重定位的目标文件中相同段名和属性的段合并,输出到最终的可执行文件中并建立相应的数据结构,可执行文件也是有格式的,linux 常见的elf,windows和eos的pe格式。
    2137. */
    2138. //重定位结构(Elf32_Rel)中的字段r_info指定重定位地址属于哪个符号,r_offset字段指定重定位的地方。然后把这个符号的绝对地址写到重定位的地方
    2139. enum obj_reloc arch_apply_relocation (struct obj_file *f,
    2140.          struct obj_section *targsec,
    2141.          struct obj_section *symsec,
    2142.          struct obj_symbol *sym,
    2143.          Elf32_Rel *rel,
    2144.          Elf32_Addr v)
    2145. {
    2146.   struct i386_file *ifile = (struct i386_file *)f;
    2147.   struct i386_symbol *isym = (struct i386_symbol *)sym;
    2148.     ////找到重定位的地方,下边在这个地方写入符号的绝对地址
    2149.   Elf32_Addr *loc = (Elf32_Addr *)(targsec->contents + rel->r_offset);
    2150.   Elf32_Addr dot = targsec->header.sh_addr + rel->r_offset;
    2151.   Elf32_Addr got = ifile->got ? ifile->got->header.sh_addr : 0;
    2152.   enum obj_reloc ret = obj_reloc_ok;
    2153.   switch (ELF32_R_TYPE(rel->r_info))//重定位类型
    2154.     {
    2155.     case R_386_NONE:
    2156.       break;
    2157.     case R_386_32:
    2158.       *loc += v;
    2159.       break;
    2160.     case R_386_PLT32:
    2161.     case R_386_PC32:
    2162.       *loc += v - dot;
    2163.       break;
    2164.     case R_386_GLOB_DAT:
    2165.     case R_386_JMP_SLOT:
    2166.       *loc = v;
    2167.       break;
    2168.     case R_386_RELATIVE:
    2169.       *loc += f->baseaddr;
    2170.       break;
    2171.     case R_386_GOTPC:
    2172.       assert(got != 0);
    2173.       *loc += got - dot;
    2174.       break;
    2175.     case R_386_GOT32:
    2176.       assert(isym != NULL);
    2177.       if (!isym->gotent.reloc_done)
    2178.             {
    2179.              isym->gotent.reloc_done = 1;
    2180.              *(Elf32_Addr *)(ifile->got->contents + isym->gotent.offset) = v;
    2181.             }
    2182.       *loc += isym->gotent.offset;
    2183.       break;
    2184.     case R_386_GOTOFF:
    2185.       assert(got != 0);
    2186.       *loc += v - got;
    2187.       break;
    2188.     default:
    2189.       ret = obj_reloc_unhandled;
    2190.       break;
    2191.     }
    2192.   return ret;
    2193. }
    2194. //insmod包含在modutils包里。我们感兴趣的东西是insmod.c文件里的init_module()函数。
    2195. static int init_module(const char *m_name, struct obj_file *f,unsigned long m_size, const char *blob_name,unsigned int noload, unsigned int flag_load_map)
    2196. {
    2197.     //传入的参数m_name是模块名称,obj_file *f已经将模块的节区信息添加到该结构中,m_size是模块大小
    2198.     struct module *module;
    2199.     struct obj_section *sec;
    2200.     void *image;
    2201.     int ret = 0;
    2202.     tgt_long m_addr;
    2203.     //从节区数组中查找.this节区
    2204.     sec = obj_find_section(f, ".this");
    2205.     module = (struct module *) sec->contents;//取得本节区的内容,是一个module结构
    2206.     //下边的操作就是初始化module结构,都保存在.this节区的contents中。
    2207.     
    2208.     //.this节区的偏移地址地址就是module结构的在内核空间的起始地址,因为.this节区是首节区,前边该节区的偏移地址根据内核空间的模块起始地址做了一个偏移即sec->header.sh_addr+m_addr,又因为.this节区的sh_addr初始值是0,所以加了这个偏移,就正好指向模块在内核空间的起始地址。
    2209.     m_addr = sec->header.sh_addr;
    2210.     
    2211.     module->size_of_struct = sizeof(*module);//模块结构大小
    2212.     module->size = m_size;//模块大小
    2213.     module->flags = flag_autoclean ? NEW_MOD_AUTOCLEAN : 0;
    2214.     //查找__ksymtab节表,保存的是该模块导出的符号
    2215.     sec = obj_find_section(f, "__ksymtab");
    2216.     if (sec && sec->header.sh_size) {
    2217.         module->syms = sec->header.sh_addr;
    2218.         module->nsyms = sec->header.sh_size / (2 * tgt_sizeof_char_p);
    2219.     }
    2220.     
    2221.     //查找.kmodtab节表,module的依赖对象对应于.kmodtab节区
    2222.     if (n_ext_modules_used) {
    2223.         sec = obj_find_section(f, ".kmodtab");
    2224.         module->deps = sec->header.sh_addr;
    2225.         module->ndeps = n_ext_modules_used;
    2226.     }
    2227.     
    2228.     //obj_find_symbol()函数遍历符号列表查找名字为init_module的符号,然后提取这个结构体符号(struct symbol)并把它传递给 obj_symbol_final_value()。后者从这个结构体符号提取出init_module函数的地址。
    2229.     module->init = obj_symbol_final_value(f, obj_find_symbol(f, "init_module"));
    2230.     module->cleanup = obj_symbol_final_value(f,obj_find_symbol(f, "cleanup_module"));
    2231.     //查找__ex_table节表
    2232.     sec = obj_find_section(f, "__ex_table");
    2233.     if (sec) {
    2234.         module->ex_table_start = sec->header.sh_addr;
    2235.         module->ex_table_end = sec->header.sh_addr + sec->header.sh_size;
    2236.     }
    2237.     
    2238.     //查找.text.init节表
    2239.     sec = obj_find_section(f, ".text.init");
    2240.     if (sec) {
    2241.         module->runsize = sec->header.sh_addr - m_addr;
    2242.     }
    2243.     //查找.data.init节表
    2244.     sec = obj_find_section(f, ".data.init");
    2245.     if (sec) {
    2246.         if (!module->runsize || module->runsize > sec->header.sh_addr - m_addr)
    2247.             module->runsize = sec->header.sh_addr - m_addr;
    2248.     }
    2249.     
    2250.     sec = obj_find_section(f, ARCHDATA_SEC_NAME);
    2251.     if (sec && sec->header.sh_size) {
    2252.         module->archdata_start = sec->header.sh_addr;
    2253.         module->archdata_end = module->archdata_start + sec->header.sh_size;
    2254.     }
    2255.     
    2256.     //查找kallsyms节区
    2257.     sec = obj_find_section(f, KALLSYMS_SEC_NAME);
    2258.     if (sec && sec->header.sh_size) {
    2259.         module->kallsyms_start = sec->header.sh_addr;//符号开始地址
    2260.         module->kallsyms_end = module->kallsyms_start + sec->header.sh_size;//符号结束地址
    2261.     }
    2262.     if (!arch_init_module(f, module))//x86下什么也不干
    2263.         return 0;
    2264.     //在用户空间分配module的image的内存,返回模块起始地址
    2265.     image = xmalloc(m_size);
    2266.     //各个section的内容拷入image中,包括原文件中的section和后来构造的section 
    2267.     obj_create_image(f, image);//模块内容从f结构指定的地址中拷贝到image中,构建模块映像
    2268.     if (flag_load_map)
    2269.         print_load_map(f);
    2270.     if (blob_name) {//是否指定了要输出模块到指定的文件blob_name
    2271.         int fd, l;
    2272.         fd = open(blob_name, O_WRONLY|O_CREAT|O_TRUNC, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
    2273.         if (fd < 0) {
    2274.             error("open %s failed %m", blob_name);
    2275.             ret = -1;
    2276.         }
    2277.         else {
    2278.             if ((l = write(fd, image, m_size)) != m_size) {
    2279.                 error("write %s failed %m", blob_name);
    2280.                 ret = -1;
    2281.             }
    2282.             close(fd);
    2283.         }
    2284.     }
    2285.     if (ret == 0 && !noload) {
    2286.         fflush(stdout);        /* Flush any debugging output */
    2287.         //sys_init_module() 这个系统调用通知内核加载相应模块,这个函数的代码可以在 /usr/src/linux/kernel/module.c 
    2288.         //在此函数中把在用户空间的module映像复制到前边由create_module创建地内核空间中。 
    2289.         ret = sys_init_module(m_name, (struct module *) image);
    2290.         if (ret) {
    2291.             error("init_module: %m");
    2292.             lprintf("Hint: insmod errors can be caused by incorrect module parameters, "
    2293.                 "including invalid IO or IRQ parameters.You may find more information in syslog or the output from dmesg

    1. }
    2.     }
    3.     free(image);
    4.     return ret == 0;
    5. }
    6. int obj_create_image (struct obj_file *f, char *image)
    7. {
    8.   struct obj_section *sec;
    9.   ElfW(Addr) base = f->baseaddr;
    10.     //注意:首个load的节区是.this节区
    11.   for (sec = f->load_order; sec ; sec = sec->load_next)
    12.   {
    13.     char *secimg;
    14.     if (sec->contents == 0)
    15.             continue;
    16.     secimg = image + (sec->header.sh_addr - base);
    17.     //所有的节区内容拷贝到以image地址开始的地方,当然第一个节区的内容恰好是struct module结构
    18.     memcpy(secimg, sec->contents, sec->header.sh_size);
    19.   }
    20.   return 1;

      1. int sys_init_module(const char *name, const struct module *info)
      2. {
      3.  //调用系统调用init_module(),系统调用init_module()在内核中的实现是sys_init_module(),这是由内核提供的,全内核只有这一个函数。注意,这是linux V2.6以前的调用。
      4.   return init_module(name, info);
      5. }
      6. asmlinkage long sys_init_module(const char *name_user, struct module *mod_user)
      7. {
      8.  struct module mod_tmp, *mod;
      9.  char *name, *n_name, *name_tmp = NULL;
      10.  long namelen, n_namelen, i, error;
      11.  unsigned long mod_user_size;
      12.  struct module_ref *dep;
      13.  
      14.  //检查模块加载的权限
      15.  if (!capable(CAP_SYS_MODULE))
      16.   return EPERM;
      17.  lock_kernel();
      18.  //复制模块名到内核空间name中
      19.  if ((namelen = get_mod_name(name_user, &name)) < 0) {
      20.   error = namelen;
      21.   goto err0;
      22.  }
      23.  //从module_list中找到之前通过creat_module()在内核空间创建的module结构,创建模块时已经将模块结构链入module_list
      24.  if ((mod = find_module(name)) == NULL) {
      25.   error = ENOENT;
      26.   goto err1;
      27.  }
      28.  //把用户空间的module结构的size_of_struct复制到内核中加以检查,将模块结构的大小size_of_struct赋值给mod_user_size,即sizeof(struct module)
      29.  if ((error = get_user(mod_user_size, &mod_user->size_of_struct)) != 0)
      30.   goto err1;
      31.   
      32.  //对用户空间和内核空间的module结构的大小进行检查
      33.  //如果申请的模块头部长度小于旧版的模块头长度或者大于将来可能的模块头长度
      34.  if (mod_user_size < (unsigned long)&((struct module *)0L)->persist_start
      35.      || mod_user_size > sizeof(struct module) + 16*sizeof(void*)) {
      36.   printk(KERN_ERR "init_module: Invalid module header size. "
      37.           KERN_ERR "A new version of the modutils is likely ""needed. ");
      38.   error = EINVAL;
      39.   goto err1;
      40.  }
      41.  mod_tmp = *mod;//内核中的module结构先保存到堆栈中
      42.  //分配保存内核空间模块名的空间
      43.  name_tmp = kmalloc(strlen(mod->name) + 1, GFP_KERNEL); /* Where's kstrdup()? */
      44.  if (name_tmp == NULL) {
      45.   error = ENOMEM;
      46.   goto err1;
      47.  }
      48.  strcpy(name_tmp, mod->name);//将内核中module的name复制给name_tmp,在堆栈中先保存起来
      49.  
      50.  //将用户空间的模块结构到内核空间原来的module地址处(即将用户空间的模块映像覆盖掉在内核空间模块映像的所在地址,这样前边设置的符号地址就不需要改变了,正好就是我们在前边按照内核空间的模块起始地址设置的),mod_user_size是模块结构的大小,即sizeof(struct module)
      51.  error = copy_from_user(mod, mod_user, mod_user_size);
      52.  if (error) {
      53.   error = EFAULT;
      54.   goto err2;
      55.  }
      56.  error = EINVAL; 
      57.  
      58.  //比较内核空间和用户空间模块大小,若在insmod用户空间创建的module结构大小大于内核空间的module大小,就出错退出 
      59.  if (mod->size > mod_tmp.size) {
      60.   printk(KERN_ERR "init_module: Size of initialized module ""exceeds size of created module. ");
      61.   goto err2;
      62.  } 
      63.  if (!mod_bound(mod->name, namelen, mod)) {//用来检查用户指针所指的对象是否落在模块的边界内
      64.   printk(KERN_ERR "init_module: mod->name out of bounds. ");
      65.   goto err2;
      66.  }
      67.  if (mod->nsyms && !mod_bound(mod->syms, mod->nsyms, mod)) {// 符号表的区域是否在模块体中
      68.   printk(KERN_ERR "init_module: mod->syms out of bounds. ");
      69.   goto err2;
      70.  }
      71.  if (mod->ndeps && !mod_bound(mod->deps, mod->ndeps, mod)) {//依赖关系表是否在模块体中
      72.   printk(KERN_ERR "init_module: mod->deps out of bounds. ");
      73.   goto err2;
      74.  }
      75.  if (mod->init && !mod_bound(mod->init, 0, mod)) {//init函数是否是模块体中
      76.   printk(KERN_ERR "init_module: mod->init out of bounds. ");
      77.   goto err2;
      78.  }
      79.  if (mod->cleanup && !mod_bound(mod->cleanup, 0, mod)) {//cleanup函数是否是模块体中
      80.   printk(KERN_ERR "init_module: mod->cleanup out of bounds. ");
      81.   goto err2;
      82.  }
      83.  //检查模块的异常描述表是否在模块影像内
      84.  if (mod->ex_table_start > mod->ex_table_end|| (mod->ex_table_start 
      85.  &&!((unsigned long)mod->ex_table_start >= ((unsigned long)mod + mod->size_of_struct)
      86.  && ((unsigned long)mod->ex_table_end< (unsigned long)mod + mod->size)))|| 
      87.  (((unsigned long)mod->ex_table_start-(unsigned long)mod->ex_table_end)% sizeof(struct exception_table_entry))) {
      88.   printk(KERN_ERR "init_module: mod->ex_table_* invalid. ");
      89.   goto err2;
      90.  }
      91.  if (mod->flags & ~MOD_AUTOCLEAN) {
      92.   printk(KERN_ERR "init_module: mod->flags invalid. ");
      93.   goto err2;
      94.  }
      95.  if (mod_member_present(mod, can_unload)//检查结构的大小,看用户模块是否包含can_unload字段
      96.  && mod->can_unload && !mod_bound(mod->can_unload, 0, mod)) {//若包含can_unload字段,就检查其边界
      97.   printk(KERN_ERR "init_module: mod->can_unload out of bounds. ");
      98.   goto err2;
      99.  }
      100.  if (mod_member_present(mod, kallsyms_end)) {
      101.     if (mod->kallsyms_end &&(!mod_bound(mod->kallsyms_start, 0, mod) ||!mod_bound(mod->kallsyms_end, 0, mod))) {
      102.       printk(KERN_ERR "init_module: mod->kallsyms out of bounds. ");
      103.       goto err2;
      104.     }
      105.     if (mod->kallsyms_start > mod->kallsyms_end) {
      106.       printk(KERN_ERR "init_module: mod->kallsyms invalid. ");
      107.       goto err2;
      108.     }
      109.  }
      110.  if (mod_member_present(mod, archdata_end)) {
      111.     if (mod->archdata_end &&(!mod_bound(mod->archdata_start, 0, mod) ||
      112.     !mod_bound(mod->archdata_end, 0, mod))) {
      113.       printk(KERN_ERR "init_module: mod->archdata out of bounds. ");
      114.       goto err2;
      115.     }
      116.     if (mod->archdata_start > mod->archdata_end) {
      117.       printk(KERN_ERR "init_module: mod->archdata invalid. ");
      118.       goto err2;
      119.     }
      120.  }
      121.  if (mod_member_present(mod, kernel_data) && mod->kernel_data) {
      122.      printk(KERN_ERR "init_module: mod->kernel_data must be zero. ");
      123.      goto err2;
      124.  }
      125.  
      126.  //在把用户空间的模块名从用户空间拷贝进来
      127.  if ((n_namelen = get_mod_name(mod->name-(unsigned long)mod+ (unsigned long)mod_user,&n_name)) < 0) {
      128.     printk(KERN_ERR "init_module: get_mod_name failure. ");
      129.     error = n_namelen;
      130.     goto err2;
      131.  }
      132.  //比较内核空间中和用户空间中模块名是否相同
      133.  if (namelen != n_namelen || strcmp(n_name, mod_tmp.name) != 0) {
      134.   printk(KERN_ERR "init_module: changed module name to ""`%s' from `%s' ",n_name, mod_tmp.name);
      135.   goto err3;
      136.  }
      137.  
      138.  //拷贝除module结构本身以外的其它section到内核空间中,就是拷贝模块映像
      139.  if (copy_from_user((char *)mod+mod_user_size,(char *)mod_user+mod_user_size,mod->size-mod_user_size)) {
      140.   error = EFAULT;
      141.   goto err3;
      142.  }
      143.  
      144.  if (module_arch_init(mod))//空操作
      145.   goto err3;
      146.  
      147.  flush_icache_range((unsigned long)mod, (unsigned long)mod + mod->size);
      148.  mod->next = mod_tmp.next;//mod->next在拷贝模块头时被覆盖了
      149.  mod->refs = NULL;//由于是新加载的,还没有别的模块引用我
      150.  
      151.  //检查模块的依赖关系,依赖的模块仍在内核中
      152.  for (i = 0, dep = mod->deps; i < mod->ndeps; ++i, ++dep) {
      153.   struct module *o, *d = dep->dep;
      154.   if (d == mod) {//依赖的模块不能使自身
      155.    printk(KERN_ERR "init_module: selfreferential""dependency in mod->deps. ");
      156.    goto err3;
      157.   }
      158.   //若依赖的模块已经不在module_list中,则系统调用失败
      159.   for (o = module_list; o != &kernel_module && o != d; o = o->next);
      160.   if (o != d) {
      161.    printk(KERN_ERR "init_module: found dependency that is ""(no longer?) a module. ");
      162.    goto err3;
      163.   }
      164.  }
      165.  //再扫描,将每个module_ref结构链入到所依赖模块的refs队列中,并将结构中的ref指针指向正在安装的nodule结构。这样每个module_ref结构既存在于所属模块的deps[]数组中,又出现于该模块所依赖的某个模块的refs队列中。
      166.  for (i = 0, dep = mod->deps; i < mod->ndeps; ++i, ++dep) {
      167.   struct module *d = dep->dep;
      168.   dep->ref = mod;
      169.   dep->next_ref = d->refs;
      170.   d->refs = dep;
      171.   d->flags |= MOD_USED_ONCE;
      172.  }
      173.  
      174.  put_mod_name(n_name);//释放空间
      175.  put_mod_name(name);//释放空间
      176.  mod->flags |= MOD_INITIALIZING;//设置模块初始化标志
      177.  atomic_set(&mod->uc.usecount,1);//用户计数设为1
      178.  
      179.   //检查模块的init_module()函数,然后执行模块的init_module()函数,注意此函数与内核中的
      180.   //init_module()函数是不一样的,内核中的调用sys_init_module()
      181.  if (mod->init && (error = mod->init()) != 0) {
      182.   atomic_set(&mod->uc.usecount,0);//模块的计数加1
      183.   mod->flags &= ~MOD_INITIALIZING;//初始化标志清零
      184.   if (error > 0) /* Buggy module */
      185.    error = EBUSY;
      186.   goto err0;
      187.  }
      188.  atomic_dec(&mod->uc.usecount);//递减计数
      189.  //初始化标志清零,标志设置为MOD_RUNNING
      190.  mod->flags = (mod->flags | MOD_RUNNING) & ~MOD_INITIALIZING;
      191.  error = 0;
      192.  goto err0;
      193. err3:
      194.  put_mod_name(n_name);
      195. err2:
      196.  *mod = mod_tmp;
      197.  strcpy((char *)mod->name, name_tmp); /* We know there is room for this */
      198. err1:
      199.  put_mod_name(name);
      200. err0:
      201.  unlock_kernel();
      202.  kfree(name_tmp);
      203.  return error;
      204. }
  • 相关阅读:
    字符串转换成整数
    回文字符串判断
    字符串包含
    翻转单词顺序VS左旋转字符串
    穷举子集合
    求S=a+aa+aaa+aaaa+aa...a的值
    数组元素去重
    找最长等差数列的长度
    Git pull and push
    Google 开发console查找元素或方法
  • 原文地址:https://www.cnblogs.com/sky-heaven/p/5587867.html
Copyright © 2011-2022 走看看