CERT.EXCEPTION.OVER.BOUNDARY

Exception thrown over execution boundary

Checker identifies calls when exception thrown over execution boundary (between C and C++, between different compilers, or between different versions of the same compiler).

Vulnerability and risk

Throwing exceptions over execution boundary is undefined behavior. Depending on combination of compilers used it could lead to non caught exceptions or crashes.

Limitations

Checker only checks when exception is thrown directly by called function. It does not detect indirect exceptions, thrown from other functions which are not called directly over execution boundary.

Vulnerable code example

Copy
// library.h
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
void library_foo(int i);
#ifdef __cplusplus
}
#endif

// library.cpp
#include "library.h"

extern "C" void library_foo(int i)
{
  if (i > 1) {
    throw 42;
  }
}

// app.c
#include "library.h"

int main() {
  library_foo(1);  // CERT.EXCEPTION.OVER.BOUNDARY
  return 0;
}

Klocwork reports defect CERT.EXCEPTION.OVER.BOUNDARY as follows, as it could lead to non caught exception or crash:

app.c:5 CERT.EXCEPTION.OVER.BOUNDARY
Function 'main' calling throwing function 'library_foo' over execution boundary
* library.cpp:3: 'library_foo' defined here

Fixed code example

Copy
// library.h
#pragma once
#ifdef __cplusplus
extern "C" {
#endif

int library_foo(int i);
#ifdef __cplusplus
}
#endif

// library.cpp
#include "library.h"

extern "C" int library_foo(int i)
{
  return i > 1 ? 42 : 0;
}

// app.c
#include "library.h"

int main() {
  return library_foo(1);
}

Here, the return code is used instead of exception.