"Linux Kernel Analysis" (vii)--LINUX executable program Analysis __linux

Source: Internet
Author: User

Author: Sandy Original works reproduced please indicate the source
"Linux kernel Analysis" MOOC course http://mooc.study.163.com/course/USTC-1000029000 "
Experimental Environment: c+ Linux64 bit (32-bit system may result in different)
in accordance with the academic integrity of the terms, I guarantee that this answer is my original, all the references to the external materials have been marked by provenance. one, the creation and format of executable files creating 1,linux Executables: preprocessing, compiling, compiling, linking

shiyanlou:~/$ cd Code [9:27:05] shiyanlou:code/$ VI hello.c [9:27:14] shiyanlou:code/$ gcc-e-o hello.cpp hello.c-m32 [9:34:55] Shiy anlou:code/$ VI hello.cpp [9:35:04] shiyanlou:code/$ gcc-x cpp-output-s-O Hell O.s hello.cpp-m32 [9:35:21] shiyanlou:code/$ VI hello.s [9:35:28] Shiyanlo                                          u:code/$ gcc-x assembler-c hello.s-o hello.o-m32 [9:35:58] shiyanlou:code/$ VI hello.o [9:38:44] shiyanlou:code/$ gcc-o Hello hello.o-m32 [9:39:37] Shiyanlou:co de/$ VI Hello [9:39:44] shiyanlou:code/$ gcc-o hello.static hello.o-m32-st atic [9:40:21] shiyanlou:code/$ ls-l [9:41:13]-rwxrwxr-x 1 shi Yanlou Shiyanlou 7292 3\u6708 09:39 hello-rw-rw-r--1 Shiyanlou shiyanlou 3\u6708 09:30 hello.c-rw-rw-r--1 Shiyanlou Shiyanlou 17302 3\u6708 09:35 hello.cpp-rw-rw-r--1 Shiyanlou Shiyanlou 1020 3\u6708 09:38 hello.o-rw-rw-r--1 shiyanl ou shiyanlou 470 3\u6708 09:35 hello.s-rwxrwxr-x 1 Shiyanlou shiyanlou 733254 3\u6708 09:41

The above process can be simply shown in the following figure:

Images from: A deep understanding of computer systems-Chapter One roaming computer systems

The more specific process is:

2, the format of the target file

The contents of the destination file have at least compiled machine instruction code, data. Yes, except for the content
, the target file also includes some information needed for the link, such as the symbol table, debug information, string
Wait
Symbolic grooming standards, variable inner layout, function invocation, etc. these are related to executable code binary compatibility, called ABI (Application Binary Interface). Our common target file (ABI) format:

  The general purpose file stores this information in different properties, in the form of "section", sometimes called "Duan" (Segment).

The following file formats are described separately.

2.1 a.out The format of the destination file

A.out is the executable file format used by the early Unix system, designed by At&t, and the format and header structure shows that the a.out format is very compact, containing only the necessary information (code, data) for the operation of the program, and that the order of each section is fixed, and this structure lacks extensibility, If you cannot include debugging information that is common in the "modern" executable file.

A.out is now largely replaced by the elf format.

2.2 COFF The format of the destination file

2.3 PE destination file format

2.4 ELF target file format

Elf Management information mainly consists of three parts: Elf Head, Program Head (Program section) Table, Section table; The address space of a segment usually includes one or more sections.
such as data section, BSS section, etc.

To view the head of an elf file:

shiyanlou:code/$ readelf-h Hello

Elf format detailed analysis: http://www.xfocus.net/articles/200105/174.html Two, executable environment for executable programs

After you understand the format of the executable file, you can consider the problem of loading the executable file. However, before an executable file is loaded, you need to understand its execution environment.
command line parameters and shell environment, we generally execute a program of shell environment, our experiment directly using EXECVE system call. $ ls-l/usr/bin Listing the directory information under/usr/bin The shell itself does not limit the number of command-line arguments,? The number of command-line arguments is limited to the command itself--for example, int main (int argc, char *argv[])--Also, int main (int argc, char *argv[], char *envp[]) The shell invokes Execve to pass command-line arguments and ambient parameters to the executable program's main function--int execve (const char * filename,char * CONST argv[],CHAR * Const envp[]); --Library function exec* are all EXECVE encapsulation routines

ENVP refers to environment variables, which are usually automatically added by the shell

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main (int argc, char * Argv[])
{
    int pid;
    /* Fork Another process
    /pid = fork ();
    if (pid<0) 
    {/ 
        * error occurred
        /fprintf (stderr, "Fork failed!");
        Exit ( -1);
    } 
    else if (pid==0) 
    {/
        * child   Process   *
        /EXECLP ("/bin/ls", "ls", NULL);
    } 
    else 
    {     /* Parent Process  *
        ////* Parent would wait for the child to complete*/wait
        (NULL); c27/>printf ("Child complete!");
        Exit (0);
    }
}

The direction of delivery is: Shell program->execve->sys_execve
It is then copied to the stack when the new program stack is initialized (see figure below), where the function call parameter is passed, and the system call parameter is passed.

Note: Command line arguments and environment strings are placed in the user state stack

examples of dynamic link and runtime dynamic link applications when loading

The above parameter transfer is just a simple static link, and now the program is generally dynamic link, at this time need to rely on dynamic link library; Dynamic link is divided into dynamic link and run-time dynamic link, the following analysis of these two different ways:

1, prepare the. So file (that is, the. dll file under window)

Shlibexample.h (1.3 KB)-Interface of Shared Lib Example
SHLIBEXAMPLE.C (1.2 KB)-Implement of Shared Lib Example

Source:

/********************************************************************//* Copyright (C) Sse@ustcsz, 2012 * *////////* name:s HLIBEXAMPLE.C * * * PRINCIPAL author:mengning * * * Subsys                                         TEM Name: *///* MODULE NAME:                                    */* LANGUAGE:C           *///* DATE of the RELEASE:2012/5/3/* DESCRIPTION

: Implement of Shared Lib Example *//********************************************************************/ * * Revision LOG: * * Created by MENGNING,2012/5/3 * */#include <stdio.h> #include "shlibexample.h" *
 Shared Lib API Example* Input:none * output:none * return:success (0)/failure ( -1) * * */int Sharedlibapi () {printf ("This is
    A shared libary!\n ");
return SUCCESS;




 }
/********************************************************************//* Copyright (C) Sse@ustcsz, 2012 * *////////* name:s Hlibexample.h * * * PRINCIPAL author:mengning * * * Subsys                                         TEM Name: *///* MODULE NAME:                                    */* LANGUAGE:C           *///* DATE of the RELEASE:2012/5/3/* DESCRIPTION

: Interface of Shared Lib Example *//********************************************************************/ * * Revision LOG: * * Created by MENGNING,2012/5/3 * */#ifndef _sh_lib_example_h_ #define _SH_LIB_EXAMPLE_H_ #def INE SUCCESS 0 #define FAIlure ( -1) #ifdef __cplusplus extern "C" {#endif/* Shared Lib API Example * input:none * Output:none * r


Eturn:success (0)/failure ( -1) * * */int sharedlibapi ();


 #ifdef __cplusplus} #endif #endif/* _sh_lib_example_h_ * *

Compile into libshlibexample.so file

$ gcc-shared Dllibexample.c-o Libdllibexample.so-m32

Dllibexample.h (1.3 KB)-Interface of dynamical Loading Lib Example
DLLIBEXAMPLE.C (1.3 KB)-Implement of dynamical Loading Lib Example

/********************************************************************//* Copyright (C) Sse@ustcsz, 2012 * *////////* NAME:D LLIBEXAMPLE.C * * * PRINCIPAL author:mengning * * * Subsys                                         TEM Name: *///* MODULE NAME:                                    */* LANGUAGE:C           *///* DATE of the RELEASE:2012/5/3/* DESCRIPTION : Implement of Dynamical Loading/* Lib Example// /* * Revision LOG: * * Created by mengning,2012/ 5/3 * * * * * #include;stdio.h> #include "dllibexample.h" #define SUCCESS 0 #define FAILURE ( -1)/* dynamical Loading Lib API Example * Input:none * Output:none * return:success (0)/failure ( -1) * * */int Dynamicalloadinglibapi () {printf (
    "This is a dynamical Loading libary!\n");
return SUCCESS;
 }
/********************************************************************//* Copyright (C) Sse@ustcsz, 2012 * *////////* NAME:D Llibexample.h * * * PRINCIPAL author:mengning * * * Subsys                                         TEM Name: *///* MODULE NAME:                                    */* LANGUAGE:C           *///* DATE of the RELEASE:2012/5/3/* DESCRIPTION : Interface of dynamical Loading/* Lib Example// /* * Revision LOG: * * Created by mengning,2012/ 5/3 * * * * * #ifndef _dl_Lib_example_h_ #define _dl_lib_example_h_ #ifdef __cplusplus extern "C" {#endif/* dynamical Loading LIB API Exampl


E * Input:none * output:none * return:success (0)/failure ( -1) * * */int dynamicalloadinglibapi ();


 #ifdef __cplusplus} #endif #endif/* _dl_lib_example_h_ * *

Compile into libdllibexample.so file

gcc-shared Dllibexample.c-o Libdllibexample.so-m32

Use libshlibexample.so and libdllibexample.so files separately as shared libraries and dynamically loaded shared libraries

MAIN.C (1.9 KB)-Main Program

/********************************************************************//* Copyright (C) Sse@ustcsz, 2012 * *////////* NAME:M AIN.C * * * PRINCIPAL author:mengning * * * Subsys                                         TEM Name: *///* MODULE NAME:                                    */* LANGUAGE:C           *///* DATE of the RELEASE:2012/5/3/* DESCRIPTION

: Main program *//********************************************************************/ * * Revision LOG: * * Created by MENGNING,2012/5/3 * */#include <stdio.h> #include "shlibexample.h" #inc Lude <dlfcn.h>/*
 * Main program * Input:none * output:none * return:success (0)/failure ( -1) */int Main () {printf
    ("This is a Main program!\n");
    /* Use Shared Lib/printf ("Calling Sharedlibapi () function of libshlibexample.so!\n");
    Sharedlibapi ();
    /* Use dynamical Loading Lib/void * handle = Dlopen ("libdllibexample.so", Rtld_now);
        if (handle = = NULL) {printf ("Open Lib libdllibexample.so error:%s\n", Dlerror ());
    return failure;
    Int (*func) (void);
    char * ERROR;
    Func = Dlsym (handle, "Dynamicalloadinglibapi");
        if (Error = Dlerror ())!= NULL) {printf ("Dynamicalloadinglibapi not found:%s\n", error);
    return failure;
    printf ("Calling Dynamicalloadinglibapi () function of libdllibexample.so!\n");  
    Func ();       
    Dlclose (handle);
return SUCCESS;




 }

Compile main, note that only the Shlibexample-L (the directory of the library's corresponding interface header files) and-L (the library name) are provided here. If Libshlibexample.so removes Lib and. So, it does not provide dllibexample information, but only indicates-LDL

$ gcc main.c-o main-l/path/to/your/dir-lshlibexample-ldl-m32
$ export ld_library_path= $PWD #将当前目录加入默认路径, or main can't find To a dependent library file, and of course you can copy the library file to the default path.
$./main
This is a Main program!
Calling Sharedlibapi () function of libshlibexample.so!
This is a shared libary!
Calling Dynamicalloadinglibapi () function of libdllibexample.so!
This is a dynamical Loading libary!

There is no difference between the two kinds of dynamic library implementation files.
The difference is critical on the caller side: main function four, executable loader Shell related

command line parameters and shell environment, we generally execute a program of shell environment, our experiment directly using EXECVE system call. $ ls-l/usr/bin Listing the directory information under/usr/bin The shell itself does not limit the number of command-line arguments,? The number of command-line arguments is limited to the command itself--for example, int main (int argc, char *argv[])--Also, int main (int argc, char *argv[], char *envp[]) The shell invokes Execve to pass command-line arguments and ambient parameters to the executable program's main function--int execve (const char * filename,char * CONST argv[],CHAR * Const envp[]); --The library function exec* are all EXECVE package routines SYS_EXECV related

Executable file format is parsed within SYS_EXECVE
-Do_execve-> Do_execve_common-> EXEC_BINPRM

Search_binary_handler conforms to the search file format corresponding to the parsing module, as follows:

List_for_each_entry (FMT, &formats, LH) {
       if (!try_module_get (fmt->module))
            continue;
        Read_unlock (&binfmt_lock);
        bprm->recursion_depth++;
        retval = Fmt->load_binary (BPRM);
        Read_lock (&binfmt_lock);

For the elf-formatted executable file Fmt->load_binary (BPRM), it should be performed load_elf_binary its internal and elf file format parsing needs to be combined with the ELF file format standard to read
How the Linux kernel supports many different executable file formats.

82static struct Linux_binfmt Elf_format = {  A. Module     = this_module,  load_binary    = Load_ Elf_binary,  load_shlib = load_elf_library,  core_dump  = Elf_core_dump, and  . Min_coredump   = elf_exec_pagesize,
88};
2198static int __init init_elf_binfmt (void)
2199{
2200    register_binfmt (&elf_format);
2201 return    0;
2202}

Reference documents
http://blog.csdn.net/morphad/article/details/8967000
http://blog.csdn.net/titer1/article/details/45127543
http://blog.csdn.net/ma89481508/article/details/8996436

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.