私たちは、PIDまたはプログラム名を入力として取り、PIDでgdbを呼び出すデバッガプログラムを実装しようとしています。以下には2つの小さなプログラムが書かれていますが、正確な問題が何であるかはわかりません。 PIDを通過した後、結果は5000以上の命令が実行されたことを示しています。
debug.c
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <signal.h>
#include <syscall.h>
#include <sys/ptrace.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/reg.h>
#include <sys/user.h>
#include <unistd.h>
#include <errno.h>
/* Print a message to stdout, prefixed by the process ID
*/
void procmsg(const char* format, ...)
{
va_list ap;
fprintf(stdout, "[%d] ", getpid());
va_start(ap, format);
vfprintf(stdout, format, ap);
va_end(ap);
}
void run_target(const char* programname)
{
procmsg("target started. will run '%s'\n", programname);
/* Allow tracing of this process */
if (ptrace(PTRACE_TRACEME, 0, 0, 0) < 0) {
perror("ptrace");
return;
}
/* Replace this process's image with the given program */
execl(programname, programname, 0);
}
void run_debugger(pid_t child_pid)
{
int wait_status;
unsigned icounter = 0;
procmsg("debugger started\n");
/* Wait for child to stop on its first instruction */
wait(&wait_status);
while (WIFSTOPPED(wait_status)) {
icounter++;
struct user_regs_struct regs;
ptrace(PTRACE_GETREGS, child_pid, 0, ®s);
unsigned instr = ptrace(PTRACE_PEEKTEXT, child_pid, regs.eip, 0);
procmsg("icounter = %u. EIP = 0x%08x. instr = 0x%08x\n",
icounter, regs.eip, instr);
/* Make the child execute another instruction */
if (ptrace(PTRACE_SINGLESTEP, child_pid, 0, 0) < 0) {
perror("ptrace");
return;
}
/* Wait for child to stop on its next instruction */
wait(&wait_status);
}
procmsg("the child executed %u instructions\n", icounter);
}
int main(int argc, char** argv)
{
pid_t child_pid_attach;
if (argc < 2) {
fprintf(stderr, "Expected a program name as argument\n");
return -1;
}
sscanf(argv[1],"%d",&child_pid_attach);
//Attaching to running process
if(ptrace(PTRACE_ATTACH,child_pid_attach,0,0)<)
{
perror("ptrace");
return;
}
else
{
printf("%d",child_pid_attach);
}
if (child_pid_attach== 0)
run_target(argv[1]);
else if (child_pid_attach > 0)
run_debugger(child_pid_attach);
else {
perror("fork");
return -1;
}
ptrace(PTRACE_DETACH,child_pid_attach,0,0);
return 0;
}
上記のプログラムは、次のプログラム(2つの数値の合計など)で生成されたプロセスをデバッグするために使用されました。 test.c
#include<stdio.h>
void main()
{
int a, b, c;
scanf("%d", &a);
scanf("%d", &b);
printf("\n Sum of Two Numbers is:");
c=a+b;
printf("%d",c);
}
まず、./testを実行してpidを確認します。次に、./Debug [pid]を実行します。上記の実行結果は、子プロセスが5000以上の命令を実行したことを示し、常に同じ命令が出力される。
これを行う方法が他にあるかどうか、他のプロセスからデータを読み取る方法を教えてください。この場合、「./testで生成されたプロセスのデータ(変数値)をどのように読み取るのですか?」です。
ベストアンサー1
実際、それは正しい行動です。
以下は以下で引用された。ここ:
答えは興味深いです。デフォルトでは、LinuxのgccはプログラムをCランタイムライブラリに動的にリンクします。これは、プログラムの実行時に最初に実行されるものの1つが必要な共有ライブラリを見つける動的ライブラリローダであることを意味します。これはかなり多くのコードです。基本的なトレーサーは、主要な機能だけでなく、プロセス全体を含むすべてのコマンドを調べます。