insmod过程详解


  1. 转自 http://blog.chinaunix.net/xmlrpc.php?r=blog/article&uid=27717694&id=3971861

  2. 一、前言
  3. 对于现在编译的一些module要insmod在系统上时,可能会报各种各样的错误。这些错误仔细研读内核源码,都能找出原因。2.6 内核以前的insmod部分主要依赖于modutils源码包,在用户层基本将工作完成,加载过程参考前一篇文章。2.6 内核以后的做法是将大部分的原来用户级操作纳入内核中来处理,无论是逻辑上还是代码量上都比原来减少了许多,通过busybox中的insmod命令与内核接入。把这套源代码弄明白,就不会出现加载模块时出现的各种各样的错误,可以写一些patch代码,修正这些内核要检查的项,比如vermagic和crc等等。

  4. 二、相关结构

  5. 1.模块依赖关系
  6. struct module_use {
  7.     struct list_head source_list;
  8.     struct list_head target_list;
  9.     struct module *source, *target;
  10. };
  11.  
  12. 2.模块状态
  13. enum module_state {
  14.     MODULE_STATE_LIVE, /* Normal state. */
  15.     MODULE_STATE_COMING, /* Full formed, running module_init. */
  16.     MODULE_STATE_GOING, /* Going away. */
  17.     MODULE_STATE_UNFORMED, /* Still setting it up. */
  18. };
  19.     
  20. 3.模块计数
  21. struct module_ref {
  22.     unsigned long incs;
  23.     unsigned long decs;
  24. } __attribute((aligned(* sizeof(unsigned long))));

  25. 4.模块结构
  26. struct module
  27. {
  28.     enum module_state state;    
  29.     /* Member of list of modules */
  30.     struct list_head list;    
  31.     /* Unique handle for this module */
  32.     char name[MODULE_NAME_LEN];
  33.     /* Sysfs stuff. */
  34.     struct module_kobject mkobj;
  35.     struct module_attribute *modinfo_attrs;
  36.     const char *version;
  37.     const char *srcversion;
  38.     struct kobject *holders_dir;    
  39.     /* Exported symbols */
  40.     const struct kernel_symbol *syms;
  41.     const unsigned long *crcs;
  42.     unsigned int num_syms;     
  43.     /* Kernel parameters. */
  44.     struct kernel_param *kp;
  45.     unsigned int num_kp;    
  46.     /* GPL-only exported symbols. */
  47.     unsigned int num_gpl_syms;
  48.     const struct kernel_symbol *gpl_syms;
  49.     const unsigned long *gpl_crcs;
  50.     
  51. #ifdef CONFIG_UNUSED_SYMBOLS
  52.     /* unused exported symbols. */
  53.     const struct kernel_symbol *unused_syms;
  54.     const unsigned long *unused_crcs;
  55.     unsigned int num_unused_syms;    
  56.     /* GPL-only, unused exported symbols. */
  57.     unsigned int num_unused_gpl_syms;
  58.     const struct kernel_symbol *unused_gpl_syms;
  59.     const unsigned long *unused_gpl_crcs;
  60. #endif
  61.      
  62. #ifdef CONFIG_MODULE_SIG
  63.     /* Signature was verified. */
  64.     bool sig_ok;
  65. #endif
  66.      
  67.     /* symbols that will be GPL-only in the near future. */
  68.     const struct kernel_symbol *gpl_future_syms;
  69.     const unsigned long *gpl_future_crcs;
  70.     unsigned int num_gpl_future_syms;
  71.      
  72.     /* Exception table */
  73.     unsigned int num_exentries;
  74.     struct exception_table_entry *extable;
  75.     
  76.     /* Startup function. */
  77.     int (*init)(void);
  78.     
  79.     /* If this is non-NULL, vfree after init() returns */
  80.     void *module_init;
  81.      
  82.     /* Here is the actual code + data, vfree'on unload. */
  83.     void *module_core;
  84.     
  85.     /* Here are the sizes of the init and core sections */
  86.     unsigned int init_size, core_size;
  87.      
  88.     /* The size of the executable code in each section. */
  89.     unsigned int init_text_size, core_text_size;
  90.     
  91.     /* Size of RO sections of the module (text+rodata) */
  92.     unsigned int init_ro_size, core_ro_size;
  93.     
  94.     /* Arch-specific module values */
  95.     struct mod_arch_specific arch;
  96.     
  97.     unsigned int taints; /* same bits as kernel:tainted */
  98.     
  99. #ifdef CONFIG_GENERIC_BUG
  100.     /* Support for BUG */
  101.     unsigned num_bugs;
  102.     struct list_head bug_list;
  103.     struct bug_entry *bug_table;
  104. #endif
  105.      
  106. #ifdef CONFIG_KALLSYMS
  107.     Elf_Sym *symtab, *core_symtab;
  108.     unsigned int num_symtab, core_num_syms;
  109.     char *strtab, *core_strtab;
  110.     
  111.     /* Section attributes */
  112.     struct module_sect_attrs *sect_attrs;
  113.     
  114.     /* Notes attributes */
  115.     struct module_notes_attrs *notes_attrs;
  116. #endif
  117.     
  118.     char *args;
  119.     
  120. #ifdef CONFIG_SMP
  121.     /* Per-cpu data. */
  122.     void __percpu *percpu;
  123.     unsigned int percpu_size;
  124. #endif
  125.      
  126. #ifdef CONFIG_TRACEPOINTS
  127.     unsigned int num_tracepoints;
  128.     struct tracepoint * const *tracepoints_ptrs;
  129. #endif

  130. #ifdef HAVE_JUMP_LABEL
  131.     struct jump_entry *jump_entries;
  132.     unsigned int num_jump_entries;
  133. #endif

  134. #ifdef CONFIG_TRACING
  135.     unsigned int num_trace_bprintk_fmt;
  136.     const char **trace_bprintk_fmt_start;
  137. #endif

  138. #ifdef CONFIG_EVENT_TRACING
  139.     struct ftrace_event_call **trace_events;
  140.     unsigned int num_trace_events;
  141. #endif

  142. #ifdef CONFIG_FTRACE_MCOUNT_RECORD
  143.     unsigned int num_ftrace_callsites;
  144.     unsigned long *ftrace_callsites;
  145. #endif
  146.     
  147. #ifdef CONFIG_MODULE_UNLOAD
  148.     /* What modules depend on me? */
  149.     struct list_head source_list;
  150.      /* What modules do I depend on? */
  151.     struct list_head target_list;
  152.     
  153.     /* Who is waiting for us to be unloaded */
  154.     struct task_struct *waiter;
  155.     
  156.      /* Destruction function. */
  157.     void (*exit)(void);
  158.     struct module_ref __percpu *refptr;
  159. #endif
  160.     
  161. #ifdef CONFIG_CONSTRUCTORS
  162.     /* Constructor functions. */
  163.     ctor_fn_t *ctors;
  164.     unsigned int num_ctors;
  165. #endif
  166. };

  167. 5.ELF文件信息结构
  168. struct load_info {
  169.     Elf_Ehdr *hdr;//指向elf头
  170.     unsigned long len;
  171.     Elf_Shdr *sechdrs;//指向节区头
  172.     char *secstrings;//指向字符串节区中节区名称所在的地址
  173.     char *strtab;//指向字符串节区的内容所在地址
  174.     unsigned long symoffs;
  175.     unsigned long stroffs;
  176.     struct _ddebug *debug;
  177.     unsigned int num_debug;
  178.     bool sig_ok;//模块签名检查
  179.     struct {
  180.         unsigned int sym;//模块的符号表节区索引号
  181.         unsigned int str;//模块的字符串节区索引号
  182.         unsigned int mod;//模块的".gnu.linkonce.this_module"节区索引号
  183.         unsigned int vers;//模块的"__versions"节区索引号
  184.         unsigned int info;//模块的.modinfo节区索引号
  185.         unsigned int pcpu;
  186.     } index;
  187. };

  188. 三、源代码解析
  189. //busybox中insmod.c文件中
  190. int insmod_main(int argc UNUSED_PARAM, char **argv)
  191. {
  192.     char *filename;
  193.     int rc;

  194.     IF_FEATURE_2_4_MODULES(
  195.         getopt32(argv, INSMOD_OPTS INSMOD_ARGS);
  196.         argv += optind - 1;
  197.     );

  198.     //取得要加载模块的路径名
  199.     filename = *++argv;
  200.     if (!filename)
  201.         bb_show_usage();

  202.     rc = bb_init_module(filename, parse_cmdline_module_options(argv,0));
  203.     if (rc)
  204.         bb_error_msg("can't insert '%s': %s", filename, moderror(rc));

  205.     return rc;
  206. }

  207. char* FAST_FUNC parse_cmdline_module_options(char **argv, int quote_spaces)
  208. {
  209.     char *options;
  210.     int optlen;

  211.     options = xzalloc(1);
  212.     optlen = 0;
  213.     
  214.     //遍历模块名后边的模块参数
  215.     while (*++argv) {
  216.         const char *fmt;
  217.         const char *var;
  218.         const char *val;

  219.         var = *argv;
  220.         //为options分配空间
  221.         options = xrealloc(options, optlen + 2 + strlen(var) + 2);
  222.         fmt = "%.*s%s ";
  223.         //'='存在于var中,则返回'='在var中出现的第一个位置的指针,否则返回字符串var末尾的空字符。
  224.         val = strchrnul(var, '=');
  225.         if (quote_spaces) {//为0
  226.             if (*val) { /* has var=val format. skip '=' */
  227.                 val++;
  228.                 if (strchr(val, ' '))
  229.                     fmt = "%.*s\"%s\" ";
  230.             }
  231.         }
  232.         //模块参数按格式存入options,"%.*s%s "中“*”对应(int)(val - var),第一个s对应var,表示在var字符串中去除(int)(val - var)个字符显示,即=前边的字符被去除。实际上只是将val字符串(=后边的字符串)存入options指针指向的地址。
  233.         optlen += sprintf(options + optlen, fmt, (int)(val - var), var, val);
  234.     }

  235.     return options;
  236. }

  237. int FAST_FUNC bb_init_module(const char *filename, const char *options)
  238. {
  239.     size_t image_size;
  240.     char *image;
  241.     int rc;
  242.     bool mmaped;

  243.     if (!options)
  244.         options = "";

  245. //若是2.6以前的版本调用bb_init_module_24(),这种处理就是以前modutils对模块的加载处理。这里要研究的是2.6以后的模块加载处理
  246. #if ENABLE_FEATURE_2_4_MODULES
  247.     if (get_linux_version_code() < KERNEL_VERSION(2,6,0))
  248.         return bb_init_module_24(filename, options);
  249. #endif

  250.     image_size = INT_MAX - 4095;//初始化为文件的最大值
  251.     mmaped = 0;
  252.     
  253.     //把模块文件映射进内存,并返回映射空间的大小image_size
  254.     image = try_to_mmap_module(filename, &image_size);
  255.     if (image) {
  256.         mmaped = 1;
  257.     } else {
  258.         errno = ENOMEM; /* may be changed by e.g. open errors below */
  259.         image = xmalloc_open_zipped_read_close(filename, &image_size);
  260.         if (!image)
  261.             return -errno;
  262.     }
  263.     errno = 0;
  264.     
  265.     //系统调用,对应内核函数是sys_init_module()函数,进入到内核空间
  266.     init_module(image, image_size, options);
  267.     rc = errno;
  268.     if (mmaped)
  269.         munmap(image, image_size);
  270.     else
  271.         free(image);
  272.     return rc;
  273. }

  274. void* FAST_FUNC try_to_mmap_module(const char *filename, size_t *image_size_p)
  275. {
  276.     void *image;
  277.     struct stat st;
  278.     int fd;

  279.     //打开模块.ko文件,获得文件描述符
  280.     fd = xopen(filename, O_RDONLY);
  281.     //由文件描述符取得文件状态
  282.     fstat(fd, &st);
  283.     image = NULL;
  284.     
  285.     //文件的size是否超过设定的文件最大值
  286.     if (st.st_size <= *image_size_p) {
  287.         size_t image_size = st.st_size;//文件size
  288.         //以只读的方式将.ko文件映射到内存中,返回在内存中的起始地址
  289.         image = mmap(NULL, image_size, PROT_READ, MAP_PRIVATE, fd, 0);
  290.         if (image == MAP_FAILED) {
  291.             image = NULL;
  292.         }
  293.         //检查一下.ko文件的开头是否为ELF标准格式 
  294.         else if (*(uint32_t*)image != SWAP_BE32(0x7f454C46)) {
  295.             munmap(image, image_size);
  296.             image = NULL;
  297.         } else {
  298.             *image_size_p = image_size;//返回文件size
  299.         }
  300.     }
  301.     close(fd);
  302.     return image;
  303. }

  304. //sys_init_module(void __user *umod,unsigned long len,const char __user *uargs)
  305. //umod : 是一个指针,指向用户地址空间中的区域,模块的二进制代码位于其中。 
  306. //len : 该区域的长度。 
  307. //uargs : 是一个指针,指定了模块的参数。
  308. SYSCALL_DEFINE3(init_module, void __user *, umod,unsigned long, len, const char __user *, uargs)
  309. {
  310.     int err;
  311.     struct load_info info = { };
  312.     
  313.     //是否有权限加载模块:capable(CAP_SYS_MODULE)
  314.     err = may_init_module();
  315.     if (err)
  316.         return err;
  317.         
  318.     pr_debug("init_module: umod=%p, len=%lu, uargs=%p\n",umod, len, uargs); 
  319.     
  320.     //将用户空间的.ko文件的内存映像(elf格式)拷贝到内核空间,并填充info结构中
  321.     err = copy_module_from_user(umod, len, &info);
  322.     if (err)
  323.         return err; 
  324.         
  325.     //模块的主要操作
  326.     return load_module(&info, uargs, 0);
  327. }

  328.  static int copy_module_from_user(const void __user *umod, unsigned long len,struct load_info *info)
  329. {
  330.     int err;
  331.     
  332.     //模块文件映射到用户空间的size(.ko文件本身的size)
  333.     info->len = len;
  334.     if (info->len < sizeof(*(info->hdr)))
  335.         return -ENOEXEC;
  336.     
  337.     err = security_kernel_module_from_file(NULL);
  338.     if (err)
  339.         return err;
  340.     
  341.     //在内核空间为模块分配内存,并将该内存的起始地址付给成员hdr,即该成员现在指向的是整个模块内存
  342.     info->hdr = vmalloc(info->len);
  343.     if (!info->hdr)
  344.         return -ENOMEM;
  345.         
  346.     //将用户空间的.ko文件的内存映像(elf格式)拷贝到内核空间info->hdr处
  347.     if (copy_from_user(info->hdr, umod, info->len) != 0) {
  348.         vfree(info->hdr);
  349.         return -EFAULT;
  350.     }
  351.     return 0;
  352. }

  353. static int load_module(struct load_info *info, const char __user *uargs,int flags)
  354. {
  355.     struct module *mod;
  356.     long err;
  357.     
  358.     err = module_sig_check(info);//检查证书
  359.     if (err)
  360.         goto free_copy; 
  361.     err = elf_header_check(info);//检查elf头
  362.     if (err)
  363.         goto free_copy; 
  364.         
  365.     //布置模块,并分配相关的内存,把相关节区复制到最终镜像中
  366.     mod = layout_and_allocate(info, flags);
  367.     if (IS_ERR(mod)) {
  368.         err = PTR_ERR(mod);
  369.         goto free_copy;
  370.     }
  371.      
  372.     //因为前边已将模块镜像复制到了内核空间的内存中,module对象也指向对应的位置,然后将此module对象添加到modules链表中
  373.     err = add_unformed_module(mod);
  374.     if (err)
  375.         goto free_module;
  376.      
  377. #ifdef CONFIG_MODULE_SIG
  378.     mod->sig_ok = info->sig_ok;
  379.     if (!mod->sig_ok) {
  380.         printk_once(KERN_NOTICE
  381.             "%s: module verification failed: signature and/or"
  382.             " required key missing - tainting kernel\n",mod->name);
  383.         add_taint_module(mod, TAINT_FORCED_MODULE, LOCKDEP_STILL_OK);
  384.     }
  385. #endif

  386.     //为节区pcpu分配空间,用于多处理器,此处不考虑
  387.     err = percpu_modalloc(mod, info);
  388.     if (err)
  389.         goto unlink_mod; 
  390.         
  391.     //模块计数加1,并初始化模块链表
  392.     err = module_unload_init(mod);
  393.     if (err)
  394.         goto unlink_mod;

  395.     //找到其余节区地址,初始化module对象相关指针
  396.     find_module_sections(mod, info);
  397.  
  398.      //检查license和version
  399.     err = check_module_license_and_versions(mod);
  400.     if (err)
  401.         goto free_unload;
  402.  
  403.     //根据.modinfo段设置模块信息
  404.     setup_modinfo(mod, info);
  405.  
  406.     //根据前边设置的模块在内核的起始地址,节区的起始地址已经更新,但是节区中符号的地址还未进行更新,这里根据节区的内存地址更新符号地址
  407.     err = simplify_symbols(mod, info);
  408.     if (err < 0)
  409.         goto free_modinfo;
  410.  
  411.      //对模块中的重定位节区做重定位操作
  412.     err = apply_relocations(mod, info);
  413.     if (err < 0)
  414.         goto free_modinfo;
  415.  
  416.     err = post_relocation(mod, info);
  417.     if (err < 0)
  418.         goto free_modinfo;
  419.  
  420.      //Flush the instruction cache,no care
  421.     flush_module_icache(mod);
  422.  
  423.     //把可选参数从用户空间复制到内核空间
  424.   mod->args = strndup_user(uargs, ~0UL >> 1);
  425.     if (IS_ERR(mod->args)) {
  426.         err = PTR_ERR(mod->args);
  427.         goto free_arch_cleanup;
  428.     }
  429.  
  430.      //处理用于debug节区
  431.     dynamic_debug_setup(info->debug, info->num_debug);
  432.  
  433.     //确认是否有重定义符号,并且设置模块状态为正在运行
  434.   err = complete_formation(mod, info);
  435.     if (err)
  436.         goto ddebug_cleanup;
  437.  
  438.     /* Module is ready to execute: parsing args may do that. */
  439.  //分析参数是否有效
  440.     err = parse_args(mod->name, mod->args, mod->kp, mod->num_kp,-32768, 32767, unknown_module_param_cb);
  441.     if (err < 0)
  442.         goto bug_cleanup; 

  443.   //sysfs文件系统相关,在sysfs中创建模块相应的项
  444.     err = mod_sysfs_setup(mod, info, mod->kp, mod->num_kp);
  445.     if (err < 0)
  446.         goto bug_cleanup;
  447.      
  448.     //释放临时模块镜像和其他临时辅助内存区
  449.   free_copy(info);
  450.     
  451.     /* */
  452.     trace_module_load(mod);
  453.     
  454.     //调用do_init_module开始运行模块 
  455.     return do_init_module(mod);
  456.      
  457. bug_cleanup:
  458.     /* module_bug_cleanup needs module_mutex protection */
  459.     mutex_lock(&module_mutex);
  460.     module_bug_cleanup(mod);
  461.     mutex_unlock(&module_mutex);
  462. ddebug_cleanup:
  463.     dynamic_debug_remove(info->debug);
  464.     synchronize_sched();
  465.     kfree(mod->args);
  466. free_arch_cleanup:
  467.     module_arch_cleanup(mod);
  468. free_modinfo:
  469.     free_modinfo(mod);
  470. free_unload:
  471.     module_unload_free(mod);
  472. unlink_mod:
  473.     mutex_lock(&module_mutex);
  474.     /* Unlink carefully: kallsyms could be walking list. */
  475.     list_del_rcu(&mod->list);
  476.     wake_up_all(&module_wq);
  477.     mutex_unlock(&module_mutex);
  478. free_module:
  479.     module_deallocate(mod, info);
  480. free_copy:
  481.     free_copy(info);
  482.     return err;
  483. }

  484. static int module_sig_check(struct load_info *info)
  485. {
  486.     //#define MODULE_SIG_STRING "~Module signature appended~\n"
  487.     int err = -ENOKEY;
  488.     const unsigned long markerlen = sizeof(MODULE_SIG_STRING) - 1;
  489.     const void *mod = info->hdr;
  490.     //elf文件长度是否大于签名字符串长度,并且比较该elf格式的模块文件是否在文件末尾有signature string。若有的话则将该文件长度减去该字符串长度,并确认该签名是module类型。
  491.     if (info->len > markerlen && memcmp(mod + info->len - markerlen, MODULE_SIG_STRING, markerlen) == 0) 
  492.     {
  493.         info->len -= markerlen;//模块长度减去签名字符串的长度
  494.         err = mod_verify_sig(mod, &info->len);//验证模块签名
  495.     }
  496.     if (!err) {
  497.         info->sig_ok = true;
  498.         return 0;
  499.     }
  500.     
  501.     /* Not having a signature is only an error if we're strict. */
  502.     if (err < 0 && fips_enabled)
  503.         panic("Module verification failed with error %d in FIPS mode\n",err);
  504.     if (err == -ENOKEY && !sig_enforce)
  505.         err = 0;
  506.     return err;
  507. }

  508. struct module_signature {
  509.     u8 algo; /* Public-key crypto algorithm [enum pkey_algo] */
  510.     u8 hash; /* Digest algorithm [enum pkey_hash_algo] */
  511.     u8 id_type; /* Key identifier type [enum pkey_id_type] */
  512.     u8 signer_len; /* Length of signer's name */
  513.     u8 key_id_len; /* Length of key identifier */
  514.     u8 __pad[3];
  515.     __be32 sig_len; /* Length of signature data */
  516. };

  517. int mod_verify_sig(const void *mod, unsigned long *_modlen)
  518. {
  519.     //mod是模块文件起始地址,_modlen是模块文件的大小(去掉了最后的签名字符串长度)
  520.     struct public_key_signature *pks;
  521.     struct module_signature ms;
  522.     struct key *key;
  523.     const void *sig;
  524.     size_t modlen = *_modlen, sig_len;
  525.     int ret;
  526.     
  527.     pr_devel("==>%s(,%zu)\n", __func__, modlen);
  528.     
  529.     //检查长度 
  530.     if (modlen <= sizeof(ms))
  531.         return -EBADMSG;
  532.      
  533.     //如果.ko文件最后有签名字符串的话,则签名字符串之上有一个module_signature结构,读出这个结构的内容
  534.     memcpy(&ms, mod + (modlen - sizeof(ms)), sizeof(ms));
  535.     modlen -= sizeof(ms);//相应修改模块文件长度
  536.  
  537.     sig_len = be32_to_cpu(ms.sig_len);//获得签名数据长度
  538.     if (sig_len >= modlen)
  539.         return -EBADMSG;
  540.     modlen -= sig_len;//模块文件长度再减去签名数据长度
  541.     
  542.     if ((size_t)ms.signer_len + ms.key_id_len >= modlen)
  543.         return -EBADMSG;
  544.     //模块文件长度再减去签名人名字长度和key长度
  545.     modlen -= (size_t)ms.signer_len + ms.key_id_len;
  546.     
  547.     *_modlen = modlen;//去掉签名验证的信息后返回模块真实size
  548.     //文件指针移到签名信息处
  549.     sig = mod + modlen;
  550.  
  551.     /* For the moment, only support RSA and X.509 identifiers */
  552.     if (ms.algo != PKEY_ALGO_RSA || ms.id_type != PKEY_ID_X509)
  553.         return -ENOPKG;
  554.  
  555.     if (ms.hash >= PKEY_HASH__LAST || !pkey_hash_algo[ms.hash])
  556.         return -ENOPKG;
  557.  
  558.      //将signer name和key identifier从文件sig处读出来,返回key
  559.     key = request_asymmetric_key(sig, ms.signer_len,sig + ms.signer_len, ms.key_id_len);
  560.     if (IS_ERR(key))
  561.         return PTR_ERR(key);
  562.      
  563.     //Digest the module contents.
  564.     pks = mod_make_digest(ms.hash, mod, modlen);
  565.     if (IS_ERR(pks)) {
  566.         ret = PTR_ERR(pks);
  567.         goto error_put_key;
  568.     }
  569.     
  570.     //Extract an MPI array from the signature data. This represents the actual signature. Each raw MPI is prefaced by a BE 2-byte value indicating the size of the MPI in bytes.RSA signatures only have one MPI, so currently we only read one.
  571.     ret = mod_extract_mpi_array(pks, sig + ms.signer_len + ms.key_id_len,sig_len);
  572.     if (ret < 0)
  573.         goto error_free_pks;
  574.      
  575.     //Initiate the use of an asymmetric key to verify a signature
  576.      //key: The asymmetric key to verify against
  577.      //sig: The signature to check
  578.     ret = verify_signature(key, pks);
  579.     pr_devel("verify_signature() = %d\n", ret);
  580.      
  581. error_free_pks:
  582.     mpi_free(pks->rsa.s);
  583.     kfree(pks);
  584. error_put_key:
  585.     key_put(key);
  586.     pr_devel("<==%s() = %d\n", __func__, ret);
  587.     return ret; 
  588. }

  589. static int elf_header_check(struct load_info *info)
  590. {
  591.     if (info->len < sizeof(*(info->hdr)))
  592.         return -ENOEXEC;
  593.  
  594.      //检查elf文件头,以及文件类型(.ko文件必是可重定位文件),架构以及节区大小是否设置正确
  595.     if (memcmp(info->hdr->e_ident, ELFMAG, SELFMAG) != 0|| info->hdr->e_type != ET_REL
  596.     || !elf_check_arch(info->hdr)|| info->hdr->e_shentsize != sizeof(Elf_Shdr))
  597.         return -ENOEXEC;
  598.  
  599.      //检查节区的偏移地址
  600.     if (info->hdr->e_shoff >= info->len
  601.     || (info->hdr->e_shnum * sizeof(Elf_Shdr) >info->len - info->hdr->e_shoff))
  602.         return -ENOEXEC;
  603.  
  604.     return 0;
  605. }

  606. static struct module *layout_and_allocate(struct load_info *info, int flags)
  607. {
  608.     struct module *mod;
  609.     int err;
  610.     
  611.     //设置info结构,并检查module_layout的crc值,并返回一个存储在.gnu.linkonce.this_module节区中的struct module结构,该module的起始地址正是.gnu.linkonce.this_module节区起始地址
  612.     mod = setup_load_info(info, flags);
  613.     if (IS_ERR(mod))
  614.         return mod;
  615.     
  616.     //检查.modinfo节区中的信息,包括version magic 
  617.     err = check_modinfo(mod, info, flags);
  618.     if (err)
  619.         return ERR_PTR(err);
  620.     
  621.     //什么也不做,返回0
  622.     err = module_frob_arch_sections(info->hdr, info->sechdrs,info->secstrings, mod);
  623.     if (err < 0)
  624.     return ERR_PTR(err);
  625.     
  626.     //移除SHF_ALLOC标志
  627.     info->sechdrs[info->index.pcpu].sh_flags &= ~(unsigned long)SHF_ALLOC;
  628.     
  629.     //只有节区头部设置了SHF_ALLOC标志,才最终存于内存中,且内存分为init部分和core部分
  630.     layout_sections(mod, info);
  631.     
  632.     //为symbol section以及跟它相关的string table布置位置,更新相关size
  633.     layout_symtab(mod, info);
  634.      
  635.     //为mod指向的临时镜像中标记了SHF_ALLOC节区分配内存,并从临时镜像复制到最终的位置,并且修改节区的起始地址
  636.     err = move_module(mod, info);
  637.     if (err)
  638.         return ERR_PTR(err);
  639.      
  640.     //因为前边已将模块靠诶到最终的内存位置,所以各个节区的起始地址已经改变,之前mod指向的地址已经无效,所以重新将新的“.gnu.linkonce.this_module”节区的起始地址(指向一个module对象)赋给mod对象
  641.     mod = (void *)info->sechdrs[info->index.mod].sh_addr;
  642.     
  643.     //扫描检查内存泄露???
  644.     kmemleak_load_module(mod, info);
  645.     return mod;
  646. }

  647. static struct module *setup_load_info(struct load_info *info) 
  648. { 
  649.   unsigned int i; 
  650.   int err; 
  651.   struct module *mod; 

  652.   //找到节区头部表开始地址
  653.   info->sechdrs = (void *)info->hdr + info->hdr->e_shoff; 
  654.   //找到节区名称的字符串节区的起始地址
  655.   info->secstrings = (void *)info->hdr + info->sechdrs[info->hdr->e_shstrndx].sh_offset; 

  656.     //根据elf格式的.ko文件拷贝到内核空间内存中的虚拟地址为基地址((void *)info->hdr),重写节区在内存映像中节区第一个字节应处的位置
  657.   err = rewrite_section_headers(info); 
  658.   if (err) 
  659.       return ERR_PTR(err); 

  660. /*遍历所有节区找到符号表(类型为 SHT_SYMTAB 的唯一段)和相关的符号字符串表的位置, 
  661. 前者的 sh_link 即为后者的段索引*/
  662.   for (= 1; i < info->hdr->e_shnum; i++) { 
  663.     if (info->sechdrs[i].sh_type == SHT_SYMTAB){ 
  664.         //找到符号表节区.symtab索引 
  665.       info->index.sym = i; 
  666.       //找到符号表字符串节区索引,即.strtab节区
  667.       info->index.str = info->sechdrs[i].sh_link; 
  668.       //字符串节区内容开始地址
  669.       info->strtab = (char *)info->hdr + info->sechdrs[info->index.str].sh_offset;
  670.       break; 
  671.     } 
  672.   } 

  673. //.gnu.linkonce.this_module节区中,有一个struct module的实例,此结构大部分成员是NULL,编译器只是初始化了name,init,exit和arch等几个成员。
  674.   info->index.mod = find_sec(info, ".gnu.linkonce.this_module"); 
  675.   if (!info->index.mod) { 
  676.       printk(KERN_WARNING "No module found in object\n"); 
  677.       return ERR_PTR(-ENOEXEC); 
  678.   } 

  679.     //mod指向 struct module的实例,该实例中提供了模块的名称和指向初始化以及清理函数的指针,但其他成员仍然初始化为 NULL 或 0. 将该模块的地址暂时设为临时映像中节区给出的地址,后边会对module的地址再做出修正.
  680.   mod = (void *)info->sechdrs[info->index.mod].sh_addr; 

  681.   if (info->index.sym == 0) { 
  682.       printk(KERN_WARNING "%s: module has no symbols (stripped?)\n", mod->name); 
  683.       return ERR_PTR(-ENOEXEC); 
  684.   } 
  685.     
  686.     //查找".data..percpu"节区索引号
  687.   info->index.pcpu = find_pcpusec(info); 

  688.   //检查模块中“module_layout”符号的crc值,若失败则打印著名模块加载错误“Exec format error ”
  689.   if (!check_modstruct_version(info->sechdrs, info->index.vers, mod)) 
  690.       return ERR_PTR(-ENOEXEC); 

  691.   return mod; 
  692. }

  693. static int rewrite_section_headers(struct load_info *info, int flags)
  694. {
  695.     unsigned int i;
  696.     info->sechdrs[0].sh_addr = 0;//节区0地址是0,表示此节区不出现在内存映像中
  697.     for (= 1; i < info->hdr->e_shnum; i++) {
  698.         Elf_Shdr *shdr = &info->sechdrs[i];
  699.         //判断节区size
  700.         if (shdr->sh_type != SHT_NOBITS && info->len < shdr->sh_offset + shdr->sh_size) {
  701.             printk(KERN_ERR "Module len %lu truncated\n",info->len);
  702.             return -ENOEXEC;
  703.         }

  704.         //在elf文件拷贝到内核空间的基地址基础上重新设置节区在内核空间的起始地址,shdr->sh_addr表示节区在内存映像中节区第一个字节应处的位置
  705.         shdr->sh_addr = (size_t)info->hdr + shdr->sh_offset;
  706. #ifndef CONFIG_MODULE_UNLOAD
  707.     /* Don't load .exit sections */
  708.         if (strstarts(info->secstrings+shdr->sh_name, ".exit"))
  709.             shdr->sh_flags &= ~(unsigned long)SHF_ALLOC;
  710. #endif
  711.     }
  712.     
  713.     //找到__versions和.modinfo节区,并记录节区索引
  714.     if (flags & MODULE_INIT_IGNORE_MODVERSIONS)
  715.         info->index.vers = 0;
  716.     else
  717.         info->index.vers = find_sec(info, "__versions");        
  718.     info->index.info = find_sec(info, ".modinfo");
  719.     //这两个节区清楚SHF_ALLOC标志,表示此节区在进程执行过程中不占用内存
  720.     info->sechdrs[info->index.info].sh_flags &= ~(unsigned long)SHF_ALLOC;
  721.     info->sechdrs[info->index.vers].sh_flags &= ~(unsigned long)SHF_ALLOC;
  722.     return 0;
  723. }

  724. static inline int check_modstruct_version(Elf_Shdr *sechdrs,unsigned int versindex,struct module *mod)
  725. {
  726.     const unsigned long *crc;
  727.     
  728.     //查找系统内核中“module_layout”符号,并返回该符号的crc值
  729.     if (!find_symbol(VMLINUX_SYMBOL_STR(module_layout), NULL,&crc, true, false))
  730.         BUG();
  731.         
  732.     //系统中“module_layout”符号的crc值与模块中的“module_layout”符号crc值是否一致
  733.     return check_version(sechdrs, versindex,VMLINUX_SYMBOL_STR(module_layout), mod, crc,NULL);
  734. }

  735. //查找符号使用的结构体
  736. struct find_symbol_arg {
  737.     //输入
  738.     const char *name;//要查找的符号名
  739.     bool gplok;//如果为真,则表示内核模块支持GPL许可
  740.     bool warn;//警告信息标志
  741.      
  742.     //输出
  743.     struct module *owner;//该符号所属的模块
  744.     const unsigned long *crc;//该符号的crc值
  745.     const struct kernel_symbol *sym;//符号结构
  746. };

  747. const struct kernel_symbol *find_symbol(const char *name,struct module **owner,const unsigned long **crc,bool gplok,bool warn)
  748. {
  749.     //设置查找符号参数结构
  750.     struct find_symbol_arg fsa;
  751.     fsa.name = name;
  752.     fsa.gplok = gplok;
  753.     fsa.warn = warn;

  754.     //查找符号,填写符号参数结构的输出部分
  755.     if (each_symbol_section(find_symbol_in_section, &fsa)) {
  756.         if (owner)//NULL,下边不需赋值
  757.             *owner = fsa.owner;
  758.             
  759.         if (crc)//得到该符号的crc值
  760.             *crc = fsa.crc;
  761.             
  762.         //返回以name命名的内核符号结构
  763.         return fsa.sym;
  764.     }
  765.      
  766.      //没有找到内核符号,返回NULL
  767.     pr_debug("Failed to find symbol %s\n", name);
  768.     return NULL;
  769. }

  770. bool each_symbol_section(bool (*fn)(const struct symsearch *arr,struct module *owner,void *data),void *data)
  771. {
  772.     struct module *mod;
  773.     //第一部分在内核导出的符号表中查找对应的符号,找到就返回对应的符号信息,否则,再进行第二部分查找.
  774. /*struct symsearch {
  775.         const struct kernel_symbol *start, *stop;
  776.         const unsigned long *crcs;
  777.         enum {
  778.             NOT_GPL_ONLY,
  779.             GPL_ONLY,
  780.             WILL_BE_GPL_ONLY,
  781.         } licence;
  782.         bool unused;
  783.     };
  784. */
  785.     static const struct symsearch arr[] = {
  786.         { __start___ksymtab, __stop___ksymtab,
  787.             __start___kcrctab,NOT_GPL_ONLY, false },
  788.         { __start___ksymtab_gpl, __stop___ksymtab_gpl,
  789.             __start___kcrctab_gpl,GPL_ONLY, false },
  790.         { __start___ksymtab_gpl_future, __stop___ksymtab_gpl_future,
  791.             __start___kcrctab_gpl_future,WILL_BE_GPL_ONLY, false },
  792. #ifdef CONFIG_UNUSED_SYMBOLS
  793.         { __start___ksymtab_unused, __stop___ksymtab_unused,
  794.             __start___kcrctab_unused,NOT_GPL_ONLY, true },
  795.         { __start___ksymtab_unused_gpl, __stop___ksymtab_unused_gpl,
  796.             __start___kcrctab_unused_gpl,GPL_ONLY, true },
  797. #endif
  798.     };

  799.     if (each_symbol_in_section(arr, ARRAY_SIZE(arr), NULL, fn, data))
  800.         return true;
  801.  
  802.      //在内核导出的符号表中没有找到对应的符号,则在系统已加载的模块中查找
  803.     list_for_each_entry_rcu(mod, &modules, list) {
  804.         struct symsearch arr[] = {
  805.             { mod->syms, mod->syms + mod->num_syms, 
  806.                 mod->crcs,NOT_GPL_ONLY, false },
  807.             { mod->gpl_syms, mod->gpl_syms + mod->num_gpl_syms,
  808.                 mod->gpl_crcs,GPL_ONLY, false },
  809.             { mod->gpl_future_syms,mod->gpl_future_syms + mod->num_gpl_future_syms,
  810.                 mod->gpl_future_crcs,WILL_BE_GPL_ONLY, false },
  811. #ifdef CONFIG_UNUSED_SYMBOLS
  812.             { mod->unused_syms,mod->unused_syms + mod->num_unused_syms,
  813.                 mod->unused_crcs, NOT_GPL_ONLY, true },
  814.             { mod->unused_gpl_syms,mod->unused_gpl_syms + mod->num_unused_gpl_syms,
  815.                 mod->unused_gpl_crcs,GPL_ONLY, true },
  816. #endif
  817.         };
  818.         
  819.         //若模块状态为MODULE_STATE_UNFORMED,则此模块的符号不可用
  820.         if (mod->state == MODULE_STATE_UNFORMED)
  821.             continue;
  822.      
  823.         if (each_symbol_in_section(arr, ARRAY_SIZE(arr), mod, fn, data))
  824.             return true;
  825.     }
  826.     return false;
  827. }

  828. static bool each_symbol_in_section(const struct symsearch *arr,unsigned int arrsize,struct module *owner,bool (*fn)(const struct symsearch *syms,struct module *owner,void *data),void *data)
  829. {
  830.     unsigned int j;
  831.     
  832.     //调用find_symbol_in_section()对每个数组指定的符号地址范围进行查找
  833.     for (= 0; j < arrsize; j++) {
  834.         if (fn(&arr[j], owner, data))//调用find_symbol_in_section()
  835.         return true;
  836.     }
  837.     return false;
  838. }

  839. static bool find_symbol_in_section(const struct symsearch *syms,struct module *owner,void *data)
  840. {
  841.     struct find_symbol_arg *fsa = data;
  842.     struct kernel_symbol *sym;
  843.     
  844.     //在范围内查找符号名为fsa->name的内核符号
  845.     sym = bsearch(fsa->name, syms->start, syms->stop - syms->start,sizeof(struct kernel_symbol), cmp_name);
  846.  
  847.      //若找到内核符号,则对其进行check是否有效
  848.     if (sym != NULL && check_symbol(syms, owner, sym - syms->start, data))
  849.         return true;
  850.      
  851.     return false;
  852. }

  853. void *bsearch(const void *key, const void *base, size_t num, size_t size,int (*cmp)(const void *key, const void *elt))
  854. {
  855.     size_t start = 0, end = num;
  856.     int result;
  857.      
  858.     while (start < end) {//折半查找
  859.         size_t mid = start + (end - start) / 2;
  860.          
  861.         //调用cmp_name()函数比较符号名是否一致
  862.         result = cmp(key, base + mid * size);
  863.         if (result < 0)
  864.             end = mid;
  865.         else if (result > 0)
  866.             start = mid + 1;
  867.         else
  868.             return (void *)base + mid * size;
  869.     }
  870.     return NULL;
  871. }

  872. static int cmp_name(const void *va, const void *vb)
  873. {
  874.     const char *a;
  875.     const struct kernel_symbol *b;
  876.     a = va; b = vb;
  877.     return strcmp(a, b->name);
  878. }

  879. static bool check_symbol(const struct symsearch *syms,struct module *owner,unsigned int symnum, void *data)
  880. {
  881.     struct find_symbol_arg *fsa = data;
  882.     
  883.     if (!fsa->gplok) {//若未设置gplok,则必须为GPL许可
  884.         if (syms->licence == GPL_ONLY)
  885.             return false;
  886.         if (syms->licence == WILL_BE_GPL_ONLY && fsa->warn) {
  887.             printk(KERN_WARNING "Symbol %s is being used "
  888.                         "by a non-GPL module, which will not "
  889.                         "be allowed in the future\n", fsa->name);
  890.         }
  891.     }
  892.     
  893. #ifdef CONFIG_UNUSED_SYMBOLS
  894.     if (syms->unused && fsa->warn) {
  895.         printk(KERN_WARNING "Symbol %s is marked as UNUSED, "
  896.                     "however this module is using it.\n", fsa->name);
  897.         printk(KERN_WARNING"This symbol will go away in the future.\n");
  898.         printk(KERN_WARNING
  899.                     "Please evalute if this is the right api to use and if "
  900.                     "it really is, submit a report the linux kernel "
  901.                     "mailinglist together with submitting your code for "
  902.                     "inclusion.\n");
  903.     }
  904. #endif
  905.      
  906.     fsa->owner = owner;//符号所属模块
  907.     //#define symversion(base, idx) ((base != NULL) ? ((base) + (idx)) : NULL)
  908.     fsa->crc = symversion(syms->crcs, symnum);//符号的crc值
  909.     fsa->sym = &syms->start[symnum];//返回的符号结构
  910.     return true;
  911. }

  912. static int check_version(Elf_Shdr *sechdrs,unsigned int versindex,const char *symname,struct module *mod, const unsigned long *crc,const struct module *crc_owner)
  913. {
  914.     unsigned int i, num_versions;
  915.     struct modversion_info *versions;
  916.     
  917.     //若系统中的该符号crc值为0,则直接返回1完事
  918.     if (!crc)
  919.         return 1;
  920.         
  921.     //若该模块的elf格式文件中没有__versions节区,则尝试强制加载模块
  922.     //但是try_to_force_load()函数的实现依赖于CONFIG_MODULE_FORCE_LOAD宏是否定义。而该宏默认是没有定义的,所以这里会返回失败,看来内核并不推荐强制加载模块。
  923.     if (versindex == 0)
  924.         return try_to_force_load(mod, symname) == 0;
  925.     
  926.     //找到模块“__versions”节区在内存映像中的起始地址。相当于节区的contents内容
  927.     versions = (void *) sechdrs[versindex].sh_addr;
  928.     num_versions = sechdrs[versindex].sh_size/ sizeof(struct modversion_info);
  929.     for (= 0; i < num_versions; i++) {
  930.         if (strcmp(versions[i].name, symname) != 0)//在此节区中找到要比较的符号
  931.             continue;
  932.             
  933.         //比较该模块中的符号crc值和现在系统上的内核符号的crc值是否一致
  934.         if (versions[i].crc == maybe_relocated(*crc, crc_owner))
  935.             return 1;
  936.         pr_debug("Found checksum %lX vs module %lX\n",maybe_relocated(*crc, crc_owner), versions[i].crc);
  937.         goto bad_version;
  938.     }
  939.     
  940.     //若在“__versions”节区没有找到要比较的符号,则会给出加载模块时常见错误:“no symbol version for”
  941.     printk(KERN_WARNING "%s: no symbol version for %s\n",mod->name, symname);
  942.     return 0;
  943. bad_version:
  944.     //如果比较符号的额crc值不一致,则会给出加载模块时常见错误“disagrees about version of symbol”
  945.     printk("%s: disagrees about version of symbol %s\n",mod->name, symname);
  946.     return 0;
  947. }

  948. static int try_to_force_load(struct module *mod, const char *reason)
  949. {
  950. #ifdef CONFIG_MODULE_FORCE_LOAD
  951.     //若选项CONFIG_MODULE_FORCE_LOAD打开,则检查tainted_mask是否设置了TAINT_FORCED_MODULE标志,若没有给出警告信息
  952.     if (!test_taint(TAINT_FORCED_MODULE))
  953.         printk(KERN_WARNING "%s: %s: kernel tainted.\n",mod->name, reason);
  954.         
  955.     //设置mod->taints和tainted_mask的TAINT_FORCED_MODULE标志,表示强制加载该模块,并返回正确值0
  956.     add_taint_module(mod, TAINT_FORCED_MODULE, LOCKDEP_NOW_UNRELIABLE);
  957.     return 0;
  958. #else
  959.     //若选项CONFIG_MODULE_FORCE_LOAD未打开,则直接返回错误
  960.     return -ENOEXEC;
  961. #endif
  962. }

  963. static int check_modinfo(struct module *mod, struct load_info *info, int flags)
  964. {
  965.     //从模块.modinfo节区中获得version magic
  966.     const char *modmagic = get_modinfo(info, "vermagic");
  967.     int err;
  968.     if (flags & MODULE_INIT_IGNORE_VERMAGIC)
  969.         modmagic = NULL;
  970.      
  971.      //若version magic为0,则尝试强制加载
  972.     if (!modmagic) {
  973.         err = try_to_force_load(mod, "bad vermagic");
  974.         if (err)
  975.             return err;
  976.     } 
  977.     //与内核的vermagic是否一致,若不一致,给出著名错误:“version magic ... should be ...,返回错误码
  978.     else if (!same_magic(modmagic, vermagic, info->index.vers)) {
  979.         printk(KERN_ERR "%s: version magic '%s' should be '%s'\n",mod->name, modmagic, vermagic);
  980.         return -ENOEXEC;
  981.     }
  982.     
  983.     //返回.modinfo节区中intree=...”的内容,若不存在设置标志TAINT_OOT_MODULE
  984.     if (!get_modinfo(info, "intree"))
  985.         add_taint_module(mod, TAINT_OOT_MODULE, LOCKDEP_STILL_OK);
  986.     
  987.     //返回.modinfo节区中staging=...”的内容,存在设置标志TAINT_CRAP
  988.     if (get_modinfo(info, "staging")) {
  989.         add_taint_module(mod, TAINT_CRAP, LOCKDEP_STILL_OK);
  990.         printk(KERN_WARNING "%s: module is from the staging directory,"" the quality is unknown, you have been warned.\n",mod->name);
  991.     }
  992.     
  993.     //取出.modinfo节区的license字段指定的license类型,并对此license检查
  994.     set_license(mod, get_modinfo(info, "license"));
  995.     return 0;
  996. }

  997. static char *get_modinfo(struct load_info *info, const char *tag)
  998. {
  999.     char *p;
  1000.     unsigned int taglen = strlen(tag);
  1001.     //找到模块.modinfo节区
  1002.     Elf_Shdr *infosec = &info->sechdrs[info->index.info];
  1003.     unsigned long size = infosec->sh_size;
  1004.     
  1005.     //查找.modinfo节区中的内容,返回"*tag"字符串=后边的内容
  1006.     for (= (char *)infosec->sh_addr; p; p = next_string(p, &size)) 
  1007.     {
  1008.         if (strncmp(p, tag, taglen) == 0 && p[taglen] == '=')
  1009.             return p + taglen + 1;
  1010.     }
  1011.     return NULL;
  1012. }

  1013. static inline int same_magic(const char *amagic, const char *bmagic, bool has_crcs)
  1014. {
  1015.     //从字符串中依次取出以“ ”结尾的字符串段进行比较
  1016.     if (has_crcs) {
  1017.         amagic += strcspn(amagic, " ");
  1018.         bmagic += strcspn(bmagic, " ");
  1019.     }
  1020.     return strcmp(amagic, bmagic) == 0;
  1021. }

  1022. static void set_license(struct module *mod, const char *license)
  1023. {
  1024.     if (!license)
  1025.         license = "unspecified";
  1026.         
  1027.     //比较模块的license类型是否是内核指定的GPL类型,若不是则设置TAINT_PROPRIETARY_MODULE标志
  1028.     if (!license_is_gpl_compatible(license)) {
  1029.         if (!test_taint(TAINT_PROPRIETARY_MODULE))
  1030.             printk(KERN_WARNING "%s: module license '%s' taints kernel.\n", mod->name, license);
  1031.         add_taint_module(mod, TAINT_PROPRIETARY_MODULE,LOCKDEP_NOW_UNRELIABLE);
  1032.     }
  1033. }

  1034. static inline int license_is_gpl_compatible(const char *license)
  1035. {
  1036.     return (strcmp(license, "GPL") == 0
  1037.                     || strcmp(license, "GPL v2") == 0
  1038.                     || strcmp(license, "GPL and additional rights") == 0
  1039.                     || strcmp(license, "Dual BSD/GPL") == 0
  1040.                     || strcmp(license, "Dual MIT/GPL") == 0
  1041.                     || strcmp(license, "Dual MPL/GPL") == 0);
  1042. }

  1043. static void layout_sections(struct module *mod, struct load_info *info)
  1044. {
  1045.     //注意:节的复制是按照原来ELF的顺序,将所有标志包含SHF_ALLOC的节都复制到相应的分配空间(module_core/module_init),例外的情况是SHT_NOBITS,也就是BSS段,文件中没有分配空间,因此不需要复制.
  1046.     
  1047.     //sections函数首先为标记了SHF_ALLOC的section定义了四种类型:code, read-only data,read-write data和small data. 带有SHF_ALLOC的section必定属于四类中的一类。函数遍历section header table中的所有项,将section name不是以".init"开始的section划归为COREsection. 以".init"开始的section划归为INIT section. 
  1048.   static unsigned long const masks[][2] = {
  1049.      { SHF_EXECINSTR | SHF_ALLOC, ARCH_SHF_SMALL },//code
  1050.      { SHF_ALLOC, SHF_WRITE | ARCH_SHF_SMALL },//read only data
  1051.      { SHF_WRITE | SHF_ALLOC, ARCH_SHF_SMALL },//read-write data
  1052.      { ARCH_SHF_SMALL | SHF_ALLOC, 0 }//small data
  1053.   };
  1054.   unsigned int m, i;

  1055.     //遍历所有节区初始化sh_entsize成员
  1056.     //某些节区中包含固定大小的项目,如符号表。对于这类节区,此成员sh_entsize给出每个表项的长度字节数。如果节区中并不包含固定长度表项的表格,此成员取值为 0。
  1057.   for (= 0; i < info->hdr->e_shnum; i++)
  1058.       info->sechdrs[i].sh_entsize = ~0UL; 
  1059.       
  1060.   //划分为两部分: CORE INIT 
  1061.   //第1部分CORE:查找标志中含有SHF_ALLOC的section
  1062.   for (= 0; m < ARRAY_SIZE(masks); ++m) {
  1063.     for (= 0; i < info->hdr->e_shnum; ++i) {
  1064.       Elf_Shdr *= &info->sechdrs[i];
  1065.       //找到节区名
  1066.       const char *sname = info->secstrings + s->sh_name; 
  1067.       //含有SHF_ALLOC的section需要加载到最终的内存 
  1068.       //含有SHF_ALLOC的section并且不以init开头的节区划分到CORE部分
  1069.       if ((s->sh_flags & masks[m][0]) != masks[m][0] 
  1070.               || (s->sh_flags & masks[m][1]) 
  1071.                || s->sh_entsize != ~0UL || strstarts(sname, ".init"))
  1072.           continue;
  1073.             
  1074.             //把由于对齐产生的偏移保存到节区的sh_entsize字段,后边mod通过sh_entsize就可以找到该节区存储的位置。并把符合要求的节区大小加到mod->core_size
  1075.       s->sh_entsize = get_offset(mod, &mod->core_size, s, i); 
  1076.     }
  1077.         
  1078.         //由于我们节的复制是按顺序的,而.text节是第一个节,因此mod->module_core实际上指向的就是.text段。而mod->core_text_size中也包含了.text节的大小.
  1079.     switch (m) {
  1080.     case 0: //可执行的段,代码段都一样
  1081.       mod->core_size = debug_align(mod->core_size);
  1082.       mod->core_text_size = mod->core_size; 
  1083.       break;
  1084.     case 1: //只读段
  1085.       mod->core_size = debug_align(mod->core_size);
  1086.       mod->core_ro_size = mod->core_size;
  1087.       break;
  1088.     case 3: //所有段
  1089.       mod->core_size = debug_align(mod->core_size);
  1090.       break;
  1091.     }
  1092.   }

  1093.   //第2部分INIT
  1094.   for (= 0; m < ARRAY_SIZE(masks); ++m) {
  1095.     for (= 0; i < info->hdr->e_shnum; ++i) {
  1096.       Elf_Shdr *= &info->sechdrs[i];
  1097.       const char *sname = info->secstrings + s->sh_name; 
  1098.         //含有SHF_ALLOC的section需要加载到最终的内存 
  1099.         //含有SHF_ALLOC的section并且以init开头的划分到INIT部分 
  1100.       if ((s->sh_flags & masks[m][0]) != masks[m][0]
  1101.        || (s->sh_flags & masks[m][1])
  1102.        || s->sh_entsize != ~0UL
  1103.        || !strstarts(sname, ".init"))
  1104.           continue;
  1105.           
  1106.       //把由于对齐产生的偏移保存到节区的sh_entsize字段,并把符合要求的节区大小加到 mod->init_size 
  1107.       s->sh_entsize = (get_offset(mod, &mod->init_size, s, i) | INIT_OFFSET_MASK);
  1108.     }

  1109.     switch (m) {
  1110.     case 0://代码段
  1111.       mod->init_size = debug_align(mod->init_size);
  1112.       mod->init_text_size = mod->init_size;
  1113.       break;
  1114.     case 1://只读段
  1115.       mod->init_size = debug_align(mod->init_size);
  1116.       mod->init_ro_size = mod->init_size;
  1117.       break;
  1118.     case 3://所有段 
  1119.       mod->init_size = debug_align(mod->init_size);
  1120.       break;
  1121.     }
  1122.   }
  1123. } 

  1124. static long get_offset(struct module *mod, unsigned int *size,Elf_Shdr *sechdr, unsigned int section)
  1125. {
  1126.     //#define ALIGN(x, a) __ALIGN_KERNEL((x), (a))
  1127.     //#define __ALIGN_KERNEL(x, a) __ALIGN_KERNEL_MASK(x, (typeof(x))(a) - 1)
  1128.   //#define __ALIGN_KERNEL_MASK(x, mask) (((x) + (mask)) & ~(mask))
  1129.     long ret;
  1130.     *size += arch_mod_section_prepend(mod, section);//空函数,返回0
  1131.     ret = ALIGN(*size, sechdr->sh_addralign ?: 1);//返回*size字节对齐后的值
  1132.     *size = ret + sechdr->sh_size;//把当前节区的size也加到*size上
  1133.     return ret;
  1134. }

  1135.  static void layout_symtab(struct module *mod, struct load_info *info)
  1136. {
  1137.     Elf_Shdr *symsect = info->sechdrs + info->index.sym;//找到符号表节区头部
  1138.     Elf_Shdr *strsect = info->sechdrs + info->index.str;//找到字符串表节区头部
  1139.     const Elf_Sym *src;
  1140.     unsigned int i, nsrc, ndst, strtab_size = 0;
  1141.     
  1142.     //符号节区设置SHF_ALLOC标志,表示在内存占空间
  1143.     symsect->sh_flags |= SHF_ALLOC;
  1144.     
  1145.     //设置符号表节区每个表项的长度字节数,并把符号表的size加到mod->init_size
  1146.     symsect->sh_entsize = get_offset(mod, &mod->init_size, symsect,info->index.sym) | INIT_OFFSET_MASK;
  1147.     
  1148.     pr_debug("\t%s\n", info->secstrings + symsect->sh_name);
  1149.     src = (void *)info->hdr + symsect->sh_offset;//符号表节区内容起始地址
  1150.     nsrc = symsect->sh_size / sizeof(*src);//符号表项个数
  1151.     
  1152.     //计算该模块包含的所有符号名长度所占的空间
  1153.     for (ndst = i = 0; i < nsrc; i++) {
  1154.         //is_core_symbol检查符号是否有效且属于SHF_ALLOC
  1155.         if (== 0 || is_core_symbol(src+i, info->sechdrs, info->hdr->e_shnum)) {
  1156.             strtab_size += strlen(&info->strtab[src[i].st_name])+1;
  1157.             ndst++;
  1158.         }
  1159.     }

  1160.     //将mod->core_size按符号节区对齐约束对齐后得到的值返回给info->symoffs
  1161.     info->symoffs = ALIGN(mod->core_size, symsect->sh_addralign ?: 1);
  1162.     //将符号表节区内容(即ndst个符号表项)添加到core部分的后边,并重新设置core部分的size。
  1163.     info->stroffs = mod->core_size = info->symoffs + ndst * sizeof(Elf_Sym);
  1164.     //core部分再把符号名的字符串所占空间加上
  1165.     mod->core_size += strtab_size;
  1166.     //注意:这里只是为符号项和符号的名称长度分配了空间,还并没有将内容拷贝过来,在下边的add_kallsyms函数中进行拷贝!!!
  1167.     
  1168.     //把字符串节区加到模块的init部分
  1169.     strsect->sh_flags |= SHF_ALLOC;//字符串节区也设置上需要内存空间标志
  1170.     strsect->sh_entsize = get_offset(mod, &mod->init_size, strsect,info->index.str) | INIT_OFFSET_MASK;
  1171.     pr_debug("\t%s\n", info->secstrings + strsect->sh_name);
  1172. }


  1173. static bool is_core_symbol(const Elf_Sym *src, const Elf_Shdr *sechdrs,unsigned int shnum)
  1174. {
  1175.     const Elf_Shdr *sec;
  1176.     //未定义的符号,或者符号索引号大于符号总个数,或者符号名为空则直接返回0
  1177.     if (src->st_shndx == SHN_UNDEF|| src->st_shndx >= shnum|| !src->st_name)
  1178.         return false;
  1179.         
  1180.     //找到符号所在的节区,若该节区不占内存,则也返回0
  1181.     sec = sechdrs + src->st_shndx;
  1182.     if (!(sec->sh_flags & SHF_ALLOC)
  1183. #ifndef CONFIG_KALLSYMS_ALL
  1184.         || !(sec->sh_flags & SHF_EXECINSTR)
  1185. #endif
  1186.         || (sec->sh_entsize & INIT_OFFSET_MASK))
  1187.         return false;
  1188.     return true;
  1189. }

  1190. static int move_module(struct module *mod, struct load_info *info)
  1191. {
  1192.     int i;
  1193.     void *ptr;
  1194.     
  1195.     //在内核空间为模块的core部分分配空间,返回地址
  1196.     ptr = module_alloc_update_bounds(mod->core_size);
  1197.     
  1198.     //但是要扫描这个指针所分配的内存的内容。分配数据结构那么该结构本身不打印,但是会扫描结构内部的成员变量,是否引用其他指针。
  1199.     kmemleak_not_leak(ptr);
  1200.     if (!ptr)
  1201.         return -ENOMEM;
  1202.     memset(ptr, 0, mod->core_size);
  1203.     mod->module_core = ptr;//地址赋给module_core成员
  1204.     
  1205.     //在内核空间为init section分配内存,初始化后存储在module对象的module_init成员中
  1206.     if (mod->init_size) {
  1207.         //为模块的init部分分配空间,返回地址
  1208.         ptr = module_alloc_update_bounds(mod->init_size);
  1209.     
  1210.         kmemleak_ignore(ptr);
  1211.         if (!ptr) {
  1212.             module_free(mod, mod->module_core);
  1213.             return -ENOMEM;
  1214.         }
  1215.         memset(ptr, 0, mod->init_size);
  1216.         mod->module_init = ptr;//地址赋给module_init
  1217.     } else
  1218.         mod->module_init = NULL;
  1219.     /* Transfer each section which specifies SHF_ALLOC */
  1220.     
  1221.     pr_debug("final section addresses:\n");
  1222.     //遍历所有节区,拷贝需要占用内存(标志为SHF_ALLOC的节区)的段到init section 或core section,并且调整各个节区的运行时地址
  1223.     for (= 0; i < info->hdr->e_shnum; i++) {
  1224.         void *dest;
  1225.         Elf_Shdr *shdr = &info->sechdrs[i];
  1226.         if (!(shdr->sh_flags & SHF_ALLOC))
  1227.             continue;
  1228.         
  1229.         //如果节区首部的sh_entsize的最高位设置的话,表示该段属于init section,则从module_init开始的内存中获取当前段应该存储的地址,否则从module_core开始的内存中获取当前段应该存储的地址。
  1230.         if (shdr->sh_entsize & INIT_OFFSET_MASK)
  1231.             dest = mod->module_init + (shdr->sh_entsize & ~INIT_OFFSET_MASK);
  1232.         else
  1233.             dest = mod->module_core + shdr->sh_entsize;
  1234.         
  1235.         //将当前节区的内容从ELF文件头拷贝到指定的段(init section或core section)中    
  1236.         if (shdr->sh_type != SHT_NOBITS)
  1237.             memcpy(dest, (void *)shdr->sh_addr, shdr->sh_size);
  1238.         
  1239.         //更改节区的运行时地址,sh_addr原先存储的地址是相对于ELF文件头的地址,现在是在内核空间分配新的内存空间后,节区新的运行地址(即节区内容的起始地址)
  1240.         shdr->sh_addr = (unsigned long)dest;
  1241.         pr_debug("\t0x%lx %s\n",(long)shdr->sh_addr, info->secstrings + shdr->sh_name);
  1242.     }
  1243.     return 0;
  1244. }

  1245. static void *module_alloc_update_bounds(unsigned long size)
  1246. {
  1247.     //在内核空间中分配size大小的空间,返回起始地址
  1248.     void *ret = module_alloc(size);
  1249.     
  1250.     //更新模块边界值
  1251.     if (ret) {
  1252.         mutex_lock(&module_mutex);
  1253.         if ((unsigned long)ret < module_addr_min)
  1254.             module_addr_min = (unsigned long)ret;
  1255.         if ((unsigned long)ret + size > module_addr_max)
  1256.             module_addr_max = (unsigned long)ret + size;
  1257.         mutex_unlock(&module_mutex);
  1258.     }
  1259.     return ret;
  1260. }

  1261. static int add_unformed_module(struct module *mod)
  1262. {
  1263.     int err;
  1264.     struct module *old;
  1265.     mod->state = MODULE_STATE_UNFORMED;
  1266. again:
  1267.     mutex_lock(&module_mutex);
  1268.     //在内核中查找此模块是否已加入链表
  1269.     old = find_module_all(mod->name, strlen(mod->name), true);
  1270.     if (old != NULL) {
  1271.         if (old->state == MODULE_STATE_COMING|| old->state == MODULE_STATE_UNFORMED) {
  1272.             /* Wait in case it fails to load. */
  1273.             mutex_unlock(&module_mutex);
  1274.             err = wait_event_interruptible(module_wq,finished_loading(mod->name));
  1275.             if (err)
  1276.                 goto out_unlocked;
  1277.             goto again;
  1278.         }
  1279.         err = -EEXIST;
  1280.         goto out;
  1281.     }
  1282.     //若还没有,则挂入全局模块链表modules
  1283.     list_add_rcu(&mod->list, &modules);
  1284.     err = 0;
  1285. out:
  1286.     mutex_unlock(&module_mutex);
  1287.     out_unlocked:
  1288.     return err;
  1289. }

  1290. static int module_unload_init(struct module *mod)
  1291. {
  1292.     //初始化多处理下用于引用计数的refptr成员
  1293.     mod->refptr = alloc_percpu(struct module_ref);
  1294.     if (!mod->refptr)
  1295.         return -ENOMEM;

  1296.     //初始化module对象的链表
  1297.     INIT_LIST_HEAD(&mod->source_list);
  1298.     INIT_LIST_HEAD(&mod->target_list);     
  1299.     //模块计数加1
  1300.     __this_cpu_write(mod->refptr->incs, 1);
  1301.     /* Backwards compatibility macros put refcount during init. */
  1302.     mod->waiter = current;
  1303.  
  1304.     return 0;
  1305. }

  1306. static void find_module_sections(struct module *mod, struct load_info *info)
  1307. {
  1308.     mod->kp = section_objs(info, "__param",sizeof(*mod->kp), &mod->num_kp);
  1309.     mod->syms = section_objs(info, "__ksymtab",sizeof(*mod->syms), &mod->num_syms);
  1310.     mod->crcs = section_addr(info, "__kcrctab");
  1311.     mod->gpl_syms = section_objs(info, "__ksymtab_gpl",sizeof(*mod->gpl_syms),&mod->num_gpl_syms);
  1312.     mod->gpl_crcs = section_addr(info, "__kcrctab_gpl");
  1313.     mod->gpl_future_syms = section_objs(info,"__ksymtab_gpl_future",
  1314.     sizeof(*mod->gpl_future_syms),&mod->num_gpl_future_syms);
  1315.     mod->gpl_future_crcs = section_addr(info, "__kcrctab_gpl_future");
  1316.     
  1317. #ifdef CONFIG_UNUSED_SYMBOLS
  1318.     mod->unused_syms = section_objs(info, "__ksymtab_unused",sizeof(*mod->unused_syms),&mod->num_unused_syms);
  1319.     mod->unused_crcs = section_addr(info, "__kcrctab_unused");
  1320.     mod->unused_gpl_syms = section_objs(info, "__ksymtab_unused_gpl",sizeof(*mod->unused_gpl_syms),&mod->num_unused_gpl_syms);
  1321.     mod->unused_gpl_crcs = section_addr(info, "__kcrctab_unused_gpl");
  1322. #endif
  1323. #ifdef CONFIG_CONSTRUCTORS
  1324.     mod->ctors = section_objs(info, ".ctors",sizeof(*mod->ctors), &mod->num_ctors);
  1325. #endif
  1326.      
  1327. #ifdef CONFIG_TRACEPOINTS
  1328.     mod->tracepoints_ptrs = section_objs(info, "__tracepoints_ptrs",sizeof(*mod->tracepoints_ptrs),&mod->num_tracepoints);
  1329. #endif
  1330. #ifdef HAVE_JUMP_LABEL
  1331.     mod->jump_entries = section_objs(info, "__jump_table",sizeof(*mod->jump_entries),&mod->num_jump_entries);
  1332. #endif
  1333. #ifdef CONFIG_EVENT_TRACING
  1334.     mod->trace_events = section_objs(info, "_ftrace_events",sizeof(*mod->trace_events),&mod->num_trace_events);
  1335. #endif
  1336. #ifdef CONFIG_TRACING
  1337.     mod->trace_bprintk_fmt_start = section_objs(info, "__trace_printk_fmt",sizeof(*mod->trace_bprintk_fmt_start),&mod->num_trace_bprintk_fmt);
  1338. #endif
  1339. #ifdef CONFIG_FTRACE_MCOUNT_RECORD
  1340.     /* sechdrs[0].sh_size is always zero */
  1341.     mod->ftrace_callsites = section_objs(info, "__mcount_loc",sizeof(*mod->ftrace_callsites),&mod->num_ftrace_callsites);
  1342. #endif
  1343.     
  1344.     mod->extable = section_objs(info, "__ex_table",sizeof(*mod->extable), &mod->num_exentries);
  1345.     
  1346.     if (section_addr(info, "__obsparm"))
  1347.         printk(KERN_WARNING "%s: Ignoring obsolete parameters\n",mod->name);
  1348.     
  1349.     info->debug = section_objs(info, "__verbose",sizeof(*info->debug), &info->num_debug);
  1350. }

  1351. static void *section_objs(const struct load_info *info,const char *name,size_t object_size,unsigned int *num)
  1352. {
  1353.     //根据节区名找到节区索引值
  1354.     unsigned int sec = find_sec(info, name);    
  1355.     //计算节区项目数
  1356.     *num = info->sechdrs[sec].sh_size / object_size;
  1357.     //返回节区起始地址
  1358.     return (void *)info->sechdrs[sec].sh_addr;
  1359. }

  1360. static int check_module_license_and_versions(struct module *mod)
  1361. {
  1362.     if (strcmp(mod->name, "ndiswrapper") == 0)
  1363.         add_taint(TAINT_PROPRIETARY_MODULE, LOCKDEP_NOW_UNRELIABLE);
  1364.     
  1365.     /* driverloader was caught wrongly pretending to be under GPL */
  1366.     if (strcmp(mod->name, "driverloader") == 0)
  1367.         add_taint_module(mod, TAINT_PROPRIETARY_MODULE,LOCKDEP_NOW_UNRELIABLE);
  1368.     
  1369.     /* lve claims to be GPL but upstream won't provide source */
  1370.     if (strcmp(mod->name, "lve") == 0)
  1371.         add_taint_module(mod, TAINT_PROPRIETARY_MODULE,LOCKDEP_NOW_UNRELIABLE);
  1372.     
  1373. #ifdef CONFIG_MODVERSIONS
  1374.     if ((mod->num_syms && !mod->crcs)|| (mod->num_gpl_syms && !mod->gpl_crcs)
  1375.         || (mod->num_gpl_future_syms && !mod->gpl_future_crcs)
  1376.     #ifdef CONFIG_UNUSED_SYMBOLS
  1377.         || (mod->num_unused_syms && !mod->unused_crcs)
  1378.         || (mod->num_unused_gpl_syms && !mod->unused_gpl_crcs)
  1379.     #endif
  1380.         ) {
  1381.             return try_to_force_load(mod,"no versions for exported symbols");
  1382.         }
  1383. #endif
  1384.     return 0;
  1385. }

  1386. static struct module_attribute *modinfo_attrs[] = {
  1387.     &module_uevent,
  1388.     &modinfo_version,
  1389.     &modinfo_srcversion,
  1390.     &modinfo_initstate,
  1391.     &modinfo_coresize,
  1392.     &modinfo_initsize,
  1393.     &modinfo_taint,
  1394. #ifdef CONFIG_MODULE_UNLOAD
  1395.     &modinfo_refcnt,
  1396. #endif
  1397.     NULL,
  1398. };

  1399. static void setup_modinfo(struct module *mod, struct load_info *info)
  1400. {
  1401.     struct module_attribute *attr;
  1402.     int i;
  1403.      
  1404.     for (= 0; (attr = modinfo_attrs[i]); i++) {
  1405.         if (attr->setup)
  1406.             attr->setup(mod, get_modinfo(info, attr->attr.name));
  1407.     }
  1408. }

  1409. static int simplify_symbols(struct module *mod, const struct load_info *info) 
  1410. { 
  1411.     Elf_Shdr *symsec = &info->sechdrs[info->index.sym]; 
  1412.     Elf_Sym *sym = (void *)symsec->sh_addr; 
  1413.     unsigned long secbase; 
  1414.     unsigned int i; 
  1415.     int ret = 0; 
  1416.     const struct kernel_symbol *ksym; 
  1417.     
  1418.     //遍历模块所有符号
  1419.     for (= 1; i < symsec->sh_size / sizeof(Elf_Sym); i++) { 
  1420.     const char *name = info->strtab + sym[i].st_name; 
  1421.         
  1422.         //不同符号类型必须进行不同的处理。
  1423.     switch (sym[i].st_shndx) { 
  1424.         case SHN_COMMON://标注了一个尚未分配的公共块符号
  1425.         DEBUGP("Common symbol: %s\n", name); 
  1426.         printk("%s: please compile with -fno-common\n", mod->name); 
  1427.         ret = -ENOEXEC; 
  1428.         break; 
  1429.         
  1430.         case SHN_ABS://完全定义的符号是最容易的,因为什么也不需要做。
  1431.         DEBUGP("Absolute symbol: 0x%08lx\n", (long)sym[i].st_value); 
  1432.         break; 
  1433.         
  1434.         case SHN_UNDEF://未定义的符号,会进行crc检查
  1435.             //会调用check_version检查crc值是否一致,若一致返回内核中的同名符号
  1436.         ksym = resolve_symbol_wait(mod, info, name);

  1437.                 //如果符号已经解决(crc一致),则没有问题,将内核中的符号地址赋给模块中的符号地址
  1438.         if (ksym && !IS_ERR(ksym)) { 
  1439.             sym[i].st_value = ksym->value;//使用内核中的符号值
  1440.             break; 
  1441.         } 

  1442.                 //如果符号定义为弱的,也没有问题
  1443.         if (!ksym && ELF_ST_BIND(sym[i].st_info) == STB_WEAK) 
  1444.             break; 

  1445.         printk(KERN_WARNING "%s: Unknown symbol %s (err %li)\n", mod->name, name, PTR_ERR(ksym)); 
  1446.         ret = PTR_ERR(ksym) ?: -ENOENT; 
  1447.         break; 

  1448.             //解决其他符号时(符号通过st_shndx成员指向固定的节区),根据节区新的起始地址
  1449.         default: 
  1450.         if (sym[i].st_shndx == info->index.pcpu) 
  1451.             secbase = (unsigned long)mod_percpu(mod); 
  1452.         else
  1453.             secbase = info->sechdrs[sym[i].st_shndx].sh_addr; 
  1454.         //根据符号所在节区的起始地址更改符号地址
  1455.         sym[i].st_value += secbase;
  1456.         break; 
  1457.     } 
  1458.     } 
  1459.     return ret; 
  1460. }

  1461. static const struct kernel_symbol *resolve_symbol_wait(struct module *mod,const struct load_info *info, const char *name)
  1462. {
  1463.     const struct kernel_symbol *ksym;
  1464.     char owner[MODULE_NAME_LEN];
  1465.     
  1466.     //调用resolve_symbol()函数
  1467.     if (wait_event_interruptible_timeout(module_wq,!IS_ERR(ksym = resolve_symbol(mod, info, name, owner))|| PTR_ERR(ksym) != -EBUSY,30 * HZ) <=0) {
  1468.         printk(KERN_WARNING "%s: gave up waiting for init of module %s.\n",mod->name, owner);
  1469.     }
  1470.     return ksym;
  1471. }

  1472. static const struct kernel_symbol *resolve_symbol(struct module *mod,const struct load_info *info,const char *name,char ownername[])
  1473. {
  1474.     struct module *owner;
  1475.     const struct kernel_symbol *sym;
  1476.     const unsigned long *crc;
  1477.     int err;
  1478.     mutex_lock(&module_mutex);
  1479.     
  1480.     //从内核中查找符号名为name的符号,并返回该符号的crc值
  1481.     sym = find_symbol(name, &owner, &crc,!(mod->taints & (<< TAINT_PROPRIETARY_MODULE)), true);
  1482.     if (!sym)
  1483.         goto unlock;
  1484.     
  1485.     //检查该内核中的符号和模块中此未定义的符号的crc值是否一致
  1486.     if (!check_version(info->sechdrs, info->index.vers, name, mod, crc,owner)) {
  1487.         sym = ERR_PTR(-EINVAL);
  1488.         goto getname;
  1489.     }
  1490.     
  1491.     //更新模块的依赖关系,即修正模块的source_list和target_list链表
  1492.     err = ref_module(mod, owner);
  1493.     if (err) {
  1494.         sym = ERR_PTR(err);
  1495.         goto getname;
  1496.     }
  1497.     
  1498. getname:
  1499.     strncpy(ownername, module_name(owner), MODULE_NAME_LEN);
  1500.     
  1501. unlock:
  1502.     mutex_unlock(&module_mutex);
  1503.     return sym;
  1504. }

  1505. static int apply_relocations(struct module *mod, const struct load_info *info)
  1506. {
  1507.   unsigned int i;
  1508.   int err = 0;
  1509.   
  1510.   //遍历所有的节区
  1511.   for (= 1; i < info->hdr->e_shnum; i++) {
  1512.       //对于重定位节区来说,其sh_info指向重定位所适用的节区的节区头部索引
  1513.       //.rel.text节区对应.text节区
  1514.     unsigned int infosec = info->sechdrs[i].sh_info;
  1515.     
  1516.     //如果当前节区附加的节区的索引大于节区的数目,则info不是一个有效的索引,不做处理。
  1517.     if (infosec >= info->hdr->e_shnum)
  1518.         continue;
  1519.     
  1520.     //如果节区在执行过程中不占内存,则 不需要进行处理。 
  1521.     if (!(info->sechdrs[infosec].sh_flags & SHF_ALLOC))
  1522.         continue;
  1523.     
  1524.     //此节区包含重定位表项,其中没有补齐,进行符号重定位,则调用apply_relocate来处理
  1525.     if (info->sechdrs[i].sh_type == SHT_REL)
  1526.         err = apply_relocate(info->sechdrs, info->strtab,info->index.sym, i, mod);
  1527.     //此节区包含重定位表项,其中有补齐,进行符号重定位,则调用apply_relocate_add来处理
  1528.     else if (info->sechdrs[i].sh_type == SHT_RELA)
  1529.         err = apply_relocate_add(info->sechdrs, info->strtab,info->index.sym, i, mod);
  1530.     if (err < 0)
  1531.         break;
  1532.   }
  1533.   return err;
  1534. }

  1535. int apply_relocate(Elf32_Shdr *sechdrs,const char *strtab,unsigned int symindex,unsigned int relsec,struct module *me)
  1536. {
  1537.     //sechdrs表示节区头部表起始地址,strtab表示字符串节区的内容,symindex表示符号节区在节区头部表的索引值,relsec表示重定位节区的索引值(例如:.rel.text节区),该节区的内容是重定位结构的表项
  1538.     unsigned int i;
  1539.     //找到重定位节区中的重定位表项起始地址
  1540.     Elf32_Rel *rel = (void *)sechdrs[relsec].sh_addr;
  1541.     Elf32_Sym *sym;
  1542.     uint32_t *location;
  1543.     
  1544.     DEBUGP("Applying relocate section %u to %u\n",relsec, sechdrs[relsec].sh_info);
  1545.     
  1546.     //遍历重定位节区中的重定位表项
  1547.     for (= 0; i < sechdrs[relsec].sh_size / sizeof(*rel); i++) {
  1548.         //r_offset指定在此节区的区间r_offset处需要重新填写这个符号(.r_info指定)的绝对地址。找到重定位的位置,重定位节区relsec的sh_info表示重定位所适用的节区的节区头部索引值
  1549.       //.rel.text节区对应.text节区
  1550.         location = (void *)sechdrs[sechdrs[relsec].sh_info].sh_addr+ rel[i].r_offset;
  1551.         //找到重定位的符号,ELF32_R_SYM(rel[i].r_info)表示这个符号在在符号表节区的内容中的索引值
  1552.         sym = (Elf32_Sym *)sechdrs[symindex].sh_addr+ ELF32_R_SYM(rel[i].r_info);
  1553.         
  1554.         //sym->st_value是符号的绝对地址
  1555.         switch (ELF32_R_TYPE(rel[i].r_info)) {//重定位类型
  1556.             case R_386_32://绝对地址修正
  1557.             //在要被修正地址处loc,把该地址下的值加上符号的绝对地址,等于这个位置处的取值就是符号地址了,一般来说*location初始值是0,加上符号绝对地址就能在此位置处找到符号地址了
  1558.             *location += sym->st_value;
  1559.             break;
  1560.             case R_386_PC32://相对地址修正
  1561.             /* Add the value, subtract its position */
  1562.             *location += sym->st_value - (uint32_t)location;
  1563.             break;
  1564.             default:
  1565.             pr_err("%s: Unknown relocation: %u\n",me->name, ELF32_R_TYPE(rel[i].r_info));
  1566.             return -ENOEXEC;
  1567.         }
  1568.     }
  1569.     return 0;
  1570. }

  1571. static int post_relocation(struct module *mod, const struct load_info *info)
  1572. {
  1573.     //对模块的异常表进行排序
  1574.     sort_extable(mod->extable, mod->extable + mod->num_exentries);
  1575.     
  1576.     //因为mod对象已经复制到了内核中的最终位置,拷贝模块的percpu数据到mod对象的内存地址处。
  1577.     percpu_modcopy(mod, (void *)info->sechdrs[info->index.pcpu].sh_addr,info->sechdrs[info->index.pcpu].sh_size);
  1578.      
  1579.     //初始化module对象中中字符串表、符号表相关的成员,初始化core部分中的字符串表和符号表
  1580.     add_kallsyms(mod, info);
  1581.     
  1582.     /* Arch-specific module finalizing. */
  1583.     return module_finalize(info->hdr, info->sechdrs, mod);//x86是空函数
  1584. }

  1585. static void add_kallsyms(struct module *mod, const struct load_info *info)
  1586. {
  1587.     unsigned int i, ndst;
  1588.     const Elf_Sym *src;
  1589.     Elf_Sym *dst;
  1590.     char *s;
  1591.     Elf_Shdr *symsec = &info->sechdrs[info->index.sym];//符号表节区
  1592.     
  1593.     //符号表节区开始地址
  1594.     mod->symtab = (void *)symsec->sh_addr;
  1595.     //符号表项个数
  1596.     mod->num_symtab = symsec->sh_size / sizeof(Elf_Sym);
  1597.     //找到字符串节区
  1598.     mod->strtab = (void *)info->sechdrs[info->index.str].sh_addr;
  1599.      
  1600.     //遍历符号表节区中的符号表项,获取符号的属性(STB_LOCAL,STB_GLOBAL...)
  1601.     for (= 0; i < mod->num_symtab; i++)
  1602.         mod->symtab[i].st_info = elf_type(&mod->symtab[i], info);
  1603.     
  1604.     //将core部分存储符号项的偏移地址info->symoffs加上core部分的起始地址得到存储符号项的地址。将符号表项的地址付给core_symtab成员,符号名称起始地址付给core_strtab成员
  1605.     mod->core_symtab = dst = mod->module_core + info->symoffs;
  1606.     mod->core_strtab = s = mod->module_core + info->stroffs;
  1607.     src = mod->symtab;//符号表节区开始地址
  1608.     
  1609.     //将符号表节区的符号项(若干的Elf_Sym结构)内容拷贝到core部分指定地址处
  1610.     //将符号项中符号的名称拷贝到core部分指定地址处,并重新设置符号项中名称在符号字符串中的索引值st_name
  1611.     for (ndst = i = 0; i < mod->num_symtab; i++) {
  1612.         if (== 0 || is_core_symbol(src+i, info->sechdrs, info->hdr->e_shnum)) {
  1613.             //符号项拷贝到mod->module_core + info->symoffs
  1614.             dst[ndst] = src[i];
  1615.             //重新设置符号名在mod->core_strtab中的索引值
  1616.             dst[ndst++].st_name = s - mod->core_strtab;
  1617.             //符号名称拷贝到mod->module_core + info->stroffs
  1618.             s += strlcpy(s, &mod->strtab[src[i].st_name],KSYM_NAME_LEN) + 1;
  1619.         }
  1620.     }
  1621.     mod->core_num_syms = ndst;//符号个数
  1622. }

  1623. static int complete_formation(struct module *mod, struct load_info *info)
  1624. {
  1625.     int err;
  1626.      
  1627.     mutex_lock(&module_mutex);
  1628.      
  1629.     //确认是否有重定义符号
  1630.     err = verify_export_symbols(mod);
  1631.     if (err < 0)
  1632.         goto out;
  1633.     
  1634.     //模块bug相关操作
  1635.     module_bug_finalize(info->hdr, info->sechdrs, mod);
  1636.      
  1637.     //设置模块的状态
  1638.     mod->state = MODULE_STATE_COMING;     
  1639. out:
  1640.     mutex_unlock(&module_mutex);
  1641.     return err;
  1642. }

  1643. static int verify_export_symbols(struct module *mod)
  1644. {
  1645.     unsigned int i;
  1646.     struct module *owner;
  1647.     const struct kernel_symbol *s;
  1648.     struct {
  1649.         const struct kernel_symbol *sym;
  1650.         unsigned int num;
  1651.     } arr[] = {
  1652.         { mod->syms, mod->num_syms },
  1653.         { mod->gpl_syms, mod->num_gpl_syms },
  1654.         { mod->gpl_future_syms, mod->num_gpl_future_syms },
  1655. #ifdef CONFIG_UNUSED_SYMBOLS
  1656.         { mod->unused_syms, mod->num_unused_syms },
  1657.         { mod->unused_gpl_syms, mod->num_unused_gpl_syms },
  1658. #endif
  1659.     };
  1660.      
  1661.     //遍历模块中的符号,在内核中检查是否已经导出,若已经导出该符号,则给出著名error:“exports duplicate symbol”
  1662.     for (= 0; i < ARRAY_SIZE(arr); i++) {
  1663.         for (= arr[i].sym; s < arr[i].sym + arr[i].num; s++) {
  1664.             if (find_symbol(s->name, &owner, NULL, true, false)) {
  1665.                 printk(KERN_ERR "%s: exports duplicate symbol %s"" (owned by %s)\n",mod->name, s->name, module_name(owner));
  1666.             return -ENOEXEC;
  1667.             }
  1668.         }
  1669.     }
  1670.     return 0;
  1671. }

  1672. static int do_init_module(struct module *mod)
  1673. {
  1674.   int ret = 0;

  1675.   current->flags &= ~PF_USED_ASYNC;
  1676.     
  1677.     //内核通知
  1678.   blocking_notifier_call_chain(&module_notify_list,MODULE_STATE_COMING, mod);
  1679.   
  1680.   //Set RO and NX regions for core
  1681.   set_section_ro_nx(mod->module_core,mod->core_text_size,mod->core_ro_size,mod->core_size);
  1682.   
  1683.   //Set RO and NX regions for init 
  1684.   set_section_ro_nx(mod->module_init,mod->init_text_size,mod->init_ro_size,mod->init_size);
  1685.   
  1686.   //调用模块构造函数
  1687.   do_mod_ctors(mod);
  1688.   
  1689.   //启动模块
  1690.   if (mod->init != NULL)
  1691.       ret = do_one_initcall(mod->init);
  1692.       
  1693.   if (ret < 0) {
  1694.       /* Init routine failed: abort. Try to protect us from buggy refcounters. */
  1695.       mod->state = MODULE_STATE_GOING;
  1696.       synchronize_sched();
  1697.       module_put(mod);
  1698.       blocking_notifier_call_chain(&module_notify_list,MODULE_STATE_GOING, mod);
  1699.       free_module(mod);
  1700.       wake_up_all(&module_wq);
  1701.       return ret;
  1702.   }
  1703.   if (ret > 0) {
  1704.       printk(KERN_WARNING"%s: '%s'->init suspiciously returned %d, it should follow 0/-E convention\n""%s: loading module anyway...\n",__func__,mod->name, ret,__func__);
  1705.       dump_stack();
  1706.   }
  1707.  
  1708.  //模块初始化完成,更改状态,通知内核
  1709.   mod->state = MODULE_STATE_LIVE;
  1710.   blocking_notifier_call_chain(&module_notify_list,MODULE_STATE_LIVE, mod);

  1711.   if (current->flags & PF_USED_ASYNC)
  1712.       async_synchronize_full();
  1713.   mutex_lock(&module_mutex);
  1714.   /* Drop initial reference. */
  1715.   module_put(mod);
  1716.   rim_init_extable(mod);
  1717. #ifdef CONFIG_KALLSYMS
  1718.   mod->num_symtab = mod->core_num_syms;
  1719.   mod->symtab = mod->core_symtab;
  1720.   mod->strtab = mod->core_strtab;
  1721. #endif
  1722.     //释放初始化部分空间,这部分只是在初始化有效,初始化结束回收资源,清空
  1723.   unset_module_init_ro_nx(mod);
  1724.   module_free(mod, mod->module_init);
  1725.   mod->module_init = NULL;
  1726.   mod->init_size = 0;
  1727.   mod->init_ro_size = 0;
  1728.   mod->init_text_size = 0;
  1729.   mutex_unlock(&module_mutex);
  1730.   wake_up_all(&module_wq);
  1731.   return 0;
  1732. }

  1733. int __init_or_module do_one_initcall(initcall_t fn)
  1734. {
  1735.     int count = preempt_count();
  1736.     int ret;
  1737.     char msgbuf[64];
  1738.     
  1739.     if (initcall_debug)
  1740.         ret = do_one_initcall_debug(fn);
  1741.     else
  1742.         ret = fn();//执行模块的init_module函数
  1743.      
  1744.     msgbuf[0] = 0;
  1745.      
  1746.     if (preempt_count() != count) {
  1747.         sprintf(msgbuf, "preemption imbalance ");
  1748.         preempt_count() = count;
  1749.     }
  1750.     
  1751.     if (irqs_disabled()) {
  1752.         strlcat(msgbuf, "disabled interrupts ", sizeof(msgbuf));
  1753.         local_irq_enable();
  1754.     }
  1755.     WARN(msgbuf[0], "initcall %pF returned with %s\n", fn, msgbuf);
  1756.      
  1757.     return ret;
  1758. }
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值