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