How to print exact value of the program counter in C

后端 未结 3 1390
有刺的猬
有刺的猬 2020-12-10 06:29

I want to write a C program which would print the contents of the program counter PC. Can this be done from user space, or assembly, or some specific kernel rou

3条回答
  •  春和景丽
    2020-12-10 07:18

    On ARM, you can use:

    static __inline__ void * get_pc(void)  {
        void *pc;
        asm("mov %0, pc" : "=r"(pc));
        return pc;
    }
    

    Or this one should work as well:

    static __inline__ void * get_pc(void) {
        register void * pc __asm__("pc");
        __asm__("" : "=r"(pc));
        return pc;
    }
    

    The forced inlining is important here, because that ensures you retrieve PC as per the call site.

    Edit: just remembered, __current_pc() ARM intrinsic. GCC should have this as well.

提交回复
热议问题