How to handle cgo

I am attempting to analyze a go project which includes and compiles C code using cgo.

For example one file contains:

// #cgo CFLAGS: -g -Wall -O3
// #cgo pkg-config: gstreamer-1.0 gstreamer-audio-1.0
// #include "c_src/gst_pipeline.c"
import "C"

If I try to analyse it without the build wrapper sonar reports:

ERROR: Error during SonarScanner execution
java.lang.UnsupportedOperationException: 

The only way to get an accurate analysis of C/C++/Objective-C files is by using the SonarSource build-wrapper and setting the property "sonar.cfamily.build-wrapper-output" or by using Clang Compilation Database and setting the property "sonar.cfamily.compile-commands". None of these two options were specified.

If you don't want to analyze C/C++/Objective-C files, then prevent them from being analyzed by setting the following properties:

    sonar.c.file.suffixes=-
    sonar.cpp.file.suffixes=-
    sonar.objc.file.suffixes=-

However if I use the build wrapper compilation by cgo does not show up and sonar reports:

java.lang.IllegalStateException: The "build-wrapper-dump.json" file was found empty. Please make sure 
that:
  * you are using the latest version of the build-wrapper and the CFamily analyzer
  * your compiler is supported
  * you are wrapping your build correctly
  * you are wrapping a full/clean build
  * if you are building your project inside a Docker container, build-wrapper is wrapping the build process inside the container and not wrapping the external Docker process

I am not sure how to resolve this. Can you help?

As far as I know golang does not support a compilation database - x/tools/gopls: support something like `compile_commands.json` · Issue #36995 · golang/go · GitHub

Possible solutions or workarounds I can think of:

  • Find a way to specifically list C files to be analysed by sonar (I do not know of one)
  • add build scripts to build the C outside of go purely for sonar’s benefit - annoying but doable
  • manually create a fake compile commands .json for sonar

If I run strace -f on go build. I can see that the C files are used and use of gcc files.
There are clear exec’s of gcc.
The exec’s of gcc explicitly reference the C files.

Interesting aside here I need to run strace with sudo or the go build fails

go clean -cache: unlinkat /tmp/00: operation not permitted
rm: cannot remove 'myProgramNameHere': No such file or directory
need to run as root or suid

Hello @KantarBruceAdams,

First, thanks for the very clear report and all the details you provided. It’s really appreciated.

This underlying issue is captured in [CPP-2372] - Jira.

Some workarounds were suggested here GO+C: Empty build-wrapper-dump.json - #2 by JolyLoic, but they are essentially the same as you mentioned, I’m afraid.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.