Strace mu Linux: mbiri, kapangidwe ndi kugwiritsa ntchito
M'machitidwe ogwiritsira ntchito a Unix, kulumikizana kwa pulogalamu ndi dziko lakunja ndi makina ogwiritsira ntchito kumachitika kudzera mumagulu ang'onoang'ono - mafoni a dongosolo. Izi zikutanthauza kuti pazolinga zowongolera zitha kukhala zothandiza kuti akazonde mafoni omwe akuchitidwa ndi njira.
Ntchito imakuthandizani kuwunika "moyo wapamtima" wa mapulogalamu pa Linux strace, yomwe ndi nkhani ya mβnkhaniyi. Zitsanzo za kugwiritsa ntchito zida za akazitape zimatsagana ndi mbiri yachidule strace ndi kufotokoza za mapangidwe a mapulogalamu otere.
Mawonekedwe akulu pakati pa mapulogalamu ndi OS kernel ku Unix ndi mafoni amtundu. mafoni adongosolo, zikwangwani), kuyanjana kwa mapulogalamu ndi akunja kumachitika kudzera mwa iwo okha.
Koma mu mtundu woyamba wa Unix (Mtundu wa 6 Unix, 1975) panalibe njira zabwino zowonera machitidwe a ogwiritsa ntchito. Kuti athetse vutoli, Bell Labs isintha mpaka mtundu wina (Mtundu wa 7 Unix, 1979) adakonza kuyitanira kwadongosolo latsopano - ptrace.
ptrace idapangidwa makamaka kuti ikhale yosokoneza, koma pofika kumapeto kwa zaka za m'ma 80s (m'nthawi yamalonda). Kutulutsidwa kwa System V 4) pazifukwa zimenezi, zida zongogwiritsa ntchito movutikira kwambiriβzozimitsa makinaβzinaonekera ndipo zinayamba kugwiritsidwa ntchito kwambiri.
Yoyamba mtundu womwewo wa strace unasindikizidwa ndi Paul Cronenburg pamndandanda wamakalata wa comp.sources.sun mu 1992 ngati njira ina yolumikizira yotsekedwa. trace kuchokera ku Sun. Zonse ziwiri ndi zoyambirira zidapangidwira SunOS, koma pofika 1994 strace idatumizidwa ku System V, Solaris ndi Linux yomwe ikukula kwambiri.
Masiku ano strace imangothandiza Linux ndipo imadalira zomwezo ptrace, yodzaza ndi zowonjezera zambiri.
Ndikofunikiranso kuti kuyimbira foni ndi zotsatsira za ptrace sikunaphatikizidwepo mu POSIX, ngakhale mbiri yakale ndikukhazikitsa mu Linux, FreeBSD, OpenBSD ndi Unix yachikhalidwe.
Strace chipangizo mwachidule: Piglet Trace
"Simukuyenera kumvetsetsa izi" (Dennis Ritchie, ndemanga mu Version 6 Unix source code)
Kuyambira ndili mwana, sindingathe kuyimilira mabokosi akuda: Sindinasewere ndi zidole, koma ndinayesera kumvetsetsa kapangidwe kawo (akuluakulu amagwiritsa ntchito mawu akuti "kusweka," koma musakhulupirire malirime oipa). Mwina ichi ndichifukwa chake chikhalidwe chosavomerezeka cha Unix yoyamba ndi kayendetsedwe kamakono kotsegula kamene kali pafupi ndi ine.
Pazolinga za nkhaniyi, sizomveka kusokoneza code code ya strace, yomwe yakula kwa zaka zambiri. Koma pasakhale zinsinsi zotsalira kwa owerenga. Chifukwa chake, kuti ndiwonetse mfundo yoyendetsera mapulogalamu otere, ndipereka kachidindo kakang'ono ka tracer - Piglet Trace (ptr). Simadziwa kuchita chilichonse chapadera, koma chinthu chachikulu ndi kuyitana kwa pulogalamu - imatuluka:
Piglet Trace imazindikira pafupifupi mazana a mafoni a Linux (onani. tebulo) ndipo imagwira ntchito pazomanga za x86-64 zokha. Izi ndizokwanira pazolinga zamaphunziro.
Tiyeni tiwone ntchito ya wojambula wathu. Pankhani ya Linux, ochotsa zolakwika ndi otsata amagwiritsa ntchito, monga tafotokozera pamwambapa, foni ya ptrace system. Zimagwira ntchito podutsa mkangano woyamba zizindikiritso za malamulo, zomwe timangofunikira PTRACE_TRACEME, PTRACE_SYSCALL ΠΈ PTRACE_GETREGS.
Tracer imayamba mwachizolowezi cha Unix: fork(2) imayambitsa ndondomeko ya mwana, yomwe imagwiritsanso ntchito exec(3) imayambitsa pulogalamu yomwe ikuphunziridwa. Chinyengo chokha apa ndizovuta ptrace(PTRACE_TRACEME) kale exec: Ndondomeko ya mwana ikuyembekeza ndondomeko ya makolo kuti iziziyang'anira:
pid_t child_pid = fork();
switch (child_pid) {
case -1:
err(EXIT_FAILURE, "fork");
case 0:
/* Child here */
/* A traced mode has to be enabled. A parent will have to wait(2) for it
* to happen. */
ptrace(PTRACE_TRACEME, 0, NULL, NULL);
/* Replace itself with a program to be run. */
execvp(argv[1], argv + 1);
err(EXIT_FAILURE, "exec");
}
Njira ya makolo iyenera kuyimba foni wait(2) mu ndondomeko ya mwana, ndiye kuti, onetsetsani kuti kusintha kwa trace mode kwachitika:
/* Parent */
/* First we wait for the child to set the traced mode (see
* ptrace(PTRACE_TRACEME) above) */
if (waitpid(child_pid, NULL, 0) == -1)
err(EXIT_FAILURE, "traceme -> waitpid");
/* A system call tracing loop, one interation per call. */
for (;;) {
/* A non-portable structure defined for ptrace/GDB/strace usage mostly.
* It allows to conveniently dump and access register state using
* ptrace. */
struct user_regs_struct registers;
/* Enter syscall: continue execution until the next system call
* beginning. Stop right before syscall.
*
* It's possible to change the system call number, system call
* arguments, return value or even avoid executing the system call
* completely. */
if (ptrace(PTRACE_SYSCALL, child_pid, NULL, NULL) == -1)
err(EXIT_FAILURE, "enter_syscall");
if (waitpid(child_pid, NULL, 0) == -1)
err(EXIT_FAILURE, "enter_syscall -> waitpid");
/* According to the x86-64 system call convention on Linux (see man 2
* syscall) the number identifying a syscall should be put into the rax
* general purpose register, with the rest of the arguments residing in
* other general purpose registers (rdi,rsi, rdx, r10, r8, r9). */
if (ptrace(PTRACE_GETREGS, child_pid, NULL, ®isters) == -1)
err(EXIT_FAILURE, "enter_syscall -> getregs");
/* Note how orig_rax is used here. That's because on x86-64 rax is used
* both for executing a syscall, and returning a value from it. To
* differentiate between the cases both rax and orig_rax are updated on
* syscall entry/exit, and only rax is updated on exit. */
print_syscall_enter(registers.orig_rax);
/* Exit syscall: execute of the syscall, and stop on system
* call exit.
*
* More system call tinkering possible: change the return value, record
* time it took to finish the system call, etc. */
if (ptrace(PTRACE_SYSCALL, child_pid, NULL, NULL) == -1)
err(EXIT_FAILURE, "exit_syscall");
if (waitpid(child_pid, NULL, 0) == -1)
err(EXIT_FAILURE, "exit_syscall -> waitpid");
/* Retrieve register state again as we want to inspect system call
* return value. */
if (ptrace(PTRACE_GETREGS, child_pid, NULL, ®isters) == -1) {
/* ESRCH is returned when a child terminates using a syscall and no
* return value is possible, e.g. as a result of exit(2). */
if (errno == ESRCH) {
fprintf(stderr, "nTracee terminatedn");
break;
}
err(EXIT_FAILURE, "exit_syscall -> getregs");
}
/* Done with this system call, let the next iteration handle the next
* one */
print_syscall_exit(registers.rax);
}
int main(int argc, char *argv[])
{
char str[] = "write me to stdoutn";
/* write(2) is a simple wrapper around a syscall so it should be easy to
* find in the syscall trace. */
if (sizeof(str) != write(STDOUT_FILENO, str, sizeof(str))){
perror("write");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
Kugwira ntchito ndi njira kudzera pa foni fork - maziko a Unixes onse. Tiyeni tiwone momwe strace imagwirira ntchito ndi mtengo wopangira njira pogwiritsa ntchito chitsanzo cha "kuswana" kosavuta. mapulogalamu:
int main(int argc, char *argv[])
{
pid_t parent_pid = getpid();
pid_t child_pid = fork();
if (child_pid == 0) {
/* A child is born! */
child_pid = getpid();
/* In the end of the day printf is just a call to write(2). */
printf("child (self=%d)n", child_pid);
exit(EXIT_SUCCESS);
}
printf("parent (self=%d, child=%d)n", parent_pid, child_pid);
wait(NULL);
exit(EXIT_SUCCESS);
}
Apa njira yoyambirira imapanga njira ya mwana, zonse zimalemba mpaka kutulutsa kokhazikika:
Mwa njira, ndi foni yanji yomwe imagwiritsidwa ntchito popanga njira yatsopano?
Chitsanzo: njira zamafayilo mβmalo mwa zogwirira
Kudziwa zofotokozera mafayilo ndikothandiza, koma mayina a mafayilo omwe pulogalamu imawapeza amathanso kukhala othandiza.
Chotsatira pulogalamuyi amalemba mzere ku fayilo yakanthawi:
void do_write(int out_fd)
{
char str[] = "write me to a filen";
if (sizeof(str) != write(out_fd, str, sizeof(str))){
perror("write");
exit(EXIT_FAILURE);
}
}
int main(int argc, char *argv[])
{
char tmp_filename_template[] = "/tmp/output_fileXXXXXX";
int out_fd = mkstemp(tmp_filename_template);
if (out_fd == -1) {
perror("mkstemp");
exit(EXIT_FAILURE);
}
do_write(out_fd);
return EXIT_SUCCESS;
}
Panthawi yoyimba bwino strace iwonetsa mtengo wa nambala yofotokozera yomwe idaperekedwa ku foni yadongosolo:
$ strace -e trace=write -o write-tmp-file.log ./write-tmp-file
$ cat write-tmp-file.log
write(3, "write me to a filen", 20) = 20
+++ exited with 0 +++
Ndi mbendera -y Chidachi chikuwonetsa njira yopita ku fayilo yomwe wofotokozera amafanana:
$ strace -y -e trace=write -o write-tmp-file.log ./write-tmp-file
$ cat write-tmp-file.log
write(3</tmp/output_fileCf5MyW>, "write me to a filen", 20) = 20
+++ exited with 0 +++
Chitsanzo: Kutsata Mafayilo
Chinthu chinanso chothandiza: wonetsani mafoni amtundu okha omwe amalumikizidwa ndi fayilo inayake. Ena pulogalamuyi imawonjezera mzere ku fayilo yosasinthika yomwe idaperekedwa ngati mkangano:
void do_write(int out_fd)
{
char str[] = "write me to a filen";
if (sizeof(str) != write(out_fd, str, sizeof(str))){
perror("write");
exit(EXIT_FAILURE);
}
}
int main(int argc, char *argv[])
{
/*
* Path will be provided by the first program argument.
* */
const char *path = argv[1];
/*
* Open an existing file for writing in append mode.
* */
int out_fd = open(path, O_APPEND | O_WRONLY);
if (out_fd == -1) {
perror("open");
exit(EXIT_FAILURE);
}
do_write(out_fd);
return EXIT_SUCCESS;
}
zotsatira strace amawonetsa zambiri zosafunikira. Mbendera -P ndi mkangano zimayambitsa strace kusindikiza mafoni okha ku fayilo yotchulidwa:
$ strace -y -P/tmp/test_file.log -o write-file.log ./write-file /tmp/test_file.log
$ cat write-file.log
openat(AT_FDCWD, "/tmp/test_file.log", O_WRONLY|O_APPEND) = 3</tmp/test_file.log>
write(3</tmp/test_file.log>, "write me to a filen", 20) = 20
+++ exited with 0 +++
Chitsanzo: Mapologalamu Ambiri
Zothandiza strace ingathandizenso pogwira ntchito ndi ma multi-threads pulogalamu. Pulogalamu yotsatirayi imalemba zotuluka mumitsinje iwiri:
void *thread(void *arg)
{
(void) arg;
printf("Secondary thread: workingn");
sleep(1);
printf("Secondary thread: donen");
return NULL;
}
int main(int argc, char *argv[])
{
printf("Initial thread: launching a threadn");
pthread_t thr;
if (0 != pthread_create(&thr, NULL, thread, NULL)) {
fprintf(stderr, "Initial thread: failed to create a thread");
exit(EXIT_FAILURE);
}
printf("Initial thread: joining a threadn");
if (0 != pthread_join(thr, NULL)) {
fprintf(stderr, "Initial thread: failed to join a thread");
exit(EXIT_FAILURE);
};
printf("Initial thread: done");
exit(EXIT_SUCCESS);
}
Mwachilengedwe, iyenera kuphatikizidwa ndi moni wapadera kwa wolumikizira - -pthread mbendera:
$ gcc examples/thread-write.c -pthread -o thread-write
$ ./thread-write
/thread-write
Initial thread: launching a thread
Initial thread: joining a thread
Secondary thread: working
Secondary thread: done
Initial thread: done
$
Sakanizani -f, monga momwe zimakhalira nthawi zonse, zidzawonjezera pid ya ndondomekoyi kumayambiriro kwa mzere uliwonse.
Mwachilengedwe, sitikulankhula za chizindikiritso cha ulusi m'lingaliro la kukhazikitsidwa kwa muyezo wa POSIX Threads, koma za chiwerengero chomwe chimagwiritsidwa ntchito ndi wopanga ntchito ku Linux. Kuchokera kumalingaliro omalizira, palibe njira kapena ulusi - pali ntchito zomwe ziyenera kugawidwa pakati pa makina omwe alipo.
Mukamagwira ntchito ndi ulusi wambiri, kuyimba foni kumachulukanso:
Mwa njira, mafunso. Ndi foni yanji yomwe imagwiritsidwa ntchito popanga ulusi watsopano? Kodi kuyitana kwa ulusi uku kumasiyana bwanji ndi kuyitanira kwa njira?
Kalasi ya Master: process stack panthawi yoyimba foni
Mmodzi wa posachedwapa anaonekera strace kuthekera - kuwonetsa kuchuluka kwa mafoni ogwira ntchito panthawi yoyimba foni. Zosavuta chitsanzo:
void do_write(void)
{
char str[] = "write me to stdoutn";
if (sizeof(str) != write(STDOUT_FILENO, str, sizeof(str))){
perror("write");
exit(EXIT_FAILURE);
}
}
int main(int argc, char *argv[])
{
do_write();
return EXIT_SUCCESS;
}
Mwachibadwa, pulogalamu linanena bungwe limakhala voluminous kwambiri, ndipo, kuwonjezera mbendera -k (chiwonetsero cha stack), ndizomveka kusefa mafoni amtundu ndi dzina:
$ gcc examples/write-simple.c -o write-simple
$ strace -k -e trace=write -o write-simple.log ./write-simple
write me to stdout
$ cat write-simple.log
write(1, "write me to stdoutn", 20) = 20
> /lib/x86_64-linux-gnu/libc-2.27.so(__write+0x14) [0x110154]
> /home/vkazanov/projects-my/strace-post/write-simple(do_write+0x50) [0x78a]
> /home/vkazanov/projects-my/strace-post/write-simple(main+0x14) [0x7d1]
> /lib/x86_64-linux-gnu/libc-2.27.so(__libc_start_main+0xe7) [0x21b97]
> /home/vkazanov/projects-my/strace-post/write-simple(_start+0x2a) [0x65a]
+++ exited with 0 +++