如何使用在同一 CPU 上运行的调试器读取 CPU 寄存器? [英] How is it possible to read the CPU registers using a debugger running on the same CPU?

查看:27
本文介绍了如何使用在同一 CPU 上运行的调试器读取 CPU 寄存器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在学习汇编时,我使用 GDB 的方式如下:

As I was learning about assembly, I used GDB the following way:

gdb ./a.out (a is a compiled C script that only prints hello world)
break main
run
info registers

当我自己使用同一个 CPU 打印寄存器时,为什么我可以看到程序使用的寄存器?不应该使用 GDB(或操作系统)覆盖寄存器并且只显示被覆盖的寄存器吗?我能想到的唯一答案是,我的 CPU 是双核的,其中一个正在使用,另一个保留给程序使用.

Why can I see the registers used by my program when I am myself using the same CPU to print the registers? Shouldn't the use of GDB (or operating system) overwrite the registers and only show me the overwritten registers? The only answer I can think of is the fact that my CPU is dual-core and that one of the cores is being used and the other is kept for the program.

推荐答案

操作系统维护每个执行线程的寄存器状态.当您检查 gdb 中的寄存器时,调试器实际上是在要求操作系统从保存状态中读取寄存器值.您的程序在那个时间点没有运行,它是调试器.

The operating system maintains the state of the registers for each execution thread. When you are examining registers in gdb, the debugger is actually asking the OS to read the register value from the saved state. Your program is not running at that point in time, it's the debugger which is.

假设您的系统上没有其他进程.以下是所发生情况的简化视图:

Let's assume there are no other processes on your system. Here is a simplified view of what happens:

  1. 调试器启动并获取 cpu
  2. 调试器要求操作系统加载你的程序
  3. 调试器要求操作系统放置断点
  4. 调试器要求操作系统开始执行您的程序.操作系统会保存 gdb 寄存器状态并将控制权转移给您的程序.
  5. 您的程序遇到断点.操作系统取得控制权,保存程序的寄存器状态,重新加载 gdb 寄存器并将 cpu 交还给 gdb.
  6. 调试器要求操作系统从保存状态读取程序的寄存器.

请注意,这种机制是多任务操作系统的正常职责的一部分,它并不特定于调试.当 OS 调度器决定应该执行不同的程序时,它会保存当前状态并加载另一个.这称为上下文切换,每秒可能发生多次,从而产生即使您只有一个 cpu 内核,程序也会同时执行的错觉.

Note that this mechanism is part of the normal duties of a multitasking operating system, it's not specific to debugging. When the OS scheduler decides a different program should be executing, it saves the current state and loads another. This is called a context switch and it may happen many times per second, giving the illusion that programs execute simultaneously even if you only have a single cpu core.

这篇关于如何使用在同一 CPU 上运行的调试器读取 CPU 寄存器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆