Repository: airbus-seclab/c-compiler-security
Branch: master
Commit: e646a72d73f8
Files: 8
Total size: 57.3 KB
Directory structure:
gitextract_elvdvo3q/
├── LICENSE
├── README.md
├── _config.yml
├── c++.md
├── clang_compilation.md
├── gcc_compilation.md
├── gcc_copt_inclusions.py
└── msvc_compilation.md
================================================
FILE CONTENTS
================================================
================================================
FILE: LICENSE
================================================
Attribution-ShareAlike 4.0 International
=======================================================================
Creative Commons Corporation ("Creative Commons") is not a law firm and
does not provide legal services or legal advice. Distribution of
Creative Commons public licenses does not create a lawyer-client or
other relationship. Creative Commons makes its licenses and related
information available on an "as-is" basis. Creative Commons gives no
warranties regarding its licenses, any material licensed under their
terms and conditions, or any related information. Creative Commons
disclaims all liability for damages resulting from their use to the
fullest extent possible.
Using Creative Commons Public Licenses
Creative Commons public licenses provide a standard set of terms and
conditions that creators and other rights holders may use to share
original works of authorship and other material subject to copyright
and certain other rights specified in the public license below. The
following considerations are for informational purposes only, are not
exhaustive, and do not form part of our licenses.
Considerations for licensors: Our public licenses are
intended for use by those authorized to give the public
permission to use material in ways otherwise restricted by
copyright and certain other rights. Our licenses are
irrevocable. Licensors should read and understand the terms
and conditions of the license they choose before applying it.
Licensors should also secure all rights necessary before
applying our licenses so that the public can reuse the
material as expected. Licensors should clearly mark any
material not subject to the license. This includes other CC-
licensed material, or material used under an exception or
limitation to copyright. More considerations for licensors:
wiki.creativecommons.org/Considerations_for_licensors
Considerations for the public: By using one of our public
licenses, a licensor grants the public permission to use the
licensed material under specified terms and conditions. If
the licensor's permission is not necessary for any reason--for
example, because of any applicable exception or limitation to
copyright--then that use is not regulated by the license. Our
licenses grant only permissions under copyright and certain
other rights that a licensor has authority to grant. Use of
the licensed material may still be restricted for other
reasons, including because others have copyright or other
rights in the material. A licensor may make special requests,
such as asking that all changes be marked or described.
Although not required by our licenses, you are encouraged to
respect those requests where reasonable. More_considerations
for the public:
wiki.creativecommons.org/Considerations_for_licensees
=======================================================================
Creative Commons Attribution-ShareAlike 4.0 International Public
License
By exercising the Licensed Rights (defined below), You accept and agree
to be bound by the terms and conditions of this Creative Commons
Attribution-ShareAlike 4.0 International Public License ("Public
License"). To the extent this Public License may be interpreted as a
contract, You are granted the Licensed Rights in consideration of Your
acceptance of these terms and conditions, and the Licensor grants You
such rights in consideration of benefits the Licensor receives from
making the Licensed Material available under these terms and
conditions.
Section 1 -- Definitions.
a. Adapted Material means material subject to Copyright and Similar
Rights that is derived from or based upon the Licensed Material
and in which the Licensed Material is translated, altered,
arranged, transformed, or otherwise modified in a manner requiring
permission under the Copyright and Similar Rights held by the
Licensor. For purposes of this Public License, where the Licensed
Material is a musical work, performance, or sound recording,
Adapted Material is always produced where the Licensed Material is
synched in timed relation with a moving image.
b. Adapter's License means the license You apply to Your Copyright
and Similar Rights in Your contributions to Adapted Material in
accordance with the terms and conditions of this Public License.
c. BY-SA Compatible License means a license listed at
creativecommons.org/compatiblelicenses, approved by Creative
Commons as essentially the equivalent of this Public License.
d. Copyright and Similar Rights means copyright and/or similar rights
closely related to copyright including, without limitation,
performance, broadcast, sound recording, and Sui Generis Database
Rights, without regard to how the rights are labeled or
categorized. For purposes of this Public License, the rights
specified in Section 2(b)(1)-(2) are not Copyright and Similar
Rights.
e. Effective Technological Measures means those measures that, in the
absence of proper authority, may not be circumvented under laws
fulfilling obligations under Article 11 of the WIPO Copyright
Treaty adopted on December 20, 1996, and/or similar international
agreements.
f. Exceptions and Limitations means fair use, fair dealing, and/or
any other exception or limitation to Copyright and Similar Rights
that applies to Your use of the Licensed Material.
g. License Elements means the license attributes listed in the name
of a Creative Commons Public License. The License Elements of this
Public License are Attribution and ShareAlike.
h. Licensed Material means the artistic or literary work, database,
or other material to which the Licensor applied this Public
License.
i. Licensed Rights means the rights granted to You subject to the
terms and conditions of this Public License, which are limited to
all Copyright and Similar Rights that apply to Your use of the
Licensed Material and that the Licensor has authority to license.
j. Licensor means the individual(s) or entity(ies) granting rights
under this Public License.
k. Share means to provide material to the public by any means or
process that requires permission under the Licensed Rights, such
as reproduction, public display, public performance, distribution,
dissemination, communication, or importation, and to make material
available to the public including in ways that members of the
public may access the material from a place and at a time
individually chosen by them.
l. Sui Generis Database Rights means rights other than copyright
resulting from Directive 96/9/EC of the European Parliament and of
the Council of 11 March 1996 on the legal protection of databases,
as amended and/or succeeded, as well as other essentially
equivalent rights anywhere in the world.
m. You means the individual or entity exercising the Licensed Rights
under this Public License. Your has a corresponding meaning.
Section 2 -- Scope.
a. License grant.
1. Subject to the terms and conditions of this Public License,
the Licensor hereby grants You a worldwide, royalty-free,
non-sublicensable, non-exclusive, irrevocable license to
exercise the Licensed Rights in the Licensed Material to:
a. reproduce and Share the Licensed Material, in whole or
in part; and
b. produce, reproduce, and Share Adapted Material.
2. Exceptions and Limitations. For the avoidance of doubt, where
Exceptions and Limitations apply to Your use, this Public
License does not apply, and You do not need to comply with
its terms and conditions.
3. Term. The term of this Public License is specified in Section
6(a).
4. Media and formats; technical modifications allowed. The
Licensor authorizes You to exercise the Licensed Rights in
all media and formats whether now known or hereafter created,
and to make technical modifications necessary to do so. The
Licensor waives and/or agrees not to assert any right or
authority to forbid You from making technical modifications
necessary to exercise the Licensed Rights, including
technical modifications necessary to circumvent Effective
Technological Measures. For purposes of this Public License,
simply making modifications authorized by this Section 2(a)
(4) never produces Adapted Material.
5. Downstream recipients.
a. Offer from the Licensor -- Licensed Material. Every
recipient of the Licensed Material automatically
receives an offer from the Licensor to exercise the
Licensed Rights under the terms and conditions of this
Public License.
b. Additional offer from the Licensor -- Adapted Material.
Every recipient of Adapted Material from You
automatically receives an offer from the Licensor to
exercise the Licensed Rights in the Adapted Material
under the conditions of the Adapter's License You apply.
c. No downstream restrictions. You may not offer or impose
any additional or different terms or conditions on, or
apply any Effective Technological Measures to, the
Licensed Material if doing so restricts exercise of the
Licensed Rights by any recipient of the Licensed
Material.
6. No endorsement. Nothing in this Public License constitutes or
may be construed as permission to assert or imply that You
are, or that Your use of the Licensed Material is, connected
with, or sponsored, endorsed, or granted official status by,
the Licensor or others designated to receive attribution as
provided in Section 3(a)(1)(A)(i).
b. Other rights.
1. Moral rights, such as the right of integrity, are not
licensed under this Public License, nor are publicity,
privacy, and/or other similar personality rights; however, to
the extent possible, the Licensor waives and/or agrees not to
assert any such rights held by the Licensor to the limited
extent necessary to allow You to exercise the Licensed
Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this
Public License.
3. To the extent possible, the Licensor waives any right to
collect royalties from You for the exercise of the Licensed
Rights, whether directly or through a collecting society
under any voluntary or waivable statutory or compulsory
licensing scheme. In all other cases the Licensor expressly
reserves any right to collect such royalties.
Section 3 -- License Conditions.
Your exercise of the Licensed Rights is expressly made subject to the
following conditions.
a. Attribution.
1. If You Share the Licensed Material (including in modified
form), You must:
a. retain the following if it is supplied by the Licensor
with the Licensed Material:
i. identification of the creator(s) of the Licensed
Material and any others designated to receive
attribution, in any reasonable manner requested by
the Licensor (including by pseudonym if
designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of
warranties;
v. a URI or hyperlink to the Licensed Material to the
extent reasonably practicable;
b. indicate if You modified the Licensed Material and
retain an indication of any previous modifications; and
c. indicate the Licensed Material is licensed under this
Public License, and include the text of, or the URI or
hyperlink to, this Public License.
2. You may satisfy the conditions in Section 3(a)(1) in any
reasonable manner based on the medium, means, and context in
which You Share the Licensed Material. For example, it may be
reasonable to satisfy the conditions by providing a URI or
hyperlink to a resource that includes the required
information.
3. If requested by the Licensor, You must remove any of the
information required by Section 3(a)(1)(A) to the extent
reasonably practicable.
b. ShareAlike.
In addition to the conditions in Section 3(a), if You Share
Adapted Material You produce, the following conditions also apply.
1. The Adapter's License You apply must be a Creative Commons
license with the same License Elements, this version or
later, or a BY-SA Compatible License.
2. You must include the text of, or the URI or hyperlink to, the
Adapter's License You apply. You may satisfy this condition
in any reasonable manner based on the medium, means, and
context in which You Share Adapted Material.
3. You may not offer or impose any additional or different terms
or conditions on, or apply any Effective Technological
Measures to, Adapted Material that restrict exercise of the
rights granted under the Adapter's License You apply.
Section 4 -- Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights that
apply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
to extract, reuse, reproduce, and Share all or a substantial
portion of the contents of the database;
b. if You include all or a substantial portion of the database
contents in a database in which You have Sui Generis Database
Rights, then the database in which You have Sui Generis Database
Rights (but not its individual contents) is Adapted Material,
including for purposes of Section 3(b); and
c. You must comply with the conditions in Section 3(a) if You Share
all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does not
replace Your obligations under this Public License where the Licensed
Rights include other Copyright and Similar Rights.
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
c. The disclaimer of warranties and limitation of liability provided
above shall be interpreted in a manner that, to the extent
possible, most closely approximates an absolute disclaimer and
waiver of all liability.
Section 6 -- Term and Termination.
a. This Public License applies for the term of the Copyright and
Similar Rights licensed here. However, if You fail to comply with
this Public License, then Your rights under this Public License
terminate automatically.
b. Where Your right to use the Licensed Material has terminated under
Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided
it is cured within 30 days of Your discovery of the
violation; or
2. upon express reinstatement by the Licensor.
For the avoidance of doubt, this Section 6(b) does not affect any
right the Licensor may have to seek remedies for Your violations
of this Public License.
c. For the avoidance of doubt, the Licensor may also offer the
Licensed Material under separate terms or conditions or stop
distributing the Licensed Material at any time; however, doing so
will not terminate this Public License.
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
License.
Section 7 -- Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different
terms or conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the
Licensed Material not stated herein are separate from and
independent of the terms and conditions of this Public License.
Section 8 -- Interpretation.
a. For the avoidance of doubt, this Public License does not, and
shall not be interpreted to, reduce, limit, restrict, or impose
conditions on any use of the Licensed Material that could lawfully
be made without permission under this Public License.
b. To the extent possible, if any provision of this Public License is
deemed unenforceable, it shall be automatically reformed to the
minimum extent necessary to make it enforceable. If the provision
cannot be reformed, it shall be severed from this Public License
without affecting the enforceability of the remaining terms and
conditions.
c. No term or condition of this Public License will be waived and no
failure to comply consented to unless expressly agreed to by the
Licensor.
d. Nothing in this Public License constitutes or may be interpreted
as a limitation upon, or waiver of, any privileges and immunities
that apply to the Licensor or You, including from the legal
processes of any jurisdiction or authority.
=======================================================================
Creative Commons is not a party to its public
licenses. Notwithstanding, Creative Commons may elect to apply one of
its public licenses to material it publishes and in those instances
will be considered the “Licensor.” The text of the Creative Commons
public licenses is dedicated to the public domain under the CC0 Public
Domain Dedication. Except for the limited purpose of indicating that
material is shared under a Creative Commons public license or as
otherwise permitted by the Creative Commons policies published at
creativecommons.org/policies, Creative Commons does not authorize the
use of the trademark "Creative Commons" or any other trademark or logo
of Creative Commons without its prior written consent including,
without limitation, in connection with any unauthorized modifications
to any of its public licenses or any other arrangements,
understandings, or agreements concerning use of licensed material. For
the avoidance of doubt, this paragraph does not form part of the
public licenses.
Creative Commons may be contacted at creativecommons.org.
================================================
FILE: README.md
================================================
# Getting the maximum of your C compiler, for security
- [GCC TL;DR](#gcc-tldr)
- [Clang TL;DR](#clang-tldr)
- [Microsoft Visual Studio 2019 TL;DR](#microsoft-visual-studio-2019-tldr)
- [References](#references)
### Introduction
This guide is intended to help you determine which flags you should use to
compile your C Code using GCC, Clang or MSVC, in order to:
* detect the maximum number of bugs or potential security problems.
* enable security mitigations in the produced binaries.
* enable runtime sanitizers to detect errors (overflows, race conditions, etc.) and make fuzzing more efficient.
**Disclaimer**:
The flags selected and recommended here were chosen to *maximize* the number of
classes of detected errors which could have a security benefit when enabled.
Code generation options (such as `-fstack-protector-strong`) can also have
performance impacts. It is up to you to assess the impact on your code base
and choose the right set of command line options.
Comments are of course [welcome](https://github.com/airbus-seclab/c-compiler-security/issues).
## GCC 12 TL;DR
[Detailed page](./gcc_compilation.md)
Always use the following [warnings](./gcc_compilation.md#warnings) and [flags](./gcc_compilation.md#compilation-flags) on the command line:
```
-O2
-Werror
-Wall -Wextra -Wpedantic -Wformat=2 -Wformat-overflow=2 -Wformat-truncation=2 -Wformat-security -Wnull-dereference -Wstack-protector -Wtrampolines -Walloca -Wvla -Warray-bounds=2 -Wimplicit-fallthrough=3 -Wtraditional-conversion -Wshift-overflow=2 -Wcast-qual -Wstringop-overflow=4 -Wconversion -Warith-conversion -Wlogical-op -Wduplicated-cond -Wduplicated-branches -Wformat-signedness -Wshadow -Wstrict-overflow=4 -Wundef -Wstrict-prototypes -Wswitch-default -Wswitch-enum -Wstack-usage=1000000 -Wcast-align=strict
-D_FORTIFY_SOURCE=3
-fstack-protector-strong -fstack-clash-protection -fPIE
-fsanitize=bounds -fsanitize-undefined-trap-on-error
-Wl,-z,relro -Wl,-z,now -Wl,-z,noexecstack -Wl,-z,separate-code
```
On legacy code bases, some of the warnings may produce some false positives. On
code where the behavior is intended, pragmas can be used to disable the specific
warning locally.
Run debug/test builds with sanitizers (in addition to the flags above):
AddressSanitizer + UndefinedBehaviorSanitizer:
```
-fsanitize=address -fsanitize=pointer-compare -fsanitize=pointer-subtract -fsanitize=leak -fno-omit-frame-pointer -fsanitize=undefined -fsanitize=bounds-strict -fsanitize=float-divide-by-zero -fsanitize=float-cast-overflow
export ASAN_OPTIONS=strict_string_checks=1:detect_stack_use_after_return=1:check_initialization_order=1:strict_init_order=1:detect_invalid_pointer_pairs=2
```
If your program is multi-threaded, run with `-fsanitize=thread` (incompatible with ASan).
Finally, use [`-fanalyzer`](./gcc_compilation.md#code-analysis) to spot potential issues.
## Clang 11 TL;DR
[Detailed page](./clang_compilation.md)
First compile with:
```
-O2
-Werror
-Walloca -Wcast-qual -Wconversion -Wformat=2 -Wformat-security -Wnull-dereference -Wstack-protector -Wvla -Warray-bounds -Warray-bounds-pointer-arithmetic -Wassign-enum -Wbad-function-cast -Wconditional-uninitialized -Wconversion -Wfloat-equal -Wformat-type-confusion -Widiomatic-parentheses -Wimplicit-fallthrough -Wloop-analysis -Wpointer-arith -Wshift-sign-overflow -Wshorten-64-to-32 -Wswitch-enum -Wtautological-constant-in-range-compare -Wunreachable-code-aggressive -Wthread-safety -Wthread-safety-beta -Wcomma
-D_FORTIFY_SOURCE=3
-fstack-protector-strong -fsanitize=safe-stack -fPIE -fstack-clash-protection
-fsanitize=bounds -fsanitize-undefined-trap-on-error
-Wl,-z,relro -Wl,-z,now -Wl,-z,noexecstack -Wl,-z,separate-code
```
On legacy code bases, some of the warnings may produce some false positives. On
code where the behavior is intended, pragmas can be used to disable the specific
warning locally.
Run debug/test builds with sanitizers, in addition to the flags above (and after removing `-fsanitize=safe-stack`, which is incompatible with LeakSanitizer):
AddressSanitizer + UndefinedBehaviorSanitizer:
```
-fsanitize=address -fsanitize=leak -fno-omit-frame-pointer -fsanitize=undefined -fsanitize=float-divide-by-zero -fsanitize=float-cast-overflow -fsanitize=integer
export ASAN_OPTIONS=strict_string_checks=1:detect_stack_use_after_return=1:check_initialization_order=1:strict_init_order=1:detect_invalid_pointer_pairs=2
```
If your program is multi-threaded, run with `-fsanitize=thread` (incompatible with ASan).
Finally, use [`scan-build`](./clang_compilation.md#code-analysis) to spot potential issues.
In addition, you can build production code with `-fsanitize=integer -fsanitize-minimal-runtime -fno-sanitize-recover` to catch integer overflows.
## Microsoft Visual Studio 2019 TL;DR
[Detailed page](./msvc_compilation.md)
* Compile with `/Wall /sdl /guard:cf /guard:ehcont /CETCOMPAT`
* Use ASan with `/fsanitize=address`
* Analyze your code with `/analyze`
## Tips
* Check <https://github.com/pkolbus/compiler-warnings> to see which compiler version supports a given flag
* Use the [Compiler explorer](https://godbolt.org/) to experiment and check the impact on machine code produced
* If you have a doubt about the actual semantics of a flag, check the tests (for Clang, GCC)
* Use [checksec.py](https://github.com/Wenzel/checksec.py) to verify your binaries have mitigations
## References
* For [GCC](./gcc_compilation.md#references)
* For [Clang](./clang_compilation.md#references)
* For [MSVC](./msvc_compilation.md#references)
* <https://github.com/pkolbus/compiler-warnings>: GCC/Clang/XCode parsers for warnings definitions.
* <https://github.com/google/sanitizers/wiki/AddressSanitizerFlags>: ASan runtime options
Written by Raphaël Rigo and reviewed by Sarah Zennou @ [Airbus Security lab](https://airbus-seclab.github.io), 2021.
## Contributing
Please open an issue if you notice any error, imprecision or have comments or improvements ideas.
This work is licensed under a
[Creative Commons Attribution-ShareAlike 4.0 International License][cc-by-sa].
[cc-by-sa]: http://creativecommons.org/licenses/by-sa/4.0/
================================================
FILE: _config.yml
================================================
theme: jekyll-theme-slate
title: "Getting the maximum of your C compiler, for security"
================================================
FILE: c++.md
================================================
## C++ specific flags
*Note*: work not really started yet
### GCC/Clang
`_GLIBCXX_SANITIZE_VECTOR`
https://docs.microsoft.com/en-us/cpp/standard-library/iterators?view=msvc-160
https://clang.llvm.org/docs/ThreadSafetyAnalysis.html
================================================
FILE: clang_compilation.md
================================================
- [Warnings](#warnings)
- [Compiler flags](#compiler-flags)
- [Runtime sanitizers](#runtime-sanitizers)
- [Code analysis](#code-analysis)
- [Fuzzing](#fuzzing)
- [References](#references)
## Clang
*Note: this guide is valid for Clang 12*
Clang compiler flags are described by a domain specific language call
[TableGen](https://llvm.org/docs/TableGen/index.html), and LLVM includes a tool
called `llvm-tblgen` which parses the definition files, `DiagnosticsGroups.td` in particular.
### Warnings
While Clang thankfully provides a `-Weverything` option which enables *all*
warnings, it is [strongly](https://quuxplusone.github.io/blog/2018/12/06/dont-use-weverything/) recommended by Clang developpers *not* to use it in production...
However, they (and I) recommend using `-Weverything` to identify warnings which
are relevant for your code base and then selectively add them to your standard
warning list.
Clang supports the following warnings which are compatible with [GCC](./gcc_compilation.md#warnings):
* the obvious `-Wall`, `-Wextra`, `-Wpedantic` and `-Werror` ([Note](https://flameeyes.blog/2009/02/25/future-proof-your-code-dont-use-werror/)).
* `-Walloca`,`-Wcast-qual`,`-Wconversion`,`-Wformat=2`,`-Wformat-security`,`-Wnull-dereference`,`-Wstack-protector`,`-Wvla`.
Some other warnings are of interest for security:
* `-Wconversion`: which enables a lot of warnings related to implicit conversions, with some which are particularly interesting:
* `-Wshorten-64-to-32`: warn on 64 bits truncation (`size_t` to `int` on 64bits Linux for example).
* `-Warray-bounds`: which does not take an argument, contrary to GCC (enabled by default).
* `-Warray-bounds-pointer-arithmetic`: a more advanced version which takes pointer arithmetic into account.
* `-Wimplicit-fallthrough`: does not take an argument. Note that Clang does not parse comments and only supports `[[clang::fallthrough]]` and `__attribute__((fallthrough))` annotations.
* `-Wconditional-uninitialized`: warn if a variable may be uninitialized depending on a conditional branch.
* `-Wloop-analysis`: warn about loop variable misuse (double increment, etc.).
* `-Wshift-sign-overflow`: warn when left shift overflows into sign bit.
* `-Wswitch-enum`: warn when a switch statement does not handle all enum values.
* `-Wtautological-constant-in-range-compare`: warn about comparisons which are always `true` or `false` due to the variables value ranges. Ex: `comparison of unsigned expression < 0 is always false`.
* `-Wcomma`: warn about possible comma misuse.
* `-Wassign-enum`: integer constant not in range of enumerated type A.
* `-Wbad-function-cast`: cast from function call of type A to non-matching type B.
* `-Wfloat-equal`: comparing floating point with == or != is unsafe.
* `-Wformat-type-confusion`: format specifies type A but the argument has type B.
* `-Wpointer-arith`: various warnings related to pointer arithmetic.
* `-Widiomatic-parentheses`: using the result of an assignment as a condition without parentheses.
* `-Wunreachable-code-aggressive`: warn about unreachable code.
* `-Wthread-safety` and `-Wthread-safety-beta`: warn about potential threading/race condition issues.
*Note*: You can disable warnings for system includes by using the `-isystem`
option to specify the paths which will be used for "system" includes (`#include <file.h>`).
### Compiler flags
Clang supports various options for stack based buffer overflow protection and mitigations against control flow attacks:
* `-fstack-protector-strong` (or `-fstack-protector-all)`: enable stack cookies.
* `-fsanitize=safe-stack`: use two stacks ("safe" and "unsafe"), should not impact performance and can be combined with `-fstack-protector` [Doc](https://releases.llvm.org/12.0.0/tools/clang/docs/SafeStack.html), [Research](https://dslab.epfl.ch/research/cpi/).
* `-fsanitize=shadow-call-stack`: stronger protection which specific arch support (currently only `Aarch64`). [Doc](https://clang.llvm.org/docs/ShadowCallStack.html).
* `-fcf-protection=full|return|branch`: Generate code for [Intel CET](https://i.blackhat.com/asia-19/Thu-March-28/bh-asia-Sun-How-to-Survive-the-Hardware-Assisted-Control-Flow-Integrity-Enforcement.pdf).
* `-fsanitize=cfi`: ControlFlowIntegrity. [Doc](https://releases.llvm.org/12.0.0/tools/clang/docs/ControlFlowIntegrity.html).
Other compilation flags:
* `-fPIE`: generate position-independent code (needed for ASLR).
* `-fstack-clash-protection`: Insert code to probe each page of stack space as it is allocated to protect from [stack-clash](https://www.qualys.com/2017/06/19/stack-clash/stack-clash.txt) style attacks.
* `-ftrivial-auto-var-init=pattern`: Auto initialize variables with a random pattern, which can be costly in some cases. `=zero` option is only supported with `-enable-trivial-auto-var-init-zero-knowing-it-will-be-removed-from-clang`.
* Glibc flags: see [GCC page](./gcc_compilation.md#glibc-flags)
* Linker flags: see [GCC page](./gcc_compilation.md#linker-flags)
### Runtime sanitizers
LLVM support of sanitizers is first class, besides [`AddressSanitizer`](https://releases.llvm.org/12.0.0/tools/clang/docs/AddressSanitizer.html), [`ThreadSanitizer`](https://releases.llvm.org/12.0.0/tools/clang/docs/ThreadSanitizer.html), [`LeakSanitizer`](https://releases.llvm.org/12.0.0/tools/clang/docs/LeakSanitizer.html) and [`UndefinedBehaviorSanitizer`](https://releases.llvm.org/12.0.0/tools/clang/docs/UndefinedBehaviorSanitizer.html), which are included in [GCC](./gcc_compilation.md#runtime-sanitizers), the following are available:
* `-fsanitize=memory`: [MemorySanitizer](https://releases.llvm.org/12.0.0/tools/clang/docs/MemorySanitizer.html) is a detector of uninitialized reads.
* `-fsanitize=integer`: advanced analysis of undefined or risky integer behavior using UBSan. Note that this [enables](https://releases.llvm.org/12.0.0/tools/clang/docs/UndefinedBehaviorSanitizer.html#available-checks) detection of *legit* (per the C langage spec) detection of *unsigned* integer overflows. Instrumentation can be disabled on functions where overflowing is expected by using `__attribute__((no_sanitize("unsigned-integer-overflow")))`. Ditto with `unsigned-shift-base`.
#### Use with fuzzing
Runtime sanitizers are particularly useful when:
* running test suites,
* fuzzing code,
as they may uncover runtime errors which would not necessarily trigger a crash.
#### In production
While most sanitizers are not intended to be used in production builds, UBSan integer's checker is very interesting, as it will detect integer overflows and abort the program.
The code should be compiled with `-fsanitize=integer -fsanitize-minimal-runtime -fno-sanitize-recover`. The performance impact should be reasonable on modern CPUs (~1%). Android [enables](https://android-developers.googleblog.com/2018/06/compiler-based-security-mitigations-in.html) it in production builds for some libraries.
### Code analysis
#### Clang static analyzer
Clang has a "modern" static analyzer which can be used to analyze whole projects
and produce HTML reports of the potential problems identified by the tool.
"It implements path-sensitive, inter-procedural analysis based on symbolic execution technique."
[`scan-build`](https://clang-analyzer.llvm.org/scan-build.html) is simple to use and can wrap compilation tools such as `make`. It
will replace the `CC` and `CXX` environment variables to analyze your build and produce
the report.
```console
$ scan-build make
```
The [*default* checkers](https://releases.llvm.org/12.0.0/tools/clang/docs/analyzer/checkers.html)
are relatively few, and do not really target security, however, "alpha" (which may have many false positives) checkers related to security can be enabled by using the `-enable-checker alpha.security` CLI option.
Other interesting checkers:
* `alpha.core.CastSize`
* `alpha.core.CastToStruct`
* `alpha.core.Conversion` (it is relevant when `-Wconversion` is enabled ?)
* `alpha.core.IdenticalExpr`
* `alpha.core.PointerArithm`
* `alpha.core.PointerSub`
* `alpha.core.SizeofPtr`
* `alpha.core.TestAfterDivZero`
* `alpha.unix`, which has a bunch of useful checks
#### Others
* [`DataFlowSanitizer`](https://releases.llvm.org/12.0.0/tools/clang/docs/DataFlowSanitizerDesign.html) can be used to develop your own, application specific, code analyzer.
### Fuzzing
While fuzzing is out of scope, you should fuzz your code with [sanitizers](#runtime-sanitizers) enabled. Options include:
* [libFuzzer](https://llvm.org/docs/LibFuzzer.html) which is included in LLVM and can be easily integrated in a build/test process.
* [AFL++](https://aflplus.plus/).
### Test files
Test files are a great way to understand in detail what is and what is not
covered by a specific command line flag.
They are located in the [`clang/test`](https://github.com/llvm/llvm-project/tree/main/clang/test) directory. For example, the test for `-Wshift-count-negative` can be found in [`clang/test/Sema/warn-shift-negative.c`](https://github.com/llvm/llvm-project/blob/main/clang/test/Sema/warn-shift-negative.c):
```C
// RUN: %clang_cc1 -fsyntax-only -Wshift-count-negative -fblocks -verify %s
int f(int a) {
const int i = -1;
return a << i; // expected-warning{{shift count is negative}}
}
```
### References
* <https://releases.llvm.org/12.0.0/tools/clang/docs/DiagnosticsReference.html>: All Clang warnings listed and "documented".
* <https://releases.llvm.org/12.0.0/tools/clang/docs/index.html>: Clang documentation
* <https://copperhead.co/blog/memory-disclosure-mitigations/>: Uses of sanitizers and hardening options in Android CopperheadOs
* <https://source.android.com/devices/tech/debug/intsan>: Android use of UBSan in production builds to mitigate integer overflows.
* <https://security.googleblog.com/2019/05/queue-hardening-enhancements.html>: Information about other hardening options in Android
* <https://clang-analyzer.llvm.org/>: Doc for `scan-build`
* <https://lld.llvm.org/>: The LLVM linker documentation.
* <https://blog.quarkslab.com/clang-hardening-cheat-sheet.html>: Quarkslab recommnendations for Clang hardening flags.
================================================
FILE: gcc_compilation.md
================================================
- [Warnings](#warnings)
- [Compilation flags](#compilation-flags)
- [Runtime sanitizers](#runtime-sanitizers)
- [Code analysis](#code-analysis)
- [Fuzzing](#fuzzing)
- [Test files](#test-files)
- [References](#references)
## GCC
*Note: this guide is valid for GCC 11*
Understanding GCC flags is a *pain*. Which ones are enabled by `-Wall` or `-Wextra` is
not very easy to untangle.
The most reliable way is to parse and analyze the `commont.opt` and `c.opt`
files, which define (partially) the command line options supported by GCC.
The format is described in the GCC internals
[manual](https://gcc.gnu.org/onlinedocs/gccint/Option-file-format.html#Option-file-format),
so I've written a partial [parser](./gcc_copt_inclusions.py) which can help
identify what flags are needed.
You *should* also check the
[compiler-warnings](https://github.com/pkolbus/compiler-warnings) project, which has a real parser
for GCC, Clang and XCode.
### Warnings
Note that some warnings **depend** on some optimizations to be enabled, so I
recommend to always use `-O2`.
#### Generic
* `-Wall`: enable "most" of warnings by default.
* `-Wextra`: enable *more* warnings by default.
* `-Wpedantic`: and even more.
* `-Werror`: treat warnings as errors. *Note:* this should only be used on manual builds to [avoid](https://flameeyes.blog/2009/02/25/future-proof-your-code-dont-use-werror/) problems in the future.
#### Security warnings
* `-Wformat=2`: check for format string problems
* `-Wformat-overflow=2`: check for *printf overflow
* `-Wformat-truncation=2`: check for *nprintf potential truncation
* `-Wformat-security`: check for dangerous format specifiers in *printf (enabled by `-Wformat=2`)
* `-Wnull-dereference`: Warn if dereferencing a NULL pointer may lead to erroneous or undefined behavior
* `-Wstack-protector`: Warn when not issuing stack smashing protection for some reason
* `-Wstrict-overflow=3`: Warn when the compiler optimizes based on the assumption that signed overflow does not occur.
* `-Wtrampolines`: Warn whenever a trampoline is generated (will probably create an executable stack)
* `-Walloca` or `-Walloca-larger-than=1048576`: don't use `alloca()`, or limit it to "small" sizes
* `-Wvla` or `-Wvla-larger-than=1048576`: don't use variable length arrays, or limit them to "small" sizes
* `-Warray-bounds=2`: Warn if an array is accessed out of bounds. Note that it is very limited and will not catch some cases which may seem obvious.
* `-Wimplicit-fallthrough=3`: already added by `-Wextra`, but mentioned for reference.
* `-Wtraditional-conversion`: Warn of prototypes causing type conversions different from what would happen in the absence of prototype.
* `-Wshift-overflow=2`: Warn if left shift of a signed value overflows.
* `-Wcast-qual`: Warn about casts which discard qualifiers.
* `-Wstringop-overflow=4`: Under the control of Object Size type, warn about buffer overflow in string manipulation functions like memcpy and strcpy.
* `-Wconversion`: Warn for implicit type conversions that may change a value. *Note*: will probably introduce lots of warnings.
* `-Warith-conversion`: Warn if conversion of the result of arithmetic might change the value even though converting the operands cannot. *Note*: will probably introduce lots of warnings.
Those are not really security options per se, but will catch some logical errors:
* `-Wlogical-op`: Warn when a logical operator is suspiciously always evaluating to true or false.
* `-Wduplicated-cond`: Warn about duplicated conditions in an if-else-if chain.
* `-Wduplicated-branches`: Warn about duplicated branches in if-else statements.
*Note*: You can disable warnings for system includes by using the `-isystem`
option to specify the paths which will be used for "system" includes (`#include <file.h>`).
##### GCC 12
GCC 12 [introduced](https://github.com/trou/compiler-warnings/blob/gcc-12/gcc/warnings-diff-11-12.txt) new warnings which are relevant for security:
* `-Wdangling-pointer=2` (enabled by `-Wall`) which checks if pointers still refer to "dead" variables.
* `-Wtrivial-auto-var-init`, to be used with `-ftrivial-auto-var-init` to warn about unhandled cases
* `-Wuse-after-free=3`, obviously warns about use-after-free.
#### Extra flags
* `-Wformat-signedness`: Warn (in format functions) about sign mismatches between the format specifiers and actual parameters.
* `-Wshadow`: Warn when one variable shadows another. Same as `-Wshadow=global`.
* `-Wstrict-overflow=4` (or 5): Warn in more cases.
* `-Wundef`: Warn if an undefined macro is used in an `#if` directive.
* `-Wstrict-prototypes`: Warn about unprototyped function declarations.
* `-Wswitch-default`: Warn about enumerated switches missing a `default:` statement.
* `-Wswitch-enum`: Warn about all enumerated switches missing a specific case.
* `-Wstack-usage=<byte-size>`: Warn if stack usage might exceed `<byte-size>`.
* `-Wcast-align=strict`: Warn about pointer casts which increase alignment.
* `-Wjump-misses-init`: Warn when a jump misses a variable initialization.
### Compilation flags
* `-fstack-protector-strong`: add stack cookie checks to functions with stack buffers or pointers.
* `-fstack-clash-protection`: Insert code to probe each page of stack space as it is allocated to protect from [stack-clash](https://www.qualys.com/2017/06/19/stack-clash/stack-clash.txt) style attacks.
* `-fPIE`: generate position-independent code (needed for ASLR).
* `-fcf-protection=full|return|branch`: Generate code for [Intel CET](https://i.blackhat.com/asia-19/Thu-March-28/bh-asia-Sun-How-to-Survive-the-Hardware-Assisted-Control-Flow-Integrity-Enforcement.pdf).
Starting with GCC 12:
* `-ftrivial-auto-var-init=zero` will initalize all uninitialized variables to zero.
#### Glibc flags
* `-D_FORTIFY_SOURCE=2` will enable additional security features of the GNU libc when calling memory and string handling functions [Ref](https://man7.org/linux/man-pages/man7/feature_test_macros.7.html).
Starting with GCC 12:
* `-D_FORTIFY_SOURCE=3` will try to detect overflows in variable length variables.
#### Linker flags
* `-Wl,-z,relro`: make the GOT read-only ([Ref](https://www.redhat.com/en/blog/hardening-elf-binaries-using-relocation-read-only-relro)).
* `-Wl,-z,now`: disable lazy binding, making the PLT read-only.
* `-Wl,-z,noexecstack`: Marks the object as not requiring executable stack.
* `-Wl,-z,separate-code`: separate code from data (default on since binutils 2.31).
### Runtime sanitizers
GCC supports various *runtime* sanitizers, which are enabled by the `-fsanitize` flags, which are often not compatible and thus must be run separately.
* `address`: AddressSanitizer, with extra options available:
* `pointer-compare`: Instrument comparison operation with pointer operands. Must be enabled at runtime by using `detect_invalid_pointer_pairs=2` in the `ASAN_OPTIONS` environment var.
* `pointer-subtract`: Instrument subtraction with pointer operands. Must be enabled at runtime by using `detect_invalid_pointer_pairs=2` in the `ASAN_OPTIONS` environment var.
* `ASAN_OPTIONS=strict_string_checks=1:detect_stack_use_after_return=1:check_initialization_order=1:strict_init_order=1`
* `thread`: ThreadSanitizer, a data race detector.
* `leak`: memory leak detector for programs which override `malloc` and other allocators.
* `undefined`: UndefinedBehaviorSanitizer. Checks not enabled by default (GCC 11):
* `-fsanitize=bounds-strict`
* `-fsanitize=float-divide-by-zero`
* `-fsanitize=float-cast-overflow`
`kernel-address` also exists and enables AddressSanitizer for the Linux kernel.
### Code analysis
GCC 10 [introduced](https://developers.redhat.com/blog/2020/03/26/static-analysis-in-gcc-10)
the `-fanalyzer` static code analysis tool, which was vastly [improved](https://developers.redhat.com/blog/2021/01/28/static-analysis-updates-in-gcc-11) in GCC 11, and [again](https://developers.redhat.com/articles/2022/04/12/state-static-analysis-gcc-12-compiler#uncovering_uninitialized_values) in GCC 12.
It tries to detect memory management issues (double free, use after free,
etc.), pointers-related problems, etc.
It *is* costly and slows down compilation and also exhibits false positives, so
its use may not always be practical.
### Fuzzing
While fuzzing is out of scope, you should use [AFL++](https://aflplus.plus/) to
fuzz your code, with [sanitizers](#runtime-sanitizers) enabled.
### Test files
Test files are a great way to understand in detail what is and what is not
covered by a specific command line flag.
They are located in the
[gcc/testsuite](https://gcc.gnu.org/git/?p=gcc.git;a=tree;f=gcc/testsuite;hb=HEAD)
directory, and in the
[gcc/testsuite/c-c++-common](https://gcc.gnu.org/git/?p=gcc.git;a=tree;f=gcc/testsuite/c-c%2B%2B-common;hb=HEAD)
and
[gcc/testsuite/gcc.dg](https://gcc.gnu.org/git/?p=gcc.git;a=tree;f=gcc/testsuite/gcc.dg;hb=HEAD)
subdirectories in particular.
For example, the test suite for the `-Walloca-larger-than` flag can be found in the following files:
```
gcc.dg/Walloca-larger-than-2.c
gcc.dg/Walloca-larger-than-3.c
gcc.dg/Walloca-larger-than-3.h
gcc.dg/Walloca-larger-than.c
```
`Walloca-larger-than.c` gives some insights on how the option behaves in practice:
```C
/* PR middle-end/82063 - issues with arguments enabled by -Wall
{ dg-do compile }
{ dg-require-effective-target alloca }
{ dg-options "-O2 -Walloca-larger-than=0 -Wvla-larger-than=0 -ftrack-macro-expansion=0" } */
extern void* alloca (__SIZE_TYPE__);
void sink (void*);
#define T(x) sink (x)
void test_alloca (void)
{
/* Verify that alloca(0) is diagnosed even if the limit is zero. */
T (alloca (0)); /* { dg-warning "argument to .alloca. is zero" } */
T (alloca (1)); /* { dg-warning "argument to .alloca. is too large" } */
}
void test_vla (unsigned n)
{
/* VLAs smaller than 32 bytes are optimized into ordinary arrays. */
if (n < 1 || 99 < n)
n = 1;
char a[n]; /* { dg-warning "argument to variable-length array " } */
T (a);
}
```
### References
* <https://developers.redhat.com/blog/2020/03/26/static-analysis-in-gcc-10>
* <https://developers.redhat.com/blog/2021/01/28/static-analysis-updates-in-gcc-11>
* <https://developers.redhat.com/blog/2017/02/22/memory-error-detection-using-gcc>
* <https://github.com/google/sanitizers/wiki/AddressSanitizerFlags>
* <https://sudonull.com/post/6959-ld-z-separate-code>: Description of the `separate-code` option of the GNU linker.
* <https://codeforces.com/blog/entry/15547>: Describes some lesser known flags
================================================
FILE: gcc_copt_inclusions.py
================================================
#!/usr/bin/env python3
# https://gcc.gnu.org/onlinedocs/gccint/Option-file-format.html#Option-file-format
import argparse
import sys
import logging
import re
from enum import Enum
languages = []
class State(Enum):
INIT = 1
LANGUAGE = 2
ENUM = 3
ENUM_VALUE = 4
OPTION = 5
OPTION_HELP = 6
IGNORE = 1000
def parse_properties_string(s):
res = {}
r = re.compile(r"([^( ]+(?:\(.*?\))?)")
name_val_r = re.compile(r"([^( ]+)(\(.*?\))?")
try:
for v in r.findall(s):
k, v = name_val_r.search(v).groups()
if v:
res[k] = v[1:-1]
else:
res[k] = None
except TypeError as e:
raise RuntimeError("Invalid properties string: "+s) from e
return res
class GCCOption():
def __init__(self, name, props):
self.name = name
self.raw_props = props.strip("\n ")
self.props = parse_properties_string(props)
self.aliases = []
self.enabled_by = []
self.enables = []
self.help = ""
self.langs = self.props.get("LangEnabledBy", "").split(',')[0].split(' ') or []
def __str__(self):
return "-%s {%r}" % (self.name, self.props)
def __repr__(self):
return str(self)
def is_valid_for_lang(self, lang):
return "Common" in self.props.keys() or lang in self.langs
def is_warning(self):
return not self.is_alias() and "Warning" in self.props.keys()
def is_alias(self):
return "Alias" in self.props.keys()
def get_alias_target(self):
if self.is_alias():
return self.props['Alias'].split(',')[0]
return None
def is_enabled_by(self):
keys = self.props.keys()
return "EnabledBy" in keys or "LangEnabledBy" in keys
def is_by_default(self):
# TODO: less hackish
return "Var(" in self.raw_props and "Init(1)" in self.raw_props and "Range" not in self.raw_props
def get_enabled_by(self):
# TODO: handle && and ||
res = []
if "EnabledBy" in self.props.keys():
res.append(self.props['EnabledBy'])
if "LangEnabledBy" in self.props.keys():
lang_args = self.props['LangEnabledBy'].split(',')
if len(lang_args) > 2:
lang_args = lang_args[0:2]
if len(lang_args) > 1:
langs, opt = lang_args
res.append(opt.strip(' '))
if res:
return res
return None
def pretty_print(self):
print("Option:", self.name, "[DEFAULT ON]" if self.is_by_default() else "")
if self.is_alias():
print("\tAlias:", self.props["Alias"])
if self.is_enabled_by():
e = self.props.get('EnabledBy', None)
if e:
print("\tEnabledBy", e)
e = self.props.get('LangEnabledBy', None)
if e:
print("\tLangEnabledBy", e)
if self.enables:
print("\tEnables:", ", ".join(self.enables))
print("\tHelp:", self.help)#.rstrip())
print("\t"+self.raw_props)
class GCCEnum():
def __init__(self, s):
enum_info = parse_properties_string(s)
self.__name__ = enum_info['Name']
self.__type__ = enum_info['Type']
self.values = {}
def __str__(self):
return "Enum: %s / %s {%r}" % (self.__name__, self.__type__, self.values)
def __repr__(self):
return str(self)
parser = argparse.ArgumentParser(description='Parse GCC option definition file (.opt)')
parser.add_argument('file', help='The file to parse')
parser.add_argument('arg', nargs='*', help='Arg to display details of')
parser.add_argument('--warn-not-enabled', action='store_true', help="List warnings not enabled by -Wall and -Wextra")
parser.add_argument('--lang', help="Restrict to this language")
parser.add_argument('-v', '--verbose', action='store_true', help='verbose operations')
args = parser.parse_args()
if args.verbose:
logging.basicConfig(level=logging.DEBUG)
state = State.INIT
current_option = None
Ignored_options = ['TargetSave', 'Variable', 'TargetVariable', 'HeaderInclude', 'SourceInclude']
enums = {}
options = {}
with open(args.file, "r") as f:
for l in f.readlines():
l = l.rstrip("\n")
logging.debug("State : %r, current_option: '%s', line: '%s'", state, current_option, l)
# Skip comment
if len(l) and l[0] == ";":
continue
# Empty line, reset State
if l == "":
state = State.INIT
current_option = None
continue
if state == State.INIT:
if l in Ignored_options:
state = State.IGNORE
elif l == "Language":
state = State.LANGUAGE
elif l == "Enum":
state = State.ENUM
elif l == "EnumValue":
state = State.ENUM_VALUE
else:
state = State.OPTION
current_option = l
elif state in (State.IGNORE, ):
logging.debug("Ignoring line")
# Ignore line
continue
elif state == State.OPTION_HELP:
options[current_option].help += l
elif state == State.LANGUAGE:
logging.debug('New language: %s',l)
languages.append(l)
elif state == State.ENUM:
new_enum = GCCEnum(l)
logging.debug('New Enum: %s',new_enum)
enums[new_enum.__name__] = new_enum
elif state == State.ENUM_VALUE:
enum_value_info = parse_properties_string(l)
enum_name = enum_value_info['Enum']
enums[enum_name].values[enum_value_info['String']] = enum_value_info['Value']
elif state == State.OPTION:
# Skip already defined options
# TODO: check which definition is the best ?
if current_option not in options:
opt = GCCOption(current_option, l)
logging.debug("%r", opt)
options[current_option] = opt
state = State.OPTION_HELP
else:
state = State.IGNORE
else:
raise RuntimeError("Invalid STATE "+str(state))
# Consolidate options
for name, opt in options.items():
# Aliases are added to the real option, then deleted
alias_target = opt.get_alias_target()
if alias_target:
try:
options[alias_target].aliases.append(name)
except KeyError:
print(f"Error: could not find Alias target '{alias_target}', check for typo")
sys.exit(1)
continue
enabled_by = opt.get_enabled_by()
if enabled_by:
for en in enabled_by:
if "&&" not in en and "||" not in en:
options[en].enables.append(name)
def get_enabled_by_recursive(opt, res=[]):
if opt.is_enabled_by():
en_by = opt.get_enabled_by()
for o in en_by:
res.append(o)
if "&&" not in o and "||" not in o:
get_enabled_by_recursive(options[o], res)
return res
return res
if args.warn_not_enabled:
for name, opt in options.items():
if opt.is_warning() and not opt.is_by_default() and name not in ("Wextra", "Wall"):
if opt.is_enabled_by():
en_by = get_enabled_by_recursive(opt)
if "Wextra" in en_by or "Wall" in en_by:
continue
opt.pretty_print()
else:
for arg in args.arg:
p = re.compile(arg)
for found_opt in filter(lambda x: p.match(x), options.keys()):
options[found_opt].pretty_print()
================================================
FILE: msvc_compilation.md
================================================
- [Warnings](#warnings)
- [Compilation flags](#compilation-flags)
- [Code analysis](#code-analysis)
- [Sanitizers](#sanitizers)
- [References](#references)
## Microsoft Visual Studio (2019)
As I am not running Windows, this section is less precise. But recent versions
of Visual Studio support using Clang as a compiler, so all the Clang options
apply.
### Note about the GUI
The flags described here are those you can set on the command line. Some options can be changed directly in the GUI.
Check the following documentation pages for reference:
* C/C++ project [properties](https://docs.microsoft.com/en-us/cpp/build/reference/c-cpp-prop-page?view=msvc-160)
* Linker [properties](https://docs.microsoft.com/en-us/cpp/build/reference/linker-property-pages?view=msvc-160)
* Setting [project properties](https://docs.microsoft.com/en-us/cpp/build/working-with-project-properties?view=msvc-160)
### Warnings
*All* warnings can be enabled by using the `/Wall` option, as documented [](https://docs.microsoft.com/en-us/cpp/preprocessor/compiler-warnings-that-are-off-by-default?view=msvc-160).
*Note*: The `/W4` option does **not** enable all "level 4" warnings: `/W4 displays level 1, level 2, and level 3 warnings, and all level 4 (informational) warnings that aren't off by default.`. So, you have to use `/Wall` and disable the ones that are not relevant.
As with GCC and Clang, MSVC supports disabling warnings for "external" headers, by using the `/external` option, documented [here](https://docs.microsoft.com/en-us/cpp/build/reference/external-external-headers-diagnostics?view=msvc-160). For example: `/external:anglebrackets /external:W3` will lower warnings to `W3` for headers included through `<>`.
### Compilation flags
* `/GS`: Checks buffer security [doc](https://docs.microsoft.com/en-us/cpp/build/reference/gs-buffer-security-check?view=msvc-160) (on by default).
* `/sdl`: enables "Strict mode" for `/GS` and additional checks. [doc](https://docs.microsoft.com/en-us/cpp/build/reference/sdl-enable-additional-security-checks?view=msvc-160)
* `/DYNAMICBASE`: Generate PIE code for ASLR (default on for recent).
* `/HIGHENTROPYVA`: High entropy ASLR for 64 bits targets (default on).
* `/SAFESEH`: Safe Structured Exception Handlers (x86 only) [doc](https://docs.microsoft.com/en-us/cpp/build/reference/safeseh-image-has-safe-exception-handlers?view=msvc-160)
* `/guard:cf`
* `/guard:ehcont`
* `/CETCOMPAT`: Mark the binary as compatible with Intel CET. [doc](https://docs.microsoft.com/en-us/cpp/build/reference/cetcompat?view=msvc-160).
* `/QSpectre` and `/Qspectre-load` can be used to produce code which mitigates the Spectre vulnerabilities on Intel and AMD. Read the [doc](https://docs.microsoft.com/en-us/cpp/build/reference/qspectre?view=msvc-160) before enabling.
### Code analysis
Recent versions of Visual Studio support "Code Analysis", as documented here: <https://docs.microsoft.com/en-us/cpp/code-quality/code-analysis-for-c-cpp-overview?view=msvc-160>
`/analyze`
### Sanitizers
Visual Studio 2019 introduced support for ASan, documented here: <https://docs.microsoft.com/en-us/cpp/sanitizers/?view=msvc-160>
The `/fsanitize` command line option is documented here: <https://docs.microsoft.com/en-us/cpp/build/reference/fsanitize?view=msvc-160>
Runtime checks (for debug builds): <https://docs.microsoft.com/en-us/cpp/build/reference/rtc-run-time-error-checks?view=msvc-160>
### References
* <https://devblogs.microsoft.com/cppblog/security-features-in-microsoft-visual-c/>
* <https://docs.microsoft.com/en-us/cpp/build/reference/linker-options?view=msvc-160>
* <https://clang.llvm.org/docs/MSVCCompatibility.html>
gitextract_elvdvo3q/ ├── LICENSE ├── README.md ├── _config.yml ├── c++.md ├── clang_compilation.md ├── gcc_compilation.md ├── gcc_copt_inclusions.py └── msvc_compilation.md
SYMBOL INDEX (19 symbols across 1 files)
FILE: gcc_copt_inclusions.py
class State (line 13) | class State(Enum):
function parse_properties_string (line 22) | def parse_properties_string(s):
class GCCOption (line 37) | class GCCOption():
method __init__ (line 38) | def __init__(self, name, props):
method __str__ (line 48) | def __str__(self):
method __repr__ (line 51) | def __repr__(self):
method is_valid_for_lang (line 54) | def is_valid_for_lang(self, lang):
method is_warning (line 57) | def is_warning(self):
method is_alias (line 60) | def is_alias(self):
method get_alias_target (line 63) | def get_alias_target(self):
method is_enabled_by (line 68) | def is_enabled_by(self):
method is_by_default (line 72) | def is_by_default(self):
method get_enabled_by (line 76) | def get_enabled_by(self):
method pretty_print (line 93) | def pretty_print(self):
class GCCEnum (line 109) | class GCCEnum():
method __init__ (line 110) | def __init__(self, s):
method __str__ (line 116) | def __str__(self):
method __repr__ (line 119) | def __repr__(self):
function get_enabled_by_recursive (line 212) | def get_enabled_by_recursive(opt, res=[]):
Condensed preview — 8 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (60K chars).
[
{
"path": "LICENSE",
"chars": 20127,
"preview": "Attribution-ShareAlike 4.0 International\n\n=======================================================================\n\nCreat"
},
{
"path": "README.md",
"chars": 6143,
"preview": "# Getting the maximum of your C compiler, for security\n\n- [GCC TL;DR](#gcc-tldr)\n- [Clang TL;DR](#clang-tldr)\n- [Microso"
},
{
"path": "_config.yml",
"chars": 88,
"preview": "theme: jekyll-theme-slate\ntitle: \"Getting the maximum of your C compiler, for security\"\n"
},
{
"path": "c++.md",
"chars": 237,
"preview": "## C++ specific flags\n\n*Note*: work not really started yet\n\n\n### GCC/Clang\n`_GLIBCXX_SANITIZE_VECTOR`\n\nhttps://docs.micr"
},
{
"path": "clang_compilation.md",
"chars": 10130,
"preview": "- [Warnings](#warnings)\n- [Compiler flags](#compiler-flags)\n- [Runtime sanitizers](#runtime-sanitizers)\n- [Code analysis"
},
{
"path": "gcc_compilation.md",
"chars": 10557,
"preview": "- [Warnings](#warnings)\n- [Compilation flags](#compilation-flags)\n- [Runtime sanitizers](#runtime-sanitizers)\n- [Code an"
},
{
"path": "gcc_copt_inclusions.py",
"chars": 7681,
"preview": "#!/usr/bin/env python3\n# https://gcc.gnu.org/onlinedocs/gccint/Option-file-format.html#Option-file-format\n\n\nimport argpa"
},
{
"path": "msvc_compilation.md",
"chars": 3667,
"preview": "- [Warnings](#warnings)\n- [Compilation flags](#compilation-flags)\n- [Code analysis](#code-analysis)\n- [Sanitizers](#sani"
}
]
About this extraction
This page contains the full source code of the airbus-seclab/c-compiler-security GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 8 files (57.3 KB), approximately 14.1k tokens, and a symbol index with 19 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.