当前位置--> 首 页 --> 文 章 -->C/C++

※阅读文章※

Unix编程/应用问答中文版 ---3.-lelf、-lkvm、-lkstat相关问题


作者:不祥 [文章出自: www.fanqiang.com]


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()等函数带来的冲突。 

文章加入时间: 2004-11-17 14:53:10 责任编辑: w9   (2582 人次查阅)
 
Copyright © 1998-2004 中国PHP联盟 All rights reserved.