这是一个使用gdb 进入共享库的示例。我正在使用 Linux(Ubuntu 18.04)。
我首先使用perlbrew安装了一个调试版本的Perl:
perlbrew install perl-5.26.2 --as=5.26.2d -DDEBUGGING
perlbrew use 5.26.2d
然后,我在文件夹 /home/hakon/mylib 中创建了一个共享库(为了测试目的而精简到非常少的内容):
mylib.c
此函数改编自perlxstut中的示例3:
#include <math.h>
#include "myclib.h"
double my_clib_function( double arg ) {
if (arg > 0.0) {
arg = floor(arg + 0.5);
} else if (arg < 0.0) {
arg = ceil(arg - 0.5);
} else {
arg = 0.0;
}
return arg;
}
myclib.h:
double my_clib_function( double arg );
然后我创建了共享库libmylib.so:
gcc -g -c -fpic mylib.c
gcc -g -shared -o libmylib.so mylib.o
请注意,我们通过将-g 切换为gcc,在libmylib.so 中包含调试符号。
现在,我们可以创建一个.xs 文件来调用共享库函数(在文件夹/home/hakon/myxstest 中):
Mytest.xs
#define PERL_NO_GET_CONTEXT
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"
#include "myclib.h"
MODULE = Mytest PACKAGE = Mytest
void
wrapper(arg)
double arg
CODE:
arg = my_clib_function( arg);
OUTPUT:
arg
然后我们需要将 XS 文件链接到一个 Perl 包名:
lib/Mytest.pm:
package Mytest;
use 5.022001;
use strict;
use warnings;
require Exporter;
our @ISA = qw(Exporter);
our %EXPORT_TAGS = ( 'all' => [ qw() ] );
our @EXPORT_OK = ( @{ $EXPORT_TAGS{'all'} } );
our @EXPORT = qw();
our $VERSION = '0.01';
require XSLoader;
XSLoader::load('Mytest', $VERSION);
接下来,我们需要像ExtUtils::MakeMaker 这样的构建系统来编译
XS 文件(进入另一个共享库):
Makefile.PL:
use 5.022001;
use ExtUtils::MakeMaker;
my $lib_dir = '/home/hakon/mylib';
WriteMakefile(
NAME => 'Mytest',
VERSION_FROM => 'lib/Mytest.pm',
PREREQ_PM => {},
ABSTRACT_FROM => 'lib/Mytest.pm',
AUTHOR => 'Håkon Hægland <xxx.yyy@gmail.com>',
LIBS => ["-L$lib_dir -lmylib"],
INC => "-I. -I$lib_dir",
OPTIMIZE => '-g',
);
请注意,我们使用OPTIMIZE => '-g' 请求调试符号(用于Mytest.so 共享对象),并且我们通过使用WriteMakefile() 的LIBS 参数来告知另一个共享库libmylib.so 的位置。
然后我们编译 XS 代码:
perl Makefile.PL
make
最后,我们编写一个小的测试 Perl 脚本:
p.pl
#! /usr/bin/env perl
use feature qw(say);
use strict;
use warnings;
use ExtUtils::testlib;
use Mytest;
my $res = 3.5;
Mytest::wrapper( $res ); # <-- Warning: modifies $res in place !
say $res;
我们可以知道在我们的测试脚本p.pl上运行gdb:
$ gdb -q --args perl p.pl
Reading symbols from perl...done.
我们在 XS 文件的第 14 行设置断点:
(gdb) break Mytest.xs:14
No source file named Mytest.xs.
Make breakpoint pending on future shared library load? (y or [n]) y
Breakpoint 1 (Mytest.xs:14) pending.
然后运行脚本:
(gdb) run
Starting program: /home/hakon/perlbrew/perls/5.26.2d/bin/perl p.pl
[Thread debugging using libthread_db enabled]
Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".
Breakpoint 1, XS_Mytest_wrapper (cv=0x555555bdc860) at Mytest.xs:14
14 arg = my_clib_function( arg);
现在我们已经停在 XS 文件中我们将调用共享库函数的位置。如果需要,我们可以检查将要传递的参数:
(gdb) p arg
$1 = 3.5
然后步入共享库:
(gdb) s
my_clib_function (arg=3.5) at mylib.c:5
5 if (arg > 0.0) {
等等..