Nick Desaulniers
The enemy’s gate is down
Static and Dynamic Libraries
Nov 20 th , 2016 | Comments
This is the second post in a series on memory segmentation. It covers working with static and dynamic libraries in Linux and OSX. Make sure to check out the first on object files and symbols.
Let’s say we wanted to reuse some of the code from our previous project in our next one. We could continue to copy around object files, but let’s say we have a bunch and it’s hard to keep track of all of them. Let’s combine multiple object files into an archive or static library. Similar to a more conventional zip file or “compressed archive,” our static library will be an uncompressed archive.
We can use the ar command to create and manipulate a static archive.
The -r flag will create the archive named libhello.a and add the files x.o and y.o to its index. I like to add the -v flag for verbose output. Then we can use the familiar nm tool I introduced in the previous post to examine the content of the archives and their symbols.
Some other useful flags for ar are -d to delete an object file, ex. ar -d libhello.a y.o and -u to update existing members of the archive when their source and object files are updated. Not only can we run nm on our archive, otool and objdump both work.
Now that we have our static library, we can statically link it to our program and see the resulting symbols. The .a suffix is typical on both OSX and Linux for archive files.
Our compiler understands how to index into archive files and pull out the functions it needs to combine into the final executable. If we use a static library to statically link all functions required, we can have one binary with no dependencies. This can make deployment of binaries simple, but also greatly increase their size. Upgrading large binaries incrementally becomes more costly in terms of space.
While static libraries allowed us to reuse source code, static linkage does not allow us to reuse memory for executable code between different processes. I really want to put off talking about memory benefits until the next post, but know that the solution to this problem lies in “dynamic libraries.”
While having a single binary file keeps things simple, it can really hamper memory sharing and incremental relinking. For example, if you have multiple executables that are all built with the same static library, unless your OS is really smart about copy-on-write page sharing, then you’re likely loading multiple copies of the same exact code into memory! What a waste! Also, when you want to rebuild or update your binary, you spend time performing relocation again and again with static libraries. What if we could set aside object files that we could share amongst multiple instances of the same or even different processes, and perform relocation at runtime?
The solution is known as dynamic libraries. If static libraries and static linkage were Atari controllers, dynamic libraries and dynamic linkage are Steel Battalion controllers. We’ll show how to work with them in the rest of this post, but I’ll prove how memory is saved in a later post.
Let’s say we want to created a shared version of libhello. Dynamic libraries typically have different suffixes per OS since each OS has it’s preferred object file format. On Linux the .so suffix is common, .dylib on OSX, and .dll on Windows.
The -shared flag tells the linker to create a special file called a shared library. The -fpic option converts absolute addresses to relative addresses, which allows for different processes to load the library at different virtual addresses and share memory.
Now that we have our shared library, let’s dynamically link it into our executable.
The dynamic linker essential produces an incomplete binary. You can verify with nm . At runtime, we’ll delay start up to perform some memory mapping early on in the process start (performed by the dynamic linker) and pay slight costs for trampolining into position independent code.
Let’s say we want to know what dynamic libraries a binary is using. You can either query the executable (most executable object file formats contain a header the dynamic linker will parse and pull in libs) or observe the executable while running it. Because each major OS has its own object file format, they each have their own tools for these two checks. Note that statically linked libraries won’t show up here, since their object code has already been linked in and thus we’re not able to differentiate between object code that came from our first party code vs third party static libraries.
On OSX, we can use otool -L to check which .dylibs will get pulled in.
So we can see that a.out depends on libhello.dylib (and expects to find it in the same directory as a.out ). It also depends on shared library called libSystem.B.dylib. If you run otool -L on libSystem itself, you’ll see it depends on a bunch of other libraries including a C runtime, malloc implementation, pthreads implementation, and more. Let’s say you want to find the final resting place of where a symbol is defined, without digging with nm and otool , you can fire up your trusty debugger and ask it.
You’ll see a lot of output since puts is treated as a regex. You’re looking for the Summary line that has an address and is not a symbol stub. You can then check your work with otool and nm .
If we want to observe the dynamic linker in action on OSX, we can use dtruss :
On Linux, we can simply use ldd or readelf -d to query an executable for a list of its dynamic libraries.
We can then use strace to observe the dynamic linker in action on Linux:
What’s this LD_LIBRARY_PATH thing? That’s shell syntax for setting an environmental variable just for the duration of that command (as opposed to exporting it so it stays set for multiple commands). As opposed to OSX’s dynamic linker, which was happy to look in the cwd for libhello.dylib, on Linux we must supply the cwd if the dynamic library we want to link in is not in the standard search path.
But what is the standard search path? Well, there’s another environmental variable we can set to see this, LD_DEBUG . For example, on OSX:
LD_DEBUG is pretty useful. Try:
For some cool stuff, I recommend checking out LD_DEBUG=symbols and LD_DEBUG=statistics .
Going back to LD_LIBRARY_PATH , usually libraries you create and want to reuse between projects go into /usr/local/lib and the headers into /usr/local/include. I think of the convention as:
Unfortunately, it’s a loose convention that’s broken down over the years and things are scattered all over the place. You can also run into dependency and versioning issues, that I don’t want to get into here, by placing libraries here instead of keeping them in-tree or out-of-tree of the source code of a project. Just know when you see a library like libc.so.6 that the numeric suffix is a major version number that follows semantic versioning. For more information, you should read Michael Kerrisk’s excellent book The Linux Programming Interface. This post is based on his chapter’s 41 & 42 (but with more info on tooling and OSX).
If we were to place our libhello.so into /usr/local/lib (on Linux you need to then run sudo ldconfig ) and move x.h and y.h to /usr/local/include, then we could then compile with:
Note that rather than give a full path to our library, we can use the -l flag followed by the name of our library with the lib prefix and .so suffix removed.
When working with shared libraries and external code, three flags I use pretty often:
For finding specific flags needed for compilation where dynamic linkage is required, a tool called pkg-config can be used for finding appropriate flags. I’ve had less than stellar experiences with the tool as it puts the onus on the library author to maintain the .pc files, and the user to have them installed in the right place that pkg-config looks. When they do exist and are installed properly, the tool works well:
Using another neat environmental variable, we can hook into the dynamic linkage process and inject our own shared libraries to be linked instead of the expected libraries. Let’s say libgood.so and libmalicous.so both define a symbol for a function (the same symbol name and function signature). We can get a binary that links in libgood.so’s function to instead call libmalicous.so’s version:
LD_PRELOAD is not available on OSX, instead you can use DYLD_INSERT_LIBRARIES , DYLD_LIBRARY_PATH , and recompile the original executable with -flat_namespace . Having to recompile the original executable is less than ideal for hooking an existing binary, but I could not hook libc as in the previous libmalicious example. I would be interested to know if you can though!
Manually invoking the dynamic linker from our code, we can even man in the middle library calls (call our hooked function first, then invoke the original target). We’ll see more of this in the next post on using the dynamic linker.
As you can guess, readjusting the search paths for dynamic libraries is a security concern as it let’s good and bad folks change the expected execution paths. Guarding against the use of these env vars becomes a rabbit hole that gets pretty tricky to solve without the heavy handed use of statically linking dependencies.
In the the previous post, I alluded to undefined symbols like puts . puts is part of libc, which is probably the most shared dynamic library on most computing devices since most every program makes use of the C runtime. (I think of a “runtime” as implicit code that runs in your program that you didn’t necessarily write yourself. Usually a runtime is provided as a library that gets implicitly linked into your executable when you compile.) You can statically link against libc with the -static flag, on Linux at least (OSX makes this difficult, “Apple does not support statically linked binaries on Mac OS X”).
I’m not sure what the benefit would be to mixing static and dynamic linking, but after searching the search paths from LD_DEBUG=libs for shared versions of a library, if any static ones are found, they will get linked in.
There’s also an interesting form of library called a “virtual dynamic shared object” on Linux. I haven’t covered memory mapping yet, but know it exists, is usually hidden for libc, and that you can read more about it via man 7 vdso .
One thing I find interesting and don’t quite understand how to recreate is that somehow glibc on Linux is also executable:
Also, note that linking against third party code has licensing implications (of course) of particular interest when it’s GPL or LGPL. Here is a good overview which I’d summarize as: code that statically links against LGPL code must also be LGPL, while any form of linkage against GPL code must be GPL’d.
Ok, that was a lot. In the previous post, we covered Object Files and Symbols. In this post we covered hacking around with static and dynamic linkage. In the next post, I hope to talk about manually invoking the dynamic linker at runtime.
Источник
Блог радиста
Блог о Linux в частности и Open Source в общем, о программировании и немного о M$ Windows
Статические и динамические библиотеки в Linux
Статические и динамические библиотеки в Linux
Сегодня мы поговорим о библиотеках в Linux (подозреваю также, что многие описанные здесь вещи возможны и в других *nix-операционных системах, но это требует проверки 🙂 ).
1) Статические библиотеки (создание с помощью Assembler, C/C++; подключение и использование в программах на Assembler,C/C++);
2) Динамические библиотеки (создание с помощью Assembler, C/C++; подключение и использование в программах на C/C++l, Python).
1) Статическая библиотека — это такая библиотека, которая связывается (линкуется) с программой в момент компиляции оной. При этом объектный код библиотеки помещается в исполняемый файл программы. С этой точки зрения статическая библиотека похожа на исходный код программы, с которой она связывается, за исключением того, что библиотека компилируется «кем-то еще» и программист, использующий библиотеку, имеет дело исключительно только с результатом этой компиляции.
В Linux, как правило, файл-статическая_библиотека имеет расширение «.a»
2) Статические библиотеки на языке C.
Исходный код библиотеки:
Сохраните его в файле static.c
Ключевое слово extern необходимо для того, чтобы функция была видна в программе.
Теперь скомпилируем (! без линковки) библиотеку:
gcc -c static.c -o static.o
(на выходе имеем файл static.o, содержащий объектный код нашей библиотеки)
ar rc libMY_STATIC.a static.o
ar упаковывает несколько (! Это важно. Дело не ограничивается только одним объектным файлом) объектных файлов в одну статическую библиотеку. Статическая библиотека имеет расширение «.a», при этом ее название должно начинаться с «lib» (дань традиции).
Параметры ar:
r — предписывает заменять старые версии объектных файлов новыми — необходим для переупаковки библиотеки;
c — создать статическую библиотеку, если та еще не существует.
Проиндексируем функции внутри библиотеки для более быстрой линковки:
Итак, мы получили статическую библиотеку libMY_STATIC.a.
Теперь попытаемся использовать библиотеку в нашей программе:
Исходный текст программы (C):
Сохраните его в файле program1.c
Способы связывания библиотеки и программы:
— Скомпилируем и слинкуем (в том числе с нашей библиотекой) нашу программу:
gcc program1.c libMY_STATIC.a
(предполагается, что в качестве аргумента gcc будут переданы полные пути (!) к вашим библиотекам)
На выходе получим:
Hello world! I’m static library
Return code: 0
— Скомпилируйте с помощью команды:
gcc program1.c -L. -lMY_STATIC -o a1.out
— путь к каталогу, содержащему наши библиотек (используйте «-L
— название нашей библиотеки (это важно — название (!), а не имя файла — собственно, если библиотека имеет своим именем «libBLABLABLA.a», то ее названием будет «BLABLABLA» — т.е. имя без приставки «lib» и расширения «.a») (для нескольких библиотек используйте «-l -l . «)
Запустите файл a1.out на выполнение и удостовертесь, что результаты те же, что и в предыдущем пункте.
— Видоизменим предыдущий способ — уберем аргументы «-L»:
В начале проверим значение переменной LD_LIBRARY_PATH и содержимое файла /etc/ld.so.conf:
echo $LD_LIBRARY_PATH ; cat /etc/ld.so.conf
На экране появился некоторый список каталогов — это те каталоги, в которых система ищет библиотеки при их линковке с программой (еще к таким каталогам относятся:
/lib
/usr/lib
. Поместите libMY_STATIC.a в один из этих каталогов:
(Я, к примеру, засуну нашу библиотеку в каталог /usr/lib):
su -c ‘cp libMY_STATIC.a /usr/lib’
(в Ubuntu — sudo cp libMY_STATIC.a /usr/lib )
ldconfig
(ldconfig обновляет кеш данных о библиотеках линковщика)
Теперь скомпилируем и запустим нашу программу:
gcc program1.c -lMY_STATIC -o a2.out
./a2.out
Hello world! I’m static library
Return code: 0
Бинго! Кстати, таким вот способом вы можете подключать к своей программе любые статические библиотеки из приведенных выше каталогов.
* Бывает полезно определить все прототипы функций библиотеки в некотором заголовочном файле, который будет потом включаться в вашу программу. Это не обязательно, но удобно.
3) Статические библиотеки на языке Assembler.
Представьте, что вам необходимо оптимизировать выполнение некоторых действий в вашей программе. Разумеется, вы может применить ключевое слово asm (если пишите программу на C/C++), но лучшим решением будет создание оптимизированной вами библиотеки на языке Assembler и подключение ее к вашей программе. Давайте попробуем:
*Кстати, углубляться в процесс компиляции библиотеки и ее линковки с вашей программой я не буду (!). Этот процесс идентичен полностью (!) тому же процессу для библиотек, написанных на языке C.
Итак, имеем вот такую программу:
Сохраните ее в файле program2.c
Скомпилируйте ее и запустите:
Я привел этот пример, чтобы показать действительно возможность оптимизации программы с помощью библиотеки на Assembler’е. Вы можете заметить, что вызов printf в main() не оптимален, т.к. printf, по крайней мере, один раз использует цикл while для поиска вхождений конструкций «%. » в строку. Это не оптимально, т.к. очевидно, что таковых символов у нас нет. Оптимизируем нашу программу с помощью библиотеки на Assebmler’е:
my_printf:
movl $4,%eax
xorl %ebx,%ebx
incl %ebx
movl $hw,%ecx
movl $hw_e,%edx
int $0x80
xorl %eax,%eax
ret
Сохраните исходный код библиотеки в файле static2.s
Это AT&T наречие Assembler’а.
.globl my_printf — «my_printf» описывается как глобальная (видимая в других объектных файлах) последовательность
my_printf: — начало описание функции my_printf
movl $4,%eax — поместим 4 в eax (4 — номер системного вызова write)
xorl %ebx,%ebx и incl %ebx — поместим в ebx единицу — номер STDOUT
movl $message,%ecx — в ecx запишем адрес начала сообщения
movl $message_l,%edx — в edx поместим адрес конца сообщения
int $0x80 — произведем системный вызов write
xorl %eax,%eax — в eax — код возврата (0)
ret — вернемся в вызывающую процедуру
.data — секция данных (разумеется, мы могли бы передавать выводимую строку как параметр, но тогда вычисление ее конца потребовало бы от нас дополнительных усилий, что, согласитесь, лениво 🙂 )
Теперь получим библиотеку:
gcc -c static2.s -o static2.o
ar rc static2.a static2.o
ranlib static2.a
На выходе имеем статическую библиотеку static2.a
Теперь напишем программу, использующую эту статическую библиотеку (язык C):
Сохраните текст программы в файле program3.c
Заметьте, я добавил прототип библиотечной функции для удобства.
Скомпилируем и слинкуем программу с библиотекой, после чего запустим программу на выполнение:
gcc program3.c static2.a
./a.out
На выходе получим:
* Принцип линкования статических библиотек с программами на Assembler’е аналогичен принципу для программ на C. Просто, когда будете использовать статические библиотеки в Assembler’е, помните о соглашениях C по передаче аргументов в функцию и возвращению результата.
4) Статические библиотеки на языке C++.
Принцип создания аналогичен статическим библиотекам на C, но перед каждой экспортируемой функцией не забывайте добавлять:
(экспортировать как функцию на C — т.е. без расширения имен).
* Кстати, используйте g++ вместо gcc, если захотите протестировать приведенные выше примеры.
Подключение к вашей программе аналогично подключению к программе, написанной на C, за исключением необходимости явно добавлять к тексту программы прототипы импортируемых функций в следующем виде:
extern «C» PROTOTYPE
Где PROTOTYPE — прототип импортируемой функции.
* При подключении статических библиотек на C++ к программе на C сопряжено с некоторыми трудностями — т.к. при компиляции и линковки программы необходимо будет также вручную подключить системные библиотеки для реализации функционала, предоставляемого библиотекой Standart C++ сверх того, что предоставляет библиотека Standart C.
Динамические библиотеки (shared).
1) Динамическая библиотека — библиотека, подключаемая к программе в момент выполнения. Это означает, что при создании библиотеки производится не только ее компиляция, но и линковка с другими, нужными ей, библиотеками (!).
Динамические библиотеки полезны в случаях, если:
— Важно не перекомпилировать всю программу, а только перекомпилировать ту часть, которая реализует определенные функции — тогда эти функции выносятся в динамическую библиотеку;
— Важно использовать в программах на C библиотеки, подготовленные на C++ и при этом избежать лишних трудностей с линковкой программы;
— Кроме того, динамические библиотеки позволяют экономить место на жестком диске и в оперативной памяти, если одна и таже библиотека используется несколькими программами.
В Linux, обычно, динамические библиотеки имеют расширение «.so».
2) Подготовим исходный код динамической библиотеки (пример на C++).
Исходный код динамической библиотеки по принципам создания ничем (!) не отличается от исходного кода статических библиотек.
Здесь мы подготовим некоторый пример, который в дальнейшем будем использовать повсеместно во всей части 2.
Итак, исходный код библиотеки (C++):
extern «C» int hello()
<
cout 3) Компиляция и линковка динамических библиотек.
Давайте получим динамическую библиотеку:
Получим файл с объектным кодом:
g++ -fPIC -c dynamic.cpp -o dynamic.o
(используйте gcc для программ на С и Assembler’е)
-fPIC — использовать относительную адресацию в переходах подпрограмм — во избежание конфликтов при динамическом связывании
А теперь из объектного файла получим библиотеку:
g++ -shared -olibdynamic.so dynamic.o
(используйте gcc для программ на С и Assembler’е)
libdynamic.so — имя результирующей библиотеки;
-shared — предписывает создать динамическую (т.е. «разделяемую») библиотеку.
* Именуйте динамические библиотеки следующим способом:
Итак, на выходе мы имеем libdynamic.so — нашу динамическую библиотеку.
4) Использование динамической библиотеки в программе на C/C++.
— Связывание с библиотекой во время компиляции программы (C/C++):
—— Подготовим исходный код нашей программы:
Сохраните его в файле Dprogram1.c
extern «C» int hello();
Сохраните его в файле Dprogram1.cpp
(единственное отличие, как вы можете заметить, в ключевом слове extern — см. часть 1 пункт 4)
—— Теперь добьемся того, чтобы система смогла найти нашу библиотеку. Поместим libdynamic.so в один из каталогов:
cat /etc/ld.so.conf
и выполните потом » ldconfig «
—— И, наконец, скомпилируем программу и слинкуем ее с библиотекой:
gcc ИСХОДНИК -lИМЯ_БИБЛИОТЕКИ -o РЕЗУЛЬТИРУЮЩИЙ_БИНАРИК
В нашем случае: gcc Dprogram1.c -L/home/amv/c/libs/ -ldynamic
(используйте g++ для программы на C++)
Запустим на исполнение полученный файл:
В итоге должно получится:
— Связывание с библиотекой во время исполнения программы (C/C++):
Разумеется, предыдущий пример неплох. Однако бывает необходимо подключать библиотеку во время выполнения программы. Для этого можно использовать функционал из заголовочного файла .
Исходный код примера (C):
int main()
<
void *handle = dlopen(«libdynamic.so»,RTLD_LAZY);
int(*fun)(void) = dlsym(handle,»hello»);
int x = (*fun)();
dlclose(handle);
printf(«Return code: %d\n»,x);
return 0;
>;
######################
Сохраните его в файле Dprogram2.c
В dlfcn.h определены следующие функции:
void* dlopen(«PATH_AND_NAME»,FLAG) — загружает в память динамическую библиотеку с полным именем PATH_AND_NAME и возвращает ее описатель (HANDLE) (NULL в случае неудачи). FLAG — флаги, описанные в «man dlopen»;
void* dlsym(HANDLE,»NAME») — возвращает указатель на функцию/переменную, импортируемую из библиотеки;
int dlclose(HANDLE) — выгружает библиотеку из памяти;
const char *dlerror() — получить сообщение о последней возникшей ошибке (NULL — если ошибок не произошло с момента последнего вызова dlerror).
* Посмотрите на досуге вот этот перевод «man dlopen»: Привет, OpenNET
gcc -ldl Dprogram2.c
(используйте g++ для программы на C++)
Запустим на исполнение полученный файл:
В итоге должно получится:
* Важно! Нет необходимости помещать библиотеку в один из специальных каталогов, модифицировать переменные окружения и выполнять «ldconfig»
— Использование динамической библиотеки в программе на Python:
Все предельно просто.
—— Поместим libdynamic.so в один из каталогов:
cat /etc/ld.so.conf
и выполните потом «ldconfig»
Исходный текст программы на python’е:
Модуль ctypes входит в стандартную поставку модулей python версии 2.5 и выше.
Фуф. Мы проделали довольно большую работу, но ведь это только верхушка айсберга.
Источник