8

I'm going JIT code generation, and I want to insert invalid opcodes into the stream in order to perform some meta-debugging. Everything is fine and good until it hits the instruction, at which point the thing goes into an infinite loop of illegal instruction to signal handler and back.

Is there any way I can set the thing to simply skip the bad instruction?

2
  • Forgive my ignorance... Shouldn't you do a runtime feature test, and then emit instructions supported by the cpu or platform?
    – jww
    May 29, 2016 at 23:20
  • What jww said. An ounce of prevention is worth a pound of cure. Prevent the illegal instruction in the first place, detect the relevant capabilities before code generation.
    – doug65536
    Mar 21, 2020 at 7:51

2 Answers 2

13

It's very hacky and UNPORTABLE but:

void sighandler (int signo, siginfo_t si, void *data) {
    ucontext_t *uc = (ucontext_t *)data;

    int instruction_length = /* the length of the "instruction" to skip */

    uc->uc_mcontext.gregs[REG_RIP] += instruction_length;
}

install the sighandler like that:

struct sigaction sa, osa;
sa.sa_flags = SA_ONSTACK | SA_RESTART | SA_SIGINFO;
sa.sa_sigaction = sighandler;
sigaction(SIGILL, &sa, &osa);

That could work if you know how far to skip (and it's a Intel proc) :-)

4
  • extremely hacky, but probably sufficient for now. any tips on extracting the instruction that caused the exception? look at siginfo_t.si_addr?
    – alexgolec
    Feb 16, 2012 at 17:39
  • The problem with illegal instructions is that you can't tell the instruction length, since it is no instruction :-). And because instruction lengths differ among architectures and even within architectures (Intel has variable length instructions) something like that has to be extremely hacky I think. Feb 16, 2012 at 17:42
  • 2
    It will work, but I suggest that you emit JMP instructions to avoid the metadata in your JIT, because your metadata might sometimes be valid (but naughty) machine code, and because catching SGILL will probably slow down a big lot your execution of JIT-ed code... Feb 17, 2012 at 6:09
  • The second parameter of the sighandler function should be a pointer, to match the definition of sigaction's property void (*sa_sigaction)(int, siginfo_t *, void *);. Otherwise, calling the handler will lead to a segmentation fault. May 14, 2022 at 16:13
0

You can also try another approach (if it applies to your case): you can use a SIGTRAP which is easier to manage.

void sigtrap_handler(int sig){
    printf("Process %d received sigtrap %d.\n", getpid(),sig);
}

signal(SIGTRAP,sigtrap_handler);
asm("int3"); // causes a SIGTRAP

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.