Jump to content

Nytro

Administrators
  • Posts

    18578
  • Joined

  • Last visited

  • Days Won

    642

Everything posted by Nytro

  1. 1. Introduction A question which frequently arises among Unix C++ programmers is how to load C++ functions and classes dynamically using the dlopen API. In fact, that is not always simple and needs some explanation. That's what this mini HOWTO does. An average understanding of the C and C++ programming language and of the dlopen API is necessary to understand this document. This HOWTO's master location is C++ dlopen mini HOWTO. 1.1. Copyright and License This document, C++ dlopen mini HOWTO, is copyrighted © 2002 by Aaron Isotton. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.1 or any later version published by the Free Software Foundation; with no Invariant Sections, with no Front-Cover Texts, and with no Back-Cover Texts. 1.2. Disclaimer No liability for the contents of this document can be accepted. Use the concepts, examples and information at your own risk. There may be errors and inaccuracies, that could be damaging to your system. Proceed with caution, and although this is highly unlikely, the author(s) do not take any responsibility. All copyrights are held by their by their respective owners, unless specifically noted otherwise. Use of a term in this document should not be regarded as affecting the validity of any trademark or service mark. Naming of particular products or brands should not be seen as endorsements. 1.3. Credits / Contributors In this document, I have the pleasure of acknowledging (in alphabetic order): Joy Y Goodreau <joyg (at) us.ibm.com> for her editing. D. Stimitis <stimitis (at) idcomm.com> for pointing out a few issues with the formatting and the name mangling, as well as pointing out a few subtleties of extern "C". 1.4. Feedback Feedback is most certainly welcome for this document. Send your additions, comments and criticisms to the following email address: <aaron@isotton.com>. 1.5. Terms Used in this Document dlopen API The dlclose, dlerror, dlopen and dlsym functions as described in the dlopen(3) man page. Notice that we use "dlopen" to refer to the individual dlopen function, and "dlopen API" to refer to the entire API. 2. The Problem At some time you might have to load a library (and use its functions) at runtime; this happens most often when you are writing some kind of plug-in or module architecture for your program. In the C language, loading a library is very simple (calling dlopen, dlsym and dlclose is enough), with C++ this is a bit more complicated. The difficulties of loading a C++ library dynamically are partially due to name mangling, and partially due to the fact that the dlopen API was written with C in mind, thus not offering a suitable way to load classes. Before explaining how to load libraries in C++, let's better analyze the problem by looking at name mangling in more detail. I recommend you read the explanation of name mangling, even if you're not interested in it because it will help you understanding why problems occur and how to solve them. 2.1. Name Mangling In every C++ program (or library, or object file), all non-static functions are represented in the binary file as symbols. These symbols are special text strings that uniquely identify a function in the program, library, or object file. In C, the symbol name is the same as the function name: the symbol of strcpy will be strcpy, and so on. This is possible because in C no two non-static functions can have the same name. Because C++ allows overloading (different functions with the same name but different arguments) and has many features C does not — like classes, member functions, exception specifications — it is not possible to simply use the function name as the symbol name. To solve that, C++ uses so-called name mangling, which transforms the function name and all the necessary information (like the number and size of the arguments) into some weird-looking string which only the compiler knows about. The mangled name of foo might look like foo@4%6^, for example. Or it might not even contain the word "foo". One of the problems with name mangling is that the C++ standard (currently [iSO14882]) does not define how names have to be mangled; thus every compiler mangles names in its own way. Some compilers even change their name mangling algorithm between different versions (notably g++ 2.x and 3.x). Even if you worked out how your particular compiler mangles names (and would thus be able to load functions via dlsym), this would most probably work with your compiler only, and might already be broken with the next version. 2.2. Classes Another problem with the dlopen API is the fact that it only supports loading functions. But in C++ a library often exposes a class which you would like to use in your program. Obviously, to use that class you need to create an instance of it, but that cannot be easily done. 3. The Solution 3.1. extern "C" C++ has a special keyword to declare a function with C bindings: extern "C". A function declared as extern "C" uses the function name as symbol name, just as a C function. For that reason, only non-member functions can be declared as extern "C", and they cannot be overloaded. Although there are severe limitations, extern "C" functions are very useful because they can be dynamically loaded using dlopen just like a C function. This does not mean that functions qualified as extern "C" cannot contain C++ code. Such a function is a full-featured C++ function which can use C++ features and take any type of argument. 3.2. Loading Functions In C++ functions are loaded just like in C, with dlsym. The functions you want to load must be qualified as extern "C" to avoid the symbol name being mangled. Example 1. Loading a Function main.cpp: #include <iostream> #include <dlfcn.h> int main() { using std::cout; using std::cerr; cout << "C++ dlopen demo\n\n"; // open the library cout << "Opening hello.so...\n"; void* handle = dlopen("./hello.so", RTLD_LAZY); if (!handle) { cerr << "Cannot open library: " << dlerror() << '\n'; return 1; } // load the symbol cout << "Loading symbol hello...\n"; typedef void (*hello_t)(); hello_t hello = (hello_t) dlsym(handle, "hello"); if (!hello) { cerr << "Cannot load symbol 'hello': " << dlerror() << '\n'; dlclose(handle); return 1; } // use it to do the calculation cout << "Calling hello...\n"; hello(); // close the library cout << "Closing library...\n"; dlclose(handle); } hello.cpp: #include <iostream> extern "C" void hello() { std::cout << "hello" << '\n'; } The function hello is defined in hello.cppas extern "C"; it is loaded in main.cpp with the dlsym call. The function must be qualified as extern "C" because otherwise we wouldn't know its symbol name. Warning There are two different forms of the extern "C" declaration: extern "C" as used above, and extern "C" { … } with the declarations between the braces. The first (inline) form is a declaration with extern linkage and with C language linkage; the second only affects language linkage. The following two declarations are thus equivalent: extern "C" int foo; extern "C" void bar(); and extern "C" { extern int foo; extern void bar(); } As there is no difference between an extern and a non-extern function declaration, this is no problem as long as you are not declaring any variables. If you declare variables, keep in mind that extern "C" int foo; and extern "C" { int foo; } are not the same thing. For further clarifications, refer to [iSO14882], 7.5, with special attention to paragraph 7, or to [sTR2000], paragraph 9.2.4. Before doing fancy things with extern variables, peruse the documents listed in the see also section. 3.3. Loading Classes Loading classes is a bit more difficult because we need an instance of a class, not just a pointer to a function. We cannot create the instance of the class using new because the class is not defined in the executable, and because (under some circumstances) we don't even know its name. The solution is achieved through polymorphism. We define a base, interface class with virtual members in the executable, and a derived, implementation class in the module. Generally the interface class is abstract (a class is abstract if it has pure virtual functions). As dynamic loading of classes is generally used for plug-ins — which must expose a clearly defined interface — we would have had to define an interface and derived implementation classes anyway. Next, while still in the module, we define two additional helper functions, known as class factory functions. One of these functions creates an instance of the class and returns a pointer to it. The other function takes a pointer to a class created by the factory and destroys it. These two functions are qualified as extern "C". To use the class from the module, load the two factory functions using dlsym just as we loaded the the hello function; then, we can create and destroy as many instances as we wish. Example 2. Loading a Class Here we use a generic polygon class as interface and the derived class triangle as implementation. main.cpp: #include "polygon.hpp" #include <iostream> #include <dlfcn.h> int main() { using std::cout; using std::cerr; // load the triangle library void* triangle = dlopen("./triangle.so", RTLD_LAZY); if (!triangle) { cerr << "Cannot load library: " << dlerror() << '\n'; return 1; } // load the symbols create_t* create_triangle = (create_t*) dlsym(triangle, "create"); destroy_t* destroy_triangle = (destroy_t*) dlsym(triangle, "destroy"); if (!create_triangle || !destroy_triangle) { cerr << "Cannot load symbols: " << dlerror() << '\n'; return 1; } // create an instance of the class polygon* poly = create_triangle(); // use the class poly->set_side_length(7); cout << "The area is: " << poly->area() << '\n'; // destroy the class destroy_triangle(poly); // unload the triangle library dlclose(triangle); } polygon.hpp: #ifndef POLYGON_HPP #define POLYGON_HPP class polygon { protected: double side_length_; public: polygon() : side_length_(0) {} void set_side_length(double side_length) { side_length_ = side_length; } virtual double area() const = 0; }; // the types of the class factories typedef polygon* create_t(); typedef void destroy_t(polygon*); #endif triangle.cpp: #include "polygon.hpp" #include <cmath> class triangle : public polygon { public: virtual double area() const { return side_length_ * side_length_ * sqrt(3) / 2; } }; // the class factories extern "C" polygon* create() { return new triangle; } extern "C" void destroy(polygon* p) { delete p; } There are a few things to note when loading classes: * You must provide both a creation and a destruction function; you must not destroy the instances using delete from inside the executable, but always pass it back to the module. This is due to the fact that in C++ the operators new and delete may be overloaded; this would cause a non-matching new and delete to be called, which could cause anything from nothing to memory leaks and segmentation faults. The same is true if different standard libraries are used to link the module and the executable. * The destructor of the interface class should be virtual in any case. There might be very rare cases where that would not be necessary, but it is not worth the risk, because the additional overhead can generally be ignored. If your base class needs no destructor, define an empty (and virtual) one anyway; otherwise you will have problems sooner or later; I can guarantee you that. You can read more about this problem in the comp.lang.c++ FAQ at C++ FAQ LITE, in section 20. 4. Frequently Asked Questions 4.1. I'm using Windows and I can't find the dlfcn.h header file on my PC! What's the problem? The problem is, as usual, Windows. There is no dlfcn.h header on Windows,and there is no dlopen API. There is a similar API around the LoadLibrary function, and most of what is written here applies to it, too. Refer to the Win32 Platform SDK documentation or have a look at MSDN. 4.2. Is there some kind of dlopen-compatible wrapper for the Windows LoadLibrary API? I don't know, and honestly I don't care. If you know of something, feel free mailing me and I'll eventually put it here. 5. See Also The dlopen(3) man page. It explains the purpose and the use of the dlopen API. The article Dynamic Class Loading for C++ on Linux by James Norton published on the Linux Journal. Your favorite C++ reference about extern "C", inheritance, virtual functions, new and delete. I recommend [sTR2000]. [iSO14882] The Program Library HOWTO, which tells you most things you'll ever need about static, shared and dynamically loaded libraries and how to create them. Highly recommended. The Linux GCC HOWTO to learn more about how to create libraries with GCC. Bibliography ISO14482 ISO/IEC 14482-1998 — The C++ Programming Language. Available as PDF and as printed book from American National Standards Institute - ANSI Standards Store. STR2000 Bjarne Stroustrup The C++ Programming Language, Special Edition. ISBN 0-201-70073-5. Addison-Wesley.
  2. Revista Chip pe mai-iunie 2009 - Linux Download: http://www.netdrive.ws/239572.html
  3. ISO/IEC 14882 - Programming languages - C++ ( 09.01.1998 ) Download: http://www.ishiboo.com/~danny/c++/C++STANDARD-ISOIEC14882-1998.pdf
  4. Loading and unloading shared libraries can be tricky sometimes. The biggest problem is when you use the g++ compiler (as opposed to the gcc compiler) it mangles the symbols in the object file so you can't load them later. Here's a "Hello World!" dynamic library in C++ example for your enjoyment. First, create the library file, called dynamic.cp #include <cstdio> extern "C" void _init(); extern "C" void hello(void); extern "C" void _fini(); void _init() { printf("Initialization Phase"); } void hello(void) { printf("Hello, Dynamic World!"); } void _fini() { printf("Deconstruction Phase"); } The _init() and _fini() functions will be called automagically when you load or unload the dynamic module. You can compile this on the command line (we'll create a Makefile in a minute): g++ -fPIC -c dynamic.cpp ld -shared -o dynamic.so dynamic.o We first compile the function with g++ first because if we just do the whole thing together it automatically adds tons of other symbols you just don't need, not to mention not allowing you to put your own _init() and _fini() functions in. If you're curious, go ahead and try to compile it with the command g++ -fPIC -shared -o dynamic.so dynamic.cpp—it probably won't work! Next, we need a program to test it with, and in a fit of creative genius I called it main.cpp: #include <cstdio> #include <cstdlib> #include <dlfcn.h> int main() { void *handle; void (*hello)(void); char *error; handle = dlopen("/path/to/my/dynamic.so", RTLD_LAZY); if(handle == NULL) { fprintf(stderr, "Error: open/load error of dynamic.so failed: %s\n", dlerror()); exit(1); } hello = (void(*)(void)) dlsym(handle, "hello"); if((error = dlerror()) != NULL) { fprintf(stderr, "Error: symbol lookup in dynamic.so failed: %s\n", dlerror()); exit(2); } hello(); dlclose(handle); return 0; } Now all we need is a good Makefile: # Makefile for dynamic module loading APP = test CC = g++ LD = ld all: $(APP) dynamic.o: dynamic.cpp $(CC) -fPIC -c dynamic.cpp dynamic.so: dynamic.o $(LD) -shared -o dynamic.so dynamic.o $(APP): dynamic.so main.cpp $(CC) -o $(APP) main.cpp -ldl clean: @rm -f *.o *.so $(APP) I realize I don't explain a lot of this code, but it's not too complicated, so it should be pretty easy to understand if you are familiar with C or C++. Run-Time Linking of Shared Libraries It's been some time since I updated this page, but I thought I'd mention the run-time linking of shared libraries option. If you create a shared library as above, and install it somewhere in your /etc/ld.so.conf path, you can compile and link to the library at run-time. This means you don't have to bother with the dlopenand dlclose functions, but the shared library must be available at compile time. First, create your library a little differently: ld -shared -o libdynamic.so.1.0 dynamic.o Then copy it to a nice place like /usr/local/lib and create some symlinks: cp libdynamic.so.1.0 /usr/local/lib ln -s /usr/local/lib/libdynamic.so.1.0 /usr/local/lib/libdynamic.so.1 ln -s /usr/local/lib/libdynamic.so.1.0 /usr/local/lib/libdynamic.so The first ln command makes this whole business work with the run-time linker, the second makes the syntax -ldynamic work. Make sure you run ldconfig as root after you install a new library! Now when you compile, just add the -ldynamic to your link command and you'll be ready to go! Autor: Scurvy Jake Va recomand sa cititi acest tutorial ( cei care veti scrie programe pentru Linux )
  5. Download: http://www.netdrive.ws/239544.html
  6. Nytro

    subtitrare film

    Cauutati pe Google: "titrare nume_film", eu am gasit cam la toate...
  7. Nytro

    WorldIT.info

    Unul dintre putinele bloguri pe care intru, felicitari
  8. Mutat la Stuff Tools. Nu trebuia acordul nimanui ca sa postezi.
  9. Pe scurt: _|_ A, ma poti da in judecata desigur: Art. 1337 din legea forumurilor: "Nu se arata muie pe forum, se pedepseste cu o amenda grasa". Sper ca nu ai mai mult de 20 de ani, ar fi pacat ca cineva mai in varsta sa vina cu asemenea prostii... O zi buna
  10. Asteptam... Sa nu se vi se rupa buzunarele de atatia bani.
  11. De unde stim ca nu sunteti dumneavoastra CancerL, cel care a postat articolul? Ei bine nu stim, deci vom concluziona ca dumneavoastra ati postat articolul.
  12. Exista LILO si GRUB. Mai usor
  13. Pe scurt: pornografie, manele, muzica de fapt... Nu rezolvi nimic cu CS.
  14. Urmatoarea versiune de Office va fi si gratuita de Catalin Calciu | 12 octombrie 2009 Surprinzator din partea companiei Microsoft iata ca ei au anuntat ca urmatoarea versiune de Office, 2010, va avea inclusiv o versiune freeware, al carei cost va fi acoperit de clasicele deja reclame. Office 2010 Starter Edition va avea versiuni de Word si de Excel mail imitate, si reclamele vor rula in “tab-urile” aplicatiei, este destinata sa vina mai degraba preinstalate pe noi calculatoare decat ca produse autonome si bineinteles ca va contine optiunea de upgrade la o versiune superioara de Office. Ca si celelalte versiuni, Office 2010 Starter va aparea pe piata in prima jumatate a anului viitor si va inlocui actualele “Microsoft Works” ce vin preinstalate pe multe PC-uri actuale. Bineinteles ca aceasta miscare a Microsoft vine sa intampine si sa concureze versiuni freeware de office, precum suita “Open Office” sau "Google Docs" sau produsele de la Apple, care au acces la o versiune de office denumita “iWorks”ce se comercializeaza cu 79 de dolari americani.
  15. Patch urias de la Microsoft de Alex Hanea | 12 octombrie 2009 Microsoft lanseaza marti cel mai mare patch de pana acum. Pachetul include 13 rezolvari pentru 34 de vulnerabilitati din mai multe produse ale companieie, printre care Office, SQL Server, Internet Explorer. Opt dintre ele sunt critice, doua vulnerabilitati fiind deja exploatate. Patchul asteptat saptamana aceasta atrage atentia asupra riscurilor existente. Vulnerabilitatile carora li se adreseaza expun intregul sistem, serviciile cheie si cateva aplicatii importante pentru utilizatori. Unul dintre aspectele tratate de acest patch se refera la un "drive-by malware", pe care utilizatorii il descarca de multe ori fara a cunoaste consecintele. Cu siguranta insa amploarea acestui patch va da batai de cap utilizatorilor. In plus, cele mai mlte vulnerabilitati sunt etichetate ca si coduri de executie si vor necesita restartarea calculatorului. Se pare ca toamna ii pune pe ganduri pe cei de la Microsoft, tinand cont ca anteriorul pach gigantic a fost in octombrie 2008, la aproape un an dupa cel din 2007 din noiembrie.
  16. Windows 8 va avea varianta 128-bit de Mina Hutterer | 10 octombrie 2009 Mai sunt inca aproape doua saptamani pana la lansarea lui Windows 7, in variante 32 si 64-bit, dar iata ca progresul nu sta in loc. Exista deja posibilitatea ca Windows 8 sa fie lansat in 2012, dar, mai mult decat atat, se pare ca vom avea si prima varianta pe 128 de biti. Eightforums a descoperit ca, in profilul de pe LinkedIn al unui angajat Microsoft Senior Research & Development, Robert Morgan, scria ca "lucreaza pentru a face ca IA-128 sa aiba backwards full binary compatibility cu instructiunile IA-64 existente in simulari hardware, pentru functionare sub Windows 8 si cu siguranta sub Windows 9." Informatia nu este o surpriza totala, deoarece este previzibil ca multi dintre utilizatorii Windows 7 vor adopta versiunea pe 64 de biti. Interesant este ca exista planuri pentru software pe 128 de biti pentru generatia imediat urmatoare. Va vom tine la curent pe masura ce noi detalii despre acest "salt tehnologic" devin disponibile.
  17. Windows 7 mai lent decat Windows Vista de Vlad Matei | 9 octombrie 2009 Odata cu aparitia ultimului sistem de operare Windows 7, reprezentantii Microsoft declarau ca toate problemele blamate la precedentul sistem de operare vor disparea, una dintre cele mai mari fiind constituita de timpii foarte mari de incarcare pentru a deveni utilizabil. Daca pana acum, toate indiciile veneau sa confirme spusele companiei Microsoft iata ca un mic producator de software denumit "Iolo" a testat timp de 3 luni sistemul de operare Windows 7 si a ajuns la niste concluzii destul de ingrijoratoare: la utilizare in viata reala el este chiar mai lent decat Vista, desi el intra in modul de desktop mai repede decat el, pana la a deveni complet utilizabil i-a luat nu mai putin de un minut si 34 de secunde, fata de 1 minut si 6 secunde in cazul Vista. Deocamdata nu sunt oferite detalii complete despre testarea facuta de cei de la Iolo, insa acestia au declarat ca in urmatoarele saptamani vor fi oferite toate informatiile adunate in urma testelor.
  18. Nytro

    Desene Animate

    http://www.anime4f.com/2007/08/dragonball-z-episodes.html
  19. Nytro

    Salut!

    Bine ai venit Iryder. Pacat ca trebuie sa inchid topicul.
  20. blueangelmnx: Ban permanent - 3 avertismente.
  21. Florin Salam - Nu mai dau bani la dusmani
  22. Nytro

    Salut!

    Wow ce 1337 sunteti scriind binar sau cu hash-uri md5...
  23. Deschideti cu Notepad si uitati-va prin el...
  24. Nytro

    ./nasa.gov/proof

    Fi nebun. Fi rau cu orice site 'neromanesc'.
×
×
  • Create New...