[ 永遠的UNIX::UNIX技術資料的寶庫 ]   GB | BIG5

首頁 > 編程技術 > C/C++ > 正文
Unix編程/應用問答中文版 ---3.-lelf、-lkvm、-lkstat相關問題
本文出自:http://www.nsfocus.com 維護:小四 (2002-10-21 06:02:01)

3.    -lelf、-lkvm、-lkstat相關問題 
3.1   如何判斷可執行文件是否攜帶了調試信息 
3.2   mprotect如何用 
3.3   mmap如何用 
3.4   getrusage如何用 
3.5   setitimer如何用 
-------------------------------------------------------------------------- 

3. -lelf、-lkvm、-lkstat相關問題 

3.1 如何判斷可執行文件是否攜帶了調試信息 

Q: 某些時候需要知道編譯可執行文件時是否攜帶了調試信息(比如是否指定了-g編譯 
   選項)。檢查可執行文件中是否包含".stab" elf section,".stab" section用 
   保存相關調試信息。 

A: Sun Microsystems 2000-05-15 

下面這個腳本演示如何判斷可執行文件是否攜帶調試信息 

-------------------------------------------------------------------------- 
#! /bin/sh 

# Script that test whether or not a given file has been built for 
# debug (-g option specified in the compilation) 

if [ $# -le 0 ] 
then 
    echo "Usage: $1 filename" 
    exit 1 
fi 

if [ ! -f $1 ] 
then 
    echo "File $1 does not exist" 
    exit 1 
fi 

/usr/ccs/bin/dump -hv $1 | /bin/egrep -s '.stab$' 
if [ $? -eq 0 ] 
then 
    echo "File '$1' has been built for debug" 
    exit 0 
else 
    echo "File '$1' has not been built for debug" 
    exit 1 
fi 
-------------------------------------------------------------------------- 

如果對ELF文件格式不熟悉,理解上述代碼可能有點困難,參看 
http://www.digibel.org/~tompy/hacking/elf.txt,這是1.1版的ELF文件格式規范。 

3.2 mprotect如何用 

A: 小四 <cloudsky@263.net> 

# truss prtconf 2>&1 | grep sysconf 
sysconfig(_CONFIG_PAGESIZE)                     = 8192 
sysconfig(_CONFIG_PHYS_PAGES)                   = 16384 


由此可知當前系統頁尺寸是8192字節。 

-------------------------------------------------------------------------- 
/* 
* gcc -Wall -g -ggdb -static -o mtest mtest.c 
*/ 
#include <stdio.h> 
#include <stdlib.h> 
#include <errno.h> 
#include <sys/mman.h> 

int main ( int argc, char * argv[] ) 

    char *buf; 
    char  c; 

    /* 
     * 分配一塊內存,擁有缺省的rw-保護 
     */ 
    buf = ( char * )malloc( 1024 + 8191 ); 
    if ( !buf ) 
    { 
        perror( "malloc" ); 
        exit( errno ); 
    } 
    /* 
     * Align to a multiple of PAGESIZE, assumed to be a power of two 
     */ 
    buf     = ( char * )( ( ( unsigned int )buf + 8191 ) & ~8191 ); 
    c       = buf[77]; 
    buf[77] = c; 
    printf( "ok\n" ); 
    /* 
     * Mark the buffer read-only. 
     * 
     * 必須保証這裡buf位頁邊界上,否則mprotect()失敗,報告無效參數 
     */ 
    if ( mprotect( buf, 1024, PROT_READ ) ) 
    { 
        perror( "\nmprotect" ); 
        exit( errno ); 
    } 
    c       = buf[77]; 
    /* 
     * Write error, program dies on SIGSEGV 
     */ 
    buf[77] = c; 

    exit( 0 ); 
}  /* end of main */ 
-------------------------------------------------------------------------- 

$ ./mtest 
ok 
段錯誤 (core dumped)  <-- 內存保護起作用了 


3.3 mmap如何用 

A: 小四 <cloudsky@263.net> 

下面寫一個完成文件復制功能的小程序,利用mmap(2),而不是標準文件I/O接口。 

-------------------------------------------------------------------------- 
/* 
* gcc -Wall -O3 -o copy_mmap copy_mmap.c 
*/ 
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h>  /* for memcpy */ 
#include <strings.h> 
#include <sys/mman.h> 
#include <sys/types.h> 
#include <sys/stat.h> 
#include <fcntl.h> 
#include <unistd.h> 

#define PERMS 0600 

int main ( int argc, char * argv[] ) 

    int          src, dst; 
    void        *sm, *dm; 
    struct stat  statbuf; 

    if ( argc != 3 ) 
    { 
        fprintf( stderr, " Usage: %s <source> <target>\n", argv[0] ); 
        exit( EXIT_FAILURE ); 
    } 
    if ( ( src = open( argv[1], O_RDONLY ) ) < 0 ) 
    { 
        perror( "open source" ); 
        exit( EXIT_FAILURE ); 
    } 
    /* 為了完成復制,必須包含讀打開,否則mmap()失敗 */ 
    if ( ( dst = open( argv[2], O_RDWR | O_CREAT | O_TRUNC, PERMS ) ) < 0 ) 
    { 
        perror( "open target" ); 
        exit( EXIT_FAILURE ); 
    } 
    if ( fstat( src, &statbuf ) < 0 ) 
    { 
        perror( "fstat source" ); 
        exit( EXIT_FAILURE ); 
    } 
    /* 
     * 參看前面man手冊中的說明,mmap()不能用擴展文件長度。所以這裡必須事 
     * 先擴大目標文件長度,準備一個空架子等待復制。 
     */ 
    if ( lseek( dst, statbuf.st_size - 1, SEEK_SET ) < 0 ) 
    { 
        perror( "lseek target" ); 
        exit( EXIT_FAILURE ); 
    } 
    if ( write( dst, &statbuf, 1 ) != 1 ) 
    { 
        perror( "write target" ); 
        exit( EXIT_FAILURE ); 
    } 
    /* 讀的時候指定 MAP_PRIVATE 即可 */ 
    sm = mmap( 0, ( size_t )statbuf.st_size, PROT_READ, 
               MAP_PRIVATE | MAP_NORESERVE, src, 0 ); 
    if ( MAP_FAILED == sm ) 
    { 
        perror( "mmap source" ); 
        exit( EXIT_FAILURE ); 
    } 
    /* 這裡必須指定 MAP_SHARED 才可能真正改變靜態文件 */ 
    dm = mmap( 0, ( size_t )statbuf.st_size, PROT_WRITE, 
               MAP_SHARED, dst, 0 ); 
    if ( MAP_FAILED == dm ) 
    { 
        perror( "mmap target" ); 
        exit( EXIT_FAILURE ); 
    } 
    memcpy( dm, sm, ( size_t )statbuf.st_size ); 
    /* 
     * 可以不要這行代碼 
     * 
     * msync( dm, ( size_t )statbuf.st_size, MS_SYNC ); 
     */ 
    return( EXIT_SUCCESS ); 
}  /* end of main */ 
-------------------------------------------------------------------------- 

mmap()好處是處理大文件時速度明顯快標準文件I/O,無論讀寫,都少了一次用戶 
空間與內核空間之間的復制過程。操作內存還便設計、優化算法。 

文件I/O操作/proc/self/mem不存在頁邊界對齊的問題。至少Linux的mmap()的最一 
個形參offset並未強制要求頁邊界對齊,如果提供的值未對齊,系統自動向上舍入到 
頁邊界上。 

malloc()分配得到的地址不見得對齊在頁邊界上 

/proc/self/mem和/dev/kmem不同。root用戶打開/dev/kmem就可以在用戶空間訪問到 
內核空間的數據,包括偏移0處的數據,系統提供了這樣的支持。 

顯然代碼段經過/proc/self/mem可寫映射已經可寫,無須mprotect()介入。 

D: scz <scz@nsfocus.com> 

Solaris 2.6下參看getpagesize(3C)手冊頁,關如何獲取頁大小,一般是8192。 
Linux下參看getpagesize(2)手冊頁,一般是4096。 

3.4 getrusage如何用 

A: 小四 <cloudsky@263.net> 

在SPARC/Solaris 2.6/7下結論一致,只支持了ru_utime和ru_stime成員,其他成員 
被設置成0。修改頭文件在FreeBSD 4.3-RELEASE上測試,則不只支持ru_utime和 
ru_stime成員。從FreeBSD的getrusage(2)手冊頁可以看到,這個函數源自4.2 BSD。 

如此來說,至少對SPARC/Solaris 2.6/7,getrusage(3C)並無多大意義。 

3.5 setitimer如何用 

D: scz <scz@nsfocus.com> 

為什要學習使用setitimer(2),因為alarm(3)屬被淘汰的定時器技術。 

A: 小四 <cloudsky@263.net> 

下面是個x86/FreeBSD 4.3-RELEASE下的例子 

-------------------------------------------------------------------------- 
/* 
* File     : timer_sample.c 
* Author   : Unknown (Don't ask me anything about this program) 
* Complie  : gcc -Wall -pipe -O3 -o timer_sample timer_sample.c 
* Platform : x86/FreeBSD 4.3-RELEASE 
* Date     : 2001-09-18 15:18 
*/ 

/************************************************************************ 
*                                                                      * 
*                               Head File                              * 
*                                                                      * 
************************************************************************/ 

#include <stdio.h> 
#include <stdlib.h> 
#include <sys/time.h> 
#include <signal.h> 

/************************************************************************ 
*                                                                      * 
*                               Macro                                  * 
*                                                                      * 
************************************************************************/ 

typedef void Sigfunc ( int );  /* for signal handlers */ 

/************************************************************************ 
*                                                                      * 
*                            Function Prototype                        * 
*                                                                      * 
************************************************************************/ 

static void      Atexit       ( void ( *func ) ( void ) ); 
static void      init_signal  ( void ); 
static void      init_timer   ( void ); 
static void      on_alarm     ( int signo ); 
static void      on_terminate ( int signo ); 
static int       Setitimer    ( int which, const struct itimerval *value, 
                                struct itimerval *ovalue ); 
       Sigfunc * signal       ( int signo, Sigfunc *func ); 
static Sigfunc * Signal       ( int signo, Sigfunc *func ); 
static void      terminate    ( void ); 

/************************************************************************ 
*                                                                      * 
*                            Static Global Var                         * 
*                                                                      * 
************************************************************************/ 

/************************************************************************/ 

static void Atexit ( void ( *func ) ( void ) ) 

    if ( atexit( func ) != 0 ) 
    { 
        perror( "atexit" ); 
        exit( EXIT_FAILURE ); 
    } 
    return; 
}  /* end of Atexit */ 

/* 
* 初始化信號句柄 
*/ 
static void init_signal ( void ) 

    int i; 

    Atexit( terminate ); 
    for ( i = 1; i < 9; i++ ) 
    { 
        Signal( i, on_terminate ); 
    } 
    Signal( SIGTERM, on_terminate ); 
    Signal( SIGALRM, on_alarm ); 
    return; 
}  /* end of init_signal */ 

static void init_timer ( void ) 

    struct itimerval value; 

    value.it_value.tv_sec  = 1; 
    value.it_value.tv_usec = 0; 
    value.it_interval      = value.it_value; 
    Setitimer( ITIMER_REAL, &value, NULL ); 
}  /* end of init_timer */ 

static void on_alarm ( int signo ) 

    static int count = 0; 

    /* 
     * 演示用,這很危險 
     */ 
    fprintf( stderr, "count = %u\n", count++ ); 
    return; 


static void on_terminate ( int signo ) 

    /* 
     * 這次我們使用atexit()函數 
     */ 
    exit( EXIT_SUCCESS ); 
}  /* end of on_terminate */ 

static int Setitimer ( int which, const struct itimerval *value, 
                       struct itimerval *ovalue ) 

    int ret; 

    if ( ( ret = setitimer( which, value, ovalue ) ) < 0 ) 
    { 
        perror( "setitimer" ); 
        exit( EXIT_FAILURE ); 
    } 
    return( ret ); 
}  /* end of Setitimer */ 

Sigfunc * signal ( int signo, Sigfunc *func ) 

    struct sigaction act, oact; 

    act.sa_handler = func; 
    sigemptyset( &act.sa_mask ); 
    act.sa_flags   = 0; 
    if ( signo == SIGALRM ) 
    { 
#ifdef  SA_INTERRUPT 
        act.sa_flags |= SA_INTERRUPT;  /* SunOS 4.x */ 
#endif 
    } 
    else 
    { 
#ifdef  SA_RESTART 
        act.sa_flags |= SA_RESTART;  /* SVR4, 44BSD */ 
#endif 
    } 
    if ( sigaction( signo, &act, &oact ) < 0 ) 
    { 
        return( SIG_ERR ); 
    } 
    return( oact.sa_handler ); 
}  /* end of signal */ 

static Sigfunc * Signal ( int signo, Sigfunc *func ) 

    Sigfunc *sigfunc; 

    if ( ( sigfunc = signal( signo, func ) ) == SIG_ERR ) 
    { 
        perror( "signal" ); 
        exit( EXIT_FAILURE ); 
    } 
    return( sigfunc ); 
}  /* end of Signal */ 

static void terminate ( void ) 

    fprintf( stderr, "\n" ); 
    return; 
}  /* end of terminate */ 

int main ( int arg, char * argv[] ) 

    init_signal(); 
    init_timer(); 
    while ( 1 ) 
    { 
        /* 
         * 形成阻塞,降低CPU佔用率 
         */ 
        getchar(); 
    } 
    return( EXIT_SUCCESS ); 
}  /* end of main */ 

/************************************************************************/ 

-------------------------------------------------------------------------- 

D: scz <scz@nsfocus.com> 

討論一個問題。getchar()的作用是降低CPU佔用率,可用top命令查看。 

timer_sample.c中換用ITIMER_PROF/SIGPROF,你會發現上述程序無輸出,我據此 
認為getchar()形成的阻塞不計算在進程虛擬時鐘中,也不認為系統正在為進程利益 
而運行。 

如果進一步將getchar()去掉,直接一個while()無限循環,即使換用 
ITIMER_PROF/SIGPROF,程序還是有輸出。不過top命令查看的結果讓你吐血,CPU幾 
乎無空閑。 

D: scz <scz@nsfocus.com> 

setitimer( ITIMER_REAL, &value, NULL )導致分發SIGALRM信號,如果同時使用 
alarm(),勢畢造成沖突。此外注意sleep()、pause()等函數帶來的沖突。 
(http://www.fanqiang.com)
    進入【UNIX論壇

相關文章
Unix編程/應用問答中文版 ---2.堆棧相關問題 (2002-10-18 06:02:00)
Unix編程/應用問答中文版 ---1.系統管理配置問題 (2002-10-17 06:02:00)
Unix編程/應用問答中文版 ---0.簡介 Unix/C傳奇問題 (2002-10-16 06:02:01)
 

★  樊強制作 歡迎分享  ★