dlsym RTLD_DEFAULT和RTLD_NEXT

https://blog.csdn.net/ustcxiangchun/article/details/6310085
https://linux.die.net/man/3/dlsym
http://man7.org/linux/man-pages/man3/dlsym.3.html

dlsym()

函數dlsym()接受dlopen()返回的動態庫的“句柄” 和以空字符結尾的符號名稱,返回將該符號加載到內存中的地址。如果未找到該符號,則在指定的庫中,或在加載該庫時由dlopen()自動加載的任何 庫中,dlsym()返回NULL。(由dlsym()執行的搜索首先遍歷這些庫的依賴關係樹。)由於該符號的值實際上可以爲NULL(因此從dlsym()返回的NULL 不必表示錯誤),因此採用正確的方法測試錯誤是調用dlerror()清除任何舊的錯誤條件,然後調用dlsym(),然後再次調用dlerror(),將其返回值保存到變量中,並檢查此保存的值是否不爲NULL。
有兩個特殊的僞句柄,RTLD_DEFAULT和RTLD_NEXT。前者將使用默認的庫搜索順序找到所需符號的第一個匹配項。後者將在當前庫之後的搜索順序中找到功能的下一個出現。這樣一來,用戶就可以在另一個共享庫中爲函數提供包裝。

 

今天看alsa-lib的代碼,發現一個場景是會調到

dlsym(RTLD_DEFAULT, name);

也就是說,handle=RTLD_DEFAULT,在網上查了下,這種情況下會發生的事情是,會在當前進程中按照 default library search order搜索name這個symbol,網上的介紹摘錄如下:

 

http://www.qnx.de/developers/docs/6.4.0/neutrino/lib_ref/d/dlsym.html?lang=cn

If handle is a handle returned by dlopen(), you must not have closed that shared object by calling dlclose(). The dlsym() functions also searches for the named symbol in the objects loaded as part of the dependencies for that object.

 

If handle is RTLD_DEFAULT, dlsym() searches all objects in the current process, in load-order.

 

In the case of RTLD_DEFAULT, if the objects being searched were loaded with dlopen(), dlsym() searches the object only if the caller is part of the same dependency hierarchy, or if the object was loaded with global search access (using the RTLD_GLOBAL mode).

 

http://www.linux.com/learn/docs/man/2818-dlsym3

dlsym()
The function dlsym() takes a "handle" of a dynamic library returned by dlopen() and the null-terminated symbol name, returning the address where that symbol is loaded into memory. If the symbol is not found, in the specified library or any of the libraries that were automatically loaded by dlopen() when that library was loaded, dlsym() returns NULL. (The search performed by dlsym() is breadth first through the dependency tree of these libraries.) Since the value of the symbol could actually be NULL (so that a NULL return from dlsym() need not indicate an error), the correct way to test for an error is to call dlerror() to clear any old error conditions, then call dlsym(), and then call dlerror() again, saving its return value into a variable, and check whether this saved value is not NULL.

There are two special pseudo-handles, RTLD_DEFAULT and RTLD_NEXT. The former will find the first occurrence of the desired symbol using the default library search order. The latter will find the next occurrence of a function in the search order after the current library. This allows one to provide a wrapper around a function in another shared library.  
 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章