Debugging Foreign Predicate

Hi,
i’m writing a foreign predicate using the C interface. Is there a way to debug the C code inside the functions i wrote in the .c file while executing prolog? So for instance, i have function in C

static extern_pred(term_t a, term_t b) {
  int i;
  ...
  for(i = 0; i < N; i++) {
    ...
  }
  ...
  return(PL_unify(...));
}

Then in prolog:

test:-
  extern_pred(A,B).

Is there a way to set a brakpoint inside the C function, so the execution stops, let’s say, before the for loop, when calling ?- test. from prolog, and then i can proceed step by step? For instance, using gdb?
Thanks

What is the problem? Just compile the extension for debugging, run gdb swipl and load the program. Now break using ^C and set a gdb breakpoint on the function. Continue from gdb, call the predicate from Prolog and gdb should trap the breakpoint.

Once there, Prolog objects are typically either integers or anonymous pointers. There is a large number of utility functions that you can call from gdb to know what these objects are. In this context the most practical is

(gdb) call pl_writeln(a)

where a is a variable ot type term_t to print the Prolog term. Another useful function is PL_backtrace(depth, flags) to print a Prolog backtrace.

2 Likes

Hi Jan,

This is one of those pieces of knowledge that is deeply embedded in your mind and is very valuable: I have a suggestion to make this kind of knowledge available to others and also make it easy for you:

  • Next time you debug a foreign C predicate (or even some part of SWI Prolog core), could you record the terminal session using https://asciinema.org/? Then we will be able to learn by watching you do it. I think this would be very useful.
2 Likes

I surely have a lot of experience debugging SWI-Prolog and foreign extensions. Most of this is pretty much general experience in C debugging. There is quite a bit of support you get notably when building SWI-Prolog for debugging that provide additional runtime consistency checks, controlled debug messages and functions you can call from the C debugger to analyze the status. I couple of people have a more or less complete view on what is there.

Recording a single terminal isn’t that useful. I tend to use multiple as well as multiple editor windows when debugging. So, only full screen recording will help. When not done slowly and explained carefully for tutorial reasons I consider it really hard to figure out what someone is doing behind a terminal.