diff --git a/.ci/clang-tidy.py b/.ci/clang-tidy.py new file mode 100644 index 00000000000..e21845c3ef5 --- /dev/null +++ b/.ci/clang-tidy.py @@ -0,0 +1,228 @@ +""" +Clang-tidy Checker +================== +This script runs the llvm helper tool run-clang-tidy on all compilation units specified by compile_commands.json. +It filters out files from excluded directories (by default: 3rdparty), exports the findings to a specified YAML file, +and generates a detailed report with the number of findings per diagnostic which is printed to stdout. + +The script exits with: + - Exit code 0: No findings detected + - Exit code 1: Findings were detected or an error occurred +""" + +import argparse +import subprocess +import sys +import yaml +from pathlib import Path +from collections import Counter + + +def parse_arguments(): + """ + Parse command line arguments. + + Returns: + argparse.Namespace: Parsed command line arguments + """ + parser = argparse.ArgumentParser( + description="Run clang-tidy on a CMake build directory and analyze findings.", + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog=""" +Examples: + %(prog)s --build_directory build/tests/posix/Debug --output_file ct-findings.yaml + %(prog)s --build_directory build/tests/posix/Debug --output_file ct-findings.yaml --exclude "test|mock" + %(prog)s --build_directory build/tests/posix/Debug --output_file ct-findings.yaml --quiet + %(prog)s --build_directory build/tests/posix/Debug --output_file ct-findings.yaml --verbose + """, + ) + + parser.add_argument( + "--build_directory", + type=Path, + help="Path to the build directory containing compile_commands.json generated by CMake", + ) + + parser.add_argument( + "--output_file", + type=str, + help="Path to the output YAML file where clang-tidy findings will be stored", + ) + + parser.add_argument( + "--exclude", + type=str, + default="3rdparty", + help="Regular expression pattern to match files to exclude (default: '3rdparty')", + ) + + parser.add_argument( + "--ignore-checks", + type=str, + default="", + help="Comma-separated list of diagnostic names to ignore (e.g., 'clang-diagnostic-error,clang-diagnostic-warning')", + ) + + output_group = parser.add_mutually_exclusive_group() + output_group.add_argument( + "--quiet", + action="store_true", + help="Suppress run-clang-tidy progress output (default)", + ) + + output_group.add_argument( + "--verbose", + action="store_true", + help="Show run-clang-tidy progress output", + ) + + args = parser.parse_args() + + # Validate that build directory exists + if not args.build_directory.exists(): + parser.error(f"Build directory does not exist: {args.build_directory}") + + # Validate that compile_commands.json exists in build directory + compile_commands = args.build_directory / "compile_commands.json" + if not compile_commands.exists(): + parser.error( + f"compile_commands.json not found in build directory: {args.build_directory}" + ) + + return args + + +def count_findings(file_name: Path, ignored_checks: list = []) -> int: + """ + Reads the YAML file generated by clang-tidy and counts the number of findings per diagnostic name. + + Args: + file_name: Path to the YAML file containing clang-tidy findings + ignored_checks: List of diagnostic names to ignore + + Returns: + Total number of findings (excluding ignored checks) + """ + + with open(file_name, "r") as f: + data = yaml.safe_load(f) + + # Count findings per diagnostic name + counter = Counter() + ignored_counter = Counter() + + for diagnostic in data.get("Diagnostics", []): + diagnostic_name = diagnostic.get("DiagnosticName") + if diagnostic_name: + if diagnostic_name in ignored_checks: + ignored_counter[diagnostic_name] += 1 + else: + counter[diagnostic_name] += 1 + + # Sort by count (descending) and then by name + sorted_findings = sorted(counter.items(), key=lambda x: (-x[1], x[0])) + + # Print the report + total_findings = sum(counter.values()) + total_ignored = sum(ignored_counter.values()) + print("Clang-Tidy Findings Report") + print("=" * 60) + print(f"\nTotal unique checks: {len(sorted_findings)}") + print(f"Total findings: {total_findings}") + if total_ignored > 0: + print(f"Total ignored findings: {total_ignored}") + + if sorted_findings: + print("\nFindings per check:") + print("-" * 60) + + for check_name, count in sorted_findings: + print(f"{check_name}: {count}") + else: + print("\n✓ No findings detected!") + + if total_ignored > 0: + print("\nIgnored findings:") + print("-" * 60) + for check_name, count in sorted( + ignored_counter.items(), key=lambda x: (-x[1], x[0]) + ): + print(f"{check_name}: {count}") + + return total_findings + + +def run_clang_tidy( + build_dir: Path, output_file: Path, exclude_pattern: str, quiet: bool +) -> int: + """ + Run clang-tidy on the build directory. + + Args: + build_dir: Path to the build directory + output_file: Path to the output YAML file + exclude_pattern: Regular expression pattern to exclude files + quiet: Whether to suppress run-clang-tidy output + + Returns: + Return code from run-clang-tidy + """ + # Convert the exclusion pattern to a negative lookahead pattern + # This makes run-clang-tidy check files that DO NOT match the exclude pattern + negated_pattern = f"^(?!.*({exclude_pattern})).*" + + cmd = [ + "run-clang-tidy-17.py", + "-p", + str(build_dir), + "-export-fixes", + str(output_file), + negated_pattern, + ] + + if quiet: + cmd.insert(3, "-quiet") + + try: + result = subprocess.run(cmd, check=False) + return result.returncode + except FileNotFoundError: + print( + "Error: run-clang-tidy not found. Please ensure LLVM tools are installed.", + file=sys.stderr, + ) + sys.exit(1) + except Exception as e: + print(f"Error running clang-tidy: {e}", file=sys.stderr) + sys.exit(1) + + +if __name__ == "__main__": + args = parse_arguments() + + print(f"Running clang-tidy on build directory: {args.build_directory}") + print(f"Output file: {args.output_file}") + print(f"Exclude pattern: {args.exclude}") + print("-" * 60) + + # Run clang-tidy + run_clang_tidy( + args.build_directory, + args.output_file, + args.exclude, + not args.verbose, # quiet mode is default unless --verbose is specified + ) + + # Parse ignored checks + ignored_checks = [ + check.strip() for check in args.ignore_checks.split(",") if check.strip() + ] + + # Count and report findings + number_of_findings = count_findings(args.output_file, ignored_checks) + + # Exit with appropriate code + if number_of_findings != 0: + sys.exit(1) + else: + sys.exit(0) diff --git a/.clang-tidy b/.clang-tidy new file mode 100644 index 00000000000..e6534658d0d --- /dev/null +++ b/.clang-tidy @@ -0,0 +1,180 @@ +--- +# TODO: Re-enable these checks in smaller steps +# cppcoreguidelines-*, +# portability-* if needed +# readability-*, -readability-magic-numbers, +# misc-*, -misc-no-recursion, +# modernize-*, -modernize-use-trailing-return-type, +# performance-*, + +Checks: >- + cert-*, + clang-analyzer-*, + bugprone-*, + -bugprone-easily-swappable-parameters, + llvm-*,-llvm-header-guard,-llvm-include-order, + google-readability-casting +ExtraArgs: ['-Wno-unknown-warning-option'] +HeaderFileExtensions: ['h', 'hpp'] +HeaderFilterRegex: '^(?!.*(3rdparty|test|mock)).*' +ImplementationFileExtensions: ['cpp'] +UseColor: true +# TODO: Re-enable these when readibility check is enabled +# CheckOptions : +# - key: readability-identifier-naming.AbstractClassCase +# value: CamelCase +# - key: readability-identifier-naming.AbstractClassPrefix +# value: I +# - key: readability-identifier-naming.AbstractClassSuffix +# value: '' +# - key: readability-identifier-naming.ClassCase +# value: CamelCase +# - key: readability-identifier-naming.ClassPrefix +# value: '' +# - key: readability-identifier-naming.ClassSuffix +# value: '' +# - key: readability-identifier-naming.GlobalConstantCase +# value: UPPER_CASE +# - key: readability-identifier-naming.GlobalConstantPrefix +# value: '' +# - key: readability-identifier-naming.GlobalConstantSuffix +# value: '' +# - key: readability-identifier-naming.ConstantCase +# value: camelBack +# - key: readability-identifier-naming.ConstantPrefix +# value: '' +# - key: readability-identifier-naming.ConstantSuffix +# value: '' +# - key: readability-identifier-naming.ConstantMemberCase +# value: CamelCase +# - key: readability-identifier-naming.ConstantMemberPrefix +# value: k +# - key: readability-identifier-naming.ConstantMemberSuffix +# value: '' +# - key: readability-identifier-naming.StaticConstantCase +# value: camelBack +# - key: readability-identifier-naming.StaticConstantPrefix +# value: k +# - key: readability-identifier-naming.StaticConstantSuffix +# value: '' +# - key: readability-identifier-naming.EnumCase +# value: CamelCase +# - key: readability-identifier-naming.EnumPrefix +# value: '' +# - key: readability-identifier-naming.EnumSuffix +# value: '' +# - key: readability-identifier-naming.EnumConstantCase +# value: CamelCase +# - key: readability-identifier-naming.EnumConstantPrefix +# value: '' +# - key: readability-identifier-naming.EnumConstantSuffix +# value: '' +# - key: readability-identifier-naming.GlobalVariableCase +# value: CamelCase +# - key: readability-identifier-naming.GlobalVariablePrefix +# value: g +# - key: readability-identifier-naming.GlobalVariableSuffix +# value: '' +# - key: readability-identifier-naming.LocalVariableCase +# value: camelBack +# - key: readability-identifier-naming.LocalVariablePrefix +# value: '' +# - key: readability-identifier-naming.LocalVariableSuffix +# value: '' +# - key: readability-identifier-naming.StructCase +# value: aNy_CasE +# - key: readability-identifier-naming.StructPrefix +# value: '' +# - key: readability-identifier-naming.StructSuffix +# value: '' +# - key: readability-identifier-naming.FunctionCase +# value: camelBack +# - key: readability-identifier-naming.FunctionPrefix +# value: '' +# - key: readability-identifier-naming.FunctionSuffix +# value: '' +# - key: readability-identifier-naming.MethodCase +# value: camelBack +# - key: readability-identifier-naming.MethodPrefix +# value: '' +# - key: readability-identifier-naming.MethodSuffix +# value: '' +# - key: readability-identifier-naming.ParameterCase +# value: camelBack +# - key: readability-identifier-naming.PrivateMethodCase +# value: camelBack +# - key: readability-identifier-naming.PrivateMethodPrefix +# value: '' +# - key: readability-identifier-naming.PrivateMethodSuffix +# value: '' +# - key: readability-identifier-naming.PublicMethodCase +# value: camelBack +# - key: readability-identifier-naming.PublicMethodPrefix +# value: '' +# - key: readability-identifier-naming.PublicMethodSuffix +# value: '' +# - key: readability-identifier-naming.MemberCase +# value: camelBack +# - key: readability-identifier-naming.MemberPrefix +# value: _ +# - key: readability-identifier-naming.MemberSuffix +# value: '' +# - key: readability-identifier-naming.PrivateMemberCase +# value: camelBack +# - key: readability-identifier-naming.PrivateMemberPrefix +# value: _ +# - key: readability-identifier-naming.PrivateMemberSuffix +# value: '' +# - key: readability-identifier-naming.PublicMemberCase +# value: camelBack +# - key: readability-identifier-naming.PublicMemberPrefix +# value: '' +# - key: readability-identifier-naming.PublicMemberSuffix +# value: '' +# - key: readability-identifier-naming.NamespaceCase +# value: lower_case +# - key: readability-identifier-naming.NamespacePrefix +# value: '' +# - key: readability-identifier-naming.NamespaceSuffix +# value: '' +# - key: readability-identifier-naming.InlineNamespaceCase +# value: lower_case +# - key: readability-identifier-naming.InlineNamespacePrefix +# value: '' +# - key: readability-identifier-naming.InlineNamespaceSuffix +# value: '' +# - key: readability-identifier-length.IgnoredParameterNames +# value: ^(n|id|a|b|x|y)$ +# - key: readability-identifier-length.IgnoredLoopCounterNames +# value: ^[ijkxy_]$ +# - key: readability-identifier-naming.GlobalFunctionCase +# value: camelBack +# - key: readability-identifier-naming.GlobalFunctionPrefix +# value: '' +# - key: readability-identifier-naming.GlobalFunctionSuffix +# value: '' +# - key: readability-identifier-naming.TemplateParameterCase +# value: CamelCase +# - key: readability-identifier-naming.TemplateParameterPrefix +# value: '' +# - key: readability-identifier-naming.TemplateParameterSuffix +# value: '' +# - key: readability-identifier-naming.TemplateTemplateParameterCase +# value: CamelCase +# - key: readability-identifier-naming.TemplateTemplateParameterPrefix +# value: 'TPL' +# - key: readability-identifier-naming.TemplateTemplateParameterSuffix +# value: '' +# - key: readability-identifier-naming.TypeTemplateParameterCase +# value: CamelCase +# - key: readability-identifier-naming.TypeTemplateParameterPrefix +# value: 'T' +# - key: readability-identifier-naming.TypeTemplateParameterSuffix +# value: '' +# - key: readability-identifier-naming.ValueTemplateParameterCase +# value: UPPER_CASE +# - key: readability-identifier-naming.ValueTemplateParameterPrefix +# value: '' +# - key: readability-identifier-naming.ValueTemplateParameterSuffix +# value: '' +... diff --git a/.github/workflows/clang-tidy.yml b/.github/workflows/clang-tidy.yml new file mode 100644 index 00000000000..8b0fa4603f8 --- /dev/null +++ b/.github/workflows/clang-tidy.yml @@ -0,0 +1,55 @@ +name: Clang-tidy check + +on: [ merge_group, push, pull_request ] + +jobs: + clang-tidy: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + preset: ["tests-posix-release", "tests-s32k1xx-release"] + config: [Release] + platform: [posix, s32k1xx] + exclude: + - preset: "tests-posix-release" + platform: "s32k1xx" + - preset: "tests-s32k1xx-release" + platform: "posix" + steps: + - name: Checkout code + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Build development Image + id: build-docker-development + uses: docker/build-push-action@v6 + with: + context: "{{defaultContext}}:docker/development" + push: false + tags: openbsw-development:local + outputs: type=docker + cache-from: type=gha + cache-to: type=gha,mode=max,ignore-error=true + + - name: Run the ${{ matrix.platform }} ${{ matrix.config }} build inside the docker container + run: >- + DOCKER_UID=$(id -u) DOCKER_GID=$(id -g) DOCKER_HISTORY=/dev/null docker compose run --rm development + python3 .ci/build.py --preset ${{ matrix.preset }} --platform "linux" --cxxid "clang" --cxxstd "14" --config "${{ matrix.config }}" + - name: Run the clang-tidy.py inside the docker container + run: >- + DOCKER_UID=$(id -u) DOCKER_GID=$(id -g) DOCKER_HISTORY=/dev/null docker compose run --rm development + python3 .ci/clang-tidy.py --build_directory=build/tests/${{ matrix.platform }}/${{ matrix.config }} --output_file=ct-findings.yaml --exclude="3rdparty" --ignore-checks="clang-diagnostic-error" + + - name: Upload clang-tidy findings + if: always() + uses: actions/upload-artifact@v4 + with: + name: ct-findings-${{ matrix.platform }}-${{ matrix.config }} + path: ct-findings.yaml + if-no-files-found: warn + overwrite: true \ No newline at end of file diff --git a/doc/dev/guidelines/practices.rst b/doc/dev/guidelines/practices.rst index 0c957730b0d..1db3137190e 100644 --- a/doc/dev/guidelines/practices.rst +++ b/doc/dev/guidelines/practices.rst @@ -7,6 +7,36 @@ secure coding practices. The following practices apply to all of our code except when stated otherwise, regardless of the programming language. +Clang-tidy +---------- + +Additionally, most of these practices are enforced by clang-tidy which is run as part of our CI pipeline. +The clang-tidy configuration can be found in the file ``.clang-tidy`` in the root directory of openbsw repository. +The ci script for running clang-tidy is located in ``.ci/clang-tidy.py``, which runs an llvm helper tool called +``run-clang-tidy`` which checks all compilation units specified in a compile_commands.json file, which is generated by +current CMake configurations. +In case you want to run the llvm helper tool ``run-clang-tidy`` locally, you can use the dev container in the root +``docker-compose.yaml``, build the project with a unit test configuration, in order to generate the +compile_commands.json file, which will appear in ``build/tests/posix/Debug/compile_commands.json``, if you use the +tests-posix-debug preset: + +.. code-block:: bash + + run-clang-tidy-17 -p -export-fixes + +Alternatively you can run the same script that is used in the CI pipeline: + +.. code-block:: bash + + python3 .ci/clang-tidy.py + +In case you want to run clang-tidy on a single file, you can also use the following command: + +.. code-block:: bash + + clang-tidy-17 -p + + Validate Input -------------- diff --git a/docker/development/files/requirements.lock b/docker/development/files/requirements.lock index 7610a11fb86..102164142d1 100644 --- a/docker/development/files/requirements.lock +++ b/docker/development/files/requirements.lock @@ -131,6 +131,8 @@ python-can==4.4.2 # via # -r test/pyTest/requirements.txt # -r tools/UdsTool/requirements.txt +pyyaml==6.0.3 + # via -r docker/development/files/requirements.txt rapidfuzz==3.14.3 # via cleo requests==2.32.5 diff --git a/docker/development/files/requirements.txt b/docker/development/files/requirements.txt index 14c2dd8560b..e1b0cdae099 100644 --- a/docker/development/files/requirements.txt +++ b/docker/development/files/requirements.txt @@ -1,4 +1,5 @@ cmakelang~=0.6 poetry~=2.2 rich~=14.2 -sniffio~=1.3 \ No newline at end of file +sniffio~=1.3 +PyYAML~=6.0 diff --git a/executables/unitTest/bsp/bspConfiguration/include/bsp/io/input/inputConfiguration.h b/executables/unitTest/bsp/bspConfiguration/include/bsp/io/input/inputConfiguration.h new file mode 100644 index 00000000000..c1ebc2d7dd4 --- /dev/null +++ b/executables/unitTest/bsp/bspConfiguration/include/bsp/io/input/inputConfiguration.h @@ -0,0 +1,28 @@ +#if (BSP_INPUT_PIN_CONFIGURATION == 1) + +DigitalInput::InputConfiguration const + DigitalInput::sfDigitalInputConfigurations[][DigitalInput::NUMBER_OF_INTERNAL_DIGITAL_INPUTS] + = { + {/* 0 */ {Io::TestPin0, Io::HIGH_ACTIVE, 1}}, +}; + +DigitalInput::InputConfiguration const* +DigitalInput::getConfiguration(uint8_t /* hardwareVersion */) +{ + return &sfDigitalInputConfigurations[0][0]; +} + +#else + +enum DigitalInputId +{ + InternalInput1, + InternalInput2, + LAST_INTERNAL_DIGITAL_INPUT = InternalInput2, + ExternalInput1, + ExternalInput2, + LAST_DYNAMIC_DIGITAL_INPUT = ExternalInput2, + PORT_UNAVAILABLE +}; + +#endif /* BSP_INPUT_PIN_CONFIGURATION == 1 */ diff --git a/libs/bsp/bspInputManager/test/mock/include/bsp/io/input/inputConfigurationStrings.h b/executables/unitTest/bsp/bspConfiguration/include/bsp/io/input/inputConfigurationStrings.h similarity index 100% rename from libs/bsp/bspInputManager/test/mock/include/bsp/io/input/inputConfigurationStrings.h rename to executables/unitTest/bsp/bspConfiguration/include/bsp/io/input/inputConfigurationStrings.h diff --git a/executables/unitTest/bsp/bspConfiguration/include/bsp/io/io/ioConfiguration.h b/executables/unitTest/bsp/bspConfiguration/include/bsp/io/io/ioConfiguration.h index f50b7a41827..5679d7726b8 100644 --- a/executables/unitTest/bsp/bspConfiguration/include/bsp/io/io/ioConfiguration.h +++ b/executables/unitTest/bsp/bspConfiguration/include/bsp/io/io/ioConfiguration.h @@ -1,217 +1,22 @@ -// Copyright 2024 Accenture. +#if (BSP_IO_PIN_CONFIGURATION == 1) -// IGNORE_INCLUDE_GUARD_CHECK - -#if defined(BSP_IO_PIN_CONFIGURATION) && (BSP_IO_PIN_CONFIGURATION == 1) +#define MODULE_P22 /*lint --e(923, 9078)*/ ((*(Ifx_P*)0xF003B600u)) Io::PinConfiguration const Io::fPinConfiguration[Io::NUMBER_OF_IOS] = { - /* 00 */ {_PORTA_, PA0, _IN, FILTER_ACTIVE | FILTER_TICK1, GPIO}, - /* 01 */ {_PORTA_, PA1, _OUT, FILTER_ACTIVE | FILTER_TICK1, GPIO | STRENGTH_ON}, - /* 02 */ {_PORTA_, PA2, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 03 */ {_PORTA_, PA3, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 04 */ {_PORTA_, PA4, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 05 */ {_PORTA_, PA5, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 06 */ {_PORTA_, PA6, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 07 */ {_PORTA_, PA7, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 08 */ {_PORTA_, PA8, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 09 */ {_PORTA_, PA9, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 10 */ {_PORTA_, PA10, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 11 */ {_PORTA_, PA11, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 12 */ {_PORTA_, PA12, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 13 */ {_PORTA_, PA13, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 14 */ {_PORTA_, PA14, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 15 */ {_PORTA_, PA15, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 16 */ {_PORTA_, PA16, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 17 */ {_PORTA_, PA17, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - - /* 18 */ {_PORTB_, PB0, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 19 */ {_PORTB_, PB1, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 20 */ {_PORTB_, PB2, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 21 */ {_PORTB_, PB3, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 22 */ {_PORTB_, PB4, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 23 */ {_PORTB_, PB5, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 24 */ {_PORTB_, PB6, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 25 */ {_PORTB_, PB7, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 26 */ {_PORTB_, PB8, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 27 */ {_PORTB_, PB9, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 28 */ {_PORTB_, PB10, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 29 */ {_PORTB_, PB11, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 30 */ {_PORTB_, PB12, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 31 */ {_PORTB_, PB13, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 32 */ {_PORTB_, PB14, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 33 */ {_PORTB_, PB15, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 34 */ {_PORTB_, PB16, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 35 */ {_PORTB_, PB17, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - - /* 36 */ {_PORTC_, PC0, _IN, FILTER_ACTIVE | FILTER_TICK1, ALT3}, - /* 37 */ {_PORTC_, PC1, _OUT, FILTER_ACTIVE | FILTER_TICK1, ALT3 | STRENGTH_ON}, - /* 38 */ {_PORTC_, PC2, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 39 */ {_PORTC_, PC3, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 40 */ {_PORTC_, PC4, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 41 */ {_PORTC_, PC5, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 42 */ {_PORTC_, PC6, _IN, 0, ALT2}, - /* 43 */ {_PORTC_, PC7, _OUT, 0, ALT2 | STRENGTH_ON}, - /* 44 */ {_PORTC_, PC8, _IN, 0, ALT2}, - /* 45 */ {_PORTC_, PC9, _OUT, 0, ALT2 | STRENGTH_ON}, - /* 46 */ {_PORTC_, PC10, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 47 */ {_PORTC_, PC11, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 48 */ {_PORTC_, PC12, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 49 */ {_PORTC_, PC13, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 50 */ {_PORTC_, PC14, _OUT, FILTER_ACTIVE | FILTER_TICK1, GPIO | STRENGTH_ON}, - /* 51 */ {_PORTC_, PC15, _OUT, FILTER_ACTIVE | FILTER_TICK1, ALT3 | STRENGTH_ON}, - /* 52 */ {_PORTC_, PC16, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 53 */ {_PORTC_, PC17, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 54 */ {_PORTC_, PC28, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - - /* 55 */ {_PORTD_, PD0, _OUT, 0, ALT3 | STRENGTH_ON | PULLUP}, - /* 56 */ {_PORTD_, PD1, _IN, 0, ALT3 | PULLUP}, - /* 57 */ {_PORTD_, PD2, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 58 */ {_PORTD_, PD3, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 59 */ {_PORTD_, PD4, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 61 */ {_PORTD_, PD5, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 62 */ {_PORTD_, PD6, _IN, 0, ALT2}, - /* 63 */ {_PORTD_, PD7, _OUT, 0, ALT2 | STRENGTH_ON}, - /* 64 */ {_PORTD_, PD8, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 65 */ {_PORTD_, PD9, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 66 */ {_PORTD_, PD10, _OUT, FILTER_ACTIVE | FILTER_TICK1, GPIO | STRENGTH_ON | PULLUP}, - /* 67 */ {_PORTD_, PD11, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 68 */ {_PORTD_, PD12, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 69 */ {_PORTD_, PD13, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 70 */ {_PORTD_, PD14, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 71 */ {_PORTD_, PD15, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 72 */ {_PORTD_, PD16, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 73 */ {_PORTD_, PD17, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, + /* 00 */ {0UL}, - /* 74 */ {_PORTE_, PE0, _OUT, 0, ALT5 | STRENGTH_ON}, - /* 75 */ {_PORTE_, PE1, _OUT, 0, GPIO | STRENGTH_ON | PULLUP}, - /* 76 */ {_PORTE_, PE2, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 77 */ {_PORTE_, PE3, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 78 */ {_PORTE_, PE4, _IN, 0, ALT5}, - /* 79 */ {_PORTE_, PE5, _OUT, 0, ALT5 | STRENGTH_ON}, - /* 80 */ {_PORTE_, PE6, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 81 */ {_PORTE_, PE7, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 82 */ {_PORTE_, PE8, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 83 */ {_PORTE_, PE9, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 84 */ {_PORTE_, PE10, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 85 */ {_PORTE_, PE11, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 86 */ {_PORTE_, PE12, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 87 */ {_PORTE_, PE13, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 88 */ {_PORTE_, PE14, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 89 */ {_PORTE_, PE15, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 90 */ {_PORTE_, PE16, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, - /* 91 */ {_PORTE_, PE21, _OUT, FILTER_ACTIVE | FILTER_TICK1, ALT2 | STRENGTH_ON}, - /* 92 */ {_PORTE_, PE22, _OUT, FILTER_ACTIVE | FILTER_TICK1, ALT2 | STRENGTH_ON}, - /* 93 */ {_PORTE_, PE23, _OUT, FILTER_ACTIVE | FILTER_TICK1, ALT2 | STRENGTH_ON}, - - /* 94 */ {_PORTC_, PC29, _IN, FILTER_ACTIVE | FILTER_TICK1, PINDISABLE}, }; #else enum PinId { - /* 00 */ EVAL_DI_1, - /* 01 */ EVAL_DO_1, - /* 02 */ EVAL_AI_1, - /* 03 */ PIN_A_3, - /* 04 */ PIN_A_4, - /* 05 */ PIN_A_5, - /* 06 */ PIN_A_6, - /* 07 */ PIN_A_7, - /* 08 */ PIN_A_8, - /* 09 */ PIN_A_9, - /* 10 */ PIN_A_10, - /* 11 */ PIN_A_11, - /* 12 */ PIN_A_12, - /* 13 */ PIN_A_13, - /* 14 */ PIN_A_14, - /* 15 */ PIN_A_15, - /* 16 */ PIN_A_16, - /* 17 */ PIN_A_17, - - /* 18 */ PIN_B_0, - /* 19 */ PIN_B_1, - /* 20 */ PIN_B_2, - /* 21 */ PIN_B_3, - /* 22 */ PIN_B_4, - /* 23 */ PIN_B_5, - /* 24 */ PIN_B_6, - /* 25 */ PIN_B_7, - /* 26 */ PIN_B_8, - /* 27 */ PIN_B_9, - /* 28 */ PIN_B_10, - /* 29 */ PIN_B_11, - /* 30 */ PIN_B_12, - /* 31 */ PIN_B_13, - /* 32 */ PIN_B_14, - /* 33 */ PIN_B_15, - /* 34 */ PIN_B_16, - /* 35 */ PIN_B_17, - - /* 36 */ SPI2_MISO, - /* 37 */ SPI2_MOSI, - /* 38 */ PIN_C_2, - /* 39 */ PIN_C_3, - /* 40 */ PIN_C_4, - /* 41 */ PIN_C_5, - /* 42 */ UART1_RX, - /* 43 */ UART1_TX, - /* 44 */ LIN1_Rx, - /* 45 */ LIN1_Tx, - /* 46 */ PIN_C_10, - /* 47 */ PIN_C_11, - /* 48 */ PIN_C_12, - /* 49 */ PIN_C_13, - /* 50 */ SPI2_CSN0, - /* 51 */ SPI2_SCK, - /* 52 */ PIN_C_16, - /* 53 */ PIN_C_17, - /* 54 */ EVAL_POTI_ADC, - - /* 55 */ SPI1_SCK, - /* 56 */ SPI1_MISO, - /* 57 */ PIN_D_2, - /* 58 */ PIN_D_3, - /* 59 */ PIN_D_4, - /* 61 */ PIN_D_5, - /* 62 */ UART_RX, - /* 63 */ UART_TX, - /* 64 */ PIN_D_8, - /* 65 */ PIN_D_9, - /* 66 */ SPI1_CSN1, - /* 67 */ PIN_D_11, - /* 68 */ PIN_D_12, - /* 69 */ PIN_D_13, - /* 70 */ PIN_D_14, - /* 71 */ PIN_D_15, - /* 72 */ PIN_D_16, - /* 73 */ PIN_D_17, + /* 00 */ TestPin0, - /* 74 */ SPI1_MOSI, - /* 75 */ SPI1_CSN0, - /* 76 */ PIN_E_2, - /* 77 */ PIN_E_3, - /* 78 */ canRx, - /* 79 */ canTx, - /* 80 */ PIN_E_6, - /* 81 */ PIN_E_7, - /* 82 */ PIN_E_8, - /* 83 */ PIN_E_9, - /* 84 */ PIN_E_10, - /* 85 */ PIN_E_11, - /* 86 */ PIN_E_12, - /* 87 */ PIN_E_13, - /* 88 */ PIN_E_14, - /* 89 */ PIN_E_15, - /* 90 */ PIN_E_16, - /* 91 */ EVAL_LED_RED, - /* 92 */ EVAL_LED_GREEN, - /* 93 */ EVAL_LED_BLUE, - /* 94 */ EVAL_ADC, + /* 00 */ NUMBER_OF_INPUTS_AND_OUTPUTS, + /* 00 */ PORT_UNAVAILABLE = NUMBER_OF_INPUTS_AND_OUTPUTS - /* xx */ NUMBER_OF_INPUTS_AND_OUTPUTS, - /* xx */ PORT_UNAVAILABLE = NUMBER_OF_INPUTS_AND_OUTPUTS, }; #endif /* BSP_IO_PIN_CONFIGURATION == 1 */ diff --git a/libs/bsp/bspOutputManager/test/mock/include/bsp/io/output/outputConfiguration.h b/executables/unitTest/bsp/bspConfiguration/include/bsp/io/output/outputConfiguration.h similarity index 75% rename from libs/bsp/bspOutputManager/test/mock/include/bsp/io/output/outputConfiguration.h rename to executables/unitTest/bsp/bspConfiguration/include/bsp/io/output/outputConfiguration.h index cab676a235e..3177906d3ff 100644 --- a/libs/bsp/bspOutputManager/test/mock/include/bsp/io/output/outputConfiguration.h +++ b/executables/unitTest/bsp/bspConfiguration/include/bsp/io/output/outputConfiguration.h @@ -1,14 +1,13 @@ - #if (BSPOUTPUTCONFIG == 1) Output::OutputConfig const Output::sfOutputConfigurations[][Output::NUMBER_OF_INTERNAL_OUTPUTS] = { { - /* 00 */ {Io::MOCK_OUTPUT_1, Io::HIGH, Io::HIGH_ACTIVE}, + /* 00 */ {Io::TestPin0, Io::HIGH, Io::HIGH_ACTIVE}, }, }; -Output::OutputConfig const* Output::getConfiguration(uint8_t hw) +Output::OutputConfig const* Output::getConfiguration(uint8_t /* hw */) { return &sfOutputConfigurations[0][0]; } diff --git a/libs/bsp/bspOutputManager/test/mock/include/bsp/io/output/outputConfigurationStrings.h b/executables/unitTest/bsp/bspConfiguration/include/bsp/io/output/outputConfigurationStrings.h similarity index 100% rename from libs/bsp/bspOutputManager/test/mock/include/bsp/io/output/outputConfigurationStrings.h rename to executables/unitTest/bsp/bspConfiguration/include/bsp/io/output/outputConfigurationStrings.h diff --git a/executables/unitTest/bsp/bspIo/CMakeLists.txt b/executables/unitTest/bsp/bspIo/CMakeLists.txt index 4d529722b00..304b4699d35 100644 --- a/executables/unitTest/bsp/bspIo/CMakeLists.txt +++ b/executables/unitTest/bsp/bspIo/CMakeLists.txt @@ -1,5 +1,5 @@ -add_library(utbspIo src/io/Io.cpp) +add_library(bspIo src/io/Io.cpp) -target_include_directories(utbspIo PUBLIC include test/include) +target_include_directories(bspIo PUBLIC include test/include) -target_link_libraries(utbspIo PUBLIC bsp) +target_link_libraries(bspIo PUBLIC bsp bspConfiguration) diff --git a/executables/unitTest/bsp/bspIo/include/bsp/io/io/ioConfiguration.h b/executables/unitTest/bsp/bspIo/include/bsp/io/io/ioConfiguration.h deleted file mode 100644 index 5679d7726b8..00000000000 --- a/executables/unitTest/bsp/bspIo/include/bsp/io/io/ioConfiguration.h +++ /dev/null @@ -1,22 +0,0 @@ -#if (BSP_IO_PIN_CONFIGURATION == 1) - -#define MODULE_P22 /*lint --e(923, 9078)*/ ((*(Ifx_P*)0xF003B600u)) - -Io::PinConfiguration const Io::fPinConfiguration[Io::NUMBER_OF_IOS] = { - - /* 00 */ {0UL}, - -}; - -#else - -enum PinId -{ - /* 00 */ TestPin0, - - /* 00 */ NUMBER_OF_INPUTS_AND_OUTPUTS, - /* 00 */ PORT_UNAVAILABLE = NUMBER_OF_INPUTS_AND_OUTPUTS - -}; - -#endif /* BSP_IO_PIN_CONFIGURATION == 1 */ diff --git a/libs/bsp/bspCharInputOutput/src/charInputOutput/bspIo.cpp b/libs/bsp/bspCharInputOutput/src/charInputOutput/bspIo.cpp index 3adaea5c382..073c0e978b4 100644 --- a/libs/bsp/bspCharInputOutput/src/charInputOutput/bspIo.cpp +++ b/libs/bsp/bspCharInputOutput/src/charInputOutput/bspIo.cpp @@ -13,6 +13,9 @@ extern "C" { #endif +// NOLINTBEGIN(cert-dcl51-cpp): Explanation for this suppression is below +// NOLINTBEGIN(cert-dcl37-c): Explanation for this suppression is below +// NOLINTBEGIN(bugprone-reserved-identifier): Explanation for this suppression is below /** * \par Linking this module * The diab compiler is providing these methods for char in-/output. They will @@ -36,6 +39,10 @@ int __outedit(int const c, int const last) return __outchar(c, last); } +// NOLINTEND(bugprone-reserved-identifier) +// NOLINTEND(cert-dcl37-c) +// NOLINTEND(cert-dcl51-cpp) + int vsnprintf(char* buf, size_t const maxsize, char const* fmt, va_list args) { return vsnprintf_(buf, maxsize, fmt, args); diff --git a/libs/bsp/bspCharInputOutput/src/charInputOutput/charIoSerial.cpp b/libs/bsp/bspCharInputOutput/src/charInputOutput/charIoSerial.cpp index 1e6c8fd81fa..6c4e35c1ef2 100644 --- a/libs/bsp/bspCharInputOutput/src/charInputOutput/charIoSerial.cpp +++ b/libs/bsp/bspCharInputOutput/src/charInputOutput/charIoSerial.cpp @@ -9,6 +9,13 @@ using bsp::Uart; +namespace +{ + +Uart& getUart() { return Uart::getInstance(Uart::Id::TERMINAL); } + +} // namespace + extern "C" { namespace // file-local variables moved from global to anonymous namespace @@ -18,7 +25,7 @@ etl::span LoggerBuffer(SerialLogger_buffer, CHARIOSERIAL_BUFFERSIZE); int SerialLogger_bufferInd = 0; // use synchronous by default so that less memory is needed int SerialLogger_consoleAsynchronous = 0; -Uart& uart = Uart::getInstance(Uart::Id::TERMINAL); + } // namespace /** @@ -37,26 +44,26 @@ void SerialLogger_setSynchronous() { SerialLogger_consoleAsynchronous = 0; } * - 1 if already initialized * - 0 if not yet initialized */ -uint8_t SerialLogger_getInitState() { return (static_cast(uart.isInitialized())); } +uint8_t SerialLogger_getInitState() { return (static_cast(getUart().isInitialized())); } // below functions documented in the header file void SerialLogger_init() { // setup UART on ESCIA - uart.init(); + getUart().init(); } int SerialLogger_putc(int const c) { uint8_t const byte = static_cast(c); - return uart.write(etl::span(&byte, 1U)); + return static_cast(getUart().write(etl::span(&byte, 1U))); } int SerialLogger_getc() { uint8_t data_byte = 0; etl::span data(&data_byte, 1U); - uart.read(data); + getUart().read(data); if (data.size() == 0) { return -1; @@ -68,7 +75,7 @@ void SerialLogger_Idle() { etl::span const data( reinterpret_cast(LoggerBuffer.data()), SerialLogger_bufferInd); - uart.write(data); + getUart().write(data); SerialLogger_bufferInd = 0; } diff --git a/libs/bsp/bspInputManager/CMakeLists.txt b/libs/bsp/bspInputManager/CMakeLists.txt index bab343fe30a..3612d2c9bec 100644 --- a/libs/bsp/bspInputManager/CMakeLists.txt +++ b/libs/bsp/bspInputManager/CMakeLists.txt @@ -9,6 +9,8 @@ target_link_libraries( bspInputManager PUBLIC bsp bspDynamicClient + bspInterrupts + bspConfiguration bspIo etl platform diff --git a/libs/bsp/bspInputManager/src/inputManager/DigitalInput.cpp b/libs/bsp/bspInputManager/src/inputManager/DigitalInput.cpp index 082843746a6..dd7e3a68d3b 100644 --- a/libs/bsp/bspInputManager/src/inputManager/DigitalInput.cpp +++ b/libs/bsp/bspInputManager/src/inputManager/DigitalInput.cpp @@ -115,35 +115,23 @@ bsp::BspReturnCode DigitalInput::get(DigitalInputId const channel, bool& result) } return bsp::BSP_OK; } - else if ( - (DigitalInputId::LAST_DYNAMIC_DIGITAL_INPUT > DigitalInputId::LAST_INTERNAL_DIGITAL_INPUT) + + if ((DigitalInputId::LAST_DYNAMIC_DIGITAL_INPUT > DigitalInputId::LAST_INTERNAL_DIGITAL_INPUT) && (channel > DigitalInputId::LAST_INTERNAL_DIGITAL_INPUT) && (channel <= DigitalInputId::LAST_DYNAMIC_DIGITAL_INPUT)) { // dynamic instance dynamicClientType const dynamicChannel = static_cast(tmpChannel - NUMBER_OF_INTERNAL_DIGITAL_INPUTS); - if (dynamicChannel < NumberOfDynamicInputs) - { - if (dynamicInputCfg.getClientValid(dynamicChannel)) - { - return (dynamicInputCfg.getClientInstance(dynamicChannel) - ->get(dynamicInputCfg.getChannelInsideClient(dynamicChannel), result)); - } - else - { - return bsp::BSP_ERROR; - } - } - else + if ((dynamicChannel < NumberOfDynamicInputs) + && dynamicInputCfg.getClientValid(dynamicChannel)) { - return bsp::BSP_ERROR; + return (dynamicInputCfg.getClientInstance(dynamicChannel) + ->get(dynamicInputCfg.getChannelInsideClient(dynamicChannel), result)); } } - else - { - return bsp::BSP_ERROR; - } + + return bsp::BSP_ERROR; } bsp::BspReturnCode DigitalInput::setDynamicClient( @@ -162,16 +150,11 @@ bsp::BspReturnCode DigitalInput::setDynamicClient( fLock.resume(); return bsp::BSP_OK; } - else - { - fLock.resume(); - return bsp::BSP_ERROR; - } - } - else - { - return bsp::BSP_ERROR; + + fLock.resume(); } + + return bsp::BSP_ERROR; } bsp::BspReturnCode DigitalInput::clrDynamicClient(uint16_t const inputNumber) @@ -189,16 +172,10 @@ bsp::BspReturnCode DigitalInput::clrDynamicClient(uint16_t const inputNumber) fLock.resume(); return bsp::BSP_OK; } - else - { - fLock.resume(); - return bsp::BSP_ERROR; - } - } - else - { - return bsp::BSP_ERROR; + fLock.resume(); } + + return bsp::BSP_ERROR; } void DigitalInput::cleanDynamicClients() @@ -215,10 +192,8 @@ char const* DigitalInput::getName(uint16_t const channel) { return inputConfigurationStrings[channel]; } - else - { - return ("??? ->"); - } + + return ("??? ->"); } } /* namespace bios */ diff --git a/libs/bsp/bspInputManager/test/CMakeLists.txt b/libs/bsp/bspInputManager/test/CMakeLists.txt index 7b53436bfd7..209ae3c24b3 100644 --- a/libs/bsp/bspInputManager/test/CMakeLists.txt +++ b/libs/bsp/bspInputManager/test/CMakeLists.txt @@ -1,8 +1,8 @@ add_executable(bspInputManagerTest src/IncludeTest.cpp) -target_include_directories(bspInputManagerTest PRIVATE ../include mock/include) +target_include_directories(bspInputManagerTest PRIVATE ../include) -target_link_libraries(bspInputManagerTest PRIVATE bspDynamicClient utbspIo util +target_link_libraries(bspInputManagerTest PRIVATE bspDynamicClient bspIo util gtest_main) gtest_discover_tests(bspInputManagerTest PROPERTIES LABELS diff --git a/libs/bsp/bspInputManager/test/mock/include/bsp/io/input/inputConfiguration.h b/libs/bsp/bspInputManager/test/mock/include/bsp/io/input/inputConfiguration.h deleted file mode 100644 index 481792649f4..00000000000 --- a/libs/bsp/bspInputManager/test/mock/include/bsp/io/input/inputConfiguration.h +++ /dev/null @@ -1,11 +0,0 @@ - -enum DigitalInputId -{ - InternalInput1, - InternalInput2, - LAST_INTERNAL_DIGITAL_INPUT = InternalInput2, - ExternalInput1, - ExternalInput2, - LAST_DYNAMIC_DIGITAL_INPUT = ExternalInput2, - PORT_UNAVAILABLE -}; diff --git a/libs/bsp/bspOutputManager/CMakeLists.txt b/libs/bsp/bspOutputManager/CMakeLists.txt index e29f24ca4be..fb3a9b7b8da 100644 --- a/libs/bsp/bspOutputManager/CMakeLists.txt +++ b/libs/bsp/bspOutputManager/CMakeLists.txt @@ -3,4 +3,11 @@ add_library(bspOutputManager src/outputManager/Output.cpp target_include_directories(bspOutputManager PUBLIC include) -target_link_libraries(bspOutputManager PUBLIC bspDynamicClient bspIo etl util) +target_link_libraries( + bspOutputManager + PUBLIC bspDynamicClient + bspConfiguration + bspInterrupts + bspIo + etl + util) diff --git a/libs/bsp/bspOutputManager/src/outputManager/Output.cpp b/libs/bsp/bspOutputManager/src/outputManager/Output.cpp index 5c8abeb4d3a..4c89e63e087 100644 --- a/libs/bsp/bspOutputManager/src/outputManager/Output.cpp +++ b/libs/bsp/bspOutputManager/src/outputManager/Output.cpp @@ -52,27 +52,23 @@ bsp::BspReturnCode Output::invert(OutputId const chan) if (chan < NUMBER_OF_INTERNAL_OUTPUTS) { - bool t; if (Io::PORT_UNAVAILABLE == sfpOutputConfiguration[chan].ioNumber) { return bsp::BSP_NOT_SUPPORTED; } - t = Io::getPin(static_cast(sfpOutputConfiguration[chan].ioNumber)); - if (t) - { - (void)Io::setPin(static_cast(sfpOutputConfiguration[chan].ioNumber), 0); - } - else - { - (void)Io::setPin(static_cast(sfpOutputConfiguration[chan].ioNumber), 1); - } + + bool const pinVal + = Io::getPin(static_cast(sfpOutputConfiguration[chan].ioNumber)); + (void)Io::setPin(static_cast(sfpOutputConfiguration[chan].ioNumber), !pinVal); return bsp::BSP_OK; } - else if (chan == NUMBER_OF_INTERNAL_OUTPUTS) + + if (chan == NUMBER_OF_INTERNAL_OUTPUTS) { return bsp::BSP_NOT_SUPPORTED; } - else if (chan < TOTAL_NUMBER_OF_OUTPUTS) + + if (chan < TOTAL_NUMBER_OF_OUTPUTS) { // dynamic instance dynamicClientType const channel = chan - NUMBER_OF_INTERNAL_OUTPUTS - 1; @@ -90,31 +86,15 @@ bsp::BspReturnCode Output::invert(OutputId const chan) return (dynamicOutputCfg.getClientInstance(channel)->set( dynamicOutputCfg.getChannelInsideClient(channel), 0U, true)); } - else - { - return (dynamicOutputCfg.getClientInstance(channel)->set( - dynamicOutputCfg.getChannelInsideClient(channel), 1U, true)); - } - } - else - { - return bsp::BSP_ERROR; + + return (dynamicOutputCfg.getClientInstance(channel)->set( + dynamicOutputCfg.getChannelInsideClient(channel), 1U, true)); } } - else - { - return bsp::BSP_ERROR; - } - } - else - { - return bsp::BSP_ERROR; } } - else - { - return bsp::BSP_ERROR; - } + + return bsp::BSP_ERROR; } bsp::BspReturnCode Output::init(OutputId const chan) @@ -177,35 +157,19 @@ bsp::BspReturnCode Output::get(OutputId const chan, bool& result) result = volRow; return bsp::BSP_OK; } - else if (chan == NUMBER_OF_INTERNAL_OUTPUTS) - { - return bsp::BSP_ERROR; - } - else if (chan < TOTAL_NUMBER_OF_OUTPUTS) + + if ((chan != NUMBER_OF_INTERNAL_OUTPUTS) && (chan < TOTAL_NUMBER_OF_OUTPUTS)) { // dynamic instance dynamicClientType const channel = chan - NUMBER_OF_INTERNAL_OUTPUTS - 1; - if (channel < NUMBER_OF_DYNAMIC_OUTPUTS) - { - if (dynamicOutputCfg.getClientValid(channel)) - { - return (dynamicOutputCfg.getClientInstance(channel)->get( - dynamicOutputCfg.getChannelInsideClient(channel), result)); - } - else - { - return bsp::BSP_ERROR; - } - } - else + if ((channel < NUMBER_OF_DYNAMIC_OUTPUTS) && dynamicOutputCfg.getClientValid(channel)) { - return bsp::BSP_ERROR; + return (dynamicOutputCfg.getClientInstance(channel)->get( + dynamicOutputCfg.getChannelInsideClient(channel), result)); } } - else - { - return bsp::BSP_ERROR; - } + + return bsp::BSP_ERROR; } bsp::BspReturnCode Output::set(OutputId const chan, uint8_t const vol, bool const latch) @@ -229,35 +193,19 @@ bsp::BspReturnCode Output::set(OutputId const chan, uint8_t const vol, bool cons (void)Io::setPin(static_cast(sfpOutputConfiguration[chan].ioNumber), volRow); return bsp::BSP_OK; } - else if (chan == NUMBER_OF_INTERNAL_OUTPUTS) - { - return bsp::BSP_NOT_SUPPORTED; - } - else if (chan < TOTAL_NUMBER_OF_OUTPUTS) + + if ((chan != NUMBER_OF_INTERNAL_OUTPUTS) && (chan < TOTAL_NUMBER_OF_OUTPUTS)) { // dynamic instance dynamicClientType const channel = chan - NUMBER_OF_INTERNAL_OUTPUTS - 1; - if (channel < NUMBER_OF_DYNAMIC_OUTPUTS) + if ((channel < NUMBER_OF_DYNAMIC_OUTPUTS) && dynamicOutputCfg.getClientValid(channel)) { - if (dynamicOutputCfg.getClientValid(channel)) - { - return (dynamicOutputCfg.getClientInstance(channel)->set( - dynamicOutputCfg.getChannelInsideClient(channel), vol, latch)); - } - else - { - return bsp::BSP_ERROR; - } - } - else - { - return bsp::BSP_ERROR; + return (dynamicOutputCfg.getClientInstance(channel)->set( + dynamicOutputCfg.getChannelInsideClient(channel), vol, latch)); } } - else - { - return bsp::BSP_ERROR; - } + + return bsp::BSP_ERROR; } bsp::BspReturnCode Output::setDynamicClient( @@ -277,16 +225,10 @@ bsp::BspReturnCode Output::setDynamicClient( fLock.resume(); return bsp::BSP_OK; } - else - { - fLock.resume(); - return bsp::BSP_ERROR; - } - } - else - { - return bsp::BSP_ERROR; + fLock.resume(); } + + return bsp::BSP_ERROR; } bsp::BspReturnCode Output::clrDynamicClient(uint16_t const outputNumber) @@ -302,16 +244,10 @@ bsp::BspReturnCode Output::clrDynamicClient(uint16_t const outputNumber) fLock.resume(); return bsp::BSP_OK; } - else - { - fLock.resume(); - return bsp::BSP_ERROR; - } - } - else - { - return bsp::BSP_ERROR; + fLock.resume(); } + + return bsp::BSP_ERROR; } void Output::cleanDynamicClients() @@ -328,10 +264,7 @@ char const* Output::getName(uint16_t const channel) { return outputConfigurationStrings[channel]; } - else - { - return ("??? ->"); - } + return ("??? ->"); } } /* namespace bios */ diff --git a/libs/bsp/bspOutputManager/test/CMakeLists.txt b/libs/bsp/bspOutputManager/test/CMakeLists.txt index 4590b02966a..7f96d523dba 100644 --- a/libs/bsp/bspOutputManager/test/CMakeLists.txt +++ b/libs/bsp/bspOutputManager/test/CMakeLists.txt @@ -1,6 +1,4 @@ add_executable(bspOutputManagerTest src/IncludeTest.cpp) -target_include_directories(bspOutputManagerTest PRIVATE ../include mock/include) -target_link_libraries(bspOutputManagerTest PRIVATE bspDynamicClient utbspIo - util gtest_main) +target_link_libraries(bspOutputManagerTest PUBLIC bspOutputManager gtest_main) gtest_discover_tests(bspOutputManagerTest PROPERTIES LABELS "bspOutputManagerTest") diff --git a/libs/bsp/bspOutputPwm/src/outputPwm/OutputPwm.cpp b/libs/bsp/bspOutputPwm/src/outputPwm/OutputPwm.cpp index b262e4d8c0f..2491be24085 100644 --- a/libs/bsp/bspOutputPwm/src/outputPwm/OutputPwm.cpp +++ b/libs/bsp/bspOutputPwm/src/outputPwm/OutputPwm.cpp @@ -32,35 +32,21 @@ bsp::BspReturnCode OutputPwm::setDuty(uint16_t chan, uint16_t duty, bool immedia // dummy channel return bsp::BSP_OK; } - else + + if (chan < outputPwmNumberAll) { - if (chan < outputPwmNumberAll) + dynamicClientType channel = chan - outputPwmStaticNumber; // dynamic instance + if (channel < outputNumberDynamic) { - dynamicClientType channel = chan - outputPwmStaticNumber; // dynamic instance - if (channel < outputNumberDynamic) - { - if (dynamicPwmOutputCfg.getClientValid(channel)) - { - return (dynamicPwmOutputCfg.getClientInstance(channel)->setDuty( - dynamicPwmOutputCfg.getChannelInsideClient(channel), - duty, - immediateUpdate)); - } - else - { - return bsp::BSP_ERROR; - } - } - else + if (dynamicPwmOutputCfg.getClientValid(channel)) { - return bsp::BSP_ERROR; + return (dynamicPwmOutputCfg.getClientInstance(channel)->setDuty( + dynamicPwmOutputCfg.getChannelInsideClient(channel), duty, immediateUpdate)); } } - else - { - return bsp::BSP_ERROR; - } } + + return bsp::BSP_ERROR; } bsp::BspReturnCode OutputPwm::setPeriod(uint16_t chan, uint16_t period) @@ -70,33 +56,18 @@ bsp::BspReturnCode OutputPwm::setPeriod(uint16_t chan, uint16_t period) // dummy channel return bsp::BSP_OK; } - else + + if (chan < outputPwmNumberAll) { - if (chan < outputPwmNumberAll) + dynamicClientType channel = chan - outputPwmStaticNumber; // dynamic instance + if ((channel < outputNumberDynamic) && dynamicPwmOutputCfg.getClientValid(channel)) { - dynamicClientType channel = chan - outputPwmStaticNumber; // dynamic instance - if (channel < outputNumberDynamic) - { - if (dynamicPwmOutputCfg.getClientValid(channel)) - { - return (dynamicPwmOutputCfg.getClientInstance(channel)->setPeriod( - dynamicPwmOutputCfg.getChannelInsideClient(channel), period)); - } - else - { - return bsp::BSP_ERROR; - } - } - else - { - return bsp::BSP_ERROR; - } - } - else - { - return bsp::BSP_ERROR; + return (dynamicPwmOutputCfg.getClientInstance(channel)->setPeriod( + dynamicPwmOutputCfg.getChannelInsideClient(channel), period)); } } + + return bsp::BSP_ERROR; } bsp::BspReturnCode OutputPwm::setDynamicClient( @@ -113,16 +84,10 @@ bsp::BspReturnCode OutputPwm::setDynamicClient( fLock.resume(); return bsp::BSP_OK; } - else - { - fLock.resume(); - return bsp::BSP_ERROR; - } - } - else - { - return bsp::BSP_ERROR; + fLock.resume(); } + + return bsp::BSP_ERROR; } bsp::BspReturnCode OutputPwm::clrDynamicClient(uint16_t outputNumber) @@ -138,16 +103,10 @@ bsp::BspReturnCode OutputPwm::clrDynamicClient(uint16_t outputNumber) fLock.resume(); return bsp::BSP_OK; } - else - { - fLock.resume(); - return bsp::BSP_ERROR; - } - } - else - { - return bsp::BSP_ERROR; + fLock.resume(); } + + return bsp::BSP_ERROR; } void OutputPwm::cleanDynamicClients() @@ -164,10 +123,7 @@ char const* OutputPwm::getName(uint16_t channel) { return outputPwmConfigurationStrings[channel]; } - else - { - return ("??? ->"); - } + return ("??? ->"); } } // namespace bios diff --git a/libs/bsp/bspOutputPwm/test/CMakeLists.txt b/libs/bsp/bspOutputPwm/test/CMakeLists.txt index 1bef66e00a9..89add20c3e2 100644 --- a/libs/bsp/bspOutputPwm/test/CMakeLists.txt +++ b/libs/bsp/bspOutputPwm/test/CMakeLists.txt @@ -7,7 +7,7 @@ target_link_libraries( PRIVATE etl bspDynamicClient bspConfiguration - utbspIo + bspIo utbspMcu util gtest_main) diff --git a/libs/bsw/async/mock/gmock/src/async/TestContext.cpp b/libs/bsw/async/mock/gmock/src/async/TestContext.cpp index eca08d2891c..aadcdffce7b 100644 --- a/libs/bsw/async/mock/gmock/src/async/TestContext.cpp +++ b/libs/bsw/async/mock/gmock/src/async/TestContext.cpp @@ -108,7 +108,14 @@ void TestContext::expire() TimeoutType& timeout = current->_key; TimeoutValue const value = current->_value; current = _timeoutQueue.remove(*current, prev); - if ((value._period > 0U) && (value._runnable != nullptr)) + + if (value._runnable == nullptr) + { + // Should not happen, but guard against it + continue; + } + + if (value._period > 0U) { schedule(*value._runnable, timeout, value._period, true); } diff --git a/libs/bsw/async/mock/gmock/src/async/Types.cpp b/libs/bsw/async/mock/gmock/src/async/Types.cpp index 21fa1a8a42b..5d34bf86cec 100644 --- a/libs/bsw/async/mock/gmock/src/async/Types.cpp +++ b/libs/bsw/async/mock/gmock/src/async/Types.cpp @@ -20,6 +20,7 @@ LockType::LockType() } } +// NOLINTBEGIN(bugprone-exception-escape): This is just for testing purposes. LockType::~LockType() { if (singleton_base::is_valid()) @@ -28,8 +29,11 @@ LockType::~LockType() } } +// NOLINTEND(bugprone-exception-escape) + ModifiableLockType::ModifiableLockType() : _isLocked(false) { lock(); } +// NOLINTNEXTLINE(bugprone-exception-escape): This is just for testing purposes. ModifiableLockType::~ModifiableLockType() { unlock(); } void ModifiableLockType::unlock() diff --git a/libs/bsw/asyncImpl/examples/src/example.cpp b/libs/bsw/asyncImpl/examples/src/example.cpp index e3371210067..a40b13422ba 100644 --- a/libs/bsw/asyncImpl/examples/src/example.cpp +++ b/libs/bsw/asyncImpl/examples/src/example.cpp @@ -93,6 +93,7 @@ void exampleRunnableA() { printf("exampleRunnableA is called.\n"); } void exampleRunnableB() { printf("exampleRunnableB is called.\n"); } +// NOLINTBEGIN(bugprone-exception-escape): This is just for testing purposes. int main() { auto eventManager = asyncNewPlatform::AsyncImplExample(); @@ -106,4 +107,6 @@ int main() return 0; } +// NOLINTEND(bugprone-exception-escape) + // EXAMPLE_END AsyncImplExample diff --git a/libs/bsw/cpp2can/test/src/can/filter/BitFieldFilterTest.cpp b/libs/bsw/cpp2can/test/src/can/filter/BitFieldFilterTest.cpp index 8d3b1d0eb6e..650c771aca4 100644 --- a/libs/bsw/cpp2can/test/src/can/filter/BitFieldFilterTest.cpp +++ b/libs/bsw/cpp2can/test/src/can/filter/BitFieldFilterTest.cpp @@ -141,9 +141,11 @@ TEST_F(BitFieldFilterTest, MergeWithIntervalFilter) IntervalFilter intervalFilter; set randomIds; pair::iterator, bool> result; + // NOLINTNEXTLINE(cert-msc30-c, cert-msc32-c, cert-msc51-cpp): Constant seed is fine. srand(0); while (randomIds.size() < 100) { // generate 100 + // NOLINTNEXTLINE(cert-msc30-c, cert-msc50-cpp): Probably not needed for this test purpose. result = randomIds.insert(rand() % BitFieldFilter::MAX_ID + 1); fFilter.add(*result.first); } diff --git a/libs/bsw/cpp2ethernet/src/udp/util/UdpEchoTestServer.cpp b/libs/bsw/cpp2ethernet/src/udp/util/UdpEchoTestServer.cpp index f523199ee42..d5934a8b5d6 100644 --- a/libs/bsw/cpp2ethernet/src/udp/util/UdpEchoTestServer.cpp +++ b/libs/bsw/cpp2ethernet/src/udp/util/UdpEchoTestServer.cpp @@ -23,28 +23,26 @@ bool UdpEchoTestServer::start() Logger::info(UDP, "UDP echo test server initialisation"); _socket.setDataListener(this); - if (_socket.bind(&_ipAddr, _rxPort) == ::udp::AbstractDatagramSocket::ErrorCode::UDP_SOCKET_OK) - { - _socket.setDataListener(this); - Logger::info(UDP, "Listening on port %d.", _rxPort); - } - else + if (_socket.bind(&_ipAddr, _rxPort) != ::udp::AbstractDatagramSocket::ErrorCode::UDP_SOCKET_OK) { Logger::error(UDP, "UDP socket bind failed"); return false; } - if (_socket.join(_multicastAddr) == ::udp::AbstractDatagramSocket::ErrorCode::UDP_SOCKET_OK) + _socket.setDataListener(this); + Logger::info(UDP, "Listening on port %d.", _rxPort); + + if (_socket.join(_multicastAddr) != ::udp::AbstractDatagramSocket::ErrorCode::UDP_SOCKET_OK) { + Logger::error(UDP, "Multicast join failed"); + return false; Logger::info(UDP, "Joined multicast group"); return true; } - else - { - Logger::error(UDP, "Multicast join failed"); - } - return false; + Logger::info(UDP, "Joined multicast group"); + + return true; } void UdpEchoTestServer::stop() diff --git a/libs/bsw/cpp2ethernet/test/mock/src/logger/Logger.cpp b/libs/bsw/cpp2ethernet/test/mock/src/logger/Logger.cpp index 3d5c18b3238..059c5346ab3 100644 --- a/libs/bsw/cpp2ethernet/test/mock/src/logger/Logger.cpp +++ b/libs/bsw/cpp2ethernet/test/mock/src/logger/Logger.cpp @@ -6,9 +6,16 @@ using namespace ::util::logger; -LoggerComponentInfo components[] = { - LoggerComponentInfo(ETHERNET, "ETHERNET", LEVEL_DEBUG), - LoggerComponentInfo(TCP, "TCP", LEVEL_DEBUG), -}; +etl::span getComponents() +{ + static auto components = etl::make_array( + LoggerComponentInfo(ETHERNET, "ETHERNET", LEVEL_DEBUG), + LoggerComponentInfo(TCP, "TCP", LEVEL_DEBUG)); + return components; +} -TestConsoleLogger logger(components); +TestConsoleLogger& getLogger() +{ + static TestConsoleLogger logger(getComponents()); + return logger; +} diff --git a/libs/bsw/docan/test/src/docan/addressing/DoCanNormalAddressingFilterTest.cpp b/libs/bsw/docan/test/src/docan/addressing/DoCanNormalAddressingFilterTest.cpp index dc3bb9cda92..08f29d7fd50 100644 --- a/libs/bsw/docan/test/src/docan/addressing/DoCanNormalAddressingFilterTest.cpp +++ b/libs/bsw/docan/test/src/docan/addressing/DoCanNormalAddressingFilterTest.cpp @@ -23,9 +23,12 @@ using DoCanNormalAddressingFilterType = DoCanNormalAddressingFilter; +// NOLINTBEGIN(cert-err58-cpp): Lots of references to these names in this file, as such suppress was +// prefered here since it's just a test file. static TransmitActionSetType storeSeparationTime = TransmitActionSetType().set(TransmitAction::STORE_SEPARATION_TIME); static TransmitActionSetType cancelSend = TransmitActionSetType().set(TransmitAction::CANCEL_SEND); +// NOLINTEND(cert-err58-cpp) + TEST(DoCanMessageTransmitProtocolHandlerTest, testResultClass) { TransmitActionSetType noAction; diff --git a/libs/bsw/docan/test/src/docan/transmitter/DoCanMessageTransmitterTest.cpp b/libs/bsw/docan/test/src/docan/transmitter/DoCanMessageTransmitterTest.cpp index 888b72dfd68..ada8931d6b6 100644 --- a/libs/bsw/docan/test/src/docan/transmitter/DoCanMessageTransmitterTest.cpp +++ b/libs/bsw/docan/test/src/docan/transmitter/DoCanMessageTransmitterTest.cpp @@ -32,8 +32,12 @@ using TransmitProtocolHandler = DoCanMessageTransmitProtocolHandler; -static TransmitActionSetType storeSeparationTime - = TransmitActionSetType().set(TransmitAction::STORE_SEPARATION_TIME); +TransmitActionSetType& getStoreSeparationTime() +{ + static TransmitActionSetType storeSeparationTime + = TransmitActionSetType().set(TransmitAction::STORE_SEPARATION_TIME); + return storeSeparationTime; +} TEST(DoCanMessageTransmitterTest, testConstructedTransmitter) { @@ -173,7 +177,7 @@ TEST(DoCanMessageTransmitterTest, testMultipleFramesAreEmitted) EXPECT_EQ(TransmitState::WAIT, cut.getState()); EXPECT_EQ(TransmitTimeout::FLOW_CONTROL, cut.getTimeout()); EXPECT_EQ( - TransmitResult(true).setActionSet(storeSeparationTime), + TransmitResult(true).setActionSet(getStoreSeparationTime()), cut.handleFlowControl(FlowStatus::CTS, 0, 0, 2)); EXPECT_EQ( true, @@ -238,7 +242,7 @@ TEST(DoCanMessageTransmitterTest, testMultipleFramesAreEmittedWithEscapeSequence EXPECT_EQ(TransmitState::WAIT, cut.getState()); EXPECT_EQ(TransmitTimeout::FLOW_CONTROL, cut.getTimeout()); EXPECT_EQ( - TransmitResult(true).setActionSet(storeSeparationTime), + TransmitResult(true).setActionSet(getStoreSeparationTime()), cut.handleFlowControl(FlowStatus::CTS, 0, 0, 2)); EXPECT_TRUE(::etl::equal(span, cut.getSendData())); EXPECT_EQ(TransmitState::SEND, cut.getState()); @@ -247,7 +251,7 @@ TEST(DoCanMessageTransmitterTest, testMultipleFramesAreEmittedWithEscapeSequence EXPECT_EQ(TransmitState::WAIT, cut.getState()); EXPECT_EQ(TransmitTimeout::TX_CALLBACK, cut.getTimeout()); EXPECT_EQ(TransmitResult(true), cut.framesSent(51U, 51 * 7U)); - span.advance(51 * 7); + span.advance(51UL * 7UL); EXPECT_EQ(TransmitState::SEND, cut.getState()); EXPECT_EQ(TransmitTimeout::TX_CALLBACK, cut.getTimeout()); EXPECT_TRUE(::etl::equal(span, cut.getSendData())); diff --git a/libs/bsw/doip/src/doip/common/DoIpTcpConnection.cpp b/libs/bsw/doip/src/doip/common/DoIpTcpConnection.cpp index 91bd263dd2e..fb9725f634f 100644 --- a/libs/bsw/doip/src/doip/common/DoIpTcpConnection.cpp +++ b/libs/bsw/doip/src/doip/common/DoIpTcpConnection.cpp @@ -115,10 +115,8 @@ bool DoIpTcpConnection::receivePayload( tryReceive(); return true; } - else - { - return false; - } + + return false; } void DoIpTcpConnection::endReceiveMessage( @@ -166,10 +164,8 @@ bool DoIpTcpConnection::sendMessage(IDoIpSendJob& sendJob) } return true; } - else - { - return false; - } + + return false; } void DoIpTcpConnection::close() { closeConnection(ConnectionState::INACTIVE, false, true); } diff --git a/libs/bsw/doip/src/doip/common/DoIpTransportMessageProvidingListenerHelper.cpp b/libs/bsw/doip/src/doip/common/DoIpTransportMessageProvidingListenerHelper.cpp index 7059a33074d..87c0871c5e3 100644 --- a/libs/bsw/doip/src/doip/common/DoIpTransportMessageProvidingListenerHelper.cpp +++ b/libs/bsw/doip/src/doip/common/DoIpTransportMessageProvidingListenerHelper.cpp @@ -20,11 +20,9 @@ DoIpTransportMessageProvidingListenerHelper::getTransportMessage( return _transportMessageProvidingListener->getTransportMessage( sourceBusId, sourceId, targetId, size, peek, transportMessage); } - else - { - return createGetResult(_fallbackTransportMessageProvidingListener.getTransportMessage( - sourceBusId, sourceId, targetId, size, peek, transportMessage)); - } + + return createGetResult(_fallbackTransportMessageProvidingListener.getTransportMessage( + sourceBusId, sourceId, targetId, size, peek, transportMessage)); } void DoIpTransportMessageProvidingListenerHelper::releaseTransportMessage( @@ -51,11 +49,9 @@ DoIpTransportMessageProvidingListenerHelper::messageReceived( return _transportMessageProvidingListener->messageReceived( sourceBusId, transportMessage, notificationListener); } - else - { - return createReceiveResult(_fallbackTransportMessageProvidingListener.messageReceived( - sourceBusId, transportMessage, notificationListener)); - } + + return createReceiveResult(_fallbackTransportMessageProvidingListener.messageReceived( + sourceBusId, transportMessage, notificationListener)); } ::transport::ITransportMessageProvider::ErrorCode diff --git a/libs/bsw/doip/src/doip/common/DoIpUdpConnection.cpp b/libs/bsw/doip/src/doip/common/DoIpUdpConnection.cpp index 7badcf73860..41bcb8a579f 100644 --- a/libs/bsw/doip/src/doip/common/DoIpUdpConnection.cpp +++ b/libs/bsw/doip/src/doip/common/DoIpUdpConnection.cpp @@ -62,10 +62,8 @@ bool DoIpUdpConnection::receivePayload( _payloadReceivedCallback = payloadReceivedCallback; return true; } - else - { - return false; - } + + return false; } void DoIpUdpConnection::endReceiveMessage( @@ -101,10 +99,8 @@ bool DoIpUdpConnection::sendMessage(IDoIpSendJob& sendJob) } return true; } - else - { - return false; - } + + return false; } void DoIpUdpConnection::close() { closeConnection(ConnectionState::INACTIVE); } @@ -265,10 +261,8 @@ ::estd::slice DoIpUdpConnection::prepareSendBuffer(IDoIpSendJob& { return job.getSendBuffer(_writeBuffer, 0U); } - else - { - return fillWriteBuffer(job); - } + + return fillWriteBuffer(job); } void DoIpUdpConnection::closeConnection(ConnectionState const connectionState) diff --git a/libs/bsw/doip/src/doip/server/DoIpServerConnectionHandler.cpp b/libs/bsw/doip/src/doip/server/DoIpServerConnectionHandler.cpp index 9d21b282988..011640895b8 100644 --- a/libs/bsw/doip/src/doip/server/DoIpServerConnectionHandler.cpp +++ b/libs/bsw/doip/src/doip/server/DoIpServerConnectionHandler.cpp @@ -538,14 +538,12 @@ DoIpServerConnectionHandler::StaticPayloadSendJobType* DoIpServerConnectionHandl { return nullptr; } - else if (closeAfterSend) + + if (closeAfterSend) { _state = State::CLOSING; } - else - { - // no special handling here - } + // RAII mutex DoIpLock const lock; if (_sendJobPool.empty()) diff --git a/libs/bsw/doip/src/doip/server/DoIpServerTransportLayer.cpp b/libs/bsw/doip/src/doip/server/DoIpServerTransportLayer.cpp index 708824ff5b3..8fe202a8944 100644 --- a/libs/bsw/doip/src/doip/server/DoIpServerTransportLayer.cpp +++ b/libs/bsw/doip/src/doip/server/DoIpServerTransportLayer.cpp @@ -75,10 +75,8 @@ AbstractTransportLayer::ErrorCode DoIpServerTransportLayer::send( { return ErrorCode::TP_OK; } - else - { - return ErrorCode::TP_QUEUE_FULL; - } + + return ErrorCode::TP_QUEUE_FULL; } } Logger::warn( @@ -260,17 +258,15 @@ DoIpServerTransportLayer::checkRoutingActivation( oemField, isResuming); } - else if (activationType <= 0x01U) + + if (activationType <= 0x01U) { return RoutingActivationCheckResult(); } - else - { - return RoutingActivationCheckResult() - .setAction(Action::REJECT) - .setResponseCode( - DoIpConstants::RoutingResponseCodes::ROUTING_UNSUPPORTED_ACTIVATION_TYPE); - } + + return RoutingActivationCheckResult() + .setAction(Action::REJECT) + .setResponseCode(DoIpConstants::RoutingResponseCodes::ROUTING_UNSUPPORTED_ACTIVATION_TYPE); } void DoIpServerTransportLayer::routingActive(DoIpServerConnectionHandler& handler) diff --git a/libs/bsw/doip/src/doip/server/DoIpServerTransportMessageHandler.cpp b/libs/bsw/doip/src/doip/server/DoIpServerTransportMessageHandler.cpp index d21d4dc24a3..c65dbe844e7 100644 --- a/libs/bsw/doip/src/doip/server/DoIpServerTransportMessageHandler.cpp +++ b/libs/bsw/doip/src/doip/server/DoIpServerTransportMessageHandler.cpp @@ -28,6 +28,10 @@ using ::transport::TransportMessage; using ::util::logger::DOIP; using ::util::logger::Logger; +constexpr size_t DoIpServerTransportMessageHandler::PEEK_MAX_SIZE; +constexpr size_t DoIpServerTransportMessageHandler::ACK_PAYLOAD_SIZE; +constexpr size_t DoIpServerTransportMessageHandler::PAYLOAD_PREFIX_BUFFER_SIZE; + DoIpServerTransportMessageHandler::DoIpServerTransportMessageHandler( DoIpConstants::ProtocolVersion const protocolVersion, ::util::estd::block_pool& diagnosticSendJobBlockPool, @@ -148,8 +152,8 @@ DoIpTransportMessageSendJob* DoIpServerTransportMessageHandler::allocateJob( void DoIpServerTransportMessageHandler::releaseSendJob( DoIpTransportMessageSendJob& sendJob, bool const success) { - auto const busIdName = ::common::busid::BusIdTraits::getName(_config.getBusId()); - auto const sourceAddress = sendJob.getSourceAddress(); + auto const* const busIdName = ::common::busid::BusIdTraits::getName(_config.getBusId()); + auto const sourceAddress = sendJob.getSourceAddress(); if (success) { Logger::debug( @@ -179,8 +183,8 @@ void DoIpServerTransportMessageHandler::diagnosticMessageLogicalAddressInfoRecei = logicalAddressInfo.reinterpret_as<::estd::be_uint16_t const>()[0]; _payloadPeekContext.targetAddress = logicalAddressInfo.reinterpret_as<::estd::be_uint16_t const>()[1]; - auto const payloadPrefixSize = std::min( - static_cast(_receiveMessagePayloadLength), size_t(PAYLOAD_PREFIX_BUFFER_SIZE)); + auto const payloadPrefixSize + = std::min(static_cast(_receiveMessagePayloadLength), PAYLOAD_PREFIX_BUFFER_SIZE); (void)_connection->receivePayload( ::estd::make_slice(_payloadPeekContext.payloadPrefixBuffer).subslice(payloadPrefixSize), IDoIpConnection::PayloadReceivedCallbackType::create< @@ -194,8 +198,7 @@ DoIpServerTransportMessageHandler::getTpMessageAndReceiveDiagnosticUserData( uint16_t const /* targetAddress */, ::estd::slice const payloadPrefix) { - auto const peekSlice - = payloadPrefix.subslice(std::min(payloadPrefix.size(), size_t(PEEK_MAX_SIZE))); + auto const peekSlice = payloadPrefix.subslice(std::min(payloadPrefix.size(), PEEK_MAX_SIZE)); auto const getResult = _config.getMessageProvidingListener().getTransportMessage( _config.getBusId(), _connection->getInternalSourceAddress(), @@ -274,7 +277,7 @@ void DoIpServerTransportMessageHandler::diagnosticMessageUserDataPrefixReceivedN uint8_t const nackCode, bool const closeAfterSend, ::estd::slice const payload) { _connection->endReceiveMessage(IDoIpConnection::PayloadDiscardedCallbackType{}); - auto const job = queueDiagnosticAck( + auto* const job = queueDiagnosticAck( DoIpConstants::PayloadTypes::DIAGNOSTIC_MESSAGE_NEGATIVE_ACK, _payloadPeekContext.sourceAddress, _payloadPeekContext.targetAddress, diff --git a/libs/bsw/doip/src/doip/server/DoIpServerVehicleIdentification.cpp b/libs/bsw/doip/src/doip/server/DoIpServerVehicleIdentification.cpp index 6aa0e2cdbe7..cf0d13c305c 100644 --- a/libs/bsw/doip/src/doip/server/DoIpServerVehicleIdentification.cpp +++ b/libs/bsw/doip/src/doip/server/DoIpServerVehicleIdentification.cpp @@ -40,7 +40,7 @@ DoIpServerVehicleIdentification::getOemMessageHandler(uint16_t payloadType) cons { return nullptr; } - auto const oemMessageHandler = _oemMessageHandlers->find(payloadType); + auto const* const oemMessageHandler = _oemMessageHandlers->find(payloadType); if (oemMessageHandler == _oemMessageHandlers->end()) { return nullptr; diff --git a/libs/bsw/doip/src/doip/server/DoIpServerVehicleIdentificationSocketHandler.cpp b/libs/bsw/doip/src/doip/server/DoIpServerVehicleIdentificationSocketHandler.cpp index b4efec864fd..37806c3950c 100644 --- a/libs/bsw/doip/src/doip/server/DoIpServerVehicleIdentificationSocketHandler.cpp +++ b/libs/bsw/doip/src/doip/server/DoIpServerVehicleIdentificationSocketHandler.cpp @@ -221,11 +221,13 @@ bool DoIpServerVehicleIdentificationSocketHandler::checkVersion(DoIpHeader const { return false; } - else if (checkProtocolVersion(header, static_cast(_protocolVersion))) + + if (checkProtocolVersion(header, static_cast(_protocolVersion))) { return true; } - else if (checkProtocolVersion(header, 0xffU)) + + if (checkProtocolVersion(header, 0xffU)) { if ((payloadType == DoIpConstants::PayloadTypes::VEHICLE_IDENTIFICATION_REQUEST_MESSAGE) || (payloadType @@ -235,17 +237,13 @@ bool DoIpServerVehicleIdentificationSocketHandler::checkVersion(DoIpHeader const { return true; } - else - { - enqueueNack(DoIpConstants::NackCodes::NACK_UNKNOWN_PAYLOAD_TYPE); - return false; - } - } - else - { - enqueueNack(DoIpConstants::NackCodes::NACK_INCORRECT_PATTERN); + + enqueueNack(DoIpConstants::NackCodes::NACK_UNKNOWN_PAYLOAD_TYPE); return false; } + + enqueueNack(DoIpConstants::NackCodes::NACK_INCORRECT_PATTERN); + return false; } bool DoIpServerVehicleIdentificationSocketHandler::handleVehicleIdentificationRequestMessage( @@ -667,11 +665,9 @@ DoIpServerVehicleIdentificationSocketHandler::createResponse( { return createResponseOemMessage(oemMessageHandler); } - else - { - // should never be reached - return createResponseHeaderNack(nackCode); - } + + // should never be reached + return createResponseHeaderNack(nackCode); } } diff --git a/libs/bsw/doip/test/src/doip/common/DoIpCyclicTaskGeneratorTest.cpp b/libs/bsw/doip/test/src/doip/common/DoIpCyclicTaskGeneratorTest.cpp index 6c466fd3001..6327cee054f 100644 --- a/libs/bsw/doip/test/src/doip/common/DoIpCyclicTaskGeneratorTest.cpp +++ b/libs/bsw/doip/test/src/doip/common/DoIpCyclicTaskGeneratorTest.cpp @@ -17,9 +17,9 @@ struct DoIpCyclicTaskGeneratorTest : Test { DoIpCyclicTaskGeneratorTest() : asyncMock(), testContext(1U) {} - void SetUp() override { testContext.setNow(1 * 1000U); } + void SetUp() override { testContext.setNow(1000U); } - void TearDown() override { testContext.setNow(0 * 1000U); } + void TearDown() override { testContext.setNow(0U); } MOCK_METHOD0(cyclicTask, void()); @@ -39,25 +39,25 @@ TEST_F(DoIpCyclicTaskGeneratorTest, TestAll) testContext.expire(); - testContext.elapse(99 * 1000U); + testContext.elapse(static_cast(99U * 1000U)); testContext.expire(); - testContext.elapse(1 * 1000U); + testContext.elapse(1000U); EXPECT_CALL(*this, cyclicTask()); testContext.expire(); Mock::VerifyAndClearExpectations(this); - testContext.elapse(80 * 1000U); + testContext.elapse(static_cast(80U * 1000U)); testContext.expire(); - testContext.elapse(80 * 1000U); + testContext.elapse(static_cast(80U * 1000U)); EXPECT_CALL(*this, cyclicTask()); testContext.expire(); Mock::VerifyAndClearExpectations(this); cut.shutdown(); - testContext.elapse(200 * 1000U); + testContext.elapse(static_cast(200U * 1000U)); testContext.expire(); } diff --git a/libs/bsw/doip/test/src/doip/common/DoIpTcpConnectionTest.cpp b/libs/bsw/doip/test/src/doip/common/DoIpTcpConnectionTest.cpp index 820a471f353..3d8ec20468c 100644 --- a/libs/bsw/doip/test/src/doip/common/DoIpTcpConnectionTest.cpp +++ b/libs/bsw/doip/test/src/doip/common/DoIpTcpConnectionTest.cpp @@ -408,7 +408,7 @@ TEST_F(DoIpTcpConnectionTest, RepeatSendingOfUnsentMessageBlockAfterDataHasBeenQ EXPECT_CALL(fSocketMock, flush()) .InSequence(seq) .WillOnce(Return(::tcp::AbstractSocket::ErrorCode::SOCKET_ERR_OK)); - testContext.elapse(1 * 1000U); + testContext.elapse(1000U); testContext.expireAndExecute(); Mock::VerifyAndClearExpectations(&sendJobMock); Mock::VerifyAndClearExpectations(&fSocketMock); diff --git a/libs/bsw/doip/test/src/doip/server/DoIpServerConnectionHandlerTest.cpp b/libs/bsw/doip/test/src/doip/server/DoIpServerConnectionHandlerTest.cpp index 52ed6dec4a4..ae21ac8177b 100644 --- a/libs/bsw/doip/test/src/doip/server/DoIpServerConnectionHandlerTest.cpp +++ b/libs/bsw/doip/test/src/doip/server/DoIpServerConnectionHandlerTest.cpp @@ -1197,9 +1197,9 @@ TEST_F(DoIpServerConnectionHandlerTest, TestAliveCheckTimeoutExpires) ::estd::slice::from_pointer(request + 8U, 0U), sendJob->getSendBuffer(fHeaderBuffer, 1U))); // increase timer - testContext.elapse((fParameters.getAliveCheckTimeout() - 1) * 1000U); + testContext.elapse(static_cast(fParameters.getAliveCheckTimeout() - 1) * 1000U); testContext.expireAndExecute(); - testContext.elapse(1 * 1000U); + testContext.elapse(1000U); EXPECT_CALL(fMessageHandlerMock, connectionClosed()); EXPECT_CALL(fConnectionMock, close()); Sequence seq; @@ -1305,12 +1305,13 @@ TEST_F(DoIpServerConnectionHandlerTest, TestInitialTimeout) IDoIpConnection::PayloadDiscardedCallbackType{}}); // step within time - testContext.elapse((fParameters.getInitialInactivityTimeout() - 1) * 1000U); + testContext.elapse( + static_cast(fParameters.getInitialInactivityTimeout() - 1) * 1000U); testContext.expireAndExecute(); EXPECT_CALL(fMessageHandlerMock, connectionClosed()); EXPECT_CALL(fConnectionMock, close()); EXPECT_CALL(fCallbackMock, connectionClosed(Ref(cut))); - testContext.elapse(1 * 1000U); + testContext.elapse(1000U); testContext.expireAndExecute(); // now start alive check and expect negative response } @@ -1391,13 +1392,14 @@ TEST_F(DoIpServerConnectionHandlerTest, TestGeneralInactivityTimeout) ::estd::slice::from_pointer(activationResponse + 8U, 9U), sendJob->getSendBuffer(fHeaderBuffer, 1U))); // Routing is active => now general inactivity timer should expire if no message is sent - testContext.elapse((fParameters.getGeneralInactivityTimeout() - 1) * 1000U); + testContext.elapse( + static_cast(fParameters.getGeneralInactivityTimeout() - 1) * 1000U); testContext.expireAndExecute(); EXPECT_CALL(fMessageHandlerMock, connectionClosed()); EXPECT_CALL(fConnectionMock, setCloseMode(IDoIpTcpConnection::CloseMode::ABORT)); EXPECT_CALL(fConnectionMock, close()); EXPECT_CALL(fCallbackMock, connectionClosed(Ref(cut))); - testContext.elapse(1 * 1000U); + testContext.elapse(1000U); testContext.expireAndExecute(); // now start alive check and expect negative response } @@ -1431,7 +1433,7 @@ TEST_F(DoIpServerConnectionHandlerTest, TestTimeoutDuringSendingNack) Mock::VerifyAndClearExpectations(&fConnectionMock); EXPECT_TRUE(sendJob != nullptr); // Timeout will be ignored - testContext.elapse(fParameters.getGeneralInactivityTimeout() * 1000U); + testContext.elapse(static_cast(fParameters.getGeneralInactivityTimeout()) * 1000U); testContext.expireAndExecute(); // close expected EXPECT_CALL(fMessageHandlerMock, connectionClosed()); diff --git a/libs/bsw/doip/test/src/doip/server/DoIpServerSocketHandlerTest.cpp b/libs/bsw/doip/test/src/doip/server/DoIpServerSocketHandlerTest.cpp index 2c7a18bc8a2..5b0fbdca4f7 100644 --- a/libs/bsw/doip/test/src/doip/server/DoIpServerSocketHandlerTest.cpp +++ b/libs/bsw/doip/test/src/doip/server/DoIpServerSocketHandlerTest.cpp @@ -125,7 +125,8 @@ TEST_P(DoIpServerSocketHandlerTest, SimpleServerLifecycle) Mock::VerifyAndClearExpectations(&serverSocketMock1); // unknown config has changed - fNetworkInterfaceConfigRegistryMock.configChangedSignal(NetworkInterfaceConfigKey(1U), config2); + fNetworkInterfaceConfigRegistryMock.configChangedSignal( + static_cast(1U), config2); EXPECT_CALL(serverSocketMock1, isClosed()).WillOnce(Return(true)); EXPECT_CALL(serverSocketMock2, isClosed()).WillOnce(Return(false)); diff --git a/libs/bsw/doip/test/src/doip/server/DoIpServerTransportLayerTest.cpp b/libs/bsw/doip/test/src/doip/server/DoIpServerTransportLayerTest.cpp index 22374bbabce..027548a5330 100644 --- a/libs/bsw/doip/test/src/doip/server/DoIpServerTransportLayerTest.cpp +++ b/libs/bsw/doip/test/src/doip/server/DoIpServerTransportLayerTest.cpp @@ -1260,7 +1260,6 @@ TEST_F( .InSequence(seq) .WillOnce( Invoke(ReadBytesFrom(::estd::slice::from_pointer(messagePtr, 4U)))); - messagePtr += 4; EXPECT_CALL( fMessageProvidingListenerMock, getTransportMessage(fBusId, 0x1234, 0x1519, 3, _, _)) @@ -1814,7 +1813,7 @@ TEST_F(DoIpServerTransportLayerTest, TestAliveCheckWithInactiveRegisteredSource) .WillOnce(Return(::tcp::AbstractSocket::ErrorCode::SOCKET_ERR_OK)); EXPECT_CALL(fConnectionPoolMock, releaseConnection(Ref(fConnection1))); EXPECT_CALL(fSocketHandlerMock, releaseSocket(Ref(fSocketMock1), ConnectionType::PLAIN)); - testContext.elapse(fParameters.getAliveCheckTimeout() * 1000U); + testContext.elapse(static_cast(fParameters.getAliveCheckTimeout()) * 1000U); testContext.expireAndExecute(); ASSERT_THAT(response, ElementsAreArray(expectedResponse)); endRoutingActivationResponse(fSocketMock2); @@ -2096,8 +2095,8 @@ void DoIpServerTransportLayerTest::expectRoutingActivationRequest( 0x00, 0x00, 0x07, - uint8_t((sourceAddress >> 8) & 0xff), - uint8_t(sourceAddress & 0xff), + static_cast((sourceAddress >> 8) & 0xff), + static_cast(sourceAddress & 0xff), activationType, 0x00, 0x00, @@ -2156,8 +2155,8 @@ void DoIpServerTransportLayerTest::expectAliveCheckResponse( 0x00, 0x00, 0x02, - uint8_t((sourceAddress >> 8) & 0xff), - uint8_t(sourceAddress & 0xff)}; + static_cast((sourceAddress >> 8) & 0xff), + static_cast(sourceAddress & 0xff)}; ::estd::slice response = allocateBuffer(sizeof(responseData)); ::estd::memory::copy(response, responseData); diff --git a/libs/bsw/doip/test/src/doip/server/DoIpServerVehicleIdentificationSocketHandlerTest.cpp b/libs/bsw/doip/test/src/doip/server/DoIpServerVehicleIdentificationSocketHandlerTest.cpp index 8ee168fc55c..481cbd5d542 100644 --- a/libs/bsw/doip/test/src/doip/server/DoIpServerVehicleIdentificationSocketHandlerTest.cpp +++ b/libs/bsw/doip/test/src/doip/server/DoIpServerVehicleIdentificationSocketHandlerTest.cpp @@ -256,7 +256,7 @@ TEST_F(DoIpServerVehicleIdentificationSocketHandlerTest, IgnoreUnknownNetworkCon cut.start(); fNetworkInterfaceConfigRegistryMock.configChangedSignal( - ::ip::NetworkInterfaceConfigKey(1U), config); + static_cast<::ip::NetworkInterfaceConfigKey>(1U), config); cut.shutdown(); @@ -755,7 +755,7 @@ TEST_F(DoIpServerVehicleIdentificationSocketHandlerTest, SendAnnouncementsToUnic .WillRepeatedly(Return(fParametersMock.getAnnounceWait())); cut.updateUnicastAddresses(configKey, unicastAddresses); testContext.expireAndExecute(); - testContext.elapse(1 * 1000U); + testContext.elapse(1000U); testContext.expireAndExecute(); // expect unicast packets first broadcast @@ -1031,7 +1031,7 @@ TEST_F(DoIpServerVehicleIdentificationSocketHandlerTest, AnnouncementTimeouts) tick(2896U); // 10 more seconds pass, nothing should happen - testContext.elapse(10000U * 1000U); + testContext.elapse(static_cast(10000U * 1000U)); testContext.expireAndExecute(); EXPECT_CALL(*fSocketMock, close()); cut.shutdown(); @@ -1276,7 +1276,7 @@ void DoIpServerVehicleIdentificationSocketHandlerTest::expectEntityStatusRespons void DoIpServerVehicleIdentificationSocketHandlerTest::tick(uint32_t epochTime) { - testContext.setNow(epochTime * 1000); + testContext.setNow(static_cast(epochTime) * 1000U); testContext.expireAndExecute(); Mock::VerifyAndClearExpectations(fSocketMock); Mock::VerifyAndClearExpectations(&timerMock); diff --git a/libs/bsw/doip/test/src/doip/server/DoIpServerVehicleIdentificationTest.cpp b/libs/bsw/doip/test/src/doip/server/DoIpServerVehicleIdentificationTest.cpp index f5a939f69d3..85e70a53d0e 100644 --- a/libs/bsw/doip/test/src/doip/server/DoIpServerVehicleIdentificationTest.cpp +++ b/libs/bsw/doip/test/src/doip/server/DoIpServerVehicleIdentificationTest.cpp @@ -21,8 +21,7 @@ struct DoIpServerVehicleIdentificationTest : Test DoIpServerVehicleIdentificationTest() { ON_CALL(fVehicleIdentificationCallbackMock, getPowerMode()) - .WillByDefault(Return( - DoIpConstants::DiagnosticPowerMode(DoIpConstants::DiagnosticPowerMode::READY))); + .WillByDefault(Return(DoIpConstants::DiagnosticPowerMode::READY)); } doip::DoIpServerVehicleIdentificationCallbackMock fVehicleIdentificationCallbackMock; diff --git a/libs/bsw/io/test/src/io/BufferedWriterTest.cpp b/libs/bsw/io/test/src/io/BufferedWriterTest.cpp index 625cd6ad109..1be99d7b43e 100644 --- a/libs/bsw/io/test/src/io/BufferedWriterTest.cpp +++ b/libs/bsw/io/test/src/io/BufferedWriterTest.cpp @@ -13,8 +13,8 @@ namespace { struct BufferedWriterTest : ::testing::Test { - static size_t const QUEUE_SIZE = 10 * 1024; - static size_t const MAX_ELEMENT_SIZE = 1024; + static constexpr size_t MAX_ELEMENT_SIZE = 1024UL; + static constexpr size_t QUEUE_SIZE = MAX_ELEMENT_SIZE * 10UL; using Q = ::io::MemoryQueue; @@ -27,8 +27,8 @@ struct BufferedWriterTest : ::testing::Test ::io::BufferedWriter _bmqw; }; -size_t const BufferedWriterTest::QUEUE_SIZE; -size_t const BufferedWriterTest::MAX_ELEMENT_SIZE; +constexpr size_t BufferedWriterTest::QUEUE_SIZE; +constexpr size_t BufferedWriterTest::MAX_ELEMENT_SIZE; /** * \refs: SMD_io_BufferedWriter @@ -70,7 +70,7 @@ TEST_F(BufferedWriterTest, allocate_max_size_will_return_max_size_slice) */ TEST_F(BufferedWriterTest, allocate_on_full_writer_will_return_empty_slice) { - for (size_t i = 0; i < 10 * 10; ++i) + for (size_t i = 0; i < 100U; ++i) { auto const b = _bmqw.allocate(100); ASSERT_EQ(100, b.size()) << "@" << i; diff --git a/libs/bsw/io/test/src/io/MemoryQueueTest.cpp b/libs/bsw/io/test/src/io/MemoryQueueTest.cpp index dd432ed9d70..266c0a39318 100644 --- a/libs/bsw/io/test/src/io/MemoryQueueTest.cpp +++ b/libs/bsw/io/test/src/io/MemoryQueueTest.cpp @@ -35,9 +35,9 @@ size_t const MemoryQueueTest::MAX_ELEMENT_SIZE; template struct MemoryQueueTypedTest : public ::testing::Test { - static size_t const QUEUE_SIZE = Q::capacity(); - static size_t const MAX_ELEMENT_SIZE = Q::maxElementSize(); - static size_t const NUM_POSSIBLE_MAX_ELEMENT_SIZE_ALLOCATIONS + static constexpr size_t QUEUE_SIZE = Q::capacity(); + static constexpr size_t MAX_ELEMENT_SIZE = Q::maxElementSize(); + static constexpr size_t NUM_POSSIBLE_MAX_ELEMENT_SIZE_ALLOCATIONS = (QUEUE_SIZE / (MAX_ELEMENT_SIZE + sizeof(typename Q::size_type))); MemoryQueueTypedTest() : _q(), _w(_q), _r(_q) {} diff --git a/libs/bsw/io/test/src/io/VariantQueueTest.cpp b/libs/bsw/io/test/src/io/VariantQueueTest.cpp index d28881e81f9..ce7238566ab 100644 --- a/libs/bsw/io/test/src/io/VariantQueueTest.cpp +++ b/libs/bsw/io/test/src/io/VariantQueueTest.cpp @@ -147,7 +147,7 @@ TEST(VariantQueue, manually_allocate_header) Visit visitor; - auto const b = abc_queue::alloc_header(writer); + auto* const b = abc_queue::alloc_header(writer); ASSERT_NE(b, nullptr); b->x = 42; b->y = 1337; diff --git a/libs/bsw/logger/include/logger/EntrySerializer.h b/libs/bsw/logger/include/logger/EntrySerializer.h index 040413c8324..048a57b2a79 100644 --- a/libs/bsw/logger/include/logger/EntrySerializer.h +++ b/libs/bsw/logger/include/logger/EntrySerializer.h @@ -175,9 +175,9 @@ void EntrySerializer::deserialize( ::etl::span const& srcBuffer, IEntrySerializerCallback& callback) { EntryReader reader(srcBuffer.data(), srcBuffer.data() + srcBuffer.size()); - Timestamp timestamp; - uint8_t componentIdx; - uint8_t level; + Timestamp timestamp{}; + uint8_t componentIdx{}; + uint8_t level{}; reader.readBytes(×tamp, static_cast(sizeof(timestamp))); reader.readBytes(&componentIdx, static_cast(sizeof(componentIdx))); reader.readBytes(&level, static_cast(sizeof(level))); diff --git a/libs/bsw/logger/test/src/logger/BufferedLoggerOutputTest.cpp b/libs/bsw/logger/test/src/logger/BufferedLoggerOutputTest.cpp index 88a7e5492eb..7016b9c57cf 100644 --- a/libs/bsw/logger/test/src/logger/BufferedLoggerOutputTest.cpp +++ b/libs/bsw/logger/test/src/logger/BufferedLoggerOutputTest.cpp @@ -68,6 +68,7 @@ struct BufferedLoggerOutputTest writer.printf("%d", timestamp); } + // NOLINTBEGIN(cert-dcl50-cpp): va_list usage only for this test file. template void callLogOutput( T& buffer, @@ -82,6 +83,8 @@ struct BufferedLoggerOutputTest va_end(ap); } + // NOLINTEND(cert-dcl50-cpp) + void setTimestamp(uint32_t timestamp) { _timestamp = timestamp; } bool checkAndResetEntry(char const* expected) @@ -102,6 +105,7 @@ LOGGER_COMPONENT_MAPPING_INFO(LEVEL_DEBUG, CONF2) LOGGER_COMPONENT_MAPPING_INFO(LEVEL_DEBUG, CONF3) END_LOGGER_COMPONENT_MAPPING_INFO_TABLE(); +// NOLINTBEGIN(cert-err58-cpp): Instantiation of variable is done by macro. DEFINE_LOGGER_COMPONENT_MAPPING( TestMappingType, testMapping, @@ -109,6 +113,8 @@ DEFINE_LOGGER_COMPONENT_MAPPING( ::util::logger::LevelInfo::getDefaultTable(), CONF1); +// NOLINTEND(cert-err58-cpp) + TEST_F(BufferedLoggerOutputTest, testAll) { declare::BufferedLoggerOutput<4096, TestLock> cut(testMapping, *this); diff --git a/libs/bsw/logger/test/src/logger/ComponentConfigTest.cpp b/libs/bsw/logger/test/src/logger/ComponentConfigTest.cpp index e80af448d33..96faa2d76aa 100644 --- a/libs/bsw/logger/test/src/logger/ComponentConfigTest.cpp +++ b/libs/bsw/logger/test/src/logger/ComponentConfigTest.cpp @@ -39,9 +39,13 @@ LOGGER_COMPONENT_MAPPING_INFO(LEVEL_NONE, _CONF2) LOGGER_COMPONENT_MAPPING_INFO(LEVEL_NONE, _CONF3) END_LOGGER_COMPONENT_MAPPING_INFO_TABLE(); +// NOLINTBEGIN(cert-err58-cpp): Instantiation of variable is done by macro. + DEFINE_LOGGER_COMPONENT_MAPPING( TestMappingType, testMapping, componentInfoTable, LevelInfo::getDefaultTable(), _CONF1); +// NOLINTEND(cert-err58-cpp) + TEST_F(ComponentConfigTest, testBasicFunctionality) { ComponentConfig cut(testMapping); diff --git a/libs/bsw/logger/test/src/logger/DefaultLoggerCommandTest.cpp b/libs/bsw/logger/test/src/logger/DefaultLoggerCommandTest.cpp index e9ede9db397..a6ad87334a9 100644 --- a/libs/bsw/logger/test/src/logger/DefaultLoggerCommandTest.cpp +++ b/libs/bsw/logger/test/src/logger/DefaultLoggerCommandTest.cpp @@ -31,9 +31,12 @@ LOGGER_COMPONENT_MAPPING_INFO(LEVEL_DEBUG, _CONF2) LOGGER_COMPONENT_MAPPING_INFO(LEVEL_NONE, _CONF3) END_LOGGER_COMPONENT_MAPPING_INFO_TABLE(); +// NOLINTBEGIN(cert-err58-cpp): Instantiation of variable is done by macro. DEFINE_LOGGER_COMPONENT_MAPPING( TestMappingType, testMapping, componentInfoTable, LevelInfo::getDefaultTable(), _CONF1); +// NOLINTEND(cert-err58-cpp) + struct DefaultLoggerCommandTest : Test { ::util::stream::declare::StringBufferOutputStream<100> stream; diff --git a/libs/bsw/logger/test/src/logger/EntryBufferTest.cpp b/libs/bsw/logger/test/src/logger/EntryBufferTest.cpp index c0040449caf..cdc78bb26d7 100644 --- a/libs/bsw/logger/test/src/logger/EntryBufferTest.cpp +++ b/libs/bsw/logger/test/src/logger/EntryBufferTest.cpp @@ -17,7 +17,7 @@ struct EntryBufferTest : ::testing::Test B& buffer, typename B::EntryRef& entryRef, int32_t expectedIdx = -1, int32_t entrySize = -1) { ::etl::span const* pEntry = nullptr; - if (expectedIdx >= 0 && expectedIdx < int32_t(fEntries.size())) + if (expectedIdx >= 0 && expectedIdx < static_cast(fEntries.size())) { pEntry = &(*(fEntries.begin() + expectedIdx)); } diff --git a/libs/bsw/logger/test/src/logger/EntrySerializerTest.cpp b/libs/bsw/logger/test/src/logger/EntrySerializerTest.cpp index 6d269159f9f..0eb3197cb99 100644 --- a/libs/bsw/logger/test/src/logger/EntrySerializerTest.cpp +++ b/libs/bsw/logger/test/src/logger/EntrySerializerTest.cpp @@ -15,6 +15,7 @@ struct EntrySerializerTest : ::testing::Test , private IEntrySerializerCallback { + // NOLINTNEXTLINE(cert-dcl50-cpp): va_list usage only in these tests. std::string const& serializeAndDeserialize( uint32_t bufferSize, uint32_t timestamp, @@ -43,8 +44,9 @@ struct EntrySerializerTest char const* addConstString(char const* string) { - char* destString = _constStrings + _nextConstStringOffset; - strcpy(destString, string); + size_t const maxSize = sizeof(_constStrings) - _nextConstStringOffset; + char* destString = _constStrings + _nextConstStringOffset; + etl::strncpy(destString, string, maxSize); _nextConstStringOffset += strlen(destString) + 1; return destString; } diff --git a/libs/bsw/logger/test/src/logger/PersistentComponentConfigTest.cpp b/libs/bsw/logger/test/src/logger/PersistentComponentConfigTest.cpp index 3487dd2803b..434e5479438 100644 --- a/libs/bsw/logger/test/src/logger/PersistentComponentConfigTest.cpp +++ b/libs/bsw/logger/test/src/logger/PersistentComponentConfigTest.cpp @@ -51,8 +51,10 @@ LOGGER_COMPONENT_MAPPING_INFO(LEVEL_NONE, CONF1) LOGGER_COMPONENT_MAPPING_INFO(LEVEL_NONE, CONF2) END_LOGGER_COMPONENT_MAPPING_INFO_TABLE(); +// NOLINTBEGIN(cert-err58-cpp): Instantiation of variable is done by macro. DEFINE_LOGGER_COMPONENT_MAPPING( TestMappingType, testMapping, componentInfoTable, LevelInfo::getDefaultTable(), CONF1); +// NOLINTEND(cert-err58-cpp) } // namespace mapping1 @@ -64,8 +66,10 @@ LOGGER_COMPONENT_MAPPING_INFO(LEVEL_NONE, CONF2) LOGGER_COMPONENT_MAPPING_INFO(LEVEL_NONE, CONF3) END_LOGGER_COMPONENT_MAPPING_INFO_TABLE(); +// NOLINTBEGIN(cert-err58-cpp): Instantiation of variable is done by macro. DEFINE_LOGGER_COMPONENT_MAPPING( TestMappingType, testMapping, componentInfoTable, LevelInfo::getDefaultTable(), CONF1); +// NOLINTEND(cert-err58-cpp) } // namespace mapping2 @@ -77,8 +81,10 @@ LOGGER_COMPONENT_MAPPING_INFO(LEVEL_NONE, CONF1) LOGGER_COMPONENT_MAPPING_INFO(LEVEL_NONE, CONF2) END_LOGGER_COMPONENT_MAPPING_INFO_TABLE(); +// NOLINTBEGIN(cert-err58-cpp): Instantiation of variable is done by macro. DEFINE_LOGGER_COMPONENT_MAPPING( TestMappingType, testMapping, componentInfoTable, LevelInfo::getDefaultTable(), CONF1); +// NOLINTEND(cert-err58-cpp) } // namespace mapping3 @@ -88,8 +94,10 @@ START_LOGGER_COMPONENT_MAPPING_INFO_TABLE(componentInfoTable) LOGGER_COMPONENT_MAPPING_INFO(LEVEL_NONE, CONF1) END_LOGGER_COMPONENT_MAPPING_INFO_TABLE(); +// NOLINTBEGIN(cert-err58-cpp): Instantiation of variable is done by macro. DEFINE_LOGGER_COMPONENT_MAPPING( TestMappingType, testMapping, componentInfoTable, LevelInfo::getDefaultTable(), CONF1); +// NOLINTEND(cert-err58-cpp) } // namespace mapping4 diff --git a/libs/bsw/loggerIntegration/src/logger/LoggerTime.cpp b/libs/bsw/loggerIntegration/src/logger/LoggerTime.cpp index fdad3203d42..3727802d948 100644 --- a/libs/bsw/loggerIntegration/src/logger/LoggerTime.cpp +++ b/libs/bsw/loggerIntegration/src/logger/LoggerTime.cpp @@ -38,8 +38,8 @@ void LoggerTime::formatTimestamp( size_t const timestampBufferSize = 50; char timestampBuffer[timestampBufferSize]; - ::std::tm* localTime = ::std::localtime(&seconds); - int timestampLength = 0; + ::std::tm* localTime = ::std::localtime(&seconds); + size_t timestampLength = 0; if (timestamp < NO_INIT_BOUNDARY) { @@ -52,7 +52,7 @@ void LoggerTime::formatTimestamp( = ::std::strftime(timestampBuffer, timestampBufferSize, _timestampFormat, localTime); } - if (timestampLength != 0) + if (timestampLength > 0) { int n = snprintf( timestampBuffer + timestampLength, diff --git a/libs/bsw/lwipSocket/src/lwipSocket/tcp/LwipSocket.cpp b/libs/bsw/lwipSocket/src/lwipSocket/tcp/LwipSocket.cpp index 6dd005f78e1..cf957925323 100644 --- a/libs/bsw/lwipSocket/src/lwipSocket/tcp/LwipSocket.cpp +++ b/libs/bsw/lwipSocket/src/lwipSocket/tcp/LwipSocket.cpp @@ -23,7 +23,7 @@ extern "C" namespace { err_t const ERR_NO_MORE_BUF = -100; -} +} // namespace namespace tcp { @@ -61,52 +61,40 @@ AbstractSocket::ErrorCode LwipSocket::send(::etl::span const& dat logger::Logger::warn(logger::TCP, "LwipSocket::send() called on closed or closing socket!"); return AbstractSocket::ErrorCode::SOCKET_ERR_NOT_OPEN; } - else - { - if ((0L == fPendingTcpData.size()) && (data.size() > 0U)) - { // no data is pending - logger::Logger::debug( - logger::TCP, - "LwipSocket::send(%x, %u) no data is pending!", - data.data(), - data.size()); - if (available() > 0) + + if ((0L == fPendingTcpData.size()) && (data.size() > 0U)) + { // no data is pending + logger::Logger::debug( + logger::TCP, "LwipSocket::send(%x, %u) no data is pending!", data.data(), data.size()); + if (available() > 0) + { + fPendingTcpData = data; + + err_t const e = sendPendingData(fpHandle); + if (e == ERR_OK) { - fPendingTcpData = data; + return AbstractSocket::ErrorCode::SOCKET_ERR_OK; + } - err_t const e = sendPendingData(fpHandle); - if (e == ERR_OK) - { - return AbstractSocket::ErrorCode::SOCKET_ERR_OK; - } - else if (e == ERR_NO_MORE_BUF) - { - // wait for send ack before return - return AbstractSocket::ErrorCode::SOCKET_ERR_NO_MORE_BUFFER; - } - else if (e == ERR_MEM) - { - fPendingTcpData = {}; - // flush and wait for send ack before return - return AbstractSocket::ErrorCode::SOCKET_FLUSH; - } - else - { - fPendingTcpData = {}; - return AbstractSocket::ErrorCode::SOCKET_ERR_NOT_OK; - } + if (e == ERR_NO_MORE_BUF) + { + // wait for send ack before return + return AbstractSocket::ErrorCode::SOCKET_ERR_NO_MORE_BUFFER; } - else + + // flush pending data + fPendingTcpData = {}; + if (e == ERR_MEM) { - // wait for send ack before retry - return AbstractSocket::ErrorCode::SOCKET_ERR_NOT_OK; + // wait for send ack before return + return AbstractSocket::ErrorCode::SOCKET_FLUSH; } } - else - { - return AbstractSocket::ErrorCode::SOCKET_FLUSH; - } + // wait for send ack before retry + return AbstractSocket::ErrorCode::SOCKET_ERR_NOT_OK; } + + return AbstractSocket::ErrorCode::SOCKET_FLUSH; } err_t LwipSocket::tcpSentListener(void* const arg, tcp_pcb* const pcb, uint16_t const len) @@ -145,7 +133,12 @@ err_t LwipSocket::sendPendingData(tcp_pcb* const pcb) return checkResult(ERR_OK); } - size_t const availableBuffer = static_cast(tcp_sndbuf(pcb)); + size_t availableBuffer{0U}; + if (pcb != nullptr) + { + availableBuffer = static_cast(tcp_sndbuf(pcb)); + }; + if (availableBuffer == 0U) { return checkResult(ERR_MEM); @@ -474,10 +467,7 @@ AbstractSocket::ErrorCode LwipSocket::flush() } return AbstractSocket::ErrorCode::SOCKET_ERR_OK; } - else - { - return AbstractSocket::ErrorCode::SOCKET_ERR_NOT_OPEN; - } + return AbstractSocket::ErrorCode::SOCKET_ERR_NOT_OPEN; } uint8_t LwipSocket::read(uint8_t& byte) @@ -488,10 +478,8 @@ uint8_t LwipSocket::read(uint8_t& byte) byte = value[0]; return 1U; } - else - { - return 0U; - } + + return 0U; } size_t LwipSocket::read(uint8_t* buffer, size_t n) @@ -537,10 +525,7 @@ size_t LwipSocket::read(uint8_t* buffer, size_t n) } return n; } - else - { - return 0; - } + return 0; } void LwipSocket::discardData() @@ -705,10 +690,7 @@ err_t LwipSocket::checkResult(err_t const error) const { return ERR_ABRT; } - else - { - return error; - } + return error; } void LwipSocket::enableKeepAlive( diff --git a/libs/bsw/lwipSocket/src/lwipSocket/udp/LwipDatagramSocket.cpp b/libs/bsw/lwipSocket/src/lwipSocket/udp/LwipDatagramSocket.cpp index c7fce2a2502..0fd0ed90198 100644 --- a/libs/bsw/lwipSocket/src/lwipSocket/udp/LwipDatagramSocket.cpp +++ b/libs/bsw/lwipSocket/src/lwipSocket/udp/LwipDatagramSocket.cpp @@ -135,13 +135,7 @@ AbstractDatagramSocket::ErrorCode LwipDatagramSocket::join(ip::IPAddress const& } err_t const status = igmp_joingroup(ip_2_ip4(&fpRxPcb->local_ip), ip_2_ip4(&lwipGroupAddr)); - if (status == ERR_OK) - { - logger::Logger::info(logger::UDP, "DatagramSocket joined the group"); - fMulticastPcbs.push_back(pRxMulticastPcb); - return AbstractDatagramSocket::ErrorCode::UDP_SOCKET_OK; - } - else + if (status != ERR_OK) { logger::Logger::error( logger::UDP, @@ -149,6 +143,9 @@ AbstractDatagramSocket::ErrorCode LwipDatagramSocket::join(ip::IPAddress const& status); return AbstractDatagramSocket::ErrorCode::UDP_SOCKET_NOT_OK; } + + logger::Logger::info(logger::UDP, "DatagramSocket joined the group"); + fMulticastPcbs.push_back(pRxMulticastPcb); } #else return AbstractDatagramSocket::ErrorCode::UDP_SOCKET_NOT_OK; @@ -176,25 +173,26 @@ AbstractDatagramSocket::ErrorCode LwipDatagramSocket::join(ip::IPAddress const& pRxMulticastPcb->remote_ip = fpRxPcb->local_ip; udp_recv(pRxMulticastPcb, &udpReceiveListener, static_cast(this)); } - if (mld6_joingroup(ip_2_ip6(&fpRxPcb->local_ip), ip_2_ip6(&lwipGroupAddr)) == ERR_OK) + if (mld6_joingroup(ip_2_ip6(&fpRxPcb->local_ip), ip_2_ip6(&lwipGroupAddr)) != ERR_OK) { - fMulticastPcbs.push_back(pRxMulticastPcb); - return AbstractDatagramSocket::ErrorCode::UDP_SOCKET_OK; + return AbstractDatagramSocket::ErrorCode::UDP_SOCKET_NOT_OK; } + + fMulticastPcbs.push_back(pRxMulticastPcb); } #else return AbstractDatagramSocket::ErrorCode::UDP_SOCKET_NOT_OK; #endif // LWIP_IPV6 } - return AbstractDatagramSocket::ErrorCode::UDP_SOCKET_NOT_OK; + return AbstractDatagramSocket::ErrorCode::UDP_SOCKET_OK; } bool LwipDatagramSocket::isAlreadyJoined(ip::IPAddress const& ip) const { ip_addr_t groupAddr = lwiputils::to_lwipIp(ip); - for (auto it = fMulticastPcbs.begin(); it != fMulticastPcbs.end(); ++it) + for (auto const* it = fMulticastPcbs.begin(); it != fMulticastPcbs.end(); ++it) { if (ip_addr_cmp(&(*it)->local_ip, &groupAddr) != 0) { @@ -280,10 +278,8 @@ size_t LwipDatagramSocket::read(uint8_t* buffer, size_t n) } return n; } - else - { - return 0; - } + + return 0; } AbstractDatagramSocket::ErrorCode LwipDatagramSocket::connect( @@ -445,7 +441,6 @@ LwipDatagramSocket::ErrorCode LwipDatagramSocket::send(DatagramPacket const& pac logger::UDP, "LwipDatagramSocket::send() failed (status:0x%x)!", status); return AbstractDatagramSocket::ErrorCode::UDP_SOCKET_NOT_OK; } - return AbstractDatagramSocket::ErrorCode::UDP_SOCKET_OK; } else { @@ -466,8 +461,9 @@ LwipDatagramSocket::ErrorCode LwipDatagramSocket::send(DatagramPacket const& pac logger::UDP, "LwipDatagramSocket::send() failed (status:0x%x)!", status); return AbstractDatagramSocket::ErrorCode::UDP_SOCKET_NOT_OK; } - return AbstractDatagramSocket::ErrorCode::UDP_SOCKET_OK; } + + return AbstractDatagramSocket::ErrorCode::UDP_SOCKET_OK; } void LwipDatagramSocket::close() @@ -480,7 +476,7 @@ void LwipDatagramSocket::close() udp_remove(fpRxPcb); fpRxPcb = nullptr; } - for (auto it = fMulticastPcbs.begin(); it != fMulticastPcbs.end(); ++it) + for (auto* it = fMulticastPcbs.begin(); it != fMulticastPcbs.end(); ++it) { udp_remove(*it); } diff --git a/libs/bsw/lwipSocket/src/lwipSocket/utils/FilterFrame.cpp b/libs/bsw/lwipSocket/src/lwipSocket/utils/FilterFrame.cpp index 7d16513de37..3eadb677508 100644 --- a/libs/bsw/lwipSocket/src/lwipSocket/utils/FilterFrame.cpp +++ b/libs/bsw/lwipSocket/src/lwipSocket/utils/FilterFrame.cpp @@ -93,8 +93,8 @@ bool processPbufQueue( auto const queued = receiver.size(); for (size_t i = 0; i < queued; ++i) { - auto const p = receiver.read(); - auto const pNetIf = filterETHFrames(p, lwnetifs, vlanIds); + auto* const p = receiver.read(); + auto* const pNetIf = filterETHFrames(p, lwnetifs, vlanIds); if ((pNetIf != nullptr) && (pNetIf->input != nullptr)) { (void)pNetIf->input(p, pNetIf); @@ -162,14 +162,11 @@ ::ip::IPAddress from_lwipIp(ip_addr_t const& lwipIp) ::etl::span const ip4Slice = ::etl::span(lwipIp4Ptr, 1U); return ::ip::make_ip4(ip4Slice.reinterpret_as()); } - else - { #if LWIP_IPV6 - ::etl::span const ip6Slice(ip_2_ip6(&lwipIp)->addr); - return ::ip::make_ip6(ip6Slice.reinterpret_as()); + ::etl::span const ip6Slice(ip_2_ip6(&lwipIp)->addr); + return ::ip::make_ip6(ip6Slice.reinterpret_as()); #else - return ::ip::IPAddress(); + return ::ip::IPAddress(); #endif - } } } // namespace lwiputils diff --git a/libs/bsw/runtime/test/src/SharedStatisticsContainerTest.cpp b/libs/bsw/runtime/test/src/SharedStatisticsContainerTest.cpp index 06cdcdd2c2d..c19489f50cb 100644 --- a/libs/bsw/runtime/test/src/SharedStatisticsContainerTest.cpp +++ b/libs/bsw/runtime/test/src/SharedStatisticsContainerTest.cpp @@ -16,6 +16,8 @@ using namespace ::testing; using namespace ::runtime; using namespace ::estd::test; +// NOLINTBEGIN(cert-oop54-cpp): This is intentional for testing purposes. +// NOLINTBEGIN(bugprone-unhandled-self-assignment): This is intentional for testing purposes. struct TestStatistics { TestStatistics& operator=(TestStatistics const& src) @@ -27,6 +29,9 @@ struct TestStatistics TestStatistics const* _assignedFrom = nullptr; }; +// NOLINTEND(bugprone-unhandled-self-assignment) +// NOLINTEND(cert-oop54-cpp) + struct TestEntry : public TestStatistics {}; diff --git a/libs/bsw/runtime/test/src/StatisticsContainerTest.cpp b/libs/bsw/runtime/test/src/StatisticsContainerTest.cpp index f940d8af333..227656f4a52 100644 --- a/libs/bsw/runtime/test/src/StatisticsContainerTest.cpp +++ b/libs/bsw/runtime/test/src/StatisticsContainerTest.cpp @@ -13,6 +13,8 @@ using namespace ::testing; using namespace ::runtime; using namespace ::estd::test; +// NOLINTBEGIN(cert-oop54-cpp): This is intentional for testing purposes. +// NOLINTBEGIN(bugprone-unhandled-self-assignment): This is intentional for testing purposes. struct TestStatistics { TestStatistics& operator=(TestStatistics const& src) @@ -24,6 +26,9 @@ struct TestStatistics TestStatistics const* _assignedFrom = nullptr; }; +// NOLINTEND(bugprone-unhandled-self-assignment) +// NOLINTEND(cert-oop54-cpp) + struct TestEntry : public TestStatistics {}; diff --git a/libs/bsw/stdioConsoleInput/src/console/StdioConsoleInput.cpp b/libs/bsw/stdioConsoleInput/src/console/StdioConsoleInput.cpp index 793865d5654..2834c8e0c68 100644 --- a/libs/bsw/stdioConsoleInput/src/console/StdioConsoleInput.cpp +++ b/libs/bsw/stdioConsoleInput/src/console/StdioConsoleInput.cpp @@ -35,7 +35,7 @@ constexpr char MAX_VALID_CHR = 0x7EU; // tilde */ bool getline(::etl::istring& line) { - char const chr = getByteFromStdin(); + char const chr = static_cast(getByteFromStdin()); if (chr <= 0) { diff --git a/libs/bsw/timer/test/src/TimerTest.cpp b/libs/bsw/timer/test/src/TimerTest.cpp index aa748316a21..aab21d26f37 100644 --- a/libs/bsw/timer/test/src/TimerTest.cpp +++ b/libs/bsw/timer/test/src/TimerTest.cpp @@ -48,6 +48,7 @@ struct LockPolicyMock } } + // NOLINTBEGIN(bugprone-exception-escape): This is just for testing purposes. ~LockPolicyMock() { if (_lock) @@ -57,6 +58,8 @@ struct LockPolicyMock } } + // NOLINTEND(bugprone-exception-escape) + static void setLock(LockPolicyMock* mock) { _lock = mock; } static uint8_t lockCounter; diff --git a/libs/bsw/transport/src/LogicalAddress.cpp b/libs/bsw/transport/src/LogicalAddress.cpp index f805c8b0ef7..e2f9b1401e4 100644 --- a/libs/bsw/transport/src/LogicalAddress.cpp +++ b/libs/bsw/transport/src/LogicalAddress.cpp @@ -11,7 +11,7 @@ namespace addressfinder ::etl::optional findDoipAddressInSlice(uint16_t const address, ::etl::span const& list) { - auto const iter = etl::find_if( + auto* const iter = etl::find_if( list.begin(), list.end(), [address](LogicalAddress const addr) -> bool { return addr.addressDoip == address; }); @@ -25,7 +25,7 @@ findDoipAddressInSlice(uint16_t const address, ::etl::span ::etl::optional find8BitAddressInSlice(uint16_t const address, ::etl::span const& list) { - auto const iter = etl::find_if( + auto* const iter = etl::find_if( list.begin(), list.end(), [address](LogicalAddress const addr) -> bool { return addr.address8Bit == address; }); diff --git a/libs/bsw/transport/test/src/Logger.cpp b/libs/bsw/transport/test/src/Logger.cpp index 0abd8c5ef5d..dbb2b9fe9f9 100644 --- a/libs/bsw/transport/test/src/Logger.cpp +++ b/libs/bsw/transport/test/src/Logger.cpp @@ -1,11 +1,22 @@ // Copyright 2024 Accenture. #include "transport/TransportLogger.h" - #include +#include +#include + using namespace ::util::logger; -LoggerComponentInfo components[] = {LoggerComponentInfo(TRANSPORT, "TRANSPORT", LEVEL_DEBUG)}; +etl::span getComponents() +{ + static auto components = etl::make_array( + LoggerComponentInfo(TRANSPORT, "TRANSPORT", LEVEL_DEBUG)); + return components; +} -TestConsoleLogger logger(components); +TestConsoleLogger& getLogger() +{ + static TestConsoleLogger logger(getComponents()); + return logger; +} diff --git a/libs/bsw/uds/include/uds/base/AbstractDiagJob.h b/libs/bsw/uds/include/uds/base/AbstractDiagJob.h index d9e89a60e3a..3c237eaaa34 100644 --- a/libs/bsw/uds/include/uds/base/AbstractDiagJob.h +++ b/libs/bsw/uds/include/uds/base/AbstractDiagJob.h @@ -159,6 +159,8 @@ class AbstractDiagJob : public ::etl::uncopyable } #ifdef UNIT_TEST + static void unsetDiagSession() { sfpSessionManager = nullptr; } + virtual ~AbstractDiagJob() {} #endif diff --git a/libs/bsw/uds/src/uds/DiagDispatcher.cpp b/libs/bsw/uds/src/uds/DiagDispatcher.cpp index 3c07550db0d..feb1a6a7ea1 100644 --- a/libs/bsw/uds/src/uds/DiagDispatcher.cpp +++ b/libs/bsw/uds/src/uds/DiagDispatcher.cpp @@ -206,11 +206,11 @@ PrecheckResult precheckRequest( } } TransportMessage& transportMessage = *job.transportMessage; - TransportMessage* pRequest = &transportMessage; if (configuration.CopyFunctionalRequests && TransportConfiguration::isFunctionallyAddressed(transportMessage)) { - pRequest = copyFunctionalRequest(transportMessage, providingListener, configuration); + TransportMessage* pRequest + = copyFunctionalRequest(transportMessage, providingListener, configuration); if (pRequest != nullptr) { if (job.processedListener != nullptr) @@ -312,10 +312,8 @@ ESR_NO_INLINE AbstractTransportLayer::ErrorCode DiagDispatcher::send( { return AbstractTransportLayer::ErrorCode::TP_OK; } - else - { - return AbstractTransportLayer::ErrorCode::TP_SEND_FAIL; - } + + return AbstractTransportLayer::ErrorCode::TP_SEND_FAIL; } if ((transportMessage.getTargetId() != _configuration.DiagAddress) && ((_configuration.BroadcastAddress != TransportMessage::INVALID_ADDRESS) @@ -361,10 +359,8 @@ AbstractTransportLayer::ErrorCode DiagDispatcher::resume( _configuration.DiagAddress); return AbstractTransportLayer::ErrorCode::TP_SEND_FAIL; } - else - { - transportMessage.setTargetAddress(TransportMessage::INVALID_ADDRESS); - } + + transportMessage.setTargetAddress(TransportMessage::INVALID_ADDRESS); auto const result = enqueueMessage( _sendJobQueue, @@ -416,8 +412,8 @@ void DiagDispatcher::processQueue() void DiagDispatcher::diagConnectionTerminated(IncomingDiagConnection& diagConnection) { - auto const requestMessage = diagConnection.requestMessage; - auto const notificationListener = diagConnection.requestNotificationListener; + auto* const requestMessage = diagConnection.requestMessage; + auto* const notificationListener = diagConnection.requestNotificationListener; if ((notificationListener != nullptr) && (requestMessage != nullptr)) { requestMessage->resetValidBytes(); diff --git a/libs/bsw/uds/src/uds/async/AsyncDiagJobHelper.cpp b/libs/bsw/uds/src/uds/async/AsyncDiagJobHelper.cpp index 814c0f91115..e27966fb3ec 100644 --- a/libs/bsw/uds/src/uds/async/AsyncDiagJobHelper.cpp +++ b/libs/bsw/uds/src/uds/async/AsyncDiagJobHelper.cpp @@ -36,10 +36,8 @@ DiagReturnCode::Type AsyncDiagJobHelper::enqueueRequest( fPendingRequests.push_back(*storedRequest); return DiagReturnCode::OK; } - else - { - return DiagReturnCode::ISO_BUSY_REPEAT_REQUEST; - } + + return DiagReturnCode::ISO_BUSY_REPEAT_REQUEST; } void AsyncDiagJobHelper::startAsyncRequest(IncomingDiagConnection& connection) diff --git a/libs/bsw/uds/src/uds/base/AbstractDiagJob.cpp b/libs/bsw/uds/src/uds/base/AbstractDiagJob.cpp index b2b37e9ea62..5bd5cc3723e 100644 --- a/libs/bsw/uds/src/uds/base/AbstractDiagJob.cpp +++ b/libs/bsw/uds/src/uds/base/AbstractDiagJob.cpp @@ -61,9 +61,8 @@ DiagReturnCode::Type AbstractDiagJob::execute( request - fPrefixLength, requestLength + fPrefixLength); if (vsistat != DiagReturnCode::OK) { - status = vsistat; acceptJob(connection, request, requestLength); - return status; + return vsistat; } } if (fRequestPayloadLength != VARIABLE_REQUEST_LENGTH) @@ -94,13 +93,13 @@ DiagReturnCode::Type AbstractDiagJob::execute( request + (fRequestLength - fPrefixLength), requestLength - (static_cast(fRequestLength) - fPrefixLength)); Logger::debug(UDS, "Process diag job 0x%X", getRequestId()); - status = process( + return process( connection, request + (fRequestLength - fPrefixLength), requestLength - (static_cast(fRequestLength) - fPrefixLength)); - return status; } - else if (status != DiagReturnCode::NOT_RESPONSIBLE) + + if (status != DiagReturnCode::NOT_RESPONSIBLE) { if ((jobRoot != nullptr) && (status != DiagReturnCode::ISO_SERVICE_NOT_SUPPORTED) && (status != DiagReturnCode::ISO_SERVICE_NOT_SUPPORTED_IN_ACTIVE_SESSION) @@ -115,10 +114,7 @@ DiagReturnCode::Type AbstractDiagJob::execute( } (void)getDiagSessionManager().acceptedJob(connection, *this, request, requestLength); } - else - { - // nothing to do - } + return status; } @@ -220,27 +216,22 @@ void AbstractDiagJob::removeAbstractDiagJob(AbstractDiagJob& job) fpFirstChild = job.getNextJob(); return; } - else if (fpFirstChild != nullptr) + + if (fpFirstChild != nullptr) { fpFirstChild->removeAbstractDiagJob(job); } - else - { - // nothing to do - } + if (getNextJob() == &job) { setNextJob(job.getNextJob()); return; } - else if (getNextJob() != nullptr) + + if (getNextJob() != nullptr) { getNextJob()->removeAbstractDiagJob(job); } - else - { - // nothing to do - } } IDiagSessionManager& AbstractDiagJob::getDiagSessionManager() @@ -285,10 +276,8 @@ bool AbstractDiagJob::isFamily(uint8_t const* const prefix, uint16_t const lengt { return compare(prefix, fpImplementedRequest, length); } - else - { - return false; - } + + return false; } bool AbstractDiagJob::isChild(uint8_t const* const prefix, uint16_t const length) const @@ -297,10 +286,7 @@ bool AbstractDiagJob::isChild(uint8_t const* const prefix, uint16_t const length { return compare(prefix, fpImplementedRequest, length); } - else - { - return false; - } + return false; } DiagReturnCode::Type AbstractDiagJob::process( @@ -318,10 +304,7 @@ DiagReturnCode::Type AbstractDiagJob::process( { return fDefaultDiagReturnCode; } - else - { - return result; - } + return result; } bool AbstractDiagJob::compare( diff --git a/libs/bsw/uds/src/uds/connection/IncomingDiagConnection.cpp b/libs/bsw/uds/src/uds/connection/IncomingDiagConnection.cpp index 07930e89c0e..200b21cf141 100644 --- a/libs/bsw/uds/src/uds/connection/IncomingDiagConnection.cpp +++ b/libs/bsw/uds/src/uds/connection/IncomingDiagConnection.cpp @@ -176,9 +176,9 @@ void IncomingDiagConnection::asyncSendPositiveResponse( } } responseMessage->resetValidBytes(); - for (uint8_t i = 0U; i < _identifiers.size(); ++i) + for (auto& identifier : _identifiers) { - (void)responseMessage->append(_identifiers[i]); + (void)responseMessage->append(identifier); } responseMessage->setServiceId(serviceId + DiagReturnCode::POSITIVE_RESPONSE_OFFSET); (void)responseMessage->increaseValidBytes(length); @@ -242,6 +242,11 @@ DiagReturnCode::Type IncomingDiagConnection::startNestedRequest( ::uds::ErrorCode IncomingDiagConnection::sendResponse() { + if (responseMessage == nullptr) + { + return ::uds::ErrorCode::NO_TP_MESSAGE; + } + AbstractTransportLayer::ErrorCode const sendResult = messageSender->send(*responseMessage, this); if (sendResult == AbstractTransportLayer::ErrorCode::TP_OK) @@ -439,7 +444,7 @@ void IncomingDiagConnection::triggerNextNestedRequest() void IncomingDiagConnection::endNestedRequest() { - auto const sender = _nestedRequest->senderJob; + auto* const sender = _nestedRequest->senderJob; auto const length = _nestedRequest->responseLength(); auto const responseCode = _nestedRequest->responseCode; _nestedRequest = nullptr; @@ -550,10 +555,8 @@ uint16_t IncomingDiagConnection::getMaximumResponseLength() const { return _nestedRequest->getMaxNestedResponseLength(); } - else - { - return requestMessage->getMaxPayloadLength() - _identifiers.size(); - } + + return requestMessage->getMaxPayloadLength() - _identifiers.size(); } PositiveResponse& IncomingDiagConnection::releaseRequestGetResponse() diff --git a/libs/bsw/uds/src/uds/connection/NestedDiagRequest.cpp b/libs/bsw/uds/src/uds/connection/NestedDiagRequest.cpp index 40a1589b6dd..a0751d62338 100644 --- a/libs/bsw/uds/src/uds/connection/NestedDiagRequest.cpp +++ b/libs/bsw/uds/src/uds/connection/NestedDiagRequest.cpp @@ -104,10 +104,8 @@ uint8_t NestedDiagRequest::getIdentifier(uint16_t const idx) const { return _nestedRequest[static_cast(idx)]; } - else - { - return 0U; - } + + return 0U; } uint16_t NestedDiagRequest::getStoredRequestLength(::etl::span const& request) const diff --git a/libs/bsw/uds/src/uds/resume/ResumableResetDriver.cpp b/libs/bsw/uds/src/uds/resume/ResumableResetDriver.cpp index f6da479c954..87070740bb1 100644 --- a/libs/bsw/uds/src/uds/resume/ResumableResetDriver.cpp +++ b/libs/bsw/uds/src/uds/resume/ResumableResetDriver.cpp @@ -79,10 +79,8 @@ bool ResumableResetDriver::prepareReset(::transport::TransportMessage const* con fDiagDispatcher->fEnabled = false; return true; } - else - { - return false; - } + + return false; } void ResumableResetDriver::abortReset() diff --git a/libs/bsw/uds/src/uds/services/communicationcontrol/CommunicationControl.cpp b/libs/bsw/uds/src/uds/services/communicationcontrol/CommunicationControl.cpp index c6fc6791bb5..a9db3676d28 100644 --- a/libs/bsw/uds/src/uds/services/communicationcontrol/CommunicationControl.cpp +++ b/libs/bsw/uds/src/uds/services/communicationcontrol/CommunicationControl.cpp @@ -134,9 +134,6 @@ DiagReturnCode::Type CommunicationControl::process( PositiveResponse& response = connection.releaseRequestGetResponse(); - ICommunicationStateListener::CommunicationState newState - = fCommunicationState; // default to no change - /* */ switch (controlType) { @@ -144,18 +141,20 @@ DiagReturnCode::Type CommunicationControl::process( { if (static_cast(NORMAL_COMMUNICATION_MESSAGES) == communicationTypeLo) { - newState = ICommunicationStateListener:: - DISABLE_REC_ENABLE_NORMAL_MESSAGE_SEND_TRANSMISSION; + setCommunicationState(ICommunicationStateListener:: + DISABLE_REC_ENABLE_NORMAL_MESSAGE_SEND_TRANSMISSION); } else if (static_cast(NM_COMMUNICATION_MESSAGES) == communicationTypeLo) { - newState = ICommunicationStateListener::DISABLE_REC_ENABLE_NM_SEND_TRANSMISSION; + setCommunicationState( + ICommunicationStateListener::DISABLE_REC_ENABLE_NM_SEND_TRANSMISSION); } else { - newState = ICommunicationStateListener::DISABLE_REC_ENABLE_ALL_SEND_TRANSMISSION; + setCommunicationState( + ICommunicationStateListener::DISABLE_REC_ENABLE_ALL_SEND_TRANSMISSION); } - setCommunicationState(newState); + (void)response.appendUint8(controlType); (void)connection.sendPositiveResponseInternal(response.getLength(), *this); } @@ -164,18 +163,19 @@ DiagReturnCode::Type CommunicationControl::process( { if (static_cast(NORMAL_COMMUNICATION_MESSAGES) == communicationTypeLo) { - newState = ICommunicationStateListener::DISABLE_NORMAL_MESSAGE_TRANSMISSION; + setCommunicationState( + ICommunicationStateListener::DISABLE_NORMAL_MESSAGE_TRANSMISSION); } else if (static_cast(NM_COMMUNICATION_MESSAGES) == communicationTypeLo) { - newState = ICommunicationStateListener::DISABLE_NM_MESSAGE_TRANSMISSION; + setCommunicationState(ICommunicationStateListener::DISABLE_NM_MESSAGE_TRANSMISSION); } else { - newState = ICommunicationStateListener::DISABLE_ALL_MESSAGE_TRANSMISSION; + setCommunicationState( + ICommunicationStateListener::DISABLE_ALL_MESSAGE_TRANSMISSION); } - setCommunicationState(newState); (void)response.appendUint8(controlType); (void)connection.sendPositiveResponseInternal(response.getLength(), *this); } @@ -184,17 +184,18 @@ DiagReturnCode::Type CommunicationControl::process( { if (static_cast(NORMAL_COMMUNICATION_MESSAGES) == communicationTypeLo) { - newState = ICommunicationStateListener::ENABLE_NORMAL_MESSAGE_TRANSMISSION; + setCommunicationState( + ICommunicationStateListener::ENABLE_NORMAL_MESSAGE_TRANSMISSION); } else if (static_cast(NM_COMMUNICATION_MESSAGES) == communicationTypeLo) { - newState = ICommunicationStateListener::ENABLE_NN_MESSAGE_TRANSMISSION; + setCommunicationState(ICommunicationStateListener::ENABLE_NN_MESSAGE_TRANSMISSION); } else { - newState = ICommunicationStateListener::ENABLE_ALL_MESSAGE_TRANSMISSION; + setCommunicationState(ICommunicationStateListener::ENABLE_ALL_MESSAGE_TRANSMISSION); } - setCommunicationState(newState); + // reset also subnet nodes under these circumstances if (((REC_NODE_COMMUNICATION_MESSAGES == communicationTypeHi) || (NO_REC_NODE_COMMUNICATION_MESSAGES == communicationTypeHi)) @@ -211,18 +212,20 @@ DiagReturnCode::Type CommunicationControl::process( { if (static_cast(NORMAL_COMMUNICATION_MESSAGES) == communicationTypeLo) { - newState = ICommunicationStateListener:: - ENABLE_REC_DISABLE_NORMAL_MESSAGE_SEND_TRANSMISSION; + setCommunicationState(ICommunicationStateListener:: + ENABLE_REC_DISABLE_NORMAL_MESSAGE_SEND_TRANSMISSION); } else if (static_cast(NM_COMMUNICATION_MESSAGES) == communicationTypeLo) { - newState = ICommunicationStateListener::ENABLE_REC_DISABLE_NM_SEND_TRANSMISSION; + setCommunicationState( + ICommunicationStateListener::ENABLE_REC_DISABLE_NM_SEND_TRANSMISSION); } else { - newState = ICommunicationStateListener::ENABLE_REC_DISABLE_ALL_SEND_TRANSMISSION; + setCommunicationState( + ICommunicationStateListener::ENABLE_REC_DISABLE_ALL_SEND_TRANSMISSION); } - setCommunicationState(newState); + (void)response.appendUint8(controlType); (void)connection.sendPositiveResponseInternal(response.getLength(), *this); } diff --git a/libs/bsw/uds/src/uds/services/controldtcsetting/ControlDTCSetting.cpp b/libs/bsw/uds/src/uds/services/controldtcsetting/ControlDTCSetting.cpp index e51d68a5256..dbb83dd1cc7 100644 --- a/libs/bsw/uds/src/uds/services/controldtcsetting/ControlDTCSetting.cpp +++ b/libs/bsw/uds/src/uds/services/controldtcsetting/ControlDTCSetting.cpp @@ -32,6 +32,7 @@ DiagReturnCode::Type ControlDTCSetting::process( Logger::debug(UDS, "ControlDTCSetting %d", dtcSettingType); switch (dtcSettingType) { + // NOLINTNEXTLINE(bugprone-branch-clone): Remove suppression when cases are implemented. case CONTROL_DTC_SETTING_ON: { // Allow creation of new DTCs. Intentionally not implemented. diff --git a/libs/bsw/uds/src/uds/services/ecureset/HardReset.cpp b/libs/bsw/uds/src/uds/services/ecureset/HardReset.cpp index c87c429c24a..b1e7226bf44 100644 --- a/libs/bsw/uds/src/uds/services/ecureset/HardReset.cpp +++ b/libs/bsw/uds/src/uds/services/ecureset/HardReset.cpp @@ -32,10 +32,8 @@ DiagReturnCode::Type HardReset::process( (void)connection.sendPositiveResponse(*this); return DiagReturnCode::OK; } - else - { - return DiagReturnCode::ISO_CONDITIONS_NOT_CORRECT; - } + + return DiagReturnCode::ISO_CONDITIONS_NOT_CORRECT; } void HardReset::responseSent( diff --git a/libs/bsw/uds/src/uds/services/ecureset/SoftReset.cpp b/libs/bsw/uds/src/uds/services/ecureset/SoftReset.cpp index c34cc54c410..5e85ca9cdc3 100644 --- a/libs/bsw/uds/src/uds/services/ecureset/SoftReset.cpp +++ b/libs/bsw/uds/src/uds/services/ecureset/SoftReset.cpp @@ -37,10 +37,7 @@ DiagReturnCode::Type SoftReset::process( (void)connection.sendPositiveResponse(*this); return DiagReturnCode::OK; } - else - { - return DiagReturnCode::ISO_CONDITIONS_NOT_CORRECT; - } + return DiagReturnCode::ISO_CONDITIONS_NOT_CORRECT; } void SoftReset::responseSent( diff --git a/libs/bsw/uds/src/uds/services/readdata/MultipleReadDataByIdentifier.cpp b/libs/bsw/uds/src/uds/services/readdata/MultipleReadDataByIdentifier.cpp index 7a26be8b0fa..101eb61c9b8 100644 --- a/libs/bsw/uds/src/uds/services/readdata/MultipleReadDataByIdentifier.cpp +++ b/libs/bsw/uds/src/uds/services/readdata/MultipleReadDataByIdentifier.cpp @@ -73,15 +73,11 @@ MultipleReadDataByIdentifier::verify(uint8_t const* const request, uint16_t cons { return DiagReturnCode::OK; } - else - { - return DiagReturnCode::ISO_INVALID_FORMAT; - } - } - else - { - return DiagReturnCode::NOT_RESPONSIBLE; + + return DiagReturnCode::ISO_INVALID_FORMAT; } + + return DiagReturnCode::NOT_RESPONSIBLE; } DiagReturnCode::Type MultipleReadDataByIdentifier::process( @@ -91,7 +87,8 @@ DiagReturnCode::Type MultipleReadDataByIdentifier::process( { return AbstractDiagJob::process(connection, request, requestLength); } - else if (fGetDidLimit.is_valid()) + + if (fGetDidLimit.is_valid()) { uint8_t const didLimit = fGetDidLimit(*connection.requestMessage); if ((didLimit > 0U) && ((requestLength / 2U) > didLimit)) @@ -99,14 +96,12 @@ DiagReturnCode::Type MultipleReadDataByIdentifier::process( return DiagReturnCode::ISO_INVALID_FORMAT; } } - else - { - // nothing to do - } + if (fAsyncJobHelper.hasPendingAsyncRequest()) { return fAsyncJobHelper.enqueueRequest(connection, request, requestLength); } + fCombinedResponseCode = DiagReturnCode::ISO_REQUEST_OUT_OF_RANGE; fAsyncJobHelper.startAsyncRequest(connection); return connection.startNestedRequest(*this, *this, request, requestLength); @@ -128,11 +123,9 @@ MultipleReadDataByIdentifier::prepareNestedRequest(::etl::span co (void)::etl::mem_copy(src.cbegin(), src.size(), fBuffer.begin() + 1); return fBuffer; } - else - { - responseCode = fCombinedResponseCode; - return {}; - } + + responseCode = fCombinedResponseCode; + return {}; } DiagReturnCode::Type MultipleReadDataByIdentifier::processNestedRequest( @@ -165,11 +158,9 @@ bool MultipleReadDataByIdentifier::defaultCheckResponse( { return true; } - else - { - combinedResponse = responseCode; - return responseCode == DiagReturnCode::OK; - } + + combinedResponse = responseCode; + return responseCode == DiagReturnCode::OK; } } // namespace uds diff --git a/libs/bsw/uds/src/uds/services/testerpresent/TesterPresent.cpp b/libs/bsw/uds/src/uds/services/testerpresent/TesterPresent.cpp index 7a322abaa24..08a2d72da55 100644 --- a/libs/bsw/uds/src/uds/services/testerpresent/TesterPresent.cpp +++ b/libs/bsw/uds/src/uds/services/testerpresent/TesterPresent.cpp @@ -37,10 +37,8 @@ DiagReturnCode::Type TesterPresent::process( (void)connection.sendPositiveResponseInternal(response.getLength(), *this); return DiagReturnCode::OK; } - else - { - return DiagReturnCode::ISO_SUBFUNCTION_NOT_SUPPORTED; - } + + return DiagReturnCode::ISO_SUBFUNCTION_NOT_SUPPORTED; } } // namespace uds diff --git a/libs/bsw/uds/test/mock/src/Logger.cpp b/libs/bsw/uds/test/mock/src/Logger.cpp index 29af273770e..109cd0007d6 100644 --- a/libs/bsw/uds/test/mock/src/Logger.cpp +++ b/libs/bsw/uds/test/mock/src/Logger.cpp @@ -3,12 +3,23 @@ #include "uds/UdsLogger.h" #include "util/logger/TestConsoleLogger.h" +#include +#include + DEFINE_LOGGER_COMPONENT(GLOBAL) using namespace ::util::logger; -LoggerComponentInfo components[] - = {LoggerComponentInfo(GLOBAL, "GLOBAL", LEVEL_DEBUG), - LoggerComponentInfo(UDS, "UDS", LEVEL_DEBUG)}; +etl::span getComponents() +{ + static auto components = etl::make_array( + LoggerComponentInfo(GLOBAL, "GLOBAL", LEVEL_DEBUG), + LoggerComponentInfo(UDS, "UDS", LEVEL_DEBUG)); + return components; +} -TestConsoleLogger logger(components); +TestConsoleLogger& getLogger() +{ + static TestConsoleLogger logger(getComponents()); + return logger; +} diff --git a/libs/bsw/uds/test/src/uds/base/AbstractDiagJobTest.cpp b/libs/bsw/uds/test/src/uds/base/AbstractDiagJobTest.cpp index 8f4cea47cb8..be39ba5e631 100644 --- a/libs/bsw/uds/test/src/uds/base/AbstractDiagJobTest.cpp +++ b/libs/bsw/uds/test/src/uds/base/AbstractDiagJobTest.cpp @@ -287,8 +287,7 @@ TEST_F( AbstractDiagJobTest, getDiagSessionManager_calls_an_exception_if_a_sessionManager_does_not_exist) { - IDiagSessionManager* diagSessionManager = nullptr; - AbstractDiagJob::setDefaultDiagSessionManager(*diagSessionManager); + AbstractDiagJob::unsetDiagSession(); ASSERT_THROW(fTestableDiagJob.getDiagSessionManager(), ::etl::exception); } @@ -296,10 +295,9 @@ TEST_F( AbstractDiagJobTest, const_getDiagSessionManager_calls_an_exception_if_a_sessionManager_does_not_exist) { + AbstractDiagJob::unsetDiagSession(); TestableDiagJob const diagJob(IMPLEMENTED_REQUEST, sizeof(IMPLEMENTED_REQUEST), 0U, 0U, 1U); - IDiagSessionManager* diagSessionManager = nullptr; - AbstractDiagJob::setDefaultDiagSessionManager(*diagSessionManager); ASSERT_THROW(diagJob.getDiagSessionManager(), ::etl::exception); } diff --git a/libs/bsw/uds/test/src/uds/resume/ResumableResetDriverTest.cpp b/libs/bsw/uds/test/src/uds/resume/ResumableResetDriverTest.cpp index 82c91bff6da..968b563fc9e 100644 --- a/libs/bsw/uds/test/src/uds/resume/ResumableResetDriverTest.cpp +++ b/libs/bsw/uds/test/src/uds/resume/ResumableResetDriverTest.cpp @@ -82,10 +82,7 @@ class TestResumableResetDriverPersistence : public IResumableResetDriverPersiste message.setPayloadLength(fTransportMessage.getPayloadLength()); return true; } - else - { - return false; - } + return false; } void writeRequest(::transport::TransportMessage const& message) override diff --git a/libs/bsw/util/mock/gmock/include/util/logger/TestConsoleLogger.h b/libs/bsw/util/mock/gmock/include/util/logger/TestConsoleLogger.h index 32bf343aa79..5ff2d5a1282 100644 --- a/libs/bsw/util/mock/gmock/include/util/logger/TestConsoleLogger.h +++ b/libs/bsw/util/mock/gmock/include/util/logger/TestConsoleLogger.h @@ -5,6 +5,8 @@ #include "util/logger/IComponentMapping.h" #include "util/logger/ILoggerOutput.h" +#include + namespace util { namespace logger @@ -29,8 +31,7 @@ class TestConsoleLogger , private ILoggerOutput { public: - template - TestConsoleLogger(LoggerComponentInfo (&firstComponentInfo)[Count]); + TestConsoleLogger(etl::span firstComponentInfo); ~TestConsoleLogger(); static void init(); @@ -65,12 +66,5 @@ class TestLoggingGuard ~TestLoggingGuard(); }; -template -TestConsoleLogger::TestConsoleLogger(LoggerComponentInfo (&firstComponentInfo)[Count]) -: _firstComponent(firstComponentInfo), _count(Count), _prevInstance(_instance) -{ - _instance = this; -} - } // namespace logger } // namespace util diff --git a/libs/bsw/util/mock/gmock/src/util/logger/TestConsoleLogger.cpp b/libs/bsw/util/mock/gmock/src/util/logger/TestConsoleLogger.cpp index cde17f80b61..4782aa56209 100644 --- a/libs/bsw/util/mock/gmock/src/util/logger/TestConsoleLogger.cpp +++ b/libs/bsw/util/mock/gmock/src/util/logger/TestConsoleLogger.cpp @@ -13,6 +13,14 @@ namespace logger { TestConsoleLogger* TestConsoleLogger::_instance = nullptr; +TestConsoleLogger::TestConsoleLogger(etl::span firstComponentInfo) +: _firstComponent(firstComponentInfo.data()) +, _count(firstComponentInfo.size()) +, _prevInstance(_instance) +{ + _instance = this; +} + TestConsoleLogger::~TestConsoleLogger() { if (_instance == this) diff --git a/libs/bsw/util/src/util/format/PrintfFormatter.cpp b/libs/bsw/util/src/util/format/PrintfFormatter.cpp index 77f8dd1e3ef..e1a7f297610 100644 --- a/libs/bsw/util/src/util/format/PrintfFormatter.cpp +++ b/libs/bsw/util/src/util/format/PrintfFormatter.cpp @@ -15,6 +15,7 @@ PrintfFormatter::PrintfFormatter(IOutputStream& strm, bool const writeParam) : _stream(strm), _writeParam(writeParam), _pos(0U) {} +// NOLINTNEXTLINE(cert-dcl50-cpp): va_list usage only for printing functionalities. void PrintfFormatter::format(char const* const formatString, ...) { va_list ap; diff --git a/libs/bsw/util/src/util/format/StringWriter.cpp b/libs/bsw/util/src/util/format/StringWriter.cpp index 3befaaa9133..7a3b4152e58 100644 --- a/libs/bsw/util/src/util/format/StringWriter.cpp +++ b/libs/bsw/util/src/util/format/StringWriter.cpp @@ -45,6 +45,7 @@ StringWriter& StringWriter::write(ConstString const& str) return write(str.data(), str.length()); } +// NOLINTNEXTLINE(cert-dcl50-cpp): va_list usage only for printing functionalities. StringWriter& StringWriter::printf(char const* const formatString, ...) { va_list ap; diff --git a/libs/bsw/util/src/util/logger/LevelInfo.cpp b/libs/bsw/util/src/util/logger/LevelInfo.cpp index f1dba7c74b6..22cb2b75568 100644 --- a/libs/bsw/util/src/util/logger/LevelInfo.cpp +++ b/libs/bsw/util/src/util/logger/LevelInfo.cpp @@ -11,7 +11,7 @@ namespace logger { using ::util::format::BOLD; -LevelInfo::PlainInfo const LevelInfo::_defaultConstLevelInfos[LEVEL_COUNT] +constexpr LevelInfo::PlainInfo LevelInfo::_defaultConstLevelInfos[LEVEL_COUNT] = {{{"DEBUG", {format::Color::DEFAULT_COLOR, 0U, format::Color::DEFAULT_COLOR}}, LEVEL_DEBUG}, {{"INFO", {format::Color::DEFAULT_COLOR, 0U, format::Color::DEFAULT_COLOR}}, LEVEL_INFO}, {{"WARN", {format::Color::YELLOW, BOLD, format::Color::DEFAULT_COLOR}}, LEVEL_WARN}, diff --git a/libs/bsw/util/test/src/util/format/PrintfArgumentReaderTest.cpp b/libs/bsw/util/test/src/util/format/PrintfArgumentReaderTest.cpp index 90320b50655..170e834149f 100644 --- a/libs/bsw/util/test/src/util/format/PrintfArgumentReaderTest.cpp +++ b/libs/bsw/util/test/src/util/format/PrintfArgumentReaderTest.cpp @@ -20,6 +20,7 @@ ParamVariant const& safeReadArgument(PrintfArgumentReader& reader, ParamDatatype return *pVariant; } +// NOLINTNEXTLINE(cert-dcl50-cpp): va_list usage only for this file. void readArguments(char const* pDummy, ...) { va_list ap; @@ -49,14 +50,14 @@ TEST(PrintfArgumentReaderTest, testRead) { readArguments( "", - (int8_t)1, - (uint8_t)2, - (int16_t)3, - (uint16_t)4, - (int32_t)5, - (uint32_t)6, - (int64_t)7, - (uint64_t)8, + static_cast(1), + static_cast(2), + static_cast(3), + static_cast(4), + static_cast(5), + static_cast(6), + static_cast(7), + static_cast(8), toPointer(9), toPointer(10), toPointer(11)); diff --git a/libs/bsw/util/test/src/util/format/PrintfFormatterTest.cpp b/libs/bsw/util/test/src/util/format/PrintfFormatterTest.cpp index 383f2809958..d7eb02fc6cd 100644 --- a/libs/bsw/util/test/src/util/format/PrintfFormatterTest.cpp +++ b/libs/bsw/util/test/src/util/format/PrintfFormatterTest.cpp @@ -32,6 +32,7 @@ struct PrintfFormatterTest ParamVariant const* readArgument(ParamDatatype /* datatype */) override { return nullptr; } #if defined(__linux) && defined(__GNUC__) && __x86_64__ + // NOLINTNEXTLINE(cert-dcl50-cpp): va_list usage only for printing functionalities. std::string printf(char const* formatString, ...) { va_list ap; @@ -44,10 +45,11 @@ struct PrintfFormatterTest std::string printfV(char const* formatString, va_list ap) { char buffer[300]; - vsnprintf(buffer, sizeof(buffer), formatString, ap); + static_cast(vsnprintf(buffer, sizeof(buffer), formatString, ap)); return buffer; } #endif + // NOLINTNEXTLINE(cert-dcl50-cpp): va_list usage only for printing functionalities. std::string format(char const* formatString, ...) { va_list ap; @@ -91,6 +93,7 @@ struct PrintfFormatterTest {} #endif + // NOLINTNEXTLINE(cert-dcl50-cpp): va_list usage only for printing functionalities. void expectPrintf(char const* pExpected, char const* formatString, ...) { va_list ap; @@ -145,7 +148,7 @@ struct PrintfFormatterTest uint8_t flags = 0) { expectAndCheckIntPrintf(!(flags & IGNORE_NEGATIVE), pNegative, formatString, -value); - expectAndCheckIntPrintf(!(flags & IGNORE_ZERO), pZero, formatString, (T)0); + expectAndCheckIntPrintf(!(flags & IGNORE_ZERO), pZero, formatString, static_cast(0)); expectAndCheckIntPrintf(!(flags & IGNORE_POSITIVE), pPositive, formatString, value); } }; @@ -255,7 +258,7 @@ TEST_F(PrintfFormatterTest, testFormatParamWithInvalidValues) { PrintfFormatter formatter(stream); { - ParamInfo paramInfo = {(ParamType)80, 0, 10, ParamDatatype::UINT16, 0, 0}; + ParamInfo paramInfo = {static_cast(80), 0, 10, ParamDatatype::UINT16, 0, 0}; formatter.formatParam(paramInfo, ParamVariant()); } stream.write('.'); diff --git a/libs/bsw/util/test/src/util/format/StringWriterTest.cpp b/libs/bsw/util/test/src/util/format/StringWriterTest.cpp index c71043b7d13..cde94224d0d 100644 --- a/libs/bsw/util/test/src/util/format/StringWriterTest.cpp +++ b/libs/bsw/util/test/src/util/format/StringWriterTest.cpp @@ -14,6 +14,7 @@ struct StringWriterTest : ::testing::Test { void apply(format::StringWriter& writer) const { writer.printf("ext0"); } + // NOLINTNEXTLINE(cert-dcl50-cpp): va_list usage only for printing functionalities. void callVprintf(format::StringWriter& writer, char const* format, ...) { va_list va; @@ -33,7 +34,7 @@ TEST_F(StringWriterTest, testMixedUsage) .printf("%d", 10) .printf(nullptr) .write("test") - .write((char const*)nullptr) + .write(nullptr) .write("test", 3) .write(::util::string::ConstString("ABCD")) .endl(); diff --git a/libs/bsw/util/test/src/util/logger/LoggerTest.cpp b/libs/bsw/util/test/src/util/logger/LoggerTest.cpp index a4e404ec849..0e5944da596 100644 --- a/libs/bsw/util/test/src/util/logger/LoggerTest.cpp +++ b/libs/bsw/util/test/src/util/logger/LoggerTest.cpp @@ -11,6 +11,7 @@ using namespace ::util::format; namespace { +// NOLINTNEXTLINE(cert-dcl50-cpp): va_list usage only for printing functionalities. void callLog(uint8_t index, Level level, char const* formatString, ...) { va_list ap; @@ -62,7 +63,7 @@ struct LoggerTest _outComponentInfo = componentInfo; _outLevelInfo = levelInfo; char buffer[300]; - vsnprintf(buffer, sizeof(buffer), str, ap); + static_cast(vsnprintf(buffer, sizeof(buffer), str, ap)); _logStr = buffer; } diff --git a/libs/bsw/util/test/src/util/stream/TaggedSharedOutputStreamTest.cpp b/libs/bsw/util/test/src/util/stream/TaggedSharedOutputStreamTest.cpp index e36f5890bc1..4a72c5ea34a 100644 --- a/libs/bsw/util/test/src/util/stream/TaggedSharedOutputStreamTest.cpp +++ b/libs/bsw/util/test/src/util/stream/TaggedSharedOutputStreamTest.cpp @@ -140,7 +140,7 @@ TEST_F(TaggedSharedOutputStreamTestFixture, testContinuousStream) stream = &cut.startOutput(&otherUser); stream->write('d'); cut.endOutput(&otherUser); - stream = &cut.startOutput(this); + static_cast(cut.startOutput(this)); cut.endOutput(this); stream = &cut.startOutput(this); stream->write('e'); diff --git a/libs/safety/safeMonitor/test/src/RegisterTest.cpp b/libs/safety/safeMonitor/test/src/RegisterTest.cpp index cf8763deb72..6c5ead7fe34 100644 --- a/libs/safety/safeMonitor/test/src/RegisterTest.cpp +++ b/libs/safety/safeMonitor/test/src/RegisterTest.cpp @@ -176,7 +176,7 @@ TEST_F(RegisterTest, LastCheckedEntryIsInitiallyNull) TEST_F(RegisterTest, LastCheckedEntryPointsToLastEntryAfterCheck) { - auto const ptrToLastEntry = &_entries[NUMBER_OF_ENTRIES - 1]; + auto* const ptrToLastEntry = &_entries[NUMBER_OF_ENTRIES - 1]; _registerMonitor.check(); EXPECT_EQ(_registerMonitor.getLastCheckedEntry(), ptrToLastEntry); } @@ -184,8 +184,8 @@ TEST_F(RegisterTest, LastCheckedEntryPointsToLastEntryAfterCheck) TEST_F(RegisterTest, LastCheckedEntryPointsToFaultyEntry) { EXPECT_CALL(_handler, handle(SOMETHING_HAPPENED)); - auto const ptrToFaultyEntry = &_entries[2]; - _r2 = ~_r2; + auto* const ptrToFaultyEntry = &_entries[2]; + _r2 = ~_r2; _registerMonitor.check(); EXPECT_EQ(_registerMonitor.getLastCheckedEntry(), ptrToFaultyEntry); } diff --git a/platforms/posix/bsp/bspInterruptsImpl/freertos/src/interrupts/suspendResumeAllInterrupts.cpp b/platforms/posix/bsp/bspInterruptsImpl/freertos/src/interrupts/suspendResumeAllInterrupts.cpp index 05554f15b92..10c76db1628 100644 --- a/platforms/posix/bsp/bspInterruptsImpl/freertos/src/interrupts/suspendResumeAllInterrupts.cpp +++ b/platforms/posix/bsp/bspInterruptsImpl/freertos/src/interrupts/suspendResumeAllInterrupts.cpp @@ -21,11 +21,11 @@ OldIntEnabledStatusValueType getOldIntEnabledStatusValueAndSuspendAllInterrupts( // 2. Inside vTaskStartScheduler(), with interrupts disabled, asyncEnterTask() is called. // We shall not mess with the interrupt logic there. - return OldIntEnabledStatusValueType(0); + return static_cast(0); } taskENTER_CRITICAL(); - return OldIntEnabledStatusValueType(1); + return static_cast(1); } void resumeAllInterrupts(OldIntEnabledStatusValueType const oldIntEnabledStatusValue) diff --git a/platforms/posix/bsp/bspSystemTime/src/bsp/time/systemTimer.cpp b/platforms/posix/bsp/bspSystemTime/src/bsp/time/systemTimer.cpp index 2c1398aa57a..ff816af4753 100644 --- a/platforms/posix/bsp/bspSystemTime/src/bsp/time/systemTimer.cpp +++ b/platforms/posix/bsp/bspSystemTime/src/bsp/time/systemTimer.cpp @@ -30,6 +30,7 @@ void sysDelayUs(uint32_t const delay) while ((getSystemTimeUs32Bit() - t) < delay) {} } +// NOLINTNEXTLINE(cert-err58-cpp): Not sure about the need of this here. uint64_t const SystemTimeNs = getSystemTimeNs(); // only used in statistics, where it should not overflow for 1-second intervals. diff --git a/platforms/posix/bsp/bspUart/src/bsp/Uart.cpp b/platforms/posix/bsp/bspUart/src/bsp/Uart.cpp index 1f7a4e3c787..6f50c0c493f 100644 --- a/platforms/posix/bsp/bspUart/src/bsp/Uart.cpp +++ b/platforms/posix/bsp/bspUart/src/bsp/Uart.cpp @@ -75,12 +75,12 @@ void Uart::deinit() } } -static Uart instances[] = { - Uart(Uart::Id::TERMINAL), -}; - bsp::Uart& Uart::getInstance(Id id) { + static Uart instances[] = { + Uart(Uart::Id::TERMINAL), + }; + ETL_ASSERT( id < Id::INVALID, ETL_ERROR_GENERIC("UartId::INVALID is not a valid Uart identifier")); diff --git a/platforms/posix/bsp/socketCanTransceiver/src/can/SocketCanTransceiver.cpp b/platforms/posix/bsp/socketCanTransceiver/src/can/SocketCanTransceiver.cpp index 676816dd419..09a50e03eb8 100644 --- a/platforms/posix/bsp/socketCanTransceiver/src/can/SocketCanTransceiver.cpp +++ b/platforms/posix/bsp/socketCanTransceiver/src/can/SocketCanTransceiver.cpp @@ -15,8 +15,10 @@ #include #include +#include #include #include +#include static_assert( std::is_standard_layout<::can::CANFrame>::value @@ -173,7 +175,7 @@ void SocketCanTransceiver::guardedOpen() } struct ifreq ifr; - ::std::strcpy(ifr.ifr_name, name); + etl::strncpy(ifr.ifr_name, name, sizeof(ifr.ifr_name) / sizeof(ifr.ifr_name[0])); error = ioctl(fd, SIOCGIFINDEX, &ifr); if (error < 0) { @@ -209,7 +211,7 @@ void SocketCanTransceiver::guardedOpen() ::std::memset(&addr, 0, sizeof(addr)); addr.can_family = AF_CAN; addr.can_ifindex = ifr.ifr_ifindex; - error = bind(fd, (struct sockaddr*)&addr, sizeof(addr)); + error = bind(fd, reinterpret_cast(&addr), sizeof(addr)); if (error < 0) { Logger::error( @@ -251,8 +253,9 @@ void SocketCanTransceiver::guardedRun(int maxSentPerRun, int maxReceivedPerRun) socketCanFrame.can_dlc = length; ::std::memcpy(socketCanFrame.data, canFrame.getPayload(), length); ::std::memset(socketCanFrame.data + length, 0, sizeof(socketCanFrame.data) - length); - length = ::write(_fileDescriptor, reinterpret_cast(&socketCanFrame), CAN_MTU); - if (length != CAN_MTU) + ssize_t const bytesWritten + = ::write(_fileDescriptor, reinterpret_cast(&socketCanFrame), CAN_MTU); + if (bytesWritten != CAN_MTU) { break; } @@ -266,7 +269,7 @@ void SocketCanTransceiver::guardedRun(int maxSentPerRun, int maxReceivedPerRun) for (int count = 0; count < maxReceivedPerRun; ++count) { alignas(can_frame) uint8_t buffer[CANFD_MTU]; - int const length = read(_fileDescriptor, reinterpret_cast(buffer), CANFD_MTU); + ssize_t const length = read(_fileDescriptor, reinterpret_cast(buffer), CANFD_MTU); if (length < 0) { break; @@ -277,8 +280,8 @@ void SocketCanTransceiver::guardedRun(int maxSentPerRun, int maxReceivedPerRun) Logger::debug( CAN, "[SocketCanTransceiver] received CAN frame, id=0x%X, length=%d", - (int)socketCanFrame.can_id, - (int)socketCanFrame.can_dlc); + static_cast(socketCanFrame.can_id), + static_cast(socketCanFrame.can_dlc)); CANFrame canFrame; canFrame.setId(socketCanFrame.can_id); canFrame.setPayload(socketCanFrame.data, socketCanFrame.can_dlc); diff --git a/platforms/posix/bsp/tapEthernetDriver/src/TapEthernetDriver.cpp b/platforms/posix/bsp/tapEthernetDriver/src/TapEthernetDriver.cpp index 37b5547a6af..3ed4d8252a7 100644 --- a/platforms/posix/bsp/tapEthernetDriver/src/TapEthernetDriver.cpp +++ b/platforms/posix/bsp/tapEthernetDriver/src/TapEthernetDriver.cpp @@ -42,7 +42,7 @@ static int allocTapInterface(char const* const ifName) strncpy(ifr.ifr_name, ifName, IFNAMSIZ); } - int result = ioctl(fd, TUNSETIFF, (void*)&ifr); + int result = ioctl(fd, TUNSETIFF, &ifr); if (result < 0) { close(fd); @@ -79,15 +79,15 @@ void TapEthernetDriver::readFrame() return; } - auto const frameData = new uint8_t[::ethernet::TapEthernetDriver::MAX_FRAME_LENGTH]; - auto const nread = read(_tapFd, frameData, ::ethernet::TapEthernetDriver::MAX_FRAME_LENGTH); + auto* const frameData = new uint8_t[::ethernet::TapEthernetDriver::MAX_FRAME_LENGTH]; + auto const nread = read(_tapFd, frameData, ::ethernet::TapEthernetDriver::MAX_FRAME_LENGTH); if ((nread <= 0) || (nread > MAX_FRAME_LENGTH)) { delete[] frameData; return; } - auto const frameBuf = new ::lwiputils::RxCustomPbuf; + auto* const frameBuf = new ::lwiputils::RxCustomPbuf; // This lwip function is thread safe, so we can call it outside the lwip thread pbuf_alloced_custom( diff --git a/platforms/s32k1xx/bsp/CMakeLists.txt b/platforms/s32k1xx/bsp/CMakeLists.txt index 6f510c26729..599ee0d17db 100644 --- a/platforms/s32k1xx/bsp/CMakeLists.txt +++ b/platforms/s32k1xx/bsp/CMakeLists.txt @@ -7,7 +7,11 @@ add_subdirectory(bspFlexCan) add_subdirectory(bspFtm) add_subdirectory(bspFtmPwm) add_subdirectory(bspInterruptsImpl) -add_subdirectory(bspIo) + +if (BUILD_EXECUTABLE STREQUAL "referenceApp") + add_subdirectory(bspIo) +endif () + add_subdirectory(bspMcu) add_subdirectory(bspTja1101) add_subdirectory(bspUart) diff --git a/platforms/s32k1xx/bsp/bspEepromDriver/src/eeprom/EepromDriver.cpp b/platforms/s32k1xx/bsp/bspEepromDriver/src/eeprom/EepromDriver.cpp index c18d4f59af3..4e3128dc6a2 100644 --- a/platforms/s32k1xx/bsp/bspEepromDriver/src/eeprom/EepromDriver.cpp +++ b/platforms/s32k1xx/bsp/bspEepromDriver/src/eeprom/EepromDriver.cpp @@ -133,10 +133,8 @@ bsp::BspReturnCode EepromDriver::launchCommand() { return bsp::BSP_OK; } - else - { - return bsp::BSP_ERROR; - } + + return bsp::BSP_ERROR; } bsp::BspReturnCode EepromDriver::init() diff --git a/platforms/s32k1xx/bsp/bspEepromDriver/test/CMakeLists.txt b/platforms/s32k1xx/bsp/bspEepromDriver/test/CMakeLists.txt index ceb4c23094b..5e59fc84aaf 100644 --- a/platforms/s32k1xx/bsp/bspEepromDriver/test/CMakeLists.txt +++ b/platforms/s32k1xx/bsp/bspEepromDriver/test/CMakeLists.txt @@ -2,7 +2,7 @@ add_executable(bspEepromDriverTestS32K1 src/IncludeTest.cpp) target_include_directories(bspEepromDriverTestS32K1 PRIVATE ../include) -target_link_libraries(bspEepromDriverTestS32K1 PRIVATE gtest_main utbspIo +target_link_libraries(bspEepromDriverTestS32K1 PRIVATE gtest_main bspIo utbspMcu util) gtest_discover_tests(bspEepromDriverTestS32K1 diff --git a/platforms/s32k1xx/bsp/bspEthernet/src/ethernet/EnetDriver.cpp b/platforms/s32k1xx/bsp/bspEthernet/src/ethernet/EnetDriver.cpp index 3f48a2b2f2e..2f5f1f2a15f 100644 --- a/platforms/s32k1xx/bsp/bspEthernet/src/ethernet/EnetDriver.cpp +++ b/platforms/s32k1xx/bsp/bspEthernet/src/ethernet/EnetDriver.cpp @@ -87,7 +87,7 @@ uint8_t initDevice( IP_ENET->ECR = ENET_ECR_RESET_MASK; if (::bsp::isEqualAfterTimeout( - (uint32_t*)(&IP_ENET->ECR), ENET_ECR_RESET_MASK, ENET_ECR_RESET_MASK, 1U)) + const_cast(&IP_ENET->ECR), ENET_ECR_RESET_MASK, ENET_ECR_RESET_MASK, 1U)) { return 0x14U; } @@ -101,12 +101,12 @@ uint8_t initDevice( uint32_t address; /* Set physical address lower register. */ - address = ((uint32_t)macAddr[0] << 24) | ((uint32_t)macAddr[1] << 16) - | ((uint32_t)macAddr[2] << 8) | ((uint32_t)macAddr[3] << 0); + address = (static_cast(macAddr[0]) << 24) | (static_cast(macAddr[1]) << 16) + | (static_cast(macAddr[2]) << 8) | (static_cast(macAddr[3]) << 0); IP_ENET->PALR = address; /* Set physical address high register. */ - address = ((uint32_t)macAddr[4] << 8) | ((uint32_t)macAddr[5] << 0); + address = (static_cast(macAddr[4]) << 8) | (static_cast(macAddr[5]) << 0); IP_ENET->PAUR = ENET_PAUR_PADDR2(address); // Transmit FIFO watermark: Min. (64 bytes) diff --git a/platforms/s32k1xx/bsp/bspEthernet/src/ethernet/RxBuffers.cpp b/platforms/s32k1xx/bsp/bspEthernet/src/ethernet/RxBuffers.cpp index f425b38bce9..e2db4225529 100644 --- a/platforms/s32k1xx/bsp/bspEthernet/src/ethernet/RxBuffers.cpp +++ b/platforms/s32k1xx/bsp/bspEthernet/src/ethernet/RxBuffers.cpp @@ -18,8 +18,8 @@ uint8_t freeRxDescriptorIndex( { ETL_ASSERT(pbufAtIndex.size() != 0L, ETL_ERROR_GENERIC("buffer size must not be null")); - auto const pbuf1 = reinterpret_cast<::lwiputils::RxCustomPbuf*>(pbufAtIndex[nextBusy]); - auto const pbuf2 = reinterpret_cast<::lwiputils::RxCustomPbuf*>(pbufAtIndex[descriptorIndex]); + auto* const pbuf1 = reinterpret_cast<::lwiputils::RxCustomPbuf*>(pbufAtIndex[nextBusy]); + auto* const pbuf2 = reinterpret_cast<::lwiputils::RxCustomPbuf*>(pbufAtIndex[descriptorIndex]); ::ETL_OR_STD::swap(pbufAtIndex[nextBusy], pbufAtIndex[descriptorIndex]); ::ETL_OR_STD::swap(pbuf1->slot, pbuf2->slot); @@ -31,8 +31,8 @@ void freeCustomPbufHelper(pbuf* const p) { // We can "upcast" here since the initial allocation was made as RxCustimPbuf // The pbuf is embedded as the first memeber so the address stays the same. - auto const customPbuf = reinterpret_cast<::lwiputils::RxCustomPbuf*>(p); - auto const driver = reinterpret_cast(customPbuf->driver); + auto* const customPbuf = reinterpret_cast<::lwiputils::RxCustomPbuf*>(p); + auto* const driver = reinterpret_cast(customPbuf->driver); auto const index = reinterpret_cast(customPbuf->slot) - driver->_descriptors.begin(); diff --git a/platforms/s32k1xx/bsp/bspEthernet/src/ethernet/TxBuffers.cpp b/platforms/s32k1xx/bsp/bspEthernet/src/ethernet/TxBuffers.cpp index 42e87bbf319..5c89a9e790d 100644 --- a/platforms/s32k1xx/bsp/bspEthernet/src/ethernet/TxBuffers.cpp +++ b/platforms/s32k1xx/bsp/bspEthernet/src/ethernet/TxBuffers.cpp @@ -11,6 +11,7 @@ #include #include +#include #include using namespace ::util::logger; @@ -29,7 +30,7 @@ void TxBuffers::freeDescriptor(uint8_t const n) void TxBuffers::init() { // initialize transmit buffer descriptors - for (uint8_t i = 0U; i < _descriptors.size(); i++) + for (size_t i = 0U; i < _descriptors.size(); i++) { _referencedPbufs[i] = 0L; _descriptors[i].status1 = ENET_ETXD_STATUS1_TO2(1); @@ -172,9 +173,10 @@ bool TxBuffers::writeFrame(uint16_t const vlanId, const struct pbuf* const buf) if (0U == bufferIndex) { // Copy the original ETYPE - uint16_t const etherType = ::etl::be_uint16_t(payload + 6U * 2); - uint8_t* header = payload; - uint8_t writeLen = 0U; + size_t const ethTypeOffset = static_cast(6U * 2U); + uint16_t const etherType = ::etl::be_uint16_t(payload + ethTypeOffset); + uint8_t* header = payload; + uint8_t writeLen = 0U; if (_enableVlanTagging) // VLAN enabled { @@ -186,8 +188,8 @@ bool TxBuffers::writeFrame(uint16_t const vlanId, const struct pbuf* const buf) uint8_t* insert = header; if (payload != header) { - (void)memmove(header, payload, 6U * 2); // Copy MACS - insert += 6U * 2; // Move pointer by 12 + (void)memmove(header, payload, 6UL * 2UL); // Copy MACS + insert += 6UL * 2UL; // Move pointer by 12 } if (vlanId != 0) diff --git a/platforms/s32k1xx/bsp/bspFlexCan/src/can/FlexCANDevice.cpp b/platforms/s32k1xx/bsp/bspFlexCan/src/can/FlexCANDevice.cpp index fd803622721..db4da29d286 100644 --- a/platforms/s32k1xx/bsp/bspFlexCan/src/can/FlexCANDevice.cpp +++ b/platforms/s32k1xx/bsp/bspFlexCan/src/can/FlexCANDevice.cpp @@ -302,10 +302,8 @@ uint8_t FlexCANDevice::getTransmitBuffer(CANFrame const& frame, bool callbackReq { return CALLBACK_TRANSMIT_BUFFER; } - else - { - return TRANSMIT_BUFFER_UNAVAILABLE; - } + + return TRANSMIT_BUFFER_UNAVAILABLE; } uint32_t frameId = CanId::rawId(frame.getId()); @@ -356,50 +354,40 @@ ICanTransceiver::ErrorCode FlexCANDevice::transmit(CANFrame const& frame, uint8_t bufIdx, bool txInterruptNeeded) { interrupts::SuspendResumeAllInterruptsScopedLock lock; - - if (((bufIdx >= FIRST_TRANSMIT_BUFFER) - && (bufIdx < FIRST_TRANSMIT_BUFFER + fConfig.numTxBufsApp)) - || (CALLBACK_TRANSMIT_BUFFER == bufIdx)) + bool const isValidBufferIdx = ((bufIdx >= FIRST_TRANSMIT_BUFFER) + && (bufIdx < (FIRST_TRANSMIT_BUFFER + fConfig.numTxBufsApp))) + || (CALLBACK_TRANSMIT_BUFFER == bufIdx); + if (isValidBufferIdx && (CANTxBuffer::CODE_INACTIVE == messageBuffer(bufIdx).FLAGS.B.CODE)) { - if (CANTxBuffer::CODE_INACTIVE == messageBuffer(bufIdx).FLAGS.B.CODE) + if (txInterruptNeeded) { - if (txInterruptNeeded) - { - fTxInterruptMask0 = 0; - fTxInterruptMask0 - |= (1 << (bufIdx - e_TRANSMIT_BUFFER_START + FIRST_TRANSMIT_BUFFER)); - } - if (CanId::isExtended(frame.getId())) - { - messageBuffer(bufIdx).ID.R = CanId::rawId(frame.getId()); - messageBuffer(bufIdx).FLAGS.B.IDE = 1; - messageBuffer(bufIdx).FLAGS.B.SRR = 1; - } - else - { - messageBuffer(bufIdx).ID.B.ID_STD = CanId::rawId(frame.getId()); - messageBuffer(bufIdx).FLAGS.B.IDE = 0; - } - ::etl::byte_stream_reader byte_stream{frame.getPayload(), 8, etl::endian::big}; - messageBuffer(bufIdx).DATA.W[0] = byte_stream.read_unchecked(); - messageBuffer(bufIdx).DATA.W[1] = byte_stream.read_unchecked(); - messageBuffer(bufIdx).FLAGS.B.DLC = frame.getPayloadLength(); - if (txInterruptNeeded) - { - enableTransmitInterrupt(); - } - messageBuffer(bufIdx).FLAGS.B.CODE = CANTxBuffer::CODE_TRANSMIT; - return ICanTransceiver::ErrorCode::CAN_ERR_OK; + fTxInterruptMask0 = 0; + fTxInterruptMask0 |= (1 << (bufIdx - e_TRANSMIT_BUFFER_START + FIRST_TRANSMIT_BUFFER)); + } + if (CanId::isExtended(frame.getId())) + { + messageBuffer(bufIdx).ID.R = CanId::rawId(frame.getId()); + messageBuffer(bufIdx).FLAGS.B.IDE = 1; + messageBuffer(bufIdx).FLAGS.B.SRR = 1; } else { - return ICanTransceiver::ErrorCode::CAN_ERR_TX_FAIL; + messageBuffer(bufIdx).ID.B.ID_STD = CanId::rawId(frame.getId()); + messageBuffer(bufIdx).FLAGS.B.IDE = 0; } + ::etl::byte_stream_reader byte_stream{frame.getPayload(), 8, etl::endian::big}; + messageBuffer(bufIdx).DATA.W[0] = byte_stream.read_unchecked(); + messageBuffer(bufIdx).DATA.W[1] = byte_stream.read_unchecked(); + messageBuffer(bufIdx).FLAGS.B.DLC = frame.getPayloadLength(); + if (txInterruptNeeded) + { + enableTransmitInterrupt(); + } + messageBuffer(bufIdx).FLAGS.B.CODE = CANTxBuffer::CODE_TRANSMIT; + return ICanTransceiver::ErrorCode::CAN_ERR_OK; } - else - { - return ICanTransceiver::ErrorCode::CAN_ERR_TX_FAIL; - } + + return ICanTransceiver::ErrorCode::CAN_ERR_TX_FAIL; } unsigned char FlexCANDevice::dequeueRxFrameStream(unsigned char* data) @@ -411,21 +399,19 @@ unsigned char FlexCANDevice::dequeueRxFrameStream(unsigned char* data) { return 0; } - else + + can::CANFrame& frame = fRxQueue.front(); + data[0] = frame.getPayloadLength(); + id = frame.getId(); + data[1] = static_cast(id >> 8); + data[2] = static_cast(id); + ptr = frame.getPayload(); + for (i = 0; i < data[0]; ++i) { - can::CANFrame& frame = fRxQueue.front(); - data[0] = frame.getPayloadLength(); - id = frame.getId(); - data[1] = static_cast(id >> 8); - data[2] = static_cast(id); - ptr = frame.getPayload(); - for (i = 0; i < data[0]; ++i) - { - data[3 + i] = ptr[i]; - } - fRxQueue.pop(); - return 1; + data[3 + i] = ptr[i]; } + fRxQueue.pop(); + return 1; } ICanTransceiver::ErrorCode diff --git a/platforms/s32k1xx/bsp/bspIo/test/CMakeLists.txt b/platforms/s32k1xx/bsp/bspIo/test/CMakeLists.txt index e90624821a7..0a56900cac0 100644 --- a/platforms/s32k1xx/bsp/bspIo/test/CMakeLists.txt +++ b/platforms/s32k1xx/bsp/bspIo/test/CMakeLists.txt @@ -2,5 +2,5 @@ add_executable(bspIoTest src/IncludeTest.cpp) target_include_directories(bspIoTest PRIVATE) -target_link_libraries(bspIoTest PRIVATE gtest_main utbspIo utbspMcu) +target_link_libraries(bspIoTest PRIVATE gtest_main bspIo utbspMcu) gtest_discover_tests(bspIoTest PROPERTIES LABELS "bspIoTest") diff --git a/platforms/s32k1xx/bsp/bspUart/test/CMakeLists.txt b/platforms/s32k1xx/bsp/bspUart/test/CMakeLists.txt index 2561df6830f..f3cdc53e3de 100644 --- a/platforms/s32k1xx/bsp/bspUart/test/CMakeLists.txt +++ b/platforms/s32k1xx/bsp/bspUart/test/CMakeLists.txt @@ -2,6 +2,6 @@ add_executable(bspUartTest src/IncludeTest.cpp) target_include_directories(bspUartTest PRIVATE mock/include) -target_link_libraries(bspUartTest PRIVATE bspMock utbspIo gmock gtest_main) +target_link_libraries(bspUartTest PRIVATE bspMock bspIo gmock gtest_main) gtest_discover_tests(bspUartTest PROPERTIES LABELS "bspUartTest") diff --git a/platforms/s32k1xx/bsp/canflex2Transceiver/CMakeLists.txt b/platforms/s32k1xx/bsp/canflex2Transceiver/CMakeLists.txt index 1510f1caf38..3f777c6390f 100644 --- a/platforms/s32k1xx/bsp/canflex2Transceiver/CMakeLists.txt +++ b/platforms/s32k1xx/bsp/canflex2Transceiver/CMakeLists.txt @@ -11,7 +11,7 @@ if (BUILD_EXECUTABLE STREQUAL "unitTest") bsp cpp2can etl - utbspIo + bspIo lifecycle gmock) else () diff --git a/platforms/s32k1xx/bsp/canflex2Transceiver/src/can/transceiver/canflex2/CanFlex2Transceiver.cpp b/platforms/s32k1xx/bsp/canflex2Transceiver/src/can/transceiver/canflex2/CanFlex2Transceiver.cpp index 860a013a7b1..49265a4fbf3 100644 --- a/platforms/s32k1xx/bsp/canflex2Transceiver/src/can/transceiver/canflex2/CanFlex2Transceiver.cpp +++ b/platforms/s32k1xx/bsp/canflex2Transceiver/src/can/transceiver/canflex2/CanFlex2Transceiver.cpp @@ -220,6 +220,7 @@ uint16_t CanFlex2Transceiver::getHwQueueTimeout() const { // 64 = 8 byte payload // 53 = CAN overhead + // NOLINTNEXTLINE(clang-analyzer-core.DivideZero): CAN Baudrate can never be zero here. auto const timeout = ((53U + 64U) * 1000U / (fFlexCANDevice.getBaudrate())); return static_cast(timeout); } @@ -244,31 +245,23 @@ ::can::ICanTransceiver::ErrorCode CanFlex2Transceiver::open(::can::CANFrame cons ::can::ICanTransceiver::ErrorCode CanFlex2Transceiver::open() { - if ((State::INITIALIZED == _state) || (State::CLOSED == _state)) + bool const isStateValid = (State::INITIALIZED == _state) || (State::CLOSED == _state); + if (isStateValid && (ErrorCode::CAN_ERR_OK == fFlexCANDevice.start())) { - if (ErrorCode::CAN_ERR_OK == fFlexCANDevice.start()) - { - (void)fFlexCANDevice.getPhy().setMode(CanPhy::CAN_PHY_MODE_ACTIVE, fdevConfig.BusId); - _state = State::OPEN; + (void)fFlexCANDevice.getPhy().setMode(CanPhy::CAN_PHY_MODE_ACTIVE, fdevConfig.BusId); + _state = State::OPEN; - ::async::scheduleAtFixedRate( - _context, - _cyclicTask, - _cyclicTaskTimeout, - ERROR_POLLING_TIMEOUT, - ::async::TimeUnitType::MILLISECONDS); + ::async::scheduleAtFixedRate( + _context, + _cyclicTask, + _cyclicTaskTimeout, + ERROR_POLLING_TIMEOUT, + ::async::TimeUnitType::MILLISECONDS); - return ErrorCode::CAN_ERR_OK; - } - else - { - return ErrorCode::CAN_ERR_ILLEGAL_STATE; - } - } - else - { - return ErrorCode::CAN_ERR_ILLEGAL_STATE; + return ErrorCode::CAN_ERR_OK; } + + return ErrorCode::CAN_ERR_ILLEGAL_STATE; } ::can::ICanTransceiver::ErrorCode CanFlex2Transceiver::close() @@ -287,10 +280,8 @@ ::can::ICanTransceiver::ErrorCode CanFlex2Transceiver::close() } return ErrorCode::CAN_ERR_OK; } - else - { - return ErrorCode::CAN_ERR_ILLEGAL_STATE; - } + + return ErrorCode::CAN_ERR_ILLEGAL_STATE; } void CanFlex2Transceiver::shutdown() @@ -311,10 +302,8 @@ ::can::ICanTransceiver::ErrorCode CanFlex2Transceiver::mute() _state = State::MUTED; return ErrorCode::CAN_ERR_OK; } - else - { - return ErrorCode::CAN_ERR_ILLEGAL_STATE; - } + + return ErrorCode::CAN_ERR_ILLEGAL_STATE; } ::can::ICanTransceiver::ErrorCode CanFlex2Transceiver::unmute() @@ -325,10 +314,8 @@ ::can::ICanTransceiver::ErrorCode CanFlex2Transceiver::unmute() _state = State::OPEN; return ErrorCode::CAN_ERR_OK; } - else - { - return ErrorCode::CAN_ERR_ILLEGAL_STATE; - } + + return ErrorCode::CAN_ERR_ILLEGAL_STATE; } void CanFlex2Transceiver::receiveTask() diff --git a/platforms/s32k1xx/bsp/canflex2Transceiver/test/CMakeLists.txt b/platforms/s32k1xx/bsp/canflex2Transceiver/test/CMakeLists.txt index d35744f1489..33a32185163 100644 --- a/platforms/s32k1xx/bsp/canflex2Transceiver/test/CMakeLists.txt +++ b/platforms/s32k1xx/bsp/canflex2Transceiver/test/CMakeLists.txt @@ -6,7 +6,7 @@ target_link_libraries( bsp canflex2Transceiver cpp2can - utbspIo + bspIo lifecycle bspMock gmock) diff --git a/platforms/s32k1xx/safety/safeBspMcuWatchdog/src/watchdog/Watchdog.cpp b/platforms/s32k1xx/safety/safeBspMcuWatchdog/src/watchdog/Watchdog.cpp index 31348b34dc9..674251310aa 100644 --- a/platforms/s32k1xx/safety/safeBspMcuWatchdog/src/watchdog/Watchdog.cpp +++ b/platforms/s32k1xx/safety/safeBspMcuWatchdog/src/watchdog/Watchdog.cpp @@ -129,18 +129,17 @@ bool Watchdog::executeFastTest(uint32_t const timeout) // Watchdog reset should occur before reaching the return statement return false; } - else if (isWdFastTestHigh()) + + if (isWdFastTestHigh()) { setUserMode(); return true; } - else - { - startFastTestLow(); - sysDelayUs(timeout); - // Watchdog reset should occur before reaching the return statement - return false; - } + + startFastTestLow(); + sysDelayUs(timeout); + // Watchdog reset should occur before reaching the return statement + return false; } void Watchdog::setUserMode()