From 65ee2da05497f56123488c2780ae769efa9178a8 Mon Sep 17 00:00:00 2001 From: Andrea Terzolo Date: Thu, 29 Aug 2024 17:12:35 +0200 Subject: [PATCH] chore: scaffolding for enabling code formatting Signed-off-by: Andrea Terzolo --- .clang-format | 37 ++- .cmake-format.json | 254 ++++++++++++++++ .git-blame-ignore-revs | 3 + .github/workflows/format.yml | 38 +++ .pre-commit-config.yaml | 23 ++ Contributing.md | 207 +++++++++++++ Makefile | 81 +++++ coding_conventions.md | 278 ------------------ .../modern_bpf/definitions/aarch64/vmlinux.h | 2 + .../modern_bpf/definitions/ppc64le/vmlinux.h | 2 + driver/modern_bpf/definitions/s390x/vmlinux.h | 2 + .../modern_bpf/definitions/x86_64/vmlinux.h | 2 + tools/local_hooks/dco-pre-commit-msg.sh | 16 + 13 files changed, 658 insertions(+), 287 deletions(-) create mode 100644 .cmake-format.json create mode 100644 .git-blame-ignore-revs create mode 100644 .github/workflows/format.yml create mode 100644 .pre-commit-config.yaml create mode 100644 Contributing.md create mode 100644 Makefile delete mode 100644 coding_conventions.md create mode 100755 tools/local_hooks/dco-pre-commit-msg.sh diff --git a/.clang-format b/.clang-format index 49b29803400..599d06e3923 100644 --- a/.clang-format +++ b/.clang-format @@ -1,16 +1,35 @@ ---- Language: Cpp -BasedOnStyle: LLVM -AccessModifierOffset: -8 -BreakBeforeBraces: Allman +BasedOnStyle: Google +AccessModifierOffset: -4 +BreakBeforeBraces: Attach +AllowAllArgumentsOnNextLine: false +AllowAllConstructorInitializersOnNextLine: false +AllowAllParametersOfDeclarationOnNextLine: false +AllowShortFunctionsOnASingleLine: Inline +AllowShortIfStatementsOnASingleLine: Never +AllowShortLoopsOnASingleLine: false +BinPackArguments: false +BinPackParameters: false +ColumnLimit: 100 +DerivePointerBinding: false +IndentCaseLabels: false +IndentWidth: 4 +SpaceAfterTemplateKeyword: false +TabWidth: 4 +UseTab: ForIndentation BreakConstructorInitializers: AfterColon -ColumnLimit: 120 ConstructorInitializerIndentWidth: 8 ContinuationIndentWidth: 8 DerivePointerAlignment: true -IndentWidth: 8 -SortIncludes: false -SpaceAfterTemplateKeyword: false +SortIncludes: Never SpaceBeforeCtorInitializerColon: false SpaceBeforeParens: Never -UseTab: Always +--- +Language: Proto +DisableFormat: true +--- +Language: JavaScript +DisableFormat: true +--- +Language: Java +DisableFormat: true diff --git a/.cmake-format.json b/.cmake-format.json new file mode 100644 index 00000000000..530500d3277 --- /dev/null +++ b/.cmake-format.json @@ -0,0 +1,254 @@ +{ + "_help_format": "Options affecting formatting.", + "format": { + "_help_disable": [ + "Disable formatting entirely, making cmake-format a no-op" + ], + "disable": false, + "_help_line_width": [ + "How wide to allow formatted cmake files" + ], + "line_width": 100, + "_help_tab_size": [ + "How many spaces to tab for indent" + ], + "tab_size": 4, + "_help_use_tabchars": [ + "If true, lines are indented using tab characters (utf-8", + "0x09) instead of space characters (utf-8 0x20).", + "In cases where the layout would require a fractional tab", + "character, the behavior of the fractional indentation is", + "governed by " + ], + "use_tabchars": false, + "_help_fractional_tab_policy": [ + "If is True, then the value of this variable", + "indicates how fractional indentions are handled during", + "whitespace replacement. If set to 'use-space', fractional", + "indentation is left as spaces (utf-8 0x20). If set to", + "`round-up` fractional indentation is replaced with a single", + "tab character (utf-8 0x09) effectively shifting the column", + "to the next tabstop" + ], + "fractional_tab_policy": "use-space", + "_help_max_subgroups_hwrap": [ + "If an argument group contains more than this many sub-groups", + "(parg or kwarg groups) then force it to a vertical layout." + ], + "max_subgroups_hwrap": 2, + "_help_max_pargs_hwrap": [ + "If a positional argument group contains more than this many", + "arguments, then force it to a vertical layout." + ], + "max_pargs_hwrap": 6, + "_help_max_rows_cmdline": [ + "If a cmdline positional group consumes more than this many", + "lines without nesting, then invalidate the layout (and nest)" + ], + "max_rows_cmdline": 2, + "_help_separate_ctrl_name_with_space": [ + "If true, separate flow control names from their parentheses", + "with a space" + ], + "separate_ctrl_name_with_space": false, + "_help_separate_fn_name_with_space": [ + "If true, separate function names from parentheses with a", + "space" + ], + "separate_fn_name_with_space": false, + "_help_dangle_parens": [ + "If a statement is wrapped to more than one line, than dangle", + "the closing parenthesis on its own line." + ], + "dangle_parens": true, + "_help_dangle_align": [ + "If the trailing parenthesis must be 'dangled' on its on", + "line, then align it to this reference: `prefix`: the start", + "of the statement, `prefix-indent`: the start of the", + "statement, plus one indentation level, `child`: align to", + "the column of the arguments" + ], + "dangle_align": "prefix", + "_help_min_prefix_chars": [ + "If the statement spelling length (including space and", + "parenthesis) is smaller than this amount, then force reject", + "nested layouts." + ], + "min_prefix_chars": 4, + "_help_max_prefix_chars": [ + "If the statement spelling length (including space and", + "parenthesis) is larger than the tab width by more than this", + "amount, then force reject un-nested layouts." + ], + "max_prefix_chars": 10, + "_help_max_lines_hwrap": [ + "If a candidate layout is wrapped horizontally but it exceeds", + "this many lines, then reject the layout." + ], + "max_lines_hwrap": 2, + "_help_line_ending": [ + "What style line endings to use in the output." + ], + "line_ending": "unix", + "_help_command_case": [ + "Format command names consistently as 'lower' or 'upper' case" + ], + "command_case": "canonical", + "_help_keyword_case": [ + "Format keywords consistently as 'lower' or 'upper' case" + ], + "keyword_case": "unchanged", + "_help_always_wrap": [ + "A list of command names which should always be wrapped" + ], + "always_wrap": [], + "_help_enable_sort": [ + "If true, the argument lists which are known to be sortable", + "will be sorted lexicographicall" + ], + "enable_sort": true, + "_help_autosort": [ + "If true, the parsers may infer whether or not an argument", + "list is sortable (without annotation)." + ], + "autosort": false, + "_help_require_valid_layout": [ + "By default, if cmake-format cannot successfully fit", + "everything into the desired linewidth it will apply the", + "last, most agressive attempt that it made. If this flag is", + "True, however, cmake-format will print error, exit with non-", + "zero status code, and write-out nothing" + ], + "require_valid_layout": false, + "_help_layout_passes": [ + "A dictionary mapping layout nodes to a list of wrap", + "decisions. See the documentation for more information." + ], + "layout_passes": {} + }, + "_help_markup": "Options affecting comment reflow and formatting.", + "markup": { + "_help_bullet_char": [ + "What character to use for bulleted lists" + ], + "bullet_char": "*", + "_help_enum_char": [ + "What character to use as punctuation after numerals in an", + "enumerated list" + ], + "enum_char": ".", + "_help_first_comment_is_literal": [ + "If comment markup is enabled, don't reflow the first comment", + "block in each listfile. Use this to preserve formatting of", + "your copyright/license statements." + ], + "first_comment_is_literal": false, + "_help_literal_comment_pattern": [ + "If comment markup is enabled, don't reflow any comment block", + "which matches this (regex) pattern. Default is `None`", + "(disabled)." + ], + "literal_comment_pattern": null, + "_help_fence_pattern": [ + "Regular expression to match preformat fences in comments", + "default= ``r'^\\s*([`~]{3}[`~]*)(.*)$'``" + ], + "fence_pattern": "^\\s*([`~]{3}[`~]*)(.*)$", + "_help_ruler_pattern": [ + "Regular expression to match rulers in comments default=", + "``r'^\\s*[^\\w\\s]{3}.*[^\\w\\s]{3}$'``" + ], + "ruler_pattern": "^\\s*[^\\w\\s]{3}.*[^\\w\\s]{3}$", + "_help_explicit_trailing_pattern": [ + "If a comment line matches starts with this pattern then it", + "is explicitly a trailing comment for the preceeding", + "argument. Default is '#<'" + ], + "explicit_trailing_pattern": "#<", + "_help_hashruler_min_length": [ + "If a comment line starts with at least this many consecutive", + "hash characters, then don't lstrip() them off. This allows", + "for lazy hash rulers where the first hash char is not", + "separated by space" + ], + "hashruler_min_length": 10, + "_help_canonicalize_hashrulers": [ + "If true, then insert a space between the first hash char and", + "remaining hash chars in a hash ruler, and normalize its", + "length to fill the column" + ], + "canonicalize_hashrulers": true, + "_help_enable_markup": [ + "enable comment markup parsing and reflow" + ], + "enable_markup": true + }, + "_help_lint": "Options affecting the linter", + "lint": { + "_help_disabled_codes": [ + "a list of lint codes to disable" + ], + "disabled_codes": [], + "_help_function_pattern": [ + "regular expression pattern describing valid function names" + ], + "function_pattern": "[0-9a-z_]+", + "_help_macro_pattern": [ + "regular expression pattern describing valid macro names" + ], + "macro_pattern": "[0-9A-Z_]+", + "_help_global_var_pattern": [ + "regular expression pattern describing valid names for", + "variables with global (cache) scope" + ], + "global_var_pattern": "[A-Z][0-9A-Z_]+", + "_help_internal_var_pattern": [ + "regular expression pattern describing valid names for", + "variables with global scope (but internal semantic)" + ], + "internal_var_pattern": "_[A-Z][0-9A-Z_]+", + "_help_local_var_pattern": [ + "regular expression pattern describing valid names for", + "variables with local scope" + ], + "local_var_pattern": "[a-z][a-z0-9_]+", + "_help_private_var_pattern": [ + "regular expression pattern describing valid names for", + "privatedirectory variables" + ], + "private_var_pattern": "_[0-9a-z_]+", + "_help_public_var_pattern": [ + "regular expression pattern describing valid names for public", + "directory variables" + ], + "public_var_pattern": "[A-Z][0-9A-Z_]+", + "_help_argument_var_pattern": [ + "regular expression pattern describing valid names for", + "function/macro arguments and loop variables." + ], + "argument_var_pattern": "[a-z][a-z0-9_]+", + "_help_keyword_pattern": [ + "regular expression pattern describing valid names for", + "keywords used in functions or macros" + ], + "keyword_pattern": "[A-Z][0-9A-Z_]+", + "_help_max_conditionals_custom_parser": [ + "In the heuristic for C0201, how many conditionals to match", + "within a loop in before considering the loop a parser." + ], + "max_conditionals_custom_parser": 2, + "_help_min_statement_spacing": [ + "Require at least this many newlines between statements" + ], + "min_statement_spacing": 1, + "_help_max_statement_spacing": [ + "Require no more than this many newlines between statements" + ], + "max_statement_spacing": 2, + "max_returns": 6, + "max_branches": 12, + "max_arguments": 5, + "max_localvars": 15, + "max_statements": 50 + } +} diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 00000000000..6b08356b287 --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,3 @@ +# This commit has completely rewritten the history of file `userspace/libscap/engine/savefile/scap_savefile.c`. +# https://github.com/falcosecurity/libs/commit/a6df8fc90e3be0209c5a5f9bb0443077cd5d0967 +a6df8fc90e3be0209c5a5f9bb0443077cd5d0967 diff --git a/.github/workflows/format.yml b/.github/workflows/format.yml new file mode 100644 index 00000000000..2fea0261965 --- /dev/null +++ b/.github/workflows/format.yml @@ -0,0 +1,38 @@ +name: Format code +on: + pull_request: + push: + branches: + - master + - 'release/**' + +jobs: + format: + name: format code 🐲 + runs-on: ubuntu-22.04 + steps: + - name: Checkout repository 🎉 + uses: actions/checkout@v3 + with: + fetch-depth: 0 + + - name: Install deps ⛓ī¸ + run: | + sudo apt update -y + sudo apt install -y --no-install-recommends ca-certificates pip git + pip install pre-commit + + - name: Run pre-commit Šī¸ + run: | + pre-commit run --all-files + + - name: Generate the git-diff 🚒 + if: failure() + run: git diff > format_diff.patch + + - name: Upload the git diff artifact đŸ“Ļ + if: failure() + uses: actions/upload-artifact@v3 + with: + name: format_diff.patch + path: ./format_diff.patch diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 00000000000..853d2aa4610 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,23 @@ +# See https://pre-commit.com for more information +# See https://pre-commit.com/hooks.html for more hooks +fail_fast: false +minimum_pre_commit_version: '0' +repos: +- repo: https://github.com/cheshirekow/cmake-format-precommit + rev: v0.6.13 + hooks: + - id: cmake-format + stages: [commit] +- repo: https://github.com/pre-commit/mirrors-clang-format + rev: v17.0.6 + hooks: + - id: clang-format + types_or: [c++, c] + stages: [commit] +- repo: local + hooks: + - id: dco-hook-local + name: DCO hook local + entry: ./tools/local_hooks/dco-pre-commit-msg.sh + language: script + stages: [prepare-commit-msg] diff --git a/Contributing.md b/Contributing.md new file mode 100644 index 00000000000..baaf61bedd4 --- /dev/null +++ b/Contributing.md @@ -0,0 +1,207 @@ +# How to contribute + +## Enforce coding style đŸ’ģ + +### Introduction + +This document introduces the coding style that will be applied in this repository. +This coding style involves all the following files: `.c`, `.h`, `.cpp`, `.cmake`, `CMakeLists.txt`. To enforce it we rely on two main tools: + +1. `clang-format` version `17.0.6`. +2. `cmake-format` version `0.6.13`. + +> __Please note__: tools versions are important! Different versions will enforce slightly different changes on the code. For example `clang-format-17` will produce a slightly different output respect to `clang-format-16` always respecting the imposed style. + +The coding style is expressed through the 2 configuration file that you find in this repo: `.clang-format`, `.cmake-format.json`. + +### Enforce the style locally + +There are many ways to enforce the style locally, here we will describe two of them: + +1. Use `pre-commit` framework. +2. Use the repo `Makefile`. + +#### 1.Pre-commit framework (suggested if you don't have the 2 tools already installed on your machine) + +The `pre-commit` framework allows you to automatically install different `git-hooks` that will run at every new commit. More precisely, if you use the `.pre-commit-config.yaml` in this repo you will install 3 different hooks: + +1. The `clang-format` hook: this is a `pre-commit` git hook that runs `clang-format` on your staged changes. +2. The `cmake-format` hook: this is a `pre-commit` git hook that runs `cmake-format` on your staged changes. +3. The `DCO signed-off` hook: this is a `pre-commit-msg` git hook that adds the `DCO` on your commit if not present. This hook is not strictly related to the coding style so we will talk about it in a separate section: [Add DCO signed-off to your commits](#add-dco-signed-off-to-your-commits). + +Now let's see what we need to use `pre-commit` framework. + +##### Step 1 + +Install `pre-commit` framework following the [official documentation](https://pre-commit.com/#installation). + +> __Please note__: you have to follow only the "Installation" section. + +##### Step 2 + +Once you have installed `pre-commit`, you don't need to install anything else! This is the good point of using a framework like `pre-commit`, all the tools necessary to format your code will be directly managed by the framework. But in order to be ready, you need to install the git hooks in your local repo. + +This simple command allows you to install the two `pre-commit` git hooks, `clang-format` and `cmake-format`. + +```bash +pre-commit install --install-hooks --hook-type pre-commit --overwrite +``` + +If you want to install also the `pre-commit-msg` git hook for the DCO you have to type the following command, but be sure to have configured all you need as said in the [dedicated section]((#add-dco-signed-off-to-your-commits)) + +```bash +pre-commit install --install-hooks --hook-type prepare-commit-msg --overwrite +``` + +You have done, at every new commit, this hook will check that your patch respects the coding style of this repo! + +If you want to detach the git hooks, you can simply type: + +```bash +pre-commit uninstall --hook-type prepare-commit-msg +pre-commit uninstall --hook-type pre-commit +``` + +#### 2.Makefile + +##### Step 1 + +In order to use the repo `Makefile`, you need to install on your local machine the two aforementioned tools: + +__clang-format v17.0.6__ + +One of the easiest ways to install `clang-format` could be directly downloading its static binary from [here](https://github.com/muttleyxd/clang-tools-static-binaries). +There are other ways for example you can download the package for your distro or you can also build it from sources. + +__cmake-format v0.6.13__ + +To install `cmake-format` you can follow the official documentation [here](https://cmake-format.readthedocs.io/en/latest/installation.html). + +> __NOTE__: Please check the versions of the two tool with `clang-format --version` and `cmake-format --version`. + +##### Step 2 + +Once you have installed the __right__ versions of the 2 tools, you can simply type `make format-all` from the root directory of the project (`/libs`) to format all your code according to the coding style. + +Remember to do that before submitting a new patch upstream! 😁 + +#### Other solutions + +Obviously, you can also install the 2 tools locally and enable some extension of your favorite IDE (like `VScode`) to format your code every time you save your files! + +## Add DCO signed-off to your commits 🔏 + +### Introduction + +Another requirement for contributing to the `libs` repository, is applying the [DCO](https://cert-manager.io/docs/contributing/sign-off/) to every commit you want to push upstream. +Before doing this you have to configure your git user `name` and `email` if you haven't already done it. To check your actual `name` and `email` type: + +```bash +git config --get user.name +git config --get user.email +``` + +If they are correct you have done, otherwise, you have to set them: + +```bash +git config user.name +git config user.email +``` + +>__Please note__: If you have problems in doing this you can read the full documentation [here](https://docs.github.com/en/get-started/getting-started-with-git/setting-your-username-in-git). + +### Enforce the DCO locally + +Now you are ready to sign your commits! You have two main ways to do this: + +1. Manually with `git` tool. +2. Use the `pre-commit-msg` hook quoted before. + +### Manually + +To do this you just need to remember the `-s` while performing your commits: + +```bash +git commit -s +``` + +or with the inline message: + +```bash +git commit -s -m "my first commit" +``` + +### Use `pre-commit` hook + +Here if you have already added the hook in the [previous section](#step-2), you have to do nothing otherwise you have to simply install the DCO hook with: + +```bash +pre-commit install --install-hooks --hook-type prepare-commit-msg --overwrite +``` + +And you have done! Now you don't have to remember the `-s` option every time you commit something, the DCO hook will automatically add the DCO if you forget it! 😄 + +## Some best practices 📏 + +### Class variables + +To know whether a variable belongs to a `class` or a `function`, we start member variables with `m_`. + +Example: + +```c + public int32_t m_counter; +``` + +### Global variables + +To know whether the variable is global or not, we start globals with `g_`. + +Example: + +```c + int g_nplugins; +``` + +### Capitalization + +The naming convention is camel-cased "Unix" style, i.e. always lower case. Words are separated by underscores. + +Example: + +```c + int32_t g_global_bean_counter; + int32_t count_beans(); +``` + +and not, + +```c + int32_t GlobalBeanCounter; + int32_t CountBeans(); +``` + +### Packed Structures + +Packed structures should use the GCC and MSVC-style supported `pragma`: + +Example: + +```c + #pragma pack(push,1) + struct frame_control + { + struct fields.... + }; + #pragma pack(pop) +``` + +### 64-bit constants + +Put an `LL` at the end of your `64-bit` constants. Without the `LL`, some platform compilers try to interpret the constant on the right-hand side as a `long integer` instead of a `long long` and this could lead to an error at building time. + +Example: + +```c + x=0X00FF00000000000LL +``` diff --git a/Makefile b/Makefile new file mode 100644 index 00000000000..8ea203712f2 --- /dev/null +++ b/Makefile @@ -0,0 +1,81 @@ +# +# Copyright (C) 2024 The Falco Authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# mofidy the following variables to match your paths +CLANG_FORMAT_EXE ?= clang-format +CLANG_FORMAT_VERSION = "$(shell ${CLANG_FORMAT_EXE} --version | grep -o '[0-9]*\.[0-9]*\.[0-9]*')" +CLANG_FORMAT_DESIRED_VERSION ="17.0.6" + +CMAKE_FORMAT_EXE ?= cmake-format +CMAKE_FORMAT_VERSION = "$(shell ${CMAKE_FORMAT_EXE} --version | grep -o '[0-9]*\.[0-9]*\.[0-9]*')" +CMAKE_FORMAT_DESIRED_VERSION = "0.6.13" + +PROJECT_ROOT_DIR = $(shell git rev-parse --show-toplevel) + +###################### +# Clang-format # +###################### +.PHONY: clang-format-install +clang-format-install: +ifeq (, $(shell ${CLANG_FORMAT_EXE} --version)) + @echo "${CLANG_FORMAT_EXE} is not installed. Please read the 'coding style' doc to get more info." + @exit 1 +endif + +ifneq ($(CLANG_FORMAT_VERSION), $(CLANG_FORMAT_DESIRED_VERSION)) + @echo "${CLANG_FORMAT_EXE} version is not '${CLANG_FORMAT_DESIRED_VERSION}'. Actual version is '${CLANG_FORMAT_VERSION}'" + @exit 1 +endif + +.PHONY: format-clang +format-clang: clang-format-install + git ls-files --directory ${PROJECT_ROOT_DIR} | grep -E '\.(cpp|h|c)$$' | xargs ${CLANG_FORMAT_EXE} -Werror --style=file:${PROJECT_ROOT_DIR}/.clang-format -i + +.PHONY: check-clang +check-clang: clang-format-install + git ls-files --directory ${PROJECT_ROOT_DIR} | grep -E '\.(cpp|h|c)$$' | xargs ${CLANG_FORMAT_EXE} -Werror --style=file:${PROJECT_ROOT_DIR}/.clang-format -n + +###################### +# Cmake-format # +###################### +.PHONY: cmake-format-install +cmake-format-install: +ifeq (, $(shell ${CMAKE_FORMAT_EXE} --version)) + @echo "${CMAKE_FORMAT_EXE} is not installed. Please read the 'coding style' doc to get more info." + @exit 1 +endif + +ifneq ($(CMAKE_FORMAT_VERSION), $(CMAKE_FORMAT_DESIRED_VERSION)) + @echo "${CMAKE_FORMAT_EXE} version is not '${CMAKE_FORMAT_DESIRED_VERSION}'. Actual version is '${CMAKE_FORMAT_VERSION}'" + @exit 1 +endif + +.PHONY: format-cmake +format-cmake: cmake-format-install + git ls-files --directory ${PROJECT_ROOT_DIR} | grep -E '\.(cmake)$$|CMakeLists.txt$$' | xargs ${CMAKE_FORMAT_EXE} --config-files ${PROJECT_ROOT_DIR}/.cmake-format.json -i + +.PHONY: check-cmake +check-cmake: cmake-format-install + git ls-files --directory ${PROJECT_ROOT_DIR} | grep -E '\.(cmake)$$|CMakeLists.txt$$' | xargs ${CMAKE_FORMAT_EXE} --config-files ${PROJECT_ROOT_DIR}/.cmake-format.json --check + +# Add new formatters here... + +.PHONY: format-all +format-all: format-clang format-cmake + +.PHONY: check-all +check-all: check-clang check-cmake + diff --git a/coding_conventions.md b/coding_conventions.md deleted file mode 100644 index d57ab6b1e1a..00000000000 --- a/coding_conventions.md +++ /dev/null @@ -1,278 +0,0 @@ -0 Introduction ------- - -This repository strives for a consistent high quality code base and uses the conventions -below. If you are going to commit code that doesn't follow them, then you put the -work on us. :-( - -If you use vim or emacs, you can put a custom configuration file in the base -directory in order to follow the conventions. - -Also, note that the conventions in this file apply **strictly to the userspace** part -of this repository. For the kernel code, you should refer to -https://www.kernel.org/doc/html/latest/process/coding-style.html -and always run `checkpatch.pl` from the kernel tree before submitting pull requests. - -Thanks for your attention and time. - -1 Curly Braces ------- - -Every curly brace ("{" and "}") should go on its own line. - -Example: - - if(a == 0) - { - b = 1; - } - -2 If and for statements ------- - -Every `if` and `for` statement should have the curly braces. - -Example: - - if(a == 0) - { - b = 1; - } - -and not - - if(a == 0) - b = 1; - -3 Whitespace usage ------- - -Spaces are used in the following way: - - int32_t foo(int32_t a, int32_t b) - { - for(j = 0; j < 10; j++) - { - foo(a, b); - } - } - -Note that: - - * in a function declaration, there is no space between the function name and the "(". - * in a function declaration, there is no space between the "(" and the first parameter. - * in a statement (e.g `for`, `while`...), there is no space between the "for" and the "(". - * in a statement (e.g `for`), there is no space between the "(" and the variable name. - * in a function call, there is no space between the function name and the "(". - * in a function call, there is no space between the "(" and the first parameter. - * "," and ";" work like in English: there should be a space after them. - -4 Primitive types ------- - -For portability reasons, please use the standard C99 types instead of the native C types -like `int` and `long`. C99 types types will be available in all the user level -source files: - -Example: - - int32_t foo; - -5 Commenting Style ------- - -Comments should be in the C++ style so we can use `/* */` to quickly remove -portions of code during development. - -Example: - - // this is a comment - -6 Commenting Content ------- - -Code comments work in the following 2-level way: - - * A three-line comment should document what the code does and give higher level explanations. - * A one line comment should detail single code lines or explain specific actions. - -Example: - - // - // Swap two variables - // - int a = 1, b = 2, t; - - // make a copy of a - t = a; - - // perform the swap - a = b; - b = t; - -7 Class variables ------- - -In order to know whether a variable belongs to a `class` or a `function` we start member variables with "`m_`". - -Example: - - public int32_t m_counter; - -8 Global variables ------- - -Similarly, in order to know whether the variable is global or not, we start -globals with "`g_`". - -Example: - - int g_nplugins; - -9 Capitalization ------- - -The naming convention is camel-cased "Unix" style, i.e. always lower case. Words are separated by underscores. - -Example: - - int32_t g_global_bean_counter; - - int32_t count_beans(); - -and not, - - int32_t GlobalBeanCounter; - -10 Packed Structures -------- -Packed structures should use the GCC and MSVC-style supported `pragma`: - - #pragma pack(push,1) - struct frame_control - { - struct fields.... - }; - #pragma pack(pop) - -11 OS-specific macros -------- - -There's an online wiki which enumerates the different macros for compilers, operating systems, and architectures. -It's available at [http://sourceforge.net/p/predef/wiki/Home/](http://sourceforge.net/p/predef/wiki/Home/). Generally speaking we use the operating system page: [http://sourceforge.net/p/predef/wiki/OperatingSystems/](http://sourceforge.net/p/predef/wiki/OperatingSystems/). - -12 64-bit constants -------- - -Put an "LL" at the end of your 64 bit constants. Without the LL, on some platforms the compiler tries to interpret the constant on the right hand side -as a long integer instead of a long long and in some platform this generate an error at building time. - -Example: - - x=0X00FF00000000000LL - -13 Class Declaration -------- - -Class declarations follow the following sequence - - 1. constructors and destructor - 2. public functions - 3. public data - 4. private functions - 5. private data - 6. friend declarations - -Example: - - class foo - { - public: - foo(); - ~foo(); - - int32_t lonli(); - int32_t m_val; - - private: - int32_t temustra(); - int32_t m_val2; - }; - -14 Struct guidelines -------- - -We think hiding the presence of a pointer makes the code unnecessarily -ambiguous and more difficult. - -Seeing a * in a variable declaration immediately identifies a pointer, which -is easier to mentally keep track of! - -Also we think that defining the struct as a typedef makes forward declarations -clunky and find using the C++ style when declaring our structs makes our -lives easier. - - // - // Us human parsers find this confusing. - // - typedef struct _my_struct - { - u_int16 m_field; - } my_struct, - *p_my_struct; - - // - // This is easier! - // - struct my_struct { - u_int16 m_field; - }; - - -15 Temporary variables -------- - -Since "j" is used less frequently in english prose than "a" or "i", we find -that these variables (in hierarchical order) are great for counters: j, k, l, -m, n. - -Example: - - int32_t j,k; - for(j = 0; j < 10; j++) - { - for(k = 0; k < 10; k++) - { - int32_t foo = j + k; - } - } - -as opposed to: - - int32_t i,counter; - for(i = 0; i < 10; i++) - { - for(counter = 0; counter < 10; counter++) - { - int32_t foo = i + counter; - } - } - -16 Error management -------- - -Error management inside libscap is done through return values, since the scap -library is written in C. -Error management in the rest of the user level code base is done through -exceptions. We know there's a lot of debate between return values and -exceptions. We decided to pick the latter, so please stick with that. - -## You Made It! - -Phew! That's it. Thanks! - -If we've left anything in the open, feel free to contact us and we'll be happy -to get back to you. Also, you can look at the existing code and see how it's -done. - -Have a good one! diff --git a/driver/modern_bpf/definitions/aarch64/vmlinux.h b/driver/modern_bpf/definitions/aarch64/vmlinux.h index f353b7d7bae..3dc7593d3bb 100644 --- a/driver/modern_bpf/definitions/aarch64/vmlinux.h +++ b/driver/modern_bpf/definitions/aarch64/vmlinux.h @@ -1,3 +1,4 @@ +// clang-format off: autogenerated #ifndef __VMLINUX_H__ #define __VMLINUX_H__ @@ -153858,3 +153859,4 @@ union efi_pci_io_protocol { #endif #endif /* __VMLINUX_H__ */ +// clang-format on diff --git a/driver/modern_bpf/definitions/ppc64le/vmlinux.h b/driver/modern_bpf/definitions/ppc64le/vmlinux.h index e1b843805cb..7521a1592d9 100644 --- a/driver/modern_bpf/definitions/ppc64le/vmlinux.h +++ b/driver/modern_bpf/definitions/ppc64le/vmlinux.h @@ -1,3 +1,4 @@ +// clang-format off: autogenerated #ifndef __VMLINUX_H__ #define __VMLINUX_H__ @@ -142499,3 +142500,4 @@ struct mptcp_subflow_addrs { #endif #endif /* __VMLINUX_H__ */ +// clang-format on diff --git a/driver/modern_bpf/definitions/s390x/vmlinux.h b/driver/modern_bpf/definitions/s390x/vmlinux.h index e739ac893fc..acefb8252c7 100644 --- a/driver/modern_bpf/definitions/s390x/vmlinux.h +++ b/driver/modern_bpf/definitions/s390x/vmlinux.h @@ -1,3 +1,4 @@ +// clang-format off: autogenerated #ifndef __VMLINUX_H__ #define __VMLINUX_H__ @@ -111300,3 +111301,4 @@ struct airq_info { #endif #endif /* __VMLINUX_H__ */ +// clang-format on diff --git a/driver/modern_bpf/definitions/x86_64/vmlinux.h b/driver/modern_bpf/definitions/x86_64/vmlinux.h index 44aa16d1bc2..a21e1463b48 100644 --- a/driver/modern_bpf/definitions/x86_64/vmlinux.h +++ b/driver/modern_bpf/definitions/x86_64/vmlinux.h @@ -1,3 +1,4 @@ +// clang-format off: autogenerated #ifndef __VMLINUX_H__ #define __VMLINUX_H__ @@ -126666,3 +126667,4 @@ struct restore_data_record { #endif #endif /* __VMLINUX_H__ */ +// clang-format on diff --git a/tools/local_hooks/dco-pre-commit-msg.sh b/tools/local_hooks/dco-pre-commit-msg.sh new file mode 100755 index 00000000000..8d9c395c3fd --- /dev/null +++ b/tools/local_hooks/dco-pre-commit-msg.sh @@ -0,0 +1,16 @@ +#!/bin/bash +# +# This is a git pre-commit-msg hook which automatically add a +# DCO signed-off message if one is missing. +# + +MESSAGE_FILE="$1" +GIT_AUTHOR=$(git var GIT_AUTHOR_IDENT) +SIGNOFF_BY=$(echo $GIT_AUTHOR | sed -n 's/^\(.*>\).*$/Signed-off-by: \1/p') + +# Verify if a DCO signoff message exists. +# Append a DCO signoff message if one doesn't exist. +if ! $(grep -qs "^$SIGNOFF_BY" "$MESSAGE_FILE") ; then + echo -e "\n$SIGNOFF_BY" >> "$MESSAGE_FILE" +fi +exit 0