符號鏈接也是一種文件,只不過其內容是另一個文件的路徑名。對於符號鏈接的處理,要注意避免死循環的產生,如一個符號鏈接指向其本身。符號鏈接可能包含了符號鏈接,因此內核采用遞歸的方式來處理這個問題,為了避免符號鏈接的死循環而導致無窮遞歸,內核采用link_count和total_link_count來跟蹤符號鏈接的處理,其中前者表示連續的符號鏈接數,後者表示總共的符號鏈接數,兩者都不能超過各自的限制,否則內核會放棄解析。
相關閱讀: http://www.linuxidc.com/search.aspx?where=nkey&keyword=3305
- staticinlineint do_follow_link(struct path *path, struct nameidata *nd)
- {
- int err = -ELOOP;
- /*如果處理的鏈接數超過下面的限制則會放棄搜索(因為有可能陷入死循環)*/
- /*link_count表示連續的符號鏈接數,其值不能超過8,total_link_count表示總共的
- 鏈接數,氣值不能超過40*/
- if (current->link_count >= MAX_NESTED_LINKS)
- goto loop;
- if (current->total_link_count >= 40)
- goto loop;
- BUG_ON(nd->depth >= MAX_NESTED_LINKS);
- cond_resched();
- err = security_inode_follow_link(path->dentry, nd);
- if (err)
- goto loop;
- /*每處理一次符號鏈接,link_count,total_link_count和depth都要加1*/
- current->link_count++;
- current->total_link_count++;//
- nd->depth++;
- /*主要是調用特定於文件系統的follow_link函數進行符號鏈接的跟蹤*/
- err = __do_follow_link(path, nd);
- /*每執行完一次符號鏈接,link_count和depth都要減1*/
- current->link_count--;
- nd->depth--;
- return err;
- loop:
- path_put_conditional(path, nd);
- path_put(&nd->path);
- return err;
- }
- static __always_inline int __do_follow_link(struct path *path, struct nameidata *nd)
- {
- int error;
- void *cookie;
- struct dentry *dentry = path->dentry;
- touch_atime(path->mnt, dentry);
- nd_set_link(nd, NULL);//在saved_names中清除當前解析的符號鏈接路徑
- if (path->mnt != nd->path.mnt) {
- path_to_nameidata(path, nd);
- dget(dentry);
- }
- mntget(path->mnt);
- /*調用特定於文件系統的follow_link方法來跟蹤符號鏈接,並將符號鏈接中保存的路徑名提取出來
- 存放在nd的saved_names中*/
- cookie = dentry->d_inode->i_op->follow_link(dentry, nd);
- error = PTR_ERR(cookie);
- if (!IS_ERR(cookie)) {
- char *s = nd_get_link(nd);//提取saved_names中的路徑
- error = 0;
- if (s)//路徑存在,則繼續解析,__vfs_follow_link將會調用link_path_walk,因此對於
- //路徑中存在多個符號鏈接的情況,這是一個遞歸的過程
- error = __vfs_follow_link(nd, s);
- if (dentry->d_inode->i_op->put_link)
- dentry->d_inode->i_op->put_link(dentry, nd, cookie);
- }
- path_put(path);
- return error;
- }
- static __always_inline int __vfs_follow_link(struct nameidata *nd, constchar *link)
- {
- int res = 0;
- char *name;
- if (IS_ERR(link))
- goto fail;
- if (*link == '/') {
- set_root(nd);
- path_put(&nd->path);
- nd->path = nd->root;
- path_get(&nd->root);
- }
- res = link_path_walk(link, nd);
- if (nd->depth || res || nd->last_type!=LAST_NORM)
- return res;
- /*
- * If it is an iterative symlinks resolution in open_namei() we
- * have to copy the last component. And all that crap because of
- * bloody create() on broken symlinks. Furrfu...
- */
- name = __getname();
- if (unlikely(!name)) {
- path_put(&nd->path);
- return -ENOMEM;
- }
- strcpy(name, nd->last.name);
- nd->last.name = name;
- return 0;
- fail:
- path_put(&nd->path);
- return PTR_ERR(link);
- }