Sponsored Content
Top Forums UNIX for Advanced & Expert Users Dynamic Downloading and executing of ELF files Post 302385219 by Corona688 on Thursday 7th of January 2010 11:33:09 AM
Old 01-07-2010
You can't just download an ELF file into memory and execute it because an ELF file needs processing to load in the first place. An ELF file has potentially many separate memory segments with different characteristics, not one glob that it just lives in.

Build a shared library, use dlopen, that's what they're there for. Not to mention that how libraries are handled can depend a lot on your architecture and configuration, doing that manually yourself would be very unportable(not to mention reinventing the wheel.)

It handles everything for you, from filename to symbol name in two easy steps. Here's an example:
Code:
// shared.c
// compile like:  gcc shared.c -shared -fPIC -o shared.so
#include <stdio.h>

int library_function(int argc, char *argv[])
{
        fprintf(stderr, "library_function called\n");
        return(0);
}

Code:
// main.c
// compile like:  gcc main.c -ldl -o main
#include <stdio.h>
#include <dlfcn.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main(int argc, char *argv[])
{
        void *h=dlopen("./shared.so", RTLD_NOW);
        int (*fn)(int argc, char *argv[]);
        pid_t pid;

        if(h == NULL)
        {
                fprintf(stderr, "Couldn't open shared.so\n");
                return(1);
        }

        fn=dlsym(h, "library_function");
        if(fn == NULL)
        {
                fprintf(stderr, "Couldn't find library_function\n");
        }

        pid=fork();  // Create new process
        if(pid == 0)    // child code
        {       return(fn(argc, argv));         }
        else // Wait for child process
        {
                int status;
                wait(&status);
                fprintf(stderr, "Child returned %d\n", WEXITSTATUS(status));
        }

        dlclose(h);

        return(0);
}


Last edited by Corona688; 01-07-2010 at 12:39 PM..
 

10 More Discussions You Might Find Interesting

1. HP-UX

dynamic names for .tar.gz files?

Hi All, I have a requirement to zip and compress files with dynamic names (which includes date and time component in their names) needs to be compressed with same name. for example I have a file T.30.SLS_ORD.SO.27.2_2_2.20080623.041415.dat which needs to archived as... (1 Reply)
Discussion started by: srinivas_paluku
1 Replies

2. UNIX for Dummies Questions & Answers

Running elf files

I have a few questions about elf files and how they are executed. When gcc compiles a elf file it creates an executable. Is this executable then run directly by the hardware or does the kernel get involved, interpret the elf file and place the asm code directly in memory. Cheers (0 Replies)
Discussion started by: mshindo
0 Replies

3. Shell Programming and Scripting

Problem in Downloading one day old files from FTP site

HI, I'm downloading one day old files from ftp site. Below is my script ---------------------------- printf "open $HOST \n" > ftp.cmd printf "user $USER $PASSWD\n" >> ftp.cmd printf "bin\n" >> ftp.cmd #printf "cd /Models/\n" >> ftp.cmd printf "prompt\n" >> ftp.cmd printf "for oldfile... (4 Replies)
Discussion started by: shekhar_v4
4 Replies

4. Shell Programming and Scripting

shell script - ftp downloading serveral files without mget

Hello guys, i'm searching for a solution how to download all files from root-directory of an ftp-server through an ftp proxy getting through the ftp proxy and download one file with get ist no problem, but mget * does nothing! ftp -n -i -v <<EOF open proxyHost proxyPort user... (19 Replies)
Discussion started by: macProgger23
19 Replies

5. Shell Programming and Scripting

Help with dynamic configure cfg files

hi; i have one configuration file(configuration.cfg),where contents are below.. filename = charge.cfg sectionname = networkid = 1 retrytimes = 2 ------------- -------------- sectionname = networkid = 1 retrytimes = 2 filename = xyz.cfg ------------------ ----------------- There is... (7 Replies)
Discussion started by: suryanarayan
7 Replies

6. Shell Programming and Scripting

Downloading FTP Files

Hi every one, I have the requirement to download the files from FTP and move those files to unix box. Once after coping the files, i need to remove the files in FTP. I'm a newbie in Unix script. Can you please suggest a script for this.. Thanks in advance.. (2 Replies)
Discussion started by: Murali4u
2 Replies

7. Shell Programming and Scripting

Help Dynamic looping based on files

Hi I have to run the script (a part of the code) in a loop for the no of times the files present in the directory, by taking one file and process and next another file. For example, if we do ls and the result have: $ls abc.dat def.dat ghi.dat The script code should loop for 3... (4 Replies)
Discussion started by: karumudi7
4 Replies

8. Shell Programming and Scripting

downloading mutilple files

hey i have a text file thats filled with info like this $ cat /private/var/lib/apt/lists/idwaneo.org_repo_._Packages Package: org.idwaneo.ldid Priority: optional Section: iDWANEO.org Maintainer: Admin <admin@idwaneo.org> Architecture: iphoneos-arm Version: 610-5 Pre-Depends: dpkg... (1 Reply)
Discussion started by: lewisdenny
1 Replies

9. Shell Programming and Scripting

Comparing 2 text files & downloading a file if the last lines are different

Hello I'm having a little difficulty in writing a shell script for a few simple tasks. First I have two files "file1.txt" and "file2.txt" and I want to read and compare the last line of each file. The files look like this. File1.txt File2.txt After comparing the two lines I would... (2 Replies)
Discussion started by: RustikGaming
2 Replies

10. UNIX for Advanced & Expert Users

Executing if dynamic conditions in awk

Hi All, I got struck at the below point where i am unable to get the desired output after forming the dynamic conditions.Below is the design. 1. We are getting inputs from the shell arguments and storing in a variable like below. CONDITIONS="1=CT,2=US_10,3=CT_US_10" 2. After this i am... (14 Replies)
Discussion started by: cskumar
14 Replies
DLOPEN(3)						     Linux Programmer's Manual							 DLOPEN(3)

NAME
dlclose, dlerror, dlopen, dlsym - Programming interface to dynamic linking loader. SYNOPSIS
#include <dlfcn.h> void *dlopen(const char *filename, int flag); const char *dlerror(void); void *dlsym(void *handle, char *symbol); int dlclose(void *handle); Special symbols: _init, _fini. DESCRIPTION
dlopen loads a dynamic library from the file named by the null terminated string filename and returns an opaque "handle" for the dynamic library. If filename is not an absolute path (i.e., it does not begin with a "/"), then the file is searched for in the following loca- tions: A colon-separated list of directories in the user's LD_LIBRARY_PATH environment variable. The list of libraries cached in /etc/ld.so.cache. /lib, followed by /usr/lib. If filename is a NULL pointer, then the returned handle is for the main program. External references in the library are resolved using the libraries in that library's dependency list and any other libraries previously opened with the RTLD_GLOBAL flag. If the executable was linked with the flag "-rdynamic", then the global symbols in the executable will also be used to resolve references in a dynamically loaded library. flag must be either RTLD_LAZY, meaning resolve undefined symbols as code from the dynamic library is executed, or RTLD_NOW, meaning resolve all undefined symbols before dlopen returns, and fail if this cannot be done. Optionally, RTLD_GLOBAL may be or'ed with flag, in which case the external symbols defined in the library will be made available to subsequently loaded libraries. If the library exports a routine named _init, then that code is executed before dlopen returns. If the same library is loaded twice with dlopen(), the same file handle is returned. The dl library maintains link counts for dynamic file handles, so a dynamic library is not deallocated until dlclose has been called on it as many times as dlopen has succeeded on it. If dlopen fails for any reason, it returns NULL. A human readable string describing the most recent error that occurred from any of the dl routines (dlopen, dlsym or dlclose) can be extracted with dlerror(). dlerror returns NULL if no errors have occurred since initialization or since it was last called. (Calling dlerror() twice consecutively, will always result in the second call returning NULL.) 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. If the symbol is not found, dlsym returns NULL; however, the correct way to test for an error from dlsym is to save the result of dlerror into a variable, and then check if saved value is not NULL. This is because the value of the symbol could actually be NULL. It is also necessary to save the results of dlerror into a variable because if dlerror is called again, it will return 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, which is usable only from within a dynamic library, will find the next occurrence of a func- tion in the search order after the current library. This allows one to provide a wrapper around a function in another shared library. dlclose decrements the reference count on the dynamic library handle handle. If the reference count drops to zero and no other loaded libraries use symbols in it, then the dynamic library is unloaded. If the dynamic library exports a routine named _fini, then that routine is called just before the library is unloaded. RETURN VALUE
dlclose returns 0 on success, and non-zero on error. EXAMPLE
Load the math library, and print the cosine of 2.0: #include <stdio.h> #include <dlfcn.h> int main(int argc, char **argv) { void *handle; double (*cosine)(double); char *error; handle = dlopen ("libm.so", RTLD_LAZY); if (!handle) { fprintf (stderr, "%s ", dlerror()); exit(1); } cosine = dlsym(handle, "cos"); if ((error = dlerror()) != NULL) { fprintf (stderr, "%s ", error); exit(1); } printf ("%f ", (*cosine)(2.0)); dlclose(handle); return 0; } If this program were in a file named "foo.c", you would build the program with the following command: gcc -rdynamic -o foo foo.c -ldl NOTES
The symbols RTLD_DEFAULT and RTLD_NEXT are defined by <dlfcn.h> only when _GNU_SOURCE was defined before including it. ACKNOWLEDGEMENTS
The dlopen interface standard comes from Solaris. The Linux dlopen implementation was primarily written by Eric Youngdale with help from Mitch D'Souza, David Engel, Hongjiu Lu, Andreas Schwab and others. The manual page was written by Adam Richter. SEE ALSO
ld(1), ld.so(8), ldconfig(8), ldd(1), ld.so.info Linux 2001-12-14 DLOPEN(3)
All times are GMT -4. The time now is 01:10 PM.
Unix & Linux Forums Content Copyright 1993-2022. All Rights Reserved.
Privacy Policy