Visitar URL original
General issue (No source was seen and extracted) · Issue #10132 · github/codeql · GitHub
The Wayback Machine - https://web.archive.org/web/20240324153151/https://github.com/github/codeql/issues/10132
Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

General issue (No source was seen and extracted) #10132

Closed
FaiqueAli opened this issue Aug 22, 2022 · 62 comments
Closed

General issue (No source was seen and extracted) #10132

FaiqueAli opened this issue Aug 22, 2022 · 62 comments
Labels
question Further information is requested

Comments

@FaiqueAli
Copy link

Hi,
i am trying to use codeql cli in my cpp project and trying to create a database file in a docker container.
but I am getting this issue
No source code was seen and extracted to C:\xxx.
This can occur if the specified build commands failed to compile or process any code.

  • For codebases written in Go, JavaScript, TypeScript, and Python, do not specify
    an explicit --command.
  • For other languages, the --command must specify a "clean" build which compiles
    all the source code files without reusing existing build artefacts.

I am using the GNU MinGW compiler to compile my code.
the commands are using the script(.bat) file

cmake -G "MSYS Makefiles" ../
make

waiting for good response :)

@FaiqueAli FaiqueAli added the question Further information is requested label Aug 22, 2022
@aibaars
Copy link
Contributor

aibaars commented Aug 23, 2022

The CodeQL C/C++ analyser tracks which source files are compiled during the build process. The error message says that CodeQL somehow did not "see" any source files. This can have various causes:

  • CodeQL did not detect any compiler commands (such as gcc.exe)
  • CodeQL failed to parse the source files (or its included files)
  • Source files were found and parsed but they were not in the expected source location.

Could you have a look at codeql-database.yml in the database folder? There should be a property named sourceLocationPrefix.

Could you have a look in the src.zip file in the database folder? This file contains copies of the source files that CodeQL analysed. If there are files but the folder structure does not match the sourceLocationPrefix, then you could try to adjust the sourceLocationPrefix (-s, --source-root flag to codeql database create).

If there are few (or no) files in the zip file then CodeQL likely failed to detect the compiler calls. In this case you best have a look at the log/build-tracer.log file in the database folder.

@FaiqueAli
Copy link
Author

thank you for the valuable information,
after analyzing the > codeql-database.yml file I found the property > sourceLocationPrefix with the correct codebase path (c:/xxx), but I did not find any src.zip file in the database folder (c:/xxx/codeqldb).

any idea?

@aibaars
Copy link
Contributor

aibaars commented Aug 24, 2022

thank you for the valuable information, after analyzing the > codeql-database.yml file I found the property > sourceLocationPrefix with the correct codebase path (c:/xxx), but I did not find any src.zip file in the database folder (c:/xxx/codeqldb).

any idea?

Apologies, the src.zip is only created when there were no errors. There should, however, be a c:/xxx/codeqldb/src folder.

@FaiqueAli
Copy link
Author

This is the current structure of the database folder
image

@aibaars
Copy link
Contributor

aibaars commented Aug 24, 2022 •

Ok, in that case we should have a look in the log folder for a file named build-tracer.log . Hopefully that file contains an explanation of why things did not work at all.

One thing to check; did you run make clean or checked out a fresh copy of the repository? A common pitfall is that make won't do anything if the code has already been built, and as a result CodeQL won't "see" any compilation steps.

@FaiqueAli
Copy link
Author

I am running all the steps in docker container in the interactive mode.
I have seen build-tracer.log file, but its too long and have no idea what values should I check..
I am going to clean and give a try one more time an let you know the outcomes..

@FaiqueAli
Copy link
Author

since I am working in docker so it already has a copy of uncompiled code.
however, I also tried with make clean option and got the same result (No source code was seen...).
getting a look at the build-tracer.log file got nothing, it's just showing some repetition of steps, like in the image below..
image

@aibaars
Copy link
Contributor

aibaars commented Aug 24, 2022

The build-tracer.log file tends to be very large and repetitive and it can be a bit challenging to find the interesting parts. It would be good to look for lines like Candidate to intercept: ......\gcc.exe . For every compiler call there should also be a line containing \extractor.exe with a ton of command line arguments. Lines containing error: and catastrophic error are also interesting.

If you are comfortable sharing the contents of the build-tracer.log file (please zip it first) then you can attach it to the issue. The log file should not contain any source code, but it does contain file paths of commands and source files.

@FaiqueAli
Copy link
Author

Please have a review on this attached .zip
it also contains the script I am providing to database create command.
rootfolder.zip

@aibaars
Copy link
Contributor

aibaars commented Aug 24, 2022

I found the relevant bits of the build-tracer.log . I think CodeQL could not understand the output of cc.exe --version and c++.exe --version . I'll pass it on to the team, hopefully there is an easy fix.

[T 10:02:13 1904] ==== Candidate to intercept: C:\msys64\mingw64\bin\cc.exe (1556) ====
[T 10:02:13 1904] Lua: === Intercepted call to c:\msys64\mingw64\bin\cc.exe ===
[T 10:02:13 1904] Executing the following tracer actions:
[T 10:02:13 1904] Tracer actions:
[T 10:02:13 1904] pre_invocations(0)
[T 10:02:13 1904] post_invocations(1)
[T 10:02:13 1904] invocation: C:\codeql\cpp\tools\win64\extractor.exe, args: --mimic "c:\msys64\mingw64\bin\cc.exe" --version
[T 10:02:13 1904] trace_languages(1): [cpp]
[E 10:02:13 1076] CodeQL C/C++ Extractor 2.10.3
[E 10:02:13 1076] Current directory: C:\xxx\build
[E 10:02:13 1076] Command: C:\codeql\cpp\tools\win64\extractor.exe --mimic c:\msys64\mingw64\bin\cc.exe --version
Warning: c:\msys64\mingw64\bin\cc.exe does not look like a compiler. If it is infact a compiler, please contact GitHub.
[E 10:02:14 1076] Not a compiler; exiting. Reason: --version stdout was:
cc.exe (Rev1, Built by MSYS2 project) 12.2.0

Copyright (C) 2022 Free Software Foundation, Inc.

This is free software; see the source for copying conditions.  There is NO

warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.




--version stderr was:

process exited with code 0

and

[T 10:02:14 1904] Lua: === Intercepted call to c:\msys64\mingw64\bin\c++.exe ===
[T 10:02:14 1904] Executing the following tracer actions:
[T 10:02:14 1904] Tracer actions:
[T 10:02:14 1904] pre_invocations(0)
[T 10:02:14 1904] post_invocations(1)
[T 10:02:14 1904] invocation: C:\codeql\cpp\tools\win64\extractor.exe, args: --mimic "c:\msys64\mingw64\bin\c++.exe" --version
[T 10:02:14 1904] trace_languages(1): [cpp]
[E 10:02:14 1880] CodeQL C/C++ Extractor 2.10.3
[E 10:02:14 1880] Current directory: C:\xxx\build
[E 10:02:14 1880] Command: C:\codeql\cpp\tools\win64\extractor.exe --mimic c:\msys64\mingw64\bin\c++.exe --version
Warning: c:\msys64\mingw64\bin\c++.exe does not look like a compiler. If it is infact a compiler, please contact GitHub.
[E 10:02:15 1880] Not a compiler; exiting. Reason: --version stdout was:
c++.exe (Rev1, Built by MSYS2 project) 12.2.0

Copyright (C) 2022 Free Software Foundation, Inc.

This is free software; see the source for copying conditions.  There is NO

warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.




--version stderr was:

process exited with code 0

@FaiqueAli
Copy link
Author

Thank you very much for the identification, I hope we will have some good fix.
Now waiting for the fix, in order to include codeql in my workflow.

second, I need one clarification,
In my docker file, first I am compiling my code without codeql which is a normal process before codeql integration into my workflow.
Now adding codeql in my workflow, I need to compile my code again which means I need to compile my code two times.
is there any way in which I can omit the second-time compilation?
because the codebase compilation takes time (10min to 25 min) and increases performance issues on the server.

Thanks :)

@aibaars
Copy link
Contributor

aibaars commented Aug 24, 2022

Now adding codeql in my workflow, I need to compile my code again which means I need to compile my code two times. is there any way in which I can omit the second-time compilation? because the codebase compilation takes time (10min to 25 min) and increases performance issues on the server.

You could skip the first compilation and compile your code only once with CodeQL. CodeQL shouldn't change the compilation process.

If you're using the https://github.com/github/codeql-action them you can add a codeql-action/init step before your normal build command, and add a codeql-action/analyze step right after the build step.

You can do something similar with the codeql CLI using a feature called indirect build tracing. See also: https://codeql.github.com/docs/codeql-cli/creating-codeql-databases/#using-indirect-build-tracing

@FaiqueAli
Copy link
Author

Hi aibaars,
any information about the fix?
I am waiting for your response..

Thanks:)

@aibaars
Copy link
Contributor

aibaars commented Aug 26, 2022

@FaiqueAli There is no fix yet. In the mean time, could you try switching to gcc and g++ if MSYS provides them, perhaps these commands are recognized.

@FaiqueAli
Copy link
Author

How can I switch to them?
I mean could you please guid me what is the way to do that ?
I have installed mingw-w64-x86_64-gcc compiler in my container using MSYS, I am wondering why codelql cli calling cc.exe or c++.exe.

@aibaars
Copy link
Contributor

aibaars commented Aug 26, 2022 •

@FaiqueAli I think make runs cc and c++ ; could you try the following to switch to gcc and g++ ?

cmake -G "MSYS Makefiles" -D CMAKE_CXX_COMPILER=g++  -D CMAKE_C_COMPILER=gcc  ../ 
make

@FaiqueAli
Copy link
Author

Well, I have compiled the code it has been compiled but while generating the database it pop up error..

Finalizing database at C:\xxx\DB-codeql.
A fatal error occurred: Evaluator heap must be at least 384.00 MiB

also, it seems that the compiler is not compatible with the code as it takes too much time to compile code..

Have a look at the attached log file below..
log.zip
.

@aibaars
Copy link
Contributor

aibaars commented Aug 26, 2022 •

@FaiqueAli It is normal for the compilation to get slower when running CodeQL. The CodeQL analyser is like a C compiler, so when running CodeQL actually 2 compilers are being run. Therefore a slowdown of 2-3 times the normal compilation is quite common.

The error message about the evaluator heap surprises me a little. Does this machine (or the docker container) have very little memory?

I believe if no --ram is passed to CodeQL flag it will use the JVM default heap, which I think is something like a quarter or a half of the total RAM on the machine/container. Perhaps the Dockerfile (or invocation of it) is somehow limiting the memory that can be used by container and, hence, by the CLI. Could you try adding a --ram option to the codeql database create command. I think 2048 or 4096 should be more than enough.

@FaiqueAli
Copy link
Author

FaiqueAli commented Aug 26, 2022 •

without --ram flag I am still getting the same error, infact I close all running processes and restarted my pc.

Finalizing database at C:\xxx\DB-codeql.
A fatal error occurred: Evaluator heap must be at least 384.00 MiB

having --ram flag I am getting

Invalid value for option '--ram': 'C:\\xxx\\DB-codeql' is not an int
Try codeql database create --help for usage help.

current codeql CLI create query is
RUN codeql database create --language=cpp --ram "C:\\xxx\\DB-codeql" -c "C:\\xxx\\codeql-build.bat"

@aibaars
Copy link
Contributor

aibaars commented Aug 26, 2022

@FaiqueAli you need to write something like --ram 4096

@FaiqueAli
Copy link
Author

still getting same with RUN codeql database create --language=cpp --ram 4096 "C:\\xxx\\DB-codeql" -c "C:\\xxx\\codeql-build.bat"

error :

Finalizing database at C:\xxx\DB-codeql.
A fatal error occurred: Evaluator heap must be at least 384.00 MiB

@aibaars
Copy link
Contributor

aibaars commented Aug 26, 2022

@FaiqueAli could you also add the following flag -J-Xmx1G , that should start the JVM with 1GB of heap space?

It would also be great if you could share the logs of the database create command and also add a -vvvv flag to increase verbosity. For some reason the Java JVM is started with very little heap size. Hopefully the logs will clarify why this is happening.

@FaiqueAli
Copy link
Author

Hi,
I executed the query with the said flags and finally, the database has been created I got the following message in the terminal

Finalizing database at C:\xxx\DB-codeql.
Running TRAP import for CodeQL database at C:\xxx\DB-codeql...
Writing logs to C:\xxx\DB-codeql\log\dataset-import-20220829.121409.454.log.
TRAP import complete (59.2s).
Cleaning up existing TRAP files after import...
TRAP files cleaned up (172ms).
Cleaning up scratch directory...
Scratch directory cleaned up (156ms).
Cleaning up dataset in C:\xxx\DB-codeql\db-cpp.
Trimmed disposable data from cache.
Finalizing dataset in C:\xxx\DB-codeql\db-cpp
Finished deleting ID pool from C:\xxx\DB-codeql\db-cpp (46ms).
Successfully created database at C:\xxx\DB-codeql.

is that everything normal?

Second, I can not actually change the compiler setting and build commands, so I can not use this GCC compiler as per the instruction by the team. For the time, I am trying with this solution to proceed with further steps but I am actually looking for the fixes, could you please guess how much time the codeql support team will take to provide some fix for my current compiler (cc c++)?

@aibaars
Copy link
Contributor

aibaars commented Aug 29, 2022 •

@FaiqueAli Yes, that looks all normal now. It's still a bit of a mystery why this worked so badly without the memory related flags. I guess things behave slightly differently in the docker container.

Other than their names c++.exe and g++.exe are likely the same thing. On my linux machine both are symlinks that eventually resolve to /usr/bin/x86_64-linux-gnu-gcc-9 . I suspect that CodeQL does not have explicit support the the cc and c++ commands because it assumes that both resolve to gcc and g++ . On Windows they are probably not symlinks so the CodeQL team would probably have to add explicit support.

I think the quickest work-around would be to specify an "additional tracing config" file to database create using the --extra-tracing-config` flag. See also :

codeql database create --help -v
...
Tracing options:
      --no-tracing           [Advanced] Do not trace the specified command, instead rely on it to produce all necessary data directly.
      --extra-tracing-config=<tracing-config.lua>
                             [Advanced] The path to a tracer configuration file. It may be used to modify the behaviour of the build tracer. It may be used to pick out
                               compiler processes that run as part of the build command, and trigger the execution of other tools. The extractors will provide default
                               tracer configuration files that should work in most situations.
...

I think it should be possible to tell CodeQL to "mimic" g++.exe behaviour each time it intercepts c++.exe. It think something like the following could work. This is a modified version codeql/cpp/tools/tracing-config.lua with two additional CreatePatternMatcher entries added as windowsPatterns. I don't have Windows, so I cannot check whether the changes work.

function RegisterExtraConfig(id)
    local cppExtractor = GetPlatformToolsDirectory() .. 'extractor'
    if OperatingSystem == 'windows' then
        cppExtractor = cppExtractor .. '.exe'
    end
    local windowsPatterns = {
        CreatePatternMatcher({
            '^cc%.exe$'
        }, MatchCompilerName, cppExtractor, {
            prepend = {'--mimic', '"C:\\msys64\\mingw64\\bin\\gcc.exe"'},
            order = ORDER_AFTER
        }),
        CreatePatternMatcher({
            '^c%+%+%.exe$'
        }, MatchCompilerName, cppExtractor, {
            prepend = {'--mimic', '"C:\\msys64\\mingw64\\bin\\g++.exe"'},
            order = ORDER_AFTER
        }),
        CreatePatternMatcher({
            '^cl%.exe$', '^clang%-cl%.exe$', '^.*clang.*%.exe$',
            '^.*cc.*%.exe$', '^.*++.*%.exe$', '^c51%.exe$', '^cx51%.exe$'
        }, MatchCompilerName, cppExtractor, {
            prepend = {'--mimic', '"${compiler}"'},
            order = ORDER_AFTER
        }),
        CreatePatternMatcher(
            {'^collect2%.exe$', '^ld.*%.exe$', '^.*%-ld.*%.exe$'},
            MatchCompilerName, cppExtractor, {
                prepend = {
                    '--linker', '--semmle-linker-executable', '"${compiler}"'
                },
                order = ORDER_AFTER
            }),
        CreatePatternMatcher({'^link%.exe$', '^lld%-link%.exe$'},
                             MatchCompilerName, cppExtractor, {
            prepend = {
                '--ms-linker', '--semmle-linker-executable', '"${compiler}"'
            },
            order = ORDER_AFTER
        }),
        CreatePatternMatcher({'^as%.exe$', '^.*%-as%.exe$'}, MatchCompilerName,
                             cppExtractor, {
            prepend = {
                '--assembler', '--codeql-assembler-executable', '"${compiler}"'
            },
            order = ORDER_AFTER
        })
    }
    local posixPatterns = {
        CreatePatternMatcher({'^configure$', '^do%-prebuild$'},
                             MatchCompilerName, nil, {trace = false}),
        CreatePatternMatcher({'^collect2$', '^ld.*$', '^.*%-ld.*$', '^lld.*$'},
                             MatchCompilerName, cppExtractor, {
            prepend = {'--linker', '--semmle-linker-executable', '${compiler}'},
            order = ORDER_AFTER
        }),
        CreatePatternMatcher({'^as$', '^.*%-as$'}, MatchCompilerName,
                             cppExtractor, {
            prepend = {
                '--assembler', '--codeql-assembler-executable', '${compiler}'
            },
            order = ORDER_AFTER
        }),
        CreatePatternMatcher({'^armlink$'}, MatchCompilerName, cppExtractor, {
            prepend = {
                '--arm-linker', '--semmle-linker-executable', '${compiler}'
            },
            order = ORDER_AFTER
        }),
        CreatePatternMatcher({'^.*clang.*$', '^.*cc.*$', '^.*++.*$', '^icpc$'},
                             MatchCompilerName, cppExtractor, {
            prepend = {'--mimic', '${compiler}'},
            order = ORDER_AFTER
        })
    }
    if OperatingSystem == 'windows' then
        return { cpp =  windowsPatterns } 
    else
        return { cpp =  posixPatterns } 
    end
end

-- Return a list of minimum supported versions of the configuration file format
-- return one entry per supported major version.
function GetCompatibleVersions() return {'1.0.0'} end

@FaiqueAli
Copy link
Author

Thank you for the detailed description,
You mean it is almost the same if I use g++.exe instead of cc.exe or c++.exe..
I can make amendments to my current CLI version just for testing purposes but the problem is, I am downloading codeql CLI package directly into the docker container and would be unable to modify it during the production environment.
but for the moment, I am currently uploading the .sarif file in which I am getting some trouble (created a separate issue here ) which I need to resolve first then I will try your proposed solution which could take some time to update you, or maybe we would have some fixes until then.

@aibaars
Copy link
Contributor

aibaars commented Aug 31, 2022

Glad we got #10188 sorted out.

From CodeQL's perspective using the configuration above is indeed very similar to switching to g++ and gcc during the build. The main difference is that the configuration does not actually change the compiler that is used for building the code. Instead it tells CodeQL to pretend it saw a call to gcc or g++ each time a call to cc or c++ is intercepted.

@FaiqueAli
Copy link
Author

Yes, it seems like that,
but the team development team is not happy to change their predefine compiler setting.

Anyway, as I got my .sarif file and after uploading the result to Github it shows nothing. In fact, I made some changes in code to generate some warning or failure but still, the result count is zero.

Second, I n my Github Actions there are multiple workflows being executed at the same time but I noticed in the code scanning screen in Github, it just hide/update the previous workflow, as we need to show and keep tracing on each push/ pull.

@aibaars
Copy link
Contributor

aibaars commented Aug 31, 2022

Yes, it seems like that, but the team development team is not happy to change their predefine compiler setting.

That makes sense.

Anyway, as I got my .sarif file and after uploading the result to Github it shows nothing. In fact, I made some changes in code to generate some warning or failure but still, the result count is zero.

Have you checked the contents of the SARIF file? SARIF is just JSON so you can open it in a text editor and see if there are any results. Just search for any "message" fields. An example result looks like

      "results": [
        {
          "ruleId": "com.lgtm/java-queries:java/non-sync-override",
          "ruleIndex": 0,
          "rule": {
            "id": "com.lgtm/java-queries:java/non-sync-override",
            "index": 0
          },
          "message": {
            "text": "Method 'mark' overrides a synchronized method in [org.apache.commons.io.input.ProxyInputStream](1) but is not synchronized."
          },
          "locations": [
            {
              "physicalLocation": {
                "artifactLocation": {
                  "uri": "src/main/java/org/apache/commons/io/input/MarkShieldInputStream.java",
                  "uriBaseId": "%SRCROOT%",
                  "index": 0
                },
                "region": {
                  "startLine": 50,
                  "startColumn": 17,
                  "endColumn": 21
                }
              }
            }
          ],

If there are no result entries then it is expected that CodeScanning does not show any alerts. If there are results, then

  • make sure the SARIF file was uploaded for the correct branch and commit SHA. The branch needs to be the default branch of your repository and I think the --ref flags needs to be like --ref=refs/heads/master.
  • make sure the uri fields are paths relative to the repository root folder. If they are not then CodeScanning cannot map them to files in the UI. If the uri field values are wrong then most likely you need to correct the --source-root=<dir> or -s flag for the codeql database create command

Second, I n my Github Actions there are multiple workflows being executed at the same time but I noticed in the code scanning screen in Github, it just hide/update the previous workflow, as we need to show and keep tracing on each push/ pull.

I'm not sure I understand the question. The CodeScanning screen only shows the latest run to give an idea of whether things are working.

@FaiqueAli
Copy link
Author

@FaiqueAli Yes, that looks all normal now. It's still a bit of a mystery why this worked so badly without the memory related flags. I guess things behave slightly differently in the docker container.

Other than their names c++.exe and g++.exe are likely the same thing. On my linux machine both are symlinks that eventually resolve to /usr/bin/x86_64-linux-gnu-gcc-9 . I suspect that CodeQL does not have explicit support the the cc and c++ commands because it assumes that both resolve to gcc and g++ . On Windows they are probably not symlinks so the CodeQL team would probably have to add explicit support.

I think the quickest work-around would be to specify an "additional tracing config" file to database create using the --extra-tracing-config` flag. See also :

codeql database create --help -v
...
Tracing options:
      --no-tracing           [Advanced] Do not trace the specified command, instead rely on it to produce all necessary data directly.
      --extra-tracing-config=<tracing-config.lua>
                             [Advanced] The path to a tracer configuration file. It may be used to modify the behaviour of the build tracer. It may be used to pick out
                               compiler processes that run as part of the build command, and trigger the execution of other tools. The extractors will provide default
                               tracer configuration files that should work in most situations.
...

I think it should be possible to tell CodeQL to "mimic" g++.exe behaviour each time it intercepts c++.exe. It think something like the following could work. This is a modified version codeql/cpp/tools/tracing-config.lua with two additional CreatePatternMatcher entries added as windowsPatterns. I don't have Windows, so I cannot check whether the changes work.

function RegisterExtraConfig(id)
    local cppExtractor = GetPlatformToolsDirectory() .. 'extractor'
    if OperatingSystem == 'windows' then
        cppExtractor = cppExtractor .. '.exe'
    end
    local windowsPatterns = {
        CreatePatternMatcher({
            '^cc%.exe$'
        }, MatchCompilerName, cppExtractor, {
            prepend = {'--mimic', '"gcc.exe"'},
            order = ORDER_AFTER
        }),
        CreatePatternMatcher({
            '^c%+%+%.exe$'
        }, MatchCompilerName, cppExtractor, {
            prepend = {'--mimic', '"g++.exe"'},
            order = ORDER_AFTER
        }),
        CreatePatternMatcher({
            '^cl%.exe$', '^clang%-cl%.exe$', '^.*clang.*%.exe$',
            '^.*cc.*%.exe$', '^.*++.*%.exe$', '^c51%.exe$', '^cx51%.exe$'
        }, MatchCompilerName, cppExtractor, {
            prepend = {'--mimic', '"${compiler}"'},
            order = ORDER_AFTER
        }),
        CreatePatternMatcher(
            {'^collect2%.exe$', '^ld.*%.exe$', '^.*%-ld.*%.exe$'},
            MatchCompilerName, cppExtractor, {
                prepend = {
                    '--linker', '--semmle-linker-executable', '"${compiler}"'
                },
                order = ORDER_AFTER
            }),
        CreatePatternMatcher({'^link%.exe$', '^lld%-link%.exe$'},
                             MatchCompilerName, cppExtractor, {
            prepend = {
                '--ms-linker', '--semmle-linker-executable', '"${compiler}"'
            },
            order = ORDER_AFTER
        }),
        CreatePatternMatcher({'^as%.exe$', '^.*%-as%.exe$'}, MatchCompilerName,
                             cppExtractor, {
            prepend = {
                '--assembler', '--codeql-assembler-executable', '"${compiler}"'
            },
            order = ORDER_AFTER
        })
    }
    local posixPatterns = {
        CreatePatternMatcher({'^configure$', '^do%-prebuild$'},
                             MatchCompilerName, nil, {trace = false}),
        CreatePatternMatcher({'^collect2$', '^ld.*$', '^.*%-ld.*$', '^lld.*$'},
                             MatchCompilerName, cppExtractor, {
            prepend = {'--linker', '--semmle-linker-executable', '${compiler}'},
            order = ORDER_AFTER
        }),
        CreatePatternMatcher({'^as$', '^.*%-as$'}, MatchCompilerName,
                             cppExtractor, {
            prepend = {
                '--assembler', '--codeql-assembler-executable', '${compiler}'
            },
            order = ORDER_AFTER
        }),
        CreatePatternMatcher({'^armlink$'}, MatchCompilerName, cppExtractor, {
            prepend = {
                '--arm-linker', '--semmle-linker-executable', '${compiler}'
            },
            order = ORDER_AFTER
        }),
        CreatePatternMatcher({'^.*clang.*$', '^.*cc.*$', '^.*++.*$', '^icpc$'},
                             MatchCompilerName, cppExtractor, {
            prepend = {'--mimic', '${compiler}'},
            order = ORDER_AFTER
        })
    }
    if OperatingSystem == 'windows' then
        return { cpp =  windowsPatterns } 
    else
        return { cpp =  posixPatterns } 
    end
end

-- Return a list of minimum supported versions of the configuration file format
-- return one entry per supported major version.
function GetCompatibleVersions() return {'1.0.0'} end

I have applied these suggested changes and it is not working hence getting the same error

Finalizing database at C:\xxx\DB-codeql.
No source code was seen and extracted to C:\xxx\db-codeql.
This can occur if the specified build commands failed to compile or process any code.
 - Confirm that there is some source code for the specified language in the project.
 - For codebases written in Go, JavaScript, TypeScript, and Python, do not specify
   an explicit --command.
 - For other languages, the --command must specify a "clean" build which compiles
   all the source code files without reusing existing build artefacts.

@aibaars
Copy link
Contributor

aibaars commented Sep 5, 2022

I have applied these suggested changes and it is not working hence getting the same error

There is probably some mistake in the script above. I don't have Windows myself so I cannot try things out. Could you look in the build-tracer.log file for hints what went wrong? See also #10132 (comment)

@FaiqueAli
Copy link
Author

could you please have a look into the attached log file.
codeql log.zip

@aibaars
Copy link
Contributor

aibaars commented Sep 5, 2022 •

could you please have a look into the attached log file.

Sure, the relevant snippet is

[T 17:05:29 1748] ==== Candidate to intercept: C:\msys64\mingw64\bin\cc.exe (1248) ====
[T 17:05:29 1748] Lua: === Intercepted call to c:\msys64\mingw64\bin\cc.exe ===
[T 17:05:29 1748] Executing the following tracer actions:
[T 17:05:29 1748] Tracer actions:
[T 17:05:29 1748] pre_invocations(0)
[T 17:05:29 1748] post_invocations(1)
[T 17:05:29 1748] invocation: C:\codeql\cpp\tools\win64\extractor.exe, args: --mimic "gcc.exe" CMakeCCompilerId.c
[T 17:05:29 1748] trace_languages(1): [cpp]
[E 17:05:30 1396] CodeQL C/C++ Extractor 2.10.3
[E 17:05:30 1396] Current directory: C:\xxx\build\buildcpp\CMakeFiles\3.24.1\CompilerIdC
[E 17:05:30 1396] Command: C:\codeql\cpp\tools\win64\extractor.exe --mimic gcc.exe CMakeCCompilerId.c
[E 17:05:30 1396] Unknown program type; exiting.
9D47E3DE000006D4_0000000000000001 (parent C1C14BC400000264_0000000000000001)
[T 17:05:29 1248] Allocated ID 223BDB3E000004E0_0000000000000001 (parent 9D47E3DE000006D4_0000000000000001)

It looks like the Lua script actually works. The error message is different than the one before and it replaced c:\msys64\mingw64\bin\cc.exe with gcc.exe for the --mimic flag. I suppose CodeQL expects a full path and not just a command name. Could you try replacing "gcc.exe" with "c:\msys64\mingw64\bin\gcc.exe" and "g++.exe" with "c:\msys64\mingw64\bin\g++.exe" in the lua script?

@phnx
Copy link

phnx commented Sep 6, 2022

Sorry for jumping in the middle of conversation. Just want to point out a place regarding this comment.

At the moment I inserted the below c++ code, it will be better if you have some CPP initial knowledge to make some corrections in order to generate failure or if you have some web link to find CPP code that has some issue as per the codeql.

You can find snippets that could trigger some warnings from here https://codeql.github.com/codeql-query-help/cpp/.

@FaiqueAli
Copy link
Author

could you please have a look into the attached log file.

Sure, the relevant snippet is

[T 17:05:29 1748] ==== Candidate to intercept: C:\msys64\mingw64\bin\cc.exe (1248) ====
[T 17:05:29 1748] Lua: === Intercepted call to c:\msys64\mingw64\bin\cc.exe ===
[T 17:05:29 1748] Executing the following tracer actions:
[T 17:05:29 1748] Tracer actions:
[T 17:05:29 1748] pre_invocations(0)
[T 17:05:29 1748] post_invocations(1)
[T 17:05:29 1748] invocation: C:\codeql\cpp\tools\win64\extractor.exe, args: --mimic "gcc.exe" CMakeCCompilerId.c
[T 17:05:29 1748] trace_languages(1): [cpp]
[E 17:05:30 1396] CodeQL C/C++ Extractor 2.10.3
[E 17:05:30 1396] Current directory: C:\xxx\build\buildcpp\CMakeFiles\3.24.1\CompilerIdC
[E 17:05:30 1396] Command: C:\codeql\cpp\tools\win64\extractor.exe --mimic gcc.exe CMakeCCompilerId.c
[E 17:05:30 1396] Unknown program type; exiting.
9D47E3DE000006D4_0000000000000001 (parent C1C14BC400000264_0000000000000001)
[T 17:05:29 1248] Allocated ID 223BDB3E000004E0_0000000000000001 (parent 9D47E3DE000006D4_0000000000000001)

It looks like the Lua script actually works. The error message is different than the one before and it replaced c:\msys64\mingw64\bin\cc.exe with gcc.exe for the --mimic flag. I suppose CodeQL expects a full path and not just a command name. Could you try replacing "gcc.exe" with "c:\msys64\mingw64\bin\gcc.exe" and "g++.exe" with "c:\msys64\mingw64\bin\g++.exe" in the lua script?

Hi,
as per the suggestion I made the changes in the .lua script as follow,

local windowsPatterns = {
		CreatePatternMatcher({
            '^cc%.exe$'
        }, MatchCompilerName, cppExtractor, {
            prepend = {'--mimic', '"C:\\msys64\\mingw64\\bin\\gcc.exe"'},
            order = ORDER_AFTER
        }),
        CreatePatternMatcher({
            '^c%+%+%.exe$'
        }, MatchCompilerName, cppExtractor, {
            prepend = {'--mimic', '"C:\\msys64\\mingw64\\bin\\g++.exe"'},
            order = ORDER_AFTER
        }),

that works!
but my question is, we are ultimately mimicking the gcc or g++ compiler whenever there's a call from cc or c++.
then why are we updating the .lua script instead of just adding parameters in the command file -DCMAKE_CXX_COMPILER=g++ -DCMAKE_C_COMPILER=gcc ?

Second, I also tried cc.exe and c++.exe with complete paths, because these are also available in my container

local windowsPatterns = {
		CreatePatternMatcher({
            '^cc%.exe$'
        }, MatchCompilerName, cppExtractor, {
            prepend = {'--mimic', '"C:\\msys64\\mingw64\\bin\\cc.exe"'},
            order = ORDER_AFTER
        }),
        CreatePatternMatcher({
            '^c%+%+%.exe$'
        }, MatchCompilerName, cppExtractor, {
            prepend = {'--mimic', '"C:\\msys64\\mingw64\\bin\\c++.exe"'},
            order = ORDER_AFTER
        }),

but it stuck with the same error

No source code was seen and extracted to C:\xxx\DB-codeql.
This can occur if the specified build commands failed to compile or process any code.
 - Confirm that there is some source code for the specified language in the project.
 - For codebases written in Go, JavaScript, TypeScript, and Python, do not specify
   an explicit --command.
 - For other languages, the --command must specify a "clean" build which compiles
   all the source code files without reusing existing build artefacts.

@aibaars
Copy link
Contributor

aibaars commented Sep 6, 2022

but my question is, we are ultimately mimicking the gcc or g++ compiler whenever there's a call from cc or c++. then why are we updating the .lua script instead of just adding parameters in the command file -DCMAKE_CXX_COMPILER=g++ -DCMAKE_C_COMPILER=gcc ?

You mentioned:

Second, I can not actually change the compiler setting and build commands, so I can not use this GCC compiler as per the instruction by the team.

Which means that the team does not like changing the compiler using -DCMAKE_CXX_COMPILER=g++ -DCMAKE_C_COMPILER=gcc . That's why I proposed tweaking CodeQL's compiler tracing configuration (Lua script) instead.

When you set CMAKE_CXX_COMPILER=g++ then your code will be compiled using g++.exe. If you use the tweaked Lua script then your code will still be compiled using c++.exe, however, the CodeQL "extractor" for C++ is "tricked" into treating the compiler as-if you were running g++.exe.

The --mimic COMPILER tells the extractor.exe to investigate the behaviour of the COMPILER to figure out things like compiler version, C/C++ version, dialect, compiler builtins, platform architecture, etc. The extractor.exe uses this information to configure itself, so it can mimic the behaviour of the COMPILER as closely as possible when analysing the provided source file(s). As part of its "investigation" the extractor runs the compiler with the --version flag . The g++.exe compiler mentions g++ in its --version output while c++.exe mentions c++, which the extractor does not have in its list of supported compilers. I suspect that there aren't many other differences between the two compilers, so from an analysis point of view tweaking the Lua script should be fine.

I hope this clarifies things a bit.

Second, I also tried cc.exe and c++.exe with complete paths, because these are also available in my container but it stuck with the same error

yes, that is expected. The original Lua script has '"${compiler}"' which expands to the complete path of the intercepted compiler (ie '"C:\\msys64\\mingw64\\bin\\cc.exe"' and `'"C:\msys64\mingw64\bin\c++.exe"'. So, you end up with the same behaviour as the unmodified version of CodeQL.

@FaiqueAli
Copy link
Author

Ah ok, that means tweaking the Lua script, setups the things(versioning, plateform architecutre, etc) for extractor of c++ with the help of g++ configurations, at the end, it will invoke c++ COMPILER.
This is what I understand from your last comments..

@aibaars
Copy link
Contributor

aibaars commented Sep 6, 2022

Ah ok, that means tweaking the Lua script, setups the things(versioning, plateform architecutre, etc) for extractor of c++ with the help of g++ configurations, at the end, it will invoke c++ COMPILER. This is what I understand from your last comments..

Yes that is right, the original call to c++ is left unchanged, so actual compilation carries on as usual.

@FaiqueAli
Copy link
Author

Hi,
I am using the docker container and downloading codeQL directly.
The process is automated and it seems difficult to update the tracing-config.lua file in the container for different repositories.

For testing purposes, I updated the file manually and uploaded it by the container ID.
But for the automated process, therefore we need a proper package to install in a container.

Since it is more than 10 to 15 days we need to implement the process asap.
could we expect the proper package soon?

@aibaars
Copy link
Contributor

aibaars commented Sep 7, 2022

I don't expect a fiv to be included in a released package soon.

Can't you include the additional lua script in the Docker image and use the --extra-tracing-config= flag?

codeql database create --help -v
...
Tracing options:
      --no-tracing           [Advanced] Do not trace the specified command, instead rely on it to produce all necessary data directly.
      --extra-tracing-config=<tracing-config.lua>
                             [Advanced] The path to a tracer configuration file. It may be used to modify the behaviour of the build tracer. It may be used to pick out
                               compiler processes that run as part of the build command, and trigger the execution of other tools. The extractors will provide default
                               tracer configuration files that should work in most situations.
...

See also #10132 (comment)

@FaiqueAli
Copy link
Author

In order to avail of this option, I need to include tracing-config.lua file into each git repository which I don't think will be allowed by the teams.
If I include the file it will also be super easy to update the orginal file at the installation location.

@aibaars
Copy link
Contributor

aibaars commented Sep 8, 2022

In order to avail of this option, I need to include tracing-config.lua file into each git repository which I don't think will be allowed by the teams.

I understand, it would also be tricky to maintain. Having to update that file in all repositories if you need to make a change to the configuration would be a hassle. That's why I suggested including the file in a custom docker image. Not sure if that is possible for your use-case. With file approach all repositories can use the same docker image, which should be easier to maintain.

@FaiqueAli
Copy link
Author

FaiqueAli commented Sep 8, 2022 •

Each repo has its own docker files according to project configurations. To include tracing-config.lua in the docker configuration, I need to include tracing-config.lua file in each project along with the docker file. Because there is no common docker file for all projects.
So, it seems it doesn't suites in my case mean while I am trying to convince teams to go with (-DCMAKE_CXX_COMPILER=g++) external flag.

@aibaars
Copy link
Contributor

aibaars commented Sep 8, 2022

Thanks for clarifying. I had hoped there was at least some shared base image that all projects were using. In that case the best short-term solution would be to use the -DCMAKE_CXX_COMPILER=g++ flags for the CodeQL analysis commands. For other CI tasks the team can still use their normal build commands. I understand they do not want to change their build configurations for all tasks, but making an exception for the CodeQL analysis task is hopefully fine.

@FaiqueAli
Copy link
Author

FaiqueAli commented Sep 21, 2022 •

Hi Aibaars,
I have a question, we need to execute codeql in a scheduled workflow (cron job) that requires to run only through the default branch,
in this case what will be the value for the SHA --commit & branch --ref name?

@aibaars
Copy link
Contributor

aibaars commented Sep 21, 2022

Hi Aibaars, I have a question, we need to execute codeql in a scheduled workflow (cron job) that requires to run only through the default branch, in this case what will be the value for the SHA --commit & branch --ref name?

The --ref should be refs/heads/main (replace main if your default branch name is different). The --commit should be the commit SHA of the code you analyzed.

@FaiqueAli
Copy link
Author

No, I actually know how to use these.
But my question is that I only need to execute codeql on the default branch with cron job (scheduled job).
In the case of the cron job we do not have any push or pull therefore there is no --commit or SHA.
so is there any way to upload result without any --commit.
I actually tried with this (without any --commit. ) but it say it can not detect automatically please provide a --commit

@aibaars
Copy link
Contributor

aibaars commented Sep 21, 2022

I actually tried with this (without any --commit. ) but it say it can not detect automatically please provide a --commit

Are you running the codeql github upload-results command in the directory where you have the source code checked out? If no --commit is provided, then the command will try to infer it from the local repository folder.

Otherwise you need to supply a --commit flag. You can get the SHA by running git log -1 --format="%H" or git rev-parse HEAD on the local repository you just analysed.

@FaiqueAli
Copy link
Author

Are you running the codeql github upload-results command in the directory where you have the source code checked out? If no --commit is provided, then the command will try to infer it from the local repository folder.

No, I am just using a separate folder where my .sarif file is located and uploading it using the command codeql github upload-result to my GH repo. At the moment I am providing details of the github repo using the available list of parameters of this command.

Right now I am using codeql github upload-results along with --commit=${{github.sha}} in my workflow with push operation that triggers the workflow in a feature branch and works fine but for the main branch I will execute this same command in a workflow using a cron job (not pull/push) and I hope it will work with the main branch too and get latest available sha.

Secondly, in my feature branch, I got the result of codeql which shows an error(as a result of codeql analysis) but when I go to the security>code scanning tab inside github.com, it is not displaying this error.

Similarly, it counts the total lines but it is not counting the total number of user-written code, please have a look (below screen shots) and suggest something.

image

codeql-issue

Thanks :)

@aibaars
Copy link
Contributor

aibaars commented Sep 26, 2022

Right now I am using codeql github upload-results along with --commit=${{github.sha}} in my workflow with push operation that triggers the workflow in a feature branch and works fine but for the main branch I will execute this same command in a workflow using a cron job (not pull/push) and I hope it will work with the main branch too and get latest available sha.

For GitHub Actions cron jobs (schedule events) github.sha and github.ref should have the values you expect. See also: https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#schedule

Secondly, in my feature branch, I got the result of codeql which shows an error(as a result of codeql analysis) but when I go to the security>code scanning tab inside github.com, it is not displaying this error.

I assume you are talking about the Failed extractor invocations | 1 result (1 error)) | line in the image. The diagnostic output informs us about any failures in the CodeQL scanner itself. Typically these are parse errors by the tool. As a result of such an error part of a file may be skipped. A single error is not much of a problem, but if there are many then that means that CodeQL may be skipping lots of the source code, which degrades the quality of the results.

Similarly, it counts the total lines but it is not counting the total number of user-written code, please have a look (below screen shots) and suggest something.

The lines of code numbers are an indication of how many lines of code were actually analysed by CodeQL. If this number is much lower than expected then CodeQL is probably not "seeing" all of the code. A typical cause is that a build command may be compiling only a subset of the components in the repo which can be solved by providing a better build command.

The total lines of code includes both user written code (the code from the repository) as well as system header or other "library" files .

In your case the total lines of user written code looks wrong. It shouldn't be 0. The most likely cause in your case is a mismatch of the "source root" where the repository was checked out and the sourceLocationPrefix defined in the codeql-database.yml file. CodeQL uses the sourceLocationPrefix to determine which files originate from the repository folder when calculating the number of "user written" lines.

@FaiqueAli
Copy link
Author

I understand all the answers and that make scens..

regarding

In your case the total lines of user written code looks wrong. It shouldn't be 0. The most likely cause in your case is a mismatch of the "source root" where the repository was checked out and the sourceLocationPrefix defined in the codeql-database.yml file. CodeQL uses the sourceLocationPrefix to determine which files originate from the repository folder when calculating the number of "user written" lines.

So, I checked the source root in sourceLocationPrefix and yes it has only the root path C:\ not the source code path.
how can I update the value of the source root in sourceLocationPrefix?
I am writing build command from the root folder like

cmake -G 'MinGW Makefiles' -S C:\\source-folder -B C:\\source-folder\\build -DCMAKE_BUILD_TYPE=Debug -DCMAKE_CXX_COMPILER=g++

what I am getting, codeql is taking a source-path where actually the build command is being executed.
In my case, I am executing a build command from the root folder by providing the source path and build folder path to build command.

@aibaars
Copy link
Contributor

aibaars commented Sep 26, 2022

@FaiqueAli The source location prefix is set by codeql database create; the value is taken from the --source-root flag, or the current working directory if the flag is not provided. If I recall correctly you were running the analysis in a docker container. If you are "mounting" folders from the host into the container then this may need careful configuration of the source root property to avoid mismatches.

Could you have a look at the folder structure of the src.zip in the database? This folder structure should match up with the sourceLocationPrefix . I think C:\source-folder should appear in the src.zip as something like C_/source-folder .

@FaiqueAli
Copy link
Author

Yes, now I have added --source-root flag with the database create command, and it works as now it has generated some warnings and calculated user-generated lines of code.
Thank you :)

@aibaars
Copy link
Contributor

aibaars commented Sep 27, 2022

Great! Let's close this issue now. If you have any new questions, please open a new issue.

@aibaars aibaars closed this as completed Sep 27, 2022
@jketema
Copy link
Contributor

jketema commented Oct 14, 2022

Small follow up: the detection of cc.exe and c++.exe is fixed internally and should land in the next version of CodeQL that will be released (in a few weeks time).

@FaiqueAli
Copy link
Author

Small follow up: the detection of cc.exe and c++.exe is fixed internally and should land in the next version of CodeQL that will be released (in a few weeks time).

wonderful, thanks you very much for the information :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

4 participants