cpptcl icon indicating copy to clipboard operation
cpptcl copied to clipboard

Segfault caused by cpptcl interfering with USE_TCL_STUBS

Open mutability opened this issue 7 years ago • 2 comments

This program crashes with a segfault; it tries to call Tcl_CreateInterp via the tcl stubs pointer, but the stubs pointer is null. (case 1)

#include "cpptcl.h"
#include "tcl.h"

int main(int argc, char **argv) {
  Tcl_CreateInterp();
  return 0;
}

This program does not crash (case 2)

#include "tcl.h"

int main(int argc, char **argv) {
  Tcl_CreateInterp();
  return 0;
}

This program also does not crash (case 3)

#include "tcl.h"
#include "cpptcl.h"

int main(int argc, char **argv) {
  Tcl_CreateInterp();
  return 0;
}

The cause is that cpptcl.h is defining USE_TCL_STUBS before including tcl.h This is inappropriate for the case where cpptcl is being used from a program that's just embedding tcl, rather than an extension to be embedded in an existing interpreter.

Whether it actually breaks things is very dependent on the order of includes; if tcl.h is included before cpptcl.h, then cpptcl.h's USE_TCL_STUBS has no effect and everything is fine.

example2.cc in the cpptcl tree is an example of case 3. Swapping the order of the includes produces case 1, which then crashes.

mutability avatar Jul 31 '18 13:07 mutability

Has this been addressed?

AndruePeters avatar Dec 19 '19 12:12 AndruePeters

We failed to get a function added to Tcl which could create an interpreter regardless of the compiler macros implemented by USE_TCL_STUBS. Currently you have to create the TCL interpreter from a compilation unit without USE_TCL_STUBS defined. When USE_TCL_STUBS is defined Tcl_CreateInterp is a macro which guarantees a crash.

See https://core.tcl-lang.org/tips/doc/trunk/tip/531.md which contains an example of the C code needed to create an interpreter.

The spirit of the TIP 531 code is that one should be able to use USE_TCL_STUBS all the time. The only time you need to avoid the C macros USE_TCL_STUBS creates is when creating the first Tcl interpreter instance. That's why we are trying to get the function included with Tcl.

If you are not creating a Tcl extension, then you can avoid the use of USE_TCL_STUBS by defining CPPTCL_NO_TCL_STUBS. Note that the Tcl TEA framework for extensions always sets USE_TCL_STUBS in those build configurations. Therefore, the default is for an extension author not an embedded Tcl author.

snoe925 avatar Dec 19 '19 15:12 snoe925