- Local Shared Objects — Флеш куки
- Shared libraries with GCC on Linux
- Step 1: Compiling with Position Independent Code
- Step 2: Creating a shared library from an object file
- Step 3: Linking with a shared library
- Telling GCC where to find the shared library
- Step 4: Making the library available at runtime
- Using LD_LIBRARY_PATH
- Using rpath
- rpath vs. LD_LIBRARY_PATH
- Using ldconfig to modify ld.so
- C: создание и применение shared library в Linux
- Создание библиотеки
Local Shared Objects — Флеш куки
Вступления
Приветствую жителей хабры!
Часто бывает случаи, где нас обязывают сохранять данные над которыми работает пользователь во Flash (очки игры, оформления рабочей области и т.д.).
Многие думают что нужно создавать мост между PHP и Flash. В некоторых случаях это нужно делать, для того чтобы хранить долгое время в сети данные о тех или иных действиях пользователя. Но иногда требуется на стороне клиента сохранить данные, которые предназначены только для определения того, какую функцию пользователь выбрал и в зависимости от этого предоставить ему нужную информацию. Мы сегодня рассмотрим сохранения данных на компьютере, а именно Local Shared Object (далее LSO), что в народе иногда звется флеш куки.
Немного о технологии
Local Shared Objects — обычно называемый Flash cookie, это тип данных, хранящихся в виде файла на компьютере пользователя. На данный момент все версии Flash Player используют LSO.
Обычно с настройками по-умолчанию, Flash запрашивает у пользователя разрешения о хранении локальных файлов на компьютере. Уверен многие это видели, так что некоторые из читателей уже понимают о чем я здесь пишу. Как и с обычными cookie, онлайн банки, рекламодатели или торговцы могут использовать LSO для целей учета и контроля. Flash cookie не могут быть использованы третьими лицами на других сайтах. К примеру, LSO от сайта “www.site.ru” не могут быть прочитаны сайтом “www.site.com”.
Если пользователь избавляется от cookie сайта, то уникальный ID-cookie будет присвоен новому файлу, используя данные Flash в качестве “резервного копирования”.
Пользователь может отказаться от хранения LSO используя глобальные настройки параметров хранения в Setting Manager на официальном сайте Adobe.
Хранения LSO на компьютере
Расположения файлов LSO по-умолчанию, обычно зависит от операционной системы. LSO хранятся на компьютере под форматом “.SOL”.
Windows 7:
AppData/Roaming/Macromedia/#SharedObjects/
/ Library / Preferences / Macromedia / Flash Player / # SharedObjects
От теории к практике
Я подготовил небольшой пример на ActionScript3, для того чтобы вы могли увидеть, как работать с LSO в “реальных условиях”.
Мой пример являет собой сцену на которой расположены:
- две кнопки с именами butt и butt1 ;
- полe ввода с именем texts ;
- палитра цветов — pal ;
- текстовое поле — label ;
- а также MovieClip — fon .
Кнопки служат нам для того, чтобы очищать и заносить данные в переменные, а также сохранять их в cookie.
Поле ввода используются для того, чтобы пользователь мог ввести данные, которые хочет занести в переменную, а с помощью палитры цветов выбрать цвет фона нашей сцены.
import fl. events . ColorPickerEvent ;
import flash. geom . ColorTransform ;
import flash. events . MouseEvent ;
var Save: SharedObject ;
Save = SharedObject . getLocal ( «application-name» ) ;
label. text = «Строка: ‘» + Save. data . save1 + «‘» ;
pal. selectedColor = Save. data . save2 ;
var color :ColorTransform = fon. transform . colorTransform ;
fon. addEventListener ( ColorPickerEvent. CHANGE , col ) ;
butt. addEventListener ( MouseEvent. CLICK , ok ) ;
butt1. addEventListener ( MouseEvent. CLICK , ex ) ;
function ok ( e :MouseEvent ) : void
<
Save. data . save1 = «Вы вернулись » + texts. text ;
label. text = «Привет » +texts. text ;
>
function ex ( e :MouseEvent ) : void
<
delete Save. data . save1 ;
label. text = «Exit» ;
>
function col ( e :ColorPickerEvent ) : void
<
Save. data . save2 = color . color = pal. selectedColor ;
fon. transform . colorTransform = color ;
>
Вывод
Вот и подошли мы к концу нашего эксперимента и теперь можем смело сказать, что не стоит боятся такой штуковины как Local Shared Objects.
После проделанной работы, я сразу зашел в папку где хранятся cookie. Свой же я нашел в папочке localhost, а в нем файл application-name.sol.
Открыв его увидел следующие:
ї QTCSO application-name save2Ѓ save1=Р’С‹ вернулись Ruslan
Комментарий от Emin
Крайне желательно использовать метод flush() для принудительного сохранения. Чтобы не возникало проблем при обращении к данным.
До 100 КБ Flash не запрашивает разрешение о хранении. Если больше 100 КБ, то тогда появляется запрос.
Всем спасибо за то что прочитали мою статью!
Источник
Shared libraries with GCC on Linux
Libraries are an indispensable tool for any programmer. They are pre-existing code that is compiled and ready for you to use. They often provide generic functionality, like linked lists or binary trees that can hold any data, or specific functionality like an interface to a database server such as MySQL.
Most larger software projects will contain several components, some of which you may find use for later on in some other project, or that you just want to separate out for organizational purposes. When you have a reusable or logically distinct set of functions, it is helpful to build a library from it so that you do not have to copy the source code into your current project and recompile it all the time — and so you can keep different modules of your program disjoint and change one without affecting others. Once it is been written and tested, you can safely reuse it over and over again, saving the time and hassle of building it into your project every time.
Building static libraries is fairly simple, and since we rarely get questions on them, I will not cover them. I will stick with shared libraries, which seem to be more confusing for most people.
Before we get started, it might help to get a quick rundown of everything that happens from source code to running program:
- C Preprocessor: This stage processes all the preprocessor directives. Basically, any line that starts with a #, such as #define and #include.
- Compilation Proper: Once the source file has been preprocessed, the result is then compiled. Since many people refer to the entire build process as compilation, this stage is often referred to as compilation proper. This stage turns a .c file into an .o (object) file.
- Linking: Here is where all of the object files and any libraries are linked together to make your final program. Note that for static libraries, the actual library is placed in your final program, while for shared libraries, only a reference to the library is placed inside. Now you have a complete program that is ready to run. You launch it from the shell, and the program is handed off to the loader.
- Loading: This stage happens when your program starts up. Your program is scanned for references to shared libraries. Any references found are resolved and the libraries are mapped into your program.
Steps 3 and 4 are where the magic (and confusion) happens with shared libraries.
Now, on to our (very simple) example.
foo.h defines the interface to our library, a single function, foo(). foo.c contains the implementation of that function, and main.c is a driver program that uses our library.
For the purposes of this example, everything will happen in /home/username/foo
Step 1: Compiling with Position Independent Code
We need to compile our library source code into position-independent code (PIC): 1
Step 2: Creating a shared library from an object file
Now we need to actually turn this object file into a shared library. We will call it libfoo.so:
Step 3: Linking with a shared library
As you can see, that was actually pretty easy. We have a shared library. Let us compile our main.c and link it with libfoo. We will call our final program test. Note that the -lfoo option is not looking for foo.o, but libfoo.so. GCC assumes that all libraries start with lib and end with .so or .a (.so is for shared object or shared libraries, and .a is for archive, or statically linked libraries).
Telling GCC where to find the shared library
Uh-oh! The linker does not know where to find libfoo. GCC has a list of places it looks by default, but our directory is not in that list. 2 We need to tell GCC where to find libfoo.so. We will do that with the -L option. In this example, we will use the current directory, /home/username/foo:
Step 4: Making the library available at runtime
Good, no errors. Now let us run our program:
Oh no! The loader cannot find the shared library. 3 We did not install it in a standard location, so we need to give the loader a little help. We have a couple of options: we can use the environment variable LD_LIBRARY_PATH for this, or rpath. Let us take a look first at LD_LIBRARY_PATH:
Using LD_LIBRARY_PATH
There is nothing in there. Let us fix that by prepending our working directory to the existing LD_LIBRARY_PATH:
What happened? Our directory is in LD_LIBRARY_PATH, but we did not export it. In Linux, if you do not export the changes to an environment variable, they will not be inherited by the child processes. The loader and our test program did not inherit the changes we made. Thankfully, the fix is easy:
Good, it worked! LD_LIBRARY_PATH is great for quick tests and for systems on which you do not have admin privileges. As a downside, however, exporting the LD_LIBRARY_PATH variable means it may cause problems with other programs you run that also rely on LD_LIBRARY_PATH if you do not reset it to its previous state when you are done.
Using rpath
Now let s try rpath (first we will clear LD_LIBRARY_PATH to ensure it is rpath that is finding our library). Rpath, or the run path, is a way of embedding the location of shared libraries in the executable itself, instead of relying on default locations or environment variables. We do this during the linking stage. Notice the lengthy “-Wl,-rpath=/home/username/foo” option. The -Wl portion sends comma-separated options to the linker, so we tell it to send the -rpath option to the linker with our working directory.
Excellent, it worked. The rpath method is great because each program gets to list its shared library locations independently, so there are no issues with different programs looking in the wrong paths like there were for LD_LIBRARY_PATH.
rpath vs. LD_LIBRARY_PATH
There are a few downsides to rpath, however. First, it requires that shared libraries be installed in a fixed location so that all users of your program will have access to those libraries in those locations. That means less flexibility in system configuration. Second, if that library refers to a NFS mount or other network drive, you may experience undesirable delays — or worse — on program startup.
Using ldconfig to modify ld.so
What if we want to install our library so everybody on the system can use it? For that, you will need admin privileges. You will need this for two reasons: first, to put the library in a standard location, probably /usr/lib or /usr/local/lib, which normal users do not have write access to. Second, you will need to modify the ld.so config file and cache. As root, do the following:
Now the file is in a standard location, with correct permissions, readable by everybody. We need to tell the loader it is available for use, so let us update the cache:
That should create a link to our shared library and update the cache so it is available for immediate use. Let us double check:
Now our library is installed. Before we test it, we have to clean up a few things:
Clear our LD_LIBRARY_PATH once more, just in case:
Re-link our executable. Notice we do not need the -L option since our library is stored in a default location and we are not using the rpath option:
Let us make sure we are using the /usr/lib instance of our library using ldd:
Good, now let us run it:
That about wraps it up. We have covered how to build a shared library, how to link with it, and how to resolve the most common loader issues with shared libraries — as well as the positives and negatives of different approaches.
- It looks in the DT_RPATH section of the executable, unless there is a DT_RUNPATH section.
- It looks in LD_LIBRARY_PATH. This is skipped if the executable is setuid/setgid for security reasons.
- It looks in the DT_RUNPATH section of the executable unless the setuid/setgid bits are set (for security reasons).
- It looks in the cache file /etc/ld/so/cache (disabled with the -z nodeflib linker option).
- It looks in the default directories /lib then /usr/lib (disabled with the -z nodeflib linker option).
What is position independent code? PIC is code that works no matter where in memory it is placed. Because several different programs can all use one instance of your shared library, the library cannot store things at fixed addresses, since the location of that library in memory will vary from program to program. ↩
GCC first searches for libraries in /usr/local/lib, then in /usr/lib. Following that, it searches for libraries in the directories specified by the -L parameter, in the order specified on the command line. ↩
Источник
C: создание и применение shared library в Linux
Библиотека — это файл, содержащий скопилированный код из нескольких объектных файлов в один файл библиотеки, который может содержать функции используемые другими программами.
Библиотеки могут быть статичными (static) и динамическими или разделяемыми (dynamic, shared).
Ниже — краткий пример создания и применения shared library на C в Linux.
Доступ к общей библиотеке может осуществляться по нескольким именам:
- имя, используемое «линкером» /usr/bin/ld (linker name), в виде слова lib + имя библиотеки + расширение .so , например — libpthread.so
- Полное имя (fully qualified name или soname), в виде lib + name + .so + версия (например — libpthread.so.1 )
- реальное имя — полное имя файла, содержащего версию библиотеки, в виде lib + имя + .so + версия + минорная версия и опционально — версия релиза (например — libpthread.so.1.1 )
Версия для общей бибилиотеки меняется в случае, когда изменения в коде этой бибилиотеки делают её несовместимой с предыдущими версиями, например — если из библиотеки была убрана какая-то функция ( libpthread.so.1 )
Минорная версия меняется, если изменения не затронули совметимость библиотеки, например — какой-то фикс в одной из функций. В таком случае версия останется прежней, а изменится только минорная часть ( libpthread.so.1.1 ).
Такое соглашение об именах версий библиотек позволяет существование разных версий одной библиотеки в одной системе.
Программа, которая будет линковаться с этой бибилиотекой, не будет привязана к определённому файлу с последней версией библиотеки. Вместо этого, после установки последней версии — все связанные программы будут использовать её.
Создание библиотеки
Создадим простой файл libhello.c с одной функцией:
Создаём заголовочный файл библиотеки libhello.h с прототипом функции:
Приступаем к сборке библиотеки.
Создаём объектный файл, указав опцию PIC (Position Independent Code), Warning ( -Wall — warning all), -g для добавления дебаг-информации и -c — что бы создать только файл библиотеки, без вызова линкера:
Проверяем — теперь у нас имеется объектный файл .o :
Источник