diff --git a/.github/ISSUE_TEMPLATE/logo_request.yml b/.github/ISSUE_TEMPLATE/logo_request.yml index fa0570dab3..d3d605d57e 100644 --- a/.github/ISSUE_TEMPLATE/logo_request.yml +++ b/.github/ISSUE_TEMPLATE/logo_request.yml @@ -6,16 +6,31 @@ body: - type: markdown attributes: value: | - Tip: You can display a logo in fastfetch without adding it to fastfetch's official repo. + > [!WARNING] + > **NB:** If your logo request does not meet the basic requirements outlined in this template, the issue may be closed at any time without any further explanation. + + **Tip:** You can display a logo in fastfetch without adding it to fastfetch's official repo. For highly customized, personal logos, we recommend keeping them locally. - Please refer to https://github.com/fastfetch-cli/fastfetch/wiki/Migrate-Neofetch-Logo-To-Fastfetch + You can test your logo locally using: + `fastfetch -l /path/to/logo.txt --logo-color-1 white --logo-color-2 red` + Please refer to the [Migration Guide](https://github.com/fastfetch-cli/fastfetch/wiki/Migrate-Neofetch-Logo-To-Fastfetch) for details on color placeholders (`$1`, `$2`, etc.). + - type: textarea attributes: label: OS - description: Paste the contents of `/etc/os-release` and `/etc/lsb-release` here. If neither file exists, describe how to identify the distro. + description: Paste the contents of `/etc/os-release` (specifically the `ID` and `PRETTY_NAME` fields). If neither file exists, describe how to identify the distro. placeholder: cat /etc/os-release validations: required: true + + - type: input + attributes: + label: Public repository URL + description: A public repository is required to verify the request. Please provide a link to the repository where the distro is developed. + placeholder: https://github.com/example/distro + validations: + required: true + - type: input attributes: label: Distro Website @@ -23,25 +38,35 @@ body: placeholder: https://example.com validations: required: true + - type: textarea attributes: label: ASCII Art - description: The ASCII logo should not take up too much space (smaller than 50x20 characters, W x H). Please also include the color codes if they are not available in `os-release`. - placeholder: Paste ASCII art here + description: | + The ASCII logo should not take up too much space (smaller than 50x20 characters, W x H). + **Important:** Fastfetch uses `$1`, `$2`, `$3` etc. for color placeholders. Do NOT use hardcoded ANSI escape codes (like `\033[38;2...m`) or Neofetch's `${c1}` syntax. + Take as examples. + placeholder: Paste ASCII art with $1, $2 placeholders here validations: required: true + - type: input attributes: label: Original Image URL description: If the ASCII art is based on an image, please provide a link to the original image file. placeholder: Image URL from the distro website mentioned above + - type: checkboxes attributes: label: Checklist options: + - label: My distro has reached a stable state (out of beta, alpha, RC). + required: true - label: The ASCII art is smaller than 50x20 characters (W x H). required: true - - label: The ASCII art includes color codes, or the color codes are available in `os-release`. + - label: The ASCII art uses `$N` color placeholders (or colors are natively available in `os-release`). + required: true + - label: The ASCII art has no unnecessary trailing spaces at the end of lines. required: true - - label: The ASCII art has no internal padding (spaces at the start and/or end of lines). + - label: I promise that I will send a removal request if the distro is discontinued. required: true diff --git a/.github/workflows/build-freebsd-amd64.yml b/.github/workflows/build-freebsd-amd64.yml index 041bc4ff20..a6af2cba09 100644 --- a/.github/workflows/build-freebsd-amd64.yml +++ b/.github/workflows/build-freebsd-amd64.yml @@ -31,7 +31,7 @@ jobs: - name: Update and install dependencies run: | sudo pkg update - sudo pkg install -y cmake git pkgconf binutils wayland vulkan-headers vulkan-loader libxcb libXrandr libX11 libdrm glib dconf dbus sqlite3-tcl egl opencl ocl-icd v4l_compat chafa lua54 libva libvdpau + sudo pkg install -y cmake git pkgconf binutils wayland vulkan-headers vulkan-loader libxcb libXrandr libX11 libdrm glib dconf dbus sqlite3 egl opencl ocl-icd v4l_compat chafa lua54 libva libvdpau - name: CMake configuration run: cmake -DSET_TWEAK=Off -DBUILD_TESTS=On -DENABLE_EMBEDDED_PCIIDS=On -DENABLE_EMBEDDED_AMDGPUIDS=On -DCMAKE_BUILD_TYPE=${{ vars.CMAKE_BUILD_TYPE || 'RelWithDebInfo' }} . diff --git a/.github/workflows/build-linux-armv6l.yml b/.github/workflows/build-linux-armv6l.yml deleted file mode 100644 index 81b9081455..0000000000 --- a/.github/workflows/build-linux-armv6l.yml +++ /dev/null @@ -1,40 +0,0 @@ -name: Reusable Linux armv6l - -on: - workflow_call: - -env: - CMAKE_BUILD_TYPE: ${{ vars.CMAKE_BUILD_TYPE || 'RelWithDebInfo' }} - -jobs: - build: - runs-on: ubuntu-24.04 - steps: - - name: checkout repository - uses: actions/checkout@v7 - - - name: run VM - uses: uraimo/run-on-arch-action@v3 - id: runcmd - with: - arch: armv6 - distro: bookworm - githubToken: ${{ github.token }} - run: | - uname -a - apt-get update && apt-get install -y wget - apt-get install -y cmake make gcc libvulkan-dev libwayland-dev libxrandr-dev libxcb-randr0-dev libdconf-dev libdbus-1-dev libmagickcore-dev libsqlite3-dev librpm-dev libegl-dev libglx-dev ocl-icd-opencl-dev libpulse-dev libdrm-dev libelf-dev libefl-all-dev liblua5.4-dev libvdpau-dev libva-dev rpm - cmake -DSET_TWEAK=Off -DBUILD_TESTS=On -DCMAKE_INSTALL_PREFIX=/usr . - cmake --build . --target package --verbose -j4 - ./fastfetch --list-features - time ./fastfetch -c presets/ci.jsonc --stat false - time ./fastfetch -c presets/ci.jsonc --format json - time ./flashfetch - ldd fastfetch - ctest --output-on-failure - - - name: upload artifacts - uses: actions/upload-artifact@v7 - with: - name: fastfetch-linux-armv6l - path: ./fastfetch-*.* diff --git a/.github/workflows/build-linux-loong64.yml b/.github/workflows/build-linux-loong64.yml new file mode 100644 index 0000000000..25b140d8f4 --- /dev/null +++ b/.github/workflows/build-linux-loong64.yml @@ -0,0 +1,57 @@ +name: Reusable Linux loong64 + +on: + workflow_call: + +env: + CMAKE_BUILD_TYPE: ${{ vars.CMAKE_BUILD_TYPE || 'RelWithDebInfo' }} + +jobs: + build: + runs-on: ubuntu-24.04 + steps: + - name: checkout repository + uses: actions/checkout@v7 + + - name: set up QEMU for loong64 + uses: docker/setup-qemu-action@06116385d9baf250c9f4dcb4858b16962ea869c3 # v4.1.0 + + - name: build in loong64 container + run: | + docker run --rm --platform linux/loong64 \ + -v ${{ github.workspace }}:/workspace \ + -w /workspace \ + lcr.loongnix.cn/debian:14 \ + bash -c ' + set -e + uname -a + cat /etc/os-release || true + + apt-get update + apt-get install -y --no-install-recommends \ + cmake make gcc g++ \ + libvulkan-dev libwayland-dev libxrandr-dev libxcb-randr0-dev \ + libdconf-dev libdbus-1-dev libmagickcore-dev \ + libsqlite3-dev librpm-dev \ + libegl-dev libglx-dev ocl-icd-opencl-dev \ + libpulse-dev libdrm-dev \ + libelf-dev libefl-all-dev \ + liblua5.4-dev \ + libvdpau-dev libva-dev \ + rpm + + cmake -DSET_TWEAK=Off -DBUILD_TESTS=On -DCMAKE_INSTALL_PREFIX=/usr . + cmake --build . --target package --verbose -j$(nproc) + ./fastfetch --list-features + time ./fastfetch -c presets/ci.jsonc --stat false + time ./fastfetch -c presets/ci.jsonc --format json + time ./flashfetch + ldd fastfetch + ctest --output-on-failure + ' + + - name: upload artifacts + uses: actions/upload-artifact@v7 + with: + name: fastfetch-linux-loong64 + path: ./fastfetch-*.* diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 248c5e4ce5..46ac9d4fab 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -54,13 +54,13 @@ jobs: uses: ./.github/workflows/build-linux-armv7l.yml secrets: inherit - linux-armv6l: + linux-loong64: needs: no-features-test - name: Linux-armv6l + name: Linux-loong64 permissions: security-events: write contents: read - uses: ./.github/workflows/build-linux-armv6l.yml + uses: ./.github/workflows/build-linux-loong64.yml secrets: inherit linux-vms: @@ -154,6 +154,7 @@ jobs: secrets: inherit haiku-amd64: + if: false # Disabled because the Haiku build is currently broken needs: no-features-test name: Haiku-amd64 permissions: @@ -197,7 +198,7 @@ jobs: - linux-hosts - linux-i686 - linux-armv7l - - linux-armv6l + - linux-loong64 - linux-vms - musl-amd64 - macos-hosts @@ -207,7 +208,7 @@ jobs: - dragonfly-amd64 - solaris-amd64 - omnios-amd64 - - haiku-amd64 + # - haiku-amd64 - windows-hosts permissions: contents: write diff --git a/CHANGELOG.md b/CHANGELOG.md index 9cb47a237d..8ab97abc36 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,46 @@ +# 2.67.0 + +Changes: +* The minimum supported compiler version has been raised to GCC 13 (released on 2023-04-26) and Clang 16 (released on 2023-03-17) to accommodate the new C23 syntax used throughout the codebase. (General) + * As a result, building from source in Debian 12 (which only ships GCC 12 by default) is no longer supported. Users must upgrade their compiler or use the prebuilt binaries from the GitHub releases page. +* The `general.preRun` option has been removed due to security concerns. (General) + * Users who relied on this option to run a command before printing output will need to move that logic to an external wrapper. +* The `{status}` placeholder in Battery custom format is now an array type instead of a single comma-separated string. (Battery) + * This is a breaking change for users who print `{status}` in Lua scripts. They can use `table.concat(...)` to join the array into a single string if needed. +* The `--gen-config-*` flags (`--gen-config-full`, `--gen-config-force`, `--gen-config-full-force`) have been removed and their functions have been merged into `--gen-config`. (Global) + * See features below. + +Features: +* `--gen-config` now opens an interactive configuration TUI to make generating config files easier. + * It falls back to non-interactive generation when `$NO_COLOR` is set or when stdin/stdout is not a TTY. This behavior can also be used to disable the interactive mode. +* Added an experimental [WebUI](https://fastfetch-cli.github.io/fastfetch-config/) ([separate project](https://github.com/fastfetch-cli/fastfetch-config)) for generating and editing configs. +* Added `-w`/`--watch` as a seconds-based alias for `--dynamic-interval`, defaulting to 1 second when no value is provided. (#2478, Watch) +* Added InitSystem detection on Windows, reporting the first userland process (`smss.exe`). (InitSystem, Windows) +* Added CPU and GPU temperature detection support for Apple M5 series chips. (CPU / GPU, macOS) +* Reported `Basic` as the Windows theme when DWM is disabled. (Theme, Windows) +* Improved Ghostty terminal font detection performance. (#2122, TerminalFont) + * It now parses Ghostty directly instead of running `ghostty +show-config`. +* Added support for a wider range of TOML config syntaxes used by Alacritty. (#2456, TerminalFont) + +Bugfixes: +* Fixed a potential fish version detection error. (Shell, Linux) +* Fixed incorrect resolution reporting when a monitor advertises multiple preferred modes. (#2481, Display, Linux) +* Fixed connected monitors being missed when Wayland output events arrive late. (#2451, Display, Linux) +* Fixed VP9 codec detection on macOS. (Codec, macOS) +* Corrected Base64 encoding on big-endian hosts. (#2470) +* Fixed invalid URL parsing in the PublicIP module. (PublicIP) +* Correctly reported virtual GPUs on Windows. (#2461, GPU, Windows) +* Added a size limit for network responses to prevent excessive memory usage and mitigate potential attacks. (PublicIP / Weather) +* Fixed Ubuntu Studio Core detection (OS, Linux) +* Relaxed the HTTP response check so that both `HTTP/1.0` and `HTTP/1.1` responses are accepted when fetching data over the network. (PublicIP / Weather) +* Various internal cleanups and optimizations: + * Fixed multiple memory leaks (Separator, Camera, Codec, Display) + * Added integer overflow checks to the string buffer implementation + * Various code cleanups and compiler warning fixes + +Logos: +* Removed Hypros, MagpieOS, Furreto, EmperorOS and Magix + # 2.66.0 Changes: diff --git a/CMakeLists.txt b/CMakeLists.txt index ac2315e4ba..4cd0df0d18 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,7 +1,7 @@ cmake_minimum_required(VERSION 3.12.0) # target_link_libraries with OBJECT libs & project homepage url project(fastfetch - VERSION 2.66.0 + VERSION 2.67.0 LANGUAGES C DESCRIPTION "Fast neofetch-like system information tool" HOMEPAGE_URL "https://github.com/fastfetch-cli/fastfetch" @@ -182,7 +182,30 @@ endif() set(WARNING_FLAGS "-Wall -Wextra -Wconversion -Werror=uninitialized -Werror=return-type -Werror=vla") -set(CMAKE_C_STANDARD 11) +if(LINUX) + if(NOT IS_MUSL) # `NOT DEFINED IS_MUSL` doesn't work + execute_process( + COMMAND ${CMAKE_C_COMPILER} -print-file-name=libc.so + OUTPUT_VARIABLE LIBC_PATH + OUTPUT_STRIP_TRAILING_WHITESPACE + ) + + if(LIBC_PATH MATCHES "-musl") + set(IS_MUSL ON CACHE BOOL "Build with musl libc" FORCE) + endif() + endif() + + if(IS_MUSL) + message(STATUS "MUSL libc detected") + # Silence ioctl related warnings + set(WARNING_FLAGS "${WARNING_FLAGS} -Wno-sign-conversion") + endif() +endif() + +# Minimal compiler version supported: GCC 13 (2023-04-26), Clang 16 (2023-03-17) +# Most C23 features are allowed with noticeable exceptions of `constexpr` and `#embed` +# See https://cppreference.com/c/compiler_support/23 for detail +set(CMAKE_C_STANDARD 23) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${WARNING_FLAGS} -Werror=incompatible-pointer-types -Werror=implicit-function-declaration -Werror=int-conversion") if(WIN32 OR Haiku) @@ -411,6 +434,7 @@ set(LIBFASTFETCH_SRC src/common/impl/font.c src/common/impl/format.c src/common/impl/frequency.c + src/common/impl/genconfig.c src/common/impl/init.c src/common/impl/jsonconfig.c src/common/impl/library.c @@ -1100,7 +1124,7 @@ elseif(WIN32) src/detection/gpu/gpu_windows.cpp src/detection/host/host_windows.c src/detection/icons/icons_windows.c - src/detection/initsystem/initsystem_nosupport.c + src/detection/initsystem/initsystem_windows.c src/detection/keyboard/keyboard_windows.c src/detection/libc/libc_windows.cpp src/detection/lm/lm_nosupport.c diff --git a/README.md b/README.md index a55f2798dd..d2b0a53d92 100644 --- a/README.md +++ b/README.md @@ -199,7 +199,8 @@ See [#1096](https://github.com/fastfetch-cli/fastfetch/issues/1096). ### Q: Fastfetch shows fewer dpkg packages than neofetch. Is it a bug? -Neofetch incorrectly counts `rc` packages (packages that have been removed but still have configuration files remaining). See bug: https://github.com/dylanaraps/neofetch/issues/2278 +1. Neofetch incorrectly counts `rc` packages for apt (packages that have been removed but still have configuration files remaining). See bug: https://github.com/dylanaraps/neofetch/issues/2278 +2. Neofetch incorrectly counts `gpg-pubkey` as packages for rpm. You may check the results of `dnf list --installed | wc -l` and `rpm -qa | wc -l` to see the difference. ### Q: I use Debian / Ubuntu / Debian-derived distro. My GPU is detected as `XXXX Device XXXX (VGA compatible)`. Is this a bug? diff --git a/debian/changelog.tpl b/debian/changelog.tpl index ccf540012a..5907db1c60 100644 --- a/debian/changelog.tpl +++ b/debian/changelog.tpl @@ -1,3 +1,9 @@ +fastfetch (2.66.0~#UBUNTU_CODENAME#) #UBUNTU_CODENAME#; urgency=medium + + * Update to 2.66.0 + + -- Carter Li Fri, 10 Jul 2026 15:13:37 +0800 + fastfetch (2.65.2~#UBUNTU_CODENAME#) #UBUNTU_CODENAME#; urgency=medium * Update to 2.65.2 diff --git a/doc/help.json b/doc/help.json index da6732fbc3..e24d294fc7 100644 --- a/doc/help.json +++ b/doc/help.json @@ -83,6 +83,16 @@ "type": "num", "default": 0 } + }, + { + "long": "watch", + "short": "w", + "desc": "Alias of dynamic-interval, but the value is in seconds instead of milliseconds. If no value is provided, it defaults to 1 second", + "arg": { + "type": "num", + "optional": true, + "default": 1 + } } ], "Config": [ @@ -97,26 +107,8 @@ }, { "long": "gen-config", - "desc": "Generate a minimal config file at the specified path", - "remark": "Defaults to \"~/.config/fastfetch/config.jsonc\". Prints the generated config if is \"-\"", - "arg": { - "type": "path", - "optional": true - } - }, - { - "long": "gen-config-full", - "desc": "Generate a full config file with all optional settings at the specified path", - "remark": "Defaults to \"~/.config/fastfetch/config.jsonc\". Prints the generated config if is \"-\"", - "arg": { - "type": "path", - "optional": true - } - }, - { - "long": "gen-config-force", - "desc": "Generate a config file at the specified path, overwriting any existing file", - "remark": "Defaults to \"~/.config/fastfetch/config.jsonc\"", + "desc": "Interactively generate a config file at the specified path", + "remark": "Opens an interactive configuration UI when run in a terminal. Falls back to non-interactive generation when env-var `$NO_COLOR` is set or stdin/stdout is not a TTY. Defaults to \"~/.config/fastfetch/config.jsonc\". Prints the generated config if is \"-\"", "arg": { "type": "path", "optional": true diff --git a/doc/json_schema.json b/doc/json_schema.json index e9271b2ff7..4197c241bf 100644 --- a/doc/json_schema.json +++ b/doc/json_schema.json @@ -912,11 +912,6 @@ "description": "Set the timeout (ms) when waiting for child processes, `-1` for no timeout", "default": 5000 }, - "preRun": { - "type": "string", - "description": "Command to run before printing logos", - "default": "" - }, "detectVersion": { "type": "boolean", "description": "Whether to detect and display component versions. Mainly for benchmarking", diff --git a/src/common/FFlist.h b/src/common/FFlist.h index b409c6d4bc..630b0734b2 100644 --- a/src/common/FFlist.h +++ b/src/common/FFlist.h @@ -1,11 +1,10 @@ #pragma once -#include "common/attributes.h" - #include #include #include #include +#include #define FF_LIST_DEFAULT_ALLOC 16 @@ -23,33 +22,33 @@ bool ffListPop(FFlist* list, uint32_t elementSize, void* __restrict result); static inline void ffListInit(FFlist* list) { list->capacity = 0; list->length = 0; - list->data = NULL; + list->data = nullptr; } static inline void ffListInitA(FFlist* list, uint32_t elementSize, uint32_t capacity) { ffListInit(list); list->capacity = capacity; - list->data = __builtin_expect(capacity == 0, 0) ? NULL : (uint8_t*) malloc((size_t) capacity * elementSize); + list->data = __builtin_expect(capacity == 0, 0) ? nullptr : (uint8_t*) malloc((size_t) capacity * elementSize); } -FF_A_NODISCARD static inline FFlist ffListCreate() { +[[nodiscard]] static inline FFlist ffListCreate() { FFlist result; ffListInit(&result); return result; } -FF_A_NODISCARD static inline FFlist ffListCreateA(uint32_t elementSize, uint32_t capacity) { +[[nodiscard]] static inline FFlist ffListCreateA(uint32_t elementSize, uint32_t capacity) { FFlist result; ffListInitA(&result, elementSize, capacity); return result; } -FF_A_NODISCARD static inline void* ffListGet(const FFlist* list, uint32_t elementSize, uint32_t index) { +[[nodiscard]] static inline void* ffListGet(const FFlist* list, uint32_t elementSize, uint32_t index) { assert(list->capacity > index); return list->data + (index * elementSize); } -FF_A_NODISCARD static inline uint32_t ffListFirstIndexComp(const FFlist* list, uint32_t elementSize, void* compElement, bool (*compFunc)(const void*, const void*)) { +[[nodiscard]] static inline uint32_t ffListFirstIndexComp(const FFlist* list, uint32_t elementSize, void* compElement, bool (*compFunc)(const void*, const void*)) { for (uint32_t i = 0; i < list->length; i++) { if (compFunc(ffListGet(list, elementSize, i), compElement)) { return i; @@ -59,7 +58,7 @@ FF_A_NODISCARD static inline uint32_t ffListFirstIndexComp(const FFlist* list, u return list->length; } -FF_A_NODISCARD static inline bool ffListContains(const FFlist* list, uint32_t elementSize, void* compElement, bool (*compFunc)(const void*, const void*)) { +[[nodiscard]] static inline bool ffListContains(const FFlist* list, uint32_t elementSize, void* compElement, bool (*compFunc)(const void*, const void*)) { return ffListFirstIndexComp(list, elementSize, compElement, compFunc) != list->length; } @@ -87,7 +86,7 @@ static inline void ffListDestroy(FFlist* list) { // Avoid free-after-use. These 3 assignments are cheap so don't remove them list->capacity = list->length = 0; free(list->data); - list->data = NULL; + list->data = nullptr; } static inline void ffListClear(FFlist* list) { @@ -112,12 +111,25 @@ static inline void* ffListAdd(FFlist* list, uint32_t elementSize) { return ffListGet(list, elementSize, list->length - 1); } +static inline void ffListRemoveAt(FFlist* list, uint32_t elementSize, uint32_t index) { + assert(list->length > index); + memmove(list->data + (index * elementSize), list->data + ((index + 1) * elementSize), (size_t) (list->length - index - 1) * elementSize); + --list->length; +} + +static inline void ffListInsertAt(FFlist* list, uint32_t elementSize, uint32_t index, const void* element) { + assert(list->length >= index); + ffListAdd(list, elementSize); + memmove(list->data + ((index + 1) * elementSize), list->data + (index * elementSize), (size_t) (list->length - index - 1) * elementSize); + memcpy(list->data + (index * elementSize), element, elementSize); +} + #define FF_LIST_FOR_EACH(itemType, itemVarName, listVar) \ for (itemType* itemVarName = (itemType*) (listVar).data; \ itemVarName - (itemType*) (listVar).data < (intptr_t) (listVar).length; \ ++itemVarName) -#define FF_LIST_AUTO_DESTROY FFlist FF_A_CLEANUP(ffListDestroy) +#define FF_LIST_AUTO_DESTROY [[gnu::cleanup(ffListDestroy)]] FFlist #define FF_LIST_GET(itemType, listVar, index) \ ({ \ @@ -127,6 +139,12 @@ static inline void* ffListAdd(FFlist* list, uint32_t elementSize) { #define FF_LIST_ADD(itemType, listVar) (itemType*) ffListAdd(&(listVar), (uint32_t) sizeof(itemType)) +#define FF_LIST_REMOVE_AT(itemType, listVar, index) \ + ffListRemoveAt(&(listVar), (uint32_t) sizeof(itemType), (index)) + +#define FF_LIST_INSERT_AT(itemType, listVar, index, pElement) \ + ffListInsertAt(&(listVar), (uint32_t) sizeof(itemType), (index), (pElement)) + #define FF_LIST_FIRST(itemType, listVar) FF_LIST_GET(itemType, listVar, 0) #define FF_LIST_LAST(itemType, listVar) \ ({ \ @@ -136,9 +154,9 @@ static inline void* ffListAdd(FFlist* list, uint32_t elementSize) { #define FF_LIST_CONTAINS(listVar, pCompElement, compFunc) \ ({ \ - typedef __typeof__(*(pCompElement)) compElementType; \ + typedef typeof(*(pCompElement)) compElementType; \ typedef bool compFuncType(const compElementType*, const compElementType*); \ - static_assert(__builtin_types_compatible_p(__typeof__(compFunc), compFuncType), "Incompatible callback function"); \ + static_assert(__builtin_types_compatible_p(typeof(compFunc), compFuncType), "Incompatible callback function"); \ ffListContains(&(listVar), (uint32_t) sizeof(*(pCompElement)), (pCompElement), (bool (*)(const void*, const void*)) compFunc); \ }) diff --git a/src/common/FFstrbuf.h b/src/common/FFstrbuf.h index 4c89b9a32e..e3722ad82d 100644 --- a/src/common/FFstrbuf.h +++ b/src/common/FFstrbuf.h @@ -1,7 +1,5 @@ #pragma once -#include "common/attributes.h" - #include #include #include @@ -37,15 +35,15 @@ static inline void ffStrbufInit(FFstrbuf* strbuf); void ffStrbufInitA(FFstrbuf* strbuf, uint32_t allocate); void ffStrbufInitVF(FFstrbuf* strbuf, const char* format, va_list arguments); void ffStrbufInitMoveNS(FFstrbuf* strbuf, uint32_t length, char* heapStr); -FF_A_PRINTF(2, 3) void ffStrbufInitF(FFstrbuf* strbuf, const char* format, ...); -FF_A_PRINTF(1, 2) FF_A_NODISCARD FFstrbuf ffStrbufCreateF(const char* format, ...); +[[gnu::format(printf, 2, 3)]] void ffStrbufInitF(FFstrbuf* strbuf, const char* format, ...); +[[gnu::format(printf, 1, 2)]] [[nodiscard]] FFstrbuf ffStrbufCreateF(const char* format, ...); void ffStrbufEnsureFixedLengthFree(FFstrbuf* strbuf, uint32_t free); void ffStrbufEnsureFreeNoCheck(FFstrbuf* strbuf, uint32_t free); static inline void ffStrbufAppend(FFstrbuf* __restrict strbuf, const FFstrbuf* __restrict value); void ffStrbufAppendTransformS(FFstrbuf* strbuf, const char* value, int (*transformFunc)(int)); -FF_A_PRINTF(2, 3) void ffStrbufAppendF(FFstrbuf* strbuf, const char* format, ...); +[[gnu::format(printf, 2, 3)]] void ffStrbufAppendF(FFstrbuf* strbuf, const char* format, ...); void ffStrbufAppendVF(FFstrbuf* strbuf, const char* format, va_list arguments); const char* ffStrbufAppendSUntilC(FFstrbuf* strbuf, const char* value, char until); @@ -58,7 +56,7 @@ void ffStrbufInsertNC(FFstrbuf* strbuf, uint32_t index, uint32_t num, char c); // NOTE: Unlike ffStrbufAppend*, ffStrbufSet* functions may NOT reserve extra space void ffStrbufSet(FFstrbuf* strbuf, const FFstrbuf* value); void ffStrbufSetNS(FFstrbuf* strbuf, uint32_t length, const char* value); -FF_A_PRINTF(2, 3) void ffStrbufSetF(FFstrbuf* strbuf, const char* format, ...); +[[gnu::format(printf, 2, 3)]] void ffStrbufSetF(FFstrbuf* strbuf, const char* format, ...); void ffStrbufTrimLeft(FFstrbuf* strbuf, char c); void ffStrbufTrimRight(FFstrbuf* strbuf, char c); @@ -79,7 +77,7 @@ bool ffStrbufSubstrAfterFirstS(FFstrbuf* strbuf, const char* str); bool ffStrbufSubstrAfterLastC(FFstrbuf* strbuf, char c); bool ffStrbufSubstr(FFstrbuf* strbuf, uint32_t start, uint32_t end); -FF_A_NODISCARD uint32_t ffStrbufCountC(const FFstrbuf* strbuf, char c); +[[nodiscard]] uint32_t ffStrbufCountC(const FFstrbuf* strbuf, char c); bool ffStrbufRemoveIgnCaseEndS(FFstrbuf* strbuf, const char* end); @@ -90,7 +88,7 @@ void ffStrbufLowerCase(FFstrbuf* strbuf); // Function alters the buffer to extract lines or delimited segments (replaces the delimiter with '\0') // so that buffer MUST be heap allocated (NOT a static string) -// `lineptr` must be `NULL` and `n` MUST be `0` for the first call +// `lineptr` must be `nullptr` and `n` MUST be `0` for the first call // Caller MUST NOT free `*lineptr` bool ffStrbufGetdelim(char** lineptr, size_t* n, char delimiter, FFstrbuf* buffer); void ffStrbufGetdelimRestore(char** lineptr, size_t* n, char delimiter, FFstrbuf* buffer); @@ -103,7 +101,7 @@ void ffStrbufGetdelimRestore(char** lineptr, size_t* n, char delimiter, FFstrbuf * @param[in,out] lineptr The pointer to a pointer that will be set to the start of the line (points to buffer's internal memory address to avoid memory allocation and copy). MUST NOT be freed by the caller, unlike `getline(3)`. - * MUST be NULL for the first call. + * MUST be nullptr for the first call. * @param[in,out] n The pointer to the size of the buffer of lineptr. MUST be 0 for the first call. * @param[in] buffer The buffer to read from. @@ -135,7 +133,7 @@ void ffStrbufAppendUInt(FFstrbuf* strbuf, uint64_t value); // if `precision < 0`, let yyjson decide the precision void ffStrbufAppendDouble(FFstrbuf* strbuf, double value, int8_t precision, bool trailingZeros); -FF_A_NODISCARD static inline FFstrbuf ffStrbufCreateA(uint32_t allocate) { +[[nodiscard]] static inline FFstrbuf ffStrbufCreateA(uint32_t allocate) { FFstrbuf strbuf; ffStrbufInitA(&strbuf, allocate); return strbuf; @@ -150,7 +148,7 @@ static inline void ffStrbufInitCopy(FFstrbuf* __restrict strbuf, const FFstrbuf* } } -FF_A_NODISCARD static inline FFstrbuf ffStrbufCreateCopy(const FFstrbuf* src) { +[[nodiscard]] static inline FFstrbuf ffStrbufCreateCopy(const FFstrbuf* src) { FFstrbuf strbuf; ffStrbufInitCopy(&strbuf, src); return strbuf; @@ -166,7 +164,7 @@ static inline void ffStrbufInitMove(FFstrbuf* strbuf, FFstrbuf* src) { } } -FF_A_NODISCARD static inline FFstrbuf ffStrbufCreateMove(FFstrbuf* src) { +[[nodiscard]] static inline FFstrbuf ffStrbufCreateMove(FFstrbuf* src) { FFstrbuf strbuf; ffStrbufInitMove(&strbuf, src); return strbuf; @@ -185,8 +183,8 @@ static inline void ffStrbufDestroy(FFstrbuf* strbuf) { ffStrbufInit(strbuf); } -FF_A_NODISCARD static inline uint32_t ffStrbufGetFree(const FFstrbuf* strbuf) { - assert(strbuf != NULL); +[[nodiscard]] static inline uint32_t ffStrbufGetFree(const FFstrbuf* strbuf) { + assert(strbuf != nullptr); if (strbuf->allocated == 0) { return 0; } @@ -210,7 +208,7 @@ static inline void ffStrbufEnsureFree(FFstrbuf* strbuf, uint32_t free) { static inline void ffStrbufClear(FFstrbuf* strbuf) { - assert(strbuf != NULL); + assert(strbuf != nullptr); extern char* CHAR_NULL_PTR; if (strbuf->allocated == 0) { @@ -223,9 +221,7 @@ static inline void ffStrbufClear(FFstrbuf* strbuf) { } static inline void ffStrbufAppendC(FFstrbuf* strbuf, char c) { - if (__builtin_expect(ffStrbufGetFree(strbuf) == 0, false)) { - ffStrbufEnsureFreeNoCheck(strbuf, 1); - } + ffStrbufEnsureFree(strbuf, 1); strbuf->chars[strbuf->length++] = c; strbuf->chars[strbuf->length] = '\0'; } @@ -234,9 +230,7 @@ static inline void ffStrbufAppendNC(FFstrbuf* strbuf, uint32_t num, char c) { if (__builtin_expect(num == 0, false)) { return; } - if (__builtin_expect(ffStrbufGetFree(strbuf) < num, false)) { - ffStrbufEnsureFreeNoCheck(strbuf, num); - } + ffStrbufEnsureFree(strbuf, num); memset(&strbuf->chars[strbuf->length], c, num); strbuf->length += num; @@ -244,12 +238,10 @@ static inline void ffStrbufAppendNC(FFstrbuf* strbuf, uint32_t num, char c) { } static inline void ffStrbufAppendNS(FFstrbuf* strbuf, uint32_t length, const char* value) { - if (__builtin_expect(value == NULL || length == 0, false)) { + if (__builtin_expect(value == nullptr || length == 0, false)) { return; } - if (__builtin_expect(ffStrbufGetFree(strbuf) < length, false)) { - ffStrbufEnsureFreeNoCheck(strbuf, length); - } + ffStrbufEnsureFree(strbuf, length); memcpy(&strbuf->chars[strbuf->length], value, length); strbuf->length += length; @@ -258,7 +250,7 @@ static inline void ffStrbufAppendNS(FFstrbuf* strbuf, uint32_t length, const cha static inline void ffStrbufAppend(FFstrbuf* __restrict strbuf, const FFstrbuf* __restrict value) { assert(value != strbuf); - if (value == NULL) { + if (value == nullptr) { return; } ffStrbufAppendNS(strbuf, value->length, value->chars); @@ -269,9 +261,9 @@ static inline void ffStrbufRecalculateLength(FFstrbuf* strbuf) { } static inline void ffStrbufSetS(FFstrbuf* strbuf, const char* value) { - assert(strbuf != NULL); + assert(strbuf != nullptr); - if (value == NULL) { + if (value == nullptr) { ffStrbufClear(strbuf); } else { ffStrbufSetNS(strbuf, (uint32_t) strlen(value), value); @@ -279,7 +271,7 @@ static inline void ffStrbufSetS(FFstrbuf* strbuf, const char* value) { } static inline bool ffStrbufSetJsonVal(FFstrbuf* strbuf, yyjson_val* jsonVal) { - assert(strbuf != NULL); + assert(strbuf != nullptr); if (yyjson_is_str(jsonVal)) { ffStrbufSetNS(strbuf, (uint32_t) unsafe_yyjson_get_len(jsonVal), unsafe_yyjson_get_str(jsonVal)); @@ -291,7 +283,7 @@ static inline bool ffStrbufSetJsonVal(FFstrbuf* strbuf, yyjson_val* jsonVal) { } static inline void ffStrbufAppendS(FFstrbuf* strbuf, const char* value) { - if (value == NULL) { + if (value == nullptr) { return; } ffStrbufAppendNS(strbuf, (uint32_t) strlen(value), value); @@ -311,7 +303,7 @@ static inline void ffStrbufInit(FFstrbuf* strbuf) { strbuf->chars = CHAR_NULL_PTR; } -FF_A_NODISCARD static inline FFstrbuf ffStrbufCreate(void) { +[[nodiscard]] static inline FFstrbuf ffStrbufCreate(void) { FFstrbuf strbuf; ffStrbufInit(&strbuf); return strbuf; @@ -328,7 +320,7 @@ static inline void ffStrbufInitStatic(FFstrbuf* strbuf, const char* str) { strbuf->chars = (char*) str; } -FF_A_NODISCARD static inline FFstrbuf ffStrbufCreateStatic(const char* str) { +[[nodiscard]] static inline FFstrbuf ffStrbufCreateStatic(const char* str) { FFstrbuf strbuf; ffStrbufInitStatic(&strbuf, str); return strbuf; @@ -339,7 +331,7 @@ static inline void ffStrbufSetStatic(FFstrbuf* strbuf, const char* value) { free(strbuf->chars); } - if (value != NULL) { + if (value != nullptr) { ffStrbufInitStatic(strbuf, value); } else { ffStrbufInit(strbuf); @@ -351,7 +343,7 @@ static inline void ffStrbufInitNS(FFstrbuf* strbuf, uint32_t length, const char* ffStrbufAppendNS(strbuf, length, str); } -FF_A_NODISCARD static inline FFstrbuf ffStrbufCreateNS(uint32_t length, const char* str) { +[[nodiscard]] static inline FFstrbuf ffStrbufCreateNS(uint32_t length, const char* str) { FFstrbuf strbuf; ffStrbufInitNS(&strbuf, length, str); return strbuf; @@ -367,113 +359,113 @@ static inline void ffStrbufInitS(FFstrbuf* strbuf, const char* str) { ffStrbufAppendS(strbuf, str); } -FF_A_NODISCARD static inline FFstrbuf ffStrbufCreateS(const char* str) { +[[nodiscard]] static inline FFstrbuf ffStrbufCreateS(const char* str) { FFstrbuf strbuf; ffStrbufInitS(&strbuf, str); return strbuf; } static inline void ffStrbufPrepend(FFstrbuf* strbuf, FFstrbuf* value) { - if (value == NULL) { + if (value == nullptr) { return; } ffStrbufPrependNS(strbuf, value->length, value->chars); } static inline void ffStrbufPrependS(FFstrbuf* strbuf, const char* value) { - if (value == NULL) { + if (value == nullptr) { return; } ffStrbufPrependNS(strbuf, (uint32_t) strlen(value), value); } -static inline FF_A_NODISCARD int ffStrbufComp(const FFstrbuf* strbuf, const FFstrbuf* comp) { +[[nodiscard]] static inline int ffStrbufComp(const FFstrbuf* strbuf, const FFstrbuf* comp) { uint32_t length = strbuf->length > comp->length ? comp->length : strbuf->length; return memcmp(strbuf->chars, comp->chars, length + 1); } -static inline FF_A_NODISCARD bool ffStrbufEqual(const FFstrbuf* strbuf, const FFstrbuf* comp) { +[[nodiscard]] static inline bool ffStrbufEqual(const FFstrbuf* strbuf, const FFstrbuf* comp) { return ffStrbufComp(strbuf, comp) == 0; } -static inline FF_A_NODISCARD int ffStrbufCompS(const FFstrbuf* strbuf, const char* comp) { +[[nodiscard]] static inline int ffStrbufCompS(const FFstrbuf* strbuf, const char* comp) { return strcmp(strbuf->chars, comp); } -static inline FF_A_NODISCARD bool ffStrbufEqualS(const FFstrbuf* strbuf, const char* comp) { +[[nodiscard]] static inline bool ffStrbufEqualS(const FFstrbuf* strbuf, const char* comp) { return ffStrbufCompS(strbuf, comp) == 0; } -static inline FF_A_NODISCARD int ffStrbufIgnCaseCompS(const FFstrbuf* strbuf, const char* comp) { +[[nodiscard]] static inline int ffStrbufIgnCaseCompS(const FFstrbuf* strbuf, const char* comp) { return strcasecmp(strbuf->chars, comp); } -static inline FF_A_NODISCARD bool ffStrbufIgnCaseEqualS(const FFstrbuf* strbuf, const char* comp) { +[[nodiscard]] static inline bool ffStrbufIgnCaseEqualS(const FFstrbuf* strbuf, const char* comp) { return ffStrbufIgnCaseCompS(strbuf, comp) == 0; } -static inline FF_A_NODISCARD int ffStrbufIgnCaseComp(const FFstrbuf* strbuf, const FFstrbuf* comp) { +[[nodiscard]] static inline int ffStrbufIgnCaseComp(const FFstrbuf* strbuf, const FFstrbuf* comp) { return ffStrbufIgnCaseCompS(strbuf, comp->chars); } -static inline FF_A_NODISCARD bool ffStrbufIgnCaseEqual(const FFstrbuf* strbuf, const FFstrbuf* comp) { +[[nodiscard]] static inline bool ffStrbufIgnCaseEqual(const FFstrbuf* strbuf, const FFstrbuf* comp) { return ffStrbufIgnCaseComp(strbuf, comp) == 0; } -static inline FF_A_NODISCARD bool ffStrbufContainC(const FFstrbuf* strbuf, char c) { - return memchr(strbuf->chars, c, strbuf->length) != NULL; +[[nodiscard]] static inline bool ffStrbufContainC(const FFstrbuf* strbuf, char c) { + return memchr(strbuf->chars, c, strbuf->length) != nullptr; } -static inline FF_A_NODISCARD bool ffStrbufContainS(const FFstrbuf* strbuf, const char* str) { - return strstr(strbuf->chars, str) != NULL; +[[nodiscard]] static inline bool ffStrbufContainS(const FFstrbuf* strbuf, const char* str) { + return strstr(strbuf->chars, str) != nullptr; } -static inline FF_A_NODISCARD bool ffStrbufContain(const FFstrbuf* strbuf, const FFstrbuf* str) { +[[nodiscard]] static inline bool ffStrbufContain(const FFstrbuf* strbuf, const FFstrbuf* str) { return ffStrbufContainS(strbuf, str->chars); } -static inline FF_A_NODISCARD bool ffStrbufContainIgnCaseS(const FFstrbuf* strbuf, const char* str) { - return strcasestr(strbuf->chars, str) != NULL; +[[nodiscard]] static inline bool ffStrbufContainIgnCaseS(const FFstrbuf* strbuf, const char* str) { + return strcasestr(strbuf->chars, str) != nullptr; } -static inline FF_A_NODISCARD bool ffStrbufContainIgnCase(const FFstrbuf* strbuf, const FFstrbuf* str) { +[[nodiscard]] static inline bool ffStrbufContainIgnCase(const FFstrbuf* strbuf, const FFstrbuf* str) { return ffStrbufContainIgnCaseS(strbuf, str->chars); } -FF_A_NODISCARD static inline uint32_t ffStrbufNextIndexC(const FFstrbuf* strbuf, uint32_t start, char c) { +[[nodiscard]] static inline uint32_t ffStrbufNextIndexC(const FFstrbuf* strbuf, uint32_t start, char c) { assert(start <= strbuf->length); const char* ptr = (const char*) memchr(strbuf->chars + start, c, strbuf->length - start); return ptr ? (uint32_t) (ptr - strbuf->chars) : strbuf->length; } -FF_A_NODISCARD static inline uint32_t ffStrbufNextIndexS(const FFstrbuf* strbuf, uint32_t start, const char* str) { +[[nodiscard]] static inline uint32_t ffStrbufNextIndexS(const FFstrbuf* strbuf, uint32_t start, const char* str) { assert(start <= strbuf->length); const char* ptr = strstr(strbuf->chars + start, str); return ptr ? (uint32_t) (ptr - strbuf->chars) : strbuf->length; } -FF_A_NODISCARD static inline uint32_t ffStrbufPreviousIndexC(const FFstrbuf* strbuf, uint32_t start, char c) { +[[nodiscard]] static inline uint32_t ffStrbufPreviousIndexC(const FFstrbuf* strbuf, uint32_t start, char c) { assert(start <= strbuf->length); const char* ptr = (const char*) memrchr(strbuf->chars, c, start + 1); return ptr ? (uint32_t) (ptr - strbuf->chars) : strbuf->length; } -static inline FF_A_NODISCARD uint32_t ffStrbufFirstIndexC(const FFstrbuf* strbuf, char c) { +[[nodiscard]] static inline uint32_t ffStrbufFirstIndexC(const FFstrbuf* strbuf, char c) { return ffStrbufNextIndexC(strbuf, 0, c); } -static inline FF_A_NODISCARD uint32_t ffStrbufFirstIndex(const FFstrbuf* strbuf, const FFstrbuf* searched) { +[[nodiscard]] static inline uint32_t ffStrbufFirstIndex(const FFstrbuf* strbuf, const FFstrbuf* searched) { return ffStrbufNextIndexS(strbuf, 0, searched->chars); } -static inline FF_A_NODISCARD uint32_t ffStrbufFirstIndexS(const FFstrbuf* strbuf, const char* str) { +[[nodiscard]] static inline uint32_t ffStrbufFirstIndexS(const FFstrbuf* strbuf, const char* str) { return ffStrbufNextIndexS(strbuf, 0, str); } -static inline FF_A_NODISCARD uint32_t ffStrbufLastIndexC(const FFstrbuf* strbuf, char c) { +[[nodiscard]] static inline uint32_t ffStrbufLastIndexC(const FFstrbuf* strbuf, char c) { if (strbuf->length == 0) { return 0; } @@ -489,11 +481,11 @@ static inline bool ffStrbufSubstrBeforeLastC(FFstrbuf* strbuf, char c) { return ffStrbufSubstrBefore(strbuf, ffStrbufLastIndexC(strbuf, c)); } -static inline FF_A_NODISCARD bool ffStrbufStartsWithC(const FFstrbuf* strbuf, char c) { +[[nodiscard]] static inline bool ffStrbufStartsWithC(const FFstrbuf* strbuf, char c) { return strbuf->chars[0] == c; } -static inline FF_A_NODISCARD bool ffStrbufStartsWithSN(const FFstrbuf* strbuf, const char* start, uint32_t length) { +[[nodiscard]] static inline bool ffStrbufStartsWithSN(const FFstrbuf* strbuf, const char* start, uint32_t length) { if (length > strbuf->length) { return false; } @@ -501,34 +493,34 @@ static inline FF_A_NODISCARD bool ffStrbufStartsWithSN(const FFstrbuf* strbuf, c return memcmp(strbuf->chars, start, length) == 0; } -static inline FF_A_NODISCARD bool ffStrbufStartsWithS(const FFstrbuf* strbuf, const char* start) { +[[nodiscard]] static inline bool ffStrbufStartsWithS(const FFstrbuf* strbuf, const char* start) { return ffStrbufStartsWithSN(strbuf, start, (uint32_t) strlen(start)); } -static inline FF_A_NODISCARD bool ffStrbufStartsWith(const FFstrbuf* strbuf, const FFstrbuf* start) { +[[nodiscard]] static inline bool ffStrbufStartsWith(const FFstrbuf* strbuf, const FFstrbuf* start) { return ffStrbufStartsWithSN(strbuf, start->chars, start->length); } -static inline FF_A_NODISCARD bool ffStrbufStartsWithIgnCaseNS(const FFstrbuf* strbuf, uint32_t length, const char* start) { +[[nodiscard]] static inline bool ffStrbufStartsWithIgnCaseNS(const FFstrbuf* strbuf, uint32_t length, const char* start) { if (length > strbuf->length) { return false; } return strncasecmp(strbuf->chars, start, length) == 0; } -static inline FF_A_NODISCARD bool ffStrbufStartsWithIgnCaseS(const FFstrbuf* strbuf, const char* start) { +[[nodiscard]] static inline bool ffStrbufStartsWithIgnCaseS(const FFstrbuf* strbuf, const char* start) { return ffStrbufStartsWithIgnCaseNS(strbuf, (uint32_t) strlen(start), start); } -static inline FF_A_NODISCARD bool ffStrbufStartsWithIgnCase(const FFstrbuf* strbuf, const FFstrbuf* start) { +[[nodiscard]] static inline bool ffStrbufStartsWithIgnCase(const FFstrbuf* strbuf, const FFstrbuf* start) { return ffStrbufStartsWithIgnCaseNS(strbuf, start->length, start->chars); } -static inline FF_A_NODISCARD bool ffStrbufEndsWithC(const FFstrbuf* strbuf, char c) { +[[nodiscard]] static inline bool ffStrbufEndsWithC(const FFstrbuf* strbuf, char c) { return strbuf->length == 0 ? false : strbuf->chars[strbuf->length - 1] == c; } -static inline FF_A_NODISCARD bool ffStrbufEndsWithNS(const FFstrbuf* strbuf, uint32_t endLength, const char* end) { +[[nodiscard]] static inline bool ffStrbufEndsWithNS(const FFstrbuf* strbuf, uint32_t endLength, const char* end) { if (endLength > strbuf->length) { return false; } @@ -536,30 +528,30 @@ static inline FF_A_NODISCARD bool ffStrbufEndsWithNS(const FFstrbuf* strbuf, uin return memcmp(strbuf->chars + strbuf->length - endLength, end, endLength) == 0; } -static inline FF_A_NODISCARD bool ffStrbufEndsWithS(const FFstrbuf* strbuf, const char* end) { +[[nodiscard]] static inline bool ffStrbufEndsWithS(const FFstrbuf* strbuf, const char* end) { return ffStrbufEndsWithNS(strbuf, (uint32_t) strlen(end), end); } -static inline FF_A_NODISCARD bool ffStrbufEndsWithFn(const FFstrbuf* strbuf, int (*const fn)(int)) { +[[nodiscard]] static inline bool ffStrbufEndsWithFn(const FFstrbuf* strbuf, int (*const fn)(int)) { return strbuf->length == 0 ? false : fn(strbuf->chars[strbuf->length - 1]); } -static inline FF_A_NODISCARD bool ffStrbufEndsWith(const FFstrbuf* strbuf, const FFstrbuf* end) { +[[nodiscard]] static inline bool ffStrbufEndsWith(const FFstrbuf* strbuf, const FFstrbuf* end) { return ffStrbufEndsWithNS(strbuf, end->length, end->chars); } -static inline FF_A_NODISCARD bool ffStrbufEndsWithIgnCaseNS(const FFstrbuf* strbuf, uint32_t endLength, const char* end) { +[[nodiscard]] static inline bool ffStrbufEndsWithIgnCaseNS(const FFstrbuf* strbuf, uint32_t endLength, const char* end) { if (endLength > strbuf->length) { return false; } return strcasecmp(strbuf->chars + strbuf->length - endLength, end) == 0; } -static inline FF_A_NODISCARD bool ffStrbufEndsWithIgnCaseS(const FFstrbuf* strbuf, const char* end) { +[[nodiscard]] static inline bool ffStrbufEndsWithIgnCaseS(const FFstrbuf* strbuf, const char* end) { return ffStrbufEndsWithIgnCaseNS(strbuf, (uint32_t) strlen(end), end); } -static inline FF_A_NODISCARD bool ffStrbufEndsWithIgnCase(const FFstrbuf* strbuf, const FFstrbuf* end) { +[[nodiscard]] static inline bool ffStrbufEndsWithIgnCase(const FFstrbuf* strbuf, const FFstrbuf* end) { return ffStrbufEndsWithIgnCaseNS(strbuf, end->length, end->chars); } @@ -614,19 +606,19 @@ static inline void ffStrbufPutTo(const FFstrbuf* strbuf, FILE* file) { fputc('\n', file); } -FF_A_NODISCARD static inline double ffStrbufToDouble(const FFstrbuf* strbuf, double defaultValue) { +[[nodiscard]] static inline double ffStrbufToDouble(const FFstrbuf* strbuf, double defaultValue) { char* str_end; double result = strtod(strbuf->chars, &str_end); return str_end == strbuf->chars ? defaultValue : result; } -FF_A_NODISCARD static inline uint64_t ffStrbufToUInt(const FFstrbuf* strbuf, uint64_t defaultValue) { +[[nodiscard]] static inline uint64_t ffStrbufToUInt(const FFstrbuf* strbuf, uint64_t defaultValue) { char* str_end; unsigned long long result = strtoull(strbuf->chars, &str_end, 10); return str_end == strbuf->chars ? defaultValue : (uint64_t) result; } -FF_A_NODISCARD static inline int64_t ffStrbufToSInt(const FFstrbuf* strbuf, int64_t defaultValue) { +[[nodiscard]] static inline int64_t ffStrbufToSInt(const FFstrbuf* strbuf, int64_t defaultValue) { char* str_end; long long result = strtoll(strbuf->chars, &str_end, 10); return str_end == strbuf->chars ? defaultValue : (int64_t) result; @@ -635,4 +627,4 @@ FF_A_NODISCARD static inline int64_t ffStrbufToSInt(const FFstrbuf* strbuf, int6 // Returns true if the strbuf is modified bool ffStrbufDecodeHexEscapeSequences(FFstrbuf* strbuf); -#define FF_STRBUF_AUTO_DESTROY FFstrbuf FF_A_CLEANUP(ffStrbufDestroy) +#define FF_STRBUF_AUTO_DESTROY [[gnu::cleanup(ffStrbufDestroy)]] FFstrbuf diff --git a/src/common/apple/cf_helpers.c b/src/common/apple/cf_helpers.c index 60e1a1c592..87ea2bbb19 100644 --- a/src/common/apple/cf_helpers.c +++ b/src/common/apple/cf_helpers.c @@ -5,13 +5,13 @@ const char* ffCfNumGetInt64(CFTypeRef cf, int64_t* result) { if (!CFNumberGetValue((CFNumberRef) cf, kCFNumberSInt64Type, result)) { return "Number type is not SInt64"; } - return NULL; + return nullptr; } else if (CFGetTypeID(cf) == CFDataGetTypeID()) { if (CFDataGetLength((CFDataRef) cf) != sizeof(int64_t)) { return "Data length is not sizeof(int64_t)"; } CFDataGetBytes((CFDataRef) cf, CFRangeMake(0, sizeof(int64_t)), (uint8_t*) result); - return NULL; + return nullptr; } return "TypeID is neither 'CFNumber' nor 'CFData'"; @@ -22,13 +22,13 @@ const char* ffCfNumGetInt(CFTypeRef cf, int32_t* result) { if (!CFNumberGetValue((CFNumberRef) cf, kCFNumberSInt32Type, result)) { return "Number type is not SInt32"; } - return NULL; + return nullptr; } else if (CFGetTypeID(cf) == CFDataGetTypeID()) { if (CFDataGetLength((CFDataRef) cf) != sizeof(*result)) { return "Data length is not sizeof(int32_t)"; } CFDataGetBytes((CFDataRef) cf, CFRangeMake(0, sizeof(*result)), (uint8_t*) result); - return NULL; + return nullptr; } return "TypeID is neither 'CFNumber' nor 'CFData'"; @@ -40,7 +40,7 @@ const char* ffCfNumGetDouble(CFTypeRef cf, double* result) { !CFNumberGetValue((CFNumberRef) cf, kCFNumberFloatType, result)) { return "Number type is not Double or Float"; } - return NULL; + return nullptr; } return "TypeID is neither 'CFNumber'"; @@ -54,13 +54,13 @@ const char* ffCfDateGetEpoch(CFTypeRef cf, uint64_t* result) { CFAbsoluteTime absTime = CFDateGetAbsoluteTime((CFDateRef) cf); // Convert from seconds to milliseconds and add the difference between 1970 and 2001 in milliseconds *result = (uint64_t) ((absTime + 978307200 /*kCFAbsoluteTimeIntervalSince1970*/) * 1000); - return NULL; + return nullptr; } const char* ffCfStrGetString(CFTypeRef cf, FFstrbuf* result) { ffStrbufClear(result); if (!cf) { - return NULL; + return nullptr; } if (CFGetTypeID(cf) == CFStringGetTypeID()) { @@ -72,7 +72,7 @@ const char* ffCfStrGetString(CFTypeRef cf, FFstrbuf* result) { } else { uint32_t length = (uint32_t) CFStringGetLength(cfStr); if (length == 0) { - return NULL; + return nullptr; } ffStrbufEnsureFixedLengthFree(result, (uint32_t) CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8)); if (!CFStringGetCString(cfStr, result->chars, result->allocated, kCFStringEncodingUTF8)) { @@ -86,7 +86,7 @@ const char* ffCfStrGetString(CFTypeRef cf, FFstrbuf* result) { CFDataRef cfData = (CFDataRef) cf; uint32_t length = (uint32_t) CFDataGetLength(cfData); if (length == 0) { - return NULL; + return nullptr; } ffStrbufEnsureFixedLengthFree(result, length + 1); CFDataGetBytes(cfData, CFRangeMake(0, length), (uint8_t*) result->chars); @@ -96,20 +96,20 @@ const char* ffCfStrGetString(CFTypeRef cf, FFstrbuf* result) { return "TypeID is neither 'CFString' nor 'CFData'"; } - return NULL; + return nullptr; } const char* ffCfDataGetDataAsString(CFTypeRef cf, FFstrbuf* result) { ffStrbufClear(result); if (!cf) { - return NULL; + return nullptr; } if (CFGetTypeID(cf) == CFDataGetTypeID()) { CFDataRef cfData = (CFDataRef) cf; uint32_t length = (uint32_t) CFDataGetLength(cfData); if (length == 0) { - return NULL; + return nullptr; } ffStrbufEnsureFixedLengthFree(result, length + 1); CFDataGetBytes(cfData, CFRangeMake(0, length), (uint8_t*) result->chars); @@ -119,12 +119,12 @@ const char* ffCfDataGetDataAsString(CFTypeRef cf, FFstrbuf* result) { return "TypeID is not 'CFData'"; } - return NULL; + return nullptr; } const char* ffCfDictGetString(CFDictionaryRef dict, CFStringRef key, FFstrbuf* result) { CFTypeRef cf = (CFTypeRef) CFDictionaryGetValue(dict, key); - if (cf == NULL) { + if (cf == nullptr) { return "CFDictionaryGetValue() failed"; } @@ -133,7 +133,7 @@ const char* ffCfDictGetString(CFDictionaryRef dict, CFStringRef key, FFstrbuf* r const char* ffCfDictGetDataAsString(CFDictionaryRef dict, CFStringRef key, FFstrbuf* result) { CFTypeRef cf = (CFTypeRef) CFDictionaryGetValue(dict, key); - if (cf == NULL) { + if (cf == nullptr) { return "CFDictionaryGetValue() failed"; } @@ -142,7 +142,7 @@ const char* ffCfDictGetDataAsString(CFDictionaryRef dict, CFStringRef key, FFstr const char* ffCfDictGetBool(CFDictionaryRef dict, CFStringRef key, bool* result) { CFBooleanRef cf = (CFBooleanRef) CFDictionaryGetValue(dict, key); - if (cf == NULL) { + if (cf == nullptr) { return "CFDictionaryGetValue() failed"; } @@ -151,12 +151,12 @@ const char* ffCfDictGetBool(CFDictionaryRef dict, CFStringRef key, bool* result) } *result = CFBooleanGetValue(cf); - return NULL; + return nullptr; } const char* ffCfDictGetInt(CFDictionaryRef dict, CFStringRef key, int* result) { CFTypeRef cf = (CFTypeRef) CFDictionaryGetValue(dict, key); - if (cf == NULL) { + if (cf == nullptr) { return "CFDictionaryGetValue() failed"; } @@ -165,7 +165,7 @@ const char* ffCfDictGetInt(CFDictionaryRef dict, CFStringRef key, int* result) { const char* ffCfDictGetInt64(CFDictionaryRef dict, CFStringRef key, int64_t* result) { CFTypeRef cf = (CFTypeRef) CFDictionaryGetValue(dict, key); - if (cf == NULL) { + if (cf == nullptr) { return "CFDictionaryGetValue() failed"; } @@ -174,7 +174,7 @@ const char* ffCfDictGetInt64(CFDictionaryRef dict, CFStringRef key, int64_t* res const char* ffCfDictGetDouble(CFDictionaryRef dict, CFStringRef key, double* result) { CFTypeRef cf = (CFTypeRef) CFDictionaryGetValue(dict, key); - if (cf == NULL) { + if (cf == nullptr) { return "CFDictionaryGetValue() failed"; } @@ -183,7 +183,7 @@ const char* ffCfDictGetDouble(CFDictionaryRef dict, CFStringRef key, double* res const char* ffCfDictGetData(CFDictionaryRef dict, CFStringRef key, uint32_t offset, uint32_t size, uint8_t* result, uint32_t* length) { CFTypeRef cf = (CFTypeRef) CFDictionaryGetValue(dict, key); - if (cf == NULL) { + if (cf == nullptr) { return "CFDictionaryGetValue() failed"; } @@ -202,22 +202,22 @@ const char* ffCfDictGetData(CFDictionaryRef dict, CFStringRef key, uint32_t offs } CFDataGetBytes((CFDataRef) cf, CFRangeMake(offset, size), result); - return NULL; + return nullptr; } const char* ffCfDictGetDict(CFDictionaryRef dict, CFStringRef key, CFDictionaryRef* result) { CFDictionaryRef cf = (CFDictionaryRef) CFDictionaryGetValue(dict, key); - if (cf == NULL || CFGetTypeID(cf) != CFDictionaryGetTypeID()) { + if (cf == nullptr || CFGetTypeID(cf) != CFDictionaryGetTypeID()) { return "TypeID is not 'CFDictionary'"; } *result = cf; - return NULL; + return nullptr; } const char* ffCfDictGetDateAsEpoch(CFDictionaryRef dict, CFStringRef key, uint64_t* result) { CFTypeRef cf = (CFTypeRef) CFDictionaryGetValue(dict, key); - if (cf == NULL) { + if (cf == nullptr) { return "CFDictionaryGetValue() failed"; } diff --git a/src/common/apple/cf_helpers.h b/src/common/apple/cf_helpers.h index a929f030e8..3df16b5942 100644 --- a/src/common/apple/cf_helpers.h +++ b/src/common/apple/cf_helpers.h @@ -4,7 +4,7 @@ #include #include -// Return error info if failed, NULL otherwise +// Return error info if failed, nullptr otherwise const char* ffCfStrGetString(CFTypeRef cf, FFstrbuf* result); const char* ffCfNumGetInt(CFTypeRef cf, int32_t* result); const char* ffCfNumGetInt64(CFTypeRef cf, int64_t* result); @@ -32,7 +32,7 @@ static inline void cfReleaseWrapper(void* type) { } } -#define FF_CFTYPE_AUTO_RELEASE FF_A_CLEANUP(cfReleaseWrapper) +#define FF_CFTYPE_AUTO_RELEASE [[gnu::cleanup(cfReleaseWrapper)]] static inline void wrapIoObjectRelease(io_object_t* service) { assert(service); @@ -40,4 +40,4 @@ static inline void wrapIoObjectRelease(io_object_t* service) { IOObjectRelease(*service); } } -#define FF_IOOBJECT_AUTO_RELEASE FF_A_CLEANUP(wrapIoObjectRelease) +#define FF_IOOBJECT_AUTO_RELEASE [[gnu::cleanup(wrapIoObjectRelease)]] diff --git a/src/common/apple/smc_temps.c b/src/common/apple/smc_temps.c index 6669c31259..9fb18210f4 100644 --- a/src/common/apple/smc_temps.c +++ b/src/common/apple/smc_temps.c @@ -86,7 +86,7 @@ static const char* smcCall(io_connect_t conn, uint32_t selector, SmcKeyData_t* i if (IOConnectCallStructMethod(conn, selector, inputStructure, size, outputStructure, &size) != kIOReturnSuccess) { return "IOConnectCallStructMethod(conn) failed"; } - return NULL; + return nullptr; } // Provides key info, using a cache to dramatically improve the energy impact of smcFanControl @@ -103,7 +103,7 @@ static const char* smcGetKeyInfo(io_connect_t conn, const uint32_t key, SmcKeyDa } *key_info = outputStructure.keyInfo; - return NULL; + return nullptr; } static const char* smcReadSmcVal(io_connect_t conn, const UInt32Char_t key, SmcVal_t* val) { @@ -130,7 +130,7 @@ static const char* smcReadSmcVal(io_connect_t conn, const UInt32Char_t key, SmcV memcpy(val->bytes, outputStructure.bytes, sizeof(outputStructure.bytes)); - return NULL; + return nullptr; } static const char* smcOpen(io_connect_t* conn) { @@ -143,13 +143,13 @@ static const char* smcOpen(io_connect_t* conn) { return "IOServiceOpen() failed"; } - return NULL; + return nullptr; } static const char* smcReadValue(io_connect_t conn, const UInt32Char_t key, double* value) { SmcVal_t val = { 0 }; const char* error = smcReadSmcVal(conn, key, &val); - if (error != NULL) { + if (error != nullptr) { return error; } if (val.dataSize == 0) { @@ -270,7 +270,7 @@ static const char* smcReadValue(io_connect_t conn, const UInt32Char_t key, doubl default: return "Unsupported SMC data type"; } - return NULL; + return nullptr; } static bool detectTemp(io_connect_t conn, const char* sensor, double* sum) { @@ -291,7 +291,7 @@ static io_connect_t conn; const char* ffDetectSmcSpecificTemp(const char* sensor, double* result) { if (!conn) { - if (smcOpen(&conn) != NULL) { + if (smcOpen(&conn) != nullptr) { conn = (io_connect_t) -1; } } @@ -303,12 +303,12 @@ const char* ffDetectSmcSpecificTemp(const char* sensor, double* result) { return "Could not read SMC temperature"; } - return NULL; + return nullptr; } const char* ffDetectSmcTemps(enum FFTempType type, double* result) { if (!conn) { - if (smcOpen(&conn) != NULL) { + if (smcOpen(&conn) != nullptr) { conn = (io_connect_t) -1; } } @@ -392,6 +392,27 @@ const char* ffDetectSmcTemps(enum FFTempType type, double* result) { count += detectTemp(conn, "Tp0e", result); // CPU performance core 8 break; + case FF_TEMP_CPU_M5X: + count += detectTemp(conn, "Tp00", result); // CPU super core 1 + count += detectTemp(conn, "Tp04", result); // CPU super core 2 + count += detectTemp(conn, "Tp08", result); // CPU super core 3 + count += detectTemp(conn, "Tp0C", result); // CPU super core 4 + count += detectTemp(conn, "Tp0G", result); // CPU super core 5 + count += detectTemp(conn, "Tp0K", result); // CPU super core 6 + count += detectTemp(conn, "Tp0O", result); // CPU performance core 1 + count += detectTemp(conn, "Tp0R", result); // CPU performance core 2 + count += detectTemp(conn, "Tp0U", result); // CPU performance core 3 + count += detectTemp(conn, "Tp0X", result); // CPU performance core 4 + count += detectTemp(conn, "Tp0a", result); // CPU performance core 5 + count += detectTemp(conn, "Tp0d", result); // CPU performance core 6 + count += detectTemp(conn, "Tp0g", result); // CPU performance core 7 + count += detectTemp(conn, "Tp0j", result); // CPU performance core 8 + count += detectTemp(conn, "Tp0m", result); // CPU performance core 9 + count += detectTemp(conn, "Tp0p", result); // CPU performance core 10 + count += detectTemp(conn, "Tp0u", result); // CPU performance core 11 + count += detectTemp(conn, "Tp0y", result); // CPU performance core 12 + break; + case FF_TEMP_GPU_INTEL: count += detectTemp(conn, "TCGC", result); // GPU Intel Graphics goto gpu_unknown; @@ -442,6 +463,17 @@ const char* ffDetectSmcTemps(enum FFTempType type, double* result) { count += detectTemp(conn, "Tg0k", result); // GPU 8 break; + case FF_TEMP_GPU_M5X: + count += detectTemp(conn, "Tg0U", result); // GPU 1 + count += detectTemp(conn, "Tg0X", result); // GPU 2 + count += detectTemp(conn, "Tg0d", result); // GPU 3 + count += detectTemp(conn, "Tg0g", result); // GPU 4 + count += detectTemp(conn, "Tg0j", result); // GPU 5 + count += detectTemp(conn, "Tg1Y", result); // GPU 6 + count += detectTemp(conn, "Tg1c", result); // GPU 7 + count += detectTemp(conn, "Tg1g", result); // GPU 8 + break; + case FF_TEMP_BATTERY: count += detectTemp(conn, "TB1T", result); // Battery count += detectTemp(conn, "TB2T", result); // Battery @@ -452,6 +484,9 @@ const char* ffDetectSmcTemps(enum FFTempType type, double* result) { count += detectTemp(conn, "Tm06", result); // Memory 2 count += detectTemp(conn, "Tm08", result); // Memory 3 count += detectTemp(conn, "Tm09", result); // Memory 4 + count += detectTemp(conn, "Tm0p", result); // Memory Proximity 1 (M4) + count += detectTemp(conn, "Tm1p", result); // Memory Proximity 2 (M4) + count += detectTemp(conn, "Tm2p", result); // Memory Proximity 3 (M4) break; } @@ -461,5 +496,5 @@ const char* ffDetectSmcTemps(enum FFTempType type, double* result) { *result /= count; - return NULL; + return nullptr; } diff --git a/src/common/apple/smc_temps.h b/src/common/apple/smc_temps.h index 6783bb95b9..0f03a912b3 100644 --- a/src/common/apple/smc_temps.h +++ b/src/common/apple/smc_temps.h @@ -8,12 +8,13 @@ typedef struct FFTempValue { double value; } FFTempValue; -enum FFTempType { +enum FFTempType: uint8_t { FF_TEMP_CPU_X64, FF_TEMP_CPU_M1X, FF_TEMP_CPU_M2X, FF_TEMP_CPU_M3X, FF_TEMP_CPU_M4X, + FF_TEMP_CPU_M5X, FF_TEMP_GPU_INTEL, FF_TEMP_GPU_AMD, @@ -22,6 +23,7 @@ enum FFTempType { FF_TEMP_GPU_M2X, FF_TEMP_GPU_M3X, FF_TEMP_GPU_M4X, + FF_TEMP_GPU_M5X, FF_TEMP_BATTERY, diff --git a/src/common/apple/version.m b/src/common/apple/version.m index 133ec5b196..e6d4fae621 100644 --- a/src/common/apple/version.m +++ b/src/common/apple/version.m @@ -16,7 +16,7 @@ bool ffGetAppNameAndVersion(const char* exePath, FFstrbuf* retName, FFstrbuf* re lastSlash -= strlen("MacOS"); char infoPlistPath[PATH_MAX]; - memcpy(infoPlistPath, exePath, lastSlash - exePath); + memcpy(infoPlistPath, exePath, (size_t) (lastSlash - exePath)); memcpy(infoPlistPath + (lastSlash - exePath), "Info.plist", sizeof("Info.plist")); // X.app/Contents/Info.plist NSError* error; NSDictionary* dict = [NSDictionary dictionaryWithContentsOfURL:[NSURL fileURLWithPath:@(infoPlistPath)] diff --git a/src/common/argType.h b/src/common/argType.h index 81217c7f94..5851be7a2f 100644 --- a/src/common/argType.h +++ b/src/common/argType.h @@ -10,7 +10,7 @@ typedef struct FFArgBuffer { uint32_t length; } FFArgBuffer; -typedef enum FF_A_PACKED FFArgType { +typedef enum FFArgType: uint8_t { FF_ARG_TYPE_NULL = 0, FF_ARG_TYPE_UINT, FF_ARG_TYPE_UINT64, diff --git a/src/common/arrutil.h b/src/common/arrutil.h index 83a49d6aa0..d2c47b151d 100644 --- a/src/common/arrutil.h +++ b/src/common/arrutil.h @@ -6,9 +6,9 @@ #if !__cplusplus && FF_SUPPORTS_COUNT_OF #define ARRAY_SIZE(x) _Countof(x) #elif __has_builtin(__is_array) - #define ARRAY_SIZE(x) ({ static_assert(__is_array(__typeof__(x)), "Must be an array"); (uint32_t) (sizeof(x) / sizeof(*(x))); }) + #define ARRAY_SIZE(x) ({ static_assert(__is_array(typeof(x)), "Must be an array"); (uint32_t) (sizeof(x) / sizeof(*(x))); }) #elif __has_builtin(__builtin_types_compatible_p) - #define ARRAY_SIZE(x) ({ static_assert(!__builtin_types_compatible_p(__typeof__(x), __typeof__(&*(x))), "Must not be a pointer"); (uint32_t) (sizeof(x) / sizeof(*(x))); }) + #define ARRAY_SIZE(x) ({ static_assert(!__builtin_types_compatible_p(typeof(x), typeof(&*(x))), "Must not be a pointer"); (uint32_t) (sizeof(x) / sizeof(*(x))); }) #endif #endif #ifndef ARRAY_SIZE diff --git a/src/common/attributes.h b/src/common/attributes.h deleted file mode 100644 index a7b964c4d4..0000000000 --- a/src/common/attributes.h +++ /dev/null @@ -1,20 +0,0 @@ -#pragma once - -#ifndef __has_attribute - #error Unsupported compiler - #define __attribute__(x) -#endif - -#define FF_A_FALLTHROUGH __attribute__((__fallthrough__)) -#define FF_A_DEPRECATED __attribute__((__deprecated__)) -#define FF_A_CLEANUP(func) __attribute__((__cleanup__(func))) -#define FF_A_NODISCARD __attribute__((__warn_unused_result__)) -#define FF_A_PRINTF(formatStrIndex, argsStartIndex) __attribute__((__format__(printf, formatStrIndex, argsStartIndex))) -#define FF_A_SCANF(formatStrIndex, argsStartIndex) __attribute__((__format__(scanf, formatStrIndex, argsStartIndex))) -#define FF_A_NONNULL(argIndex, ...) __attribute__((__nonnull__(argIndex, ##__VA_ARGS__))) -#define FF_A_RETURNS_NONNULL __attribute__((__returns_nonnull__)) -#define FF_A_UNUSED __attribute__((__unused__)) -#define FF_A_PACKED __attribute__((__packed__)) -#define FF_A_WEAK_IMPORT __attribute__((__weak_import__)) -#define FF_A_ALWAYS_INLINE __attribute__((__always_inline__)) -#define FF_A_COLD __attribute__((__cold__)) diff --git a/src/common/binary.h b/src/common/binary.h index 2d2d7849bd..b4580e7a08 100644 --- a/src/common/binary.h +++ b/src/common/binary.h @@ -11,7 +11,7 @@ * @param userdata User-provided data passed to the callback function * @param minLength Minimum length of strings to extract * - * @return NULL on success, error message on failure. + * @return nullptr on success, error message on failure. * @note This function won't return an error if no strings are found. * Always check if strings are correctly extracted after this function all. */ diff --git a/src/common/dbus.h b/src/common/dbus.h index e0689c3fee..e4274180a7 100644 --- a/src/common/dbus.h +++ b/src/common/dbus.h @@ -26,7 +26,7 @@ typedef struct FFDBusData { DBusConnection* connection; } FFDBusData; -const char* ffDBusLoadData(DBusBusType busType, FFDBusData* data); // Returns an error message or NULL on success +const char* ffDBusLoadData(DBusBusType busType, FFDBusData* data); // Returns an error message or nullptr on success bool ffDBusGetString(FFDBusData* dbus, DBusMessageIter* iter, FFstrbuf* result); bool ffDBusGetBool(FFDBusData* dbus, DBusMessageIter* iter, bool* result); bool ffDBusGetUint(FFDBusData* dbus, DBusMessageIter* iter, uint64_t* result); @@ -38,9 +38,9 @@ bool ffDBusGetPropertyUint(FFDBusData* dbus, const char* busName, const char* ob void ffDBusDestroyData(FFDBusData* data); static inline DBusMessage* ffDBusGetAllProperties(FFDBusData* dbus, const char* busName, const char* objectPath, const char* interface) { - return ffDBusGetMethodReply(dbus, busName, objectPath, "org.freedesktop.DBus.Properties", "GetAll", interface, NULL); + return ffDBusGetMethodReply(dbus, busName, objectPath, "org.freedesktop.DBus.Properties", "GetAll", interface, nullptr); } - #define FF_DBUS_AUTO_DESTROY_DATA FF_A_CLEANUP(ffDBusDestroyData) + #define FF_DBUS_AUTO_DESTROY_DATA [[gnu::cleanup(ffDBusDestroyData)]] #endif // FF_HAVE_DBUS diff --git a/src/common/debug.h b/src/common/debug.h index d79c48880f..ee7f4be04a 100644 --- a/src/common/debug.h +++ b/src/common/debug.h @@ -6,11 +6,11 @@ static inline const char* ffFindFileName(const char* file) { const char* lastSlash = __builtin_strrchr(file, '/'); #ifdef _WIN32 - if (lastSlash == NULL) { + if (lastSlash == nullptr) { lastSlash = __builtin_strrchr(file, '\\'); } #endif - if (lastSlash != NULL) { + if (lastSlash != nullptr) { return lastSlash + 1; } return file; diff --git a/src/common/ffdata.h b/src/common/ffdata.h index 189c0fab27..fe2d4f66f2 100644 --- a/src/common/ffdata.h +++ b/src/common/ffdata.h @@ -2,7 +2,7 @@ #include "common/FFstrbuf.h" -typedef enum FF_A_PACKED FFDataResultDocType { +typedef enum FFDataResultDocType: uint8_t { FF_RESULT_DOC_TYPE_DEFAULT = 0, FF_RESULT_DOC_TYPE_JSON, FF_RESULT_DOC_TYPE_CONFIG, @@ -19,4 +19,5 @@ typedef struct FFdata { FFstrbuf genConfigPath; // Path to generate configuration file FFDataResultDocType docType; // Type of result document bool configLoaded; + bool genConfigInteractive; // `--gen-config` entered the interactive CUI } FFdata; diff --git a/src/common/font.h b/src/common/font.h index f9d25e7fd0..cdb8b200e9 100644 --- a/src/common/font.h +++ b/src/common/font.h @@ -21,5 +21,5 @@ void ffFontInitWithSpace(FFfont* font, const char* rawName); void ffFontDestroy(FFfont* font); static inline void ffFontInitCopy(FFfont* font, const char* name) { - ffFontInitValues(font, name, NULL); + ffFontInitValues(font, name, nullptr); } diff --git a/src/common/genconfig.h b/src/common/genconfig.h new file mode 100644 index 0000000000..91f136a3d0 --- /dev/null +++ b/src/common/genconfig.h @@ -0,0 +1,11 @@ +#pragma once + +#include "common/ffdata.h" + +// Runs the interactive config generation CUI. +// +// On success (the user saved the config), it sets `data->structure` to the user chosen +// module structure and `instance.config.logo.type` to the user chosen logo type, creates +// the result document and returns true. The caller is expected to call `writeConfigFile`. +// Returns false if the user quits without saving. +bool ffGenConfigInteractive(FFdata* data); diff --git a/src/common/impl/FFPlatform_unix.c b/src/common/impl/FFPlatform_unix.c index 3b9c87db7e..ec2ef1699d 100644 --- a/src/common/impl/FFPlatform_unix.c +++ b/src/common/impl/FFPlatform_unix.c @@ -57,7 +57,7 @@ static void getExePath(FFPlatform* platform) { 4, exePath, &exePathLen, - NULL, + nullptr, 0) < 0) exePathLen = 0; else { @@ -68,7 +68,7 @@ static void getExePath(FFPlatform* platform) { // Current implementation uses argv[0], which can be easily spoofed. // See #2195 size_t exePathLen = 0; - kvm_t* kd = kvm_openfiles(NULL, NULL, NULL, KVM_NO_FILES, NULL); + kvm_t* kd = kvm_openfiles(nullptr, nullptr, nullptr, KVM_NO_FILES, nullptr); if (kd) { int kpCount; struct kinfo_proc* kp = kvm_getprocs(kd, KERN_PROC_PID, (pid_t) platform->pid, sizeof(*kp), &kpCount); @@ -77,7 +77,7 @@ static void getExePath(FFPlatform* platform) { if (argv && argv[0]) { char* arg0 = argv[0]; if (arg0[0]) { - if (strchr(arg0, '/') != NULL) // likely a path (absolute or relative) + if (strchr(arg0, '/') != nullptr) // likely a path (absolute or relative) { exePathLen = strlen(arg0); if (exePathLen < ARRAY_SIZE(exePath)) { @@ -88,7 +88,7 @@ static void getExePath(FFPlatform* platform) { } } else { FF_STRBUF_AUTO_DESTROY tmpPath = ffStrbufCreate(); - if (ffFindExecutableInPath(arg0, &tmpPath) == NULL && tmpPath.length < ARRAY_SIZE(exePath)) { + if (ffFindExecutableInPath(arg0, &tmpPath) == nullptr && tmpPath.length < ARRAY_SIZE(exePath)) { memcpy(exePath, tmpPath.chars, tmpPath.length + 1); exePathLen = tmpPath.length; } @@ -282,7 +282,7 @@ static void getSysinfo(FFPlatformSysinfo* info, const struct utsname* uts) { #if defined(__FreeBSD__) || defined(__APPLE__) || defined(__OpenBSD__) || defined(__NetBSD__) size_t length = sizeof(info->pageSize); - sysctl((int[]) { CTL_HW, HW_PAGESIZE }, 2, &info->pageSize, &length, NULL, 0); + sysctl((int[]) { CTL_HW, HW_PAGESIZE }, 2, &info->pageSize, &length, nullptr, 0); #else info->pageSize = (uint32_t) sysconf(_SC_PAGESIZE); #endif @@ -290,7 +290,7 @@ static void getSysinfo(FFPlatformSysinfo* info, const struct utsname* uts) { static void getCwd(FFPlatform* platform) { char cwd[PATH_MAX]; - if (getcwd(cwd, sizeof(cwd)) != NULL) { + if (getcwd(cwd, sizeof(cwd)) != nullptr) { ffStrbufSetS(&platform->cwd, cwd); ffStrbufEnsureEndsWithC(&platform->cwd, '/'); } diff --git a/src/common/impl/FFPlatform_windows.c b/src/common/impl/FFPlatform_windows.c index b07e9c8c9a..dea4c2deba 100644 --- a/src/common/impl/FFPlatform_windows.c +++ b/src/common/impl/FFPlatform_windows.c @@ -21,10 +21,10 @@ static void getExePath(FFPlatform* platform) { ffGetPeb()->ProcessParameters->ImagePathName.Buffer, GENERIC_READ, FILE_SHARE_READ, - NULL, + nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, - NULL); + nullptr); if (hPath != INVALID_HANDLE_VALUE) { DWORD len = GetFinalPathNameByHandleW(hPath, exePathW, MAX_PATH, FILE_NAME_NORMALIZED); if (len > 0 && len < MAX_PATH) { @@ -44,8 +44,8 @@ static void getExePath(FFPlatform* platform) { } static void getHomeDir(FFPlatform* platform) { - PWSTR pPath = NULL; - if (SUCCEEDED(SHGetKnownFolderPath(&FOLDERID_Profile, KF_FLAG_DEFAULT, NULL, &pPath))) { + PWSTR pPath = nullptr; + if (SUCCEEDED(SHGetKnownFolderPath(&FOLDERID_Profile, KF_FLAG_DEFAULT, nullptr, &pPath))) { ffStrbufSetWS(&platform->homeDir, pPath); ffStrbufReplaceAllC(&platform->homeDir, '\\', '/'); ffStrbufEnsureEndsWithC(&platform->homeDir, '/'); @@ -58,8 +58,8 @@ static void getHomeDir(FFPlatform* platform) { } static void getCacheDir(FFPlatform* platform) { - PWSTR pPath = NULL; - if (SUCCEEDED(SHGetKnownFolderPath(&FOLDERID_LocalAppData, KF_FLAG_DEFAULT, NULL, &pPath))) { + PWSTR pPath = nullptr; + if (SUCCEEDED(SHGetKnownFolderPath(&FOLDERID_LocalAppData, KF_FLAG_DEFAULT, nullptr, &pPath))) { ffStrbufSetWS(&platform->cacheDir, pPath); ffStrbufReplaceAllC(&platform->cacheDir, '\\', '/'); ffStrbufEnsureEndsWithC(&platform->cacheDir, '/'); @@ -71,8 +71,8 @@ static void getCacheDir(FFPlatform* platform) { } static void platformPathAddKnownFolder(FFlist* dirs, REFKNOWNFOLDERID folderId) { - PWSTR pPath = NULL; - if (SUCCEEDED(SHGetKnownFolderPath(folderId, KF_FLAG_DEFAULT, NULL, &pPath))) { + PWSTR pPath = nullptr; + if (SUCCEEDED(SHGetKnownFolderPath(folderId, KF_FLAG_DEFAULT, nullptr, &pPath))) { FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreateWS(pPath); CoTaskMemFree(pPath); ffStrbufReplaceAllC(&buffer, '\\', '/'); @@ -107,7 +107,7 @@ static void getConfigDirs(FFPlatform* platform) { if (getenv("MSYSTEM")) { // We are in MSYS2 / Git Bash platformPathAddEnvSuffix(&platform->configDirs, "HOME", ".config/"); - platformPathAddEnvSuffix(&platform->configDirs, "HOME", NULL); + platformPathAddEnvSuffix(&platform->configDirs, "HOME", nullptr); platformPathAddEnvSuffix(&platform->configDirs, "MINGW_PREFIX", "etc"); } @@ -122,7 +122,7 @@ static void getDataDirs(FFPlatform* platform) { if (getenv("MSYSTEM") && getenv("HOME")) { // We are in MSYS2 / Git Bash platformPathAddEnvSuffix(&platform->dataDirs, "HOME", ".local/share/"); - platformPathAddEnvSuffix(&platform->dataDirs, "HOME", NULL); + platformPathAddEnvSuffix(&platform->dataDirs, "HOME", nullptr); platformPathAddEnvSuffix(&platform->dataDirs, "MINGW_PREFIX", "share"); } ffPlatformPathAddHome(&platform->dataDirs, platform, ".local/share/"); @@ -142,8 +142,8 @@ static void getUserName(FFPlatform* platform) { NTSYSAPI NTSTATUS NTAPI LsaGetUserName( _Outptr_ PLSA_UNICODE_STRING * UserName, _Outptr_opt_ PLSA_UNICODE_STRING * DomainName); - PLSA_UNICODE_STRING userName = NULL; - if (NT_SUCCESS(LsaGetUserName(&userName, NULL))) { + PLSA_UNICODE_STRING userName = nullptr; + if (NT_SUCCESS(LsaGetUserName(&userName, nullptr))) { ffStrbufSetNWS(&platform->userName, userName->Length / sizeof(wchar_t), userName->Buffer); RtlFreeUnicodeString(userName); // Required. userName.Buffer is allocated separately LsaFreeMemory(userName); @@ -187,18 +187,18 @@ static const char* detectWine(void) { const char* __cdecl wine_get_version(void); void* hntdll = ffLibraryGetModule(L"ntdll.dll"); if (!hntdll) { - return NULL; + return nullptr; } FF_LIBRARY_LOAD_SYMBOL_LAZY(hntdll, wine_get_version); if (!ffwine_get_version) { - return NULL; + return nullptr; } return ffwine_get_version(); } static void getSystemReleaseAndVersion(FFPlatformSysinfo* info) { - FF_AUTO_CLOSE_FD HANDLE hKey = NULL; - if (!ffRegOpenKeyForRead(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", &hKey, NULL)) { + FF_AUTO_CLOSE_FD HANDLE hKey = nullptr; + if (!ffRegOpenKeyForRead(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", &hKey, nullptr)) { return; } @@ -207,7 +207,7 @@ static void getSystemReleaseAndVersion(FFPlatformSysinfo* info) { FF_ARG(ubr, L"UBR"), FF_ARG(info->version, L"BuildLabEx"), }, - NULL); + nullptr); PPEB_FULL peb = ffGetPeb(); @@ -228,7 +228,7 @@ static void getSystemReleaseAndVersion(FFPlatformSysinfo* info) { static void getSystemPageSize(FFPlatformSysinfo* info) { SYSTEM_BASIC_INFORMATION sbi; - if (NT_SUCCESS(NtQuerySystemInformation(SystemBasicInformation, &sbi, sizeof(sbi), NULL))) { + if (NT_SUCCESS(NtQuerySystemInformation(SystemBasicInformation, &sbi, sizeof(sbi), nullptr))) { info->pageSize = sbi.PhysicalPageSize; } else { info->pageSize = 4096; diff --git a/src/common/impl/FFstrbuf.c b/src/common/impl/FFstrbuf.c index 5b392eb8f9..2ed3e9de84 100644 --- a/src/common/impl/FFstrbuf.c +++ b/src/common/impl/FFstrbuf.c @@ -1,6 +1,7 @@ #include "common/FFstrbuf.h" #include "common/mallocHelper.h" #include "common/strutil.h" +#include "common/debug.h" #include #include @@ -20,9 +21,9 @@ void ffStrbufInitA(FFstrbuf* strbuf, uint32_t allocate) { } void ffStrbufInitVF(FFstrbuf* strbuf, const char* format, va_list arguments) { - assert(format != NULL); + assert(format != nullptr); - char* buffer = NULL; + char* buffer = nullptr; int len = vasprintf(&buffer, format, arguments); assert(len >= 0); @@ -32,7 +33,7 @@ void ffStrbufInitVF(FFstrbuf* strbuf, const char* format, va_list arguments) { // Takes ownership of `heapStr`. The caller must not free `heapStr` after calling this // function; the memory will be managed and freed via the associated FFstrbuf. void ffStrbufInitMoveNS(FFstrbuf* strbuf, uint32_t length, char* heapStr) { - assert(heapStr != NULL); + assert(heapStr != nullptr); strbuf->length = length; size_t allocSize = ffMallocUsableSize(heapStr); @@ -64,13 +65,24 @@ FFstrbuf ffStrbufCreateF(const char* format, ...) { } void ffStrbufEnsureFreeNoCheck(FFstrbuf* strbuf, uint32_t free) { - uint32_t allocate = strbuf->length + free; + uint32_t allocate; + if (__builtin_expect(__builtin_uadd_overflow(strbuf->length, free, &allocate), false)) { + FF_DEBUG("Error: Integer overflow when calculating allocation size. Aborting"); + abort(); + } + if (allocate < FASTFETCH_STRBUF_DEFAULT_ALLOC) { // `<` for null terminator allocate = FASTFETCH_STRBUF_DEFAULT_ALLOC; } else { + if (__builtin_expect(allocate > (UINT32_MAX >> 1), false)) { + // User tried to allocate more than 2GB of memory, which exceeds the maximum size supported by FFstrbuf. + // This is likely an error or an attempt to exploit the program. Abort to prevent potential issues. + FF_DEBUG("Error: Attempted to allocate %" PRIu32 " bytes more than 2GB of memory in FFstrbuf. Aborting", allocate); + abort(); + } + // Round up to the next power of 2. // If the value is already a power of 2, it will be rounded up to the next power of 2. - assert(allocate < (UINT32_MAX >> 1)); allocate = 1U << (32 - __builtin_clz(allocate)); } @@ -91,16 +103,17 @@ void ffStrbufEnsureFreeNoCheck(FFstrbuf* strbuf, uint32_t free) { // Ensure that at least `free` bytes are available in the buffer besides the current length // for an empty buffer, free + 1 length memory will be allocated(+1 for the NUL) +// This function ensures a dynamic buffer is allocated even if free == 0 void ffStrbufEnsureFixedLengthFree(FFstrbuf* strbuf, uint32_t free) { - uint32_t oldFree = ffStrbufGetFree(strbuf); - if (oldFree >= free && !(strbuf->allocated == 0 && strbuf->length > 0)) { - return; - } - - uint32_t newCap = strbuf->allocated + (free - oldFree); + uint32_t newCap; if (strbuf->allocated == 0) { - newCap += strbuf->length + 1; + assert(strbuf->length < UINT32_MAX - 1); // We don't use static strings with length >= UINT32_MAX - 1, so this should never happen + if (__builtin_expect(__builtin_uadd_overflow(strbuf->length + 1, free, &newCap), false)) { + FF_DEBUG("Error: Integer overflow when calculating new capacity. Aborting"); + abort(); + } + char* newbuf = malloc(sizeof(*strbuf->chars) * newCap); if (strbuf->length == 0) { *newbuf = '\0'; @@ -109,6 +122,15 @@ void ffStrbufEnsureFixedLengthFree(FFstrbuf* strbuf, uint32_t free) { } strbuf->chars = newbuf; } else { + uint32_t oldFree = ffStrbufGetFree(strbuf); + if (oldFree >= free) { + return; + } + + if (__builtin_expect(__builtin_uadd_overflow(strbuf->allocated, free - oldFree, &newCap), false)) { + FF_DEBUG("Error: Integer overflow when calculating new capacity. Aborting"); + abort(); + } strbuf->chars = realloc(strbuf->chars, sizeof(*strbuf->chars) * newCap); } @@ -116,7 +138,7 @@ void ffStrbufEnsureFixedLengthFree(FFstrbuf* strbuf, uint32_t free) { } void ffStrbufAppendTransformS(FFstrbuf* strbuf, const char* value, int (*transformFunc)(int)) { - if (value == NULL) { + if (value == nullptr) { return; } @@ -134,7 +156,7 @@ void ffStrbufAppendTransformS(FFstrbuf* strbuf, const char* value, int (*transfo } void ffStrbufAppendVF(FFstrbuf* strbuf, const char* format, va_list arguments) { - assert(format != NULL); + assert(format != nullptr); va_list copy; va_copy(copy, arguments); @@ -155,12 +177,12 @@ void ffStrbufAppendVF(FFstrbuf* strbuf, const char* format, va_list arguments) { } const char* ffStrbufAppendSUntilC(FFstrbuf* strbuf, const char* value, char until) { - if (value == NULL) { - return NULL; + if (value == nullptr) { + return nullptr; } const char* end = strchr(value, until); - if (end == NULL) { + if (end == nullptr) { ffStrbufAppendS(strbuf, value); } else { ffStrbufAppendNS(strbuf, (uint32_t) (end - value), value); @@ -169,7 +191,7 @@ const char* ffStrbufAppendSUntilC(FFstrbuf* strbuf, const char* value, char unti } void ffStrbufSetF(FFstrbuf* strbuf, const char* format, ...) { - assert(format != NULL); + assert(format != nullptr); va_list arguments; va_start(arguments, format); @@ -186,7 +208,7 @@ void ffStrbufSetF(FFstrbuf* strbuf, const char* format, ...) { } void ffStrbufAppendF(FFstrbuf* strbuf, const char* format, ...) { - assert(format != NULL); + assert(format != nullptr); va_list arguments; va_start(arguments, format); @@ -195,7 +217,7 @@ void ffStrbufAppendF(FFstrbuf* strbuf, const char* format, ...) { } void ffStrbufPrependNS(FFstrbuf* strbuf, uint32_t length, const char* value) { - if (value == NULL || length == 0) { + if (value == nullptr || length == 0) { return; } @@ -213,14 +235,14 @@ void ffStrbufPrependC(FFstrbuf* strbuf, char c) { } void ffStrbufSetNS(FFstrbuf* strbuf, uint32_t length, const char* value) { - assert(strbuf != NULL); + assert(strbuf != nullptr); if (length == 0) { ffStrbufClear(strbuf); return; } - assert(value != NULL); + assert(value != nullptr); if (strbuf->allocated <= length) { char* newBuf = malloc(sizeof(char) * (length + 1)); @@ -410,9 +432,7 @@ bool ffStrbufSubstrBefore(FFstrbuf* strbuf, uint32_t index) { if (strbuf->allocated == 0) { // static string - if (index < strbuf->length) { - ffStrbufInitNS(strbuf, index, strbuf->chars); - } + ffStrbufInitNS(strbuf, index, strbuf->chars); return true; } @@ -533,7 +553,7 @@ void ffStrbufAppendSInt(FFstrbuf* strbuf, int64_t value) { unsafe_yyjson_set_sint(&val, value); char* end = yyjson_write_number(&val, start); - assert(end != NULL); + assert(end != nullptr); strbuf->length += (uint32_t) (end - start); } @@ -546,7 +566,7 @@ void ffStrbufAppendUInt(FFstrbuf* strbuf, uint64_t value) { unsafe_yyjson_set_uint(&val, value); char* end = yyjson_write_number(&val, start); - assert(end != NULL); + assert(end != nullptr); strbuf->length += (uint32_t) (end - start); } @@ -713,7 +733,7 @@ bool ffStrbufMatchSeparatedNS(const FFstrbuf* strbuf, uint32_t compLength, const for (const char* p = comp; p < comp + compLength;) { const char* colon = memchr(p, separator, (size_t) (comp + compLength - p)); - if (colon == NULL) { + if (colon == nullptr) { uint32_t remainingLen = (uint32_t) (comp + compLength - p); return strbuf->length == remainingLen && memcmp(strbuf->chars, p, remainingLen) == 0; } @@ -741,7 +761,7 @@ bool ffStrbufMatchSeparatedIgnCaseNS(const FFstrbuf* strbuf, uint32_t compLength for (const char* p = comp; p < comp + compLength;) { const char* colon = memchr(p, separator, (size_t) (comp + compLength - p)); - if (colon == NULL) { + if (colon == nullptr) { uint32_t remainingLen = (uint32_t) (comp + compLength - p); return strbuf->length == remainingLen && strncasecmp(strbuf->chars, p, remainingLen) == 0; } diff --git a/src/common/impl/base64.c b/src/common/impl/base64.c index 98a415ffbd..fa987c303c 100644 --- a/src/common/impl/base64.c +++ b/src/common/impl/base64.c @@ -6,7 +6,13 @@ void ffBase64EncodeRaw(uint32_t size, const char* str, uint32_t* out_size, char* char* out = output; const char* ends = str + (size - size % 3); while (str != ends) { - uint32_t n = __builtin_bswap32(*(uint32_t*) str); + uint32_t n = *(uint32_t*) str; + #if !__BIG_ENDIAN__ + // The 3 input bytes must be laid out big-endian (str[0] in the most + // significant position). On little-endian hosts swap; on big-endian + // hosts the word is already in the right order. + n = __builtin_bswap32(n); + #endif *out++ = chars[(n >> 26) & 63]; *out++ = chars[(n >> 20) & 63]; *out++ = chars[(n >> 14) & 63]; diff --git a/src/common/impl/binary_apple.c b/src/common/impl/binary_apple.c index 84781693a9..c25df7a922 100644 --- a/src/common/impl/binary_apple.c +++ b/src/common/impl/binary_apple.c @@ -20,7 +20,7 @@ typedef struct { static inline void wrapMunmap(FFMemoryMapping* mapping) { assert(mapping); - if (mapping->data == NULL || mapping->data == MAP_FAILED) { + if (mapping->data == nullptr || mapping->data == MAP_FAILED) { return; } munmap((void*) mapping->data, mapping->length); @@ -31,12 +31,12 @@ static inline void wrapMunmap(FFMemoryMapping* mapping) { */ static inline const void* readData(const FFMemoryMapping* mapping, size_t size, off_t offset) { if (offset < 0) { - return NULL; + return nullptr; } size_t start = (size_t) offset; if (start > mapping->length || size > mapping->length - start) { - return NULL; + return nullptr; } return mapping->data + start; @@ -99,7 +99,7 @@ static bool handleMachSection(const FFMemoryMapping* mapping, const char* name, * @param userdata User data for the callback * @param minLength Minimum string length to extract * - * @return NULL on success, error message on failure + * @return nullptr on success, error message on failure */ static const char* dumpMachHeader(const FFMemoryMapping* mapping, off_t offset, bool is_64, bool (*cb)(const char* str, uint32_t len, void* userdata), void* userdata, uint32_t minLength) { uint32_t ncmds; @@ -124,7 +124,7 @@ static const char* dumpMachHeader(const FFMemoryMapping* mapping, off_t offset, } off_t commandOffset = loadCommandsOffset; - const struct load_command* cmd = NULL; + const struct load_command* cmd = nullptr; for (uint32_t i = 0U; i < ncmds; i++, commandOffset += cmd->cmdsize) { cmd = readData(mapping, sizeof(*cmd), commandOffset); if (!cmd) { @@ -153,7 +153,7 @@ static const char* dumpMachHeader(const FFMemoryMapping* mapping, off_t offset, } if (!handleMachSection(mapping, section->sectname, (off_t) section->offset, (size_t) section->size, cb, userdata, minLength)) { - return NULL; + return nullptr; } } } else if (cmd->cmd == LC_SEGMENT) { @@ -174,13 +174,13 @@ static const char* dumpMachHeader(const FFMemoryMapping* mapping, off_t offset, } if (!handleMachSection(mapping, section->sectname, (off_t) section->offset, (size_t) section->size, cb, userdata, minLength)) { - return NULL; + return nullptr; } } } } - return NULL; + return nullptr; } /** @@ -195,7 +195,7 @@ static const char* dumpMachHeader(const FFMemoryMapping* mapping, off_t offset, * @param userdata User data for the callback * @param minLength Minimum string length to extract * - * @return NULL on success, error message on failure + * @return nullptr on success, error message on failure */ static const char* dumpFatHeader(const FFMemoryMapping* mapping, bool (*cb)(const char* str, uint32_t len, void* userdata), void* userdata, uint32_t minLength) { const struct fat_header* headerRaw = readData(mapping, sizeof(struct fat_header), 0); @@ -273,8 +273,8 @@ const char* ffBinaryExtractStrings(const char* machoFile, bool (*cb)(const char* return "Failed to stat file"; } - FF_A_CLEANUP(wrapMunmap) FFMemoryMapping mapping = { - .data = mmap(NULL, (size_t) st.st_size, PROT_READ, MAP_PRIVATE, fd, 0), + [[gnu::cleanup(wrapMunmap)]] FFMemoryMapping mapping = { + .data = mmap(nullptr, (size_t) st.st_size, PROT_READ, MAP_PRIVATE, fd, 0), .length = (size_t) st.st_size, }; if (mapping.data == MAP_FAILED) { diff --git a/src/common/impl/binary_linux.c b/src/common/impl/binary_linux.c index 9a24217326..2d8d50b199 100644 --- a/src/common/impl/binary_linux.c +++ b/src/common/impl/binary_linux.c @@ -56,10 +56,10 @@ const char* ffBinaryExtractStrings(const char* elfFile, bool (*cb)(const char* s FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(libelf, elfData, elf_strptr) FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(libelf, elfData, elf_end) - libelf = NULL; + libelf = nullptr; } - if (elfData.ffelf_end == NULL) { + if (elfData.ffelf_end == nullptr) { return "load libelf failed"; } @@ -69,8 +69,8 @@ const char* ffBinaryExtractStrings(const char* elfFile, bool (*cb)(const char* s return "open() failed"; } - Elf* elf = elfData.ffelf_begin(fd, ELF_C_READ, NULL); - if (elf == NULL) { + Elf* elf = elfData.ffelf_begin(fd, ELF_C_READ, nullptr); + if (elf == nullptr) { return "elf_begin() failed"; } @@ -82,27 +82,27 @@ const char* ffBinaryExtractStrings(const char* elfFile, bool (*cb)(const char* s } // Iterate through all sections, looking for .rodata which contains string literals - Elf_Scn* scn = NULL; - while ((scn = elfData.ffelf_nextscn(elf, scn)) != NULL) { + Elf_Scn* scn = nullptr; + while ((scn = elfData.ffelf_nextscn(elf, scn)) != nullptr) { // Try 64-bit section header first, then 32-bit if that fails Elf64_Shdr* shdr64 = elfData.ffelf64_getshdr(scn); - Elf32_Shdr* shdr32 = NULL; - if (shdr64 == NULL) { + Elf32_Shdr* shdr32 = nullptr; + if (shdr64 == nullptr) { shdr32 = elfData.ffelf32_getshdr(scn); - if (shdr32 == NULL) { + if (shdr32 == nullptr) { continue; } } // Get the section name and check if it's .rodata const char* name = elfData.ffelf_strptr(elf, shstrndx, shdr64 ? shdr64->sh_name : shdr32->sh_name); - if (name == NULL || !ffStrEquals(name, ".rodata")) { + if (name == nullptr || !ffStrEquals(name, ".rodata")) { continue; } // Get the section data - Elf_Data* data = elfData.ffelf_getdata(scn, NULL); - if (data == NULL) { + Elf_Data* data = elfData.ffelf_getdata(scn, nullptr); + if (data == nullptr) { continue; } @@ -131,7 +131,7 @@ const char* ffBinaryExtractStrings(const char* elfFile, bool (*cb)(const char* s } elfData.ffelf_end(elf); - return NULL; + return nullptr; } #else diff --git a/src/common/impl/binary_windows.c b/src/common/impl/binary_windows.c index 918cad5312..005389ff05 100644 --- a/src/common/impl/binary_windows.c +++ b/src/common/impl/binary_windows.c @@ -15,19 +15,19 @@ * Each string found is passed to the callback function for processing. */ const char* ffBinaryExtractStrings(const char* peFile, bool (*cb)(const char* str, uint32_t len, void* userdata), void* userdata, uint32_t minLength) { - FF_AUTO_CLOSE_FD HANDLE hFile = CreateFileA(peFile, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + FF_AUTO_CLOSE_FD HANDLE hFile = CreateFileA(peFile, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if (hFile == INVALID_HANDLE_VALUE) { return "CreateFileA() failed"; } - FF_AUTO_CLOSE_FD HANDLE hSection = NULL; - if (!NT_SUCCESS(NtCreateSection(&hSection, SECTION_MAP_READ, NULL, NULL, PAGE_READONLY, SEC_COMMIT, hFile))) { + FF_AUTO_CLOSE_FD HANDLE hSection = nullptr; + if (!NT_SUCCESS(NtCreateSection(&hSection, SECTION_MAP_READ, nullptr, nullptr, PAGE_READONLY, SEC_COMMIT, hFile))) { return "NtCreateSection() failed"; } - PVOID base = NULL; + PVOID base = nullptr; SIZE_T viewSize = 0; - if (!NT_SUCCESS(NtMapViewOfSection(hSection, NtCurrentProcess(), &base, 0, 0, NULL, &viewSize, ViewUnmap, 0, PAGE_READONLY))) { + if (!NT_SUCCESS(NtMapViewOfSection(hSection, NtCurrentProcess(), &base, 0, 0, nullptr, &viewSize, ViewUnmap, 0, PAGE_READONLY))) { return "NtMapViewOfSection() failed"; } @@ -67,5 +67,5 @@ const char* ffBinaryExtractStrings(const char* peFile, bool (*cb)(const char* st } NtUnmapViewOfSection(NtCurrentProcess(), base); - return NULL; + return nullptr; } diff --git a/src/common/impl/commandoption.c b/src/common/impl/commandoption.c index 2f548dfada..f0b5f06672 100644 --- a/src/common/impl/commandoption.c +++ b/src/common/impl/commandoption.c @@ -15,12 +15,12 @@ bool ffParseModuleOptions(const char* key, const char* value) { return false; } if (value && !*value) { - value = NULL; + value = nullptr; } for (FFModuleBaseInfo** modules = ffModuleInfos[toupper(key[2]) - 'A']; *modules; ++modules) { FFModuleBaseInfo* baseInfo = *modules; const char* subKey = ffOptionTestPrefix(key, baseInfo->name); - if (subKey != NULL) { + if (subKey != nullptr) { if (subKey[0] == '\0' || subKey[0] == '-') // Key is exactly the module name or has a leading '-' { fprintf(stderr, "Error: unknown module key %s\n", key); @@ -64,7 +64,7 @@ bool ffParseModuleOptions(const char* key, const char* value) { } void ffPrepareCommandOption(FFdata* data) { - char* moduleType = NULL; + char* moduleType = nullptr; size_t moduleLen = 0; while (ffStrbufGetdelim(&moduleType, &moduleLen, ':', &data->structure)) { #define FF_IF_MODULE_MATCH(moduleNameConstant) if (moduleLen == strlen(moduleNameConstant) && ffStrEqualsIgnCase(moduleType, moduleNameConstant) && !ffStrbufSeparatedContainIgnCaseS(&data->structureDisabled, moduleNameConstant, ':')) @@ -82,7 +82,7 @@ void ffPrepareCommandOption(FFdata* data) { case 'D': case 'd': FF_IF_MODULE_MATCH(FF_DISKIO_MODULE_NAME) { - FF_A_CLEANUP(ffDestroyDiskIOOptions) FFDiskIOOptions options; + [[gnu::cleanup(ffDestroyDiskIOOptions)]] FFDiskIOOptions options; ffInitDiskIOOptions(&options); ffPrepareDiskIO(&options); } @@ -93,7 +93,7 @@ void ffPrepareCommandOption(FFdata* data) { case 'N': case 'n': FF_IF_MODULE_MATCH(FF_NETIO_MODULE_NAME) { - FF_A_CLEANUP(ffDestroyNetIOOptions) FFNetIOOptions options; + [[gnu::cleanup(ffDestroyNetIOOptions)]] FFNetIOOptions options; ffInitNetIOOptions(&options); ffPrepareNetIO(&options); } @@ -104,7 +104,7 @@ void ffPrepareCommandOption(FFdata* data) { case 'P': case 'p': FF_IF_MODULE_MATCH(FF_PUBLICIP_MODULE_NAME) { - FF_A_CLEANUP(ffDestroyPublicIpOptions) FFPublicIPOptions options; + [[gnu::cleanup(ffDestroyPublicIpOptions)]] FFPublicIPOptions options; ffInitPublicIpOptions(&options); ffPreparePublicIp(&options); } @@ -115,7 +115,7 @@ void ffPrepareCommandOption(FFdata* data) { case 'W': case 'w': FF_IF_MODULE_MATCH(FF_WEATHER_MODULE_NAME) { - FF_A_CLEANUP(ffDestroyWeatherOptions) FFWeatherOptions options; + [[gnu::cleanup(ffDestroyWeatherOptions)]] FFWeatherOptions options; ffInitWeatherOptions(&options); ffPrepareWeather(&options); } @@ -175,9 +175,9 @@ static bool parseStructureCommand( for (FFModuleBaseInfo** modules = ffModuleInfos[toupper(line[0]) - 'A']; *modules; ++modules) { FFModuleBaseInfo* baseInfo = *modules; if (ffStrEqualsIgnCase(line, baseInfo->name)) { - uint8_t optionBuf[FF_OPTION_MAX_SIZE]; + alignas(uint64_t) uint8_t optionBuf[FF_OPTION_MAX_SIZE]; baseInfo->initOptions(optionBuf); - if (data->resultDoc != NULL) { + if (data->resultDoc != nullptr) { fn(data, baseInfo, optionBuf); } else { baseInfo->printModule(optionBuf); @@ -194,7 +194,7 @@ static bool parseStructureCommand( yyjson_mut_obj_add_str(doc, module, "type", line); yyjson_mut_obj_add_str(doc, module, "error", "Unknown module type"); } else { - ffPrintError(line, 0, NULL, FF_PRINT_TYPE_NO_CUSTOM_KEY, ""); + ffPrintError(line, 0, nullptr, FF_PRINT_TYPE_NO_CUSTOM_KEY, ""); } return false; } @@ -203,7 +203,7 @@ void ffPrintCommandOption(FFdata* data) { // Parse the structure and call the modules int32_t thres = instance.config.display.stat; - char* moduleType = NULL; + char* moduleType = nullptr; size_t moduleLen = 0; while (ffStrbufGetdelim(&moduleType, &moduleLen, ':', &data->structure)) { if (ffStrbufSeparatedContainIgnCaseS(&data->structureDisabled, moduleType, ':')) { @@ -249,7 +249,7 @@ void ffMigrateCommandOptionToJsonc(FFdata* data) { ffStrbufAppendS(&data->structure, FASTFETCH_DATATEXT_STRUCTURE); // Cannot use `ffStrbufSetStatic` here because we will modify the string } - char* moduleType = NULL; + char* moduleType = nullptr; size_t moduleLen = 0; while (ffStrbufGetdelim(&moduleType, &moduleLen, ':', &data->structure)) { if (ffStrbufSeparatedContainIgnCaseS(&data->structureDisabled, moduleType, ':')) { diff --git a/src/common/impl/dbus.c b/src/common/impl/dbus.c index 473af2d200..ca20efb180 100644 --- a/src/common/impl/dbus.c +++ b/src/common/impl/dbus.c @@ -19,7 +19,7 @@ static bool loadLibSymbols(FFDBusLibrary* lib) { FF_LIBRARY_LOAD_SYMBOL_PTR(dbus, lib, dbus_message_unref, false) FF_LIBRARY_LOAD_SYMBOL_PTR(dbus, lib, dbus_connection_send_with_reply_and_block, false) FF_LIBRARY_LOAD_SYMBOL_PTR(dbus, lib, dbus_connection_unref, false) - dbus = NULL; // don't auto dlclose + dbus = nullptr; // don't auto dlclose return true; } @@ -33,27 +33,27 @@ static const FFDBusLibrary* loadLib(void) { loadSuccess = loadLibSymbols(&lib); } - return loadSuccess ? &lib : NULL; + return loadSuccess ? &lib : nullptr; } const char* ffDBusLoadData(DBusBusType busType, FFDBusData* data) { data->lib = loadLib(); - if (data->lib == NULL) { + if (data->lib == nullptr) { return "Failed to load DBus library"; } - data->connection = data->lib->ffdbus_bus_get(busType, NULL); - if (data->connection == NULL) { + data->connection = data->lib->ffdbus_bus_get(busType, nullptr); + if (data->connection == nullptr) { return "Failed to connect to DBus"; } - return NULL; + return nullptr; } void ffDBusDestroyData(FFDBusData* data) { - if (data->connection != NULL) { + if (data->connection != nullptr) { data->lib->ffdbus_connection_unref(data->connection); - data->connection = NULL; + data->connection = nullptr; } } @@ -61,7 +61,7 @@ bool ffDBusGetString(FFDBusData* dbus, DBusMessageIter* iter, FFstrbuf* result) int argType = dbus->lib->ffdbus_message_iter_get_arg_type(iter); if (argType == DBUS_TYPE_STRING || argType == DBUS_TYPE_OBJECT_PATH) { - const char* value = NULL; + const char* value = nullptr; dbus->lib->ffdbus_message_iter_get_basic(iter, &value); if (!ffStrSet(value)) { @@ -254,8 +254,8 @@ bool ffDBusGetInt(FFDBusData* dbus, DBusMessageIter* iter, int64_t* result) { DBusMessage* ffDBusGetMethodReply(FFDBusData* dbus, const char* busName, const char* objectPath, const char* interface, const char* method, const char* arg1, const char* arg2) { DBusMessage* message = dbus->lib->ffdbus_message_new_method_call(busName, objectPath, interface, method); - if (message == NULL) { - return NULL; + if (message == nullptr) { + return nullptr; } if (arg1) { @@ -266,7 +266,7 @@ DBusMessage* ffDBusGetMethodReply(FFDBusData* dbus, const char* busName, const c } } - DBusMessage* reply = dbus->lib->ffdbus_connection_send_with_reply_and_block(dbus->connection, message, instance.config.general.processingTimeout, NULL); + DBusMessage* reply = dbus->lib->ffdbus_connection_send_with_reply_and_block(dbus->connection, message, instance.config.general.processingTimeout, nullptr); dbus->lib->ffdbus_message_unref(message); @@ -275,8 +275,8 @@ DBusMessage* ffDBusGetMethodReply(FFDBusData* dbus, const char* busName, const c DBusMessage* ffDBusGetProperty(FFDBusData* dbus, const char* busName, const char* objectPath, const char* interface, const char* property) { DBusMessage* message = dbus->lib->ffdbus_message_new_method_call(busName, objectPath, "org.freedesktop.DBus.Properties", "Get"); - if (message == NULL) { - return NULL; + if (message == nullptr) { + return nullptr; } dbus->lib->ffdbus_message_append_args(message, @@ -286,7 +286,7 @@ DBusMessage* ffDBusGetProperty(FFDBusData* dbus, const char* busName, const char &property, DBUS_TYPE_INVALID); - DBusMessage* reply = dbus->lib->ffdbus_connection_send_with_reply_and_block(dbus->connection, message, instance.config.general.processingTimeout, NULL); + DBusMessage* reply = dbus->lib->ffdbus_connection_send_with_reply_and_block(dbus->connection, message, instance.config.general.processingTimeout, nullptr); dbus->lib->ffdbus_message_unref(message); @@ -295,7 +295,7 @@ DBusMessage* ffDBusGetProperty(FFDBusData* dbus, const char* busName, const char bool ffDBusGetPropertyString(FFDBusData* dbus, const char* busName, const char* objectPath, const char* interface, const char* property, FFstrbuf* result) { DBusMessage* reply = ffDBusGetProperty(dbus, busName, objectPath, interface, property); - if (reply == NULL) { + if (reply == nullptr) { return false; } @@ -314,7 +314,7 @@ bool ffDBusGetPropertyString(FFDBusData* dbus, const char* busName, const char* bool ffDBusGetPropertyUint(FFDBusData* dbus, const char* busName, const char* objectPath, const char* interface, const char* property, uint64_t* result) { DBusMessage* reply = ffDBusGetProperty(dbus, busName, objectPath, interface, property); - if (reply == NULL) { + if (reply == nullptr) { return false; } diff --git a/src/common/impl/debug_windows.c b/src/common/impl/debug_windows.c index a3fb7f3dc0..6247ec4376 100644 --- a/src/common/impl/debug_windows.c +++ b/src/common/impl/debug_windows.c @@ -10,12 +10,12 @@ const char* ffDebugWin32Error(DWORD errorCode) { wchar_t bufferW[256]; ULONG len = FormatMessageW( FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, + nullptr, (DWORD) errorCode, 0, bufferW, ARRAY_SIZE(bufferW), - NULL); + nullptr); if (len == 0) { snprintf(buffer, sizeof(buffer), "Unknown error code (%lu)", errorCode); diff --git a/src/common/impl/font.c b/src/common/impl/font.c index 93feff15c7..681c249069 100644 --- a/src/common/impl/font.c +++ b/src/common/impl/font.c @@ -16,7 +16,7 @@ void ffFontInit(FFfont* font) { } static void strbufAppendNSExcludingC(FFstrbuf* strbuf, uint32_t length, const char* value, char exclude) { - if (value == NULL || length == 0) { + if (value == nullptr || length == 0) { return; } @@ -151,7 +151,7 @@ static void fontPangoParseWord(const char** data, FFfont* font, FFstrbuf* altern ffStrStartsWithIgnCase(wordStart, "Black") || ffStrStartsWithIgnCase(wordStart, "Condensed") || ffStrStartsWithIgnCase(wordStart, "Expanded")) { - if (alternativeBuffer == NULL) { + if (alternativeBuffer == nullptr) { alternativeBuffer = FF_LIST_ADD(FFstrbuf, font->styles); ffStrbufInit(alternativeBuffer); } @@ -169,7 +169,7 @@ static void fontPangoParseWord(const char** data, FFfont* font, FFstrbuf* altern return; } - if (alternativeBuffer != NULL) { + if (alternativeBuffer != nullptr) { strbufAppendNSExcludingC(alternativeBuffer, wordLength, wordStart, '-'); return; } @@ -184,7 +184,7 @@ void ffFontInitPango(FFfont* font, const char* data) { ffFontInit(font); while (*data != '\0' && *data != '`' && *data != '\\') { - fontPangoParseWord(&data, font, NULL); + fontPangoParseWord(&data, font, nullptr); } fontInitPretty(font); @@ -329,8 +329,8 @@ void ffFontInitXft(FFfont* font, const char* xft) { } // Try parse trailing "-" as size, otherwise entire head is name - const char* dashPos = NULL; - const char* sizeStart = NULL; + const char* dashPos = nullptr; + const char* sizeStart = nullptr; for (const char* q = headEnd; q > headStart;) { --q; @@ -488,7 +488,7 @@ void ffFontInitMoveValues(FFfont* font, FFstrbuf* name, FFstrbuf* size, FFstrbuf void ffFontInitWithSpace(FFfont* font, const char* rawName) { const char* pspace = strrchr(rawName, ' '); - if (pspace == NULL) { + if (pspace == nullptr) { ffFontInitCopy(font, rawName); return; } diff --git a/src/common/impl/format.c b/src/common/impl/format.c index db414bc5aa..978011bd1e 100644 --- a/src/common/impl/format.c +++ b/src/common/impl/format.c @@ -78,7 +78,7 @@ static uint32_t getArgumentIndex(const char* placeholderValue, uint32_t numArgs, } if (firstChar >= '0' && firstChar <= '9') { - char* pEnd = NULL; + char* pEnd = nullptr; uint32_t result = (uint32_t) strtoul(placeholderValue, &pEnd, 10); if (result > numArgs) { return UINT32_MAX; @@ -109,10 +109,10 @@ static inline void appendInvalidPlaceholder(FFstrbuf* buffer, const char* start, } static inline bool formatArgSet(const FFformatarg* arg) { - return arg->value != NULL && ((arg->type == FF_ARG_TYPE_DOUBLE && *(double*) arg->value > 0.0) || (arg->type == FF_ARG_TYPE_FLOAT && *(float*) arg->value > 0.0) || (arg->type == FF_ARG_TYPE_INT && *(int32_t*) arg->value > 0) || (arg->type == FF_ARG_TYPE_STRBUF && ((FFstrbuf*) arg->value)->length > 0) || (arg->type == FF_ARG_TYPE_STRING && ffStrSet((char*) arg->value)) || (arg->type == FF_ARG_TYPE_UINT8 && *(uint8_t*) arg->value > 0) || (arg->type == FF_ARG_TYPE_UINT16 && *(uint16_t*) arg->value > 0) || (arg->type == FF_ARG_TYPE_UINT && *(uint32_t*) arg->value > 0) || (arg->type == FF_ARG_TYPE_UINT64 && *(uint64_t*) arg->value > 0) || (arg->type == FF_ARG_TYPE_BOOL && *(bool*) arg->value) || (arg->type == FF_ARG_TYPE_LIST && ((FFlist*) arg->value)->length > 0)); + return arg->value != nullptr && ((arg->type == FF_ARG_TYPE_DOUBLE && *(double*) arg->value > 0.0) || (arg->type == FF_ARG_TYPE_FLOAT && *(float*) arg->value > 0.0) || (arg->type == FF_ARG_TYPE_INT && *(int32_t*) arg->value > 0) || (arg->type == FF_ARG_TYPE_STRBUF && ((FFstrbuf*) arg->value)->length > 0) || (arg->type == FF_ARG_TYPE_STRING && ffStrSet((char*) arg->value)) || (arg->type == FF_ARG_TYPE_UINT8 && *(uint8_t*) arg->value > 0) || (arg->type == FF_ARG_TYPE_UINT16 && *(uint16_t*) arg->value > 0) || (arg->type == FF_ARG_TYPE_UINT && *(uint32_t*) arg->value > 0) || (arg->type == FF_ARG_TYPE_UINT64 && *(uint64_t*) arg->value > 0) || (arg->type == FF_ARG_TYPE_BOOL && *(bool*) arg->value) || (arg->type == FF_ARG_TYPE_LIST && ((FFlist*) arg->value)->length > 0)); } -FF_A_UNUSED static inline void normalizeArgName(FFstrbuf* dst, const char* src) { +[[maybe_unused]] static inline void normalizeArgName(FFstrbuf* dst, const char* src) { ffStrbufClear(dst); bool flag = false; for (const char* p = src; *p; ++p) { @@ -131,7 +131,7 @@ FF_A_UNUSED static inline void normalizeArgName(FFstrbuf* dst, const char* src) #include "common/lua.h" static void appendLuaError(FFstrbuf* buffer, const char* prefix, lua_State* L) { - const char* err = lua_tolstring(L, -1, NULL); + const char* err = lua_tolstring(L, -1, nullptr); if (err) { const char* tmp = strchr(err, ':'); if (tmp) { @@ -228,12 +228,12 @@ static bool parseLuaString(FFstrbuf* buffer, const char* script, uint32_t script ffStrbufAppendS(buffer, "Lua result error: no result"); } else { // Convert first result to string - const char* res = lua_tolstring(L, 1, NULL); + const char* res = lua_tolstring(L, 1, nullptr); if (res) { ffStrbufAppendS(buffer, res); } else { - luaL_tolstring(L, 1, NULL); - const char* sval = lua_tolstring(L, -1, NULL); + luaL_tolstring(L, 1, nullptr); + const char* sval = lua_tolstring(L, -1, nullptr); if (sval) { ffStrbufAppendS(buffer, sval); } @@ -273,10 +273,10 @@ struct FFQuickJSData { static const char* loadQuickJSState(void) { if (qjsData.inited) { - if (qjsData.ctx == NULL) { + if (qjsData.ctx == nullptr) { return "QuickJS is not available"; } - return NULL; + return nullptr; } qjsData.inited = true; @@ -301,20 +301,20 @@ static const char* loadQuickJSState(void) { FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(libqjs, qjsData, JS_FreeValue) qjsData.rt = qjsData.ffJS_NewRuntime(); - if (qjsData.rt == NULL) { + if (qjsData.rt == nullptr) { return "JS_NewRuntime() failed"; } qjsData.ctx = qjsData.ffJS_NewContext(qjsData.rt); - if (qjsData.ctx == NULL) { + if (qjsData.ctx == nullptr) { qjsData.ffJS_FreeRuntime(qjsData.rt); - qjsData.rt = NULL; + qjsData.rt = nullptr; return "JS_NewContext() failed"; } - libqjs = NULL; // don't close quickjs + libqjs = nullptr; // don't close quickjs - return NULL; + return nullptr; } static bool parseQuickJSString(FFstrbuf* buffer, const char* script, uint32_t scriptLen, uint32_t numArgs, const FFformatarg* arguments) { @@ -401,7 +401,7 @@ static bool parseQuickJSString(FFstrbuf* buffer, const char* script, uint32_t sc bool ret = false; if (JS_IsException(result)) { JSValue exc = qjsData.ffJS_GetException(ctx); - const char* message = qjsData.ffJS_ToCStringLen2(ctx, NULL, exc, false); + const char* message = qjsData.ffJS_ToCStringLen2(ctx, nullptr, exc, false); qjsData.ffJS_FreeValue(ctx, exc); ffStrbufAppendF(buffer, "Qjs runtime error: %s", message ?: "unknown"); if (message) { @@ -587,7 +587,7 @@ static bool parseFormatString(FFstrbuf* buffer, const FFstrbuf* formatstr, uint3 // test for constant or env var, if so evaluate it if (firstChar == '$') { - char* pend = NULL; + char* pend = nullptr; int32_t indexSigned = (int32_t) strtol(placeholderValue.chars + 1, &pend, 10); if (pend == placeholderValue.chars + 1) { // treat placeholder as an environment variable @@ -620,7 +620,7 @@ static bool parseFormatString(FFstrbuf* buffer, const FFstrbuf* formatstr, uint3 cSep = *pSep; *pSep = '\0'; } else { - pSep = NULL; + pSep = nullptr; } uint32_t index = getArgumentIndex(placeholderValue.chars, numArgs, arguments); @@ -646,7 +646,7 @@ static bool parseFormatString(FFstrbuf* buffer, const FFstrbuf* formatstr, uint3 FF_STRBUF_AUTO_DESTROY trailingEscape = ffStrbufCreate(); skipAnsiEscape(&tempString, buffer, &trailingEscape); - char* pEnd = NULL; + char* pEnd = nullptr; int32_t start = (int32_t) strtol(pSep + 1, &pEnd, 10); if (start < 0) { start = (int32_t) tempString.length + start; @@ -680,7 +680,7 @@ static bool parseFormatString(FFstrbuf* buffer, const FFstrbuf* formatstr, uint3 continue; } } else { - char* pEnd = NULL; + char* pEnd = nullptr; int32_t truncLength = (int32_t) strtol(pSep + 1, &pEnd, 10); if (*pEnd != '\0') { *pSep = cSep; diff --git a/src/common/impl/genconfig.c b/src/common/impl/genconfig.c new file mode 100644 index 0000000000..f874790774 --- /dev/null +++ b/src/common/impl/genconfig.c @@ -0,0 +1,1092 @@ +#include "common/genconfig.h" + +#include "fastfetch.h" + +#include "common/io.h" +#include "common/strutil.h" +#include "detection/terminalsize/terminalsize.h" +#include "fastfetch_datatext.h" +#include "modules/modules.h" + +#include +#include +#include + +#ifndef _WIN32 + #include + #include + #include +#else + #include +#endif + +// Layout (rows): +// 0: title +// 1: blank +// 2: logo type row +// 3: output mode row +// 4: blank +// 5: modules title row +// 6: blank +// 7..7+listRows-1: module grid +// 7+listRows: description row +// 8+listRows: help line 1 +// 9+listRows: help line 2 +#define FF_GEN_CONFIG_LIST_TOP 7 +#define FF_GEN_CONFIG_BOTTOM_CHROME 3 + +typedef enum : uint8_t { + FF_GEN_CONFIG_ITEM_STATUS_UNSELECTED = false, + FF_GEN_CONFIG_ITEM_STATUS_SELECTED = true, + FF_GEN_CONFIG_ITEM_STATUS_SPECIAL = 2, +} FFGenConfigItemStatus; + +typedef struct FFGenConfigItem { + FFModuleBaseInfo* baseInfo; + FFGenConfigItemStatus status; +} FFGenConfigItem; + +typedef struct FFGenConfigLayout { + uint16_t listLeft; + uint16_t listRows; + uint32_t colWidth; + uint32_t columns; + uint32_t itemsPerColumn; +} FFGenConfigLayout; + +typedef struct FFGenConfigUI { + FFlist items; // FFGenConfigItem + int32_t cursor; + uint32_t viewOffset; + FFLogoType logoType; + bool fullConfig; + bool confirmingOverwrite; + uint16_t rows; + uint16_t cols; + FFGenConfigLayout layout; +} FFGenConfigUI; + +typedef enum : uint8_t { + FF_GEN_KEY_UP, + FF_GEN_KEY_DOWN, + FF_GEN_KEY_LEFT, + FF_GEN_KEY_RIGHT, + FF_GEN_KEY_PAGE_UP, + FF_GEN_KEY_PAGE_DOWN, + FF_GEN_KEY_HOME, + FF_GEN_KEY_END, + FF_GEN_KEY_ENTER, + FF_GEN_KEY_ESCAPE, + FF_GEN_KEY_CHAR, + FF_GEN_KEY_UNKNOWN, +} FFGenConfigKey; + +#ifndef _WIN32 +static struct termios gOriginalTermios; +static bool gRawModeActive = false; + +static void restoreRawMode(void) { + if (gRawModeActive) { + tcsetattr(STDIN_FILENO, TCSAFLUSH, &gOriginalTermios); + gRawModeActive = false; + } +} + +static void enterRawMode(void) { + if (gRawModeActive) { + return; + } + if (tcgetattr(STDIN_FILENO, &gOriginalTermios) != 0) { + return; + } + struct termios raw = gOriginalTermios; + raw.c_lflag &= (tcflag_t) ~(ICANON | ECHO | ISIG | IEXTEN); + raw.c_iflag &= (tcflag_t) ~(IXON | ICRNL | BRKINT | INPCK | ISTRIP); + raw.c_cflag |= CS8; + raw.c_oflag &= (tcflag_t) ~OPOST; + raw.c_cc[VMIN] = 0; + raw.c_cc[VTIME] = 1; + if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw) != 0) { + return; + } + gRawModeActive = true; +} +#else +static DWORD gOriginalInputMode; +static DWORD gOriginalOutputMode; +static bool gRawModeActive = false; + +static void restoreRawMode(void) { + if (gRawModeActive) { + SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), gOriginalInputMode); + SetConsoleMode(GetStdHandle(STD_OUTPUT_HANDLE), gOriginalOutputMode); + gRawModeActive = false; + } +} + +static void enterRawMode(void) { + if (gRawModeActive) { + return; + } + HANDLE hInput = GetStdHandle(STD_INPUT_HANDLE); + HANDLE hOutput = GetStdHandle(STD_OUTPUT_HANDLE); + + if (GetConsoleMode(hInput, &gOriginalInputMode)) { + DWORD newMode = gOriginalInputMode; + newMode &= ~(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT | ENABLE_PROCESSED_INPUT); + newMode |= ENABLE_VIRTUAL_TERMINAL_INPUT; + SetConsoleMode(hInput, newMode); + } + + if (GetConsoleMode(hOutput, &gOriginalOutputMode)) { + DWORD newMode = gOriginalOutputMode; + newMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING | DISABLE_NEWLINE_AUTO_RETURN; + SetConsoleMode(hOutput, newMode); + } + + FlushConsoleInputBuffer(hInput); + gRawModeActive = true; +} +#endif + +static void getTerminalSize(uint16_t* rows, uint16_t* cols) { + FFTerminalSizeResult size; + if (ffDetectTerminalSize(&size) && size.rows > 0 && size.columns > 0) { + *rows = size.rows; + *cols = size.columns; + } else { + *rows = 24; + *cols = 80; + } +} + +static int compareModuleInfo(const void* a, const void* b) { + const FFModuleBaseInfo* const* ma = (const FFModuleBaseInfo* const*) a; + const FFModuleBaseInfo* const* mb = (const FFModuleBaseInfo* const*) b; + if ((*ma)->defaultOrder != (*mb)->defaultOrder) { + return (int) (*ma)->defaultOrder - (int) (*mb)->defaultOrder; + } + return strcmp((*ma)->name, (*mb)->name); +} + +static void collectModuleInfos(FFlist* modules) { + ffListInitA(modules, sizeof(FFModuleBaseInfo*), 64); + for (uint32_t i = 0; i <= 'Z' - 'A'; ++i) { + for (FFModuleBaseInfo** it = ffModuleInfos[i]; *it; ++it) { + if ((*it)->defaultOrder == 0) { + continue; + } + *(FFModuleBaseInfo**) ffListAdd(modules, sizeof(FFModuleBaseInfo*)) = *it; + } + } + ffListSort(modules, sizeof(FFModuleBaseInfo*), compareModuleInfo); +} + +static bool isInDefaultStructure(const char* moduleName) { + char* moduleType = nullptr; + size_t moduleLen = 0; + FF_STRBUF_AUTO_DESTROY structure = ffStrbufCreateS(FASTFETCH_DATATEXT_STRUCTURE); + while (ffStrbufGetdelim(&moduleType, &moduleLen, ':', &structure)) { + if (moduleLen == strlen(moduleName) && ffStrEqualsIgnCase(moduleType, moduleName)) { + return true; + } + } + return false; +} + +static void initItems(FFlist* items, const FFlist* modules) { + ffListInitA(items, sizeof(FFGenConfigItem), modules->length + 8); + FF_LIST_FOR_EACH (FFModuleBaseInfo*, info, *modules) { + FFGenConfigItem* item = FF_LIST_ADD(FFGenConfigItem, *items); + item->baseInfo = *info; + if (ffStrEqualsIgnCase((*info)->name, FF_BREAK_MODULE_NAME) || + ffStrEqualsIgnCase((*info)->name, FF_SEPARATOR_MODULE_NAME)) { + item->status = FF_GEN_CONFIG_ITEM_STATUS_SPECIAL; + } else { + item->status = isInDefaultStructure((*info)->name) + ? FF_GEN_CONFIG_ITEM_STATUS_SELECTED + : FF_GEN_CONFIG_ITEM_STATUS_UNSELECTED; + } + } +} + +static void moveItemDown(FFGenConfigUI* ui, uint32_t idx) { + if (idx + 1 >= ui->items.length) { + return; + } + FFGenConfigItem* items = (FFGenConfigItem*) ui->items.data; + FFGenConfigItem tmp = items[idx]; + items[idx] = items[idx + 1]; + items[idx + 1] = tmp; + ui->cursor = (int32_t) (idx + 1); +} + +static void moveItemUp(FFGenConfigUI* ui, uint32_t idx) { + if (idx == 0) { + return; + } + FFGenConfigItem* items = (FFGenConfigItem*) ui->items.data; + FFGenConfigItem tmp = items[idx]; + items[idx] = items[idx - 1]; + items[idx - 1] = tmp; + ui->cursor = (int32_t) (idx - 1); +} + +static void removeAllBreaksSeparators(FFGenConfigUI* ui) { + for (uint32_t i = ui->items.length; i-- > 0;) { + FFGenConfigItem* item = FF_LIST_GET(FFGenConfigItem, ui->items, i); + if (item->status == FF_GEN_CONFIG_ITEM_STATUS_SPECIAL) { + FF_LIST_REMOVE_AT(FFGenConfigItem, ui->items, i); + } + } + if ((uint32_t) ui->cursor >= ui->items.length && ui->items.length > 0) { + ui->cursor = (int32_t) ui->items.length - 1; + } +} + +static void computeLayout(FFGenConfigUI* ui) { + FFGenConfigLayout* layout = &ui->layout; + if (ui->rows < 10) { + ui->rows = 10; + } + int32_t listRows = (int32_t) ui->rows - FF_GEN_CONFIG_LIST_TOP - FF_GEN_CONFIG_BOTTOM_CHROME; + layout->listRows = listRows < 0 ? 0 : (uint16_t) listRows; + layout->listLeft = 2; + + uint32_t maxContentWidth = 0; + FF_LIST_FOR_EACH (FFGenConfigItem, item, ui->items) { + uint32_t w = (uint32_t) strlen(item->baseInfo->name) + 4; // "[x] " / "[─] " prefix + if (w > maxContentWidth) { + maxContentWidth = w; + } + } + layout->colWidth = maxContentWidth + 2; + if (layout->colWidth < 1) { + layout->colWidth = 1; + } + + uint32_t gridWidth = ui->cols > 4 ? (uint32_t) ui->cols - 4 : 1; + uint32_t maxColumns = gridWidth / layout->colWidth; + if (maxColumns < 1) { + maxColumns = 1; + } + + uint32_t length = ui->items.length; + if (length == 0 || layout->listRows == 0) { + layout->columns = 1; + layout->itemsPerColumn = length > 0 ? length : 1; + return; + } + uint32_t neededColumns = (length + layout->listRows - 1) / layout->listRows; + if (neededColumns < 1) { + neededColumns = 1; + } + layout->columns = neededColumns < maxColumns ? neededColumns : maxColumns; + layout->itemsPerColumn = (length + layout->columns - 1) / layout->columns; +} + +static void recomputeView(FFGenConfigUI* ui) { + const FFGenConfigLayout* layout = &ui->layout; + uint32_t length = ui->items.length; + if (length == 0) { + ui->cursor = 0; + ui->viewOffset = 0; + return; + } + if (ui->cursor < 0) { + ui->cursor = 0; + } + if ((uint32_t) ui->cursor >= length) { + ui->cursor = (int32_t) length - 1; + } + + uint32_t rowsPerColumn = layout->itemsPerColumn; + if (rowsPerColumn <= layout->listRows) { + ui->viewOffset = 0; + return; + } + + uint32_t cursorRow = (uint32_t) ui->cursor % rowsPerColumn; + uint32_t pageTop = ui->viewOffset; + if (cursorRow < pageTop) { + pageTop = cursorRow; + } else if (cursorRow >= pageTop + layout->listRows) { + pageTop = cursorRow - layout->listRows + 1; + } + uint32_t maxTop = rowsPerColumn - layout->listRows; + if (pageTop > maxTop) { + pageTop = maxTop; + } + ui->viewOffset = pageTop; +} + +static void toggleItem(FFGenConfigUI* ui, uint32_t idx) { + FFGenConfigItem* item = FF_LIST_GET(FFGenConfigItem, ui->items, idx); + if (item->status == FF_GEN_CONFIG_ITEM_STATUS_SPECIAL) { + return; + } + item->status = !item->status; +} + +static void selectAllModules(FFGenConfigUI* ui) { + FF_LIST_FOR_EACH (FFGenConfigItem, item, ui->items) { + if (item->status != FF_GEN_CONFIG_ITEM_STATUS_SPECIAL) { + item->status = FF_GEN_CONFIG_ITEM_STATUS_SELECTED; + } + } +} + +static void invertAllModules(FFGenConfigUI* ui) { + FF_LIST_FOR_EACH (FFGenConfigItem, item, ui->items) { + if (item->status != FF_GEN_CONFIG_ITEM_STATUS_SPECIAL) { + item->status = !item->status; + } + } +} + +static void addBreakBelow(FFGenConfigUI* ui, uint32_t idx) { + FFGenConfigItem br = { .baseInfo = &ffBreakModuleInfo, .status = FF_GEN_CONFIG_ITEM_STATUS_SPECIAL }; + FF_LIST_INSERT_AT(FFGenConfigItem, ui->items, idx + 1, &br); +} + +static void addSeparatorBelow(FFGenConfigUI* ui, uint32_t idx) { + FFGenConfigItem sep = { .baseInfo = &ffSeparatorModuleInfo, .status = FF_GEN_CONFIG_ITEM_STATUS_SPECIAL }; + FF_LIST_INSERT_AT(FFGenConfigItem, ui->items, idx + 1, &sep); +} + +static void cycleLogoType(FFGenConfigUI* ui, int delta) { + switch (ui->logoType) { + case FF_LOGO_TYPE_AUTO: + ui->logoType = delta > 0 ? FF_LOGO_TYPE_SMALL : FF_LOGO_TYPE_NONE; + break; + case FF_LOGO_TYPE_SMALL: + ui->logoType = delta > 0 ? FF_LOGO_TYPE_NONE : FF_LOGO_TYPE_AUTO; + break; + default: + ui->logoType = delta > 0 ? FF_LOGO_TYPE_AUTO : FF_LOGO_TYPE_SMALL; + break; + } +} + +static uint32_t countSelectedModules(const FFlist* items) { + uint32_t count = 0; + FF_LIST_FOR_EACH (FFGenConfigItem, item, *items) { + if (item->status == FF_GEN_CONFIG_ITEM_STATUS_SELECTED) { + ++count; + } + } + return count; +} + +static uint32_t countModules(const FFlist* items) { + uint32_t count = 0; + FF_LIST_FOR_EACH (FFGenConfigItem, item, *items) { + if (item->status != FF_GEN_CONFIG_ITEM_STATUS_SPECIAL) { + ++count; + } + } + return count; +} + +// ---- Row builder ----------------------------------------------------------- + +typedef struct FFRow { + FFstrbuf buf; + uint32_t visualCol; + uint16_t cols; +} FFRow; + +static void rowInit(FFRow* row, uint16_t cols) { + ffStrbufInitA(&row->buf, (uint32_t) cols + 16); + row->visualCol = 0; + row->cols = cols; +} + +static void rowAppendRaw(FFRow* row, const char* s) { + ffStrbufAppendS(&row->buf, s); +} + +static void rowAppendVisual(FFRow* row, const char* s) { + uint32_t len = (uint32_t) strlen(s); + ffStrbufAppendNS(&row->buf, len, s); + row->visualCol += ffUtf8StrWidth(s, len); +} + +static void rowAppendVisualTruncated(FFRow* row, const char* s, uint32_t maxWidth) { + uint32_t total = (uint32_t) strlen(s); + uint32_t bytes = total; + if (ffUtf8StrWidth(s, total) > maxWidth) { + bytes = 0; + uint32_t used = 0; + const char* p = s; + uint32_t remaining = total; + while (remaining > 0 && used < maxWidth) { + uint8_t w = 0; + uint8_t cbytes = ffUtf8CharLenWidth(p, remaining, &w); + if (cbytes == 0 || used + w > maxWidth) { + break; + } + used += w; + bytes += cbytes; + p += cbytes; + remaining -= cbytes; + } + } + ffStrbufAppendNS(&row->buf, bytes, s); + row->visualCol += ffUtf8StrWidth(s, bytes); +} + +static void rowPadVisual(FFRow* row, uint32_t col) { + while (row->visualCol < col) { + ffStrbufAppendC(&row->buf, ' '); + ++row->visualCol; + } +} + +static uint32_t rowAnsiSeqLength(const char* s, uint32_t length) { + uint32_t i = 1; + while (i < length) { + uint8_t c = (uint8_t) s[i]; + if (c >= 0x40 && c <= 0x7e) { + return i + 1; + } + ++i; + } + return length; +} + +static void truncateRow(FFRow* row) { + FFstrbuf src = row->buf; + ffStrbufInitA(&row->buf, row->cols + 32); + uint32_t used = 0; + uint32_t remaining = src.length; + const char* p = src.chars; + while (remaining > 0 && used < row->cols) { + if (*p == '\x1b') { + uint32_t len = rowAnsiSeqLength(p, remaining); + ffStrbufAppendNS(&row->buf, len, p); + p += len; + remaining -= len; + } else { + uint8_t w = 0; + uint8_t cbytes = ffUtf8CharLenWidth(p, remaining, &w); + if (cbytes == 0) { + cbytes = 1; + w = 1; + } + if (used + w > row->cols) { + break; + } + ffStrbufAppendNS(&row->buf, cbytes, p); + used += w; + p += cbytes; + remaining -= cbytes; + } + } + ffStrbufDestroy(&src); + row->visualCol = used; +} + +static void finishRow(FFRow* row, FFstrbuf* out, bool isLastRow) { + if (row->visualCol > row->cols) { + truncateRow(row); + ffStrbufAppendS(&row->buf, "\e[m"); + } + if (row->visualCol < row->cols) { + rowPadVisual(row, row->cols); + } + ffStrbufAppend(out, &row->buf); + ffStrbufAppendS(out, "\e[K"); + if (!isLastRow) { + ffStrbufAppendS(out, "\r\n"); + } + ffStrbufDestroy(&row->buf); +} + +static void drawModuleItem(FFRow* row, const FFGenConfigItem* item, uint32_t cellWidth, bool highlight) { + const uint32_t nameMax = cellWidth > 4 ? cellWidth - 4 : 0; + + if (item->baseInfo == &ffBreakModuleInfo) { + rowAppendRaw(row, highlight ? "\e[1;95;7m" : "\e[1;95m"); + ffStrbufAppendS(&row->buf, "[─]"); + row->visualCol += 3; + rowAppendRaw(row, "\e[m"); + rowAppendVisual(row, " "); + rowAppendRaw(row, highlight ? "\e[1;95;7m" : "\e[1;95m"); + rowAppendVisualTruncated(row, item->baseInfo->name, nameMax); + rowAppendRaw(row, "\e[m"); + return; + } + if (item->baseInfo == &ffSeparatorModuleInfo) { + rowAppendRaw(row, highlight ? "\e[1;96;7m" : "\e[1;96m"); + ffStrbufAppendS(&row->buf, "[═]"); + row->visualCol += 3; + rowAppendRaw(row, "\e[m"); + rowAppendVisual(row, " "); + rowAppendRaw(row, highlight ? "\e[1;96;7m" : "\e[1;96m"); + rowAppendVisualTruncated(row, item->baseInfo->name, nameMax); + rowAppendRaw(row, "\e[m"); + return; + } + + if (item->status == FF_GEN_CONFIG_ITEM_STATUS_SELECTED) { + rowAppendRaw(row, highlight ? "\e[1;92;7m" : "\e[1;92m"); + ffStrbufAppendS(&row->buf, "[x]"); + row->visualCol += 3; + rowAppendRaw(row, "\e[m"); + rowAppendVisual(row, " "); + rowAppendRaw(row, highlight ? "\e[1;97;7m" : "\e[1;97m"); + rowAppendVisualTruncated(row, item->baseInfo->name, nameMax); + rowAppendRaw(row, "\e[m"); + } else { + rowAppendRaw(row, highlight ? "\e[90;7m" : "\e[90m"); + ffStrbufAppendS(&row->buf, "[ ]"); + row->visualCol += 3; + rowAppendRaw(row, "\e[m"); + rowAppendVisual(row, " "); + rowAppendVisualTruncated(row, item->baseInfo->name, nameMax); + rowAppendRaw(row, "\e[m"); + } +} + +static void drawItemCell(FFRow* row, uint32_t startCol, uint32_t cellWidth, const FFGenConfigItem* item, bool highlight) { + rowPadVisual(row, startCol); + drawModuleItem(row, item, cellWidth, highlight); + rowPadVisual(row, startCol + cellWidth); +} + +static void drawLogoOption(FFRow* row, const char* name, bool active) { + if (active) { + rowAppendRaw(row, "\e[1;92m"); + rowAppendVisual(row, "● "); + rowAppendRaw(row, "\e[m"); + rowAppendRaw(row, "\e[1m"); + rowAppendVisual(row, name); + rowAppendRaw(row, "\e[m"); + } else { + rowAppendRaw(row, "\e[90m"); + rowAppendVisual(row, "○ "); + rowAppendVisual(row, name); + rowAppendRaw(row, "\e[m"); + } +} + +static void renderFrame(FFGenConfigUI* ui, FFstrbuf* out) { + getTerminalSize(&ui->rows, &ui->cols); + computeLayout(ui); + recomputeView(ui); + + const FFGenConfigLayout* layout = &ui->layout; + const uint16_t cols = ui->cols; + const uint32_t selectedCount = countSelectedModules(&ui->items); + const uint32_t moduleCount = countModules(&ui->items); + + ffStrbufAppendS(out, "\e[?25l\e[H"); + uint32_t rowCount = 0; + + FFRow row; + + // Row 0: title + rowInit(&row, cols); + rowAppendVisual(&row, " "); + rowAppendRaw(&row, "\e[1;36m"); + rowAppendVisual(&row, "fastfetch"); + rowAppendRaw(&row, "\e[m"); + rowAppendRaw(&row, "\e[1m"); + rowAppendVisual(&row, " configuration"); + rowAppendRaw(&row, "\e[m"); + if (cols >= 48) { + rowAppendVisual(&row, " "); + rowAppendRaw(&row, "\e[90m"); + rowAppendVisual(&row, "interactive config generator"); + rowAppendRaw(&row, "\e[m"); + } + finishRow(&row, out, ++rowCount == ui->rows); + + // Row 1: blank + rowInit(&row, cols); + finishRow(&row, out, ++rowCount == ui->rows); + + // Row 2: logo type + rowInit(&row, cols); + rowAppendVisual(&row, " "); + rowAppendRaw(&row, "\e[1;97m"); + rowAppendVisual(&row, "Logo type:"); + rowAppendRaw(&row, "\e[m"); + rowAppendVisual(&row, " "); + drawLogoOption(&row, "default", ui->logoType == FF_LOGO_TYPE_AUTO); + rowAppendVisual(&row, " "); + drawLogoOption(&row, "small", ui->logoType == FF_LOGO_TYPE_SMALL); + rowAppendVisual(&row, " "); + drawLogoOption(&row, "none", ui->logoType == FF_LOGO_TYPE_NONE); + if (cols >= 72) { + rowAppendVisual(&row, " "); + rowAppendRaw(&row, "\e[90m"); + rowAppendVisual(&row, "(l)"); + rowAppendRaw(&row, "\e[m"); + } + finishRow(&row, out, ++rowCount == ui->rows); + + // Row 3: output mode + rowInit(&row, cols); + rowAppendVisual(&row, " "); + rowAppendRaw(&row, "\e[1;97m"); + rowAppendVisual(&row, "Output:"); + rowAppendRaw(&row, "\e[m"); + rowAppendVisual(&row, " "); + drawLogoOption(&row, "minimal", !ui->fullConfig); + rowAppendVisual(&row, " "); + drawLogoOption(&row, "full", ui->fullConfig); + if (cols >= 64) { + rowAppendVisual(&row, " "); + rowAppendRaw(&row, "\e[90m"); + rowAppendVisual(&row, "(o)"); + rowAppendRaw(&row, "\e[m"); + } + finishRow(&row, out, ++rowCount == ui->rows); + + // Row 4: blank + rowInit(&row, cols); + finishRow(&row, out, ++rowCount == ui->rows); + + // Row 5: modules title + rowInit(&row, cols); + rowAppendVisual(&row, " "); + rowAppendRaw(&row, "\e[1;97m"); + rowAppendVisual(&row, "Modules:"); + rowAppendRaw(&row, "\e[m"); + rowAppendRaw(&row, "\e[92m"); + FF_STRBUF_AUTO_DESTROY counter = ffStrbufCreateA(32); + ffStrbufAppendF(&counter, " [%u/%u selected]", selectedCount, moduleCount); + rowAppendVisual(&row, counter.chars); + rowAppendRaw(&row, "\e[m"); + finishRow(&row, out, ++rowCount == ui->rows); + + // Row 6: blank + rowInit(&row, cols); + finishRow(&row, out, ++rowCount == ui->rows); + + // Grid rows + const uint32_t rowsPerColumn = layout->itemsPerColumn; + const uint32_t length = ui->items.length; + for (uint16_t screenRow = 0; screenRow < layout->listRows; ++screenRow) { + rowInit(&row, cols); + for (uint32_t c = 0; c < layout->columns; ++c) { + uint32_t startCol = layout->listLeft + c * layout->colWidth; + uint32_t index = (ui->viewOffset + screenRow) + c * rowsPerColumn; + if (screenRow < rowsPerColumn && index < length) { + const FFGenConfigItem* item = FF_LIST_GET(FFGenConfigItem, ui->items, index); + drawItemCell(&row, startCol, layout->colWidth, item, (uint32_t) ui->cursor == index); + } else { + rowPadVisual(&row, startCol + layout->colWidth); + } + } + finishRow(&row, out, ++rowCount == ui->rows); + } + + // Row after grid: description + rowInit(&row, cols); + if (ui->cursor >= 0 && (uint32_t) ui->cursor < ui->items.length) { + const FFGenConfigItem* item = FF_LIST_GET(FFGenConfigItem, ui->items, (uint32_t) ui->cursor); + if (item->baseInfo && item->baseInfo->description) { + rowAppendVisual(&row, " "); + rowAppendRaw(&row, "\e[90m"); + rowAppendVisualTruncated(&row, item->baseInfo->description, cols > 4 ? cols - 4 : 1); + rowAppendRaw(&row, "\e[m"); + } + } + finishRow(&row, out, ++rowCount == ui->rows); + + // Help lines + rowInit(&row, cols); + rowAppendRaw(&row, "\e[90m"); + rowAppendVisual(&row, " ↑/↓ k/j move ←/→ col Space toggle f/F all/invert K/J reorder b/B break/sep d/D del"); + if (ui->confirmingOverwrite) { + rowAppendRaw(&row, "\e[m"); + rowAppendRaw(&row, "\e[1;93m"); + rowAppendVisual(&row, " File exists. Overwrite? (y/N)"); + rowAppendRaw(&row, "\e[m"); + } + finishRow(&row, out, ++rowCount == ui->rows); + + rowInit(&row, cols); + rowAppendRaw(&row, "\e[90m"); + rowAppendVisual(&row, " l logo o minimal/full s/Enter save q/Esc quit g/G top/bottom"); + rowAppendRaw(&row, "\e[m"); + finishRow(&row, out, ++rowCount == ui->rows); + + ffStrbufAppendS(out, "\e[J"); +} + +// ---- Key input ------------------------------------------------------------- + +static FFGenConfigKey readKey(char* outChar) { +#ifndef _WIN32 + struct pollfd pfd = { + .fd = STDIN_FILENO, + .events = POLLIN, + }; + if (poll(&pfd, 1, 100) <= 0) { + return FF_GEN_KEY_UNKNOWN; + } +#else + HANDLE hInput = GetStdHandle(STD_INPUT_HANDLE); + DWORD waitResult = WaitForSingleObject(hInput, 100); + if (waitResult != WAIT_OBJECT_0) { + return FF_GEN_KEY_UNKNOWN; + } + DWORD numEvents; + while (GetNumberOfConsoleInputEvents(hInput, &numEvents) && numEvents > 0) { + INPUT_RECORD record; + DWORD read; + if (!PeekConsoleInput(hInput, &record, 1, &read) || read == 0) { + break; + } + if (record.EventType == KEY_EVENT && record.Event.KeyEvent.bKeyDown) { + break; + } + ReadConsoleInput(hInput, &record, 1, &read); + } + if (!GetNumberOfConsoleInputEvents(hInput, &numEvents) || numEvents == 0) { + return FF_GEN_KEY_UNKNOWN; + } +#endif + + char buf[16]; + ssize_t n = ffReadFDData(FFUnixFD2NativeFD(STDIN_FILENO), sizeof(buf), buf); + if (n <= 0) { + return FF_GEN_KEY_UNKNOWN; + } + if (buf[0] == '\r' || buf[0] == '\n') { + return FF_GEN_KEY_ENTER; + } + if (buf[0] != '\x1b') { + *outChar = buf[0]; + return FF_GEN_KEY_CHAR; + } + if (n == 1) { + return FF_GEN_KEY_ESCAPE; + } + + if (buf[1] == '[') { + size_t i = 2; + if (i < (size_t) n && buf[i] >= 'A' && buf[i] <= 'D') { + switch (buf[i]) { + case 'A': + return FF_GEN_KEY_UP; + case 'B': + return FF_GEN_KEY_DOWN; + case 'C': + return FF_GEN_KEY_RIGHT; + case 'D': + return FF_GEN_KEY_LEFT; + } + } + uint32_t param = 0; + while (i < (size_t) n && buf[i] >= '0' && buf[i] <= '9') { + param = param * 10 + (uint32_t) (buf[i] - '0'); + ++i; + } + while (i < (size_t) n && buf[i] == ';') { + ++i; + while (i < (size_t) n && buf[i] >= '0' && buf[i] <= '9') { + ++i; + } + } + if (i < (size_t) n) { + switch (buf[i]) { + case 'A': + return FF_GEN_KEY_UP; + case 'B': + return FF_GEN_KEY_DOWN; + case 'C': + return FF_GEN_KEY_RIGHT; + case 'D': + return FF_GEN_KEY_LEFT; + case 'H': + return FF_GEN_KEY_HOME; + case 'F': + return FF_GEN_KEY_END; + case '~': + switch (param) { + case 5: + return FF_GEN_KEY_PAGE_UP; + case 6: + return FF_GEN_KEY_PAGE_DOWN; + case 7: + return FF_GEN_KEY_HOME; + case 8: + return FF_GEN_KEY_END; + } + } + } + return FF_GEN_KEY_UNKNOWN; + } + + if (buf[1] == 'O') { + if (n >= 3) { + switch (buf[2]) { + case 'H': + return FF_GEN_KEY_HOME; + case 'F': + return FF_GEN_KEY_END; + } + } + return FF_GEN_KEY_UNKNOWN; + } + + return FF_GEN_KEY_ESCAPE; +} + +static void moveCursorLeft(FFGenConfigUI* ui) { + uint32_t rowsPerColumn = ui->layout.itemsPerColumn; + if (rowsPerColumn == 0) { + return; + } + if ((uint32_t) ui->cursor >= rowsPerColumn) { + ui->cursor -= rowsPerColumn; + } +} + +static void moveCursorRight(FFGenConfigUI* ui) { + uint32_t rowsPerColumn = ui->layout.itemsPerColumn; + if (rowsPerColumn == 0) { + return; + } + uint32_t newCursor = (uint32_t) ui->cursor + rowsPerColumn; + if (newCursor < ui->items.length) { + ui->cursor = (int32_t) newCursor; + } +} + +static void moveCursorUp(FFGenConfigUI* ui) { + if (ui->cursor > 0) { + --ui->cursor; + } +} + +static void moveCursorDown(FFGenConfigUI* ui) { + if (ui->items.length == 0) { + return; + } + if ((uint32_t) ui->cursor + 1 < ui->items.length) { + ++ui->cursor; + } else { + ui->cursor = 0; + } +} + +// Returns 1 on save, 0 on quit, -1 on continue +static int handleKey(FFGenConfigUI* ui, FFGenConfigKey key, char ch, bool fileExists) { + if (key == FF_GEN_KEY_UNKNOWN) { + return -1; + } + + if (ui->confirmingOverwrite) { + if (key == FF_GEN_KEY_CHAR && (ch == 'y' || ch == 'Y')) { + return 1; + } + if ((key == FF_GEN_KEY_CHAR && (ch == 'n' || ch == 'N')) || key == FF_GEN_KEY_ESCAPE || key == FF_GEN_KEY_ENTER) { + ui->confirmingOverwrite = false; + } + return -1; + } + + switch (key) { + case FF_GEN_KEY_UP: + moveCursorUp(ui); + break; + case FF_GEN_KEY_DOWN: + moveCursorDown(ui); + break; + case FF_GEN_KEY_LEFT: + moveCursorLeft(ui); + break; + case FF_GEN_KEY_RIGHT: + moveCursorRight(ui); + break; + case FF_GEN_KEY_PAGE_UP: + ui->cursor -= (int32_t) ui->layout.listRows; + if (ui->cursor < 0) { + ui->cursor = 0; + } + break; + case FF_GEN_KEY_PAGE_DOWN: + if (ui->items.length == 0) { + break; + } + ui->cursor += (int32_t) ui->layout.listRows; + if ((uint32_t) ui->cursor >= ui->items.length) { + ui->cursor = (int32_t) ui->items.length - 1; + } + break; + case FF_GEN_KEY_HOME: + ui->cursor = 0; + break; + case FF_GEN_KEY_END: + ui->cursor = ui->items.length > 0 ? (int32_t) ui->items.length - 1 : 0; + break; + case FF_GEN_KEY_ENTER: + if (fileExists) { + ui->confirmingOverwrite = true; + } else { + return 1; + } + break; + case FF_GEN_KEY_ESCAPE: + return 0; + case FF_GEN_KEY_CHAR: + if (ch == 'q') { + return 0; + } else if (ch == 's') { + if (fileExists) { + ui->confirmingOverwrite = true; + } else { + return 1; + } + } else if (ch == ' ') { + if (ui->cursor >= 0 && (uint32_t) ui->cursor < ui->items.length) { + toggleItem(ui, (uint32_t) ui->cursor); + } + } else if (ch == 'f') { + selectAllModules(ui); + } else if (ch == 'F') { + invertAllModules(ui); + } else if (ch == 'o') { + ui->fullConfig = !ui->fullConfig; + } else if (ch == 'j') { + moveCursorDown(ui); + } else if (ch == 'k') { + moveCursorUp(ui); + } else if (ch == 'J') { + if (ui->cursor >= 0 && (uint32_t) ui->cursor < ui->items.length) { + moveItemDown(ui, (uint32_t) ui->cursor); + } + } else if (ch == 'K') { + if (ui->cursor >= 0 && (uint32_t) ui->cursor < ui->items.length) { + moveItemUp(ui, (uint32_t) ui->cursor); + } + } else if (ch == 'b') { + if (ui->cursor >= 0 && (uint32_t) ui->cursor < ui->items.length) { + addBreakBelow(ui, (uint32_t) ui->cursor); + } + } else if (ch == 'B') { + if (ui->cursor >= 0 && (uint32_t) ui->cursor < ui->items.length) { + addSeparatorBelow(ui, (uint32_t) ui->cursor); + } + } else if (ch == 'd') { + if (ui->cursor >= 0 && (uint32_t) ui->cursor < ui->items.length) { + FFGenConfigItem* item = FF_LIST_GET(FFGenConfigItem, ui->items, (uint32_t) ui->cursor); + if (item->status == FF_GEN_CONFIG_ITEM_STATUS_SPECIAL) { + FF_LIST_REMOVE_AT(FFGenConfigItem, ui->items, (uint32_t) ui->cursor); + if ((uint32_t) ui->cursor >= ui->items.length && ui->items.length > 0) { + ui->cursor = (int32_t) ui->items.length - 1; + } + } + } + } else if (ch == 'D') { + removeAllBreaksSeparators(ui); + } else if (ch == 'g') { + ui->cursor = 0; + } else if (ch == 'G') { + ui->cursor = ui->items.length > 0 ? (int32_t) ui->items.length - 1 : 0; + } else if (ch == 'l') { + cycleLogoType(ui, 1); + } else if (ch == '\x03' || ch == '\x04' || ch == '\x1a' || ch == '\x1c') { + return 0; + } + break; + case FF_GEN_KEY_UNKNOWN: + break; + } + return -1; +} + +static int runCui(FFGenConfigUI* ui, bool fileExists) { + while (true) { + FF_STRBUF_AUTO_DESTROY frame = ffStrbufCreateA((uint32_t) ui->cols * ((uint32_t) ui->rows + 4)); + renderFrame(ui, &frame); + ffWriteFDData(FFUnixFD2NativeFD(STDOUT_FILENO), frame.length, frame.chars); + fflush(stdout); + + char ch = 0; + FFGenConfigKey key = readKey(&ch); + int result = handleKey(ui, key, ch, fileExists); + if (result != -1) { + return result; + } + } +} + +static FFLogoType initialLogoType(void) { + switch (instance.config.logo.type) { + case FF_LOGO_TYPE_SMALL: + return FF_LOGO_TYPE_SMALL; + case FF_LOGO_TYPE_NONE: + return FF_LOGO_TYPE_NONE; + default: + return FF_LOGO_TYPE_AUTO; + } +} + +static bool applyConfig(FFdata* data, const FFlist* items, bool fullConfig) { + if (data->resultDoc) { + fputs("Error: duplicated `--gen-config` or `--format json` flags found\n", stderr); + return false; + } + + FF_STRBUF_AUTO_DESTROY structure = ffStrbufCreateA(256); + FF_LIST_FOR_EACH (FFGenConfigItem, item, *items) { + if (item->status == FF_GEN_CONFIG_ITEM_STATUS_UNSELECTED) { + continue; + } + ffStrbufAppendS(&structure, item->baseInfo->name); + ffStrbufAppendC(&structure, ':'); + } + ffStrbufTrimRight(&structure, ':'); + ffStrbufSet(&data->structure, &structure); + + data->docType = fullConfig ? FF_RESULT_DOC_TYPE_CONFIG_FULL : FF_RESULT_DOC_TYPE_CONFIG; + data->resultDoc = yyjson_mut_doc_new(nullptr); + return true; +} + +bool ffGenConfigInteractive(FFdata* data) { + FF_LIST_AUTO_DESTROY modules; + collectModuleInfos(&modules); + + FFGenConfigUI ui = { + .items = ffListCreate(), + .cursor = 0, + .viewOffset = 0, + .logoType = initialLogoType(), + .fullConfig = false, + .confirmingOverwrite = false, + .rows = 24, + .cols = 80, + }; + initItems(&ui.items, &modules); + + getTerminalSize(&ui.rows, &ui.cols); + enterRawMode(); + ffWriteFDData(FFUnixFD2NativeFD(STDOUT_FILENO), strlen("\e[?1049h\e[?25l"), "\e[?1049h\e[?25l"); + + const bool fileExists = ffPathExists(data->genConfigPath.chars, FF_PATHTYPE_ANY); + int result = runCui(&ui, fileExists); + + restoreRawMode(); + ffWriteFDData(FFUnixFD2NativeFD(STDOUT_FILENO), strlen("\e[?1049l\e[?25h\e[m"), "\e[?1049l\e[?25h\e[m"); + + bool success = false; + if (result == 1) { + if (applyConfig(data, &ui.items, ui.fullConfig)) { + instance.config.logo.type = ui.logoType; + success = true; + } + } else { + fputs("\nConfig generation cancelled.\n", stderr); + } + + ffListDestroy(&ui.items); + return success; +} diff --git a/src/common/impl/init.c b/src/common/impl/init.c index 95e6cfd766..8f6edbe7f4 100644 --- a/src/common/impl/init.c +++ b/src/common/impl/init.c @@ -105,12 +105,12 @@ static void resetConsole(void) { } #ifdef _WIN32 -BOOL WINAPI consoleHandler(FF_A_UNUSED DWORD signal) { +BOOL WINAPI consoleHandler([[maybe_unused]] DWORD signal) { resetConsole(); exit(0); } #else -static void exitSignalHandler(FF_A_UNUSED int signal) { +static void exitSignalHandler([[maybe_unused]] int signal) { resetConsole(); exit(0); } @@ -123,26 +123,26 @@ void ffStart(void) { #ifdef _WIN32 SetErrorMode(SEM_FAILCRITICALERRORS); if (instance.config.display.noBuffer) { - setvbuf(stdout, NULL, _IONBF, 0); + setvbuf(stdout, nullptr, _IONBF, 0); } else { - setvbuf(stdout, NULL, _IOFBF, 4096); + setvbuf(stdout, nullptr, _IOFBF, 4096); } SetConsoleCtrlHandler(consoleHandler, TRUE); #else if (instance.config.display.noBuffer) { - setvbuf(stdout, NULL, _IONBF, 0); + setvbuf(stdout, nullptr, _IONBF, 0); } struct sigaction action; sigemptyset(&action.sa_mask); action.sa_flags = 0; action.sa_handler = exitSignalHandler; - sigaction(SIGINT, &action, NULL); - sigaction(SIGTERM, &action, NULL); - sigaction(SIGQUIT, &action, NULL); + sigaction(SIGINT, &action, nullptr); + sigaction(SIGTERM, &action, nullptr); + sigaction(SIGQUIT, &action, nullptr); sigset_t newmask; sigemptyset(&newmask); sigaddset(&newmask, SIGCHLD); - sigprocmask(SIG_BLOCK, &newmask, NULL); + sigprocmask(SIG_BLOCK, &newmask, nullptr); #endif // reset everything to default before we start printing diff --git a/src/common/impl/io_unix.c b/src/common/impl/io_unix.c index e603186117..840df3be68 100644 --- a/src/common/impl/io_unix.c +++ b/src/common/impl/io_unix.c @@ -22,8 +22,8 @@ static void createSubfolders(const char* fileName) { FF_STRBUF_AUTO_DESTROY path = ffStrbufCreate(); - const char* token = NULL; - while ((token = strchr(fileName, '/')) != NULL) { + const char* token = nullptr; + while ((token = strchr(fileName, '/')) != nullptr) { ffStrbufAppendNS(&path, (uint32_t) (token - fileName + 1), fileName); mkdir(path.chars, S_IRWXU | S_IRGRP | S_IROTH); fileName = token + 1; @@ -34,7 +34,7 @@ bool ffWriteFileData(const char* fileName, size_t dataSize, const void* data) { int openFlagsModes = O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC; mode_t openFlagsRights = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; - int FF_AUTO_CLOSE_FD fd = open(fileName, openFlagsModes, openFlagsRights); + FF_AUTO_CLOSE_FD int fd = open(fileName, openFlagsModes, openFlagsRights); if (fd == -1) { if (errno == ENOENT) { createSubfolders(fileName); @@ -119,7 +119,7 @@ bool ffPathExpandEnv(const char* in, FFstrbuf* out) { | GLOB_BRACE #endif , - NULL, + nullptr, &gb) != 0) return false; @@ -174,7 +174,7 @@ const char* ffGetTerminalResponse(const char* request, int nParams, const char* fd_set rd; FD_ZERO(&rd); FD_SET(ftty, &rd); - if (select(ftty + 1, &rd, NULL, NULL, &(struct timeval) { .tv_sec = FF_IO_TERM_RESP_WAIT_MS / 1000, .tv_usec = (FF_IO_TERM_RESP_WAIT_MS % 1000) * 1000 }) <= 0) { + if (select(ftty + 1, &rd, nullptr, nullptr, &(struct timeval) { .tv_sec = FF_IO_TERM_RESP_WAIT_MS / 1000, .tv_usec = (FF_IO_TERM_RESP_WAIT_MS % 1000) * 1000 }) <= 0) { return "select(/dev/tty) timeout or failed"; } } @@ -213,7 +213,7 @@ const char* ffGetTerminalResponse(const char* request, int nParams, const char* va_end(args); - return NULL; + return nullptr; } bool ffSuppressIO(bool suppress) { @@ -258,14 +258,14 @@ void listFilesRecursively(uint32_t baseLength, FFstrbuf* folder, uint8_t indenta } FF_AUTO_CLOSE_DIR DIR* dir = fdopendir(dfd); - if (dir == NULL) { + if (dir == nullptr) { close(dfd); return; // Should not happen } uint32_t folderLength = folder->length; - if (pretty && folderName != NULL) { + if (pretty && folderName != nullptr) { for (uint8_t i = 0; i < indentation - 1; i++) { fputs(" | ", stdout); } @@ -274,7 +274,7 @@ void listFilesRecursively(uint32_t baseLength, FFstrbuf* folder, uint8_t indenta struct dirent* entry; - while ((entry = readdir(dir)) != NULL) { + while ((entry = readdir(dir)) != nullptr) { if (entry->d_name[0] == '.') { // skip hidden files continue; } @@ -316,7 +316,7 @@ void listFilesRecursively(uint32_t baseLength, FFstrbuf* folder, uint8_t indenta void ffListFilesRecursively(const char* path, bool pretty) { FF_STRBUF_AUTO_DESTROY folder = ffStrbufCreateS(path); ffStrbufEnsureEndsWithC(&folder, '/'); - listFilesRecursively(folder.length, &folder, 0, NULL, pretty); + listFilesRecursively(folder.length, &folder, 0, nullptr, pretty); } FFNativeFD ffGetNullFD(void) { diff --git a/src/common/impl/io_windows.c b/src/common/impl/io_windows.c index e085bf2ca9..b9691eb39e 100644 --- a/src/common/impl/io_windows.c +++ b/src/common/impl/io_windows.c @@ -20,10 +20,10 @@ static bool createSubfolders(wchar_t* fileName) { fileName, FILE_LIST_DIRECTORY | FILE_TRAVERSE | SYNCHRONIZE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, - NULL, + nullptr, OPEN_EXISTING, FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT | FILE_FLAG_BACKUP_SEMANTICS, - NULL); + nullptr); ptr[3] = saved; if (hRoot == INVALID_HANDLE_VALUE) { @@ -36,12 +36,12 @@ static bool createSubfolders(wchar_t* fileName) { // UNC path: \\server\share\... else if (ptr[0] == L'\\' && ptr[1] == L'\\') { wchar_t* serverEnd = wcschr(ptr + 2, L'\\'); - if (serverEnd == NULL) { + if (serverEnd == nullptr) { return false; } wchar_t* shareEnd = wcschr(serverEnd + 1, L'\\'); - if (shareEnd == NULL) { + if (shareEnd == nullptr) { return true; // no parent subfolder exists before file name } @@ -52,10 +52,10 @@ static bool createSubfolders(wchar_t* fileName) { fileName, FILE_LIST_DIRECTORY | FILE_TRAVERSE | SYNCHRONIZE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, - NULL, + nullptr, OPEN_EXISTING, FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT | FILE_FLAG_BACKUP_SEMANTICS, - NULL); + nullptr); *shareEnd = saved; if (hRoot == INVALID_HANDLE_VALUE) { @@ -73,10 +73,10 @@ static bool createSubfolders(wchar_t* fileName) { driveRoot, FILE_LIST_DIRECTORY | FILE_TRAVERSE | SYNCHRONIZE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, - NULL, + nullptr, OPEN_EXISTING, FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT | FILE_FLAG_BACKUP_SEMANTICS, - NULL); + nullptr); if (hRoot == INVALID_HANDLE_VALUE) { return false; } @@ -86,7 +86,7 @@ static bool createSubfolders(wchar_t* fileName) { while (true) { wchar_t* token = wcschr(ptr, L'\\'); - if (token == NULL) { + if (token == nullptr) { break; } @@ -113,12 +113,12 @@ static bool createSubfolders(wchar_t* fileName) { .Attributes = OBJ_CASE_INSENSITIVE, }, &iosb, - NULL, + nullptr, FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, FILE_OPEN_IF, FILE_DIRECTORY_FILE | FILE_SYNCHRONOUS_IO_NONALERT, - NULL, + nullptr, 0); if (!NT_SUCCESS(status)) { @@ -157,13 +157,13 @@ bool ffWriteFileData(const char* fileName, size_t dataSize, const void* data) { } } - HANDLE FF_AUTO_CLOSE_FD handle = CreateFileW(fileNameW, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + FF_AUTO_CLOSE_FD HANDLE handle = CreateFileW(fileNameW, GENERIC_WRITE, FILE_SHARE_WRITE, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); if (handle == INVALID_HANDLE_VALUE) { if (GetLastError() == ERROR_PATH_NOT_FOUND) { if (!createSubfolders(fileNameW)) { return false; } - handle = CreateFileW(fileNameW, GENERIC_WRITE, FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + handle = CreateFileW(fileNameW, GENERIC_WRITE, FILE_SHARE_WRITE, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); if (handle == INVALID_HANDLE_VALUE) { return false; } @@ -173,7 +173,7 @@ bool ffWriteFileData(const char* fileName, size_t dataSize, const void* data) { } DWORD written; - return !!WriteFile(handle, data, (DWORD) dataSize, &written, NULL); + return !!WriteFile(handle, data, (DWORD) dataSize, &written, nullptr); } static inline void readWithLength(HANDLE handle, FFstrbuf* buffer, uint32_t length) { @@ -181,7 +181,7 @@ static inline void readWithLength(HANDLE handle, FFstrbuf* buffer, uint32_t leng DWORD bytesRead = 0; while ( length > 0 && - ReadFile(handle, buffer->chars + buffer->length, length, &bytesRead, NULL) != FALSE && + ReadFile(handle, buffer->chars + buffer->length, length, &bytesRead, nullptr) != FALSE && bytesRead > 0) { buffer->length += (uint32_t) bytesRead; length -= (uint32_t) bytesRead; @@ -193,7 +193,7 @@ static inline void readUntilEOF(HANDLE handle, FFstrbuf* buffer) { uint32_t available = ffStrbufGetFree(buffer); DWORD bytesRead = 0; while ( - ReadFile(handle, buffer->chars + buffer->length, available, &bytesRead, NULL) != FALSE && + ReadFile(handle, buffer->chars + buffer->length, available, &bytesRead, nullptr) != FALSE && bytesRead > 0) { buffer->length += (uint32_t) bytesRead; if ((uint32_t) bytesRead == available) { @@ -282,7 +282,7 @@ bool ffPathExpandEnv(const char* in, FFstrbuf* out) { len /= sizeof(wchar_t); // convert from bytes to characters SIZE_T outLen; // in characters, including null terminator - if (!NT_SUCCESS(RtlExpandEnvironmentStrings(NULL, pathInW, len, pathOutW, ARRAY_SIZE(pathOutW), &outLen))) { + if (!NT_SUCCESS(RtlExpandEnvironmentStrings(nullptr, pathInW, len, pathOutW, ARRAY_SIZE(pathOutW), &outLen))) { return false; } @@ -336,7 +336,7 @@ bool ffSuppressIO(bool suppress) { void listFilesRecursively(uint32_t baseLength, FFstrbuf* folder, uint8_t indentation, const char* folderName, bool pretty) { uint32_t folderLength = folder->length; - if (pretty && folderName != NULL) { + if (pretty && folderName != nullptr) { for (uint8_t i = 0; i < indentation - 1; i++) { fputs(" | ", stdout); } @@ -381,7 +381,7 @@ void listFilesRecursively(uint32_t baseLength, FFstrbuf* folder, uint8_t indenta void ffListFilesRecursively(const char* path, bool pretty) { FF_STRBUF_AUTO_DESTROY folder = ffStrbufCreateS(path); ffStrbufEnsureEndsWithC(&folder, '/'); - listFilesRecursively(folder.length, &folder, 0, NULL, pretty); + listFilesRecursively(folder.length, &folder, 0, nullptr, pretty); } const char* ffGetTerminalResponse(const char* request, int nParams, const char* format, ...) { @@ -390,7 +390,7 @@ const char* ffGetTerminalResponse(const char* request, int nParams, const char* DWORD inputMode = 0; bool hasInputMode = !!GetConsoleMode(hInput, &inputMode); if (!hasInputMode) { - hConin = CreateFileW(L"CONIN$", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, NULL); + hConin = CreateFileW(L"CONIN$", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, nullptr); hInput = hConin; hasInputMode = !!GetConsoleMode(hInput, &inputMode); } @@ -404,10 +404,10 @@ const char* ffGetTerminalResponse(const char* request, int nParams, const char* FF_AUTO_CLOSE_FD HANDLE hConout = INVALID_HANDLE_VALUE; DWORD outputMode; if (!GetConsoleMode(hOutput, &outputMode)) { - hConout = CreateFileW(L"CONOUT$", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, NULL); + hConout = CreateFileW(L"CONOUT$", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, nullptr); hOutput = hConout; } - WriteFile(hOutput, request, (DWORD) strlen(request), &bytes, NULL); + WriteFile(hOutput, request, (DWORD) strlen(request), &bytes, nullptr); } while (true) { @@ -441,7 +441,7 @@ const char* ffGetTerminalResponse(const char* request, int nParams, const char* while (true) { DWORD bytes = 0; - if (!ReadFile(hInput, buffer + bytesRead, (DWORD) (sizeof(buffer) - 1 - bytesRead), &bytes, NULL) || bytes == 0) { + if (!ReadFile(hInput, buffer + bytesRead, (DWORD) (sizeof(buffer) - 1 - bytesRead), &bytes, nullptr) || bytes == 0) { va_end(args); return "ReadFile() failed"; } @@ -473,7 +473,7 @@ const char* ffGetTerminalResponse(const char* request, int nParams, const char* va_end(args); - return NULL; + return nullptr; } FFNativeFD ffGetNullFD(void) { @@ -490,7 +490,7 @@ FFNativeFD ffGetNullFD(void) { 0, &(SECURITY_ATTRIBUTES) { .nLength = sizeof(SECURITY_ATTRIBUTES), - .lpSecurityDescriptor = NULL, + .lpSecurityDescriptor = nullptr, .bInheritHandle = TRUE, }); return hNullFile; diff --git a/src/common/impl/jsonconfig.c b/src/common/impl/jsonconfig.c index fccc56cc07..5179d5b5d3 100644 --- a/src/common/impl/jsonconfig.c +++ b/src/common/impl/jsonconfig.c @@ -67,7 +67,7 @@ const char* ffJsonConfigParseEnum(yyjson_val* val, int* result, FFKeyValuePair p for (const FFKeyValuePair* pPair = pairs; pPair->key; ++pPair) { if (intVal == pPair->value) { *result = pPair->value; - return NULL; + return nullptr; } } @@ -77,7 +77,7 @@ const char* ffJsonConfigParseEnum(yyjson_val* val, int* result, FFKeyValuePair p for (const FFKeyValuePair* pPair = pairs; pPair->key; ++pPair) { if (ffStrEqualsIgnCase(strVal, pPair->key)) { *result = pPair->value; - return NULL; + return nullptr; } } @@ -95,7 +95,7 @@ static bool parseModuleJsonObject(const char* type, yyjson_val* jsonVal, yyjson_ for (FFModuleBaseInfo** modules = ffModuleInfos[toupper(type[0]) - 'A']; *modules; ++modules) { FFModuleBaseInfo* baseInfo = *modules; if (ffStrEqualsIgnCase(type, baseInfo->name)) { - uint8_t optionBuf[FF_OPTION_MAX_SIZE]; + alignas(uint64_t) uint8_t optionBuf[FF_OPTION_MAX_SIZE]; baseInfo->initOptions(optionBuf); if (jsonVal) { baseInfo->parseJsonObject(optionBuf, jsonVal); @@ -139,7 +139,7 @@ static void prepareModuleJsonObject(const char* type, yyjson_val* module) { if (ffStrEqualsIgnCase(type, FF_CPUUSAGE_MODULE_NAME)) { ffPrepareCPUUsage(); } else if (ffStrEqualsIgnCase(type, FF_COMMAND_MODULE_NAME)) { - FF_A_CLEANUP(ffDestroyCommandOptions) FFCommandOptions options; + [[gnu::cleanup(ffDestroyCommandOptions)]] FFCommandOptions options; ffInitCommandOptions(&options); if (module) { ffCommandModuleInfo.parseJsonObject(&options, module); @@ -154,7 +154,7 @@ static void prepareModuleJsonObject(const char* type, yyjson_val* module) { case 'd': case 'D': { if (ffStrEqualsIgnCase(type, FF_DISKIO_MODULE_NAME)) { - FF_A_CLEANUP(ffDestroyDiskIOOptions) FFDiskIOOptions options; + [[gnu::cleanup(ffDestroyDiskIOOptions)]] FFDiskIOOptions options; ffInitDiskIOOptions(&options); if (module) { ffDiskIOModuleInfo.parseJsonObject(&options, module); @@ -169,7 +169,7 @@ static void prepareModuleJsonObject(const char* type, yyjson_val* module) { case 'n': case 'N': { if (ffStrEqualsIgnCase(type, FF_NETIO_MODULE_NAME)) { - FF_A_CLEANUP(ffDestroyNetIOOptions) FFNetIOOptions options; + [[gnu::cleanup(ffDestroyNetIOOptions)]] FFNetIOOptions options; ffInitNetIOOptions(&options); if (module) { ffNetIOModuleInfo.parseJsonObject(&options, module); @@ -184,7 +184,7 @@ static void prepareModuleJsonObject(const char* type, yyjson_val* module) { case 'p': case 'P': { if (ffStrEqualsIgnCase(type, FF_PUBLICIP_MODULE_NAME)) { - FF_A_CLEANUP(ffDestroyPublicIpOptions) FFPublicIPOptions options; + [[gnu::cleanup(ffDestroyPublicIpOptions)]] FFPublicIPOptions options; ffInitPublicIpOptions(&options); if (module) { ffPublicIPModuleInfo.parseJsonObject(&options, module); @@ -199,7 +199,7 @@ static void prepareModuleJsonObject(const char* type, yyjson_val* module) { case 'w': case 'W': { if (ffStrEqualsIgnCase(type, FF_WEATHER_MODULE_NAME)) { - FF_A_CLEANUP(ffDestroyWeatherOptions) FFWeatherOptions options; + [[gnu::cleanup(ffDestroyWeatherOptions)]] FFWeatherOptions options; ffInitWeatherOptions(&options); if (module) { ffWeatherModuleInfo.parseJsonObject(&options, module); @@ -244,7 +244,7 @@ static const char* printJsonConfig(FFdata* data, bool prepare) { yyjson_val* modules = yyjson_obj_get(root, "modules"); if (!modules) { - return NULL; + return nullptr; } if (!yyjson_is_arr(modules)) { return "Property 'modules' must be an array of strings or objects"; @@ -263,7 +263,7 @@ static const char* printJsonConfig(FFdata* data, bool prepare) { yyjson_val* module = item; const char* type = yyjson_get_str(module); if (type) { - module = NULL; + module = nullptr; } else if (yyjson_is_obj(module)) { yyjson_val* conditions = yyjson_obj_get(module, "condition"); if (conditions) { @@ -307,7 +307,7 @@ static const char* printJsonConfig(FFdata* data, bool prepare) { return "module object must contain a \"type\" key ( case sensitive )"; } if (yyjson_obj_size(module) == 1) { // contains only Property type - module = NULL; + module = nullptr; } } else { return "modules must be an array of strings or objects"; @@ -347,7 +347,7 @@ static const char* printJsonConfig(FFdata* data, bool prepare) { #endif } - return NULL; + return nullptr; } void ffPrintJsonConfig(FFdata* data, bool prepare) { @@ -359,7 +359,7 @@ void ffPrintJsonConfig(FFdata* data, bool prepare) { yyjson_mut_obj_add_str(jsonDoc, obj, "error", error); yyjson_mut_doc_set_root(jsonDoc, obj); } else { - ffPrintError("JsonConfig", 0, NULL, FF_PRINT_TYPE_NO_CUSTOM_KEY, "%s", error); + ffPrintError("JsonConfig", 0, nullptr, FF_PRINT_TYPE_NO_CUSTOM_KEY, "%s", error); } } } diff --git a/src/common/impl/kmod_apple.c b/src/common/impl/kmod_apple.c index 82edc49463..3f1395f5cb 100644 --- a/src/common/impl/kmod_apple.c +++ b/src/common/impl/kmod_apple.c @@ -6,7 +6,7 @@ bool ffKmodLoaded(const char* modName) { FF_CFTYPE_AUTO_RELEASE CFStringRef name = CFStringCreateWithCString(kCFAllocatorDefault, modName, kCFStringEncodingUTF8); FF_CFTYPE_AUTO_RELEASE CFArrayRef identifiers = CFArrayCreate(kCFAllocatorDefault, (const void**) &name, 1, &kCFTypeArrayCallBacks); - FF_CFTYPE_AUTO_RELEASE CFArrayRef keys = CFArrayCreate(kCFAllocatorDefault, NULL, 0, NULL); + FF_CFTYPE_AUTO_RELEASE CFArrayRef keys = CFArrayCreate(kCFAllocatorDefault, nullptr, 0, nullptr); FF_CFTYPE_AUTO_RELEASE CFDictionaryRef kextInfo = KextManagerCopyLoadedKextInfo(identifiers, keys); return CFDictionaryContainsKey(kextInfo, name); } diff --git a/src/common/impl/kmod_linux.c b/src/common/impl/kmod_linux.c index 204ab35857..e5f9d1029a 100644 --- a/src/common/impl/kmod_linux.c +++ b/src/common/impl/kmod_linux.c @@ -3,7 +3,7 @@ bool ffKmodLoaded(const char* modName) { static FFstrbuf modules; - if (modules.chars == NULL) { + if (modules.chars == nullptr) { ffStrbufInitS(&modules, "\n"); ffAppendFileBuffer("/proc/modules", &modules); } @@ -21,5 +21,5 @@ bool ffKmodLoaded(const char* modName) { temp[0] = '\n'; memcpy(temp + 1, modName, len); temp[1 + len] = ' '; - return memmem(modules.chars, modules.length, temp, len + 2) != NULL; + return memmem(modules.chars, modules.length, temp, len + 2) != nullptr; } diff --git a/src/common/impl/kmod_nbsd.c b/src/common/impl/kmod_nbsd.c index f1b450a9bd..2352bb52c4 100644 --- a/src/common/impl/kmod_nbsd.c +++ b/src/common/impl/kmod_nbsd.c @@ -4,15 +4,15 @@ #include #include -typedef struct FF_A_PACKED FFNbsdModList { +typedef struct [[gnu::packed]] FFNbsdModList { int len; modstat_t mods[]; } FFNbsdModList; bool ffKmodLoaded(const char* modName) { - static FFNbsdModList* list = NULL; + static FFNbsdModList* list = nullptr; - if (list == NULL) { + if (list == nullptr) { struct iovec iov = {}; for (size_t len = 8192;; len = iov.iov_len) { diff --git a/src/common/impl/kmod_nosupport.c b/src/common/impl/kmod_nosupport.c index c254ba7b21..6335a7fd1f 100644 --- a/src/common/impl/kmod_nosupport.c +++ b/src/common/impl/kmod_nosupport.c @@ -1,5 +1,5 @@ #include "common/kmod.h" -bool ffKmodLoaded(FF_A_UNUSED const char* modName) { +bool ffKmodLoaded([[maybe_unused]] const char* modName) { return true; // Don't generate kernel module related errors } diff --git a/src/common/impl/kmod_windows.c b/src/common/impl/kmod_windows.c index 081e5a788c..be3ec1b489 100644 --- a/src/common/impl/kmod_windows.c +++ b/src/common/impl/kmod_windows.c @@ -5,7 +5,7 @@ bool ffKmodLoaded(const char* modName) { ULONG bufferSize = 0; - NtQuerySystemInformation(SystemModuleInformation, NULL, 0, &bufferSize); + NtQuerySystemInformation(SystemModuleInformation, nullptr, 0, &bufferSize); if (bufferSize == 0) { return true; // ignore errors } diff --git a/src/common/impl/library.c b/src/common/impl/library.c index c16e0b11d8..440ea1336a 100644 --- a/src/common/impl/library.c +++ b/src/common/impl/library.c @@ -35,7 +35,7 @@ void* ffLibraryLoadSingle(const char* path, int maxVersion) { // libX.dll.1 never exists on Windows, while libX-1.dll may exist FF_UNUSED(maxVersion) - if (result != NULL) { + if (result != nullptr) { return result; } @@ -50,11 +50,11 @@ void* ffLibraryLoadSingle(const char* path, int maxVersion) { #else - if (result == NULL) { + if (result == nullptr) { FF_DEBUG("dlopen(\"%s\"): %s", path, dlerror()); } - if (result != NULL || maxVersion < 0) { + if (result != nullptr || maxVersion < 0) { return result; } @@ -67,7 +67,7 @@ void* ffLibraryLoadSingle(const char* path, int maxVersion) { ffStrbufAppendSInt(&pathbuf, i); result = dlopen(pathbuf.chars, FF_DLOPEN_FLAGS); - if (result != NULL) { + if (result != nullptr) { break; } else { FF_DEBUG("dlopen(\"%s\"): %s", pathbuf.chars, dlerror()); @@ -90,7 +90,7 @@ void* ffLibraryLoadMulti(const char* path, int maxVersion, ...) { do { const char* pathRest = va_arg(defaultNames, const char*); - if (pathRest == NULL) { + if (pathRest == nullptr) { break; } @@ -108,18 +108,18 @@ void* ffLibraryLoadMulti(const char* path, int maxVersion, ...) { #if _WIN32 -void* dlopen(const char* path, FF_A_UNUSED int mode) { +void* dlopen(const char* path, [[maybe_unused]] int mode) { wchar_t pathW[MAX_PATH + 1]; ULONG pathWBytes = 0; NTSTATUS status = RtlUTF8ToUnicodeN(pathW, sizeof(pathW), &pathWBytes, path, (uint32_t) strlen(path) + 1); if (!NT_SUCCESS(status)) { FF_DEBUG("RtlUTF8ToUnicodeN failed for path %s with status 0x%08lX: %s", path, status, ffDebugNtStatus(status)); - return NULL; + return nullptr; } - PVOID module = NULL; - status = LdrLoadDll(NULL, NULL, &(UNICODE_STRING) { + PVOID module = nullptr; + status = LdrLoadDll(nullptr, nullptr, &(UNICODE_STRING) { .Length = (USHORT) (pathWBytes - sizeof(wchar_t)), // Exclude null terminator .MaximumLength = (USHORT) pathWBytes, .Buffer = pathW, @@ -128,7 +128,7 @@ void* dlopen(const char* path, FF_A_UNUSED int mode) { if (!NT_SUCCESS(status)) { FF_DEBUG("LdrLoadDll failed for path %s with status 0x%08lX: %s", path, status, ffDebugNtStatus(status)); - return NULL; + return nullptr; } return module; @@ -155,17 +155,17 @@ void* dlsym(void* handle, const char* symbol) { &address); if (!NT_SUCCESS(status)) { FF_DEBUG("LdrGetProcedureAddress failed for symbol %s with status 0x%08lX: %s", symbol, status, ffDebugNtStatus(status)); - return NULL; + return nullptr; } return address; } void* ffLibraryGetModule(const wchar_t* libraryFileName) { - assert(libraryFileName != NULL && "Use \"ffGetPeb()->ImageBaseAddress\" instead"); + assert(libraryFileName != nullptr && "Use \"ffGetPeb()->ImageBaseAddress\" instead"); - void* module = NULL; + void* module = nullptr; USHORT libraryFileNameBytes = (USHORT) (wcslen(libraryFileName) * sizeof(wchar_t) + sizeof(wchar_t)); - NTSTATUS status = LdrGetDllHandle(NULL, NULL, &(UNICODE_STRING) { + NTSTATUS status = LdrGetDllHandle(nullptr, nullptr, &(UNICODE_STRING) { .Length = libraryFileNameBytes - sizeof(wchar_t), .MaximumLength = libraryFileNameBytes, .Buffer = (wchar_t*) libraryFileName, @@ -173,7 +173,7 @@ void* ffLibraryGetModule(const wchar_t* libraryFileName) { &module); if (!NT_SUCCESS(status)) { FF_DEBUG("LdrGetDllHandle failed for library %ls with status 0x%08lX: %s", libraryFileName, status, ffDebugNtStatus(status)); - return NULL; + return nullptr; } return module; } diff --git a/src/common/impl/lua.c b/src/common/impl/lua.c index ffc1d83c92..871bf43b0c 100644 --- a/src/common/impl/lua.c +++ b/src/common/impl/lua.c @@ -109,7 +109,7 @@ static int yyjsonEncode(lua_State* L) { pretty = (int) lua_toboolean(L, 2); } - yyjson_mut_doc* doc = yyjson_mut_doc_new(NULL); + yyjson_mut_doc* doc = yyjson_mut_doc_new(nullptr); if (__builtin_expect(!doc, false)) { lua_pushlstring(L, "yyjson: yyjson_mut_doc_new() failed", strlen("yyjson: yyjson_mut_doc_new() failed")); return lua_error(L); @@ -120,9 +120,9 @@ static int yyjsonEncode(lua_State* L) { size_t jsonLen; yyjson_write_err err = {}; - FF_AUTO_FREE const char* jsonStr = yyjson_mut_write_opts(doc, YYJSON_WRITE_ALLOW_INF_AND_NAN | (pretty ? YYJSON_WRITE_PRETTY_TWO_SPACES : 0), NULL, &jsonLen, &err); + FF_AUTO_FREE const char* jsonStr = yyjson_mut_write_opts(doc, YYJSON_WRITE_ALLOW_INF_AND_NAN | (pretty ? YYJSON_WRITE_PRETTY_TWO_SPACES : 0), nullptr, &jsonLen, &err); - if (__builtin_expect(jsonStr != NULL, true)) { + if (__builtin_expect(jsonStr != nullptr, true)) { lua_pushlstring(L, jsonStr, jsonLen); yyjson_mut_doc_free(doc); return 1; @@ -140,10 +140,10 @@ static int yyjsonEncode(lua_State* L) { const char* ffLuaLoadState(void) { if (luaData.inited) { - if (luaData.L == NULL) { + if (luaData.L == nullptr) { return "Lua library is not available"; } - return NULL; + return nullptr; } luaData.inited = true; @@ -211,7 +211,7 @@ const char* ffLuaLoadState(void) { #endif lua_State* L = ffluaL_newstate(); - if (L == NULL) { + if (L == nullptr) { return "luaL_newstate() failed"; } #if LUA_VERSION_NUM >= 505 @@ -226,8 +226,8 @@ const char* ffLuaLoadState(void) { lua_pushcfunction(L, yyjsonEncode); lua_setglobal(L, "json_encode"); luaData.L = L; - liblua = NULL; // don't close lua - return NULL; + liblua = nullptr; // don't close lua + return nullptr; } #endif diff --git a/src/common/impl/memrchr.c b/src/common/impl/memrchr.c index aaf97e604a..4acca548d9 100644 --- a/src/common/impl/memrchr.c +++ b/src/common/impl/memrchr.c @@ -4,7 +4,7 @@ void* memrchr(const void* s, int c, size_t n) { if (n == 0) { - return NULL; + return nullptr; } const uint8_t uc = (uint8_t) c; @@ -17,5 +17,5 @@ void* memrchr(const void* s, int c, size_t n) { } } - return NULL; + return nullptr; } diff --git a/src/common/impl/netif_apple.c b/src/common/impl/netif_apple.c index 2d42735ffd..ed2fb56155 100644 --- a/src/common/impl/netif_apple.c +++ b/src/common/impl/netif_apple.c @@ -52,7 +52,7 @@ get_rt_address(struct rt_msghdr* rtm, int desired) { sa = (struct sockaddr*) (ROUNDUP(salen) + (char*) sa); } } - return NULL; + return nullptr; } bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result) { diff --git a/src/common/impl/netif_bsd.c b/src/common/impl/netif_bsd.c index 2b59c6d533..b81bbfe78f 100644 --- a/src/common/impl/netif_bsd.c +++ b/src/common/impl/netif_bsd.c @@ -39,20 +39,20 @@ get_rt_address(struct rt_msghdr* rtm, int desired) { sa = (struct sockaddr*) (ROUNDUP(sa->sa_len) + (char*) sa); } } - return NULL; + return nullptr; } bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result) { int mib[6] = { CTL_NET, PF_ROUTE, 0, AF_INET, NET_RT_FLAGS, RTF_GATEWAY }; size_t needed; - if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0 || needed == 0) { + if (sysctl(mib, 6, nullptr, &needed, nullptr, 0) < 0 || needed == 0) { return false; } FF_AUTO_FREE char* buf = malloc(needed); - if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0) { + if (sysctl(mib, 6, buf, &needed, nullptr, 0) < 0) { return false; } @@ -89,13 +89,13 @@ bool ffNetifGetDefaultRouteImplV6(FFNetifDefaultRouteResult* result) { int mib[6] = { CTL_NET, PF_ROUTE, 0, AF_INET6, NET_RT_FLAGS, RTF_GATEWAY }; size_t needed; - if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0 || needed == 0) { + if (sysctl(mib, 6, nullptr, &needed, nullptr, 0) < 0 || needed == 0) { return false; } FF_AUTO_FREE char* buf = malloc(needed); - if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0) { + if (sysctl(mib, 6, buf, &needed, nullptr, 0) < 0) { return false; } diff --git a/src/common/impl/netif_gnu.c b/src/common/impl/netif_gnu.c index 6593899a65..5e890dda0b 100644 --- a/src/common/impl/netif_gnu.c +++ b/src/common/impl/netif_gnu.c @@ -6,7 +6,7 @@ #include bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result) { - FILE* FF_AUTO_CLOSE_FILE netRoute = fopen("/proc/route", "r"); + FF_AUTO_CLOSE_FILE FILE* netRoute = fopen("/proc/route", "r"); if (!netRoute) { return false; diff --git a/src/common/impl/netif_haiku.c b/src/common/impl/netif_haiku.c index a32138c68e..73782d919b 100644 --- a/src/common/impl/netif_haiku.c +++ b/src/common/impl/netif_haiku.c @@ -29,7 +29,7 @@ bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result) { } FF_AUTO_FREE void* buffer = malloc((size_t) size); - if (buffer == NULL) { + if (buffer == nullptr) { return false; } @@ -54,13 +54,13 @@ bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result) { } size_t addressSize = 0; - if (interface->ifr_route.destination != NULL) { + if (interface->ifr_route.destination != nullptr) { addressSize += interface->ifr_route.destination->sa_len; } - if (interface->ifr_route.mask != NULL) { + if (interface->ifr_route.mask != nullptr) { addressSize += interface->ifr_route.mask->sa_len; } - if (interface->ifr_route.gateway != NULL) { + if (interface->ifr_route.gateway != nullptr) { addressSize += interface->ifr_route.gateway->sa_len; } @@ -88,7 +88,7 @@ bool ffNetifGetDefaultRouteImplV6(FFNetifDefaultRouteResult* result) { } FF_AUTO_FREE void* buffer = malloc((size_t) size); - if (buffer == NULL) { + if (buffer == nullptr) { return false; } @@ -109,13 +109,13 @@ bool ffNetifGetDefaultRouteImplV6(FFNetifDefaultRouteResult* result) { } size_t addressSize = 0; - if (interface->ifr_route.destination != NULL) { + if (interface->ifr_route.destination != nullptr) { addressSize += interface->ifr_route.destination->sa_len; } - if (interface->ifr_route.mask != NULL) { + if (interface->ifr_route.mask != nullptr) { addressSize += interface->ifr_route.mask->sa_len; } - if (interface->ifr_route.gateway != NULL) { + if (interface->ifr_route.gateway != nullptr) { addressSize += interface->ifr_route.gateway->sa_len; } diff --git a/src/common/impl/netif_linux.c b/src/common/impl/netif_linux.c index 67e4868212..623cc0ec8b 100644 --- a/src/common/impl/netif_linux.c +++ b/src/common/impl/netif_linux.c @@ -44,7 +44,7 @@ bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result) { uint32_t pid = ffNetifGetNetlinkPortId(sock_fd); - struct FF_A_PACKED { + struct [[gnu::packed]] { struct nlmsghdr nlh; struct rtmsg rtm; struct rtattr rta; @@ -97,7 +97,7 @@ bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result) { uint8_t buffer[1024 * 16]; // 16 KB buffer should be sufficient uint32_t minMetric = UINT32_MAX; - FF_A_UNUSED int routeCount = 0; + [[maybe_unused]] int routeCount = 0; while (true) { ssize_t received = recvfrom(sock_fd, buffer, sizeof(buffer), 0, (struct sockaddr*) &src_addr, &src_addr_len); @@ -163,7 +163,7 @@ bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result) { } FF_DEBUG("Processing IPv4 default route candidate #%d", routeCount); - entry = (__typeof__(entry)) {}; // Default to zero metric (no RTA_PRIORITY found) + entry = (typeof(entry)) {}; // Default to zero metric (no RTA_PRIORITY found) // Parse route attributes size_t rtm_len = RTM_PAYLOAD(nlh); @@ -254,7 +254,7 @@ bool ffNetifGetDefaultRouteImplV6(FFNetifDefaultRouteResult* result) { uint32_t pid = ffNetifGetNetlinkPortId(sock_fd); - struct FF_A_PACKED { + struct [[gnu::packed]] { struct nlmsghdr nlh; struct rtmsg rtm; struct rtattr rta; @@ -307,7 +307,7 @@ bool ffNetifGetDefaultRouteImplV6(FFNetifDefaultRouteResult* result) { uint8_t buffer[1024 * 16]; // 16 KB buffer should be sufficient uint32_t minMetric = UINT32_MAX; - FF_A_UNUSED int routeCount = 0; + [[maybe_unused]] int routeCount = 0; while (true) { ssize_t received = recvfrom(sock_fd, buffer, sizeof(buffer), 0, (struct sockaddr*) &src_addr, &src_addr_len); @@ -372,7 +372,7 @@ bool ffNetifGetDefaultRouteImplV6(FFNetifDefaultRouteResult* result) { } FF_DEBUG("Processing IPv6 default route candidate #%d", routeCount); - entry = (__typeof__(entry)) {}; // Default to zero metric (no RTA_PRIORITY found) + entry = (typeof(entry)) {}; // Default to zero metric (no RTA_PRIORITY found) // Parse route attributes size_t rtm_len = RTM_PAYLOAD(nlh); @@ -382,7 +382,7 @@ bool ffNetifGetDefaultRouteImplV6(FFNetifDefaultRouteResult* result) { switch (rta->rta_type) { case RTA_DST: if (RTA_PAYLOAD(rta) >= sizeof(struct in6_addr)) { - FF_A_UNUSED char str[INET6_ADDRSTRLEN]; + [[maybe_unused]] char str[INET6_ADDRSTRLEN]; FF_DEBUG("Unexpected RTA_DST: %s", inet_ntop(AF_INET6, RTA_DATA(rta), str, sizeof(str))); goto next; } @@ -399,7 +399,7 @@ bool ffNetifGetDefaultRouteImplV6(FFNetifDefaultRouteResult* result) { if (IN6_IS_ADDR_UNSPECIFIED(gw)) { goto next; } - FF_A_UNUSED char str[INET6_ADDRSTRLEN]; + [[maybe_unused]] char str[INET6_ADDRSTRLEN]; FF_DEBUG("Found gateway: %s", inet_ntop(AF_INET6, gw, str, sizeof(str))); } break; diff --git a/src/common/impl/netif_windows.c b/src/common/impl/netif_windows.c index 7531ae0640..9a21678e06 100644 --- a/src/common/impl/netif_windows.c +++ b/src/common/impl/netif_windows.c @@ -4,7 +4,7 @@ #include bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result) { - PMIB_IPFORWARD_TABLE2 pIpForwardTable = NULL; + PMIB_IPFORWARD_TABLE2 pIpForwardTable = nullptr; if (!NETIO_SUCCESS(GetIpForwardTable2(AF_INET, &pIpForwardTable))) { return false; @@ -48,7 +48,7 @@ bool ffNetifGetDefaultRouteImplV4(FFNetifDefaultRouteResult* result) { } bool ffNetifGetDefaultRouteImplV6(FFNetifDefaultRouteResult* result) { - PMIB_IPFORWARD_TABLE2 pIpForwardTable = NULL; + PMIB_IPFORWARD_TABLE2 pIpForwardTable = nullptr; if (!NETIO_SUCCESS(GetIpForwardTable2(AF_INET6, &pIpForwardTable))) { return false; diff --git a/src/common/impl/networking_common.c b/src/common/impl/networking_common.c index e63979bf27..2c436590e8 100644 --- a/src/common/impl/networking_common.c +++ b/src/common/impl/networking_common.c @@ -29,9 +29,9 @@ const char* ffNetworkingLoadZlibLibrary(void) { FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(zlib, zlibData, inflateInit2_) FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(zlib, zlibData, inflate) FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(zlib, zlibData, inflateEnd) - zlib = NULL; // don't auto dlclose + zlib = nullptr; // don't auto dlclose } - return zlibData.ffinflateEnd == NULL ? "Failed to load libz" : NULL; + return zlibData.ffinflateEnd == nullptr ? "Failed to load libz" : nullptr; } // Try to pre-read gzip header to determine uncompressed size @@ -64,14 +64,14 @@ static uint32_t guessGzipOutputSize(const void* data, uint32_t dataSize) { // Decompress gzip content bool ffNetworkingDecompressGzip(FFstrbuf* buffer, char* headerEnd) { - assert(headerEnd != NULL && *headerEnd == '\r'); + assert(headerEnd != nullptr && *headerEnd == '\r'); // Calculate header size uint32_t headerSize = (uint32_t) (headerEnd - buffer->chars); *headerEnd = '\0'; // Replace delimiter with null character for easier processing // Ensure Content-Encoding is in response headers, not in response body - bool hasGzip = strcasestr(buffer->chars, "\nContent-Encoding: gzip") != NULL; + bool hasGzip = strcasestr(buffer->chars, "\nContent-Encoding: gzip") != nullptr; *headerEnd = '\r'; // Restore delimiter if (!hasGzip) { @@ -165,7 +165,7 @@ bool ffNetworkingDecompressGzip(FFstrbuf* buffer, char* headerEnd) { // Use decompressedBuffer.length (total) not decompressedSize (last chunk only) FF_STRBUF_AUTO_DESTROY newBuffer = ffStrbufCreateA(headerSize + decompressedBuffer.length + 64); - char* line = NULL; + char* line = nullptr; size_t len = 0; while (ffStrbufGetline(&line, &len, buffer)) { if (ffStrStartsWithIgnCase(line, "Content-Encoding:")) { diff --git a/src/common/impl/networking_linux.c b/src/common/impl/networking_linux.c index 7e40567927..770c0ce774 100644 --- a/src/common/impl/networking_linux.c +++ b/src/common/impl/networking_linux.c @@ -97,7 +97,7 @@ static const char* tryNonThreadingFastPath(FFNetworkingState* state) { }, 1, &sent, - NULL) != 0) { + nullptr) != 0) { sent = 0; } if (fcntl(state->sockfd, F_SETFL, 0) == -1) { @@ -123,9 +123,9 @@ static const char* tryNonThreadingFastPath(FFNetworkingState* state) { sent, strerror(errno)); freeaddrinfo(state->addr); - state->addr = NULL; + state->addr = nullptr; ffStrbufDestroy(&state->command); - return NULL; + return nullptr; } FF_DEBUG( @@ -149,7 +149,7 @@ static const char* tryNonThreadingFastPath(FFNetworkingState* state) { // Traditional connect and send function static const char* connectAndSend(FFNetworkingState* state) { - const char* ret = NULL; + const char* ret = nullptr; FF_DEBUG("Using traditional connection method to connect"); FF_DEBUG("Attempting connect() to server..."); @@ -178,7 +178,7 @@ static const char* connectAndSend(FFNetworkingState* state) { exit: FF_DEBUG("Releasing address info and other resources"); freeaddrinfo(state->addr); - state->addr = NULL; + state->addr = nullptr; ffStrbufDestroy(&state->command); return ret; @@ -212,7 +212,7 @@ static const char* initNetworkingState(FFNetworkingState* state, const char* hos FF_DEBUG("Thread ID initialized to 0"); #endif - const char* ret = NULL; + const char* ret = nullptr; struct addrinfo hints = { .ai_family = state->ipv6 ? AF_INET6 : AF_INET, @@ -261,7 +261,7 @@ static const char* initNetworkingState(FFNetworkingState* state, const char* hos if (state->timeout > 0) { FF_DEBUG("Setting connection timeout: %u ms", state->timeout); - FF_A_UNUSED uint32_t sec = state->timeout / 1000; + [[maybe_unused]] uint32_t sec = state->timeout / 1000; if (sec == 0) { sec = 1; } @@ -280,14 +280,14 @@ static const char* initNetworkingState(FFNetworkingState* state, const char* hos #endif } - return NULL; + return nullptr; error: FF_DEBUG("Error occurred during initialization"); - if (state->addr != NULL) { + if (state->addr != nullptr) { FF_DEBUG("Releasing address information"); freeaddrinfo(state->addr); - state->addr = NULL; + state->addr = nullptr; } if (state->sockfd > 0) { @@ -307,7 +307,7 @@ const char* ffNetworkingSendHttpRequest(FFNetworkingState* state, const char* ho #ifdef FF_HAVE_ZLIB const char* zlibError = ffNetworkingLoadZlibLibrary(); // Only enable compression if zlib library is successfully loaded - if (zlibError == NULL) { + if (zlibError == nullptr) { FF_DEBUG("Successfully loaded zlib library, compression enabled"); } else { FF_DEBUG("Failed to load zlib library, compression disabled: %s", zlibError); @@ -322,16 +322,16 @@ const char* ffNetworkingSendHttpRequest(FFNetworkingState* state, const char* ho } const char* initResult = initNetworkingState(state, host, path, headers); - if (initResult != NULL) { + if (initResult != nullptr) { FF_DEBUG("Initialization failed: %s", initResult); return initResult; } FF_DEBUG("Network state initialization successful"); const char* tfoResult = tryNonThreadingFastPath(state); - if (tfoResult == NULL) { + if (tfoResult == nullptr) { FF_DEBUG("TryNonThreadingFastPath() succeeded or in progress"); - return NULL; + return nullptr; } FF_DEBUG("TryNonThreadingFastPath() failed: %s, trying traditional connection", tfoResult); @@ -341,7 +341,7 @@ const char* ffNetworkingSendHttpRequest(FFNetworkingState* state, const char* ho state->thread = ffThreadCreate(connectAndSendThreadMain, state); if (state->thread) { FF_DEBUG("Thread creation successful: thread=%p", (void*) (uintptr_t) state->thread); - return NULL; + return nullptr; } FF_DEBUG("Thread creation failed"); } else { @@ -406,7 +406,7 @@ const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buf FF_DEBUG("Setting receive timeout: %u ms", timeout); struct timeval timev; timev.tv_sec = timeout / 1000; - timev.tv_usec = (__typeof__(timev.tv_usec)) ((timeout % 1000) * 1000); // milliseconds to microseconds + timev.tv_usec = (typeof(timev.tv_usec)) ((timeout % 1000) * 1000); // milliseconds to microseconds setsockopt(state->sockfd, SOL_SOCKET, SO_RCVTIMEO, &timev, sizeof(timev)); } #endif @@ -417,7 +417,7 @@ const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buf } FF_DEBUG("Starting data reception"); - FF_A_UNUSED int recvCount = 0; + [[maybe_unused]] int recvCount = 0; uint32_t contentLength = 0; uint32_t headerEnd = 0; @@ -455,8 +455,15 @@ const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buf // Check for Content-Length header to pre-allocate enough memory const char* clHeader = strcasestr(buffer->chars, "Content-Length:"); if (clHeader) { - contentLength = (uint32_t) strtoul(clHeader + 15, NULL, 10); + contentLength = (uint32_t) strtoul(clHeader + 15, nullptr, 10); if (contentLength > 0) { + if (contentLength > 1024 * 1024) { // 1MB limit to prevent excessive memory allocation and potential attacks + FF_DEBUG("Content-Length is too large: %u bytes, aborting", contentLength); + close(state->sockfd); + state->sockfd = -1; + return "Content-Length too large"; + } + FF_DEBUG("Detected Content-Length: %u, pre-allocating buffer", contentLength); // Ensure buffer is large enough, adding header size and some margin ffStrbufEnsureFree(buffer, contentLength + 16); @@ -481,7 +488,7 @@ const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buf return "No HTTP header end found"; } - if (!ffStrbufStartsWithS(buffer, "HTTP/1.0 200 OK\r\n")) { + if (!ffStrbufStartsWithS(buffer, "HTTP/1.0 200 OK\r\n") && !ffStrbufStartsWithS(buffer, "HTTP/1.1 200 OK\r\n")) { FF_DEBUG("Invalid response: %.40s...", buffer->chars); return "Invalid response"; } @@ -505,5 +512,5 @@ const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buf } #endif - return NULL; + return nullptr; } diff --git a/src/common/impl/networking_windows.c b/src/common/impl/networking_windows.c index d3a7752285..409edff7e5 100644 --- a/src/common/impl/networking_windows.c +++ b/src/common/impl/networking_windows.c @@ -23,7 +23,7 @@ static const char* initWsaData(WSADATA* wsaData) { } // Dummy socket needed for WSAIoctl - SOCKET sockfd = WSASocketW(AF_INET, SOCK_STREAM, 0, NULL, 0, 0); + SOCKET sockfd = WSASocketW(AF_INET, SOCK_STREAM, 0, nullptr, 0, 0); if (sockfd == INVALID_SOCKET) { FF_DEBUG("WSASocketW(AF_INET, SOCK_STREAM) failed"); WSACleanup(); @@ -32,7 +32,7 @@ static const char* initWsaData(WSADATA* wsaData) { DWORD dwBytes; GUID guid = WSAID_CONNECTEX; - if (WSAIoctl(sockfd, SIO_GET_EXTENSION_FUNCTION_POINTER, &guid, sizeof(guid), &ConnectEx, sizeof(ConnectEx), &dwBytes, NULL, NULL) != 0) { + if (WSAIoctl(sockfd, SIO_GET_EXTENSION_FUNCTION_POINTER, &guid, sizeof(guid), &ConnectEx, sizeof(ConnectEx), &dwBytes, nullptr, nullptr) != 0) { FF_DEBUG("WSAIoctl(sockfd, SIO_GET_EXTENSION_FUNCTION_POINTER) failed"); closesocket(sockfd); WSACleanup(); @@ -42,7 +42,7 @@ static const char* initWsaData(WSADATA* wsaData) { closesocket(sockfd); FF_DEBUG("WinSock initialized successfully"); - return NULL; + return nullptr; } const char* ffNetworkingSendHttpRequest(FFNetworkingState* state, const char* host, const char* path, const char* headers) { @@ -52,7 +52,7 @@ const char* ffNetworkingSendHttpRequest(FFNetworkingState* state, const char* ho #ifdef FF_HAVE_ZLIB const char* zlibError = ffNetworkingLoadZlibLibrary(); // Only enable compression if zlib library is successfully loaded - if (zlibError == NULL) { + if (zlibError == nullptr) { FF_DEBUG("Successfully loaded zlib library, compression enabled"); } else { FF_DEBUG("Failed to load zlib library, compression disabled: %s", zlibError); @@ -69,7 +69,7 @@ const char* ffNetworkingSendHttpRequest(FFNetworkingState* state, const char* ho static WSADATA wsaData; if (wsaData.wVersion == 0) { const char* error = initWsaData(&wsaData); - if (error != NULL) { + if (error != nullptr) { wsaData.wVersion = (WORD) -1; FF_DEBUG("WinSock initialization failed: %s", error); return error; @@ -87,7 +87,7 @@ const char* ffNetworkingSendHttpRequest(FFNetworkingState* state, const char* ho }; wchar_t hostW[256]; - if (!NT_SUCCESS(RtlUTF8ToUnicodeN(hostW, (ULONG) sizeof(hostW), NULL, host, (ULONG) strlen(host) + 1))) { + if (!NT_SUCCESS(RtlUTF8ToUnicodeN(hostW, (ULONG) sizeof(hostW), nullptr, host, (ULONG) strlen(host) + 1))) { FF_DEBUG("Failed to convert host to wide string: %s", host); return "Failed to convert host to wide string"; } @@ -98,7 +98,7 @@ const char* ffNetworkingSendHttpRequest(FFNetworkingState* state, const char* ho return "GetAddrInfoW() failed"; } - state->sockfd = WSASocketW(addr->ai_family, addr->ai_socktype, addr->ai_protocol, NULL, 0, 0); + state->sockfd = WSASocketW(addr->ai_family, addr->ai_socktype, addr->ai_protocol, nullptr, 0, 0); if (state->sockfd == INVALID_SOCKET) { FF_DEBUG("WSASocketW() failed"); FreeAddrInfoW(addr); @@ -141,16 +141,14 @@ const char* ffNetworkingSendHttpRequest(FFNetworkingState* state, const char* ho } // Initialize overlapped structure with WSA event for asynchronous I/O - state->overlapped = (OVERLAPPED) { - .hEvent = WSACreateEvent() - }; + state->overlapped = (OVERLAPPED) {}; - if (state->overlapped.hEvent == WSA_INVALID_EVENT) { - FF_DEBUG("WSACreateEvent() failed"); + if (!NT_SUCCESS(NtCreateEvent(&state->overlapped.hEvent, EVENT_ALL_ACCESS, nullptr, NotificationEvent, FALSE))) { + FF_DEBUG("NtCreateEvent() failed"); closesocket(state->sockfd); FreeAddrInfoW(addr); state->sockfd = INVALID_SOCKET; - return "WSACreateEvent() failed"; + return "NtCreateEvent() failed"; } // Build HTTP command @@ -189,12 +187,12 @@ const char* ffNetworkingSendHttpRequest(FFNetworkingState* state, const char* ho BOOL result = ConnectEx(state->sockfd, addr->ai_addr, (int) addr->ai_addrlen, state->command.chars, state->command.length, &sent, &state->overlapped); FreeAddrInfoW(addr); - addr = NULL; + addr = nullptr; if (!result) { if (WSAGetLastError() != WSA_IO_PENDING) { FF_DEBUG("ConnectEx() failed: %s", ffDebugWin32Error((DWORD) WSAGetLastError())); - WSACloseEvent(state->overlapped.hEvent); + NtClose(state->overlapped.hEvent); closesocket(state->sockfd); state->sockfd = INVALID_SOCKET; ffStrbufDestroy(&state->command); @@ -207,7 +205,7 @@ const char* ffNetworkingSendHttpRequest(FFNetworkingState* state, const char* ho } // No need to cleanup state fields here since we need them in the receive function - return NULL; + return nullptr; } const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buffer) { @@ -219,40 +217,30 @@ const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buf return "ffNetworkingSendHttpRequest() failed"; } + DWORD transfer; uint32_t timeout = state->timeout; - if (timeout > 0) { - FF_DEBUG("WSAWaitForMultipleEvents with timeout: %u ms", timeout); - DWORD result = WSAWaitForMultipleEvents(1, &state->overlapped.hEvent, TRUE, timeout, FALSE); - if (result != WSA_WAIT_EVENT_0) { - if (result == WSA_WAIT_TIMEOUT) { - FF_DEBUG("WSAWaitForMultipleEvents timed out"); - } else { - FF_DEBUG("WSAWaitForMultipleEvents failed: %s", ffDebugWin32Error((DWORD) WSAGetLastError())); - } - if (CancelIoEx((HANDLE) state->sockfd, &state->overlapped)) { - WSAWaitForMultipleEvents(1, &state->overlapped.hEvent, TRUE, 10, TRUE); - } - WSACloseEvent(state->overlapped.hEvent); - closesocket(state->sockfd); - ffStrbufDestroy(&state->command); - return "WSAWaitForMultipleEvents() failed or timeout"; + if (!GetOverlappedResultEx((HANDLE) state->sockfd, &state->overlapped, &transfer, timeout > 0 ? timeout : INFINITE, FALSE)) { + DWORD error = GetLastError(); + if (error == WAIT_TIMEOUT) { + FF_DEBUG("GetOverlappedResultEx timed out"); + } else { + FF_DEBUG("GetOverlappedResultEx failed: %s", ffDebugWin32Error(error)); } - } - - DWORD transfer, flags; - if (!WSAGetOverlappedResult(state->sockfd, &state->overlapped, &transfer, TRUE, &flags)) { - FF_DEBUG("WSAGetOverlappedResult failed: %s", ffDebugWin32Error((DWORD) WSAGetLastError())); + IO_STATUS_BLOCK cancelIosb = {}; + if (NT_SUCCESS(NtCancelIoFileEx((HANDLE) state->sockfd, (PIO_STATUS_BLOCK) &state->overlapped, &cancelIosb))) { + NtWaitForSingleObject(state->overlapped.hEvent, TRUE, &(LARGE_INTEGER) { .QuadPart = (int64_t) 10 * -10000 }); + } + NtClose(state->overlapped.hEvent); closesocket(state->sockfd); - WSACloseEvent(state->overlapped.hEvent); ffStrbufDestroy(&state->command); - return "WSAGetOverlappedResult() failed"; + return "GetOverlappedResultEx() failed or timeout"; } - FF_DEBUG("WSAGetOverlappedResult succeeded, %u bytes sent", (unsigned) transfer); + FF_DEBUG("GetOverlappedResultEx succeeded, %u bytes sent", (unsigned) transfer); ffStrbufDestroy(&state->command); - WSACloseEvent(state->overlapped.hEvent); - state->overlapped.hEvent = NULL; + NtClose(state->overlapped.hEvent); + state->overlapped.hEvent = nullptr; - if (setsockopt(state->sockfd, SOL_SOCKET, SO_UPDATE_CONNECT_CONTEXT, NULL, 0) != 0) { + if (setsockopt(state->sockfd, SOL_SOCKET, SO_UPDATE_CONNECT_CONTEXT, nullptr, 0) != 0) { FF_DEBUG("Failed to update connect context: %s", ffDebugWin32Error((DWORD) WSAGetLastError())); // Not a critical error, continue anyway } @@ -275,7 +263,7 @@ const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buf } FF_DEBUG("Starting data reception"); - FF_A_UNUSED int recvCount = 0; + [[maybe_unused]] int recvCount = 0; uint32_t contentLength = 0; uint32_t headerEnd = 0; @@ -293,8 +281,8 @@ const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buf 1, &received, &recvFlags, - NULL, - NULL); + nullptr, + nullptr); if (recvResult == SOCKET_ERROR || received == 0) { if (recvResult == 0 && received == 0) { @@ -320,8 +308,15 @@ const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buf // Check for Content-Length header to pre-allocate enough memory const char* clHeader = strcasestr(buffer->chars, "Content-Length:"); if (clHeader) { - contentLength = (uint32_t) strtoul(clHeader + 15, NULL, 10); + contentLength = (uint32_t) strtoul(clHeader + 15, nullptr, 10); if (contentLength > 0) { + if (contentLength > 1024 * 1024) { // 1MB limit to prevent excessive memory allocation and potential attacks + FF_DEBUG("Content-Length is too large: %u bytes, aborting", contentLength); + closesocket(state->sockfd); + state->sockfd = INVALID_SOCKET; + return "Content-Length too large"; + } + FF_DEBUG("Detected Content-Length: %u, pre-allocating buffer", contentLength); // Ensure buffer is large enough, adding header size and some margin ffStrbufEnsureFree(buffer, contentLength + 16); @@ -346,7 +341,7 @@ const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buf return "No HTTP header end found"; } - if (!ffStrbufStartsWithS(buffer, "HTTP/1.0 200 OK\r\n")) { + if (!ffStrbufStartsWithS(buffer, "HTTP/1.0 200 OK\r\n") && !ffStrbufStartsWithS(buffer, "HTTP/1.1 200 OK\r\n")) { FF_DEBUG("Invalid response: %.40s...", buffer->chars); return "Invalid response"; } @@ -372,5 +367,5 @@ const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buf } #endif - return NULL; + return nullptr; } diff --git a/src/common/impl/option.c b/src/common/impl/option.c index 3d592d0ec1..87b004aea2 100644 --- a/src/common/impl/option.c +++ b/src/common/impl/option.c @@ -5,19 +5,19 @@ #include -// Return start position of the inner key if the argument key belongs to the module specified, NULL otherwise +// Return start position of the inner key if the argument key belongs to the module specified, nullptr otherwise const char* ffOptionTestPrefix(const char* argumentKey, const char* moduleName) { assert(argumentKey && moduleName); const char* subKey = argumentKey; if (!(subKey[0] == '-' && subKey[1] == '-')) { - return NULL; + return nullptr; } subKey += 2; uint32_t moduleNameLen = (uint32_t) strlen(moduleName); if (strncasecmp(subKey, moduleName, moduleNameLen) != 0) { - return NULL; + return nullptr; } subKey += moduleNameLen; @@ -27,7 +27,7 @@ const char* ffOptionTestPrefix(const char* argumentKey, const char* moduleName) } if (subKey[0] != '-') { - return NULL; + return nullptr; } subKey += 1; @@ -36,7 +36,7 @@ const char* ffOptionTestPrefix(const char* argumentKey, const char* moduleName) } void ffOptionParseString(const char* argumentKey, const char* value, FFstrbuf* buffer) { - if (value == NULL) { + if (value == nullptr) { fprintf(stderr, "Error: usage: %s \n", argumentKey); exit(477); } @@ -45,7 +45,7 @@ void ffOptionParseString(const char* argumentKey, const char* value, FFstrbuf* b } uint32_t ffOptionParseUInt32(const char* argumentKey, const char* value) { - if (value == NULL) { + if (value == nullptr) { fprintf(stderr, "Error: usage: %s \n", argumentKey); exit(480); } @@ -61,7 +61,7 @@ uint32_t ffOptionParseUInt32(const char* argumentKey, const char* value) { } int32_t ffOptionParseInt32(const char* argumentKey, const char* value) { - if (value == NULL) { + if (value == nullptr) { fprintf(stderr, "Error: usage: %s \n", argumentKey); exit(480); } @@ -77,7 +77,7 @@ int32_t ffOptionParseInt32(const char* argumentKey, const char* value) { } int ffOptionParseEnum(const char* argumentKey, const char* requestedKey, FFKeyValuePair pairs[]) { - if (requestedKey == NULL) { + if (requestedKey == nullptr) { fprintf(stderr, "Error: usage: %s \n", argumentKey); exit(476); } @@ -139,7 +139,7 @@ void ffOptionParseColorNoClear(const char* value, FFstrbuf* buffer) { } else if (value[0] == '@') { // Xterm 256 color ++value; - char* pend = NULL; + char* pend = nullptr; uint32_t color = (uint32_t) strtoul(value, &pend, 10); if (pend == value || color > 255) { fprintf(stderr, "Error: invalid 256 color code found: %s\n", value); @@ -153,7 +153,7 @@ void ffOptionParseColorNoClear(const char* value, FFstrbuf* buffer) { } else if (value[0] == '#') { // RGB color ++value; - char* pend = NULL; + char* pend = nullptr; uint32_t rgb = (uint32_t) strtoul(value, &pend, 16); if (pend == value) { fprintf(stderr, "Error: invalid RGB color code found: %s\n", value); diff --git a/src/common/impl/path.c b/src/common/impl/path.c index c97210e969..32e21ca8fb 100644 --- a/src/common/impl/path.c +++ b/src/common/impl/path.c @@ -47,7 +47,7 @@ const char* ffFindExecutableInPath(const char* name, FFstrbuf* result) { } #endif - return NULL; + return nullptr; } ffStrbufClear(result); return "Executable not found"; @@ -60,13 +60,13 @@ const char* ffFindExecutableInPath(const char* name, FFstrbuf* result) { const char* ffFindExecutableInPath(const char* name, FFstrbuf* result) { char buffer[MAX_PATH + 1]; - DWORD length = SearchPathA(NULL, name, ".exe", sizeof(buffer), buffer, NULL); + DWORD length = SearchPathA(nullptr, name, ".exe", sizeof(buffer), buffer, nullptr); if (length == 0) { ffStrbufClear(result); return "Executable not found"; } ffStrbufSetS(result, buffer); - return NULL; + return nullptr; } static inline int winerr2Errno(DWORD err) { @@ -93,7 +93,7 @@ static inline int winerr2Errno(DWORD err) { char* frealpath(HANDLE hFile, char* resolved_name) { if (__builtin_expect(hFile == INVALID_HANDLE_VALUE || !hFile, false)) { errno = EINVAL; - return NULL; + return nullptr; } wchar_t resolvedNameW[MAX_PATH + 4]; /* +4 for "\\\\?\\" prefix */ @@ -101,11 +101,11 @@ char* frealpath(HANDLE hFile, char* resolved_name) { if (lenW == 0) { errno = winerr2Errno(GetLastError()); - return NULL; + return nullptr; } if (lenW >= ARRAY_SIZE(resolvedNameW)) { errno = E2BIG; - return NULL; + return nullptr; } lenW++; // Include null terminator @@ -126,7 +126,7 @@ char* frealpath(HANDLE hFile, char* resolved_name) { ULONG outBytes = 0; if (!NT_SUCCESS(RtlUnicodeToUTF8N(resolved_name, MAX_PATH, &outBytes, srcW, (ULONG) (srcLenW * sizeof(wchar_t))))) { errno = E2BIG; - return NULL; + return nullptr; } } else { /* UTF-8 worst-case: up to 4 bytes per UTF-16 code unit */ @@ -135,13 +135,13 @@ char* frealpath(HANDLE hFile, char* resolved_name) { if (!NT_SUCCESS(RtlUnicodeToUTF8N(tmp, (ULONG) sizeof(tmp), &outBytes, srcW, (ULONG) (srcLenW * sizeof(wchar_t))))) { errno = E2BIG; - return NULL; + return nullptr; } resolved_name = (char*) malloc(outBytes); if (!resolved_name) { errno = ENOMEM; - return NULL; + return nullptr; } memcpy(resolved_name, tmp, outBytes); @@ -153,7 +153,7 @@ char* frealpath(HANDLE hFile, char* resolved_name) { char* realpath(const char* __restrict file_name, char* __restrict resolved_name) { if (!file_name) { errno = EINVAL; - return NULL; + return nullptr; } wchar_t fileNameW[MAX_PATH]; @@ -161,21 +161,21 @@ char* realpath(const char* __restrict file_name, char* __restrict resolved_name) if (!NT_SUCCESS(RtlUTF8ToUnicodeN(fileNameW, (ULONG) sizeof(fileNameW), &lenBytes, file_name, (ULONG) strlen(file_name) + 1))) { errno = EINVAL; - return NULL; + return nullptr; } FF_AUTO_CLOSE_FD HANDLE hFile = CreateFileW( fileNameW, 0, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, - NULL, + nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, - NULL); + nullptr); if (hFile == INVALID_HANDLE_VALUE) { errno = winerr2Errno(GetLastError()); - return NULL; + return nullptr; } return frealpath(hFile, resolved_name); @@ -189,13 +189,13 @@ ssize_t freadlink(HANDLE hFile, char* buf, size_t bufsiz) { alignas(REPARSE_DATA_BUFFER) BYTE reparseBuf[MAXIMUM_REPARSE_DATA_BUFFER_SIZE]; DWORD bytesReturned = 0; - if (!DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT, NULL, 0, reparseBuf, (DWORD) sizeof(reparseBuf), &bytesReturned, NULL)) { + if (!DeviceIoControl(hFile, FSCTL_GET_REPARSE_POINT, nullptr, 0, reparseBuf, (DWORD) sizeof(reparseBuf), &bytesReturned, nullptr)) { errno = winerr2Errno(GetLastError()); return -1; } REPARSE_DATA_BUFFER* rp = (REPARSE_DATA_BUFFER*) reparseBuf; - const wchar_t* targetW = NULL; + const wchar_t* targetW = nullptr; USHORT targetBytes = 0; if (rp->ReparseTag == IO_REPARSE_TAG_SYMLINK) { @@ -262,10 +262,10 @@ ssize_t readlink(const char* path, char* buf, size_t bufsiz) { pathW, 0, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, - NULL, + nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT, - NULL); + nullptr); if (hFile == INVALID_HANDLE_VALUE) { errno = winerr2Errno(GetLastError()); diff --git a/src/common/impl/percent.c b/src/common/impl/percent.c index 266588cb68..ef276484f5 100644 --- a/src/common/impl/percent.c +++ b/src/common/impl/percent.c @@ -17,7 +17,7 @@ static void appendOutputColor(FFstrbuf* buffer, const FFModuleArgs* module) { const char* ffPercentParseTypeJsonConfig(yyjson_val* jsonVal, FFPercentageTypeFlags* result) { if (yyjson_is_uint(jsonVal)) { *result = (FFPercentageTypeFlags) yyjson_get_uint(jsonVal); - return NULL; + return nullptr; } if (yyjson_is_arr(jsonVal)) { FFPercentageTypeFlags flags = 0; @@ -45,7 +45,7 @@ const char* ffPercentParseTypeJsonConfig(yyjson_val* jsonVal, FFPercentageTypeFl } *result = flags; - return NULL; + return nullptr; } return "Error: usage: percent.type must be a number or an array of strings"; @@ -90,7 +90,7 @@ void ffPercentAppendBar(FFstrbuf* buffer, double percent, FFPercentageModuleConf bool monochrome = (percentType & FF_PERCENTAGE_TYPE_BAR_MONOCHROME_BIT) || !autoColorElapsed; if (!options->pipe && options->barColorElapsed.length > 0 && monochrome) { - const char* color = NULL; + const char* color = nullptr; if (!autoColorElapsed) { color = options->barColorElapsed.chars; } else if (green <= yellow) { diff --git a/src/common/impl/printing.c b/src/common/impl/printing.c index 9f372d9378..1203dfb0a0 100644 --- a/src/common/impl/printing.c +++ b/src/common/impl/printing.c @@ -7,7 +7,7 @@ void ffPrintLogoAndKey(const char* moduleName, uint8_t moduleIndex, const FFModu ffLogoPrintLine(); // This is used by --set-keyless, in this case we want neither the module name nor the separator - if (moduleName == NULL) { + if (moduleName == nullptr) { return; } @@ -35,7 +35,7 @@ void ffPrintLogoAndKey(const char* moduleName, uint8_t moduleIndex, const FFModu if (instance.config.display.keyType & FF_MODULE_KEY_TYPE_STRING) { ffPrintCharTimes(' ', instance.config.display.keyType >> FF_MODULE_KEY_TYPE_SPACE_SHIFT); - // NULL check is required for modules with custom keys, e.g. disk with the folder path + // nullptr check is required for modules with custom keys, e.g. disk with the folder path if ((printType & FF_PRINT_TYPE_NO_CUSTOM_KEY) || !moduleArgs || moduleArgs->key.length == 0) { fputs(moduleName, stdout); @@ -84,7 +84,7 @@ void ffPrintLogoAndKey(const char* moduleName, uint8_t moduleIndex, const FFModu bool ffPrintFormat(const char* moduleName, uint8_t moduleIndex, const FFModuleArgs* moduleArgs, FFPrintType printType, uint32_t numArgs, const FFformatarg* arguments) { FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); bool success; - if (__builtin_expect(moduleArgs != NULL, 1)) { + if (__builtin_expect(moduleArgs != nullptr, 1)) { success = ffParseFormatString(&buffer, &moduleArgs->outputFormat, numArgs, arguments); } else { ffStrbufSetStatic(&buffer, "undefined format"); diff --git a/src/common/impl/processing_linux.c b/src/common/impl/processing_linux.c index 828d4846d8..e43aff2b9f 100644 --- a/src/common/impl/processing_linux.c +++ b/src/common/impl/processing_linux.c @@ -79,7 +79,7 @@ const char* ffProcessSpawn(char* const argv[], bool useStdErr, FFProcessHandle* posix_spawn_file_actions_adddup2(&file_actions, pipes[1], useStdErr ? STDERR_FILENO : STDOUT_FILENO); posix_spawn_file_actions_adddup2(&file_actions, nullFile, useStdErr ? STDOUT_FILENO : STDERR_FILENO); - static char* oldLang = NULL; + static char* oldLang = nullptr; static int langIndex = -1; if (langIndex >= 0) { @@ -95,7 +95,7 @@ const char* ffProcessSpawn(char* const argv[], bool useStdErr, FFProcessHandle* } } if (langIndex < 0) { - for (int i = 0; environ[i] != NULL; i++) { + for (int i = 0; environ[i] != nullptr; i++) { if (ffStrStartsWith(environ[i], "LANG=")) { langIndex = i; const char* langValue = environ[i] + 5; // Skip "LANG=" @@ -112,7 +112,7 @@ const char* ffProcessSpawn(char* const argv[], bool useStdErr, FFProcessHandle* } } - int ret = posix_spawnp(&childPid, argv[0], &file_actions, NULL, argv, environ); + int ret = posix_spawnp(&childPid, argv[0], &file_actions, nullptr, argv, environ); if (oldLang) { environ[langIndex] = oldLang; @@ -153,7 +153,7 @@ const char* ffProcessSpawn(char* const argv[], bool useStdErr, FFProcessHandle* close(pipes[1]); outHandle->pid = childPid; outHandle->pipeRead = pipes[0]; - return NULL; + return nullptr; } const char* ffProcessReadOutput(FFProcessHandle* handle, FFstrbuf* buffer) { @@ -173,11 +173,11 @@ const char* ffProcessReadOutput(FFProcessHandle* handle, FFstrbuf* buffer) { int pollret = poll(&pollfd, 1, timeout); if (pollret == 0) { kill(childPid, SIGTERM); - waitpid(childPid, NULL, 0); + waitpid(childPid, nullptr, 0); return "poll(&pollfd, 1, timeout) timeout (try increasing --processing-timeout)"; } else if (pollret < 0 || (pollfd.revents & POLLERR)) { kill(childPid, SIGTERM); - waitpid(childPid, NULL, 0); + waitpid(childPid, nullptr, 0); return pollret < 0 ? "poll(&pollfd, 1, timeout) error: pollret < 0" : "poll(&pollfd, 1, timeout) error: pollfd.revents & POLLERR"; @@ -197,9 +197,9 @@ const char* ffProcessReadOutput(FFProcessHandle* handle, FFstrbuf* buffer) { return "command not found"; } // We only handle 127 as an error. See `getTerminalVersionUrxvt` in `terminalshell.c` - return NULL; + return nullptr; } - return NULL; + return nullptr; } else if (nRead < 0) { break; } @@ -278,11 +278,11 @@ void ffProcessGetInfoLinux(pid_t pid, FFstrbuf* processName, FFstrbuf* exe, cons size_t len = 0; int mibs[] = { CTL_KERN, KERN_PROCARGS2, pid }; - if (sysctl(mibs, ARRAY_SIZE(mibs), NULL, &len, NULL, 0) == 0) { // try get arg0 + if (sysctl(mibs, ARRAY_SIZE(mibs), nullptr, &len, nullptr, 0) == 0) { // try get arg0 // don't know why if don't let len longer, proArgs2 and len will change during the following sysctl() in old MacOS version. len++; FF_AUTO_FREE char* const procArgs2 = malloc(len); - if (sysctl(mibs, ARRAY_SIZE(mibs), procArgs2, &len, NULL, 0) == 0) { + if (sysctl(mibs, ARRAY_SIZE(mibs), procArgs2, &len, nullptr, 0) == 0) { // https://gist.github.com/nonowarn/770696#file-getargv-c-L46 uint32_t argc = *(uint32_t*) procArgs2; const char* realExePath = procArgs2 + sizeof(argc); @@ -354,7 +354,7 @@ void ffProcessGetInfoLinux(pid_t pid, FFstrbuf* processName, FFstrbuf* exe, cons 4, args, &size, - NULL, + nullptr, 0) == 0) ffStrbufSetNS(exePath, (uint32_t) (size - 1), args); @@ -374,7 +374,7 @@ void ffProcessGetInfoLinux(pid_t pid, FFstrbuf* processName, FFstrbuf* exe, cons 4, args, &size, - NULL, + nullptr, 0) == 0) { char* arg0 = args; size_t arg0Len = strlen(args); @@ -423,7 +423,7 @@ void ffProcessGetInfoLinux(pid_t pid, FFstrbuf* processName, FFstrbuf* exe, cons #elif defined(__OpenBSD__) - kvm_t* kd = kvm_open(NULL, NULL, NULL, KVM_NO_FILES, NULL); + kvm_t* kd = kvm_open(nullptr, nullptr, nullptr, KVM_NO_FILES, nullptr); int count = 0; const struct kinfo_proc* proc = kvm_getprocs(kd, KERN_PROC_PID, pid, sizeof(struct kinfo_proc), &count); if (proc) { @@ -488,7 +488,7 @@ const char* ffProcessGetBasicInfoLinux(pid_t pid, FFstrbuf* name, pid_t* ppid, i } buf[nRead] = '\0'; // pid (comm) state ppid pgrp session tty - const char* pState = NULL; + const char* pState = nullptr; { // comm in `/proc/pid/stat` is not encoded, and may contain ' ', ')' or even `\n` @@ -542,7 +542,7 @@ const char* ffProcessGetBasicInfoLinux(pid_t pid, FFstrbuf* name, pid_t* ppid, i struct kinfo_proc proc; size_t size = sizeof(proc); if (sysctl( - (int[]) { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid }, 4, &proc, &size, NULL, 0)) { + (int[]) { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid }, 4, &proc, &size, nullptr, 0)) { return "sysctl(KERN_PROC_PID) failed"; } @@ -568,7 +568,7 @@ const char* ffProcessGetBasicInfoLinux(pid_t pid, FFstrbuf* name, pid_t* ppid, i struct kinfo_proc proc; size_t size = sizeof(proc); if (sysctl( - (int[]) { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid }, 4, &proc, &size, NULL, 0)) { + (int[]) { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid }, 4, &proc, &size, nullptr, 0)) { return "sysctl(KERN_PROC_PID) failed"; } @@ -580,7 +580,7 @@ const char* ffProcessGetBasicInfoLinux(pid_t pid, FFstrbuf* name, pid_t* ppid, i if (proc.ki_tdev != NODEV && proc.ki_flag & P_CONTROLT) { const char* ttyName = devname(proc.ki_tdev, S_IFCHR); if (ffStrStartsWith(ttyName, "pts/")) { - *tty = (int32_t) strtol(ttyName + strlen("pts/"), NULL, 10); + *tty = (int32_t) strtol(ttyName + strlen("pts/"), nullptr, 10); } else { *tty = -1; } @@ -594,7 +594,7 @@ const char* ffProcessGetBasicInfoLinux(pid_t pid, FFstrbuf* name, pid_t* ppid, i struct kinfo_proc2 proc; size_t size = sizeof(proc); if (sysctl( - (int[]) { CTL_KERN, KERN_PROC2, KERN_PROC_PID, pid, sizeof(proc), 1 }, 6, &proc, &size, NULL, 0) != 0) { + (int[]) { CTL_KERN, KERN_PROC2, KERN_PROC_PID, pid, sizeof(proc), 1 }, 6, &proc, &size, nullptr, 0) != 0) { return "sysctl(KERN_PROC_PID) failed"; } @@ -606,7 +606,7 @@ const char* ffProcessGetBasicInfoLinux(pid_t pid, FFstrbuf* name, pid_t* ppid, i if (proc.p_flag & P_CONTROLT) { const char* ttyName = devname(proc.p_tdev, S_IFCHR); if (ffStrStartsWith(ttyName, "pts/")) { - *tty = (int32_t) strtol(ttyName + strlen("pts/"), NULL, 10); + *tty = (int32_t) strtol(ttyName + strlen("pts/"), nullptr, 10); } else { *tty = -1; } @@ -633,7 +633,7 @@ const char* ffProcessGetBasicInfoLinux(pid_t pid, FFstrbuf* name, pid_t* ppid, i #elif defined(__OpenBSD__) - kvm_t* kd = kvm_open(NULL, NULL, NULL, KVM_NO_FILES, NULL); + kvm_t* kd = kvm_open(nullptr, nullptr, nullptr, KVM_NO_FILES, nullptr); int count = 0; const struct kinfo_proc* proc = kvm_getprocs(kd, KERN_PROC_PID, pid, sizeof(struct kinfo_proc), &count); if (proc) { @@ -668,5 +668,5 @@ const char* ffProcessGetBasicInfoLinux(pid_t pid, FFstrbuf* name, pid_t* ppid, i #endif - return NULL; + return nullptr; } diff --git a/src/common/impl/processing_windows.c b/src/common/impl/processing_windows.c index 846276b592..5df9f90576 100644 --- a/src/common/impl/processing_windows.c +++ b/src/common/impl/processing_windows.c @@ -15,7 +15,7 @@ static void argvToCmdline(char* const argv[], FFstrbuf* result) { // From https://gist.github.com/jin-x/cdd641d98887524b091fb1f82a68717d FF_STRBUF_AUTO_DESTROY temp = ffStrbufCreate(); - for (int i = 0; argv[i] != NULL; i++) { + for (int i = 0; argv[i] != nullptr; i++) { ffStrbufSetS(&temp, argv[i]); // Add slash (\) before double quotes (") and duplicate slashes before it for ( @@ -63,7 +63,7 @@ const char* ffProcessSpawn(char* const argv[], bool useStdErr, FFProcessHandle* FF_PIPE_BUFSIZ, FF_PIPE_BUFSIZ, 0, - NULL); + nullptr); if (hChildPipeRead == INVALID_HANDLE_VALUE) { return "CreateNamedPipeW(L\"\\\\.\\pipe\\FASTFETCH-$(PID)\") failed"; } @@ -74,12 +74,12 @@ const char* ffProcessSpawn(char* const argv[], bool useStdErr, FFProcessHandle* 0, &(SECURITY_ATTRIBUTES) { .nLength = sizeof(SECURITY_ATTRIBUTES), - .lpSecurityDescriptor = NULL, + .lpSecurityDescriptor = nullptr, .bInheritHandle = TRUE, }, OPEN_EXISTING, 0, - NULL); + nullptr); if (hChildPipeWrite == INVALID_HANDLE_VALUE) { return "CreateFileW(L\"\\\\.\\pipe\\FASTFETCH-$(PID)\") failed"; } @@ -97,26 +97,26 @@ const char* ffProcessSpawn(char* const argv[], bool useStdErr, FFProcessHandle* siStartInfo.hStdError = ffGetNullFD(); } - FF_AUTO_FREE wchar_t* cmdline = NULL; + FF_AUTO_FREE wchar_t* cmdline = nullptr; { FF_STRBUF_AUTO_DESTROY buf = ffStrbufCreate(); argvToCmdline(argv, &buf); uint32_t cmdlineBytes = (buf.length + 1) * sizeof(wchar_t); cmdline = malloc(cmdlineBytes); - if (!NT_SUCCESS(RtlUTF8ToUnicodeN(cmdline, cmdlineBytes, NULL, buf.chars, buf.length + 1))) { + if (!NT_SUCCESS(RtlUTF8ToUnicodeN(cmdline, cmdlineBytes, nullptr, buf.chars, buf.length + 1))) { return "RtlUTF8ToUnicodeN() failed"; } } BOOL success = CreateProcessW( - NULL, // application name + nullptr, // application name cmdline, // command line - NULL, // process security attributes - NULL, // primary thread security attributes + nullptr, // process security attributes + nullptr, // primary thread security attributes TRUE, // handles are inherited 0, // creation flags - NULL, // use parent's environment - NULL, // use parent's current directory + nullptr, // use parent's environment + nullptr, // use parent's current directory &siStartInfo, // STARTUPINFO pointer &piProcInfo // receives PROCESS_INFORMATION ); @@ -134,7 +134,7 @@ const char* ffProcessSpawn(char* const argv[], bool useStdErr, FFProcessHandle* outHandle->pipeRead = hChildPipeRead; hChildPipeRead = INVALID_HANDLE_VALUE; // ownership transferred, don't close it - return NULL; + return nullptr; } static void terminateChildProcess(HANDLE hProcess, HANDLE hChildPipeRead, HANDLE hReadEvent, IO_STATUS_BLOCK* piosb) { @@ -154,11 +154,11 @@ const char* ffProcessReadOutput(FFProcessHandle* handle, FFstrbuf* buffer) { int32_t timeout = instance.config.general.processingTimeout; FF_AUTO_CLOSE_FD HANDLE hProcess = handle->pid; FF_AUTO_CLOSE_FD HANDLE hChildPipeRead = handle->pipeRead; - FF_AUTO_CLOSE_FD HANDLE hReadEvent = NULL; + FF_AUTO_CLOSE_FD HANDLE hReadEvent = nullptr; handle->pid = INVALID_HANDLE_VALUE; handle->pipeRead = INVALID_HANDLE_VALUE; - if (timeout >= 0 && !NT_SUCCESS(NtCreateEvent(&hReadEvent, EVENT_ALL_ACCESS, NULL, SynchronizationEvent, FALSE))) { + if (timeout >= 0 && !NT_SUCCESS(NtCreateEvent(&hReadEvent, EVENT_ALL_ACCESS, nullptr, SynchronizationEvent, FALSE))) { return "NtCreateEvent() failed"; } @@ -169,13 +169,13 @@ const char* ffProcessReadOutput(FFProcessHandle* handle, FFstrbuf* buffer) { NTSTATUS status = NtReadFile( hChildPipeRead, hReadEvent, - NULL, - NULL, + nullptr, + nullptr, &iosb, str, (ULONG) sizeof(str), - NULL, - NULL); + nullptr, + nullptr); if (status == STATUS_PENDING) { switch (NtWaitForSingleObject(hReadEvent, FALSE, &(LARGE_INTEGER) { .QuadPart = (int64_t) timeout * -10000 })) { case STATUS_WAIT_0: @@ -198,7 +198,7 @@ const char* ffProcessReadOutput(FFProcessHandle* handle, FFstrbuf* buffer) { } if (!NT_SUCCESS(status)) { - terminateChildProcess(hProcess, hChildPipeRead, NULL, &iosb); + terminateChildProcess(hProcess, hChildPipeRead, nullptr, &iosb); return "NtReadFile(hChildPipeRead) failed"; } @@ -219,7 +219,7 @@ exit: { } } - return NULL; + return nullptr; } bool ffProcessGetInfoWindows(uint32_t pid, uint32_t* ppid, FFstrbuf* pname, FFstrbuf* exe, const char** exeName, FFstrbuf* exePath, bool* gui) { diff --git a/src/common/impl/properties.c b/src/common/impl/properties.c index c13ed1cd6d..9a4fe290ec 100644 --- a/src/common/impl/properties.c +++ b/src/common/impl/properties.c @@ -95,7 +95,7 @@ bool ffParsePropLines(const char* lines, const char* start, FFstrbuf* buffer) { bool ffParsePropFileValues(const char* filename, uint32_t numQueries, FFpropquery* queries) { FF_AUTO_CLOSE_FILE FILE* file = fopen(filename, "r"); - if (file == NULL) { + if (file == nullptr) { return false; } @@ -115,7 +115,7 @@ bool ffParsePropFileValues(const char* filename, uint32_t numQueries, FFpropquer } if (!allSet) { - FF_AUTO_FREE char* line = NULL; + FF_AUTO_FREE char* line = nullptr; size_t len = 0; while (getline(&line, &len, file) != -1) { diff --git a/src/common/impl/settings.c b/src/common/impl/settings.c index 1e1d05f357..0f00054df2 100644 --- a/src/common/impl/settings.c +++ b/src/common/impl/settings.c @@ -19,10 +19,10 @@ typedef struct GVariantGetters { static FFvariant getGVariantValue(GVariant* variant, FFvarianttype type, const GVariantGetters* variantGetters) { FFvariant result; - if (variant == NULL) { + if (variant == nullptr) { result = FF_VARIANT_NULL; } else if (type == FF_VARIANT_TYPE_STRING) { - result = (FFvariant) { .strValue = variantGetters->ffg_variant_dup_string(variant, NULL) }; // Dup string, so that variant itself can be freed + result = (FFvariant) { .strValue = variantGetters->ffg_variant_dup_string(variant, nullptr) }; // Dup string, so that variant itself can be freed } else if (type == FF_VARIANT_TYPE_BOOL) { result = (FFvariant) { .boolValue = (bool) variantGetters->ffg_variant_get_boolean(variant), .boolValueSet = true }; } else if (type == FF_VARIANT_TYPE_INT) { @@ -57,27 +57,27 @@ static const GSettingsData* getGSettingsData(void) { if (!data.inited) { data.inited = true; - FF_LIBRARY_LOAD(libgsettings, NULL, "libgio-2.0" FF_LIBRARY_EXTENSION, 1); - FF_LIBRARY_LOAD_SYMBOL_VAR(libgsettings, data, g_settings_schema_source_lookup, NULL) - FF_LIBRARY_LOAD_SYMBOL_VAR(libgsettings, data, g_settings_schema_has_key, NULL) - FF_LIBRARY_LOAD_SYMBOL_VAR(libgsettings, data, g_settings_new_full, NULL) - FF_LIBRARY_LOAD_SYMBOL_VAR(libgsettings, data, g_settings_get_value, NULL) - FF_LIBRARY_LOAD_SYMBOL_VAR(libgsettings, data, g_settings_get_user_value, NULL) - FF_LIBRARY_LOAD_SYMBOL_VAR(libgsettings, data, g_settings_get_default_value, NULL) - FF_LIBRARY_LOAD_SYMBOL_VAR(libgsettings, data, g_settings_schema_source_get_default, NULL) - - FF_LIBRARY_LOAD_SYMBOL_VAR(libgsettings, data.variantGetters, g_variant_dup_string, NULL) - FF_LIBRARY_LOAD_SYMBOL_VAR(libgsettings, data.variantGetters, g_variant_get_boolean, NULL) - FF_LIBRARY_LOAD_SYMBOL_VAR(libgsettings, data.variantGetters, g_variant_get_int32, NULL) - FF_LIBRARY_LOAD_SYMBOL_VAR(libgsettings, data.variantGetters, g_variant_unref, NULL); + FF_LIBRARY_LOAD(libgsettings, nullptr, "libgio-2.0" FF_LIBRARY_EXTENSION, 1); + FF_LIBRARY_LOAD_SYMBOL_VAR(libgsettings, data, g_settings_schema_source_lookup, nullptr) + FF_LIBRARY_LOAD_SYMBOL_VAR(libgsettings, data, g_settings_schema_has_key, nullptr) + FF_LIBRARY_LOAD_SYMBOL_VAR(libgsettings, data, g_settings_new_full, nullptr) + FF_LIBRARY_LOAD_SYMBOL_VAR(libgsettings, data, g_settings_get_value, nullptr) + FF_LIBRARY_LOAD_SYMBOL_VAR(libgsettings, data, g_settings_get_user_value, nullptr) + FF_LIBRARY_LOAD_SYMBOL_VAR(libgsettings, data, g_settings_get_default_value, nullptr) + FF_LIBRARY_LOAD_SYMBOL_VAR(libgsettings, data, g_settings_schema_source_get_default, nullptr) + + FF_LIBRARY_LOAD_SYMBOL_VAR(libgsettings, data.variantGetters, g_variant_dup_string, nullptr) + FF_LIBRARY_LOAD_SYMBOL_VAR(libgsettings, data.variantGetters, g_variant_get_boolean, nullptr) + FF_LIBRARY_LOAD_SYMBOL_VAR(libgsettings, data.variantGetters, g_variant_get_int32, nullptr) + FF_LIBRARY_LOAD_SYMBOL_VAR(libgsettings, data.variantGetters, g_variant_unref, nullptr); data.schemaSource = data.ffg_settings_schema_source_get_default(); if (data.schemaSource) { - libgsettings = NULL; + libgsettings = nullptr; } } if (!data.schemaSource) { - return NULL; + return nullptr; } return &data; @@ -85,12 +85,12 @@ static const GSettingsData* getGSettingsData(void) { FFvariant ffSettingsGetGSettings(const char* schemaName, const char* path, const char* key, FFvarianttype type) { const GSettingsData* data = getGSettingsData(); - if (data == NULL) { + if (data == nullptr) { return FF_VARIANT_NULL; } GSettingsSchema* schema = data->ffg_settings_schema_source_lookup(data->schemaSource, schemaName, true); - if (schema == NULL) { + if (schema == nullptr) { return FF_VARIANT_NULL; } @@ -98,18 +98,18 @@ FFvariant ffSettingsGetGSettings(const char* schemaName, const char* path, const return FF_VARIANT_NULL; } - GSettings* settings = data->ffg_settings_new_full(schema, NULL, path); - if (settings == NULL) { + GSettings* settings = data->ffg_settings_new_full(schema, nullptr, path); + if (settings == nullptr) { return FF_VARIANT_NULL; } GVariant* variant = data->ffg_settings_get_value(settings, key); - if (variant != NULL) { + if (variant != nullptr) { return getGVariantValue(variant, type, &data->variantGetters); } variant = data->ffg_settings_get_user_value(settings, key); - if (variant != NULL) { + if (variant != nullptr) { return getGVariantValue(variant, type, &data->variantGetters); } @@ -141,21 +141,21 @@ static const DConfData* getDConfData(void) { if (!data.inited) { data.inited = true; - FF_LIBRARY_LOAD(libdconf, NULL, "libdconf" FF_LIBRARY_EXTENSION, 2); - FF_LIBRARY_LOAD_SYMBOL_VAR(libdconf, data, dconf_client_read_full, NULL) - FF_LIBRARY_LOAD_SYMBOL_VAR(libdconf, data, dconf_client_new, NULL) - FF_LIBRARY_LOAD_SYMBOL_VAR(libdconf, data.variantGetters, g_variant_dup_string, NULL) - FF_LIBRARY_LOAD_SYMBOL_VAR(libdconf, data.variantGetters, g_variant_get_boolean, NULL) - FF_LIBRARY_LOAD_SYMBOL_VAR(libdconf, data.variantGetters, g_variant_get_int32, NULL) - FF_LIBRARY_LOAD_SYMBOL_VAR(libdconf, data.variantGetters, g_variant_unref, NULL) + FF_LIBRARY_LOAD(libdconf, nullptr, "libdconf" FF_LIBRARY_EXTENSION, 2); + FF_LIBRARY_LOAD_SYMBOL_VAR(libdconf, data, dconf_client_read_full, nullptr) + FF_LIBRARY_LOAD_SYMBOL_VAR(libdconf, data, dconf_client_new, nullptr) + FF_LIBRARY_LOAD_SYMBOL_VAR(libdconf, data.variantGetters, g_variant_dup_string, nullptr) + FF_LIBRARY_LOAD_SYMBOL_VAR(libdconf, data.variantGetters, g_variant_get_boolean, nullptr) + FF_LIBRARY_LOAD_SYMBOL_VAR(libdconf, data.variantGetters, g_variant_get_int32, nullptr) + FF_LIBRARY_LOAD_SYMBOL_VAR(libdconf, data.variantGetters, g_variant_unref, nullptr) data.client = data.ffdconf_client_new(); if (data.client) { - libdconf = NULL; + libdconf = nullptr; } } if (!data.client) { - return NULL; + return nullptr; } return &data; @@ -163,21 +163,21 @@ static const DConfData* getDConfData(void) { FFvariant ffSettingsGetDConf(const char* key, FFvarianttype type) { const DConfData* data = getDConfData(); - if (data == NULL) { + if (data == nullptr) { return FF_VARIANT_NULL; } - GVariant* variant = data->ffdconf_client_read_full(data->client, key, DCONF_READ_FLAGS_NONE, NULL); - if (variant != NULL) { + GVariant* variant = data->ffdconf_client_read_full(data->client, key, DCONF_READ_FLAGS_NONE, nullptr); + if (variant != nullptr) { return getGVariantValue(variant, type, &data->variantGetters); } - variant = data->ffdconf_client_read_full(data->client, key, DCONF_READ_USER_VALUE, NULL); - if (variant != NULL) { + variant = data->ffdconf_client_read_full(data->client, key, DCONF_READ_USER_VALUE, nullptr); + if (variant != nullptr) { return getGVariantValue(variant, type, &data->variantGetters); } - variant = data->ffdconf_client_read_full(data->client, key, DCONF_READ_DEFAULT_VALUE, NULL); + variant = data->ffdconf_client_read_full(data->client, key, DCONF_READ_DEFAULT_VALUE, nullptr); return getGVariantValue(variant, type, &data->variantGetters); } #else // FF_HAVE_DCONF @@ -192,7 +192,7 @@ FFvariant ffSettingsGetGnome(const char* dconfKey, const char* gsettingsSchemaNa if ( (type == FF_VARIANT_TYPE_BOOL && gsettings.boolValueSet) || - (type != FF_VARIANT_TYPE_BOOL && gsettings.strValue != NULL)) { + (type != FF_VARIANT_TYPE_BOOL && gsettings.strValue != nullptr)) { return gsettings; } @@ -204,7 +204,7 @@ FFvariant ffSettingsGetGnome(const char* dconfKey, const char* gsettingsSchemaNa FFvariant ffSettingsGetXFConf(const char* channelName, const char* propertyName, FFvarianttype type) { FF_DBUS_AUTO_DESTROY_DATA FFDBusData dbus = {}; - if (ffDBusLoadData(DBUS_BUS_SESSION, &dbus) != NULL) { + if (ffDBusLoadData(DBUS_BUS_SESSION, &dbus) != nullptr) { return FF_VARIANT_NULL; } @@ -260,7 +260,7 @@ FFvariant ffSettingsGetXFConf(const char* channelName, const char* propertyName, FFvariant ffSettingsGetXFConfFirstMatch(const char* channelName, const char* propertyPrefix, FFvarianttype type, void* data, FFTestXfconfPropCallback* cb) { FF_DBUS_AUTO_DESTROY_DATA FFDBusData dbus = {}; - if (ffDBusLoadData(DBUS_BUS_SESSION, &dbus) != NULL) { + if (ffDBusLoadData(DBUS_BUS_SESSION, &dbus) != nullptr) { return FF_VARIANT_NULL; } @@ -361,20 +361,20 @@ static const SQLiteData* getSQLiteData(void) { if (!data.inited) { data.inited = true; - FF_LIBRARY_LOAD(libsqlite, NULL, "libsqlite3" FF_LIBRARY_EXTENSION, 1); - FF_LIBRARY_LOAD_SYMBOL_VAR(libsqlite, data, sqlite3_open_v2, NULL) - FF_LIBRARY_LOAD_SYMBOL_VAR(libsqlite, data, sqlite3_prepare_v2, NULL) - FF_LIBRARY_LOAD_SYMBOL_VAR(libsqlite, data, sqlite3_step, NULL) - FF_LIBRARY_LOAD_SYMBOL_VAR(libsqlite, data, sqlite3_data_count, NULL) - FF_LIBRARY_LOAD_SYMBOL_VAR(libsqlite, data, sqlite3_column_int, NULL) - FF_LIBRARY_LOAD_SYMBOL_VAR(libsqlite, data, sqlite3_column_text, NULL) - FF_LIBRARY_LOAD_SYMBOL_VAR(libsqlite, data, sqlite3_finalize, NULL) - FF_LIBRARY_LOAD_SYMBOL_VAR(libsqlite, data, sqlite3_close, NULL) - libsqlite = NULL; + FF_LIBRARY_LOAD(libsqlite, nullptr, "libsqlite3" FF_LIBRARY_EXTENSION, 1); + FF_LIBRARY_LOAD_SYMBOL_VAR(libsqlite, data, sqlite3_open_v2, nullptr) + FF_LIBRARY_LOAD_SYMBOL_VAR(libsqlite, data, sqlite3_prepare_v2, nullptr) + FF_LIBRARY_LOAD_SYMBOL_VAR(libsqlite, data, sqlite3_step, nullptr) + FF_LIBRARY_LOAD_SYMBOL_VAR(libsqlite, data, sqlite3_data_count, nullptr) + FF_LIBRARY_LOAD_SYMBOL_VAR(libsqlite, data, sqlite3_column_int, nullptr) + FF_LIBRARY_LOAD_SYMBOL_VAR(libsqlite, data, sqlite3_column_text, nullptr) + FF_LIBRARY_LOAD_SYMBOL_VAR(libsqlite, data, sqlite3_finalize, nullptr) + FF_LIBRARY_LOAD_SYMBOL_VAR(libsqlite, data, sqlite3_close, nullptr) + libsqlite = nullptr; } if (!data.ffsqlite3_close) { - return NULL; + return nullptr; } return &data; @@ -386,17 +386,17 @@ int ffSettingsGetSQLite3Int(const char* dbPath, const char* query) { } const SQLiteData* data = getSQLiteData(); - if (data == NULL) { + if (data == nullptr) { return 0; } sqlite3* db; - if (data->ffsqlite3_open_v2(dbPath, &db, SQLITE_OPEN_READONLY | SQLITE_OPEN_NOMUTEX, NULL) != SQLITE_OK) { + if (data->ffsqlite3_open_v2(dbPath, &db, SQLITE_OPEN_READONLY | SQLITE_OPEN_NOMUTEX, nullptr) != SQLITE_OK) { return 0; } sqlite3_stmt* stmt; - if (data->ffsqlite3_prepare_v2(db, query, (int) strlen(query), &stmt, NULL) != SQLITE_OK) { + if (data->ffsqlite3_prepare_v2(db, query, (int) strlen(query), &stmt, nullptr) != SQLITE_OK) { data->ffsqlite3_close(db); return 0; } @@ -421,17 +421,17 @@ bool ffSettingsGetSQLite3String(const char* dbPath, const char* query, FFstrbuf* } const SQLiteData* data = getSQLiteData(); - if (data == NULL) { + if (data == nullptr) { return false; } sqlite3* db; - if (data->ffsqlite3_open_v2(dbPath, &db, SQLITE_OPEN_READONLY, NULL) != SQLITE_OK) { + if (data->ffsqlite3_open_v2(dbPath, &db, SQLITE_OPEN_READONLY, nullptr) != SQLITE_OK) { return false; } sqlite3_stmt* stmt; - if (data->ffsqlite3_prepare_v2(db, query, (int) strlen(query), &stmt, NULL) != SQLITE_OK) { + if (data->ffsqlite3_prepare_v2(db, query, (int) strlen(query), &stmt, nullptr) != SQLITE_OK) { data->ffsqlite3_close(db); return false; } @@ -514,12 +514,12 @@ typedef struct E_Config { #define FF_EET_DATA_DESCRIPTOR_ADD_BASIC(edd, struct_type, member, type) \ do { \ struct_type ___ett; \ - ffeet_data_descriptor_element_add(edd, #member, type, EET_G_UNKNOWN, (char*) (&(___ett.member)) - (char*) (&(___ett)), 0, /* 0, */ NULL, NULL); \ + ffeet_data_descriptor_element_add(edd, #member, type, EET_G_UNKNOWN, (char*) (&(___ett.member)) - (char*) (&(___ett)), 0, /* 0, */ nullptr, nullptr); \ } while (0) #define FF_EET_DATA_DESCRIPTOR_ADD_LIST(edd, struct_type, member, subtype) \ do { \ struct_type ___ett; \ - ffeet_data_descriptor_element_add(edd, #member, EET_T_UNKNOW, EET_G_LIST, (char*) (&(___ett.member)) - (char*) (&(___ett)), 0, /* 0, */ NULL, subtype); \ + ffeet_data_descriptor_element_add(edd, #member, EET_T_UNKNOW, EET_G_LIST, (char*) (&(___ett.member)) - (char*) (&(___ett)), 0, /* 0, */ nullptr, subtype); \ } while (0) bool ffSettingsGetEnlightenmentProperty(ffEnlightenmentSettings* result) { @@ -603,7 +603,7 @@ bool ffSettingsGetEnlightenmentProperty(ffEnlightenmentSettings* result) { return !!parsed; } #else -bool ffSettingsGetEnlightenmentProperty(FF_A_UNUSED ffEnlightenmentSettings* result) { +bool ffSettingsGetEnlightenmentProperty([[maybe_unused]] ffEnlightenmentSettings* result) { return false; } #endif diff --git a/src/common/impl/size.c b/src/common/impl/size.c index 4e8d1e3711..9019ac5743 100644 --- a/src/common/impl/size.c +++ b/src/common/impl/size.c @@ -27,16 +27,16 @@ void ffSizeAppendNum(uint64_t bytes, FFstrbuf* result) { const FFOptionsDisplay* options = &instance.config.display; switch (options->sizeBinaryPrefix) { case FF_SIZE_BINARY_PREFIX_TYPE_IEC: - appendNum(result, bytes, 1024, (const char*[]) { "B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB", NULL }); + appendNum(result, bytes, 1024, (const char*[]) { "B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB", nullptr }); break; case FF_SIZE_BINARY_PREFIX_TYPE_SI: - appendNum(result, bytes, 1000, (const char*[]) { "B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB", NULL }); + appendNum(result, bytes, 1000, (const char*[]) { "B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB", nullptr }); break; case FF_SIZE_BINARY_PREFIX_TYPE_JEDEC: - appendNum(result, bytes, 1024, (const char*[]) { "B", "KB", "MB", "GB", "TB", NULL }); + appendNum(result, bytes, 1024, (const char*[]) { "B", "KB", "MB", "GB", "TB", nullptr }); break; default: - appendNum(result, bytes, 1024, (const char*[]) { "B", NULL }); + appendNum(result, bytes, 1024, (const char*[]) { "B", nullptr }); break; } } diff --git a/src/common/impl/smbios.c b/src/common/impl/smbios.c index 028bcd9c19..fc7df14b37 100644 --- a/src/common/impl/smbios.c +++ b/src/common/impl/smbios.c @@ -63,10 +63,10 @@ const FFSmbiosHeader* ffSmbiosNextEntry(const FFSmbiosHeader* header) { } static bool parseSmbiosTable(const uint8_t* data, uint32_t length) { - const FFSmbiosHeader* endOfTable = NULL; + const FFSmbiosHeader* endOfTable = nullptr; FF_DEBUG("Parsing SMBIOS table structures with length %u bytes", length); - FF_A_UNUSED int structureCount = 0, totalCount = 0; + [[maybe_unused]] int structureCount = 0, totalCount = 0; for ( const FFSmbiosHeader* header = (const FFSmbiosHeader*) data; (const uint8_t*) header + sizeof(FFSmbiosHeader) < (const uint8_t*) data + length; @@ -214,7 +214,7 @@ static bool readPhysicalMemory(int fd, off_t address, size_t length, void* buffe size_t pageOffset = (size_t) (address - alignedAddress); size_t mapLength = pageOffset + length; - void* p = mmap(NULL, mapLength, PROT_READ, MAP_SHARED, fd, alignedAddress); + void* p = mmap(nullptr, mapLength, PROT_READ, MAP_SHARED, fd, alignedAddress); if (p == MAP_FAILED) { FF_DEBUG("mmap failed at aligned address 0x%lx for %zu bytes: %s", (unsigned long) alignedAddress, @@ -228,7 +228,7 @@ static bool readPhysicalMemory(int fd, off_t address, size_t length, void* buffe return true; } -typedef struct FFSmbios20EntryPoint { +typedef struct [[gnu::packed]] FFSmbios20EntryPoint { uint8_t AnchorString[4]; uint8_t EntryPointStructureChecksum; uint8_t EntryPointLength; @@ -243,11 +243,11 @@ typedef struct FFSmbios20EntryPoint { uint32_t StructureTableAddress; uint16_t NumberOfSmbiosStructures; uint8_t SmbiosBcdRevision; -} FF_A_PACKED FFSmbios20EntryPoint; +} FFSmbios20EntryPoint; static_assert(offsetof(FFSmbios20EntryPoint, SmbiosBcdRevision) == 0x1E, "FFSmbios20EntryPoint: Wrong struct alignment"); -typedef struct FFSmbios30EntryPoint { +typedef struct [[gnu::packed]] FFSmbios30EntryPoint { uint8_t AnchorString[5]; uint8_t EntryPointStructureChecksum; uint8_t EntryPointLength; @@ -258,7 +258,7 @@ typedef struct FFSmbios30EntryPoint { uint8_t Reversed; uint32_t StructureTableMaximumSize; uint64_t StructureTableAddress; -} FF_A_PACKED FFSmbios30EntryPoint; +} FFSmbios30EntryPoint; static_assert(offsetof(FFSmbios30EntryPoint, StructureTableAddress) == 0x10, "FFSmbios30EntryPoint: Wrong struct alignment"); @@ -457,7 +457,7 @@ static bool fillTableBufferPlatform(FFstrbuf* buffer) { } while (address < lineEnd && (*address == ' ' || *address == '\t')); errno = 0; - char* addressEnd = NULL; + char* addressEnd = nullptr; unsigned long long parsedAddress = strtoull(address, &addressEnd, 16); if (errno != 0 || addressEnd == address || parsedAddress == 0) { FF_DEBUG("Failed to parse OpenBSD SMBIOS table address from line: %.*s", @@ -541,7 +541,7 @@ static bool fillTableBufferPlatform(FFstrbuf* buffer) { } #endif - off_t entryAddress = (off_t) strtol(strEntryAddress.chars, NULL, 16); + off_t entryAddress = (off_t) strtol(strEntryAddress.chars, nullptr, 16); if (entryAddress == 0) { FF_DEBUG("Invalid SMBIOS entry address: 0"); return false; @@ -671,7 +671,7 @@ const FFSmbiosHeaderTable* ffGetSmbiosHeaderTable() { if (!fillTableBufferFallback(&buffer)) { FF_DEBUG("Fallback SMBIOS retrieval also failed"); ffStrbufDestroy(&buffer); - return NULL; + return nullptr; } } @@ -682,7 +682,7 @@ const FFSmbiosHeaderTable* ffGetSmbiosHeaderTable() { if (buffer.length == 0) { FF_DEBUG("No valid SMBIOS data available"); - return NULL; + return nullptr; } return &smbiosTable; @@ -717,13 +717,13 @@ const FFSmbiosHeaderTable* ffGetSmbiosHeaderTable() { NtQuerySystemInformation(SystemFirmwareTableInformation, &sfti, sizeof(sfti), &bufSize); if (bufSize <= sizeof(FFRawSmbiosData) + sizeof(sfti)) { FF_DEBUG("Invalid firmware table size: %lu (must be > %zu)", bufSize, sizeof(FFRawSmbiosData) + sizeof(sfti)); - return NULL; + return nullptr; } if (bufSize != sfti.TableBufferLength + (ULONG) sizeof(sfti)) { FF_DEBUG("Firmware table size mismatch: NtQuerySystemInformation returned %lu but expected %lu", bufSize, sfti.TableBufferLength + (ULONG) sizeof(sfti)); - return NULL; + return nullptr; } FF_DEBUG("Firmware table size: %lu bytes", bufSize); @@ -734,8 +734,8 @@ const FFSmbiosHeaderTable* ffGetSmbiosHeaderTable() { if (!NT_SUCCESS(NtQuerySystemInformation(SystemFirmwareTableInformation, buffer, bufSize, &bufSize))) { FF_DEBUG("NtQuerySystemInformation(SystemFirmwareTableInformation) failed"); free(buffer); - buffer = NULL; - return NULL; + buffer = nullptr; + return nullptr; } FFRawSmbiosData* rawData = (FFRawSmbiosData*) buffer->TableBuffer; @@ -746,14 +746,14 @@ const FFSmbiosHeaderTable* ffGetSmbiosHeaderTable() { if (!parseSmbiosTable(rawData->SMBIOSTableData, rawData->Length)) { free(buffer); - buffer = NULL; - return NULL; + buffer = nullptr; + return nullptr; } } if (!buffer) { FF_DEBUG("No valid SMBIOS data available"); - return NULL; + return nullptr; } return &smbiosTable; } @@ -771,33 +771,33 @@ const FFSmbiosHeaderTable* ffGetSmbiosHeaderTable() { if (!registryEntry) { FF_DEBUG("IOServiceGetMatchingService() failed to find AppleSMBIOS"); - return NULL; + return nullptr; } FF_DEBUG("AppleSMBIOS service found, retrieving SMBIOS data"); smbiosDataBuffer = IORegistryEntryCreateCFProperty(registryEntry, CFSTR("SMBIOS"), kCFAllocatorDefault, kNilOptions); if (!smbiosDataBuffer) { FF_DEBUG("IORegistryEntryCreateCFProperty() failed to get SMBIOS data"); - return NULL; + return nullptr; } if (CFGetTypeID(smbiosDataBuffer) != CFDataGetTypeID()) { FF_DEBUG("Unexpected SMBIOS data type: expected CFData"); CFRelease(smbiosDataBuffer); - smbiosDataBuffer = NULL; - return NULL; + smbiosDataBuffer = nullptr; + return nullptr; } FF_DEBUG("Successfully retrieved SMBIOS data: %lu bytes", CFDataGetLength(smbiosDataBuffer)); if (!parseSmbiosTable((const uint8_t*) CFDataGetBytePtr(smbiosDataBuffer), (uint32_t) CFDataGetLength(smbiosDataBuffer))) { CFRelease(smbiosDataBuffer); - smbiosDataBuffer = NULL; - return NULL; + smbiosDataBuffer = nullptr; + return nullptr; } } if (!smbiosDataBuffer) { FF_DEBUG("No valid SMBIOS data available"); - return NULL; + return nullptr; } return &smbiosTable; diff --git a/src/common/impl/strutil.c b/src/common/impl/strutil.c index 3a801f7e8d..095452dbc3 100644 --- a/src/common/impl/strutil.c +++ b/src/common/impl/strutil.c @@ -1,4 +1,5 @@ #include "common/strutil.h" +#include "common/wcwidth.h" uint8_t ffUtf8CharLenWidth(const char* str, uint32_t length, uint8_t* width) { if (__builtin_expect(length == 0 || *str == '\0', false)) { diff --git a/src/common/impl/sysctl.c b/src/common/impl/sysctl.c index 5974698147..e17b5c348e 100644 --- a/src/common/impl/sysctl.c +++ b/src/common/impl/sysctl.c @@ -5,26 +5,26 @@ #ifdef __OpenBSD__ const char* ffSysctlGetString(int mib1, int mib2, FFstrbuf* result) { size_t neededLength; - if (sysctl((int[]) { mib1, mib2 }, 2, NULL, &neededLength, NULL, 0) != 0 || neededLength == 1) { // neededLength is 1 for empty strings, because of the null terminator + if (sysctl((int[]) { mib1, mib2 }, 2, nullptr, &neededLength, nullptr, 0) != 0 || neededLength == 1) { // neededLength is 1 for empty strings, because of the null terminator return "sysctl() length query failed"; } ffStrbufEnsureFree(result, (uint32_t) neededLength - 1); - if (sysctl((int[]) { mib1, mib2 }, 2, result->chars + result->length, &neededLength, NULL, 0) != 0) { + if (sysctl((int[]) { mib1, mib2 }, 2, result->chars + result->length, &neededLength, nullptr, 0) != 0) { return "sysctl() failed to retrieve string data"; } result->length += (uint32_t) neededLength - 1; result->chars[result->length] = '\0'; - return NULL; + return nullptr; } int ffSysctlGetInt(int mib1, int mib2, int defaultValue) { int result; size_t neededLength = sizeof(result); - if (sysctl((int[]) { mib1, mib2 }, 2, &result, &neededLength, NULL, 0) != 0) { + if (sysctl((int[]) { mib1, mib2 }, 2, &result, &neededLength, nullptr, 0) != 0) { return defaultValue; } return result; @@ -33,7 +33,7 @@ int ffSysctlGetInt(int mib1, int mib2, int defaultValue) { int64_t ffSysctlGetInt64(int mib1, int mib2, int64_t defaultValue) { int64_t result; size_t neededLength = sizeof(result); - if (sysctl((int[]) { mib1, mib2 }, 2, &result, &neededLength, NULL, 0) != 0) { + if (sysctl((int[]) { mib1, mib2 }, 2, &result, &neededLength, nullptr, 0) != 0) { return defaultValue; } return result; @@ -41,13 +41,13 @@ int64_t ffSysctlGetInt64(int mib1, int mib2, int64_t defaultValue) { #else const char* ffSysctlGetString(const char* propName, FFstrbuf* result) { size_t neededLength; - if (sysctlbyname(propName, NULL, &neededLength, NULL, 0) != 0 || neededLength == 1) { // neededLength is 1 for empty strings, because of the null terminator + if (sysctlbyname(propName, nullptr, &neededLength, nullptr, 0) != 0 || neededLength == 1) { // neededLength is 1 for empty strings, because of the null terminator return "sysctlbyname() failed"; } ffStrbufEnsureFree(result, (uint32_t) neededLength - 1); - if (sysctlbyname(propName, result->chars + result->length, &neededLength, NULL, 0) != 0) { + if (sysctlbyname(propName, result->chars + result->length, &neededLength, nullptr, 0) != 0) { return "sysctlbyname() failed to retrieve string data"; } @@ -55,13 +55,13 @@ const char* ffSysctlGetString(const char* propName, FFstrbuf* result) { result->chars[result->length] = '\0'; - return NULL; + return nullptr; } int ffSysctlGetInt(const char* propName, int defaultValue) { int result; size_t neededLength = sizeof(result); - if (sysctlbyname(propName, &result, &neededLength, NULL, 0) != 0) { + if (sysctlbyname(propName, &result, &neededLength, nullptr, 0) != 0) { return defaultValue; } return result; @@ -70,7 +70,7 @@ int ffSysctlGetInt(const char* propName, int defaultValue) { int64_t ffSysctlGetInt64(const char* propName, int64_t defaultValue) { int64_t result; size_t neededLength = sizeof(result); - if (sysctlbyname(propName, &result, &neededLength, NULL, 0) != 0) { + if (sysctlbyname(propName, &result, &neededLength, nullptr, 0) != 0) { return defaultValue; } return result; @@ -78,15 +78,15 @@ int64_t ffSysctlGetInt64(const char* propName, int64_t defaultValue) { #endif // OpenBSD void* ffSysctlGetData(int* request, u_int requestLength, size_t* resultLength) { - if (sysctl(request, requestLength, NULL, resultLength, NULL, 0) != 0) { - return NULL; + if (sysctl(request, requestLength, nullptr, resultLength, nullptr, 0) != 0) { + return nullptr; } void* data = malloc(*resultLength); - if (sysctl(request, requestLength, data, resultLength, NULL, 0) != 0) { + if (sysctl(request, requestLength, data, resultLength, nullptr, 0) != 0) { free(data); - return NULL; + return nullptr; } return data; diff --git a/src/common/impl/time.c b/src/common/impl/time.c index c60d1fecee..4f52d25abb 100644 --- a/src/common/impl/time.c +++ b/src/common/impl/time.c @@ -89,7 +89,7 @@ FFTimeGetAgeResult ffTimeGetAge(uint64_t birthMs, uint64_t nowMs) { #ifdef _WIN32 double ffQpcMultiplier; -__attribute__((constructor)) static void ffTimeInitQpcMultiplier(void) { +[[gnu::constructor]] static void ffTimeInitQpcMultiplier(void) { LARGE_INTEGER frequency; RtlQueryPerformanceFrequency(&frequency); ffQpcMultiplier = 1000. / (double) frequency.QuadPart; diff --git a/src/common/impl/tracer.c b/src/common/impl/tracer.c index e031cad0d6..aa46ad5453 100644 --- a/src/common/impl/tracer.c +++ b/src/common/impl/tracer.c @@ -30,7 +30,7 @@ static struct trace_event { } events[4 * 1024 * 1024]; // 4M events, 96 MiB memory usage static _Atomic uint32_t event_count; -__attribute__((no_instrument_function, always_inline)) static inline uint64_t get_time_us() { +[[gnu::no_instrument_function, gnu::always_inline]] static inline uint64_t get_time_us() { #if !_WIN32 struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); @@ -43,12 +43,12 @@ __attribute__((no_instrument_function, always_inline)) static inline uint64_t ge } #if _WIN32 -__attribute__((constructor, no_instrument_function)) void trace_init() { +[[gnu::constructor, gnu::no_instrument_function]] void trace_init() { QueryPerformanceFrequency(&freq); } #endif -__attribute__((destructor, no_instrument_function)) void trace_fini() { +[[gnu::destructor, gnu::no_instrument_function]] void trace_fini() { #if _WIN32 uint32_t pid = (uint32_t) GetCurrentProcessId(); #else @@ -67,10 +67,10 @@ __attribute__((destructor, no_instrument_function)) void trace_fini() { #if _WIN32 SymSetOptions(SYMOPT_DEFERRED_LOADS | SYMOPT_UNDNAME); - SymInitialize(NtCurrentProcess(), NULL, TRUE); + SymInitialize(NtCurrentProcess(), nullptr, TRUE); #endif - const char* fnName = NULL; + const char* fnName = nullptr; uint32_t count = atomic_load_explicit(&event_count, memory_order_acquire); for (uint32_t i = 0; i < count; ++i) { @@ -115,7 +115,7 @@ __attribute__((destructor, no_instrument_function)) void trace_fini() { #endif } -__attribute__((no_instrument_function)) static void write_event(void* this_fn, bool is_exit) { +[[gnu::no_instrument_function]] static void write_event(void* this_fn, bool is_exit) { uint32_t idx = atomic_fetch_add_explicit(&event_count, 1, memory_order_relaxed); if (__builtin_expect(idx >= sizeof(events) / sizeof(events[0]), false)) { abort(); @@ -137,12 +137,12 @@ __attribute__((no_instrument_function)) static void write_event(void* this_fn, b } } -__attribute__((no_instrument_function)) void __cyg_profile_func_enter(void* this_fn, void* call_site) { +[[gnu::no_instrument_function]] void __cyg_profile_func_enter(void* this_fn, void* call_site) { (void) call_site; write_event(this_fn, false); } -__attribute__((no_instrument_function)) void __cyg_profile_func_exit(void* this_fn, void* call_site) { +[[gnu::no_instrument_function]] void __cyg_profile_func_exit(void* this_fn, void* call_site) { (void) call_site; write_event(this_fn, true); } diff --git a/src/common/io.h b/src/common/io.h index e317120616..9086bea43e 100644 --- a/src/common/io.h +++ b/src/common/io.h @@ -40,17 +40,16 @@ HANDLE openat(HANDLE dfd, const char* fileName, int oflag); HANDLE openatW(HANDLE dfd, const wchar_t* fileName, uint16_t fileNameLen, bool directory); #endif -FF_A_ALWAYS_INLINE static inline bool ffIsValidNativeFD(FFNativeFD fd) { #ifndef _WIN32 return fd >= 0; #else // https://devblogs.microsoft.com/oldnewthing/20040302-00/?p=40443 - return fd != INVALID_HANDLE_VALUE && fd != NULL; + return fd != INVALID_HANDLE_VALUE && fd != nullptr; #endif } -FF_A_ALWAYS_INLINE FF_A_NONNULL(1) +[[gnu::always_inline, gnu::nonnull(1)]] static inline void wrapClose(FFNativeFD* pfd) { assert(pfd); @@ -62,7 +61,7 @@ static inline void wrapClose(FFNativeFD* pfd) { #endif } } -#define FF_AUTO_CLOSE_FD FF_A_CLEANUP(wrapClose) +#define FF_AUTO_CLOSE_FD [[gnu::cleanup(wrapClose)]] static inline FFNativeFD FFUnixFD2NativeFD(int unixfd) { #ifndef _WIN32 @@ -72,31 +71,36 @@ static inline FFNativeFD FFUnixFD2NativeFD(int unixfd) { #endif } -FF_A_NONNULL(3) static inline bool ffWriteFDData(FFNativeFD fd, size_t dataSize, const void* data) { +[[gnu::nonnull(3)]] +static inline bool ffWriteFDData(FFNativeFD fd, size_t dataSize, const void* data) { #ifndef _WIN32 return write(fd, data, dataSize) != -1; #else DWORD written; - return WriteFile(fd, data, (DWORD) dataSize, &written, NULL) && written == dataSize; + return WriteFile(fd, data, (DWORD) dataSize, &written, nullptr) && written == dataSize; #endif } -FF_A_NONNULL(2) static inline bool ffWriteFDBuffer(FFNativeFD fd, const FFstrbuf* content) { +[[gnu::nonnull(2)]] +static inline bool ffWriteFDBuffer(FFNativeFD fd, const FFstrbuf* content) { return ffWriteFDData(fd, content->length, content->chars); } -FF_A_NONNULL(1, 3) bool ffWriteFileData(const char* fileName, size_t dataSize, const void* data); +[[gnu::nonnull(1, 3)]] +bool ffWriteFileData(const char* fileName, size_t dataSize, const void* data); -FF_A_NONNULL(1, 2) static inline bool ffWriteFileBuffer(const char* fileName, const FFstrbuf* buffer) { +[[gnu::nonnull(1, 2)]] +static inline bool ffWriteFileBuffer(const char* fileName, const FFstrbuf* buffer) { return ffWriteFileData(fileName, buffer->length, buffer->chars); } -FF_A_NONNULL(3) static inline ssize_t ffReadFDData(FFNativeFD fd, size_t dataSize, void* data) { +[[gnu::nonnull(3)]] +static inline ssize_t ffReadFDData(FFNativeFD fd, size_t dataSize, void* data) { #ifndef _WIN32 return read(fd, data, dataSize); #else DWORD bytesRead; - if (!ReadFile(fd, data, (DWORD) dataSize, &bytesRead, NULL)) { + if (!ReadFile(fd, data, (DWORD) dataSize, &bytesRead, nullptr)) { return -1; } @@ -104,14 +108,14 @@ FF_A_NONNULL(3) static inline ssize_t ffReadFDData(FFNativeFD fd, size_t dataSiz #endif } -FF_A_NONNULL(2) bool ffAppendFDBuffer(FFNativeFD fd, FFstrbuf* buffer); +[[gnu::nonnull(2)]] bool ffAppendFDBuffer(FFNativeFD fd, FFstrbuf* buffer); -FF_A_NONNULL(1, 3) static inline ssize_t ffReadFileData(const char* fileName, size_t dataSize, void* data) { - FFNativeFD FF_AUTO_CLOSE_FD fd = +[[gnu::nonnull(1, 3)]] static inline ssize_t ffReadFileData(const char* fileName, size_t dataSize, void* data) { + FF_AUTO_CLOSE_FD FFNativeFD fd = #ifndef _WIN32 open(fileName, O_RDONLY | O_CLOEXEC); #else - CreateFileA(fileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + CreateFileA(fileName, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); #endif if (!ffIsValidNativeFD(fd)) { @@ -121,8 +125,8 @@ FF_A_NONNULL(1, 3) static inline ssize_t ffReadFileData(const char* fileName, si return ffReadFDData(fd, dataSize, data); } -FF_A_NONNULL(2, 4) static inline ssize_t ffReadFileDataRelative(FFNativeFD dfd, const char* fileName, size_t dataSize, void* data) { - FFNativeFD FF_AUTO_CLOSE_FD fd = openat(dfd, fileName, O_RDONLY | O_CLOEXEC); +[[gnu::nonnull(2, 4)]] static inline ssize_t ffReadFileDataRelative(FFNativeFD dfd, const char* fileName, size_t dataSize, void* data) { + FF_AUTO_CLOSE_FD FFNativeFD fd = openat(dfd, fileName, O_RDONLY | O_CLOEXEC); if (!ffIsValidNativeFD(fd)) { return -1; } @@ -130,12 +134,12 @@ FF_A_NONNULL(2, 4) static inline ssize_t ffReadFileDataRelative(FFNativeFD dfd, return ffReadFDData(fd, dataSize, data); } -FF_A_NONNULL(1, 2) static inline bool ffAppendFileBuffer(const char* fileName, FFstrbuf* buffer) { - FFNativeFD FF_AUTO_CLOSE_FD fd = +[[gnu::nonnull(1, 2)]] static inline bool ffAppendFileBuffer(const char* fileName, FFstrbuf* buffer) { + FF_AUTO_CLOSE_FD FFNativeFD fd = #ifndef _WIN32 open(fileName, O_RDONLY | O_CLOEXEC); #else - CreateFileA(fileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + CreateFileA(fileName, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); #endif if (!ffIsValidNativeFD(fd)) { @@ -145,8 +149,8 @@ FF_A_NONNULL(1, 2) static inline bool ffAppendFileBuffer(const char* fileName, F return ffAppendFDBuffer(fd, buffer); } -FF_A_NONNULL(2, 3) static inline bool ffAppendFileBufferRelative(FFNativeFD dfd, const char* fileName, FFstrbuf* buffer) { - FFNativeFD FF_AUTO_CLOSE_FD fd = openat(dfd, fileName, O_RDONLY | O_CLOEXEC); +[[gnu::nonnull(2, 3)]] static inline bool ffAppendFileBufferRelative(FFNativeFD dfd, const char* fileName, FFstrbuf* buffer) { + FF_AUTO_CLOSE_FD FFNativeFD fd = openat(dfd, fileName, O_RDONLY | O_CLOEXEC); if (!ffIsValidNativeFD(fd)) { return false; } @@ -154,33 +158,32 @@ FF_A_NONNULL(2, 3) static inline bool ffAppendFileBufferRelative(FFNativeFD dfd, return ffAppendFDBuffer(fd, buffer); } -FF_A_NONNULL(2) static inline bool ffReadFDBuffer(FFNativeFD fd, FFstrbuf* buffer) { +[[gnu::nonnull(2)]] static inline bool ffReadFDBuffer(FFNativeFD fd, FFstrbuf* buffer) { ffStrbufClear(buffer); return ffAppendFDBuffer(fd, buffer); } -FF_A_NONNULL(1, 2) static inline bool ffReadFileBuffer(const char* fileName, FFstrbuf* buffer) { +[[gnu::nonnull(1, 2)]] static inline bool ffReadFileBuffer(const char* fileName, FFstrbuf* buffer) { ffStrbufClear(buffer); return ffAppendFileBuffer(fileName, buffer); } -FF_A_NONNULL(2, 3) static inline bool ffReadFileBufferRelative(FFNativeFD dfd, const char* fileName, FFstrbuf* buffer) { +[[gnu::nonnull(2, 3)]] static inline bool ffReadFileBufferRelative(FFNativeFD dfd, const char* fileName, FFstrbuf* buffer) { ffStrbufClear(buffer); return ffAppendFileBufferRelative(dfd, fileName, buffer); } -typedef enum FF_A_PACKED FFPathType { +typedef enum FFPathType: uint8_t { FF_PATHTYPE_FILE = 1 << 0, FF_PATHTYPE_DIRECTORY = 1 << 1, FF_PATHTYPE_ANY = FF_PATHTYPE_FILE | FF_PATHTYPE_DIRECTORY, - FF_PATHTYPE_FORCE_UNSIGNED = UINT8_MAX, } FFPathType; -FF_A_NONNULL(1) static inline bool ffPathExists(const char* path, FFPathType pathType) { +[[gnu::nonnull(1)]] static inline bool ffPathExists(const char* path, FFPathType pathType) { #ifdef _WIN32 wchar_t wPath[MAX_PATH]; - if (!NT_SUCCESS(RtlUTF8ToUnicodeN(wPath, (ULONG) sizeof(wPath), NULL, path, (ULONG) strlen(path) + 1))) { + if (!NT_SUCCESS(RtlUTF8ToUnicodeN(wPath, (ULONG) sizeof(wPath), nullptr, path, (ULONG) strlen(path) + 1))) { return false; } @@ -225,13 +228,11 @@ FF_A_NONNULL(1) static inline bool ffPathExists(const char* path, FFPathType pat return false; } -FF_A_NONNULL(1, 2) bool ffPathExpandEnv(const char* in, FFstrbuf* out); +[[gnu::nonnull(1, 2)]] bool ffPathExpandEnv(const char* in, FFstrbuf* out); #define FF_IO_TERM_RESP_WAIT_MS 100 // #554 -FF_A_SCANF(3, 4) -FF_A_NONNULL(1, 3) -const char* ffGetTerminalResponse(const char* request, int nParams, const char* format, ...); +[[gnu::format(scanf, 3, 4), gnu::nonnull(1, 3)]] const char* ffGetTerminalResponse(const char* request, int nParams, const char* format, ...); // Not thread safe! bool ffSuppressIO(bool suppress); @@ -244,19 +245,19 @@ static inline void ffUnsuppressIO(bool* suppressed) { *suppressed = false; } -#define FF_SUPPRESS_IO() bool FF_A_CLEANUP(ffUnsuppressIO) FF_A_UNUSED io_suppressed__ = ffSuppressIO(true) +#define FF_SUPPRESS_IO() [[maybe_unused, gnu::cleanup(ffUnsuppressIO)]] bool io_suppressed__ = ffSuppressIO(true) void ffListFilesRecursively(const char* path, bool pretty); -FF_A_NONNULL(1) FF_A_ALWAYS_INLINE static inline void wrapFclose(FILE** pfile) { +[[gnu::nonnull(1), gnu::always_inline]] static inline void wrapFclose(FILE** pfile) { assert(pfile); if (*pfile) { fclose(*pfile); } } -#define FF_AUTO_CLOSE_FILE FF_A_CLEANUP(wrapFclose) +#define FF_AUTO_CLOSE_FILE [[gnu::cleanup(wrapFclose)]] -FF_A_NONNULL(1) FF_A_ALWAYS_INLINE +[[gnu::nonnull(1), gnu::always_inline]] #ifndef _WIN32 static inline void wrapClosedir(DIR** pdir) { assert(pdir); @@ -272,9 +273,9 @@ static inline void wrapClosedir(HANDLE* pdir) { } } #endif -#define FF_AUTO_CLOSE_DIR FF_A_CLEANUP(wrapClosedir) +#define FF_AUTO_CLOSE_DIR [[gnu::cleanup(wrapClosedir)]] -FF_A_NONNULL(1, 2, 3) static inline bool ffSearchUserConfigFile(const FFlist* configDirs, const char* fileSubpath, FFstrbuf* result) { +[[gnu::nonnull(1, 2, 3)]] static inline bool ffSearchUserConfigFile(const FFlist* configDirs, const char* fileSubpath, FFstrbuf* result) { // configDirs is a list of FFstrbufs include the trailing slash FF_LIST_FOR_EACH (FFstrbuf, dir, *configDirs) { ffStrbufClear(result); diff --git a/src/common/library.h b/src/common/library.h index a584fbfc86..06003cc938 100644 --- a/src/common/library.h +++ b/src/common/library.h @@ -6,8 +6,8 @@ #if defined(_WIN32) #define FF_DLOPEN_FLAGS 0 -FF_A_NODISCARD void* dlopen(const char* path, int mode); -FF_A_NODISCARD void* dlsym(void* handle, const char* symbol); +[[nodiscard]] void* dlopen(const char* path, int mode); +[[nodiscard]] void* dlsym(void* handle, const char* symbol); int dlclose(void* handle); #else #include @@ -28,39 +28,38 @@ static inline void ffLibraryUnload(void** handle) { } } - #if __cplusplus - #define __auto_type auto - #endif - #define FF_LIBRARY_SYMBOL(symbolName) \ - __typeof__(&symbolName) ff##symbolName; + typeof(&symbolName) ff##symbolName; #define FF_LIBRARY_LOAD(libraryObjectName, returnValue, libraryFileName, maxVersion, ...) \ - void* FF_A_CLEANUP(ffLibraryUnload) libraryObjectName = ffLibraryLoadSingle(libraryFileName, maxVersion); \ - __VA_OPT__(if (__builtin_expect(libraryObjectName == NULL, false)) libraryObjectName = ffLibraryLoadMulti(__VA_ARGS__, NULL);) \ - if (__builtin_expect(libraryObjectName == NULL, false)) \ + [[gnu::cleanup(ffLibraryUnload)]] void* libraryObjectName = ffLibraryLoadSingle(libraryFileName, maxVersion); \ + __VA_OPT__(if (__builtin_expect(libraryObjectName == nullptr, false)) libraryObjectName = ffLibraryLoadMulti(__VA_ARGS__, nullptr);) \ + if (__builtin_expect(libraryObjectName == nullptr, false)) \ return returnValue; #define FF_LIBRARY_LOAD_MESSAGE(libraryObjectName, libraryFileName, maxVersion, ...) \ FF_LIBRARY_LOAD(libraryObjectName, "dlopen(" libraryFileName ") failed", libraryFileName, maxVersion, ##__VA_ARGS__) #define FF_LIBRARY_LOAD_SYMBOL_ADDRESS(library, symbolMapping, symbolName, returnValue) \ - symbolMapping = (__typeof__(&symbolName)) dlsym(library, #symbolName); \ - if (__builtin_expect(symbolMapping == NULL, false)) \ + symbolMapping = (typeof(&symbolName)) dlsym(library, #symbolName); \ + if (__builtin_expect(symbolMapping == nullptr, false)) \ return returnValue; #define FF_LIBRARY_LOAD_SYMBOL(library, symbolName, returnValue) \ - __auto_type FF_LIBRARY_LOAD_SYMBOL_ADDRESS(library, ff##symbolName, symbolName, returnValue); + auto FF_LIBRARY_LOAD_SYMBOL_ADDRESS(library, ff##symbolName, symbolName, returnValue); #define FF_LIBRARY_LOAD_SYMBOL_LAZY(library, symbolName) \ - __auto_type ff##symbolName = (__typeof__(&symbolName)) dlsym(library, #symbolName); + auto ff##symbolName = (typeof(&symbolName)) dlsym(library, #symbolName); #define FF_LIBRARY_LOAD_SYMBOL_MESSAGE(library, symbolName) \ - __auto_type FF_LIBRARY_LOAD_SYMBOL_ADDRESS(library, ff##symbolName, symbolName, "dlsym " #symbolName " failed"); + auto FF_LIBRARY_LOAD_SYMBOL_ADDRESS(library, ff##symbolName, symbolName, "dlsym " #symbolName " failed"); #define FF_LIBRARY_LOAD_SYMBOL_VAR(library, varName, symbolName, returnValue) \ FF_LIBRARY_LOAD_SYMBOL_ADDRESS(library, (varName).ff##symbolName, symbolName, returnValue); + #define FF_LIBRARY_LOAD_SYMBOL_VAR_LAZY(library, varName, symbolName) \ + (varName).ff##symbolName = (typeof(&symbolName)) dlsym(library, #symbolName); + #define FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(library, varName, symbolName) \ FF_LIBRARY_LOAD_SYMBOL_ADDRESS(library, (varName).ff##symbolName, symbolName, "dlsym " #symbolName " failed"); @@ -75,29 +74,32 @@ void* ffLibraryLoadMulti(const char* path, int maxVersion, ...); #define FF_LIBRARY_EXTENSION "" #define FF_LIBRARY_SYMBOL(symbolName) \ - __typeof__(&symbolName) ff##symbolName; + typeof(&symbolName) ff##symbolName; #define FF_LIBRARY_LOAD(libraryObjectName, returnValue, ...) \ - FF_A_UNUSED void* libraryObjectName = NULL; // Placeholder + [[maybe_unused]] void* libraryObjectName = nullptr; // Placeholder #define FF_LIBRARY_LOAD_MESSAGE(libraryObjectName, libraryFileName, maxVersion, ...) \ FF_LIBRARY_LOAD(libraryObjectName, , libraryFileName, maxVersion, ##__VA_ARGS__) #define FF_LIBRARY_LOAD_SYMBOL_ADDRESS(library, symbolMapping, symbolName, returnValue) \ - symbolMapping = (__typeof__(&symbolName)) &symbolName; + symbolMapping = (typeof(&symbolName)) &symbolName; #define FF_LIBRARY_LOAD_SYMBOL(library, symbolName, returnValue) \ - FF_A_UNUSED __auto_type FF_LIBRARY_LOAD_SYMBOL_ADDRESS(library, ff##symbolName, symbolName, returnValue); + [[maybe_unused]] auto FF_LIBRARY_LOAD_SYMBOL_ADDRESS(library, ff##symbolName, symbolName, returnValue); #define FF_LIBRARY_LOAD_SYMBOL_LAZY(library, symbolName) \ - FF_A_UNUSED __auto_type ff##symbolName = (__typeof__(&symbolName)) &symbolName; + [[maybe_unused]] auto ff##symbolName = (typeof(&symbolName)) &symbolName; #define FF_LIBRARY_LOAD_SYMBOL_MESSAGE(library, symbolName) \ - FF_A_UNUSED __auto_type FF_LIBRARY_LOAD_SYMBOL_ADDRESS(library, ff##symbolName, symbolName, "dlsym " #symbolName " failed"); + [[maybe_unused]] auto FF_LIBRARY_LOAD_SYMBOL_ADDRESS(library, ff##symbolName, symbolName, "dlsym " #symbolName " failed"); #define FF_LIBRARY_LOAD_SYMBOL_VAR(library, varName, symbolName, returnValue) \ FF_LIBRARY_LOAD_SYMBOL_ADDRESS(library, (varName).ff##symbolName, symbolName, returnValue); + #define FF_LIBRARY_LOAD_SYMBOL_VAR_LAZY(library, varName, symbolName) \ + (varName).ff##symbolName = (typeof(&symbolName)) &symbolName; + #define FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(library, varName, symbolName) \ FF_LIBRARY_LOAD_SYMBOL_ADDRESS(library, (varName).ff##symbolName, symbolName, "dlsym " #symbolName " failed"); diff --git a/src/common/lua.h b/src/common/lua.h index 06343c40e7..fab613f128 100644 --- a/src/common/lua.h +++ b/src/common/lua.h @@ -63,95 +63,95 @@ extern struct FFLuaData { } luaData; #if !FF_DISABLE_DLOPEN -FF_A_ALWAYS_INLINE void(lua_settop)(lua_State* L, int idx) { +[[gnu::always_inline]] void(lua_settop)(lua_State* L, int idx) { return luaData.fflua_settop(L, idx); } -FF_A_ALWAYS_INLINE int(luaL_loadbufferx)(lua_State* L, const char* buff, size_t sz, const char* name, const char* mode) { +[[gnu::always_inline]] int(luaL_loadbufferx)(lua_State* L, const char* buff, size_t sz, const char* name, const char* mode) { return luaData.ffluaL_loadbufferx(L, buff, sz, name, mode); } -FF_A_ALWAYS_INLINE const char*(lua_tolstring) (lua_State * L, int idx, size_t* len) { +[[gnu::always_inline]] const char*(lua_tolstring) (lua_State * L, int idx, size_t* len) { return luaData.fflua_tolstring(L, idx, len); } -FF_A_ALWAYS_INLINE void(lua_createtable)(lua_State* L, int narr, int nrec) { +[[gnu::always_inline]] void(lua_createtable)(lua_State* L, int narr, int nrec) { return luaData.fflua_createtable(L, narr, nrec); } -FF_A_ALWAYS_INLINE void(lua_pushinteger)(lua_State* L, lua_Integer n) { +[[gnu::always_inline]] void(lua_pushinteger)(lua_State* L, lua_Integer n) { return luaData.fflua_pushinteger(L, n); } -FF_A_ALWAYS_INLINE void(lua_pushnumber)(lua_State* L, lua_Number n) { +[[gnu::always_inline]] void(lua_pushnumber)(lua_State* L, lua_Number n) { return luaData.fflua_pushnumber(L, n); } -FF_A_ALWAYS_INLINE void(lua_pushboolean)(lua_State* L, int b) { +[[gnu::always_inline]] void(lua_pushboolean)(lua_State* L, int b) { return luaData.fflua_pushboolean(L, b); } -FF_A_ALWAYS_INLINE const char*(lua_pushlstring) (lua_State * L, const char* s, size_t len) { +[[gnu::always_inline]] const char*(lua_pushlstring) (lua_State * L, const char* s, size_t len) { return luaData.fflua_pushlstring(L, s, len); } -FF_A_ALWAYS_INLINE void(lua_pushvalue)(lua_State* L, int idx) { +[[gnu::always_inline]] void(lua_pushvalue)(lua_State* L, int idx) { return luaData.fflua_pushvalue(L, idx); } -FF_A_ALWAYS_INLINE void(lua_seti)(lua_State* L, int idx, lua_Integer n) { +[[gnu::always_inline]] void(lua_seti)(lua_State* L, int idx, lua_Integer n) { return luaData.fflua_seti(L, idx, n); } -FF_A_ALWAYS_INLINE void(lua_pushnil)(lua_State* L) { +[[gnu::always_inline]] void(lua_pushnil)(lua_State* L) { return luaData.fflua_pushnil(L); } -FF_A_ALWAYS_INLINE void(lua_setfield)(lua_State* L, int idx, const char* k) { +[[gnu::always_inline]] void(lua_setfield)(lua_State* L, int idx, const char* k) { return luaData.fflua_setfield(L, idx, k); } -FF_A_ALWAYS_INLINE int(lua_pcallk)(lua_State* L, int nargs, int nresults, int errfunc, lua_KContext ctx, lua_KFunction k) { +[[gnu::always_inline]] int(lua_pcallk)(lua_State* L, int nargs, int nresults, int errfunc, lua_KContext ctx, lua_KFunction k) { return luaData.fflua_pcallk(L, nargs, nresults, errfunc, ctx, k); } -FF_A_ALWAYS_INLINE int(lua_gettop)(lua_State* L) { +[[gnu::always_inline]] int(lua_gettop)(lua_State* L) { return luaData.fflua_gettop(L); } -FF_A_ALWAYS_INLINE const char*(luaL_tolstring) (lua_State * L, int idx, size_t* len) { +[[gnu::always_inline]] const char*(luaL_tolstring) (lua_State * L, int idx, size_t* len) { return luaData.ffluaL_tolstring(L, idx, len); } -FF_A_ALWAYS_INLINE int(lua_error)(lua_State* L) { +[[gnu::always_inline]] int(lua_error)(lua_State* L) { return luaData.fflua_error(L); } -FF_A_ALWAYS_INLINE void(lua_pushcclosure)(lua_State* L, lua_CFunction fn, int n) { +[[gnu::always_inline]] void(lua_pushcclosure)(lua_State* L, lua_CFunction fn, int n) { return luaData.fflua_pushcclosure(L, fn, n); } -FF_A_ALWAYS_INLINE void(luaL_checkany)(lua_State* L, int idx) { +[[gnu::always_inline]] void(luaL_checkany)(lua_State* L, int idx) { return luaData.ffluaL_checkany(L, idx); } -FF_A_ALWAYS_INLINE void(lua_callk)(lua_State* L, int nargs, int nresults, lua_KContext ctx, lua_KFunction k) { +[[gnu::always_inline]] void(lua_callk)(lua_State* L, int nargs, int nresults, lua_KContext ctx, lua_KFunction k) { return luaData.fflua_callk(L, nargs, nresults, ctx, k); } -FF_A_ALWAYS_INLINE int(lua_isinteger)(lua_State* L, int idx) { +[[gnu::always_inline]] int(lua_isinteger)(lua_State* L, int idx) { return luaData.fflua_isinteger(L, idx); } -FF_A_ALWAYS_INLINE int(lua_next)(lua_State* L, int idx) { +[[gnu::always_inline]] int(lua_next)(lua_State* L, int idx) { return luaData.fflua_next(L, idx); } -FF_A_ALWAYS_INLINE int(lua_rawgeti)(lua_State* L, int idx, lua_Integer n) { +[[gnu::always_inline]] int(lua_rawgeti)(lua_State* L, int idx, lua_Integer n) { return luaData.fflua_rawgeti(L, idx, n); } -FF_A_ALWAYS_INLINE +[[gnu::always_inline]] #if LUA_VERSION_NUM > 503 lua_Unsigned #else @@ -161,23 +161,23 @@ size_t return luaData.fflua_rawlen(L, idx); } -FF_A_ALWAYS_INLINE void(lua_setglobal)(lua_State* L, const char* name) { +[[gnu::always_inline]] void(lua_setglobal)(lua_State* L, const char* name) { return luaData.fflua_setglobal(L, name); } -FF_A_ALWAYS_INLINE int(lua_toboolean)(lua_State* L, int idx) { +[[gnu::always_inline]] int(lua_toboolean)(lua_State* L, int idx) { return luaData.fflua_toboolean(L, idx); } -FF_A_ALWAYS_INLINE lua_Integer(lua_tointegerx)(lua_State* L, int idx, int* isnum) { +[[gnu::always_inline]] lua_Integer(lua_tointegerx)(lua_State* L, int idx, int* isnum) { return luaData.fflua_tointegerx(L, idx, isnum); } -FF_A_ALWAYS_INLINE lua_Number(lua_tonumberx)(lua_State* L, int idx, int* isnum) { +[[gnu::always_inline]] lua_Number(lua_tonumberx)(lua_State* L, int idx, int* isnum) { return luaData.fflua_tonumberx(L, idx, isnum); } -FF_A_ALWAYS_INLINE int(lua_type)(lua_State* L, int idx) { +[[gnu::always_inline]] int(lua_type)(lua_State* L, int idx) { return luaData.fflua_type(L, idx); } #endif diff --git a/src/common/mallocHelper.h b/src/common/mallocHelper.h index a130118388..e917fe6bf2 100644 --- a/src/common/mallocHelper.h +++ b/src/common/mallocHelper.h @@ -2,7 +2,6 @@ #include #include -#include "common/attributes.h" #if FF_HAVE_MALLOC_USABLE_SIZE || FF_HAVE_MSVC_MSIZE #if __has_include() @@ -14,7 +13,7 @@ #include #endif -FF_A_ALWAYS_INLINE FF_A_NONNULL(1) +[[gnu::always_inline, gnu::nonnull(1)]] static inline void ffWrapFree(const void* pPtr) { assert(pPtr); if (*(void**) pPtr) { @@ -22,7 +21,7 @@ static inline void ffWrapFree(const void* pPtr) { } } -#define FF_AUTO_FREE FF_A_CLEANUP(ffWrapFree) +#define FF_AUTO_FREE [[gnu::cleanup(ffWrapFree)]] // ptr MUST be a malloc'ed pointer static inline size_t ffMallocUsableSize(const void* ptr) { @@ -38,3 +37,180 @@ static inline size_t ffMallocUsableSize(const void* ptr) { return 0; // Not supported #endif } + +#if __cplusplus + + #include + #include + + #if defined(_WIN32) + #include + #endif + +[[gnu::always_inline]] +static inline void* ffAlignedAlloc(size_t size, size_t alignment) noexcept { + #if defined(_WIN32) + return _aligned_malloc(size, alignment); + #else + void* ptr = nullptr; + if (posix_memalign(&ptr, alignment, size) == 0) [[likely]] { + return ptr; + } + return nullptr; + #endif +} + +[[gnu::always_inline]] +static inline void ffAlignedFree(void* ptr) noexcept { + #if defined(_WIN32) + _aligned_free(ptr); + #else + ::free(ptr); + #endif +} + +[[gnu::always_inline]] +void* operator new(size_t size) { + if (void* ptr = ::malloc(size)) [[likely]] { + return ptr; + } + std::abort(); +} + +[[gnu::always_inline]] +void operator delete(void* ptr) noexcept { + ::free(ptr); +} + +[[gnu::always_inline]] +void operator delete(void* ptr, size_t size) noexcept { + (void) size; + ::free(ptr); +} + +[[gnu::always_inline]] +void* operator new(size_t size, const std::nothrow_t&) noexcept { + return ::malloc(size); +} + +[[gnu::always_inline]] +void operator delete(void* ptr, const std::nothrow_t&) noexcept { + ::free(ptr); +} + +[[gnu::always_inline]] +void operator delete(void* ptr, size_t size, const std::nothrow_t&) noexcept { + (void) size; + ::free(ptr); +} + +[[gnu::always_inline]] +void* operator new[](size_t size) { + if (void* ptr = ::malloc(size)) [[likely]] { + return ptr; + } + std::abort(); +} + +[[gnu::always_inline]] +void operator delete[](void* ptr) noexcept { + ::free(ptr); +} + +[[gnu::always_inline]] +void operator delete[](void* ptr, size_t size) noexcept { + (void) size; + ::free(ptr); +} + +[[gnu::always_inline]] +void* operator new[](size_t size, const std::nothrow_t&) noexcept { + return ::malloc(size); +} + +[[gnu::always_inline]] +void operator delete[](void* ptr, const std::nothrow_t&) noexcept { + ::free(ptr); +} + +[[gnu::always_inline]] +void operator delete[](void* ptr, size_t size, const std::nothrow_t&) noexcept { + (void) size; + ::free(ptr); +} + + #if __cplusplus >= 201703L // std::align_val_t (over-aligned new/delete, C++17) + +[[gnu::always_inline]] +void* operator new(size_t size, std::align_val_t alignment) { + if (void* ptr = ffAlignedAlloc(size, alignment)) { + return ptr; + } + std::abort(); +} + +[[gnu::always_inline]] +void operator delete(void* ptr, std::align_val_t) noexcept { + ffAlignedFree(ptr); +} + +[[gnu::always_inline]] +void operator delete(void* ptr, size_t size, std::align_val_t) noexcept { + (void) size; + ffAlignedFree(ptr); +} + +[[gnu::always_inline]] +void* operator new(size_t size, std::align_val_t alignment, const std::nothrow_t&) noexcept { + return ffAlignedAlloc(size, static_cast(alignment)); +} + +[[gnu::always_inline]] +void operator delete(void* ptr, std::align_val_t, const std::nothrow_t&) noexcept { + ffAlignedFree(ptr); +} + +[[gnu::always_inline]] +void operator delete(void* ptr, size_t size, std::align_val_t, const std::nothrow_t&) noexcept { + (void) size; + ffAlignedFree(ptr); +} + +[[gnu::always_inline]] +void* operator new[](size_t size, std::align_val_t alignment) { + if (void* ptr = ffAlignedAlloc(size, static_cast(alignment))) { + return ptr; + } + std::abort(); +} + +[[gnu::always_inline]] +void operator delete[](void* ptr, std::align_val_t) noexcept { + ffAlignedFree(ptr); +} + +[[gnu::always_inline]] +void operator delete[](void* ptr, size_t size, std::align_val_t) noexcept { + (void) size; + ffAlignedFree(ptr); +} + +[[gnu::always_inline]] +void* operator new[](size_t size, std::align_val_t alignment, const std::nothrow_t&) noexcept { + return ffAlignedAlloc(size, static_cast(alignment)); +} + +[[gnu::always_inline]] +void operator delete[](void* ptr, std::align_val_t, const std::nothrow_t&) noexcept { + ffAlignedFree(ptr); +} + +[[gnu::always_inline]] +void operator delete[](void* ptr, size_t size, std::align_val_t, const std::nothrow_t&) noexcept { + (void) size; + ffAlignedFree(ptr); +} + + #endif // __cplusplus >= 201703L + +#endif diff --git a/src/common/netif.h b/src/common/netif.h index d3984df423..75735f51bb 100644 --- a/src/common/netif.h +++ b/src/common/netif.h @@ -7,7 +7,7 @@ #include #endif -typedef enum FF_A_PACKED FFNetifDefaultRouteResultStatus { +typedef enum FFNetifDefaultRouteResultStatus: uint8_t { FF_NETIF_UNINITIALIZED, FF_NETIF_INVALID, FF_NETIF_OK diff --git a/src/common/option.h b/src/common/option.h index ce0a0ab015..e2697042c6 100644 --- a/src/common/option.h +++ b/src/common/option.h @@ -34,9 +34,10 @@ typedef struct FFModuleBaseInfo { bool (*generateJsonResult)(void* options, struct yyjson_mut_doc* doc, struct yyjson_mut_val* module); // true on success void (*generateJsonConfig)(void* options, struct yyjson_mut_doc* doc, struct yyjson_mut_val* obj); FFModuleFormatArgList formatArgs; + const uint8_t defaultOrder; } FFModuleBaseInfo; -typedef enum FF_A_PACKED FFModuleKeyType { +typedef enum FFModuleKeyType: uint8_t { FF_MODULE_KEY_TYPE_NONE = 0, FF_MODULE_KEY_TYPE_STRING = 1 << 0, FF_MODULE_KEY_TYPE_ICON = 1 << 1, @@ -47,7 +48,6 @@ typedef enum FF_A_PACKED FFModuleKeyType { FF_MODULE_KEY_TYPE_BOTH_2 = FF_MODULE_KEY_TYPE_BOTH_0 | (2 << FF_MODULE_KEY_TYPE_SPACE_SHIFT), FF_MODULE_KEY_TYPE_BOTH_3 = FF_MODULE_KEY_TYPE_BOTH_0 | (3 << FF_MODULE_KEY_TYPE_SPACE_SHIFT), FF_MODULE_KEY_TYPE_BOTH_4 = FF_MODULE_KEY_TYPE_BOTH_0 | (4 << FF_MODULE_KEY_TYPE_SPACE_SHIFT), - FF_MODULE_KEY_TYPE_FORCE_UNSIGNED = UINT8_MAX, } FFModuleKeyType; typedef struct FFModuleArgs { @@ -66,10 +66,10 @@ typedef struct FFKeyValuePair { const char* ffOptionTestPrefix(const char* argumentKey, const char* moduleName); void ffOptionParseString(const char* argumentKey, const char* value, FFstrbuf* buffer); -FF_A_NODISCARD uint32_t ffOptionParseUInt32(const char* argumentKey, const char* value); -FF_A_NODISCARD int32_t ffOptionParseInt32(const char* argumentKey, const char* value); -FF_A_NODISCARD int ffOptionParseEnum(const char* argumentKey, const char* requestedKey, FFKeyValuePair pairs[]); -FF_A_NODISCARD bool ffOptionParseBoolean(const char* str); +[[nodiscard]] uint32_t ffOptionParseUInt32(const char* argumentKey, const char* value); +[[nodiscard]] int32_t ffOptionParseInt32(const char* argumentKey, const char* value); +[[nodiscard]] int ffOptionParseEnum(const char* argumentKey, const char* requestedKey, FFKeyValuePair pairs[]); +[[nodiscard]] bool ffOptionParseBoolean(const char* str); void ffOptionParseColorNoClear(const char* value, FFstrbuf* buffer); static inline void ffOptionParseColor(const char* value, FFstrbuf* buffer) { ffStrbufClear(buffer); diff --git a/src/common/percent.h b/src/common/percent.h index c2eeba6b9d..5e71dc7d78 100644 --- a/src/common/percent.h +++ b/src/common/percent.h @@ -4,14 +4,13 @@ #include "common/parsing.h" #include "common/option.h" -typedef enum FF_A_PACKED FFPercentageTypeFlags { +typedef enum FFPercentageTypeFlags: uint8_t { FF_PERCENTAGE_TYPE_NONE = 0, FF_PERCENTAGE_TYPE_NUM_BIT = 1 << 0, FF_PERCENTAGE_TYPE_BAR_BIT = 1 << 1, FF_PERCENTAGE_TYPE_HIDE_OTHERS_BIT = 1 << 2, FF_PERCENTAGE_TYPE_NUM_COLOR_BIT = 1 << 3, FF_PERCENTAGE_TYPE_BAR_MONOCHROME_BIT = 1 << 4, - FF_PERCENTAGE_TYPE_FORCE_UNSIGNED_ = UINT8_MAX, } FFPercentageTypeFlags; static_assert(sizeof(FFPercentageTypeFlags) == 1, ""); diff --git a/src/common/printing.h b/src/common/printing.h index f20a244166..29f8c12279 100644 --- a/src/common/printing.h +++ b/src/common/printing.h @@ -3,19 +3,18 @@ #include "fastfetch.h" #include "common/format.h" -typedef enum FF_A_PACKED FFPrintType { +typedef enum FFPrintType: uint8_t { FF_PRINT_TYPE_DEFAULT = 0, FF_PRINT_TYPE_NO_CUSTOM_KEY = 1 << 0, // key has been formatted outside FF_PRINT_TYPE_NO_CUSTOM_KEY_COLOR = 1 << 1, FF_PRINT_TYPE_NO_CUSTOM_KEY_WIDTH = 1 << 2, FF_PRINT_TYPE_NO_CUSTOM_OUTPUT_FORMAT = 1 << 3, // reserved - FF_PRINT_TYPE_FORCE_UNSIGNED = UINT8_MAX, } FFPrintType; void ffPrintLogoAndKey(const char* moduleName, uint8_t moduleIndex, const FFModuleArgs* moduleArgs, FFPrintType printType); bool ffPrintFormat(const char* moduleName, uint8_t moduleIndex, const FFModuleArgs* moduleArgs, FFPrintType printType, uint32_t numArgs, const FFformatarg* arguments); #define FF_PRINT_FORMAT_CHECKED(moduleName, moduleIndex, moduleArgs, printType, arguments) \ ffPrintFormat((moduleName), (moduleIndex), (moduleArgs), (printType), (sizeof(arguments) / sizeof(*arguments)), (arguments)); -FF_A_PRINTF(5, 6) void ffPrintError(const char* moduleName, uint8_t moduleIndex, const FFModuleArgs* moduleArgs, FFPrintType printType, const char* message, ...); +[[gnu::format(printf, 5, 6)]] void ffPrintError(const char* moduleName, uint8_t moduleIndex, const FFModuleArgs* moduleArgs, FFPrintType printType, const char* message, ...); void ffPrintColor(const FFstrbuf* colorValue); void ffPrintCharTimes(char c, uint32_t times); diff --git a/src/common/settings.h b/src/common/settings.h index f2143cf46c..bd96634f91 100644 --- a/src/common/settings.h +++ b/src/common/settings.h @@ -2,10 +2,10 @@ #include "fastfetch.h" -typedef enum FF_A_PACKED FFvarianttype { +typedef enum FFvarianttype: uint8_t { FF_VARIANT_TYPE_STRING, FF_VARIANT_TYPE_BOOL, - FF_VARIANT_TYPE_INT + FF_VARIANT_TYPE_INT, } FFvarianttype; typedef union FFvariant { @@ -18,7 +18,7 @@ typedef union FFvariant { }; } FFvariant; -#define FF_VARIANT_NULL ((FFvariant) { .strValue = NULL }) +#define FF_VARIANT_NULL ((FFvariant) { .strValue = nullptr }) FFvariant ffSettingsGetDConf(const char* key, FFvarianttype type); FFvariant ffSettingsGetGSettings(const char* schemaName, const char* path, const char* key, FFvarianttype type); diff --git a/src/common/smbios.h b/src/common/smbios.h index 24edbdabb3..15c0b0ce6e 100644 --- a/src/common/smbios.h +++ b/src/common/smbios.h @@ -12,8 +12,7 @@ static inline void ffCleanUpSmbiosValue(FFstrbuf* value) { // https://github.com/KunYi/DumpSMBIOS // https://www.dmtf.org/sites/default/files/standards/documents/DSP0134_3.9.0.pdf -typedef enum FF_A_PACKED FFSmbiosType // : uint8_t -{ +typedef enum FFSmbiosType : uint8_t { FF_SMBIOS_TYPE_BIOS = 0, FF_SMBIOS_TYPE_SYSTEM_INFO = 1, FF_SMBIOS_TYPE_BASEBOARD_INFO = 2, @@ -68,7 +67,7 @@ typedef enum FF_A_PACKED FFSmbiosType // : uint8_t } FFSmbiosType; static_assert(sizeof(FFSmbiosType) == 1, "FFSmbiosType should be 1 byte"); -typedef struct FFSmbiosHeader { +typedef struct [[gnu::packed]] FFSmbiosHeader { // Type of SMBIOS structure. Do NOT test `Type == FF_SMBIOS_END_OF_TABLE` to determine the end of the table, // as malformed tables may be missing the end-of-table marker. // **Use FFSmbiosHeaderTable[FF_SMBIOS_TYPE_END_OF_TABLE] pointer instead.** @@ -80,12 +79,12 @@ typedef struct FFSmbiosHeader { // Not guaranteed to be consistent across reboots or even multiple reads of the same table. // Must be less than 0xFF00 uint16_t Handle; -} FF_A_PACKED FFSmbiosHeader; +} FFSmbiosHeader; static_assert(sizeof(FFSmbiosHeader) == 4, "FFSmbiosHeader should be 4 bytes"); static inline const char* ffSmbiosLocateString(const char* start, uint8_t index /* start from 1 */) { if (index == 0 || *start == '\0') { - return NULL; + return nullptr; } while (--index) { start += strlen(start) + 1; diff --git a/src/common/strutil.h b/src/common/strutil.h index 6d8b639b11..a9c43c4957 100644 --- a/src/common/strutil.h +++ b/src/common/strutil.h @@ -5,9 +5,6 @@ #include #include -#include "common/attributes.h" -#include "common/wcwidth.h" - #ifdef _WIN32 // #include __stdcall char* StrStrIA(const char* lpFirst, const char* lpSrch); @@ -18,7 +15,7 @@ __stdcall char* StrStrIA(const char* lpFirst, const char* lpSrch); #define FF_STR(x) FF_STR_INDIR(x) static inline bool ffStrSet(const char* str) { - if (str == NULL) { + if (str == nullptr) { return false; } @@ -29,17 +26,17 @@ static inline bool ffStrSet(const char* str) { return *str != '\0'; } -FF_A_ALWAYS_INLINE +[[gnu::always_inline]] static inline bool ffStrStartsWithIgnCase(const char* str, const char* compareTo) { return strncasecmp(str, compareTo, strlen(compareTo)) == 0; } -FF_A_ALWAYS_INLINE +[[gnu::always_inline]] static inline bool ffStrEqualsIgnCase(const char* str, const char* compareTo) { return strcasecmp(str, compareTo) == 0; } -FF_A_ALWAYS_INLINE +[[gnu::always_inline]] static inline bool ffStrStartsWith(const char* str, const char* compareTo) { return strncmp(str, compareTo, strlen(compareTo)) == 0; } @@ -62,32 +59,32 @@ static inline bool ffStrEndsWithIgnCase(const char* str, const char* compareTo) return strncasecmp(str + strLength - compareToLength, compareTo, compareToLength) == 0; } -FF_A_ALWAYS_INLINE +[[gnu::always_inline]] static inline bool ffStrEquals(const char* str, const char* compareTo) { return strcmp(str, compareTo) == 0; } -FF_A_ALWAYS_INLINE +[[gnu::always_inline]] static inline bool ffStrContains(const char* str, const char* compareTo) { - return strstr(str, compareTo) != NULL; + return strstr(str, compareTo) != nullptr; } -FF_A_ALWAYS_INLINE +[[gnu::always_inline]] static inline bool ffStrContainsIgnCase(const char* str, const char* compareTo) { - return strcasestr(str, compareTo) != NULL; + return strcasestr(str, compareTo) != nullptr; } -FF_A_ALWAYS_INLINE +[[gnu::always_inline]] static inline bool ffStrContainsC(const char* str, char compareTo) { - return strchr(str, compareTo) != NULL; + return strchr(str, compareTo) != nullptr; } -FF_A_ALWAYS_INLINE +[[gnu::always_inline]] static inline bool ffCharIsEnglishAlphabet(char c) { return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z'); } -FF_A_ALWAYS_INLINE +[[gnu::always_inline]] static inline bool ffCharIsDigit(char c) { return '0' <= c && c <= '9'; } @@ -99,7 +96,7 @@ uint8_t ffUtf8CharLenWidth(const char* str, uint32_t length, uint8_t* width); uint32_t ffUtf8StrWidth(const char* str, uint32_t length); -FF_A_ALWAYS_INLINE +[[gnu::always_inline]] static inline bool ffCharIsHexDigit(char c) { return ffCharIsDigit(c) || ('a' <= c && c <= 'f') || ('A' <= c && c <= 'F'); } @@ -118,7 +115,7 @@ static inline int8_t ffHexCharToInt(char c) { // Copies at most (dstBufSiz - 1) bytes from src to dst; dst is always null-terminated static inline char* ffStrCopy(char* __restrict__ dst, const char* __restrict__ src, size_t dstBufSiz) { - if (__builtin_expect(dst == NULL, false) || dstBufSiz == 0) { + if (__builtin_expect(dst == nullptr, false) || dstBufSiz == 0) { return dst; } diff --git a/src/common/sysctl.h b/src/common/sysctl.h index 1baabe6285..7e59ec663c 100644 --- a/src/common/sysctl.h +++ b/src/common/sysctl.h @@ -7,11 +7,11 @@ #ifdef __OpenBSD__ const char* ffSysctlGetString(int mib1, int mib2, FFstrbuf* result); -FF_A_NODISCARD int ffSysctlGetInt(int mib1, int mib2, int defaultValue); -FF_A_NODISCARD int64_t ffSysctlGetInt64(int mib1, int mib2, int64_t defaultValue); +[[nodiscard]] int ffSysctlGetInt(int mib1, int mib2, int defaultValue); +[[nodiscard]] int64_t ffSysctlGetInt64(int mib1, int mib2, int64_t defaultValue); #else const char* ffSysctlGetString(const char* propName, FFstrbuf* result); -FF_A_NODISCARD int ffSysctlGetInt(const char* propName, int defaultValue); -FF_A_NODISCARD int64_t ffSysctlGetInt64(const char* propName, int64_t defaultValue); +[[nodiscard]] int ffSysctlGetInt(const char* propName, int defaultValue); +[[nodiscard]] int64_t ffSysctlGetInt64(const char* propName, int64_t defaultValue); #endif -FF_A_NODISCARD void* ffSysctlGetData(int* request, u_int requestLength, size_t* resultLength); +[[nodiscard]] void* ffSysctlGetData(int* request, u_int requestLength, size_t* resultLength); diff --git a/src/common/thread.h b/src/common/thread.h index 84c247cae8..c8212c2550 100644 --- a/src/common/thread.h +++ b/src/common/thread.h @@ -18,7 +18,7 @@ static inline void ffThreadMutexUnlock(FFThreadMutex* mutex) { ReleaseSRWLockExclusive(mutex); } static inline FFThreadType ffThreadCreate(unsigned(__stdcall* func)(void*), void* data) { - return (FFThreadType) _beginthreadex(NULL, 0, func, data, 0, NULL); + return (FFThreadType) _beginthreadex(nullptr, 0, func, data, 0, nullptr); } #define FF_THREAD_ENTRY_DECL_WRAPPER(fn, paramType) \ static __stdcall unsigned fn##ThreadMain(void* data) { \ @@ -34,7 +34,7 @@ static inline void ffThreadDetach(FFThreadType thread) { NtClose(thread); } static inline bool ffThreadJoin(FFThreadType thread, uint32_t timeout) { - if (NtWaitForSingleObject(thread, FALSE, timeout == 0 ? NULL : &(LARGE_INTEGER) { .QuadPart = (int64_t) timeout * -10000 }) != STATUS_WAIT_0) { + if (NtWaitForSingleObject(thread, FALSE, timeout == 0 ? nullptr : &(LARGE_INTEGER) { .QuadPart = (int64_t) timeout * -10000 }) != STATUS_WAIT_0) { TerminateThread(thread, (DWORD) -1); NtClose(thread); return false; @@ -74,30 +74,30 @@ static inline void ffThreadMutexUnlock(FFThreadMutex* mutex) { #endif static inline FFThreadType ffThreadCreate(void* (*func)(void*), void* data) { FFThreadType newThread = 0; - pthread_create(&newThread, NULL, func, data); + pthread_create(&newThread, nullptr, func, data); return newThread; } #define FF_THREAD_ENTRY_DECL_WRAPPER(fn, paramType) \ static void* fn##ThreadMain(void* data) { \ fn((paramType) data); \ - return NULL; \ + return nullptr; \ } #define FF_THREAD_ENTRY_DECL_WRAPPER_NOPARAM(fn) \ static void* fn##ThreadMain() { \ fn(); \ - return NULL; \ + return nullptr; \ } static inline void ffThreadDetach(FFThreadType thread) { pthread_detach(thread); } -static inline bool ffThreadJoin(FFThreadType thread, FF_A_UNUSED uint32_t timeout) { +static inline bool ffThreadJoin(FFThreadType thread, [[maybe_unused]] uint32_t timeout) { #if HAVE_TIMEDJOIN_NP if (timeout > 0) { struct timespec ts; if (clock_gettime(CLOCK_REALTIME, &ts) == 0) { ts.tv_sec += timeout / 1000; ts.tv_nsec += (timeout % 1000) * 1000000; - if (pthread_timedjoin_np(thread, NULL, &ts) != 0) { + if (pthread_timedjoin_np(thread, nullptr, &ts) != 0) { pthread_kill(thread, SIGTERM); return false; } @@ -105,7 +105,7 @@ static inline bool ffThreadJoin(FFThreadType thread, FF_A_UNUSED uint32_t timeou } } #endif - pthread_join(thread, NULL); + pthread_join(thread, nullptr); return true; } static inline uintptr_t ffThreadGetCurrentId() { @@ -115,7 +115,7 @@ static inline uintptr_t ffThreadGetCurrentId() { #else // FF_HAVE_THREADS #define FF_THREAD_MUTEX_INITIALIZER 0 typedef char FFThreadMutex; -static inline void ffThreadMutexLock(FF_A_UNUSED FFThreadMutex* mutex) {} -static inline void ffThreadMutexUnlock(FF_A_UNUSED FFThreadMutex* mutex) {} +static inline void ffThreadMutexLock([[maybe_unused]] FFThreadMutex* mutex) {} +static inline void ffThreadMutexUnlock([[maybe_unused]] FFThreadMutex* mutex) {} #define FF_THREAD_ENTRY_DECL_WRAPPER(fn, paramType) #endif // FF_HAVE_THREADS diff --git a/src/common/time.h b/src/common/time.h index e2d86ab1de..a4d25341bb 100644 --- a/src/common/time.h +++ b/src/common/time.h @@ -58,7 +58,7 @@ static inline bool ffTimeSleep(uint32_t msec) { interval.QuadPart = -(int64_t) msec * 10000; // Relative time in 100-nanosecond intervals return NT_SUCCESS(NtDelayExecution(TRUE, &interval)); #else - return nanosleep(&(struct timespec) { msec / 1000, (long) (msec % 1000) * 1000000 }, NULL) == 0; + return nanosleep(&(struct timespec) { msec / 1000, (long) (msec % 1000) * 1000000 }, nullptr) == 0; #endif } diff --git a/src/common/unused.h b/src/common/unused.h index 98e21a2e6e..9eb9f7dca4 100644 --- a/src/common/unused.h +++ b/src/common/unused.h @@ -1,6 +1,4 @@ #pragma once -static inline void ffUnused(int dummy, ...) { - (void) dummy; -} -#define FF_UNUSED(...) ffUnused(0, __VA_ARGS__); +static inline void ffUnused(...) { /* no-op */ } +#define FF_UNUSED(...) ffUnused(__VA_ARGS__); diff --git a/src/common/windows/com.c b/src/common/windows/com.c index a400ca9c65..1dab646cd8 100644 --- a/src/common/windows/com.c +++ b/src/common/windows/com.c @@ -21,14 +21,14 @@ static const char* doInitCom() { return "RoInitialize() failed: unexpected error"; case RPC_E_CHANGED_MODE: // COM was already initialized with a different concurrency model - return NULL; + return nullptr; default: return "RoInitialize() failed: unknown error"; } } atexit(RoUninitializeWrap); - return NULL; + return nullptr; } #else #include @@ -38,7 +38,7 @@ static void CoUninitializeWrap(void) { } static const char* doInitCom() { - HRESULT res = CoInitializeEx(NULL, COINIT_MULTITHREADED); + HRESULT res = CoInitializeEx(nullptr, COINIT_MULTITHREADED); if (FAILED(res)) { switch (res) { case E_INVALIDARG: @@ -47,14 +47,14 @@ static const char* doInitCom() { return "CoInitializeEx() failed: out of memory"; case RPC_E_CHANGED_MODE: // COM was already initialized with a different concurrency model - return NULL; + return nullptr; default: return "CoInitializeEx() failed: unknown error"; } } atexit(CoUninitializeWrap); - return NULL; + return nullptr; } #endif diff --git a/src/common/windows/com.h b/src/common/windows/com.h index 57b8c6d812..34de125dd9 100644 --- a/src/common/windows/com.h +++ b/src/common/windows/com.h @@ -1,6 +1,5 @@ #pragma once -#include "common/attributes.h" #include #include @@ -16,8 +15,8 @@ static inline void ffReleaseComObject(void* ppUnknown) { #else pUnknown->lpVtbl->Release(pUnknown); #endif - *(IUnknown**) ppUnknown = NULL; + *(IUnknown**) ppUnknown = nullptr; } } -#define FF_AUTO_RELEASE_COM_OBJECT FF_A_CLEANUP(ffReleaseComObject) +#define FF_AUTO_RELEASE_COM_OBJECT [[gnu::cleanup(ffReleaseComObject)]] diff --git a/src/common/windows/getline.c b/src/common/windows/getline.c index 3d43d55f37..fda41b0a4f 100644 --- a/src/common/windows/getline.c +++ b/src/common/windows/getline.c @@ -7,7 +7,7 @@ ssize_t getline(char** lineptr, size_t* n, FILE* stream) { ssize_t pos = -1; int c; - if (lineptr == NULL || stream == NULL || n == NULL) { + if (lineptr == nullptr || stream == nullptr || n == nullptr) { errno = EINVAL; return -1; } @@ -19,9 +19,9 @@ ssize_t getline(char** lineptr, size_t* n, FILE* stream) { goto exit; } - if (*lineptr == NULL) { + if (*lineptr == nullptr) { *lineptr = malloc(128); - if (*lineptr == NULL) { + if (*lineptr == nullptr) { goto exit; } *n = 128; @@ -35,7 +35,7 @@ ssize_t getline(char** lineptr, size_t* n, FILE* stream) { new_size = 128; } char* new_ptr = realloc(*lineptr, new_size); - if (new_ptr == NULL) { + if (new_ptr == nullptr) { pos = -1; goto exit; } diff --git a/src/common/windows/nt.h b/src/common/windows/nt.h index 2f476b8d64..77e0a00c18 100644 --- a/src/common/windows/nt.h +++ b/src/common/windows/nt.h @@ -604,7 +604,7 @@ typedef struct _KUSER_SHARED_DATA { #ifdef __aarch64__ #define SharedUserData ({ \ - __auto_type shared_user_data = (const volatile KUSER_SHARED_DATA*) (uintptr_t) 0x7FFE0000UL; \ + auto shared_user_data = (const volatile KUSER_SHARED_DATA*) (uintptr_t) 0x7FFE0000UL; \ __asm__("" : "+r"(shared_user_data)); /* https://github.com/lhmouse/mcfgthread/issues/330 */ \ shared_user_data; \ }) diff --git a/src/common/windows/registry.c b/src/common/windows/registry.c index 3618760c20..8bd2e09fd9 100644 --- a/src/common/windows/registry.c +++ b/src/common/windows/registry.c @@ -42,7 +42,7 @@ HANDLE ffRegGetRootKeyHandle(HKEY hKey) { NTSTATUS status = RtlOpenCurrentUser(KEY_READ, &result); if (!NT_SUCCESS(status)) { FF_DEBUG("RtlOpenCurrentUser() failed: %s", ffDebugNtStatus(status)); - return NULL; + return nullptr; } break; } @@ -51,13 +51,13 @@ HANDLE ffRegGetRootKeyHandle(HKEY hKey) { UNICODE_STRING path = RTL_CONSTANT_STRING(L"\\Registry\\Machine"); NTSTATUS status = NtOpenKey(&result, KEY_READ, &(OBJECT_ATTRIBUTES) { .Length = sizeof(OBJECT_ATTRIBUTES), - .RootDirectory = NULL, + .RootDirectory = nullptr, .ObjectName = &path, .Attributes = OBJ_CASE_INSENSITIVE, }); if (!NT_SUCCESS(status)) { FF_DEBUG("NtOpenKey(%ls) failed: %s (0x%08lx)", path.Buffer, ffDebugNtStatus(status), status); - return NULL; + return nullptr; } break; } @@ -65,7 +65,7 @@ HANDLE ffRegGetRootKeyHandle(HKEY hKey) { // Unsupported FF_DEBUG("Unsupported root key: %p", hKey); assert(false); - return NULL; + return nullptr; } hRootKeys[(uintptr_t) hKey - (uintptr_t) HKEY_CLASSES_ROOT] = result; FF_DEBUG("Opened root key %s -> %p", hKey2Str(result), result); @@ -241,7 +241,7 @@ bool ffRegReadValue(HANDLE hKey, const FFRegValueArg* arg, FFstrbuf* error) { }; alignas(KEY_VALUE_PARTIAL_INFORMATION) uint8_t staticBuffer[128 + sizeof(KEY_VALUE_PARTIAL_INFORMATION)]; - FF_AUTO_FREE uint8_t* dynamicBuffer = NULL; + FF_AUTO_FREE uint8_t* dynamicBuffer = nullptr; KEY_VALUE_PARTIAL_INFORMATION* buffer = (KEY_VALUE_PARTIAL_INFORMATION*) &staticBuffer; DWORD bufSize = sizeof(staticBuffer); @@ -287,9 +287,9 @@ bool ffRegReadValues(HANDLE hKey, uint32_t argc, const FFRegValueArg argv[], FFs for (uint32_t i = 0; i < argc; ++i) { if (__builtin_expect(!argv[i].value, false)) { - FF_DEBUG("ffRegReadValues(argv[%u].value) is NULL", (unsigned) i); + FF_DEBUG("ffRegReadValues(argv[%u].value) is nullptr", (unsigned) i); if (error) { - ffStrbufAppendF(error, "ffRegReadValues(argv[%u].pVar) is NULL", (unsigned) i); + ffStrbufAppendF(error, "ffRegReadValues(argv[%u].pVar) is nullptr", (unsigned) i); } return false; } @@ -307,7 +307,7 @@ bool ffRegReadValues(HANDLE hKey, uint32_t argc, const FFRegValueArg argv[], FFs bufferSize = 512; } - FF_AUTO_FREE uint8_t* buffer = NULL; + FF_AUTO_FREE uint8_t* buffer = nullptr; while (true) { buffer = (uint8_t*) realloc(buffer, bufferSize); diff --git a/src/common/windows/unicode.c b/src/common/windows/unicode.c index 06008ba429..534c399f20 100644 --- a/src/common/windows/unicode.c +++ b/src/common/windows/unicode.c @@ -9,7 +9,7 @@ void ffStrbufSetNWS(FFstrbuf* result, uint32_t length, const wchar_t* source) { } ULONG size_needed = 0; - NTSTATUS status = RtlUnicodeToUTF8N(NULL, 0, &size_needed, source, length * sizeof(wchar_t)); + NTSTATUS status = RtlUnicodeToUTF8N(nullptr, 0, &size_needed, source, length * sizeof(wchar_t)); if (size_needed == 0) { ffStrbufSetF(result, "RtlUnicodeToUTF8N failed: %X", (unsigned) status); @@ -29,7 +29,7 @@ void ffStrbufAppendNWS(FFstrbuf* result, uint32_t length, const wchar_t* source) } ULONG size_needed = 0; - NTSTATUS status = RtlUnicodeToUTF8N(NULL, 0, &size_needed, source, length * sizeof(wchar_t)); + NTSTATUS status = RtlUnicodeToUTF8N(nullptr, 0, &size_needed, source, length * sizeof(wchar_t)); if (size_needed == 0) { ffStrbufAppendF(result, "RtlUnicodeToUTF8N failed: %X", (unsigned) status); diff --git a/src/common/windows/wmi.h b/src/common/windows/wmi.h index aa50c00439..2ff6282f51 100644 --- a/src/common/windows/wmi.h +++ b/src/common/windows/wmi.h @@ -49,6 +49,4 @@ static inline void ffCloseWmiBlock(HANDLE* hBlock) { } } -#define FF_AUTO_CLOSE_WMI_BLOCK __attribute__((cleanup(ffCloseWmiBlock))) - // MOF: https://github.com/tpn/winsdk-10/blob/master/Include/10.0.16299.0/km/wmicore.mof diff --git a/src/detection/battery/battery_android.c b/src/detection/battery/battery_android.c index d76c4adaaa..325be96cb7 100644 --- a/src/detection/battery/battery_android.c +++ b/src/detection/battery/battery_android.c @@ -17,11 +17,11 @@ static inline void wrapYyjsonFree(yyjson_doc** doc) { static const char* parseTermuxApi(FFBatteryOptions* options, FFlist* results) { FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); - if (ffProcessAppendStdOut(&buffer, (char* const[]) { FF_TERMUX_API_PATH, FF_TERMUX_API_PARAM, NULL })) { + if (ffProcessAppendStdOut(&buffer, (char* const[]) { FF_TERMUX_API_PATH, FF_TERMUX_API_PARAM, nullptr })) { return "Starting `" FF_TERMUX_API_PATH " " FF_TERMUX_API_PARAM "` failed"; } - yyjson_doc* FF_A_CLEANUP(wrapYyjsonFree) doc = yyjson_read_opts(buffer.chars, buffer.length, 0, NULL, NULL); + [[gnu::cleanup(wrapYyjsonFree)]] yyjson_doc* doc = yyjson_read_opts(buffer.chars, buffer.length, 0, nullptr, nullptr); if (!doc) { return "Failed to parse battery info"; } @@ -66,7 +66,7 @@ static const char* parseTermuxApi(FFBatteryOptions* options, FFlist* results) { battery->temperature = yyjson_get_num(yyjson_obj_get(root, "temperature")); } - return NULL; + return nullptr; } static const char* parseDumpsys(FFBatteryOptions* options, FFlist* results) { @@ -74,8 +74,8 @@ static const char* parseDumpsys(FFBatteryOptions* options, FFlist* results) { if (ffProcessAppendStdOut(&buf, (char*[]) { "/system/bin/dumpsys", "battery", - NULL, - }) != NULL || + nullptr, + }) != nullptr || buf.length == 0) { return "Executing `/system/bin/dumpsys battery` failed"; // Only works in `adb shell`, or when rooted } @@ -88,7 +88,7 @@ static const char* parseDumpsys(FFBatteryOptions* options, FFlist* results) { FF_STRBUF_AUTO_DESTROY temp = ffStrbufCreate(); if (!ffParsePropLines(start, "present: ", &temp) || !ffStrbufEqualS(&temp, "true")) { - return NULL; + return nullptr; } ffStrbufClear(&temp); @@ -148,13 +148,13 @@ static const char* parseDumpsys(FFBatteryOptions* options, FFlist* results) { ffParsePropLines(start, "technology: ", &battery->technology); - return NULL; + return nullptr; } const char* ffDetectBattery(FFBatteryOptions* options, FFlist* results) { const char* error = parseTermuxApi(options, results); - if (error && parseDumpsys(options, results) == NULL) { - return NULL; + if (error && parseDumpsys(options, results) == nullptr) { + return nullptr; } return error; } diff --git a/src/detection/battery/battery_apple.c b/src/detection/battery/battery_apple.c index c22aa6d43e..fb60303919 100644 --- a/src/detection/battery/battery_apple.c +++ b/src/detection/battery/battery_apple.c @@ -15,18 +15,18 @@ const char* ffDetectBattery(FFBatteryOptions* options, FFlist* results) { io_registry_entry_t registryEntry; while ((registryEntry = IOIteratorNext(iterator)) != IO_OBJECT_NULL) { FF_IOOBJECT_AUTO_RELEASE io_registry_entry_t entryBattery = registryEntry; - FF_CFTYPE_AUTO_RELEASE CFMutableDictionaryRef properties = NULL; + FF_CFTYPE_AUTO_RELEASE CFMutableDictionaryRef properties = nullptr; if (IORegistryEntryCreateCFProperties(entryBattery, &properties, kCFAllocatorDefault, kNilOptions) != kIOReturnSuccess) { continue; } int currentCapacity, maxCapacity; - if (ffCfDictGetInt(properties, CFSTR(kIOPMPSMaxCapacityKey), &maxCapacity) != NULL || maxCapacity <= 0) { + if (ffCfDictGetInt(properties, CFSTR(kIOPMPSMaxCapacityKey), &maxCapacity) != nullptr || maxCapacity <= 0) { continue; } - if (ffCfDictGetInt(properties, CFSTR(kIOPMPSCurrentCapacityKey), ¤tCapacity) != NULL || currentCapacity <= 0) { + if (ffCfDictGetInt(properties, CFSTR(kIOPMPSCurrentCapacityKey), ¤tCapacity) != nullptr || currentCapacity <= 0) { continue; } @@ -63,7 +63,7 @@ const char* ffDetectBattery(FFBatteryOptions* options, FFlist* results) { battery->cycleCount = cycleCount < 0 ? 0 : (uint32_t) cycleCount; battery->timeRemaining = -1; - if (ffCfDictGetBool(properties, CFSTR(kIOPMPSExternalConnectedKey), &boolValue) == NULL) { + if (ffCfDictGetBool(properties, CFSTR(kIOPMPSExternalConnectedKey), &boolValue) == nullptr) { if (boolValue) { battery->status |= FF_BATTERY_STATUS_AC_CONNECTED; } else { @@ -76,24 +76,24 @@ const char* ffDetectBattery(FFBatteryOptions* options, FFlist* results) { } } } - if (ffCfDictGetBool(properties, CFSTR(kIOPMPSIsChargingKey), &boolValue) == NULL && boolValue) { + if (ffCfDictGetBool(properties, CFSTR(kIOPMPSIsChargingKey), &boolValue) == nullptr && boolValue) { battery->status |= FF_BATTERY_STATUS_CHARGING; } - if (ffCfDictGetBool(properties, CFSTR(kIOPMPSAtCriticalLevelKey), &boolValue) == NULL && boolValue) { + if (ffCfDictGetBool(properties, CFSTR(kIOPMPSAtCriticalLevelKey), &boolValue) == nullptr && boolValue) { battery->status |= FF_BATTERY_STATUS_CRITICAL; } int sbdsManufactureDate = 0; - if (ffCfDictGetInt(properties, CFSTR(kIOPMPSManufactureDateKey), &sbdsManufactureDate) == NULL) { + if (ffCfDictGetInt(properties, CFSTR(kIOPMPSManufactureDateKey), &sbdsManufactureDate) == nullptr) { int day = sbdsManufactureDate & 0b11111; int month = (sbdsManufactureDate >> 5) & 0b1111; int year = (sbdsManufactureDate >> 9) + 1800; ffStrbufSetF(&battery->manufactureDate, "%.4d-%.2d-%.2d", year, month, day); } else { CFDictionaryRef batteryData; - if (ffCfDictGetDict(properties, CFSTR("BatteryData"), &batteryData) == NULL) { + if (ffCfDictGetDict(properties, CFSTR("BatteryData"), &batteryData) == nullptr) { char manufactureDate[sizeof(uint64_t)]; - if (ffCfDictGetInt64(batteryData, CFSTR(kIOPMPSManufactureDateKey), (int64_t*) manufactureDate) == NULL) { + if (ffCfDictGetInt64(batteryData, CFSTR(kIOPMPSManufactureDateKey), (int64_t*) manufactureDate) == nullptr) { // https://github.com/AsahiLinux/linux/blob/b5c05cbffb0488c7618106926d522cc3b43d93d5/drivers/power/supply/macsmc_power.c#L410-L419 int year = (manufactureDate[0] - '0') * 10 + (manufactureDate[1] - '0') + 2000 - 8; int month = (manufactureDate[2] - '0') * 10 + (manufactureDate[3] - '0'); @@ -113,5 +113,5 @@ const char* ffDetectBattery(FFBatteryOptions* options, FFlist* results) { } } - return NULL; + return nullptr; } diff --git a/src/detection/battery/battery_bsd.c b/src/detection/battery/battery_bsd.c index 336a17e06b..cff41d5a68 100644 --- a/src/detection/battery/battery_bsd.c +++ b/src/detection/battery/battery_bsd.c @@ -8,7 +8,7 @@ #include #include -const char* ffDetectBattery(FF_A_UNUSED FFBatteryOptions* options, FFlist* results) { +const char* ffDetectBattery([[maybe_unused]] FFBatteryOptions* options, FFlist* results) { // https://www.freebsd.org/cgi/man.cgi?acpi_battery(4) // https://gitlab.xfce.org/panel-plugins/xfce4-battery-plugin/-/blob/master/panel-plugin/libacpi.c @@ -18,7 +18,7 @@ const char* ffDetectBattery(FF_A_UNUSED FFBatteryOptions* options, FFlist* resul } if (units == 0) { - return NULL; + return nullptr; } FF_AUTO_CLOSE_FD int acpifd = open("/dev/acpi", O_RDONLY | O_CLOEXEC); @@ -86,5 +86,5 @@ const char* ffDetectBattery(FF_A_UNUSED FFBatteryOptions* options, FFlist* resul } #endif } - return NULL; + return nullptr; } diff --git a/src/detection/battery/battery_haiku.c b/src/detection/battery/battery_haiku.c index aa620e6e5c..523d33d933 100644 --- a/src/detection/battery/battery_haiku.c +++ b/src/detection/battery/battery_haiku.c @@ -50,10 +50,10 @@ const char* parseBattery(int dfd, const char* battId, FFlist* results) { battery->status |= FF_BATTERY_STATUS_AC_CONNECTED; } - return NULL; + return nullptr; } -const char* ffDetectBattery(FF_A_UNUSED FFBatteryOptions* options, FFlist* results) { +const char* ffDetectBattery([[maybe_unused]] FFBatteryOptions* options, FFlist* results) { FF_AUTO_CLOSE_DIR DIR* dir = opendir("/dev/power/acpi_battery/"); if (!dir) { return "opendir(/dev/power/acpi_battery) failed"; @@ -67,5 +67,5 @@ const char* ffDetectBattery(FF_A_UNUSED FFBatteryOptions* options, FFlist* resul parseBattery(dirfd(dir), entry->d_name, results); } - return NULL; + return nullptr; } diff --git a/src/detection/battery/battery_linux.c b/src/detection/battery/battery_linux.c index 6c1f711256..0362cbcd19 100644 --- a/src/detection/battery/battery_linux.c +++ b/src/detection/battery/battery_linux.c @@ -175,14 +175,14 @@ static bool parseBattery(int dfd, const char* id, FFBatteryOptions* options, FFl const char* ffDetectBattery(FFBatteryOptions* options, FFlist* results) { FF_AUTO_CLOSE_DIR DIR* dirp = opendir("/sys/class/power_supply/"); - if (dirp == NULL) { - return "opendir(\"/sys/class/power_supply/\") == NULL"; + if (dirp == nullptr) { + return "opendir(\"/sys/class/power_supply/\") == nullptr"; } bool acConnected = false; struct dirent* entry; - while ((entry = readdir(dirp)) != NULL) { + while ((entry = readdir(dirp)) != nullptr) { if (entry->d_name[0] == '.') { continue; } @@ -199,5 +199,5 @@ const char* ffDetectBattery(FFBatteryOptions* options, FFlist* results) { } } - return NULL; + return nullptr; } diff --git a/src/detection/battery/battery_nbsd.c b/src/detection/battery/battery_nbsd.c index 2e8b42680a..eaf1fc7155 100644 --- a/src/detection/battery/battery_nbsd.c +++ b/src/detection/battery/battery_nbsd.c @@ -14,13 +14,13 @@ #include #include -const char* ffDetectBattery(FF_A_UNUSED FFBatteryOptions* options, FFlist* results) { +const char* ffDetectBattery([[maybe_unused]] FFBatteryOptions* options, FFlist* results) { FF_AUTO_CLOSE_FD int fd = open(_PATH_SYSMON, O_RDONLY | O_CLOEXEC); if (fd < 0) { return "open(_PATH_SYSMON, O_RDONLY | O_CLOEXEC) failed"; } - prop_dictionary_t root = NULL; + prop_dictionary_t root = nullptr; if (prop_dictionary_recv_ioctl(fd, ENVSYS_GETDICTIONARY, &root) < 0) { return "prop_dictionary_recv_ioctl(ENVSYS_GETDICTIONARY) failed"; } @@ -35,7 +35,7 @@ const char* ffDetectBattery(FF_A_UNUSED FFBatteryOptions* options, FFlist* resul } prop_object_iterator_t itKey = prop_dictionary_iterator(root); - for (prop_dictionary_keysym_t key; (key = prop_object_iterator_next(itKey)) != NULL;) { + for (prop_dictionary_keysym_t key; (key = prop_object_iterator_next(itKey)) != nullptr;) { if (!ffStrStartsWith(prop_dictionary_keysym_value(key), "acpibat")) { continue; } @@ -44,12 +44,12 @@ const char* ffDetectBattery(FF_A_UNUSED FFBatteryOptions* options, FFlist* resul uint32_t max = 0, curr = 0, dischargeRate = 0; bool charging = false, critical = false; prop_object_iterator_t iter = prop_array_iterator(bat); - for (prop_dictionary_t dict; (dict = prop_object_iterator_next(iter)) != NULL;) { + for (prop_dictionary_t dict; (dict = prop_object_iterator_next(iter)) != nullptr;) { if (prop_object_type(dict) != PROP_TYPE_DICTIONARY) { continue; } - const char* desc = NULL; + const char* desc = nullptr; if (!prop_dictionary_get_string(dict, "description", &desc)) { continue; } @@ -64,7 +64,7 @@ const char* ffDetectBattery(FF_A_UNUSED FFBatteryOptions* options, FFlist* resul } else if (ffStrEquals(desc, "charge")) { prop_dictionary_get_uint32(dict, "max-value", &max); prop_dictionary_get_uint32(dict, "cur-value", &curr); - const char* state = NULL; + const char* state = nullptr; if (prop_dictionary_get_string(dict, "state", &state) && ffStrEquals(state, "critical")) { critical = true; } @@ -105,5 +105,5 @@ const char* ffDetectBattery(FF_A_UNUSED FFBatteryOptions* options, FFlist* resul prop_object_iterator_release(itKey); prop_object_release(root); - return NULL; + return nullptr; } diff --git a/src/detection/battery/battery_obsd.c b/src/detection/battery/battery_obsd.c index ee664ce690..c5c6c3c391 100644 --- a/src/detection/battery/battery_obsd.c +++ b/src/detection/battery/battery_obsd.c @@ -6,7 +6,7 @@ #include #include -const char* ffDetectBattery(FF_A_UNUSED FFBatteryOptions* options, FFlist* result) { +const char* ffDetectBattery([[maybe_unused]] FFBatteryOptions* options, FFlist* result) { FF_AUTO_CLOSE_FD int devfd = open("/dev/apm", O_RDONLY | O_CLOEXEC); if (devfd < 0) { @@ -20,7 +20,7 @@ const char* ffDetectBattery(FF_A_UNUSED FFBatteryOptions* options, FFlist* resul } if (info.battery_state == APM_BATTERY_ABSENT) { - return NULL; + return nullptr; } FFBatteryResult* battery = FF_LIST_ADD(FFBatteryResult, *result); @@ -56,5 +56,5 @@ const char* ffDetectBattery(FF_A_UNUSED FFBatteryOptions* options, FFlist* resul } } - return NULL; + return nullptr; } diff --git a/src/detection/battery/battery_windows.c b/src/detection/battery/battery_windows.c index 84f2a907cf..720d5cbd3b 100644 --- a/src/detection/battery/battery_windows.c +++ b/src/detection/battery/battery_windows.c @@ -51,21 +51,21 @@ static FFBatteryWmiEntry* getBatteryEntry(FFlist* entries, FFlist* results, ULON } static const char* queryWmiAllData(const GUID* guid, const char* guidStr, PWNODE_ALL_DATA* pAllData, ULONG* pBufferSize) { - FF_AUTO_CLOSE_WMI_BLOCK HANDLE hBlock = NULL; + [[gnu::cleanup(ffCloseWmiBlock)]] HANDLE hBlock = nullptr; ULONG status = WmiOpenBlock(guid, WMIGUID_QUERY, &hBlock); if (status != ERROR_SUCCESS) { FF_DEBUG("WMI: WmiOpenBlock() failed for %s: %s", guidStr, ffDebugWin32Error(status)); return "WmiOpenBlock() failed"; } - status = WmiQueryAllDataW(hBlock, pBufferSize, NULL); + status = WmiQueryAllDataW(hBlock, pBufferSize, nullptr); if (status != ERROR_SUCCESS && status != ERROR_INSUFFICIENT_BUFFER) { FF_DEBUG("WMI: first WmiQueryAllDataW() failed: %s", ffDebugWin32Error(status)); - return "WmiQueryAllDataW(NULL) failed"; + return "WmiQueryAllDataW(nullptr) failed"; } if (*pBufferSize == 0) { - return "WmiQueryAllDataW(NULL) returned no data"; + return "WmiQueryAllDataW(nullptr) returned no data"; } if (*pBufferSize < sizeof(WNODE_ALL_DATA)) { @@ -79,11 +79,11 @@ static const char* queryWmiAllData(const GUID* guid, const char* guidStr, PWNODE if (status != ERROR_SUCCESS) { FF_DEBUG("WMI: second WmiQueryAllDataW failed: %s", ffDebugWin32Error(status)); free(*pAllData); - *pAllData = NULL; + *pAllData = nullptr; return "WmiQueryAllDataW(*pAllData) failed"; } - return NULL; + return nullptr; } static bool getInstanceData(const PWNODE_ALL_DATA allData, ULONG bufferSize, ULONG index, const uint8_t** instanceData, ULONG* instanceLength) { @@ -109,7 +109,7 @@ static bool getInstanceData(const PWNODE_ALL_DATA allData, ULONG bufferSize, ULO static void detectStaticData(FFlist* entries, FFlist* results) { FF_DEBUG("detectStaticData"); - FF_AUTO_FREE PWNODE_ALL_DATA allData = NULL; + FF_AUTO_FREE PWNODE_ALL_DATA allData = nullptr; ULONG bufferSize = 0; const char* error = queryWmiAllData(&BATTERY_STATIC_DATA_WMI_GUID, "BATTERY_STATIC_DATA_WMI_GUID", &allData, &bufferSize); if (error) { @@ -117,7 +117,7 @@ static void detectStaticData(FFlist* entries, FFlist* results) { } for (ULONG i = 0; i < allData->InstanceCount; ++i) { - const uint8_t* instanceData = NULL; + const uint8_t* instanceData = nullptr; ULONG instanceLength = 0; if (!getInstanceData(allData, bufferSize, i, &instanceData, &instanceLength) || instanceLength < offsetof(BATTERY_WMI_STATIC_DATA, Strings)) { continue; @@ -187,7 +187,7 @@ static void detectStaticData(FFlist* entries, FFlist* results) { static void detectStatus(FFlist* entries, FFlist* results) { FF_DEBUG("detectStatus"); - FF_AUTO_FREE PWNODE_ALL_DATA allData = NULL; + FF_AUTO_FREE PWNODE_ALL_DATA allData = nullptr; ULONG bufferSize = 0; const char* error = queryWmiAllData(&BATTERY_STATUS_WMI_GUID, "BATTERY_STATUS_WMI_GUID", &allData, &bufferSize); if (error) { @@ -195,7 +195,7 @@ static void detectStatus(FFlist* entries, FFlist* results) { } for (ULONG i = 0; i < allData->InstanceCount; ++i) { - const uint8_t* instanceData = NULL; + const uint8_t* instanceData = nullptr; ULONG instanceLength = 0; if (!getInstanceData(allData, bufferSize, i, &instanceData, &instanceLength) || instanceLength < sizeof(BATTERY_WMI_STATUS)) { continue; @@ -225,7 +225,7 @@ static void detectStatus(FFlist* entries, FFlist* results) { static void detectRuntime(FFlist* entries, FFlist* results) { FF_DEBUG("detectRuntime"); - FF_AUTO_FREE PWNODE_ALL_DATA allData = NULL; + FF_AUTO_FREE PWNODE_ALL_DATA allData = nullptr; ULONG bufferSize = 0; const char* error = queryWmiAllData(&BATTERY_RUNTIME_WMI_GUID, "BATTERY_RUNTIME_WMI_GUID", &allData, &bufferSize); if (error) { @@ -233,7 +233,7 @@ static void detectRuntime(FFlist* entries, FFlist* results) { } for (ULONG i = 0; i < allData->InstanceCount; ++i) { - const uint8_t* instanceData = NULL; + const uint8_t* instanceData = nullptr; ULONG instanceLength = 0; if (!getInstanceData(allData, bufferSize, i, &instanceData, &instanceLength) || instanceLength < sizeof(BATTERY_WMI_RUNTIME)) { continue; @@ -249,7 +249,7 @@ static void detectRuntime(FFlist* entries, FFlist* results) { static void detectFullChargedCapacity(FFlist* entries, FFlist* results) { FF_DEBUG("detectFullChargedCapacity"); - FF_AUTO_FREE PWNODE_ALL_DATA allData = NULL; + FF_AUTO_FREE PWNODE_ALL_DATA allData = nullptr; ULONG bufferSize = 0; const char* error = queryWmiAllData(&BATTERY_FULL_CHARGED_CAPACITY_WMI_GUID, "BATTERY_FULL_CHARGED_CAPACITY_WMI_GUID", &allData, &bufferSize); if (error) { @@ -257,7 +257,7 @@ static void detectFullChargedCapacity(FFlist* entries, FFlist* results) { } for (ULONG i = 0; i < allData->InstanceCount; ++i) { - const uint8_t* instanceData = NULL; + const uint8_t* instanceData = nullptr; ULONG instanceLength = 0; if (!getInstanceData(allData, bufferSize, i, &instanceData, &instanceLength) || instanceLength < sizeof(BATTERY_WMI_FULL_CHARGED_CAPACITY)) { continue; @@ -275,7 +275,7 @@ static void detectFullChargedCapacity(FFlist* entries, FFlist* results) { static void detectCycleCount(FFlist* entries, FFlist* results) { FF_DEBUG("detectCycleCount"); - FF_AUTO_FREE PWNODE_ALL_DATA allData = NULL; + FF_AUTO_FREE PWNODE_ALL_DATA allData = nullptr; ULONG bufferSize = 0; const char* error = queryWmiAllData(&BATTERY_CYCLE_COUNT_WMI_GUID, "BATTERY_CYCLE_COUNT_WMI_GUID", &allData, &bufferSize); if (error) { @@ -283,7 +283,7 @@ static void detectCycleCount(FFlist* entries, FFlist* results) { } for (ULONG i = 0; i < allData->InstanceCount; ++i) { - const uint8_t* instanceData = NULL; + const uint8_t* instanceData = nullptr; ULONG instanceLength = 0; if (!getInstanceData(allData, bufferSize, i, &instanceData, &instanceLength) || instanceLength < sizeof(BATTERY_WMI_CYCLE_COUNT)) { continue; @@ -296,7 +296,7 @@ static void detectCycleCount(FFlist* entries, FFlist* results) { static void detectTemperature(FFlist* entries, FFlist* results) { FF_DEBUG("detectTemperature"); - FF_AUTO_FREE PWNODE_ALL_DATA allData = NULL; + FF_AUTO_FREE PWNODE_ALL_DATA allData = nullptr; ULONG bufferSize = 0; const char* error = queryWmiAllData(&BATTERY_TEMPERATURE_WMI_GUID, "BATTERY_TEMPERATURE_WMI_GUID", &allData, &bufferSize); if (error) { @@ -304,7 +304,7 @@ static void detectTemperature(FFlist* entries, FFlist* results) { } for (ULONG i = 0; i < allData->InstanceCount; ++i) { - const uint8_t* instanceData = NULL; + const uint8_t* instanceData = nullptr; ULONG instanceLength = 0; if (!getInstanceData(allData, bufferSize, i, &instanceData, &instanceLength) || instanceLength < sizeof(BATTERY_WMI_TEMPERATURE)) { continue; @@ -319,7 +319,7 @@ static const char* detectWithNtApi(FFBatteryResult* battery) { // Reports summary battery information, not per battery FF_DEBUG("NtApi: start detection"); SYSTEM_BATTERY_STATE info; - NTSTATUS status = NtPowerInformation(SystemBatteryState, NULL, 0, &info, sizeof(info)); + NTSTATUS status = NtPowerInformation(SystemBatteryState, nullptr, 0, &info, sizeof(info)); if (!NT_SUCCESS(status)) { FF_DEBUG("NtApi: NtPowerInformation(SystemBatteryState) failed: %s", ffDebugNtStatus(status)); return "NtPowerInformation(SystemBatteryState) failed"; @@ -346,7 +346,7 @@ static const char* detectWithNtApi(FFBatteryResult* battery) { battery->status |= FF_BATTERY_STATUS_CRITICAL; } battery->timeRemaining = info.EstimatedTime == BATTERY_UNKNOWN_TIME ? -1 : (int32_t) info.EstimatedTime; - return NULL; + return nullptr; } const char* ffDetectBattery(FFBatteryOptions* options, FFlist* results) { @@ -355,7 +355,7 @@ const char* ffDetectBattery(FFBatteryOptions* options, FFlist* results) { FF_LIST_AUTO_DESTROY entries = ffListCreate(); detectStaticData(&entries, results); if (results->length == 0) { - return NULL; + return nullptr; } else if (results->length == 1) { // Fast path for single battery detectWithNtApi(FF_LIST_FIRST(FFBatteryWmiEntry, entries)->result); @@ -380,5 +380,5 @@ const char* ffDetectBattery(FFBatteryOptions* options, FFlist* results) { } FF_DEBUG("WMI: finished detection, total results=%u", results->length); - return NULL; + return nullptr; } diff --git a/src/detection/bios/bios_android.c b/src/detection/bios/bios_android.c index a53db0db50..7d3409a28b 100644 --- a/src/detection/bios/bios_android.c +++ b/src/detection/bios/bios_android.c @@ -12,5 +12,5 @@ const char* ffDetectBios(FFBiosResult* bios) { ffStrbufSetStatic(&bios->type, "Bootloader"); - return NULL; + return nullptr; } diff --git a/src/detection/bios/bios_apple.c b/src/detection/bios/bios_apple.c index 6b046d2ea6..c9a6759b68 100644 --- a/src/detection/bios/bios_apple.c +++ b/src/detection/bios/bios_apple.c @@ -13,7 +13,7 @@ const char* ffDetectBios(FFBiosResult* bios) { return "IODeviceTree:/rom not found"; } - FF_CFTYPE_AUTO_RELEASE CFMutableDictionaryRef deviceRomProps = NULL; + FF_CFTYPE_AUTO_RELEASE CFMutableDictionaryRef deviceRomProps = nullptr; if (IORegistryEntryCreateCFProperties(deviceRom, &deviceRomProps, kCFAllocatorDefault, kNilOptions) != kIOReturnSuccess) { return "IORegistryEntryCreateCFProperties(deviceRom) failed"; } @@ -54,5 +54,5 @@ const char* ffDetectBios(FFBiosResult* bios) { } #endif - return NULL; + return nullptr; } diff --git a/src/detection/bios/bios_bsd.c b/src/detection/bios/bios_bsd.c index 66e50ea517..93f21eaac8 100644 --- a/src/detection/bios/bios_bsd.c +++ b/src/detection/bios/bios_bsd.c @@ -27,5 +27,5 @@ const char* ffDetectBios(FFBiosResult* result) { : "BIOS"); } } - return NULL; + return nullptr; } diff --git a/src/detection/bios/bios_linux.c b/src/detection/bios/bios_linux.c index 8776631e2d..9db76a54bc 100644 --- a/src/detection/bios/bios_linux.c +++ b/src/detection/bios/bios_linux.c @@ -17,5 +17,5 @@ const char* ffDetectBios(FFBiosResult* bios) { } else { ffStrbufSetStatic(&bios->type, "BIOS"); } - return NULL; + return nullptr; } diff --git a/src/detection/bios/bios_nbsd.c b/src/detection/bios/bios_nbsd.c index 3ab43ed0b4..836f836b21 100644 --- a/src/detection/bios/bios_nbsd.c +++ b/src/detection/bios/bios_nbsd.c @@ -4,17 +4,17 @@ #include "common/io.h" const char* ffDetectBios(FFBiosResult* bios) { - if (ffSysctlGetString("machdep.dmi.bios-date", &bios->date) == NULL) { + if (ffSysctlGetString("machdep.dmi.bios-date", &bios->date) == nullptr) { ffCleanUpSmbiosValue(&bios->date); } - if (ffSysctlGetString("machdep.dmi.bios-version", &bios->version) == NULL) { + if (ffSysctlGetString("machdep.dmi.bios-version", &bios->version) == nullptr) { ffCleanUpSmbiosValue(&bios->version); } - if (ffSysctlGetString("machdep.dmi.bios-vendor", &bios->vendor) == NULL) { + if (ffSysctlGetString("machdep.dmi.bios-vendor", &bios->vendor) == nullptr) { ffCleanUpSmbiosValue(&bios->vendor); } - if (ffSysctlGetString("machdep.bootmethod", &bios->type) != NULL) { + if (ffSysctlGetString("machdep.bootmethod", &bios->type) != nullptr) { ffStrbufSetStatic(&bios->type, ffPathExists("/dev/efi", FF_PATHTYPE_FILE) ? "UEFI" : "BIOS"); } - return NULL; + return nullptr; } diff --git a/src/detection/bios/bios_nosupport.c b/src/detection/bios/bios_nosupport.c index e044835700..a8b055e1e2 100644 --- a/src/detection/bios/bios_nosupport.c +++ b/src/detection/bios/bios_nosupport.c @@ -1,5 +1,5 @@ #include "bios.h" -const char* ffDetectBios(FF_A_UNUSED FFBiosResult* bios) { +const char* ffDetectBios([[maybe_unused]] FFBiosResult* bios) { return "Not supported on this platform"; } diff --git a/src/detection/bios/bios_windows.c b/src/detection/bios/bios_windows.c index 42b7674a42..b1d309f5e0 100644 --- a/src/detection/bios/bios_windows.c +++ b/src/detection/bios/bios_windows.c @@ -19,7 +19,7 @@ #include #endif -typedef struct FFSmbiosBios { +typedef struct [[gnu::packed]] FFSmbiosBios { FFSmbiosHeader Header; uint8_t Vendor; // string @@ -38,7 +38,7 @@ typedef struct FFSmbiosBios { // 3.1+ uint16_t ExtendedBiosRomSize; // bit field -} FF_A_PACKED FFSmbiosBios; +} FFSmbiosBios; static_assert(offsetof(FFSmbiosBios, ExtendedBiosRomSize) == 0x18, "FFSmbiosBios: Wrong struct alignment"); @@ -71,7 +71,7 @@ const char* ffDetectBios(FFBiosResult* bios) { // Same as GetFirmwareType, but support (?) Windows 7 // https://ntdoc.m417z.com/system_information_class SYSTEM_BOOT_ENVIRONMENT_INFORMATION sbei; - if (NT_SUCCESS(NtQuerySystemInformation(SystemBootEnvironmentInformation, &sbei, sizeof(sbei), NULL))) { + if (NT_SUCCESS(NtQuerySystemInformation(SystemBootEnvironmentInformation, &sbei, sizeof(sbei), nullptr))) { switch (sbei.FirmwareType) { case FirmwareTypeBios: ffStrbufSetStatic(&bios->type, "BIOS"); @@ -86,7 +86,7 @@ const char* ffDetectBios(FFBiosResult* bios) { #elif __sun di_node_t rootNode = di_init("/", DINFOPROP); if (rootNode != DI_NODE_NIL) { - char* efiVersion = NULL; + char* efiVersion = nullptr; if (di_prop_lookup_strings(DDI_DEV_T_ANY, rootNode, "efi-version", &efiVersion) > 0) { ffStrbufSetStatic(&bios->type, "UEFI"); } else { @@ -103,5 +103,5 @@ const char* ffDetectBios(FFBiosResult* bios) { ffStrbufSetStatic(&bios->type, deviceEfi ? "UEFI" : "BIOS"); #endif - return NULL; + return nullptr; } diff --git a/src/detection/bluetooth/bluetooth_apple.m b/src/detection/bluetooth/bluetooth_apple.m index 9cbf732a50..22ae236b50 100644 --- a/src/detection/bluetooth/bluetooth_apple.m +++ b/src/detection/bluetooth/bluetooth_apple.m @@ -108,5 +108,5 @@ @interface IOBluetoothDevice() } } - return NULL; + return nullptr; } diff --git a/src/detection/bluetooth/bluetooth_bsd.c b/src/detection/bluetooth/bluetooth_bsd.c index db9f23cf74..af1d6effdd 100644 --- a/src/detection/bluetooth/bluetooth_bsd.c +++ b/src/detection/bluetooth/bluetooth_bsd.c @@ -3,7 +3,7 @@ #define L2CAP_SOCKET_CHECKED #include -static int enumDev(FF_A_UNUSED int sockfd, struct bt_devinfo const* dev, FFlist* devices) { +static int enumDev([[maybe_unused]] int sockfd, struct bt_devinfo const* dev, FFlist* devices) { FFBluetoothResult* device = FF_LIST_ADD(FFBluetoothResult, *devices); ffStrbufInitS(&device->name, #if __FreeBSD__ @@ -12,7 +12,7 @@ static int enumDev(FF_A_UNUSED int sockfd, struct bt_devinfo const* dev, FFlist* dev->devname #endif ); - ffStrbufInitS(&device->address, bt_ntoa(&dev->bdaddr, NULL)); + ffStrbufInitS(&device->address, bt_ntoa(&dev->bdaddr, nullptr)); ffStrbufUpperCase(&device->address); ffStrbufInit(&device->type); device->battery = 0; @@ -20,11 +20,11 @@ static int enumDev(FF_A_UNUSED int sockfd, struct bt_devinfo const* dev, FFlist* return 0; } -const char* ffDetectBluetooth(FF_A_UNUSED FFBluetoothOptions* options, FF_A_UNUSED FFlist* devices /* FFBluetoothResult */) { +const char* ffDetectBluetooth([[maybe_unused]] FFBluetoothOptions* options, [[maybe_unused]] FFlist* devices /* FFBluetoothResult */) { // struct hostent* ent = bt_gethostent(); if (bt_devenum((void*) enumDev, devices) < 0) { return "bt_devenum() failed"; } - return NULL; + return nullptr; } diff --git a/src/detection/bluetooth/bluetooth_haiku.cpp b/src/detection/bluetooth/bluetooth_haiku.cpp index 8ed52c5ac5..b4479d6007 100644 --- a/src/detection/bluetooth/bluetooth_haiku.cpp +++ b/src/detection/bluetooth/bluetooth_haiku.cpp @@ -5,13 +5,13 @@ extern "C" { #include -const char* ffDetectBluetooth(FF_A_UNUSED FFBluetoothOptions* options, FFlist* devices /* FFBluetoothResult */) { +const char* ffDetectBluetooth([[maybe_unused]] FFBluetoothOptions* options, FFlist* devices /* FFBluetoothResult */) { using namespace Bluetooth; FF_SUPPRESS_IO(); LocalDevice* dev = LocalDevice::GetLocalDevice(); if (!dev) { - return NULL; + return nullptr; } BString devClass; @@ -26,5 +26,5 @@ const char* ffDetectBluetooth(FF_A_UNUSED FFBluetoothOptions* options, FFlist* d // TODO: more devices? - return NULL; + return nullptr; } diff --git a/src/detection/bluetooth/bluetooth_linux.c b/src/detection/bluetooth/bluetooth_linux.c index fb4e422425..f99d8289e9 100644 --- a/src/detection/bluetooth/bluetooth_linux.c +++ b/src/detection/bluetooth/bluetooth_linux.c @@ -124,14 +124,14 @@ static void detectBluetoothProperty(FFDBusData* dbus, DBusMessageIter* iter, FFB static FFBluetoothResult* detectBluetoothObject(FFlist* devices, FFDBusData* dbus, DBusMessageIter* iter) { if (dbus->lib->ffdbus_message_iter_get_arg_type(iter) != DBUS_TYPE_DICT_ENTRY) { - return NULL; + return nullptr; } DBusMessageIter dictIter; dbus->lib->ffdbus_message_iter_recurse(iter, &dictIter); if (dbus->lib->ffdbus_message_iter_get_arg_type(&dictIter) != DBUS_TYPE_OBJECT_PATH) { - return NULL; + return nullptr; } const char* objectPath; @@ -139,13 +139,13 @@ static FFBluetoothResult* detectBluetoothObject(FFlist* devices, FFDBusData* dbu // We don't want adapter objects if (!ffStrContains(objectPath, "/dev_")) { - return NULL; + return nullptr; } dbus->lib->ffdbus_message_iter_next(&dictIter); if (dbus->lib->ffdbus_message_iter_get_arg_type(&dictIter) != DBUS_TYPE_ARRAY) { - return NULL; + return nullptr; } DBusMessageIter arrayIter; @@ -202,7 +202,7 @@ static const char* detectBluetooth(FFBluetoothOptions* options, FFlist* devices, return error; } - DBusMessage* managedObjects = ffDBusGetMethodReply(&dbus, "org.bluez", "/", "org.freedesktop.DBus.ObjectManager", "GetManagedObjects", NULL, NULL); + DBusMessage* managedObjects = ffDBusGetMethodReply(&dbus, "org.bluez", "/", "org.freedesktop.DBus.ObjectManager", "GetManagedObjects", nullptr, nullptr); if (!managedObjects) { return "Failed to call GetManagedObjects"; } @@ -216,19 +216,19 @@ static const char* detectBluetooth(FFBluetoothOptions* options, FFlist* devices, detectBluetoothRoot(options, devices, &dbus, &rootIter, connectedCount); dbus.lib->ffdbus_message_unref(managedObjects); - return NULL; + return nullptr; } static uint32_t connectedDevices(void) { FF_AUTO_CLOSE_DIR DIR* dirp = opendir("/sys/class/bluetooth"); - if (dirp == NULL) { + if (dirp == nullptr) { return 0; } uint32_t result = 0; struct dirent* entry; - while ((entry = readdir(dirp)) != NULL) { - if (strchr(entry->d_name, ':') != NULL) { + while ((entry = readdir(dirp)) != nullptr) { + if (strchr(entry->d_name, ':') != nullptr) { ++result; } } @@ -244,7 +244,7 @@ const char* ffDetectBluetooth(FFBluetoothOptions* options, FFlist* devices /* FF if (!options->showDisconnected) { connectedCount = (int32_t) connectedDevices(); if (connectedCount == 0) { - return NULL; + return nullptr; } } diff --git a/src/detection/bluetooth/bluetooth_nosupport.c b/src/detection/bluetooth/bluetooth_nosupport.c index ac93ceed41..ae54eb0558 100644 --- a/src/detection/bluetooth/bluetooth_nosupport.c +++ b/src/detection/bluetooth/bluetooth_nosupport.c @@ -1,5 +1,5 @@ #include "bluetooth.h" -const char* ffDetectBluetooth(FF_A_UNUSED FFBluetoothOptions* options, FF_A_UNUSED FFlist* devices /* FFBluetoothResult */) { +const char* ffDetectBluetooth([[maybe_unused]] FFBluetoothOptions* options, [[maybe_unused]] FFlist* devices /* FFBluetoothResult */) { return "Not supported on this platform"; } diff --git a/src/detection/bluetooth/bluetooth_windows.c b/src/detection/bluetooth/bluetooth_windows.c index 8932aef505..8f765c21ad 100644 --- a/src/detection/bluetooth/bluetooth_windows.c +++ b/src/detection/bluetooth/bluetooth_windows.c @@ -35,10 +35,10 @@ static const char* ffBluetoothDetectBattery(FFlist* devices) { } if (idListLength == 0) { - return NULL; + return nullptr; } - wchar_t* FF_AUTO_FREE idList = (wchar_t*) malloc((size_t) idListLength * sizeof(wchar_t)); + FF_AUTO_FREE wchar_t* idList = (wchar_t*) malloc((size_t) idListLength * sizeof(wchar_t)); if (!idList) { return "malloc() failed"; } @@ -94,7 +94,7 @@ static const char* ffBluetoothDetectBattery(FFlist* devices) { } } - return NULL; + return nullptr; } const char* ffDetectBluetooth(FFBluetoothOptions* options, FFlist* devices /* FFBluetoothResult */) { @@ -114,7 +114,7 @@ const char* ffDetectBluetooth(FFBluetoothOptions* options, FFlist* devices /* FF &btdi); if (!hFind) { if (GetLastError() == ERROR_NO_MORE_ITEMS) { - return NULL; + return nullptr; } return "BluetoothFindFirstDevice() failed"; } @@ -219,5 +219,5 @@ const char* ffDetectBluetooth(FFBluetoothOptions* options, FFlist* devices /* FF ffBluetoothDetectBattery(devices); } - return NULL; + return nullptr; } diff --git a/src/detection/bluetoothradio/bluetoothradio_apple.m b/src/detection/bluetoothradio/bluetoothradio_apple.m index c5154abf1a..be662f9f9e 100644 --- a/src/detection/bluetoothradio/bluetoothradio_apple.m +++ b/src/detection/bluetoothradio/bluetoothradio_apple.m @@ -21,8 +21,8 @@ + (id)controllers; "-xml", "-detailLevel", "basic", - NULL - }) != NULL) + nullptr + }) != nullptr) return "Starting `system_profiler SPBluetoothDataType -xml -detailLevel basic` failed"; NSArray* arr = [NSPropertyListSerialization propertyListWithData:[NSData dataWithBytes:buffer.chars length:buffer.length] @@ -65,5 +65,5 @@ + (id)controllers; } } - return NULL; + return nullptr; } diff --git a/src/detection/bluetoothradio/bluetoothradio_linux.c b/src/detection/bluetoothradio/bluetoothradio_linux.c index a7d92a4830..c3a33a9cc0 100644 --- a/src/detection/bluetoothradio/bluetoothradio_linux.c +++ b/src/detection/bluetoothradio/bluetoothradio_linux.c @@ -73,14 +73,14 @@ static const char* detectBluetoothProperty(FFBluetoothRadioResult* device, FFDBu ffDBusGetBool(dbus, &dictIter, &device->connectable); } - return NULL; + return nullptr; } static const char* detectBluetoothRoot(FFBluetoothRadioResult* device, const char* hciName, FFDBusData* dbus) { char objPath[300]; snprintf(objPath, sizeof(objPath), "/org/bluez/%s", hciName); - DBusMessage* properties = ffDBusGetMethodReply(dbus, "org.bluez", objPath, "org.freedesktop.DBus.Properties", "GetAll", "org.bluez.Adapter1", NULL); + DBusMessage* properties = ffDBusGetMethodReply(dbus, "org.bluez", objPath, "org.freedesktop.DBus.Properties", "GetAll", "org.bluez.Adapter1", nullptr); if (!properties) { return "Failed to call org.freedesktop.DBus.Properties.GetAll"; } @@ -104,12 +104,12 @@ static const char* detectBluetoothRoot(FFBluetoothRadioResult* device, const cha } while (dbus->lib->ffdbus_message_iter_next(&arrayIter)); dbus->lib->ffdbus_message_unref(properties); - return NULL; + return nullptr; } static const char* detectBluetooth(FFlist* devices) { FF_AUTO_CLOSE_DIR DIR* dirp = opendir("/sys/class/bluetooth"); - if (dirp == NULL) { + if (dirp == nullptr) { return "Failed to open /sys/class/bluetooth"; } @@ -120,12 +120,12 @@ static const char* detectBluetooth(FFlist* devices) { } struct dirent* entry; - while ((entry = readdir(dirp)) != NULL) { + while ((entry = readdir(dirp)) != nullptr) { if (entry->d_name[0] == '.') { continue; } - if (strchr(entry->d_name, ':') != NULL) { // ignore connected devices + if (strchr(entry->d_name, ':') != nullptr) { // ignore connected devices continue; } @@ -138,7 +138,7 @@ static const char* detectBluetooth(FFlist* devices) { device->enabled = false; detectBluetoothRoot(device, entry->d_name, &dbus); } - return NULL; + return nullptr; } #endif diff --git a/src/detection/bluetoothradio/bluetoothradio_nosupport.c b/src/detection/bluetoothradio/bluetoothradio_nosupport.c index 08fb6f8a7a..feeab46a34 100644 --- a/src/detection/bluetoothradio/bluetoothradio_nosupport.c +++ b/src/detection/bluetoothradio/bluetoothradio_nosupport.c @@ -1,5 +1,5 @@ #include "bluetoothradio.h" -const char* ffDetectBluetoothRadio(FF_A_UNUSED FFlist* devices /* FFBluetoothRadioResult */) { +const char* ffDetectBluetoothRadio([[maybe_unused]] FFlist* devices /* FFBluetoothRadioResult */) { return "Not supported on this platform"; } diff --git a/src/detection/bluetoothradio/bluetoothradio_windows.c b/src/detection/bluetoothradio/bluetoothradio_windows.c index f0b55d4550..11f7879d5f 100644 --- a/src/detection/bluetoothradio/bluetoothradio_windows.c +++ b/src/detection/bluetoothradio/bluetoothradio_windows.c @@ -14,7 +14,7 @@ #define IOCTL_BTH_GET_LOCAL_INFO BTH_CTL(BTH_IOCTL_BASE + 0x00) #define LMP_LE_SUPPORTED(x) ((x >> 38) & 1) -typedef struct _BTH_RADIO_INFO { +typedef struct [[gnu::packed]] _BTH_RADIO_INFO { // Supported LMP features of the radio. Use LMP_XXX() to extract // the desired bits. ULONGLONG lmpSupportedFeatures; @@ -27,9 +27,9 @@ typedef struct _BTH_RADIO_INFO { // LMP version UCHAR lmpVersion; -} FF_A_PACKED BTH_RADIO_INFO; +} BTH_RADIO_INFO; -typedef struct _BTH_LOCAL_RADIO_INFO { +typedef struct [[gnu::packed]] _BTH_LOCAL_RADIO_INFO { // Local BTH_ADDR, class of device, and radio name BTH_DEVICE_INFO localInfo; @@ -44,7 +44,7 @@ typedef struct _BTH_LOCAL_RADIO_INFO { // More information about the local radio (LMP, MFG) BTH_RADIO_INFO radioInfo; -} FF_A_PACKED BTH_LOCAL_RADIO_INFO; +} BTH_LOCAL_RADIO_INFO; static_assert(sizeof(BTH_LOCAL_RADIO_INFO) == 292, "BTH_LOCAL_RADIO_INFO should be 292 bytes"); #pragma GCC diagnostic ignored "-Wpointer-sign" @@ -58,7 +58,7 @@ const char* ffDetectBluetoothRadio(FFlist* devices /* FFBluetoothRadioResult */) FF_LIBRARY_LOAD_SYMBOL_MESSAGE(bluetoothapis, BluetoothIsConnectable) FF_LIBRARY_LOAD_SYMBOL_MESSAGE(bluetoothapis, BluetoothIsDiscoverable) - HANDLE hRadio = NULL; + HANDLE hRadio = nullptr; HBLUETOOTH_DEVICE_FIND hFind = ffBluetoothFindFirstRadio(&(BLUETOOTH_FIND_RADIO_PARAMS) { .dwSize = sizeof(BLUETOOTH_FIND_RADIO_PARAMS) }, &hRadio); @@ -73,7 +73,7 @@ const char* ffDetectBluetoothRadio(FFlist* devices /* FFBluetoothRadioResult */) do { BTH_LOCAL_RADIO_INFO blri; DWORD returned; - if (!DeviceIoControl(hRadio, IOCTL_BTH_GET_LOCAL_INFO, NULL, 0, &blri, sizeof(blri), &returned, NULL)) { + if (!DeviceIoControl(hRadio, IOCTL_BTH_GET_LOCAL_INFO, nullptr, 0, &blri, sizeof(blri), &returned, nullptr)) { continue; } @@ -95,5 +95,5 @@ const char* ffDetectBluetoothRadio(FFlist* devices /* FFBluetoothRadioResult */) ffBluetoothFindRadioClose(hFind); - return NULL; + return nullptr; } diff --git a/src/detection/board/board_android.c b/src/detection/board/board_android.c index b5978d1f27..f70c1abb3c 100644 --- a/src/detection/board/board_android.c +++ b/src/detection/board/board_android.c @@ -5,5 +5,5 @@ const char* ffDetectBoard(FFBoardResult* board) { if (!ffSettingsGetAndroidProperty("ro.product.board", &board->name)) { ffSettingsGetAndroidProperty("ro.board.platform", &board->name); } - return NULL; + return nullptr; } diff --git a/src/detection/board/board_apple.c b/src/detection/board/board_apple.c index e7c4d381d6..f3b39538d9 100644 --- a/src/detection/board/board_apple.c +++ b/src/detection/board/board_apple.c @@ -28,5 +28,5 @@ const char* ffDetectBoard(FFBoardResult* result) { ffCfStrGetString(manufacturer, &result->vendor); } - return NULL; + return nullptr; } diff --git a/src/detection/board/board_bsd.c b/src/detection/board/board_bsd.c index 2e0e41720a..62a8ab1ff8 100644 --- a/src/detection/board/board_bsd.c +++ b/src/detection/board/board_bsd.c @@ -11,5 +11,5 @@ const char* ffDetectBoard(FFBoardResult* result) { ffCleanUpSmbiosValue(&result->vendor); ffSettingsGetFreeBSDKenv("smbios.planar.version", &result->version); ffCleanUpSmbiosValue(&result->version); - return NULL; + return nullptr; } diff --git a/src/detection/board/board_linux.c b/src/detection/board/board_linux.c index 52b3df2cd8..c2315b47fe 100644 --- a/src/detection/board/board_linux.c +++ b/src/detection/board/board_linux.c @@ -22,5 +22,5 @@ const char* ffDetectBoard(FFBoardResult* board) { ffStrbufSubstrBefore(&board->vendor, comma); } } - return NULL; + return nullptr; } diff --git a/src/detection/board/board_nbsd.c b/src/detection/board/board_nbsd.c index cc3ff938dc..09bcab71fd 100644 --- a/src/detection/board/board_nbsd.c +++ b/src/detection/board/board_nbsd.c @@ -3,18 +3,18 @@ #include "common/smbios.h" const char* ffDetectBoard(FFBoardResult* board) { - if (ffSysctlGetString("machdep.dmi.board-product", &board->name) == NULL) { + if (ffSysctlGetString("machdep.dmi.board-product", &board->name) == nullptr) { ffCleanUpSmbiosValue(&board->name); } - if (ffSysctlGetString("machdep.dmi.board-version", &board->version) == NULL) { + if (ffSysctlGetString("machdep.dmi.board-version", &board->version) == nullptr) { ffCleanUpSmbiosValue(&board->version); } - if (ffSysctlGetString("machdep.dmi.board-vendor", &board->vendor) == NULL) { + if (ffSysctlGetString("machdep.dmi.board-vendor", &board->vendor) == nullptr) { ffCleanUpSmbiosValue(&board->vendor); } - if (ffSysctlGetString("machdep.dmi.board-serial", &board->serial) == NULL) { + if (ffSysctlGetString("machdep.dmi.board-serial", &board->serial) == nullptr) { ffCleanUpSmbiosValue(&board->serial); } - return NULL; + return nullptr; } diff --git a/src/detection/board/board_nosupport.c b/src/detection/board/board_nosupport.c index befc630832..1b7bf1e319 100644 --- a/src/detection/board/board_nosupport.c +++ b/src/detection/board/board_nosupport.c @@ -1,5 +1,5 @@ #include "board.h" -const char* ffDetectBoard(FF_A_UNUSED FFBoardResult* board) { +const char* ffDetectBoard([[maybe_unused]] FFBoardResult* board) { return "Not supported on this platform"; } diff --git a/src/detection/board/board_windows.c b/src/detection/board/board_windows.c index 079e64d516..7ce50032dd 100644 --- a/src/detection/board/board_windows.c +++ b/src/detection/board/board_windows.c @@ -1,7 +1,7 @@ #include "board.h" #include "common/smbios.h" -typedef struct FFSmbiosBaseboard { +typedef struct [[gnu::packed]] FFSmbiosBaseboard { FFSmbiosHeader Header; uint8_t Manufacturer; // string @@ -15,7 +15,7 @@ typedef struct FFSmbiosBaseboard { uint8_t BoardType; // enum uint8_t NumberOfContainedObjectHandles; // varies uint16_t ContainedObjectHandles[]; // varies -} FF_A_PACKED FFSmbiosBaseboard; +} FFSmbiosBaseboard; static_assert(offsetof(FFSmbiosBaseboard, ContainedObjectHandles) == 0x0F, "FFSmbiosBaseboard: Wrong struct alignment"); @@ -42,5 +42,5 @@ const char* ffDetectBoard(FFBoardResult* board) { ffStrbufSetStatic(&board->version, ffSmbiosLocateString(strings, data->Version)); ffCleanUpSmbiosValue(&board->version); - return NULL; + return nullptr; } diff --git a/src/detection/bootmgr/bootmgr_apple.c b/src/detection/bootmgr/bootmgr_apple.c index d2b24e00e8..59aaa78316 100644 --- a/src/detection/bootmgr/bootmgr_apple.c +++ b/src/detection/bootmgr/bootmgr_apple.c @@ -39,7 +39,7 @@ static const char* detectSecureBoot(bool* result) { *result = *CFDataGetBytePtr((CFDataRef) prop) != 0x02 /* Permissive Security */; #endif - return NULL; + return nullptr; } const char* ffDetectBootmgr(FFBootmgrResult* result) { @@ -65,5 +65,5 @@ const char* ffDetectBootmgr(FFBootmgrResult* result) { detectSecureBoot(&result->secureBoot); - return NULL; + return nullptr; } diff --git a/src/detection/bootmgr/bootmgr_bsd.c b/src/detection/bootmgr/bootmgr_bsd.c index cfaa41d269..93983ab377 100644 --- a/src/detection/bootmgr/bootmgr_bsd.c +++ b/src/detection/bootmgr/bootmgr_bsd.c @@ -58,5 +58,5 @@ const char* ffDetectBootmgr(FFBootmgrResult* result) { result->secureBoot = !!buffer[0]; } - return NULL; + return nullptr; } diff --git a/src/detection/bootmgr/bootmgr_haiku.cpp b/src/detection/bootmgr/bootmgr_haiku.cpp index 72358fca0a..78060b2963 100644 --- a/src/detection/bootmgr/bootmgr_haiku.cpp +++ b/src/detection/bootmgr/bootmgr_haiku.cpp @@ -13,5 +13,5 @@ const char* ffDetectBootmgr(FFBootmgrResult* result) { // TODO: detectSecureBoot(&result->secureBoot); - return NULL; + return nullptr; } diff --git a/src/detection/bootmgr/bootmgr_linux.c b/src/detection/bootmgr/bootmgr_linux.c index 0fd019a2f4..daae9e79ec 100644 --- a/src/detection/bootmgr/bootmgr_linux.c +++ b/src/detection/bootmgr/bootmgr_linux.c @@ -28,5 +28,5 @@ const char* ffDetectBootmgr(FFBootmgrResult* result) { result->secureBoot = buffer[4] == 1; } - return NULL; + return nullptr; } diff --git a/src/detection/bootmgr/bootmgr_nosupport.c b/src/detection/bootmgr/bootmgr_nosupport.c index bb01714270..12b7f84c64 100644 --- a/src/detection/bootmgr/bootmgr_nosupport.c +++ b/src/detection/bootmgr/bootmgr_nosupport.c @@ -1,5 +1,5 @@ #include "bootmgr.h" -const char* ffDetectBootmgr(FF_A_UNUSED FFBootmgrResult* result) { +const char* ffDetectBootmgr([[maybe_unused]] FFBootmgrResult* result) { return "Not supported on this platform"; } diff --git a/src/detection/bootmgr/bootmgr_windows.c b/src/detection/bootmgr/bootmgr_windows.c index e83e1e2a12..0a1a55994b 100644 --- a/src/detection/bootmgr/bootmgr_windows.c +++ b/src/detection/bootmgr/bootmgr_windows.c @@ -7,7 +7,7 @@ #include const char* enablePrivilege(const wchar_t* privilege) { - FF_AUTO_CLOSE_FD HANDLE token = NULL; + FF_AUTO_CLOSE_FD HANDLE token = nullptr; if (!NT_SUCCESS(NtOpenProcessToken(NtCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &token))) { return "NtOpenProcessToken() failed"; } @@ -17,11 +17,11 @@ const char* enablePrivilege(const wchar_t* privilege) { .Privileges = { (LUID_AND_ATTRIBUTES) { .Attributes = SE_PRIVILEGE_ENABLED } }, }; - if (!LookupPrivilegeValueW(NULL, privilege, &tp.Privileges[0].Luid)) { + if (!LookupPrivilegeValueW(nullptr, privilege, &tp.Privileges[0].Luid)) { return "LookupPrivilegeValue() failed"; } - NTSTATUS status = NtAdjustPrivilegesToken(token, false, &tp, sizeof(tp), NULL, NULL); + NTSTATUS status = NtAdjustPrivilegesToken(token, false, &tp, sizeof(tp), nullptr, nullptr); if (!NT_SUCCESS(status)) { return "NtAdjustPrivilegesToken() failed"; } @@ -30,12 +30,12 @@ const char* enablePrivilege(const wchar_t* privilege) { return "The token does not have the specified privilege; try sudo please"; } - return NULL; + return nullptr; } const char* ffDetectBootmgr(FFBootmgrResult* result) { const char* err = enablePrivilege(L"SeSystemEnvironmentPrivilege"); - if (err != NULL) { + if (err != nullptr) { return err; } @@ -45,7 +45,7 @@ const char* ffDetectBootmgr(FFBootmgrResult* result) { } ULONG size = sizeof(result->order); - if (!NT_SUCCESS(NtQuerySystemEnvironmentValueEx(&(UNICODE_STRING) RTL_CONSTANT_STRING(L"BootCurrent"), &efiGlobalGuid, &result->order, &size, NULL))) { + if (!NT_SUCCESS(NtQuerySystemEnvironmentValueEx(&(UNICODE_STRING) RTL_CONSTANT_STRING(L"BootCurrent"), &efiGlobalGuid, &result->order, &size, nullptr))) { return "NtQuerySystemEnvironmentValueEx(BootCurrent) failed"; } if (size != sizeof(result->order)) { @@ -56,7 +56,7 @@ const char* ffDetectBootmgr(FFBootmgrResult* result) { wchar_t key[9]; swprintf(key, ARRAY_SIZE(key), L"Boot%04X", result->order); size = sizeof(buffer); - if (!NT_SUCCESS(NtQuerySystemEnvironmentValueEx(&(UNICODE_STRING) RTL_CONSTANT_STRING(key), &efiGlobalGuid, buffer, &size, NULL))) { + if (!NT_SUCCESS(NtQuerySystemEnvironmentValueEx(&(UNICODE_STRING) RTL_CONSTANT_STRING(key), &efiGlobalGuid, buffer, &size, nullptr))) { return "NtQuerySystemEnvironmentValueEx(Boot####) failed"; } if (size < sizeof(FFEfiLoadOption) || size == ARRAY_SIZE(buffer)) { @@ -66,9 +66,9 @@ const char* ffDetectBootmgr(FFBootmgrResult* result) { ffEfiFillLoadOption((FFEfiLoadOption*) buffer, result); SYSTEM_SECUREBOOT_INFORMATION ssi; - if (NT_SUCCESS(NtQuerySystemInformation(SystemSecureBootInformation, &ssi, sizeof(ssi), NULL))) { + if (NT_SUCCESS(NtQuerySystemInformation(SystemSecureBootInformation, &ssi, sizeof(ssi), nullptr))) { result->secureBoot = ssi.SecureBootEnabled; } - return NULL; + return nullptr; } diff --git a/src/detection/brightness/brightness_apple.c b/src/detection/brightness/brightness_apple.c index 5dd12b2a4b..14f490067d 100644 --- a/src/detection/brightness/brightness_apple.c +++ b/src/detection/brightness/brightness_apple.c @@ -9,25 +9,25 @@ // DDC/CI #ifdef __aarch64__ typedef CFTypeRef IOAVServiceRef; -extern IOAVServiceRef IOAVServiceCreate(CFAllocatorRef allocator) FF_A_WEAK_IMPORT; -extern IOAVServiceRef IOAVServiceCreateWithService(CFAllocatorRef allocator, io_service_t service) FF_A_WEAK_IMPORT; -extern IOReturn IOAVServiceCopyEDID(IOAVServiceRef service, CFDataRef* x2) FF_A_WEAK_IMPORT; -extern IOReturn IOAVServiceReadI2C(IOAVServiceRef service, uint32_t chipAddress, uint32_t offset, void* outputBuffer, uint32_t outputBufferSize) FF_A_WEAK_IMPORT; -extern IOReturn IOAVServiceWriteI2C(IOAVServiceRef service, uint32_t chipAddress, uint32_t dataAddress, void* inputBuffer, uint32_t inputBufferSize) FF_A_WEAK_IMPORT; +[[clang::weak_import]] extern IOAVServiceRef IOAVServiceCreate(CFAllocatorRef allocator); +[[clang::weak_import]] extern IOAVServiceRef IOAVServiceCreateWithService(CFAllocatorRef allocator, io_service_t service); +[[clang::weak_import]] extern IOReturn IOAVServiceCopyEDID(IOAVServiceRef service, CFDataRef* x2); +[[clang::weak_import]] extern IOReturn IOAVServiceReadI2C(IOAVServiceRef service, uint32_t chipAddress, uint32_t offset, void* outputBuffer, uint32_t outputBufferSize); +[[clang::weak_import]] extern IOReturn IOAVServiceWriteI2C(IOAVServiceRef service, uint32_t chipAddress, uint32_t dataAddress, void* inputBuffer, uint32_t inputBufferSize); #else // DDC/CI (Intel) #include #include #include -extern void CGSServiceForDisplayNumber(CGDirectDisplayID display, io_service_t* service) FF_A_WEAK_IMPORT; +[[clang::weak_import]] extern void CGSServiceForDisplayNumber(CGDirectDisplayID display, io_service_t* service); #endif // ACPI -extern int DisplayServicesGetBrightness(CGDirectDisplayID display, float* brightness) FF_A_WEAK_IMPORT; +[[clang::weak_import]] extern int DisplayServicesGetBrightness(CGDirectDisplayID display, float* brightness); // Works for internal display static const char* detectWithDisplayServices(const FFDisplayServerResult* displayServer, FFlist* result) { - if (DisplayServicesGetBrightness == NULL) { + if (DisplayServicesGetBrightness == nullptr) { return "DisplayServices function DisplayServicesGetBrightness is not available"; } @@ -45,13 +45,13 @@ static const char* detectWithDisplayServices(const FFDisplayServerResult* displa } } - return NULL; + return nullptr; } #ifdef __aarch64__ // https://github.com/waydabber/m1ddc // Works for Apple Silicon and USB-C adapter connection ( but not HTMI ) -static const char* detectWithDdcci(FF_A_UNUSED const FFDisplayServerResult* displayServer, FFBrightnessOptions* options, FFlist* result) { +static const char* detectWithDdcci([[maybe_unused]] const FFDisplayServerResult* displayServer, FFBrightnessOptions* options, FFlist* result) { if (!IOAVServiceCreate || !IOAVServiceReadI2C || !IOAVServiceWriteI2C) { return "IOAVService is not available"; } @@ -63,7 +63,7 @@ static const char* detectWithDdcci(FF_A_UNUSED const FFDisplayServerResult* disp io_registry_entry_t registryEntry; while ((registryEntry = IOIteratorNext(iterator)) != IO_OBJECT_NULL) { - FF_CFTYPE_AUTO_RELEASE IOAVServiceRef service = NULL; + FF_CFTYPE_AUTO_RELEASE IOAVServiceRef service = nullptr; { FF_IOOBJECT_AUTO_RELEASE io_registry_entry_t entryAv = registryEntry; @@ -118,7 +118,7 @@ static const char* detectWithDdcci(FF_A_UNUSED const FFDisplayServerResult* disp } } - return NULL; + return nullptr; } #else static IOOptionBits getSupportedTransactionType(void) { @@ -181,7 +181,7 @@ static const char* detectWithDdcci(const FFDisplayServerResult* displayServer, F } uint8_t i2cOut[12] = {}; - IOI2CConnectRef connect = NULL; + IOI2CConnectRef connect = nullptr; if (IOI2CInterfaceOpen(interface, kNilOptions, &connect) != KERN_SUCCESS) { continue; } @@ -227,7 +227,7 @@ static const char* detectWithDdcci(const FFDisplayServerResult* displayServer, F } } - return NULL; + return nullptr; } #endif @@ -240,5 +240,5 @@ const char* ffDetectBrightness(FFBrightnessOptions* options, FFlist* result) { detectWithDdcci(displayServer, options, result); } - return NULL; + return nullptr; } diff --git a/src/detection/brightness/brightness_bsd.c b/src/detection/brightness/brightness_bsd.c index 5ff411c618..bf09098b25 100644 --- a/src/detection/brightness/brightness_bsd.c +++ b/src/detection/brightness/brightness_bsd.c @@ -12,7 +12,7 @@ #if __has_include() #include -const char* detectWithDdcci(FF_A_UNUSED FFBrightnessOptions* options, FFlist* result) { +const char* detectWithDdcci([[maybe_unused]] FFBrightnessOptions* options, FFlist* result) { // FIXME: doesn't work for me for (char i = '0'; i <= '9'; ++i) { char path[] = "/dev/iic0"; @@ -69,12 +69,12 @@ const char* detectWithDdcci(FF_A_UNUSED FFBrightnessOptions* options, FFlist* re brightness->builtin = false; } - return NULL; + return nullptr; } #else -const char* detectWithDdcci(FF_A_UNUSED FFBrightnessOptions* options, FF_A_UNUSED FFlist* result) { +const char* detectWithDdcci([[maybe_unused]] FFBrightnessOptions* options, [[maybe_unused]] FFlist* result) { FF_DEBUG("DDC/CI support is not available on this system"); return "DDC/CI is supported only on FreeBSD"; } @@ -84,7 +84,7 @@ const char* detectWithDdcci(FF_A_UNUSED FFBrightnessOptions* options, FF_A_UNUSE #if __has_include() #include -const char* detectWithBacklight(FF_A_UNUSED FFBrightnessOptions* options, FFlist* result) { +const char* detectWithBacklight([[maybe_unused]] FFBrightnessOptions* options, FFlist* result) { // https://man.freebsd.org/cgi/man.cgi?query=backlight&sektion=9 char path[] = "/dev/backlight/backlight0"; @@ -125,23 +125,23 @@ const char* detectWithBacklight(FF_A_UNUSED FFBrightnessOptions* options, FFlist ffStrbufAppendS(&brightness->name, path + strlen("/dev/backlight/")); } } - return NULL; + return nullptr; } #else -const char* detectWithBacklight(FF_A_UNUSED FFBrightnessOptions* options, FF_A_UNUSED FFlist* result) { +const char* detectWithBacklight([[maybe_unused]] FFBrightnessOptions* options, [[maybe_unused]] FFlist* result) { FF_DEBUG("Backlight support is not available on this system"); return "Backlight is supported only on FreeBSD 13 and newer"; } #endif -const char* ffDetectBrightness(FF_A_UNUSED FFBrightnessOptions* options, FFlist* result) { +const char* ffDetectBrightness([[maybe_unused]] FFBrightnessOptions* options, FFlist* result) { detectWithBacklight(options, result); if (options->ddcciSleep != FF_BRIGHTNESS_DDCCI_SLEEP_SKIP && result->length == 0) { detectWithDdcci(options, result); } - return NULL; + return nullptr; } diff --git a/src/detection/brightness/brightness_haiku.cpp b/src/detection/brightness/brightness_haiku.cpp index 86fbe6d82b..0c189da824 100644 --- a/src/detection/brightness/brightness_haiku.cpp +++ b/src/detection/brightness/brightness_haiku.cpp @@ -6,7 +6,7 @@ extern "C" { #include #include -const char* ffDetectBrightness(FF_A_UNUSED FFBrightnessOptions* options, FFlist* result) { +const char* ffDetectBrightness([[maybe_unused]] FFBrightnessOptions* options, FFlist* result) { // We need a valid be_app to query the app_server here. BApplication app("application/x-vnd.fastfetch-cli-fastfetch"); BScreen screen{}; // default screen is the main one @@ -42,5 +42,5 @@ const char* ffDetectBrightness(FF_A_UNUSED FFBrightnessOptions* options, FFlist* } while (screen.SetToNext() == B_OK); - return NULL; + return nullptr; } diff --git a/src/detection/brightness/brightness_linux.c b/src/detection/brightness/brightness_linux.c index c0012c4342..ab82ac0b5c 100644 --- a/src/detection/brightness/brightness_linux.c +++ b/src/detection/brightness/brightness_linux.c @@ -11,7 +11,7 @@ static const char* detectWithBacklight(FFlist* result) { const char* backlightDirPath = "/sys/class/backlight/"; FF_AUTO_CLOSE_DIR DIR* dirp = opendir(backlightDirPath); - if (dirp == NULL) { + if (dirp == nullptr) { return "Failed to open `/sys/class/backlight/`"; } @@ -23,7 +23,7 @@ static const char* detectWithBacklight(FFlist* result) { FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); struct dirent* entry; - while ((entry = readdir(dirp)) != NULL) { + while ((entry = readdir(dirp)) != nullptr) { if (entry->d_name[0] == '.') { continue; } @@ -72,7 +72,7 @@ static const char* detectWithBacklight(FFlist* result) { ffStrbufSubstrBefore(&backlightDir, backlightDirLength); } - return NULL; + return nullptr; } #ifdef FF_HAVE_DDCUTIL @@ -90,7 +90,7 @@ double ddca_set_default_sleep_multiplier(double multiplier); // ddcutil 1.4 DDCA_Status ddca_init(const char* libopts, int syslog_level, int opts); #endif -static const char* detectWithDdcci(FF_A_UNUSED FFBrightnessOptions* options, FFlist* result) { +static const char* detectWithDdcci([[maybe_unused]] FFBrightnessOptions* options, FFlist* result) { FF_LIBRARY_LOAD_MESSAGE(libddcutil, "libddcutil" FF_LIBRARY_EXTENSION, 5); FF_LIBRARY_LOAD_SYMBOL_MESSAGE(libddcutil, ddca_get_display_info_list2) FF_LIBRARY_LOAD_SYMBOL_MESSAGE(libddcutil, ddca_open_display2) @@ -103,7 +103,7 @@ static const char* detectWithDdcci(FF_A_UNUSED FFBrightnessOptions* options, FFl if (ffddca_init) { FF_SUPPRESS_IO(); // Ref: https://github.com/rockowitz/ddcutil/issues/344 - if (ffddca_init(NULL, -1 /*DDCA_SYSLOG_NOT_SET*/, 1 /*DDCA_INIT_OPTIONS_DISABLE_CONFIG_FILE*/) < 0) { + if (ffddca_init(nullptr, -1 /*DDCA_SYSLOG_NOT_SET*/, 1 /*DDCA_INIT_OPTIONS_DISABLE_CONFIG_FILE*/) < 0) { return "ddca_init() failed"; } } else { @@ -112,11 +112,11 @@ static const char* detectWithDdcci(FF_A_UNUSED FFBrightnessOptions* options, FFl ffddca_set_default_sleep_multiplier(options->ddcciSleep / 40.0); } - libddcutil = NULL; // Don't dlclose libddcutil. See https://github.com/rockowitz/ddcutil/issues/330 + libddcutil = nullptr; // Don't dlclose libddcutil. See https://github.com/rockowitz/ddcutil/issues/330 } #else #if DDCUTIL_VMAJOR >= 2 - if (ddca_init(NULL, -1 /*DDCA_SYSLOG_NOT_SET*/, 1 /*DDCA_INIT_OPTIONS_DISABLE_CONFIG_FILE*/) < 0) { + if (ddca_init(nullptr, -1 /*DDCA_SYSLOG_NOT_SET*/, 1 /*DDCA_INIT_OPTIONS_DISABLE_CONFIG_FILE*/) < 0) { return "ddca_init() failed"; } #else @@ -124,7 +124,7 @@ static const char* detectWithDdcci(FF_A_UNUSED FFBrightnessOptions* options, FFl #endif #endif - FF_AUTO_FREE DDCA_Display_Info_List* infoList = NULL; + FF_AUTO_FREE DDCA_Display_Info_List* infoList = nullptr; if (ffddca_get_display_info_list2(false, &infoList) < 0) { return "ddca_get_display_info_list2(false, &infoList) failed"; } @@ -138,7 +138,7 @@ static const char* detectWithDdcci(FF_A_UNUSED FFBrightnessOptions* options, FFl DDCA_Display_Handle handle; if (ffddca_open_display2(display->dref, false, &handle) >= 0) { - DDCA_Any_Vcp_Value* vcpValue = NULL; + DDCA_Any_Vcp_Value* vcpValue = nullptr; if (ffddca_get_any_vcp_value_using_explicit_type(handle, 0x10 /*brightness*/, DDCA_NON_TABLE_VCP_VALUE, &vcpValue) >= 0) { assert(vcpValue->value_type == DDCA_NON_TABLE_VCP_VALUE); int current = VALREC_CUR_VAL(vcpValue), max = VALREC_MAX_VAL(vcpValue); @@ -154,11 +154,11 @@ static const char* detectWithDdcci(FF_A_UNUSED FFBrightnessOptions* options, FFl } } - return NULL; + return nullptr; } #endif -const char* ffDetectBrightness(FF_A_UNUSED FFBrightnessOptions* options, FFlist* result) { +const char* ffDetectBrightness([[maybe_unused]] FFBrightnessOptions* options, FFlist* result) { detectWithBacklight(result); #ifdef FF_HAVE_DDCUTIL @@ -170,5 +170,5 @@ const char* ffDetectBrightness(FF_A_UNUSED FFBrightnessOptions* options, FFlist* } #endif - return NULL; + return nullptr; } diff --git a/src/detection/brightness/brightness_nbsd.c b/src/detection/brightness/brightness_nbsd.c index afd6656049..56dd39ce50 100644 --- a/src/detection/brightness/brightness_nbsd.c +++ b/src/detection/brightness/brightness_nbsd.c @@ -2,7 +2,7 @@ #include "common/sysctl.h" -const char* ffDetectBrightness(FF_A_UNUSED FFBrightnessOptions* options, FFlist* result) { +const char* ffDetectBrightness([[maybe_unused]] FFBrightnessOptions* options, FFlist* result) { // https://man.netbsd.org/NetBSD-10.1/acpiout.4#DESCRIPTION char key[] = "hw.acpi.acpiout0.brightness"; char* pn = key + strlen("hw.acpi.acpiout"); @@ -22,5 +22,5 @@ const char* ffDetectBrightness(FF_A_UNUSED FFBrightnessOptions* options, FFlist* brightness->current = value; brightness->builtin = true; } - return NULL; + return nullptr; } diff --git a/src/detection/brightness/brightness_nosupport.c b/src/detection/brightness/brightness_nosupport.c index 6e9284e96f..4cc53e5ec7 100644 --- a/src/detection/brightness/brightness_nosupport.c +++ b/src/detection/brightness/brightness_nosupport.c @@ -1,5 +1,5 @@ #include "brightness.h" -const char* ffDetectBrightness(FF_A_UNUSED FFBrightnessOptions* options, FF_A_UNUSED FFlist* result) { +const char* ffDetectBrightness([[maybe_unused]] FFBrightnessOptions* options, [[maybe_unused]] FFlist* result) { return "Not supported on this platform"; } diff --git a/src/detection/brightness/brightness_obsd.c b/src/detection/brightness/brightness_obsd.c index 102a8c256d..2c9847c662 100644 --- a/src/detection/brightness/brightness_obsd.c +++ b/src/detection/brightness/brightness_obsd.c @@ -6,7 +6,7 @@ #include #include -const char* ffDetectBrightness(FF_A_UNUSED FFBrightnessOptions* options, FFlist* result) { +const char* ffDetectBrightness([[maybe_unused]] FFBrightnessOptions* options, FFlist* result) { char path[] = "/dev/ttyCX"; for (char i = '0'; i <= '9'; ++i) { path[strlen("/dev/ttyC")] = i; @@ -40,5 +40,5 @@ const char* ffDetectBrightness(FF_A_UNUSED FFBrightnessOptions* options, FFlist* brightness->builtin = true; } - return NULL; + return nullptr; } diff --git a/src/detection/brightness/brightness_windows.c b/src/detection/brightness/brightness_windows.c index 70b7f0197e..fc3bf8270f 100644 --- a/src/detection/brightness/brightness_windows.c +++ b/src/detection/brightness/brightness_windows.c @@ -45,7 +45,7 @@ static const char* detectWithWmi(FFlist* result) { 0xd43412ac, 0x67f9, 0x4fbb, { 0xa0, 0x81, 0x17, 0x52, 0xa2, 0xc3, 0x3e, 0x84 } }; - FF_AUTO_CLOSE_WMI_BLOCK HANDLE hBlock = NULL; + [[gnu::cleanup(ffCloseWmiBlock)]] HANDLE hBlock = nullptr; ULONG status = WmiOpenBlock(&WmiMonitorBrightnessGuid, WMIGUID_QUERY, &hBlock); if (status != 0) { @@ -54,7 +54,7 @@ static const char* detectWithWmi(FFlist* result) { } ULONG bufferSize = 0; - status = WmiQueryAllDataW(hBlock, &bufferSize, NULL); + status = WmiQueryAllDataW(hBlock, &bufferSize, nullptr); if (status != ERROR_SUCCESS && status != ERROR_INSUFFICIENT_BUFFER) { FF_DEBUG("WMI: first WmiQueryAllDataW failed, bufferSize=%lu: %s", bufferSize, ffDebugWin32Error(status)); return "WmiQueryAllDataW() failed"; @@ -121,7 +121,7 @@ static const char* detectWithWmi(FFlist* result) { FF_DEBUG("WMI: finished detection, total results=%u", result->length); - return NULL; + return nullptr; } static const char* detectWithDdcci(const FFDisplayServerResult* displayServer, FFlist* result) { @@ -159,7 +159,7 @@ static const char* detectWithDdcci(const FFDisplayServerResult* displayServer, F NTSTATUS monitorStatus = ffGetPhysicalMonitors(&deviceName, 1, &monitorCount, &physicalMonitor); if (NT_SUCCESS(monitorStatus) && monitorCount >= 1) { DWORD curr = 0, max = 0; - if (NT_SUCCESS(ffDDCCIGetVCPFeature(physicalMonitor, FF_DDC_CI_LUMINANCE_OPCODE, NULL, &curr, &max))) { + if (NT_SUCCESS(ffDDCCIGetVCPFeature(physicalMonitor, FF_DDC_CI_LUMINANCE_OPCODE, nullptr, &curr, &max))) { FFBrightnessResult* brightness = FF_LIST_ADD(FFBrightnessResult, *result); if (display->name.length > 0) { ffStrbufInitCopy(&brightness->name, &display->name); @@ -192,7 +192,7 @@ static const char* detectWithDdcci(const FFDisplayServerResult* displayServer, F } FF_DEBUG("DDC/CI: finished detection, total results=%u", result->length); - return NULL; + return nullptr; } static bool hasBuiltinDisplay(const FFDisplayServerResult* displayServer) { @@ -204,7 +204,7 @@ static bool hasBuiltinDisplay(const FFDisplayServerResult* displayServer) { return false; } -const char* ffDetectBrightness(FF_A_UNUSED FFBrightnessOptions* options, FFlist* result) { +const char* ffDetectBrightness([[maybe_unused]] FFBrightnessOptions* options, FFlist* result) { const FFDisplayServerResult* displayServer = ffConnectDisplayServer(); FF_DEBUG("start, displayCount=%u", displayServer->displays.length); @@ -219,5 +219,5 @@ const char* ffDetectBrightness(FF_A_UNUSED FFBrightnessOptions* options, FFlist* } FF_DEBUG("finished, resultCount=%u", result->length); - return NULL; + return nullptr; } diff --git a/src/detection/btrfs/btrfs_linux.c b/src/detection/btrfs/btrfs_linux.c index 41914d7099..120b3f6c21 100644 --- a/src/detection/btrfs/btrfs_linux.c +++ b/src/detection/btrfs/btrfs_linux.c @@ -12,13 +12,13 @@ static const char* enumerateDevices(FFBtrfsResult* item, int dfd, FFstrbuf* buff } FF_AUTO_CLOSE_DIR DIR* dirp = fdopendir(subfd); - if (dirp == NULL) { + if (dirp == nullptr) { close(subfd); - return "fdopendir(\"/sys/fs/btrfs/UUID/devices\") == NULL"; + return "fdopendir(\"/sys/fs/btrfs/UUID/devices\") == nullptr"; } struct dirent* entry; - while ((entry = readdir(dirp)) != NULL) { + while ((entry = readdir(dirp)) != nullptr) { if (entry->d_name[0] == '.') { continue; } @@ -36,7 +36,7 @@ static const char* enumerateDevices(FFBtrfsResult* item, int dfd, FFstrbuf* buff } } - return NULL; + return nullptr; } static const char* enumerateFeatures(FFBtrfsResult* item, int dfd) { @@ -46,12 +46,12 @@ static const char* enumerateFeatures(FFBtrfsResult* item, int dfd) { } FF_AUTO_CLOSE_DIR DIR* dirp = fdopendir(subfd); - if (dirp == NULL) { - return "fdopendir(\"/sys/fs/btrfs/UUID/features\") == NULL"; + if (dirp == nullptr) { + return "fdopendir(\"/sys/fs/btrfs/UUID/features\") == nullptr"; } struct dirent* entry; - while ((entry = readdir(dirp)) != NULL) { + while ((entry = readdir(dirp)) != nullptr) { if (entry->d_name[0] == '.') { continue; } @@ -61,7 +61,7 @@ static const char* enumerateFeatures(FFBtrfsResult* item, int dfd) { ffStrbufAppendS(&item->features, entry->d_name); } - return NULL; + return nullptr; } static const char* detectAllocation(FFBtrfsResult* item, int dfd, FFstrbuf* buffer) { @@ -73,7 +73,7 @@ static const char* detectAllocation(FFBtrfsResult* item, int dfd, FFstrbuf* buff if (ffReadFileBufferRelative(subfd, "global_rsv_size", buffer)) { item->globalReservationTotal = ffStrbufToUInt(buffer, 0); } else { - return "ffReadFileBuffer(\"/sys/fs/btrfs/UUID/allocation/global_rsv_size\") == NULL"; + return "ffReadFileBuffer(\"/sys/fs/btrfs/UUID/allocation/global_rsv_size\") == nullptr"; } if (ffReadFileBufferRelative(subfd, "global_rsv_reserved", buffer)) { @@ -118,19 +118,19 @@ static const char* detectAllocation(FFBtrfsResult* item, int dfd, FFstrbuf* buff #undef FF_BTRFS_DETECT_TYPE - return NULL; + return nullptr; } const char* ffDetectBtrfs(FFlist* result) { FF_AUTO_CLOSE_DIR DIR* dirp = opendir("/sys/fs/btrfs/"); - if (dirp == NULL) { - return "opendir(\"/sys/fs/btrfs\") == NULL"; + if (dirp == nullptr) { + return "opendir(\"/sys/fs/btrfs\") == nullptr"; } FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); struct dirent* entry; - while ((entry = readdir(dirp)) != NULL) { + while ((entry = readdir(dirp)) != nullptr) { if (entry->d_name[0] == '.') { continue; } @@ -174,5 +174,5 @@ const char* ffDetectBtrfs(FFlist* result) { detectAllocation(item, dfd, &buffer); } - return NULL; + return nullptr; } diff --git a/src/detection/btrfs/btrfs_nosupport.c b/src/detection/btrfs/btrfs_nosupport.c index b51d2c5cd5..62e041bb27 100644 --- a/src/detection/btrfs/btrfs_nosupport.c +++ b/src/detection/btrfs/btrfs_nosupport.c @@ -1,5 +1,5 @@ #include "btrfs.h" -const char* ffDetectBtrfs(FF_A_UNUSED FFlist* result) { +const char* ffDetectBtrfs([[maybe_unused]] FFlist* result) { return "Not supported on this platform"; } diff --git a/src/detection/camera/camera_android.c b/src/detection/camera/camera_android.c index b09314d39d..9a82668d6c 100644 --- a/src/detection/camera/camera_android.c +++ b/src/detection/camera/camera_android.c @@ -13,14 +13,14 @@ static inline void wrapYyjsonFree(yyjson_doc** doc) { } } -const char* ffDetectCamera(FF_A_UNUSED FFlist* result) { +const char* ffDetectCamera([[maybe_unused]] FFlist* result) { FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); - if (ffProcessAppendStdOut(&buffer, (char* const[]) { FF_TERMUX_API_PATH, FF_TERMUX_API_PARAM, NULL })) { + if (ffProcessAppendStdOut(&buffer, (char* const[]) { FF_TERMUX_API_PATH, FF_TERMUX_API_PARAM, nullptr })) { return "Starting `" FF_TERMUX_API_PATH " " FF_TERMUX_API_PARAM "` failed"; } - yyjson_doc* FF_A_CLEANUP(wrapYyjsonFree) doc = yyjson_read_opts(buffer.chars, buffer.length, 0, NULL, NULL); + [[gnu::cleanup(wrapYyjsonFree)]] yyjson_doc* doc = yyjson_read_opts(buffer.chars, buffer.length, 0, nullptr, nullptr); if (!doc) { return "Failed to parse camera info"; } @@ -54,5 +54,5 @@ const char* ffDetectCamera(FF_A_UNUSED FFlist* result) { ffStrbufInit(&camera->colorspace); } - return NULL; + return nullptr; } diff --git a/src/detection/camera/camera_apple.m b/src/detection/camera/camera_apple.m index aa5c1cf91a..da6884486c 100644 --- a/src/detection/camera/camera_apple.m +++ b/src/detection/camera/camera_apple.m @@ -8,7 +8,7 @@ #ifdef MAC_OS_VERSION_14_0 // To make fastfetch compiled on newer macOS versions runs on older ones -AVF_EXPORT FF_A_WEAK_IMPORT AVCaptureDeviceType const AVCaptureDeviceTypeExternal; +[[clang::weak_import]] AVF_EXPORT AVCaptureDeviceType const AVCaptureDeviceTypeExternal; #endif const char* ffDetectCamera(FFlist* result) @@ -16,7 +16,7 @@ #ifdef MAC_OS_X_VERSION_10_15 FF_SUPPRESS_IO(); // #822 - AVCaptureDeviceType deviceType = NULL; + AVCaptureDeviceType deviceType = nullptr; #ifdef MAC_OS_VERSION_14_0 // Strangely `@available(macOS 14.0, *)` doesn't work here (#1594) @@ -26,7 +26,7 @@ deviceType = AVCaptureDeviceTypeExternal; } #endif - if (deviceType == NULL) + if (deviceType == nullptr) deviceType = AVCaptureDeviceTypeExternalUnknown; AVCaptureDeviceDiscoverySession* session = [AVCaptureDeviceDiscoverySession discoverySessionWithDeviceTypes:@[AVCaptureDeviceTypeBuiltInWideAngleCamera, deviceType] @@ -54,7 +54,7 @@ camera->width = size.width < 0 ? 0 : (uint32_t) size.width; camera->height = size.height < 0 ? 0 : (uint32_t) size.height; } - return NULL; + return nullptr; #else return "No support for old MacOS version"; #endif diff --git a/src/detection/camera/camera_linux.c b/src/detection/camera/camera_linux.c index 2fea2b4b2c..2fc8b129c7 100644 --- a/src/detection/camera/camera_linux.c +++ b/src/detection/camera/camera_linux.c @@ -86,7 +86,7 @@ const char* ffDetectCamera(FFlist* result) { camera->height = fmt.fmt.pix.height; } - return NULL; + return nullptr; #else FF_UNUSED(result); return "Fastfetch was compiled without "; diff --git a/src/detection/camera/camera_nosupport.c b/src/detection/camera/camera_nosupport.c index ae5b2432d6..ca8e64a16d 100644 --- a/src/detection/camera/camera_nosupport.c +++ b/src/detection/camera/camera_nosupport.c @@ -1,5 +1,5 @@ #include "camera.h" -const char* ffDetectCamera(FF_A_UNUSED FFlist* result) { +const char* ffDetectCamera([[maybe_unused]] FFlist* result) { return "Not support on this platform"; } diff --git a/src/detection/camera/camera_windows.cpp b/src/detection/camera/camera_windows.cpp index 1f42306962..22d2fdec19 100644 --- a/src/detection/camera/camera_windows.cpp +++ b/src/detection/camera/camera_windows.cpp @@ -10,7 +10,7 @@ extern "C" { #include #include -extern "C" const char* ffDetectCamera(FF_A_UNUSED FFlist* result) { +extern "C" const char* ffDetectCamera([[maybe_unused]] FFlist* result) { FF_LIBRARY_LOAD_MESSAGE(mfplat, "mfplat" FF_LIBRARY_EXTENSION, 1) FF_LIBRARY_LOAD_SYMBOL_MESSAGE(mfplat, MFCreateAttributes) FF_LIBRARY_LOAD_MESSAGE(mf, "mf" FF_LIBRARY_EXTENSION, 1) @@ -21,7 +21,7 @@ extern "C" const char* ffDetectCamera(FF_A_UNUSED FFlist* result) { return error; } - IMFAttributes* FF_AUTO_RELEASE_COM_OBJECT attrs = nullptr; + FF_AUTO_RELEASE_COM_OBJECT IMFAttributes* attrs = nullptr; if (FAILED(ffMFCreateAttributes(&attrs, 1))) { return "MFCreateAttributes() failed"; } @@ -32,7 +32,7 @@ extern "C" const char* ffDetectCamera(FF_A_UNUSED FFlist* result) { return "SetGUID(MF_*) failed"; } - IMFActivate** devices = NULL; + IMFActivate** devices = nullptr; uint32_t count; if (FAILED(ffMFEnumDeviceSources(attrs, &devices, &count))) { @@ -40,7 +40,7 @@ extern "C" const char* ffDetectCamera(FF_A_UNUSED FFlist* result) { } for (uint32_t i = 0; i < count; i++) { - IMFActivate* FF_AUTO_RELEASE_COM_OBJECT device = devices[i]; + FF_AUTO_RELEASE_COM_OBJECT IMFActivate* device = devices[i]; wchar_t buffer[256]; uint32_t length = 0; @@ -60,25 +60,25 @@ extern "C" const char* ffDetectCamera(FF_A_UNUSED FFlist* result) { ffStrbufSetNWS(&camera->id, length, buffer); } - IMFMediaSource* FF_AUTO_RELEASE_COM_OBJECT source = nullptr; + FF_AUTO_RELEASE_COM_OBJECT IMFMediaSource* source = nullptr; if (FAILED(device->ActivateObject(IID_PPV_ARGS(&source)))) { continue; } on_scope_exit destroySource([&] { source->Shutdown(); }); - IMFPresentationDescriptor* FF_AUTO_RELEASE_COM_OBJECT pd = nullptr; + FF_AUTO_RELEASE_COM_OBJECT IMFPresentationDescriptor* pd = nullptr; if (FAILED(source->CreatePresentationDescriptor(&pd))) { continue; } - IMFStreamDescriptor* FF_AUTO_RELEASE_COM_OBJECT sd = nullptr; + FF_AUTO_RELEASE_COM_OBJECT IMFStreamDescriptor* sd = nullptr; BOOL selected; if (FAILED(pd->GetStreamDescriptorByIndex(0, &selected, &sd))) { continue; } - IMFMediaTypeHandler* FF_AUTO_RELEASE_COM_OBJECT handler = nullptr; + FF_AUTO_RELEASE_COM_OBJECT IMFMediaTypeHandler* handler = nullptr; if (FAILED(sd->GetMediaTypeHandler(&handler))) { continue; } @@ -89,7 +89,7 @@ extern "C" const char* ffDetectCamera(FF_A_UNUSED FFlist* result) { } // Assume first type is the maximum resolution - IMFMediaType* type = NULL; + IMFMediaType* type = nullptr; for (DWORD idx = 0; SUCCEEDED(handler->GetMediaTypeByIndex(idx, &type)); ++idx) { on_scope_exit destroyType([=] { type->Release(); }); diff --git a/src/detection/chassis/chassis.c b/src/detection/chassis/chassis.c index d4d1fd3788..d87e3a71f3 100644 --- a/src/detection/chassis/chassis.c +++ b/src/detection/chassis/chassis.c @@ -76,6 +76,6 @@ const char* ffChassisTypeToString(uint32_t type) { case 0x24: return "Stick PC"; default: - return NULL; + return nullptr; } } diff --git a/src/detection/chassis/chassis_apple.c b/src/detection/chassis/chassis_apple.c index 1ff4fee523..b5a041dcf0 100644 --- a/src/detection/chassis/chassis_apple.c +++ b/src/detection/chassis/chassis_apple.c @@ -11,7 +11,7 @@ const char* ffDetectChassis(FFChassisResult* result) { .uuid = ffStrbufCreate(), .vendor = ffStrbufCreate(), }; - if (ffDetectHost(&host) != NULL) { + if (ffDetectHost(&host) != nullptr) { return "Failed to detect host"; } @@ -36,5 +36,5 @@ const char* ffDetectChassis(FFChassisResult* result) { ffStrbufDestroy(&host.uuid); ffStrbufDestroy(&host.vendor); - return NULL; + return nullptr; } diff --git a/src/detection/chassis/chassis_bsd.c b/src/detection/chassis/chassis_bsd.c index fa13718909..dc839bcd2a 100644 --- a/src/detection/chassis/chassis_bsd.c +++ b/src/detection/chassis/chassis_bsd.c @@ -12,5 +12,5 @@ const char* ffDetectChassis(FFChassisResult* result) { ffCleanUpSmbiosValue(&result->serial); ffSettingsGetFreeBSDKenv("smbios.chassis.version", &result->version); ffCleanUpSmbiosValue(&result->version); - return NULL; + return nullptr; } diff --git a/src/detection/chassis/chassis_linux.c b/src/detection/chassis/chassis_linux.c index af7ed0a1e6..686fc67be9 100644 --- a/src/detection/chassis/chassis_linux.c +++ b/src/detection/chassis/chassis_linux.c @@ -35,5 +35,5 @@ const char* ffDetectChassis(FFChassisResult* result) { result->type.chars[0] = (char) toupper(result->type.chars[0]); } } - return NULL; + return nullptr; } diff --git a/src/detection/chassis/chassis_nbsd.c b/src/detection/chassis/chassis_nbsd.c index 56447982d1..386da9212a 100644 --- a/src/detection/chassis/chassis_nbsd.c +++ b/src/detection/chassis/chassis_nbsd.c @@ -3,18 +3,18 @@ #include "common/smbios.h" const char* ffDetectChassis(FFChassisResult* chassis) { - if (ffSysctlGetString("machdep.dmi.chassis-type", &chassis->type) == NULL) { + if (ffSysctlGetString("machdep.dmi.chassis-type", &chassis->type) == nullptr) { ffCleanUpSmbiosValue(&chassis->type); } - if (ffSysctlGetString("machdep.dmi.chassis-version", &chassis->version) == NULL) { + if (ffSysctlGetString("machdep.dmi.chassis-version", &chassis->version) == nullptr) { ffCleanUpSmbiosValue(&chassis->version); } - if (ffSysctlGetString("machdep.dmi.chassis-vendor", &chassis->vendor) == NULL) { + if (ffSysctlGetString("machdep.dmi.chassis-vendor", &chassis->vendor) == nullptr) { ffCleanUpSmbiosValue(&chassis->vendor); } - if (ffSysctlGetString("machdep.dmi.chassis-serial", &chassis->serial) == NULL) { + if (ffSysctlGetString("machdep.dmi.chassis-serial", &chassis->serial) == nullptr) { ffCleanUpSmbiosValue(&chassis->serial); } - return NULL; + return nullptr; } diff --git a/src/detection/chassis/chassis_nosupport.c b/src/detection/chassis/chassis_nosupport.c index 0fc4dd949d..4b73180803 100644 --- a/src/detection/chassis/chassis_nosupport.c +++ b/src/detection/chassis/chassis_nosupport.c @@ -1,5 +1,5 @@ #include "chassis.h" -const char* ffDetectChassis(FF_A_UNUSED FFChassisResult* result) { +const char* ffDetectChassis([[maybe_unused]] FFChassisResult* result) { return "Not supported on this platform"; } diff --git a/src/detection/chassis/chassis_windows.c b/src/detection/chassis/chassis_windows.c index 51a4c6c160..25b37f85ad 100644 --- a/src/detection/chassis/chassis_windows.c +++ b/src/detection/chassis/chassis_windows.c @@ -2,7 +2,7 @@ #include "common/smbios.h" // 7.4 -typedef struct FFSmbiosSystemEnclosure { +typedef struct [[gnu::packed]] FFSmbiosSystemEnclosure { FFSmbiosHeader Header; uint8_t Manufacturer; // string @@ -24,7 +24,7 @@ typedef struct FFSmbiosSystemEnclosure { uint8_t ContainedElementCount; // varies uint8_t ContainedRecordLength; // varies uint8_t ContainedElements[]; // varies -} FF_A_PACKED FFSmbiosSystemEnclosure; +} FFSmbiosSystemEnclosure; static_assert(offsetof(FFSmbiosSystemEnclosure, ContainedElements) == 0x15, "FFSmbiosSystemEnclosure: Wrong struct alignment"); @@ -50,5 +50,5 @@ const char* ffDetectChassis(FFChassisResult* result) { ffCleanUpSmbiosValue(&result->version); ffStrbufSetStatic(&result->type, ffChassisTypeToString(data->Type)); - return NULL; + return nullptr; } diff --git a/src/detection/codec/codec.h b/src/detection/codec/codec.h index d0f48d9787..5f771a3251 100644 --- a/src/detection/codec/codec.h +++ b/src/detection/codec/codec.h @@ -3,7 +3,7 @@ #include "fastfetch.h" #include "modules/codec/option.h" -typedef enum FF_A_PACKED FFCodecType { +typedef enum FFCodecType: uint32_t { FF_CODEC_TYPE_NONE = 0, FF_CODEC_TYPE_UNKNOWN = UINT32_C(1) << 0, FF_CODEC_TYPE_H261 = UINT32_C(1) << 1, @@ -25,7 +25,6 @@ typedef enum FF_A_PACKED FFCodecType { FF_CODEC_TYPE_PRORES = UINT32_C(1) << 17, FF_CODEC_TYPE_PRORES_RAW = UINT32_C(1) << 18, FF_CODEC_TYPE_MAX = FF_CODEC_TYPE_PRORES_RAW, - FF_CODEC_TYPE_FORCE_UNSIGNED = UINT32_MAX, } FFCodecType; typedef struct FFCodecResult { diff --git a/src/detection/codec/codec_android.c b/src/detection/codec/codec_android.c index 238dab7e81..15782bee4e 100644 --- a/src/detection/codec/codec_android.c +++ b/src/detection/codec/codec_android.c @@ -37,13 +37,13 @@ static bool ffCodecIsLikelySoftware(const char* codecName) { static bool ffCodecIsHardwareAccelerated( AMediaCodec* codec, - __typeof__(&AMediaCodec_getName) ffAMediaCodec_getName, - __typeof__(&AMediaCodec_releaseName) ffAMediaCodec_releaseName) { + typeof(&AMediaCodec_getName) ffAMediaCodec_getName, + typeof(&AMediaCodec_releaseName) ffAMediaCodec_releaseName) { if (!codec) { return false; } - char* codecName = NULL; + char* codecName = nullptr; media_status_t status = ffAMediaCodec_getName(codec, &codecName); if (status != AMEDIA_OK || !codecName) { return false; @@ -98,5 +98,5 @@ const char* ffDetectCodecNative(FFCodecOptions* options, FFlist* result /*list o item->platformApi = "AMediaCodec"; } - return NULL; + return nullptr; } diff --git a/src/detection/codec/codec_apple.c b/src/detection/codec/codec_apple.c index 377837303e..2cf2a48b2f 100644 --- a/src/detection/codec/codec_apple.c +++ b/src/detection/codec/codec_apple.c @@ -41,8 +41,8 @@ static FFCodecType ffCodecCodecToType(CMVideoCodecType codec) { } static FFCodecType ffCodecDetectEncoders(void) { - CFArrayRef encoderList = NULL; - if (VTCopyVideoEncoderList(NULL, &encoderList) != noErr || !encoderList) { + FF_CFTYPE_AUTO_RELEASE CFArrayRef encoderList = nullptr; + if (VTCopyVideoEncoderList(nullptr, &encoderList) != noErr || !encoderList) { return FF_CODEC_TYPE_NONE; } @@ -51,9 +51,9 @@ static FFCodecType ffCodecDetectEncoders(void) { CFDictionaryRef encoder = CFArrayGetValueAtIndex(encoderList, i); bool isHardwareAccelerated; int codec; - if (ffCfDictGetBool(encoder, CFSTR("IsHardwareAccelerated"), &isHardwareAccelerated) != NULL || + if (ffCfDictGetBool(encoder, CFSTR("IsHardwareAccelerated"), &isHardwareAccelerated) != nullptr || !isHardwareAccelerated || - ffCfDictGetInt(encoder, CFSTR("CodecType"), &codec) != NULL) { + ffCfDictGetInt(encoder, CFSTR("CodecType"), &codec) != nullptr) { continue; } types |= ffCodecCodecToType((CMVideoCodecType) codec); @@ -65,16 +65,20 @@ static FFCodecType ffCodecDetectEncoders(void) { static FFCodecType ffCodecDetectDecoders() { FFCodecType types = FF_CODEC_TYPE_NONE; for (uint32_t i = 0; i < ARRAY_SIZE(FF_CODEC_CODECS); ++i) { - if (types & FF_CODEC_CODECS[i].type) { + auto codec = FF_CODEC_CODECS[i]; + if (types & codec.type) { continue; } - bool supported = VTIsHardwareDecodeSupported(FF_CODEC_CODECS[i].codec); + if (__builtin_available(macOS 11.0, *)) { + VTRegisterSupplementalVideoDecoderIfAvailable(codec.codec); + } + bool supported = VTIsHardwareDecodeSupported(codec.codec); if (!supported) { continue; } - types |= FF_CODEC_CODECS[i].type; + types |= codec.type; } return types; @@ -92,5 +96,5 @@ const char* ffDetectCodecNative(FFCodecOptions* options, FFlist* result /* list item->platformApi = "VideoToolbox"; } - return NULL; + return nullptr; } diff --git a/src/detection/codec/codec_linux.c b/src/detection/codec/codec_linux.c index 2a2c213ca2..f058744bb1 100644 --- a/src/detection/codec/codec_linux.c +++ b/src/detection/codec/codec_linux.c @@ -226,13 +226,13 @@ static const char* detectCodecByVaDrm(FFVAData* vaData, FFCodecOptions* options, const char* error = "No DRM device could initialize VA-API"; FF_AUTO_CLOSE_DIR DIR* dirp = opendir("/dev/dri/"); - if (dirp == NULL) { + if (dirp == nullptr) { return "opendir(/dev/dri/) failed"; } int drifd = dirfd(dirp); struct dirent* entry; - while ((entry = readdir(dirp)) != NULL) { + while ((entry = readdir(dirp)) != nullptr) { if (entry->d_name[0] == '.' || !ffStrStartsWith(entry->d_name, "renderD")) { continue; } @@ -248,7 +248,7 @@ static const char* detectCodecByVaDrm(FFVAData* vaData, FFCodecOptions* options, } if (vaDetectDisplay(display, vaData, options, result, "VA-API (DRM)")) { - error = NULL; + error = nullptr; } } @@ -266,7 +266,7 @@ static const char* detectCodecByVaX11(FFVAData* vaData, FFCodecOptions* options, FF_LIBRARY_LOAD_MESSAGE(libvaX11, "libva-x11" FF_LIBRARY_EXTENSION, 2) FF_LIBRARY_LOAD_SYMBOL_MESSAGE(libvaX11, vaGetDisplay) - Display* x11Display = ffXOpenDisplay(NULL); + Display* x11Display = ffXOpenDisplay(nullptr); if (!x11Display) { return "XOpenDisplay() failed"; } @@ -283,7 +283,7 @@ static const char* detectCodecByVaX11(FFVAData* vaData, FFCodecOptions* options, } ffXCloseDisplay(x11Display); - return NULL; + return nullptr; } #endif @@ -301,14 +301,14 @@ static const char* detectCodecByVa(FFCodecOptions* options, FFlist* result) { FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(libva, vaData, vaGetConfigAttributes) #if FF_HAVE_VADRM - if (detectCodecByVaDrm(&vaData, options, result) == NULL) { - return NULL; + if (detectCodecByVaDrm(&vaData, options, result) == nullptr) { + return nullptr; } #endif #if FF_HAVE_VAX11 - if (detectCodecByVaX11(&vaData, options, result) == NULL) { - return NULL; + if (detectCodecByVaX11(&vaData, options, result) == nullptr) { + return nullptr; } #endif @@ -378,26 +378,26 @@ static const char* detectCodecByVdpau(FFCodecOptions* options, FFlist* result) { FF_LIBRARY_LOAD_MESSAGE(libvdpau, "libvdpau" FF_LIBRARY_EXTENSION, 1) FF_LIBRARY_LOAD_SYMBOL_MESSAGE(libvdpau, vdp_device_create_x11) - Display* x11Display = ffXOpenDisplay(NULL); + Display* x11Display = ffXOpenDisplay(nullptr); if (!x11Display) { return "XOpenDisplay() failed"; } VdpDevice device = VDP_INVALID_HANDLE; - VdpGetProcAddress* ffvdp_get_proc_address = NULL; + VdpGetProcAddress* ffvdp_get_proc_address = nullptr; if (ffvdp_device_create_x11(x11Display, ffXDefaultScreen(x11Display), &device, &ffvdp_get_proc_address) != VDP_STATUS_OK || device == VDP_INVALID_HANDLE || - ffvdp_get_proc_address == NULL) { + ffvdp_get_proc_address == nullptr) { ffXCloseDisplay(x11Display); return "vdp_device_create_x11() failed"; } - VdpDeviceDestroy* ffvdp_device_destroy = NULL; - VdpDecoderQueryCapabilities* ffvdp_decoder_query_capabilities = NULL; + VdpDeviceDestroy* ffvdp_device_destroy = nullptr; + VdpDecoderQueryCapabilities* ffvdp_decoder_query_capabilities = nullptr; if (ffvdp_get_proc_address(device, VDP_FUNC_ID_DEVICE_DESTROY, (void**) &ffvdp_device_destroy) != VDP_STATUS_OK || ffvdp_get_proc_address(device, VDP_FUNC_ID_DECODER_QUERY_CAPABILITIES, (void**) &ffvdp_decoder_query_capabilities) != VDP_STATUS_OK || - ffvdp_device_destroy == NULL || - ffvdp_decoder_query_capabilities == NULL) { + ffvdp_device_destroy == nullptr || + ffvdp_decoder_query_capabilities == nullptr) { if (ffvdp_device_destroy) { ffvdp_device_destroy(device); } @@ -426,7 +426,7 @@ static const char* detectCodecByVdpau(FFCodecOptions* options, FFlist* result) { ffXCloseDisplay(x11Display); if (decoderTypes == FF_CODEC_TYPE_NONE) { - return NULL; + return nullptr; } FFCodecResult* item = FF_LIST_ADD(FFCodecResult, *result); @@ -441,7 +441,7 @@ static const char* detectCodecByVdpau(FFCodecOptions* options, FFlist* result) { item->encoders = FF_CODEC_TYPE_NONE; item->platformApi = "VDPAU"; - return NULL; + return nullptr; } #endif @@ -449,13 +449,13 @@ const char* ffDetectCodecNative(FFCodecOptions* options, FFlist* result /* list FF_SUPPRESS_IO(); #if FF_HAVE_VA - if (detectCodecByVa(options, result) == NULL) { - return NULL; + if (detectCodecByVa(options, result) == nullptr) { + return nullptr; } #endif #if FF_HAVE_VDPAU - if (detectCodecByVdpau(options, result) == NULL) { - return NULL; + if (detectCodecByVdpau(options, result) == nullptr) { + return nullptr; } #endif diff --git a/src/detection/codec/codec_vulkan.c b/src/detection/codec/codec_vulkan.c index eabfe26160..a0c833f2ff 100644 --- a/src/detection/codec/codec_vulkan.c +++ b/src/detection/codec/codec_vulkan.c @@ -80,8 +80,8 @@ const char* ffDetectCodecVulkan(FFCodecOptions* options, FFlist* result /*list o FF_SUPPRESS_IO(); uint32_t apiVersion = VK_API_VERSION_1_0; - PFN_vkEnumerateInstanceVersion ffvkEnumerateInstanceVersion = (PFN_vkEnumerateInstanceVersion) ffvkGetInstanceProcAddr(NULL, "vkEnumerateInstanceVersion"); - if (ffvkEnumerateInstanceVersion != NULL) { + PFN_vkEnumerateInstanceVersion ffvkEnumerateInstanceVersion = (PFN_vkEnumerateInstanceVersion) ffvkGetInstanceProcAddr(nullptr, "vkEnumerateInstanceVersion"); + if (ffvkEnumerateInstanceVersion != nullptr) { uint32_t detectedApiVersion = 0; if (ffvkEnumerateInstanceVersion(&detectedApiVersion) == VK_SUCCESS) { apiVersion = detectedApiVersion; @@ -105,7 +105,7 @@ const char* ffDetectCodecVulkan(FFCodecOptions* options, FFlist* result /*list o .apiVersion = apiVersion, }, }, - NULL, + nullptr, &vkInstance); if (res != VK_SUCCESS) { FF_DEBUG("ffvkCreateInstance() failed with VkResult=%d", res); @@ -129,25 +129,25 @@ const char* ffDetectCodecVulkan(FFCodecOptions* options, FFlist* result /*list o PFN_vkGetPhysicalDeviceProperties ffvkGetPhysicalDeviceProperties = (PFN_vkGetPhysicalDeviceProperties) ffvkGetInstanceProcAddr(vkInstance, "vkGetPhysicalDeviceProperties"); if (!ffvkGetPhysicalDeviceProperties) { - ffvkDestroyInstance(vkInstance, NULL); + ffvkDestroyInstance(vkInstance, nullptr); return "vkGetPhysicalDeviceProperties is not available"; } PFN_vkGetPhysicalDeviceQueueFamilyProperties2 ffvkGetPhysicalDeviceQueueFamilyProperties2 = (PFN_vkGetPhysicalDeviceQueueFamilyProperties2) ffvkGetInstanceProcAddr(vkInstance, "vkGetPhysicalDeviceQueueFamilyProperties2"); if (!ffvkGetPhysicalDeviceQueueFamilyProperties2) { - ffvkDestroyInstance(vkInstance, NULL); + ffvkDestroyInstance(vkInstance, nullptr); return "vkGetPhysicalDeviceQueueFamilyProperties2 is not available"; } uint32_t physicalDeviceCount = 0; - res = ffvkEnumeratePhysicalDevices(vkInstance, &physicalDeviceCount, NULL); + res = ffvkEnumeratePhysicalDevices(vkInstance, &physicalDeviceCount, nullptr); if (res != VK_SUCCESS) { FF_DEBUG("ffvkEnumeratePhysicalDevices(count) failed with VkResult=%d", res); - ffvkDestroyInstance(vkInstance, NULL); + ffvkDestroyInstance(vkInstance, nullptr); return "ffvkEnumeratePhysicalDevices() failed during Vulkan codec detection"; } if (physicalDeviceCount == 0) { - ffvkDestroyInstance(vkInstance, NULL); + ffvkDestroyInstance(vkInstance, nullptr); return "No Vulkan physical devices found"; } @@ -156,7 +156,7 @@ const char* ffDetectCodecVulkan(FFCodecOptions* options, FFlist* result /*list o res = ffvkEnumeratePhysicalDevices(vkInstance, &physicalDeviceCount, physicalDevices); if (res != VK_SUCCESS) { FF_DEBUG("ffvkEnumeratePhysicalDevices(list) failed with VkResult=%d", res); - ffvkDestroyInstance(vkInstance, NULL); + ffvkDestroyInstance(vkInstance, nullptr); return "ffvkEnumeratePhysicalDevices() failed during Vulkan codec detection"; } @@ -167,7 +167,7 @@ const char* ffDetectCodecVulkan(FFCodecOptions* options, FFlist* result /*list o ffvkGetPhysicalDeviceProperties(physicalDevices[i], &properties); uint32_t extensionCount = 0; - res = ffvkEnumerateDeviceExtensionProperties(physicalDevices[i], NULL, &extensionCount, NULL); + res = ffvkEnumerateDeviceExtensionProperties(physicalDevices[i], nullptr, &extensionCount, nullptr); if (res != VK_SUCCESS) { FF_DEBUG("vkEnumerateDeviceExtensionProperties(count) failed for '%s' with VkResult=%d", properties.deviceName, res); continue; @@ -180,7 +180,7 @@ const char* ffDetectCodecVulkan(FFCodecOptions* options, FFlist* result /*list o FF_AUTO_FREE VkExtensionProperties* extensions = (VkExtensionProperties*) malloc(sizeof(VkExtensionProperties) * (size_t) extensionCount); - res = ffvkEnumerateDeviceExtensionProperties(physicalDevices[i], NULL, &extensionCount, extensions); + res = ffvkEnumerateDeviceExtensionProperties(physicalDevices[i], nullptr, &extensionCount, extensions); if (res != VK_SUCCESS) { FF_DEBUG("vkEnumerateDeviceExtensionProperties(list) failed for '%s' with VkResult=%d", properties.deviceName, res); continue; @@ -198,7 +198,7 @@ const char* ffDetectCodecVulkan(FFCodecOptions* options, FFlist* result /*list o sawVideoQueueExtension = true; uint32_t queueFamilyCount = 0; - ffvkGetPhysicalDeviceQueueFamilyProperties2(physicalDevices[i], &queueFamilyCount, NULL); + ffvkGetPhysicalDeviceQueueFamilyProperties2(physicalDevices[i], &queueFamilyCount, nullptr); if (queueFamilyCount == 0) { FF_DEBUG("Skipping Vulkan device '%s' because it has no queue families", properties.deviceName); continue; @@ -248,10 +248,10 @@ const char* ffDetectCodecVulkan(FFCodecOptions* options, FFlist* result /*list o FF_DEBUG("Added Vulkan codec result for '%s': decoders=%u encoders=%u", properties.deviceName, (unsigned) decoders, (unsigned) encoders); } - ffvkDestroyInstance(vkInstance, NULL); + ffvkDestroyInstance(vkInstance, nullptr); if (result->length > 0) { - return NULL; + return nullptr; } return sawVideoQueueExtension ? "No supported Vulkan video codec operations found" diff --git a/src/detection/codec/codec_windows.cpp b/src/detection/codec/codec_windows.cpp index 9e2183959a..1820361df2 100644 --- a/src/detection/codec/codec_windows.cpp +++ b/src/detection/codec/codec_windows.cpp @@ -277,8 +277,8 @@ static const FFCodecMftEncoderSubtype FF_D3D11VA_MFT_ENCODER_SUBTYPES[] = { { &MFVideoFormat_AV1, FF_CODEC_TYPE_AV1 }, }; -static FFCodecType ffDetectD3d11vaDecoders(IDXGIAdapter1* adapter, __typeof__(&D3D11CreateDevice) ffD3D11CreateDevice) { - ID3D11Device* FF_AUTO_RELEASE_COM_OBJECT d3dDevice = nullptr; +static FFCodecType ffDetectD3d11vaDecoders(IDXGIAdapter1* adapter, typeof(&D3D11CreateDevice) ffD3D11CreateDevice) { + FF_AUTO_RELEASE_COM_OBJECT ID3D11Device* d3dDevice = nullptr; D3D_FEATURE_LEVEL featureLevel; if (FAILED(ffD3D11CreateDevice( adapter, @@ -295,7 +295,7 @@ static FFCodecType ffDetectD3d11vaDecoders(IDXGIAdapter1* adapter, __typeof__(&D return FF_CODEC_TYPE_NONE; } - ID3D11VideoDevice* FF_AUTO_RELEASE_COM_OBJECT videoDevice = nullptr; + FF_AUTO_RELEASE_COM_OBJECT ID3D11VideoDevice* videoDevice = nullptr; if (FAILED(d3dDevice->QueryInterface(__uuidof(ID3D11VideoDevice), (void**) &videoDevice)) || !videoDevice) { return FF_CODEC_TYPE_NONE; } @@ -319,8 +319,8 @@ static FFCodecType ffDetectD3d11vaDecoders(IDXGIAdapter1* adapter, __typeof__(&D return decoders; } -static FFCodecType ffDetectD3d11MftEncoders(const LUID& adapterLuid, __typeof__(&MFCreateAttributes) ffMFCreateAttributes, __typeof__(&MFTEnum2) ffMFTEnum2) { - IMFAttributes* FF_AUTO_RELEASE_COM_OBJECT attributes = nullptr; +static FFCodecType ffDetectD3d11MftEncoders(const LUID& adapterLuid, typeof(&MFCreateAttributes) ffMFCreateAttributes, typeof(&MFTEnum2) ffMFTEnum2) { + FF_AUTO_RELEASE_COM_OBJECT IMFAttributes* attributes = nullptr; if (FAILED(ffMFCreateAttributes(&attributes, 1)) || !attributes) { return FF_CODEC_TYPE_NONE; } @@ -382,7 +382,7 @@ static FFCodecType ffCodecEncoderToType(D3D12_VIDEO_ENCODER_CODEC codec) { template static void ffEnumHardwareAdapters(IDXGIFactory1* factory, Func&& onAdapter) { for (UINT adapterIndex = 0;; ++adapterIndex) { - IDXGIAdapter1* FF_AUTO_RELEASE_COM_OBJECT adapter = nullptr; + FF_AUTO_RELEASE_COM_OBJECT IDXGIAdapter1* adapter = nullptr; HRESULT adapterStatus = factory->EnumAdapters1(adapterIndex, &adapter); if (adapterStatus == DXGI_ERROR_NOT_FOUND) { break; @@ -468,7 +468,7 @@ const char* detectD3d12va(FFCodecOptions* options, FFlist* result /*list of FFCo const uint32_t resultLengthBefore = result->length; ffEnumHardwareAdapters(factory, [&](IDXGIAdapter1* adapter, const DXGI_ADAPTER_DESC1& desc) { - ID3D12Device* FF_AUTO_RELEASE_COM_OBJECT d3dDevice = nullptr; + FF_AUTO_RELEASE_COM_OBJECT ID3D12Device* d3dDevice = nullptr; if (FAILED(ffD3D12CreateDevice( adapter, D3D_FEATURE_LEVEL_11_0, @@ -478,7 +478,7 @@ const char* detectD3d12va(FFCodecOptions* options, FFlist* result /*list of FFCo return; } - ID3D12VideoDevice* FF_AUTO_RELEASE_COM_OBJECT videoDevice = nullptr; + FF_AUTO_RELEASE_COM_OBJECT ID3D12VideoDevice* videoDevice = nullptr; if (FAILED(d3dDevice->QueryInterface(__uuidof(ID3D12VideoDevice), (void**) &videoDevice)) || !videoDevice) { return; } @@ -538,7 +538,7 @@ const char* ffDetectCodecNative(FFCodecOptions* options, FFlist* result /*list o return error; } - IDXGIFactory1* FF_AUTO_RELEASE_COM_OBJECT factory = nullptr; + FF_AUTO_RELEASE_COM_OBJECT IDXGIFactory1* factory = nullptr; if (FAILED(ffCreateDXGIFactory1(__uuidof(IDXGIFactory1), (void**) &factory)) || !factory) { return "CreateDXGIFactory1() failed"; } diff --git a/src/detection/command/command.c b/src/detection/command/command.c index 28c6f4b727..5be3d8aea8 100644 --- a/src/detection/command/command.c +++ b/src/detection/command/command.c @@ -19,8 +19,8 @@ static const char* spawnProcess(FFCommandOptions* options, FFProcessHandle* hand options->shell.chars, options->param.chars, options->text.chars, - NULL } - : (char* const[]) { options->shell.chars, options->text.chars, NULL }, + nullptr } + : (char* const[]) { options->shell.chars, options->text.chars, nullptr }, options->useStdErr, handle); } @@ -54,5 +54,5 @@ const char* ffDetectCommand(FFCommandOptions* options, FFstrbuf* result) { } ffStrbufTrimRightSpace(result); - return NULL; + return nullptr; } diff --git a/src/detection/cpu/cpu.c b/src/detection/cpu/cpu.c index 155c0328c8..a796175e0d 100644 --- a/src/detection/cpu/cpu.c +++ b/src/detection/cpu/cpu.c @@ -27,7 +27,7 @@ const char* ffDetectCPU(const FFCPUOptions* options, FFCPUResult* cpu) { ffCPUDetectX86Specific(cpu); #endif - return NULL; + return nullptr; } const char* ffCPUAppleCodeToName(uint32_t code) { @@ -63,7 +63,7 @@ const char* ffCPUAppleCodeToName(uint32_t code) { case 6041: return "Apple M4 Max"; default: - return NULL; + return nullptr; } } @@ -79,7 +79,7 @@ const char* ffCPUQualcommCodeToName(uint32_t code) { case 8280: return "Qualcomm Snapdragon 8cx Gen 3"; default: - return NULL; + return nullptr; } } @@ -299,7 +299,7 @@ void ffCPUDetectByCpuid(FFCPUResult* cpu) { uint64_t caps[2] = { 0 }; // 80-bit capability mask, split into two 64-bit values size_t size = sizeof(caps); - if (sysctlbyname("hw.optional.arm.caps", caps, &size, NULL, 0) != 0) { + if (sysctlbyname("hw.optional.arm.caps", caps, &size, nullptr, 0) != 0) { return; } @@ -510,14 +510,14 @@ void ffCPUDetectByCpuid(FFCPUResult* cpu) { } } #else -void ffCPUDetectByCpuid(FF_A_UNUSED FFCPUResult* cpu) { +void ffCPUDetectByCpuid([[maybe_unused]] FFCPUResult* cpu) { // Unsupported system } #endif #else -void ffCPUDetectByCpuid(FF_A_UNUSED FFCPUResult* cpu) { +void ffCPUDetectByCpuid([[maybe_unused]] FFCPUResult* cpu) { // Unsupported architecture } diff --git a/src/detection/cpu/cpu_apple.c b/src/detection/cpu/cpu_apple.c index 7820192559..bce7d55b29 100644 --- a/src/detection/cpu/cpu_apple.c +++ b/src/detection/cpu/cpu_apple.c @@ -6,13 +6,13 @@ static double detectCpuTemp(const FFCPUOptions* options, const FFstrbuf* cpuName) { double result = 0; - const char* error = NULL; + const char* error = nullptr; if (options->tempSensor.length) { error = ffDetectSmcSpecificTemp(options->tempSensor.chars, &result); } else { if (ffStrbufStartsWithS(cpuName, "Apple M")) { - switch (strtol(cpuName->chars + strlen("Apple M"), NULL, 10)) { + switch (strtol(cpuName->chars + strlen("Apple M"), nullptr, 10)) { case 1: error = ffDetectSmcTemps(FF_TEMP_CPU_M1X, &result); break; @@ -25,6 +25,9 @@ static double detectCpuTemp(const FFCPUOptions* options, const FFstrbuf* cpuName case 4: error = ffDetectSmcTemps(FF_TEMP_CPU_M4X, &result); break; + case 5: + error = ffDetectSmcTemps(FF_TEMP_CPU_M5X, &result); + break; default: error = "Unsupported Apple Silicon CPU"; } @@ -83,7 +86,7 @@ static const char* detectFrequency(FFCPUResult* cpu) { } } - return NULL; + return nullptr; } #else static const char* detectFrequency(FFCPUResult* cpu) { @@ -92,11 +95,11 @@ static const char* detectFrequency(FFCPUResult* cpu) { if (cpu->frequencyBase == 0) { unsigned current = 0; size_t size = sizeof(current); - if (sysctl((int[]) { CTL_HW, HW_CPU_FREQ }, 2, ¤t, &size, NULL, 0) == 0) { + if (sysctl((int[]) { CTL_HW, HW_CPU_FREQ }, 2, ¤t, &size, nullptr, 0) == 0) { cpu->frequencyBase = (uint32_t) (current / 1000 / 1000); } } - return NULL; + return nullptr; } #endif @@ -117,11 +120,11 @@ static const char* detectCoreCount(FFCPUResult* cpu) { .count = (uint32_t) ffSysctlGetInt(sysctlKey, 0), }; } - return NULL; + return nullptr; } const char* ffDetectCPUImpl(const FFCPUOptions* options, FFCPUResult* cpu) { - if (ffSysctlGetString("machdep.cpu.brand_string", &cpu->name) != NULL) { + if (ffSysctlGetString("machdep.cpu.brand_string", &cpu->name) != nullptr) { return "sysctlbyname(machdep.cpu.brand_string) failed"; } @@ -154,5 +157,5 @@ const char* ffDetectCPUImpl(const FFCPUOptions* options, FFCPUResult* cpu) { cpu->temperature = options->temp ? detectCpuTemp(options, &cpu->name) : FF_CPU_TEMP_UNSET; - return NULL; + return nullptr; } diff --git a/src/detection/cpu/cpu_arm.h b/src/detection/cpu/cpu_arm.h index 571761aebf..23839bbbaa 100644 --- a/src/detection/cpu/cpu_arm.h +++ b/src/detection/cpu/cpu_arm.h @@ -221,7 +221,7 @@ static const char* armPartId2name(uint32_t partId) { case 0xd90: return "C1-Premium"; default: - return NULL; + return nullptr; } } @@ -234,7 +234,7 @@ static const char* brcmPartId2name(uint32_t partId) { case 0x516: return "ThunderX2"; default: - return NULL; + return nullptr; } } @@ -245,7 +245,7 @@ static const char* decPartId2name(uint32_t partId) { case 0xa11: return "SA1100"; default: - return NULL; + return nullptr; } } @@ -278,7 +278,7 @@ static const char* caviumPartId2name(uint32_t partId) { case 0x0b8: return "ThunderX3-T110"; default: - return NULL; + return nullptr; } } @@ -287,7 +287,7 @@ static const char* apmPartId2name(uint32_t partId) { case 0x000: return "X-Gene"; default: - return NULL; + return nullptr; } } @@ -328,7 +328,7 @@ static const char* qcomPartId2name(uint32_t partId) { case 0xc01: return "Saphira"; default: - return NULL; + return nullptr; } } @@ -343,7 +343,7 @@ static const char* samsungPartId2name(uint32_t partId) { case 0x004: return "Exynos-M5"; default: - return NULL; + return nullptr; } } @@ -358,7 +358,7 @@ static const char* nvidiaPartId2name(uint32_t partId) { case 0x010: return "Olympus"; default: - return NULL; + return nullptr; } } @@ -371,7 +371,7 @@ static const char* marvellPartId2name(uint32_t partId) { case 0x584: return "PJ4B-MP"; default: - return NULL; + return nullptr; } } @@ -456,7 +456,7 @@ static const char* applePartId2name(uint32_t partId) { case 0x049: return "Everest-M3-Max"; default: - return NULL; + return nullptr; } } @@ -467,7 +467,7 @@ static const char* faradayPartId2name(uint32_t partId) { case 0x626: return "FA626"; default: - return NULL; + return nullptr; } } @@ -516,7 +516,7 @@ static const char* intelPartId2name(uint32_t partId) { case 0xc12: return "IPX1200"; default: - return NULL; + return nullptr; } } @@ -527,7 +527,7 @@ static const char* fujitsuPartId2name(uint32_t partId) { case 0x003: return "MONAKA"; default: - return NULL; + return nullptr; } } @@ -542,7 +542,7 @@ static const char* hisiPartId2name(uint32_t partId) { case 0xd41: return "Cortex-A77"; /* HiSilicon uses this ID though advertises A77 */ default: - return NULL; + return nullptr; } } @@ -553,7 +553,7 @@ static const char* amperePartId2name(uint32_t partId) { case 0xac4: return "Ampere-1a"; default: - return NULL; + return nullptr; } } @@ -574,7 +574,7 @@ static const char* ftPartId2name(uint32_t partId) { case 0x862: return "FTC862"; default: - return NULL; + return nullptr; } } @@ -583,6 +583,6 @@ static const char* msPartId2name(uint32_t partId) { case 0xd49: return "Azure-Cobalt-100"; default: - return NULL; + return nullptr; } } diff --git a/src/detection/cpu/cpu_bsd.c b/src/detection/cpu/cpu_bsd.c index 4cca30e736..085b014988 100644 --- a/src/detection/cpu/cpu_bsd.c +++ b/src/detection/cpu/cpu_bsd.c @@ -28,11 +28,11 @@ static const char* detectCpuTemp(const FFCPUOptions* options, double* current) { // In tenth of degrees Kelvin *current = (double) temp / 10 - 273.15; - return NULL; + return nullptr; } const char* ffDetectCPUImpl(const FFCPUOptions* options, FFCPUResult* cpu) { - if (ffSysctlGetString("hw.model", &cpu->name) != NULL) { + if (ffSysctlGetString("hw.model", &cpu->name) != nullptr) { return "sysctlbyname(hw.model) failed"; } @@ -41,7 +41,7 @@ const char* ffDetectCPUImpl(const FFCPUOptions* options, FFCPUResult* cpu) { cpu->coresOnline = (uint16_t) ffSysctlGetInt("kern.smp.cpus", cpu->coresLogical); FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); - if (ffSysctlGetString("kern.sched.topology_spec", &buffer) == NULL && buffer.length > 0) { + if (ffSysctlGetString("kern.sched.topology_spec", &buffer) == nullptr && buffer.length > 0) { // // // 0, 1, 2, 3 @@ -82,13 +82,13 @@ const char* ffDetectCPUImpl(const FFCPUOptions* options, FFCPUResult* cpu) { ffStrbufClear(&buffer); char key[32]; snprintf(key, sizeof(key), "dev.cpu.%u.freq_levels", i); - if (ffSysctlGetString(key, &buffer) == NULL) { + if (ffSysctlGetString(key, &buffer) == nullptr) { if (buffer.length == 0) { continue; } // MHz/Watts pairs like: 2501/32000 2187/27125 2000/24000 - uint32_t fmax = (uint32_t) strtoul(buffer.chars, NULL, 10); + uint32_t fmax = (uint32_t) strtoul(buffer.chars, nullptr, 10); if (cpu->frequencyMax < fmax) { cpu->frequencyMax = fmax; } @@ -105,5 +105,5 @@ const char* ffDetectCPUImpl(const FFCPUOptions* options, FFCPUResult* cpu) { cpu->numaNodes = (uint16_t) ffSysctlGetInt("vm.ndomains", 0); - return NULL; + return nullptr; } diff --git a/src/detection/cpu/cpu_haiku.c b/src/detection/cpu/cpu_haiku.c index 9a8acb5879..5ca06a2842 100644 --- a/src/detection/cpu/cpu_haiku.c +++ b/src/detection/cpu/cpu_haiku.c @@ -4,16 +4,16 @@ #include #include -const char* ffDetectCPUImpl(FF_A_UNUSED const FFCPUOptions* options, FFCPUResult* cpu) { +const char* ffDetectCPUImpl([[maybe_unused]] const FFCPUOptions* options, FFCPUResult* cpu) { system_info sysInfo; if (get_system_info(&sysInfo) != B_OK) { return "get_system_info() failed"; } uint32 topoNodeCount = 0; - get_cpu_topology_info(NULL, &topoNodeCount); + get_cpu_topology_info(nullptr, &topoNodeCount); if (topoNodeCount == 0) { - return "get_cpu_topology_info(NULL) failed"; + return "get_cpu_topology_info(nullptr) failed"; } FF_AUTO_FREE cpu_topology_node_info* topology = malloc(sizeof(*topology) * topoNodeCount); @@ -64,5 +64,5 @@ const char* ffDetectCPUImpl(FF_A_UNUSED const FFCPUOptions* options, FFCPUResult cpu->packages = packages; cpu->coresPhysical = cores; cpu->coresOnline = cpu->coresLogical = (uint16_t) sysInfo.cpu_count; - return NULL; + return nullptr; } diff --git a/src/detection/cpu/cpu_linux.c b/src/detection/cpu/cpu_linux.c index df0135ef89..e41aeabe8a 100644 --- a/src/detection/cpu/cpu_linux.c +++ b/src/detection/cpu/cpu_linux.c @@ -69,7 +69,7 @@ static double detectCPUTemp(const FFCPUOptions* options) { if (options->tempSensor.length > 0) { FF_AUTO_CLOSE_FD int subfd = -1; - const char* fileName = NULL; + const char* fileName = nullptr; if (ffStrbufStartsWithS(&options->tempSensor, "hwmon") && ffCharIsDigit(options->tempSensor.chars[strlen("hwmon")])) { FF_AUTO_CLOSE_FD int dfd = open("/sys/class/hwmon/", O_PATH | O_CLOEXEC); subfd = openat(dfd, options->tempSensor.chars, O_RDONLY | O_DIRECTORY | O_CLOEXEC); @@ -115,7 +115,7 @@ static double detectCPUTemp(const FFCPUOptions* options) { int dfd = dirfd(dirp); struct dirent* entry; - while ((entry = readdir(dirp)) != NULL) { + while ((entry = readdir(dirp)) != nullptr) { if (entry->d_name[0] == '.') { continue; } @@ -137,7 +137,7 @@ static double detectCPUTemp(const FFCPUOptions* options) { if (dirp) { int dfd = dirfd(dirp); struct dirent* entry; - while ((entry = readdir(dirp)) != NULL) { + while ((entry = readdir(dirp)) != nullptr) { if (entry->d_name[0] == '.') { continue; } @@ -162,7 +162,7 @@ static double detectCPUTemp(const FFCPUOptions* options) { if (dirp) { int dfd = dirfd(dirp); struct dirent* entry; - while ((entry = readdir(dirp)) != NULL) { + while ((entry = readdir(dirp)) != nullptr) { if (entry->d_name[0] == '.') { continue; } @@ -193,7 +193,7 @@ static void detectNumaNodes(FFCPUResult* cpu) { } struct dirent* entry; - while ((entry = readdir(dir)) != NULL) { + while ((entry = readdir(dir)) != nullptr) { if (entry->d_type != DT_DIR && entry->d_type != DT_UNKNOWN) { continue; } @@ -210,8 +210,8 @@ static void detectQualcomm(FFCPUResult* cpu) { // https://en.wikipedia.org/wiki/List_of_Qualcomm_Snapdragon_systems_on_chips assert(cpu->name.length >= 2); - uint32_t code = (uint32_t) strtoul(cpu->name.chars + 2, NULL, 10); - const char* name = NULL; + uint32_t code = (uint32_t) strtoul(cpu->name.chars + 2, nullptr, 10); + const char* name = nullptr; switch (code) { case 8845: @@ -300,8 +300,8 @@ static void detectMediaTek(FFCPUResult* cpu) { // https://en.wikipedia.org/wiki/List_of_MediaTek_systems_on_chips assert(cpu->name.length >= 2); - uint32_t code = (uint32_t) strtoul(cpu->name.chars + 2, NULL, 10); - const char* name = NULL; + uint32_t code = (uint32_t) strtoul(cpu->name.chars + 2, nullptr, 10); + const char* name = nullptr; switch (code) // The SOC code of MTK Dimensity series is full of mess { @@ -353,8 +353,8 @@ static void detectExynos(FFCPUResult* cpu) { // https://en.wikipedia.org/wiki/Exynos assert(cpu->name.length > 3); - uint32_t code = (uint32_t) strtoul(cpu->name.chars + 3, NULL, 10); - const char* name = NULL; + uint32_t code = (uint32_t) strtoul(cpu->name.chars + 3, nullptr, 10); + const char* name = nullptr; switch (code) { case 9965: @@ -458,15 +458,15 @@ static void detectAndroid(FFCPUResult* cpu) { #include "cpu_arm.h" static void detectArmName(FFstrbuf* cpuinfo, FFCPUResult* cpu, uint32_t implId) { - char* line = NULL; + char* line = nullptr; size_t len = 0; uint32_t lastPartId = UINT32_MAX; while (ffStrbufGetline(&line, &len, cpuinfo)) { if (!ffStrStartsWith(line, "CPU part\t: ")) { continue; } - uint32_t partId = (uint32_t) strtoul(line + strlen("CPU part\t: "), NULL, 16); - const char* name = NULL; + uint32_t partId = (uint32_t) strtoul(line + strlen("CPU part\t: "), nullptr, 16); + const char* name = nullptr; switch (implId) { case 0x41: name = armPartId2name(partId); @@ -546,12 +546,12 @@ static void detectArmName(FFstrbuf* cpuinfo, FFCPUResult* cpu, uint32_t implId) static const char* parseCpuInfo( FFstrbuf* cpuinfo, FFCPUResult* cpu, - FF_A_UNUSED FFstrbuf* physicalCoresBuffer, - FF_A_UNUSED FFstrbuf* cpuMHz, - FF_A_UNUSED FFstrbuf* cpuIsa, - FF_A_UNUSED FFstrbuf* cpuUarch, - FF_A_UNUSED FFstrbuf* cpuImplementer) { - char* line = NULL; + [[maybe_unused]] FFstrbuf* physicalCoresBuffer, + [[maybe_unused]] FFstrbuf* cpuMHz, + [[maybe_unused]] FFstrbuf* cpuIsa, + [[maybe_unused]] FFstrbuf* cpuUarch, + [[maybe_unused]] FFstrbuf* cpuImplementer) { + char* line = nullptr; size_t len = 0; while (ffStrbufGetline(&line, &len, cpuinfo)) { @@ -606,7 +606,7 @@ static const char* parseCpuInfo( false); } - return NULL; + return nullptr; } static uint32_t getFrequency(int policyFd, const char* cpuinfoFileName, const char* scalingFileName, FFstrbuf* buffer) { @@ -636,7 +636,7 @@ static bool detectFrequency(FFCPUResult* cpu, const FFCPUOptions* options) { FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); struct dirent* entry; - while ((entry = readdir(dir)) != NULL) { + while ((entry = readdir(dir)) != nullptr) { if (ffStrStartsWith(entry->d_name, "policy") && ffCharIsDigit(entry->d_name[strlen("policy")])) { FF_AUTO_CLOSE_FD int policyFd = openat(freqFd, entry->d_name, O_RDONLY | O_DIRECTORY | O_CLOEXEC | O_PATH); if (policyFd < 0) { @@ -656,7 +656,7 @@ static bool detectFrequency(FFCPUResult* cpu, const FFCPUOptions* options) { cpu->frequencyMax = fmax; } - uint32_t fbase = getFrequency(policyFd, "base_frequency", NULL, &buffer); + uint32_t fbase = getFrequency(policyFd, "base_frequency", nullptr, &buffer); if (fbase > 0) { cpu->frequencyBase = cpu->frequencyBase > fbase ? cpu->frequencyBase : fbase; } @@ -681,7 +681,7 @@ static bool detectFrequency(FFCPUResult* cpu, const FFCPUOptions* options) { #if __i386__ || __x86_64__ -FF_A_UNUSED static uint16_t getPackageCount(FFstrbuf* cpuinfo) { +[[maybe_unused]] static uint16_t getPackageCount(FFstrbuf* cpuinfo) { const char* p = cpuinfo->chars; uint64_t low = 0, high = 0; @@ -700,7 +700,7 @@ FF_A_UNUSED static uint16_t getPackageCount(FFstrbuf* cpuinfo) { return (uint16_t) (__builtin_popcountll(low) + __builtin_popcountll(high)); } -FF_A_UNUSED static const char* detectCPUX86(const FFCPUOptions* options, FFCPUResult* cpu) { +[[maybe_unused]] static const char* detectCPUX86(const FFCPUOptions* options, FFCPUResult* cpu) { FF_STRBUF_AUTO_DESTROY cpuinfo = ffStrbufCreateA(PROC_FILE_BUFFSIZ); if (!ffReadFileBuffer(FF_CPUINFO_PATH, &cpuinfo) || cpuinfo.length == 0) { return "ffReadFileBuffer(\"" FF_CPUINFO_PATH "\") failed"; @@ -708,7 +708,7 @@ FF_A_UNUSED static const char* detectCPUX86(const FFCPUOptions* options, FFCPURe FF_STRBUF_AUTO_DESTROY physicalCoresBuffer = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY cpuMHz = ffStrbufCreate(); - const char* error = parseCpuInfo(&cpuinfo, cpu, &physicalCoresBuffer, &cpuMHz, NULL, NULL, NULL); + const char* error = parseCpuInfo(&cpuinfo, cpu, &physicalCoresBuffer, &cpuMHz, nullptr, nullptr, nullptr); if (error) { return error; } @@ -729,7 +729,7 @@ FF_A_UNUSED static const char* detectCPUX86(const FFCPUOptions* options, FFCPURe detectNumaNodes(cpu); - return NULL; + return nullptr; } #else @@ -750,7 +750,7 @@ static const char* detectPhysicalCores(FFCPUResult* cpu) { struct dirent* entry; FF_LIST_AUTO_DESTROY cpuList = ffListCreate(); - while ((entry = readdir(dir)) != NULL) { + while ((entry = readdir(dir)) != nullptr) { if (entry->d_type != DT_DIR || !ffStrStartsWith(entry->d_name, "cpu") || !ffCharIsDigit(entry->d_name[strlen("cpu")])) { continue; } @@ -768,7 +768,7 @@ static const char* detectPhysicalCores(FFCPUResult* cpu) { ssize_t len = ffReadFileDataRelative(cpuxfd, "topology/physical_package_id", sizeof(buf) - 1, buf); if (len > 0) { buf[len] = '\0'; - unsigned long long id = strtoull(buf, NULL, 10); + unsigned long long id = strtoull(buf, nullptr, 10); if (__builtin_expect(id < 128, true)) { // Do 129-socket boards exist? if (__builtin_expect(id >= 64, false)) { @@ -810,10 +810,10 @@ static const char* detectPhysicalCores(FFCPUResult* cpu) { cpu->coresPhysical = (uint16_t) cpuList.length; cpu->packages = (uint16_t) (__builtin_popcountll(pkgLow) + __builtin_popcountll(pkgHigh)); - return NULL; + return nullptr; } -FF_A_UNUSED static void parseIsa(FFstrbuf* cpuIsa) { +[[maybe_unused]] static void parseIsa(FFstrbuf* cpuIsa) { // Always use the last part of the ISA string. Ref: #590 #1204 ffStrbufSubstrAfterLastC(cpuIsa, ' '); @@ -833,7 +833,7 @@ FF_A_UNUSED static void parseIsa(FFstrbuf* cpuIsa) { } } -FF_A_UNUSED static void detectSocName(FFCPUResult* cpu) { +[[maybe_unused]] static void detectSocName(FFCPUResult* cpu) { if (cpu->name.length > 0) { return; } @@ -851,8 +851,8 @@ FF_A_UNUSED static void detectSocName(FFCPUResult* cpu) { --length; - char* vendor = NULL; - char* model = NULL; + char* vendor = nullptr; + char* model = nullptr; for (char* p; length > 0; length = p ? (ssize_t) (p - content) - 1 : 0) { p = memrchr(content, '\0', (size_t) length); @@ -899,7 +899,7 @@ FF_A_UNUSED static void detectSocName(FFCPUResult* cpu) { else if (ffStrEquals(vendor, "apple")) { // https://elixir.bootlin.com/linux/v6.11/source/arch/arm64/boot/dts/apple if (model[0] == 't') { - uint32_t deviceId = (uint32_t) strtoul(model + 1, NULL, 10); + uint32_t deviceId = (uint32_t) strtoul(model + 1, nullptr, 10); ffStrbufSetStatic(&cpu->name, ffCPUAppleCodeToName(deviceId)); if (!cpu->name.length) { @@ -922,7 +922,7 @@ FF_A_UNUSED static void detectSocName(FFCPUResult* cpu) { } } else if (ffStrStartsWith(model, "sc")) { const char* code = model + 2; - uint32_t deviceId = (uint32_t) strtoul(code, NULL, 10); + uint32_t deviceId = (uint32_t) strtoul(code, nullptr, 10); ffStrbufSetStatic(&cpu->name, ffCPUQualcommCodeToName(deviceId)); if (!cpu->name.length) { ffStrbufAppendS(&cpu->name, "Qualcomm Snapdragon SC"); @@ -953,7 +953,7 @@ FF_A_UNUSED static void detectSocName(FFCPUResult* cpu) { } #ifdef __loongarch__ -FF_A_UNUSED static uint16_t getLoongarchPropCount(FFstrbuf* cpuinfo, const char* key) { +[[maybe_unused]] static uint16_t getLoongarchPropCount(FFstrbuf* cpuinfo, const char* key) { const char* p = cpuinfo->chars; uint64_t low = 0, high = 0; uint32_t keylen = (uint32_t) strlen(key); @@ -974,7 +974,7 @@ FF_A_UNUSED static uint16_t getLoongarchPropCount(FFstrbuf* cpuinfo, const char* } #endif -FF_A_UNUSED static const char* detectCPUOthers(const FFCPUOptions* options, FFCPUResult* cpu) { +[[maybe_unused]] static const char* detectCPUOthers(const FFCPUOptions* options, FFCPUResult* cpu) { cpu->coresLogical = (uint16_t) get_nprocs_conf(); cpu->coresOnline = (uint16_t) get_nprocs(); @@ -997,7 +997,7 @@ FF_A_UNUSED static const char* detectCPUOthers(const FFCPUOptions* options, FFCP FF_STRBUF_AUTO_DESTROY cpuUarch = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY cpuImplementerStr = ffStrbufCreate(); - const char* error = parseCpuInfo(&cpuinfo, cpu, NULL, &cpuMHz, &cpuIsa, &cpuUarch, &cpuImplementerStr); + const char* error = parseCpuInfo(&cpuinfo, cpu, nullptr, &cpuMHz, &cpuIsa, &cpuUarch, &cpuImplementerStr); if (error) { return error; } @@ -1007,7 +1007,7 @@ FF_A_UNUSED static const char* detectCPUOthers(const FFCPUOptions* options, FFCP } #if __arm__ || __aarch64__ - uint32_t cpuImplementer = (uint32_t) strtoul(cpuImplementerStr.chars, NULL, 16); + uint32_t cpuImplementer = (uint32_t) strtoul(cpuImplementerStr.chars, nullptr, 16); ffStrbufSetStatic(&cpu->vendor, hwImplId2Vendor(cpuImplementer)); if (cpu->name.length == 0) { @@ -1050,7 +1050,7 @@ FF_A_UNUSED static const char* detectCPUOthers(const FFCPUOptions* options, FFCP ffCPUDetectByCpuid(cpu); detectNumaNodes(cpu); - return NULL; + return nullptr; } #endif diff --git a/src/detection/cpu/cpu_nbsd.c b/src/detection/cpu/cpu_nbsd.c index 9c88c0ece7..d5ccbf2305 100644 --- a/src/detection/cpu/cpu_nbsd.c +++ b/src/detection/cpu/cpu_nbsd.c @@ -10,8 +10,8 @@ #include static void freePropDict(prop_dictionary_t* pdict) { - assert(pdict != NULL); - if (*pdict == NULL) { + assert(pdict != nullptr); + if (*pdict == nullptr) { return; } prop_object_release(*pdict); @@ -23,7 +23,7 @@ static const char* detectCpuTemp(const FFCPUOptions* options, double* current) { return "open(_PATH_SYSMON, O_RDONLY | O_CLOEXEC) failed"; } - FF_A_CLEANUP(freePropDict) prop_dictionary_t root = NULL; + [[gnu::cleanup(freePropDict)]] prop_dictionary_t root = nullptr; if (prop_dictionary_recv_ioctl(fd, ENVSYS_GETDICTIONARY, &root) < 0) { return "prop_dictionary_recv_ioctl(ENVSYS_GETDICTIONARY) failed"; } @@ -67,18 +67,18 @@ static const char* detectCpuTemp(const FFCPUOptions* options, double* current) { *current = temp / 1e6 - 273.15; - return NULL; + return nullptr; } const char* ffDetectCPUImpl(const FFCPUOptions* options, FFCPUResult* cpu) { - if (ffSysctlGetString("machdep.cpu_brand", &cpu->name) != NULL && - ffSysctlGetString("machdep.dmi.processor-version", &cpu->name) != NULL && - ffSysctlGetString("hw.cpu0.name", &cpu->name) != NULL && - ffSysctlGetString("hw.model", &cpu->name) != NULL) { + if (ffSysctlGetString("machdep.cpu_brand", &cpu->name) != nullptr && + ffSysctlGetString("machdep.dmi.processor-version", &cpu->name) != nullptr && + ffSysctlGetString("hw.cpu0.name", &cpu->name) != nullptr && + ffSysctlGetString("hw.model", &cpu->name) != nullptr) { ffStrbufSetS(&cpu->name, "Unknown CPU"); } - if (ffSysctlGetString("machdep.dmi.processor-vendor", &cpu->vendor) == NULL) { + if (ffSysctlGetString("machdep.dmi.processor-vendor", &cpu->vendor) == nullptr) { ffStrbufTrimRightSpace(&cpu->vendor); } @@ -105,5 +105,5 @@ const char* ffDetectCPUImpl(const FFCPUOptions* options, FFCPUResult* cpu) { detectCpuTemp(options, &cpu->temperature); } - return NULL; + return nullptr; } diff --git a/src/detection/cpu/cpu_nosupport.c b/src/detection/cpu/cpu_nosupport.c index 309883db26..3b014a4cbb 100644 --- a/src/detection/cpu/cpu_nosupport.c +++ b/src/detection/cpu/cpu_nosupport.c @@ -1,5 +1,5 @@ #include "cpu.h" -const char* ffDetectCPUImpl(FF_A_UNUSED const FFCPUOptions* options, FF_A_UNUSED FFCPUResult* cpu) { +const char* ffDetectCPUImpl([[maybe_unused]] const FFCPUOptions* options, [[maybe_unused]] FFCPUResult* cpu) { return "Not supported on this platform"; } diff --git a/src/detection/cpu/cpu_obsd.c b/src/detection/cpu/cpu_obsd.c index e5b8d2fdf1..5583fe59f4 100644 --- a/src/detection/cpu/cpu_obsd.c +++ b/src/detection/cpu/cpu_obsd.c @@ -12,7 +12,7 @@ static const char* detectCPUTemp(const FFCPUOptions* options, FFCPUResult* cpu) for (mib[2] = 0; mib[2] < 1024; mib[2]++) { struct sensordev sensordev; size_t sdlen = sizeof(struct sensordev); - if (sysctl(mib, 3, &sensordev, &sdlen, NULL, 0) < 0) { + if (sysctl(mib, 3, &sensordev, &sdlen, nullptr, 0) < 0) { if (errno == ENOENT) { break; } @@ -35,7 +35,7 @@ static const char* detectCPUTemp(const FFCPUOptions* options, FFCPUResult* cpu) for (mib[4] = 0; mib[4] < sensordev.maxnumt[SENSOR_TEMP]; mib[4]++) { struct sensor sensor; size_t slen = sizeof(struct sensor); - if (sysctl(mib, 5, &sensor, &slen, NULL, 0) < 0) { + if (sysctl(mib, 5, &sensor, &slen, nullptr, 0) < 0) { if (errno != ENOENT) { return "sysctl(sensor) failed"; } @@ -46,7 +46,7 @@ static const char* detectCPUTemp(const FFCPUOptions* options, FFCPUResult* cpu) } cpu->temperature = (double) (sensor.value - 273150000) / 1E6; - return NULL; + return nullptr; } } @@ -74,5 +74,5 @@ const char* ffDetectCPUImpl(const FFCPUOptions* options, FFCPUResult* cpu) { detectCPUTemp(options, cpu); } - return NULL; + return nullptr; } diff --git a/src/detection/cpu/cpu_sunos.c b/src/detection/cpu/cpu_sunos.c index 9b1cab503d..43b92c3715 100644 --- a/src/detection/cpu/cpu_sunos.c +++ b/src/detection/cpu/cpu_sunos.c @@ -4,28 +4,28 @@ #include static const char* detectCPUTempByKstat(const FFCPUOptions* options, kstat_ctl_t* kc, FFCPUResult* cpu) { - const char* possibleModules[] = { "temperature", "cpu_temp", "acpi_thermal", NULL }; + const char* possibleModules[] = { "temperature", "cpu_temp", "acpi_thermal", nullptr }; if (options->tempSensor.length > 0) { possibleModules[0] = options->tempSensor.chars; - possibleModules[1] = NULL; + possibleModules[1] = nullptr; } - for (int i = 0; possibleModules[i] != NULL; i++) { - kstat_t* ks = kstat_lookup(kc, possibleModules[i], -1, NULL); - if (ks && kstat_read(kc, ks, NULL) >= 0) { + for (int i = 0; possibleModules[i] != nullptr; i++) { + kstat_t* ks = kstat_lookup(kc, possibleModules[i], -1, nullptr); + if (ks && kstat_read(kc, ks, nullptr) >= 0) { kstat_named_t* kn = kstat_data_lookup(ks, "temperature"); if (kn) { switch (kn->data_type) { case KSTAT_DATA_INT32: cpu->temperature = (float) kn->value.i32; - return NULL; + return nullptr; case KSTAT_DATA_UINT32: cpu->temperature = (float) kn->value.ui32; - return NULL; + return nullptr; case KSTAT_DATA_FLOAT: cpu->temperature = kn->value.f; - return NULL; + return nullptr; } } } @@ -36,17 +36,17 @@ static const char* detectCPUTempByKstat(const FFCPUOptions* options, kstat_ctl_t static const char* detectCPUTempByIpmiTool(FFCPUResult* cpu) { FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); - const char* error = ffProcessAppendStdOut(&buffer, (char* const[]) { "ipmitool", "-c", "sdr", "list", NULL }); + const char* error = ffProcessAppendStdOut(&buffer, (char* const[]) { "ipmitool", "-c", "sdr", "list", nullptr }); if (error) { return error; } - char* line = NULL; + char* line = nullptr; size_t len = 0; while (ffStrbufGetline(&line, &len, &buffer)) { if (sscanf(line, "CPU%*d Temp,%lf,degrees C,ok", &cpu->temperature) == 1) { - return NULL; + return nullptr; } } @@ -64,7 +64,7 @@ static inline uint16_t countTypeId(kstat_ctl_t* kc, const char* type) { uint64_t low = 0, high = 0; for (kstat_t* ksp = kc->kc_chain; ksp; ksp = ksp->ks_next) { if (ffStrStartsWith(ksp->ks_module, "cpu_info")) { - if (kstat_read(kc, ksp, NULL) < 0) { + if (kstat_read(kc, ksp, nullptr) < 0) { continue; } @@ -99,17 +99,17 @@ static inline uint16_t countTypeId(kstat_ctl_t* kc, const char* type) { } const char* ffDetectCPUImpl(const FFCPUOptions* options, FFCPUResult* cpu) { - FF_A_CLEANUP(kstatFreeWrap) kstat_ctl_t* kc = kstat_open(); + [[gnu::cleanup(kstatFreeWrap)]] kstat_ctl_t* kc = kstat_open(); if (!kc) { return "kstat_open() failed"; } - kstat_t* ks = kstat_lookup(kc, "cpu_info", -1, NULL); + kstat_t* ks = kstat_lookup(kc, "cpu_info", -1, nullptr); if (!ks) { return "kstat_lookup() failed"; } - if (kstat_read(kc, ks, NULL) < 0) { + if (kstat_read(kc, ks, nullptr) < 0) { return "kstat_read() failed"; } @@ -134,7 +134,7 @@ const char* ffDetectCPUImpl(const FFCPUOptions* options, FFCPUResult* cpu) { } ks = kstat_lookup(kc, "unix", -1, "system_misc"); - if (ks && kstat_read(kc, ks, NULL) >= 0) { + if (ks && kstat_read(kc, ks, nullptr) >= 0) { kstat_named_t* kn = kstat_data_lookup(ks, "ncpus"); if (kn) { cpu->coresLogical = cpu->coresOnline = (uint16_t) kn->value.ui32; @@ -145,10 +145,10 @@ const char* ffDetectCPUImpl(const FFCPUOptions* options, FFCPUResult* cpu) { cpu->coresPhysical = countTypeId(kc, "core_id"); if (options->temp) { - if (detectCPUTempByKstat(options, kc, cpu) != NULL) { + if (detectCPUTempByKstat(options, kc, cpu) != nullptr) { detectCPUTempByIpmiTool(cpu); } } - return NULL; + return nullptr; } diff --git a/src/detection/cpu/cpu_windows.c b/src/detection/cpu/cpu_windows.c index 078ba0b837..82b656e4f0 100644 --- a/src/detection/cpu/cpu_windows.c +++ b/src/detection/cpu/cpu_windows.c @@ -10,9 +10,9 @@ #include static inline void ffPerfCloseQueryHandle(HANDLE* phQuery) { - if (*phQuery != NULL) { + if (*phQuery != nullptr) { PerfCloseQueryHandle(*phQuery); - *phQuery = NULL; + *phQuery = nullptr; } } @@ -33,13 +33,13 @@ const char* detectThermalTemp(const FFCPUOptions* options, double* result) { }; if (options->tempSensor.length > 0) { - if (!NT_SUCCESS(RtlUTF8ToUnicodeN(querySpec.Name, (ULONG) sizeof(querySpec.Name), NULL, options->tempSensor.chars, (ULONG) options->tempSensor.length + 1))) { + if (!NT_SUCCESS(RtlUTF8ToUnicodeN(querySpec.Name, (ULONG) sizeof(querySpec.Name), nullptr, options->tempSensor.chars, (ULONG) options->tempSensor.length + 1))) { return "Invalid temp sensor string"; } } DWORD dataSize = 0; - if (PerfEnumerateCounterSetInstances(NULL, &querySpec.Identifier.CounterSetGuid, NULL, 0, &dataSize) != ERROR_NOT_ENOUGH_MEMORY) { + if (PerfEnumerateCounterSetInstances(nullptr, &querySpec.Identifier.CounterSetGuid, nullptr, 0, &dataSize) != ERROR_NOT_ENOUGH_MEMORY) { return "PerfEnumerateCounterSetInstances() failed"; } @@ -49,7 +49,7 @@ const char* detectThermalTemp(const FFCPUOptions* options, double* result) { { FF_AUTO_FREE PERF_INSTANCE_HEADER* const pHead = malloc(dataSize); - if (PerfEnumerateCounterSetInstances(NULL, &querySpec.Identifier.CounterSetGuid, pHead, dataSize, &dataSize) != ERROR_SUCCESS) { + if (PerfEnumerateCounterSetInstances(nullptr, &querySpec.Identifier.CounterSetGuid, pHead, dataSize, &dataSize) != ERROR_SUCCESS) { return "PerfEnumerateCounterSetInstances() failed to get instance headers"; } @@ -77,10 +77,10 @@ const char* detectThermalTemp(const FFCPUOptions* options, double* result) { } } - FF_A_CLEANUP(ffPerfCloseQueryHandle) - HANDLE hQuery = NULL; + [[gnu::cleanup(ffPerfCloseQueryHandle)]] + HANDLE hQuery = nullptr; - if (PerfOpenQueryHandle(NULL, &hQuery) != ERROR_SUCCESS) { + if (PerfOpenQueryHandle(nullptr, &hQuery) != ERROR_SUCCESS) { return "PerfOpenQueryHandle() failed"; } @@ -92,8 +92,8 @@ const char* detectThermalTemp(const FFCPUOptions* options, double* result) { return "PerfAddCounters() reports invalid identifier"; } - if (PerfQueryCounterData(hQuery, NULL, 0, &dataSize) != ERROR_NOT_ENOUGH_MEMORY) { - return "PerfQueryCounterData(NULL) failed"; + if (PerfQueryCounterData(hQuery, nullptr, 0, &dataSize) != ERROR_NOT_ENOUGH_MEMORY) { + return "PerfQueryCounterData(nullptr) failed"; } if (dataSize <= sizeof(PERF_DATA_HEADER) + sizeof(PERF_COUNTER_HEADER)) { // PERF_ERROR_RETURN, should not happen @@ -135,11 +135,11 @@ const char* detectThermalTemp(const FFCPUOptions* options, double* result) { pCounterData = (PERF_COUNTER_DATA*) ((BYTE*) pCounterData + pCounterData->dwSize); } - return NULL; + return nullptr; } // 7.5 -typedef struct FFSmbiosProcessorInfo { +typedef struct [[gnu::packed]] FFSmbiosProcessorInfo { FFSmbiosHeader Header; uint8_t SocketDesignation; // string @@ -181,7 +181,7 @@ typedef struct FFSmbiosProcessorInfo { // 3.6+ uint16_t ThreadEnabled; // varies -} FF_A_PACKED FFSmbiosProcessorInfo; +} FFSmbiosProcessorInfo; static_assert(offsetof(FFSmbiosProcessorInfo, ThreadEnabled) == 0x30, "FFSmbiosProcessorInfo: Wrong struct alignment"); @@ -213,7 +213,7 @@ static const char* detectMaxSpeedBySmbios(FFCPUResult* cpu) { cpu->frequencyMax = speed; - return NULL; + return nullptr; } static uint32_t getNumLogicalCores(const SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX* ptr) { @@ -233,12 +233,12 @@ static uint32_t getNumLogicalCores(const SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX static const char* detectNCores(const FFCPUOptions* options, FFCPUResult* cpu) { LOGICAL_PROCESSOR_RELATIONSHIP lpr = RelationAll; ULONG length = 0; - NtQuerySystemInformationEx(SystemLogicalProcessorAndGroupInformation, &lpr, sizeof(lpr), NULL, 0, &length); + NtQuerySystemInformationEx(SystemLogicalProcessorAndGroupInformation, &lpr, sizeof(lpr), nullptr, 0, &length); if (length == 0) { - return "GetLogicalProcessorInformationEx(RelationAll, NULL, &length) failed"; + return "GetLogicalProcessorInformationEx(RelationAll, nullptr, &length) failed"; } - SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX* FF_AUTO_FREE + FF_AUTO_FREE SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX* pProcessorInfo = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*) malloc(length); if (!NT_SUCCESS(NtQuerySystemInformationEx(SystemLogicalProcessorAndGroupInformation, &lpr, sizeof(lpr), pProcessorInfo, length, &length))) { @@ -276,13 +276,13 @@ static const char* detectNCores(const FFCPUOptions* options, FFCPUResult* cpu) { } } - return NULL; + return nullptr; } static const char* detectByRegistry(FFCPUResult* cpu) { - FF_AUTO_CLOSE_FD HANDLE hKey = NULL; - if (!ffRegOpenKeyForRead(HKEY_LOCAL_MACHINE, L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", &hKey, NULL)) { - return "ffRegOpenKeyForRead(HKEY_LOCAL_MACHINE, L\"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0\", &hKey, NULL) failed"; + FF_AUTO_CLOSE_FD HANDLE hKey = nullptr; + if (!ffRegOpenKeyForRead(HKEY_LOCAL_MACHINE, L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", &hKey, nullptr)) { + return "ffRegOpenKeyForRead(HKEY_LOCAL_MACHINE, L\"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0\", &hKey, nullptr) failed"; } if (ffRegReadValues(hKey, 3, (FFRegValueArg[]){ @@ -290,13 +290,13 @@ static const char* detectByRegistry(FFCPUResult* cpu) { FF_ARG(cpu->vendor, L"VendorIdentifier"), FF_ARG(cpu->frequencyBase, L"~MHz"), }, - NULL)) { + nullptr)) { ffStrbufTrimRightSpace(&cpu->vendor); } else { return "ffRegReadValues() failed for CPU registry key"; } - return NULL; + return nullptr; } const char* ffDetectCPUImpl(const FFCPUOptions* options, FFCPUResult* cpu) { @@ -317,5 +317,5 @@ const char* ffDetectCPUImpl(const FFCPUOptions* options, FFCPUResult* cpu) { detectThermalTemp(options, &cpu->temperature); } - return NULL; + return nullptr; } diff --git a/src/detection/cpu/cpu_x86.c b/src/detection/cpu/cpu_x86.c index 9deb103745..fbef527235 100644 --- a/src/detection/cpu/cpu_x86.c +++ b/src/detection/cpu/cpu_x86.c @@ -1311,7 +1311,7 @@ bool ffCPUDetectX86Specific(FFCPUResult* cpu) { int32_t xmodel = (eax >> 16) & 0xF; int32_t ext_model = model + (xmodel << 4); - const struct match_entry_t* matchtable = NULL; + const struct match_entry_t* matchtable = nullptr; uint32_t count = 0; if (ffStrbufEqualS(&cpu->vendor, "GenuineIntel")) { @@ -1327,7 +1327,7 @@ bool ffCPUDetectX86Specific(FFCPUResult* cpu) { return false; } - const FFCPUX86MatchEntry* bestEntry = NULL; + const FFCPUX86MatchEntry* bestEntry = nullptr; int32_t bestScore = -1; for (uint32_t i = 0; i < count; i++) { diff --git a/src/detection/cpucache/cpucache.h b/src/detection/cpucache/cpucache.h index 287154bbc6..20f4657875 100644 --- a/src/detection/cpucache/cpucache.h +++ b/src/detection/cpucache/cpucache.h @@ -3,7 +3,7 @@ #include "fastfetch.h" #include "modules/cpucache/option.h" -typedef enum FF_A_PACKED FFCPUCacheType { +typedef enum FFCPUCacheType: uint8_t { FF_CPU_CACHE_TYPE_UNIFIED = 0, FF_CPU_CACHE_TYPE_INSTRUCTION = 1, FF_CPU_CACHE_TYPE_DATA = 2, diff --git a/src/detection/cpucache/cpucache_apple.c b/src/detection/cpucache/cpucache_apple.c index 3d1562cef2..50aec02320 100644 --- a/src/detection/cpucache/cpucache_apple.c +++ b/src/detection/cpucache/cpucache_apple.c @@ -59,5 +59,5 @@ const char* ffDetectCPUCache(FFCPUCacheResult* result) { } } - return NULL; + return nullptr; } diff --git a/src/detection/cpucache/cpucache_linux.c b/src/detection/cpucache/cpucache_linux.c index 0657c84ae6..a551849558 100644 --- a/src/detection/cpucache/cpucache_linux.c +++ b/src/detection/cpucache/cpucache_linux.c @@ -6,7 +6,7 @@ static const char* parseCpuCacheIndex(FFstrbuf* path, FFCPUCacheResult* result, uint32_t baseLen = path->length; ffStrbufAppendS(path, "/level"); if (!ffReadFileBuffer(path->chars, buffer)) { - return "ffReadFileBuffer(\"/sys/devices/system/cpu/cpuX/cache/indexX/level\") == NULL"; + return "ffReadFileBuffer(\"/sys/devices/system/cpu/cpuX/cache/indexX/level\") == nullptr"; } uint32_t level = (uint32_t) ffStrbufToUInt(buffer, 0); @@ -17,7 +17,7 @@ static const char* parseCpuCacheIndex(FFstrbuf* path, FFCPUCacheResult* result, ffStrbufSubstrBefore(path, baseLen); ffStrbufAppendS(path, "/size"); if (!ffReadFileBuffer(path->chars, buffer)) { - return "ffReadFileBuffer(\"/sys/devices/system/cpu/cpuX/cache/indexX/size\") == NULL"; + return "ffReadFileBuffer(\"/sys/devices/system/cpu/cpuX/cache/indexX/size\") == nullptr"; } uint32_t sizeKb = (uint32_t) ffStrbufToUInt(buffer, 0); @@ -28,7 +28,7 @@ static const char* parseCpuCacheIndex(FFstrbuf* path, FFCPUCacheResult* result, ffStrbufSubstrBefore(path, baseLen); ffStrbufAppendS(path, "/type"); if (!ffReadFileBuffer(path->chars, buffer)) { - return "ffReadFileBuffer(\"/sys/devices/system/cpu/cpuX/cache/indexX/type\") == NULL"; + return "ffReadFileBuffer(\"/sys/devices/system/cpu/cpuX/cache/indexX/type\") == nullptr"; } ffStrbufTrimRightSpace(buffer); @@ -62,7 +62,7 @@ static const char* parseCpuCacheIndex(FFstrbuf* path, FFCPUCacheResult* result, ffStrbufClear(buffer); ffStrbufAppendC(buffer, '['); if (!ffAppendFileBuffer(path->chars, buffer)) { - return "ffAppendFileBuffer(\"/sys/devices/system/cpu/cpuX/cache/indexX/shared_cpu_list\") == NULL"; + return "ffAppendFileBuffer(\"/sys/devices/system/cpu/cpuX/cache/indexX/shared_cpu_list\") == nullptr"; } ffStrbufTrimRightSpace(buffer); @@ -70,11 +70,11 @@ static const char* parseCpuCacheIndex(FFstrbuf* path, FFCPUCacheResult* result, ffStrbufAppendF(buffer, "_%u_%u_%u_%u]", level, sizeKb, lineSize, cacheType); if (ffStrbufContain(added, buffer)) { - return NULL; + return nullptr; } ffStrbufAppend(added, buffer); ffCPUCacheAddItem(result, level, sizeKb * 1024, lineSize, cacheType); - return NULL; + return nullptr; } static const char* parseCpuCache(FFstrbuf* path, FFCPUCacheResult* result, FFstrbuf* buffer, FFstrbuf* added) { @@ -82,11 +82,11 @@ static const char* parseCpuCache(FFstrbuf* path, FFCPUCacheResult* result, FFstr uint32_t baseLen = path->length; FF_AUTO_CLOSE_DIR DIR* pathCacheDir = opendir(path->chars); if (!pathCacheDir) { - return "opendir(\"/sys/devices/system/cpu/cpuX/cache/\") == NULL"; + return "opendir(\"/sys/devices/system/cpu/cpuX/cache/\") == nullptr"; } struct dirent* pathCacheEntry; - while ((pathCacheEntry = readdir(pathCacheDir)) != NULL) { + while ((pathCacheEntry = readdir(pathCacheDir)) != nullptr) { if (!ffStrStartsWith(pathCacheEntry->d_name, "index") || !ffCharIsDigit(pathCacheEntry->d_name[strlen("index")])) { continue; } @@ -99,7 +99,7 @@ static const char* parseCpuCache(FFstrbuf* path, FFCPUCacheResult* result, FFstr ffStrbufSubstrBefore(path, baseLen); } - return NULL; + return nullptr; } const char* ffDetectCPUCache(FFCPUCacheResult* result) { @@ -108,14 +108,14 @@ const char* ffDetectCPUCache(FFCPUCacheResult* result) { uint32_t baseLen = path.length; FF_AUTO_CLOSE_DIR DIR* pathCpuDir = opendir(path.chars); if (!pathCpuDir) { - return "opendir(\"/sys/devices/system/cpu/\") == NULL"; + return "opendir(\"/sys/devices/system/cpu/\") == nullptr"; } FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY added = ffStrbufCreate(); struct dirent* pathCpuEntry; - while ((pathCpuEntry = readdir(pathCpuDir)) != NULL) { + while ((pathCpuEntry = readdir(pathCpuDir)) != nullptr) { if (!ffStrStartsWith(pathCpuEntry->d_name, "cpu") || !ffCharIsDigit(pathCpuEntry->d_name[strlen("cpu")])) { continue; @@ -128,5 +128,5 @@ const char* ffDetectCPUCache(FFCPUCacheResult* result) { } ffStrbufSubstrBefore(&path, baseLen); } - return NULL; + return nullptr; } diff --git a/src/detection/cpucache/cpucache_nosupport.c b/src/detection/cpucache/cpucache_nosupport.c index 51d22563cf..002e64216f 100644 --- a/src/detection/cpucache/cpucache_nosupport.c +++ b/src/detection/cpucache/cpucache_nosupport.c @@ -1,5 +1,5 @@ #include "cpucache.h" -const char* ffDetectCPUCache(FF_A_UNUSED FFCPUCacheResult* result) { +const char* ffDetectCPUCache([[maybe_unused]] FFCPUCacheResult* result) { return "Not supported on this platform"; } diff --git a/src/detection/cpucache/cpucache_shared.c b/src/detection/cpucache/cpucache_shared.c index c13e351685..58419a9632 100644 --- a/src/detection/cpucache/cpucache_shared.c +++ b/src/detection/cpucache/cpucache_shared.c @@ -2,7 +2,7 @@ #include "common/smbios.h" #include "common/strutil.h" -typedef struct FFSmbiosCacheInfo { +typedef struct [[gnu::packed]] FFSmbiosCacheInfo { FFSmbiosHeader Header; uint8_t SocketDesignation; // string @@ -21,7 +21,7 @@ typedef struct FFSmbiosCacheInfo { // 3.1+ uint32_t MaximumCacheSize2; // bit field uint32_t InstalledCacheSize2; // bit field -} FF_A_PACKED FFSmbiosCacheInfo; +} FFSmbiosCacheInfo; static_assert(offsetof(FFSmbiosCacheInfo, InstalledCacheSize2) == 0x17, "FFSmbiosCacheInfo: Wrong struct alignment"); @@ -78,5 +78,5 @@ const char* ffDetectCPUCache(FFCPUCacheResult* result) { ffCPUCacheAddItem(result, level, size, 0, type); } - return NULL; + return nullptr; } diff --git a/src/detection/cpucache/cpucache_windows.c b/src/detection/cpucache/cpucache_windows.c index b9d3815fd6..0bfc579821 100644 --- a/src/detection/cpucache/cpucache_windows.c +++ b/src/detection/cpucache/cpucache_windows.c @@ -5,12 +5,12 @@ const char* ffDetectCPUCache(FFCPUCacheResult* result) { LOGICAL_PROCESSOR_RELATIONSHIP lpr = RelationCache; DWORD length = 0; - NtQuerySystemInformationEx(SystemLogicalProcessorAndGroupInformation, &lpr, sizeof(lpr), NULL, 0, &length); + NtQuerySystemInformationEx(SystemLogicalProcessorAndGroupInformation, &lpr, sizeof(lpr), nullptr, 0, &length); if (length == 0) { - return "GetLogicalProcessorInformationEx(RelationCache, NULL, &length) failed"; + return "GetLogicalProcessorInformationEx(RelationCache, nullptr, &length) failed"; } - SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX* FF_AUTO_FREE + FF_AUTO_FREE SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX* pProcessorInfo = (SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*) malloc(length); if (!NT_SUCCESS(NtQuerySystemInformationEx(SystemLogicalProcessorAndGroupInformation, &lpr, sizeof(lpr), pProcessorInfo, length, &length))) { @@ -43,5 +43,5 @@ const char* ffDetectCPUCache(FFCPUCacheResult* result) { } } - return NULL; + return nullptr; } diff --git a/src/detection/cpuusage/cpuusage.c b/src/detection/cpuusage/cpuusage.c index a78ae7b13c..bbc005476b 100644 --- a/src/detection/cpuusage/cpuusage.c +++ b/src/detection/cpuusage/cpuusage.c @@ -18,7 +18,7 @@ void ffPrepareCPUUsage(void) { } const char* ffGetCpuUsageResult(FFCPUUsageOptions* options, FFlist* result) { - const char* error = NULL; + const char* error = nullptr; if (startTime == 0) { ffListInit(&cpuTimes1); error = ffGetCpuUsageInfo(&cpuTimes1); @@ -70,5 +70,5 @@ const char* ffGetCpuUsageResult(FFCPUUsageOptions* options, FFlist* result) { cpuTime1->totalAll = cpuTime2->totalAll; } startTime = ffTimeGetNow(); - return NULL; + return nullptr; } diff --git a/src/detection/cpuusage/cpuusage_apple.c b/src/detection/cpuusage/cpuusage_apple.c index 50a8b15b4a..bdec58aa1b 100644 --- a/src/detection/cpuusage/cpuusage_apple.c +++ b/src/detection/cpuusage/cpuusage_apple.c @@ -29,5 +29,5 @@ const char* ffGetCpuUsageInfo(FFlist* cpuTimes) { } vm_deallocate(mach_task_self(), (vm_address_t) cpuInfo, numCpuInfo * sizeof(integer_t)); - return NULL; + return nullptr; } diff --git a/src/detection/cpuusage/cpuusage_bsd.c b/src/detection/cpuusage/cpuusage_bsd.c index f690d15d43..d3c43345c2 100644 --- a/src/detection/cpuusage/cpuusage_bsd.c +++ b/src/detection/cpuusage/cpuusage_bsd.c @@ -18,12 +18,12 @@ const char* ffGetCpuUsageInfo(FFlist* cpuTimes) { #else int ctls[] = { CTL_KERN, KERN_CP_TIME }; #endif - if (sysctl(ctls, 2, NULL, &neededLength, NULL, 0) != 0) { - return "sysctl({CTL_KERN, KERN_CPTIME}, 2, NULL) failed"; + if (sysctl(ctls, 2, nullptr, &neededLength, nullptr, 0) != 0) { + return "sysctl({CTL_KERN, KERN_CPTIME}, 2, nullptr) failed"; } #else - if (sysctlbyname("kern.cp_times", NULL, &neededLength, NULL, 0) != 0) { - return "sysctlbyname(kern.cp_times, NULL) failed"; + if (sysctlbyname("kern.cp_times", nullptr, &neededLength, nullptr, 0) != 0) { + return "sysctlbyname(kern.cp_times, nullptr) failed"; } #endif @@ -33,11 +33,11 @@ const char* ffGetCpuUsageInfo(FFlist* cpuTimes) { FF_AUTO_FREE uint64_t (*cpTimes)[CPUSTATES] = malloc(neededLength); #if __OpenBSD__ || __NetBSD__ - if (sysctl(ctls, 2, cpTimes, &neededLength, NULL, 0) != 0) { - return "sysctl({CTL_KERN, KERN_CPTIME}, 2, NULL) failed"; + if (sysctl(ctls, 2, cpTimes, &neededLength, nullptr, 0) != 0) { + return "sysctl({CTL_KERN, KERN_CPTIME}, 2, nullptr) failed"; } #else - if (sysctlbyname("kern.cp_times", cpTimes, &neededLength, NULL, 0) != 0) { + if (sysctlbyname("kern.cp_times", cpTimes, &neededLength, nullptr, 0) != 0) { return "sysctlbyname(kern.cp_times, cpTime) failed"; } #endif @@ -54,5 +54,5 @@ const char* ffGetCpuUsageInfo(FFlist* cpuTimes) { }; } - return NULL; + return nullptr; } diff --git a/src/detection/cpuusage/cpuusage_haiku.c b/src/detection/cpuusage/cpuusage_haiku.c index f4d3c632d0..35fba5949e 100644 --- a/src/detection/cpuusage/cpuusage_haiku.c +++ b/src/detection/cpuusage/cpuusage_haiku.c @@ -23,5 +23,5 @@ const char* ffGetCpuUsageInfo(FFlist* cpuTimes) { info->totalAll = uptime; } - return NULL; + return nullptr; } diff --git a/src/detection/cpuusage/cpuusage_linux.c b/src/detection/cpuusage/cpuusage_linux.c index fd2f43bb8c..e4711fff9c 100644 --- a/src/detection/cpuusage/cpuusage_linux.c +++ b/src/detection/cpuusage/cpuusage_linux.c @@ -18,14 +18,14 @@ const char* ffGetCpuUsageInfo(FFlist* cpuTimes) { buf[nRead] = '\0'; // Skip first line - char* start = NULL; - if ((start = strchr(buf, '\n')) == NULL) { + char* start = nullptr; + if ((start = strchr(buf, '\n')) == nullptr) { return "skip first line failed"; } ++start; uint64_t user = 0, nice = 0, system = 0, idle = 0, iowait = 0, irq = 0, softirq = 0; - char* token = NULL; + char* token = nullptr; while ((token = strchr(start, '\n'))) { if (sscanf(start, "cpu%*d%" PRIu64 "%" PRIu64 "%" PRIu64 "%" PRIu64 "%" PRIu64 "%" PRIu64 "%" PRIu64 "%*[^\n]\n", &user, &nice, &system, &idle, &iowait, &irq, &softirq) == 7) { uint64_t inUse = user + nice + system + irq + softirq; @@ -42,5 +42,5 @@ const char* ffGetCpuUsageInfo(FFlist* cpuTimes) { start = token + 1; } - return NULL; + return nullptr; } diff --git a/src/detection/cpuusage/cpuusage_nosupport.c b/src/detection/cpuusage/cpuusage_nosupport.c index faade7b841..4b0ba7aa87 100644 --- a/src/detection/cpuusage/cpuusage_nosupport.c +++ b/src/detection/cpuusage/cpuusage_nosupport.c @@ -1,6 +1,6 @@ #include "fastfetch.h" #include "detection/cpuusage/cpuusage.h" -const char* ffGetCpuUsageInfo(FF_A_UNUSED FFlist* cpuTimes) { +const char* ffGetCpuUsageInfo([[maybe_unused]] FFlist* cpuTimes) { return "Not support on this platform"; } diff --git a/src/detection/cpuusage/cpuusage_sunos.c b/src/detection/cpuusage/cpuusage_sunos.c index 813d74d245..a10f09ed73 100644 --- a/src/detection/cpuusage/cpuusage_sunos.c +++ b/src/detection/cpuusage/cpuusage_sunos.c @@ -12,13 +12,13 @@ static inline void kstatFreeWrap(kstat_ctl_t** pkc) { } const char* ffGetCpuUsageInfo(FFlist* cpuTimes) { - FF_A_CLEANUP(kstatFreeWrap) kstat_ctl_t* kc = kstat_open(); + [[gnu::cleanup(kstatFreeWrap)]] kstat_ctl_t* kc = kstat_open(); if (!kc) { return "kstat_open() failed"; } for (int i = 0;; ++i) { - kstat_t* ks = kstat_lookup(kc, "cpu_stat", i, NULL); + kstat_t* ks = kstat_lookup(kc, "cpu_stat", i, nullptr); cpu_stat_t cs; if (!ks || kstat_read(kc, ks, &cs) < 0) { @@ -34,5 +34,5 @@ const char* ffGetCpuUsageInfo(FFlist* cpuTimes) { .totalAll = total, }; } - return NULL; + return nullptr; } diff --git a/src/detection/cpuusage/cpuusage_windows.c b/src/detection/cpuusage/cpuusage_windows.c index c23c28ac1a..a208c40f44 100644 --- a/src/detection/cpuusage/cpuusage_windows.c +++ b/src/detection/cpuusage/cpuusage_windows.c @@ -10,11 +10,11 @@ static const char* getInfoByNqsi(FFlist* cpuTimes) { ULONG size = 0; - if (NtQuerySystemInformation(SystemProcessorPerformanceInformation, NULL, 0, &size) != STATUS_INFO_LENGTH_MISMATCH) { - return "NtQuerySystemInformation(SystemProcessorPerformanceInformation, NULL) failed"; + if (NtQuerySystemInformation(SystemProcessorPerformanceInformation, nullptr, 0, &size) != STATUS_INFO_LENGTH_MISMATCH) { + return "NtQuerySystemInformation(SystemProcessorPerformanceInformation, nullptr) failed"; } - SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION* FF_AUTO_FREE pinfo = (SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION*) malloc(size); + FF_AUTO_FREE SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION* pinfo = (SYSTEM_PROCESSOR_PERFORMANCE_INFORMATION*) malloc(size); if (!NT_SUCCESS(NtQuerySystemInformation(SystemProcessorPerformanceInformation, pinfo, size, &size))) { return "NtQuerySystemInformation(SystemProcessorPerformanceInformation, size) failed"; } @@ -35,13 +35,13 @@ static const char* getInfoByNqsi(FFlist* cpuTimes) { }; } - return NULL; + return nullptr; } static const char* getInfoByPerflib(FFlist* cpuTimes) { - static HANDLE hQuery = NULL; + static HANDLE hQuery = nullptr; - if (hQuery == NULL) { + if (hQuery == nullptr) { struct FFPerfQuerySpec { PERF_COUNTER_IDENTIFIER Identifier; WCHAR Name[16]; @@ -57,7 +57,7 @@ static const char* getInfoByPerflib(FFlist* cpuTimes) { .Name = PERF_WILDCARD_INSTANCE, }; - if (PerfOpenQueryHandle(NULL, &hQuery) != ERROR_SUCCESS) { + if (PerfOpenQueryHandle(nullptr, &hQuery) != ERROR_SUCCESS) { PerfCloseQueryHandle(hQuery); hQuery = INVALID_HANDLE_VALUE; return "PerfOpenQueryHandle() failed"; @@ -81,8 +81,8 @@ static const char* getInfoByPerflib(FFlist* cpuTimes) { } DWORD dataSize = 0; - if (PerfQueryCounterData(hQuery, NULL, 0, &dataSize) != ERROR_NOT_ENOUGH_MEMORY) { - return "PerfQueryCounterData(NULL) failed"; + if (PerfQueryCounterData(hQuery, nullptr, 0, &dataSize) != ERROR_NOT_ENOUGH_MEMORY) { + return "PerfQueryCounterData(nullptr) failed"; } if (dataSize <= sizeof(PERF_DATA_HEADER) + sizeof(PERF_COUNTER_HEADER)) { @@ -133,7 +133,7 @@ static const char* getInfoByPerflib(FFlist* cpuTimes) { pCounterData = (PERF_COUNTER_DATA*) ((BYTE*) pCounterData + pCounterData->dwSize); } - if (wcschr(instanceName, L'_') == NULL /* ignore `_Total` */) { + if (wcschr(instanceName, L'_') == nullptr /* ignore `_Total` */) { if (processorUtility == UINT64_MAX) { return "Counter \"% Processor Utility\" are not supported"; } @@ -148,17 +148,17 @@ static const char* getInfoByPerflib(FFlist* cpuTimes) { pInstanceHeader = (PERF_INSTANCE_HEADER*) pCounterData; } - return NULL; + return nullptr; } const char* ffGetCpuUsageInfo(FFlist* cpuTimes) { - const char* error = NULL; + const char* error = nullptr; if (ffIsWindows10OrGreater()) { error = getInfoByPerflib(cpuTimes); FF_DEBUG("Get CPU usage info by Perflib: %s", error ?: "success"); if (!error) { - return NULL; + return nullptr; } ffListClear(cpuTimes); } diff --git a/src/detection/cursor/cursor_nosupport.c b/src/detection/cursor/cursor_nosupport.c index 6413d92d31..123beacb0b 100644 --- a/src/detection/cursor/cursor_nosupport.c +++ b/src/detection/cursor/cursor_nosupport.c @@ -1,5 +1,5 @@ #include "cursor.h" -void ffDetectCursor(FF_A_UNUSED FFCursorResult* result) { +void ffDetectCursor([[maybe_unused]] FFCursorResult* result) { ffStrbufInitS(&result->error, "Not supported on this platform"); } diff --git a/src/detection/cursor/cursor_windows.c b/src/detection/cursor/cursor_windows.c index a6814ecc22..12f8d6a2eb 100644 --- a/src/detection/cursor/cursor_windows.c +++ b/src/detection/cursor/cursor_windows.c @@ -4,11 +4,11 @@ #include "common/windows/registry.h" void ffDetectCursor(FFCursorResult* result) { - FF_AUTO_CLOSE_FD HANDLE hKey = NULL; + FF_AUTO_CLOSE_FD HANDLE hKey = nullptr; if (ffRegOpenKeyForRead(HKEY_CURRENT_USER, L"Control Panel\\Cursors", &hKey, &result->error)) { - if (ffRegReadStrbuf(hKey, NULL, &result->theme, &result->error)) { + if (ffRegReadStrbuf(hKey, nullptr, &result->theme, &result->error)) { uint32_t cursorBaseSize; - if (ffRegReadUint(hKey, L"CursorBaseSize", &cursorBaseSize, NULL)) { + if (ffRegReadUint(hKey, L"CursorBaseSize", &cursorBaseSize, nullptr)) { // Not available on Windows 8.1 ffStrbufAppendUInt(&result->size, cursorBaseSize); }; diff --git a/src/detection/de/de_linux.c b/src/detection/de/de_linux.c index de7a220c63..e79c3f4183 100644 --- a/src/detection/de/de_linux.c +++ b/src/detection/de/de_linux.c @@ -22,7 +22,7 @@ #define _PATH_LOCALBASE "/usr/pkg" #endif -static void getKDE(FFstrbuf* result, FF_A_UNUSED FFDEOptions* options) { +static void getKDE(FFstrbuf* result, [[maybe_unused]] FFDEOptions* options) { #ifdef _PATH_LOCALBASE ffParsePropFile(_PATH_LOCALBASE "/share/wayland-sessions/plasma.desktop", "X-KDE-PluginInfo-Version =", result); if (result->length == 0) { @@ -50,37 +50,37 @@ static void getKDE(FFstrbuf* result, FF_A_UNUSED FFDEOptions* options) { } if (result->length == 0) { - if (ffProcessAppendStdOut(result, (char* const[]) { "plasmashell", "--version", NULL }) == NULL) { // plasmashell 5.27.5 + if (ffProcessAppendStdOut(result, (char* const[]) { "plasmashell", "--version", nullptr }) == nullptr) { // plasmashell 5.27.5 ffStrbufSubstrAfterLastC(result, ' '); } } } -static const char* getGnomeByDbus(FF_A_UNUSED FFstrbuf* result) { +static const char* getGnomeByDbus([[maybe_unused]] FFstrbuf* result) { #ifdef FF_HAVE_DBUS FF_DBUS_AUTO_DESTROY_DATA FFDBusData dbus = {}; - if (ffDBusLoadData(DBUS_BUS_SESSION, &dbus) != NULL) { + if (ffDBusLoadData(DBUS_BUS_SESSION, &dbus) != nullptr) { return "ffDBusLoadData() failed"; } ffDBusGetPropertyString(&dbus, "org.gnome.Shell", "/org/gnome/Shell", "org.gnome.Shell", "ShellVersion", result); - return NULL; + return nullptr; #else // FF_HAVE_DBUS return "ffDBusLoadData() failed: dbus support not compiled in"; #endif // FF_HAVE_DBUS } -static void getGnome(FFstrbuf* result, FF_A_UNUSED FFDEOptions* options) { +static void getGnome(FFstrbuf* result, [[maybe_unused]] FFDEOptions* options) { getGnomeByDbus(result); if (result->length == 0) { - if (ffProcessAppendStdOut(result, (char* const[]) { "gnome-shell", "--version", NULL }) == NULL) { // GNOME Shell 44.1 + if (ffProcessAppendStdOut(result, (char* const[]) { "gnome-shell", "--version", nullptr }) == nullptr) { // GNOME Shell 44.1 ffStrbufSubstrAfterLastC(result, ' '); } } } -static void getCinnamon(FFstrbuf* result, FF_A_UNUSED FFDEOptions* options) { +static void getCinnamon(FFstrbuf* result, [[maybe_unused]] FFDEOptions* options) { ffStrbufSetS(result, getenv("CINNAMON_VERSION")); if (result->length == 0) { @@ -88,13 +88,13 @@ static void getCinnamon(FFstrbuf* result, FF_A_UNUSED FFDEOptions* options) { } if (result->length == 0) { - if (ffProcessAppendStdOut(result, (char* const[]) { "cinnamon", "--version", NULL }) == NULL) { // Cinnamon 6.2.2 + if (ffProcessAppendStdOut(result, (char* const[]) { "cinnamon", "--version", nullptr }) == nullptr) { // Cinnamon 6.2.2 ffStrbufSubstrAfterLastC(result, ' '); } } } -static void getMate(FFstrbuf* result, FF_A_UNUSED FFDEOptions* options) { +static void getMate(FFstrbuf* result, [[maybe_unused]] FFDEOptions* options) { FF_STRBUF_AUTO_DESTROY major = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY minor = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY micro = ffStrbufCreate(); @@ -104,7 +104,7 @@ static void getMate(FFstrbuf* result, FF_A_UNUSED FFDEOptions* options) { ffParseSemver(result, &major, &minor, µ); if (result->length == 0) { - ffProcessAppendStdOut(result, (char* const[]) { "mate-session", "--version", NULL }); + ffProcessAppendStdOut(result, (char* const[]) { "mate-session", "--version", nullptr }); ffStrbufSubstrAfterFirstC(result, ' '); ffStrbufTrim(result, ' '); @@ -117,19 +117,19 @@ static const char* getXfce4ByLib(FFstrbuf* result) { FF_LIBRARY_LOAD_MESSAGE(xfce4util, "libxfce4util" FF_LIBRARY_EXTENSION, 7); FF_LIBRARY_LOAD_SYMBOL_MESSAGE(xfce4util, xfce_version_string); ffStrbufSetS(result, ffxfce_version_string()); - return NULL; + return nullptr; #else FF_UNUSED(result); return "dlopen is disabled"; #endif } -static void getXFCE4(FFstrbuf* result, FF_A_UNUSED FFDEOptions* options) { +static void getXFCE4(FFstrbuf* result, [[maybe_unused]] FFDEOptions* options) { getXfce4ByLib(result); if (result->length == 0) { // This is somewhat slow - ffProcessAppendStdOut(result, (char* const[]) { "xfce4-session", "--version", NULL }); + ffProcessAppendStdOut(result, (char* const[]) { "xfce4-session", "--version", nullptr }); ffStrbufSubstrBeforeFirstC(result, ')'); ffStrbufSubstrAfterLastC(result, ' '); @@ -137,7 +137,7 @@ static void getXFCE4(FFstrbuf* result, FF_A_UNUSED FFDEOptions* options) { } } -static void getLXQt(FFstrbuf* result, FF_A_UNUSED FFDEOptions* options) { +static void getLXQt(FFstrbuf* result, [[maybe_unused]] FFDEOptions* options) { ffParsePropFileData("gconfig/lxqt.pc", "Version:", result); if (result->length == 0) { @@ -149,18 +149,18 @@ static void getLXQt(FFstrbuf* result, FF_A_UNUSED FFDEOptions* options) { if (result->length == 0) { // This is really, really, really slow. Thank you, LXQt developers - ffProcessAppendStdOut(result, (char* const[]) { "lxqt-session", "-v", NULL }); + ffProcessAppendStdOut(result, (char* const[]) { "lxqt-session", "-v", nullptr }); result->length = 0; // don't set '\0' byte ffParsePropLines(result->chars, "liblxqt", result); } } -static void getBudgie(FFstrbuf* result, FF_A_UNUSED FFDEOptions* options) { +static void getBudgie(FFstrbuf* result, [[maybe_unused]] FFDEOptions* options) { ffParsePropFileData("budgie/budgie-version.xml", "", result); } -static void getUnity(FFstrbuf* result, FF_A_UNUSED FFDEOptions* options) { +static void getUnity(FFstrbuf* result, [[maybe_unused]] FFDEOptions* options) { if (ffParsePropFile("/usr/bin/unity", "parser = OptionParser(version= \"%prog ", result)) { ffStrbufSubstrBeforeFirstC(result, '"'); } @@ -177,7 +177,7 @@ static bool extractTdeVersion(const char* line, uint32_t len, void* userdata) { return false; } -static const char* getTrinity(FFstrbuf* result, FF_A_UNUSED FFDEOptions* options) { +static const char* getTrinity(FFstrbuf* result, [[maybe_unused]] FFDEOptions* options) { FF_STRBUF_AUTO_DESTROY path = ffStrbufCreate(); const char* error = ffFindExecutableInPath("tde-config", &path); if (error) { @@ -187,38 +187,38 @@ static const char* getTrinity(FFstrbuf* result, FF_A_UNUSED FFDEOptions* options ffStrbufSubstrBeforeLastC(&path, '/'); ffStrbufAppendS(&path, "/../lib/libtdecore.so"); - if (ffBinaryExtractStrings(path.chars, extractTdeVersion, result, strlen("R0.0.0")) == NULL) { - return NULL; + if (ffBinaryExtractStrings(path.chars, extractTdeVersion, result, strlen("R0.0.0")) == nullptr) { + return nullptr; } ffStrbufClear(&path); - if (ffProcessAppendStdOut(&path, (char* const[]) { "tde-config", "--version", NULL }) == NULL) { + if (ffProcessAppendStdOut(&path, (char* const[]) { "tde-config", "--version", nullptr }) == nullptr) { ffParsePropLines(path.chars, "TDE: ", result); - return NULL; + return nullptr; } return "All methods failed"; } -static const char* getCosmic(FFstrbuf* result, FF_A_UNUSED FFDEOptions* options) { - if (ffProcessAppendStdOut(result, (char* const[]) { "cosmic-comp", "--version", NULL }) == NULL) { +static const char* getCosmic(FFstrbuf* result, [[maybe_unused]] FFDEOptions* options) { + if (ffProcessAppendStdOut(result, (char* const[]) { "cosmic-comp", "--version", nullptr }) == nullptr) { // cosmic-comp 0.1.0 (git commit fa88002ba41d2edec25dd7ffdee9719fbb928fc0) ffStrbufSubstrAfterFirstC(result, ' '); ffStrbufSubstrBeforeFirstC(result, ' '); - return NULL; + return nullptr; } return "All methods failed"; } -static const char* getEnlightenmentByDbus(FF_A_UNUSED FFstrbuf* result) { +static const char* getEnlightenmentByDbus([[maybe_unused]] FFstrbuf* result) { #ifdef FF_HAVE_DBUS FF_DBUS_AUTO_DESTROY_DATA FFDBusData dbus = {}; - if (ffDBusLoadData(DBUS_BUS_SESSION, &dbus) != NULL) { + if (ffDBusLoadData(DBUS_BUS_SESSION, &dbus) != nullptr) { return "ffDBusLoadData() failed"; } - DBusMessage* reply = ffDBusGetMethodReply(&dbus, "org.enlightenment.wm.service", "/org/enlightenment/wm/RemoteObject", "org.enlightenment.wm.Core", "Version", NULL, NULL); + DBusMessage* reply = ffDBusGetMethodReply(&dbus, "org.enlightenment.wm.service", "/org/enlightenment/wm/RemoteObject", "org.enlightenment.wm.Core", "Version", nullptr, nullptr); if (!reply) { return "ffDBusGetMethodReply() failed"; } @@ -234,17 +234,17 @@ static const char* getEnlightenmentByDbus(FF_A_UNUSED FFstrbuf* result) { } dbus.lib->ffdbus_message_unref(reply); - return NULL; + return nullptr; #else // FF_HAVE_DBUS return "ffDBusLoadData() failed: dbus support not compiled in"; #endif // FF_HAVE_DBUS } -static void getEnlightenment(FFstrbuf* result, FF_A_UNUSED FFDEOptions* options) { +static void getEnlightenment(FFstrbuf* result, [[maybe_unused]] FFDEOptions* options) { getEnlightenmentByDbus(result); if (result->length == 0) { - if (ffProcessAppendStdOut(result, (char* const[]) { "enlightenment", "--version", NULL }) == NULL) { // ...\nVersion: 0.27.1\n... + if (ffProcessAppendStdOut(result, (char* const[]) { "enlightenment", "--version", nullptr }) == nullptr) { // ...\nVersion: 0.27.1\n... ffStrbufSubstrAfterFirstS(result, "Version: "); ffStrbufSubstrBeforeFirstC(result, '\n'); } @@ -280,5 +280,5 @@ const char* ffDetectDEVersion(const FFstrbuf* deName, FFstrbuf* result, FFDEOpti } else { return "Unsupported DE"; } - return NULL; + return nullptr; } diff --git a/src/detection/de/de_nosupport.c b/src/detection/de/de_nosupport.c index d870ae0335..d9262c4f15 100644 --- a/src/detection/de/de_nosupport.c +++ b/src/detection/de/de_nosupport.c @@ -1,5 +1,5 @@ #include "de.h" -const char* ffDetectDEVersion(FF_A_UNUSED const FFstrbuf* deName, FF_A_UNUSED FFstrbuf* result, FF_A_UNUSED FFDEOptions* options) { +const char* ffDetectDEVersion([[maybe_unused]] const FFstrbuf* deName, [[maybe_unused]] FFstrbuf* result, [[maybe_unused]] FFDEOptions* options) { return "Not supported on this platform"; } diff --git a/src/detection/disk/disk.c b/src/detection/disk/disk.c index c86282d63f..b1ad006bd4 100644 --- a/src/detection/disk/disk.c +++ b/src/detection/disk/disk.c @@ -11,7 +11,7 @@ const char* ffDetectDisks(FFDiskOptions* options, FFlist* disks) { return error; } if (disks->length == 0) { - return NULL; + return nullptr; } // We need to sort the disks, so that we can detect, which disk a path resides on @@ -27,7 +27,7 @@ const char* ffDetectDisks(FFDiskOptions* options, FFlist* disks) { } } - return NULL; + return nullptr; } #ifndef _WIN32 diff --git a/src/detection/disk/disk_bsd.c b/src/detection/disk/disk_bsd.c index 9156d79efd..aaa69b294a 100644 --- a/src/detection/disk/disk_bsd.c +++ b/src/detection/disk/disk_bsd.c @@ -51,10 +51,10 @@ static const char* detectFsLabel(struct statfs* fs, FFDisk* disk) { ffStrbufSetS(&disk->name, str ? str + 1 : provider->lg_name); } - return NULL; + return nullptr; } #else -static const char* detectFsLabel(FF_A_UNUSED struct statfs* fs, FF_A_UNUSED FFDisk* disk) { +static const char* detectFsLabel([[maybe_unused]] struct statfs* fs, [[maybe_unused]] FFDisk* disk) { return "Fastfetch was compiled without libgeom support"; } #endif @@ -84,11 +84,11 @@ static void detectFsInfo(struct statfs* fs, FFDisk* disk) { #define MNT_REMOVABLE 0x00000200 #endif -struct CmnAttrBuf { +struct [[gnu::packed]] CmnAttrBuf { uint32_t length; attrreference_t nameRef; char nameSpace[NAME_MAX * 3 + 1]; -} FF_A_PACKED; +}; void detectFsInfo(struct statfs* fs, FFDisk* disk) { if (fs->f_flags & MNT_DONTBROWSE) { @@ -127,14 +127,14 @@ static void detectFsInfo(struct statfs* fs, FFDisk* disk) { const char* ffDetectDisksImpl(FFDiskOptions* options, FFlist* disks) { #ifndef __NetBSD__ - int size = getfsstat(NULL, 0, MNT_WAIT); + int size = getfsstat(nullptr, 0, MNT_WAIT); if (size <= 0) { - return "getfsstat(NULL, 0, MNT_WAIT) failed"; + return "getfsstat(nullptr, 0, MNT_WAIT) failed"; } #else - int size = getvfsstat(NULL, 0, ST_WAIT); + int size = getvfsstat(nullptr, 0, ST_WAIT); if (size <= 0) { - return "getvfsstat(NULL, 0, ST_WAIT) failed"; + return "getvfsstat(nullptr, 0, ST_WAIT) failed"; } #endif @@ -210,5 +210,5 @@ const char* ffDetectDisksImpl(FFDiskOptions* options, FFlist* disks) { #endif } - return NULL; + return nullptr; } diff --git a/src/detection/disk/disk_haiku.cpp b/src/detection/disk/disk_haiku.cpp index 0987897101..bce8932d6b 100644 --- a/src/detection/disk/disk_haiku.cpp +++ b/src/detection/disk/disk_haiku.cpp @@ -70,5 +70,5 @@ const char* ffDetectDisksImpl(FFDiskOptions* options, FFlist* disks) { disk->createTime = (uint64_t) crTime * 1000; } } - return NULL; + return nullptr; } diff --git a/src/detection/disk/disk_linux.c b/src/detection/disk/disk_linux.c index 720531731f..bb1a695124 100644 --- a/src/detection/disk/disk_linux.c +++ b/src/detection/disk/disk_linux.c @@ -107,14 +107,14 @@ static bool isPhysicalDevice(const struct mntent* device) { static void detectNameFromPath(FFDisk* disk, const struct stat* deviceStat, FFstrbuf* basePath) { FF_AUTO_CLOSE_DIR DIR* dir = opendir(basePath->chars); - if (dir == NULL) { + if (dir == nullptr) { return; } uint32_t basePathLength = basePath->length; struct dirent* entry; - while ((entry = readdir(dir)) != NULL) { + while ((entry = readdir(dir)) != nullptr) { if (entry->d_name[0] == '.') { continue; } @@ -162,7 +162,7 @@ static void detectName(FFDisk* disk) { #ifdef __ANDROID__ -static void detectType(FF_A_UNUSED const FFlist* disks, FFDisk* currentDisk, FF_A_UNUSED struct mntent* device) { +static void detectType([[maybe_unused]] const FFlist* disks, FFDisk* currentDisk, [[maybe_unused]] struct mntent* device) { if (ffStrbufEqualS(¤tDisk->mountpoint, "/") || ffStrbufEqualS(¤tDisk->mountpoint, "/storage/emulated")) { currentDisk->type = FF_DISK_VOLUME_TYPE_REGULAR_BIT; } else if (ffStrbufStartsWithS(¤tDisk->mountpoint, "/mnt/media_rw/")) { @@ -218,11 +218,11 @@ static bool isRemovable(FFDisk* currentDisk) { snprintf(sysBlockPartition, ARRAY_SIZE(sysBlockPartition), "/sys/class/block/%s", currentDisk->mountFrom.chars + strlen("/dev/")); char sysBlockVolume[PATH_MAX]; // /sys/devices/pci0000:00/0000:00:14.0/usb4/4-3/4-3:1.0/host0/target0:0:0/0:0:0:0/block/sda/sda1 - if (realpath(sysBlockPartition, sysBlockVolume) == NULL) { + if (realpath(sysBlockPartition, sysBlockVolume) == nullptr) { return false; } char* lastSlash = strrchr(sysBlockVolume, '/'); - if (lastSlash == NULL) { + if (lastSlash == nullptr) { return false; } strcpy(lastSlash + 1, "removable"); @@ -284,8 +284,8 @@ static void detectStats(FFDisk* disk) { const char* ffDetectDisksImpl(FFDiskOptions* options, FFlist* disks) { FILE* mountsFile = setmntent("/proc/mounts", "r"); - if (mountsFile == NULL) { - return "setmntent(\"/proc/mounts\", \"r\") == NULL"; + if (mountsFile == nullptr) { + return "setmntent(\"/proc/mounts\", \"r\") == nullptr"; } struct mntent* device; @@ -333,5 +333,5 @@ const char* ffDetectDisksImpl(FFDiskOptions* options, FFlist* disks) { endmntent(mountsFile); - return NULL; + return nullptr; } diff --git a/src/detection/disk/disk_nosupport.c b/src/detection/disk/disk_nosupport.c index eabddbc885..0623336dcd 100644 --- a/src/detection/disk/disk_nosupport.c +++ b/src/detection/disk/disk_nosupport.c @@ -1,5 +1,5 @@ #include "disk.h" -const char* ffDetectDisksImpl(FF_A_UNUSED FFDiskOptions* options, FF_A_UNUSED FFlist* disks) { +const char* ffDetectDisksImpl([[maybe_unused]] FFDiskOptions* options, [[maybe_unused]] FFlist* disks) { return "Not supported on this platform"; } diff --git a/src/detection/disk/disk_sunos.c b/src/detection/disk/disk_sunos.c index 3d811e03e4..85087fe7bb 100644 --- a/src/detection/disk/disk_sunos.c +++ b/src/detection/disk/disk_sunos.c @@ -107,8 +107,8 @@ static void detectStats(FFDisk* disk) { const char* ffDetectDisksImpl(FFDiskOptions* options, FFlist* disks) { FF_AUTO_CLOSE_FILE FILE* mountsFile = fopen(MNTTAB, "r"); - if (mountsFile == NULL) { - return "fopen(\"" MNTTAB "\", \"r\") == NULL"; + if (mountsFile == nullptr) { + return "fopen(\"" MNTTAB "\", \"r\") == nullptr"; } struct mnttab device; @@ -141,5 +141,5 @@ const char* ffDetectDisksImpl(FFDiskOptions* options, FFlist* disks) { detectStats(disk); } - return NULL; + return nullptr; } diff --git a/src/detection/disk/disk_windows.c b/src/detection/disk/disk_windows.c index 0b3c93d3e9..c5093fed2f 100644 --- a/src/detection/disk/disk_windows.c +++ b/src/detection/disk/disk_windows.c @@ -46,7 +46,7 @@ const char* ffDetectDisksImpl(FFDiskOptions* options, FFlist* disks) { continue; } - FF_AUTO_CLOSE_FD HANDLE handle = CreateFileW(mountpointW, FILE_READ_ATTRIBUTES, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); + FF_AUTO_CLOSE_FD HANDLE handle = CreateFileW(mountpointW, FILE_READ_ATTRIBUTES, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, nullptr); if (handle == INVALID_HANDLE_VALUE) { continue; } @@ -56,7 +56,7 @@ const char* ffDetectDisksImpl(FFDiskOptions* options, FFlist* disks) { alignas(FILE_FS_ATTRIBUTE_INFORMATION) uint8_t bufFsAttr[1024]; FILE_FS_ATTRIBUTE_INFORMATION* fsAttr = NT_SUCCESS(NtQueryVolumeInformationFile(handle, &iosb, bufFsAttr, sizeof(bufFsAttr), FileFsAttributeInformation)) ? (FILE_FS_ATTRIBUTE_INFORMATION*) bufFsAttr - : NULL; + : nullptr; FF_STRBUF_AUTO_DESTROY diskFileSystemBuf = ffStrbufCreate(); if (fsAttr) { @@ -97,7 +97,7 @@ const char* ffDetectDisksImpl(FFDiskOptions* options, FFlist* disks) { alignas(FILE_FS_VOLUME_INFORMATION) uint8_t bufFsVolume[1024]; FILE_FS_VOLUME_INFORMATION* fsVolume = NT_SUCCESS(NtQueryVolumeInformationFile(handle, &iosb, bufFsVolume, sizeof(bufFsVolume), FileFsVolumeInformation)) ? (FILE_FS_VOLUME_INFORMATION*) bufFsVolume - : NULL; + : nullptr; if (fsVolume) { if (fsVolume->VolumeLabelLength > 0) { @@ -124,5 +124,5 @@ const char* ffDetectDisksImpl(FFDiskOptions* options, FFlist* disks) { } } - return NULL; + return nullptr; } diff --git a/src/detection/diskio/diskio.c b/src/detection/diskio/diskio.c index 6ff66be446..73f0075a75 100644 --- a/src/detection/diskio/diskio.c +++ b/src/detection/diskio/diskio.c @@ -22,14 +22,14 @@ void ffPrepareDiskIO(FFDiskIOOptions* options) { } const char* ffDetectDiskIO(FFlist* result, FFDiskIOOptions* options) { - const char* error = NULL; + const char* error = nullptr; if (options->detectTotal) { error = ffDiskIOGetIoCounters(result, options); if (error) { return error; } - return NULL; + return nullptr; } if (time1 == 0) { @@ -84,5 +84,5 @@ const char* ffDetectDiskIO(FFlist* result, FFDiskIOOptions* options) { time1 = time2; // Leak ioCounters1 here - return NULL; + return nullptr; } diff --git a/src/detection/diskio/diskio_apple.c b/src/detection/diskio/diskio_apple.c index dc2890701f..c389cb2c4d 100644 --- a/src/detection/diskio/diskio_apple.c +++ b/src/detection/diskio/diskio_apple.c @@ -53,5 +53,5 @@ const char* ffDiskIOGetIoCounters(FFlist* result, FFDiskIOOptions* options) { } } - return NULL; + return nullptr; } diff --git a/src/detection/diskio/diskio_bsd.c b/src/detection/diskio/diskio_bsd.c index f5eb4b8b84..495d1a95a7 100644 --- a/src/detection/diskio/diskio_bsd.c +++ b/src/detection/diskio/diskio_bsd.c @@ -12,7 +12,7 @@ #include const char* ffDiskIOGetIoCounters(FFlist* result, FFDiskIOOptions* options) { - FF_A_CLEANUP(geom_deletetree) struct gmesh geomTree = {}; + [[gnu::cleanup(geom_deletetree)]] struct gmesh geomTree = {}; if (geom_gettree(&geomTree) < 0) { return "geom_gettree() failed"; } @@ -27,12 +27,12 @@ const char* ffDiskIOGetIoCounters(FFlist* result, FFDiskIOOptions* options) { } struct devstat* snapIter; - while ((snapIter = geom_stats_snapshot_next(snap)) != NULL) { + while ((snapIter = geom_stats_snapshot_next(snap)) != nullptr) { if (snapIter->device_type & DEVSTAT_TYPE_PASS) { continue; } struct gident* geomId = geom_lookupid(&geomTree, snapIter->id); - if (geomId == NULL) { + if (geomId == nullptr) { continue; } if (geomId->lg_what != ISPROVIDER) { @@ -69,7 +69,7 @@ const char* ffDiskIOGetIoCounters(FFlist* result, FFDiskIOOptions* options) { geom_stats_snapshot_free(snap); geom_stats_close(); - return NULL; + return nullptr; } #else @@ -114,7 +114,7 @@ const char* ffDiskIOGetIoCounters(FFlist* result, FFDiskIOOptions* options) { free(stats.dinfo->mem_ptr); free(stats.dinfo); - return NULL; + return nullptr; } #endif diff --git a/src/detection/diskio/diskio_linux.c b/src/detection/diskio/diskio_linux.c index c7ddc55ea3..327e75b6d2 100644 --- a/src/detection/diskio/diskio_linux.c +++ b/src/detection/diskio/diskio_linux.c @@ -72,17 +72,17 @@ static const char* parseDiskIOCounters(int dfd, const char* devName, FFlist* res device->readCount = nRead; device->writeCount = nWritten; - return NULL; + return nullptr; } const char* ffDiskIOGetIoCounters(FFlist* result, FFDiskIOOptions* options) { FF_AUTO_CLOSE_DIR DIR* sysBlockDirp = opendir("/sys/block/"); - if (sysBlockDirp == NULL) { - return "opendir(\"/sys/block/\") == NULL"; + if (sysBlockDirp == nullptr) { + return "opendir(\"/sys/block/\") == nullptr"; } struct dirent* sysBlockEntry; - while ((sysBlockEntry = readdir(sysBlockDirp)) != NULL) { + while ((sysBlockEntry = readdir(sysBlockDirp)) != nullptr) { const char* const devName = sysBlockEntry->d_name; if (devName[0] == '.') { @@ -95,5 +95,5 @@ const char* ffDiskIOGetIoCounters(FFlist* result, FFDiskIOOptions* options) { } } - return NULL; + return nullptr; } diff --git a/src/detection/diskio/diskio_nbsd.c b/src/detection/diskio/diskio_nbsd.c index 9ca9578a8e..c8835bf065 100644 --- a/src/detection/diskio/diskio_nbsd.c +++ b/src/detection/diskio/diskio_nbsd.c @@ -9,14 +9,14 @@ const char* ffDiskIOGetIoCounters(FFlist* result, FFDiskIOOptions* options) { int mib[] = { CTL_HW, HW_IOSTATS, sizeof(struct io_sysctl) }; size_t len; - if (sysctl(mib, ARRAY_SIZE(mib), NULL, &len, NULL, 0) < 0) { - return "sysctl({HW_IOSTATS}, NULL) failed"; + if (sysctl(mib, ARRAY_SIZE(mib), nullptr, &len, nullptr, 0) < 0) { + return "sysctl({HW_IOSTATS}, nullptr) failed"; } uint32_t nDrive = (uint32_t) (len / sizeof(struct io_sysctl)); FF_AUTO_FREE struct io_sysctl* stats = malloc(len); - if (sysctl(mib, ARRAY_SIZE(mib), stats, &len, NULL, 0) < 0) { + if (sysctl(mib, ARRAY_SIZE(mib), stats, &len, nullptr, 0) < 0) { return "sysctl({HW_IOSTATS}, stats) failed"; } @@ -46,5 +46,5 @@ const char* ffDiskIOGetIoCounters(FFlist* result, FFDiskIOOptions* options) { device->writeCount = st->wxfer; } - return NULL; + return nullptr; } diff --git a/src/detection/diskio/diskio_nosupport.c b/src/detection/diskio/diskio_nosupport.c index f5de15d087..8711e342e4 100644 --- a/src/detection/diskio/diskio_nosupport.c +++ b/src/detection/diskio/diskio_nosupport.c @@ -1,5 +1,5 @@ #include "diskio.h" -const char* ffDiskIOGetIoCounters(FF_A_UNUSED FFlist* result, FF_A_UNUSED FFDiskIOOptions* options) { +const char* ffDiskIOGetIoCounters([[maybe_unused]] FFlist* result, [[maybe_unused]] FFDiskIOOptions* options) { return "Not supported on this platform"; } diff --git a/src/detection/diskio/diskio_obsd.c b/src/detection/diskio/diskio_obsd.c index 8dbc67ebde..c367dcb988 100644 --- a/src/detection/diskio/diskio_obsd.c +++ b/src/detection/diskio/diskio_obsd.c @@ -8,14 +8,14 @@ const char* ffDiskIOGetIoCounters(FFlist* result, FFDiskIOOptions* options) { int mib[] = { CTL_HW, HW_DISKSTATS }; size_t len; - if (sysctl(mib, ARRAY_SIZE(mib), NULL, &len, NULL, 0) < 0) { - return "sysctl({HW_DISKSTATS}, NULL) failed"; + if (sysctl(mib, ARRAY_SIZE(mib), nullptr, &len, nullptr, 0) < 0) { + return "sysctl({HW_DISKSTATS}, nullptr) failed"; } uint32_t nDrive = (uint32_t) (len / sizeof(struct diskstats)); FF_AUTO_FREE struct diskstats* stats = malloc(len); - if (sysctl(mib, ARRAY_SIZE(mib), stats, &len, NULL, 0) < 0) { + if (sysctl(mib, ARRAY_SIZE(mib), stats, &len, nullptr, 0) < 0) { return "sysctl({HW_DISKSTATS}, stats) failed"; } @@ -35,5 +35,5 @@ const char* ffDiskIOGetIoCounters(FFlist* result, FFDiskIOOptions* options) { device->writeCount = st->ds_wxfer; } - return NULL; + return nullptr; } diff --git a/src/detection/diskio/diskio_sunos.c b/src/detection/diskio/diskio_sunos.c index 7cda42081f..c79e3daeab 100644 --- a/src/detection/diskio/diskio_sunos.c +++ b/src/detection/diskio/diskio_sunos.c @@ -10,7 +10,7 @@ static inline void kstatFreeWrap(kstat_ctl_t** pkc) { } const char* ffDiskIOGetIoCounters(FFlist* result, FFDiskIOOptions* options) { - FF_A_CLEANUP(kstatFreeWrap) kstat_ctl_t* kc = kstat_open(); + [[gnu::cleanup(kstatFreeWrap)]] kstat_ctl_t* kc = kstat_open(); if (!kc) { return "kstat_open() failed"; } @@ -38,5 +38,5 @@ const char* ffDiskIOGetIoCounters(FFlist* result, FFDiskIOOptions* options) { device->writeCount = kio.writes; } - return NULL; + return nullptr; } diff --git a/src/detection/diskio/diskio_windows.c b/src/detection/diskio/diskio_windows.c index 80ad94e3da..ea01129383 100644 --- a/src/detection/diskio/diskio_windows.c +++ b/src/detection/diskio/diskio_windows.c @@ -6,7 +6,7 @@ #include static bool detectPhysicalDisk(const wchar_t* szDevice, FFlist* result, FFDiskIOOptions* options) { - FF_AUTO_CLOSE_FD HANDLE hDevice = CreateFileW(szDevice, FILE_READ_ATTRIBUTES, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); + FF_AUTO_CLOSE_FD HANDLE hDevice = CreateFileW(szDevice, FILE_READ_ATTRIBUTES, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); if (hDevice == INVALID_HANDLE_VALUE) { return false; } @@ -24,7 +24,7 @@ static bool detectPhysicalDisk(const wchar_t* szDevice, FFlist* result, FFDiskIO &sddBuffer, ARRAY_SIZE(sddBuffer), &retSize, - NULL) || + nullptr) || retSize == 0) { return true; } @@ -57,7 +57,7 @@ static bool detectPhysicalDisk(const wchar_t* szDevice, FFlist* result, FFDiskIO } DISK_PERFORMANCE dp = {}; - if (DeviceIoControl(hDevice, IOCTL_DISK_PERFORMANCE, NULL, 0, &dp, sizeof(dp), &retSize, NULL)) { + if (DeviceIoControl(hDevice, IOCTL_DISK_PERFORMANCE, nullptr, 0, &dp, sizeof(dp), &retSize, nullptr)) { device->bytesRead = (uint64_t) dp.BytesRead.QuadPart; device->readCount = (uint64_t) dp.ReadCount; device->bytesWritten = (uint64_t) dp.BytesWritten.QuadPart; @@ -97,5 +97,5 @@ const char* ffDiskIOGetIoCounters(FFlist* result, FFDiskIOOptions* options) { } } - return NULL; + return nullptr; } diff --git a/src/detection/displayserver/displayserver.c b/src/detection/displayserver/displayserver.c index e913771097..b5cc8eb7d1 100644 --- a/src/detection/displayserver/displayserver.c +++ b/src/detection/displayserver/displayserver.c @@ -18,7 +18,7 @@ FFDisplayResult* ffdsAppendDisplay( uint32_t physicalHeight, const char* platformApi) { if (width == 0 || height == 0) { - return NULL; + return nullptr; } FFDisplayResult* display = FF_LIST_ADD(FFDisplayResult, result->displays); diff --git a/src/detection/displayserver/displayserver.h b/src/detection/displayserver/displayserver.h index 53c0de3ea1..715a2de439 100644 --- a/src/detection/displayserver/displayserver.h +++ b/src/detection/displayserver/displayserver.h @@ -50,20 +50,20 @@ #define FF_WM_PROTOCOL_WAYLAND "Wayland" #define FF_WM_PROTOCOL_SURFACEFLINGER "SurfaceFlinger" -typedef enum FF_A_PACKED FFDisplayType { +typedef enum FFDisplayType: uint8_t { FF_DISPLAY_TYPE_UNKNOWN, FF_DISPLAY_TYPE_BUILTIN, FF_DISPLAY_TYPE_EXTERNAL, } FFDisplayType; -typedef enum FF_A_PACKED FFDisplayHdrStatus { +typedef enum FFDisplayHdrStatus: uint8_t { FF_DISPLAY_HDR_STATUS_UNKNOWN, FF_DISPLAY_HDR_STATUS_UNSUPPORTED, FF_DISPLAY_HDR_STATUS_SUPPORTED, FF_DISPLAY_HDR_STATUS_ENABLED, } FFDisplayHdrStatus; -typedef enum FF_A_PACKED FFDisplayVrrStatus { +typedef enum FFDisplayVrrStatus: uint8_t { FF_DISPLAY_DRR_STATUS_UNKNOWN, FF_DISPLAY_DRR_STATUS_DISABLED, FF_DISPLAY_DRR_STATUS_ENABLED, diff --git a/src/detection/displayserver/displayserver_android.c b/src/detection/displayserver/displayserver_android.c index 9b2848a137..13f5fab0ef 100644 --- a/src/detection/displayserver/displayserver_android.c +++ b/src/detection/displayserver/displayserver_android.c @@ -33,8 +33,8 @@ static void detectWithDumpsys(FFDisplayServerResult* ds) { if (ffProcessAppendStdOut(&buf, (char*[]) { "/system/bin/dumpsys", "display", - NULL, - }) != NULL || + nullptr, + }) != nullptr || buf.length == 0) { return; // Only works in `adb shell`, or when rooted } @@ -119,7 +119,7 @@ static bool detectWithGetprop(FFDisplayServerResult* ds) { 0, 0, 0, - NULL, + nullptr, FF_DISPLAY_TYPE_BUILTIN, false, 0, diff --git a/src/detection/displayserver/displayserver_apple.c b/src/detection/displayserver/displayserver_apple.c index a539cb3f95..94c86dfb6c 100644 --- a/src/detection/displayserver/displayserver_apple.c +++ b/src/detection/displayserver/displayserver_apple.c @@ -12,9 +12,9 @@ #include #ifdef MAC_OS_X_VERSION_10_15 -extern Boolean CoreDisplay_Display_SupportsHDRMode(CGDirectDisplayID display) FF_A_WEAK_IMPORT; -extern Boolean CoreDisplay_Display_IsHDRModeEnabled(CGDirectDisplayID display) FF_A_WEAK_IMPORT; -extern CFDictionaryRef CoreDisplay_DisplayCreateInfoDictionary(CGDirectDisplayID display) FF_A_WEAK_IMPORT; +[[clang::weak_import]] extern Boolean CoreDisplay_Display_SupportsHDRMode(CGDirectDisplayID display); +[[clang::weak_import]] extern Boolean CoreDisplay_Display_IsHDRModeEnabled(CGDirectDisplayID display); +[[clang::weak_import]] extern CFDictionaryRef CoreDisplay_DisplayCreateInfoDictionary(CGDirectDisplayID display); #else #include #endif @@ -50,7 +50,7 @@ static void detectDisplays(FFDisplayServerResult* ds) { } ffStrbufClear(&buffer); - CFDictionaryRef FF_CFTYPE_AUTO_RELEASE displayInfo = NULL; + FF_CFTYPE_AUTO_RELEASE CFDictionaryRef displayInfo = nullptr; #ifdef MAC_OS_X_VERSION_10_15 if (CoreDisplay_DisplayCreateInfoDictionary) { displayInfo = CoreDisplay_DisplayCreateInfoDictionary(screen); @@ -77,14 +77,14 @@ static void detectDisplays(FFDisplayServerResult* ds) { ffEdidGetPhysicalSize(edidData, &physicalWidth, &physicalHeight); ffEdidGetSerial(edidData, &serial); } - } else if (!builtin && ffCfDictGetString(displayInfo, CFSTR(kIODisplayLocationKey), &buffer) == NULL) { + } else if (!builtin && ffCfDictGetString(displayInfo, CFSTR(kIODisplayLocationKey), &buffer) == nullptr) { FF_IOOBJECT_AUTO_RELEASE io_registry_entry_t ioDisplay = IORegistryEntryFromPath(MACH_PORT_NULL, buffer.chars); ffStrbufClear(&buffer); if (ioDisplay) { FF_CFTYPE_AUTO_RELEASE CFDictionaryRef displayAttrRef = IORegistryEntryCreateCFProperty(ioDisplay, CFSTR("DisplayAttributes"), kCFAllocatorDefault, kNilOptions); if (displayAttrRef && CFGetTypeID(displayAttrRef) == CFDictionaryGetTypeID()) { CFDictionaryRef productAttrs; - if (ffCfDictGetDict(displayAttrRef, CFSTR("ProductAttributes"), &productAttrs) == NULL) { + if (ffCfDictGetDict(displayAttrRef, CFSTR("ProductAttributes"), &productAttrs) == nullptr) { ffCfDictGetString(productAttrs, CFSTR("AlphanumericSerialNumber"), &serial); ffCfDictGetString(productAttrs, CFSTR("ProductName"), &buffer); } @@ -94,13 +94,13 @@ static void detectDisplays(FFDisplayServerResult* ds) { if (!buffer.length) { CFDictionaryRef productNames; - if (ffCfDictGetDict(displayInfo, CFSTR(kDisplayProductName), &productNames) == NULL) { + if (ffCfDictGetDict(displayInfo, CFSTR(kDisplayProductName), &productNames) == nullptr) { ffCfDictGetString(productNames, CFSTR("en_US"), &buffer); } } if (!physicalWidth || !physicalHeight) { - if (ffCfDictGetInt(displayInfo, CFSTR(kDisplayHorizontalImageSize), (int*) &physicalWidth) == NULL) { + if (ffCfDictGetInt(displayInfo, CFSTR(kDisplayHorizontalImageSize), (int*) &physicalWidth) == nullptr) { ffCfDictGetInt(displayInfo, CFSTR(kDisplayVerticalImageSize), (int*) &physicalHeight); } } @@ -108,7 +108,7 @@ static void detectDisplays(FFDisplayServerResult* ds) { ffCfDictGetInt(displayInfo, CFSTR("kCGDisplayPixelWidth"), (int*) &preferredWidth); ffCfDictGetInt(displayInfo, CFSTR("kCGDisplayPixelHeight"), (int*) &preferredHeight); if (preferredWidth && preferredHeight) { - FF_CFTYPE_AUTO_RELEASE CFArrayRef allModes = CGDisplayCopyAllDisplayModes(screen, NULL); + FF_CFTYPE_AUTO_RELEASE CFArrayRef allModes = CGDisplayCopyAllDisplayModes(screen, nullptr); if (allModes) { for (CFIndex i = 0, count = CFArrayGetCount(allModes); i < count; i++) { CGDisplayModeRef modeInfo = (CGDisplayModeRef) CFArrayGetValueAtIndex(allModes, i); @@ -196,10 +196,10 @@ static void detectDisplays(FFDisplayServerResult* ds) { if (displayInfo) { int value; - if (ffCfDictGetInt(displayInfo, CFSTR(kDisplayYearOfManufacture), &value) == NULL) { + if (ffCfDictGetInt(displayInfo, CFSTR(kDisplayYearOfManufacture), &value) == nullptr) { display->manufactureYear = (uint16_t) value; } - if (ffCfDictGetInt(displayInfo, CFSTR(kDisplayWeekOfManufacture), &value) == NULL) { + if (ffCfDictGetInt(displayInfo, CFSTR(kDisplayWeekOfManufacture), &value) == nullptr) { display->manufactureWeek = (uint16_t) value; } } diff --git a/src/detection/displayserver/displayserver_windows.c b/src/detection/displayserver/displayserver_windows.c index 5c4f57e630..63d9e9a80f 100644 --- a/src/detection/displayserver/displayserver_windows.c +++ b/src/detection/displayserver/displayserver_windows.c @@ -10,10 +10,9 @@ static inline void freeArgBuffer(FFArgBuffer* buffer) { if (buffer->data) { free(buffer->data); } - buffer->data = NULL; + buffer->data = nullptr; buffer->length = 0; -} -#define FF_AUTO_FREE_ARG_BUFFER FF_A_CLEANUP(freeArgBuffer) +}\ // http://undoc.airesoft.co.uk/user32.dll/IsThreadDesktopComposited.php BOOL WINAPI IsThreadDesktopComposited(); @@ -31,7 +30,7 @@ static void detectDisplays(FFDisplayServerResult* ds) { paths, &modeCount, modes, - NULL) == ERROR_SUCCESS) { + nullptr) == ERROR_SUCCESS) { for (uint32_t i = 0; i < pathCount; ++i) { const DISPLAYCONFIG_PATH_INFO* path = &paths[i]; const DISPLAYCONFIG_SOURCE_MODE* sourceMode = &modes[path->sourceInfo.modeInfoIdx].sourceMode; @@ -47,7 +46,7 @@ static void detectDisplays(FFDisplayServerResult* ds) { .id = path->targetInfo.id, }, }; - FF_AUTO_FREE_ARG_BUFFER FFArgBuffer edid = {}; + [[gnu::cleanup(freeArgBuffer)]] FFArgBuffer edid = {}; if (DisplayConfigGetDeviceInfo(&targetName.header) == ERROR_SUCCESS) { wchar_t regPath[256] = L"SYSTEM\\CurrentControlSet\\Enum"; wchar_t* pRegPath = regPath + strlen("SYSTEM\\CurrentControlSet\\Enum"); @@ -64,9 +63,9 @@ static void detectDisplays(FFDisplayServerResult* ds) { } wcscpy(pRegPath, L"Device Parameters"); - FF_AUTO_CLOSE_FD HANDLE hKey = NULL; - if (ffRegOpenKeyForRead(HKEY_LOCAL_MACHINE, regPath, &hKey, NULL) && - ffRegReadData(hKey, L"EDID", &edid, NULL) && + FF_AUTO_CLOSE_FD HANDLE hKey = nullptr; + if (ffRegOpenKeyForRead(HKEY_LOCAL_MACHINE, regPath, &hKey, nullptr) && + ffRegReadData(hKey, L"EDID", &edid, nullptr) && ffEdidIsValid(edid.data, edid.length)) { ffEdidGetName(edid.data, &name); ffEdidGetPhysicalSize(edid.data, &physicalWidth, &physicalHeight); @@ -122,12 +121,12 @@ static void detectDisplays(FFDisplayServerResult* ds) { } if (systemDpi == 0) { - HDC hdc = GetDC(NULL); + HDC hdc = GetDC(nullptr); systemDpi = (uint32_t) GetDeviceCaps(hdc, LOGPIXELSX); if (systemDpi == 0) { systemDpi = 96; } - ReleaseDC(NULL, hdc); + ReleaseDC(nullptr, hdc); } if (path->targetInfo.rotation == DISPLAYCONFIG_ROTATION_ROTATE90 || diff --git a/src/detection/displayserver/linux/displayserver_linux.c b/src/detection/displayserver/linux/displayserver_linux.c index 70d2d40014..8907b7bdfd 100644 --- a/src/detection/displayserver/linux/displayserver_linux.c +++ b/src/detection/displayserver/linux/displayserver_linux.c @@ -22,12 +22,12 @@ static void getWMProtocolNameFromEnv(FFDisplayServerResult* result) { return; } - if (getenv("WAYLAND_DISPLAY") != NULL || getenv("WAYLAND_SOCKET") != NULL) { + if (getenv("WAYLAND_DISPLAY") != nullptr || getenv("WAYLAND_SOCKET") != nullptr) { ffStrbufSetStatic(&result->wmProtocolName, FF_WM_PROTOCOL_WAYLAND); return; } - if (getenv("DISPLAY") != NULL) // XWayland also set this + if (getenv("DISPLAY") != nullptr) // XWayland also set this { ffStrbufSetStatic(&result->wmProtocolName, FF_WM_PROTOCOL_X11); return; @@ -73,7 +73,7 @@ void ffConnectDisplayServerImpl(FFDisplayServerResult* ds) { ffStrbufClear(&buf); if (ffSettingsGetFreeBSDKenv("screen.height", &buf)) { uint32_t height = (uint32_t) ffStrbufToUInt(&buf, 0); - ffdsAppendDisplay(ds, width, height, 0, 0, 0, 0, 0, 0, NULL, FF_DISPLAY_TYPE_UNKNOWN, false, 0, 0, 0, "kenv"); + ffdsAppendDisplay(ds, width, height, 0, 0, 0, 0, 0, 0, nullptr, FF_DISPLAY_TYPE_UNKNOWN, false, 0, 0, 0, "kenv"); } } } diff --git a/src/detection/displayserver/linux/drm.c b/src/detection/displayserver/linux/drm.c index 61c30cd140..21d70ea069 100644 --- a/src/detection/displayserver/linux/drm.c +++ b/src/detection/displayserver/linux/drm.c @@ -11,7 +11,7 @@ static const char* drmParseSysfs(FFDisplayServerResult* result) { const char* drmDirPath = "/sys/class/drm/"; FF_AUTO_CLOSE_DIR DIR* dirp = opendir(drmDirPath); - if (dirp == NULL) { + if (dirp == nullptr) { return "opendir(drmDirPath) failed"; } @@ -21,7 +21,7 @@ static const char* drmParseSysfs(FFDisplayServerResult* result) { uint32_t drmDirLength = drmDir.length; struct dirent* entry; - while ((entry = readdir(dirp)) != NULL) { + while ((entry = readdir(dirp)) != nullptr) { if (entry->d_name[0] == '.') { continue; } @@ -105,7 +105,7 @@ static const char* drmParseSysfs(FFDisplayServerResult* result) { ffStrbufSubstrBefore(&drmDir, drmDirLength); } - return NULL; + return nullptr; } #endif @@ -175,11 +175,11 @@ static inline const char* drmType2Name(uint32_t connector_type) { } } -FF_A_UNUSED static const char* drmGetEdidByConnId(uint32_t connId, uint8_t* edidData, ssize_t* edidLength) { +[[maybe_unused]] static const char* drmGetEdidByConnId(uint32_t connId, uint8_t* edidData, ssize_t* edidLength) { const char* drmDirPath = "/sys/class/drm/"; FF_AUTO_CLOSE_DIR DIR* dirp = opendir(drmDirPath); - if (dirp == NULL) { + if (dirp == nullptr) { return "opendir(drmDirPath) failed"; } @@ -189,7 +189,7 @@ FF_A_UNUSED static const char* drmGetEdidByConnId(uint32_t connId, uint8_t* edid uint32_t drmDirLength = drmDir.length; struct dirent* entry; - while ((entry = readdir(dirp)) != NULL) { + while ((entry = readdir(dirp)) != nullptr) { if (entry->d_name[0] == '.') { continue; } @@ -201,7 +201,7 @@ FF_A_UNUSED static const char* drmGetEdidByConnId(uint32_t connId, uint8_t* edid ffStrbufAppendS(&drmDir, "/connector_id"); ffReadFileData(drmDir.chars, ARRAY_SIZE(connectorId), connectorId); - if (strtoul(connectorId, NULL, 10) != connId) { + if (strtoul(connectorId, nullptr, 10) != connId) { ffStrbufSubstrBefore(&drmDir, drmDirLength); continue; } @@ -209,7 +209,7 @@ FF_A_UNUSED static const char* drmGetEdidByConnId(uint32_t connId, uint8_t* edid ffStrbufSubstrBefore(&drmDir, drmDirWithDnameLength); ffStrbufAppendS(&drmDir, "/edid"); *edidLength = ffReadFileData(drmDir.chars, (uint32_t) *edidLength, edidData); - return NULL; + return nullptr; } return "Failed to match connector ID"; @@ -217,7 +217,7 @@ FF_A_UNUSED static const char* drmGetEdidByConnId(uint32_t connId, uint8_t* edid static const char* drmConnectLibdrm(FFDisplayServerResult* result) { FF_AUTO_CLOSE_DIR DIR* dirp = opendir("/dev/dri/"); - if (dirp == NULL) { + if (dirp == nullptr) { return "opendir(/dev/dri/) failed"; } int drifd = dirfd(dirp); @@ -225,7 +225,7 @@ static const char* drmConnectLibdrm(FFDisplayServerResult* result) { int nSuccess = 0; struct dirent* entry; - while ((entry = readdir(dirp)) != NULL) { + while ((entry = readdir(dirp)) != nullptr) { if (entry->d_name[0] == '.' || !ffStrStartsWith(entry->d_name, "card")) { continue; } @@ -392,7 +392,7 @@ static const char* drmConnectLibdrm(FFDisplayServerResult* result) { if (name.length == 0) { const char* connectorTypeName = drmType2Name(conn.connector_type); - if (connectorTypeName == NULL) { + if (connectorTypeName == nullptr) { connectorTypeName = "Unknown"; } ffStrbufSetF(&name, "%s-%d", connectorTypeName, iConn + 1); @@ -429,16 +429,16 @@ static const char* drmConnectLibdrm(FFDisplayServerResult* result) { } } - return nSuccess > 0 ? NULL : "No connectors found using libdrm"; + return nSuccess > 0 ? nullptr : "No connectors found using libdrm"; } #endif -const char* ffdsConnectDrm(FF_A_UNUSED FFDisplayServerResult* result) { +const char* ffdsConnectDrm([[maybe_unused]] FFDisplayServerResult* result) { #if FF_HAVE_DRM if (instance.config.general.dsForceDrm != FF_DS_FORCE_DRM_TYPE_SYSFS_ONLY) { - if (drmConnectLibdrm(result) == NULL) { - return NULL; + if (drmConnectLibdrm(result) == nullptr) { + return nullptr; } } #endif diff --git a/src/detection/displayserver/linux/wayland/global-output.c b/src/detection/displayserver/linux/wayland/global-output.c index e15199218a..6639a70c28 100644 --- a/src/detection/displayserver/linux/wayland/global-output.c +++ b/src/detection/displayserver/linux/wayland/global-output.c @@ -5,7 +5,7 @@ #include "xdg-output-unstable-v1-client-protocol.h" #include "wp-color-management-v1-client-protocol.h" -static void waylandOutputModeListener(void* data, FF_A_UNUSED struct wl_output* output, uint32_t flags, int32_t width, int32_t height, int32_t refreshRate) { +static void waylandOutputModeListener(void* data, [[maybe_unused]] struct wl_output* output, uint32_t flags, int32_t width, int32_t height, int32_t refreshRate) { WaylandDisplay* display = data; if (flags & WL_OUTPUT_MODE_CURRENT) { @@ -20,20 +20,25 @@ static void waylandOutputModeListener(void* data, FF_A_UNUSED struct wl_output* } } -static void waylandOutputScaleListener(void* data, FF_A_UNUSED struct wl_output* output, int32_t scale) { +static void waylandOutputScaleListener(void* data, [[maybe_unused]] struct wl_output* output, int32_t scale) { WaylandDisplay* display = data; display->dpi = 96 * (uint32_t) scale; } +static void waylandOutputDoneListener(void* data, [[maybe_unused]] struct wl_output* output) { + WaylandDisplay* display = data; + display->done = true; +} + static void waylandOutputGeometryListener(void* data, - FF_A_UNUSED struct wl_output* output, - FF_A_UNUSED int32_t x, - FF_A_UNUSED int32_t y, + [[maybe_unused]] struct wl_output* output, + [[maybe_unused]] int32_t x, + [[maybe_unused]] int32_t y, int32_t physical_width, int32_t physical_height, - FF_A_UNUSED int32_t subpixel, - FF_A_UNUSED const char* make, - FF_A_UNUSED const char* model, + [[maybe_unused]] int32_t subpixel, + [[maybe_unused]] const char* make, + [[maybe_unused]] const char* model, int32_t transform) { WaylandDisplay* display = data; display->physicalWidth = physical_width; @@ -41,7 +46,7 @@ static void waylandOutputGeometryListener(void* data, display->transform = (enum wl_output_transform) transform; } -static void handleXdgLogicalSize(void* data, FF_A_UNUSED struct zxdg_output_v1* _, int32_t width, FF_A_UNUSED int32_t height) { +static void handleXdgLogicalSize(void* data, [[maybe_unused]] struct zxdg_output_v1* _, int32_t width, [[maybe_unused]] int32_t height) { WaylandDisplay* display = data; // Seems the values are only useful when ractional scale is enabled if (width < display->width) { @@ -49,29 +54,24 @@ static void handleXdgLogicalSize(void* data, FF_A_UNUSED struct zxdg_output_v1* } } -// Dirty hack for #477 -// The order of these callbacks MUST follow `struct wl_output_listener` -static void* outputListener[] = { - waylandOutputGeometryListener, // geometry - waylandOutputModeListener, // mode - stubListener, // done - waylandOutputScaleListener, // scale - ffWaylandOutputNameListener, // name - ffWaylandOutputDescriptionListener, // description +static struct wl_output_listener outputListener = { + .geometry = waylandOutputGeometryListener, + .mode = waylandOutputModeListener, + .done = waylandOutputDoneListener, + .scale = waylandOutputScaleListener, + .name = (void*) ffWaylandOutputNameListener, + .description = (void*) ffWaylandOutputDescriptionListener, }; -static_assert( - sizeof(outputListener) >= sizeof(struct wl_output_listener), - "sizeof(outputListener) is too small. Please report it to fastfetch github issue"); static struct zxdg_output_v1_listener zxdgOutputListener = { - .logical_position = (void*) stubListener, + .logical_position = (void*) ffUnused, .logical_size = handleXdgLogicalSize, - .done = (void*) stubListener, + .done = (void*) ffUnused, .name = (void*) ffWaylandOutputNameListener, .description = (void*) ffWaylandOutputDescriptionListener, }; -static void handleWpTfNamed(void *data, FF_A_UNUSED struct wp_image_description_info_v1* wp_image_description_info_v1, uint32_t tf) { +static void handleWpTfNamed(void *data, [[maybe_unused]] struct wp_image_description_info_v1* wp_image_description_info_v1, uint32_t tf) { // KDE reports `gamma 2.2` even in HDR mode, but it should be handled in KDE specific path WaylandDisplay* display = data; switch (tf) { @@ -84,24 +84,24 @@ static void handleWpTfNamed(void *data, FF_A_UNUSED struct wp_image_description_ } static const struct wp_image_description_info_v1_listener wpImageDescInfoListener = { - .done = (void*) stubListener, - .icc_file = (void*) stubListener, - .primaries = (void*) stubListener, - .primaries_named = (void*) stubListener, - .tf_power = (void*) stubListener, + .done = (void*) ffUnused, + .icc_file = (void*) ffUnused, + .primaries = (void*) ffUnused, + .primaries_named = (void*) ffUnused, + .tf_power = (void*) ffUnused, .tf_named = (void*) handleWpTfNamed, - .luminances = (void*) stubListener, - .target_primaries = (void*) stubListener, - .target_luminance = (void*) stubListener, - .target_max_cll = (void*) stubListener, - .target_max_fall = (void*) stubListener, + .luminances = (void*) ffUnused, + .target_primaries = (void*) ffUnused, + .target_luminance = (void*) ffUnused, + .target_max_cll = (void*) ffUnused, + .target_max_fall = (void*) ffUnused, }; const char* ffWaylandHandleGlobalOutput(WaylandData* wldata, struct wl_registry* registry, uint32_t name, uint32_t version) { const char* api = "wayland-base"; uint32_t bindVersion = min(version, WL_OUTPUT_DESCRIPTION_SINCE_VERSION); - struct wl_proxy* output = wldata->ffwl_proxy_marshal_constructor_versioned((struct wl_proxy*) registry, WL_REGISTRY_BIND, &wl_output_interface, bindVersion, name, wl_output_interface.name, bindVersion, NULL); - if (output == NULL) { + struct wl_proxy* output = wldata->ffwl_proxy_marshal_constructor_versioned((struct wl_proxy*) registry, WL_REGISTRY_BIND, &wl_output_interface, bindVersion, name, wl_output_interface.name, bindVersion, nullptr); + if (output == nullptr) { return "Failed to create wl_output"; } @@ -122,10 +122,17 @@ const char* ffWaylandHandleGlobalOutput(WaylandData* wldata, struct wl_registry* wldata->ffwl_proxy_destroy(output); return "Failed to roundtrip wl_output"; } + if (bindVersion >= WL_OUTPUT_DONE_SINCE_VERSION && !display.done) { + const char* error = ffWaylandWaitForDone(&display); + if (error) { + wldata->ffwl_proxy_destroy(output); + return error; + } + } if (wldata->zxdgOutputManager) { uint32_t bindVersion = min(version, ZXDG_OUTPUT_V1_DESCRIPTION_SINCE_VERSION); - struct wl_proxy* zxdgOutput = wldata->ffwl_proxy_marshal_constructor_versioned(wldata->zxdgOutputManager, ZXDG_OUTPUT_MANAGER_V1_GET_XDG_OUTPUT, &zxdg_output_v1_interface, bindVersion, NULL, output); + struct wl_proxy* zxdgOutput = wldata->ffwl_proxy_marshal_constructor_versioned(wldata->zxdgOutputManager, ZXDG_OUTPUT_MANAGER_V1_GET_XDG_OUTPUT, &zxdg_output_v1_interface, bindVersion, nullptr, output); if (zxdgOutput) { wldata->ffwl_proxy_add_listener(zxdgOutput, (void (**)(void)) &zxdgOutputListener, &display); @@ -137,12 +144,12 @@ const char* ffWaylandHandleGlobalOutput(WaylandData* wldata, struct wl_registry* if (wldata->wpColorManager) { uint32_t bindVersion = min(version, WP_COLOR_MANAGER_V1_GET_OUTPUT_SINCE_VERSION); - struct wl_proxy* wpColorOutput = wldata->ffwl_proxy_marshal_constructor_versioned(wldata->wpColorManager, WP_COLOR_MANAGER_V1_GET_OUTPUT, &wp_color_management_output_v1_interface, bindVersion, NULL, output); + struct wl_proxy* wpColorOutput = wldata->ffwl_proxy_marshal_constructor_versioned(wldata->wpColorManager, WP_COLOR_MANAGER_V1_GET_OUTPUT, &wp_color_management_output_v1_interface, bindVersion, nullptr, output); if (wpColorOutput) { - struct wl_proxy* wpImageDesc = wldata->ffwl_proxy_marshal_constructor_versioned(wpColorOutput, WP_COLOR_MANAGEMENT_OUTPUT_V1_GET_IMAGE_DESCRIPTION, &wp_image_description_v1_interface, bindVersion, NULL); + struct wl_proxy* wpImageDesc = wldata->ffwl_proxy_marshal_constructor_versioned(wpColorOutput, WP_COLOR_MANAGEMENT_OUTPUT_V1_GET_IMAGE_DESCRIPTION, &wp_image_description_v1_interface, bindVersion, nullptr); if (wpImageDesc) { - struct wl_proxy* wpImageDescInfo = wldata->ffwl_proxy_marshal_constructor_versioned(wpImageDesc, WP_IMAGE_DESCRIPTION_V1_GET_INFORMATION, &wp_image_description_info_v1_interface, bindVersion, NULL); + struct wl_proxy* wpImageDescInfo = wldata->ffwl_proxy_marshal_constructor_versioned(wpImageDesc, WP_IMAGE_DESCRIPTION_V1_GET_INFORMATION, &wp_image_description_info_v1_interface, bindVersion, nullptr); if (wpImageDescInfo) { wldata->ffwl_proxy_add_listener(wpImageDescInfo, (void (**)(void)) &wpImageDescInfoListener, &display); wldata->ffwl_display_roundtrip(wldata->display); @@ -205,31 +212,31 @@ const char* ffWaylandHandleGlobalOutput(WaylandData* wldata, struct wl_registry* ffStrbufDestroy(&display.name); ffStrbufDestroy(&display.edidName); - return NULL; + return nullptr; } const char* ffWaylandHandleZxdgOutput(WaylandData* wldata, struct wl_registry* registry, uint32_t name, uint32_t version) { uint32_t bindVersion = min(version, ZXDG_OUTPUT_MANAGER_V1_GET_XDG_OUTPUT_SINCE_VERSION); - struct wl_proxy* manager = wldata->ffwl_proxy_marshal_constructor_versioned((struct wl_proxy*) registry, WL_REGISTRY_BIND, &zxdg_output_manager_v1_interface, bindVersion, name, zxdg_output_manager_v1_interface.name, bindVersion, NULL); - if (manager == NULL) { + struct wl_proxy* manager = wldata->ffwl_proxy_marshal_constructor_versioned((struct wl_proxy*) registry, WL_REGISTRY_BIND, &zxdg_output_manager_v1_interface, bindVersion, name, zxdg_output_manager_v1_interface.name, bindVersion, nullptr); + if (manager == nullptr) { return "Failed to create zxdg_output_manager_v1"; } wldata->zxdgOutputManager = manager; - return NULL; + return nullptr; } const char* ffWaylandHandleWpColor(WaylandData* wldata, struct wl_registry* registry, uint32_t name, uint32_t version) { uint32_t bindVersion = min(version, WP_COLOR_MANAGER_V1_GET_OUTPUT_SINCE_VERSION); - struct wl_proxy* manager = wldata->ffwl_proxy_marshal_constructor_versioned((struct wl_proxy*) registry, WL_REGISTRY_BIND, &wp_color_manager_v1_interface, bindVersion, name, wp_color_manager_v1_interface.name, bindVersion, NULL); - if (manager == NULL) { + struct wl_proxy* manager = wldata->ffwl_proxy_marshal_constructor_versioned((struct wl_proxy*) registry, WL_REGISTRY_BIND, &wp_color_manager_v1_interface, bindVersion, name, wp_color_manager_v1_interface.name, bindVersion, nullptr); + if (manager == nullptr) { return "Failed to create wp_color_manager_v1"; } wldata->wpColorManager = manager; - return NULL; + return nullptr; } #endif diff --git a/src/detection/displayserver/linux/wayland/kde-output-device-v2-client-protocol.h b/src/detection/displayserver/linux/wayland/kde-output-device-v2-client-protocol.h index 44ab8ab13a..aee08a11d9 100644 --- a/src/detection/displayserver/linux/wayland/kde-output-device-v2-client-protocol.h +++ b/src/detection/displayserver/linux/wayland/kde-output-device-v2-client-protocol.h @@ -252,7 +252,7 @@ kde_output_device_registry_v2_destroy(struct kde_output_device_registry_v2* kde_ // kde_output_device_registry_v2_stop(struct kde_output_device_registry_v2* kde_output_device_registry_v2) { // wl_proxy_marshal_flags((struct wl_proxy*) kde_output_device_registry_v2, // KDE_OUTPUT_DEVICE_REGISTRY_V2_STOP, -// NULL, +// nullptr, // wl_proxy_get_version((struct wl_proxy*) kde_output_device_registry_v2), // 0); // } @@ -1248,7 +1248,7 @@ kde_output_device_v2_destroy(struct kde_output_device_v2* kde_output_device_v2) // kde_output_device_v2_release(struct kde_output_device_v2* kde_output_device_v2) { // wl_proxy_marshal_flags((struct wl_proxy*) kde_output_device_v2, // KDE_OUTPUT_DEVICE_V2_RELEASE, -// NULL, +// nullptr, // wl_proxy_get_version((struct wl_proxy*) kde_output_device_v2), // WL_MARSHAL_FLAG_DESTROY); // } diff --git a/src/detection/displayserver/linux/wayland/kde-output-device-v2-protocol.c b/src/detection/displayserver/linux/wayland/kde-output-device-v2-protocol.c index 9dd7556765..9f6a4bdaf6 100644 --- a/src/detection/displayserver/linux/wayland/kde-output-device-v2-protocol.c +++ b/src/detection/displayserver/linux/wayland/kde-output-device-v2-protocol.c @@ -21,14 +21,14 @@ extern const struct wl_interface kde_output_device_mode_v2_interface; extern const struct wl_interface kde_output_device_v2_interface; static const struct wl_interface* kde_output_device_v2_types[] = { - NULL, - NULL, - NULL, - NULL, - NULL, - NULL, - NULL, - NULL, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, &kde_output_device_v2_interface, &kde_output_device_mode_v2_interface, &kde_output_device_mode_v2_interface, @@ -120,7 +120,7 @@ WL_EXPORT const struct wl_interface kde_output_device_mode_v2_interface = { "kde_output_device_mode_v2", 22, 0, - NULL, + nullptr, 5, kde_output_device_mode_v2_events, }; diff --git a/src/detection/displayserver/linux/wayland/kde-output.c b/src/detection/displayserver/linux/wayland/kde-output.c index 73f9ac5aff..7c49d858cf 100644 --- a/src/detection/displayserver/linux/wayland/kde-output.c +++ b/src/detection/displayserver/linux/wayland/kde-output.c @@ -13,18 +13,18 @@ typedef struct WaylandKdeMode { struct kde_output_device_mode_v2* pMode; } WaylandKdeMode; -static void waylandKdeModeSizeListener(void* data, FF_A_UNUSED struct kde_output_device_mode_v2* _, int32_t width, int32_t height) { +static void waylandKdeModeSizeListener(void* data, [[maybe_unused]] struct kde_output_device_mode_v2* _, int32_t width, int32_t height) { WaylandKdeMode* mode = (WaylandKdeMode*) data; mode->width = width; mode->height = height; } -static void waylandKdeModeRefreshListener(void* data, FF_A_UNUSED struct kde_output_device_mode_v2* _, int32_t rate) { +static void waylandKdeModeRefreshListener(void* data, [[maybe_unused]] struct kde_output_device_mode_v2* _, int32_t rate) { WaylandKdeMode* mode = (WaylandKdeMode*) data; mode->refreshRate = rate; } -static void waylandKdeModePreferredListener(void* data, FF_A_UNUSED struct kde_output_device_mode_v2* _) { +static void waylandKdeModePreferredListener(void* data, [[maybe_unused]] struct kde_output_device_mode_v2* _) { WaylandKdeMode* mode = (WaylandKdeMode*) data; mode->preferred = true; } @@ -33,11 +33,11 @@ static const struct kde_output_device_mode_v2_listener modeListener = { .size = waylandKdeModeSizeListener, .refresh = waylandKdeModeRefreshListener, .preferred = waylandKdeModePreferredListener, - .removed = (void*) stubListener, - .flags = (void*) stubListener, + .removed = (void*) ffUnused, + .flags = (void*) ffUnused, }; -static void waylandKdeModeListener(void* data, FF_A_UNUSED struct kde_output_device_v2* _, struct kde_output_device_mode_v2* mode) { +static void waylandKdeModeListener(void* data, [[maybe_unused]] struct kde_output_device_v2* _, struct kde_output_device_mode_v2* mode) { WaylandDisplay* wldata = (WaylandDisplay*) data; if (!wldata->internal) { return; @@ -50,40 +50,39 @@ static void waylandKdeModeListener(void* data, FF_A_UNUSED struct kde_output_dev wldata->parent->ffwl_proxy_add_listener((struct wl_proxy*) mode, (void (**)(void)) &modeListener, newMode); } -static void waylandKdeCurrentModeListener(void* data, FF_A_UNUSED struct kde_output_device_v2* _, struct kde_output_device_mode_v2* mode) { +static void waylandKdeCurrentModeListener(void* data, [[maybe_unused]] struct kde_output_device_v2* _, struct kde_output_device_mode_v2* mode) { // waylandKdeModeListener is always run before this WaylandDisplay* wldata = (WaylandDisplay*) data; if (!wldata->internal) { return; } - int set = 0; + bool foundCurrent = false, foundPreferred = false; FF_LIST_FOR_EACH (WaylandKdeMode, m, *(FFlist*) wldata->internal) { - if (m->pMode == mode) { + if (!foundCurrent && m->pMode == mode) { wldata->width = m->width; wldata->height = m->height; wldata->refreshRate = m->refreshRate; - if (++set == 2) { - break; - } + foundCurrent = true; } - if (m->preferred) { + if (!foundPreferred && m->preferred) { wldata->preferredWidth = m->width; wldata->preferredHeight = m->height; wldata->preferredRefreshRate = m->refreshRate; - if (++set == 2) { - break; - } + foundPreferred = true; + } + if (foundCurrent && foundPreferred) { + break; } } } -static void waylandKdeScaleListener(void* data, FF_A_UNUSED struct kde_output_device_v2* _, wl_fixed_t scale) { +static void waylandKdeScaleListener(void* data, [[maybe_unused]] struct kde_output_device_v2* _, wl_fixed_t scale) { WaylandDisplay* wldata = (WaylandDisplay*) data; wldata->dpi = (uint32_t) scale * 3 / 8; // wl_fixed_to_double(scale) * 96; } -static void waylandKdeEdidListener(void* data, FF_A_UNUSED struct kde_output_device_v2* _, const char* raw) { +static void waylandKdeEdidListener(void* data, [[maybe_unused]] struct kde_output_device_v2* _, const char* raw) { if (!*raw) { return; } @@ -100,22 +99,22 @@ static void waylandKdeEdidListener(void* data, FF_A_UNUSED struct kde_output_dev wldata->hdrInfoAvailable = true; } -static void waylandKdeEnabledListener(void* data, FF_A_UNUSED struct kde_output_device_v2* _, int32_t enabled) { +static void waylandKdeEnabledListener(void* data, [[maybe_unused]] struct kde_output_device_v2* _, int32_t enabled) { WaylandDisplay* wldata = (WaylandDisplay*) data; if (!enabled) { - wldata->internal = NULL; + wldata->internal = nullptr; } } static void waylandKdeGeometryListener(void* data, - FF_A_UNUSED struct kde_output_device_v2* kde_output_device_v2, - FF_A_UNUSED int32_t x, - FF_A_UNUSED int32_t y, + [[maybe_unused]] struct kde_output_device_v2* kde_output_device_v2, + [[maybe_unused]] int32_t x, + [[maybe_unused]] int32_t y, int32_t physical_width, int32_t physical_height, - FF_A_UNUSED int32_t subpixel, - FF_A_UNUSED const char* make, - FF_A_UNUSED const char* model, + [[maybe_unused]] int32_t subpixel, + [[maybe_unused]] const char* make, + [[maybe_unused]] const char* model, int32_t transform) { WaylandDisplay* display = data; display->physicalWidth = physical_width; @@ -123,7 +122,7 @@ static void waylandKdeGeometryListener(void* data, display->transform = (enum wl_output_transform) transform; } -static void waylandKdeNameListener(void* data, FF_A_UNUSED struct kde_output_device_v2* kde_output_device_v2, const char* name) { +static void waylandKdeNameListener(void* data, [[maybe_unused]] struct kde_output_device_v2* kde_output_device_v2, const char* name) { WaylandDisplay* display = data; display->type = ffdsGetDisplayType(name); // As display->id is used as an internal identifier, we don't need it to be NUL terminated @@ -132,62 +131,67 @@ static void waylandKdeNameListener(void* data, FF_A_UNUSED struct kde_output_dev ffStrbufAppendS(&display->name, name); } -static void waylandKdeHdrListener(void* data, FF_A_UNUSED struct kde_output_device_v2* kde_output_device_v2, uint32_t hdr_enabled) { +static void waylandKdeHdrListener(void* data, [[maybe_unused]] struct kde_output_device_v2* kde_output_device_v2, uint32_t hdr_enabled) { WaylandDisplay* display = data; display->hdrEnabled = !!hdr_enabled; } -static void waylandKdeMaxBitsPerColorListener(void* data, FF_A_UNUSED struct kde_output_device_v2* kde_output_device_v2, uint32_t max_bpc) { +static void waylandKdeMaxBitsPerColorListener(void* data, [[maybe_unused]] struct kde_output_device_v2* kde_output_device_v2, uint32_t max_bpc) { WaylandDisplay* display = data; display->bitDepth = (uint8_t) max_bpc; } -static void waylandKdePriorityListener(void* data, FF_A_UNUSED struct kde_output_device_v2* kde_output_device_v2, uint32_t priority) { +static void waylandKdePriorityListener(void* data, [[maybe_unused]] struct kde_output_device_v2* kde_output_device_v2, uint32_t priority) { WaylandDisplay* display = data; display->primary = priority == 1; } +static void waylandKdeDoneListener(void* data, [[maybe_unused]] struct kde_output_device_v2* kde_output_device_v2) { + WaylandDisplay* display = data; + display->done = true; +} + static struct kde_output_device_v2_listener outputListener = { .geometry = waylandKdeGeometryListener, .current_mode = waylandKdeCurrentModeListener, .mode = waylandKdeModeListener, - .done = (void*) stubListener, + .done = waylandKdeDoneListener, .scale = waylandKdeScaleListener, .edid = waylandKdeEdidListener, .enabled = waylandKdeEnabledListener, - .uuid = (void*) stubListener, - .serial_number = (void*) stubListener, - .eisa_id = (void*) stubListener, - .capabilities = (void*) stubListener, - .overscan = (void*) stubListener, - .vrr_policy = (void*) stubListener, - .rgb_range = (void*) stubListener, + .uuid = (void*) ffUnused, + .serial_number = (void*) ffUnused, + .eisa_id = (void*) ffUnused, + .capabilities = (void*) ffUnused, + .overscan = (void*) ffUnused, + .vrr_policy = (void*) ffUnused, + .rgb_range = (void*) ffUnused, .name = waylandKdeNameListener, .high_dynamic_range = waylandKdeHdrListener, - .sdr_brightness = (void*) stubListener, - .wide_color_gamut = (void*) stubListener, - .auto_rotate_policy = (void*) stubListener, - .icc_profile_path = (void*) stubListener, - .brightness_metadata = (void*) stubListener, - .brightness_overrides = (void*) stubListener, - .sdr_gamut_wideness = (void*) stubListener, - .color_profile_source = (void*) stubListener, - .brightness = (void*) stubListener, - .color_power_tradeoff = (void*) stubListener, - .dimming = (void*) stubListener, - .replication_source = (void*) stubListener, - .ddc_ci_allowed = (void*) stubListener, + .sdr_brightness = (void*) ffUnused, + .wide_color_gamut = (void*) ffUnused, + .auto_rotate_policy = (void*) ffUnused, + .icc_profile_path = (void*) ffUnused, + .brightness_metadata = (void*) ffUnused, + .brightness_overrides = (void*) ffUnused, + .sdr_gamut_wideness = (void*) ffUnused, + .color_profile_source = (void*) ffUnused, + .brightness = (void*) ffUnused, + .color_power_tradeoff = (void*) ffUnused, + .dimming = (void*) ffUnused, + .replication_source = (void*) ffUnused, + .ddc_ci_allowed = (void*) ffUnused, .max_bits_per_color = (void*) waylandKdeMaxBitsPerColorListener, - .max_bits_per_color_range = (void*) stubListener, - .automatic_max_bits_per_color_limit = (void*) stubListener, - .edr_policy = (void*) stubListener, - .sharpness = (void*) stubListener, + .max_bits_per_color_range = (void*) ffUnused, + .automatic_max_bits_per_color_limit = (void*) ffUnused, + .edr_policy = (void*) ffUnused, + .sharpness = (void*) ffUnused, .priority = waylandKdePriorityListener, - .auto_brightness = (void*) stubListener, - .removed = (void*) stubListener, - .hdr_icc_profile_path = (void*) stubListener, - .hdr_color_profile_source = (void*) stubListener, - .abm_level = (void*) stubListener, + .auto_brightness = (void*) ffUnused, + .removed = (void*) ffUnused, + .hdr_icc_profile_path = (void*) ffUnused, + .hdr_color_profile_source = (void*) ffUnused, + .abm_level = (void*) ffUnused, }; static const char* waylandKdeHandleOutput(WaylandData* wldata, struct wl_proxy* output) { @@ -211,13 +215,20 @@ static const char* waylandKdeHandleOutput(WaylandData* wldata, struct wl_proxy* wldata->ffwl_proxy_destroy(output); return "Failed to roundtrip kde_output_device_v2"; } + if (!display.done) { + const char* error = ffWaylandWaitForDone(&display); + if (error) { + wldata->ffwl_proxy_destroy(output); + return error; + } + } // Destroy any mode proxies that were created during the listeners. // wl proxies created for modes are not automatically freed by destroying // the parent output proxy, so destroy them explicitly to avoid leaks. FF_LIST_FOR_EACH (WaylandKdeMode, m, modes) { if (m->pMode) { wldata->ffwl_proxy_destroy((struct wl_proxy*) m->pMode); - m->pMode = NULL; + m->pMode = nullptr; } } @@ -268,33 +279,33 @@ static const char* waylandKdeHandleOutput(WaylandData* wldata, struct wl_proxy* ffStrbufDestroy(&display.name); ffStrbufDestroy(&display.edidName); - return NULL; + return nullptr; } const char* ffWaylandHandleKdeOutput(WaylandData* wldata, struct wl_registry* registry, uint32_t name, uint32_t version) { // TODO: remove this in future versions uint32_t bindVersion = min(version, KDE_OUTPUT_DEVICE_V2_PRIORITY_SINCE_VERSION); - struct wl_proxy* output = wldata->ffwl_proxy_marshal_constructor_versioned((struct wl_proxy*) registry, WL_REGISTRY_BIND, &kde_output_device_v2_interface, bindVersion, name, kde_output_device_v2_interface.name, bindVersion, NULL); - if (output == NULL) { + struct wl_proxy* output = wldata->ffwl_proxy_marshal_constructor_versioned((struct wl_proxy*) registry, WL_REGISTRY_BIND, &kde_output_device_v2_interface, bindVersion, name, kde_output_device_v2_interface.name, bindVersion, nullptr); + if (output == nullptr) { return "Failed to create kde_output_device_v2"; } return waylandKdeHandleOutput(wldata, output); } -static void waylandKdeOutputListener(void* data, FF_A_UNUSED struct kde_output_device_registry_v2* kde_output_device_registry_v2, struct kde_output_device_v2* output) { +static void waylandKdeOutputListener(void* data, [[maybe_unused]] struct kde_output_device_registry_v2* kde_output_device_registry_v2, struct kde_output_device_v2* output) { waylandKdeHandleOutput((WaylandData*) data, (struct wl_proxy*) output); } static struct kde_output_device_registry_v2_listener registryListener = { .output = waylandKdeOutputListener, - .finished = (void*) stubListener, + .finished = (void*) ffUnused, }; const char* ffWaylandHandleKdeOutputRegistry(WaylandData* wldata, struct wl_registry* registry, uint32_t name, uint32_t version) { uint32_t bindVersion = min(version, KDE_OUTPUT_DEVICE_REGISTRY_V2_OUTPUT_SINCE_VERSION); - struct wl_proxy* outputRegistry = wldata->ffwl_proxy_marshal_constructor_versioned((struct wl_proxy*) registry, WL_REGISTRY_BIND, &kde_output_device_registry_v2_interface, bindVersion, name, kde_output_device_registry_v2_interface.name, bindVersion, NULL); - if (outputRegistry == NULL) { + struct wl_proxy* outputRegistry = wldata->ffwl_proxy_marshal_constructor_versioned((struct wl_proxy*) registry, WL_REGISTRY_BIND, &kde_output_device_registry_v2_interface, bindVersion, name, kde_output_device_registry_v2_interface.name, bindVersion, nullptr); + if (outputRegistry == nullptr) { return "Failed to create kde_output_device_registry_v2"; } if (wldata->ffwl_proxy_add_listener(outputRegistry, (void (**)(void)) ®istryListener, wldata) < 0) { @@ -307,7 +318,7 @@ const char* ffWaylandHandleKdeOutputRegistry(WaylandData* wldata, struct wl_regi } wldata->ffwl_proxy_destroy(outputRegistry); - return NULL; + return nullptr; } #endif diff --git a/src/detection/displayserver/linux/wayland/wayland.c b/src/detection/displayserver/linux/wayland/wayland.c index 647aa067f7..29c1d46e9b 100644 --- a/src/detection/displayserver/linux/wayland/wayland.c +++ b/src/detection/displayserver/linux/wayland/wayland.c @@ -48,7 +48,7 @@ static bool waylandDetectWM(int fd, FFDisplayServerResult* result) { size_t size = 4096; ffStrbufEnsureFixedLengthFree(&result->wmProcessName, (uint32_t) size); - if (sysctl((int[]) { CTL_KERN, KERN_PROC, KERN_PROC_ARGS, ucred.cr_pid }, 4, result->wmProcessName.chars, &size, NULL, 0) != 0) { + if (sysctl((int[]) { CTL_KERN, KERN_PROC, KERN_PROC_ARGS, ucred.cr_pid }, 4, result->wmProcessName.chars, &size, nullptr, 0) != 0) { return false; } result->wmProcessName.length = (uint32_t) size - 1; @@ -82,17 +82,17 @@ static void waylandGlobalAddListener(void* data, struct wl_registry* registry, u if ((wldata->protocolType == FF_WAYLAND_PROTOCOL_TYPE_NONE || wldata->protocolType == FF_WAYLAND_PROTOCOL_TYPE_GLOBAL) && ffStrEquals(interface, wl_output_interface.name)) { wldata->protocolType = FF_WAYLAND_PROTOCOL_TYPE_GLOBAL; - if (ffWaylandHandleGlobalOutput(wldata, registry, name, version) != NULL) { + if (ffWaylandHandleGlobalOutput(wldata, registry, name, version) != nullptr) { wldata->protocolType = FF_WAYLAND_PROTOCOL_TYPE_NONE; } } else if ((wldata->protocolType == FF_WAYLAND_PROTOCOL_TYPE_NONE) && ffStrEquals(interface, kde_output_device_registry_v2_interface.name)) { wldata->protocolType = FF_WAYLAND_PROTOCOL_TYPE_KDE_REGISTRY; - if (ffWaylandHandleKdeOutputRegistry(wldata, registry, name, version) != NULL) { + if (ffWaylandHandleKdeOutputRegistry(wldata, registry, name, version) != nullptr) { wldata->protocolType = FF_WAYLAND_PROTOCOL_TYPE_NONE; } } else if ((wldata->protocolType == FF_WAYLAND_PROTOCOL_TYPE_NONE || wldata->protocolType == FF_WAYLAND_PROTOCOL_TYPE_KDE_DEPRECATED) && ffStrEquals(interface, kde_output_device_v2_interface.name)) { wldata->protocolType = FF_WAYLAND_PROTOCOL_TYPE_KDE_DEPRECATED; - if (ffWaylandHandleKdeOutput(wldata, registry, name, version) != NULL) { + if (ffWaylandHandleKdeOutput(wldata, registry, name, version) != nullptr) { wldata->protocolType = FF_WAYLAND_PROTOCOL_TYPE_NONE; } } else if ((wldata->protocolType == FF_WAYLAND_PROTOCOL_TYPE_GLOBAL || wldata->protocolType == FF_WAYLAND_PROTOCOL_TYPE_NONE) && ffStrEquals(interface, zxdg_output_manager_v1_interface.name)) { @@ -102,19 +102,19 @@ static void waylandGlobalAddListener(void* data, struct wl_registry* registry, u } } -static FF_A_UNUSED bool matchDrmConnector(const char* connName, WaylandDisplay* wldata) { +[[maybe_unused]] static bool matchDrmConnector(const char* connName, WaylandDisplay* wldata) { // https://wayland.freedesktop.org/docs/html/apa.html#protocol-spec-wl_output-event-name // The doc says that "do not assume that the name is a reflection of an underlying DRM connector, X11 connection, etc." // However I can't find a better method to get the edid data const char* drmDirPath = "/sys/class/drm/"; FF_AUTO_CLOSE_DIR DIR* dirp = opendir(drmDirPath); - if (dirp == NULL) { + if (dirp == nullptr) { return false; } struct dirent* entry; - while ((entry = readdir(dirp)) != NULL) { + while ((entry = readdir(dirp)) != nullptr) { const char* plainName = entry->d_name; if (ffStrStartsWith(plainName, "card")) { const char* tmp = strchr(plainName + strlen("card"), '-'); @@ -149,7 +149,7 @@ static FF_A_UNUSED bool matchDrmConnector(const char* connName, WaylandDisplay* return false; } -void ffWaylandOutputNameListener(void* data, FF_A_UNUSED void* output, const char* name) { +void ffWaylandOutputNameListener(void* data, [[maybe_unused]] void* output, const char* name) { WaylandDisplay* display = data; if (display->id) { return; @@ -165,7 +165,7 @@ void ffWaylandOutputNameListener(void* data, FF_A_UNUSED void* output, const cha ffStrbufAppendS(&display->name, name); } -void ffWaylandOutputDescriptionListener(void* data, FF_A_UNUSED void* output, const char* description) { +void ffWaylandOutputDescriptionListener(void* data, [[maybe_unused]] void* output, const char* description) { WaylandDisplay* display = data; if (display->description.length) { return; @@ -217,8 +217,41 @@ uint32_t ffWaylandHandleRotation(WaylandDisplay* display) { return rotation; } +const char* ffWaylandWaitForDone(WaylandDisplay* display) { + int32_t timeout = instance.config.general.processingTimeout; + struct timespec ts; + if (timeout == 0) { + return "timeout is disabled"; + } else if (timeout > 0) { + if (!display->parent->ffwl_display_dispatch_timeout) { + return "timeout is enabled, but the libwayland-client version is too old to support it"; + } + ts.tv_sec = timeout / 1000; + ts.tv_nsec = (timeout % 1000) * 1000000; + } + + WaylandData* wldata = display->parent; + + // Some compositors emit the final output state asynchronously after the roundtrip callback (#2074) + while (!display->done) { + if (timeout > 0) { + if (wldata->ffwl_display_dispatch_timeout(wldata->display, &ts) < 0) { + return "wl_display_dispatch_timeout() failed"; + } + } else if (timeout < 0) { + if (wldata->ffwl_display_dispatch(wldata->display) < 0) { + return "wl_display_dispatch() failed"; + } + } else { + return "Timeout exceeded, but the compositor did not send a done event"; + } + } + + return nullptr; +} + const char* ffdsConnectWayland(FFDisplayServerResult* result) { - if (getenv("XDG_RUNTIME_DIR") == NULL) { + if (getenv("XDG_RUNTIME_DIR") == nullptr) { return "Wayland requires $XDG_RUNTIME_DIR being set"; } @@ -236,24 +269,30 @@ const char* ffdsConnectWayland(FFDisplayServerResult* result) { FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(wayland, data, wl_proxy_destroy) FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(wayland, data, wl_display_roundtrip) - data.display = ffwl_display_connect(NULL); - if (data.display == NULL) { - return "wl_display_connect returned NULL"; + if (instance.config.general.processingTimeout < 0) { + FF_LIBRARY_LOAD_SYMBOL_VAR_LAZY(wayland, data, wl_display_dispatch) + } else if (instance.config.general.processingTimeout > 0) { + FF_LIBRARY_LOAD_SYMBOL_VAR_LAZY(wayland, data, wl_display_dispatch_timeout) + } + + data.display = ffwl_display_connect(nullptr); + if (data.display == nullptr) { + return "wl_display_connect returned nullptr"; } waylandDetectWM(ffwl_display_get_fd(data.display), result); - struct wl_proxy* registry = ffwl_proxy_marshal_constructor((struct wl_proxy*) data.display, WL_DISPLAY_GET_REGISTRY, &wl_registry_interface, NULL); - if (registry == NULL) { + struct wl_proxy* registry = ffwl_proxy_marshal_constructor((struct wl_proxy*) data.display, WL_DISPLAY_GET_REGISTRY, &wl_registry_interface, nullptr); + if (registry == nullptr) { ffwl_display_disconnect(data.display); - return "wl_display_get_registry returned NULL"; + return "wl_display_get_registry returned nullptr"; } data.result = result; struct wl_registry_listener registry_listener = { .global = waylandGlobalAddListener, - .global_remove = (void*) stubListener + .global_remove = (void*) ffUnused }; data.ffwl_proxy_add_listener(registry, (void (**)(void)) ®istry_listener, &data); @@ -275,7 +314,7 @@ const char* ffdsConnectWayland(FFDisplayServerResult* result) { ? "monitors.xml" : ffStrbufEqualS(&result->wmProcessName, "cinnamon") ? "cinnamon-monitors.xml" - : NULL; + : nullptr; if (fileName) { FF_STRBUF_AUTO_DESTROY monitorsXml = ffStrbufCreate(); FF_LIST_FOR_EACH (FFstrbuf, basePath, instance.state.platform.configDirs) { @@ -336,12 +375,12 @@ const char* ffdsConnectWayland(FFDisplayServerResult* result) { // So we can set set the session type to wayland. // This is used as an indicator that we are running wayland by the x11 backends. ffStrbufSetStatic(&result->wmProtocolName, FF_WM_PROTOCOL_WAYLAND); - return NULL; + return nullptr; } #else -const char* ffdsConnectWayland(FF_A_UNUSED FFDisplayServerResult* result) { +const char* ffdsConnectWayland([[maybe_unused]] FFDisplayServerResult* result) { return "Fastfetch was compiled without Wayland support"; } diff --git a/src/detection/displayserver/linux/wayland/wayland.h b/src/detection/displayserver/linux/wayland/wayland.h index e9d4fede83..e225eb881b 100644 --- a/src/detection/displayserver/linux/wayland/wayland.h +++ b/src/detection/displayserver/linux/wayland/wayland.h @@ -13,19 +13,26 @@ static inline uint32_t min(uint32_t a, uint32_t b) { return a < b ? a : b; } -typedef enum FF_A_PACKED WaylandProtocolType { +typedef enum WaylandProtocolType: uint8_t { FF_WAYLAND_PROTOCOL_TYPE_NONE, FF_WAYLAND_PROTOCOL_TYPE_GLOBAL, FF_WAYLAND_PROTOCOL_TYPE_KDE_DEPRECATED, FF_WAYLAND_PROTOCOL_TYPE_KDE_REGISTRY, } WaylandProtocolType; +// In case users have an ancient version of libwayland-client +int wl_display_dispatch_timeout(struct wl_display *display, const struct timespec *timeout); + typedef struct WaylandData { FFDisplayServerResult* result; FF_LIBRARY_SYMBOL(wl_proxy_marshal_constructor_versioned) FF_LIBRARY_SYMBOL(wl_proxy_add_listener) FF_LIBRARY_SYMBOL(wl_proxy_destroy) FF_LIBRARY_SYMBOL(wl_display_roundtrip) + union { + FF_LIBRARY_SYMBOL(wl_display_dispatch) + FF_LIBRARY_SYMBOL(wl_display_dispatch_timeout) + }; struct wl_display* display; WaylandProtocolType protocolType; struct wl_proxy* zxdgOutputManager; @@ -58,12 +65,9 @@ typedef struct WaylandDisplay { FFstrbuf serial; uint8_t bitDepth; bool primary; + bool done; } WaylandDisplay; -inline static void stubListener(void* data, ...) { - (void) data; -} - inline static uint64_t ffWaylandGenerateIdFromName(const char* name) { uint64_t id = 0; size_t len = strlen(name); @@ -75,10 +79,11 @@ inline static uint64_t ffWaylandGenerateIdFromName(const char* name) { return id; } -void ffWaylandOutputNameListener(void* data, FF_A_UNUSED void* output, const char* name); -void ffWaylandOutputDescriptionListener(void* data, FF_A_UNUSED void* output, const char* description); +void ffWaylandOutputNameListener(void* data, [[maybe_unused]] void* output, const char* name); +void ffWaylandOutputDescriptionListener(void* data, [[maybe_unused]] void* output, const char* description); // Modifies content of display. Don't call this function when calling ffdsAppendDisplay uint32_t ffWaylandHandleRotation(WaylandDisplay* display); +const char* ffWaylandWaitForDone(WaylandDisplay* display); const char* ffWaylandHandleGlobalOutput(WaylandData* wldata, struct wl_registry* registry, uint32_t name, uint32_t version); const char* ffWaylandHandleKdeOutputRegistry(WaylandData* wldata, struct wl_registry* registry, uint32_t name, uint32_t version); diff --git a/src/detection/displayserver/linux/wayland/wl-output-protocol.c b/src/detection/displayserver/linux/wayland/wl-output-protocol.c index 86701209ad..7f50c7e60a 100644 --- a/src/detection/displayserver/linux/wayland/wl-output-protocol.c +++ b/src/detection/displayserver/linux/wayland/wl-output-protocol.c @@ -52,38 +52,38 @@ extern const struct wl_interface wl_surface_interface; extern const struct wl_interface wl_touch_interface; static const struct wl_interface *wayland_types[] = { - NULL, - NULL, - NULL, - NULL, - NULL, - NULL, - NULL, - NULL, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, &wl_callback_interface, &wl_registry_interface, &wl_surface_interface, &wl_region_interface, &wl_buffer_interface, - NULL, - NULL, - NULL, - NULL, - NULL, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, &wl_shm_pool_interface, - NULL, - NULL, + nullptr, + nullptr, &wl_data_source_interface, &wl_surface_interface, &wl_surface_interface, - NULL, + nullptr, &wl_data_source_interface, - NULL, + nullptr, &wl_data_offer_interface, - NULL, + nullptr, &wl_surface_interface, - NULL, - NULL, + nullptr, + nullptr, &wl_data_offer_interface, &wl_data_offer_interface, &wl_data_source_interface, @@ -92,27 +92,27 @@ static const struct wl_interface *wayland_types[] = { &wl_shell_surface_interface, &wl_surface_interface, &wl_seat_interface, - NULL, + nullptr, &wl_seat_interface, - NULL, - NULL, + nullptr, + nullptr, &wl_surface_interface, - NULL, - NULL, - NULL, - NULL, - NULL, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, &wl_output_interface, &wl_seat_interface, - NULL, + nullptr, &wl_surface_interface, - NULL, - NULL, - NULL, + nullptr, + nullptr, + nullptr, &wl_output_interface, &wl_buffer_interface, - NULL, - NULL, + nullptr, + nullptr, &wl_callback_interface, &wl_region_interface, &wl_region_interface, @@ -121,27 +121,27 @@ static const struct wl_interface *wayland_types[] = { &wl_pointer_interface, &wl_keyboard_interface, &wl_touch_interface, - NULL, + nullptr, &wl_surface_interface, - NULL, - NULL, - NULL, + nullptr, + nullptr, + nullptr, &wl_surface_interface, - NULL, - NULL, - NULL, + nullptr, + nullptr, + nullptr, &wl_surface_interface, - NULL, + nullptr, &wl_surface_interface, - NULL, - NULL, + nullptr, + nullptr, &wl_surface_interface, - NULL, - NULL, + nullptr, + nullptr, &wl_surface_interface, - NULL, - NULL, - NULL, + nullptr, + nullptr, + nullptr, &wl_subsurface_interface, &wl_surface_interface, &wl_surface_interface, @@ -187,7 +187,7 @@ static const struct wl_message wl_callback_events[] = { WL_EXPORT const struct wl_interface wl_callback_interface = { "wl_callback", 1, - 0, NULL, + 0, nullptr, 1, wl_callback_events, }; @@ -199,7 +199,7 @@ static const struct wl_message wl_compositor_requests[] = { WL_EXPORT const struct wl_interface wl_compositor_interface = { "wl_compositor", 6, 2, wl_compositor_requests, - 0, NULL, + 0, nullptr, }; static const struct wl_message wl_shm_pool_requests[] = { @@ -211,7 +211,7 @@ static const struct wl_message wl_shm_pool_requests[] = { WL_EXPORT const struct wl_interface wl_shm_pool_interface = { "wl_shm_pool", 2, 3, wl_shm_pool_requests, - 0, NULL, + 0, nullptr, }; static const struct wl_message wl_shm_requests[] = { @@ -313,7 +313,7 @@ static const struct wl_message wl_data_device_manager_requests[] = { WL_EXPORT const struct wl_interface wl_data_device_manager_interface = { "wl_data_device_manager", 3, 2, wl_data_device_manager_requests, - 0, NULL, + 0, nullptr, }; static const struct wl_message wl_shell_requests[] = { @@ -323,7 +323,7 @@ static const struct wl_message wl_shell_requests[] = { WL_EXPORT const struct wl_interface wl_shell_interface = { "wl_shell", 1, 1, wl_shell_requests, - 0, NULL, + 0, nullptr, }; static const struct wl_message wl_shell_surface_requests[] = { @@ -488,7 +488,7 @@ static const struct wl_message wl_region_requests[] = { WL_EXPORT const struct wl_interface wl_region_interface = { "wl_region", 1, 3, wl_region_requests, - 0, NULL, + 0, nullptr, }; static const struct wl_message wl_subcompositor_requests[] = { @@ -499,7 +499,7 @@ static const struct wl_message wl_subcompositor_requests[] = { WL_EXPORT const struct wl_interface wl_subcompositor_interface = { "wl_subcompositor", 1, 2, wl_subcompositor_requests, - 0, NULL, + 0, nullptr, }; static const struct wl_message wl_subsurface_requests[] = { @@ -514,7 +514,7 @@ static const struct wl_message wl_subsurface_requests[] = { WL_EXPORT const struct wl_interface wl_subsurface_interface = { "wl_subsurface", 1, 6, wl_subsurface_requests, - 0, NULL, + 0, nullptr, }; static const struct wl_message wl_fixes_requests[] = { @@ -525,7 +525,7 @@ static const struct wl_message wl_fixes_requests[] = { WL_EXPORT const struct wl_interface wl_fixes_interface = { "wl_fixes", 1, 2, wl_fixes_requests, - 0, NULL, + 0, nullptr, }; #endif diff --git a/src/detection/displayserver/linux/wayland/wp-color-management-v1-client-protocol.h b/src/detection/displayserver/linux/wayland/wp-color-management-v1-client-protocol.h index 5db1d71216..0b8a4926b8 100644 --- a/src/detection/displayserver/linux/wayland/wp-color-management-v1-client-protocol.h +++ b/src/detection/displayserver/linux/wayland/wp-color-management-v1-client-protocol.h @@ -1059,7 +1059,7 @@ static inline void wp_color_manager_v1_destroy(struct wp_color_manager_v1 *wp_color_manager_v1) { wl_proxy_marshal_flags((struct wl_proxy *) wp_color_manager_v1, - WP_COLOR_MANAGER_V1_DESTROY, NULL, wl_proxy_get_version((struct wl_proxy *) wp_color_manager_v1), WL_MARSHAL_FLAG_DESTROY); + WP_COLOR_MANAGER_V1_DESTROY, nullptr, wl_proxy_get_version((struct wl_proxy *) wp_color_manager_v1), WL_MARSHAL_FLAG_DESTROY); } /** @@ -1076,7 +1076,7 @@ wp_color_manager_v1_get_output(struct wp_color_manager_v1 *wp_color_manager_v1, struct wl_proxy *id; id = wl_proxy_marshal_flags((struct wl_proxy *) wp_color_manager_v1, - WP_COLOR_MANAGER_V1_GET_OUTPUT, &wp_color_management_output_v1_interface, wl_proxy_get_version((struct wl_proxy *) wp_color_manager_v1), 0, NULL, output); + WP_COLOR_MANAGER_V1_GET_OUTPUT, &wp_color_management_output_v1_interface, wl_proxy_get_version((struct wl_proxy *) wp_color_manager_v1), 0, nullptr, output); return (struct wp_color_management_output_v1 *) id; } @@ -1098,7 +1098,7 @@ wp_color_manager_v1_get_surface(struct wp_color_manager_v1 *wp_color_manager_v1, struct wl_proxy *id; id = wl_proxy_marshal_flags((struct wl_proxy *) wp_color_manager_v1, - WP_COLOR_MANAGER_V1_GET_SURFACE, &wp_color_management_surface_v1_interface, wl_proxy_get_version((struct wl_proxy *) wp_color_manager_v1), 0, NULL, surface); + WP_COLOR_MANAGER_V1_GET_SURFACE, &wp_color_management_surface_v1_interface, wl_proxy_get_version((struct wl_proxy *) wp_color_manager_v1), 0, nullptr, surface); return (struct wp_color_management_surface_v1 *) id; } @@ -1118,7 +1118,7 @@ wp_color_manager_v1_get_surface_feedback(struct wp_color_manager_v1 *wp_color_ma struct wl_proxy *id; id = wl_proxy_marshal_flags((struct wl_proxy *) wp_color_manager_v1, - WP_COLOR_MANAGER_V1_GET_SURFACE_FEEDBACK, &wp_color_management_surface_feedback_v1_interface, wl_proxy_get_version((struct wl_proxy *) wp_color_manager_v1), 0, NULL, surface); + WP_COLOR_MANAGER_V1_GET_SURFACE_FEEDBACK, &wp_color_management_surface_feedback_v1_interface, wl_proxy_get_version((struct wl_proxy *) wp_color_manager_v1), 0, nullptr, surface); return (struct wp_color_management_surface_feedback_v1 *) id; } @@ -1141,7 +1141,7 @@ wp_color_manager_v1_create_icc_creator(struct wp_color_manager_v1 *wp_color_mana struct wl_proxy *obj; obj = wl_proxy_marshal_flags((struct wl_proxy *) wp_color_manager_v1, - WP_COLOR_MANAGER_V1_CREATE_ICC_CREATOR, &wp_image_description_creator_icc_v1_interface, wl_proxy_get_version((struct wl_proxy *) wp_color_manager_v1), 0, NULL); + WP_COLOR_MANAGER_V1_CREATE_ICC_CREATOR, &wp_image_description_creator_icc_v1_interface, wl_proxy_get_version((struct wl_proxy *) wp_color_manager_v1), 0, nullptr); return (struct wp_image_description_creator_icc_v1 *) obj; } @@ -1164,7 +1164,7 @@ wp_color_manager_v1_create_parametric_creator(struct wp_color_manager_v1 *wp_col struct wl_proxy *obj; obj = wl_proxy_marshal_flags((struct wl_proxy *) wp_color_manager_v1, - WP_COLOR_MANAGER_V1_CREATE_PARAMETRIC_CREATOR, &wp_image_description_creator_params_v1_interface, wl_proxy_get_version((struct wl_proxy *) wp_color_manager_v1), 0, NULL); + WP_COLOR_MANAGER_V1_CREATE_PARAMETRIC_CREATOR, &wp_image_description_creator_params_v1_interface, wl_proxy_get_version((struct wl_proxy *) wp_color_manager_v1), 0, nullptr); return (struct wp_image_description_creator_params_v1 *) obj; } @@ -1223,7 +1223,7 @@ wp_color_manager_v1_create_windows_scrgb(struct wp_color_manager_v1 *wp_color_ma struct wl_proxy *image_description; image_description = wl_proxy_marshal_flags((struct wl_proxy *) wp_color_manager_v1, - WP_COLOR_MANAGER_V1_CREATE_WINDOWS_SCRGB, &wp_image_description_v1_interface, wl_proxy_get_version((struct wl_proxy *) wp_color_manager_v1), 0, NULL); + WP_COLOR_MANAGER_V1_CREATE_WINDOWS_SCRGB, &wp_image_description_v1_interface, wl_proxy_get_version((struct wl_proxy *) wp_color_manager_v1), 0, nullptr); return (struct wp_image_description_v1 *) image_description; } @@ -1242,7 +1242,7 @@ wp_color_manager_v1_get_image_description(struct wp_color_manager_v1 *wp_color_m struct wl_proxy *image_description; image_description = wl_proxy_marshal_flags((struct wl_proxy *) wp_color_manager_v1, - WP_COLOR_MANAGER_V1_GET_IMAGE_DESCRIPTION, &wp_image_description_v1_interface, wl_proxy_get_version((struct wl_proxy *) wp_color_manager_v1), 0, NULL, reference); + WP_COLOR_MANAGER_V1_GET_IMAGE_DESCRIPTION, &wp_image_description_v1_interface, wl_proxy_get_version((struct wl_proxy *) wp_color_manager_v1), 0, nullptr, reference); return (struct wp_image_description_v1 *) image_description; } @@ -1325,7 +1325,7 @@ static inline void wp_color_management_output_v1_destroy(struct wp_color_management_output_v1 *wp_color_management_output_v1) { wl_proxy_marshal_flags((struct wl_proxy *) wp_color_management_output_v1, - WP_COLOR_MANAGEMENT_OUTPUT_V1_DESTROY, NULL, wl_proxy_get_version((struct wl_proxy *) wp_color_management_output_v1), WL_MARSHAL_FLAG_DESTROY); + WP_COLOR_MANAGEMENT_OUTPUT_V1_DESTROY, nullptr, wl_proxy_get_version((struct wl_proxy *) wp_color_management_output_v1), WL_MARSHAL_FLAG_DESTROY); } /** @@ -1369,7 +1369,7 @@ wp_color_management_output_v1_get_image_description(struct wp_color_management_o struct wl_proxy *image_description; image_description = wl_proxy_marshal_flags((struct wl_proxy *) wp_color_management_output_v1, - WP_COLOR_MANAGEMENT_OUTPUT_V1_GET_IMAGE_DESCRIPTION, &wp_image_description_v1_interface, wl_proxy_get_version((struct wl_proxy *) wp_color_management_output_v1), 0, NULL); + WP_COLOR_MANAGEMENT_OUTPUT_V1_GET_IMAGE_DESCRIPTION, &wp_image_description_v1_interface, wl_proxy_get_version((struct wl_proxy *) wp_color_management_output_v1), 0, nullptr); return (struct wp_image_description_v1 *) image_description; } @@ -1444,7 +1444,7 @@ static inline void wp_color_management_surface_v1_destroy(struct wp_color_management_surface_v1 *wp_color_management_surface_v1) { wl_proxy_marshal_flags((struct wl_proxy *) wp_color_management_surface_v1, - WP_COLOR_MANAGEMENT_SURFACE_V1_DESTROY, NULL, wl_proxy_get_version((struct wl_proxy *) wp_color_management_surface_v1), WL_MARSHAL_FLAG_DESTROY); + WP_COLOR_MANAGEMENT_SURFACE_V1_DESTROY, nullptr, wl_proxy_get_version((struct wl_proxy *) wp_color_management_surface_v1), WL_MARSHAL_FLAG_DESTROY); } /** @@ -1494,7 +1494,7 @@ static inline void wp_color_management_surface_v1_set_image_description(struct wp_color_management_surface_v1 *wp_color_management_surface_v1, struct wp_image_description_v1 *image_description, uint32_t render_intent) { wl_proxy_marshal_flags((struct wl_proxy *) wp_color_management_surface_v1, - WP_COLOR_MANAGEMENT_SURFACE_V1_SET_IMAGE_DESCRIPTION, NULL, wl_proxy_get_version((struct wl_proxy *) wp_color_management_surface_v1), 0, image_description, render_intent); + WP_COLOR_MANAGEMENT_SURFACE_V1_SET_IMAGE_DESCRIPTION, nullptr, wl_proxy_get_version((struct wl_proxy *) wp_color_management_surface_v1), 0, image_description, render_intent); } /** @@ -1511,7 +1511,7 @@ static inline void wp_color_management_surface_v1_unset_image_description(struct wp_color_management_surface_v1 *wp_color_management_surface_v1) { wl_proxy_marshal_flags((struct wl_proxy *) wp_color_management_surface_v1, - WP_COLOR_MANAGEMENT_SURFACE_V1_UNSET_IMAGE_DESCRIPTION, NULL, wl_proxy_get_version((struct wl_proxy *) wp_color_management_surface_v1), 0); + WP_COLOR_MANAGEMENT_SURFACE_V1_UNSET_IMAGE_DESCRIPTION, nullptr, wl_proxy_get_version((struct wl_proxy *) wp_color_management_surface_v1), 0); } #ifndef WP_COLOR_MANAGEMENT_SURFACE_FEEDBACK_V1_ERROR_ENUM @@ -1647,7 +1647,7 @@ static inline void wp_color_management_surface_feedback_v1_destroy(struct wp_color_management_surface_feedback_v1 *wp_color_management_surface_feedback_v1) { wl_proxy_marshal_flags((struct wl_proxy *) wp_color_management_surface_feedback_v1, - WP_COLOR_MANAGEMENT_SURFACE_FEEDBACK_V1_DESTROY, NULL, wl_proxy_get_version((struct wl_proxy *) wp_color_management_surface_feedback_v1), WL_MARSHAL_FLAG_DESTROY); + WP_COLOR_MANAGEMENT_SURFACE_FEEDBACK_V1_DESTROY, nullptr, wl_proxy_get_version((struct wl_proxy *) wp_color_management_surface_feedback_v1), WL_MARSHAL_FLAG_DESTROY); } /** @@ -1693,7 +1693,7 @@ wp_color_management_surface_feedback_v1_get_preferred(struct wp_color_management struct wl_proxy *image_description; image_description = wl_proxy_marshal_flags((struct wl_proxy *) wp_color_management_surface_feedback_v1, - WP_COLOR_MANAGEMENT_SURFACE_FEEDBACK_V1_GET_PREFERRED, &wp_image_description_v1_interface, wl_proxy_get_version((struct wl_proxy *) wp_color_management_surface_feedback_v1), 0, NULL); + WP_COLOR_MANAGEMENT_SURFACE_FEEDBACK_V1_GET_PREFERRED, &wp_image_description_v1_interface, wl_proxy_get_version((struct wl_proxy *) wp_color_management_surface_feedback_v1), 0, nullptr); return (struct wp_image_description_v1 *) image_description; } @@ -1714,7 +1714,7 @@ wp_color_management_surface_feedback_v1_get_preferred_parametric(struct wp_color struct wl_proxy *image_description; image_description = wl_proxy_marshal_flags((struct wl_proxy *) wp_color_management_surface_feedback_v1, - WP_COLOR_MANAGEMENT_SURFACE_FEEDBACK_V1_GET_PREFERRED_PARAMETRIC, &wp_image_description_v1_interface, wl_proxy_get_version((struct wl_proxy *) wp_color_management_surface_feedback_v1), 0, NULL); + WP_COLOR_MANAGEMENT_SURFACE_FEEDBACK_V1_GET_PREFERRED_PARAMETRIC, &wp_image_description_v1_interface, wl_proxy_get_version((struct wl_proxy *) wp_color_management_surface_feedback_v1), 0, nullptr); return (struct wp_image_description_v1 *) image_description; } @@ -1818,7 +1818,7 @@ wp_image_description_creator_icc_v1_create(struct wp_image_description_creator_i struct wl_proxy *image_description; image_description = wl_proxy_marshal_flags((struct wl_proxy *) wp_image_description_creator_icc_v1, - WP_IMAGE_DESCRIPTION_CREATOR_ICC_V1_CREATE, &wp_image_description_v1_interface, wl_proxy_get_version((struct wl_proxy *) wp_image_description_creator_icc_v1), WL_MARSHAL_FLAG_DESTROY, NULL); + WP_IMAGE_DESCRIPTION_CREATOR_ICC_V1_CREATE, &wp_image_description_v1_interface, wl_proxy_get_version((struct wl_proxy *) wp_image_description_creator_icc_v1), WL_MARSHAL_FLAG_DESTROY, nullptr); return (struct wp_image_description_v1 *) image_description; } @@ -1870,7 +1870,7 @@ static inline void wp_image_description_creator_icc_v1_set_icc_file(struct wp_image_description_creator_icc_v1 *wp_image_description_creator_icc_v1, int32_t icc_profile, uint32_t offset, uint32_t length) { wl_proxy_marshal_flags((struct wl_proxy *) wp_image_description_creator_icc_v1, - WP_IMAGE_DESCRIPTION_CREATOR_ICC_V1_SET_ICC_FILE, NULL, wl_proxy_get_version((struct wl_proxy *) wp_image_description_creator_icc_v1), 0, icc_profile, offset, length); + WP_IMAGE_DESCRIPTION_CREATOR_ICC_V1_SET_ICC_FILE, nullptr, wl_proxy_get_version((struct wl_proxy *) wp_image_description_creator_icc_v1), 0, icc_profile, offset, length); } #ifndef WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_ERROR_ENUM @@ -2027,7 +2027,7 @@ wp_image_description_creator_params_v1_create(struct wp_image_description_creato struct wl_proxy *image_description; image_description = wl_proxy_marshal_flags((struct wl_proxy *) wp_image_description_creator_params_v1, - WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_CREATE, &wp_image_description_v1_interface, wl_proxy_get_version((struct wl_proxy *) wp_image_description_creator_params_v1), WL_MARSHAL_FLAG_DESTROY, NULL); + WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_CREATE, &wp_image_description_v1_interface, wl_proxy_get_version((struct wl_proxy *) wp_image_description_creator_params_v1), WL_MARSHAL_FLAG_DESTROY, nullptr); return (struct wp_image_description_v1 *) image_description; } @@ -2052,7 +2052,7 @@ static inline void wp_image_description_creator_params_v1_set_tf_named(struct wp_image_description_creator_params_v1 *wp_image_description_creator_params_v1, uint32_t tf) { wl_proxy_marshal_flags((struct wl_proxy *) wp_image_description_creator_params_v1, - WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_SET_TF_NAMED, NULL, wl_proxy_get_version((struct wl_proxy *) wp_image_description_creator_params_v1), 0, tf); + WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_SET_TF_NAMED, nullptr, wl_proxy_get_version((struct wl_proxy *) wp_image_description_creator_params_v1), 0, tf); } /** @@ -2081,7 +2081,7 @@ static inline void wp_image_description_creator_params_v1_set_tf_power(struct wp_image_description_creator_params_v1 *wp_image_description_creator_params_v1, uint32_t eexp) { wl_proxy_marshal_flags((struct wl_proxy *) wp_image_description_creator_params_v1, - WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_SET_TF_POWER, NULL, wl_proxy_get_version((struct wl_proxy *) wp_image_description_creator_params_v1), 0, eexp); + WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_SET_TF_POWER, nullptr, wl_proxy_get_version((struct wl_proxy *) wp_image_description_creator_params_v1), 0, eexp); } /** @@ -2102,7 +2102,7 @@ static inline void wp_image_description_creator_params_v1_set_primaries_named(struct wp_image_description_creator_params_v1 *wp_image_description_creator_params_v1, uint32_t primaries) { wl_proxy_marshal_flags((struct wl_proxy *) wp_image_description_creator_params_v1, - WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_SET_PRIMARIES_NAMED, NULL, wl_proxy_get_version((struct wl_proxy *) wp_image_description_creator_params_v1), 0, primaries); + WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_SET_PRIMARIES_NAMED, nullptr, wl_proxy_get_version((struct wl_proxy *) wp_image_description_creator_params_v1), 0, primaries); } /** @@ -2126,7 +2126,7 @@ static inline void wp_image_description_creator_params_v1_set_primaries(struct wp_image_description_creator_params_v1 *wp_image_description_creator_params_v1, int32_t r_x, int32_t r_y, int32_t g_x, int32_t g_y, int32_t b_x, int32_t b_y, int32_t w_x, int32_t w_y) { wl_proxy_marshal_flags((struct wl_proxy *) wp_image_description_creator_params_v1, - WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_SET_PRIMARIES, NULL, wl_proxy_get_version((struct wl_proxy *) wp_image_description_creator_params_v1), 0, r_x, r_y, g_x, g_y, b_x, b_y, w_x, w_y); + WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_SET_PRIMARIES, nullptr, wl_proxy_get_version((struct wl_proxy *) wp_image_description_creator_params_v1), 0, r_x, r_y, g_x, g_y, b_x, b_y, w_x, w_y); } /** @@ -2186,7 +2186,7 @@ static inline void wp_image_description_creator_params_v1_set_luminances(struct wp_image_description_creator_params_v1 *wp_image_description_creator_params_v1, uint32_t min_lum, uint32_t max_lum, uint32_t reference_lum) { wl_proxy_marshal_flags((struct wl_proxy *) wp_image_description_creator_params_v1, - WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_SET_LUMINANCES, NULL, wl_proxy_get_version((struct wl_proxy *) wp_image_description_creator_params_v1), 0, min_lum, max_lum, reference_lum); + WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_SET_LUMINANCES, nullptr, wl_proxy_get_version((struct wl_proxy *) wp_image_description_creator_params_v1), 0, min_lum, max_lum, reference_lum); } /** @@ -2243,7 +2243,7 @@ static inline void wp_image_description_creator_params_v1_set_mastering_display_primaries(struct wp_image_description_creator_params_v1 *wp_image_description_creator_params_v1, int32_t r_x, int32_t r_y, int32_t g_x, int32_t g_y, int32_t b_x, int32_t b_y, int32_t w_x, int32_t w_y) { wl_proxy_marshal_flags((struct wl_proxy *) wp_image_description_creator_params_v1, - WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_SET_MASTERING_DISPLAY_PRIMARIES, NULL, wl_proxy_get_version((struct wl_proxy *) wp_image_description_creator_params_v1), 0, r_x, r_y, g_x, g_y, b_x, b_y, w_x, w_y); + WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_SET_MASTERING_DISPLAY_PRIMARIES, nullptr, wl_proxy_get_version((struct wl_proxy *) wp_image_description_creator_params_v1), 0, r_x, r_y, g_x, g_y, b_x, b_y, w_x, w_y); } /** @@ -2287,7 +2287,7 @@ static inline void wp_image_description_creator_params_v1_set_mastering_luminance(struct wp_image_description_creator_params_v1 *wp_image_description_creator_params_v1, uint32_t min_lum, uint32_t max_lum) { wl_proxy_marshal_flags((struct wl_proxy *) wp_image_description_creator_params_v1, - WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_SET_MASTERING_LUMINANCE, NULL, wl_proxy_get_version((struct wl_proxy *) wp_image_description_creator_params_v1), 0, min_lum, max_lum); + WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_SET_MASTERING_LUMINANCE, nullptr, wl_proxy_get_version((struct wl_proxy *) wp_image_description_creator_params_v1), 0, min_lum, max_lum); } /** @@ -2301,7 +2301,7 @@ static inline void wp_image_description_creator_params_v1_set_max_cll(struct wp_image_description_creator_params_v1 *wp_image_description_creator_params_v1, uint32_t max_cll) { wl_proxy_marshal_flags((struct wl_proxy *) wp_image_description_creator_params_v1, - WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_SET_MAX_CLL, NULL, wl_proxy_get_version((struct wl_proxy *) wp_image_description_creator_params_v1), 0, max_cll); + WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_SET_MAX_CLL, nullptr, wl_proxy_get_version((struct wl_proxy *) wp_image_description_creator_params_v1), 0, max_cll); } /** @@ -2316,7 +2316,7 @@ static inline void wp_image_description_creator_params_v1_set_max_fall(struct wp_image_description_creator_params_v1 *wp_image_description_creator_params_v1, uint32_t max_fall) { wl_proxy_marshal_flags((struct wl_proxy *) wp_image_description_creator_params_v1, - WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_SET_MAX_FALL, NULL, wl_proxy_get_version((struct wl_proxy *) wp_image_description_creator_params_v1), 0, max_fall); + WP_IMAGE_DESCRIPTION_CREATOR_PARAMS_V1_SET_MAX_FALL, nullptr, wl_proxy_get_version((struct wl_proxy *) wp_image_description_creator_params_v1), 0, max_fall); } #ifndef WP_IMAGE_DESCRIPTION_V1_ERROR_ENUM @@ -2515,7 +2515,7 @@ static inline void wp_image_description_v1_destroy(struct wp_image_description_v1 *wp_image_description_v1) { wl_proxy_marshal_flags((struct wl_proxy *) wp_image_description_v1, - WP_IMAGE_DESCRIPTION_V1_DESTROY, NULL, wl_proxy_get_version((struct wl_proxy *) wp_image_description_v1), WL_MARSHAL_FLAG_DESTROY); + WP_IMAGE_DESCRIPTION_V1_DESTROY, nullptr, wl_proxy_get_version((struct wl_proxy *) wp_image_description_v1), WL_MARSHAL_FLAG_DESTROY); } /** @@ -2535,7 +2535,7 @@ wp_image_description_v1_get_information(struct wp_image_description_v1 *wp_image struct wl_proxy *information; information = wl_proxy_marshal_flags((struct wl_proxy *) wp_image_description_v1, - WP_IMAGE_DESCRIPTION_V1_GET_INFORMATION, &wp_image_description_info_v1_interface, wl_proxy_get_version((struct wl_proxy *) wp_image_description_v1), 0, NULL); + WP_IMAGE_DESCRIPTION_V1_GET_INFORMATION, &wp_image_description_info_v1_interface, wl_proxy_get_version((struct wl_proxy *) wp_image_description_v1), 0, nullptr); return (struct wp_image_description_info_v1 *) information; } @@ -2861,7 +2861,7 @@ static inline void wp_image_description_reference_v1_destroy(struct wp_image_description_reference_v1 *wp_image_description_reference_v1) { wl_proxy_marshal_flags((struct wl_proxy *) wp_image_description_reference_v1, - WP_IMAGE_DESCRIPTION_REFERENCE_V1_DESTROY, NULL, wl_proxy_get_version((struct wl_proxy *) wp_image_description_reference_v1), WL_MARSHAL_FLAG_DESTROY); + WP_IMAGE_DESCRIPTION_REFERENCE_V1_DESTROY, nullptr, wl_proxy_get_version((struct wl_proxy *) wp_image_description_reference_v1), WL_MARSHAL_FLAG_DESTROY); } #ifdef __cplusplus diff --git a/src/detection/displayserver/linux/wayland/wp-color-management-v1-protocol.c b/src/detection/displayserver/linux/wayland/wp-color-management-v1-protocol.c index fd2ce26bd5..b57873782d 100644 --- a/src/detection/displayserver/linux/wayland/wp-color-management-v1-protocol.c +++ b/src/detection/displayserver/linux/wayland/wp-color-management-v1-protocol.c @@ -47,14 +47,14 @@ extern const struct wl_interface wp_image_description_reference_v1_interface; extern const struct wl_interface wp_image_description_v1_interface; static const struct wl_interface *color_management_v1_types[] = { - NULL, - NULL, - NULL, - NULL, - NULL, - NULL, - NULL, - NULL, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, &wp_color_management_output_v1_interface, &wl_output_interface, &wp_color_management_surface_v1_interface, @@ -68,7 +68,7 @@ static const struct wl_interface *color_management_v1_types[] = { &wp_image_description_reference_v1_interface, &wp_image_description_v1_interface, &wp_image_description_v1_interface, - NULL, + nullptr, &wp_image_description_v1_interface, &wp_image_description_v1_interface, &wp_image_description_v1_interface, @@ -125,7 +125,7 @@ static const struct wl_message wp_color_management_surface_v1_requests[] = { WL_EXPORT const struct wl_interface wp_color_management_surface_v1_interface = { "wp_color_management_surface_v1", 2, 3, wp_color_management_surface_v1_requests, - 0, NULL, + 0, nullptr, }; static const struct wl_message wp_color_management_surface_feedback_v1_requests[] = { @@ -153,7 +153,7 @@ static const struct wl_message wp_image_description_creator_icc_v1_requests[] = WL_EXPORT const struct wl_interface wp_image_description_creator_icc_v1_interface = { "wp_image_description_creator_icc_v1", 2, 2, wp_image_description_creator_icc_v1_requests, - 0, NULL, + 0, nullptr, }; static const struct wl_message wp_image_description_creator_params_v1_requests[] = { @@ -172,7 +172,7 @@ static const struct wl_message wp_image_description_creator_params_v1_requests[] WL_EXPORT const struct wl_interface wp_image_description_creator_params_v1_interface = { "wp_image_description_creator_params_v1", 2, 10, wp_image_description_creator_params_v1_requests, - 0, NULL, + 0, nullptr, }; static const struct wl_message wp_image_description_v1_requests[] = { @@ -208,7 +208,7 @@ static const struct wl_message wp_image_description_info_v1_events[] = { WL_EXPORT const struct wl_interface wp_image_description_info_v1_interface = { "wp_image_description_info_v1", 2, - 0, NULL, + 0, nullptr, 11, wp_image_description_info_v1_events, }; @@ -219,7 +219,7 @@ static const struct wl_message wp_image_description_reference_v1_requests[] = { WL_EXPORT const struct wl_interface wp_image_description_reference_v1_interface = { "wp_image_description_reference_v1", 1, 1, wp_image_description_reference_v1_requests, - 0, NULL, + 0, nullptr, }; #endif diff --git a/src/detection/displayserver/linux/wayland/xdg-output-unstable-v1-client-protocol.h b/src/detection/displayserver/linux/wayland/xdg-output-unstable-v1-client-protocol.h index 51784c6c13..2998d51a02 100644 --- a/src/detection/displayserver/linux/wayland/xdg-output-unstable-v1-client-protocol.h +++ b/src/detection/displayserver/linux/wayland/xdg-output-unstable-v1-client-protocol.h @@ -172,7 +172,7 @@ extern const struct wl_interface zxdg_output_v1_interface; // zxdg_output_manager_v1_destroy(struct zxdg_output_manager_v1 *zxdg_output_manager_v1) // { // wl_proxy_marshal_flags((struct wl_proxy *) zxdg_output_manager_v1, -// ZXDG_OUTPUT_MANAGER_V1_DESTROY, NULL, wl_proxy_get_version((struct wl_proxy *) zxdg_output_manager_v1), WL_MARSHAL_FLAG_DESTROY); +// ZXDG_OUTPUT_MANAGER_V1_DESTROY, nullptr, wl_proxy_get_version((struct wl_proxy *) zxdg_output_manager_v1), WL_MARSHAL_FLAG_DESTROY); // } // /** @@ -186,7 +186,7 @@ extern const struct wl_interface zxdg_output_v1_interface; // struct wl_proxy *id; // id = wl_proxy_marshal_flags((struct wl_proxy *) zxdg_output_manager_v1, -// ZXDG_OUTPUT_MANAGER_V1_GET_XDG_OUTPUT, &zxdg_output_v1_interface, wl_proxy_get_version((struct wl_proxy *) zxdg_output_manager_v1), 0, NULL, output); +// ZXDG_OUTPUT_MANAGER_V1_GET_XDG_OUTPUT, &zxdg_output_v1_interface, wl_proxy_get_version((struct wl_proxy *) zxdg_output_manager_v1), 0, nullptr, output); // return (struct zxdg_output_v1 *) id; // } @@ -404,7 +404,7 @@ zxdg_output_v1_add_listener(struct zxdg_output_v1* zxdg_output_v1, // zxdg_output_v1_destroy(struct zxdg_output_v1 *zxdg_output_v1) // { // wl_proxy_marshal_flags((struct wl_proxy *) zxdg_output_v1, -// ZXDG_OUTPUT_V1_DESTROY, NULL, wl_proxy_get_version((struct wl_proxy *) zxdg_output_v1), WL_MARSHAL_FLAG_DESTROY); +// ZXDG_OUTPUT_V1_DESTROY, nullptr, wl_proxy_get_version((struct wl_proxy *) zxdg_output_v1), WL_MARSHAL_FLAG_DESTROY); // } #ifdef __cplusplus diff --git a/src/detection/displayserver/linux/wayland/xdg-output-unstable-v1-protocol.c b/src/detection/displayserver/linux/wayland/xdg-output-unstable-v1-protocol.c index fb1273e63f..64367f1db1 100644 --- a/src/detection/displayserver/linux/wayland/xdg-output-unstable-v1-protocol.c +++ b/src/detection/displayserver/linux/wayland/xdg-output-unstable-v1-protocol.c @@ -32,8 +32,8 @@ extern const struct wl_interface wl_output_interface; extern const struct wl_interface zxdg_output_v1_interface; static const struct wl_interface* xdg_output_unstable_v1_types[] = { - NULL, - NULL, + nullptr, + nullptr, &zxdg_output_v1_interface, &wl_output_interface, }; @@ -49,7 +49,7 @@ WL_EXPORT const struct wl_interface zxdg_output_manager_v1_interface = { 2, zxdg_output_manager_v1_requests, 0, - NULL, + nullptr, }; static const struct wl_message zxdg_output_v1_requests[] = { diff --git a/src/detection/displayserver/linux/wmde.c b/src/detection/displayserver/linux/wmde.c index f0321c8ada..8044c4a95a 100644 --- a/src/detection/displayserver/linux/wmde.c +++ b/src/detection/displayserver/linux/wmde.c @@ -51,39 +51,39 @@ static const char* parseEnv(void) { return env; } - if (getenv("KDE_FULL_SESSION") != NULL || getenv("KDE_SESSION_UID") != NULL || getenv("KDE_SESSION_VERSION") != NULL) { + if (getenv("KDE_FULL_SESSION") != nullptr || getenv("KDE_SESSION_UID") != nullptr || getenv("KDE_SESSION_VERSION") != nullptr) { return "KDE"; } - if (getenv("GNOME_DESKTOP_SESSION_ID") != NULL) { + if (getenv("GNOME_DESKTOP_SESSION_ID") != nullptr) { return "GNOME"; } - if (getenv("MATE_DESKTOP_SESSION_ID") != NULL) { + if (getenv("MATE_DESKTOP_SESSION_ID") != nullptr) { return "Mate"; } - if (getenv("TDE_FULL_SESSION") != NULL) { + if (getenv("TDE_FULL_SESSION") != nullptr) { return "Trinity"; } - if (getenv("HYPRLAND_CMD") != NULL) { + if (getenv("HYPRLAND_CMD") != nullptr) { return "Hyprland"; } - if (getenv("SWAYSOCK") != NULL) { + if (getenv("SWAYSOCK") != nullptr) { return "Sway"; } #if __linux__ && !__ANDROID__ if ( - getenv("WAYLAND_DISPLAY") != NULL && + getenv("WAYLAND_DISPLAY") != nullptr && ffPathExists("/mnt/wslg/", FF_PATHTYPE_DIRECTORY)) { return "WSLg"; } #endif - return NULL; + return nullptr; } static void applyPrettyNameIfWM(FFDisplayServerResult* result, const char* name) { @@ -285,12 +285,12 @@ static const char* getFromProcesses(FFDisplayServerResult* result) { int request[] = { CTL_KERN, KERN_PROC, KERN_PROC_UID, (int) userId }; size_t length = 0; - if (sysctl(request, ARRAY_SIZE(request), NULL, &length, NULL, 0) != 0) { - return "sysctl({CTL_KERN, KERN_PROC, KERN_PROC_UID}, NULL) failed"; + if (sysctl(request, ARRAY_SIZE(request), nullptr, &length, nullptr, 0) != 0) { + return "sysctl({CTL_KERN, KERN_PROC, KERN_PROC_UID}, nullptr) failed"; } FF_AUTO_FREE struct kinfo_proc* procs = (struct kinfo_proc*) malloc(length); - if (sysctl(request, ARRAY_SIZE(request), procs, &length, NULL, 0) != 0) { + if (sysctl(request, ARRAY_SIZE(request), procs, &length, nullptr, 0) != 0) { return "sysctl({CTL_KERN, KERN_PROC, KERN_PROC_UID}, procs) failed"; } @@ -310,7 +310,7 @@ static const char* getFromProcesses(FFDisplayServerResult* result) { } } #elif __OpenBSD__ - kvm_t* kd = kvm_open(NULL, NULL, NULL, KVM_NO_FILES, NULL); + kvm_t* kd = kvm_open(nullptr, nullptr, nullptr, KVM_NO_FILES, nullptr); int count = 0; const struct kinfo_proc* proc = kvm_getprocs(kd, KERN_PROC_UID, (int) userId, sizeof(*proc), &count); if (proc) { @@ -331,7 +331,7 @@ static const char* getFromProcesses(FFDisplayServerResult* result) { kvm_close(kd); #elif __sun FF_AUTO_CLOSE_DIR DIR* procdir = opendir("/proc"); - if (procdir == NULL) { + if (procdir == nullptr) { return "opendir(\"/proc\") failed"; } @@ -341,7 +341,7 @@ static const char* getFromProcesses(FFDisplayServerResult* result) { uint32_t procPathLength = procPath.length; struct dirent* dirent; - while ((dirent = readdir(procdir)) != NULL) { + while ((dirent = readdir(procdir)) != nullptr) { if (!ffCharIsDigit(dirent->d_name[0])) { continue; } @@ -371,7 +371,7 @@ static const char* getFromProcesses(FFDisplayServerResult* result) { } #elif __linux__ || __GNU__ FF_AUTO_CLOSE_DIR DIR* procdir = opendir("/proc"); - if (procdir == NULL) { + if (procdir == nullptr) { return "opendir(\"/proc\") failed"; } @@ -384,7 +384,7 @@ static const char* getFromProcesses(FFDisplayServerResult* result) { FF_STRBUF_AUTO_DESTROY processName = ffStrbufCreateA(256); // Some processes have large command lines (looking at you chrome) struct dirent* dirent; - while ((dirent = readdir(procdir)) != NULL) { + while ((dirent = readdir(procdir)) != nullptr) { // Match only folders starting with a number (the pid folders) if (dirent->d_type != DT_DIR || !ffCharIsDigit(dirent->d_name[0])) { continue; @@ -428,13 +428,13 @@ static const char* getFromProcesses(FFDisplayServerResult* result) { int request[] = { CTL_KERN, KERN_PROC2, KERN_PROC_UID, (int) userId, sizeof(struct kinfo_proc2), INT_MAX }; size_t size = 0; - if (sysctl(request, ARRAY_SIZE(request), NULL, &size, NULL, 0) != 0) { - return "sysctl(KERN_PROC_UID, NULL) failed"; + if (sysctl(request, ARRAY_SIZE(request), nullptr, &size, nullptr, 0) != 0) { + return "sysctl(KERN_PROC_UID, nullptr) failed"; } FF_AUTO_FREE struct kinfo_proc2* procs = malloc(size); - if (sysctl(request, ARRAY_SIZE(request), procs, &size, NULL, 0) != 0) { + if (sysctl(request, ARRAY_SIZE(request), procs, &size, nullptr, 0) != 0) { return "sysctl(KERN_PROC_UID, procs) failed"; } @@ -453,7 +453,7 @@ static const char* getFromProcesses(FFDisplayServerResult* result) { } #endif - return NULL; + return nullptr; } void ffdsDetectWMDE(FFDisplayServerResult* result) { diff --git a/src/detection/displayserver/linux/xcb.c b/src/detection/displayserver/linux/xcb.c index 8ad663d173..f3c3711370 100644 --- a/src/detection/displayserver/linux/xcb.c +++ b/src/detection/displayserver/linux/xcb.c @@ -55,20 +55,20 @@ typedef struct XcbRandrData { static void* xcbGetProperty(XcbRandrData* data, xcb_window_t window, const char* request) { xcb_intern_atom_cookie_t requestAtomCookie = data->ffxcb_intern_atom(data->connection, true, (uint16_t) strlen(request), request); - FF_AUTO_FREE xcb_intern_atom_reply_t* requestAtomReply = data->ffxcb_intern_atom_reply(data->connection, requestAtomCookie, NULL); - if (requestAtomReply == NULL) { - return NULL; + FF_AUTO_FREE xcb_intern_atom_reply_t* requestAtomReply = data->ffxcb_intern_atom_reply(data->connection, requestAtomCookie, nullptr); + if (requestAtomReply == nullptr) { + return nullptr; } xcb_get_property_cookie_t propertyCookie = data->ffxcb_get_property(data->connection, false, window, requestAtomReply->atom, XCB_ATOM_ANY, 0, 8 * 1024); - FF_AUTO_FREE xcb_get_property_reply_t* propertyReply = data->ffxcb_get_property_reply(data->connection, propertyCookie, NULL); - if (propertyReply == NULL) { - return NULL; + FF_AUTO_FREE xcb_get_property_reply_t* propertyReply = data->ffxcb_get_property_reply(data->connection, propertyCookie, nullptr); + if (propertyReply == nullptr) { + return nullptr; } int length = data->ffxcb_get_property_value_length(propertyReply); if (length <= 0) { - return NULL; + return nullptr; } // Why are xcb property strings not null terminated??? @@ -81,13 +81,13 @@ static void* xcbGetProperty(XcbRandrData* data, xcb_window_t window, const char* static xcb_randr_get_output_property_reply_t* xcbRandrGetProperty(XcbRandrData* data, xcb_randr_output_t output, const char* name) { xcb_intern_atom_cookie_t requestAtomCookie = data->ffxcb_intern_atom(data->connection, true, (uint16_t) strlen(name), name); - FF_AUTO_FREE xcb_intern_atom_reply_t* requestAtomReply = data->ffxcb_intern_atom_reply(data->connection, requestAtomCookie, NULL); + FF_AUTO_FREE xcb_intern_atom_reply_t* requestAtomReply = data->ffxcb_intern_atom_reply(data->connection, requestAtomCookie, nullptr); if (requestAtomReply) { xcb_randr_get_output_property_cookie_t outputPropertyCookie = data->ffxcb_randr_get_output_property(data->connection, output, requestAtomReply->atom, XCB_GET_PROPERTY_TYPE_ANY, 0, 100, false, false); - return data->ffxcb_randr_get_output_property_reply(data->connection, outputPropertyCookie, NULL); + return data->ffxcb_randr_get_output_property_reply(data->connection, outputPropertyCookie, nullptr); } - return NULL; + return nullptr; } static void xcbDetectWMfromEWMH(XcbRandrData* data, xcb_window_t rootWindow, FFDisplayServerResult* result) { @@ -96,7 +96,7 @@ static void xcbDetectWMfromEWMH(XcbRandrData* data, xcb_window_t rootWindow, FFD } FF_AUTO_FREE xcb_window_t* wmWindow = (xcb_window_t*) xcbGetProperty(data, rootWindow, "_NET_SUPPORTING_WM_CHECK"); - if (wmWindow == NULL) { + if (wmWindow == nullptr) { return; } @@ -131,13 +131,13 @@ static void xcbFetchServerVendor(XcbRandrData* data, FFDisplayServerResult* resu static bool xcbRandrHandleOutput(XcbRandrData* data, xcb_randr_output_t output, FFstrbuf* name, bool primary, FFDisplayType displayType, struct xcb_randr_get_screen_resources_current_reply_t* screenResources, uint8_t bitDepth, uint32_t dpi) { xcb_randr_get_output_info_cookie_t outputInfoCookie = data->ffxcb_randr_get_output_info(data->connection, output, XCB_CURRENT_TIME); - FF_AUTO_FREE xcb_randr_get_output_info_reply_t* outputInfoReply = data->ffxcb_randr_get_output_info_reply(data->connection, outputInfoCookie, NULL); - if (outputInfoReply == NULL) { + FF_AUTO_FREE xcb_randr_get_output_info_reply_t* outputInfoReply = data->ffxcb_randr_get_output_info_reply(data->connection, outputInfoCookie, nullptr); + if (outputInfoReply == nullptr) { return false; } FF_AUTO_FREE xcb_randr_get_output_property_reply_t* edidReply = xcbRandrGetProperty(data, output, "EDID"); - uint8_t* edidData = NULL; + uint8_t* edidData = nullptr; uint32_t edidLength = 0; if (edidReply) { int len = data->ffxcb_randr_get_output_property_data_length(edidReply); @@ -162,8 +162,8 @@ static bool xcbRandrHandleOutput(XcbRandrData* data, xcb_randr_output_t output, } xcb_randr_get_crtc_info_cookie_t crtcInfoCookie = data->ffxcb_randr_get_crtc_info(data->connection, outputInfoReply->crtc, XCB_CURRENT_TIME); - FF_AUTO_FREE xcb_randr_get_crtc_info_reply_t* crtcInfoReply = data->ffxcb_randr_get_crtc_info_reply(data->connection, crtcInfoCookie, NULL); - if (crtcInfoReply == NULL) { + FF_AUTO_FREE xcb_randr_get_crtc_info_reply_t* crtcInfoReply = data->ffxcb_randr_get_crtc_info_reply(data->connection, crtcInfoCookie, nullptr); + if (crtcInfoReply == nullptr) { return false; } @@ -183,8 +183,8 @@ static bool xcbRandrHandleOutput(XcbRandrData* data, xcb_randr_output_t output, break; } - xcb_randr_mode_info_t* currentMode = NULL; - xcb_randr_mode_info_t* preferredMode = NULL; + xcb_randr_mode_info_t* currentMode = nullptr; + xcb_randr_mode_info_t* preferredMode = nullptr; if (screenResources) { xcb_randr_mode_info_iterator_t modesIterator = data->ffxcb_randr_get_screen_resources_current_modes_iterator(screenResources); @@ -253,7 +253,7 @@ static bool xcbRandrHandleMonitor(XcbRandrData* data, xcb_randr_monitor_info_t* FF_AUTO_FREE xcb_get_atom_name_reply_t* nameReply = data->ffxcb_get_atom_name_reply( data->connection, data->ffxcb_get_atom_name(data->connection, monitor->name), - NULL); + nullptr); FF_STRBUF_AUTO_DESTROY name = ffStrbufCreateNS( (uint32_t) data->ffxcb_get_atom_name_name_length(nameReply), data->ffxcb_get_atom_name_name(nameReply)); @@ -297,14 +297,14 @@ static bool xcbRandrHandleMonitor(XcbRandrData* data, xcb_randr_monitor_info_t* static bool xcbRandrHandleMonitors(XcbRandrData* data, xcb_screen_t* screen) { xcb_randr_get_monitors_cookie_t monitorsCookie = data->ffxcb_randr_get_monitors(data->connection, screen->root, true); - FF_AUTO_FREE xcb_randr_get_monitors_reply_t* monitorsReply = data->ffxcb_randr_get_monitors_reply(data->connection, monitorsCookie, NULL); - if (monitorsReply == NULL) { + FF_AUTO_FREE xcb_randr_get_monitors_reply_t* monitorsReply = data->ffxcb_randr_get_monitors_reply(data->connection, monitorsCookie, nullptr); + if (monitorsReply == nullptr) { return false; } - // Init screen resources. They are used to iterate over all modes. xcbRandrHandleMode checks for " == NULL", to fail as late as possible. + // Init screen resources. They are used to iterate over all modes. xcbRandrHandleMode checks for " == nullptr", to fail as late as possible. xcb_randr_get_screen_resources_current_cookie_t screenResourcesCookie = data->ffxcb_randr_get_screen_resources_current(data->connection, screen->root); - FF_AUTO_FREE struct xcb_randr_get_screen_resources_current_reply_t* screenResources = data->ffxcb_randr_get_screen_resources_current_reply(data->connection, screenResourcesCookie, NULL); + FF_AUTO_FREE struct xcb_randr_get_screen_resources_current_reply_t* screenResources = data->ffxcb_randr_get_screen_resources_current_reply(data->connection, screenResourcesCookie, nullptr); uint32_t dpi = 0; FF_AUTO_FREE const char* resourceManager = xcbGetProperty(data, screen->root, "RESOURCE_MANAGER"); @@ -347,7 +347,7 @@ static void xcbRandrHandleScreen(XcbRandrData* data, xcb_screen_t* screen) { 0, 0, 0, - NULL, + nullptr, FF_DISPLAY_TYPE_UNKNOWN, false, (uint64_t) screen->root, @@ -401,7 +401,7 @@ const char* ffdsConnectXcbRandr(FFDisplayServerResult* result) { FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(xcbRandr, data, xcb_randr_get_crtc_info) FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(xcbRandr, data, xcb_randr_get_crtc_info_reply) - data.connection = ffxcb_connect(NULL, NULL); + data.connection = ffxcb_connect(nullptr, nullptr); if (ffxcb_connection_has_error(data.connection) > 0) { ffxcb_disconnect(data.connection); return "xcb_connect() failed"; @@ -428,7 +428,7 @@ const char* ffdsConnectXcbRandr(FFDisplayServerResult* result) { ffStrbufSetS(&result->wmProtocolName, FF_WM_PROTOCOL_X11); } - return NULL; + return nullptr; } #else diff --git a/src/detection/displayserver/linux/xlib.c b/src/detection/displayserver/linux/xlib.c index 642a0d2f22..00ec05e403 100644 --- a/src/detection/displayserver/linux/xlib.c +++ b/src/detection/displayserver/linux/xlib.c @@ -34,15 +34,15 @@ typedef struct XrandrData { static unsigned char* x11GetProperty(XrandrData* data, Display* display, Window window, const char* request) { Atom requestAtom = data->ffXInternAtom(display, request, False); if (requestAtom == None) { - return NULL; + return nullptr; } Atom actualType; unsigned long unused; - unsigned char* result = NULL; + unsigned char* result = nullptr; if (data->ffXGetWindowProperty(display, window, requestAtom, 0, 64, False, AnyPropertyType, &actualType, (int*) &unused, &unused, &unused, &result) != Success) { - return NULL; + return nullptr; } return result; @@ -50,7 +50,7 @@ static unsigned char* x11GetProperty(XrandrData* data, Display* display, Window static uint8_t* xrandrGetProperty(XrandrData* data, RROutput output, const char* name, uint32_t* bufSize) { unsigned long size = 0; - uint8_t* result = NULL; + uint8_t* result = nullptr; Atom atomEdid = data->ffXInternAtom(data->display, name, true); if (atomEdid != None) { int actual_format = 0; @@ -68,7 +68,7 @@ static uint8_t* xrandrGetProperty(XrandrData* data, RROutput output, const char* } } - return NULL; + return nullptr; } static void x11DetectWMFromEWMH(XrandrData* data, FFDisplayServerResult* result) { @@ -77,7 +77,7 @@ static void x11DetectWMFromEWMH(XrandrData* data, FFDisplayServerResult* result) } Window* wmWindow = (Window*) x11GetProperty(data, data->display, DefaultRootWindow(data->display), "_NET_SUPPORTING_WM_CHECK"); - if (wmWindow == NULL) { + if (wmWindow == nullptr) { return; } @@ -103,12 +103,12 @@ static void x11FetchServerVendor(XrandrData* data, FFDisplayServerResult* result static bool xrandrHandleCrtc(XrandrData* data, XRROutputInfo* output, FFstrbuf* name, bool primary, FFDisplayType displayType, uint8_t* edidData, uint32_t edidLength, XRRScreenResources* screenResources, uint8_t bitDepth, uint32_t dpi, bool randrEmulation) { // We do the check here, because we want the best fallback display if this call failed - if (screenResources == NULL) { + if (screenResources == nullptr) { return false; } XRRCrtcInfo* crtcInfo = data->ffXRRGetCrtcInfo(data->display, screenResources, output->crtc); - if (crtcInfo == NULL) { + if (crtcInfo == nullptr) { return false; } @@ -128,7 +128,7 @@ static bool xrandrHandleCrtc(XrandrData* data, XRROutputInfo* output, FFstrbuf* break; } - XRRModeInfo* currentMode = NULL; + XRRModeInfo* currentMode = nullptr; for (int i = 0; i < screenResources->nmode; i++) { if (screenResources->modes[i].id == crtcInfo->mode) { currentMode = &screenResources->modes[i]; @@ -136,7 +136,7 @@ static bool xrandrHandleCrtc(XrandrData* data, XRROutputInfo* output, FFstrbuf* } } - XRRModeInfo* preferredMode = output->npreferred > 0 ? &screenResources->modes[0] : NULL; + XRRModeInfo* preferredMode = output->npreferred > 0 ? &screenResources->modes[0] : nullptr; FFDisplayResult* item = ffdsAppendDisplay( data->result, @@ -179,7 +179,7 @@ static bool xrandrHandleCrtc(XrandrData* data, XRROutputInfo* output, FFstrbuf* static bool xrandrHandleOutput(XrandrData* data, RROutput output, FFstrbuf* name, bool primary, FFDisplayType displayType, XRRScreenResources* screenResources, uint8_t bitDepth, uint32_t dpi) { XRROutputInfo* outputInfo = data->ffXRRGetOutputInfo(data->display, screenResources, output); - if (outputInfo == NULL) { + if (outputInfo == nullptr) { return false; } @@ -193,7 +193,7 @@ static bool xrandrHandleOutput(XrandrData* data, RROutput output, FFstrbuf* name edidLength = 0; } - uint8_t* randrEmulation = xrandrGetProperty(data, output, "RANDR Emulation", NULL); + uint8_t* randrEmulation = xrandrGetProperty(data, output, "RANDR Emulation", nullptr); bool res = xrandrHandleCrtc(data, outputInfo, name, primary, displayType, edidData, edidLength, screenResources, bitDepth, dpi, randrEmulation ? !!randrEmulation[0] : false); @@ -250,7 +250,7 @@ static bool xrandrHandleMonitor(XrandrData* data, XRRMonitorInfo* monitorInfo, X static bool xrandrHandleMonitors(XrandrData* data, Screen* screen) { int numberOfMonitors; XRRMonitorInfo* monitorInfos = data->ffXRRGetMonitors(data->display, RootWindowOfScreen(screen), True, &numberOfMonitors); - if (monitorInfos == NULL) { + if (monitorInfos == nullptr) { return false; } @@ -297,7 +297,7 @@ static void xrandrHandleScreen(XrandrData* data, Screen* screen) { 0, 0, 0, - NULL, + nullptr, FF_DISPLAY_TYPE_UNKNOWN, false, RootWindowOfScreen(screen), @@ -329,8 +329,8 @@ const char* ffdsConnectXrandr(FFDisplayServerResult* result) { FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(xrandr, data, XRRFreeScreenResources); FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(xrandr, data, XRRFreeMonitors); - data.display = ffXOpenDisplay(NULL); - if (data.display == NULL) { + data.display = ffXOpenDisplay(nullptr); + if (data.display == nullptr) { return "XOpenDisplay() failed"; } @@ -352,7 +352,7 @@ const char* ffdsConnectXrandr(FFDisplayServerResult* result) { ffStrbufSetS(&result->wmProtocolName, FF_WM_PROTOCOL_X11); } - return NULL; + return nullptr; } #else diff --git a/src/detection/dns/dns_apple.c b/src/detection/dns/dns_apple.c index e490ffe743..e04bb5256d 100644 --- a/src/detection/dns/dns_apple.c +++ b/src/detection/dns/dns_apple.c @@ -25,7 +25,7 @@ static const char* detectDnsFromConf(const char* path, FFDNSOptions* options, FF ffListClear(results); } - FF_AUTO_FREE char* line = NULL; + FF_AUTO_FREE char* line = nullptr; size_t len = 0; while (getline(&line, &len, file) != -1) { @@ -56,7 +56,7 @@ static const char* detectDnsFromConf(const char* path, FFDNSOptions* options, FF } FF_DEBUG("Found %u DNS servers in %s", results->length, path); - return NULL; + return nullptr; } const char* ffDetectDNS(FFDNSOptions* options, FFlist* results) { @@ -64,10 +64,10 @@ const char* ffDetectDNS(FFDNSOptions* options, FFlist* results) { FF_DEBUG("Using SystemConfiguration framework for macOS"); // Create a reference to the dynamic store - FF_CFTYPE_AUTO_RELEASE SCDynamicStoreRef store = SCDynamicStoreCreate(NULL, CFSTR("fastfetch"), NULL, NULL); + FF_CFTYPE_AUTO_RELEASE SCDynamicStoreRef store = SCDynamicStoreCreate(nullptr, CFSTR("fastfetch"), nullptr, nullptr); if (store) { // Get the network global IPv4 and IPv6 configuration - FF_CFTYPE_AUTO_RELEASE CFStringRef key = SCDynamicStoreKeyCreateNetworkGlobalEntity(NULL, kSCDynamicStoreDomainState, kSCEntNetDNS); + FF_CFTYPE_AUTO_RELEASE CFStringRef key = SCDynamicStoreKeyCreateNetworkGlobalEntity(nullptr, kSCDynamicStoreDomainState, kSCEntNetDNS); if (key) { FF_CFTYPE_AUTO_RELEASE CFDictionaryRef dict = SCDynamicStoreCopyValue(store, key); if (dict) { @@ -77,7 +77,7 @@ const char* ffDetectDNS(FFDNSOptions* options, FFlist* results) { if (dnsServers) { FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); for (CFIndex i = 0; i < CFArrayGetCount(dnsServers); i++) { - if (ffCfStrGetString(CFArrayGetValueAtIndex(dnsServers, i), &buffer) == NULL) { + if (ffCfStrGetString(CFArrayGetValueAtIndex(dnsServers, i), &buffer) == nullptr) { // Check if the address matches our filter if ((ffStrbufContainC(&buffer, ':') && !(options->showType & FF_DNS_TYPE_IPV6_BIT)) || (ffStrbufContainC(&buffer, '.') && !(options->showType & FF_DNS_TYPE_IPV4_BIT))) { @@ -97,7 +97,7 @@ const char* ffDetectDNS(FFDNSOptions* options, FFlist* results) { // If we didn't find any servers, try resolv.conf as fallback if (results->length > 0) { - return NULL; + return nullptr; } FF_DEBUG("No DNS servers found via SystemConfiguration, trying resolv.conf"); diff --git a/src/detection/dns/dns_linux.c b/src/detection/dns/dns_linux.c index 41e008cc21..a92057575e 100644 --- a/src/detection/dns/dns_linux.c +++ b/src/detection/dns/dns_linux.c @@ -28,7 +28,7 @@ static const char* detectDnsFromConf(const char* path, FFDNSOptions* options, FF ffListClear(results); } - FF_AUTO_FREE char* line = NULL; + FF_AUTO_FREE char* line = nullptr; size_t len = 0; while (getline(&line, &len, file) != -1) { @@ -59,14 +59,14 @@ static const char* detectDnsFromConf(const char* path, FFDNSOptions* options, FF } FF_DEBUG("Found %u DNS servers in %s", results->length, path); - return NULL; + return nullptr; } const char* ffDetectDNS(FFDNSOptions* options, FFlist* results) { FF_DEBUG("Starting DNS detection"); const char* error = detectDnsFromConf(FASTFETCH_TARGET_DIR_ROOT RESOLV_CONF, options, results); - if (error != NULL) { + if (error != nullptr) { FF_DEBUG("Error detecting DNS: %s", error); return error; } @@ -79,14 +79,14 @@ const char* ffDetectDNS(FFDNSOptions* options, FFlist* results) { if (ffStrbufEqualS(firstEntry, "127.0.0.53")) { FF_DEBUG("Detected systemd-resolved (127.0.0.53), checking actual DNS servers"); // Managed by systemd-resolved - if (detectDnsFromConf("/run/systemd/resolve/resolv.conf", options, results) == NULL) { - return NULL; + if (detectDnsFromConf("/run/systemd/resolve/resolv.conf", options, results) == nullptr) { + return nullptr; } } else if (ffStrbufEqualS(firstEntry, "127.0.0.1")) { FF_DEBUG("Detected possible NetworkManager (127.0.0.1), checking actual DNS servers"); // Managed by NetworkManager - if (detectDnsFromConf("/var/run/NetworkManager/resolv.conf", options, results) == NULL) { - return NULL; + if (detectDnsFromConf("/var/run/NetworkManager/resolv.conf", options, results) == nullptr) { + return nullptr; } } } @@ -97,20 +97,20 @@ const char* ffDetectDNS(FFDNSOptions* options, FFlist* results) { // Try resolvconf FF_DEBUG("Trying resolvconf configuration"); - if (detectDnsFromConf(FASTFETCH_TARGET_DIR_ROOT "/run/resolvconf/resolv.conf", options, results) == NULL && results->length > 0) { - return NULL; + if (detectDnsFromConf(FASTFETCH_TARGET_DIR_ROOT "/run/resolvconf/resolv.conf", options, results) == nullptr && results->length > 0) { + return nullptr; } // Try dnsmasq FF_DEBUG("Trying dnsmasq configuration"); - if (detectDnsFromConf(FASTFETCH_TARGET_DIR_ROOT "/var/run/dnsmasq/resolv.conf", options, results) == NULL && results->length > 0) { - return NULL; + if (detectDnsFromConf(FASTFETCH_TARGET_DIR_ROOT "/var/run/dnsmasq/resolv.conf", options, results) == nullptr && results->length > 0) { + return nullptr; } // Try openresolv FF_DEBUG("Trying openresolv configuration"); - if (detectDnsFromConf(FASTFETCH_TARGET_DIR_ROOT "/etc/resolv.conf.openresolv", options, results) == NULL && results->length > 0) { - return NULL; + if (detectDnsFromConf(FASTFETCH_TARGET_DIR_ROOT "/etc/resolv.conf.openresolv", options, results) == nullptr && results->length > 0) { + return nullptr; } } #elif defined(__FreeBSD__) || defined(__DragonFly__) || defined(__NetBSD__) || defined(__OpenBSD__) @@ -120,24 +120,24 @@ const char* ffDetectDNS(FFDNSOptions* options, FFlist* results) { // FreeBSD and other BSDs may use resolvconf service FF_DEBUG("Trying BSD resolvconf configuration"); - if (detectDnsFromConf(FASTFETCH_TARGET_DIR_ROOT "/var/run/resolvconf/resolv.conf", options, results) == NULL && results->length > 0) { - return NULL; + if (detectDnsFromConf(FASTFETCH_TARGET_DIR_ROOT "/var/run/resolvconf/resolv.conf", options, results) == nullptr && results->length > 0) { + return nullptr; } // Some BSDs store DNS configuration here FF_DEBUG("Trying BSD nameserver configuration"); - if (detectDnsFromConf(FASTFETCH_TARGET_DIR_ROOT "/var/run/nameserver", options, results) == NULL && results->length > 0) { - return NULL; + if (detectDnsFromConf(FASTFETCH_TARGET_DIR_ROOT "/var/run/nameserver", options, results) == nullptr && results->length > 0) { + return nullptr; } // Try common BSD paths FF_DEBUG("Trying BSD common paths"); - if (detectDnsFromConf(FASTFETCH_TARGET_DIR_ROOT "/etc/nameserver", options, results) == NULL && results->length > 0) { - return NULL; + if (detectDnsFromConf(FASTFETCH_TARGET_DIR_ROOT "/etc/nameserver", options, results) == nullptr && results->length > 0) { + return nullptr; } } #endif FF_DEBUG("DNS detection completed with %u servers found", results->length); - return NULL; + return nullptr; } diff --git a/src/detection/dns/dns_windows.c b/src/detection/dns/dns_windows.c index b28eefb9e1..4f63d91f9a 100644 --- a/src/detection/dns/dns_windows.c +++ b/src/detection/dns/dns_windows.c @@ -6,7 +6,7 @@ #include const char* ffDetectDNS(FFDNSOptions* options, FFlist* results) { - IP_ADAPTER_ADDRESSES* FF_AUTO_FREE adapter_addresses = NULL; + FF_AUTO_FREE IP_ADAPTER_ADDRESSES* adapter_addresses = nullptr; // Multiple attempts in case interfaces change while // we are in the middle of querying them. @@ -22,7 +22,7 @@ const char* ffDetectDNS(FFDNSOptions* options, FFlist* results) { ? options->showType & FF_DNS_TYPE_IPV6_BIT ? AF_UNSPEC : AF_INET : AF_INET6, GAA_FLAG_SKIP_UNICAST | GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_FRIENDLY_NAME, - NULL, + nullptr, adapter_addresses, &adapter_addresses_buffer_size); @@ -59,5 +59,5 @@ const char* ffDetectDNS(FFDNSOptions* options, FFlist* results) { } break; } - return NULL; + return nullptr; } diff --git a/src/detection/editor/editor.c b/src/detection/editor/editor.c index b84f279bb0..a4176636ac 100644 --- a/src/detection/editor/editor.c +++ b/src/detection/editor/editor.c @@ -7,7 +7,7 @@ #include -static bool extractNvimVersionFromBinary(const char* str, FF_A_UNUSED uint32_t len, void* userdata) { +static bool extractNvimVersionFromBinary(const char* str, [[maybe_unused]] uint32_t len, void* userdata) { if (!ffStrStartsWith(str, "NVIM v")) { return true; } @@ -15,7 +15,7 @@ static bool extractNvimVersionFromBinary(const char* str, FF_A_UNUSED uint32_t l return false; } -static bool extractVimVersionFromBinary(const char* str, FF_A_UNUSED uint32_t len, void* userdata) { +static bool extractVimVersionFromBinary(const char* str, [[maybe_unused]] uint32_t len, void* userdata) { if (!ffStrStartsWith(str, "VIM - Vi IMproved ")) { return true; } @@ -24,7 +24,7 @@ static bool extractVimVersionFromBinary(const char* str, FF_A_UNUSED uint32_t le return false; } -static bool extractNanoVersionFromBinary(const char* str, FF_A_UNUSED uint32_t len, void* userdata) { +static bool extractNanoVersionFromBinary(const char* str, [[maybe_unused]] uint32_t len, void* userdata) { if (!ffStrStartsWith(str, "GNU nano ")) { return true; } @@ -50,14 +50,14 @@ const char* ffDetectEditor(FFEditorResult* result) { } else { const char* error = ffFindExecutableInPath(result->name.chars, &result->path); if (error) { - return NULL; + return nullptr; } } { char buf[PATH_MAX + 1]; if (!realpath(result->path.chars, buf)) { - return NULL; + return nullptr; } // WIN32: Should we handle scoop shim exe here? @@ -77,11 +77,11 @@ const char* ffDetectEditor(FFEditorResult* result) { #endif ); if (index == result->path.length) { - return NULL; + return nullptr; } ffStrbufSetS(&result->exe, &result->path.chars[index + 1]); if (!result->exe.length) { - return NULL; + return nullptr; } #ifdef _WIN32 @@ -92,7 +92,7 @@ const char* ffDetectEditor(FFEditorResult* result) { } if (!instance.config.general.detectVersion) { - return NULL; + return nullptr; } if (ffStrbufEqualS(&result->exe, "nvim")) { @@ -104,10 +104,10 @@ const char* ffDetectEditor(FFEditorResult* result) { } if (result->version.length > 0) { - return NULL; + return nullptr; } - const char* param = NULL; + const char* param = nullptr; if ( ffStrbufEqualS(&result->exe, "nano") || ffStrbufEqualS(&result->exe, "vim") || @@ -130,24 +130,24 @@ const char* ffDetectEditor(FFEditorResult* result) { ffStrbufEqualS(&result->exe, "ne")) { param = "-h"; } else { - return NULL; + return nullptr; } ffProcessAppendStdOut(&result->version, (char* const[]) { result->path.chars, (char*) param, - NULL, + nullptr, }); if (result->version.length == 0) { - return NULL; + return nullptr; } ffStrbufSubstrBeforeFirstC(&result->version, '\n'); const char* versionStart = strpbrk(result->version.chars, "0123456789"); - if (versionStart != NULL) { + if (versionStart != nullptr) { const char* versionEnd = strpbrk(versionStart, " \t\v\f\r"); - if (versionEnd != NULL) { + if (versionEnd != nullptr) { ffStrbufSubstrBefore(&result->version, (uint32_t) (versionEnd - result->version.chars)); } @@ -156,5 +156,5 @@ const char* ffDetectEditor(FFEditorResult* result) { } } - return NULL; + return nullptr; } diff --git a/src/detection/font/font.c b/src/detection/font/font.c index c651f29bd0..4c223224ca 100644 --- a/src/detection/font/font.c +++ b/src/detection/font/font.c @@ -11,7 +11,7 @@ const char* ffDetectFont(FFFontResult* font) { for (uint32_t i = 0; i < FF_DETECT_FONT_NUM_FONTS; ++i) { if (font->fonts[i].length > 0) { - return NULL; + return nullptr; } } diff --git a/src/detection/font/font_apple.m b/src/detection/font/font_apple.m index e8aff3c5f0..ba92981c7a 100644 --- a/src/detection/font/font_apple.m +++ b/src/detection/font/font_apple.m @@ -33,5 +33,5 @@ static void generateString(FFFontResult* font) ffStrbufAppendS(&result->fonts[3], [NSFont userFixedPitchFontOfSize:12].familyName.UTF8String); generateString(result); - return NULL; + return nullptr; } diff --git a/src/detection/font/font_haiku.cpp b/src/detection/font/font_haiku.cpp index dc29dd0045..b00b9d6f67 100644 --- a/src/detection/font/font_haiku.cpp +++ b/src/detection/font/font_haiku.cpp @@ -32,23 +32,23 @@ const char* ffDetectFontImpl(FFFontResult* result) { // We need a valid be_app to query the app_server here. BApplication app("application/x-vnd.fastfetch-cli-fastfetch"); - if ((f = be_plain_font) != NULL) { + if ((f = be_plain_font) != nullptr) { f->GetFamilyAndStyle(&menuInfo.f_family, &menuInfo.f_style); ffStrbufAppendF(&result->fonts[0], "%s %s (%dpt)", menuInfo.f_family, menuInfo.f_style, (int) f->Size()); } if (get_menu_info(&menuInfo) == B_OK) { ffStrbufAppendF(&result->fonts[1], "%s %s (%dpt)", menuInfo.f_family, menuInfo.f_style, (int) menuInfo.font_size); } - if ((f = be_bold_font) != NULL) { + if ((f = be_bold_font) != nullptr) { f->GetFamilyAndStyle(&menuInfo.f_family, &menuInfo.f_style); ffStrbufAppendF(&result->fonts[2], "%s %s (%dpt)", menuInfo.f_family, menuInfo.f_style, (int) f->Size()); } - if ((f = be_fixed_font) != NULL) { + if ((f = be_fixed_font) != nullptr) { f->GetFamilyAndStyle(&menuInfo.f_family, &menuInfo.f_style); ffStrbufAppendF(&result->fonts[3], "%s %s (%dpt)", menuInfo.f_family, menuInfo.f_style, (int) f->Size()); } generateString(result); - return NULL; + return nullptr; } diff --git a/src/detection/font/font_linux.c b/src/detection/font/font_linux.c index 5e82b682cc..29f95e2a7b 100644 --- a/src/detection/font/font_linux.c +++ b/src/detection/font/font_linux.c @@ -49,5 +49,5 @@ const char* ffDetectFontImpl(FFFontResult* result) { generateString(result); - return NULL; + return nullptr; } diff --git a/src/detection/font/font_nosupport.c b/src/detection/font/font_nosupport.c index 26f9ec68a7..8dc7b1c773 100644 --- a/src/detection/font/font_nosupport.c +++ b/src/detection/font/font_nosupport.c @@ -1,7 +1,7 @@ #include "fastfetch.h" #include "font.h" -const char* ffDetectFontImpl(FF_A_UNUSED FFFontResult* result) { +const char* ffDetectFontImpl([[maybe_unused]] FFFontResult* result) { FF_UNUSED(result); return "Not supported on this platform"; } diff --git a/src/detection/font/font_windows.c b/src/detection/font/font_windows.c index 4fc28d320c..960a75abd9 100644 --- a/src/detection/font/font_windows.c +++ b/src/detection/font/font_windows.c @@ -21,8 +21,8 @@ static void generateString(FFFontResult* font) { } const char* ffDetectFontImpl(FFFontResult* result) { - FF_AUTO_CLOSE_FD HANDLE hKey = NULL; - if (!ffRegOpenKeyForRead(HKEY_CURRENT_USER, L"Control Panel\\Desktop\\WindowMetrics", &hKey, NULL)) { + FF_AUTO_CLOSE_FD HANDLE hKey = nullptr; + if (!ffRegOpenKeyForRead(HKEY_CURRENT_USER, L"Control Panel\\Desktop\\WindowMetrics", &hKey, nullptr)) { return "ffRegOpenKeyForRead(HKEY_CURRENT_USER\\Control Panel\\Desktop\\WindowMetrics) failed"; } @@ -40,7 +40,7 @@ const char* ffDetectFontImpl(FFFontResult* result) { FF_ARG(fontBuffers[2], L"MessageFont"), FF_ARG(fontBuffers[3], L"StatusFont"), }, - NULL)) { + nullptr)) { return "ffRegReadValues(HKEY_CURRENT_USER\\Control Panel\\Desktop\\WindowMetrics) failed"; } @@ -59,5 +59,5 @@ const char* ffDetectFontImpl(FFFontResult* result) { generateString(result); - return NULL; + return nullptr; } diff --git a/src/detection/gamepad/gamepad_apple.c b/src/detection/gamepad/gamepad_apple.c index c262c8668e..7f70cfc9a0 100644 --- a/src/detection/gamepad/gamepad_apple.c +++ b/src/detection/gamepad/gamepad_apple.c @@ -28,21 +28,21 @@ static void enumSet(IOHIDDeviceRef value, FFlist* results) { } const char* ffDetectGamepad(FFlist* devices /* List of FFGamepadDevice */) { - IOHIDManagerRef FF_CFTYPE_AUTO_RELEASE manager = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone); + FF_CFTYPE_AUTO_RELEASE IOHIDManagerRef manager = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone); if (IOHIDManagerOpen(manager, kIOHIDOptionsTypeNone) != kIOReturnSuccess) { return "IOHIDManagerOpen() failed"; } - CFDictionaryRef FF_CFTYPE_AUTO_RELEASE matching1 = CFDictionaryCreate(kCFAllocatorDefault, (const void**) (CFStringRef[]) { CFSTR(kIOHIDDeviceUsagePageKey), CFSTR(kIOHIDDeviceUsageKey) }, (const void**) (CFNumberRef[]) { ffCfCreateInt(kHIDPage_GenericDesktop), ffCfCreateInt(kHIDUsage_GD_Joystick) }, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); - CFDictionaryRef FF_CFTYPE_AUTO_RELEASE matching2 = CFDictionaryCreate(kCFAllocatorDefault, (const void**) (CFStringRef[]) { CFSTR(kIOHIDDeviceUsagePageKey), CFSTR(kIOHIDDeviceUsageKey) }, (const void**) (CFNumberRef[]) { ffCfCreateInt(kHIDPage_GenericDesktop), ffCfCreateInt(kHIDUsage_GD_GamePad) }, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); - CFArrayRef FF_CFTYPE_AUTO_RELEASE matchings = CFArrayCreate(kCFAllocatorDefault, (const void**) (CFTypeRef[]) { matching1, matching2 }, 2, &kCFTypeArrayCallBacks); + FF_CFTYPE_AUTO_RELEASE CFDictionaryRef matching1 = CFDictionaryCreate(kCFAllocatorDefault, (const void**) (CFStringRef[]) { CFSTR(kIOHIDDeviceUsagePageKey), CFSTR(kIOHIDDeviceUsageKey) }, (const void**) (CFNumberRef[]) { ffCfCreateInt(kHIDPage_GenericDesktop), ffCfCreateInt(kHIDUsage_GD_Joystick) }, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); + FF_CFTYPE_AUTO_RELEASE CFDictionaryRef matching2 = CFDictionaryCreate(kCFAllocatorDefault, (const void**) (CFStringRef[]) { CFSTR(kIOHIDDeviceUsagePageKey), CFSTR(kIOHIDDeviceUsageKey) }, (const void**) (CFNumberRef[]) { ffCfCreateInt(kHIDPage_GenericDesktop), ffCfCreateInt(kHIDUsage_GD_GamePad) }, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); + FF_CFTYPE_AUTO_RELEASE CFArrayRef matchings = CFArrayCreate(kCFAllocatorDefault, (const void**) (CFTypeRef[]) { matching1, matching2 }, 2, &kCFTypeArrayCallBacks); IOHIDManagerSetDeviceMatchingMultiple(manager, matchings); - CFSetRef FF_CFTYPE_AUTO_RELEASE set = IOHIDManagerCopyDevices(manager); + FF_CFTYPE_AUTO_RELEASE CFSetRef set = IOHIDManagerCopyDevices(manager); if (set) { CFSetApplyFunction(set, (CFSetApplierFunction) &enumSet, devices); } IOHIDManagerClose(manager, kIOHIDOptionsTypeNone); - return NULL; + return nullptr; } diff --git a/src/detection/gamepad/gamepad_bsd.c b/src/detection/gamepad/gamepad_bsd.c index b67b8fd2db..475bd061fa 100644 --- a/src/detection/gamepad/gamepad_bsd.c +++ b/src/detection/gamepad/gamepad_bsd.c @@ -61,5 +61,5 @@ const char* ffDetectGamepad(FFlist* devices /* List of FFGamepadDevice */) { hid_dispose_report_desc(repDesc); } - return NULL; + return nullptr; } diff --git a/src/detection/gamepad/gamepad_haiku.cpp b/src/detection/gamepad/gamepad_haiku.cpp index 50b43a0434..ae601064ca 100644 --- a/src/detection/gamepad/gamepad_haiku.cpp +++ b/src/detection/gamepad/gamepad_haiku.cpp @@ -14,5 +14,5 @@ const char* ffDetectGamepad(FFlist* devices /* List of FFGamepadDevice */) { device->battery = 0; } } - return NULL; + return nullptr; } diff --git a/src/detection/gamepad/gamepad_linux.c b/src/detection/gamepad/gamepad_linux.c index 6bb4ee214c..2c2e10587e 100644 --- a/src/detection/gamepad/gamepad_linux.c +++ b/src/detection/gamepad/gamepad_linux.c @@ -20,7 +20,7 @@ static void detectGamepad(FFlist* devices, FFstrbuf* name, FFstrbuf* path) { FF_AUTO_CLOSE_DIR DIR* dirp = opendir(path->chars); if (dirp) { struct dirent* entry; - while ((entry = readdir(dirp)) != NULL) { + while ((entry = readdir(dirp)) != nullptr) { if (entry->d_name[0] == '.' || (entry->d_type != DT_DIR && entry->d_type != DT_UNKNOWN)) { continue; } @@ -31,7 +31,7 @@ static void detectGamepad(FFlist* devices, FFstrbuf* name, FFstrbuf* path) { if (nRead > 0) // Tested with a PS4 controller { capacity[nRead] = '\0'; - device->battery = (uint8_t) strtoul(capacity, NULL, 10); + device->battery = (uint8_t) strtoul(capacity, nullptr, 10); break; } @@ -64,15 +64,15 @@ static void detectGamepad(FFlist* devices, FFstrbuf* name, FFstrbuf* path) { const char* ffDetectGamepad(FFlist* devices /* List of FFGamepadDevice */) { FF_AUTO_CLOSE_DIR DIR* dirp = opendir("/sys/class/input/"); - if (dirp == NULL) { - return "opendir(\"/sys/class/input/\") == NULL"; + if (dirp == nullptr) { + return "opendir(\"/sys/class/input/\") == nullptr"; } FF_STRBUF_AUTO_DESTROY path = ffStrbufCreateS("/sys/class/input/"); uint32_t baseLen = path.length; struct dirent* entry; - while ((entry = readdir(dirp)) != NULL) { + while ((entry = readdir(dirp)) != nullptr) { if (!ffStrStartsWith(entry->d_name, "js")) { continue; } @@ -93,5 +93,5 @@ const char* ffDetectGamepad(FFlist* devices /* List of FFGamepadDevice */) { ffStrbufSubstrBefore(&path, baseLen); } - return NULL; + return nullptr; } diff --git a/src/detection/gamepad/gamepad_nosupport.c b/src/detection/gamepad/gamepad_nosupport.c index c0d791e711..ad6a3741ef 100644 --- a/src/detection/gamepad/gamepad_nosupport.c +++ b/src/detection/gamepad/gamepad_nosupport.c @@ -1,5 +1,5 @@ #include "gamepad.h" -const char* ffDetectGamepad(FF_A_UNUSED FFlist* devices /* List of FFGamepadDevice */) { +const char* ffDetectGamepad([[maybe_unused]] FFlist* devices /* List of FFGamepadDevice */) { return "Not supported on this platform"; } diff --git a/src/detection/gamepad/gamepad_windows.c b/src/detection/gamepad/gamepad_windows.c index 9cbb5618e1..b7f23e18cb 100644 --- a/src/detection/gamepad/gamepad_windows.c +++ b/src/detection/gamepad/gamepad_windows.c @@ -23,7 +23,7 @@ static const char* detectKnownDeviceName(uint32_t vendorId, uint32_t productId) return "Nintendo Switch SNES Controller"; default: - return NULL; + return nullptr; } } @@ -46,7 +46,7 @@ static const char* detectKnownDeviceName(uint32_t vendorId, uint32_t productId) return "Sony DualSense Edge"; default: - return NULL; + return nullptr; } } @@ -67,25 +67,25 @@ static const char* detectKnownDeviceName(uint32_t vendorId, uint32_t productId) return "Logitech F710"; default: - return NULL; + return nullptr; } } case 0x045E: // Microsoft Xbox compatible controllers should be handled by Windows without problems default: - return NULL; + return nullptr; } } const char* ffDetectGamepad(FFlist* devices /* List of FFGamepadDevice */) { UINT nDevices = 0; - if (GetRawInputDeviceList(NULL, &nDevices, sizeof(RAWINPUTDEVICELIST))) { - return "GetRawInputDeviceList(NULL) failed"; + if (GetRawInputDeviceList(nullptr, &nDevices, sizeof(RAWINPUTDEVICELIST))) { + return "GetRawInputDeviceList(nullptr) failed"; } if (nDevices == 0) { return "No HID devices found"; } - RAWINPUTDEVICELIST* FF_AUTO_FREE pRawInputDeviceList = (RAWINPUTDEVICELIST*) malloc(sizeof(RAWINPUTDEVICELIST) * nDevices); + FF_AUTO_FREE RAWINPUTDEVICELIST* pRawInputDeviceList = (RAWINPUTDEVICELIST*) malloc(sizeof(RAWINPUTDEVICELIST) * nDevices); if ((nDevices = GetRawInputDeviceList(pRawInputDeviceList, &nDevices, sizeof(RAWINPUTDEVICELIST))) == (UINT) -1) { return "GetRawInputDeviceList(pRawInputDeviceList) failed"; } @@ -122,7 +122,7 @@ const char* ffDetectGamepad(FFlist* devices /* List of FFGamepadDevice */) { if (knownGamepad) { ffStrbufSetS(&device->name, knownGamepad); } - HANDLE FF_AUTO_CLOSE_FD hHidFile = CreateFileW(devName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL); + FF_AUTO_CLOSE_FD HANDLE hHidFile = CreateFileW(devName, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, nullptr); if (hHidFile == INVALID_HANDLE_VALUE) { if (!knownGamepad) { ffStrbufSetF(&device->name, "Unknown gamepad %04X-%04X", (unsigned) rdi.hid.dwVendorId, (unsigned) rdi.hid.dwProductId); @@ -150,7 +150,7 @@ const char* ffDetectGamepad(FFlist* devices /* List of FFGamepadDevice */) { ffStrbufSetWS(&device->serial, serialNumber); } - PHIDP_PREPARSED_DATA preparsedData = NULL; + PHIDP_PREPARSED_DATA preparsedData = nullptr; if (HidD_GetPreparsedData(hHidFile, &preparsedData)) { HIDP_CAPS caps; NTSTATUS capsResult = HidP_GetCaps(preparsedData, &caps); @@ -197,5 +197,5 @@ const char* ffDetectGamepad(FFlist* devices /* List of FFGamepadDevice */) { } } - return NULL; + return nullptr; } diff --git a/src/detection/gpu/d3dkmthk.h b/src/detection/gpu/d3dkmthk.h index e32241164c..0fe47398b1 100644 --- a/src/detection/gpu/d3dkmthk.h +++ b/src/detection/gpu/d3dkmthk.h @@ -316,18 +316,18 @@ typedef struct _DXGK_NODEMETADATA_FLAGS { }; } DXGK_NODEMETADATA_FLAGS; -typedef struct _DXGK_NODEMETADATA { +typedef struct [[gnu::packed]] _DXGK_NODEMETADATA { DXGK_ENGINE_TYPE EngineType; WCHAR FriendlyName[DXGK_MAX_METADATA_NAME_LENGTH]; DXGK_NODEMETADATA_FLAGS Flags; // WDDM 2.2 BOOLEAN GpuMmuSupported; // WDDM 2.0 ??? BOOLEAN IoMmuSupported; -} FF_A_PACKED DXGK_NODEMETADATA; +} DXGK_NODEMETADATA; -typedef struct _D3DKMT_NODEMETADATA { +typedef struct [[gnu::packed]] _D3DKMT_NODEMETADATA { UINT NodeOrdinalAndAdapterIndex; // WDDMv2: High word is physical adapter index, low word is node ordinal DXGK_NODEMETADATA NodeData; -} FF_A_PACKED D3DKMT_NODEMETADATA; +} D3DKMT_NODEMETADATA; static_assert(sizeof(D3DKMT_NODEMETADATA) == 0x4E, "D3DKMT_NODEMETADATA structure size mismatch"); // Functions diff --git a/src/detection/gpu/gpu.c b/src/detection/gpu/gpu.c index 7400652ad8..6fb0fe7f71 100644 --- a/src/detection/gpu/gpu.c +++ b/src/detection/gpu/gpu.c @@ -73,7 +73,7 @@ const char* ffGPUGetVendorString(unsigned vendorId) { case 0x1234: // https://admin.pci-ids.ucw.cz/read/PC/1234 return FF_GPU_VENDOR_NAME_QEMU; default: - return NULL; + return nullptr; } } @@ -106,7 +106,7 @@ const char* detectByOpenGL(FFlist* gpus) { ffStrbufInit(&result.slv); ffStrbufInit(&result.library); - FF_A_CLEANUP(ffDestroyOpenGLOptions) FFOpenGLOptions options; + [[gnu::cleanup(ffDestroyOpenGLOptions)]] FFOpenGLOptions options; ffInitOpenGLOptions(&options); const char* error = ffDetectOpenGL(&options, &result); FF_DEBUG("OpenGL detection returns: %s", error ?: "success"); @@ -202,7 +202,7 @@ const char* detectByEglext(FFlist* result) { const char* name = ffeglQueryDeviceStringEXT(device, EGL_RENDERER_EXT); if (!name) { - FF_DEBUG("eglQueryDeviceStringEXT() returned NULL name for device %d, skipping", i); + FF_DEBUG("eglQueryDeviceStringEXT() returned nullptr name for device %d, skipping", i); continue; } @@ -222,7 +222,7 @@ const char* detectByEglext(FFlist* result) { gpu->frequency = FF_GPU_FREQUENCY_UNSET; gpu->pcieSpeed = FF_GPU_PCIE_SPEED_UNSET; - ffeglQueryDeviceBinaryEXT(device, EGL_DEVICE_UUID_EXT, sizeof(gpu->deviceId), &gpu->deviceId, NULL); + ffeglQueryDeviceBinaryEXT(device, EGL_DEVICE_UUID_EXT, sizeof(gpu->deviceId), &gpu->deviceId, nullptr); if (!normalizeVendorName(gpu)) { ffStrbufSetS(&gpu->vendor, ffeglQueryDeviceStringEXT(device, EGL_VENDOR)); @@ -234,7 +234,7 @@ const char* detectByEglext(FFlist* result) { FF_DEBUG("eglQueryDevicesEXT() returned EGL_FALSE"); } - return NULL; + return nullptr; } #endif @@ -249,7 +249,7 @@ const char* ffDetectGPU(const FFGPUOptions* options, FFlist* result) { const char* error = ffDetectGPUImpl(options, result); if (!error && result->length > 0) { FF_DEBUG("PCI/native GPU detection succeeded with %u GPU(s)", result->length); - return NULL; + return nullptr; } FF_DEBUG("PCI/native GPU detection did not produce results (error=%s, gpuCount=%u)", @@ -272,7 +272,7 @@ const char* ffDetectGPU(const FFGPUOptions* options, FFlist* result) { } #endif - return NULL; + return nullptr; } FF_DEBUG("Vulkan detection did not produce results (error=%s, gpuCount=%u)", @@ -286,7 +286,7 @@ const char* ffDetectGPU(const FFGPUOptions* options, FFlist* result) { FF_DEBUG("OpenCL detection succeeded with %u GPU(s)", opencl->gpus.length); ffListDestroy(result); ffListInitMove(result, &opencl->gpus); - return NULL; + return nullptr; } FF_DEBUG("OpenCL detection did not produce results (error=%s, gpuCount=%u)", @@ -299,7 +299,7 @@ const char* ffDetectGPU(const FFGPUOptions* options, FFlist* result) { const char* error = detectByEglext(result); if (!error && result->length > 0) { FF_DEBUG("EGL_EXT GPU detection succeeded with %u GPU(s)", result->length); - return NULL; + return nullptr; } FF_DEBUG("EGL_EXT GPU detection did not produce results (error=%s, gpuCount=%u)", @@ -312,9 +312,9 @@ const char* ffDetectGPU(const FFGPUOptions* options, FFlist* result) { if (options->detectionMethod <= FF_GPU_DETECTION_METHOD_OPENGL) { FF_DEBUG("Trying OpenGL GPU detection fallback"); const char* error = detectByOpenGL(result); - if (error == NULL) { + if (error == nullptr) { FF_DEBUG("OpenGL fallback succeeded with %u GPU(s)", result->length); - return NULL; + return nullptr; } FF_DEBUG("OpenGL fallback failed: %s", error); diff --git a/src/detection/gpu/gpu.h b/src/detection/gpu/gpu.h index 32b6ff636e..546de07495 100644 --- a/src/detection/gpu/gpu.h +++ b/src/detection/gpu/gpu.h @@ -64,8 +64,8 @@ typedef struct FFGPUResult { uint64_t deviceId; } FFGPUResult; -static_assert(sizeof(((FFGPUResult*) NULL)->pcieSpeed) == 8, "pcieSpeed is not 8 bytes"); -static_assert(sizeof(((FFGPUResult*) NULL)->psMax) == 4, "psMax has padding"); +static_assert(sizeof(((FFGPUResult*) nullptr)->pcieSpeed) == 8, "pcieSpeed is not 8 bytes"); +static_assert(sizeof(((FFGPUResult*) nullptr)->psMax) == 4, "psMax has padding"); const char* ffDetectGPU(const FFGPUOptions* options, FFlist* result); const char* ffDetectGPUImpl(const FFGPUOptions* options, FFlist* gpus); diff --git a/src/detection/gpu/gpu_amd.c b/src/detection/gpu/gpu_amd.c index 4a8134cf82..858bac0f33 100644 --- a/src/detection/gpu/gpu_amd.c +++ b/src/detection/gpu/gpu_amd.c @@ -6,7 +6,7 @@ #include "common/debug.h" // Helper function to convert ADL status code to string -FF_A_UNUSED static const char* ffAdlStatusToString(int status) { +[[maybe_unused]] static const char* ffAdlStatusToString(int status) { switch (status) { #define FF_ADL_STATUS_CASE(name) \ case name: \ @@ -72,7 +72,7 @@ static void shutdownAdl() { if (adlData.apiHandle) { FF_DEBUG("Destroying ADL context"); adlData.ffADL2_Main_Control_Destroy(adlData.apiHandle); - adlData.apiHandle = NULL; + adlData.apiHandle = nullptr; } } @@ -110,7 +110,7 @@ const char* ffDetectAmdGpuInfo(const FFGpuDriverCondition* cond, FFGpuDriverResu } atexit(shutdownAdl); - atiadl = NULL; // don't close atiadl + atiadl = nullptr; // don't close atiadl FF_DEBUG("ADL initialization complete"); } @@ -119,7 +119,7 @@ const char* ffDetectAmdGpuInfo(const FFGpuDriverCondition* cond, FFGpuDriverResu return "ffADL2_Main_Control_Create() failed"; } - FF_AUTO_FREE AdapterInfo* devices = NULL; + FF_AUTO_FREE AdapterInfo* devices = nullptr; int numDevices = 0; int adapterResult = adlData.ffADL2_Adapter_AdapterInfoX3_Get(adlData.apiHandle, -1, &numDevices, &devices); FF_DEBUG("ADL2_Adapter_AdapterInfoX3_Get returned %s (%d)", ffAdlStatusToString(adapterResult), adapterResult); @@ -131,7 +131,7 @@ const char* ffDetectAmdGpuInfo(const FFGpuDriverCondition* cond, FFGpuDriverResu return "ffADL2_Adapter_AdapterInfoX3_Get() failed"; } - const AdapterInfo* device = NULL; + const AdapterInfo* device = nullptr; for (int iDev = 0; iDev < numDevices; iDev++) { if (cond->type & FF_GPU_DRIVER_CONDITION_TYPE_BUS_ID) { FF_DEBUG("Checking device %d: bus=%d, device=%d, func=%d against requested bus=%u, device=%u, func=%u", @@ -492,5 +492,5 @@ const char* ffDetectAmdGpuInfo(const FFGpuDriverCondition* cond, FFGpuDriverResu return "Unknown Overdrive version"; } FF_DEBUG("AMD GPU detection complete - returning success"); - return NULL; + return nullptr; } diff --git a/src/detection/gpu/gpu_android.c b/src/detection/gpu/gpu_android.c index 08fd48af22..f25756b4cd 100644 --- a/src/detection/gpu/gpu_android.c +++ b/src/detection/gpu/gpu_android.c @@ -27,7 +27,7 @@ double ffGPUDetectTempFromTZ(void) { FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); int dfd = dirfd(dirp); struct dirent* entry; - while ((entry = readdir(dirp)) != NULL) { + while ((entry = readdir(dirp)) != nullptr) { if (entry->d_name[0] == '.') { continue; } diff --git a/src/detection/gpu/gpu_apple.c b/src/detection/gpu/gpu_apple.c index fc9fd457d7..f3775bc5a3 100644 --- a/src/detection/gpu/gpu_apple.c +++ b/src/detection/gpu/gpu_apple.c @@ -9,10 +9,10 @@ const char* ffGpuDetectDriverVersion(FFlist* gpus); static double detectGpuTemp(const FFstrbuf* gpuName) { double result = 0; - const char* error = NULL; + const char* error = nullptr; if (ffStrbufStartsWithS(gpuName, "Apple M")) { - switch (strtol(gpuName->chars + strlen("Apple M"), NULL, 10)) { + switch (strtol(gpuName->chars + strlen("Apple M"), nullptr, 10)) { case 0: error = "Invalid Apple Silicon GPU"; break; @@ -28,6 +28,9 @@ static double detectGpuTemp(const FFstrbuf* gpuName) { case 4: error = ffDetectSmcTemps(FF_TEMP_GPU_M4X, &result); break; + case 5: + error = ffDetectSmcTemps(FF_TEMP_GPU_M5X, &result); + break; default: error = "Unsupported Apple Silicon GPU"; break; @@ -88,7 +91,7 @@ static const char* detectFrequency(FFGPUResult* gpu) { } } - return NULL; + return nullptr; } #endif @@ -123,27 +126,27 @@ const char* ffDetectGPUImpl(const FFGPUOptions* options, FFlist* gpus) { ffStrbufInit(&gpu->driver); // Ok for both Apple and Intel ffCfDictGetString(properties, CFSTR("CFBundleIdentifier"), &gpu->driver); - if (ffCfDictGetInt(properties, CFSTR("gpu-core-count"), &gpu->coreCount) != NULL) { // For Apple + if (ffCfDictGetInt(properties, CFSTR("gpu-core-count"), &gpu->coreCount) != nullptr) { // For Apple gpu->coreCount = FF_GPU_CORE_COUNT_UNSET; } gpu->coreUsage = FF_GPU_CORE_USAGE_UNSET; - CFDictionaryRef perfStatistics = NULL; + CFDictionaryRef perfStatistics = nullptr; uint64_t vramUsed = 0, vramTotal = 0; - if (ffCfDictGetDict(properties, CFSTR("PerformanceStatistics"), &perfStatistics) == NULL) { + if (ffCfDictGetDict(properties, CFSTR("PerformanceStatistics"), &perfStatistics) == nullptr) { int64_t utilization; - if (ffCfDictGetInt64(perfStatistics, CFSTR("Device Utilization %"), &utilization) == NULL) { + if (ffCfDictGetInt64(perfStatistics, CFSTR("Device Utilization %"), &utilization) == nullptr) { gpu->coreUsage = (double) utilization; - } else if (ffCfDictGetInt64(perfStatistics, CFSTR("GPU Core Utilization"), &utilization) == NULL) { + } else if (ffCfDictGetInt64(perfStatistics, CFSTR("GPU Core Utilization"), &utilization) == nullptr) { gpu->coreUsage = (double) utilization / 10000000.; // Nvidia? } - if (ffCfDictGetInt64(perfStatistics, CFSTR("Alloc system memory"), (int64_t*) &vramTotal) == NULL) { - if (ffCfDictGetInt64(perfStatistics, CFSTR("In use system memory"), (int64_t*) &vramUsed) != NULL) { + if (ffCfDictGetInt64(perfStatistics, CFSTR("Alloc system memory"), (int64_t*) &vramTotal) == nullptr) { + if (ffCfDictGetInt64(perfStatistics, CFSTR("In use system memory"), (int64_t*) &vramUsed) != nullptr) { vramTotal = 0; } - } else if (ffCfDictGetInt64(perfStatistics, CFSTR("vramFreeBytes"), (int64_t*) &vramTotal) == NULL) { - if (ffCfDictGetInt64(perfStatistics, CFSTR("vramUsedBytes"), (int64_t*) &vramUsed) == NULL) { + } else if (ffCfDictGetInt64(perfStatistics, CFSTR("vramFreeBytes"), (int64_t*) &vramTotal) == nullptr) { + if (ffCfDictGetInt64(perfStatistics, CFSTR("vramUsedBytes"), (int64_t*) &vramUsed) == nullptr) { vramTotal += vramUsed; } else { vramTotal = 0; @@ -154,9 +157,9 @@ const char* ffDetectGPUImpl(const FFGPUOptions* options, FFlist* gpus) { ffStrbufInit(&gpu->name); // IOAccelerator returns model / vendor-id properties for Apple Silicon, but not for Intel Iris GPUs. // Still needs testing for AMD's - if (ffCfDictGetString(properties, CFSTR("model"), &gpu->name) != NULL) { + if (ffCfDictGetString(properties, CFSTR("model"), &gpu->name) != nullptr) { CFRelease(properties); - properties = NULL; + properties = nullptr; FF_IOOBJECT_AUTO_RELEASE io_registry_entry_t parentEntry = 0; if (IORegistryEntryGetParentEntry(registryEntry, kIOServicePlane, &parentEntry) != kIOReturnSuccess || @@ -169,7 +172,7 @@ const char* ffDetectGPUImpl(const FFGPUOptions* options, FFlist* gpus) { ffStrbufInit(&gpu->vendor); int vendorId; - if (ffCfDictGetInt(properties, CFSTR("vendor-id"), &vendorId) == NULL) { + if (ffCfDictGetInt(properties, CFSTR("vendor-id"), &vendorId) == nullptr) { const char* vendorStr = ffGPUGetVendorString((unsigned) vendorId); ffStrbufAppendS(&gpu->vendor, vendorStr); if (vendorStr == FF_GPU_VENDOR_NAME_APPLE || vendorStr == FF_GPU_VENDOR_NAME_INTEL) { @@ -203,5 +206,5 @@ const char* ffDetectGPUImpl(const FFGPUOptions* options, FFlist* gpus) { if (instance.config.general.detectVersion) { ffGpuDetectDriverVersion(gpus); } - return NULL; + return nullptr; } diff --git a/src/detection/gpu/gpu_apple.m b/src/detection/gpu/gpu_apple.m index e206bdc1a5..24ede6de2c 100644 --- a/src/detection/gpu/gpu_apple.m +++ b/src/detection/gpu/gpu_apple.m @@ -32,7 +32,7 @@ ffStrbufAppendS(&x->driver, version.UTF8String); } } - return NULL; + return nullptr; } return "Unsupported macOS version"; } @@ -43,7 +43,7 @@ { for (id device in MTLCopyAllDevices()) { - FFGPUResult* gpu = NULL; + FFGPUResult* gpu = nullptr; FF_LIST_FOR_EACH(FFGPUResult, x, *gpus) { if (x->deviceId == device.registryID) @@ -81,7 +81,7 @@ gpu->shared.total = device.recommendedMaxWorkingSetSize; #endif } - return NULL; + return nullptr; } return "Metal API is not supported by this macOS version"; } diff --git a/src/detection/gpu/gpu_bsd.c b/src/detection/gpu/gpu_bsd.c index f5f8d58003..64e1a74ecd 100644 --- a/src/detection/gpu/gpu_bsd.c +++ b/src/detection/gpu/gpu_bsd.c @@ -80,7 +80,7 @@ static const char* detectByPci(const FFGPUOptions* options, FFlist* gpus) { ffGPUDetectTypeByVendorAndName(gpu); } - return NULL; + return nullptr; } const char* ffDetectGPUImpl(const FFGPUOptions* options, FFlist* gpus) { @@ -88,7 +88,7 @@ const char* ffDetectGPUImpl(const FFGPUOptions* options, FFlist* gpus) { if (options->detectionMethod == FF_GPU_DETECTION_METHOD_AUTO) { ffGPUDetectByDrmBSD(options, gpus); if (gpus->length > 0) { - return NULL; + return nullptr; } } #endif diff --git a/src/detection/gpu/gpu_bsddrm.c b/src/detection/gpu/gpu_bsddrm.c index 2fcf9c96df..c90a37f4de 100644 --- a/src/detection/gpu/gpu_bsddrm.c +++ b/src/detection/gpu/gpu_bsddrm.c @@ -46,7 +46,7 @@ static const char* drmGetPciinfo(int drmfd, const char* drmId, struct drm_pciinf snprintf(requestBuf, ARRAY_SIZE(requestBuf), "hw.dri.%s.busid", drmId); char pciidBuf[64]; size_t pciidLen = ARRAY_SIZE(pciidBuf); - if (sysctlbyname(requestBuf, pciidBuf, &pciidLen, NULL, 0) < 0) { + if (sysctlbyname(requestBuf, pciidBuf, &pciidLen, nullptr, 0) < 0) { return "sysctlbyname(hw.dri.%s.busid) failed"; } // hw.dri.0.busid: pci:0000:01:00.0 @@ -100,18 +100,18 @@ static const char* drmGetPciinfo(int drmfd, const char* drmId, struct drm_pciinf // dev.drm.0.PCI_ID: 10de:2782 #endif - return NULL; + return nullptr; } const char* ffGPUDetectByDrmBSD(const FFGPUOptions* options, FFlist* gpus) { FF_AUTO_CLOSE_DIR DIR* dirp = opendir("/dev/dri/"); - if (dirp == NULL) { + if (dirp == nullptr) { return "opendir(/dev/dri/) failed"; } int drifd = dirfd(dirp); struct dirent* entry; - while ((entry = readdir(dirp)) != NULL) { + while ((entry = readdir(dirp)) != nullptr) { if (entry->d_name[0] == '.' || !ffStrStartsWith(entry->d_name, "card")) { continue; } @@ -123,7 +123,7 @@ const char* ffGPUDetectByDrmBSD(const FFGPUOptions* options, FFlist* gpus) { // Currently, DRM_BUS_PCI is the only bus type supported by drm-kmod on BSD (hard-coded in libdrm source tree) struct drm_pciinfo pciInfo; - if (drmGetPciinfo(fd, entry->d_name + strlen("card"), &pciInfo) != NULL) { + if (drmGetPciinfo(fd, entry->d_name + strlen("card"), &pciInfo) != nullptr) { continue; } @@ -157,11 +157,11 @@ const char* ffGPUDetectByDrmBSD(const FFGPUOptions* options, FFlist* gpus) { if (ffStrStartsWith(driverName, "i915")) { ffDrmDetectI915(gpu, fd); } else if (ffStrStartsWith(driverName, "amdgpu")) { - uint32_t primaryNodeId = (uint32_t) strtoul(entry->d_name + strlen("card"), NULL, 10); + uint32_t primaryNodeId = (uint32_t) strtoul(entry->d_name + strlen("card"), nullptr, 10); FF_STRBUF_AUTO_DESTROY renderNode = ffStrbufCreateF("/dev/dri/renderD%d", primaryNodeId + 128); ffDrmDetectAmdgpu(options, gpu, renderNode.chars); } else if (ffStrStartsWith(driverName, "radeon")) { - uint32_t primaryNodeId = (uint32_t) strtoul(entry->d_name + strlen("card"), NULL, 10); + uint32_t primaryNodeId = (uint32_t) strtoul(entry->d_name + strlen("card"), nullptr, 10); FF_STRBUF_AUTO_DESTROY renderNode = ffStrbufCreateF("/dev/dri/renderD%d", primaryNodeId + 128); ffDrmDetectRadeon(options, gpu, renderNode.chars); } else if (ffStrStartsWith(driverName, "xe")) { @@ -191,7 +191,7 @@ const char* ffGPUDetectByDrmBSD(const FFGPUOptions* options, FFlist* gpus) { ffGPUDetectTypeByVendorAndName(gpu); } - return NULL; + return nullptr; } #else diff --git a/src/detection/gpu/gpu_driver_specific.h b/src/detection/gpu/gpu_driver_specific.h index 807a0eb6ef..c8aa34876a 100644 --- a/src/detection/gpu/gpu_driver_specific.h +++ b/src/detection/gpu/gpu_driver_specific.h @@ -2,11 +2,10 @@ #include "gpu.h" -typedef enum FF_A_PACKED FFGpuDriverConditionType { +typedef enum FFGpuDriverConditionType: uint8_t { FF_GPU_DRIVER_CONDITION_TYPE_BUS_ID = 1 << 0, FF_GPU_DRIVER_CONDITION_TYPE_DEVICE_ID = 1 << 1, FF_GPU_DRIVER_CONDITION_TYPE_LUID = 1 << 2, - FF_GPU_DRIVER_CONDITION_TYPE_FORCE_UNSIGNED = UINT8_MAX, } FFGpuDriverConditionType; typedef struct FFGpuDriverPciDeviceId { @@ -16,7 +15,7 @@ typedef struct FFGpuDriverPciDeviceId { uint32_t revId; } FFGpuDriverPciDeviceId; -// Use pciBusId if not NULL; use pciDeviceId otherwise +// Use pciBusId if not nullptr; use pciDeviceId otherwise typedef struct FFGpuDriverCondition { FFGpuDriverConditionType type; FFGpuDriverPciBusId pciBusId; @@ -24,7 +23,7 @@ typedef struct FFGpuDriverCondition { uint64_t luid; } FFGpuDriverCondition; -// detect x if not NULL +// detect x if not nullptr typedef struct FFGpuDriverResult { uint32_t* index; double* temp; @@ -49,7 +48,7 @@ const char* ffDetectMthreadsGpuInfo(const FFGpuDriverCondition* cond, FFGpuDrive #define FF_GPU_DRIVER_DLLNAME_PATH_PREFIX #endif -FF_A_UNUSED static inline bool getDriverSpecificDetectionFn(const char* vendor, __typeof__(&ffDetectNvidiaGpuInfo)* pDetectFn, const char** pDllName) { +[[maybe_unused]] static inline bool getDriverSpecificDetectionFn(const char* vendor, typeof(&ffDetectNvidiaGpuInfo)* pDetectFn, const char** pDllName) { if (vendor == FF_GPU_VENDOR_NAME_NVIDIA) { *pDetectFn = ffDetectNvidiaGpuInfo; #ifdef _WIN32 @@ -83,8 +82,8 @@ FF_A_UNUSED static inline bool getDriverSpecificDetectionFn(const char* vendor, } #endif else { - *pDetectFn = NULL; - *pDllName = NULL; + *pDetectFn = nullptr; + *pDllName = nullptr; return false; } diff --git a/src/detection/gpu/gpu_drm.c b/src/detection/gpu/gpu_drm.c index b22d0a7a9e..77f31799e6 100644 --- a/src/detection/gpu/gpu_drm.c +++ b/src/detection/gpu/gpu_drm.c @@ -80,7 +80,7 @@ const char* ffDrmDetectRadeon(const FFGPUOptions* options, FFGPUResult* gpu, con } } - return NULL; + return nullptr; } const char* ffDrmDetectAmdgpu(const FFGPUOptions* options, FFGPUResult* gpu, const char* renderPath) { @@ -172,7 +172,7 @@ const char* ffDrmDetectAmdgpu(const FFGPUOptions* options, FFGPUResult* gpu, con gpu->coreUsage = value; } - return NULL; + return nullptr; } const char* ffDrmDetectI915(FFGPUResult* gpu, int fd) { @@ -213,7 +213,7 @@ const char* ffDrmDetectI915(FFGPUResult* gpu, int fd) { } } } - return NULL; + return nullptr; } static inline int popcountBytes(uint8_t* bytes, uint32_t length) { @@ -296,7 +296,7 @@ const char* ffDrmDetectXe(FFGPUResult* gpu, int fd) { } } } - return flag ? NULL : "Failed to query Xe GPU information"; + return flag ? nullptr : "Failed to query Xe GPU information"; } const char* ffDrmDetectAsahi(FFGPUResult* gpu, int fd) { @@ -334,7 +334,7 @@ const char* ffDrmDetectAsahi(FFGPUResult* gpu, int fd) { ffStrbufSetF(&gpu->name, "Apple M%d%s (G%d%c %02X)", paramsGlobal.gpu_generation - 12, variant, paramsGlobal.gpu_generation, paramsGlobal.gpu_variant, paramsGlobal.gpu_revision + 0xA0); } - return NULL; + return nullptr; } return "Failed to query Asahi GPU information"; @@ -362,7 +362,7 @@ const char* ffDrmDetectNouveau(FFGPUResult* gpu, int fd) { gpu->coreCount = (int32_t) getparam.value; } - return NULL; + return nullptr; } #endif // FF_HAVE_DRM @@ -371,7 +371,7 @@ const char* ffDrmDetectNouveau(FFGPUResult* gpu, int fd) { const char* ffGPUDetectDriverSpecific(const FFGPUOptions* options, FFGPUResult* gpu, FFGpuDriverPciBusId pciBusId) { #if !__OpenBSD__ - __typeof__(&ffDetectNvidiaGpuInfo) detectFn; + typeof(&ffDetectNvidiaGpuInfo) detectFn; const char* soName; if (getDriverSpecificDetectionFn(gpu->vendor.chars, &detectFn, &soName) && (options->temp || options->driverSpecific)) { return detectFn(&(FFGpuDriverCondition) { @@ -380,17 +380,17 @@ const char* ffGPUDetectDriverSpecific(const FFGPUOptions* options, FFGPUResult* }, (FFGpuDriverResult) { .index = &gpu->index, - .temp = options->temp ? &gpu->temperature : NULL, - .memory = options->driverSpecific ? &gpu->dedicated : NULL, - .sharedMemory = options->driverSpecific ? &gpu->shared : NULL, - .memoryType = options->driverSpecific ? &gpu->memoryType : NULL, - .coreCount = options->driverSpecific ? (uint32_t*) &gpu->coreCount : NULL, - .coreUsage = options->driverSpecific ? &gpu->coreUsage : NULL, + .temp = options->temp ? &gpu->temperature : nullptr, + .memory = options->driverSpecific ? &gpu->dedicated : nullptr, + .sharedMemory = options->driverSpecific ? &gpu->shared : nullptr, + .memoryType = options->driverSpecific ? &gpu->memoryType : nullptr, + .coreCount = options->driverSpecific ? (uint32_t*) &gpu->coreCount : nullptr, + .coreUsage = options->driverSpecific ? &gpu->coreUsage : nullptr, .type = &gpu->type, - .frequency = options->driverSpecific ? &gpu->frequency : NULL, + .frequency = options->driverSpecific ? &gpu->frequency : nullptr, .name = &gpu->name, - .psCurr = options->driverSpecific ? &gpu->psCurr : NULL, - .psMax = options->driverSpecific ? &gpu->psMax : NULL, + .psCurr = options->driverSpecific ? &gpu->psCurr : nullptr, + .psMax = options->driverSpecific ? &gpu->psMax : nullptr, }, soName); } diff --git a/src/detection/gpu/gpu_gnu.c b/src/detection/gpu/gpu_gnu.c index 30cadf81b3..3edb32d6cb 100644 --- a/src/detection/gpu/gpu_gnu.c +++ b/src/detection/gpu/gpu_gnu.c @@ -15,19 +15,19 @@ enum { PCI_CONF_SIZE = 0x40, }; -const char* ffDetectGPUImpl(FF_A_UNUSED const FFGPUOptions* options, FFlist* gpus) { +const char* ffDetectGPUImpl([[maybe_unused]] const FFGPUOptions* options, FFlist* gpus) { int dDomainFd = open(_SERVERS_BUS "/pci/0000", O_RDONLY | O_CLOEXEC); if (dDomainFd < 0) { return "open(_SERVERS_BUS \"/pci/0000\") failed"; } FF_AUTO_CLOSE_DIR DIR* dirDomain = fdopendir(dDomainFd); - if (dirDomain == NULL) { + if (dirDomain == nullptr) { return "fdopendir(domain) failed"; } struct dirent* busEntry; - while ((busEntry = readdir(dirDomain)) != NULL) { + while ((busEntry = readdir(dirDomain)) != nullptr) { if (busEntry->d_type != DT_DIR || busEntry->d_name[0] == '.') { continue; } @@ -44,12 +44,12 @@ const char* ffDetectGPUImpl(FF_A_UNUSED const FFGPUOptions* options, FFlist* gpu } FF_AUTO_CLOSE_DIR DIR* dirBus = fdopendir(dBusFd); - if (dirBus == NULL) { + if (dirBus == nullptr) { continue; } struct dirent* devEntry; - while ((devEntry = readdir(dirBus)) != NULL) { + while ((devEntry = readdir(dirBus)) != nullptr) { if (devEntry->d_type != DT_DIR || devEntry->d_name[0] == '.') { continue; } @@ -65,12 +65,12 @@ const char* ffDetectGPUImpl(FF_A_UNUSED const FFGPUOptions* options, FFlist* gpu } FF_AUTO_CLOSE_DIR DIR* dirDev = fdopendir(dDevFd); - if (dirDev == NULL) { + if (dirDev == nullptr) { continue; } struct dirent* funcEntry; - while ((funcEntry = readdir(dirDev)) != NULL) { + while ((funcEntry = readdir(dirDev)) != nullptr) { if (funcEntry->d_type != DT_DIR || funcEntry->d_name[0] == '.') { continue; } @@ -143,5 +143,5 @@ const char* ffDetectGPUImpl(FF_A_UNUSED const FFGPUOptions* options, FFlist* gpu } } - return NULL; + return nullptr; } diff --git a/src/detection/gpu/gpu_haiku.c b/src/detection/gpu/gpu_haiku.c index 20a4ae5f6c..6d2bf7d3fa 100644 --- a/src/detection/gpu/gpu_haiku.c +++ b/src/detection/gpu/gpu_haiku.c @@ -3,7 +3,7 @@ #include -const char* ffDetectGPUImpl(FF_A_UNUSED const FFGPUOptions* options, FFlist* gpus) { +const char* ffDetectGPUImpl([[maybe_unused]] const FFGPUOptions* options, FFlist* gpus) { FF_AUTO_CLOSE_FD int pokefd = open(POKE_DEVICE_FULLNAME, O_RDWR | O_CLOEXEC); if (pokefd < 0) { return "open(POKE_DEVICE_FULLNAME) failed"; @@ -48,5 +48,5 @@ const char* ffDetectGPUImpl(FF_A_UNUSED const FFGPUOptions* options, FFlist* gpu } } - return NULL; + return nullptr; } diff --git a/src/detection/gpu/gpu_intel.c b/src/detection/gpu/gpu_intel.c index 04025b36c8..f19a00e24a 100644 --- a/src/detection/gpu/gpu_intel.c +++ b/src/detection/gpu/gpu_intel.c @@ -26,7 +26,7 @@ struct FFIgclData { static void shutdownIgcl() { if (igclData.apiHandle) { igclData.ffctlClose(igclData.apiHandle); - igclData.apiHandle = NULL; + igclData.apiHandle = nullptr; } } @@ -58,7 +58,7 @@ const char* ffDetectIntelGpuInfo(const FFGpuDriverCondition* cond, FFGpuDriverRe return "loading igcl library failed"; } atexit(shutdownIgcl); - libigcl = NULL; // don't close igcl + libigcl = nullptr; // don't close igcl } if (!igclData.apiHandle) { @@ -66,11 +66,11 @@ const char* ffDetectIntelGpuInfo(const FFGpuDriverCondition* cond, FFGpuDriverRe } uint32_t deviceCount = 0; - // ctlEnumerateDevices MUST be called with deviceCount = 0 and devices = NULL first, + // ctlEnumerateDevices MUST be called with deviceCount = 0 and devices = nullptr first, // otherwise it will be silently ignored and return CTL_RESULT_SUCCESS with deviceCount and devices unmodified. // VERY STRANGE BEHAVIOR - if (igclData.ffctlEnumerateDevices(igclData.apiHandle, &deviceCount, NULL) != CTL_RESULT_SUCCESS) { - return "ctlEnumerateDevices(NULL) failed"; + if (igclData.ffctlEnumerateDevices(igclData.apiHandle, &deviceCount, nullptr) != CTL_RESULT_SUCCESS) { + return "ctlEnumerateDevices(nullptr) failed"; } if (deviceCount == 0) { return "No Intel graphics adapter found"; @@ -81,7 +81,7 @@ const char* ffDetectIntelGpuInfo(const FFGpuDriverCondition* cond, FFGpuDriverRe return "ctlEnumerateDevices(devices) failed"; } - ctl_device_adapter_handle_t device = NULL; + ctl_device_adapter_handle_t device = nullptr; uint64_t /* LUID */ deviceId = 0; ctl_device_adapter_properties_t properties = { @@ -257,5 +257,5 @@ const char* ffDetectIntelGpuInfo(const FFGpuDriverCondition* cond, FFGpuDriverRe } } - return NULL; + return nullptr; } diff --git a/src/detection/gpu/gpu_linux.c b/src/detection/gpu/gpu_linux.c index 91f6b566d6..9575d9ff46 100644 --- a/src/detection/gpu/gpu_linux.c +++ b/src/detection/gpu/gpu_linux.c @@ -7,7 +7,7 @@ #include #include -static bool detectDriverFromSysfs(FFstrbuf* result, FFstrbuf* pciDir, FFstrbuf* buffer, FF_A_UNUSED const char* drmKey) { +static bool detectDriverFromSysfs(FFstrbuf* result, FFstrbuf* pciDir, FFstrbuf* buffer, [[maybe_unused]] const char* drmKey) { uint32_t pciDirLength = pciDir->length; ffStrbufAppendS(pciDir, "/driver"); char pathBuf[PATH_MAX]; @@ -52,7 +52,7 @@ static bool detectDriverFromSysfs(FFstrbuf* result, FFstrbuf* pciDir, FFstrbuf* return true; } -FF_A_UNUSED static const char* drmFindRenderFromCard(const char* drmCardKey, FFstrbuf* result) { +[[maybe_unused]] static const char* drmFindRenderFromCard(const char* drmCardKey, FFstrbuf* result) { char path[PATH_MAX]; sprintf(path, "/sys/class/drm/%s/device/drm", drmCardKey); FF_AUTO_CLOSE_DIR DIR* dirp = opendir(path); @@ -61,11 +61,11 @@ FF_A_UNUSED static const char* drmFindRenderFromCard(const char* drmCardKey, FFs } struct dirent* entry; - while ((entry = readdir(dirp)) != NULL) { + while ((entry = readdir(dirp)) != nullptr) { if (ffStrStartsWith(entry->d_name, "render")) { ffStrbufSetS(result, "/dev/dri/"); ffStrbufAppendS(result, entry->d_name); - return NULL; + return nullptr; } } return "Failed to find render device"; @@ -95,7 +95,7 @@ static void pciDetectAmdSpecific(const FFGPUOptions* options, FFGPUResult* gpu, } struct dirent* entry; - while ((entry = readdir(dirp)) != NULL) { + while ((entry = readdir(dirp)) != nullptr) { if (entry->d_name[0] == '.') { continue; } @@ -186,7 +186,7 @@ static void pciDetectIntelSpecific(const FFGPUOptions* options, FFGPUResult* gpu FF_AUTO_CLOSE_DIR DIR* dirp = opendir(pciDir->chars); if (dirp) { struct dirent* entry; - while ((entry = readdir(dirp)) != NULL) { + while ((entry = readdir(dirp)) != nullptr) { if (entry->d_name[0] == '.') { continue; } @@ -249,7 +249,7 @@ static const char* pciDetectTempGeneral(const FFGPUOptions* options, FFGPUResult } ffStrbufSubstrBefore(pciDir, pciDirLen); } - return NULL; + return nullptr; } static const char* drmDetectNouveauSpecific(FFGPUResult* gpu, const char* drmKey, FFstrbuf* buffer) { @@ -302,7 +302,7 @@ static const char* pciDetectZxSpecific(const FFGPUOptions* options, FFGPUResult* } } - return NULL; + return nullptr; } static inline uint16_t pcieLinkSpeedToGen(const FFstrbuf* buffer) { @@ -344,7 +344,7 @@ static const char* detectPci(const FFGPUOptions* options, FFlist* gpus, FFstrbuf } char pciPath[PATH_MAX]; - const char* pPciPath = NULL; + const char* pPciPath = nullptr; if (drmKey) { ssize_t pathLength = readlink(deviceDir->chars, pciPath, ARRAY_SIZE(pciPath) - 1); if (pathLength <= 0) { @@ -352,7 +352,7 @@ static const char* detectPci(const FFGPUOptions* options, FFlist* gpus, FFstrbuf } pciPath[pathLength] = '\0'; pPciPath = strrchr(pciPath, '/'); - if (__builtin_expect(pPciPath != NULL, true)) { + if (__builtin_expect(pPciPath != nullptr, true)) { pPciPath++; } else { pPciPath = pciPath; @@ -394,7 +394,7 @@ static const char* detectPci(const FFGPUOptions* options, FFlist* gpus, FFstrbuf FF_AUTO_CLOSE_DIR DIR* dirp = opendir(deviceDir->chars); if (dirp) { struct dirent* entry; - while ((entry = readdir(dirp)) != NULL) { + while ((entry = readdir(dirp)) != nullptr) { if (ffStrStartsWith(entry->d_name, "card")) { ffStrCopy(drmKeyBuffer, entry->d_name, ARRAY_SIZE(drmKeyBuffer)); drmKey = drmKeyBuffer; @@ -415,7 +415,7 @@ static const char* detectPci(const FFGPUOptions* options, FFlist* gpus, FFstrbuf if (gpu->vendor.chars == FF_GPU_VENDOR_NAME_AMD) { bool ok = false; if (drmKey && options->driverSpecific) { - ok = drmDetectAmdSpecific(options, gpu, drmKey, buffer) == NULL; + ok = drmDetectAmdSpecific(options, gpu, drmKey, buffer) == nullptr; } if (!ok) { @@ -491,13 +491,13 @@ static const char* detectPci(const FFGPUOptions* options, FFlist* gpus, FFstrbuf } } - return NULL; + return nullptr; } #if __aarch64__ #include "detection/cpu/cpu.h" -FF_A_UNUSED static const char* drmDetectAsahiSpecific(FFGPUResult* gpu, const char* name, FF_A_UNUSED FFstrbuf* buffer, FF_A_UNUSED const char* drmKey) { +[[maybe_unused]] static const char* drmDetectAsahiSpecific(FFGPUResult* gpu, const char* name, [[maybe_unused]] FFstrbuf* buffer, [[maybe_unused]] const char* drmKey) { if (sscanf(name, "agx-t%lu", &gpu->deviceId) == 1) { ffStrbufSetStatic(&gpu->name, ffCPUAppleCodeToName((uint32_t) gpu->deviceId)); } @@ -510,7 +510,7 @@ FF_A_UNUSED static const char* drmDetectAsahiSpecific(FFGPUResult* gpu, const ch return ffDrmDetectAsahi(gpu, fd); } - return NULL; + return nullptr; } #endif @@ -563,7 +563,7 @@ static const char* detectOf(FFlist* gpus, FFstrbuf* buffer, FFstrbuf* drmDir, co } } - return NULL; + return nullptr; } static const char* drmDetectGPUs(const FFGPUOptions* options, FFlist* gpus) { @@ -572,16 +572,16 @@ static const char* drmDetectGPUs(const FFGPUOptions* options, FFlist* gpus) { const uint32_t drmDirLength = drmDir.length; FF_AUTO_CLOSE_DIR DIR* dir = opendir(drmDir.chars); - if (dir == NULL) { + if (dir == nullptr) { return "Failed to open `/sys/class/drm/`"; } FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); struct dirent* entry; - while ((entry = readdir(dir)) != NULL) { + while ((entry = readdir(dir)) != nullptr) { if (!ffStrStartsWith(entry->d_name, "card") || - strchr(entry->d_name + 4, '-') != NULL) { + strchr(entry->d_name + 4, '-') != nullptr) { continue; } @@ -603,7 +603,7 @@ static const char* drmDetectGPUs(const FFGPUOptions* options, FFlist* gpus) { ffStrbufSubstrBefore(&drmDir, drmDirLength); } - return NULL; + return nullptr; } static const char* pciDetectGPUs(const FFGPUOptions* options, FFlist* gpus) { @@ -611,7 +611,7 @@ static const char* pciDetectGPUs(const FFGPUOptions* options, FFlist* gpus) { const char* pciDirPath = "/sys/bus/pci/devices/"; FF_AUTO_CLOSE_DIR DIR* dirp = opendir(pciDirPath); - if (dirp == NULL) { + if (dirp == nullptr) { return "Failed to open `/sys/bus/pci/devices/`"; } @@ -623,7 +623,7 @@ static const char* pciDetectGPUs(const FFGPUOptions* options, FFlist* gpus) { FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); struct dirent* entry; - while ((entry = readdir(dirp)) != NULL) { + while ((entry = readdir(dirp)) != nullptr) { if (entry->d_name[0] == '.') { continue; } @@ -639,24 +639,24 @@ static const char* pciDetectGPUs(const FFGPUOptions* options, FFlist* gpus) { ffStrbufSubstrBefore(&pciDir, pciDevDirLength); assert(ffStrbufStartsWithS(&buffer, "pci:")); - detectPci(options, gpus, &buffer, &pciDir, NULL); + detectPci(options, gpus, &buffer, &pciDir, nullptr); ffStrbufSubstrBefore(&pciDir, pciBaseDirLength); } - return NULL; + return nullptr; } const char* ffDetectGPUImpl(const FFGPUOptions* options, FFlist* gpus) { #if __x86_64__ || __aarch64__ const char* ffGPUDetectWsl2(const FFGPUOptions* options, FFlist* gpus); - if (ffGPUDetectWsl2(options, gpus) == NULL) { - return NULL; + if (ffGPUDetectWsl2(options, gpus) == nullptr) { + return nullptr; } #endif if (options->detectionMethod == FF_GPU_DETECTION_METHOD_AUTO) { - if (drmDetectGPUs(options, gpus) == NULL && gpus->length > 0) { - return NULL; + if (drmDetectGPUs(options, gpus) == nullptr && gpus->length > 0) { + return nullptr; } } return pciDetectGPUs(options, gpus); diff --git a/src/detection/gpu/gpu_mthreads.c b/src/detection/gpu/gpu_mthreads.c index 8d5271935e..5a6b6a467d 100644 --- a/src/detection/gpu/gpu_mthreads.c +++ b/src/detection/gpu/gpu_mthreads.c @@ -29,7 +29,7 @@ struct FFMtmlData { MtmlSystem* sys; } mtmlData; -FF_A_UNUSED static void shutdownMtml(void) { +[[maybe_unused]] static void shutdownMtml(void) { mtmlData.ffmtmlLibraryShutDown(mtmlData.lib); } @@ -61,23 +61,23 @@ const char* ffDetectMthreadsGpuInfo(const FFGpuDriverCondition* cond, FFGpuDrive FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(libmtml, mtmlData, mtmlLibraryShutDown) if (ffmtmlLibraryInit(&mtmlData.lib) != MTML_SUCCESS) { - mtmlData.ffmtmlLibraryInitSystem = NULL; + mtmlData.ffmtmlLibraryInitSystem = nullptr; return "mtmlLibraryInit failed"; } if (mtmlData.ffmtmlLibraryInitSystem(mtmlData.lib, &mtmlData.sys) != MTML_SUCCESS) { mtmlData.ffmtmlLibraryShutDown(mtmlData.lib); - mtmlData.ffmtmlLibraryInitSystem = NULL; + mtmlData.ffmtmlLibraryInitSystem = nullptr; return "mtmlLibraryInitSystem failed"; } atexit(shutdownMtml); - libmtml = NULL; // don't close mtml + libmtml = nullptr; // don't close mtml } - if (mtmlData.ffmtmlLibraryInitSystem == NULL) { + if (mtmlData.ffmtmlLibraryInitSystem == nullptr) { return "loading mtml library failed"; } - MtmlDevice* device = NULL; + MtmlDevice* device = nullptr; if (cond->type & FF_GPU_DRIVER_CONDITION_TYPE_BUS_ID) { char pciBusIdStr[32]; snprintf(pciBusIdStr, ARRAY_SIZE(pciBusIdStr) - 1, "%04x:%02x:%02x.%d", cond->pciBusId.domain, cond->pciBusId.bus, cond->pciBusId.device, cond->pciBusId.func); @@ -92,7 +92,7 @@ const char* ffDetectMthreadsGpuInfo(const FFGpuDriverCondition* cond, FFGpuDrive return "mtmlLibraryCountDevice() failed"; } - for (uint32_t i = 0; i < count; i++, device = NULL) { + for (uint32_t i = 0; i < count; i++, device = nullptr) { if (mtmlData.ffmtmlLibraryInitDeviceByIndex(mtmlData.lib, i, &device) != MTML_SUCCESS) { continue; } @@ -135,7 +135,7 @@ const char* ffDetectMthreadsGpuInfo(const FFGpuDriverCondition* cond, FFGpuDrive } if (result.temp) { - MtmlGpu* gpu = NULL; + MtmlGpu* gpu = nullptr; if (mtmlData.ffmtmlDeviceInitGpu(device, &gpu) == MTML_SUCCESS) { uint32_t value; if (mtmlData.ffmtmlGpuGetTemperature(gpu, &value) == MTML_SUCCESS) { @@ -145,7 +145,7 @@ const char* ffDetectMthreadsGpuInfo(const FFGpuDriverCondition* cond, FFGpuDrive } if (result.memory) { - MtmlMemory* mem = NULL; + MtmlMemory* mem = nullptr; if (mtmlData.ffmtmlDeviceInitMemory(device, &mem) == MTML_SUCCESS) { unsigned long long total; if (mtmlData.ffmtmlMemoryGetTotal(mem, &total) == MTML_SUCCESS) { @@ -164,7 +164,7 @@ const char* ffDetectMthreadsGpuInfo(const FFGpuDriverCondition* cond, FFGpuDrive } if (result.frequency) { - MtmlGpu* gpu = NULL; + MtmlGpu* gpu = nullptr; if (mtmlData.ffmtmlDeviceInitGpu(device, &gpu) == MTML_SUCCESS) { uint32_t clockMHz; if (mtmlData.ffmtmlGpuGetMaxClock(gpu, &clockMHz) == MTML_SUCCESS) { @@ -174,7 +174,7 @@ const char* ffDetectMthreadsGpuInfo(const FFGpuDriverCondition* cond, FFGpuDrive } if (result.coreUsage) { - MtmlGpu* gpu = NULL; + MtmlGpu* gpu = nullptr; if (mtmlData.ffmtmlDeviceInitGpu(device, &gpu) == MTML_SUCCESS) { unsigned int utilization; if (mtmlData.ffmtmlGpuGetUtilization(gpu, &utilization) == MTML_SUCCESS) { @@ -204,7 +204,7 @@ const char* ffDetectMthreadsGpuInfo(const FFGpuDriverCondition* cond, FFGpuDrive } } - return NULL; + return nullptr; #else diff --git a/src/detection/gpu/gpu_nbsd.c b/src/detection/gpu/gpu_nbsd.c index 10b920da93..e3d04c14e4 100644 --- a/src/detection/gpu/gpu_nbsd.c +++ b/src/detection/gpu/gpu_nbsd.c @@ -26,7 +26,7 @@ static inline int pciReadConf(int fd, uint32_t bus, uint32_t device, uint32_t fu return 0; } -const char* ffDetectGPUImpl(FF_A_UNUSED const FFGPUOptions* options, FFlist* gpus) { +const char* ffDetectGPUImpl([[maybe_unused]] const FFGPUOptions* options, FFlist* gpus) { char pciDevPath[] = "/dev/pciXXX"; for (uint32_t idev = 0; idev <= 255; idev++) { @@ -117,5 +117,5 @@ const char* ffDetectGPUImpl(FF_A_UNUSED const FFGPUOptions* options, FFlist* gpu } } - return NULL; + return nullptr; } diff --git a/src/detection/gpu/gpu_nvidia.c b/src/detection/gpu/gpu_nvidia.c index 4ec979f6b5..d32dd542e3 100644 --- a/src/detection/gpu/gpu_nvidia.c +++ b/src/detection/gpu/gpu_nvidia.c @@ -52,8 +52,8 @@ static const char* detectMoreByNvapi(FFGpuDriverResult* result) { 1); FF_LIBRARY_LOAD_SYMBOL_MESSAGE(libnvapi, nvapi_QueryInterface) #define FF_NVAPI_INTERFACE(iName, iOffset) \ - __typeof__(&iName) ff##iName = ffnvapi_QueryInterface(iOffset); \ - if (ff##iName == NULL) return "nvapi_QueryInterface " #iName " failed"; + typeof(&iName) ff##iName = ffnvapi_QueryInterface(iOffset); \ + if (ff##iName == nullptr) return "nvapi_QueryInterface " #iName " failed"; FF_NVAPI_INTERFACE(nvapi_Initialize, NVAPI_INTERFACE_OFFSET_INITIALIZE) FF_NVAPI_INTERFACE(nvapi_Unload, NVAPI_INTERFACE_OFFSET_UNLOAD) @@ -72,10 +72,10 @@ static const char* detectMoreByNvapi(FFGpuDriverResult* result) { nvapiData.ffnvapi_Unload = ffnvapi_Unload; atexit((void*) ffnvapi_Unload); - libnvapi = NULL; // don't close nvapi + libnvapi = nullptr; // don't close nvapi } - if (nvapiData.ffnvapi_EnumPhysicalGPUs == NULL) { + if (nvapiData.ffnvapi_EnumPhysicalGPUs == nullptr) { return "loading nvapi library failed"; } @@ -141,7 +141,7 @@ static const char* detectMoreByNvapi(FFGpuDriverResult* result) { } } - return NULL; + return nullptr; } #endif @@ -173,18 +173,18 @@ const char* ffDetectNvidiaGpuInfo(const FFGpuDriverCondition* cond, FFGpuDriverR FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(libnvml, nvmlData, nvmlDeviceGetName) if (ffnvmlInit_v2() != NVML_SUCCESS) { - nvmlData.ffnvmlDeviceGetNumGpuCores = NULL; + nvmlData.ffnvmlDeviceGetNumGpuCores = nullptr; return "nvmlInit_v2() failed"; } atexit((void*) ffnvmlShutdown); - libnvml = NULL; // don't close nvml + libnvml = nullptr; // don't close nvml } - if (nvmlData.ffnvmlDeviceGetNumGpuCores == NULL) { + if (nvmlData.ffnvmlDeviceGetNumGpuCores == nullptr) { return "loading nvml library failed"; } - nvmlDevice_t device = NULL; + nvmlDevice_t device = nullptr; if (cond->type & FF_GPU_DRIVER_CONDITION_TYPE_BUS_ID) { char pciBusIdStr[32]; snprintf(pciBusIdStr, ARRAY_SIZE(pciBusIdStr), "%04x:%02x:%02x.%d", cond->pciBusId.domain, cond->pciBusId.bus, cond->pciBusId.device, cond->pciBusId.func); @@ -199,7 +199,7 @@ const char* ffDetectNvidiaGpuInfo(const FFGpuDriverCondition* cond, FFGpuDriverR return "nvmlDeviceGetCount_v2() failed"; } - for (uint32_t i = 0; i < count; i++, device = NULL) { + for (uint32_t i = 0; i < count; i++, device = nullptr) { if (nvmlData.ffnvmlDeviceGetHandleByIndex_v2(i, &device) != NVML_SUCCESS) { continue; } @@ -319,7 +319,7 @@ const char* ffDetectNvidiaGpuInfo(const FFGpuDriverCondition* cond, FFGpuDriverR } } - return NULL; + return nullptr; #else diff --git a/src/detection/gpu/gpu_obsd.c b/src/detection/gpu/gpu_obsd.c index 8d0ee9a31f..4dd2d83278 100644 --- a/src/detection/gpu/gpu_obsd.c +++ b/src/detection/gpu/gpu_obsd.c @@ -27,7 +27,7 @@ static inline int pciReadConf(int fd, uint8_t bus, uint8_t device, uint8_t func, return 0; } -const char* detectByPci(FF_A_UNUSED const FFGPUOptions* options, FFlist* gpus) { +const char* detectByPci([[maybe_unused]] const FFGPUOptions* options, FFlist* gpus) { char pciDevPath[] = "/dev/pci0"; FF_AUTO_CLOSE_FD int pcifd = open(pciDevPath, O_RDONLY | O_CLOEXEC); if (pcifd < 0) { @@ -98,7 +98,7 @@ const char* detectByPci(FF_A_UNUSED const FFGPUOptions* options, FFlist* gpus) { } } - return NULL; + return nullptr; } const char* ffDetectGPUImpl(const FFGPUOptions* options, FFlist* gpus) { @@ -106,7 +106,7 @@ const char* ffDetectGPUImpl(const FFGPUOptions* options, FFlist* gpus) { if (options->detectionMethod == FF_GPU_DETECTION_METHOD_AUTO) { ffGPUDetectByDrmBSD(options, gpus); if (gpus->length > 0) { - return NULL; + return nullptr; } } #endif diff --git a/src/detection/gpu/gpu_sunos.c b/src/detection/gpu/gpu_sunos.c index dbf168c578..8e896625ff 100644 --- a/src/detection/gpu/gpu_sunos.c +++ b/src/detection/gpu/gpu_sunos.c @@ -3,7 +3,7 @@ #include -static int walkDevTree(di_node_t node, FF_A_UNUSED di_minor_t minor, FFlist* gpus) { +static int walkDevTree(di_node_t node, [[maybe_unused]] di_minor_t minor, FFlist* gpus) { int* vendorId; int* deviceId; if (di_prop_lookup_ints(DDI_DEV_T_ANY, node, "vendor-id", &vendorId) > 0 && di_prop_lookup_ints(DDI_DEV_T_ANY, node, "device-id", &deviceId) > 0) { @@ -19,7 +19,7 @@ static int walkDevTree(di_node_t node, FF_A_UNUSED di_minor_t minor, FFlist* gpu gpu->coreUsage = FF_GPU_CORE_USAGE_UNSET; gpu->type = FF_GPU_TYPE_UNKNOWN; gpu->dedicated.total = gpu->dedicated.used = gpu->shared.total = gpu->shared.used = FF_GPU_VMEM_SIZE_UNSET; - gpu->deviceId = strtoul(di_bus_addr(node), NULL, 16); + gpu->deviceId = strtoul(di_bus_addr(node), nullptr, 16); gpu->frequency = FF_GPU_FREQUENCY_UNSET; gpu->pcieSpeed = FF_GPU_PCIE_SPEED_UNSET; @@ -43,7 +43,7 @@ static int walkDevTree(di_node_t node, FF_A_UNUSED di_minor_t minor, FFlist* gpu return DI_WALK_CONTINUE; } -const char* ffDetectGPUImpl(FF_A_UNUSED const FFGPUOptions* options, FFlist* gpus) { +const char* ffDetectGPUImpl([[maybe_unused]] const FFGPUOptions* options, FFlist* gpus) { di_node_t rootNode = di_init("/", DINFOCPYALL); if (rootNode == DI_NODE_NIL) { return "di_init() failed"; @@ -51,5 +51,5 @@ const char* ffDetectGPUImpl(FF_A_UNUSED const FFGPUOptions* options, FFlist* gpu di_walk_minor(rootNode, DDI_NT_DISPLAY, DI_WALK_CLDFIRST, gpus, (void*) walkDevTree); di_fini(rootNode); - return NULL; + return nullptr; } diff --git a/src/detection/gpu/gpu_windows.c b/src/detection/gpu/gpu_windows.c index 589fee4e1c..526ff66a5d 100644 --- a/src/detection/gpu/gpu_windows.c +++ b/src/detection/gpu/gpu_windows.c @@ -17,12 +17,16 @@ #include #include #include + #include #include #define GUID_DEVCLASS_DISPLAY_STRING L"{4d36e968-e325-11ce-bfc1-08002be10318}" // Found in -static bool queryPciDeviceInfo(FFGPUResult* gpu, D3DKMT_DEVICE_IDS* outDeviceIds, bool queryPcieGen) { - FF_DEBUG("Query PCI device info: %08llX", gpu->deviceId); +// https://wine-devel.winehq.narkive.com/vKO2Bkgj/patch-1-2-dxgi-tests-add-test-for-enumerating-display-adapters-using-setupapi +DEFINE_DEVPROPKEY(DEVPROPKEY_DISPLAY_ADAPTER_LUID, 0x60b193cb, 0x5276, 0x4d0f, 0x96, 0xfc, 0xf1, 0x73, 0xab, 0xad, 0x3e, 0xc6, 2); + +static bool queryDeviceInfoCM(FFGPUResult* gpu, uint64_t luid, D3DKMT_DEVICE_IDS* outDeviceIds, bool queryPcieGen) { + FF_DEBUG("Query PCI device info: %08llX with LUID: %08llX", gpu->deviceId, luid); static FFlist deviceIdsCache; static bool initialized; @@ -32,7 +36,10 @@ static bool queryPciDeviceInfo(FFGPUResult* gpu, D3DKMT_DEVICE_IDS* outDeviceIds uint32_t maxLinkSpeed; uint32_t maxLinkWidth; D3DKMT_DEVICE_IDS deviceIds; - uint64_t adapterAddress; + uint64_t pciAddr; + uint64_t luid; + FFstrbuf vendor; + FFstrbuf name; } CacheEntry; if (!initialized) { @@ -71,13 +78,36 @@ static bool queryPciDeviceInfo(FFGPUResult* gpu, D3DKMT_DEVICE_IDS* outDeviceIds } } - if (wcsncmp(devId, L"PCI\\", 4) != 0) { - FF_DEBUG("Skipping non-PCI device ID: %ls", devId); - continue; - } - CacheEntry* entry = FF_LIST_ADD(CacheEntry, deviceIdsCache); - *entry = (CacheEntry) {}; + *entry = (CacheEntry){}; + + ULONG bufLen = sizeof(entry->luid); + DEVPROPTYPE type; + CONFIGRET ret = CM_Get_DevNode_PropertyW(devInst, &DEVPROPKEY_DISPLAY_ADAPTER_LUID, &type, (PBYTE) &entry->luid, &bufLen, 0); + if (ret != CR_SUCCESS) { // Not available on Windows 8.1 + FF_DEBUG("Failed to get device LUID: %s", ffDebugConfigRet(ret)); + + uint32_t pciBus = 0; + ULONG pciBufLen = sizeof(pciBus); + if (CM_Get_DevNode_Registry_PropertyW(devInst, CM_DRP_BUSNUMBER, nullptr, &pciBus, &pciBufLen, 0) == CR_SUCCESS) { + uint32_t pciAddr = 0; + pciBufLen = sizeof(pciAddr); + if (CM_Get_DevNode_Registry_PropertyW(devInst, CM_DRP_ADDRESS, nullptr, &pciAddr, &pciBufLen, 0) == CR_SUCCESS) { + entry->pciAddr = ffGPUPciAddr2Id(0, pciBus, (pciAddr >> 16) & 0xFFFF, pciAddr & 0xFFFF); + FF_DEBUG("Cached device IDs for PCI bus %u: vendor=0x%04x device=0x%04x", pciBus, entry->deviceIds.VendorID, entry->deviceIds.DeviceID); + } else { + FF_DEBUG("Failed to get PCI address"); + } + } else { + FF_DEBUG("Failed to get PCI bus number"); + } + + if (entry->pciAddr == 0) { + FF_DEBUG("Skipping device ID: %ls due to missing LUID and PCI address", devId); + deviceIdsCache.length--; + continue; + } + } // L"PCI\\VEN_10DE&DEV_2782&SUBSYS_513417AA&REV_A1\\4&3674a6b9&0&0008" if (swscanf(devId + 4, L"VEN_%x&DEV_%x&SUBSYS_%4x%4x&REV_%x", &entry->deviceIds.VendorID, &entry->deviceIds.DeviceID, &entry->deviceIds.SubSystemID, &entry->deviceIds.SubVendorID, &entry->deviceIds.RevisionID) >= 2) { @@ -87,32 +117,44 @@ static bool queryPciDeviceInfo(FFGPUResult* gpu, D3DKMT_DEVICE_IDS* outDeviceIds // And yeah, DXGKMDT_OPM_BUS_TYPE_PCIEXPRESS (3) exists entry->deviceIds.BusType = 1; } else { - FF_DEBUG("Failed to parse PCI IDs from device ID string"); - deviceIdsCache.length--; // remove the cache entry since it's not valid - continue; + FF_DEBUG("Failed to parse PCI IDs from device ID: %ls", devId); + entry->deviceIds.VendorID = -1u; } - uint32_t pciBus = 0; - ULONG pciBufLen = sizeof(pciBus); - if (CM_Get_DevNode_Registry_PropertyW(devInst, CM_DRP_BUSNUMBER, NULL, &pciBus, &pciBufLen, 0) == CR_SUCCESS) { - uint32_t pciAddr = 0; - pciBufLen = sizeof(pciAddr); - if (CM_Get_DevNode_Registry_PropertyW(devInst, CM_DRP_ADDRESS, NULL, &pciAddr, &pciBufLen, 0) == CR_SUCCESS) { - entry->adapterAddress = ffGPUPciAddr2Id(0, pciBus, (pciAddr >> 16) & 0xFFFF, pciAddr & 0xFFFF); - FF_DEBUG("Cached device IDs for PCI bus %u: vendor=0x%04x device=0x%04x", pciBus, entry->deviceIds.VendorID, entry->deviceIds.DeviceID); + wchar_t wstr[256]; + bufLen = sizeof(wstr); + ret = CM_Get_DevNode_PropertyW(devInst, &DEVPKEY_Device_FriendlyName, &type, (PBYTE) wstr, &bufLen, 0); + if (ret == CR_SUCCESS) { + ffStrbufSetNWS(&entry->name, (bufLen - 1) / sizeof(wchar_t), wstr); + FF_DEBUG("Device friendly name: %ls", wstr); + } else { + FF_DEBUG("Failed to get device friendly name: %s", ffDebugConfigRet(ret)); + + bufLen = sizeof(wstr); + ret = CM_Get_DevNode_PropertyW(devInst, &DEVPKEY_Device_DeviceDesc, &type, (PBYTE) wstr, &bufLen, 0); + if (ret == CR_SUCCESS) { + ffStrbufSetNWS(&entry->name, (bufLen - 1) / sizeof(wchar_t), wstr); + FF_DEBUG("Device description: %ls", wstr); } else { - FF_DEBUG("Failed to get PCI address"); + FF_DEBUG("Failed to get device description: %s", ffDebugConfigRet(ret)); } + } + + bufLen = sizeof(wstr); + ret = CM_Get_DevNode_PropertyW(devInst, &DEVPKEY_Device_Manufacturer, &type, (PBYTE) wstr, &bufLen, 0); + if (ret == CR_SUCCESS) { + ffStrbufSetNWS(&entry->vendor, (bufLen - 1) / sizeof(wchar_t), wstr); + FF_DEBUG("Device vendor name: %ls", wstr); } else { - FF_DEBUG("Failed to get PCI bus number"); + FF_DEBUG("Failed to get device vendor name: %s", ffDebugConfigRet(ret)); } - if (queryPcieGen) { + if (queryPcieGen && entry->deviceIds.VendorID != -1u) { DEVPROPTYPE propType; - pciBufLen = sizeof(entry->maxLinkSpeed); + bufLen = sizeof(entry->maxLinkSpeed); // Reports PCIe gen despite the PKEY name - CONFIGRET ret = CM_Get_DevNode_PropertyW(devInst, &DEVPKEY_PciDevice_MaxLinkSpeed, &propType, (PBYTE) &entry->maxLinkSpeed, &pciBufLen, 0); + CM_Get_DevNode_PropertyW(devInst, &DEVPKEY_PciDevice_MaxLinkSpeed, &propType, (PBYTE) &entry->maxLinkSpeed, &bufLen, 0); if (ret == CR_SUCCESS) { FF_DEBUG("PCIe max GEN: %u", entry->maxLinkSpeed); } else { @@ -120,8 +162,8 @@ static bool queryPciDeviceInfo(FFGPUResult* gpu, D3DKMT_DEVICE_IDS* outDeviceIds } if (entry->maxLinkSpeed != FF_GPU_PCIE_SPEED_UNSET) { - pciBufLen = sizeof(entry->maxLinkWidth); - ret = CM_Get_DevNode_PropertyW(devInst, &DEVPKEY_PciDevice_MaxLinkWidth, &propType, (PBYTE) &entry->maxLinkWidth, &pciBufLen, 0); + bufLen = sizeof(entry->maxLinkWidth); + ret = CM_Get_DevNode_PropertyW(devInst, &DEVPKEY_PciDevice_MaxLinkWidth, &propType, (PBYTE) &entry->maxLinkWidth, &bufLen, 0); if (ret == CR_SUCCESS) { FF_DEBUG("PCIe max link width: %u", entry->maxLinkWidth); } else { @@ -129,8 +171,8 @@ static bool queryPciDeviceInfo(FFGPUResult* gpu, D3DKMT_DEVICE_IDS* outDeviceIds } } - pciBufLen = sizeof(entry->currentLinkSpeed); - ret = CM_Get_DevNode_PropertyW(devInst, &DEVPKEY_PciDevice_CurrentLinkSpeed, &propType, (PBYTE) &entry->currentLinkSpeed, &pciBufLen, 0); + bufLen = sizeof(entry->currentLinkSpeed); + ret = CM_Get_DevNode_PropertyW(devInst, &DEVPKEY_PciDevice_CurrentLinkSpeed, &propType, (PBYTE) &entry->currentLinkSpeed, &bufLen, 0); if (ret == CR_SUCCESS) { FF_DEBUG("PCIe GEN: %u", entry->currentLinkSpeed); } else { @@ -138,8 +180,8 @@ static bool queryPciDeviceInfo(FFGPUResult* gpu, D3DKMT_DEVICE_IDS* outDeviceIds } if (entry->currentLinkSpeed != FF_GPU_PCIE_SPEED_UNSET) { - pciBufLen = sizeof(entry->currentLinkWidth); - ret = CM_Get_DevNode_PropertyW(devInst, &DEVPKEY_PciDevice_CurrentLinkWidth, &propType, (PBYTE) &entry->currentLinkWidth, &pciBufLen, 0); + bufLen = sizeof(entry->currentLinkWidth); + ret = CM_Get_DevNode_PropertyW(devInst, &DEVPKEY_PciDevice_CurrentLinkWidth, &propType, (PBYTE) &entry->currentLinkWidth, &bufLen, 0); if (ret == CR_SUCCESS) { FF_DEBUG("PCIe current link width: %u", entry->currentLinkWidth); } else { @@ -151,12 +193,31 @@ static bool queryPciDeviceInfo(FFGPUResult* gpu, D3DKMT_DEVICE_IDS* outDeviceIds } FF_LIST_FOR_EACH (CacheEntry, entry, deviceIdsCache) { - if (gpu->deviceId == entry->adapterAddress) { - FF_DEBUG("Cache hit for adapter address: %08llX", gpu->deviceId); + if (luid == entry->luid || entry->pciAddr == gpu->deviceId) { + FF_DEBUG("Cache hit for adapter LUID: %08llX", luid); if (outDeviceIds->VendorID == -1u) { *outDeviceIds = entry->deviceIds; } + if (gpu->vendor.length == 0) { + if (entry->deviceIds.VendorID != -1u) { + ffStrbufSetStatic(&gpu->vendor, ffGPUGetVendorString(entry->deviceIds.VendorID)); + } + if (gpu->vendor.length == 0 && entry->vendor.length > 0) { + ffStrbufDestroy(&gpu->vendor); + ffStrbufInitMove(&gpu->vendor, &entry->vendor); + } + } else if (gpu->name.length == 0 && entry->deviceIds.VendorID == -1u) { + // Some Indirect display adapters reports fake Device IDs + ffStrbufDestroy(&gpu->vendor); + ffStrbufInitMove(&gpu->vendor, &entry->vendor); + } + + if (gpu->name.length == 0) { + ffStrbufDestroy(&gpu->name); + ffStrbufInitMove(&gpu->name, &entry->name); + } + if (queryPcieGen) { gpu->psMax.gen = (uint16_t) entry->maxLinkSpeed; gpu->psMax.lanes = (uint16_t) entry->maxLinkWidth; @@ -167,37 +228,10 @@ static bool queryPciDeviceInfo(FFGPUResult* gpu, D3DKMT_DEVICE_IDS* outDeviceIds } } - FF_DEBUG("Cache miss for adapter address: %08llX", gpu->deviceId); + FF_DEBUG("Cache miss for adapter LUID: %08llX", luid); return false; } -static bool queryVendorNameViaRegistry(FFstrbuf* vendor, D3DKMT_HANDLE hAdapter) { - // `KMTQAITYPE_QUERY_ADAPTER_UNIQUE_GUID` reports the GUID value used by the adapter's registry key (DirectX and Video) - - GUID guid; - NTSTATUS status = D3DKMTQueryAdapterInfo(&(D3DKMT_QUERYADAPTERINFO) { - .hAdapter = hAdapter, - .Type = KMTQAITYPE_QUERY_ADAPTER_UNIQUE_GUID, - .pPrivateDriverData = &guid, - .PrivateDriverDataSize = sizeof(guid), - }); - if (!NT_SUCCESS(status)) { - FF_DEBUG("Failed to query adapter unique GUID: %s", ffDebugNtStatus(status)); - return false; - } - - wchar_t path[PATH_MAX]; - swprintf(path, ARRAY_SIZE(path), L"SYSTEM\\CurrentControlSet\\Control\\Video\\{%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X}\\0000", guid.Data1, guid.Data2, guid.Data3, guid.Data4[0], guid.Data4[1], guid.Data4[2], guid.Data4[3], guid.Data4[4], guid.Data4[5], guid.Data4[6], guid.Data4[7]); - - FF_DEBUG("Querying registry: HKEY_LOCAL_MACHINE\\%ls\\ProviderName", path); - FF_AUTO_CLOSE_FD HANDLE key = NULL; - if (!ffRegOpenKeyForRead(HKEY_LOCAL_MACHINE, path, &key, NULL)) { - return false; - } - - return ffRegReadStrbuf(key, L"ProviderName", vendor, NULL); -} - #else #include #include @@ -230,7 +264,7 @@ static void closeDxgfd(void) { } } -FF_A_UNUSED static inline const char* ffDebugNtStatus(NTSTATUS status) { +[[maybe_unused]] static inline const char* ffDebugNtStatus(NTSTATUS status) { return status < 0 ? strerror(-status) : "Success"; } #endif @@ -301,6 +335,8 @@ ffGPUDetectWsl2 goto close_adapter; } + uint64_t luid = ((uint64_t) adapter->AdapterLuid.HighPart << 32) | (uint64_t) adapter->AdapterLuid.LowPart; + FFGPUResult* gpu = FF_LIST_ADD(FFGPUResult, *gpus); ffStrbufInit(&gpu->vendor); ffStrbufInit(&gpu->name); @@ -321,7 +357,7 @@ ffGPUDetectWsl2 : FF_GPU_TYPE_UNKNOWN; gpu->pcieSpeed = FF_GPU_PCIE_SPEED_UNSET; - D3DKMT_DRIVERVERSION wddmVersion = KMT_DRIVERVERSION_WDDM_2_0; + D3DKMT_DRIVERVERSION wddmVersion; status = D3DKMTQueryAdapterInfo(&(D3DKMT_QUERYADAPTERINFO) { .hAdapter = adapter->hAdapter, .Type = KMTQAITYPE_DRIVERVERSION, @@ -332,6 +368,7 @@ ffGPUDetectWsl2 ffStrbufSetF(&gpu->platformApi, "WDDM %u.%u", (uint32_t) wddmVersion / 1000, ((uint32_t) wddmVersion % 1000) / 100); FF_DEBUG("Adapter #%u WDDM version: %u", i, (uint32_t) wddmVersion); } else { + wddmVersion = KMT_DRIVERVERSION_WDDM_1_3; // Smallest supported WDDM version, used for fallback ffStrbufSetStatic(&gpu->platformApi, "WDDM"); FF_DEBUG("KMTQAITYPE_DRIVERVERSION query failed for adapter #%u", i); } @@ -352,7 +389,7 @@ ffGPUDetectWsl2 adapterAddress.FunctionNumber); } else { adapterAddress.BusNumber = -1u; - gpu->deviceId = ffGPUGeneral2Id(((uint64_t) adapter->AdapterLuid.HighPart << 32) | (uint64_t) adapter->AdapterLuid.LowPart); + gpu->deviceId = ffGPUGeneral2Id(luid); FF_DEBUG("KMTQAITYPE_ADAPTERADDRESS query failed for adapter #%u, fallback to LUID-based deviceId: %s", i, ffDebugNtStatus(status)); @@ -376,14 +413,6 @@ ffGPUDetectWsl2 FF_DEBUG("KMTQAITYPE_PHYSICALADAPTERDEVICEIDS query failed for adapter #%u: %s", i, ffDebugNtStatus(status)); } - #if _WIN32 && FF_WIN81_COMPAT - if (adapterAddress.BusNumber != -1u && (deviceIds.DeviceIds.VendorID == -1u || options->driverSpecific)) { - if (queryPciDeviceInfo(gpu, &deviceIds.DeviceIds, options->driverSpecific) && gpu->vendor.length == 0) { - ffStrbufSetStatic(&gpu->vendor, ffGPUGetVendorString(deviceIds.DeviceIds.VendorID)); - } - } - #endif - D3DKMT_UMD_DRIVER_VERSION umdDriverVersion; status = D3DKMTQueryAdapterInfo(&(D3DKMT_QUERYADAPTERINFO) { .hAdapter = adapter->hAdapter, @@ -403,63 +432,55 @@ ffGPUDetectWsl2 FF_DEBUG("KMTQAITYPE_UMD_DRIVER_VERSION query failed for adapter #%u: %s", i, ffDebugNtStatus(status)); } - __typeof__(&ffDetectNvidiaGpuInfo) detectFn; - const char* dllName; - if (options->driverSpecific && getDriverSpecificDetectionFn(gpu->vendor.chars, &detectFn, &dllName)) { - FF_DEBUG("Calling driver-specific detection function for vendor: %s, DLL: %s", gpu->vendor.chars, dllName); - FF_A_UNUSED const char* error = detectFn( - &(FFGpuDriverCondition) { - .type = FF_GPU_DRIVER_CONDITION_TYPE_LUID | - (deviceIds.DeviceIds.VendorID != -1u ? FF_GPU_DRIVER_CONDITION_TYPE_DEVICE_ID : 0) | - (adapterAddress.BusNumber != -1u ? FF_GPU_DRIVER_CONDITION_TYPE_BUS_ID : 0), - .pciDeviceId = { - .deviceId = deviceIds.DeviceIds.DeviceID, - .vendorId = deviceIds.DeviceIds.VendorID, - .subSystemId = deviceIds.DeviceIds.SubSystemID, - .revId = deviceIds.DeviceIds.RevisionID, - }, - .pciBusId = { - .domain = 0, - .bus = adapterAddress.BusNumber, - .device = adapterAddress.DeviceNumber, - .func = adapterAddress.FunctionNumber, - }, - .luid = ((uint64_t) adapter->AdapterLuid.HighPart << 32) | (uint64_t) adapter->AdapterLuid.LowPart, - }, - (FFGpuDriverResult) { - .index = &gpu->index, - .temp = options->temp ? &gpu->temperature : NULL, - .memory = options->driverSpecific ? &gpu->dedicated : NULL, - .sharedMemory = options->driverSpecific ? &gpu->shared : NULL, - .memoryType = options->driverSpecific ? &gpu->memoryType : NULL, - .coreCount = options->driverSpecific ? (uint32_t*) &gpu->coreCount : NULL, - .coreUsage = options->driverSpecific ? &gpu->coreUsage : NULL, - .type = &gpu->type, - .frequency = options->driverSpecific ? &gpu->frequency : NULL, - .name = &gpu->name, - .psCurr = options->driverSpecific ? &gpu->psCurr : NULL, - .psMax = options->driverSpecific ? &gpu->psMax : NULL, - }, - dllName); - FF_DEBUG("Driver-specific detection completed: %s", error ?: "Success"); - } else if (options->driverSpecific) { - FF_DEBUG("No driver-specific detection function found for vendor: %s", gpu->vendor.chars); - } - -#if _WIN32 - // Put this after the driver-specific detection, as `getDriverSpecificDetectionFn` never succeeds - if (gpu->vendor.length == 0 && wddmVersion >= KMT_DRIVERVERSION_WDDM_2_4) { - // For non-PCI devices - FF_DEBUG("Attempting to query vendor name via registry for adapter #%u", i); - queryVendorNameViaRegistry(&gpu->vendor, adapter->hAdapter); + bool isIndirectDisplayDevice = gpu->type == FF_GPU_TYPE_UNKNOWN && adapterType.IndirectDisplayDevice; + if (isIndirectDisplayDevice) { + FF_DEBUG("Adapter #%u is an indirect display device", i); } - #if !FF_WIN81_COMPAT - if (adapterAddress.BusNumber != -1u && options->driverSpecific && gpu->pcieSpeed == FF_GPU_PCIE_SPEED_UNSET) { - queryPciDeviceInfo(gpu, &deviceIds.DeviceIds, options->driverSpecific); - } - #endif -#endif + if (!isIndirectDisplayDevice) { + typeof(&ffDetectNvidiaGpuInfo) detectFn; + const char* dllName; + if (options->driverSpecific && getDriverSpecificDetectionFn(gpu->vendor.chars, &detectFn, &dllName)) { + FF_DEBUG("Calling driver-specific detection function for vendor: %s, DLL: %s", gpu->vendor.chars, dllName); + [[maybe_unused]] const char* error = detectFn( + &(FFGpuDriverCondition) { + .type = FF_GPU_DRIVER_CONDITION_TYPE_LUID | + (deviceIds.DeviceIds.VendorID != -1u ? FF_GPU_DRIVER_CONDITION_TYPE_DEVICE_ID : 0) | + (adapterAddress.BusNumber != -1u ? FF_GPU_DRIVER_CONDITION_TYPE_BUS_ID : 0), + .pciDeviceId = { + .deviceId = deviceIds.DeviceIds.DeviceID, + .vendorId = deviceIds.DeviceIds.VendorID, + .subSystemId = deviceIds.DeviceIds.SubSystemID, + .revId = deviceIds.DeviceIds.RevisionID, + }, + .pciBusId = { + .domain = 0, + .bus = adapterAddress.BusNumber, + .device = adapterAddress.DeviceNumber, + .func = adapterAddress.FunctionNumber, + }, + .luid = luid, + }, + (FFGpuDriverResult) { + .index = &gpu->index, + .temp = options->temp ? &gpu->temperature : nullptr, + .memory = options->driverSpecific ? &gpu->dedicated : nullptr, + .sharedMemory = options->driverSpecific ? &gpu->shared : nullptr, + .memoryType = options->driverSpecific ? &gpu->memoryType : nullptr, + .coreCount = options->driverSpecific ? (uint32_t*) &gpu->coreCount : nullptr, + .coreUsage = options->driverSpecific ? &gpu->coreUsage : nullptr, + .type = &gpu->type, + .frequency = options->driverSpecific ? &gpu->frequency : nullptr, + .name = &gpu->name, + .psCurr = options->driverSpecific ? &gpu->psCurr : nullptr, + .psMax = options->driverSpecific ? &gpu->psMax : nullptr, + }, + dllName); + FF_DEBUG("Driver-specific detection completed: %s", error ?: "Success"); + } else if (options->driverSpecific) { + FF_DEBUG("No driver-specific detection function found for vendor: %s", gpu->vendor.chars); + } + }; if (gpu->name.length == 0) { D3DKMT_ADAPTERREGISTRYINFO registryInfo; @@ -477,148 +498,156 @@ ffGPUDetectWsl2 } } - if (gpu->dedicated.total == FF_GPU_VMEM_SIZE_UNSET && gpu->shared.total == FF_GPU_VMEM_SIZE_UNSET) { - if (wddmVersion >= KMT_DRIVERVERSION_WDDM_3_1 && options->driverSpecific) { - // Supports memory usage query; requires Windows 11 (22H2) or later - D3DKMT_QUERYSTATISTICS queryStatistics = { - .Type = D3DKMT_QUERYSTATISTICS_SEGMENT_GROUP_USAGE, - .AdapterLuid = adapter->AdapterLuid, - .QuerySegmentGroupUsage = { - .PhysicalAdapterIndex = 0, - .SegmentGroup = D3DKMT_MEMORY_SEGMENT_GROUP_LOCAL, - }, - }; - status = D3DKMTQueryStatistics(&queryStatistics); - if (NT_SUCCESS(status)) { - D3DKMT_QUERYSTATISTICS_MEMORY_USAGE* info = &queryStatistics.QueryResult.SegmentGroupUsageInformation; - uint64_t used = info->AllocatedBytes + info->ModifiedBytes + info->StandbyBytes; - uint64_t total = used + info->FreeBytes + info->ZeroBytes; - gpu->dedicated.used = used; - gpu->dedicated.total = total; - FF_DEBUG("Adapter #%u local memory usage: used=%" PRIu64 " total=%" PRIu64, i, used, total); - } else { - FF_DEBUG("D3DKMT_QUERYSTATISTICS_SEGMENT_GROUP_USAGE (LOCAL) failed for adapter #%u: %s", - i, - ffDebugNtStatus(status)); - } - - queryStatistics.QuerySegmentGroupUsage.SegmentGroup = D3DKMT_MEMORY_SEGMENT_GROUP_NON_LOCAL; - status = D3DKMTQueryStatistics(&queryStatistics); - if (NT_SUCCESS(status)) { - D3DKMT_QUERYSTATISTICS_MEMORY_USAGE* info = &queryStatistics.QueryResult.SegmentGroupUsageInformation; - uint64_t used = info->AllocatedBytes + info->ModifiedBytes + info->StandbyBytes; - uint64_t total = used + info->FreeBytes + info->ZeroBytes; - gpu->shared.used = used; - gpu->shared.total = total; - FF_DEBUG("Adapter #%u non-local memory usage: used=%" PRIu64 " total=%" PRIu64, i, used, total); - } else { - FF_DEBUG("D3DKMT_QUERYSTATISTICS_SEGMENT_GROUP_USAGE (NON_LOCAL) failed for adapter #%u: %s", - i, - ffDebugNtStatus(status)); - } - } else { - // Supports basic segment (total) size query - D3DKMT_SEGMENTSIZEINFO segmentSizeInfo = {}; - status = D3DKMTQueryAdapterInfo(&(D3DKMT_QUERYADAPTERINFO) { - .hAdapter = adapter->hAdapter, - .Type = KMTQAITYPE_GETSEGMENTSIZE, - .pPrivateDriverData = &segmentSizeInfo, - .PrivateDriverDataSize = sizeof(segmentSizeInfo), - }); - if (NT_SUCCESS(status)) { - FF_DEBUG("Adapter #%u segment size - DedicatedVideoMemorySize: %" PRIu64 - ", DedicatedSystemMemorySize: %" PRIu64 ", SharedSystemMemorySize: %" PRIu64, - i, - (uint64_t) segmentSizeInfo.DedicatedVideoMemorySize, - (uint64_t) segmentSizeInfo.DedicatedSystemMemorySize, - (uint64_t) segmentSizeInfo.SharedSystemMemorySize); - gpu->dedicated.total = segmentSizeInfo.DedicatedVideoMemorySize; - gpu->shared.total = segmentSizeInfo.DedicatedSystemMemorySize + segmentSizeInfo.SharedSystemMemorySize; - } else { - FF_DEBUG("Failed to query segment size information for adapter #%u: %s", i, ffDebugNtStatus(status)); - } - } + #if _WIN32 + if (gpu->name.length == 0 || gpu->vendor.length == 0 || (options->driverSpecific && gpu->pcieSpeed == FF_GPU_PCIE_SPEED_UNSET)) { + queryDeviceInfoCM(gpu, luid, &deviceIds.DeviceIds, options->driverSpecific); } + #endif - if (wddmVersion >= KMT_DRIVERVERSION_WDDM_2_4) { - if (gpu->frequency == FF_GPU_FREQUENCY_UNSET) { - for (uint32_t nodeIdx = 0;; nodeIdx++) { - D3DKMT_NODEMETADATA nodeMetadata = { - .NodeOrdinalAndAdapterIndex = (0 << 16) | nodeIdx, + if (!isIndirectDisplayDevice) { + if (gpu->dedicated.total == FF_GPU_VMEM_SIZE_UNSET && gpu->shared.total == FF_GPU_VMEM_SIZE_UNSET) { + if (wddmVersion >= KMT_DRIVERVERSION_WDDM_3_1 && options->driverSpecific) { + // Supports memory usage query; requires Windows 11 (22H2) or later + D3DKMT_QUERYSTATISTICS queryStatistics = { + .Type = D3DKMT_QUERYSTATISTICS_SEGMENT_GROUP_USAGE, + .AdapterLuid = adapter->AdapterLuid, + .QuerySegmentGroupUsage = { + .PhysicalAdapterIndex = 0, + .SegmentGroup = D3DKMT_MEMORY_SEGMENT_GROUP_LOCAL, + }, }; + status = D3DKMTQueryStatistics(&queryStatistics); + if (NT_SUCCESS(status)) { + D3DKMT_QUERYSTATISTICS_MEMORY_USAGE* info = &queryStatistics.QueryResult.SegmentGroupUsageInformation; + uint64_t used = info->AllocatedBytes + info->ModifiedBytes + info->StandbyBytes; + uint64_t total = used + info->FreeBytes + info->ZeroBytes; + gpu->dedicated.used = used; + gpu->dedicated.total = total; + FF_DEBUG("Adapter #%u local memory usage: used=%" PRIu64 " total=%" PRIu64, i, used, total); + } else { + FF_DEBUG("D3DKMT_QUERYSTATISTICS_SEGMENT_GROUP_USAGE (LOCAL) failed for adapter #%u: %s", + i, + ffDebugNtStatus(status)); + } + + queryStatistics.QuerySegmentGroupUsage.SegmentGroup = D3DKMT_MEMORY_SEGMENT_GROUP_NON_LOCAL; + status = D3DKMTQueryStatistics(&queryStatistics); + if (NT_SUCCESS(status)) { + D3DKMT_QUERYSTATISTICS_MEMORY_USAGE* info = &queryStatistics.QueryResult.SegmentGroupUsageInformation; + uint64_t used = info->AllocatedBytes + info->ModifiedBytes + info->StandbyBytes; + uint64_t total = used + info->FreeBytes + info->ZeroBytes; + gpu->shared.used = used; + gpu->shared.total = total; + FF_DEBUG("Adapter #%u non-local memory usage: used=%" PRIu64 " total=%" PRIu64, i, used, total); + } else { + FF_DEBUG("D3DKMT_QUERYSTATISTICS_SEGMENT_GROUP_USAGE (NON_LOCAL) failed for adapter #%u: %s", + i, + ffDebugNtStatus(status)); + } + } else { + // Supports basic segment (total) size query + D3DKMT_SEGMENTSIZEINFO segmentSizeInfo = {}; status = D3DKMTQueryAdapterInfo(&(D3DKMT_QUERYADAPTERINFO) { .hAdapter = adapter->hAdapter, - .Type = KMTQAITYPE_NODEMETADATA, - .pPrivateDriverData = &nodeMetadata, - .PrivateDriverDataSize = sizeof(nodeMetadata), + .Type = KMTQAITYPE_GETSEGMENTSIZE, + .pPrivateDriverData = &segmentSizeInfo, + .PrivateDriverDataSize = sizeof(segmentSizeInfo), }); - if (!NT_SUCCESS(status)) { break; } + if (NT_SUCCESS(status)) { + FF_DEBUG("Adapter #%u segment size - DedicatedVideoMemorySize: %" PRIu64 + ", DedicatedSystemMemorySize: %" PRIu64 ", SharedSystemMemorySize: %" PRIu64, + i, + (uint64_t) segmentSizeInfo.DedicatedVideoMemorySize, + (uint64_t) segmentSizeInfo.DedicatedSystemMemorySize, + (uint64_t) segmentSizeInfo.SharedSystemMemorySize); + gpu->dedicated.total = segmentSizeInfo.DedicatedVideoMemorySize; + gpu->shared.total = segmentSizeInfo.DedicatedSystemMemorySize + segmentSizeInfo.SharedSystemMemorySize; + } else { + FF_DEBUG("Failed to query segment size information for adapter #%u: %s", i, ffDebugNtStatus(status)); + } + } + } - if (nodeMetadata.NodeData.EngineType != DXGK_ENGINE_TYPE_3D) { continue; } + if (wddmVersion >= KMT_DRIVERVERSION_WDDM_2_4) { + if (gpu->frequency == FF_GPU_FREQUENCY_UNSET) { + for (uint32_t nodeIdx = 0;; nodeIdx++) { + D3DKMT_NODEMETADATA nodeMetadata = { + .NodeOrdinalAndAdapterIndex = (0 << 16) | nodeIdx, + }; + status = D3DKMTQueryAdapterInfo(&(D3DKMT_QUERYADAPTERINFO) { + .hAdapter = adapter->hAdapter, + .Type = KMTQAITYPE_NODEMETADATA, + .pPrivateDriverData = &nodeMetadata, + .PrivateDriverDataSize = sizeof(nodeMetadata), + }); + if (!NT_SUCCESS(status)) { break; } + + if (nodeMetadata.NodeData.EngineType != DXGK_ENGINE_TYPE_3D) { continue; } + + D3DKMT_NODE_PERFDATA nodePerfData = { + .NodeOrdinal = nodeIdx, + .PhysicalAdapterIndex = 0, + }; + status = D3DKMTQueryAdapterInfo(&(D3DKMT_QUERYADAPTERINFO) { + .hAdapter = adapter->hAdapter, + .Type = KMTQAITYPE_NODEPERFDATA, + .pPrivateDriverData = &nodePerfData, + .PrivateDriverDataSize = sizeof(nodePerfData), + }); + if (NT_SUCCESS(status)) { + if (nodePerfData.MaxFrequency != 0) { + gpu->frequency = (uint32_t) (nodePerfData.MaxFrequency / 1000 / 1000); + FF_DEBUG("Adapter #%u max graphics frequency: %u MHz", i, gpu->frequency); + } else { + FF_DEBUG("Adapter #%u does not report max graphics frequency", i); + } + break; + } else { + FF_DEBUG("Failed to query node performance data for adapter #%u node #%u: %s", + i, + nodeIdx, + ffDebugNtStatus(status)); + } + } + } - D3DKMT_NODE_PERFDATA nodePerfData = { - .NodeOrdinal = nodeIdx, + if (options->temp && gpu->temperature == FF_GPU_TEMP_UNSET) { + D3DKMT_ADAPTER_PERFDATA adapterPerfData = { .PhysicalAdapterIndex = 0, }; status = D3DKMTQueryAdapterInfo(&(D3DKMT_QUERYADAPTERINFO) { .hAdapter = adapter->hAdapter, - .Type = KMTQAITYPE_NODEPERFDATA, - .pPrivateDriverData = &nodePerfData, - .PrivateDriverDataSize = sizeof(nodePerfData), + .Type = KMTQAITYPE_ADAPTERPERFDATA, + .pPrivateDriverData = &adapterPerfData, + .PrivateDriverDataSize = sizeof(adapterPerfData), }); if (NT_SUCCESS(status)) { - if (nodePerfData.MaxFrequency != 0) { - gpu->frequency = (uint32_t) (nodePerfData.MaxFrequency / 1000 / 1000); - FF_DEBUG("Adapter #%u max graphics frequency: %u MHz", i, gpu->frequency); + if (adapterPerfData.Temperature != 0) { + gpu->temperature = adapterPerfData.Temperature / 10.0; + FF_DEBUG("Adapter #%u temperature: %.1f°C", i, gpu->temperature); } else { - FF_DEBUG("Adapter #%u does not report max graphics frequency", i); + FF_DEBUG("Adapter #%u does not report temperature data", i); } - break; } else { - FF_DEBUG("Failed to query node performance data for adapter #%u node #%u: %s", - i, - nodeIdx, - ffDebugNtStatus(status)); + FF_DEBUG("Failed to query temperature for adapter #%u: %s", i, ffDebugNtStatus(status)); } } } - if (options->temp && gpu->temperature == FF_GPU_TEMP_UNSET) { - D3DKMT_ADAPTER_PERFDATA adapterPerfData = { - .PhysicalAdapterIndex = 0, - }; - status = D3DKMTQueryAdapterInfo(&(D3DKMT_QUERYADAPTERINFO) { - .hAdapter = adapter->hAdapter, - .Type = KMTQAITYPE_ADAPTERPERFDATA, - .pPrivateDriverData = &adapterPerfData, - .PrivateDriverDataSize = sizeof(adapterPerfData), - }); - if (NT_SUCCESS(status)) { - if (adapterPerfData.Temperature != 0) { - gpu->temperature = adapterPerfData.Temperature / 10.0; - FF_DEBUG("Adapter #%u temperature: %.1f°C", i, gpu->temperature); - } else { - FF_DEBUG("Adapter #%u does not report temperature data", i); - } - } else { - FF_DEBUG("Failed to query temperature for adapter #%u: %s", i, ffDebugNtStatus(status)); + if (gpu->type == FF_GPU_TYPE_UNKNOWN) { + if (ffGPUDetectTypeByVendorAndName(gpu)) { + // OK + } + #if _WIN32 + else if (ffIsWindows10OrGreater()) { + const char* ffGPUDetectTypeWithDXCore(LUID adapterLuid, FFGPUResult * gpu); + [[maybe_unused]] const char* error = ffGPUDetectTypeWithDXCore(adapter->AdapterLuid, gpu); + FF_DEBUG("DXCore GPU type detection result: %s", error ?: "Success"); + } + #endif + else { + FF_DEBUG("Unable to determine GPU type by any method for this adapter"); } - } - } - - if (gpu->type == FF_GPU_TYPE_UNKNOWN) { - if (ffGPUDetectTypeByVendorAndName(gpu)) { - // OK - } -#if _WIN32 - else if (ffIsWindows10OrGreater()) { - const char* ffGPUDetectTypeWithDXCore(LUID adapterLuid, FFGPUResult * gpu); - FF_A_UNUSED const char* error = ffGPUDetectTypeWithDXCore(adapter->AdapterLuid, gpu); - FF_DEBUG("DXCore GPU type detection result: %s", error ?: "Success"); - } -#endif - else { - FF_DEBUG("Unable to determine GPU type by any method for this adapter"); } } @@ -638,5 +667,5 @@ ffGPUDetectWsl2 } } - return NULL; + return nullptr; } diff --git a/src/detection/gpu/gpu_windows.cpp b/src/detection/gpu/gpu_windows.cpp index ae6f00ef97..e5cdecedec 100644 --- a/src/detection/gpu/gpu_windows.cpp +++ b/src/detection/gpu/gpu_windows.cpp @@ -18,7 +18,7 @@ static IDXCoreAdapterFactory* loadDxCoreFactory() { } initialized = true; - FF_LIBRARY_LOAD(dxcore, NULL, "dxcore" FF_LIBRARY_EXTENSION, 1) + FF_LIBRARY_LOAD(dxcore, nullptr, "dxcore" FF_LIBRARY_EXTENSION, 1) // DXCoreCreateAdapterFactory is a reloaded function, so we can't use FF_LIBRARY_LOAD_SYMBOL_MESSAGE here typedef HRESULT (*DXCoreCreateAdapterFactory_t)(REFIID riid, void** ppvFactory); @@ -26,7 +26,7 @@ static IDXCoreAdapterFactory* loadDxCoreFactory() { #ifndef FF_DISABLE_DLOPEN auto ffDXCoreCreateAdapterFactory = (DXCoreCreateAdapterFactory_t) dlsym(dxcore, "DXCoreCreateAdapterFactory"); if (ffDXCoreCreateAdapterFactory == nullptr) { - return NULL; + return nullptr; } #else auto ffDXCoreCreateAdapterFactory = (DXCoreCreateAdapterFactory_t) DXCoreCreateAdapterFactory; @@ -35,10 +35,10 @@ static IDXCoreAdapterFactory* loadDxCoreFactory() { HRESULT hr = ffDXCoreCreateAdapterFactory(IID_PPV_ARGS(&factory)); if (FAILED(hr)) { FF_DEBUG("DXCoreCreateAdapterFactory failed with HRESULT: 0x%08lX (%s)", hr, ffDebugHResult(hr)); - return NULL; + return nullptr; } - dxcore = NULL; // Don't unload + dxcore = nullptr; // Don't unload return factory; } diff --git a/src/detection/gpu/mtml.h b/src/detection/gpu/mtml.h index 9f62fc326e..1ebd5398b8 100644 --- a/src/detection/gpu/mtml.h +++ b/src/detection/gpu/mtml.h @@ -32,7 +32,7 @@ typedef struct MtmlMemory MtmlMemory; */ typedef struct { - char sbdf[MTML_DEVICE_PCI_SBDF_BUFFER_SIZE]; //!< The tuple segment:bus:device.function PCI identifier (& NULL terminator). + char sbdf[MTML_DEVICE_PCI_SBDF_BUFFER_SIZE]; //!< The tuple segment:bus:device.function PCI identifier (& nullptr terminator). unsigned int segment; //!< The PCI segment group(domain) on which the device's bus resides, 0 to 0xffffffff. unsigned int bus; //!< The bus on which the device resides, 0 to 0xff. unsigned int device; //!< The device ID on the bus, 0 to 31. diff --git a/src/detection/gpu/nvml.h b/src/detection/gpu/nvml.h index 52adaa3b5c..ea2455179c 100644 --- a/src/detection/gpu/nvml.h +++ b/src/detection/gpu/nvml.h @@ -18,7 +18,7 @@ typedef struct nvmlDevice_t* nvmlDevice_t; // https://docs.nvidia.com/deploy/nvml-api/structnvmlPciInfo__t.html // PCI information about a GPU device typedef struct { - // The legacy tuple domain:bus:device.function PCI identifier (& NULL terminator) + // The legacy tuple domain:bus:device.function PCI identifier (& nullptr terminator) char busIdLegacy[NVML_DEVICE_PCI_BUS_ID_BUFFER_V2_SIZE]; // The PCI domain on which the device's bus resides, 0 to 0xffffffff unsigned int domain; @@ -30,7 +30,7 @@ typedef struct { unsigned int pciDeviceId; // The 32-bit Sub System Device ID unsigned int pciSubSystemId; - // The tuple domain:bus:device.function PCI identifier (& NULL terminator) + // The tuple domain:bus:device.function PCI identifier (& nullptr terminator) char busId[NVML_DEVICE_PCI_BUS_ID_BUFFER_SIZE]; } nvmlPciInfo_t; diff --git a/src/detection/gtk_qt/gtk.c b/src/detection/gtk_qt/gtk.c index 05a8db1b36..12aaeac143 100644 --- a/src/detection/gtk_qt/gtk.c +++ b/src/detection/gtk_qt/gtk.c @@ -37,19 +37,19 @@ static inline void applyGTKSettings(FFGTKResult* result, const char* themeName, } } -static bool testXfconfWallpaperPropKey(FF_A_UNUSED void* data, const char* key) { +static bool testXfconfWallpaperPropKey([[maybe_unused]] void* data, const char* key) { int count = 0; sscanf(key, "/backdrop/screen0/monitor%*[^/]/workspace0/last-image%n", &count); return count == 0; } static void detectGTKFromSettings(FFGTKResult* result) { - static const char* themeName = NULL; - static const char* iconsName = NULL; - static const char* fontName = NULL; - static const char* cursorTheme = NULL; + static const char* themeName = nullptr; + static const char* iconsName = nullptr; + static const char* fontName = nullptr; + static const char* cursorTheme = nullptr; static int cursorSize = 0; - static const char* wallpaper = NULL; + static const char* wallpaper = nullptr; static bool init = false; @@ -68,33 +68,33 @@ static void detectGTKFromSettings(FFGTKResult* result) { fontName = ffSettingsGetXFConf("xsettings", "/Gtk/FontName", FF_VARIANT_TYPE_STRING).strValue; cursorTheme = ffSettingsGetXFConf("xsettings", "/Gtk/CursorThemeName", FF_VARIANT_TYPE_STRING).strValue; cursorSize = ffSettingsGetXFConf("xsettings", "/Gtk/CursorThemeSize", FF_VARIANT_TYPE_INT).intValue; - wallpaper = ffSettingsGetXFConfFirstMatch("xfce4-desktop", "/backdrop/screen0", FF_VARIANT_TYPE_STRING, NULL, testXfconfWallpaperPropKey).strValue; + wallpaper = ffSettingsGetXFConfFirstMatch("xfce4-desktop", "/backdrop/screen0", FF_VARIANT_TYPE_STRING, nullptr, testXfconfWallpaperPropKey).strValue; } else if (ffStrbufIgnCaseEqualS(&wmde->dePrettyName, FF_DE_PRETTY_CINNAMON)) { - themeName = ffSettingsGetGnome("/org/cinnamon/desktop/interface/gtk-theme", "org.cinnamon.desktop.interface", NULL, "gtk-theme", FF_VARIANT_TYPE_STRING).strValue; - iconsName = ffSettingsGetGnome("/org/cinnamon/desktop/interface/icon-theme", "org.cinnamon.desktop.interface", NULL, "icon-theme", FF_VARIANT_TYPE_STRING).strValue; - fontName = ffSettingsGetGnome("/org/cinnamon/desktop/interface/font-name", "org.cinnamon.desktop.interface", NULL, "font-name", FF_VARIANT_TYPE_STRING).strValue; - cursorTheme = ffSettingsGetGnome("/org/cinnamon/desktop/interface/cursor-theme", "org.cinnamon.desktop.interface", NULL, "cursor-theme", FF_VARIANT_TYPE_STRING).strValue; - cursorSize = ffSettingsGetGnome("/org/cinnamon/desktop/interface/cursor-size", "org.cinnamon.desktop.interface", NULL, "cursor-size", FF_VARIANT_TYPE_INT).intValue; - wallpaper = ffSettingsGetGnome("/org/cinnamon/desktop/background/picture-uri", "org.cinnamon.desktop.background", NULL, "picture-uri", FF_VARIANT_TYPE_STRING).strValue; + themeName = ffSettingsGetGnome("/org/cinnamon/desktop/interface/gtk-theme", "org.cinnamon.desktop.interface", nullptr, "gtk-theme", FF_VARIANT_TYPE_STRING).strValue; + iconsName = ffSettingsGetGnome("/org/cinnamon/desktop/interface/icon-theme", "org.cinnamon.desktop.interface", nullptr, "icon-theme", FF_VARIANT_TYPE_STRING).strValue; + fontName = ffSettingsGetGnome("/org/cinnamon/desktop/interface/font-name", "org.cinnamon.desktop.interface", nullptr, "font-name", FF_VARIANT_TYPE_STRING).strValue; + cursorTheme = ffSettingsGetGnome("/org/cinnamon/desktop/interface/cursor-theme", "org.cinnamon.desktop.interface", nullptr, "cursor-theme", FF_VARIANT_TYPE_STRING).strValue; + cursorSize = ffSettingsGetGnome("/org/cinnamon/desktop/interface/cursor-size", "org.cinnamon.desktop.interface", nullptr, "cursor-size", FF_VARIANT_TYPE_INT).intValue; + wallpaper = ffSettingsGetGnome("/org/cinnamon/desktop/background/picture-uri", "org.cinnamon.desktop.background", nullptr, "picture-uri", FF_VARIANT_TYPE_STRING).strValue; } else if (ffStrbufIgnCaseEqualS(&wmde->dePrettyName, FF_DE_PRETTY_MATE)) { - themeName = ffSettingsGetGnome("/org/mate/interface/gtk-theme", "org.mate.interface", NULL, "gtk-theme", FF_VARIANT_TYPE_STRING).strValue; - iconsName = ffSettingsGetGnome("/org/mate/interface/icon-theme", "org.mate.interface", NULL, "icon-theme", FF_VARIANT_TYPE_STRING).strValue; - fontName = ffSettingsGetGnome("/org/mate/interface/font-name", "org.mate.interface", NULL, "font-name", FF_VARIANT_TYPE_STRING).strValue; - cursorTheme = ffSettingsGetGnome("/org/mate/peripherals-mouse/cursor-theme", "org.mate.peripherals-mouse", NULL, "cursor-theme", FF_VARIANT_TYPE_STRING).strValue; - cursorSize = ffSettingsGetGnome("/org/mate/peripherals-mouse/cursor-size", "org.mate.peripherals-mouse", NULL, "cursor-size", FF_VARIANT_TYPE_INT).intValue; - wallpaper = ffSettingsGetGnome("/org/mate/desktop/background", "org.mate.background", NULL, "picture-filename", FF_VARIANT_TYPE_STRING).strValue; + themeName = ffSettingsGetGnome("/org/mate/interface/gtk-theme", "org.mate.interface", nullptr, "gtk-theme", FF_VARIANT_TYPE_STRING).strValue; + iconsName = ffSettingsGetGnome("/org/mate/interface/icon-theme", "org.mate.interface", nullptr, "icon-theme", FF_VARIANT_TYPE_STRING).strValue; + fontName = ffSettingsGetGnome("/org/mate/interface/font-name", "org.mate.interface", nullptr, "font-name", FF_VARIANT_TYPE_STRING).strValue; + cursorTheme = ffSettingsGetGnome("/org/mate/peripherals-mouse/cursor-theme", "org.mate.peripherals-mouse", nullptr, "cursor-theme", FF_VARIANT_TYPE_STRING).strValue; + cursorSize = ffSettingsGetGnome("/org/mate/peripherals-mouse/cursor-size", "org.mate.peripherals-mouse", nullptr, "cursor-size", FF_VARIANT_TYPE_INT).intValue; + wallpaper = ffSettingsGetGnome("/org/mate/desktop/background", "org.mate.background", nullptr, "picture-filename", FF_VARIANT_TYPE_STRING).strValue; } else if ( ffStrbufIgnCaseEqualS(&wmde->dePrettyName, FF_DE_PRETTY_GNOME) || ffStrbufIgnCaseEqualS(&wmde->dePrettyName, FF_DE_PRETTY_GNOME_CLASSIC) || ffStrbufIgnCaseEqualS(&wmde->dePrettyName, FF_DE_PRETTY_UNITY) || ffStrbufIgnCaseEqualS(&wmde->dePrettyName, FF_DE_PRETTY_BUDGIE) || ffStrbufIgnCaseEqualS(&wmde->dePrettyName, FF_DE_PRETTY_NEBIDE)) { - themeName = ffSettingsGetGnome("/org/gnome/desktop/interface/gtk-theme", "org.gnome.desktop.interface", NULL, "gtk-theme", FF_VARIANT_TYPE_STRING).strValue; - iconsName = ffSettingsGetGnome("/org/gnome/desktop/interface/icon-theme", "org.gnome.desktop.interface", NULL, "icon-theme", FF_VARIANT_TYPE_STRING).strValue; - fontName = ffSettingsGetGnome("/org/gnome/desktop/interface/font-name", "org.gnome.desktop.interface", NULL, "font-name", FF_VARIANT_TYPE_STRING).strValue; - cursorTheme = ffSettingsGetGnome("/org/gnome/desktop/interface/cursor-theme", "org.gnome.desktop.interface", NULL, "cursor-theme", FF_VARIANT_TYPE_STRING).strValue; - cursorSize = ffSettingsGetGnome("/org/gnome/desktop/interface/cursor-size", "org.gnome.desktop.interface", NULL, "cursor-size", FF_VARIANT_TYPE_INT).intValue; - wallpaper = ffSettingsGetGnome("/org/gnome/desktop/background/picture-uri", "org.gnome.desktop.background", NULL, "picture-uri", FF_VARIANT_TYPE_STRING).strValue; + themeName = ffSettingsGetGnome("/org/gnome/desktop/interface/gtk-theme", "org.gnome.desktop.interface", nullptr, "gtk-theme", FF_VARIANT_TYPE_STRING).strValue; + iconsName = ffSettingsGetGnome("/org/gnome/desktop/interface/icon-theme", "org.gnome.desktop.interface", nullptr, "icon-theme", FF_VARIANT_TYPE_STRING).strValue; + fontName = ffSettingsGetGnome("/org/gnome/desktop/interface/font-name", "org.gnome.desktop.interface", nullptr, "font-name", FF_VARIANT_TYPE_STRING).strValue; + cursorTheme = ffSettingsGetGnome("/org/gnome/desktop/interface/cursor-theme", "org.gnome.desktop.interface", nullptr, "cursor-theme", FF_VARIANT_TYPE_STRING).strValue; + cursorSize = ffSettingsGetGnome("/org/gnome/desktop/interface/cursor-size", "org.gnome.desktop.interface", nullptr, "cursor-size", FF_VARIANT_TYPE_INT).intValue; + wallpaper = ffSettingsGetGnome("/org/gnome/desktop/background/picture-uri", "org.gnome.desktop.background", nullptr, "picture-uri", FF_VARIANT_TYPE_STRING).strValue; } else if ( ffStrbufIgnCaseEqualS(&wmde->dePrettyName, FF_DE_PRETTY_ENLIGHTENMENT)) { ffEnlightenmentSettings settings = {}; diff --git a/src/detection/gtk_qt/qt.c b/src/detection/gtk_qt/qt.c index 26c8b58e23..f7eb22bc4b 100644 --- a/src/detection/gtk_qt/qt.c +++ b/src/detection/gtk_qt/qt.c @@ -16,7 +16,7 @@ static inline bool allValuesSet(const FFQtResult* result) { result->wallpaper.length > 0; } -typedef enum FF_A_PACKED PlasmaCategory { +typedef enum PlasmaCategory: uint8_t { PLASMA_CATEGORY_GENERAL, PLASMA_CATEGORY_KDE, PLASMA_CATEGORY_ICONS, @@ -25,11 +25,11 @@ typedef enum FF_A_PACKED PlasmaCategory { static bool detectPlasmaFromFile(const char* filename, FFQtResult* result) { FILE* kdeglobals = fopen(filename, "r"); - if (kdeglobals == NULL) { + if (kdeglobals == nullptr) { return false; } - char* line = NULL; + char* line = nullptr; size_t len = 0; PlasmaCategory category = PLASMA_CATEGORY_OTHER; @@ -153,7 +153,7 @@ static void detectQtCt(char qver, FFQtResult* result) { while (*p) { if (p[0] == '\\' && p[1] == 'x' && isxdigit(p[2]) && isxdigit(p[3]) && isxdigit(p[4]) && isxdigit(p[5])) { - uint32_t codepoint = (uint32_t) strtoul((char[]) { p[2], p[3], p[4], p[5], '\0' }, NULL, 16); + uint32_t codepoint = (uint32_t) strtoul((char[]) { p[2], p[3], p[4], p[5], '\0' }, nullptr, 16); ffStrbufAppendUtf32CodePoint(&result->font, codepoint); p += 6; } else { diff --git a/src/detection/host/host_android.c b/src/detection/host/host_android.c index 1157a92f03..dffe066b98 100644 --- a/src/detection/host/host_android.c +++ b/src/detection/host/host_android.c @@ -23,5 +23,5 @@ const char* ffDetectHost(FFHostResult* host) { ffStrbufPrepend(&host->name, &host->vendor); } - return NULL; + return nullptr; } diff --git a/src/detection/host/host_apple.c b/src/detection/host/host_apple.c index a177bf4053..a855ba5a49 100644 --- a/src/detection/host/host_apple.c +++ b/src/detection/host/host_apple.c @@ -44,7 +44,7 @@ const char* getOthersByIokit(FFHostResult* host) { ffCfStrGetString(version, &host->version); } - return NULL; + return nullptr; } const char* ffDetectHost(FFHostResult* host) { @@ -64,5 +64,5 @@ const char* ffDetectHost(FFHostResult* host) { ffStrbufSet(&host->name, &host->family); } getOthersByIokit(host); - return NULL; + return nullptr; } diff --git a/src/detection/host/host_bsd.c b/src/detection/host/host_bsd.c index 3eb547d1bc..8b5269d424 100644 --- a/src/detection/host/host_bsd.c +++ b/src/detection/host/host_bsd.c @@ -22,5 +22,5 @@ const char* ffDetectHost(FFHostResult* host) { ffHostDetectMac(host); #endif - return NULL; + return nullptr; } diff --git a/src/detection/host/host_linux.c b/src/detection/host/host_linux.c index 81418a81d2..9252c76299 100644 --- a/src/detection/host/host_linux.c +++ b/src/detection/host/host_linux.c @@ -86,7 +86,7 @@ const char* ffDetectHost(FFHostResult* host) { if (host->family.length == 0 && host->name.length == 0) { const char* wslDistroName = getenv("WSL_DISTRO_NAME"); // On WSL, the real host can't be detected. Instead use WSL as host. - if (wslDistroName != NULL || getenv("WSL_DISTRO") != NULL || getenv("WSL_INTEROP") != NULL) { + if (wslDistroName != nullptr || getenv("WSL_DISTRO") != nullptr || getenv("WSL_INTEROP") != nullptr) { ffStrbufSetStatic(&host->name, "Windows Subsystem for Linux"); if (wslDistroName) { ffStrbufAppendF(&host->name, " - %s", wslDistroName); @@ -99,7 +99,7 @@ const char* ffDetectHost(FFHostResult* host) { "wslinfo", "--wsl-version", "-n", - NULL, + nullptr, }); // supported in 2.2.3 and later } } else if (ffStrbufStartsWithS(&instance.state.platform.sysinfo.version, "FreeBSD ")) { @@ -113,5 +113,5 @@ const char* ffDetectHost(FFHostResult* host) { } } - return NULL; + return nullptr; } diff --git a/src/detection/host/host_mac.c b/src/detection/host/host_mac.c index d680332630..f610c3ddec 100644 --- a/src/detection/host/host_mac.c +++ b/src/detection/host/host_mac.c @@ -425,7 +425,7 @@ const char* ffHostGetMacProductNameWithHwModel(const FFstrbuf* hwModel) { return "iMac (24/20-inch, Early 2009)"; } } - return NULL; + return nullptr; } #ifdef __x86_64__ diff --git a/src/detection/host/host_nbsd.c b/src/detection/host/host_nbsd.c index a5a29d2890..265641dddd 100644 --- a/src/detection/host/host_nbsd.c +++ b/src/detection/host/host_nbsd.c @@ -3,23 +3,23 @@ #include "common/smbios.h" const char* ffDetectHost(FFHostResult* host) { - const char* error = NULL; + const char* error = nullptr; if ((error = ffSysctlGetString("machdep.dmi.system-product", &host->name))) { return error; } ffCleanUpSmbiosValue(&host->name); - if (ffSysctlGetString("machdep.dmi.system-vendor", &host->vendor) == NULL) { + if (ffSysctlGetString("machdep.dmi.system-vendor", &host->vendor) == nullptr) { ffCleanUpSmbiosValue(&host->vendor); } - if (ffSysctlGetString("machdep.dmi.system-version", &host->version) == NULL) { + if (ffSysctlGetString("machdep.dmi.system-version", &host->version) == nullptr) { ffCleanUpSmbiosValue(&host->version); } - if (ffSysctlGetString("machdep.dmi.system-serial", &host->serial) == NULL) { + if (ffSysctlGetString("machdep.dmi.system-serial", &host->serial) == nullptr) { ffCleanUpSmbiosValue(&host->serial); } - if (ffSysctlGetString("machdep.dmi.system-uuid", &host->uuid) == NULL) { + if (ffSysctlGetString("machdep.dmi.system-uuid", &host->uuid) == nullptr) { ffCleanUpSmbiosValue(&host->uuid); } - return NULL; + return nullptr; } diff --git a/src/detection/host/host_nosupport.c b/src/detection/host/host_nosupport.c index 61a7254336..4475f24f9b 100644 --- a/src/detection/host/host_nosupport.c +++ b/src/detection/host/host_nosupport.c @@ -1,5 +1,5 @@ #include "host.h" -const char* ffDetectHost(FF_A_UNUSED FFHostResult* host) { +const char* ffDetectHost([[maybe_unused]] FFHostResult* host) { return "Not supported on this platform"; } diff --git a/src/detection/host/host_obsd.c b/src/detection/host/host_obsd.c index cb16ecf396..85d2c0836a 100644 --- a/src/detection/host/host_obsd.c +++ b/src/detection/host/host_obsd.c @@ -3,20 +3,20 @@ #include "common/smbios.h" const char* ffDetectHost(FFHostResult* host) { - const char* error = NULL; + const char* error = nullptr; if ((error = ffSysctlGetString(CTL_HW, HW_PRODUCT, &host->name))) { return error; } ffCleanUpSmbiosValue(&host->name); - if (ffSysctlGetString(CTL_HW, HW_VENDOR, &host->vendor) == NULL) { + if (ffSysctlGetString(CTL_HW, HW_VENDOR, &host->vendor) == nullptr) { ffCleanUpSmbiosValue(&host->vendor); } - if (ffSysctlGetString(CTL_HW, HW_VERSION, &host->version) == NULL) { + if (ffSysctlGetString(CTL_HW, HW_VERSION, &host->version) == nullptr) { ffCleanUpSmbiosValue(&host->version); } - if (ffSysctlGetString(CTL_HW, HW_SERIALNO, &host->serial) == NULL) { + if (ffSysctlGetString(CTL_HW, HW_SERIALNO, &host->serial) == nullptr) { ffCleanUpSmbiosValue(&host->serial); } - return NULL; + return nullptr; } diff --git a/src/detection/host/host_windows.c b/src/detection/host/host_windows.c index 9f25829119..13bf56e88d 100644 --- a/src/detection/host/host_windows.c +++ b/src/detection/host/host_windows.c @@ -1,7 +1,7 @@ #include "host.h" #include "common/smbios.h" -typedef struct FFSmbiosSystemInfo { +typedef struct [[gnu::packed]] FFSmbiosSystemInfo { FFSmbiosHeader Header; uint8_t Manufacturer; // string @@ -10,20 +10,20 @@ typedef struct FFSmbiosSystemInfo { uint8_t SerialNumber; // string // 2.1+ - struct { + struct [[gnu::packed]] { uint32_t TimeLow; uint16_t TimeMid; uint16_t TimeHighAndVersion; uint8_t ClockSeqHiAndReserved; uint8_t ClockSeqLow; uint8_t Node[6]; - } FF_A_PACKED UUID; // varies + } UUID; // varies uint8_t WakeUpType; // enum // 2.4+ uint8_t SKUNumber; // string uint8_t Family; // string -} FF_A_PACKED FFSmbiosSystemInfo; +} FFSmbiosSystemInfo; static_assert(offsetof(FFSmbiosSystemInfo, Family) == 0x1A, "FFSmbiosSystemInfo: Wrong struct alignment"); @@ -70,5 +70,5 @@ const char* ffDetectHost(FFHostResult* host) { ffHostDetectMac(host); #endif - return NULL; + return nullptr; } diff --git a/src/detection/icons/icons_linux.c b/src/detection/icons/icons_linux.c index 0ecaa07046..fb1b12621a 100644 --- a/src/detection/icons/icons_linux.c +++ b/src/detection/icons/icons_linux.c @@ -26,5 +26,5 @@ const char* ffDetectIcons(FFIconsResult* result) { ffStrbufAppendS(&result->icons1, " [Qt]"); } - return NULL; + return nullptr; } diff --git a/src/detection/icons/icons_nosupport.c b/src/detection/icons/icons_nosupport.c index ab8cebbc70..ff5ef01ea3 100644 --- a/src/detection/icons/icons_nosupport.c +++ b/src/detection/icons/icons_nosupport.c @@ -1,5 +1,5 @@ #include "icons.h" -const char* ffDetectIcons(FF_A_UNUSED FFIconsResult* result) { +const char* ffDetectIcons([[maybe_unused]] FFIconsResult* result) { return "Not supported on this platform"; } diff --git a/src/detection/icons/icons_windows.c b/src/detection/icons/icons_windows.c index e199432653..407dd7fe0a 100644 --- a/src/detection/icons/icons_windows.c +++ b/src/detection/icons/icons_windows.c @@ -2,21 +2,21 @@ #include "common/windows/registry.h" const char* ffDetectIcons(FFIconsResult* result) { - FF_AUTO_CLOSE_FD HANDLE hKey = NULL; - if (!ffRegOpenKeyForRead(HKEY_CURRENT_USER, L"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\HideDesktopIcons\\NewStartPanel", &hKey, NULL) && - !ffRegOpenKeyForRead(HKEY_CURRENT_USER, L"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\HideDesktopIcons\\ClassicStartMenu", &hKey, NULL)) { + FF_AUTO_CLOSE_FD HANDLE hKey = nullptr; + if (!ffRegOpenKeyForRead(HKEY_CURRENT_USER, L"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\HideDesktopIcons\\NewStartPanel", &hKey, nullptr) && + !ffRegOpenKeyForRead(HKEY_CURRENT_USER, L"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\HideDesktopIcons\\ClassicStartMenu", &hKey, nullptr)) { // If the key doesn't exist, it means that the user never changed the default settings. ffStrbufSetStatic(&result->icons2, "Recycle Bin"); - return NULL; + return nullptr; } // Whether these icons are hidden uint32_t ThisPC = 1, UsersFiles = 1, RemoteNetwork = 1, RecycleBin = 0 /* Shown by default */, ControlPanel = 1; - ffRegReadUint(hKey, L"{20D04FE0-3AEA-1069-A2D8-08002B30309D}", &ThisPC, NULL); - ffRegReadUint(hKey, L"{59031a47-3f72-44a7-89c5-5595fe6b30ee}", &UsersFiles, NULL); - ffRegReadUint(hKey, L"{F02C1A0D-BE21-4350-88B0-7367FC96EF3C}", &RemoteNetwork, NULL); - ffRegReadUint(hKey, L"{645FF040-5081-101B-9F08-00AA002F954E}", &RecycleBin, NULL); - ffRegReadUint(hKey, L"{5399E694-6CE5-4D6C-8FCE-1D8870FDCBA0}", &ControlPanel, NULL); + ffRegReadUint(hKey, L"{20D04FE0-3AEA-1069-A2D8-08002B30309D}", &ThisPC, nullptr); + ffRegReadUint(hKey, L"{59031a47-3f72-44a7-89c5-5595fe6b30ee}", &UsersFiles, nullptr); + ffRegReadUint(hKey, L"{F02C1A0D-BE21-4350-88B0-7367FC96EF3C}", &RemoteNetwork, nullptr); + ffRegReadUint(hKey, L"{645FF040-5081-101B-9F08-00AA002F954E}", &RecycleBin, nullptr); + ffRegReadUint(hKey, L"{5399E694-6CE5-4D6C-8FCE-1D8870FDCBA0}", &ControlPanel, nullptr); if (ThisPC && UsersFiles && RemoteNetwork && RecycleBin && ControlPanel) { return "All icons are hidden"; @@ -43,5 +43,5 @@ const char* ffDetectIcons(FFIconsResult* result) { ffStrbufTrimRight(&result->icons2, ' '); ffStrbufTrimRight(&result->icons2, ','); - return NULL; + return nullptr; } diff --git a/src/detection/initsystem/initsystem_haiku.c b/src/detection/initsystem/initsystem_haiku.c index 04857bca30..bdcb64d9a3 100644 --- a/src/detection/initsystem/initsystem_haiku.c +++ b/src/detection/initsystem/initsystem_haiku.c @@ -31,5 +31,5 @@ const char* ffDetectInitSystem(FFInitSystemResult* result) { ffGetFileVersion(path, &result->version); } - return NULL; + return nullptr; } diff --git a/src/detection/initsystem/initsystem_linux.c b/src/detection/initsystem/initsystem_linux.c index 445657bad2..12243bb4d2 100644 --- a/src/detection/initsystem/initsystem_linux.c +++ b/src/detection/initsystem/initsystem_linux.c @@ -6,7 +6,7 @@ #include #include -FF_A_UNUSED static bool extractSystemdVersion(const char* str, uint32_t len, void* userdata) { +[[maybe_unused]] static bool extractSystemdVersion(const char* str, uint32_t len, void* userdata) { if (!ffStrStartsWith(str, "systemd ")) { return true; } @@ -20,13 +20,13 @@ FF_A_UNUSED static bool extractSystemdVersion(const char* str, uint32_t len, voi } const char* ffDetectInitSystem(FFInitSystemResult* result) { - const char* error = ffProcessGetBasicInfoLinux((int) result->pid, &result->name, NULL, NULL); + const char* error = ffProcessGetBasicInfoLinux((int) result->pid, &result->name, nullptr, nullptr); if (error) { #ifdef __ANDROID__ if (access("/system/bin/init", F_OK) == 0) { ffStrbufSetStatic(&result->exe, "/system/bin/init"); ffStrbufSetStatic(&result->name, "init"); - return NULL; + return nullptr; } #endif return error; @@ -34,7 +34,7 @@ const char* ffDetectInitSystem(FFInitSystemResult* result) { const char* _; // In linux /proc/1/exe is not readable - ffProcessGetInfoLinux((int) result->pid, &result->name, &result->exe, &_, NULL); + ffProcessGetInfoLinux((int) result->pid, &result->name, &result->exe, &_, nullptr); if (result->exe.chars[0] == '/') { // In some old system, /sbin/init is a symlink char buf[PATH_MAX]; @@ -52,8 +52,8 @@ const char* ffDetectInitSystem(FFInitSystemResult* result) { if (ffProcessAppendStdOut(&result->version, (char* const[]) { ffStrbufEndsWithS(&result->exe, "/systemd") ? result->exe.chars : "systemctl", // use exe path in case users have another systemd installed "--version", - NULL, - }) == NULL && + nullptr, + }) == nullptr && result->version.length) { uint32_t iStart = ffStrbufFirstIndexC(&result->version, '('); if (iStart < result->version.length) { @@ -67,8 +67,8 @@ const char* ffDetectInitSystem(FFInitSystemResult* result) { if (ffProcessAppendStdOut(&result->version, (char* const[]) { ffStrbufEndsWithS(&result->exe, "/dinit") ? result->exe.chars : "dinit", "--version", - NULL, - }) == NULL && + nullptr, + }) == nullptr && result->version.length) { // Dinit version 0.18.0. ffStrbufSubstrBeforeFirstC(&result->version, '\n'); @@ -79,8 +79,8 @@ const char* ffDetectInitSystem(FFInitSystemResult* result) { if (ffProcessAppendStdOut(&result->version, (char* const[]) { ffStrbufEndsWithS(&result->exe, "/shepherd") ? result->exe.chars : "shepherd", "--version", - NULL, - }) == NULL && + nullptr, + }) == nullptr && result->version.length) { // shepherd (GNU Shepherd) 1.0.6 // The first line in the output might not contain the version @@ -97,8 +97,8 @@ const char* ffDetectInitSystem(FFInitSystemResult* result) { if (ffProcessAppendStdOut(&result->version, (char* const[]) { "/bin/launchctl", "version", - NULL, - }) == NULL && + nullptr, + }) == nullptr && result->version.length) { uint32_t iStart = ffStrbufFirstIndexS(&result->version, "Version "); if (iStart < result->version.length) { @@ -112,5 +112,5 @@ const char* ffDetectInitSystem(FFInitSystemResult* result) { #endif } - return NULL; + return nullptr; } diff --git a/src/detection/initsystem/initsystem_nosupport.c b/src/detection/initsystem/initsystem_nosupport.c index e8ccb8e16c..b3a5036f49 100644 --- a/src/detection/initsystem/initsystem_nosupport.c +++ b/src/detection/initsystem/initsystem_nosupport.c @@ -1,5 +1,5 @@ #include "initsystem.h" -const char* ffDetectInitSystem(FF_A_UNUSED FFInitSystemResult* result) { +const char* ffDetectInitSystem([[maybe_unused]] FFInitSystemResult* result) { return "Not supported on this platform"; } diff --git a/src/detection/initsystem/initsystem_windows.c b/src/detection/initsystem/initsystem_windows.c new file mode 100644 index 0000000000..4b4e647728 --- /dev/null +++ b/src/detection/initsystem/initsystem_windows.c @@ -0,0 +1,38 @@ +#include "initsystem.h" +#include "common/windows/unicode.h" +#include "common/windows/nt.h" +#include "common/windows/version.h" + +#include +#include +#include + +const char* ffDetectInitSystem(FFInitSystemResult* result) { + // We only need to find the first user process, so 1024 entries should be enough + SYSTEM_PROCESS_INFORMATION buffer[1024] = {}; + ULONG size = sizeof(buffer); + NTSTATUS status = NtQuerySystemInformation(SystemProcessInformation, buffer, size, &size); + if (status != STATUS_INFO_LENGTH_MISMATCH && !NT_SUCCESS(status)) { + return "NtQuerySystemInformation(SystemProcessInformation) failed"; + } + + for (SYSTEM_PROCESS_INFORMATION* ptr = buffer; ; ptr = (SYSTEM_PROCESS_INFORMATION*) ((uint8_t*) ptr + ptr->NextEntryOffset)) { + assert(ptr >= buffer && (uint8_t*) ptr < (uint8_t*) buffer + size); + uint16_t len = ptr->ImageName.Length / sizeof(*ptr->ImageName.Buffer); + if (ptr->InheritedFromUniqueProcessId == (HANDLE)(uintptr_t) 4 /* System */ && + len > 4 && _wcsnicmp(ptr->ImageName.Buffer + len - 4, L".exe", 4) == 0) { // smss.exe + result->pid = (uint32_t)(uintptr_t) ptr->UniqueProcessId; + // We have no permission to open the process for querying the full information + wchar_t exePath[MAX_PATH]; + _snwprintf(exePath, ARRAY_SIZE(exePath), L"%ls\\system32\\%.*ls", (const wchar_t*) SharedUserData->NtSystemRoot, len, ptr->ImageName.Buffer); + ffGetFileVersion(exePath, NULL, &result->version); + ffStrbufSetWS(&result->exe, exePath); + ffStrbufSetNWS(&result->name, len - 4, ptr->ImageName.Buffer); + return nullptr; + } + // The last process in the list always has a NextEntryOffset of 0, even if the buffer was truncated. + if (!ptr->NextEntryOffset) { + return "Could not find init system process"; + } + } +} diff --git a/src/detection/keyboard/keyboard_apple.c b/src/detection/keyboard/keyboard_apple.c index e2ecc37e45..63adcafd74 100644 --- a/src/detection/keyboard/keyboard_apple.c +++ b/src/detection/keyboard/keyboard_apple.c @@ -18,19 +18,19 @@ static void enumSet(IOHIDDeviceRef value, FFlist* results) { } const char* ffDetectKeyboard(FFlist* devices /* List of FFKeyboardDevice */) { - IOHIDManagerRef FF_CFTYPE_AUTO_RELEASE manager = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone); + FF_CFTYPE_AUTO_RELEASE IOHIDManagerRef manager = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone); if (IOHIDManagerOpen(manager, kIOHIDOptionsTypeNone) != kIOReturnSuccess) { return "IOHIDManagerOpen() failed"; } - CFDictionaryRef FF_CFTYPE_AUTO_RELEASE matching1 = CFDictionaryCreate(kCFAllocatorDefault, (const void**) (CFStringRef[]) { CFSTR(kIOHIDDeviceUsagePageKey), CFSTR(kIOHIDDeviceUsageKey) }, (const void**) (CFNumberRef[]) { ffCfCreateInt(kHIDPage_GenericDesktop), ffCfCreateInt(kHIDUsage_GD_Keyboard) }, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); + FF_CFTYPE_AUTO_RELEASE CFDictionaryRef matching1 = CFDictionaryCreate(kCFAllocatorDefault, (const void**) (CFStringRef[]) { CFSTR(kIOHIDDeviceUsagePageKey), CFSTR(kIOHIDDeviceUsageKey) }, (const void**) (CFNumberRef[]) { ffCfCreateInt(kHIDPage_GenericDesktop), ffCfCreateInt(kHIDUsage_GD_Keyboard) }, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); IOHIDManagerSetDeviceMatching(manager, matching1); - CFSetRef FF_CFTYPE_AUTO_RELEASE set = IOHIDManagerCopyDevices(manager); + FF_CFTYPE_AUTO_RELEASE CFSetRef set = IOHIDManagerCopyDevices(manager); if (set) { CFSetApplyFunction(set, (CFSetApplierFunction) &enumSet, devices); } IOHIDManagerClose(manager, kIOHIDOptionsTypeNone); - return NULL; + return nullptr; } diff --git a/src/detection/keyboard/keyboard_bsd.c b/src/detection/keyboard/keyboard_bsd.c index 4b0ee574a9..46a703b579 100644 --- a/src/detection/keyboard/keyboard_bsd.c +++ b/src/detection/keyboard/keyboard_bsd.c @@ -35,7 +35,7 @@ static const char* detectByIoctl(FFlist* devices) { ffStrbufAppendF(&device->name, " (kbd%d)", kbdInfo.kb_index); ffStrbufInit(&device->serial); - return NULL; + return nullptr; } #define MAX_UHID_KBDS 64 @@ -80,13 +80,13 @@ static const char* detectByUsbhid(FFlist* devices) { hid_dispose_report_desc(repDesc); } - return NULL; + return nullptr; } const char* ffDetectKeyboard(FFlist* devices /* List of FFKeyboardDevice */) { detectByUsbhid(devices); if (devices->length > 0) { - return NULL; + return nullptr; } return detectByIoctl(devices); } diff --git a/src/detection/keyboard/keyboard_haiku.cpp b/src/detection/keyboard/keyboard_haiku.cpp index dc1d28a0eb..2063f059f0 100644 --- a/src/detection/keyboard/keyboard_haiku.cpp +++ b/src/detection/keyboard/keyboard_haiku.cpp @@ -23,5 +23,5 @@ const char* ffDetectKeyboard(FFlist* devices /* List of FFKeyboardDevice */) { ffStrbufInitS(&item->name, device->Name()); } - return NULL; + return nullptr; } diff --git a/src/detection/keyboard/keyboard_linux.c b/src/detection/keyboard/keyboard_linux.c index 1a29abb01e..539282ab85 100644 --- a/src/detection/keyboard/keyboard_linux.c +++ b/src/detection/keyboard/keyboard_linux.c @@ -9,7 +9,7 @@ const char* ffDetectKeyboard(FFlist* devices /* List of FFKeyboardDevice */) { // This detects both wired and Bluetooth keyboards uniformly. FF_STRBUF_AUTO_DESTROY content = ffStrbufCreate(); if (!ffAppendFileBuffer("/proc/bus/input/devices", &content)) { - return "ffAppendFileBuffer(\"/proc/bus/input/devices\") == NULL"; + return "ffAppendFileBuffer(\"/proc/bus/input/devices\") == nullptr"; } FFstrbuf kbd = ffStrbufCreateStatic("kbd"); @@ -19,7 +19,7 @@ const char* ffDetectKeyboard(FFlist* devices /* List of FFKeyboardDevice */) { .serial = ffStrbufCreate() }; - char* line = NULL; + char* line = nullptr; size_t len = 0; while (ffStrbufGetline(&line, &len, &content)) { switch (line[0]) { @@ -51,7 +51,7 @@ const char* ffDetectKeyboard(FFlist* devices /* List of FFKeyboardDevice */) { if (ffStrStartsWith(bits, "EV=")) { // Check EV_REP (auto-repeat, bit 20) to filter pseudo-keyboards (Power Button, PC Speaker). const char* evBits = bits + strlen("EV="); - uint64_t val = strtoull(evBits, NULL, 16); + uint64_t val = strtoull(evBits, nullptr, 16); if (!(val & (1ULL << EV_REP))) { goto skipDevice; } @@ -63,7 +63,7 @@ const char* ffDetectKeyboard(FFlist* devices /* List of FFKeyboardDevice */) { const char* lastWord = memrchr(keyBits, ' ', len - (size_t) (keyBits - line)); lastWord = lastWord ? lastWord + 1 : keyBits; - uint64_t val = strtoull(lastWord, NULL, 16); + uint64_t val = strtoull(lastWord, nullptr, 16); if (!(val & (1ULL << KEY_A))) { goto skipDevice; } @@ -100,5 +100,5 @@ const char* ffDetectKeyboard(FFlist* devices /* List of FFKeyboardDevice */) { ffStrbufDestroy(&device.serial); } - return NULL; + return nullptr; } diff --git a/src/detection/keyboard/keyboard_nosupport.c b/src/detection/keyboard/keyboard_nosupport.c index 6523ed4051..a80dfd0aeb 100644 --- a/src/detection/keyboard/keyboard_nosupport.c +++ b/src/detection/keyboard/keyboard_nosupport.c @@ -1,5 +1,5 @@ #include "keyboard.h" -const char* ffDetectKeyboard(FF_A_UNUSED FFlist* devices /* List of FFKeyboardDevice */) { +const char* ffDetectKeyboard([[maybe_unused]] FFlist* devices /* List of FFKeyboardDevice */) { return "No mouse support on this platform"; } diff --git a/src/detection/keyboard/keyboard_windows.c b/src/detection/keyboard/keyboard_windows.c index 272f632e54..7d98ac4edd 100644 --- a/src/detection/keyboard/keyboard_windows.c +++ b/src/detection/keyboard/keyboard_windows.c @@ -12,14 +12,14 @@ const char* ffDetectKeyboard(FFlist* devices /* List of FFKeyboardDevice */) { UINT nDevices = 0; - if (GetRawInputDeviceList(NULL, &nDevices, sizeof(RAWINPUTDEVICELIST))) { - return "GetRawInputDeviceList(NULL) failed"; + if (GetRawInputDeviceList(nullptr, &nDevices, sizeof(RAWINPUTDEVICELIST))) { + return "GetRawInputDeviceList(nullptr) failed"; } if (nDevices == 0) { return "No HID devices found"; } - RAWINPUTDEVICELIST* FF_AUTO_FREE pRawInputDeviceList = (RAWINPUTDEVICELIST*) malloc(sizeof(RAWINPUTDEVICELIST) * nDevices); + FF_AUTO_FREE RAWINPUTDEVICELIST* pRawInputDeviceList = (RAWINPUTDEVICELIST*) malloc(sizeof(RAWINPUTDEVICELIST) * nDevices); if ((nDevices = GetRawInputDeviceList(pRawInputDeviceList, &nDevices, sizeof(RAWINPUTDEVICELIST))) == (UINT) -1) { return "GetRawInputDeviceList(pRawInputDeviceList) failed"; } @@ -49,7 +49,7 @@ const char* ffDetectKeyboard(FFlist* devices /* List of FFKeyboardDevice */) { wchar_t buffer[MAX_PATH]; - HANDLE FF_AUTO_CLOSE_FD hHidFile = CreateFileW(devName, 0 /* must be 0 instead of GENERIC_READ */, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); + FF_AUTO_CLOSE_FD HANDLE hHidFile = CreateFileW(devName, 0 /* must be 0 instead of GENERIC_READ */, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); if (hHidFile != INVALID_HANDLE_VALUE) { if (HidD_GetProductString(hHidFile, buffer, (ULONG) sizeof(buffer))) { ffStrbufSetWS(&device->name, buffer); @@ -81,5 +81,5 @@ const char* ffDetectKeyboard(FFlist* devices /* List of FFKeyboardDevice */) { } } - return NULL; + return nullptr; } diff --git a/src/detection/libc/libc_android.c b/src/detection/libc/libc_android.c index 9d7762c783..14f4ab1ba4 100644 --- a/src/detection/libc/libc_android.c +++ b/src/detection/libc/libc_android.c @@ -15,7 +15,7 @@ const char* ffDetectLibc(FFLibcResult* result) { #endif ; - return NULL; + return nullptr; #else return "Unknown Android libc"; #endif diff --git a/src/detection/libc/libc_apple.c b/src/detection/libc/libc_apple.c index 07ca2b5a86..51b8d1d5c4 100644 --- a/src/detection/libc/libc_apple.c +++ b/src/detection/libc/libc_apple.c @@ -6,7 +6,7 @@ const char* ffDetectLibc(FFLibcResult* result) { #ifdef FF_LIBSYSTEM_VERSION result->version = FF_LIBSYSTEM_VERSION; #else - result->version = NULL; + result->version = nullptr; #endif - return NULL; + return nullptr; } diff --git a/src/detection/libc/libc_bsd.c b/src/detection/libc/libc_bsd.c index bd73165c00..de5176acf1 100644 --- a/src/detection/libc/libc_bsd.c +++ b/src/detection/libc/libc_bsd.c @@ -2,7 +2,7 @@ const char* ffDetectLibc(FFLibcResult* result) { result->name = "Unknown"; - result->version = NULL; + result->version = nullptr; #ifdef __DragonFly__ // We define `__FreeBSD__` on DragonFly BSD for simplification result->name = "DF"; @@ -16,5 +16,5 @@ const char* ffDetectLibc(FFLibcResult* result) { #endif #endif - return NULL; + return nullptr; } diff --git a/src/detection/libc/libc_linux.c b/src/detection/libc/libc_linux.c index a445c7b9b5..358b717eba 100644 --- a/src/detection/libc/libc_linux.c +++ b/src/detection/libc/libc_linux.c @@ -15,9 +15,9 @@ const char* ffDetectLibc(FFLibcResult* result) { #ifdef FF_MUSL_VERSION result->version = FF_MUSL_VERSION; #else - result->version = NULL; + result->version = nullptr; #endif #endif - return NULL; + return nullptr; } diff --git a/src/detection/libc/libc_nosupport.c b/src/detection/libc/libc_nosupport.c index e4687b0723..9aacd5947f 100644 --- a/src/detection/libc/libc_nosupport.c +++ b/src/detection/libc/libc_nosupport.c @@ -2,6 +2,6 @@ const char* ffDetectLibc(FFLibcResult* result) { result->name = "Unknown"; - result->version = NULL; - return NULL; + result->version = nullptr; + return nullptr; } diff --git a/src/detection/libc/libc_windows.cpp b/src/detection/libc/libc_windows.cpp index c94062a4bd..c3d866eb4d 100644 --- a/src/detection/libc/libc_windows.cpp +++ b/src/detection/libc/libc_windows.cpp @@ -7,48 +7,37 @@ extern "C" { #endif template -class version_t { - constexpr static auto buflen() noexcept { - unsigned int len = 2; // "." - if (Major == 0) { +struct version_t { + static constexpr uint32_t digits(uint32_t n) noexcept { + uint32_t len = 1; + for (auto temp = n / 10; temp; temp /= 10) { len++; - } else { - for (auto n = Major; n; len++, n /= 10); - } - - if (Minor == 0) { - len++; - } else { - for (auto n = Minor; n; len++, n /= 10); } return len; } - char buf[buflen()] = {}; + char buf[digits(Major) + digits(Minor) + 2]; - public: constexpr version_t() noexcept { - auto ptr = buf + buflen(); + auto ptr = buf + sizeof(buf); *--ptr = '\0'; - if (Minor == 0) { - *--ptr = '0'; - } else { - for (auto n = Minor; n; n /= 10) { - *--ptr = "0123456789"[n % 10]; + auto append = [&](uint32_t n) noexcept { + if (n == 0) { + *--ptr = '0'; + } else { + for (; n; n /= 10) { + *--ptr = static_cast('0' + n % 10); + } } - } + }; + + append(Minor); *--ptr = '.'; - if (Major == 0) { - *--ptr = '0'; - } else { - for (auto n = Major; n; n /= 10) { - *--ptr = "0123456789"[n % 10]; - } - } + append(Major); } - constexpr operator const char*() const { + constexpr operator const char*() const noexcept { return buf; } }; @@ -63,6 +52,6 @@ extern "C" const char* ffDetectLibc(FFLibcResult* result) { result->name = "msvcrt"; #endif - result->version = version<(__MSVCRT_VERSION__ >> 8), (__MSVCRT_VERSION__ & 8)>; - return NULL; + result->version = version<(__MSVCRT_VERSION__ >> 8), (__MSVCRT_VERSION__ & 0xFF)>; + return nullptr; } diff --git a/src/detection/lm/lm_linux.c b/src/detection/lm/lm_linux.c index 140205d318..1623c72775 100644 --- a/src/detection/lm/lm_linux.c +++ b/src/detection/lm/lm_linux.c @@ -10,9 +10,9 @@ #define FF_SYSTEMD_USERS_PATH "/run/systemd/users/" static const char* getGdmVersion(FFstrbuf* version) { - const char* error = ffProcessAppendStdOut(version, (char* const[]) { "gdm", "--version", NULL }); + const char* error = ffProcessAppendStdOut(version, (char* const[]) { "gdm", "--version", nullptr }); if (error || version->length == 0) { - error = ffProcessAppendStdOut(version, (char* const[]) { "gdm3", "--version", NULL }); + error = ffProcessAppendStdOut(version, (char* const[]) { "gdm3", "--version", nullptr }); if (error || version->length == 0) { return "Failed to get GDM version"; } @@ -20,11 +20,11 @@ static const char* getGdmVersion(FFstrbuf* version) { // GDM 44.1 ffStrbufSubstrAfterFirstC(version, ' '); - return NULL; + return nullptr; } static const char* getSshdVersion(FFstrbuf* version) { - const char* error = ffProcessAppendStdErr(version, (char* const[]) { "sshd", "-V", NULL }); + const char* error = ffProcessAppendStdErr(version, (char* const[]) { "sshd", "-V", nullptr }); if (error) { return error; } @@ -32,7 +32,7 @@ static const char* getSshdVersion(FFstrbuf* version) { // OpenSSH_9.0p1, OpenSSL 3.0.9 30 May 2023... ffStrbufSubstrBeforeFirstC(version, ','); ffStrbufSubstrAfterFirstC(version, '_'); - return NULL; + return nullptr; } #ifdef FF_HAVE_ZLIB @@ -78,16 +78,16 @@ static const char* getSddmVersion(FFstrbuf* version) { ffStrbufTrimRight(version, '"'); ffStrbufSubstrAfterLastC(version, ' '); - return NULL; + return nullptr; } #else -static const char* getSddmVersion(FF_A_UNUSED FFstrbuf* version) { +static const char* getSddmVersion([[maybe_unused]] FFstrbuf* version) { return "Fastfetch is built without libz support"; } #endif static const char* getXfwmVersion(FFstrbuf* version) { - const char* error = ffProcessAppendStdOut(version, (char* const[]) { "xfwm4", "--version", NULL }); + const char* error = ffProcessAppendStdOut(version, (char* const[]) { "xfwm4", "--version", nullptr }); if (error) { return error; } @@ -96,11 +96,11 @@ static const char* getXfwmVersion(FFstrbuf* version) { ffStrbufSubstrAfterFirstS(version, "version "); ffStrbufSubstrBeforeFirstC(version, ' '); - return NULL; + return nullptr; } static const char* getLightdmVersion(FFstrbuf* version) { - const char* error = ffProcessAppendStdErr(version, (char* const[]) { "lightdm", "--version", NULL }); + const char* error = ffProcessAppendStdErr(version, (char* const[]) { "lightdm", "--version", nullptr }); if (error) { return error; } @@ -109,7 +109,7 @@ static const char* getLightdmVersion(FFstrbuf* version) { ffStrbufSubstrAfterFirstC(version, ' '); ffStrbufTrimRight(version, '\n'); - return NULL; + return nullptr; } const char* ffDetectLM(FFLMResult* result) { @@ -164,5 +164,5 @@ const char* ffDetectLM(FFLMResult* result) { ffStrbufSetS(&result->type, FF_WM_PROTOCOL_TTY); } - return NULL; + return nullptr; } diff --git a/src/detection/lm/lm_nosupport.c b/src/detection/lm/lm_nosupport.c index 22c1803077..2f6811379c 100644 --- a/src/detection/lm/lm_nosupport.c +++ b/src/detection/lm/lm_nosupport.c @@ -1,5 +1,5 @@ #include "lm.h" -const char* ffDetectLM(FF_A_UNUSED FFLMResult* result) { +const char* ffDetectLM([[maybe_unused]] FFLMResult* result) { return "Not supported on this platform"; } diff --git a/src/detection/loadavg/loadavg_bsd.c b/src/detection/loadavg/loadavg_bsd.c index 83896b299b..7ef95ed77a 100644 --- a/src/detection/loadavg/loadavg_bsd.c +++ b/src/detection/loadavg/loadavg_bsd.c @@ -13,11 +13,11 @@ const char* ffDetectLoadavg(double result[3]) { struct loadavg load; size_t size = sizeof(load); - if (sysctl((int[]) { CTL_VM, VM_LOADAVG }, 2, &load, &size, NULL, 0) < 0) { + if (sysctl((int[]) { CTL_VM, VM_LOADAVG }, 2, &load, &size, nullptr, 0) < 0) { return "sysctl({CTL_VM, VM_LOADAVG}) failed"; } for (int i = 0; i < 3; i++) { result[i] = (double) load.ldavg[i] / (double) load.fscale; } - return NULL; + return nullptr; } diff --git a/src/detection/loadavg/loadavg_linux.c b/src/detection/loadavg/loadavg_linux.c index a1693123f3..ab4c7373f3 100644 --- a/src/detection/loadavg/loadavg_linux.c +++ b/src/detection/loadavg/loadavg_linux.c @@ -13,7 +13,7 @@ const char* ffDetectLoadavg(double result[3]) { buf[nRead] = '\0'; if (sscanf(buf, "%lf%lf%lf", &result[0], &result[1], &result[2]) == 3) { - return NULL; + return nullptr; } } @@ -29,5 +29,5 @@ const char* ffDetectLoadavg(double result[3]) { result[i] = (double) si.loads[i] / (1 << SI_LOAD_SHIFT); } #endif - return NULL; + return nullptr; } diff --git a/src/detection/loadavg/loadavg_nosupport.c b/src/detection/loadavg/loadavg_nosupport.c index f14c717953..40dde9d2aa 100644 --- a/src/detection/loadavg/loadavg_nosupport.c +++ b/src/detection/loadavg/loadavg_nosupport.c @@ -1,5 +1,5 @@ #include "detection/loadavg/loadavg.h" -const char* ffDetectLoadavg(FF_A_UNUSED double result[3]) { +const char* ffDetectLoadavg([[maybe_unused]] double result[3]) { return "Not supported on this platform"; } diff --git a/src/detection/loadavg/loadavg_sunos.c b/src/detection/loadavg/loadavg_sunos.c index 91e3edd733..7cf63eec67 100644 --- a/src/detection/loadavg/loadavg_sunos.c +++ b/src/detection/loadavg/loadavg_sunos.c @@ -3,5 +3,5 @@ #include const char* ffDetectLoadavg(double result[3]) { - return getloadavg(result, 3) == 3 ? NULL : "getloadavg() failed"; + return getloadavg(result, 3) == 3 ? nullptr : "getloadavg() failed"; } diff --git a/src/detection/locale/locale_linux.c b/src/detection/locale/locale_linux.c index 4c04f26eb2..ab630a7a3c 100644 --- a/src/detection/locale/locale_linux.c +++ b/src/detection/locale/locale_linux.c @@ -5,17 +5,17 @@ const char* ffDetectLocale(FFstrbuf* result) { ffStrbufAppendS(result, getenv("LC_ALL")); if (result->length > 0) { - return NULL; + return nullptr; } ffStrbufAppendS(result, getenv("LANG")); if (result->length > 0) { - return NULL; + return nullptr; } - ffStrbufAppendS(result, setlocale(LC_TIME, NULL)); + ffStrbufAppendS(result, setlocale(LC_TIME, nullptr)); if (result->length > 0) { - return NULL; + return nullptr; } return "Failed to detect locale"; diff --git a/src/detection/locale/locale_windows.c b/src/detection/locale/locale_windows.c index b247365069..0f17e8bfae 100644 --- a/src/detection/locale/locale_windows.c +++ b/src/detection/locale/locale_windows.c @@ -12,5 +12,5 @@ const char* ffDetectLocale(FFstrbuf* result) { ffStrbufSetNWS(result, (uint32_t) size - 1, name); - return NULL; + return nullptr; } diff --git a/src/detection/localip/localip_linux.c b/src/detection/localip/localip_linux.c index d07ec76961..203543c67c 100644 --- a/src/detection/localip/localip_linux.c +++ b/src/detection/localip/localip_linux.c @@ -181,7 +181,7 @@ static FFLocalIpIpv6Type getIpv6Type(struct ifaddrs* ifa) { return result; } - char* line = NULL; + char* line = nullptr; size_t len = 0; while (ffStrbufGetline(&line, &len, &buffer)) { struct in6_addr* entry = FF_LIST_ADD(struct in6_addr, addresses); @@ -278,7 +278,7 @@ const char* ffDetectLocalIps(const FFLocalIpOptions* options, FFlist* results) { options->showType, options->namePrefix.chars); - struct ifaddrs* ifAddrStruct = NULL; + struct ifaddrs* ifAddrStruct = nullptr; if (getifaddrs(&ifAddrStruct) < 0) { FF_DEBUG("getifaddrs() failed"); return "getifaddrs(&ifAddrStruct) failed"; @@ -335,7 +335,7 @@ const char* ffDetectLocalIps(const FFLocalIpOptions* options, FFlist* results) { ifa->ifa_addr->sa_family, (unsigned long) ifa->ifa_flags); - FFAdapter* adapter = NULL; + FFAdapter* adapter = nullptr; FF_LIST_FOR_EACH (FFAdapter, x, adapters) { if (ffStrEquals(x->mac->ifa_name, ifa->ifa_name)) { adapter = x; @@ -425,7 +425,7 @@ const char* ffDetectLocalIps(const FFLocalIpOptions* options, FFlist* results) { } if (!(options->showType & FF_LOCALIP_TYPE_ALL_IPS_BIT)) { - struct ifaddrs* ifa = NULL; + struct ifaddrs* ifa = nullptr; if (isDefaultRouteIf && defaultRouteV4->preferredSourceAddrV4 != 0) { FF_LIST_FOR_EACH (struct ifaddrs*, pifa, adapter->ipv4) { struct sockaddr_in* ipv4 = (struct sockaddr_in*) (*pifa)->ifa_addr; @@ -468,8 +468,8 @@ const char* ffDetectLocalIps(const FFLocalIpOptions* options, FFlist* results) { if (options->ipv6Type == FF_LOCALIP_IPV6_TYPE_AUTO) { if (!(options->showType & FF_LOCALIP_TYPE_ALL_IPS_BIT)) { - struct ifaddrs* selected = NULL; - struct ifaddrs* secondary = NULL; + struct ifaddrs* selected = nullptr; + struct ifaddrs* secondary = nullptr; FF_LIST_FOR_EACH (struct ifaddrs*, pifa, adapter->ipv6) { FFLocalIpIpv6Type type = getIpv6Type(*pifa); @@ -542,7 +542,7 @@ const char* ffDetectLocalIps(const FFLocalIpOptions* options, FFlist* results) { if (ifAddrStruct) { freeifaddrs(ifAddrStruct); - ifAddrStruct = NULL; + ifAddrStruct = nullptr; FF_DEBUG("Cleaned up interface address structures"); } @@ -982,13 +982,13 @@ const char* ffDetectLocalIps(const FFLocalIpOptions* options, FFlist* results) { #endif #if __sun if (options->showType & FF_LOCALIP_TYPE_SPEED_BIT) { - FF_A_CLEANUP(kstatFreeWrap) kstat_ctl_t* kc = kstat_open(); + [[gnu::cleanup(kstatFreeWrap)]] kstat_ctl_t* kc = kstat_open(); for (kstat_t* ks = kc->kc_chain; ks; ks = ks->ks_next) { if (!ffStrEquals(ks->ks_class, "net") || !ffStrEquals(ks->ks_module, "link")) { continue; } if (ffStrbufEqualS(&iface->name, ks->ks_name)) { - if (kstat_read(kc, ks, NULL) >= 0) { + if (kstat_read(kc, ks, nullptr) >= 0) { kstat_named_t* ifspeed = (kstat_named_t*) kstat_data_lookup(ks, "ifspeed"); if (ifspeed) { iface->speed = (int32_t) (ifspeed->value.ui64 / 1000 / 1000); @@ -1007,5 +1007,5 @@ const char* ffDetectLocalIps(const FFLocalIpOptions* options, FFlist* results) { } FF_DEBUG("Local IP detection completed, found %u interfaces", results->length); - return NULL; + return nullptr; } diff --git a/src/detection/localip/localip_windows.c b/src/detection/localip/localip_windows.c index 6a7e0e79ba..c36118015c 100644 --- a/src/detection/localip/localip_windows.c +++ b/src/detection/localip/localip_windows.c @@ -30,7 +30,7 @@ const char* ffDetectLocalIps(const FFLocalIpOptions* options, FFlist* results) { (int) options->namePrefix.length, options->namePrefix.chars); - IP_ADAPTER_ADDRESSES* FF_AUTO_FREE adapter_addresses = NULL; + FF_AUTO_FREE IP_ADAPTER_ADDRESSES* adapter_addresses = nullptr; // Multiple attempts in case interfaces change while // we are in the middle of querying them. @@ -51,7 +51,7 @@ const char* ffDetectLocalIps(const FFLocalIpOptions* options, FFlist* results) { DWORD error = GetAdaptersAddresses( family, GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER, - NULL, + nullptr, adapter_addresses, &adapter_addresses_buffer_size); @@ -67,7 +67,7 @@ const char* ffDetectLocalIps(const FFLocalIpOptions* options, FFlist* results) { } } - FF_A_UNUSED int adapterCount = 0, processedCount = 0; + [[maybe_unused]] int adapterCount = 0, processedCount = 0; // Iterate through all of the adapters for (IP_ADAPTER_ADDRESSES* adapter = adapter_addresses; adapter; adapter = adapter->Next) { @@ -127,7 +127,7 @@ const char* ffDetectLocalIps(const FFLocalIpOptions* options, FFlist* results) { uint32_t typesToAdd = options->showType & (FF_LOCALIP_TYPE_IPV4_BIT | FF_LOCALIP_TYPE_IPV6_BIT | FF_LOCALIP_TYPE_ALL_IPS_BIT); FF_DEBUG("Types to add for adapter %u: 0x%X", (unsigned) adapter->IfIndex, typesToAdd); - FF_A_UNUSED int ipv4Count = 0, ipv6Count = 0; + [[maybe_unused]] int ipv4Count = 0, ipv6Count = 0; for (IP_ADAPTER_UNICAST_ADDRESS* ifa = adapter->FirstUnicastAddress; ifa; ifa = ifa->Next) { FF_DEBUG("Processing unicast address: prefix origin=%d, suffix origin=%d, family=%d, DadState=%d", @@ -266,5 +266,5 @@ const char* ffDetectLocalIps(const FFLocalIpOptions* options, FFlist* results) { processedCount, results->length); - return NULL; + return nullptr; } diff --git a/src/detection/media/media.c b/src/detection/media/media.c index 7adfb991bc..2dfd28a61a 100644 --- a/src/detection/media/media.c +++ b/src/detection/media/media.c @@ -13,7 +13,7 @@ static void removeMediaCoverFile(void) { } const FFMediaResult* ffDetectMedia(bool saveCover) { - if (result.error.chars == NULL) { + if (result.error.chars == nullptr) { ffStrbufInit(&result.error); ffStrbufInit(&result.playerId); ffStrbufInit(&result.player); diff --git a/src/detection/media/media_apple.m b/src/detection/media/media_apple.m index 6dcc782811..a9f2ada5e4 100644 --- a/src/detection/media/media_apple.m +++ b/src/detection/media/media_apple.m @@ -9,14 +9,14 @@ #import // https://github.com/andrewwiik/iOS-Blocks/blob/master/Widgets/Music/MediaRemote.h -extern void MRMediaRemoteGetNowPlayingInfo(dispatch_queue_t dispatcher, void (^callback)(_Nullable CFDictionaryRef info)) FF_A_WEAK_IMPORT; -extern void MRMediaRemoteGetNowPlayingApplicationIsPlaying(dispatch_queue_t queue, void (^callback)(BOOL playing)) FF_A_WEAK_IMPORT; -extern void MRMediaRemoteGetNowPlayingApplicationDisplayID(dispatch_queue_t queue, void (^callback)(_Nullable CFStringRef displayID)) FF_A_WEAK_IMPORT; -extern void MRMediaRemoteGetNowPlayingApplicationDisplayName(int unknown, dispatch_queue_t queue, void (^callback)(_Nullable CFStringRef name)) FF_A_WEAK_IMPORT; +[[clang::weak_import]] extern void MRMediaRemoteGetNowPlayingInfo(dispatch_queue_t dispatcher, void (^callback)(_Nullable CFDictionaryRef info)); +[[clang::weak_import]] extern void MRMediaRemoteGetNowPlayingApplicationIsPlaying(dispatch_queue_t queue, void (^callback)(BOOL playing)); +[[clang::weak_import]] extern void MRMediaRemoteGetNowPlayingApplicationDisplayID(dispatch_queue_t queue, void (^callback)(_Nullable CFStringRef displayID)); +[[clang::weak_import]] extern void MRMediaRemoteGetNowPlayingApplicationDisplayName(int unknown, dispatch_queue_t queue, void (^callback)(_Nullable CFStringRef name)); static uint32_t getTrueElapsedTime(CFDictionaryRef info) { double elapsedTime; - if (ffCfDictGetDouble(info, CFSTR("kMRMediaRemoteNowPlayingInfoElapsedTime"), &elapsedTime) != NULL) { + if (ffCfDictGetDouble(info, CFSTR("kMRMediaRemoteNowPlayingInfoElapsedTime"), &elapsedTime) != nullptr) { return 0; } @@ -24,8 +24,8 @@ static uint32_t getTrueElapsedTime(CFDictionaryRef info) { double playbackRate; uint64_t timestampEpoch; - if (ffCfDictGetDouble(info, CFSTR("kMRMediaRemoteNowPlayingInfoPlaybackRate"), &playbackRate) == NULL && - ffCfDictGetDateAsEpoch(info, CFSTR("kMRMediaRemoteNowPlayingInfoTimestamp"), ×tampEpoch) == NULL) { + if (ffCfDictGetDouble(info, CFSTR("kMRMediaRemoteNowPlayingInfoPlaybackRate"), &playbackRate) == nullptr && + ffCfDictGetDateAsEpoch(info, CFSTR("kMRMediaRemoteNowPlayingInfoTimestamp"), ×tampEpoch) == nullptr) { uint64_t timeDiff = ffTimeGetNow() - timestampEpoch; elapsedTime += (double) timeDiff * playbackRate; } @@ -44,14 +44,14 @@ static uint32_t getTrueElapsedTime(CFDictionaryRef info) { dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0); dispatch_group_enter(group); - __block const char* error = NULL; + __block const char* error = nullptr; MRMediaRemoteGetNowPlayingInfo(queue, ^(_Nullable CFDictionaryRef info) { if (info != nil) { ffCfDictGetString(info, CFSTR("kMRMediaRemoteNowPlayingInfoTitle"), &result->song); ffCfDictGetString(info, CFSTR("kMRMediaRemoteNowPlayingInfoArtist"), &result->artist); ffCfDictGetString(info, CFSTR("kMRMediaRemoteNowPlayingInfoAlbum"), &result->album); double value; - if (ffCfDictGetDouble(info, CFSTR("kMRMediaRemoteNowPlayingInfoDuration"), &value) == NULL) { + if (ffCfDictGetDouble(info, CFSTR("kMRMediaRemoteNowPlayingInfoDuration"), &value) == nullptr) { result->length = (uint32_t) (value * 1000); result->position = getTrueElapsedTime(info); } @@ -62,7 +62,7 @@ static uint32_t getTrueElapsedTime(CFDictionaryRef info) { CFStringRef mime = (CFStringRef) CFDictionaryGetValue(info, CFSTR("kMRMediaRemoteNowPlayingInfoArtworkMIMEType")); #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" - FF_CFTYPE_AUTO_RELEASE CFStringRef uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, mime, NULL); + FF_CFTYPE_AUTO_RELEASE CFStringRef uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, mime, nullptr); FF_CFTYPE_AUTO_RELEASE CFStringRef ext = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassFilenameExtension); #pragma clang diagnostic pop NSString* tmpDir = NSTemporaryDirectory(); @@ -104,14 +104,14 @@ static uint32_t getTrueElapsedTime(CFDictionaryRef info) { // Don't dispatch_release because we are using ARC if (result->song.length > 0) { - return NULL; + return nullptr; } return error; } #if !FF_MODULE_DISABLE_MEDIA -__attribute__((visibility("default"), used)) int ffPrintMediaByMediaRemote(int saveCover) { +[[gnu::visibility("default"), gnu::used]] int ffPrintMediaByMediaRemote(int saveCover) { FFMediaResult media = { .status = ffStrbufCreate(), .song = ffStrbufCreate(), @@ -121,7 +121,7 @@ static uint32_t getTrueElapsedTime(CFDictionaryRef info) { .player = ffStrbufCreate(), .cover = ffStrbufCreate(), }; - if (getMediaByMediaRemote(&media, !!saveCover) != NULL) { + if (getMediaByMediaRemote(&media, !!saveCover) != nullptr) { return 1; } ffStrbufAppendC(&media.status, '\n'); @@ -180,16 +180,16 @@ static uint32_t getTrueElapsedTime(CFDictionaryRef info) { // status\ntitle\nartist\nalbum\nbundleName\nappName\ncoverPath\nelapsedTimeMS\ndurationMS FFstrbuf* const strList[] = { &result->status, &result->song, &result->artist, &result->album, &result->playerId, &result->player, &result->cover }; - char* line = NULL; + char* line = nullptr; size_t len = 0; for (uint32_t i = 0; i < ARRAY_SIZE(strList) && ffStrbufGetline(&line, &len, &buffer); ++i) { ffStrbufSetS(strList[i], line); } uint32_t* const numList[] = { &result->position, &result->length }; for (uint32_t i = 0; i < ARRAY_SIZE(numList) && ffStrbufGetline(&line, &len, &buffer); ++i) { - *numList[i] = (uint32_t) strtoul(line, NULL, 10); + *numList[i] = (uint32_t) strtoul(line, nullptr, 10); } - return NULL; + return nullptr; } void ffDetectMediaImpl(FFMediaResult* media, bool saveCover) { diff --git a/src/detection/media/media_linux.c b/src/detection/media/media_linux.c index 724e834845..dcd4a05f5b 100644 --- a/src/detection/media/media_linux.c +++ b/src/detection/media/media_linux.c @@ -81,7 +81,7 @@ static bool parseMprisMetadata(FFDBusData* data, DBusMessageIter* rootIterator, break; } char str[] = { path.chars[i + 1], path.chars[i + 2], 0 }; - char* end = NULL; + char* end = nullptr; const char decodedChar = (char) strtoul(str, &end, 16); if (end == &str[2]) { i += 2; @@ -111,7 +111,7 @@ static bool parseMprisMetadata(FFDBusData* data, DBusMessageIter* rootIterator, static bool getBusProperties(FFDBusData* data, const char* busName, FFMediaResult* result) { // Get all properties at once to reduce the number of IPCs DBusMessage* reply = ffDBusGetAllProperties(data, busName, "/org/mpris/MediaPlayer2", "org.mpris.MediaPlayer2.Player"); - if (reply == NULL) { + if (reply == nullptr) { return false; } @@ -166,7 +166,7 @@ static bool getBusProperties(FFDBusData* data, const char* busName, FFMediaResul break; } char str[] = { fileName[1], fileName[2], 0 }; - ffStrbufAppendC(&result->song, (char) strtoul(str, NULL, 16)); + ffStrbufAppendC(&result->song, (char) strtoul(str, nullptr, 16)); fileName += 2; } } @@ -221,8 +221,8 @@ static void getBestBus(FFDBusData* data, FFMediaResult* result) { return; } - DBusMessage* reply = ffDBusGetMethodReply(data, "org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "ListNames", NULL, NULL); - if (reply == NULL) { + DBusMessage* reply = ffDBusGetMethodReply(data, "org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "ListNames", nullptr, nullptr); + if (reply == nullptr) { return; } @@ -260,7 +260,7 @@ static void getBestBus(FFDBusData* data, FFMediaResult* result) { static const char* getMedia(FFMediaResult* result) { FF_DBUS_AUTO_DESTROY_DATA FFDBusData data = {}; const char* error = ffDBusLoadData(DBUS_BUS_SESSION, &data); - if (error != NULL) { + if (error != nullptr) { return error; } @@ -272,7 +272,7 @@ static const char* getMedia(FFMediaResult* result) { getBestBus(&data, result); } - return NULL; + return nullptr; } #endif diff --git a/src/detection/media/media_windows.cpp b/src/detection/media/media_windows.cpp index f0ebd35f81..8f608c1250 100644 --- a/src/detection/media/media_windows.cpp +++ b/src/detection/media/media_windows.cpp @@ -51,7 +51,7 @@ static inline HRESULT ffQueryInterface(SourceAbi* source, abi_t static HRESULT ffWaitForAsyncOperation(TOperationAbi* operation, TResultAbi** result) { - IAsyncInfo* FF_AUTO_RELEASE_COM_OBJECT asyncInfo = NULL; + FF_AUTO_RELEASE_COM_OBJECT IAsyncInfo* asyncInfo = nullptr; HRESULT hr = ffQueryInterface(operation, &asyncInfo); if (FAILED(hr)) { return hr; @@ -82,7 +82,7 @@ static HRESULT ffWaitForAsyncOperation(TOperationAbi* operation, TResultAbi** re template static HRESULT ffRunAndWait(TOperation&& operation, abi_t** result) { - abi_t>* FF_AUTO_RELEASE_COM_OBJECT opResult = NULL; + FF_AUTO_RELEASE_COM_OBJECT abi_t>* opResult = nullptr; HRESULT hr = operation(reinterpret_cast(&opResult)); if (FAILED(hr) || !opResult) { return hr; @@ -93,9 +93,9 @@ static HRESULT ffRunAndWait(TOperation&& operation, abi_t** r template static HRESULT ffRunAndWait2(TOperation&& operation, abi_t** result) { - *result = NULL; + *result = nullptr; - abi_t>* FF_AUTO_RELEASE_COM_OBJECT opResult = NULL; + FF_AUTO_RELEASE_COM_OBJECT abi_t>* opResult = nullptr; HRESULT hr = operation(reinterpret_cast(&opResult)); if (FAILED(hr) || !opResult) { return hr; @@ -107,7 +107,7 @@ static HRESULT ffRunAndWait2(TOperation&& operation, abi_t** static HRESULT ffSaveThumbnailToTempPath( abi_t* thumbnail, FFstrbuf* destination) { - abi_t* FF_AUTO_RELEASE_COM_OBJECT contentStream = NULL; + FF_AUTO_RELEASE_COM_OBJECT abi_t* contentStream = nullptr; HRESULT hr = ffRunAndWait([=](void** result) { return thumbnail->OpenReadAsync(result); }, @@ -116,7 +116,7 @@ static HRESULT ffSaveThumbnailToTempPath( return FAILED(hr) ? hr : E_FAIL; } - abi_t* FF_AUTO_RELEASE_COM_OBJECT randomAccessStream = NULL; + FF_AUTO_RELEASE_COM_OBJECT abi_t* randomAccessStream = nullptr; hr = ffQueryInterface(contentStream, &randomAccessStream); if (FAILED(hr)) { return hr; @@ -132,25 +132,25 @@ static HRESULT ffSaveThumbnailToTempPath( return HRESULT_FROM_WIN32(ERROR_FILE_TOO_LARGE); } - abi_t* FF_AUTO_RELEASE_COM_OBJECT bufferFactory = NULL; + FF_AUTO_RELEASE_COM_OBJECT abi_t* bufferFactory = nullptr; hr = ffGetActivationFactory(L"Windows.Storage.Streams.Buffer", winrt::guid_of(), &bufferFactory); if (FAILED(hr)) { return hr; } - abi_t* FF_AUTO_RELEASE_COM_OBJECT buffer = NULL; + FF_AUTO_RELEASE_COM_OBJECT abi_t* buffer = nullptr; hr = bufferFactory->Create((UINT32) size, reinterpret_cast(&buffer)); if (FAILED(hr) || !buffer) { return FAILED(hr) ? hr : E_FAIL; } - abi_t* FF_AUTO_RELEASE_COM_OBJECT inputStream = NULL; + FF_AUTO_RELEASE_COM_OBJECT abi_t* inputStream = nullptr; hr = ffQueryInterface(contentStream, &inputStream); if (FAILED(hr)) { return hr; } - abi_t* FF_AUTO_RELEASE_COM_OBJECT readBuffer = NULL; + FF_AUTO_RELEASE_COM_OBJECT abi_t* readBuffer = nullptr; hr = ffRunAndWait2([=](void** result) { return inputStream->ReadAsync(buffer, (uint32_t) size, (uint32_t) winrt::Windows::Storage::Streams::InputStreamOptions::None, result); }, @@ -165,13 +165,13 @@ static HRESULT ffSaveThumbnailToTempPath( return FAILED(hr) ? hr : S_FALSE; } - Windows::Storage::Streams::IBufferByteAccess* FF_AUTO_RELEASE_COM_OBJECT byteAccess = NULL; + FF_AUTO_RELEASE_COM_OBJECT Windows::Storage::Streams::IBufferByteAccess* byteAccess = nullptr; hr = readBuffer->QueryInterface(IID_PPV_ARGS(&byteAccess)); if (FAILED(hr)) { return hr; } - byte* bytes = NULL; + byte* bytes = nullptr; hr = byteAccess->Buffer(&bytes); if (FAILED(hr) || !bytes) { return FAILED(hr) ? hr : E_FAIL; @@ -188,7 +188,7 @@ static HRESULT ffSaveThumbnailToTempPath( return HRESULT_FROM_WIN32(GetLastError()); } - HANDLE file = CreateFileW(tempFilePath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); + HANDLE file = CreateFileW(tempFilePath, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); if (file == INVALID_HANDLE_VALUE) { DWORD writeError = GetLastError(); DeleteFileW(tempFilePath); @@ -196,9 +196,9 @@ static HRESULT ffSaveThumbnailToTempPath( } DWORD written = 0; - BOOL writtenOk = WriteFile(file, bytes, length, &written, NULL); + BOOL writtenOk = WriteFile(file, bytes, length, &written, nullptr); NtClose(file); - file = NULL; + file = nullptr; if (!writtenOk || written != length) { DWORD writeError = GetLastError(); @@ -217,14 +217,14 @@ static const char* getMedia(FFMediaResult* result, bool saveCover) { } do { - abi_t* FF_AUTO_RELEASE_COM_OBJECT managerStatics = NULL; + FF_AUTO_RELEASE_COM_OBJECT abi_t* managerStatics = nullptr; HRESULT hr = ffGetActivationFactory(L"Windows.Media.Control.GlobalSystemMediaTransportControlsSessionManager", winrt::guid_of(), &managerStatics); if (FAILED(hr) || !managerStatics) { error = "winrt: RoGetActivationFactory(GlobalSystemMediaTransportControlsSessionManager) failed"; break; } - abi_t* FF_AUTO_RELEASE_COM_OBJECT manager = NULL; + FF_AUTO_RELEASE_COM_OBJECT abi_t* manager = nullptr; hr = ffRunAndWait([=](void** result) { return managerStatics->RequestAsync(result); }, @@ -234,11 +234,11 @@ static const char* getMedia(FFMediaResult* result, bool saveCover) { break; } - FF_A_CLEANUP(deleteHstring) HSTRING playerId = NULL; + [[gnu::cleanup(deleteHstring)]] HSTRING playerId = nullptr; - abi_t* FF_AUTO_RELEASE_COM_OBJECT session = NULL; + FF_AUTO_RELEASE_COM_OBJECT abi_t* session = nullptr; if (instance.config.general.playerName.length) { - abi_t>* FF_AUTO_RELEASE_COM_OBJECT sessions = NULL; + FF_AUTO_RELEASE_COM_OBJECT abi_t>* sessions = nullptr; hr = manager->GetSessions(reinterpret_cast(&sessions)); if (FAILED(hr) || !sessions) { error = "winrt: GetSessions() failed"; @@ -251,7 +251,7 @@ static const char* getMedia(FFMediaResult* result, bool saveCover) { break; } for (uint32_t i = 0; i < sessionCount; i++) { - abi_t* FF_AUTO_RELEASE_COM_OBJECT currentSession = NULL; + FF_AUTO_RELEASE_COM_OBJECT abi_t* currentSession = nullptr; hr = sessions->GetAt(i, reinterpret_cast(¤tSession)); if (FAILED(hr) || !currentSession) { continue; @@ -266,7 +266,7 @@ static const char* getMedia(FFMediaResult* result, bool saveCover) { if (ffStrbufContainIgnCase(&result->playerId, &instance.config.general.playerName)) { session = currentSession; - currentSession = NULL; // Don't release the session object + currentSession = nullptr; // Don't release the session object break; } deleteHstring(&playerId); @@ -294,7 +294,7 @@ static const char* getMedia(FFMediaResult* result, bool saveCover) { ffStrbufSetHstring(&result->playerId, playerId); } - abi_t* FF_AUTO_RELEASE_COM_OBJECT mediaProps = NULL; + FF_AUTO_RELEASE_COM_OBJECT abi_t* mediaProps = nullptr; hr = ffRunAndWait([=](void** result) { return session->TryGetMediaPropertiesAsync(result); }, @@ -304,7 +304,7 @@ static const char* getMedia(FFMediaResult* result, bool saveCover) { break; } - abi_t* FF_AUTO_RELEASE_COM_OBJECT playbackInfo = NULL; + FF_AUTO_RELEASE_COM_OBJECT abi_t* playbackInfo = nullptr; hr = session->GetPlaybackInfo(reinterpret_cast(&playbackInfo)); bool isPlaying = false; double playbackRate = 1.0; @@ -327,7 +327,7 @@ static const char* getMedia(FFMediaResult* result, bool saveCover) { } } - abi_t>* FF_AUTO_RELEASE_COM_OBJECT playbackRateRef = NULL; + FF_AUTO_RELEASE_COM_OBJECT abi_t>* playbackRateRef = nullptr; if (SUCCEEDED(playbackInfo->get_PlaybackRate(reinterpret_cast(&playbackRateRef))) && playbackRateRef) { if (SUCCEEDED(playbackRateRef->get_Value(&playbackRate)) && playbackRate < 0.0) { playbackRate = 0.0; @@ -335,22 +335,22 @@ static const char* getMedia(FFMediaResult* result, bool saveCover) { } } - FF_A_CLEANUP(deleteHstring) HSTRING title = NULL; + [[gnu::cleanup(deleteHstring)]] HSTRING title = nullptr; if (SUCCEEDED(mediaProps->get_Title(reinterpret_cast(&title)))) { ffStrbufSetHstring(&result->song, title); } - FF_A_CLEANUP(deleteHstring) HSTRING artist = NULL; + [[gnu::cleanup(deleteHstring)]] HSTRING artist = nullptr; if (SUCCEEDED(mediaProps->get_Artist(reinterpret_cast(&artist)))) { ffStrbufSetHstring(&result->artist, artist); } - FF_A_CLEANUP(deleteHstring) HSTRING album = NULL; + [[gnu::cleanup(deleteHstring)]] HSTRING album = nullptr; if (SUCCEEDED(mediaProps->get_AlbumTitle(reinterpret_cast(&album)))) { ffStrbufSetHstring(&result->album, album); } - abi_t* FF_AUTO_RELEASE_COM_OBJECT timelineProps = NULL; + FF_AUTO_RELEASE_COM_OBJECT abi_t* timelineProps = nullptr; hr = session->GetTimelineProperties(reinterpret_cast(&timelineProps)); if (SUCCEEDED(hr) && timelineProps) { int64_t duration = 0; @@ -373,14 +373,14 @@ static const char* getMedia(FFMediaResult* result, bool saveCover) { } } - abi_t* FF_AUTO_RELEASE_COM_OBJECT appInfoStatics = NULL; + FF_AUTO_RELEASE_COM_OBJECT abi_t* appInfoStatics = nullptr; hr = ffGetActivationFactory(L"Windows.ApplicationModel.AppInfo", winrt::guid_of(), &appInfoStatics); if (SUCCEEDED(hr) && appInfoStatics) { - abi_t* FF_AUTO_RELEASE_COM_OBJECT appInfo = NULL; + FF_AUTO_RELEASE_COM_OBJECT abi_t* appInfo = nullptr; if (SUCCEEDED(appInfoStatics->GetFromAppUserModelId(reinterpret_cast(playerId), reinterpret_cast(&appInfo))) && appInfo) { - abi_t* FF_AUTO_RELEASE_COM_OBJECT displayInfo = NULL; + FF_AUTO_RELEASE_COM_OBJECT abi_t* displayInfo = nullptr; if (SUCCEEDED(appInfo->get_DisplayInfo(reinterpret_cast(&displayInfo))) && displayInfo) { - FF_A_CLEANUP(deleteHstring) HSTRING displayName = NULL; + [[gnu::cleanup(deleteHstring)]] HSTRING displayName = nullptr; if (SUCCEEDED(displayInfo->get_DisplayName(reinterpret_cast(&displayName)))) { ffStrbufSetHstring(&result->player, displayName); } @@ -396,7 +396,7 @@ static const char* getMedia(FFMediaResult* result, bool saveCover) { } if (saveCover) { - abi_t* FF_AUTO_RELEASE_COM_OBJECT thumbnail = NULL; + FF_AUTO_RELEASE_COM_OBJECT abi_t* thumbnail = nullptr; hr = mediaProps->get_Thumbnail(reinterpret_cast(&thumbnail)); if (SUCCEEDED(hr) && thumbnail) { if (SUCCEEDED(ffSaveThumbnailToTempPath(thumbnail, &result->cover)) && result->cover.length > 0) { diff --git a/src/detection/memory/memory_apple.c b/src/detection/memory/memory_apple.c index 62039493ec..b4f9264678 100644 --- a/src/detection/memory/memory_apple.c +++ b/src/detection/memory/memory_apple.c @@ -10,11 +10,11 @@ const char* ffDetectMemory(FFMemoryResult* ram) { size_t length = sizeof(ram->bytesTotal); #if FF_APPLE_MEMSIZE_USABLE - if (sysctlbyname("hw.memsize_usable", &ram->bytesTotal, &length, NULL, 0) != 0) { + if (sysctlbyname("hw.memsize_usable", &ram->bytesTotal, &length, nullptr, 0) != 0) { return "Failed to read hw.memsize_usable"; } #else - if (sysctl((int[]) { CTL_HW, HW_MEMSIZE }, 2, &ram->bytesTotal, &length, NULL, 0) != 0) { + if (sysctl((int[]) { CTL_HW, HW_MEMSIZE }, 2, &ram->bytesTotal, &length, nullptr, 0) != 0) { return "Failed to read hw.memsize"; } #endif @@ -31,5 +31,5 @@ const char* ffDetectMemory(FFMemoryResult* ram) { uint64_t pagesFileBacked = vmstat.external_page_count; // Cached files ram->bytesUsed = ram->bytesTotal - (pagesFree + pagesFileBacked) * instance.state.platform.sysinfo.pageSize; - return NULL; + return nullptr; } diff --git a/src/detection/memory/memory_bsd.c b/src/detection/memory/memory_bsd.c index 6deadd6358..48f2948c31 100644 --- a/src/detection/memory/memory_bsd.c +++ b/src/detection/memory/memory_bsd.c @@ -3,7 +3,7 @@ const char* ffDetectMemory(FFMemoryResult* ram) { size_t length = sizeof(ram->bytesTotal); - if (sysctl((int[]) { CTL_HW, HW_PHYSMEM }, 2, &ram->bytesTotal, &length, NULL, 0)) { + if (sysctl((int[]) { CTL_HW, HW_PHYSMEM }, 2, &ram->bytesTotal, &length, nullptr, 0)) { return "Failed to read hw.physmem"; } @@ -19,5 +19,5 @@ const char* ffDetectMemory(FFMemoryResult* ram) { ram->bytesUsed -= (uint64_t) bytesArc; } - return NULL; + return nullptr; } diff --git a/src/detection/memory/memory_haiku.c b/src/detection/memory/memory_haiku.c index 7888801ce0..9bec865eb4 100644 --- a/src/detection/memory/memory_haiku.c +++ b/src/detection/memory/memory_haiku.c @@ -12,5 +12,5 @@ const char* ffDetectMemory(FFMemoryResult* ram) { ram->bytesTotal = pageSize * info.max_pages; ram->bytesUsed = pageSize * info.used_pages; - return NULL; + return nullptr; } diff --git a/src/detection/memory/memory_linux.c b/src/detection/memory/memory_linux.c index cd2c8989e1..0a2ebd3fb1 100644 --- a/src/detection/memory/memory_linux.c +++ b/src/detection/memory/memory_linux.c @@ -17,36 +17,36 @@ const char* ffDetectMemory(FFMemoryResult* ram) { cached = 0, sReclaimable = 0; - char* token = NULL; - if ((token = memmem(buf, (size_t) nRead, "MemTotal:", strlen("MemTotal:"))) != NULL) { - memTotal = (uint64_t) strtoull(token + strlen("MemTotal:"), NULL, 10); + char* token = nullptr; + if ((token = memmem(buf, (size_t) nRead, "MemTotal:", strlen("MemTotal:"))) != nullptr) { + memTotal = (uint64_t) strtoull(token + strlen("MemTotal:"), nullptr, 10); } else { return "MemTotal not found in /proc/meminfo"; } - if ((token = memmem(buf, (size_t) nRead, "MemAvailable:", strlen("MemAvailable:"))) != NULL) { - memAvailable = (uint64_t) strtoull(token + strlen("MemAvailable:"), NULL, 10); + if ((token = memmem(buf, (size_t) nRead, "MemAvailable:", strlen("MemAvailable:"))) != nullptr) { + memAvailable = (uint64_t) strtoull(token + strlen("MemAvailable:"), nullptr, 10); } if (memAvailable == 0 || memAvailable >= memTotal) { // MemAvailable can be unreasonable. #1988 - if ((token = memmem(buf, (size_t) nRead, "MemFree:", strlen("MemFree:"))) != NULL) { - memFree = (uint64_t) strtoull(token + strlen("MemFree:"), NULL, 10); + if ((token = memmem(buf, (size_t) nRead, "MemFree:", strlen("MemFree:"))) != nullptr) { + memFree = (uint64_t) strtoull(token + strlen("MemFree:"), nullptr, 10); } - if ((token = memmem(buf, (size_t) nRead, "Buffers:", strlen("Buffers:"))) != NULL) { - buffers = (uint64_t) strtoull(token + strlen("Buffers:"), NULL, 10); + if ((token = memmem(buf, (size_t) nRead, "Buffers:", strlen("Buffers:"))) != nullptr) { + buffers = (uint64_t) strtoull(token + strlen("Buffers:"), nullptr, 10); } - if ((token = memmem(buf, (size_t) nRead, "Cached:", strlen("Cached:"))) != NULL) { - cached = (uint64_t) strtoull(token + strlen("Cached:"), NULL, 10); + if ((token = memmem(buf, (size_t) nRead, "Cached:", strlen("Cached:"))) != nullptr) { + cached = (uint64_t) strtoull(token + strlen("Cached:"), nullptr, 10); } - if ((token = memmem(buf, (size_t) nRead, "Shmem:", strlen("Shmem:"))) != NULL) { - shmem = (uint64_t) strtoull(token + strlen("Shmem:"), NULL, 10); + if ((token = memmem(buf, (size_t) nRead, "Shmem:", strlen("Shmem:"))) != nullptr) { + shmem = (uint64_t) strtoull(token + strlen("Shmem:"), nullptr, 10); } - if ((token = memmem(buf, (size_t) nRead, "SReclaimable:", strlen("SReclaimable:"))) != NULL) { - sReclaimable = (uint64_t) strtoull(token + strlen("SReclaimable:"), NULL, 10); + if ((token = memmem(buf, (size_t) nRead, "SReclaimable:", strlen("SReclaimable:"))) != nullptr) { + sReclaimable = (uint64_t) strtoull(token + strlen("SReclaimable:"), nullptr, 10); } memAvailable = memFree + buffers + cached + sReclaimable - shmem; @@ -65,25 +65,25 @@ const char* ffDetectMemory(FFMemoryResult* ram) { // Skip first line const char* p = memchr(buf, '\n', (size_t) nRead); - if (__builtin_expect(p != NULL, true)) { + if (__builtin_expect(p != nullptr, true)) { ++p; nRead -= (p - buf); assert(nRead > 0); // Find line offset of data const char* pData = memmem(p, (size_t) nRead, "data\n", strlen("data\n")); - if (__builtin_expect(pData != NULL, true)) { + if (__builtin_expect(pData != nullptr, true)) { uint32_t dataOffset = (uint32_t) (pData - p); p += dataOffset + strlen("data\n"); nRead -= (ssize_t) (dataOffset + strlen("data\n")); assert(nRead > 0); - if ((token = memmem(p, (size_t) nRead, "\nsize ", strlen("\nsize "))) != NULL) { - arcSize = (uint64_t) strtoull(token + 1 + dataOffset, NULL, 10); + if ((token = memmem(p, (size_t) nRead, "\nsize ", strlen("\nsize "))) != nullptr) { + arcSize = (uint64_t) strtoull(token + 1 + dataOffset, nullptr, 10); if (arcSize > 0) { uint64_t arcMin = 0; - if ((token = memmem(p, (size_t) nRead, "\nc_min ", strlen("\nc_min "))) != NULL) { - arcMin = (uint64_t) strtoull(token + 1 + dataOffset, NULL, 10); + if ((token = memmem(p, (size_t) nRead, "\nc_min ", strlen("\nc_min "))) != nullptr) { + arcMin = (uint64_t) strtoull(token + 1 + dataOffset, nullptr, 10); if (arcSize > arcMin) { arcSize -= arcMin; if (ram->bytesUsed > arcSize) { @@ -97,5 +97,5 @@ const char* ffDetectMemory(FFMemoryResult* ram) { } } - return NULL; + return nullptr; } diff --git a/src/detection/memory/memory_nbsd.c b/src/detection/memory/memory_nbsd.c index f7330ea316..5aa9353cfc 100644 --- a/src/detection/memory/memory_nbsd.c +++ b/src/detection/memory/memory_nbsd.c @@ -7,7 +7,7 @@ const char* ffDetectMemory(FFMemoryResult* ram) { struct uvmexp_sysctl buf; size_t length = sizeof(buf); - if (sysctl((int[]) { CTL_VM, VM_UVMEXP2 }, 2, &buf, &length, NULL, 0) < 0) { + if (sysctl((int[]) { CTL_VM, VM_UVMEXP2 }, 2, &buf, &length, nullptr, 0) < 0) { return "sysctl(CTL_VM, VM_UVMEXP2) failed"; } @@ -20,5 +20,5 @@ const char* ffDetectMemory(FFMemoryResult* ram) { ram->bytesUsed -= (uint64_t) bytesArc; } - return NULL; + return nullptr; } diff --git a/src/detection/memory/memory_nosupport.c b/src/detection/memory/memory_nosupport.c index b44aaadff8..6c11799a30 100644 --- a/src/detection/memory/memory_nosupport.c +++ b/src/detection/memory/memory_nosupport.c @@ -1,5 +1,5 @@ #include "memory.h" -const char* ffDetectMemory(FF_A_UNUSED FFMemoryResult* ram) { +const char* ffDetectMemory([[maybe_unused]] FFMemoryResult* ram) { return "Not supported on this platform"; } diff --git a/src/detection/memory/memory_obsd.c b/src/detection/memory/memory_obsd.c index c6da0877e4..f53aeefdcf 100644 --- a/src/detection/memory/memory_obsd.c +++ b/src/detection/memory/memory_obsd.c @@ -7,12 +7,12 @@ const char* ffDetectMemory(FFMemoryResult* ram) { struct uvmexp buf; size_t length = sizeof(buf); - if (sysctl((int[]) { CTL_VM, VM_UVMEXP }, 2, &buf, &length, NULL, 0) < 0) { + if (sysctl((int[]) { CTL_VM, VM_UVMEXP }, 2, &buf, &length, nullptr, 0) < 0) { return "sysctl(CTL_VM, VM_UVMEXP) failed"; } ram->bytesTotal = (uint64_t) buf.npages * instance.state.platform.sysinfo.pageSize; ram->bytesUsed = ((uint64_t) buf.active + (uint64_t) buf.inactive + (uint64_t) buf.wired) * instance.state.platform.sysinfo.pageSize; - return NULL; + return nullptr; } diff --git a/src/detection/memory/memory_sunos.c b/src/detection/memory/memory_sunos.c index 844ce9e241..f61060b3ca 100644 --- a/src/detection/memory/memory_sunos.c +++ b/src/detection/memory/memory_sunos.c @@ -15,14 +15,14 @@ const char* ffDetectMemory(FFMemoryResult* ram) { ram->bytesTotal = (uint64_t) sysconf(_SC_PHYS_PAGES) * pageSize; ram->bytesUsed = ram->bytesTotal - (uint64_t) sysconf(_SC_AVPHYS_PAGES) * pageSize; - FF_A_CLEANUP(kstatFreeWrap) kstat_ctl_t* kc = kstat_open(); - if (kc != NULL) { + [[gnu::cleanup(kstatFreeWrap)]] kstat_ctl_t* kc = kstat_open(); + if (kc != nullptr) { kstat_t* ksp = kstat_lookup(kc, "zfs", -1, "arcstats"); - if (ksp != NULL && kstat_read(kc, ksp, NULL) != -1) { + if (ksp != nullptr && kstat_read(kc, ksp, nullptr) != -1) { kstat_named_t* kn_size = (kstat_named_t*) kstat_data_lookup(ksp, "size"); kstat_named_t* kn_cmin = (kstat_named_t*) kstat_data_lookup(ksp, "c_min"); - if (kn_size != NULL && kn_cmin != NULL && + if (kn_size != nullptr && kn_cmin != nullptr && kn_size->data_type == KSTAT_DATA_UINT64 && kn_cmin->data_type == KSTAT_DATA_UINT64) { uint64_t arcSize = kn_size->value.ui64; @@ -39,5 +39,5 @@ const char* ffDetectMemory(FFMemoryResult* ram) { } } - return NULL; + return nullptr; } diff --git a/src/detection/memory/memory_windows.c b/src/detection/memory/memory_windows.c index 779425d559..da689621d2 100644 --- a/src/detection/memory/memory_windows.c +++ b/src/detection/memory/memory_windows.c @@ -15,5 +15,5 @@ const char* ffDetectMemory(FFMemoryResult* ram) { ram->bytesTotal = statex.ullTotalPhys; ram->bytesUsed = statex.ullTotalPhys - statex.ullAvailPhys; - return NULL; + return nullptr; } diff --git a/src/detection/mouse/mouse_apple.c b/src/detection/mouse/mouse_apple.c index 2c5b2d7e3c..7f0b96cd0b 100644 --- a/src/detection/mouse/mouse_apple.c +++ b/src/detection/mouse/mouse_apple.c @@ -18,19 +18,19 @@ static void enumSet(IOHIDDeviceRef value, FFlist* results) { } const char* ffDetectMouse(FFlist* devices /* List of FFMouseDevice */) { - IOHIDManagerRef FF_CFTYPE_AUTO_RELEASE manager = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone); + FF_CFTYPE_AUTO_RELEASE IOHIDManagerRef manager = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone); if (IOHIDManagerOpen(manager, kIOHIDOptionsTypeNone) != kIOReturnSuccess) { return "IOHIDManagerOpen() failed"; } - CFDictionaryRef FF_CFTYPE_AUTO_RELEASE matching1 = CFDictionaryCreate(kCFAllocatorDefault, (const void**) (CFStringRef[]) { CFSTR(kIOHIDDeviceUsagePageKey), CFSTR(kIOHIDDeviceUsageKey) }, (const void**) (CFNumberRef[]) { ffCfCreateInt(kHIDPage_GenericDesktop), ffCfCreateInt(kHIDUsage_GD_Mouse) }, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); + FF_CFTYPE_AUTO_RELEASE CFDictionaryRef matching1 = CFDictionaryCreate(kCFAllocatorDefault, (const void**) (CFStringRef[]) { CFSTR(kIOHIDDeviceUsagePageKey), CFSTR(kIOHIDDeviceUsageKey) }, (const void**) (CFNumberRef[]) { ffCfCreateInt(kHIDPage_GenericDesktop), ffCfCreateInt(kHIDUsage_GD_Mouse) }, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); IOHIDManagerSetDeviceMatching(manager, matching1); - CFSetRef FF_CFTYPE_AUTO_RELEASE set = IOHIDManagerCopyDevices(manager); + FF_CFTYPE_AUTO_RELEASE CFSetRef set = IOHIDManagerCopyDevices(manager); if (set) { CFSetApplyFunction(set, (CFSetApplierFunction) &enumSet, devices); } IOHIDManagerClose(manager, kIOHIDOptionsTypeNone); - return NULL; + return nullptr; } diff --git a/src/detection/mouse/mouse_bsd.c b/src/detection/mouse/mouse_bsd.c index da7783b0b5..065fda2be5 100644 --- a/src/detection/mouse/mouse_bsd.c +++ b/src/detection/mouse/mouse_bsd.c @@ -52,5 +52,5 @@ const char* ffDetectMouse(FFlist* devices /* List of FFMouseDevice */) { hid_dispose_report_desc(repDesc); } - return NULL; + return nullptr; } diff --git a/src/detection/mouse/mouse_haiku.cpp b/src/detection/mouse/mouse_haiku.cpp index 5835c8ec24..70a4533c36 100644 --- a/src/detection/mouse/mouse_haiku.cpp +++ b/src/detection/mouse/mouse_haiku.cpp @@ -23,5 +23,5 @@ const char* ffDetectMouse(FFlist* devices /* List of FFMouseDevice */) { ffStrbufInitS(&item->name, device->Name()); } - return NULL; + return nullptr; } diff --git a/src/detection/mouse/mouse_linux.c b/src/detection/mouse/mouse_linux.c index 939c332a12..4c66fc513e 100644 --- a/src/detection/mouse/mouse_linux.c +++ b/src/detection/mouse/mouse_linux.c @@ -4,15 +4,15 @@ const char* ffDetectMouse(FFlist* devices /* List of FFMouseDevice */) { FF_AUTO_CLOSE_DIR DIR* dirp = opendir("/sys/class/input/"); - if (dirp == NULL) { - return "opendir(\"/sys/class/input/\") == NULL"; + if (dirp == nullptr) { + return "opendir(\"/sys/class/input/\") == nullptr"; } FF_STRBUF_AUTO_DESTROY path = ffStrbufCreateS("/sys/class/input/"); uint32_t baseLen = path.length; struct dirent* entry; - while ((entry = readdir(dirp)) != NULL) { + while ((entry = readdir(dirp)) != nullptr) { if (!ffStrStartsWith(entry->d_name, "mouse")) { continue; } @@ -41,5 +41,5 @@ const char* ffDetectMouse(FFlist* devices /* List of FFMouseDevice */) { ffStrbufSubstrBefore(&path, baseLen); } - return NULL; + return nullptr; } diff --git a/src/detection/mouse/mouse_nosupport.c b/src/detection/mouse/mouse_nosupport.c index aa1332df43..a3b37e3473 100644 --- a/src/detection/mouse/mouse_nosupport.c +++ b/src/detection/mouse/mouse_nosupport.c @@ -1,5 +1,5 @@ #include "mouse.h" -const char* ffDetectMouse(FF_A_UNUSED FFlist* devices /* List of FFMouseDevice */) { +const char* ffDetectMouse([[maybe_unused]] FFlist* devices /* List of FFMouseDevice */) { return "No mouse support on this platform"; } diff --git a/src/detection/mouse/mouse_windows.c b/src/detection/mouse/mouse_windows.c index 3f2370a9a5..d600281828 100644 --- a/src/detection/mouse/mouse_windows.c +++ b/src/detection/mouse/mouse_windows.c @@ -12,13 +12,13 @@ const char* ffDetectMouse(FFlist* devices /* List of FFMouseDevice */) { UINT nDevices = 0; - if (GetRawInputDeviceList(NULL, &nDevices, sizeof(RAWINPUTDEVICELIST))) { - return "GetRawInputDeviceList(NULL) failed"; + if (GetRawInputDeviceList(nullptr, &nDevices, sizeof(RAWINPUTDEVICELIST))) { + return "GetRawInputDeviceList(nullptr) failed"; } if (nDevices == 0) { return "No HID devices found"; } - RAWINPUTDEVICELIST* FF_AUTO_FREE pRawInputDeviceList = (RAWINPUTDEVICELIST*) malloc(sizeof(RAWINPUTDEVICELIST) * nDevices); + FF_AUTO_FREE RAWINPUTDEVICELIST* pRawInputDeviceList = (RAWINPUTDEVICELIST*) malloc(sizeof(RAWINPUTDEVICELIST) * nDevices); if ((nDevices = GetRawInputDeviceList(pRawInputDeviceList, &nDevices, sizeof(RAWINPUTDEVICELIST))) == (UINT) -1) { return "GetRawInputDeviceList(pRawInputDeviceList) failed"; } @@ -48,7 +48,7 @@ const char* ffDetectMouse(FFlist* devices /* List of FFMouseDevice */) { wchar_t buffer[MAX_PATH]; - HANDLE FF_AUTO_CLOSE_FD hHidFile = CreateFileW(devName, 0 /* must be 0 instead of GENERIC_READ */, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); + FF_AUTO_CLOSE_FD HANDLE hHidFile = CreateFileW(devName, 0 /* must be 0 instead of GENERIC_READ */, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); if (hHidFile != INVALID_HANDLE_VALUE) { if (HidD_GetProductString(hHidFile, buffer, (ULONG) sizeof(buffer))) { ffStrbufSetWS(&device->name, buffer); @@ -80,5 +80,5 @@ const char* ffDetectMouse(FFlist* devices /* List of FFMouseDevice */) { } } - return NULL; + return nullptr; } diff --git a/src/detection/netio/netio.c b/src/detection/netio/netio.c index c6b9da61b2..a6348265bb 100644 --- a/src/detection/netio/netio.c +++ b/src/detection/netio/netio.c @@ -20,14 +20,14 @@ void ffPrepareNetIO(FFNetIOOptions* options) { } const char* ffDetectNetIO(FFlist* result, FFNetIOOptions* options) { - const char* error = NULL; + const char* error = nullptr; if (options->detectTotal) { error = ffNetIOGetIoCounters(result, options); if (error) { return error; } - return NULL; + return nullptr; } if (time1 == 0) { @@ -77,5 +77,5 @@ const char* ffDetectNetIO(FFlist* result, FFNetIOOptions* options) { } time1 = time2; - return NULL; + return nullptr; } diff --git a/src/detection/netio/netio_apple.c b/src/detection/netio/netio_apple.c index 125cfd90c6..1ab2c5774e 100644 --- a/src/detection/netio/netio_apple.c +++ b/src/detection/netio/netio_apple.c @@ -11,8 +11,8 @@ const char* ffNetIOGetIoCounters(FFlist* result, FFNetIOOptions* options) { int mib[] = { CTL_NET, PF_LINK, NETLINK_GENERIC, options->defaultRouteOnly ? IFMIB_IFDATA : IFMIB_IFALLDATA, options->defaultRouteOnly ? (int) ffNetifGetDefaultRouteV4()->ifIndex : 0, IFDATA_GENERAL }; size_t bufSize = 0; - if (sysctl(mib, ARRAY_SIZE(mib), NULL, &bufSize, 0, 0) < 0) { - return "sysctl(mib, ARRAY_SIZE(mib), NULL, &bufSize, 0, 0) failed"; + if (sysctl(mib, ARRAY_SIZE(mib), nullptr, &bufSize, 0, 0) < 0) { + return "sysctl(mib, ARRAY_SIZE(mib), nullptr, &bufSize, 0, 0) failed"; } assert(bufSize % sizeof(struct ifmibdata) == 0); @@ -51,5 +51,5 @@ const char* ffNetIOGetIoCounters(FFlist* result, FFNetIOOptions* options) { }; } - return NULL; + return nullptr; } diff --git a/src/detection/netio/netio_bsd.c b/src/detection/netio/netio_bsd.c index 83c1b6ba01..2641dd2493 100644 --- a/src/detection/netio/netio_bsd.c +++ b/src/detection/netio/netio_bsd.c @@ -14,8 +14,8 @@ const char* ffNetIOGetIoCounters(FFlist* result, FFNetIOOptions* options) { uint32_t defaultRouteIfIndex = ffNetifGetDefaultRouteV4()->ifIndex; size_t bufSize = 0; - if (sysctl((int[]) { CTL_NET, PF_ROUTE, 0, 0, NET_RT_IFLIST, (options->defaultRouteOnly ? (int) defaultRouteIfIndex : 0) }, 6, NULL, &bufSize, 0, 0) < 0) { - return "sysctl({ CTL_NET, PF_ROUTE, 0, 0, NET_RT_IFLIST, ifIndex }, 6, NULL, &bufSize, 0, 0) failed"; + if (sysctl((int[]) { CTL_NET, PF_ROUTE, 0, 0, NET_RT_IFLIST, (options->defaultRouteOnly ? (int) defaultRouteIfIndex : 0) }, 6, nullptr, &bufSize, 0, 0) < 0) { + return "sysctl({ CTL_NET, PF_ROUTE, 0, 0, NET_RT_IFLIST, ifIndex }, 6, nullptr, &bufSize, 0, 0) failed"; } FF_AUTO_FREE struct if_msghdr* buf = (struct if_msghdr*) malloc(bufSize); @@ -58,5 +58,5 @@ const char* ffNetIOGetIoCounters(FFlist* result, FFNetIOOptions* options) { }; } - return NULL; + return nullptr; } diff --git a/src/detection/netio/netio_haiku.cpp b/src/detection/netio/netio_haiku.cpp index 88a123d1d4..6ab15e342b 100644 --- a/src/detection/netio/netio_haiku.cpp +++ b/src/detection/netio/netio_haiku.cpp @@ -48,5 +48,5 @@ const char* ffNetIOGetIoCounters(FFlist* result, FFNetIOOptions* options) { }; } - return NULL; + return nullptr; } diff --git a/src/detection/netio/netio_linux.c b/src/detection/netio/netio_linux.c index 5870d3f439..4e5c8d61b7 100644 --- a/src/detection/netio/netio_linux.c +++ b/src/detection/netio/netio_linux.c @@ -58,7 +58,7 @@ static void getData(FFstrbuf* buffer, const char* ifName, bool isDefaultRoute, i const char* ffNetIOGetIoCounters(FFlist* result, FFNetIOOptions* options) { FF_AUTO_CLOSE_DIR DIR* dirp = opendir("/sys/class/net"); if (!dirp) { - return "opendir(\"/sys/class/net\") == NULL"; + return "opendir(\"/sys/class/net\") == nullptr"; } FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); @@ -67,13 +67,13 @@ const char* ffNetIOGetIoCounters(FFlist* result, FFNetIOOptions* options) { if (options->defaultRouteOnly) { if (options->namePrefix.length && strncmp(defaultRouteIfName, options->namePrefix.chars, options->namePrefix.length) != 0) { - return NULL; + return nullptr; } getData(&buffer, defaultRouteIfName, true, dirfd(dirp), result); } else { struct dirent* entry; - while ((entry = readdir(dirp)) != NULL) { + while ((entry = readdir(dirp)) != nullptr) { const char* ifName = entry->d_name; if (ifName[0] == '.') { continue; @@ -87,5 +87,5 @@ const char* ffNetIOGetIoCounters(FFlist* result, FFNetIOOptions* options) { } } - return NULL; + return nullptr; } diff --git a/src/detection/netio/netio_nosupport.c b/src/detection/netio/netio_nosupport.c index 30f73a7583..4b35bc0b58 100644 --- a/src/detection/netio/netio_nosupport.c +++ b/src/detection/netio/netio_nosupport.c @@ -1,5 +1,5 @@ #include "netio.h" -const char* ffNetIOGetIoCounters(FF_A_UNUSED FFlist* result, FF_A_UNUSED FFNetIOOptions* options) { +const char* ffNetIOGetIoCounters([[maybe_unused]] FFlist* result, [[maybe_unused]] FFNetIOOptions* options) { return "Not supported on this platform"; } diff --git a/src/detection/netio/netio_sunos.c b/src/detection/netio/netio_sunos.c index 3789e4528e..2b9a020387 100644 --- a/src/detection/netio/netio_sunos.c +++ b/src/detection/netio/netio_sunos.c @@ -12,7 +12,7 @@ static inline void kstatFreeWrap(kstat_ctl_t** pkc) { } const char* ffNetIOGetIoCounters(FFlist* result, FFNetIOOptions* options) { - FF_A_CLEANUP(kstatFreeWrap) kstat_ctl_t* kc = kstat_open(); + [[gnu::cleanup(kstatFreeWrap)]] kstat_ctl_t* kc = kstat_open(); if (!kc) { return "kstat_open() failed"; } @@ -33,7 +33,7 @@ const char* ffNetIOGetIoCounters(FFlist* result, FFNetIOOptions* options) { continue; } - if (kstat_read(kc, ks, NULL) < 0) { + if (kstat_read(kc, ks, nullptr) < 0) { continue; } @@ -64,5 +64,5 @@ const char* ffNetIOGetIoCounters(FFlist* result, FFNetIOOptions* options) { } } - return NULL; + return nullptr; } diff --git a/src/detection/netio/netio_windows.c b/src/detection/netio/netio_windows.c index 3c6433425a..4c3f87b3ea 100644 --- a/src/detection/netio/netio_windows.c +++ b/src/detection/netio/netio_windows.c @@ -8,7 +8,7 @@ #include const char* ffNetIOGetIoCounters(FFlist* result, FFNetIOOptions* options) { - IP_ADAPTER_ADDRESSES* FF_AUTO_FREE adapter_addresses = NULL; + FF_AUTO_FREE IP_ADAPTER_ADDRESSES* adapter_addresses = nullptr; // Multiple attempts in case interfaces change while // we are in the middle of querying them. @@ -22,7 +22,7 @@ const char* ffNetIOGetIoCounters(FFlist* result, FFNetIOOptions* options) { DWORD error = GetAdaptersAddresses( AF_UNSPEC, GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER, - NULL, + nullptr, adapter_addresses, &adapter_addresses_buffer_size); @@ -67,5 +67,5 @@ const char* ffNetIOGetIoCounters(FFlist* result, FFNetIOOptions* options) { } } - return NULL; + return nullptr; } diff --git a/src/detection/opencl/opencl.c b/src/detection/opencl/opencl.c index 74f8f6144d..5bb195ec35 100644 --- a/src/detection/opencl/opencl.c +++ b/src/detection/opencl/opencl.c @@ -53,7 +53,7 @@ static const char* openCLHandleData(OpenCLData* data, FFOpenCLResult* result) { char buffer[1024]; for (cl_uint iplat = 0; iplat < numPlatforms; ++iplat) { - if (data->ffclGetPlatformInfo(platforms[iplat], CL_PLATFORM_VERSION, sizeof(buffer), buffer, NULL) != CL_SUCCESS) { + if (data->ffclGetPlatformInfo(platforms[iplat], CL_PLATFORM_VERSION, sizeof(buffer), buffer, nullptr) != CL_SUCCESS) { return "clGetPlatformInfo() failed"; } @@ -66,11 +66,11 @@ static const char* openCLHandleData(OpenCLData* data, FFOpenCLResult* result) { ffStrbufSetS(&result->version, versionPretty); ffStrbufTrim(&result->version, ' '); - if (data->ffclGetPlatformInfo(platforms[iplat], CL_PLATFORM_NAME, sizeof(buffer), buffer, NULL) == CL_SUCCESS) { + if (data->ffclGetPlatformInfo(platforms[iplat], CL_PLATFORM_NAME, sizeof(buffer), buffer, nullptr) == CL_SUCCESS) { ffStrbufSetS(&result->name, buffer); } - if (data->ffclGetPlatformInfo(platforms[iplat], CL_PLATFORM_VENDOR, sizeof(buffer), buffer, NULL) == CL_SUCCESS) { + if (data->ffclGetPlatformInfo(platforms[iplat], CL_PLATFORM_VENDOR, sizeof(buffer), buffer, nullptr) == CL_SUCCESS) { ffStrbufSetS(&result->vendor, buffer); } } @@ -83,7 +83,7 @@ static const char* openCLHandleData(OpenCLData* data, FFOpenCLResult* result) { for (cl_uint idev = 0; idev < numDevices; ++idev) { cl_device_id deviceID = deviceIDs[idev]; - if (data->ffclGetDeviceInfo(deviceID, CL_DEVICE_NAME, sizeof(buffer), buffer, NULL) != CL_SUCCESS) { + if (data->ffclGetDeviceInfo(deviceID, CL_DEVICE_NAME, sizeof(buffer), buffer, nullptr) != CL_SUCCESS) { continue; } @@ -103,7 +103,7 @@ static const char* openCLHandleData(OpenCLData* data, FFOpenCLResult* result) { gpu->coreUsage = FF_GPU_CORE_USAGE_UNSET; gpu->pcieSpeed = FF_GPU_PCIE_SPEED_UNSET; - if (data->ffclGetDeviceInfo(deviceID, CL_DEVICE_VERSION, sizeof(buffer), buffer, NULL) == CL_SUCCESS) { + if (data->ffclGetDeviceInfo(deviceID, CL_DEVICE_VERSION, sizeof(buffer), buffer, nullptr) == CL_SUCCESS) { ffStrbufSetS(&gpu->platformApi, buffer); ffStrbufTrimRight(&gpu->platformApi, ' '); } else { @@ -112,15 +112,15 @@ static const char* openCLHandleData(OpenCLData* data, FFOpenCLResult* result) { { cl_uint vendorId; - if (data->ffclGetDeviceInfo(deviceID, CL_DEVICE_VENDOR_ID, sizeof(vendorId), &vendorId, NULL) == CL_SUCCESS) { + if (data->ffclGetDeviceInfo(deviceID, CL_DEVICE_VENDOR_ID, sizeof(vendorId), &vendorId, nullptr) == CL_SUCCESS) { ffStrbufSetStatic(&gpu->vendor, ffGPUGetVendorString(vendorId)); } - if (gpu->vendor.length == 0 && data->ffclGetDeviceInfo(deviceID, CL_DEVICE_VENDOR, sizeof(buffer), buffer, NULL) == CL_SUCCESS) { + if (gpu->vendor.length == 0 && data->ffclGetDeviceInfo(deviceID, CL_DEVICE_VENDOR, sizeof(buffer), buffer, nullptr) == CL_SUCCESS) { ffStrbufSetS(&gpu->vendor, buffer); } } - if (data->ffclGetDeviceInfo(deviceID, CL_DRIVER_VERSION, sizeof(buffer), buffer, NULL) == CL_SUCCESS) { + if (data->ffclGetDeviceInfo(deviceID, CL_DRIVER_VERSION, sizeof(buffer), buffer, nullptr) == CL_SUCCESS) { const char* versionPretty = strchr(buffer, ' '); if (versionPretty && *versionPretty) { ffStrbufSetS(&gpu->driver, versionPretty + 1); @@ -131,25 +131,25 @@ static const char* openCLHandleData(OpenCLData* data, FFOpenCLResult* result) { { cl_uint value; - if (data->ffclGetDeviceInfo(deviceID, CL_DEVICE_MAX_COMPUTE_UNITS, sizeof(value), &value, NULL) == CL_SUCCESS) { + if (data->ffclGetDeviceInfo(deviceID, CL_DEVICE_MAX_COMPUTE_UNITS, sizeof(value), &value, nullptr) == CL_SUCCESS) { gpu->coreCount = (int32_t) value; } } { cl_uint value; - if (data->ffclGetDeviceInfo(deviceID, CL_DEVICE_MAX_CLOCK_FREQUENCY, sizeof(value), &value, NULL) == CL_SUCCESS) { + if (data->ffclGetDeviceInfo(deviceID, CL_DEVICE_MAX_CLOCK_FREQUENCY, sizeof(value), &value, nullptr) == CL_SUCCESS) { gpu->frequency = value; } } { cl_bool value; - if (data->ffclGetDeviceInfo(deviceID, CL_DEVICE_HOST_UNIFIED_MEMORY, sizeof(value), &value, NULL) == CL_SUCCESS) { + if (data->ffclGetDeviceInfo(deviceID, CL_DEVICE_HOST_UNIFIED_MEMORY, sizeof(value), &value, nullptr) == CL_SUCCESS) { gpu->type = value ? FF_GPU_TYPE_INTEGRATED : FF_GPU_TYPE_DISCRETE; cl_ulong memSize; - if (data->ffclGetDeviceInfo(deviceID, CL_DEVICE_GLOBAL_MEM_SIZE, sizeof(memSize), &memSize, NULL) == CL_SUCCESS) { + if (data->ffclGetDeviceInfo(deviceID, CL_DEVICE_GLOBAL_MEM_SIZE, sizeof(memSize), &memSize, nullptr) == CL_SUCCESS) { if (gpu->type == FF_GPU_TYPE_INTEGRATED) { gpu->shared.total = memSize; } else { @@ -161,7 +161,7 @@ static const char* openCLHandleData(OpenCLData* data, FFOpenCLResult* result) { } } - return NULL; + return nullptr; } static const char* detectOpenCL(FFOpenCLResult* result) { diff --git a/src/detection/opengl/opengl_apple.c b/src/detection/opengl/opengl_apple.c index 91285938d1..d29ae284a4 100644 --- a/src/detection/opengl/opengl_apple.c +++ b/src/detection/opengl/opengl_apple.c @@ -6,7 +6,7 @@ #include #include // This brings in CGL, not GL -void ffOpenGLHandleResult(FFOpenGLResult* result, __typeof__(&glGetString) ffglGetString); +void ffOpenGLHandleResult(FFOpenGLResult* result, typeof(&glGetString) ffglGetString); static const char* cglHandleContext(FFOpenGLResult* result, CGLContextObj context) { if (CGLSetCurrentContext(context) != kCGLNoError) { @@ -19,13 +19,13 @@ static const char* cglHandleContext(FFOpenGLResult* result, CGLContextObj contex CGLGetVersion(&major, &minor); ffStrbufSetF(&result->library, "CGL %d.%d", major, minor); - return NULL; + return nullptr; } static const char* cglHandlePixelFormat(FFOpenGLResult* result, CGLPixelFormatObj pixelFormat) { CGLContextObj context; - if (CGLCreateContext(pixelFormat, NULL, &context) != kCGLNoError) { + if (CGLCreateContext(pixelFormat, nullptr, &context) != kCGLNoError) { return "CGLCreateContext() failed"; } diff --git a/src/detection/opengl/opengl_haiku.cpp b/src/detection/opengl/opengl_haiku.cpp index 64a21a0d59..47d55500eb 100644 --- a/src/detection/opengl/opengl_haiku.cpp +++ b/src/detection/opengl/opengl_haiku.cpp @@ -6,7 +6,7 @@ extern "C" { #if FF_HAVE_EGL const char* ffOpenGLDetectByEGL(FFOpenGLResult* result); #endif -void ffOpenGLHandleResult(FFOpenGLResult* result, __typeof__(&glGetString) ffglGetString); +void ffOpenGLHandleResult(FFOpenGLResult* result, typeof(&glGetString) ffglGetString); } static const char* oglDetectOpenGL(FFOpenGLResult* result) { @@ -20,7 +20,7 @@ static const char* oglDetectOpenGL(FFOpenGLResult* result) { } ffOpenGLHandleResult(result, ffglGetString); ffStrbufSetStatic(&result->library, "OpenGLKit"); - return NULL; + return nullptr; } const char* ffDetectOpenGL(FFOpenGLOptions* options, FFOpenGLResult* result) { diff --git a/src/detection/opengl/opengl_linux.c b/src/detection/opengl/opengl_linux.c index 5f88b7eb30..d63843b90c 100644 --- a/src/detection/opengl/opengl_linux.c +++ b/src/detection/opengl/opengl_linux.c @@ -18,7 +18,7 @@ #include -void ffOpenGLHandleResult(FFOpenGLResult* result, __typeof__(&glGetString) ffglGetString); +void ffOpenGLHandleResult(FFOpenGLResult* result, typeof(&glGetString) ffglGetString); #endif // FF_HAVE_GL @@ -61,13 +61,13 @@ static const char* glxHandleContext(FFOpenGLResult* result, GLXData* data) { ffStrbufSetStatic(&result->library, "GLX"); } - return NULL; + return nullptr; } static const char* glxHandleGLXPixmap(FFOpenGLResult* result, GLXData* data) { - data->context = data->ffglXCreateContext(data->display, data->visualInfo, NULL, True); - if (data->context == NULL) { - return "glXCreateContext returned NULL"; + data->context = data->ffglXCreateContext(data->display, data->visualInfo, nullptr, True); + if (data->context == nullptr) { + return "glXCreateContext returned nullptr"; } const char* error = glxHandleContext(result, data); @@ -99,8 +99,8 @@ static const char* glxHandleVisualInfo(FFOpenGLResult* result, GLXData* data) { static const char* glxHandleDisplay(FFOpenGLResult* result, GLXData* data) { data->visualInfo = data->ffglXChooseVisual(data->display, DefaultScreen(data->display), (int[]) { None }); - if (data->visualInfo == NULL) { - return "glXChooseVisual returned NULL"; + if (data->visualInfo == nullptr) { + return "glXChooseVisual returned nullptr"; } const char* error = glxHandleVisualInfo(result, data); @@ -109,14 +109,14 @@ static const char* glxHandleDisplay(FFOpenGLResult* result, GLXData* data) { } static const char* glxHandleData(FFOpenGLResult* result, GLXData* data) { - data->ffglGetString = (__typeof__(data->ffglGetString)) data->ffglXGetProcAddress((const GLubyte*) "glGetString"); - if (data->ffglGetString == NULL) { - return "glXGetProcAddress(glGetString) returned NULL"; + data->ffglGetString = (typeof(data->ffglGetString)) data->ffglXGetProcAddress((const GLubyte*) "glGetString"); + if (data->ffglGetString == nullptr) { + return "glXGetProcAddress(glGetString) returned nullptr"; } - data->display = data->ffXOpenDisplay(NULL); - if (data->display == NULL) { - return "XOpenDisplay returned NULL"; + data->display = data->ffXOpenDisplay(nullptr); + if (data->display == nullptr) { + return "XOpenDisplay returned nullptr"; } const char* error = glxHandleDisplay(result, data); @@ -176,7 +176,7 @@ const char* ffDetectOpenGL(FFOpenGLOptions* options, FFOpenGLResult* result) { #endif } - const char* error = ""; // not NULL dummy value + const char* error = ""; // not nullptr dummy value #ifdef FF_HAVE_EGL const char* ffOpenGLDetectByEGL(FFOpenGLResult * result); @@ -184,7 +184,7 @@ const char* ffDetectOpenGL(FFOpenGLOptions* options, FFOpenGLResult* result) { #endif #ifdef FF_HAVE_GLX - if (error != NULL) { + if (error != nullptr) { error = detectByGlx(result); } #endif diff --git a/src/detection/opengl/opengl_shared.c b/src/detection/opengl/opengl_shared.c index c483879cbe..b3fc2309bc 100644 --- a/src/detection/opengl/opengl_shared.c +++ b/src/detection/opengl/opengl_shared.c @@ -18,7 +18,7 @@ #define GL_SHADING_LANGUAGE_VERSION 0x8B8C #endif -void ffOpenGLHandleResult(FFOpenGLResult* result, __typeof__(&glGetString) ffglGetString) { +void ffOpenGLHandleResult(FFOpenGLResult* result, typeof(&glGetString) ffglGetString) { ffStrbufAppendS(&result->version, (const char*) ffglGetString(GL_VERSION)); ffStrbufAppendS(&result->renderer, (const char*) ffglGetString(GL_RENDERER)); ffStrbufAppendS(&result->vendor, (const char*) ffglGetString(GL_VENDOR)); @@ -67,7 +67,7 @@ static const char* eglHandleContext(FFOpenGLResult* result, EGLData* data) { result->vendor.chars, result->slv.chars, result->library.chars); - return NULL; + return nullptr; } static const char* eglHandleSurface(FFOpenGLResult* result, EGLData* data, bool gles) { @@ -166,10 +166,10 @@ const char* ffOpenGLDetectByEGL(FFOpenGLResult* result) { FF_LIBRARY_LOAD_SYMBOL_VAR_MESSAGE(egl, eglData, eglTerminate); FF_DEBUG("Resolving glGetString via eglGetProcAddress()"); - eglData.ffglGetString = (__typeof__(&glGetString)) ffeglGetProcAddress("glGetString"); + eglData.ffglGetString = (typeof(&glGetString)) ffeglGetProcAddress("glGetString"); if (!eglData.ffglGetString) { - FF_DEBUG("eglGetProcAddress('glGetString') returned NULL"); - return "eglGetProcAddress(glGetString) returned NULL"; + FF_DEBUG("eglGetProcAddress('glGetString') returned nullptr"); + return "eglGetProcAddress(glGetString) returned nullptr"; } FF_DEBUG("Loaded EGL library and required symbols"); @@ -184,7 +184,7 @@ const char* ffOpenGLDetectByEGL(FFOpenGLResult* result) { } if (ffeglGetPlatformDisplay) { FF_DEBUG("Trying eglGetPlatformDisplay(EGL_PLATFORM_SURFACELESS_MESA)"); - display = ffeglGetPlatformDisplay(EGL_PLATFORM_SURFACELESS_MESA, EGL_DEFAULT_DISPLAY, NULL); + display = ffeglGetPlatformDisplay(EGL_PLATFORM_SURFACELESS_MESA, nullptr /*EGL_DEFAULT_DISPLAY*/, nullptr); FF_DEBUG("eglGetPlatformDisplay() %s", display == EGL_NO_DISPLAY ? "failed" : "succeeded"); } else { FF_DEBUG("eglGetPlatformDisplay is unavailable, falling back to eglGetDisplay"); diff --git a/src/detection/opengl/opengl_windows.c b/src/detection/opengl/opengl_windows.c index 01bd986903..5b2262cbb7 100644 --- a/src/detection/opengl/opengl_windows.c +++ b/src/detection/opengl/opengl_windows.c @@ -13,7 +13,7 @@ typedef struct WGLData { FF_LIBRARY_SYMBOL(wglDeleteContext) } WGLData; -void ffOpenGLHandleResult(FFOpenGLResult* result, __typeof__(&glGetString) ffglGetString); +void ffOpenGLHandleResult(FFOpenGLResult* result, typeof(&glGetString) ffglGetString); static const char* wglHandleContext(WGLData* wglData, FFOpenGLResult* result, HDC hdc, HGLRC context) { if (wglData->ffwglMakeCurrent(hdc, context) == FALSE) { @@ -21,16 +21,16 @@ static const char* wglHandleContext(WGLData* wglData, FFOpenGLResult* result, HD } ffOpenGLHandleResult(result, wglData->ffglGetString); ffStrbufSetStatic(&result->library, "WGL 1.0"); - if (wglData->ffwglMakeCurrent(NULL, NULL) == FALSE) { - return "wglMakeCurrent(NULL, NULL) failed"; + if (wglData->ffwglMakeCurrent(nullptr, nullptr) == FALSE) { + return "wglMakeCurrent(nullptr, nullptr) failed"; } - return NULL; + return nullptr; } static const char* wglHandlePixelFormat(WGLData* wglData, FFOpenGLResult* result, HWND hWnd) { HDC hdc = GetDC(hWnd); - if (hdc == NULL) { + if (hdc == nullptr) { return "GetDC() failed"; } @@ -55,7 +55,7 @@ static const char* wglHandlePixelFormat(WGLData* wglData, FFOpenGLResult* result } HGLRC context = wglData->ffwglCreateContext(hdc); - if (context == NULL) { + if (context == nullptr) { ReleaseDC(hWnd, hdc); return "wglCreateContext() failed"; } @@ -91,7 +91,7 @@ static const char* wglDetectOpenGL(FFOpenGLResult* result) { return "RegisterClassW() failed"; } - HWND hWnd = CreateWindowW(wc.lpszClassName, L"ogl_version_check", 0, 0, 0, FF_OPENGL_BUFFER_WIDTH, FF_OPENGL_BUFFER_HEIGHT, NULL, NULL, hInstance, NULL); + HWND hWnd = CreateWindowW(wc.lpszClassName, L"ogl_version_check", 0, 0, 0, FF_OPENGL_BUFFER_WIDTH, FF_OPENGL_BUFFER_HEIGHT, nullptr, nullptr, hInstance, nullptr); if (!hWnd) { return "CreateWindowW() failed"; } diff --git a/src/detection/os/os.c b/src/detection/os/os.c index 7f66733bb4..0690574e40 100644 --- a/src/detection/os/os.c +++ b/src/detection/os/os.c @@ -4,7 +4,7 @@ void ffDetectOSImpl(FFOSResult* os); const FFOSResult* ffDetectOS(void) { static FFOSResult result; - if (result.name.chars == NULL) { + if (result.name.chars == nullptr) { ffStrbufInit(&result.name); ffStrbufInit(&result.prettyName); ffStrbufInit(&result.id); diff --git a/src/detection/os/os_linux.c b/src/detection/os/os_linux.c index 0c5d26362c..02dcb240ac 100644 --- a/src/detection/os/os_linux.c +++ b/src/detection/os/os_linux.c @@ -34,7 +34,7 @@ static bool parseOsRelease(const char* fileName, FFOSResult* result) { } // Common logic for detecting Armbian image version -FF_A_UNUSED static bool detectArmbianVersion(FFOSResult* result) { +[[maybe_unused]] static bool detectArmbianVersion(FFOSResult* result) { // Possible values `PRETTY_NAME` starts with on Armbian: // - `Armbian` for official releases // - `Armbian_community` for community releases @@ -55,7 +55,7 @@ FF_A_UNUSED static bool detectArmbianVersion(FFOSResult* result) { } // Returns false if PrettyName should be updated by caller -FF_A_UNUSED static bool getUbuntuFlavour(FFOSResult* result) { +[[maybe_unused]] static bool getUbuntuFlavour(FFOSResult* result) { if (detectArmbianVersion(result)) { return true; } else if (ffStrbufStartsWithS(&result->prettyName, "Linux Lite ")) { @@ -82,8 +82,8 @@ FF_A_UNUSED static bool getUbuntuFlavour(FFOSResult* result) { ffStrbufClear(&result->version); if (ffProcessAppendStdOut(&result->version, (char* const[]) { "/usr/bin/lliurex-version", - NULL, - }) == NULL) { // 8.2.2 + nullptr, + }) == nullptr) { // 8.2.2 ffStrbufTrimRightSpace(&result->version); } ffStrbufSetF(&result->prettyName, "LliureX %s", result->version.chars); @@ -92,7 +92,8 @@ FF_A_UNUSED static bool getUbuntuFlavour(FFOSResult* result) { } // xdgConfigDirs contains plasma only - if (ffPathExists("/var/lib/dpkg/info/ubuntustudio-desktop.list", FF_PATHTYPE_FILE)) { + // `ubuntustudio-desktop-core` is installed on both the full and core installations + if (ffPathExists("/var/lib/dpkg/info/ubuntustudio-desktop-core.list", FF_PATHTYPE_FILE)) { ffStrbufSetStatic(&result->name, "Ubuntu Studio"); ffStrbufSetStatic(&result->id, "ubuntu-studio"); ffStrbufSetStatic(&result->idLike, "ubuntu"); @@ -177,7 +178,7 @@ FF_A_UNUSED static bool getUbuntuFlavour(FFOSResult* result) { return false; } -FF_A_UNUSED static void getDebianVersion(FFOSResult* result) { +[[maybe_unused]] static void getDebianVersion(FFOSResult* result) { FF_STRBUF_AUTO_DESTROY debianVersion = ffStrbufCreate(); ffAppendFileBuffer("/etc/debian_version", &debianVersion); ffStrbufTrimRightSpace(&debianVersion); @@ -190,7 +191,7 @@ FF_A_UNUSED static void getDebianVersion(FFOSResult* result) { ffStrbufSetF(&result->prettyName, "%s %s (%s)", result->name.chars, result->versionID.chars, result->codename.chars); } -FF_A_UNUSED static bool detectDebianDerived(FFOSResult* result) { +[[maybe_unused]] static bool detectDebianDerived(FFOSResult* result) { if (detectArmbianVersion(result)) { return true; } else if (ffStrbufStartsWithS(&result->name, "Loc-OS")) { @@ -217,8 +218,8 @@ FF_A_UNUSED static bool detectDebianDerived(FFOSResult* result) { "--showformat=${version}", "--show", "pve-manager", - NULL, - }) == NULL) { // 8.2.2 + nullptr, + }) == nullptr) { // 8.2.2 ffStrbufTrimRightSpace(&result->versionID); ffStrbufSetStatic(&result->prettyName, "Proxmox VE "); ffStrbufAppend(&result->prettyName, &result->versionID); @@ -236,8 +237,8 @@ FF_A_UNUSED static bool detectDebianDerived(FFOSResult* result) { "--showformat=${version}", "--show", "proxmox-backup-server", - NULL, - }) == NULL) { + nullptr, + }) == nullptr) { ffStrbufTrimRightSpace(&result->versionID); ffStrbufSetStatic(&result->prettyName, "Proxmox Backup Server "); ffStrbufAppend(&result->prettyName, &result->versionID); @@ -306,7 +307,7 @@ FF_A_UNUSED static bool detectDebianDerived(FFOSResult* result) { return false; } -FF_A_UNUSED static bool detectFedoraVariant(FFOSResult* result) { +[[maybe_unused]] static bool detectFedoraVariant(FFOSResult* result) { if (ffStrbufEqualS(&result->variantID, "coreos") || ffStrbufEqualS(&result->variantID, "kinoite") || ffStrbufEqualS(&result->variantID, "sericea") || ffStrbufEqualS(&result->variantID, "silverblue")) { ffStrbufAppendC(&result->id, '-'); ffStrbufAppend(&result->id, &result->variantID); @@ -316,7 +317,7 @@ FF_A_UNUSED static bool detectFedoraVariant(FFOSResult* result) { return false; } -FF_A_UNUSED static bool detectBedrock(FFOSResult* os) { +[[maybe_unused]] static bool detectBedrock(FFOSResult* os) { const char* bedrockRestrict = getenv("BEDROCK_RESTRICT"); if (bedrockRestrict && bedrockRestrict[0] == '1') { return false; @@ -324,7 +325,7 @@ FF_A_UNUSED static bool detectBedrock(FFOSResult* os) { return parseOsRelease(FASTFETCH_TARGET_DIR_ROOT "/bedrock/strata/bedrock/etc/os-release", os); } -FF_A_UNUSED static void detectDeepinEnhancement(FFOSResult* result) { +[[maybe_unused]] static void detectDeepinEnhancement(FFOSResult* result) { if (ffStrbufContainC(&result->prettyName, '(')) { return; } @@ -352,7 +353,7 @@ FF_A_UNUSED static void detectDeepinEnhancement(FFOSResult* result) { } } -FF_A_UNUSED static void detectAstraVersion(FFOSResult* result) { +[[maybe_unused]] static void detectAstraVersion(FFOSResult* result) { // `PRETTY_NAME` is just `Astra Linux`; the version is in `VERSION_ID`, e.g. `2.12_x86-64` if (result->version.length == 0) { // Should be empty. Just in case ffStrbufAppendSUntilC(&result->version, result->versionID.chars, '_'); diff --git a/src/detection/os/os_windows.c b/src/detection/os/os_windows.c index 2f280c8425..e904616a09 100644 --- a/src/detection/os/os_windows.c +++ b/src/detection/os/os_windows.c @@ -8,14 +8,14 @@ PWSTR WINAPI BrandingFormatString(PCWSTR format); static bool getCodeName(FFOSResult* os) { - FF_AUTO_CLOSE_FD HANDLE hKey = NULL; - if (!ffRegOpenKeyForRead(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", &hKey, NULL)) { + FF_AUTO_CLOSE_FD HANDLE hKey = nullptr; + if (!ffRegOpenKeyForRead(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", &hKey, nullptr)) { return false; } - if (!ffRegReadStrbuf(hKey, L"DisplayVersion", &os->codename, NULL)) { - if (!ffRegReadStrbuf(hKey, L"CSDVersion", &os->codename, NULL)) { // For Windows 7 and Windows 8 - if (!ffRegReadStrbuf(hKey, L"ReleaseId", &os->codename, NULL)) { // For old Windows 10 + if (!ffRegReadStrbuf(hKey, L"DisplayVersion", &os->codename, nullptr)) { + if (!ffRegReadStrbuf(hKey, L"CSDVersion", &os->codename, nullptr)) { // For Windows 7 and Windows 8 + if (!ffRegReadStrbuf(hKey, L"ReleaseId", &os->codename, nullptr)) { // For old Windows 10 return false; } } @@ -39,9 +39,9 @@ void ffDetectOSImpl(FFOSResult* os) { if (os->variant.length == 0) // Windows PE? { - FF_AUTO_CLOSE_FD HANDLE hKey = NULL; - if (ffRegOpenKeyForRead(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", &hKey, NULL)) { - ffRegReadStrbuf(hKey, L"ProductName", &os->variant, NULL); + FF_AUTO_CLOSE_FD HANDLE hKey = nullptr; + if (ffRegOpenKeyForRead(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", &hKey, nullptr)) { + ffRegReadStrbuf(hKey, L"ProductName", &os->variant, nullptr); } } diff --git a/src/detection/packages/packages.c b/src/detection/packages/packages.c index 25f59b3e71..c72ea87577 100644 --- a/src/detection/packages/packages.c +++ b/src/detection/packages/packages.c @@ -18,7 +18,7 @@ const char* ffDetectPackages(FFPackagesResult* result, FFPackagesOptions* option result->all += ((uint32_t*) result)[i]; } - return NULL; + return nullptr; } bool ffPackagesReadCache(FFstrbuf* cacheDir, FFstrbuf* cacheContent, const char* filePath, const char* packageId, uint32_t* result) { @@ -36,7 +36,7 @@ bool ffPackagesReadCache(FFstrbuf* cacheDir, FFstrbuf* cacheContent, const char* uint64_t mtime_current = (uint64_t) st.st_mtim.tv_sec * 1000ull + (uint64_t) st.st_mtim.tv_nsec / 1000000ull; #else - FF_AUTO_CLOSE_FD HANDLE handle = CreateFileA(filePath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + FF_AUTO_CLOSE_FD HANDLE handle = CreateFileA(filePath, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if (handle == INVALID_HANDLE_VALUE) // file doesn't exist or isn't accessible { @@ -85,14 +85,14 @@ bool ffPackagesWriteCache(FFstrbuf* cacheDir, FFstrbuf* cacheContent, uint32_t n #ifndef _WIN32 uint32_t ffPackagesGetNumElements(const char* dirname, bool isdir) { FF_AUTO_CLOSE_DIR DIR* dirp = opendir(dirname); - if (dirp == NULL) { + if (dirp == nullptr) { return 0; } uint32_t num_elements = 0; struct dirent* entry; - while ((entry = readdir(dirp)) != NULL) { + while ((entry = readdir(dirp)) != nullptr) { bool ok = false; if (entry->d_name[0] != '.') { diff --git a/src/detection/packages/packages_linux.c b/src/detection/packages/packages_linux.c index ee4efbe4ce..6d0a716164 100644 --- a/src/detection/packages/packages_linux.c +++ b/src/detection/packages/packages_linux.c @@ -23,7 +23,7 @@ static uint32_t getNumStringsImpl(const char* filename, const char* needle) { uint32_t count = 0; char* iter = content.chars; size_t needleLength = strlen(needle); - while ((iter = memmem(iter, content.length - (size_t) (iter - content.chars), needle, needleLength)) != NULL) { + while ((iter = memmem(iter, content.length - (size_t) (iter - content.chars), needle, needleLength)) != nullptr) { ++count; iter += needleLength; } @@ -85,7 +85,7 @@ static uint32_t countFilesRecursiveImpl(FFstrbuf* baseDirPath, const char* filen } FF_AUTO_CLOSE_DIR DIR* dirp = opendir(baseDirPath->chars); - if (dirp == NULL) { + if (dirp == nullptr) { return 0; } @@ -95,7 +95,7 @@ static uint32_t countFilesRecursiveImpl(FFstrbuf* baseDirPath, const char* filen uint32_t sum = 0; struct dirent* entry; - while ((entry = readdir(dirp)) != NULL) { + while ((entry = readdir(dirp)) != nullptr) { // According to the PMS, neither category nor package name can begin with '.', so no need to check for . or .. specifically if (entry->d_type != DT_DIR || entry->d_name[0] == '.') { continue; @@ -122,13 +122,13 @@ static uint32_t getNumElementsBySuffix(FFstrbuf* baseDir, const char* dirname, c ffStrbufAppendS(baseDir, dirname); FF_AUTO_CLOSE_DIR DIR* dirp = opendir(baseDir->chars); ffStrbufSubstrBefore(baseDir, baseDirLength); - if (dirp == NULL) { + if (dirp == nullptr) { return 0; } uint32_t count = 0; struct dirent* entry; - while ((entry = readdir(dirp)) != NULL) { + while ((entry = readdir(dirp)) != nullptr) { if (entry->d_name[0] != '.' && ffStrEndsWithIgnCase(entry->d_name, suffix)) { ++count; } @@ -138,14 +138,14 @@ static uint32_t getNumElementsBySuffix(FFstrbuf* baseDir, const char* dirname, c static uint32_t getXBPSImpl(FFstrbuf* baseDir) { FF_AUTO_CLOSE_DIR DIR* dir = opendir(baseDir->chars); - if (dir == NULL) { + if (dir == nullptr) { return 0; } uint32_t result = 0; struct dirent* entry; - while ((entry = readdir(dir)) != NULL) { + while ((entry = readdir(dir)) != nullptr) { if (entry->d_type != DT_REG || !ffStrStartsWithIgnCase(entry->d_name, "pkgdb-")) { continue; } @@ -198,17 +198,17 @@ static uint32_t getRpmFromLibrpm(void) { // Don't print any error messages ffrpmlogSetMask(RPMLOG_MASK(RPMLOG_EMERG)); - if (ffrpmReadConfigFiles(NULL, NULL) != 0) { + if (ffrpmReadConfigFiles(nullptr, nullptr) != 0) { return 0; } rpmts ts = ffrpmtsCreate(); - if (ts == NULL) { + if (ts == nullptr) { return 0; } - rpmdbMatchIterator mi = ffrpmtsInitIterator(ts, RPMDBI_LABEL, NULL, 0); - if (mi == NULL) { + rpmdbMatchIterator mi = ffrpmtsInitIterator(ts, RPMDBI_LABEL, nullptr, 0); + if (mi == nullptr) { ffrpmtsFree(ts); return 0; } @@ -232,7 +232,7 @@ static uint32_t getAMPackages(FFstrbuf* baseDir) { uint32_t result = 0; struct dirent* entry; - while ((entry = readdir(dirp)) != NULL) { + while ((entry = readdir(dirp)) != nullptr) { if (entry->d_name[0] == '.') { continue; } @@ -330,14 +330,14 @@ static uint32_t getGuixPackages(FFstrbuf* baseDir, const char* dirname) { static inline uint32_t getFlatpakRuntimePackagesArch(FFstrbuf* baseDir) { FF_AUTO_CLOSE_DIR DIR* dirp = opendir(baseDir->chars); - if (dirp == NULL) { + if (dirp == nullptr) { return 0; } uint32_t num_elements = 0; struct dirent* entry; - while ((entry = readdir(dirp)) != NULL) { + while ((entry = readdir(dirp)) != nullptr) { if (entry->d_type == DT_DIR && entry->d_name[0] != '.') { num_elements += getNumElements(baseDir, entry->d_name, true); } @@ -349,7 +349,7 @@ static inline uint32_t getFlatpakRuntimePackagesArch(FFstrbuf* baseDir) { static inline uint32_t getFlatpakRuntimePackages(FFstrbuf* baseDir) { ffStrbufAppendS(baseDir, "runtime/"); FF_AUTO_CLOSE_DIR DIR* dirp = opendir(baseDir->chars); - if (dirp == NULL) { + if (dirp == nullptr) { return 0; } @@ -357,7 +357,7 @@ static inline uint32_t getFlatpakRuntimePackages(FFstrbuf* baseDir) { uint32_t num_elements = 0; struct dirent* entry; - while ((entry = readdir(dirp)) != NULL) { + while ((entry = readdir(dirp)) != nullptr) { if (entry->d_type == DT_DIR && entry->d_name[0] != '.') { // `flatpak list` ignores `.Locale` and `.Debug` packages, and maybe others const char* dot = strrchr(entry->d_name, '.'); @@ -383,7 +383,7 @@ static inline uint32_t getFlatpakRuntimePackages(FFstrbuf* baseDir) { static inline uint32_t getFlatpakAppPackages(FFstrbuf* baseDir) { ffStrbufAppendS(baseDir, "app/"); FF_AUTO_CLOSE_DIR DIR* dirp = opendir(baseDir->chars); - if (dirp == NULL) { + if (dirp == nullptr) { return 0; } @@ -391,7 +391,7 @@ static inline uint32_t getFlatpakAppPackages(FFstrbuf* baseDir) { uint32_t num_elements = 0; struct dirent* entry; - while ((entry = readdir(dirp)) != NULL) { + while ((entry = readdir(dirp)) != nullptr) { if (entry->d_type == DT_DIR && entry->d_name[0] != '.') { ffStrbufAppendS(baseDir, entry->d_name); ffStrbufAppendS(baseDir, "/current"); @@ -458,13 +458,13 @@ static uint32_t getPacmanPackages(FFstrbuf* baseDir) { static uint32_t getEmergePackagesImpl(FFstrbuf* baseDir) { FF_AUTO_CLOSE_DIR DIR* dirp = opendir(baseDir->chars); - if (dirp == NULL) + if (dirp == nullptr) return 0; uint32_t result = 0; struct dirent *entry; - while ((entry = readdir(dirp)) != NULL) + while ((entry = readdir(dirp)) != nullptr) { if (entry->d_type != DT_DIR || entry->d_name[0] == '.') continue; @@ -589,7 +589,7 @@ static void getPackageCountsBedrock(FFstrbuf* baseDir, FFPackagesResult* package ffStrbufAppendS(baseDir, "/bedrock/strata"); FF_AUTO_CLOSE_DIR DIR* dir = opendir(baseDir->chars); - if (dir == NULL) { + if (dir == nullptr) { ffStrbufSubstrBefore(baseDir, baseDirLength); return; } @@ -598,7 +598,7 @@ static void getPackageCountsBedrock(FFstrbuf* baseDir, FFPackagesResult* package uint32_t baseDirLength2 = baseDir->length; struct dirent* entry; - while ((entry = readdir(dir)) != NULL) { + while ((entry = readdir(dir)) != nullptr) { if (entry->d_type != DT_DIR) { continue; } @@ -620,8 +620,8 @@ static uint32_t getInstallReleasePackages(FFstrbuf* baseDir) { uint32_t baseDirLength = baseDir->length; ffStrbufAppendS(baseDir, ".config/install_release/state.json"); if (ffPathExists(baseDir->chars, FF_PATHTYPE_ANY)) { - yyjson_doc* doc = yyjson_read_file(baseDir->chars, YYJSON_READ_NOFLAG, NULL, NULL); - if (doc != NULL) { + yyjson_doc* doc = yyjson_read_file(baseDir->chars, YYJSON_READ_NOFLAG, nullptr, nullptr); + if (doc != nullptr) { yyjson_val* root = yyjson_doc_get_root(doc); if (yyjson_is_obj(root)) { result = (uint32_t) yyjson_obj_size(root); diff --git a/src/detection/packages/packages_nix.c b/src/detection/packages/packages_nix.c index d1cc2647e3..cd2f6db299 100644 --- a/src/detection/packages/packages_nix.c +++ b/src/detection/packages/packages_nix.c @@ -101,7 +101,7 @@ static uint32_t getNixPackagesImpl(char* path) { FF_STRBUF_AUTO_DESTROY cacheHash = ffStrbufCreateA(64); uint32_t count = 0; - ffProcessAppendStdOut(&hash, (char* const[]) { "nix-store", "--query", "--hash", path, NULL }); + ffProcessAppendStdOut(&hash, (char* const[]) { "nix-store", "--query", "--hash", path, nullptr }); if (checkNixCache(&cacheDir, &cacheHash, &count) && ffStrbufEqual(&hash, &cacheHash)) { return count; @@ -115,7 +115,7 @@ static uint32_t getNixPackagesImpl(char* path) { FF_STRBUF_AUTO_DESTROY output = ffStrbufCreateA(1024); - ffProcessAppendStdOut(&output, (char* const[]) { "nix-store", "--query", "--requisites", path, NULL }); + ffProcessAppendStdOut(&output, (char* const[]) { "nix-store", "--query", "--requisites", path, nullptr }); uint32_t lineLength = 0; for (uint32_t i = 0; i < output.length; i++) { diff --git a/src/detection/packages/packages_nosupport.c b/src/detection/packages/packages_nosupport.c index 40300fab39..facc9f5453 100644 --- a/src/detection/packages/packages_nosupport.c +++ b/src/detection/packages/packages_nosupport.c @@ -1,4 +1,4 @@ #include "packages.h" -void ffDetectPackagesImpl(FF_A_UNUSED FFPackagesResult* result, FF_A_UNUSED FFPackagesOptions* options) { +void ffDetectPackagesImpl([[maybe_unused]] FFPackagesResult* result, [[maybe_unused]] FFPackagesOptions* options) { } diff --git a/src/detection/packages/packages_sunos.c b/src/detection/packages/packages_sunos.c index 16b8cd7cd9..1aa1c60df0 100644 --- a/src/detection/packages/packages_sunos.c +++ b/src/detection/packages/packages_sunos.c @@ -3,7 +3,7 @@ void ffDetectPackagesImpl(FFPackagesResult* result, FFPackagesOptions* options) { if (FF_PACKAGES_IS_ENABLED(options, PKG)) { - yyjson_doc* doc = yyjson_read_file(FASTFETCH_TARGET_DIR_ROOT "/var/pkg/state/installed/catalog.attrs", YYJSON_READ_NOFLAG, NULL, NULL); + yyjson_doc* doc = yyjson_read_file(FASTFETCH_TARGET_DIR_ROOT "/var/pkg/state/installed/catalog.attrs", YYJSON_READ_NOFLAG, nullptr, nullptr); if (doc) { yyjson_val* packageCount = yyjson_obj_get(yyjson_doc_get_root(doc), "package-count"); if (packageCount) { diff --git a/src/detection/packages/packages_windows.c b/src/detection/packages/packages_windows.c index a3faee5296..b4c3883a52 100644 --- a/src/detection/packages/packages_windows.c +++ b/src/detection/packages/packages_windows.c @@ -13,12 +13,12 @@ #include static uint32_t getNumElements(const char* searchPath, DWORD type, const wchar_t* ignore) { - FF_AUTO_CLOSE_FD HANDLE dfd = CreateFileA(searchPath, FILE_LIST_DIRECTORY | SYNCHRONIZE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); + FF_AUTO_CLOSE_FD HANDLE dfd = CreateFileA(searchPath, FILE_LIST_DIRECTORY | SYNCHRONIZE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, nullptr); if (dfd == INVALID_HANDLE_VALUE) { return 0; } - bool flag = ignore == NULL; + bool flag = ignore == nullptr; uint32_t counter = 0; alignas(8) uint8_t buffer[64 * 1024]; BOOLEAN firstScan = TRUE; @@ -29,15 +29,15 @@ static uint32_t getNumElements(const char* searchPath, DWORD type, const wchar_t IO_STATUS_BLOCK ioStatus = {}; NTSTATUS status = NtQueryDirectoryFile( dfd, - NULL, - NULL, - NULL, + nullptr, + nullptr, + nullptr, &ioStatus, buffer, ARRAY_SIZE(buffer), FileDirectoryInformation, FALSE, - NULL, + nullptr, firstScan); firstScan = FALSE; @@ -90,13 +90,13 @@ static void detectScoop(FFPackagesResult* result) { ffStrbufAppend(&scoopPath, &instance.state.platform.homeDir); ffStrbufAppendS(&scoopPath, ".config/scoop/config.json"); - yyjson_val* root = NULL; + yyjson_val* root = nullptr; - yyjson_doc* FF_A_CLEANUP(wrapYyjsonFree) doc = yyjson_read_file(scoopPath.chars, 0, NULL, NULL); + [[gnu::cleanup(wrapYyjsonFree)]] yyjson_doc* doc = yyjson_read_file(scoopPath.chars, 0, nullptr, nullptr); if (doc) { root = yyjson_doc_get_root(doc); if (!yyjson_is_obj(root)) { - root = NULL; + root = nullptr; } } @@ -119,8 +119,8 @@ static void detectScoop(FFPackagesResult* result) { ffStrbufSetJsonVal(&scoopPath, yyjson_obj_get(root, "global_path")); } if (scoopPath.length == 0) { - PWSTR pPath = NULL; - if (SUCCEEDED(SHGetKnownFolderPath(&FOLDERID_ProgramData, KF_FLAG_DEFAULT, NULL, &pPath))) { + PWSTR pPath = nullptr; + if (SUCCEEDED(SHGetKnownFolderPath(&FOLDERID_ProgramData, KF_FLAG_DEFAULT, nullptr, &pPath))) { ffStrbufSetWS(&scoopPath, pPath); CoTaskMemFree(pPath); } @@ -131,7 +131,7 @@ static void detectScoop(FFPackagesResult* result) { } } -static void detectChoco(FF_A_UNUSED FFPackagesResult* result) { +static void detectChoco([[maybe_unused]] FFPackagesResult* result) { const char* chocoInstall = getenv("ChocolateyInstall"); if (!chocoInstall || chocoInstall[0] == '\0') { return; @@ -153,7 +153,7 @@ static void detectPacman(FFPackagesResult* result) { char pacmanPath[MAX_PATH + 3]; char* pend = ffStrCopy(pacmanPath, msystemPrefix, ARRAY_SIZE(pacmanPath)); ffStrCopy(pend, "/../var/lib/pacman/local/", ARRAY_SIZE(pacmanPath) - (size_t) (pend - pacmanPath)); - result->pacman = getNumElements(pacmanPath, FILE_ATTRIBUTE_DIRECTORY, NULL); + result->pacman = getNumElements(pacmanPath, FILE_ATTRIBUTE_DIRECTORY, nullptr); } static void detectWinget(FFPackagesResult* result) { @@ -162,7 +162,7 @@ static void detectWinget(FFPackagesResult* result) { "winget.exe", "list", "--disable-interactivity", - NULL, + nullptr, })) { return; } diff --git a/src/detection/physicaldisk/physicaldisk_apple.c b/src/detection/physicaldisk/physicaldisk_apple.c index f4c5cd6ca6..47098c9441 100644 --- a/src/detection/physicaldisk/physicaldisk_apple.c +++ b/src/detection/physicaldisk/physicaldisk_apple.c @@ -22,19 +22,19 @@ static inline void wrapIoDestroyPlugInInterface(IOCFPlugInInterface*** pluginInf static const char* detectSsdTemp(io_service_t entryPhysical, double* temp) { #ifdef MAC_OS_X_VERSION_10_15 - FF_A_CLEANUP(wrapIoDestroyPlugInInterface) IOCFPlugInInterface** pluginInf = NULL; + [[gnu::cleanup(wrapIoDestroyPlugInInterface)]] IOCFPlugInInterface** pluginInf = nullptr; int32_t score; if (IOCreatePlugInInterfaceForService(entryPhysical, kIONVMeSMARTUserClientTypeID, kIOCFPlugInInterfaceID, &pluginInf, &score) != kIOReturnSuccess) { return "IOCreatePlugInInterfaceForService() failed"; } - IONVMeSMARTInterface** smartInf = NULL; + IONVMeSMARTInterface** smartInf = nullptr; if ((*pluginInf)->QueryInterface(pluginInf, CFUUIDGetUUIDBytes(kIONVMeSMARTInterfaceID), (LPVOID) &smartInf) != kIOReturnSuccess) { return "QueryInterface() failed"; } NVMeSMARTData smartData; - const char* error = NULL; + const char* error = nullptr; if ((*smartInf)->SMARTReadData(smartInf, &smartData) == kIOReturnSuccess) { *temp = smartData.TEMPERATURE - 273; } else { @@ -76,14 +76,14 @@ const char* ffDetectPhysicalDisk(FFlist* result, FFPhysicalDiskOptions* options) } if (deviceName.length == 0) { - FF_CFTYPE_AUTO_RELEASE CFDictionaryRef deviceCharacteristics = IORegistryEntryCreateCFProperty(entryPhysical, CFSTR(kIOPropertyDeviceCharacteristicsKey), NULL, kNilOptions); + FF_CFTYPE_AUTO_RELEASE CFDictionaryRef deviceCharacteristics = IORegistryEntryCreateCFProperty(entryPhysical, CFSTR(kIOPropertyDeviceCharacteristicsKey), nullptr, kNilOptions); if (deviceCharacteristics) { - if (ffCfDictGetString(deviceCharacteristics, CFSTR(kIOPropertyVendorNameKey), &deviceName) == NULL && deviceName.length > 0) { + if (ffCfDictGetString(deviceCharacteristics, CFSTR(kIOPropertyVendorNameKey), &deviceName) == nullptr && deviceName.length > 0) { ffStrbufAppendC(&deviceName, ' '); } FF_STRBUF_AUTO_DESTROY name = ffStrbufCreate(); - if (ffCfDictGetString(deviceCharacteristics, CFSTR(kIOPropertyProductNameKey), &name) == NULL) { + if (ffCfDictGetString(deviceCharacteristics, CFSTR(kIOPropertyProductNameKey), &name) == nullptr) { ffStrbufAppend(&deviceName, &name); } } @@ -96,9 +96,9 @@ const char* ffDetectPhysicalDisk(FFlist* result, FFPhysicalDiskOptions* options) FFPhysicalDiskType type = FF_PHYSICALDISK_TYPE_NONE; FF_STRBUF_AUTO_DESTROY interconnect = ffStrbufCreate(); - FF_CFTYPE_AUTO_RELEASE CFDictionaryRef protocolCharacteristics = IORegistryEntryCreateCFProperty(entryPhysical, CFSTR(kIOPropertyProtocolCharacteristicsKey), NULL, kNilOptions); + FF_CFTYPE_AUTO_RELEASE CFDictionaryRef protocolCharacteristics = IORegistryEntryCreateCFProperty(entryPhysical, CFSTR(kIOPropertyProtocolCharacteristicsKey), nullptr, kNilOptions); if (protocolCharacteristics) { - if (ffCfDictGetString(protocolCharacteristics, CFSTR(kIOPropertyPhysicalInterconnectTypeKey), &interconnect) == NULL) { + if (ffCfDictGetString(protocolCharacteristics, CFSTR(kIOPropertyPhysicalInterconnectTypeKey), &interconnect) == nullptr) { if (ffStrbufEqualS(&interconnect, kIOPropertyPhysicalInterconnectTypeVirtual)) { if (options->hideType & FF_PHYSICALDISK_TYPE_VIRTUAL) { continue; @@ -106,7 +106,7 @@ const char* ffDetectPhysicalDisk(FFlist* result, FFPhysicalDiskOptions* options) type |= FF_PHYSICALDISK_TYPE_VIRTUAL; FF_STRBUF_AUTO_DESTROY location = ffStrbufCreate(); - if (ffCfDictGetString(protocolCharacteristics, CFSTR(kIOPropertyPhysicalInterconnectLocationKey), &location) == NULL) { + if (ffCfDictGetString(protocolCharacteristics, CFSTR(kIOPropertyPhysicalInterconnectLocationKey), &location) == nullptr) { ffStrbufAppendS(&interconnect, " - "); ffStrbufAppend(&interconnect, &location); } @@ -116,7 +116,7 @@ const char* ffDetectPhysicalDisk(FFlist* result, FFPhysicalDiskOptions* options) uint64_t size = 0; if (entryMedia != IO_OBJECT_NULL) { - FF_CFTYPE_AUTO_RELEASE CFNumberRef mediaSize = IORegistryEntryCreateCFProperty(entryMedia, CFSTR(kIOMediaSizeKey), NULL, kNilOptions); + FF_CFTYPE_AUTO_RELEASE CFNumberRef mediaSize = IORegistryEntryCreateCFProperty(entryMedia, CFSTR(kIOMediaSizeKey), nullptr, kNilOptions); if (mediaSize) { ffCfNumGetInt64(mediaSize, (int64_t*) &size); } @@ -141,24 +141,24 @@ const char* ffDetectPhysicalDisk(FFlist* result, FFPhysicalDiskOptions* options) device->temperature = FF_PHYSICALDISK_TEMP_UNSET; if (entryMedia != IO_OBJECT_NULL) { - FF_CFTYPE_AUTO_RELEASE CFBooleanRef removable = IORegistryEntryCreateCFProperty(entryMedia, CFSTR(kIOMediaRemovableKey), NULL, kNilOptions); + FF_CFTYPE_AUTO_RELEASE CFBooleanRef removable = IORegistryEntryCreateCFProperty(entryMedia, CFSTR(kIOMediaRemovableKey), nullptr, kNilOptions); if (removable) { device->type |= CFBooleanGetValue(removable) ? FF_PHYSICALDISK_TYPE_REMOVABLE : FF_PHYSICALDISK_TYPE_FIXED; } - FF_CFTYPE_AUTO_RELEASE CFBooleanRef writable = IORegistryEntryCreateCFProperty(entryMedia, CFSTR(kIOMediaWritableKey), NULL, kNilOptions); + FF_CFTYPE_AUTO_RELEASE CFBooleanRef writable = IORegistryEntryCreateCFProperty(entryMedia, CFSTR(kIOMediaWritableKey), nullptr, kNilOptions); if (writable) { device->type |= CFBooleanGetValue(writable) ? FF_PHYSICALDISK_TYPE_READWRITE : FF_PHYSICALDISK_TYPE_READONLY; } - FF_CFTYPE_AUTO_RELEASE CFStringRef bsdName = IORegistryEntryCreateCFProperty(entryMedia, CFSTR(kIOBSDNameKey), NULL, kNilOptions); + FF_CFTYPE_AUTO_RELEASE CFStringRef bsdName = IORegistryEntryCreateCFProperty(entryMedia, CFSTR(kIOBSDNameKey), nullptr, kNilOptions); if (bsdName) { ffCfStrGetString(bsdName, &device->devPath); ffStrbufPrependS(&device->devPath, "/dev/"); } } - FF_CFTYPE_AUTO_RELEASE CFDictionaryRef deviceCharacteristics = IORegistryEntryCreateCFProperty(entryPhysical, CFSTR(kIOPropertyDeviceCharacteristicsKey), NULL, kNilOptions); + FF_CFTYPE_AUTO_RELEASE CFDictionaryRef deviceCharacteristics = IORegistryEntryCreateCFProperty(entryPhysical, CFSTR(kIOPropertyDeviceCharacteristicsKey), nullptr, kNilOptions); if (deviceCharacteristics) { ffCfDictGetString(deviceCharacteristics, CFSTR(kIOPropertyProductSerialNumberKey), &device->serial); ffStrbufTrimSpace(&device->serial); @@ -179,7 +179,7 @@ const char* ffDetectPhysicalDisk(FFlist* result, FFPhysicalDiskOptions* options) #ifdef MAC_OS_X_VERSION_10_15 if (!(device->type & FF_PHYSICALDISK_TYPE_VIRTUAL) && options->temp) { - FF_CFTYPE_AUTO_RELEASE CFBooleanRef nvmeSMARTCapable = IORegistryEntryCreateCFProperty(entryPhysical, CFSTR(kIOPropertyNVMeSMARTCapableKey), NULL, kNilOptions); + FF_CFTYPE_AUTO_RELEASE CFBooleanRef nvmeSMARTCapable = IORegistryEntryCreateCFProperty(entryPhysical, CFSTR(kIOPropertyNVMeSMARTCapableKey), nullptr, kNilOptions); if (nvmeSMARTCapable && CFBooleanGetValue(nvmeSMARTCapable)) { detectSsdTemp(entryPhysical, &device->temperature); } @@ -187,5 +187,5 @@ const char* ffDetectPhysicalDisk(FFlist* result, FFPhysicalDiskOptions* options) #endif } - return NULL; + return nullptr; } diff --git a/src/detection/physicaldisk/physicaldisk_bsd.c b/src/detection/physicaldisk/physicaldisk_bsd.c index 5a877681fe..cda7adda55 100644 --- a/src/detection/physicaldisk/physicaldisk_bsd.c +++ b/src/detection/physicaldisk/physicaldisk_bsd.c @@ -23,12 +23,12 @@ const char* ffDetectPhysicalDisk(FFlist* result, FFPhysicalDiskOptions* options) void* snap = geom_stats_snapshot_get(); struct devstat* snapIter; - while ((snapIter = geom_stats_snapshot_next(snap)) != NULL) { + while ((snapIter = geom_stats_snapshot_next(snap)) != nullptr) { if (snapIter->device_type & DEVSTAT_TYPE_PASS) { continue; } struct gident* geomId = geom_lookupid(&geomTree, snapIter->id); - if (geomId == NULL) { + if (geomId == nullptr) { continue; } if (geomId->lg_what != ISPROVIDER) { @@ -118,7 +118,7 @@ const char* ffDetectPhysicalDisk(FFlist* result, FFPhysicalDiskOptions* options) geom_stats_snapshot_free(snap); geom_stats_close(); - return NULL; + return nullptr; } #else const char* ffDetectPhysicalDisk(FFlist* result, FFPhysicalDiskOptions* options) { diff --git a/src/detection/physicaldisk/physicaldisk_haiku.c b/src/detection/physicaldisk/physicaldisk_haiku.c index e44ddced17..d2b83fed29 100644 --- a/src/detection/physicaldisk/physicaldisk_haiku.c +++ b/src/detection/physicaldisk/physicaldisk_haiku.c @@ -77,7 +77,7 @@ static const char* searchRawDeviceFile(FFstrbuf* path, const char* diskType, FFl ffStrbufSubstrBefore(path, baseLen); } - return NULL; + return nullptr; } const char* ffDetectPhysicalDisk(FFlist* result, FFPhysicalDiskOptions* options) { @@ -100,5 +100,5 @@ const char* ffDetectPhysicalDisk(FFlist* result, FFPhysicalDiskOptions* options) ffStrbufSubstrBefore(&path, baseLen); } - return NULL; + return nullptr; } diff --git a/src/detection/physicaldisk/physicaldisk_linux.c b/src/detection/physicaldisk/physicaldisk_linux.c index f8126b96a2..b6d4c755f7 100644 --- a/src/detection/physicaldisk/physicaldisk_linux.c +++ b/src/detection/physicaldisk/physicaldisk_linux.c @@ -18,7 +18,7 @@ static double detectNvmeTemp(int devfd) { ssize_t size = ffReadFileDataRelative(devfd, pathHwmon, ARRAY_SIZE(buffer), buffer); if (size > 0) { buffer[size] = '\0'; - double temp = strtod(buffer, NULL); + double temp = strtod(buffer, nullptr); return temp > 0 && temp < 10000000 /*VMware*/ ? temp / 1000 : FF_PHYSICALDISK_TEMP_UNSET; } } @@ -34,7 +34,7 @@ static void parsePhysicalDisk(int dfd, const char* devName, FFPhysicalDiskOption ssize_t fileSize = ffReadFileDataRelative(dfd, "size", ARRAY_SIZE(blkSize) - 1, blkSize); if (fileSize > 0) { blkSize[fileSize] = 0; - size = (uint64_t) strtoul(blkSize, NULL, 10) * 512; + size = (uint64_t) strtoul(blkSize, nullptr, 10) * 512; } } @@ -118,15 +118,15 @@ static void parsePhysicalDisk(int dfd, const char* devName, FFPhysicalDiskOption snprintf(pathSysDeviceLink, ARRAY_SIZE(pathSysDeviceLink), "/sys/block/%s/device", devName); char pathSysDeviceReal[PATH_MAX]; if (realpath(pathSysDeviceLink, pathSysDeviceReal)) { - if (strstr(pathSysDeviceReal, "/usb") != NULL) { + if (strstr(pathSysDeviceReal, "/usb") != nullptr) { ffStrbufSetStatic(&device->interconnect, "USB"); - } else if (strstr(pathSysDeviceReal, "/ata") != NULL) { + } else if (strstr(pathSysDeviceReal, "/ata") != nullptr) { ffStrbufSetStatic(&device->interconnect, "ATA"); - } else if (strstr(pathSysDeviceReal, "/scsi") != NULL) { + } else if (strstr(pathSysDeviceReal, "/scsi") != nullptr) { ffStrbufSetStatic(&device->interconnect, "SCSI"); - } else if (strstr(pathSysDeviceReal, "/nvme") != NULL) { + } else if (strstr(pathSysDeviceReal, "/nvme") != nullptr) { ffStrbufSetStatic(&device->interconnect, "NVMe"); - } else if (strstr(pathSysDeviceReal, "/virtio") != NULL) { + } else if (strstr(pathSysDeviceReal, "/virtio") != nullptr) { ffStrbufSetStatic(&device->interconnect, "VirtIO"); isVirtio = true; // VirtIO devices are virtual, but we still want to report it } else { @@ -177,12 +177,12 @@ static void parsePhysicalDisk(int dfd, const char* devName, FFPhysicalDiskOption const char* ffDetectPhysicalDisk(FFlist* result, FFPhysicalDiskOptions* options) { FF_AUTO_CLOSE_DIR DIR* sysBlockDirp = opendir("/sys/block/"); - if (sysBlockDirp == NULL) { - return "opendir(\"/sys/block/\") == NULL"; + if (sysBlockDirp == nullptr) { + return "opendir(\"/sys/block/\") == nullptr"; } struct dirent* sysBlockEntry; - while ((sysBlockEntry = readdir(sysBlockDirp)) != NULL) { + while ((sysBlockEntry = readdir(sysBlockDirp)) != nullptr) { const char* const devName = sysBlockEntry->d_name; if (devName[0] == '.') { @@ -198,5 +198,5 @@ const char* ffDetectPhysicalDisk(FFlist* result, FFPhysicalDiskOptions* options) } } - return NULL; + return nullptr; } diff --git a/src/detection/physicaldisk/physicaldisk_nbsd.c b/src/detection/physicaldisk/physicaldisk_nbsd.c index 0733f3b5ba..bf9bd3adbf 100644 --- a/src/detection/physicaldisk/physicaldisk_nbsd.c +++ b/src/detection/physicaldisk/physicaldisk_nbsd.c @@ -122,7 +122,7 @@ const char* ffDetectPhysicalDisk(FFlist* result, FFPhysicalDiskOptions* options) FF_DEBUG("Disk names: %s", diskNames.chars); - char* diskName = NULL; + char* diskName = nullptr; size_t len = 0; while (ffStrbufGetdelim(&diskName, &len, ' ', &diskNames)) { FF_DEBUG("Probing disk: %s", diskName); @@ -158,9 +158,9 @@ const char* ffDetectPhysicalDisk(FFlist* result, FFPhysicalDiskOptions* options) unsigned long sectorsPerUnit, sectorSize; - const char* devType = NULL; + const char* devType = nullptr; - prop_dictionary_t dict = NULL; + prop_dictionary_t dict = nullptr; if (prop_dictionary_recv_ioctl(f, DIOCGDISKINFO, &dict) == 0) { FF_DEBUG("DIOCGDISKINFO succeeded for %s", diskName); prop_dictionary_get_string(dict, "type", &devType); @@ -228,7 +228,7 @@ const char* ffDetectPhysicalDisk(FFlist* result, FFPhysicalDiskOptions* options) if (dict) { prop_object_release(dict); - dict = NULL; + dict = nullptr; } struct scsipi_inquiry_data inquiry = {}; @@ -320,5 +320,5 @@ const char* ffDetectPhysicalDisk(FFlist* result, FFPhysicalDiskOptions* options) FF_DEBUG("Detected disk '%s' (%s), type=%u", device->name.chars, diskName, (unsigned) device->type); } - return NULL; + return nullptr; } diff --git a/src/detection/physicaldisk/physicaldisk_nosupport.c b/src/detection/physicaldisk/physicaldisk_nosupport.c index 26e0ce881b..6e0dd582e1 100644 --- a/src/detection/physicaldisk/physicaldisk_nosupport.c +++ b/src/detection/physicaldisk/physicaldisk_nosupport.c @@ -1,5 +1,5 @@ #include "physicaldisk.h" -const char* ffDetectPhysicalDisk(FF_A_UNUSED FFlist* result, FF_A_UNUSED FFPhysicalDiskOptions* options) { +const char* ffDetectPhysicalDisk([[maybe_unused]] FFlist* result, [[maybe_unused]] FFPhysicalDiskOptions* options) { return "Not supported on this platform"; } diff --git a/src/detection/physicaldisk/physicaldisk_obsd.c b/src/detection/physicaldisk/physicaldisk_obsd.c index 6e89a99753..7b8680675d 100644 --- a/src/detection/physicaldisk/physicaldisk_obsd.c +++ b/src/detection/physicaldisk/physicaldisk_obsd.c @@ -119,7 +119,7 @@ const char* ffDetectPhysicalDisk(FFlist* result, FFPhysicalDiskOptions* options) FF_DEBUG("Disk names: %s", diskNames.chars); - char* diskName = NULL; + char* diskName = nullptr; size_t len = 0; while (ffStrbufGetdelim(&diskName, &len, ',', &diskNames)) { char* colon = strchr(diskName, ':'); @@ -138,7 +138,7 @@ const char* ffDetectPhysicalDisk(FFlist* result, FFPhysicalDiskOptions* options) continue; } - char* devPath = NULL; + char* devPath = nullptr; FF_AUTO_CLOSE_FD int f = opendev(diskName, O_RDONLY, OPENDEV_PART, &devPath); if (f < 0) { if (errno == EACCES) { @@ -275,5 +275,5 @@ const char* ffDetectPhysicalDisk(FFlist* result, FFPhysicalDiskOptions* options) FF_DEBUG("Detected disk '%s' (%s), type=%u", device->name.chars, diskName, (unsigned) device->type); } - return NULL; + return nullptr; } diff --git a/src/detection/physicaldisk/physicaldisk_sunos.c b/src/detection/physicaldisk/physicaldisk_sunos.c index d929d5a235..b65fba000f 100644 --- a/src/detection/physicaldisk/physicaldisk_sunos.c +++ b/src/detection/physicaldisk/physicaldisk_sunos.c @@ -103,5 +103,5 @@ const char* ffDetectPhysicalDisk(FFlist* result, FFPhysicalDiskOptions* options) di_walk_minor(rootNode, DDI_NT_BLOCK, DI_WALK_CLDFIRST, &(struct FFWalkTreeBundle) { options, result }, (void*) walkDevTree); di_fini(rootNode); - return NULL; + return nullptr; } diff --git a/src/detection/physicaldisk/physicaldisk_windows.c b/src/detection/physicaldisk/physicaldisk_windows.c index 5d4f7f7439..56ae1d314d 100644 --- a/src/detection/physicaldisk/physicaldisk_windows.c +++ b/src/detection/physicaldisk/physicaldisk_windows.c @@ -10,7 +10,7 @@ #include static const char* detectPhysicalDisk(const char* physicalType, const wchar_t* szDevice, FFlist* result, FFPhysicalDiskOptions* options) { - FF_AUTO_CLOSE_FD HANDLE hDevice = CreateFileW(szDevice, FILE_READ_ATTRIBUTES, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); + FF_AUTO_CLOSE_FD HANDLE hDevice = CreateFileW(szDevice, FILE_READ_ATTRIBUTES, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); if (hDevice == INVALID_HANDLE_VALUE) { return "CreateFileW() failed"; } @@ -19,30 +19,30 @@ static const char* detectPhysicalDisk(const char* physicalType, const wchar_t* s FFPhysicalDiskType type = FF_PHYSICALDISK_TYPE_NONE; FF_STRBUF_AUTO_DESTROY name = ffStrbufCreate(); - const char* interconnect = NULL; + const char* interconnect = nullptr; uint64_t size = 0; { alignas(DISK_GEOMETRY_EX) uint8_t dgeBuffer[4096]; if (DeviceIoControl( hDevice, IOCTL_DISK_GET_DRIVE_GEOMETRY_EX, - NULL, + nullptr, 0, dgeBuffer, sizeof(dgeBuffer), &retSize, - NULL)) { + nullptr)) { const DISK_GEOMETRY_EX* dge = (const DISK_GEOMETRY_EX*) dgeBuffer; size = (uint64_t) dge->DiskSize.QuadPart; } else if (DeviceIoControl( hDevice, IOCTL_DISK_GET_DRIVE_GEOMETRY, - NULL, + nullptr, 0, dgeBuffer, sizeof(dgeBuffer), &retSize, - NULL) && + nullptr) && retSize >= sizeof(DISK_GEOMETRY)) { const DISK_GEOMETRY* dg = (const DISK_GEOMETRY*) dgeBuffer; size = (uint64_t) dg->BytesPerSector * dg->SectorsPerTrack * dg->TracksPerCylinder * (uint64_t) dg->Cylinders.QuadPart; @@ -91,7 +91,7 @@ static const char* detectPhysicalDisk(const char* physicalType, const wchar_t* s type |= FF_PHYSICALDISK_TYPE_UNUSED; } - const STORAGE_DEVICE_DESCRIPTOR* sdd = NULL; + const STORAGE_DEVICE_DESCRIPTOR* sdd = nullptr; alignas(STORAGE_DEVICE_DESCRIPTOR) uint8_t sddBuffer[4096]; if (!interconnect) { if (DeviceIoControl( @@ -105,7 +105,7 @@ static const char* detectPhysicalDisk(const char* physicalType, const wchar_t* s &sddBuffer, sizeof(sddBuffer), &retSize, - NULL) || + nullptr) || retSize == 0) { sdd = (const STORAGE_DEVICE_DESCRIPTOR*) sddBuffer; @@ -236,23 +236,23 @@ static const char* detectPhysicalDisk(const char* physicalType, const wchar_t* s if (DeviceIoControl( hDevice, IOCTL_STORAGE_GET_MEDIA_TYPES_EX, - NULL, + nullptr, 0, gmt, sizeof(buffer), &retSize, - NULL) && + nullptr) && gmt->MediaInfoCount > 0) { // DiskInfo and RemovableDiskInfo have the same structures. TapeInfo doesn't. if (gmt->DeviceType != FILE_DEVICE_TAPE) { - __auto_type diskInfo = &gmt->MediaInfo[0].DeviceSpecific.DiskInfo; + auto diskInfo = &gmt->MediaInfo[0].DeviceSpecific.DiskInfo; if (diskInfo->MediaCharacteristics & MEDIA_READ_ONLY) { device->type |= FF_PHYSICALDISK_TYPE_READONLY; } else if (diskInfo->MediaCharacteristics & MEDIA_READ_WRITE) { device->type |= FF_PHYSICALDISK_TYPE_READWRITE; } } else { - __auto_type tapeInfo = &gmt->MediaInfo[0].DeviceSpecific.TapeInfo; + auto tapeInfo = &gmt->MediaInfo[0].DeviceSpecific.TapeInfo; if (tapeInfo->MediaCharacteristics & MEDIA_READ_ONLY) { device->type |= FF_PHYSICALDISK_TYPE_READONLY; } else if (tapeInfo->MediaCharacteristics & MEDIA_READ_WRITE) { @@ -275,7 +275,7 @@ static const char* detectPhysicalDisk(const char* physicalType, const wchar_t* s &dspd, sizeof(dspd), &retSize, - NULL) && + nullptr) && retSize == sizeof(dspd)) { device->type |= dspd.IncursSeekPenalty ? FF_PHYSICALDISK_TYPE_HDD : FF_PHYSICALDISK_TYPE_SSD; } @@ -293,14 +293,14 @@ static const char* detectPhysicalDisk(const char* physicalType, const wchar_t* s &stdd, sizeof(stdd), &retSize, - NULL) && + nullptr) && retSize == sizeof(stdd)) { device->temperature = stdd.TemperatureInfo[0].Temperature; } } } - return NULL; + return nullptr; } static void detectPhysicalDisksByInterfaceClass(const char* type, const GUID* interfaceClassGuid, FFlist* result, FFPhysicalDiskOptions* options) { @@ -308,20 +308,20 @@ static void detectPhysicalDisksByInterfaceClass(const char* type, const GUID* in if (CM_Get_Device_Interface_List_SizeW( &cchDeviceInterfaces, (LPGUID) interfaceClassGuid, - NULL, + nullptr, CM_GET_DEVICE_INTERFACE_LIST_PRESENT) != CR_SUCCESS || cchDeviceInterfaces <= 1) { return; } - wchar_t* FF_AUTO_FREE mszDeviceInterfaces = (wchar_t*) malloc(cchDeviceInterfaces * sizeof(wchar_t)); + FF_AUTO_FREE wchar_t* mszDeviceInterfaces = (wchar_t*) malloc(cchDeviceInterfaces * sizeof(wchar_t)); if (!mszDeviceInterfaces) { return; } if (CM_Get_Device_Interface_ListW( (LPGUID) interfaceClassGuid, - NULL, + nullptr, mszDeviceInterfaces, cchDeviceInterfaces, CM_GET_DEVICE_INTERFACE_LIST_PRESENT) != CR_SUCCESS) { @@ -331,8 +331,8 @@ static void detectPhysicalDisksByInterfaceClass(const char* type, const GUID* in // MULTI_SZ: "str1\0str2\0...\0\0" for (const wchar_t* p = mszDeviceInterfaces; *p; p += wcslen(p) + 1) { FF_DEBUG("Probing %s: %ls", type, p); - FF_A_UNUSED const char* error = detectPhysicalDisk(type, p, result, options); - if (error == NULL) { + [[maybe_unused]] const char* error = detectPhysicalDisk(type, p, result, options); + if (error == nullptr) { FF_DEBUG("Detected device \"%s\"", FF_LIST_LAST(FFPhysicalDiskResult, *result)->name.chars); } else { FF_DEBUG("Failed to detect device %s: %s", type, error); @@ -345,5 +345,5 @@ const char* ffDetectPhysicalDisk(FFlist* result, FFPhysicalDiskOptions* options) detectPhysicalDisksByInterfaceClass("Disk", &GUID_DEVINTERFACE_DISK, result, options); detectPhysicalDisksByInterfaceClass("CD-ROM", &GUID_DEVINTERFACE_CDROM, result, options); detectPhysicalDisksByInterfaceClass("Tape", &GUID_DEVINTERFACE_TAPE, result, options); - return NULL; + return nullptr; } diff --git a/src/detection/physicalmemory/physicalmemory.c b/src/detection/physicalmemory/physicalmemory.c index 0188e05447..ca1114141a 100644 --- a/src/detection/physicalmemory/physicalmemory.c +++ b/src/detection/physicalmemory/physicalmemory.c @@ -35,7 +35,7 @@ static inline const char* getVendorString(unsigned vendorId) { case 0x0467: return "Ramaxel"; default: - return NULL; + return nullptr; } } @@ -61,7 +61,7 @@ void FFPhysicalMemoryUpdateVendorString(FFPhysicalMemoryResult* device) { memcpy(vendorIdStr, device->vendor.chars, 4); } vendorIdStr[4] = '\0'; - char* pEnd = NULL; + char* pEnd = nullptr; uint32_t vendorId = (uint32_t) strtoul(vendorIdStr, &pEnd, 16); if (*pEnd != '\0') { return; diff --git a/src/detection/physicalmemory/physicalmemory_apple.m b/src/detection/physicalmemory/physicalmemory_apple.m index e35f53863f..c58c2f14bd 100644 --- a/src/detection/physicalmemory/physicalmemory_apple.m +++ b/src/detection/physicalmemory/physicalmemory_apple.m @@ -37,7 +37,7 @@ static void appendDevice( if (size) { - char* unit = NULL; + char* unit = nullptr; device->size = strtoul(size.UTF8String, &unit, 10); if (*unit == ' ') ++unit; @@ -52,7 +52,7 @@ static void appendDevice( if (speed) { - char* unit = NULL; + char* unit = nullptr; device->maxSpeed = (uint32_t) strtoul(speed.UTF8String, &unit, 10); if (*unit == ' ') ++unit; @@ -74,8 +74,8 @@ static void appendDevice( "-xml", "-detailLevel", "full", - NULL - }) != NULL) + nullptr + }) != nullptr) return "Starting `system_profiler SPMemoryDataType -xml -detailLevel full` failed"; NSArray* arr = [NSPropertyListSerialization propertyListWithData:[NSData dataWithBytes:buffer.chars length:buffer.length] @@ -118,10 +118,10 @@ static void appendDevice( } } - return NULL; + return nullptr; } -FF_A_UNUSED static const char* detectFromIokit(FFlist* result) +[[maybe_unused]] static const char* detectFromIokit(FFlist* result) { FF_IOOBJECT_AUTO_RELEASE io_registry_entry_t entryDevice = IORegistryEntryFromPath(MACH_PORT_NULL, "IODeviceTree:/chosen"); if (!entryDevice) @@ -149,14 +149,14 @@ static void appendDevice( ffCfStrGetString(dramType, &device->type); ffCfStrGetString(dramVendor, &device->vendor); ffCfNumGetInt64(dramSize, (int64_t*) &device->size); - return NULL; + return nullptr; } -const char* ffDetectPhysicalMemory(FF_A_UNUSED FFPhysicalMemoryOptions* options, FFlist* result) +const char* ffDetectPhysicalMemory([[maybe_unused]] FFPhysicalMemoryOptions* options, FFlist* result) { #if __aarch64__ - if (detectFromIokit(result) == NULL) - return NULL; + if (detectFromIokit(result) == nullptr) + return nullptr; #endif return detectFromSystemProfiler(result); diff --git a/src/detection/physicalmemory/physicalmemory_linux.c b/src/detection/physicalmemory/physicalmemory_linux.c index 02df7897ac..fe248be0c5 100644 --- a/src/detection/physicalmemory/physicalmemory_linux.c +++ b/src/detection/physicalmemory/physicalmemory_linux.c @@ -2,7 +2,7 @@ #include "common/smbios.h" // 7.18 -typedef struct FFSmbiosMemoryDevice { +typedef struct [[gnu::packed]] FFSmbiosMemoryDevice { FFSmbiosHeader Header; // 2.1+ @@ -59,7 +59,7 @@ typedef struct FFSmbiosMemoryDevice { uint16_t Pmic0RevisionNumber; // varies uint16_t RcdManufacturerID; // varies uint16_t RcdRevisionNumber; // varies -} FF_A_PACKED FFSmbiosMemoryDevice; +} FFSmbiosMemoryDevice; static_assert(offsetof(FFSmbiosMemoryDevice, RcdRevisionNumber) == 0x62, "FFSmbiosMemoryDevice: Wrong struct alignment"); @@ -129,7 +129,7 @@ const char* ffDetectPhysicalMemory(FFPhysicalMemoryOptions* options, FFlist* res } const char* formFactorNames[] = { - NULL, // 0x00 (Placeholder for indexing) + nullptr, // 0x00 (Placeholder for indexing) "Other", // 0x01 "Unknown", // 0x02 "SIMM", // 0x03 @@ -157,7 +157,7 @@ const char* ffDetectPhysicalMemory(FFPhysicalMemoryOptions* options, FFlist* res } const char* memoryTypeNames[] = { - NULL, // 0x00 (Placeholder for indexing) + nullptr, // 0x00 (Placeholder for indexing) "Other", // 0x01 "Unknown", // 0x02 "DRAM", // 0x03 @@ -231,5 +231,5 @@ const char* ffDetectPhysicalMemory(FFPhysicalMemoryOptions* options, FFlist* res } } - return NULL; + return nullptr; } diff --git a/src/detection/poweradapter/poweradapter_apple.c b/src/detection/poweradapter/poweradapter_apple.c index 9a5008abdb..444a7ae510 100644 --- a/src/detection/poweradapter/poweradapter_apple.c +++ b/src/detection/poweradapter/poweradapter_apple.c @@ -18,7 +18,7 @@ const char* ffDetectPowerAdapter(FFlist* results) { adapter->watts = 0; ffCfDictGetString(details, CFSTR(kIOPSNameKey), &adapter->name); - if (ffCfDictGetString(details, CFSTR("Model"), &adapter->modelName) != NULL) { + if (ffCfDictGetString(details, CFSTR("Model"), &adapter->modelName) != nullptr) { int adapterId; if (ffCfDictGetInt(details, CFSTR(kIOPSPowerAdapterIDKey), &adapterId) == 0) { ffStrbufSetF(&adapter->modelName, "%d", adapterId); @@ -26,7 +26,7 @@ const char* ffDetectPowerAdapter(FFlist* results) { } ffCfDictGetString(details, CFSTR("Manufacturer"), &adapter->manufacturer); ffCfDictGetString(details, CFSTR("Description"), &adapter->description); - if (ffCfDictGetString(details, CFSTR("SerialString"), &adapter->serial) != NULL) { + if (ffCfDictGetString(details, CFSTR("SerialString"), &adapter->serial) != nullptr) { int serialNumber; if (ffCfDictGetInt(details, CFSTR(kIOPSPowerAdapterSerialNumberKey), &serialNumber) == 0) { ffStrbufSetF(&adapter->serial, "%X", serialNumber); @@ -35,5 +35,5 @@ const char* ffDetectPowerAdapter(FFlist* results) { ffCfDictGetInt(details, CFSTR(kIOPSPowerAdapterWattsKey), &adapter->watts); } - return NULL; + return nullptr; } diff --git a/src/detection/poweradapter/poweradapter_linux.c b/src/detection/poweradapter/poweradapter_linux.c index fb555d5384..fd0abcc1dc 100644 --- a/src/detection/poweradapter/poweradapter_linux.c +++ b/src/detection/poweradapter/poweradapter_linux.c @@ -71,12 +71,12 @@ static void parsePowerAdapter(int dfd, const char* id, FFlist* results) { const char* ffDetectPowerAdapter(FFlist* results) { FF_AUTO_CLOSE_DIR DIR* dirp = opendir("/sys/class/power_supply/"); - if (dirp == NULL) { - return "opendir(\"/sys/class/power_supply/\") == NULL"; + if (dirp == nullptr) { + return "opendir(\"/sys/class/power_supply/\") == nullptr"; } struct dirent* entry; - while ((entry = readdir(dirp)) != NULL) { + while ((entry = readdir(dirp)) != nullptr) { if (entry->d_name[0] == '.') { continue; } @@ -87,5 +87,5 @@ const char* ffDetectPowerAdapter(FFlist* results) { } } - return NULL; + return nullptr; } diff --git a/src/detection/poweradapter/poweradapter_nosupport.c b/src/detection/poweradapter/poweradapter_nosupport.c index d5e725bf4f..0a1bcde8fc 100644 --- a/src/detection/poweradapter/poweradapter_nosupport.c +++ b/src/detection/poweradapter/poweradapter_nosupport.c @@ -1,5 +1,5 @@ #include "poweradapter.h" -const char* ffDetectPowerAdapter(FF_A_UNUSED FFlist* results) { +const char* ffDetectPowerAdapter([[maybe_unused]] FFlist* results) { return "Not supported on this platform"; } diff --git a/src/detection/processes/processes_bsd.c b/src/detection/processes/processes_bsd.c index e3f02b8db0..4d16bc3af2 100644 --- a/src/detection/processes/processes_bsd.c +++ b/src/detection/processes/processes_bsd.c @@ -14,10 +14,10 @@ const char* ffDetectProcesses(uint32_t* result) { int request[] = { CTL_KERN, KERN_PROC, KERN_PROC_PROC }; size_t length; - if (sysctl(request, ARRAY_SIZE(request), NULL, &length, NULL, 0) != 0) { + if (sysctl(request, ARRAY_SIZE(request), nullptr, &length, nullptr, 0) != 0) { return "sysctl({CTL_KERN, KERN_PROC, KERN_PROC_PROC}) failed"; } *result = (uint32_t) (length / sizeof(struct kinfo_proc)); - return NULL; + return nullptr; } diff --git a/src/detection/processes/processes_haiku.c b/src/detection/processes/processes_haiku.c index c50e62d531..0d960ab39e 100644 --- a/src/detection/processes/processes_haiku.c +++ b/src/detection/processes/processes_haiku.c @@ -10,5 +10,5 @@ const char* ffDetectProcesses(uint32_t* result) { *result = info.used_teams; - return NULL; + return nullptr; } diff --git a/src/detection/processes/processes_linux.c b/src/detection/processes/processes_linux.c index dee8c09517..78790c2ebc 100644 --- a/src/detection/processes/processes_linux.c +++ b/src/detection/processes/processes_linux.c @@ -5,14 +5,14 @@ const char* ffDetectProcesses(uint32_t* result) { FF_AUTO_CLOSE_DIR DIR* dir = opendir("/proc"); - if (dir == NULL) { + if (dir == nullptr) { return "opendir(\"/proc\") failed"; } uint32_t num = 0; struct dirent* entry; - while ((entry = readdir(dir)) != NULL) { + while ((entry = readdir(dir)) != nullptr) { if ( #ifdef _DIRENT_HAVE_D_TYPE (entry->d_type == DT_DIR || entry->d_type == DT_UNKNOWN) && @@ -23,5 +23,5 @@ const char* ffDetectProcesses(uint32_t* result) { *result = num; - return NULL; + return nullptr; } diff --git a/src/detection/processes/processes_nbsd.c b/src/detection/processes/processes_nbsd.c index efd3d6feb1..c3e7d047f1 100644 --- a/src/detection/processes/processes_nbsd.c +++ b/src/detection/processes/processes_nbsd.c @@ -6,10 +6,10 @@ const char* ffDetectProcesses(uint32_t* result) { int request[] = { CTL_KERN, KERN_PROC2, KERN_PROC_ALL, -1, sizeof(struct kinfo_proc2), 0 }; size_t length = 0; - if (sysctl(request, ARRAY_SIZE(request), NULL, &length, NULL, 0) != 0) { + if (sysctl(request, ARRAY_SIZE(request), nullptr, &length, nullptr, 0) != 0) { return "sysctl({CTL_KERN, KERN_PROC2, KERN_PROC_ALL}) failed"; } *result = (uint32_t) (length / sizeof(struct kinfo_proc2)); - return NULL; + return nullptr; } diff --git a/src/detection/processes/processes_obsd.c b/src/detection/processes/processes_obsd.c index 6246d8f8ab..5a5ba31f46 100644 --- a/src/detection/processes/processes_obsd.c +++ b/src/detection/processes/processes_obsd.c @@ -5,11 +5,11 @@ #include const char* ffDetectProcesses(uint32_t* result) { - kvm_t* kd = kvm_open(NULL, NULL, NULL, KVM_NO_FILES, NULL); + kvm_t* kd = kvm_open(nullptr, nullptr, nullptr, KVM_NO_FILES, nullptr); const void* ret = kvm_getprocs(kd, KERN_PROC_ALL, 0, 1, result); kvm_close(kd); if (!ret) { return "kvm_getprocs() failed"; } - return NULL; + return nullptr; } diff --git a/src/detection/processes/processes_windows.c b/src/detection/processes/processes_windows.c index 03b34db987..78ed840b46 100644 --- a/src/detection/processes/processes_windows.c +++ b/src/detection/processes/processes_windows.c @@ -5,7 +5,7 @@ #include const char* ffDetectProcesses(uint32_t* result) { - SYSTEM_PROCESS_INFORMATION* FF_AUTO_FREE pstart = NULL; + FF_AUTO_FREE SYSTEM_PROCESS_INFORMATION* pstart = nullptr; // Multiple attempts in case processes change while // we are in the middle of querying them. @@ -30,5 +30,5 @@ const char* ffDetectProcesses(uint32_t* result) { ++*result; } - return NULL; + return nullptr; } diff --git a/src/detection/publicip/publicip.c b/src/detection/publicip/publicip.c index abca57c3e1..c0e8afb478 100644 --- a/src/detection/publicip/publicip.c +++ b/src/detection/publicip/publicip.c @@ -19,7 +19,7 @@ void ffPreparePublicIp(FFPublicIPOptions* options) { if (options->url.length == 0) { state->compression = true; state->tfo = true; - *status = ffNetworkingSendHttpRequest(state, options->ipv6 ? "v6.ipinfo.io" : "ipinfo.io", "/json", NULL); + *status = ffNetworkingSendHttpRequest(state, options->ipv6 ? "v6.ipinfo.io" : "ipinfo.io", "/json", nullptr); } else { FF_STRBUF_AUTO_DESTROY host = ffStrbufCreateCopy(&options->url); uint32_t hostStartIndex = ffStrbufFirstIndexS(&host, "://"); @@ -34,12 +34,11 @@ void ffPreparePublicIp(FFPublicIPOptions* options) { FF_STRBUF_AUTO_DESTROY path = ffStrbufCreate(); if (pathStartIndex != host.length) { - ffStrbufAppendNS(&path, pathStartIndex, host.chars + (host.length - pathStartIndex)); - host.length = pathStartIndex; - host.chars[pathStartIndex] = '\0'; + ffStrbufAppendNS(&path, host.length - pathStartIndex, host.chars + pathStartIndex); + ffStrbufSubstrBefore(&host, pathStartIndex); } - *status = ffNetworkingSendHttpRequest(state, host.chars, path.length == 0 ? "/" : path.chars, NULL); + *status = ffNetworkingSendHttpRequest(state, host.chars, path.length == 0 ? "/" : path.chars, nullptr); } } @@ -57,7 +56,7 @@ const char* ffDetectPublicIp(FFPublicIPOptions* options, FFPublicIpResult* resul ffPreparePublicIp(options); } - if (*status != NULL) { + if (*status != nullptr) { return *status; } @@ -67,7 +66,7 @@ const char* ffDetectPublicIp(FFPublicIPOptions* options, FFPublicIpResult* resul *state = (FFNetworkingState) {}; *status = FF_UNINITIALIZED; - if (error == NULL) { + if (error == nullptr) { ffStrbufSubstrAfterFirstS(&response, "\r\n\r\n"); } else { return error; @@ -78,18 +77,18 @@ const char* ffDetectPublicIp(FFPublicIPOptions* options, FFPublicIpResult* resul } if (options->url.length == 0) { - yyjson_doc* FF_A_CLEANUP(wrapYyjsonFree) doc = yyjson_read_opts(response.chars, response.length, 0, NULL, NULL); + [[gnu::cleanup(wrapYyjsonFree)]] yyjson_doc* doc = yyjson_read_opts(response.chars, response.length, 0, nullptr, nullptr); if (doc) { yyjson_val* root = yyjson_doc_get_root(doc); ffStrbufAppendJsonVal(&result->ip, yyjson_obj_get(root, "ip")); ffStrbufDestroy(&result->location); ffStrbufInitF(&result->location, "%s, %s", yyjson_get_str(yyjson_obj_get(root, "city")), yyjson_get_str(yyjson_obj_get(root, "country"))); - return NULL; + return nullptr; } } ffStrbufDestroy(&result->ip); ffStrbufInitMove(&result->ip, &response); ffStrbufTrimRightSpace(&result->ip); - return NULL; + return nullptr; } diff --git a/src/detection/sound/sound_apple.c b/src/detection/sound/sound_apple.c index aaacf78eb5..36ebb2a8b7 100644 --- a/src/detection/sound/sound_apple.c +++ b/src/detection/sound/sound_apple.c @@ -11,7 +11,7 @@ const char* ffDetectSound(FFSoundOptions* options, FFlist* devices /* List of FFSoundDevice */) { AudioDeviceID mainDeviceId; UInt32 dataSize = sizeof(mainDeviceId); - if (AudioObjectGetPropertyData(kAudioObjectSystemObject, &(AudioObjectPropertyAddress) { kAudioHardwarePropertyDefaultOutputDevice, kAudioObjectPropertyScopeOutput, kAudioObjectPropertyElementMain }, 0, NULL, &dataSize, &mainDeviceId) != kAudioHardwareNoError) { + if (AudioObjectGetPropertyData(kAudioObjectSystemObject, &(AudioObjectPropertyAddress) { kAudioHardwarePropertyDefaultOutputDevice, kAudioObjectPropertyScopeOutput, kAudioObjectPropertyElementMain }, 0, nullptr, &dataSize, &mainDeviceId) != kAudioHardwareNoError) { return "AudioObjectGetPropertyData(kAudioHardwarePropertyDefaultOutputDevice) failed"; } @@ -21,7 +21,7 @@ const char* ffDetectSound(FFSoundOptions* options, FFlist* devices /* List of FF dataSize = sizeof(mainDeviceId); } else { dataSize = sizeof(deviceIds); - if (AudioObjectGetPropertyData(kAudioObjectSystemObject, &(AudioObjectPropertyAddress) { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeOutput, kAudioObjectPropertyElementMain }, 0, NULL, &dataSize, &deviceIds) != kAudioHardwareNoError) { + if (AudioObjectGetPropertyData(kAudioObjectSystemObject, &(AudioObjectPropertyAddress) { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeOutput, kAudioObjectPropertyElementMain }, 0, nullptr, &dataSize, &deviceIds) != kAudioHardwareNoError) { return "AudioObjectGetPropertyData(kAudioHardwarePropertyDevices) failed"; } } @@ -30,16 +30,16 @@ const char* ffDetectSound(FFSoundOptions* options, FFlist* devices /* List of FF AudioDeviceID deviceId = deviceIds[index]; // Ignore input devices - if (AudioObjectGetPropertyDataSize(deviceId, &(AudioObjectPropertyAddress) { kAudioDevicePropertyStreams, kAudioObjectPropertyScopeInput, kAudioObjectPropertyElementMain }, 0, NULL, &dataSize) == kAudioHardwareNoError && dataSize > 0) { + if (AudioObjectGetPropertyDataSize(deviceId, &(AudioObjectPropertyAddress) { kAudioDevicePropertyStreams, kAudioObjectPropertyScopeInput, kAudioObjectPropertyElementMain }, 0, nullptr, &dataSize) == kAudioHardwareNoError && dataSize > 0) { continue; } uint32_t dataSource; dataSize = sizeof(dataSource); - if (AudioObjectGetPropertyData(deviceId, &(AudioObjectPropertyAddress) { kAudioDevicePropertyDataSource, kAudioObjectPropertyScopeOutput, kAudioObjectPropertyElementMain }, 0, NULL, &dataSize, &dataSource) == kAudioHardwareNoError && dataSource == 'hdpn') { + if (AudioObjectGetPropertyData(deviceId, &(AudioObjectPropertyAddress) { kAudioDevicePropertyDataSource, kAudioObjectPropertyScopeOutput, kAudioObjectPropertyElementMain }, 0, nullptr, &dataSize, &dataSource) == kAudioHardwareNoError && dataSource == 'hdpn') { uint32_t connected; dataSize = sizeof(connected); - if (AudioObjectGetPropertyData(deviceId, &(AudioObjectPropertyAddress) { kAudioDevicePropertyJackIsConnected, kAudioObjectPropertyScopeOutput, kAudioObjectPropertyElementMain }, 0, NULL, &dataSize, &connected) == kAudioHardwareNoError) { + if (AudioObjectGetPropertyData(deviceId, &(AudioObjectPropertyAddress) { kAudioDevicePropertyJackIsConnected, kAudioObjectPropertyScopeOutput, kAudioObjectPropertyElementMain }, 0, nullptr, &dataSize, &connected) == kAudioHardwareNoError) { if (!connected) { continue; } @@ -48,7 +48,7 @@ const char* ffDetectSound(FFSoundOptions* options, FFlist* devices /* List of FF uint32_t active = true; dataSize = sizeof(active); - if (AudioObjectGetPropertyData(deviceId, &(AudioObjectPropertyAddress) { kAudioDevicePropertyDeviceIsAlive, kAudioObjectPropertyScopeOutput, kAudioObjectPropertyElementMain }, 0, NULL, &dataSize, &active) == kAudioHardwareNoError) { + if (AudioObjectGetPropertyData(deviceId, &(AudioObjectPropertyAddress) { kAudioDevicePropertyDeviceIsAlive, kAudioObjectPropertyScopeOutput, kAudioObjectPropertyElementMain }, 0, nullptr, &dataSize, &active) == kAudioHardwareNoError) { if ((options->soundType & FF_SOUND_TYPE_ACTIVE) && !active) { continue; } @@ -62,17 +62,17 @@ const char* ffDetectSound(FFSoundOptions* options, FFlist* devices /* List of FF ffStrbufInit(&device->name); ffStrbufInitStatic(&device->platformApi, "Core Audio"); - FF_CFTYPE_AUTO_RELEASE CFStringRef uid = NULL; + FF_CFTYPE_AUTO_RELEASE CFStringRef uid = nullptr; dataSize = sizeof(uid); - if (AudioObjectGetPropertyData(deviceId, &(AudioObjectPropertyAddress) { kAudioDevicePropertyDeviceUID, kAudioObjectPropertyScopeOutput, kAudioObjectPropertyElementMain }, 0, NULL, &dataSize, &uid) == kAudioHardwareNoError) { + if (AudioObjectGetPropertyData(deviceId, &(AudioObjectPropertyAddress) { kAudioDevicePropertyDeviceUID, kAudioObjectPropertyScopeOutput, kAudioObjectPropertyElementMain }, 0, nullptr, &dataSize, &uid) == kAudioHardwareNoError) { ffCfStrGetString(uid, &device->identifier); } else { ffStrbufAppendF(&device->identifier, "ID-%u", (unsigned) deviceId); } - FF_CFTYPE_AUTO_RELEASE CFStringRef name = NULL; + FF_CFTYPE_AUTO_RELEASE CFStringRef name = nullptr; dataSize = sizeof(name); - if (AudioObjectGetPropertyData(deviceId, &(AudioObjectPropertyAddress) { kAudioObjectPropertyName, kAudioObjectPropertyScopeOutput, kAudioObjectPropertyElementMain }, 0, NULL, &dataSize, &name) == kAudioHardwareNoError) { + if (AudioObjectGetPropertyData(deviceId, &(AudioObjectPropertyAddress) { kAudioObjectPropertyName, kAudioObjectPropertyScopeOutput, kAudioObjectPropertyElementMain }, 0, nullptr, &dataSize, &name) == kAudioHardwareNoError) { ffCfStrGetString(name, &device->name); } else { ffStrbufSet(&device->name, &device->identifier); @@ -80,7 +80,7 @@ const char* ffDetectSound(FFSoundOptions* options, FFlist* devices /* List of FF uint32_t muted; dataSize = sizeof(muted); - if (AudioObjectGetPropertyData(deviceId, &(AudioObjectPropertyAddress) { kAudioDevicePropertyMute, kAudioObjectPropertyScopeOutput, kAudioObjectPropertyElementMain }, 0, NULL, &dataSize, &muted) != kAudioHardwareNoError) { + if (AudioObjectGetPropertyData(deviceId, &(AudioObjectPropertyAddress) { kAudioDevicePropertyMute, kAudioObjectPropertyScopeOutput, kAudioObjectPropertyElementMain }, 0, nullptr, &dataSize, &muted) != kAudioHardwareNoError) { muted = false; // Device may not support volume control } @@ -89,17 +89,17 @@ const char* ffDetectSound(FFSoundOptions* options, FFlist* devices /* List of FF } else { float volume; dataSize = sizeof(volume); - if (AudioObjectGetPropertyData(deviceId, &(AudioObjectPropertyAddress) { kAudioDevicePropertyVolumeScalar, kAudioObjectPropertyScopeOutput, kAudioObjectPropertyElementMain }, 0, NULL, &dataSize, &volume) == kAudioHardwareNoError) { + if (AudioObjectGetPropertyData(deviceId, &(AudioObjectPropertyAddress) { kAudioDevicePropertyVolumeScalar, kAudioObjectPropertyScopeOutput, kAudioObjectPropertyElementMain }, 0, nullptr, &dataSize, &volume) == kAudioHardwareNoError) { device->volume = (uint8_t) (volume * 100 + 0.5); } else { // Try detecting volume from channels uint32_t channels[2]; dataSize = sizeof(channels); - if (AudioObjectGetPropertyData(deviceId, &(AudioObjectPropertyAddress) { kAudioDevicePropertyPreferredChannelsForStereo, kAudioObjectPropertyScopeOutput, kAudioObjectPropertyElementMain }, 0, NULL, &dataSize, channels) == kAudioHardwareNoError) { + if (AudioObjectGetPropertyData(deviceId, &(AudioObjectPropertyAddress) { kAudioDevicePropertyPreferredChannelsForStereo, kAudioObjectPropertyScopeOutput, kAudioObjectPropertyElementMain }, 0, nullptr, &dataSize, channels) == kAudioHardwareNoError) { dataSize = sizeof(volume); - if (AudioObjectGetPropertyData(deviceId, &(AudioObjectPropertyAddress) { kAudioDevicePropertyVolumeScalar, kAudioObjectPropertyScopeOutput, channels[0] }, 0, NULL, &dataSize, &volume) == kAudioHardwareNoError) { + if (AudioObjectGetPropertyData(deviceId, &(AudioObjectPropertyAddress) { kAudioDevicePropertyVolumeScalar, kAudioObjectPropertyScopeOutput, channels[0] }, 0, nullptr, &dataSize, &volume) == kAudioHardwareNoError) { float temp; - if (AudioObjectGetPropertyData(deviceId, &(AudioObjectPropertyAddress) { kAudioDevicePropertyVolumeScalar, kAudioObjectPropertyScopeOutput, channels[1] }, 0, NULL, &dataSize, &temp) == kAudioHardwareNoError) { + if (AudioObjectGetPropertyData(deviceId, &(AudioObjectPropertyAddress) { kAudioDevicePropertyVolumeScalar, kAudioObjectPropertyScopeOutput, channels[1] }, 0, nullptr, &dataSize, &temp) == kAudioHardwareNoError) { device->volume = (uint8_t) ((volume + temp) / 2 * 100 + 0.5); } } @@ -108,5 +108,5 @@ const char* ffDetectSound(FFSoundOptions* options, FFlist* devices /* List of FF } } - return NULL; + return nullptr; } diff --git a/src/detection/sound/sound_bsd.c b/src/detection/sound/sound_bsd.c index cbac86848e..118b33b091 100644 --- a/src/detection/sound/sound_bsd.c +++ b/src/detection/sound/sound_bsd.c @@ -86,5 +86,5 @@ const char* ffDetectSound(FFSoundOptions* options, FFlist* devices) { device->type = FF_SOUND_TYPE_ACTIVE | (isMain ? FF_SOUND_TYPE_MAIN : FF_SOUND_TYPE_NONE); } - return NULL; + return nullptr; } diff --git a/src/detection/sound/sound_haiku.cpp b/src/detection/sound/sound_haiku.cpp index d69602e02e..e2cc4c18fe 100644 --- a/src/detection/sound/sound_haiku.cpp +++ b/src/detection/sound/sound_haiku.cpp @@ -7,14 +7,14 @@ extern "C" { #include #include -const char* ffDetectSound(FF_A_UNUSED FFSoundOptions* options, FFlist* devices /* List of FFSoundDevice */) { +const char* ffDetectSound([[maybe_unused]] FFSoundOptions* options, FFlist* devices /* List of FFSoundDevice */) { BMediaRoster* roster = BMediaRoster::Roster(); media_node mediaNode; live_node_info liveInfo; dormant_node_info dormantInfo; if (roster->GetAudioOutput(&mediaNode) != B_OK) { - return NULL; + return nullptr; } FFSoundDevice* device = FF_LIST_ADD(FFSoundDevice, *devices); @@ -36,20 +36,20 @@ const char* ffDetectSound(FF_A_UNUSED FFSoundOptions* options, FFlist* devices / media_node mixer; if (roster->GetAudioMixer(&mixer) != B_OK) { - return NULL; + return nullptr; } BParameterWeb* web; status_t status = roster->GetParameterWebFor(mixer, &web); roster->ReleaseNode(mixer); // the web is all we need :-) if (status != B_OK) { - return NULL; + return nullptr; } - BContinuousParameter* gain = NULL; - BParameter* mute = NULL; + BContinuousParameter* gain = nullptr; + BParameter* mute = nullptr; BParameter* parameter; - for (int32 index = 0; (parameter = web->ParameterAt(index)) != NULL; index++) { + for (int32 index = 0; (parameter = web->ParameterAt(index)) != nullptr; index++) { // assume the mute preceding master gain control if (ffStrEquals(parameter->Kind(), B_MUTE)) { mute = parameter; @@ -63,8 +63,8 @@ const char* ffDetectSound(FF_A_UNUSED FFSoundOptions* options, FFlist* devices / } } - if (gain == NULL) { - return NULL; + if (gain == nullptr) { + return nullptr; } bigtime_t when; @@ -74,7 +74,7 @@ const char* ffDetectSound(FF_A_UNUSED FFSoundOptions* options, FFlist* devices / int32 isMute = false; size = sizeof(isMute); if (mute->GetValue(&isMute, &size, &when) == B_OK && isMute) { - return NULL; + return nullptr; } } @@ -84,5 +84,5 @@ const char* ffDetectSound(FF_A_UNUSED FFSoundOptions* options, FFlist* devices / device->volume = (uint8_t) (100 * (volume - gain->MinValue()) / (gain->MaxValue() - gain->MinValue())); } - return NULL; + return nullptr; } diff --git a/src/detection/sound/sound_linux.c b/src/detection/sound/sound_linux.c index 8af7e93c83..7deb1b5f4c 100644 --- a/src/detection/sound/sound_linux.c +++ b/src/detection/sound/sound_linux.c @@ -11,7 +11,7 @@ struct DetectionInfoBundle { FFSoundOptions* options; }; -static void paSinkInfoCallback(FF_A_UNUSED pa_context* c, const pa_sink_info* i, int eol, void* userdata) { +static void paSinkInfoCallback([[maybe_unused]] pa_context* c, const pa_sink_info* i, int eol, void* userdata) { if (eol > 0 || !i) { return; } @@ -39,7 +39,7 @@ static void paSinkInfoCallback(FF_A_UNUSED pa_context* c, const pa_sink_info* i, device->type = (isMain ? FF_SOUND_TYPE_MAIN : FF_SOUND_TYPE_NONE) | (isActive ? FF_SOUND_TYPE_ACTIVE : FF_SOUND_TYPE_NONE); } -static void paServerInfoCallback(FF_A_UNUSED pa_context* c, const pa_server_info* i, void* userdata) { +static void paServerInfoCallback([[maybe_unused]] pa_context* c, const pa_server_info* i, void* userdata) { if (!i) { return; } @@ -96,9 +96,9 @@ static const char* detectSound(FFSoundOptions* options, FFlist* devices) { .result = devices, .options = options, }; - const char* error = NULL; + const char* error = nullptr; - if (ffpa_context_connect(context, NULL, PA_CONTEXT_NOFLAGS, NULL) < 0) { + if (ffpa_context_connect(context, nullptr, PA_CONTEXT_NOFLAGS, nullptr) < 0) { error = "Failed to connect to pulseaudio context"; goto exit; } @@ -110,7 +110,7 @@ static const char* detectSound(FFSoundOptions* options, FFlist* devices) { goto exit; } - ffpa_mainloop_iterate(mainloop, 1, NULL); + ffpa_mainloop_iterate(mainloop, 1, nullptr); } { @@ -120,7 +120,7 @@ static const char* detectSound(FFSoundOptions* options, FFlist* devices) { goto exit; } while (ffpa_operation_get_state(operation) == PA_OPERATION_RUNNING) { - ffpa_mainloop_iterate(mainloop, 1, NULL); + ffpa_mainloop_iterate(mainloop, 1, nullptr); } ffpa_operation_unref(operation); @@ -138,7 +138,7 @@ static const char* detectSound(FFSoundOptions* options, FFlist* devices) { ffpa_operation_cancel(operation); } - ffpa_mainloop_iterate(mainloop, 1, NULL); + ffpa_mainloop_iterate(mainloop, 1, nullptr); } ffpa_operation_unref(operation); diff --git a/src/detection/sound/sound_nbsd.c b/src/detection/sound/sound_nbsd.c index efd276eac2..f52ba2cfe4 100644 --- a/src/detection/sound/sound_nbsd.c +++ b/src/detection/sound/sound_nbsd.c @@ -54,5 +54,5 @@ const char* ffDetectSound(FFSoundOptions* options, FFlist* devices) { device->type = FF_SOUND_TYPE_ACTIVE | (isMain ? FF_SOUND_TYPE_MAIN : FF_SOUND_TYPE_NONE); } - return NULL; + return nullptr; } diff --git a/src/detection/sound/sound_nosupport.c b/src/detection/sound/sound_nosupport.c index b67236082e..b04530f9eb 100644 --- a/src/detection/sound/sound_nosupport.c +++ b/src/detection/sound/sound_nosupport.c @@ -1,5 +1,5 @@ #include "sound.h" -const char* ffDetectSound(FF_A_UNUSED FFlist* devices /* List of FFSoundDevice */) { +const char* ffDetectSound([[maybe_unused]] FFlist* devices /* List of FFSoundDevice */) { return "Not supported on this platform"; } diff --git a/src/detection/sound/sound_obsd.c b/src/detection/sound/sound_obsd.c index a6dd6df405..e2c4238b5d 100644 --- a/src/detection/sound/sound_obsd.c +++ b/src/detection/sound/sound_obsd.c @@ -57,7 +57,7 @@ static void enumerate_props(FFSoundDeviceBundle* bundle, struct sioctl_desc* des } const char* ffDetectSound(FFSoundOptions* options, FFlist* devices) { - FF_A_CLEANUP(close_hdl) struct sioctl_hdl* hdl = sioctl_open(SIO_DEVANY, SIOCTL_READ, 0); + [[gnu::cleanup(close_hdl)]] struct sioctl_hdl* hdl = sioctl_open(SIO_DEVANY, SIOCTL_READ, 0); if (!hdl) { return "sio_open() failed"; } @@ -86,5 +86,5 @@ const char* ffDetectSound(FFSoundOptions* options, FFlist* devices) { } device->volume = (uint8_t) ((totalLevel * 100 + bundle.iLevel / 2) / bundle.iLevel); - return NULL; + return nullptr; } diff --git a/src/detection/sound/sound_sunos.c b/src/detection/sound/sound_sunos.c index 7c84e55cb2..3f5e2219e9 100644 --- a/src/detection/sound/sound_sunos.c +++ b/src/detection/sound/sound_sunos.c @@ -105,5 +105,5 @@ const char* ffDetectSound(FFSoundOptions* options, FFlist* devices) { (isMain ? FF_SOUND_TYPE_MAIN : FF_SOUND_TYPE_NONE); } - return NULL; + return nullptr; } diff --git a/src/detection/sound/sound_windows.cpp b/src/detection/sound/sound_windows.cpp index 6d6307a5db..59823a0b8d 100644 --- a/src/detection/sound/sound_windows.cpp +++ b/src/detection/sound/sound_windows.cpp @@ -11,21 +11,21 @@ extern "C" { #include static void ffCoTaskMemFreeWrapper(void* pptr) { - assert(pptr != NULL); + assert(pptr != nullptr); void* ptr = *(void**) pptr; if (ptr) { CoTaskMemFree(ptr); } } -#define FF_COTASK_AUTO_FREE FF_A_CLEANUP(ffCoTaskMemFreeWrapper) +#define FF_COTASK_AUTO_FREE [[gnu::cleanup(ffCoTaskMemFreeWrapper)]] static const char* detectSoundDevice(FFlist* devices /* List of FFSoundDevice */, IMMDevice* immDevice, LPWSTR mainDeviceId) { - LPWSTR FF_COTASK_AUTO_FREE immDeviceId = NULL; + FF_COTASK_AUTO_FREE LPWSTR immDeviceId = nullptr; if (FAILED(immDevice->GetId(&immDeviceId))) { return "immDevice->GetId() failed"; } - IPropertyStore* FF_AUTO_RELEASE_COM_OBJECT immPropStore = NULL; + FF_AUTO_RELEASE_COM_OBJECT IPropertyStore* immPropStore = nullptr; if (FAILED(immDevice->OpenPropertyStore(STGM_READ, &immPropStore))) { return "immDevice->OpenPropertyStore() failed"; } @@ -54,8 +54,8 @@ static const char* detectSoundDevice(FFlist* devices /* List of FFSoundDevice */ } } - IAudioEndpointVolume* FF_AUTO_RELEASE_COM_OBJECT immEndpointVolume = NULL; - if (SUCCEEDED(immDevice->Activate(IID_IAudioEndpointVolume, CLSCTX_ALL, NULL, (void**) &immEndpointVolume))) { + FF_AUTO_RELEASE_COM_OBJECT IAudioEndpointVolume* immEndpointVolume = nullptr; + if (SUCCEEDED(immDevice->Activate(IID_IAudioEndpointVolume, CLSCTX_ALL, nullptr, (void**) &immEndpointVolume))) { BOOL muted; if (FAILED(immEndpointVolume->GetMute(&muted)) || !muted) { FLOAT volume; @@ -65,7 +65,7 @@ static const char* detectSoundDevice(FFlist* devices /* List of FFSoundDevice */ } } - return NULL; + return nullptr; } const char* ffDetectSound(FFSoundOptions* options, FFlist* devices /* List of FFSoundDevice */) { @@ -74,23 +74,23 @@ const char* ffDetectSound(FFSoundOptions* options, FFlist* devices /* List of FF return error; } - IMMDeviceEnumerator* FF_AUTO_RELEASE_COM_OBJECT pEnum = NULL; + FF_AUTO_RELEASE_COM_OBJECT IMMDeviceEnumerator* pEnum = nullptr; - if (FAILED(CoCreateInstance(CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, IID_PPV_ARGS(&pEnum)))) { + if (FAILED(CoCreateInstance(CLSID_MMDeviceEnumerator, nullptr, CLSCTX_ALL, IID_PPV_ARGS(&pEnum)))) { return "CoCreateInstance(CLSID_MMDeviceEnumerator) failed"; } - LPWSTR FF_COTASK_AUTO_FREE mainDeviceId = NULL; + FF_COTASK_AUTO_FREE LPWSTR mainDeviceId = nullptr; { - IMMDevice* FF_AUTO_RELEASE_COM_OBJECT pDefaultDevice = NULL; + FF_AUTO_RELEASE_COM_OBJECT IMMDevice* pDefaultDevice = nullptr; if (FAILED(pEnum->GetDefaultAudioEndpoint(eRender, eMultimedia, &pDefaultDevice))) { return "GetDefaultAudioEndpoint() failed"; } if (options->soundType & FF_SOUND_TYPE_MAIN) { - return detectSoundDevice(devices, pDefaultDevice, NULL); + return detectSoundDevice(devices, pDefaultDevice, nullptr); } if (FAILED(pDefaultDevice->GetId(&mainDeviceId))) { @@ -98,7 +98,7 @@ const char* ffDetectSound(FFSoundOptions* options, FFlist* devices /* List of FF } } - IMMDeviceCollection* FF_AUTO_RELEASE_COM_OBJECT pDevices = NULL; + FF_AUTO_RELEASE_COM_OBJECT IMMDeviceCollection* pDevices = nullptr; if (FAILED(pEnum->EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE | (options->soundType & FF_SOUND_TYPE_ACTIVE ? 0 : DEVICE_STATE_DISABLED), &pDevices))) { return "EnumAudioEndpoints() failed"; @@ -110,7 +110,7 @@ const char* ffDetectSound(FFSoundOptions* options, FFlist* devices /* List of FF } for (uint32_t deviceIdx = 0; deviceIdx < deviceCount; ++deviceIdx) { - IMMDevice* FF_AUTO_RELEASE_COM_OBJECT immDevice = NULL; + FF_AUTO_RELEASE_COM_OBJECT IMMDevice* immDevice = nullptr; if (FAILED(pDevices->Item(deviceIdx, &immDevice))) { continue; } @@ -118,5 +118,5 @@ const char* ffDetectSound(FFSoundOptions* options, FFlist* devices /* List of FF detectSoundDevice(devices, immDevice, mainDeviceId); } - return NULL; + return nullptr; } diff --git a/src/detection/swap/swap_apple.c b/src/detection/swap/swap_apple.c index 40dda49007..3c457c0ec6 100644 --- a/src/detection/swap/swap_apple.c +++ b/src/detection/swap/swap_apple.c @@ -6,7 +6,7 @@ const char* ffDetectSwap(FFlist* result) { struct xsw_usage xsw; size_t size = sizeof(xsw); - if (sysctl((int[]) { CTL_VM, VM_SWAPUSAGE }, 2, &xsw, &size, NULL, 0) != 0) { + if (sysctl((int[]) { CTL_VM, VM_SWAPUSAGE }, 2, &xsw, &size, nullptr, 0) != 0) { return "Failed to read vm.swapusage"; } @@ -15,7 +15,7 @@ const char* ffDetectSwap(FFlist* result) { // "vm.compressor_mode" no longer exists in macOS 26.0 } else { if (ffSysctlGetInt("vm.compressor_mode", 4) <= 2) { - return NULL; // Swap is disabled + return nullptr; // Swap is disabled } } } @@ -24,5 +24,5 @@ const char* ffDetectSwap(FFlist* result) { ffStrbufInitStatic(&swap->name, xsw.xsu_encrypted ? "Encrypted" : "Normal"); swap->bytesTotal = xsw.xsu_total; swap->bytesUsed = xsw.xsu_used; - return NULL; + return nullptr; } diff --git a/src/detection/swap/swap_bsd.c b/src/detection/swap/swap_bsd.c index a54cd5252a..0172d3c03c 100644 --- a/src/detection/swap/swap_bsd.c +++ b/src/detection/swap/swap_bsd.c @@ -25,7 +25,7 @@ static void addSwapEntry(FFlist* result, struct xswdev* xsw, uint32_t pageSize) const char* ffDetectSwap(FFlist* result) { struct xswdev xsws[32]; size_t size = sizeof(xsws); - if (sysctlbyname("vm.swap_info_array", xsws, &size, NULL, 0) < 0) { + if (sysctlbyname("vm.swap_info_array", xsws, &size, nullptr, 0) < 0) { return "sysctlbyname(\"vm.swap_info_array\") failed"; } @@ -33,7 +33,7 @@ const char* ffDetectSwap(FFlist* result) { size_t count = size / sizeof(struct xswdev); if (count == 0) { - return NULL; + return nullptr; } if (xsws->xsw_version != XSWDEV_VERSION) { @@ -44,7 +44,7 @@ const char* ffDetectSwap(FFlist* result) { addSwapEntry(result, &xsws[i], pageSize); } - return NULL; + return nullptr; } #elif __FreeBSD__ @@ -62,7 +62,7 @@ const char* ffDetectSwap(FFlist* result) { mib[mibsize] = n; struct xswdev xsw; size_t size = sizeof(xsw); - if (sysctl(mib, (uint32_t) (mibsize + 1), &xsw, &size, NULL, 0) < 0) { + if (sysctl(mib, (uint32_t) (mibsize + 1), &xsw, &size, nullptr, 0) < 0) { break; } if (xsw.xsw_version != XSWDEV_VERSION) { @@ -72,7 +72,7 @@ const char* ffDetectSwap(FFlist* result) { addSwapEntry(result, &xsw, pageSize); } - return NULL; + return nullptr; } #endif diff --git a/src/detection/swap/swap_haiku.c b/src/detection/swap/swap_haiku.c index 8a3b08cbe2..cc8f855c6e 100644 --- a/src/detection/swap/swap_haiku.c +++ b/src/detection/swap/swap_haiku.c @@ -14,7 +14,7 @@ const char* ffDetectSwap(FFlist* result) { ffStrbufInitStatic(&swap->name, "System"); void* kvms = load_driver_settings("virtual_memory"); // /boot/home/config/settings/kernel/drivers/virtual_memory if (kvms) { - const char* swapAuto = get_driver_parameter(kvms, "swap_auto", NULL, NULL); + const char* swapAuto = get_driver_parameter(kvms, "swap_auto", nullptr, nullptr); if (swapAuto) { ffStrbufSetStatic(&swap->name, swapAuto[0] == 'y' ? "Auto" : "Manual"); } @@ -23,5 +23,5 @@ const char* ffDetectSwap(FFlist* result) { swap->bytesTotal = pageSize * (uint64_t) info.max_swap_pages; swap->bytesUsed = pageSize * (uint64_t) (info.max_swap_pages - info.free_swap_pages); - return NULL; + return nullptr; } diff --git a/src/detection/swap/swap_linux.c b/src/detection/swap/swap_linux.c index b31f268bfa..d72125d782 100644 --- a/src/detection/swap/swap_linux.c +++ b/src/detection/swap/swap_linux.c @@ -17,13 +17,13 @@ static const char* detectByProcMeminfo(FFlist* result) { uint64_t swapTotal = 0, swapFree = 0; - char* token = NULL; - if ((token = strstr(buf, "SwapTotal:")) != NULL) { - swapTotal = strtoul(token + strlen("SwapTotal:"), NULL, 10); + char* token = nullptr; + if ((token = strstr(buf, "SwapTotal:")) != nullptr) { + swapTotal = strtoul(token + strlen("SwapTotal:"), nullptr, 10); } - if ((token = strstr(buf, "SwapFree:")) != NULL) { - swapFree = strtoul(token + strlen("SwapFree:"), NULL, 10); + if ((token = strstr(buf, "SwapFree:")) != nullptr) { + swapFree = strtoul(token + strlen("SwapFree:"), nullptr, 10); } FFSwapResult* swap = FF_LIST_ADD(FFSwapResult, *result); @@ -31,7 +31,7 @@ static const char* detectByProcMeminfo(FFlist* result) { swap->bytesTotal = swapTotal * 1024lu; swap->bytesUsed = (swapTotal - swapFree) * 1024lu; - return NULL; + return nullptr; } static const char* detectByProcSwaps(FFlist* result) { @@ -59,7 +59,7 @@ static const char* detectByProcSwaps(FFlist* result) { for (size_t i = 0; i < nameLen; ++i) { if (name[i] == '\\') { char octal[4] = { name[i + 1], name[i + 2], name[i + 3], '\0' }; - ffStrbufAppendC(&swap->name, (char) strtol(octal, NULL, 8)); + ffStrbufAppendC(&swap->name, (char) strtol(octal, nullptr, 8)); i += 3; } else { ffStrbufAppendC(&swap->name, name[i]); @@ -71,12 +71,12 @@ static const char* detectByProcSwaps(FFlist* result) { line = memchr(line, '\n', (size_t) (nRead - (line - buf))); } - return NULL; + return nullptr; } const char* ffDetectSwap(FFlist* result) { - if (detectByProcSwaps(result) == NULL) { - return NULL; + if (detectByProcSwaps(result) == nullptr) { + return nullptr; } return detectByProcMeminfo(result); } diff --git a/src/detection/swap/swap_obsd.c b/src/detection/swap/swap_obsd.c index 1296aeb27b..9c2c98c9e0 100644 --- a/src/detection/swap/swap_obsd.c +++ b/src/detection/swap/swap_obsd.c @@ -13,7 +13,7 @@ const char* ffDetectSwap(FFlist* result) { return "swapctl(SWAP_NSWAP) failed"; } if (nswap == 0) { - return NULL; + return nullptr; } FF_AUTO_FREE struct swapent* swdev = malloc((uint32_t) nswap * sizeof(*swdev)); @@ -31,5 +31,5 @@ const char* ffDetectSwap(FFlist* result) { } } - return NULL; + return nullptr; } diff --git a/src/detection/swap/swap_sunos.c b/src/detection/swap/swap_sunos.c index fa3260d50f..b08d489ef4 100644 --- a/src/detection/swap/swap_sunos.c +++ b/src/detection/swap/swap_sunos.c @@ -28,5 +28,5 @@ const char* ffDetectSwap(FFlist* result) { swap->bytesUsed = swap->bytesTotal - (uint64_t) table->swt_ent[i].ste_free * pageSize; } - return NULL; + return nullptr; } diff --git a/src/detection/swap/swap_windows.c b/src/detection/swap/swap_windows.c index e96298bdc7..2caadaddb6 100644 --- a/src/detection/swap/swap_windows.c +++ b/src/detection/swap/swap_windows.c @@ -15,7 +15,7 @@ const char* ffDetectSwap(FFlist* result) { } if (size == 0) { - return NULL; + return nullptr; } uint32_t pageSize = instance.state.platform.sysinfo.pageSize; @@ -31,5 +31,5 @@ const char* ffDetectSwap(FFlist* result) { break; } } - return NULL; + return nullptr; } diff --git a/src/detection/terminalfont/terminalfont.c b/src/detection/terminalfont/terminalfont.c index 7ef71206af..b7c2d0a5a4 100644 --- a/src/detection/terminalfont/terminalfont.c +++ b/src/detection/terminalfont/terminalfont.c @@ -3,7 +3,6 @@ #include "common/properties.h" #include "common/processing.h" #include "common/debug.h" -#include "common/strutil.h" #include "detection/terminalshell/terminalshell.h" static void detectAlacritty(FFTerminalFontResult* terminalFont) { @@ -19,6 +18,7 @@ static void detectAlacritty(FFTerminalFontResult* terminalFont) { do { FFpropquery fontQueryToml[] = { { "normal =", &fontNormal }, + { "family =", &fontFamily }, { "size =", &fontSize }, }; @@ -35,6 +35,8 @@ static void detectAlacritty(FFTerminalFontResult* terminalFont) { } while (false); if (fontNormal.length > 0) { + ffStrbufClear(&fontFamily); // If both `normal` and `family` are specified, `normal` takes precedence + // { family = "Fira Code", style = "Medium" } ffStrbufTrimSpace(&fontNormal); ffStrbufTrimRight(&fontNormal, '}'); @@ -67,85 +69,112 @@ static void detectAlacritty(FFTerminalFontResult* terminalFont) { ffFontInitMoveValues(&terminalFont->font, &fontFamily, &fontSize, &fontStyle); } -static bool parseGhosttyConfig(FFstrbuf* path, FFstrbuf* fontName, FFstrbuf* fontNameFallback, FFstrbuf* fontSize) { +static void parseGhosttyConfig(const FFstrbuf* path, FFstrbuf* fontName, FFstrbuf* fontNameFallback, FFstrbuf* fontSize, FFlist* configFiles /* list of FFstrbuf */) { + // Maximum number of `config-file` directives to follow, guarding against runaway includes + enum { FF_GHOSTTY_MAX_CONFIG_FILES = 16 }; + FF_DEBUG("parsing config: %s", path->chars); FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY temp = ffStrbufCreate(); if (!ffAppendFileBuffer(path->chars, &buffer)) { FF_DEBUG("cannot read config: %s", path->chars); - return false; + return; } - char* line = NULL; + char* line = nullptr; size_t len = 0; while (ffStrbufGetline(&line, &len, &buffer)) { if (ffParsePropLine(line, "font-family =", &temp)) { FF_DEBUG("found font-family='%s' in %s", temp.chars, path->chars); + // Latter overrides former; former becomes the fallback font if (fontName->length > 0) { ffStrbufDestroy(fontNameFallback); ffStrbufInitMove(fontNameFallback, fontName); } ffStrbufDestroy(fontName); ffStrbufInitMove(fontName, &temp); - } else if (ffParsePropLine(line, "font-size =", fontSize)) { + } else if (ffParsePropLine(line, "font-size =", &temp)) { FF_DEBUG("found font-size='%s' in %s", temp.chars, path->chars); // Latter overrides former ffStrbufDestroy(fontSize); ffStrbufInitMove(fontSize, &temp); + } else if (ffParsePropLine(line, "config-file =", &temp)) { + // Doc: https://ghostty.org/docs/config/reference#config-file + // A leading `?` suppresses errors if the file doesn't exist; missing files are skipped here either way + ffStrbufTrimLeft(&temp, '?'); + ffStrbufTrim(&temp, '"'); + if (temp.length == 0) { + continue; + } + + if (!ffStrbufStartsWithC(&temp, '/')) { + // Relative paths are relative to the file containing the `config-file` directive + FF_STRBUF_AUTO_DESTROY absolutePath = ffStrbufCreateCopy(path); + ffStrbufSubstrBeforeLastC(&absolutePath, '/'); + ffStrbufAppendC(&absolutePath, '/'); + ffStrbufAppend(&absolutePath, &temp); + ffStrbufDestroy(&temp); + ffStrbufInitMove(&temp, &absolutePath); + } + + // Each unique file is only loaded once, which also prevents include cycles + bool loaded = ffStrbufEqual(&temp, path); + if (!loaded) { + FF_LIST_FOR_EACH(FFstrbuf, it, *configFiles) { + if (ffStrbufEqual(it, &temp)) { + loaded = true; + break; + } + } + } + + if (loaded) { + FF_DEBUG("config-file '%s' was already loaded, skipping to avoid cycles", temp.chars); + } else if (configFiles->length >= FF_GHOSTTY_MAX_CONFIG_FILES) { + FF_DEBUG("too many config-file directives, ignoring '%s'", temp.chars); + } else { + FF_DEBUG("found config-file='%s' in %s", temp.chars, path->chars); + ffStrbufInitMove(FF_LIST_ADD(FFstrbuf, *configFiles), &temp); + } + ffStrbufClear(&temp); } } - return true; } -static void detectGhostty(const FFstrbuf* exe, FFTerminalFontResult* terminalFont, const char* configPathMac, const char* configPathUnix) { +static void detectGhostty(FFTerminalFontResult* terminalFont, [[maybe_unused]] const char* configPathMac, const char* configPathUnix) { FF_DEBUG("detectGhostty: start"); FF_STRBUF_AUTO_DESTROY configPath = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY fontName = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY fontNameFallback = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY fontSize = ffStrbufCreate(); + FF_LIST_AUTO_DESTROY configFiles = ffListCreate(); // list of FFstrbuf + + // Ghostty loads the XDG config first, then (on macOS) the Application Support config, + // so values in the latter override the former + if (instance.state.platform.configDirs.length > 0) { + ffStrbufSet(&configPath, FF_LIST_FIRST(FFstrbuf, instance.state.platform.configDirs)); + ffStrbufAppendS(&configPath, configPathUnix); // ghostty/config + parseGhosttyConfig(&configPath, &fontName, &fontNameFallback, &fontSize, &configFiles); + } - if (configPathMac && configPathUnix) { #if __APPLE__ - ffStrbufSet(&configPath, &instance.state.platform.homeDir); - ffStrbufAppendS(&configPath, "Library/Application Support/"); - ffStrbufAppendS(&configPath, configPathMac); // com.mitchellh.ghostty/config - parseGhosttyConfig(&configPath, &fontName, &fontNameFallback, &fontSize); + ffStrbufSet(&configPath, &instance.state.platform.homeDir); + ffStrbufAppendS(&configPath, "Library/Application Support/"); + ffStrbufAppendS(&configPath, configPathMac); // com.mitchellh.ghostty/config + parseGhosttyConfig(&configPath, &fontName, &fontNameFallback, &fontSize, &configFiles); #endif - if (instance.state.platform.configDirs.length > 0) { - ffStrbufSet(&configPath, FF_LIST_FIRST(FFstrbuf, instance.state.platform.configDirs)); - ffStrbufAppendS(&configPath, configPathUnix); // ghostty/config - parseGhosttyConfig(&configPath, &fontName, &fontNameFallback, &fontSize); - } - } else { - // Try ghostty +show-config first - FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); - const char* error = ffProcessAppendStdOut(&buffer, (char* const[]){ - exe->chars, - "+show-config", - NULL, - }); - if (error == NULL) { - char* line = NULL; - size_t len = 0; - while (ffStrbufGetline(&line, &len, &buffer)) { - if (ffStrStartsWith(line, "font-family = ")) { - FF_DEBUG("found %s", line); - if (fontName.length > 0) { - ffStrbufDestroy(&fontNameFallback); - ffStrbufInitMove(&fontNameFallback, &fontName); - } - ffStrbufSetNS(&fontName, (uint32_t) (len - strlen("font-family = ")), line + strlen("font-family = ")); - } else if (ffStrStartsWith(line, "font-size = ")) { - FF_DEBUG("found %s", line); - // `ghostty +show-config` reports only one font size even if the config has multiple font sizes - ffStrbufSetNS(&fontSize, (uint32_t) (len - strlen("font-size = ")), line + strlen("font-size = ")); - } - } - } else { - FF_DEBUG("`ghostty +show-config` failed: %s", error); - } + // Files referenced by `config-file` don't take effect until the whole configuration is loaded, + // so they are parsed after all root config files, in the order they were found + for (uint32_t i = 0; i < configFiles.length; ++i) { + // Copy the path as parseGhosttyConfig may grow the list, invalidating pointers into it + ffStrbufSet(&configPath, FF_LIST_GET(FFstrbuf, configFiles, i)); + parseGhosttyConfig(&configPath, &fontName, &fontNameFallback, &fontSize, &configFiles); + } + + FF_LIST_FOR_EACH(FFstrbuf, it, configFiles) { + ffStrbufDestroy(it); } if (fontName.length == 0) { @@ -167,20 +196,20 @@ static void detectGhostty(const FFstrbuf* exe, FFTerminalFontResult* terminalFon ffFontInitValues(&terminalFont->font, fontName.chars, fontSize.chars); if (fontNameFallback.length > 0) { FF_DEBUG("applying fallback family='%s'", fontNameFallback.chars); - ffFontInitValues(&terminalFont->fallback, fontNameFallback.chars, NULL); + ffFontInitValues(&terminalFont->fallback, fontNameFallback.chars, nullptr); } FF_DEBUG("result family='%s' size='%s'%s", fontName.chars, fontSize.chars, fontNameFallback.length ? " (with fallback)" : ""); FF_DEBUG("detectGhostty: end"); } -FF_A_UNUSED static void detectTTY(FFTerminalFontResult* terminalFont) { +[[maybe_unused]] static void detectTTY(FFTerminalFontResult* terminalFont) { FF_STRBUF_AUTO_DESTROY fontName = ffStrbufCreate(); ffParsePropFile(FASTFETCH_TARGET_DIR_ETC "/vconsole.conf", "Font =", &fontName); if (fontName.length == 0) { ffStrbufAppendS(&fontName, "VGA default kernel font "); - ffProcessAppendStdOut(&fontName, (char* const[]){ "showconsolefont", "--info", NULL }); + ffProcessAppendStdOut(&fontName, (char* const[]){ "showconsolefont", "--info", nullptr }); ffStrbufTrimRight(&fontName, ' '); } @@ -192,7 +221,7 @@ FF_A_UNUSED static void detectTTY(FFTerminalFontResult* terminalFont) { } } -FF_A_UNUSED static bool detectKitty(const FFstrbuf* exe, FFTerminalFontResult* result) { +[[maybe_unused]] static bool detectKitty(const FFstrbuf* exe, FFTerminalFontResult* result) { FF_STRBUF_AUTO_DESTROY fontName = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY fontSize = ffStrbufCreate(); @@ -203,7 +232,7 @@ FF_A_UNUSED static bool detectKitty(const FFstrbuf* exe, FFTerminalFontResult* r 2, "\eP1+r%*[^=]=%511[^\e]\e\\\eP1+r%*[^=]=%511[^\e]\e\\", fontHex, - sizeHex) == NULL && + sizeHex) == nullptr && *fontHex && *sizeHex) { // decode hex string for (const char* p = fontHex; p[0] && p[1]; p += 2) { @@ -224,7 +253,7 @@ FF_A_UNUSED static bool detectKitty(const FFstrbuf* exe, FFTerminalFontResult* r exe->chars, "+kitten", "query-terminal", - NULL, + nullptr, })) { ffParsePropLines(buf.chars, "font_family: ", &fontName); ffParsePropLines(buf.chars, "font_size: ", &fontSize); @@ -260,7 +289,7 @@ static bool detectWezterm(const FFstrbuf* exe, FFTerminalFontResult* result) { FF_STRBUF_AUTO_DESTROY fontName = ffStrbufCreate(); - ffStrbufSetS(&result->error, ffProcessAppendStdOut(&fontName, (char* const[]){ cli.chars, "ls-fonts", "--text", "a", NULL })); + ffStrbufSetS(&result->error, ffProcessAppendStdOut(&fontName, (char* const[]){ cli.chars, "ls-fonts", "--text", "a", nullptr })); if (result->error.length) { return false; } @@ -306,7 +335,7 @@ static bool detectTabby(FFTerminalFontResult* result) { static bool detectContour(const FFstrbuf* exe, FFTerminalFontResult* result) { FF_STRBUF_AUTO_DESTROY buf = ffStrbufCreate(); - if (ffProcessAppendStdOut(&buf, (char* const[]){ exe->chars, "font-locator", NULL })) { + if (ffProcessAppendStdOut(&buf, (char* const[]){ exe->chars, "font-locator", nullptr })) { ffStrbufAppendS(&result->error, "`contour font-locator` failed"); return false; } @@ -365,9 +394,9 @@ static bool detectTerminalFontCommon(const FFTerminalResult* terminal, FFTermina } else if (ffStrbufStartsWithIgnCaseS(&terminal->processName, "contour")) { detectContour(&terminal->exe, terminalFont); } else if (ffStrbufStartsWithIgnCaseS(&terminal->processName, "ghostty")) { - detectGhostty(&terminal->exe, terminalFont, NULL, NULL); + detectGhostty(terminalFont, "com.mitchellh.ghostty/config", "ghostty/config"); } else if (ffStrbufStartsWithIgnCaseS(&terminal->processName, "Muxy")) { - detectGhostty(&terminal->exe, terminalFont, "Muxy/ghostty.conf", "muxy/ghostty.conf"); + detectGhostty(terminalFont, "Muxy/ghostty.conf", "muxy/ghostty.conf"); } else if (ffStrbufStartsWithIgnCaseS(&terminal->processName, "rio")) { detectRio(terminalFont); } diff --git a/src/detection/terminalfont/terminalfont_android.c b/src/detection/terminalfont/terminalfont_android.c index a7210783e2..666cf3e2b2 100644 --- a/src/detection/terminalfont/terminalfont_android.c +++ b/src/detection/terminalfont/terminalfont_android.c @@ -14,7 +14,7 @@ const char* detectTermux(FFTerminalFontResult* terminalFont) { if (!ffPathExists(FF_TERMUX_FONT_PATH, FF_PATHTYPE_FILE)) { ffFontInitCopy(&terminalFont->font, "monospace"); - return NULL; + return nullptr; } #ifdef FF_HAVE_FREETYPE @@ -25,9 +25,9 @@ const char* detectTermux(FFTerminalFontResult* terminalFont) { FF_LIBRARY_LOAD_SYMBOL_MESSAGE(freetype, FT_Done_Face); FF_LIBRARY_LOAD_SYMBOL_MESSAGE(freetype, FT_Done_FreeType); - FT_Library library = NULL; - FT_Face face = NULL; - const char* error = NULL; + FT_Library library = nullptr; + FT_Face face = nullptr; + const char* error = nullptr; if (ffFT_Init_FreeType(&library)) { error = "FT_Init_FreeType() failed"; diff --git a/src/detection/terminalfont/terminalfont_apple.m b/src/detection/terminalfont/terminalfont_apple.m index 126235f411..c3011846ff 100644 --- a/src/detection/terminalfont/terminalfont_apple.m +++ b/src/detection/terminalfont/terminalfont_apple.m @@ -10,7 +10,7 @@ static void detectIterm2(FFTerminalFontResult* terminalFont) { const char* profile = getenv("ITERM_PROFILE"); - if (profile == NULL) + if (profile == nullptr) { ffStrbufAppendS(&terminalFont->error, "environment variable ITERM_PROFILE not set"); return; diff --git a/src/detection/terminalfont/terminalfont_linux.c b/src/detection/terminalfont/terminalfont_linux.c index 9ae16a4301..a351e584e3 100644 --- a/src/detection/terminalfont/terminalfont_linux.c +++ b/src/detection/terminalfont/terminalfont_linux.c @@ -15,24 +15,24 @@ static const char* getSystemMonospaceFont(void) { const FFDisplayServerResult* wmde = ffConnectDisplayServer(); if (ffStrbufIgnCaseEqualS(&wmde->dePrettyName, "Cinnamon")) { - const char* systemMonospaceFont = ffSettingsGetGnome("/org/cinnamon/desktop/interface/monospace-font-name", "org.cinnamon.desktop.interface", NULL, "monospace-font-name", FF_VARIANT_TYPE_STRING).strValue; + const char* systemMonospaceFont = ffSettingsGetGnome("/org/cinnamon/desktop/interface/monospace-font-name", "org.cinnamon.desktop.interface", nullptr, "monospace-font-name", FF_VARIANT_TYPE_STRING).strValue; if (ffStrSet(systemMonospaceFont)) { return systemMonospaceFont; } } else if (ffStrbufIgnCaseEqualS(&wmde->dePrettyName, "Mate")) { - const char* systemMonospaceFont = ffSettingsGetGnome("/org/mate/interface/monospace-font-name", "org.mate.interface", NULL, "monospace-font-name", FF_VARIANT_TYPE_STRING).strValue; + const char* systemMonospaceFont = ffSettingsGetGnome("/org/mate/interface/monospace-font-name", "org.mate.interface", nullptr, "monospace-font-name", FF_VARIANT_TYPE_STRING).strValue; if (ffStrSet(systemMonospaceFont)) { return systemMonospaceFont; } } - return ffSettingsGetGnome("/org/gnome/desktop/interface/monospace-font-name", "org.gnome.desktop.interface", NULL, "monospace-font-name", FF_VARIANT_TYPE_STRING).strValue; + return ffSettingsGetGnome("/org/gnome/desktop/interface/monospace-font-name", "org.gnome.desktop.interface", nullptr, "monospace-font-name", FF_VARIANT_TYPE_STRING).strValue; } static void detectKgx(FFTerminalFontResult* terminalFont) { // kgx (gnome console) doesn't support profiles - if (!ffSettingsGetGnome("/org/gnome/Console/use-system-font", "org.gnome.Console", NULL, "use-system-font", FF_VARIANT_TYPE_BOOL).boolValue) { - FF_AUTO_FREE const char* fontName = ffSettingsGetGnome("/org/gnome/Console/custom-font", "org.gnome.Console", NULL, "custom-font", FF_VARIANT_TYPE_STRING).strValue; + if (!ffSettingsGetGnome("/org/gnome/Console/use-system-font", "org.gnome.Console", nullptr, "use-system-font", FF_VARIANT_TYPE_BOOL).boolValue) { + FF_AUTO_FREE const char* fontName = ffSettingsGetGnome("/org/gnome/Console/custom-font", "org.gnome.Console", nullptr, "custom-font", FF_VARIANT_TYPE_STRING).strValue; if (ffStrSet(fontName)) { ffFontInitPango(&terminalFont->font, fontName); } else { @@ -49,8 +49,8 @@ static void detectKgx(FFTerminalFontResult* terminalFont) { } static void detectPtyxis(FFTerminalFontResult* terminalFont) { - if (!ffSettingsGetGnome("/org/gnome/Ptyxis/use-system-font", "org.gnome.Ptyxis", NULL, "use-system-font", FF_VARIANT_TYPE_BOOL).boolValue) { - FF_AUTO_FREE const char* fontName = ffSettingsGetGnome("/org/gnome/Ptyxis/font-name", "org.gnome.Ptyxis", NULL, "font-name", FF_VARIANT_TYPE_STRING).strValue; + if (!ffSettingsGetGnome("/org/gnome/Ptyxis/use-system-font", "org.gnome.Ptyxis", nullptr, "use-system-font", FF_VARIANT_TYPE_BOOL).boolValue) { + FF_AUTO_FREE const char* fontName = ffSettingsGetGnome("/org/gnome/Ptyxis/font-name", "org.gnome.Ptyxis", nullptr, "font-name", FF_VARIANT_TYPE_STRING).strValue; if (ffStrSet(fontName)) { ffFontInitPango(&terminalFont->font, fontName); } else { @@ -67,7 +67,7 @@ static void detectPtyxis(FFTerminalFontResult* terminalFont) { } static void detectFromGSettings(const char* profilePath, const char* profileList, const char* profile, const char* defaultProfileKey, FFTerminalFontResult* terminalFont) { - FF_AUTO_FREE const char* defaultProfile = ffSettingsGetGSettings(profileList, NULL, defaultProfileKey, FF_VARIANT_TYPE_STRING).strValue; + FF_AUTO_FREE const char* defaultProfile = ffSettingsGetGSettings(profileList, nullptr, defaultProfileKey, FF_VARIANT_TYPE_STRING).strValue; if (!ffStrSet(defaultProfile)) { ffStrbufAppendF(&terminalFont->error, "Could not get default profile from gsettings: %s", profileList); return; @@ -172,7 +172,7 @@ static void detectDeepinTerminal(FFTerminalFontResult* terminalFont) { FILE* file = fopen(profile.chars, "r"); if (file) { - char* line = NULL; + char* line = nullptr; size_t len = 0; for (int count = 0; getline(&line, &len, file) != -1 && count < 2;) { @@ -230,7 +230,7 @@ static void detectFootTerminal(FFTerminalFontResult* terminalFont) { } ffFontInitValues(&terminalFont->font, font.chars, &font.chars[size]); if (comma < font.length) { - ffFontInitValues(&terminalFont->fallback, &font.chars[comma + 1], NULL); + ffFontInitValues(&terminalFont->fallback, &font.chars[comma + 1], nullptr); } } @@ -277,7 +277,7 @@ static void detectXterm(FFTerminalFontResult* terminalFont) { ffFontInitValues(&terminalFont->font, fontName.chars, fontSize.chars); } -static bool extractStTermFont(const char* str, FF_A_UNUSED uint32_t len, void* userdata) { +static bool extractStTermFont(const char* str, [[maybe_unused]] uint32_t len, void* userdata) { if (!ffStrContains(str, "size=")) { return true; } @@ -337,7 +337,7 @@ static void detectWarp(FFTerminalFontResult* terminalFont) { ffStrbufSet(&baseDir, dirPrefix); ffStrbufAppendS(&baseDir, "warp-terminal/user_preferences.json"); - yyjson_doc* doc = yyjson_read_file(baseDir.chars, YYJSON_READ_INSITU | YYJSON_READ_ALLOW_TRAILING_COMMAS | YYJSON_READ_ALLOW_COMMENTS, NULL, NULL); + yyjson_doc* doc = yyjson_read_file(baseDir.chars, YYJSON_READ_INSITU | YYJSON_READ_ALLOW_TRAILING_COMMAS | YYJSON_READ_ALLOW_COMMENTS, nullptr, nullptr); if (!doc) { continue; } @@ -434,7 +434,7 @@ static void detectUrxvt(FFTerminalFontResult* terminalFont) { uint32_t index = 0; - char* line = NULL; + char* line = nullptr; size_t len = 0; while (ffStrbufGetdelim(&line, &len, ',', &buffer)) { FFfont* font = index == 0 ? &terminalFont->font : &terminalFont->fallback; diff --git a/src/detection/terminalfont/terminalfont_windows.c b/src/detection/terminalfont/terminalfont_windows.c index 87566af8d9..c03fea1b61 100644 --- a/src/detection/terminalfont/terminalfont_windows.c +++ b/src/detection/terminalfont/terminalfont_windows.c @@ -33,7 +33,7 @@ static const char* detectWTProfile(yyjson_val* profile, FFstrbuf* name, double* *size = unsafe_yyjson_get_num(psize); } } - return NULL; + return nullptr; } static inline void wrapYyjsonFree(yyjson_doc** doc) { @@ -44,7 +44,7 @@ static inline void wrapYyjsonFree(yyjson_doc** doc) { } static const char* detectFromWTImpl(FFstrbuf* content, FFstrbuf* name, double* size) { - yyjson_doc* FF_A_CLEANUP(wrapYyjsonFree) doc = yyjson_read_opts(content->chars, content->length, YYJSON_READ_ALLOW_COMMENTS | YYJSON_READ_ALLOW_TRAILING_COMMAS, NULL, NULL); + [[gnu::cleanup(wrapYyjsonFree)]] yyjson_doc* doc = yyjson_read_opts(content->chars, content->length, YYJSON_READ_ALLOW_COMMENTS | YYJSON_READ_ALLOW_TRAILING_COMMAS, nullptr, nullptr); if (!doc) { return "Failed to parse WT JSON config file"; } @@ -86,13 +86,13 @@ static const char* detectFromWTImpl(FFstrbuf* content, FFstrbuf* name, double* s if (*size < 0) { *size = 12; } - return NULL; + return nullptr; } static void detectFromWindowsTerminal(const FFstrbuf* terminalExe, FFTerminalFontResult* terminalFont) { // https://learn.microsoft.com/en-us/windows/terminal/install#settings-json-file FF_STRBUF_AUTO_DESTROY json = ffStrbufCreate(); - const char* error = NULL; + const char* error = nullptr; if (terminalExe && ffIsAbsolutePath(terminalExe->chars)) { FF_STRBUF_AUTO_DESTROY jsonPath = ffStrbufCreateA(MAX_PATH); @@ -106,8 +106,8 @@ static void detectFromWindowsTerminal(const FFstrbuf* terminalExe, FFTerminalFon error = "Error reading Windows Terminal portable settings JSON file"; } } else { - PWSTR localAppDataW = NULL; - if (SUCCEEDED(SHGetKnownFolderPath(&FOLDERID_LocalAppData, KF_FLAG_DEFAULT, NULL, &localAppDataW))) { + PWSTR localAppDataW = nullptr; + if (SUCCEEDED(SHGetKnownFolderPath(&FOLDERID_LocalAppData, KF_FLAG_DEFAULT, nullptr, &localAppDataW))) { ffStrbufSetWS(&jsonPath, localAppDataW); CoTaskMemFree(localAppDataW); @@ -146,7 +146,7 @@ static void detectFromWindowsTerminal(const FFstrbuf* terminalExe, FFTerminalFon "else if exist \"%LOCALAPPDATA%\\Microsoft\\Windows Terminal\\settings.json\" " "( type %LOCALAPPDATA%\\Microsoft\\Windows Terminal\\settings.json ) " "else ( call )", - NULL }); + nullptr }); } if (error) { @@ -242,7 +242,7 @@ static void detectConEmu(FFTerminalFontResult* terminalFont) { } static void detectWarp(FFTerminalFontResult* terminalFont) { - FF_AUTO_CLOSE_FD HANDLE key = NULL; + FF_AUTO_CLOSE_FD HANDLE key = nullptr; if (!ffRegOpenKeyForRead(HKEY_CURRENT_USER, L"Software\\Warp.dev\\Warp", &key, &terminalFont->error)) { return; } @@ -261,7 +261,7 @@ static void detectWarp(FFTerminalFontResult* terminalFont) { FFstrbuf* fontWeight = FF_LIST_ADD(FFstrbuf, terminalFont->font.styles); ffStrbufInit(fontWeight); - if (ffRegReadStrbuf(key, L"FontWeight", fontWeight, NULL)) { + if (ffRegReadStrbuf(key, L"FontWeight", fontWeight, nullptr)) { ffStrbufTrim(fontWeight, '"'); } else { ffStrbufSetStatic(fontWeight, "Normal"); diff --git a/src/detection/terminalshell/terminalshell.c b/src/detection/terminalshell/terminalshell.c index 1d22083b66..2d531f9712 100644 --- a/src/detection/terminalshell/terminalshell.c +++ b/src/detection/terminalshell/terminalshell.c @@ -25,7 +25,7 @@ static bool getFileVersion(const FFstrbuf* exePath, const wchar_t* stringName, FFstrbuf* version) { wchar_t exePathW[PATH_MAX + 1]; - if (!NT_SUCCESS(RtlUTF8ToUnicodeN(exePathW, (ULONG) sizeof(exePathW), NULL, exePath->chars, (ULONG) exePath->length + 1))) { + if (!NT_SUCCESS(RtlUTF8ToUnicodeN(exePathW, (ULONG) sizeof(exePathW), nullptr, exePath->chars, (ULONG) exePath->length + 1))) { return false; } return ffGetFileVersion(exePathW, stringName, version); @@ -38,7 +38,7 @@ static bool getFileVersion(const FFstrbuf* exePath, const wchar_t* stringName, F #endif static bool getExeVersionRaw(FFstrbuf* exe, FFstrbuf* version) { - return ffProcessAppendStdOut(version, (char* const[]) { exe->chars, "--version", NULL }) == NULL; + return ffProcessAppendStdOut(version, (char* const[]) { exe->chars, "--version", nullptr }) == nullptr; } static bool getExeVersionGeneral(FFstrbuf* exe, FFstrbuf* version) { @@ -51,7 +51,7 @@ static bool getExeVersionGeneral(FFstrbuf* exe, FFstrbuf* version) { return true; } -static bool extractBashVersion(const char* line, FF_A_UNUSED uint32_t len, void* userdata) { +static bool extractBashVersion(const char* line, [[maybe_unused]] uint32_t len, void* userdata) { if (!ffStrStartsWith(line, "@(#)Bash version ")) { return true; } @@ -89,7 +89,14 @@ static bool getShellVersionFish(FFstrbuf* exe, FFstrbuf* version) { if (version->length < strlen("fish, v") || !ffStrbufStartsWithS(version, "fish")) { return false; } - uint32_t index = ffStrbufNextIndexC(version, strlen("fish, "), ' '); + uint32_t index = ffStrbufFirstIndexC(version, ' '); // skip "fish," + while (!ffCharIsDigit(version->chars[index + 1])) { + index = ffStrbufNextIndexC(version, index + 1, ' '); // skip "version" + if (index == version->length) { + return false; + } + } + ffStrbufSubstrAfter(version, index); ffStrbufSubstrBeforeFirstC(version, ' '); return true; @@ -105,7 +112,7 @@ static bool getShellVersionPwsh(FFstrbuf* exe, FFstrbuf* version) { } #ifdef _WIN32 - if (getFileVersion(exe, NULL, version)) { + if (getFileVersion(exe, nullptr, version)) { ffStrbufSubstrBeforeLastC(version, '.'); return true; } @@ -120,14 +127,14 @@ static bool getShellVersionPwsh(FFstrbuf* exe, FFstrbuf* version) { } static bool getShellVersionKsh(FFstrbuf* exe, FFstrbuf* version) { - if (ffProcessAppendStdErr(version, (char* const[]) { exe->chars, "--version", NULL }) == NULL && ffStrbufSubstrAfterFirstS(version, " (AT&T Research) ")) { + if (ffProcessAppendStdErr(version, (char* const[]) { exe->chars, "--version", nullptr }) == nullptr && ffStrbufSubstrAfterFirstS(version, " (AT&T Research) ")) { // version sh (AT&T Research) 93u+ 2012-08-01 ffStrbufSubstrBeforeFirstC(version, ' '); return true; } ffStrbufClear(version); - if (ffProcessAppendStdOut(version, (char* const[]) { exe->chars, "-c", "echo $KSH_VERSION", NULL }) == NULL && ffStrbufSubstrAfterFirstS(version, " KSH ")) { + if (ffProcessAppendStdOut(version, (char* const[]) { exe->chars, "-c", "echo $KSH_VERSION", nullptr }) == nullptr && ffStrbufSubstrAfterFirstS(version, " KSH ")) { // OKSH: @(#)PD KSH v5.2.14 99/07/13.2 // MKSH: @(#)MIRBSD KSH R59 2025/04/26 +Debian // $OKSH_VERSION doesn't exist on OpenBSD @@ -141,7 +148,7 @@ static bool getShellVersionKsh(FFstrbuf* exe, FFstrbuf* version) { static bool getShellVersionOksh(FFstrbuf* exe, FFstrbuf* version) { // Homebrew version - if (ffProcessAppendStdOut(version, (char* const[]) { exe->chars, "-c", "echo $OKSH_VERSION", NULL }) != NULL) { + if (ffProcessAppendStdOut(version, (char* const[]) { exe->chars, "-c", "echo $OKSH_VERSION", nullptr }) != nullptr) { return false; } @@ -151,7 +158,7 @@ static bool getShellVersionOksh(FFstrbuf* exe, FFstrbuf* version) { } static bool getShellVersionOils(FFstrbuf* exe, FFstrbuf* version) { - if (ffProcessAppendStdOut(version, (char* const[]) { exe->chars, "--version", NULL }) != NULL) { + if (ffProcessAppendStdOut(version, (char* const[]) { exe->chars, "--version", nullptr }) != nullptr) { return false; } @@ -189,9 +196,9 @@ static bool getShellVersionAsh(FFstrbuf* exe, FFstrbuf* version) { ffBinaryExtractStrings(exe->chars, extractBusyboxVersion, version, (uint32_t) strlen("BusyBox v0.0.0")); const char* error = ffStrbufEndsWithS(exe, "busybox") - ? ffProcessAppendStdErr(version, (char* const[]) { exe->chars, "ash", "--help", NULL }) - : ffProcessAppendStdErr(version, (char* const[]) { exe->chars, "--help", NULL }); - if (error != NULL) { + ? ffProcessAppendStdErr(version, (char* const[]) { exe->chars, "ash", "--help", nullptr }) + : ffProcessAppendStdErr(version, (char* const[]) { exe->chars, "--help", nullptr }); + if (error != nullptr) { return false; } @@ -202,14 +209,14 @@ static bool getShellVersionAsh(FFstrbuf* exe, FFstrbuf* version) { return true; } -static bool getShellVersionXonsh(FF_A_UNUSED FFstrbuf* exe, FFstrbuf* version) { +static bool getShellVersionXonsh([[maybe_unused]] FFstrbuf* exe, FFstrbuf* version) { ffStrbufSetS(version, getenv("XONSH_VERSION")); if (version->length) { return true; } // exe is python here - if (ffProcessAppendStdErr(version, (char* const[]) { "xonsh", "--version", NULL }) != NULL) { + if (ffProcessAppendStdErr(version, (char* const[]) { "xonsh", "--version", nullptr }) != nullptr) { return false; } @@ -218,7 +225,7 @@ static bool getShellVersionXonsh(FF_A_UNUSED FFstrbuf* exe, FFstrbuf* version) { return true; } -static bool extractZshVersion(const char* line, FF_A_UNUSED uint32_t len, void* userdata) { +static bool extractZshVersion(const char* line, [[maybe_unused]] uint32_t len, void* userdata) { if (!ffStrStartsWith(line, "zsh-")) { return true; } @@ -249,13 +256,13 @@ static bool getShellVersionWinPowerShell(FFstrbuf* exe, FFstrbuf* version) { return true; } - FF_AUTO_CLOSE_FD HANDLE hKey = NULL; - if (ffRegOpenSubkeyForRead(ffRegGetRootKeyHandle(HKEY_LOCAL_MACHINE), L"SOFTWARE\\Microsoft\\PowerShell\\3\\PowerShellEngine", &hKey, NULL) && ffRegReadStrbuf(hKey, L"PowerShellVersion", version, NULL)) { + FF_AUTO_CLOSE_FD HANDLE hKey = nullptr; + if (ffRegOpenSubkeyForRead(ffRegGetRootKeyHandle(HKEY_LOCAL_MACHINE), L"SOFTWARE\\Microsoft\\PowerShell\\3\\PowerShellEngine", &hKey, nullptr) && ffRegReadStrbuf(hKey, L"PowerShellVersion", version, nullptr)) { return true; } // Extremely slow - return ffProcessAppendStdOut(version, (char* const[]) { exe->chars, "-NoLogo", "-NoProfile", "-Command", "$PSVersionTable.PSVersion.ToString()", NULL }) == NULL; + return ffProcessAppendStdOut(version, (char* const[]) { exe->chars, "-NoLogo", "-NoProfile", "-Command", "$PSVersionTable.PSVersion.ToString()", nullptr }) == nullptr; } #endif @@ -309,18 +316,18 @@ bool fftsGetShellVersion(FFstrbuf* exe, const char* exeName, FFstrbuf* version) return getShellVersionWinPowerShell(exe, version); } - return getFileVersion(exe, NULL, version); + return getFileVersion(exe, nullptr, version); #endif return false; } -FF_A_UNUSED static bool getTerminalVersionTermux(FFstrbuf* version) { +[[maybe_unused]] static bool getTerminalVersionTermux(FFstrbuf* version) { ffStrbufSetS(version, getenv("TERMUX_VERSION")); return version->length > 0; } -static bool extractGeneralVersion(const char* str, FF_A_UNUSED uint32_t len, void* userdata) { +static bool extractGeneralVersion(const char* str, [[maybe_unused]] uint32_t len, void* userdata) { if (!ffCharIsDigit(str[0])) { return true; } @@ -333,7 +340,7 @@ static bool extractGeneralVersion(const char* str, FF_A_UNUSED uint32_t len, voi return false; } -FF_A_UNUSED static bool getTerminalVersionGnome(FFstrbuf* exe, FFstrbuf* version) { +[[maybe_unused]] static bool getTerminalVersionGnome(FFstrbuf* exe, FFstrbuf* version) { if (ffIsAbsolutePath(exe->chars)) { ffBinaryExtractStrings(exe->chars, extractGeneralVersion, version, (uint32_t) strlen("0.0.0")); if (version->length) { @@ -341,7 +348,7 @@ FF_A_UNUSED static bool getTerminalVersionGnome(FFstrbuf* exe, FFstrbuf* version } } - if (ffProcessAppendStdOut(version, (char* const[]) { "gnome-terminal", "--version", NULL })) { + if (ffProcessAppendStdOut(version, (char* const[]) { "gnome-terminal", "--version", nullptr })) { return false; } @@ -351,7 +358,7 @@ FF_A_UNUSED static bool getTerminalVersionGnome(FFstrbuf* exe, FFstrbuf* version return true; } -FF_A_UNUSED static bool getTerminalVersionXfce4Terminal(FFstrbuf* exe, FFstrbuf* version) { +[[maybe_unused]] static bool getTerminalVersionXfce4Terminal(FFstrbuf* exe, FFstrbuf* version) { if (ffIsAbsolutePath(exe->chars)) { ffBinaryExtractStrings(exe->chars, extractGeneralVersion, version, (uint32_t) strlen("0.0.0")); if (version->length) { @@ -362,8 +369,8 @@ FF_A_UNUSED static bool getTerminalVersionXfce4Terminal(FFstrbuf* exe, FFstrbuf* return getExeVersionGeneral(exe, version); // xfce4-terminal 1.0.4 (Xfce 4.18)... } -FF_A_UNUSED static bool getTerminalVersionKgx(FFstrbuf* version) { - if (ffProcessAppendStdOut(version, (char* const[]) { "kgx", "--version", NULL })) { +[[maybe_unused]] static bool getTerminalVersionKgx(FFstrbuf* version) { + if (ffProcessAppendStdOut(version, (char* const[]) { "kgx", "--version", nullptr })) { return false; } @@ -373,11 +380,11 @@ FF_A_UNUSED static bool getTerminalVersionKgx(FFstrbuf* version) { return true; } -FF_A_UNUSED static bool getTerminalVersionKonsole(FFstrbuf* exe, FFstrbuf* version) { +[[maybe_unused]] static bool getTerminalVersionKonsole(FFstrbuf* exe, FFstrbuf* version) { const char* konsoleVersion = getenv("KONSOLE_VERSION"); if (konsoleVersion) { // 221201 - long major = strtol(konsoleVersion, NULL, 10); + long major = strtol(konsoleVersion, nullptr, 10); if (major >= 0) { long patch = major % 100; major /= 100; @@ -395,9 +402,9 @@ FF_A_UNUSED static bool getTerminalVersionKonsole(FFstrbuf* exe, FFstrbuf* versi return ffStrbufSubstrAfterLastC(version, ' '); } -FF_A_UNUSED static bool getTerminalVersionFoot(FFstrbuf* exe, FFstrbuf* version) { +[[maybe_unused]] static bool getTerminalVersionFoot(FFstrbuf* exe, FFstrbuf* version) { uint32_t major = 0, minor = 0, patch = 0; - if (ffGetTerminalResponse("\e[>c", 3, "\e[>1;%2u%2u%2u;0c", &major, &minor, &patch) == NULL) { + if (ffGetTerminalResponse("\e[>c", 3, "\e[>1;%2u%2u%2u;0c", &major, &minor, &patch) == nullptr) { ffStrbufSetF(version, "%u.%u.%u", major, minor, patch); return true; } @@ -412,7 +419,7 @@ FF_A_UNUSED static bool getTerminalVersionFoot(FFstrbuf* exe, FFstrbuf* version) return true; } -FF_A_UNUSED static bool getTerminalVersionMateTerminal(FFstrbuf* exe, FFstrbuf* version) { +[[maybe_unused]] static bool getTerminalVersionMateTerminal(FFstrbuf* exe, FFstrbuf* version) { ffBinaryExtractStrings(exe->chars, extractGeneralVersion, version, (uint32_t) strlen("0.0.0")); if (version->length > 0) { return true; @@ -427,7 +434,7 @@ FF_A_UNUSED static bool getTerminalVersionMateTerminal(FFstrbuf* exe, FFstrbuf* return version->length > 0; } -FF_A_UNUSED static bool getTerminalVersionCockpit(FFstrbuf* exe, FFstrbuf* version) { +[[maybe_unused]] static bool getTerminalVersionCockpit(FFstrbuf* exe, FFstrbuf* version) { if (!getExeVersionRaw(exe, version)) { return false; } @@ -438,10 +445,10 @@ FF_A_UNUSED static bool getTerminalVersionCockpit(FFstrbuf* exe, FFstrbuf* versi return version->length > 0; } -FF_A_UNUSED static bool getTerminalVersionXterm(FFstrbuf* exe, FFstrbuf* version) { +[[maybe_unused]] static bool getTerminalVersionXterm(FFstrbuf* exe, FFstrbuf* version) { ffStrbufSetS(version, getenv("XTERM_VERSION")); if (!version->length) { - if (ffProcessAppendStdOut(version, (char* const[]) { exe->chars, "-v", NULL })) { + if (ffProcessAppendStdOut(version, (char* const[]) { exe->chars, "-v", nullptr })) { return false; } } @@ -452,8 +459,8 @@ FF_A_UNUSED static bool getTerminalVersionXterm(FFstrbuf* exe, FFstrbuf* version return version->length > 0; } -FF_A_UNUSED static bool getTerminalVersionBlackbox(FFstrbuf* exe, FFstrbuf* version) { - if (ffProcessAppendStdOut(version, (char* const[]) { exe->chars, "--version", NULL })) { +[[maybe_unused]] static bool getTerminalVersionBlackbox(FFstrbuf* exe, FFstrbuf* version) { + if (ffProcessAppendStdOut(version, (char* const[]) { exe->chars, "--version", nullptr })) { return false; } @@ -463,10 +470,10 @@ FF_A_UNUSED static bool getTerminalVersionBlackbox(FFstrbuf* exe, FFstrbuf* vers return version->length > 0; } -FF_A_UNUSED static bool getTerminalVersionUrxvt(FF_A_UNUSED FFstrbuf* exe, FFstrbuf* version) { +[[maybe_unused]] static bool getTerminalVersionUrxvt([[maybe_unused]] FFstrbuf* exe, FFstrbuf* version) { if (ffProcessAppendStdErr(version, (char* const[]) { "urxvt", // Don't use exe because of urxvtd "-invalid", - NULL })) { + nullptr })) { return false; } @@ -478,8 +485,8 @@ FF_A_UNUSED static bool getTerminalVersionUrxvt(FF_A_UNUSED FFstrbuf* exe, FFstr return version->length > 0; } -FF_A_UNUSED static bool getTerminalVersionSt(FF_A_UNUSED FFstrbuf* exe, FFstrbuf* version) { - if (ffProcessAppendStdErr(version, (char* const[]) { exe->chars, "-v", NULL })) { +[[maybe_unused]] static bool getTerminalVersionSt([[maybe_unused]] FFstrbuf* exe, FFstrbuf* version) { + if (ffProcessAppendStdErr(version, (char* const[]) { exe->chars, "-v", nullptr })) { return false; } @@ -489,7 +496,7 @@ FF_A_UNUSED static bool getTerminalVersionSt(FF_A_UNUSED FFstrbuf* exe, FFstrbuf return version->length > 0; } -FF_A_UNUSED static bool getTerminalVersionLxterminal(FFstrbuf* exe, FFstrbuf* version) { +[[maybe_unused]] static bool getTerminalVersionLxterminal(FFstrbuf* exe, FFstrbuf* version) { if (!getExeVersionRaw(exe, version)) { return false; } @@ -498,9 +505,9 @@ FF_A_UNUSED static bool getTerminalVersionLxterminal(FFstrbuf* exe, FFstrbuf* ve return version->length > 0; } -FF_A_UNUSED static bool getTerminalVersionWeston(FF_A_UNUSED FFstrbuf* exe, FFstrbuf* version) { +[[maybe_unused]] static bool getTerminalVersionWeston([[maybe_unused]] FFstrbuf* exe, FFstrbuf* version) { // weston-terminal doesn't report a version, use weston version instead - if (ffProcessAppendStdOut(version, (char* const[]) { "weston", "--version", NULL })) { + if (ffProcessAppendStdOut(version, (char* const[]) { "weston", "--version", nullptr })) { return false; } @@ -510,7 +517,7 @@ FF_A_UNUSED static bool getTerminalVersionWeston(FF_A_UNUSED FFstrbuf* exe, FFst return version->length > 0; } -FF_A_UNUSED static bool extractKmsconVersion(const char* str, FF_A_UNUSED uint32_t len, void* userdata) { +[[maybe_unused]] static bool extractKmsconVersion(const char* str, [[maybe_unused]] uint32_t len, void* userdata) { if (!ffStrStartsWith(str, "v")) { return true; } @@ -523,7 +530,7 @@ FF_A_UNUSED static bool extractKmsconVersion(const char* str, FF_A_UNUSED uint32 return false; } -FF_A_UNUSED static bool getTerminalVersionKmscon(FFstrbuf* exe, FFstrbuf* version) { +[[maybe_unused]] static bool getTerminalVersionKmscon(FFstrbuf* exe, FFstrbuf* version) { if (ffIsAbsolutePath(exe->chars)) { ffBinaryExtractStrings(exe->chars, extractKmsconVersion, version, (uint32_t) strlen("v0.0.0")); if (version->length) { @@ -565,7 +572,7 @@ static bool getTerminalVersionScreen(FFstrbuf* exe, FFstrbuf* version) { } static bool getTerminalVersionTmux(FFstrbuf* exe, FFstrbuf* version) { - if (ffProcessAppendStdOut(version, (char* const[]) { exe->chars, "-V", NULL }) != NULL) { + if (ffProcessAppendStdOut(version, (char* const[]) { exe->chars, "-V", nullptr }) != nullptr) { return false; } @@ -593,7 +600,7 @@ static bool getTerminalVersionZed(FFstrbuf* exe, FFstrbuf* version) { #endif ); - if (ffProcessAppendStdOut(version, (char* const[]) { cli.chars, "--version", NULL }) != NULL) { + if (ffProcessAppendStdOut(version, (char* const[]) { cli.chars, "--version", nullptr }) != nullptr) { return false; } @@ -603,7 +610,7 @@ static bool getTerminalVersionZed(FFstrbuf* exe, FFstrbuf* version) { return true; } -static bool extractSshdVersion(const char* str, FF_A_UNUSED uint32_t len, void* userdata) { +static bool extractSshdVersion(const char* str, [[maybe_unused]] uint32_t len, void* userdata) { if (!ffStrStartsWith(str, "OpenSSH_") || !ffCharIsDigit(str[strlen("OpenSSH_")])) { return true; } @@ -621,7 +628,7 @@ static bool getTerminalVersionSshd(FFstrbuf* exe, FFstrbuf* version) { FF_STRBUF_AUTO_DESTROY exePath = ffStrbufCreate(); if (ffIsAbsolutePath(exe->chars)) { ffStrbufSet(&exePath, exe); - } else if (ffFindExecutableInPath("sshd", &exePath) != NULL) { + } else if (ffFindExecutableInPath("sshd", &exePath) != nullptr) { return false; } @@ -630,7 +637,7 @@ static bool getTerminalVersionSshd(FFstrbuf* exe, FFstrbuf* version) { return true; } - if (ffProcessAppendStdOut(version, (char* const[]) { exePath.chars, "-V", NULL }) != NULL) { + if (ffProcessAppendStdOut(version, (char* const[]) { exePath.chars, "-V", nullptr }) != nullptr) { return false; } @@ -669,7 +676,7 @@ static bool getTerminalVersionKitty(FFstrbuf* exe, FFstrbuf* version) { } } #elif __APPLE__ - if (ffGetAppNameAndVersion(exe->chars, NULL, version)) { + if (ffGetAppNameAndVersion(exe->chars, nullptr, version)) { return true; } #endif @@ -680,7 +687,7 @@ static bool getTerminalVersionKitty(FFstrbuf* exe, FFstrbuf* version) { "\eP+q6b697474792d71756572792d76657273696f6e\e\\", // kitty-query-version 1, "\eP1+r%*[^=]=%63[^\e]\e\\\\", - versionHex) == NULL) { + versionHex) == nullptr) { // decode hex string for (const char* p = versionHex; p[0] && p[1]; p += 2) { unsigned value; @@ -695,8 +702,8 @@ static bool getTerminalVersionKitty(FFstrbuf* exe, FFstrbuf* version) { return getExeVersionGeneral(exe, version); } -FF_A_UNUSED static bool getTerminalVersionPtyxis(FF_A_UNUSED FFstrbuf* exe, FFstrbuf* version) { - if (ffProcessAppendStdOut(version, (char* const[]) { "ptyxis", "--version", NULL }) != NULL) { +[[maybe_unused]] static bool getTerminalVersionPtyxis([[maybe_unused]] FFstrbuf* exe, FFstrbuf* version) { + if (ffProcessAppendStdOut(version, (char* const[]) { "ptyxis", "--version", nullptr }) != nullptr) { return false; } @@ -705,7 +712,7 @@ FF_A_UNUSED static bool getTerminalVersionPtyxis(FF_A_UNUSED FFstrbuf* exe, FFst return true; } -FF_A_UNUSED static bool getTerminalVersionTilix(FFstrbuf* exe, FFstrbuf* version) { +[[maybe_unused]] static bool getTerminalVersionTilix(FFstrbuf* exe, FFstrbuf* version) { if (ffIsAbsolutePath(exe->chars)) { ffBinaryExtractStrings(exe->chars, extractGeneralVersion, version, (uint32_t) strlen("0.0.0")); if (version->length) { @@ -713,7 +720,7 @@ FF_A_UNUSED static bool getTerminalVersionTilix(FFstrbuf* exe, FFstrbuf* version } } - if (ffProcessAppendStdOut(version, (char* const[]) { exe->chars, "--version", NULL }) != NULL) { + if (ffProcessAppendStdOut(version, (char* const[]) { exe->chars, "--version", nullptr }) != nullptr) { return false; } @@ -730,8 +737,8 @@ FF_A_UNUSED static bool getTerminalVersionTilix(FFstrbuf* exe, FFstrbuf* version return true; } -FF_A_UNUSED static bool getTerminalVersionSakura(FFstrbuf* exe, FFstrbuf* version) { - if (ffProcessAppendStdErr(version, (char* const[]) { exe->chars, "--version", NULL }) != NULL) { // sakura version is 3.8.8 +[[maybe_unused]] static bool getTerminalVersionSakura(FFstrbuf* exe, FFstrbuf* version) { + if (ffProcessAppendStdErr(version, (char* const[]) { exe->chars, "--version", nullptr }) != nullptr) { // sakura version is 3.8.8 return false; } @@ -739,8 +746,8 @@ FF_A_UNUSED static bool getTerminalVersionSakura(FFstrbuf* exe, FFstrbuf* versio return true; } -FF_A_UNUSED static bool getTerminalVersionTermite(FFstrbuf* exe, FFstrbuf* version) { - if (ffProcessAppendStdOut(version, (char* const[]) { exe->chars, "--version", NULL }) != NULL) { // termite v16.9\nvte 0.78.1 +BIDI +GNUTLS +ICU +SYSTEMD +[[maybe_unused]] static bool getTerminalVersionTermite(FFstrbuf* exe, FFstrbuf* version) { + if (ffProcessAppendStdOut(version, (char* const[]) { exe->chars, "--version", nullptr }) != nullptr) { // termite v16.9\nvte 0.78.1 +BIDI +GNUTLS +ICU +SYSTEMD return false; } @@ -762,7 +769,7 @@ static bool getTerminalVersionWindowsTerminal(FFstrbuf* exe, FFstrbuf* version) return true; } - return getFileVersion(exe, NULL, version); + return getFileVersion(exe, nullptr, version); } static bool getTerminalVersionConEmu(FFstrbuf* exe, FFstrbuf* version) { @@ -772,12 +779,12 @@ static bool getTerminalVersionConEmu(FFstrbuf* exe, FFstrbuf* version) { return true; } - return getFileVersion(exe, NULL, version); + return getFileVersion(exe, nullptr, version); } #endif -bool fftsGetTerminalVersion(FFstrbuf* processName, FF_A_UNUSED FFstrbuf* exe, FFstrbuf* version) { +bool fftsGetTerminalVersion(FFstrbuf* processName, [[maybe_unused]] FFstrbuf* exe, FFstrbuf* version) { #ifdef __ANDROID__ if (ffStrbufEqualS(processName, "com.termux")) { @@ -980,11 +987,11 @@ bool fftsGetTerminalVersion(FFstrbuf* processName, FF_A_UNUSED FFstrbuf* exe, FF #ifdef _WIN32 - return getFileVersion(exe, NULL, version); + return getFileVersion(exe, nullptr, version); #elif __APPLE__ - return ffGetAppNameAndVersion(exe->chars, NULL, version); + return ffGetAppNameAndVersion(exe->chars, nullptr, version); #else diff --git a/src/detection/terminalshell/terminalshell_linux.c b/src/detection/terminalshell/terminalshell_linux.c index 1eccf26ebd..ae7e07b9cf 100644 --- a/src/detection/terminalshell/terminalshell_linux.c +++ b/src/detection/terminalshell/terminalshell_linux.c @@ -21,7 +21,7 @@ static pid_t getShellInfo(FFShellResult* result, pid_t pid) { pid_t ppid = 0; int32_t tty = -1; - const char* userShellName = NULL; + const char* userShellName = nullptr; { uint32_t index = ffStrbufLastIndexC(&instance.state.platform.userShell, '/'); if (index == instance.state.platform.userShell.length) { @@ -31,7 +31,7 @@ static pid_t getShellInfo(FFShellResult* result, pid_t pid) { } } - while (pid > 1 && ffProcessGetBasicInfoLinux(pid, &result->processName, &ppid, &tty) == NULL) { + while (pid > 1 && ffProcessGetBasicInfoLinux(pid, &result->processName, &ppid, &tty) == nullptr) { if (!ffStrbufEqualS(&result->processName, userShellName)) { // Common programs that are between terminal and own process, but are not the shell if ( @@ -79,7 +79,7 @@ static pid_t getShellInfo(FFShellResult* result, pid_t pid) { static pid_t getTerminalInfo(FFTerminalResult* result, pid_t pid) { pid_t ppid = 0; - while (pid > 1 && ffProcessGetBasicInfoLinux(pid, &result->processName, &ppid, NULL) == NULL) { + while (pid > 1 && ffProcessGetBasicInfoLinux(pid, &result->processName, &ppid, nullptr) == nullptr) { // Known shells if ( pid == 1 || // init/systemd @@ -130,7 +130,7 @@ static pid_t getTerminalInfo(FFTerminalResult* result, pid_t pid) { break; } } - if (pLeft == pRight && ffProcessGetBasicInfoLinux(ppid, &result->processName, &ppid, NULL) != NULL) { + if (pLeft == pRight && ffProcessGetBasicInfoLinux(ppid, &result->processName, &ppid, nullptr) != nullptr) { return 0; } } @@ -147,13 +147,13 @@ static pid_t getTerminalInfo(FFTerminalResult* result, pid_t pid) { static bool getTerminalInfoByPidEnv(FFTerminalResult* result, const char* pidEnv) { const char* envStr = getenv(pidEnv); - if (envStr == NULL) { + if (envStr == nullptr) { return false; } - pid_t pid = (pid_t) strtol(envStr, NULL, 10); + pid_t pid = (pid_t) strtol(envStr, nullptr, 10); result->pid = (uint32_t) pid; - if (ffProcessGetBasicInfoLinux(pid, &result->processName, (pid_t*) &result->ppid, NULL) == NULL) { + if (ffProcessGetBasicInfoLinux(pid, &result->processName, (pid_t*) &result->ppid, nullptr) == nullptr) { ffProcessGetInfoLinux(pid, &result->processName, &result->exe, &result->exeName, &result->exePath); return true; } @@ -185,15 +185,15 @@ static void getTerminalFromEnv(FFTerminalResult* result) { result->pid = result->ppid = 0; } - const char* term = NULL; + const char* term = nullptr; // SSH if ( - getenv("SSH_TTY") != NULL) { + getenv("SSH_TTY") != nullptr) { term = getenv("SSH_TTY"); } else if ( - getenv("KITTY_PID") != NULL || - getenv("KITTY_INSTALLATION_DIR") != NULL) { + getenv("KITTY_PID") != nullptr || + getenv("KITTY_INSTALLATION_DIR") != nullptr) { if (getTerminalInfoByPidEnv(result, "KITTY_PID")) { return; } @@ -203,29 +203,29 @@ static void getTerminalFromEnv(FFTerminalResult* result) { #ifdef __linux__ // WSL // Windows Terminal else if ( - getenv("WT_SESSION") != NULL || - getenv("WT_PROFILE_ID") != NULL) + getenv("WT_SESSION") != nullptr || + getenv("WT_PROFILE_ID") != nullptr) term = "Windows Terminal"; // ConEmu else if ( - getenv("ConEmuPID") != NULL) { + getenv("ConEmuPID") != nullptr) { term = "ConEmu"; } #endif // Alacritty else if ( - getenv("ALACRITTY_SOCKET") != NULL || - getenv("ALACRITTY_LOG") != NULL || - getenv("ALACRITTY_WINDOW_ID") != NULL) { + getenv("ALACRITTY_SOCKET") != nullptr || + getenv("ALACRITTY_LOG") != nullptr || + getenv("ALACRITTY_WINDOW_ID") != nullptr) { term = "Alacritty"; } #ifdef __ANDROID__ // Termux else if ( - getenv("TERMUX_VERSION") != NULL || - getenv("TERMUX_MAIN_PACKAGE_FORMAT") != NULL) { + getenv("TERMUX_VERSION") != nullptr || + getenv("TERMUX_MAIN_PACKAGE_FORMAT") != nullptr) { if (getTerminalInfoByPidEnv(result, "TERMUX_APP__PID")) { return; } @@ -236,22 +236,22 @@ static void getTerminalFromEnv(FFTerminalResult* result) { #if defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__GNU__) // Konsole else if ( - getenv("KONSOLE_VERSION") != NULL) + getenv("KONSOLE_VERSION") != nullptr) term = "konsole"; else if ( - getenv("GNOME_TERMINAL_SCREEN") != NULL || - getenv("GNOME_TERMINAL_SERVICE") != NULL) { + getenv("GNOME_TERMINAL_SCREEN") != nullptr || + getenv("GNOME_TERMINAL_SERVICE") != nullptr) { term = "gnome-terminal"; } #endif // MacOS, mintty - else if (getenv("TERM_PROGRAM") != NULL) { + else if (getenv("TERM_PROGRAM") != nullptr) { term = getenv("TERM_PROGRAM"); } - else if (getenv("LC_TERMINAL") != NULL) { + else if (getenv("LC_TERMINAL") != nullptr) { term = getenv("LC_TERMINAL"); } @@ -398,7 +398,7 @@ const FFShellResult* ffDetectShell() { const char* ignoreParent = getenv("FFTS_IGNORE_PARENT"); if (ignoreParent && ffStrEquals(ignoreParent, "1")) { FF_STRBUF_AUTO_DESTROY _ = ffStrbufCreate(); - ffProcessGetBasicInfoLinux(ppid, &_, &ppid, NULL); + ffProcessGetBasicInfoLinux(ppid, &_, &ppid, nullptr); } ppid = getShellInfo(&result, ppid); diff --git a/src/detection/terminalshell/terminalshell_windows.c b/src/detection/terminalshell/terminalshell_windows.c index d037663c83..08cdb17bad 100644 --- a/src/detection/terminalshell/terminalshell_windows.c +++ b/src/detection/terminalshell/terminalshell_windows.c @@ -36,7 +36,7 @@ static uint32_t getShellInfo(FFShellResult* result, uint32_t pid) { ffStrbufClear(&result->processName); ffStrbufClear(&result->prettyName); ffStrbufClear(&result->exe); - result->exeName = NULL; + result->exeName = nullptr; pid = ppid; continue; } @@ -70,7 +70,7 @@ static void setShellInfoDetails(FFShellResult* result) { ffStrbufSetS(&result->prettyName, "CMD"); if (instance.config.general.detectVersion) { - FF_AUTO_CLOSE_FD HANDLE snapshot = NULL; + FF_AUTO_CLOSE_FD HANDLE snapshot = nullptr; while (!(snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, result->pid)) && GetLastError() == ERROR_BAD_LENGTH) {} if (snapshot) { @@ -79,7 +79,7 @@ static void setShellInfoDetails(FFShellResult* result) { for (BOOL success = Module32FirstW(snapshot, &module); success; success = Module32NextW(snapshot, &module)) { if (wcsncmp(module.szModule, L"clink_dll_", strlen("clink_dll_")) == 0) { FF_STRBUF_AUTO_DESTROY clinkVersion = ffStrbufCreate(); - if (ffGetFileVersion(module.szExePath, NULL, &clinkVersion)) { + if (ffGetFileVersion(module.szExePath, nullptr, &clinkVersion)) { ffStrbufAppendF(&result->prettyName, " (with Clink %s)", clinkVersion.chars); } else { ffStrbufAppendS(&result->prettyName, " (with Clink)"); @@ -109,9 +109,9 @@ static bool getTerminalFromEnv(FFTerminalResult* result) { if (term) { // ConEmu - uint32_t pid = (uint32_t) strtoul(term, NULL, 10); + uint32_t pid = (uint32_t) strtoul(term, nullptr, 10); result->pid = pid; - if (ffProcessGetInfoWindows(pid, NULL, &result->processName, &result->exe, &result->exeName, &result->exePath, NULL)) { + if (ffProcessGetInfoWindows(pid, nullptr, &result->processName, &result->exe, &result->exeName, &result->exePath, nullptr)) { ffStrbufSet(&result->prettyName, &result->processName); if (ffStrbufEndsWithIgnCaseS(&result->prettyName, ".exe")) { ffStrbufSubstrBefore(&result->prettyName, result->prettyName.length - 4); @@ -123,17 +123,17 @@ static bool getTerminalFromEnv(FFTerminalResult* result) { } // SSH - if (getenv("SSH_TTY") != NULL) { + if (getenv("SSH_TTY") != nullptr) { term = getenv("SSH_TTY"); } // Windows Terminal - if (!term && (getenv("WT_SESSION") != NULL || getenv("WT_PROFILE_ID") != NULL)) { + if (!term && (getenv("WT_SESSION") != nullptr || getenv("WT_PROFILE_ID") != nullptr)) { term = "WindowsTerminal"; } // Alacritty - if (!term && (getenv("ALACRITTY_SOCKET") != NULL || getenv("ALACRITTY_LOG") != NULL || getenv("ALACRITTY_WINDOW_ID") != NULL)) { + if (!term && (getenv("ALACRITTY_SOCKET") != nullptr || getenv("ALACRITTY_LOG") != nullptr || getenv("ALACRITTY_WINDOW_ID") != nullptr)) { term = "Alacritty"; } @@ -160,32 +160,32 @@ static bool getTerminalFromEnv(FFTerminalResult* result) { static bool detectDefaultTerminal(FFTerminalResult* result) { wchar_t regPath[128] = L"SOFTWARE\\Classes\\PackagedCom\\ClassIndex\\"; wchar_t* uuid = regPath + strlen("SOFTWARE\\Classes\\PackagedCom\\ClassIndex\\"); - FF_AUTO_CLOSE_FD HANDLE hkcu = NULL; - if (ffRegOpenKeyForRead(HKEY_CURRENT_USER, L"Console\\%%Startup", &hkcu, NULL) && + FF_AUTO_CLOSE_FD HANDLE hkcu = nullptr; + if (ffRegOpenKeyForRead(HKEY_CURRENT_USER, L"Console\\%%Startup", &hkcu, nullptr) && ffRegReadData(hkcu, L"DelegationTerminal", &(FFArgBuffer) { .data = uuid, .length = (uint32_t) (sizeof(regPath) - (size_t) (uuid - regPath) * sizeof(wchar_t)), }, - NULL)) { + nullptr)) { if (wcscmp(uuid, L"{00000000-0000-0000-0000-000000000000}") == 0 || // Let Windows decide wcscmp(uuid, L"{B23D10C0-E52E-411E-9D5B-C09FDF709C7D}") == 0) // Conhost { goto conhost; } - FF_AUTO_CLOSE_FD HANDLE hklm = NULL; - if (ffRegOpenKeyForRead(HKEY_LOCAL_MACHINE, regPath, &hklm, NULL)) { + FF_AUTO_CLOSE_FD HANDLE hklm = nullptr; + if (ffRegOpenKeyForRead(HKEY_LOCAL_MACHINE, regPath, &hklm, nullptr)) { FF_STRBUF_AUTO_DESTROY path = ffStrbufCreate(); - if (ffRegGetSubKey(hklm, 0, &path, NULL)) { + if (ffRegGetSubKey(hklm, 0, &path, nullptr)) { if (ffStrbufStartsWithS(&path, "Microsoft.WindowsTerminal")) { ffStrbufSetS(&result->processName, "WindowsTerminal.exe"); ffStrbufSetS(&result->prettyName, "WindowsTerminal"); - PWSTR programFiles = NULL; - if (SUCCEEDED(SHGetKnownFolderPath(&FOLDERID_ProgramFiles, KF_FLAG_DEFAULT, NULL, &programFiles))) { + PWSTR programFiles = nullptr; + if (SUCCEEDED(SHGetKnownFolderPath(&FOLDERID_ProgramFiles, KF_FLAG_DEFAULT, nullptr, &programFiles))) { ffStrbufSetWS(&result->exe, programFiles); CoTaskMemFree(programFiles); - programFiles = NULL; + programFiles = nullptr; ffStrbufAppendS(&result->exe, "\\WindowsApps\\"); ffStrbufAppend(&result->exe, &path); @@ -211,7 +211,7 @@ conhost:; ULONG size; if (NT_SUCCESS(NtQueryInformationProcess(NtCurrentProcess(), ProcessConsoleHostProcess, &conhostPid, sizeof(conhostPid), &size)) && conhostPid != 0) { // For Windows Terminal, it reports the PID of OpenConsole - if (ffProcessGetInfoWindows((uint32_t) conhostPid, NULL, &result->processName, &result->exe, &result->exeName, &result->exePath, NULL)) { + if (ffProcessGetInfoWindows((uint32_t) conhostPid, nullptr, &result->processName, &result->exe, &result->exeName, &result->exePath, nullptr)) { ffStrbufSet(&result->prettyName, &result->processName); if (ffStrbufEndsWithIgnCaseS(&result->prettyName, ".exe")) { ffStrbufSubstrBefore(&result->prettyName, result->prettyName.length - 4); @@ -311,13 +311,13 @@ const FFShellResult* ffDetectShell(void) { result.tty = -1; uint32_t ppid; - if (!ffProcessGetInfoWindows(0, &ppid, NULL, NULL, NULL, NULL, NULL)) { + if (!ffProcessGetInfoWindows(0, &ppid, nullptr, nullptr, nullptr, nullptr, nullptr)) { return &result; } const char* ignoreParent = getenv("FFTS_IGNORE_PARENT"); if (ignoreParent && ffStrEquals(ignoreParent, "1")) { - ffProcessGetInfoWindows(ppid, &ppid, NULL, NULL, NULL, NULL, NULL); + ffProcessGetInfoWindows(ppid, &ppid, nullptr, nullptr, nullptr, nullptr, nullptr); } ppid = getShellInfo(&result, ppid); diff --git a/src/detection/terminalsize/terminalsize_windows.c b/src/detection/terminalsize/terminalsize_windows.c index 05888e78b8..8e8af789a3 100644 --- a/src/detection/terminalsize/terminalsize_windows.c +++ b/src/detection/terminalsize/terminalsize_windows.c @@ -9,7 +9,7 @@ bool ffDetectTerminalSize(FFTerminalSizeResult* result) { { DWORD outputMode; if (!GetConsoleMode(hOutput, &outputMode)) { - hConout = CreateFileW(L"CONOUT$", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, NULL); + hConout = CreateFileW(L"CONOUT$", GENERIC_READ | GENERIC_WRITE, FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, nullptr); hOutput = hConout; } } diff --git a/src/detection/terminaltheme/terminaltheme.c b/src/detection/terminaltheme/terminaltheme.c index e609754d7c..41b67f88af 100644 --- a/src/detection/terminaltheme/terminaltheme.c +++ b/src/detection/terminaltheme/terminaltheme.c @@ -14,7 +14,7 @@ static bool detectByEscapeCode(FFTerminalThemeResult* result) { &result->fg.b, &result->bg.r, &result->bg.g, - &result->bg.b) == NULL) { + &result->bg.b) == nullptr) { if (result->fg.r > 0x0100 || result->fg.g > 0x0100 || result->fg.b > 0x0100) { result->fg.r /= 0x0100, result->fg.g /= 0x0100, result->fg.b /= 0x0100; } diff --git a/src/detection/theme/theme_apple.c b/src/detection/theme/theme_apple.c index a60d39cdbf..99ee1d38aa 100644 --- a/src/detection/theme/theme_apple.c +++ b/src/detection/theme/theme_apple.c @@ -18,5 +18,5 @@ const char* ffDetectTheme(FFThemeResult* result) { } } - return NULL; + return nullptr; } diff --git a/src/detection/theme/theme_linux.c b/src/detection/theme/theme_linux.c index 1de7db8196..6f2bc21173 100644 --- a/src/detection/theme/theme_linux.c +++ b/src/detection/theme/theme_linux.c @@ -56,5 +56,5 @@ const char* ffDetectTheme(FFThemeResult* result) { ffStrbufAppendS(&result->theme1, " [Qt]"); } - return NULL; + return nullptr; } diff --git a/src/detection/theme/theme_nosupport.c b/src/detection/theme/theme_nosupport.c index 6f42b964d7..4e58860b20 100644 --- a/src/detection/theme/theme_nosupport.c +++ b/src/detection/theme/theme_nosupport.c @@ -1,5 +1,5 @@ #include "theme.h" -const char* ffDetectTheme(FF_A_UNUSED FFThemeResult* result) { +const char* ffDetectTheme([[maybe_unused]] FFThemeResult* result) { return "Not supported on this platform"; } diff --git a/src/detection/theme/theme_windows.c b/src/detection/theme/theme_windows.c index 339b79be93..4c82d2c04e 100644 --- a/src/detection/theme/theme_windows.c +++ b/src/detection/theme/theme_windows.c @@ -1,27 +1,34 @@ #include "theme.h" #include "detection/os/os.h" +#include "detection/displayserver/displayserver.h" const char* ffDetectTheme(FFThemeResult* result) { const FFOSResult* os = ffDetectOS(); + const FFDisplayServerResult* displayServer = ffConnectDisplayServer(); + if (ffStrbufEqualS(&displayServer->wmProcessName, "dwm.exe")) { + uint32_t ver = (uint32_t) ffStrbufToUInt(&os->version, 0); - if (ver > 1000) { - // Windows Server - if (ver >= 2016) { - ffStrbufSetStatic(&result->theme1, "Fluent"); - } else if (ver >= 2012) { - ffStrbufSetStatic(&result->theme1, "Metro"); - } else { - ffStrbufSetStatic(&result->theme1, "Aero"); - } - } else { - if (ver >= 10) { - ffStrbufSetStatic(&result->theme1, "Fluent"); - } else if (ver >= 8) { - ffStrbufSetStatic(&result->theme1, "Metro"); + if (ver > 1000) { + // Windows Server + if (ver >= 2016) { + ffStrbufSetStatic(&result->theme1, "Fluent"); + } else if (ver >= 2012) { + ffStrbufSetStatic(&result->theme1, "Metro"); + } else { + ffStrbufSetStatic(&result->theme1, "Aero"); + } } else { - ffStrbufSetStatic(&result->theme1, "Aero"); + if (ver >= 10) { + ffStrbufSetStatic(&result->theme1, "Fluent"); + } else if (ver >= 8) { + ffStrbufSetStatic(&result->theme1, "Metro"); + } else { + ffStrbufSetStatic(&result->theme1, "Aero"); + } } + } else if (ffStrbufEqualS(&displayServer->wmProcessName, "explorer.exe")) { + ffStrbufSetStatic(&result->theme1, "Basic"); } - return NULL; + return nullptr; } diff --git a/src/detection/tpm/tpm_apple.c b/src/detection/tpm/tpm_apple.c index 250dd014ed..b97ecf05bd 100644 --- a/src/detection/tpm/tpm_apple.c +++ b/src/detection/tpm/tpm_apple.c @@ -10,7 +10,7 @@ const char* ffDetectTPM(FFTPMResult* result) { ffStrbufSetStatic(&result->version, "2.0"); ffStrbufSetStatic(&result->description, "Apple Silicon Security"); - return NULL; + return nullptr; #else @@ -21,7 +21,7 @@ const char* ffDetectTPM(FFTPMResult* result) { if (t2Service) { ffStrbufSetStatic(&result->version, "2.0"); ffStrbufSetStatic(&result->description, "Apple T2 Security Chip"); - return NULL; + return nullptr; } #endif diff --git a/src/detection/tpm/tpm_bsd.c b/src/detection/tpm/tpm_bsd.c index 4b73413063..1df25fb477 100644 --- a/src/detection/tpm/tpm_bsd.c +++ b/src/detection/tpm/tpm_bsd.c @@ -3,7 +3,7 @@ #include "common/kmod.h" const char* ffDetectTPM(FFTPMResult* result) { - if (ffSysctlGetString("dev.tpmcrb.0.%desc", &result->description) != NULL) { + if (ffSysctlGetString("dev.tpmcrb.0.%desc", &result->description) != nullptr) { if (!ffKmodLoaded("tpm")) { return "`tpm` kernel module is not loaded"; } @@ -18,5 +18,5 @@ const char* ffDetectTPM(FFTPMResult* result) { ffStrbufSetStatic(&result->version, "unknown"); } - return NULL; + return nullptr; } diff --git a/src/detection/tpm/tpm_linux.c b/src/detection/tpm/tpm_linux.c index 040da38ccc..7a54f27f81 100644 --- a/src/detection/tpm/tpm_linux.c +++ b/src/detection/tpm/tpm_linux.c @@ -20,5 +20,5 @@ const char* ffDetectTPM(FFTPMResult* result) { ffStrbufTrimRightSpace(&result->description); } - return NULL; + return nullptr; } diff --git a/src/detection/tpm/tpm_nosupport.c b/src/detection/tpm/tpm_nosupport.c index 492f37f756..2e48e2b4e9 100644 --- a/src/detection/tpm/tpm_nosupport.c +++ b/src/detection/tpm/tpm_nosupport.c @@ -1,5 +1,5 @@ #include "tpm.h" -const char* ffDetectTPM(FF_A_UNUSED FFTPMResult* result) { +const char* ffDetectTPM([[maybe_unused]] FFTPMResult* result) { return "Not supported on this platform"; } diff --git a/src/detection/tpm/tpm_windows.c b/src/detection/tpm/tpm_windows.c index 14f6e8a4e8..bf3746a62a 100644 --- a/src/detection/tpm/tpm_windows.c +++ b/src/detection/tpm/tpm_windows.c @@ -47,5 +47,5 @@ const char* ffDetectTPM(FFTPMResult* result) { break; } - return NULL; + return nullptr; } diff --git a/src/detection/uptime/uptime_bsd.c b/src/detection/uptime/uptime_bsd.c index 46943b0290..00d052b370 100644 --- a/src/detection/uptime/uptime_bsd.c +++ b/src/detection/uptime/uptime_bsd.c @@ -12,7 +12,7 @@ const char* ffDetectUptime(FFUptimeResult* result) { #endif size_t bootTimeSize = sizeof(bootTime); if (sysctl( - (int[]) { CTL_KERN, KERN_BOOTTIME }, 2, &bootTime, &bootTimeSize, NULL, 0) != 0) { + (int[]) { CTL_KERN, KERN_BOOTTIME }, 2, &bootTime, &bootTimeSize, nullptr, 0) != 0) { return "sysctl({CTL_KERN, KERN_BOOTTIME}) failed"; } @@ -23,5 +23,5 @@ const char* ffDetectUptime(FFUptimeResult* result) { #endif result->uptime = ffTimeGetNow() - result->bootTime; - return NULL; + return nullptr; } diff --git a/src/detection/uptime/uptime_haiku.c b/src/detection/uptime/uptime_haiku.c index bf5dd25c7e..58434f0b19 100644 --- a/src/detection/uptime/uptime_haiku.c +++ b/src/detection/uptime/uptime_haiku.c @@ -4,5 +4,5 @@ const char* ffDetectUptime(FFUptimeResult* result) { result->uptime = (uint64_t) system_time() / 1000; result->bootTime = ffTimeGetNow() - result->uptime; - return NULL; + return nullptr; } diff --git a/src/detection/uptime/uptime_linux.c b/src/detection/uptime/uptime_linux.c index 75c7768a86..9ac709416f 100644 --- a/src/detection/uptime/uptime_linux.c +++ b/src/detection/uptime/uptime_linux.c @@ -13,12 +13,12 @@ const char* ffDetectUptime(FFUptimeResult* result) { if (nRead > 0) { buf[nRead] = '\0'; - char* err = NULL; + char* err = nullptr; double sec = strtod(buf, &err); if (err != buf) { result->uptime = (uint64_t) (sec * 1000); result->bootTime = ffTimeGetNow() - result->uptime; - return NULL; + return nullptr; } } @@ -31,7 +31,7 @@ const char* ffDetectUptime(FFUptimeResult* result) { result->uptime = (uint64_t) uptime.tv_sec * 1000 + (uint64_t) uptime.tv_nsec / 1000000; result->bootTime = ffTimeGetNow() - result->uptime; - return NULL; + return nullptr; #else return "read(/proc/uptime) failed"; #endif diff --git a/src/detection/uptime/uptime_sunos.c b/src/detection/uptime/uptime_sunos.c index 2a372999e8..1e6aa4fd29 100644 --- a/src/detection/uptime/uptime_sunos.c +++ b/src/detection/uptime/uptime_sunos.c @@ -7,7 +7,7 @@ const char* ffDetectUptime(FFUptimeResult* result) { struct utmpx* ut; setutxent(); - while (NULL != (ut = getutxent())) { + while (nullptr != (ut = getutxent())) { if (ut->ut_type == BOOT_TIME) { result->bootTime = (uint64_t) ut->ut_tv.tv_sec * 1000 + (uint64_t) ut->ut_tv.tv_usec / 1000000; result->uptime = ffTimeGetNow() - result->bootTime; @@ -15,5 +15,5 @@ const char* ffDetectUptime(FFUptimeResult* result) { } } endutxent(); - return NULL; + return nullptr; } diff --git a/src/detection/uptime/uptime_windows.c b/src/detection/uptime/uptime_windows.c index 695edadea6..5abf68ae04 100644 --- a/src/detection/uptime/uptime_windows.c +++ b/src/detection/uptime/uptime_windows.c @@ -13,5 +13,5 @@ const char* ffDetectUptime(FFUptimeResult* result) { // whose result exactly equals what WMI `Win32_OperatingSystem` reports // with much lower accuracy (0.5 seconds) - return NULL; + return nullptr; } diff --git a/src/detection/users/users_linux.c b/src/detection/users/users_linux.c index bc84eedbf9..a5f31d2a0b 100644 --- a/src/detection/users/users_linux.c +++ b/src/detection/users/users_linux.c @@ -52,7 +52,7 @@ bool detectUserBySystemd(const FFstrbuf* pathUsers, FFlist* users) { FF_STRBUF_AUTO_DESTROY remoteHost = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY service = ffStrbufCreate(); - char* token = NULL; + char* token = nullptr; size_t n = 0; while (ffStrbufGetdelim(&token, &n, ' ', &sessions)) { ffStrbufSubstrBefore(&pathSessions, pathSessionsBaseLen); @@ -116,7 +116,7 @@ const char* detectBySystemd(FFUsersOptions* options, FFlist* users) { ffStrbufSubstrBefore(&pathUsers, pathUsersBaseLen); } } - return NULL; + return nullptr; } #endif @@ -132,23 +132,23 @@ static void fillUtmpIpAddr(FFUserResult* user, struct utmpx* n) { if (isIpv6) { char ipv6_str[INET6_ADDRSTRLEN]; - if (inet_ntop(AF_INET6, n->ut_addr_v6, ipv6_str, INET6_ADDRSTRLEN) != NULL) { + if (inet_ntop(AF_INET6, n->ut_addr_v6, ipv6_str, INET6_ADDRSTRLEN) != nullptr) { ffStrbufSetS(&user->clientIp, ipv6_str); } } else if (n->ut_addr_v6[0] != 0) { char ipv4_str[INET_ADDRSTRLEN]; - if (inet_ntop(AF_INET, n->ut_addr_v6, ipv4_str, INET_ADDRSTRLEN) != NULL) { + if (inet_ntop(AF_INET, n->ut_addr_v6, ipv4_str, INET_ADDRSTRLEN) != nullptr) { ffStrbufSetS(&user->clientIp, ipv4_str); } } } #else -static void fillUtmpIpAddr(FF_A_UNUSED FFUserResult* user, FF_A_UNUSED struct utmpx* n) { +static void fillUtmpIpAddr([[maybe_unused]] FFUserResult* user, [[maybe_unused]] struct utmpx* n) { } #endif const char* detectByUtmp(FFUsersOptions* options, FFlist* users) { - struct utmpx* n = NULL; + struct utmpx* n = nullptr; setutxent(); next: @@ -185,7 +185,7 @@ const char* detectByUtmp(FFUsersOptions* options, FFlist* users) { endutxent(); - return NULL; + return nullptr; } const char* ffDetectUsers(FFUsersOptions* options, FFlist* users) { @@ -200,5 +200,5 @@ const char* ffDetectUsers(FFUsersOptions* options, FFlist* users) { } #endif - return NULL; + return nullptr; } diff --git a/src/detection/users/users_obsd.c b/src/detection/users/users_obsd.c index 97a22f039b..a9b03072c8 100644 --- a/src/detection/users/users_obsd.c +++ b/src/detection/users/users_obsd.c @@ -4,7 +4,7 @@ #include -const char* ffDetectUsers(FF_A_UNUSED FFUsersOptions* options, FFlist* users) { +const char* ffDetectUsers([[maybe_unused]] FFUsersOptions* options, FFlist* users) { FF_AUTO_CLOSE_FILE FILE* fp = fopen(_PATH_UTMP, "r"); if (!fp) { return "fopen(_PATH_UTMP, r) failed"; @@ -35,5 +35,5 @@ const char* ffDetectUsers(FF_A_UNUSED FFUsersOptions* options, FFlist* users) { user->loginTime = (uint64_t) n.ut_time * 1000; } - return NULL; + return nullptr; } diff --git a/src/detection/users/users_windows.c b/src/detection/users/users_windows.c index 4cde44e315..837159a740 100644 --- a/src/detection/users/users_windows.c +++ b/src/detection/users/users_windows.c @@ -35,7 +35,7 @@ const char* ffDetectUsers(FFUsersOptions* options, FFlist* users) { user->loginTime = 0; DWORD bytes = 0; - PWTS_CLIENT_ADDRESS address = NULL; + PWTS_CLIENT_ADDRESS address = nullptr; if (WTSQuerySessionInformationW(WTS_CURRENT_SERVER_HANDLE, session->SessionId, WTSClientAddress, (LPWSTR*) &address, &bytes)) { if (address->AddressFamily == AF_INET) { ffStrbufSetF(&user->clientIp, "%u.%u.%u.%u", address->Address[2], address->Address[3], address->Address[4], address->Address[5]); @@ -48,7 +48,7 @@ const char* ffDetectUsers(FFUsersOptions* options, FFlist* users) { } bytes = 0; - PWTSINFOW wtsInfo = NULL; + PWTSINFOW wtsInfo = nullptr; if (WTSQuerySessionInformationW(WTS_CURRENT_SERVER_HANDLE, session->SessionId, WTSSessionInfo, (LPWSTR*) &wtsInfo, &bytes)) { user->loginTime = ffFileTimeToUnixMs((uint64_t) wtsInfo->LogonTime.QuadPart); WTSFreeMemory(wtsInfo); @@ -57,5 +57,5 @@ const char* ffDetectUsers(FFUsersOptions* options, FFlist* users) { WTSFreeMemoryExW(WTSTypeSessionInfoLevel1, sessionInfo, 1); - return NULL; + return nullptr; } diff --git a/src/detection/vulkan/vulkan.c b/src/detection/vulkan/vulkan.c index a6b6fefc0f..635df6ff67 100644 --- a/src/detection/vulkan/vulkan.c +++ b/src/detection/vulkan/vulkan.c @@ -29,7 +29,7 @@ static void applyDriverName(VkPhysicalDeviceDriverPropertiesKHR* properties, FFs * Some drivers (android for example) expose a multiline string as driver info. * It contains too much info anyways, so we just don't append it. */ - if (!ffStrSet(properties->driverInfo) || strchr(properties->driverInfo, '\n') != NULL) { + if (!ffStrSet(properties->driverInfo) || strchr(properties->driverInfo, '\n') != nullptr) { return; } @@ -67,8 +67,8 @@ static const char* detectVulkan(FFVulkanResult* result) { // We need to get the function pointer this way, because it is only provided by vulkan 1.1 and higher. // a dlsym would fail on 1.0 implementations - PFN_vkEnumerateInstanceVersion ffvkEnumerateInstanceVersion = (PFN_vkEnumerateInstanceVersion) ffvkGetInstanceProcAddr(NULL, "vkEnumerateInstanceVersion"); - if (ffvkEnumerateInstanceVersion != NULL) { + PFN_vkEnumerateInstanceVersion ffvkEnumerateInstanceVersion = (PFN_vkEnumerateInstanceVersion) ffvkGetInstanceProcAddr(nullptr, "vkEnumerateInstanceVersion"); + if (ffvkEnumerateInstanceVersion != nullptr) { uint32_t version; if (ffvkEnumerateInstanceVersion(&version) == VK_SUCCESS) { applyVulkanVersion(version, &instanceVersion); @@ -89,10 +89,10 @@ static const char* detectVulkan(FFVulkanResult* result) { FF_DEBUG("Creating Vulkan instance with requested API version %s", instanceVersion.minor >= 1 ? "1.1" : "1.0"); VkResult res = ffvkCreateInstance(&(VkInstanceCreateInfo) { .sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, - .pNext = NULL, + .pNext = nullptr, .pApplicationInfo = &(VkApplicationInfo) { .sType = VK_STRUCTURE_TYPE_APPLICATION_INFO, - .pNext = NULL, + .pNext = nullptr, .pApplicationName = FASTFETCH_PROJECT_NAME, .applicationVersion = projectVersion, .pEngineName = "vulkanPrintGPUs", @@ -101,11 +101,11 @@ static const char* detectVulkan(FFVulkanResult* result) { // We need to request 1.1 to get physicalDeviceDriverProperties .apiVersion = instanceVersion.minor >= 1 ? VK_API_VERSION_1_1 : VK_API_VERSION_1_0 }, .enabledLayerCount = 0, - .ppEnabledLayerNames = NULL, + .ppEnabledLayerNames = nullptr, .enabledExtensionCount = 0, - .ppEnabledExtensionNames = NULL, + .ppEnabledExtensionNames = nullptr, .flags = 0 }, - NULL, + nullptr, &vkInstance); if (res != VK_SUCCESS) { FF_DEBUG("ffvkCreateInstance() failed with VkResult=%d", res); @@ -140,7 +140,7 @@ static const char* detectVulkan(FFVulkanResult* result) { res = ffvkEnumeratePhysicalDevices(vkInstance, &physicalDeviceCount, physicalDevices); if (res != VK_SUCCESS) { FF_DEBUG("ffvkEnumeratePhysicalDevices() failed with VkResult=%d", res); - ffvkDestroyInstance(vkInstance, NULL); + ffvkDestroyInstance(vkInstance, nullptr); switch (res) { case VK_ERROR_OUT_OF_HOST_MEMORY: return "ffvkEnumeratePhysicalDevices() failed: VK_ERROR_OUT_OF_HOST_MEMORY"; @@ -156,7 +156,7 @@ static const char* detectVulkan(FFVulkanResult* result) { } FF_DEBUG("Enumerated %u Vulkan physical device(s)", physicalDeviceCount); - PFN_vkGetPhysicalDeviceProperties ffvkGetPhysicalDeviceProperties = NULL; + PFN_vkGetPhysicalDeviceProperties ffvkGetPhysicalDeviceProperties = nullptr; PFN_vkGetPhysicalDeviceProperties2 ffvkGetPhysicalDeviceProperties2 = (PFN_vkGetPhysicalDeviceProperties2) ffvkGetInstanceProcAddr(vkInstance, "vkGetPhysicalDeviceProperties2"); // 1.1 if (!ffvkGetPhysicalDeviceProperties2) { ffvkGetPhysicalDeviceProperties = (PFN_vkGetPhysicalDeviceProperties) ffvkGetInstanceProcAddr(vkInstance, "vkGetPhysicalDeviceProperties"); @@ -167,7 +167,7 @@ static const char* detectVulkan(FFVulkanResult* result) { PFN_vkGetPhysicalDeviceMemoryProperties ffvkGetPhysicalDeviceMemoryProperties = (PFN_vkGetPhysicalDeviceMemoryProperties) ffvkGetInstanceProcAddr(vkInstance, "vkGetPhysicalDeviceMemoryProperties"); if (!ffvkGetPhysicalDeviceMemoryProperties) { FF_DEBUG("vkGetPhysicalDeviceMemoryProperties is unavailable"); - ffvkDestroyInstance(vkInstance, NULL); + ffvkDestroyInstance(vkInstance, nullptr); return "vkGetPhysicalDeviceMemoryProperties is not available"; } @@ -187,7 +187,7 @@ static const char* detectVulkan(FFVulkanResult* result) { .pNext = &driverProperties, }; - if (ffvkGetPhysicalDeviceProperties2 != NULL) { + if (ffvkGetPhysicalDeviceProperties2 != nullptr) { ffvkGetPhysicalDeviceProperties2(physicalDevices[i], &physicalDeviceProperties); } else { ffvkGetPhysicalDeviceProperties(physicalDevices[i], &physicalDeviceProperties.properties); @@ -296,9 +296,9 @@ static const char* detectVulkan(FFVulkanResult* result) { result->conformanceVersion.chars, result->gpus.length); - ffvkDestroyInstance(vkInstance, NULL); + ffvkDestroyInstance(vkInstance, nullptr); FF_DEBUG("Destroyed Vulkan instance"); - return NULL; + return nullptr; } #endif diff --git a/src/detection/wallpaper/wallpaper_apple.m b/src/detection/wallpaper/wallpaper_apple.m index 800aee9ce6..f4ba8a6823 100644 --- a/src/detection/wallpaper/wallpaper_apple.m +++ b/src/detection/wallpaper/wallpaper_apple.m @@ -40,7 +40,7 @@ } } if (result->length > 0) - return NULL; + return nullptr; } } @@ -60,13 +60,13 @@ "JOIN spaces ON pictures.space_id=spaces.ROWID\n" "WHERE display_id=1 AND space_id=1 AND key=1", result) ) - return NULL; + return nullptr; } #endif if (ffOsascript("tell application \"Finder\" to get POSIX path of (get desktop picture as alias)", result)) - return NULL; + return nullptr; return "All detection methods failed"; } diff --git a/src/detection/wallpaper/wallpaper_haiku.cpp b/src/detection/wallpaper/wallpaper_haiku.cpp index 0bfad62bb7..ee17f16a0c 100644 --- a/src/detection/wallpaper/wallpaper_haiku.cpp +++ b/src/detection/wallpaper/wallpaper_haiku.cpp @@ -50,5 +50,5 @@ const char* ffDetectWallpaper(FFstrbuf* result) { } ffStrbufAppendS(result, path.String()); - return NULL; + return nullptr; } diff --git a/src/detection/wallpaper/wallpaper_linux.c b/src/detection/wallpaper/wallpaper_linux.c index f5ad4eca70..cde9662547 100644 --- a/src/detection/wallpaper/wallpaper_linux.c +++ b/src/detection/wallpaper/wallpaper_linux.c @@ -19,9 +19,9 @@ static const char* detectCosmicComp(FFstrbuf* result) { if (!ffStrbufEqualS(&cleaned, "[]")) { const char* firstQuote = strchr(backgrounds.chars, '"'); - if (firstQuote != NULL) { + if (firstQuote != nullptr) { const char* secondQuote = strchr(firstQuote + 1, '"'); - if (secondQuote != NULL && secondQuote > firstQuote + 1) { + if (secondQuote != nullptr && secondQuote > firstQuote + 1) { ffStrbufAppendNS(&monitorName, (uint32_t) (secondQuote - firstQuote - 1), firstQuote + 1); sharedWallpaper = false; } @@ -43,12 +43,12 @@ static const char* detectCosmicComp(FFstrbuf* result) { } const char* sourceStart = strstr(output.chars, "source:"); - if (sourceStart == NULL) { + if (sourceStart == nullptr) { return "COSMIC wallpaper config doesn't contain source"; } const char* pathStart = strstr(sourceStart, "Path("); - if (pathStart == NULL) { + if (pathStart == nullptr) { return "COSMIC wallpaper source is not a Path value"; } @@ -64,12 +64,12 @@ static const char* detectCosmicComp(FFstrbuf* result) { char quote = *pathStart; ++pathStart; const char* pathEnd = strchr(pathStart, quote); - if (pathEnd == NULL || pathEnd == pathStart) { + if (pathEnd == nullptr || pathEnd == pathStart) { return "COSMIC wallpaper path is empty"; } ffStrbufAppendNS(result, (uint32_t) (pathEnd - pathStart), pathStart); - return NULL; + return nullptr; } const char* ffDetectWallpaper(FFstrbuf* result) { @@ -78,7 +78,7 @@ const char* ffDetectWallpaper(FFstrbuf* result) { return detectCosmicComp(result); } - const FFstrbuf* wallpaper = NULL; + const FFstrbuf* wallpaper = nullptr; const FFGTKResult* gtk = ffDetectGTK4(); if (gtk->wallpaper.length) { wallpaper = >k->wallpaper; @@ -98,5 +98,5 @@ const char* ffDetectWallpaper(FFstrbuf* result) { } else { ffStrbufAppend(result, wallpaper); } - return NULL; + return nullptr; } diff --git a/src/detection/wallpaper/wallpaper_nosupport.c b/src/detection/wallpaper/wallpaper_nosupport.c index 9be8e9183a..dd9783ea81 100644 --- a/src/detection/wallpaper/wallpaper_nosupport.c +++ b/src/detection/wallpaper/wallpaper_nosupport.c @@ -1,5 +1,5 @@ #include "wallpaper.h" -const char* ffDetectWallpaper(FF_A_UNUSED FFstrbuf* result) { +const char* ffDetectWallpaper([[maybe_unused]] FFstrbuf* result) { return "Not supported on this platform"; } diff --git a/src/detection/wallpaper/wallpaper_windows.c b/src/detection/wallpaper/wallpaper_windows.c index 2adf08394e..7357d39fd1 100644 --- a/src/detection/wallpaper/wallpaper_windows.c +++ b/src/detection/wallpaper/wallpaper_windows.c @@ -2,14 +2,14 @@ #include "common/windows/registry.h" const char* ffDetectWallpaper(FFstrbuf* result) { - FF_AUTO_CLOSE_FD HANDLE hKey = NULL; - if (!ffRegOpenKeyForRead(HKEY_CURRENT_USER, L"Control Panel\\Desktop", &hKey, NULL)) { + FF_AUTO_CLOSE_FD HANDLE hKey = nullptr; + if (!ffRegOpenKeyForRead(HKEY_CURRENT_USER, L"Control Panel\\Desktop", &hKey, nullptr)) { return "ffRegOpenKeyForRead(Control Panel\\Desktop) failed"; } - if (!ffRegReadStrbuf(hKey, L"WallPaper", result, NULL)) { + if (!ffRegReadStrbuf(hKey, L"WallPaper", result, nullptr)) { return "ffRegReadStrbuf(WallPaper) failed"; } - return NULL; + return nullptr; } diff --git a/src/detection/weather/weather.c b/src/detection/weather/weather.c index 69df642900..8a70a966a3 100644 --- a/src/detection/weather/weather.c +++ b/src/detection/weather/weather.c @@ -37,7 +37,7 @@ const char* ffDetectWeather(FFWeatherOptions* options, FFstrbuf* result) { ffPrepareWeather(options); } - if (status != NULL) { + if (status != nullptr) { return status; } @@ -47,7 +47,7 @@ const char* ffDetectWeather(FFWeatherOptions* options, FFstrbuf* result) { state = (FFNetworkingState) {}; status = FF_UNITIALIZED; - if (error == NULL) { + if (error == nullptr) { ffStrbufSubstrAfterFirstS(result, "\r\n\r\n"); ffStrbufTrimRightSpace(result); } else { @@ -58,5 +58,5 @@ const char* ffDetectWeather(FFWeatherOptions* options, FFstrbuf* result) { return "Empty server response received"; } - return NULL; + return nullptr; } diff --git a/src/detection/wifi/wifi_android.c b/src/detection/wifi/wifi_android.c index c4537da07f..4fbc4afb20 100644 --- a/src/detection/wifi/wifi_android.c +++ b/src/detection/wifi/wifi_android.c @@ -16,11 +16,11 @@ static inline void wrapYyjsonFree(yyjson_doc** doc) { const char* ffDetectWifi(FFlist* result) { FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); - if (ffProcessAppendStdOut(&buffer, (char* const[]) { FF_TERMUX_API_PATH, FF_TERMUX_API_PARAM, NULL })) { + if (ffProcessAppendStdOut(&buffer, (char* const[]) { FF_TERMUX_API_PATH, FF_TERMUX_API_PARAM, nullptr })) { return "Starting `" FF_TERMUX_API_PATH " " FF_TERMUX_API_PARAM "` failed"; } - yyjson_doc* FF_A_CLEANUP(wrapYyjsonFree) doc = yyjson_read_opts(buffer.chars, buffer.length, 0, NULL, NULL); + [[gnu::cleanup(wrapYyjsonFree)]] yyjson_doc* doc = yyjson_read_opts(buffer.chars, buffer.length, 0, nullptr, nullptr); if (!doc) { return "Failed to parse wifi connection info"; } @@ -47,11 +47,11 @@ const char* ffDetectWifi(FFlist* result) { ffStrbufAppendJsonVal(&item->inf.status, yyjson_obj_get(root, "supplicant_state")); if (!item->inf.status.length) { ffStrbufAppendS(&item->inf.status, "Unknown"); - return NULL; + return nullptr; } if (!ffStrbufEqualS(&item->inf.status, "COMPLETED")) { - return NULL; + return nullptr; } double rssi = yyjson_get_num(yyjson_obj_get(root, "rssi")); @@ -65,5 +65,5 @@ const char* ffDetectWifi(FFlist* result) { item->conn.txRate = yyjson_get_num(yyjson_obj_get(root, "link_speed_mbps")); item->conn.channel = ffWifiFreqToChannel(item->conn.frequency); - return NULL; + return nullptr; } diff --git a/src/detection/wifi/wifi_apple.m b/src/detection/wifi/wifi_apple.m index 21808e03df..f718179bd4 100644 --- a/src/detection/wifi/wifi_apple.m +++ b/src/detection/wifi/wifi_apple.m @@ -161,5 +161,5 @@ @interface CWNetworkProfile() } } - return NULL; + return nullptr; } diff --git a/src/detection/wifi/wifi_bsd.c b/src/detection/wifi/wifi_bsd.c index 4b49b4e56b..7ef816ad5d 100644 --- a/src/detection/wifi/wifi_bsd.c +++ b/src/detection/wifi/wifi_bsd.c @@ -20,7 +20,7 @@ const char* ffDetectWifi(FFlist* result) { return "socket() failed"; } - for (struct if_nameindex* i = infs; !(i->if_index == 0 && i->if_name == NULL); ++i) { + for (struct if_nameindex* i = infs; !(i->if_index == 0 && i->if_name == nullptr); ++i) { if (!ffStrStartsWith(i->if_name, "wlan")) { continue; } @@ -119,7 +119,7 @@ const char* ffDetectWifi(FFlist* result) { } ireq.i_type = IEEE80211_IOC_AUTHMODE; - ireq.i_data = NULL; + ireq.i_data = nullptr; ireq.i_len = 0; if (ioctl(sock, SIOCG80211, &ireq) >= 0) { switch (ireq.i_val) { @@ -159,5 +159,5 @@ const char* ffDetectWifi(FFlist* result) { } if_freenameindex(infs); - return NULL; + return nullptr; } diff --git a/src/detection/wifi/wifi_linux.c b/src/detection/wifi/wifi_linux.c index 6f761590de..c609c25c41 100644 --- a/src/detection/wifi/wifi_linux.c +++ b/src/detection/wifi/wifi_linux.c @@ -61,7 +61,7 @@ static const struct nlattr* ffWifiNlAttrNext(const struct nlattr* attr, size_t* size_t alignedLen = NLA_ALIGN(attr->nla_len); if (alignedLen > *remaining) { *remaining = 0; - return NULL; + return nullptr; } *remaining -= alignedLen; @@ -131,7 +131,7 @@ static bool ffWifiNlGetFamilyId(FFWifiNlContext* ctx) { uint8_t buffer[8192]; while (true) { - ssize_t received = recvfrom(ctx->sockFd, buffer, sizeof(buffer), 0, NULL, NULL); + ssize_t received = recvfrom(ctx->sockFd, buffer, sizeof(buffer), 0, nullptr, nullptr); if (received < 0) { FF_DEBUG("Failed to receive nl80211 family reply: %s", strerror(errno)); return false; @@ -502,7 +502,7 @@ static bool ffWifiFetchScanInfo(FFWifiNlContext* ctx, FFWifiResult* item, uint32 uint8_t buffer[1024 * 16]; while (true) { - ssize_t received = recvfrom(ctx->sockFd, buffer, sizeof(buffer), 0, NULL, NULL); + ssize_t received = recvfrom(ctx->sockFd, buffer, sizeof(buffer), 0, nullptr, nullptr); if (received < 0) { FF_DEBUG("Failed to receive nl80211 scan reply: %s", strerror(errno)); return false; @@ -617,7 +617,7 @@ static bool ffWifiFetchStationInfo(FFWifiNlContext* ctx, FFWifiResult* item, uin uint8_t buffer[8192]; bool gotStation = false; while (true) { - ssize_t received = recvfrom(ctx->sockFd, buffer, sizeof(buffer), 0, NULL, NULL); + ssize_t received = recvfrom(ctx->sockFd, buffer, sizeof(buffer), 0, nullptr, nullptr); if (received < 0) { FF_DEBUG("Failed to receive nl80211 station reply: %s", strerror(errno)); return gotStation; @@ -690,7 +690,7 @@ static const char* detectWithNetlink(FFWifiNlContext* ctx, FFWifiResult* item, u } FF_DEBUG("Netlink wifi detection completed"); - return NULL; + return nullptr; } #endif @@ -884,7 +884,7 @@ static const char* detectWithIoctl(FFWifiIcContext* ctx, FFWifiResult* item, cha } FF_DEBUG("Ioctl wifi detection completed"); - return NULL; + return nullptr; } const char* ffDetectWifi(FFlist* result) { @@ -903,7 +903,7 @@ const char* ffDetectWifi(FFlist* result) { FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); - for (struct if_nameindex* i = infs; !(i->if_index == 0 && i->if_name == NULL); ++i) { + for (struct if_nameindex* i = infs; !(i->if_index == 0 && i->if_name == nullptr); ++i) { FF_DEBUG("Checking interface: %s (index: %u)", i->if_name, i->if_index); ffStrbufSetF(&buffer, "/sys/class/net/%s/phy80211/", i->if_name); if (!ffPathExists(buffer.chars, FF_PATHTYPE_DIRECTORY)) { @@ -952,7 +952,7 @@ const char* ffDetectWifi(FFlist* result) { } flags[len] = '\0'; - unsigned flagsVal = (unsigned) strtoul(flags, NULL, 16); // parse /sys flags as hexadecimal + unsigned flagsVal = (unsigned) strtoul(flags, nullptr, 16); // parse /sys flags as hexadecimal if (flagsVal & IFF_UP) { ffStrbufSetStatic(&item->inf.status, "up"); } else { @@ -972,5 +972,5 @@ const char* ffDetectWifi(FFlist* result) { } FF_DEBUG("Wifi detection completed, found %u wifi interfaces", result->length); - return NULL; + return nullptr; } diff --git a/src/detection/wifi/wifi_nbsd.c b/src/detection/wifi/wifi_nbsd.c index 52897c487e..ea8c2ace76 100644 --- a/src/detection/wifi/wifi_nbsd.c +++ b/src/detection/wifi/wifi_nbsd.c @@ -30,7 +30,7 @@ const char* ffDetectWifi(FFlist* result) { return "socket() failed"; } - for (struct if_nameindex* i = infs; !(i->if_index == 0 && i->if_name == NULL); ++i) { + for (struct if_nameindex* i = infs; !(i->if_index == 0 && i->if_name == nullptr); ++i) { if (!ffStrStartsWith(i->if_name, "iwm")) { continue; } @@ -134,7 +134,7 @@ const char* ffDetectWifi(FFlist* result) { } ireq.i_type = IEEE80211_IOC_AUTHMODE; - ireq.i_data = NULL; + ireq.i_data = nullptr; ireq.i_len = 0; if (ioctl(sock, SIOCG80211, &ireq) >= 0) { switch (ireq.i_val) { @@ -164,5 +164,5 @@ const char* ffDetectWifi(FFlist* result) { } if_freenameindex(infs); - return NULL; + return nullptr; } diff --git a/src/detection/wifi/wifi_nosupport.c b/src/detection/wifi/wifi_nosupport.c index bb4a806eae..e49d6607fe 100644 --- a/src/detection/wifi/wifi_nosupport.c +++ b/src/detection/wifi/wifi_nosupport.c @@ -1,5 +1,5 @@ #include "wifi.h" -const char* ffDetectWifi(FF_A_UNUSED FFlist* result) { +const char* ffDetectWifi([[maybe_unused]] FFlist* result) { return "Not support on this platform"; } diff --git a/src/detection/wifi/wifi_obsd.c b/src/detection/wifi/wifi_obsd.c index f686231b31..bcaec97fd9 100644 --- a/src/detection/wifi/wifi_obsd.c +++ b/src/detection/wifi/wifi_obsd.c @@ -20,7 +20,7 @@ const char* ffDetectWifi(FFlist* result) { return "socket() failed"; } - for (struct if_nameindex* i = infs; !(i->if_index == 0 && i->if_name == NULL); ++i) { + for (struct if_nameindex* i = infs; !(i->if_index == 0 && i->if_name == nullptr); ++i) { if (!ffStrStartsWith(i->if_name, "iwm")) { continue; } @@ -105,5 +105,5 @@ const char* ffDetectWifi(FFlist* result) { } if_freenameindex(infs); - return NULL; + return nullptr; } diff --git a/src/detection/wifi/wifi_windows.c b/src/detection/wifi/wifi_windows.c index 125c314cc0..8e900ad42a 100644 --- a/src/detection/wifi/wifi_windows.c +++ b/src/detection/wifi/wifi_windows.c @@ -50,16 +50,16 @@ const char* ffDetectWifi(FFlist* result) { FF_LIBRARY_LOAD_SYMBOL_MESSAGE(wlanapi, WlanGetNetworkBssList) DWORD curVersion; - HANDLE hClient = NULL; - WLAN_INTERFACE_INFO_LIST* ifList = NULL; - const char* error = NULL; + HANDLE hClient = nullptr; + WLAN_INTERFACE_INFO_LIST* ifList = nullptr; + const char* error = nullptr; - if (ffWlanOpenHandle(2, NULL, &curVersion, &hClient) != ERROR_SUCCESS) { + if (ffWlanOpenHandle(2, nullptr, &curVersion, &hClient) != ERROR_SUCCESS) { error = "WlanOpenHandle() failed"; goto exit; } - if (ffWlanEnumInterfaces(hClient, NULL, &ifList) != ERROR_SUCCESS) { + if (ffWlanEnumInterfaces(hClient, nullptr, &ifList) != ERROR_SUCCESS) { error = "WlanEnumInterfaces() failed"; goto exit; } @@ -87,14 +87,14 @@ const char* ffDetectWifi(FFlist* result) { continue; } - WLAN_CONNECTION_ATTRIBUTES* connInfo = NULL; + WLAN_CONNECTION_ATTRIBUTES* connInfo = nullptr; DWORD bufSize = sizeof(*connInfo); WLAN_OPCODE_VALUE_TYPE opCode = wlan_opcode_value_type_query_only; if (ffWlanQueryInterface(hClient, &ifInfo->InterfaceGuid, wlan_intf_opcode_current_connection, - NULL, + nullptr, &bufSize, (PVOID*) &connInfo, &opCode) != ERROR_SUCCESS) { @@ -200,13 +200,13 @@ const char* ffDetectWifi(FFlist* result) { ffStrbufAppendS(&item->conn.security, "Insecure"); } - WLAN_BSS_LIST* bssList = NULL; + WLAN_BSS_LIST* bssList = nullptr; if (ffWlanGetNetworkBssList(hClient, &ifInfo->InterfaceGuid, &connInfo->wlanAssociationAttributes.dot11Ssid, connInfo->wlanAssociationAttributes.dot11BssType, connInfo->wlanSecurityAttributes.bSecurityEnabled, - NULL, + nullptr, &bssList) == ERROR_SUCCESS && bssList->dwNumberOfItems > 0) { item->conn.frequency = (uint16_t) (bssList->wlanBssEntries[0].ulChCenterFrequency / 1000); @@ -220,7 +220,7 @@ const char* ffDetectWifi(FFlist* result) { if (ffWlanQueryInterface(hClient, &ifInfo->InterfaceGuid, wlan_intf_opcode_channel_number, - NULL, + nullptr, &bufSize, (PVOID*) &channelNumber, &opCode) == ERROR_SUCCESS) { @@ -234,7 +234,7 @@ const char* ffDetectWifi(FFlist* result) { ffWlanFreeMemory(ifList); } if (hClient) { - ffWlanCloseHandle(hClient, NULL); + ffWlanCloseHandle(hClient, nullptr); } return error; } diff --git a/src/detection/wm/wm_apple.m b/src/detection/wm/wm_apple.m index 89273e9390..c4bc780a21 100644 --- a/src/detection/wm/wm_apple.m +++ b/src/detection/wm/wm_apple.m @@ -15,7 +15,7 @@ size_t length = 0; FF_AUTO_FREE struct kinfo_proc* processes = ffSysctlGetData(request, requestLength, &length); - if (processes == NULL) { + if (processes == nullptr) { return "sysctl(CTL_KERN, KERN_PROC, KERN_PROC_ALL) failed"; } assert(length % sizeof(struct kinfo_proc) == 0); @@ -68,10 +68,10 @@ break; } - return NULL; + return nullptr; } -const char* ffDetectWMVersion(const FFstrbuf* wmName, FFstrbuf* result, FF_A_UNUSED FFWMOptions* options) { +const char* ffDetectWMVersion(const FFstrbuf* wmName, FFstrbuf* result, [[maybe_unused]] FFWMOptions* options) { if (!wmName) { return "No WM detected"; } @@ -90,5 +90,5 @@ } } - return NULL; + return nullptr; } diff --git a/src/detection/wm/wm_linux.c b/src/detection/wm/wm_linux.c index c890de4aa7..5e3fff085c 100644 --- a/src/detection/wm/wm_linux.c +++ b/src/detection/wm/wm_linux.c @@ -7,11 +7,11 @@ #include "common/strutil.h" #include "common/debug.h" -const char* ffDetectWMPlugin(FF_A_UNUSED FFstrbuf* pluginName) { +const char* ffDetectWMPlugin([[maybe_unused]] FFstrbuf* pluginName) { return "Not supported on this platform"; } -static bool extractCommonWmVersion(const char* line, FF_A_UNUSED uint32_t len, void* userdata) { +static bool extractCommonWmVersion(const char* line, [[maybe_unused]] uint32_t len, void* userdata) { int count = 0; sscanf(line, "%*d.%*d.%*d%n", &count); if (count == 0) { @@ -52,7 +52,7 @@ static const char* getHyprland(FFstrbuf* result) { ffStrbufSubstrBeforeFirstC(result, '"'); ffStrbufTrimLeft(result, 'v'); FF_DEBUG("Extracted version from version.h: %s", result->chars); - return NULL; + return nullptr; } FF_DEBUG("Failed to extract version from version.h"); ffStrbufClear(result); @@ -70,11 +70,11 @@ static const char* getHyprland(FFstrbuf* result) { ffBinaryExtractStrings(buffer.chars, extractHyprlandVersion, result, (uint32_t) strlen("v0.0.0")); if (result->length > 0) { FF_DEBUG("Extracted version from binary strings: %s", result->chars); - return NULL; + return nullptr; } FF_DEBUG("Failed to extract version from binary strings, trying --version option"); - if (ffProcessAppendStdOut(result, (char* const[]) { buffer.chars, "--version", NULL }) == NULL) { + if (ffProcessAppendStdOut(result, (char* const[]) { buffer.chars, "--version", nullptr }) == nullptr) { // Hyprland 0.48.1 built from branch at commit 29e2e59... // Date: ... // Tag: v0.48.1, commits: 5937 @@ -90,14 +90,14 @@ static const char* getHyprland(FFstrbuf* result) { ffStrbufSubstrBeforeFirstC(result, ' '); FF_DEBUG("Extracted version from output: %s", result->chars); } - return NULL; + return nullptr; } FF_DEBUG("Failed to run Hyprland --version command"); return "Failed to run command `Hyprland --version`"; } -static bool extractSwayVersion(const char* line, FF_A_UNUSED uint32_t len, void* userdata) { +static bool extractSwayVersion(const char* line, [[maybe_unused]] uint32_t len, void* userdata) { FFstrbuf* result = (FFstrbuf*) userdata; if (!ffStrStartsWith(line, "sway")) { return true; @@ -126,12 +126,12 @@ static const char* getSway(FFstrbuf* result) { ffBinaryExtractStrings(path.chars, extractSwayVersion, result, (uint32_t) strlen("sway version 0.0.0")); if (result->length > 0) { - return NULL; + return nullptr; } FF_STRBUF_AUTO_DESTROY buffer = ffStrbufCreate(); - if (ffProcessAppendStdOut(&buffer, (char* const[]) { path.chars, "--version", NULL }) == NULL) { // sway version 1.10 - return extractSwayVersion(buffer.chars, buffer.length, result) ? "Failed to parse sway version output" : NULL; + if (ffProcessAppendStdOut(&buffer, (char* const[]) { path.chars, "--version", nullptr }) == nullptr) { // sway version 1.10 + return extractSwayVersion(buffer.chars, buffer.length, result) ? "Failed to parse sway version output" : nullptr; } return "Failed to run command `sway --version`"; @@ -146,24 +146,24 @@ static const char* getLabwc(FFstrbuf* result) { ffBinaryExtractStrings(path.chars, extractCommonWmVersion, result, (uint32_t) strlen("0.0.0")); if (result->length > 0) { - return NULL; + return nullptr; } - if (ffProcessAppendStdOut(result, (char* const[]) { path.chars, "--version", NULL }) == NULL) { // labwc 0.9.0 (+xwayland +nls +rsvg +libsfdo) + if (ffProcessAppendStdOut(result, (char* const[]) { path.chars, "--version", nullptr }) == nullptr) { // labwc 0.9.0 (+xwayland +nls +rsvg +libsfdo) ffStrbufSubstrAfterFirstC(result, ' '); ffStrbufSubstrBeforeFirstC(result, ' '); - return NULL; + return nullptr; } return "Failed to run command `labwc --version`"; } static const char* getNiri(FFstrbuf* result) { - if (ffProcessAppendStdOut(result, (char* const[]) { "niri", "--version", NULL }) == NULL) { // niri 25.11 (commit b35bcae) + if (ffProcessAppendStdOut(result, (char* const[]) { "niri", "--version", nullptr }) == nullptr) { // niri 25.11 (commit b35bcae) ffStrbufSubstrAfterFirstC(result, ' '); ffStrbufSubstrBeforeLastC(result, '('); ffStrbufTrimRightSpace(result); - return NULL; + return nullptr; } return "Failed to run command `niri --version`"; @@ -176,10 +176,10 @@ static const char* getWeston(FFstrbuf* result) { return "Failed to find weston executable path"; } - if (ffProcessAppendStdOut(result, (char* const[]) { path.chars, "--version", NULL }) == NULL) { // weston 8.0.0\n... + if (ffProcessAppendStdOut(result, (char* const[]) { path.chars, "--version", nullptr }) == nullptr) { // weston 8.0.0\n... ffStrbufSubstrBeforeFirstC(result, '\n'); ffStrbufSubstrAfterLastC(result, ' '); - return NULL; + return nullptr; } return "Failed to run command `weston --version`"; @@ -204,13 +204,13 @@ static const char* getWslg(FFstrbuf* result) { return "Failed to parse WSLg version from /mnt/wslg/versions.txt"; } - return NULL; + return nullptr; } #endif #endif // !__ANDROID__ -static bool extractI3Version(const char* line, FF_A_UNUSED uint32_t len, void* userdata) { +static bool extractI3Version(const char* line, [[maybe_unused]] uint32_t len, void* userdata) { int count = 0; sscanf(line, "%*d.%*d%n", &count); if (count == 0) { @@ -230,13 +230,13 @@ static const char* getI3(FFstrbuf* result) { ffBinaryExtractStrings(path.chars, extractI3Version, result, (uint32_t) strlen("0.0")); if (result->length > 0) { - return NULL; + return nullptr; } - if (ffProcessAppendStdOut(result, (char* const[]) { path.chars, "--version", NULL }) == NULL) { // i3 version 1.10 C 2009... + if (ffProcessAppendStdOut(result, (char* const[]) { path.chars, "--version", nullptr }) == nullptr) { // i3 version 1.10 C 2009... ffStrbufSubstrAfterFirstS(result, "version "); ffStrbufSubstrBeforeFirstC(result, ' '); - return NULL; + return nullptr; } return "Failed to run command `i3 --version`"; @@ -251,13 +251,13 @@ static const char* getCtwm(FFstrbuf* result) { ffBinaryExtractStrings(path.chars, extractCommonWmVersion, result, (uint32_t) strlen("0.0.0")); if (result->length > 0) { - return NULL; + return nullptr; } - if (ffProcessAppendStdOut(result, (char* const[]) { path.chars, "--version", NULL }) == NULL) { // ctwm version 4.0.1\n... + if (ffProcessAppendStdOut(result, (char* const[]) { path.chars, "--version", nullptr }) == nullptr) { // ctwm version 4.0.1\n... ffStrbufSubstrBeforeFirstC(result, '\n'); ffStrbufSubstrAfterLastC(result, ' '); - return NULL; + return nullptr; } return "Failed to run command `ctwm --version`"; @@ -272,13 +272,13 @@ static const char* getFvwm(FFstrbuf* result) { ffBinaryExtractStrings(path.chars, extractCommonWmVersion, result, (uint32_t) strlen("0.0.0")); if (result->length > 0) { - return NULL; + return nullptr; } - if (ffProcessAppendStdOut(result, (char* const[]) { path.chars, "-version", NULL }) == NULL) { // [FVWM][main]: fvwm Version 2.2.5\n... + if (ffProcessAppendStdOut(result, (char* const[]) { path.chars, "-version", nullptr }) == nullptr) { // [FVWM][main]: fvwm Version 2.2.5\n... ffStrbufSubstrBeforeFirstC(result, '\n'); ffStrbufSubstrAfterLastC(result, ' '); - return NULL; + return nullptr; } return "Failed to run command `fvwm -version`"; @@ -293,19 +293,19 @@ static const char* getOpenbox(FFstrbuf* result) { ffBinaryExtractStrings(path.chars, extractCommonWmVersion, result, (uint32_t) strlen("0.0.0")); if (result->length > 0) { - return NULL; + return nullptr; } - if (ffProcessAppendStdOut(result, (char* const[]) { path.chars, "--version", NULL }) == NULL) { // Openbox 3.6.1\n... + if (ffProcessAppendStdOut(result, (char* const[]) { path.chars, "--version", nullptr }) == nullptr) { // Openbox 3.6.1\n... ffStrbufSubstrBeforeFirstC(result, '\n'); ffStrbufSubstrAfterLastC(result, ' '); - return NULL; + return nullptr; } return "Failed to run command `openbox --version`"; } -const char* ffDetectWMVersion(const FFstrbuf* wmName, FFstrbuf* result, FF_A_UNUSED FFWMOptions* options) { +const char* ffDetectWMVersion(const FFstrbuf* wmName, FFstrbuf* result, [[maybe_unused]] FFWMOptions* options) { if (!wmName) { return "No WM detected"; } diff --git a/src/detection/wm/wm_nosupport.c b/src/detection/wm/wm_nosupport.c index 65c53489b0..8cf845c818 100644 --- a/src/detection/wm/wm_nosupport.c +++ b/src/detection/wm/wm_nosupport.c @@ -1,9 +1,9 @@ #include "wm.h" -const char* ffDetectWMPlugin(FF_A_UNUSED FFstrbuf* pluginName) { +const char* ffDetectWMPlugin([[maybe_unused]] FFstrbuf* pluginName) { return "Not supported on this platform"; } -const char* ffDetectWMVersion(FF_A_UNUSED const FFstrbuf* wmName, FF_A_UNUSED FFstrbuf* result, FF_A_UNUSED FFWMOptions* options) { +const char* ffDetectWMVersion([[maybe_unused]] const FFstrbuf* wmName, [[maybe_unused]] FFstrbuf* result, [[maybe_unused]] FFWMOptions* options) { return "Not supported on this platform"; } diff --git a/src/detection/wm/wm_windows.c b/src/detection/wm/wm_windows.c index ee363995b5..01a336b287 100644 --- a/src/detection/wm/wm_windows.c +++ b/src/detection/wm/wm_windows.c @@ -42,15 +42,15 @@ static bool verifySignature(const wchar_t* filePath) { .dwProvFlags = WTD_SAFER_FLAG, }; - LONG status = ffWinVerifyTrustEx(NULL, &actionID, &trustData); + LONG status = ffWinVerifyTrustEx(nullptr, &actionID, &trustData); trustData.dwStateAction = WTD_STATEACTION_CLOSE; - ffWinVerifyTrustEx(NULL, &actionID, &trustData); + ffWinVerifyTrustEx(nullptr, &actionID, &trustData); return status == ERROR_SUCCESS; } static bool isProcessTrusted(DWORD processId, FFProcessType processType, UNICODE_STRING* buffer, size_t bufSize) { - FF_AUTO_CLOSE_FD HANDLE hProcess = NULL; + FF_AUTO_CLOSE_FD HANDLE hProcess = nullptr; if (!NT_SUCCESS(NtOpenProcess(&hProcess, PROCESS_QUERY_LIMITED_INFORMATION, &(OBJECT_ATTRIBUTES) { .Length = sizeof(OBJECT_ATTRIBUTES), }, @@ -63,14 +63,14 @@ static bool isProcessTrusted(DWORD processId, FFProcessType processType, UNICODE buffer->Length == 0) { return false; } - assert(buffer->MaximumLength >= buffer->Length + 2); // NULL terminated + assert(buffer->MaximumLength >= buffer->Length + 2); // nullptr terminated if (processType & FF_PROCESS_TYPE_WINDOWS_STORE) { static wchar_t windowsAppsPath[MAX_PATH]; static uint32_t windowsAppsPathLen; if (windowsAppsPathLen == 0) { - PWSTR pPath = NULL; - if (SUCCEEDED(SHGetKnownFolderPath(&FOLDERID_ProgramFiles, KF_FLAG_DEFAULT, NULL, &pPath))) { + PWSTR pPath = nullptr; + if (SUCCEEDED(SHGetKnownFolderPath(&FOLDERID_ProgramFiles, KF_FLAG_DEFAULT, nullptr, &pPath))) { windowsAppsPathLen = (uint32_t) wcslen(pPath); memcpy(windowsAppsPath, pPath, windowsAppsPathLen * sizeof(wchar_t)); memcpy(windowsAppsPath + windowsAppsPathLen, L"\\WindowsApps\\", sizeof(L"\\WindowsApps\\")); @@ -117,7 +117,7 @@ static bool isProcessTrusted(DWORD processId, FFProcessType processType, UNICODE const char* ffDetectWMPlugin(FFstrbuf* pluginName) { alignas(UNICODE_STRING) uint8_t buffer[4096]; UNICODE_STRING* filePath = (UNICODE_STRING*) buffer; - SYSTEM_PROCESS_INFORMATION* FF_AUTO_FREE pstart = NULL; + FF_AUTO_FREE SYSTEM_PROCESS_INFORMATION* pstart = nullptr; // Multiple attempts in case processes change while // we are in the middle of querying them. @@ -138,11 +138,11 @@ const char* ffDetectWMPlugin(FFstrbuf* pluginName) { } for (SYSTEM_PROCESS_INFORMATION* ptr = pstart;; ptr = (SYSTEM_PROCESS_INFORMATION*) ((uint8_t*) ptr + ptr->NextEntryOffset)) { - assert(ptr->ImageName.Length == 0 || ptr->ImageName.MaximumLength >= ptr->ImageName.Length + 2); // NULL terminated + assert(ptr->ImageName.Length == 0 || ptr->ImageName.MaximumLength >= ptr->ImageName.Length + 2); // nullptr terminated if (ptr->ImageName.Length == strlen("FancyWM-GUI.exe") * sizeof(wchar_t) && ffStrEqualNWS(ptr->ImageName.Buffer, "FancyWM-GUI.exe") && isProcessTrusted((DWORD) (uintptr_t) ptr->UniqueProcessId, FF_PROCESS_TYPE_WINDOWS_STORE | FF_PROCESS_TYPE_GUI, filePath, sizeof(buffer))) { - if (instance.config.general.detectVersion && ffGetFileVersion(filePath->Buffer, NULL, pluginName)) { + if (instance.config.general.detectVersion && ffGetFileVersion(filePath->Buffer, nullptr, pluginName)) { ffStrbufPrependS(pluginName, "FancyWM "); } else { ffStrbufSetStatic(pluginName, "FancyWM"); @@ -151,7 +151,7 @@ const char* ffDetectWMPlugin(FFstrbuf* pluginName) { } else if (ptr->ImageName.Length == strlen("glazewm-watcher.exe") * sizeof(wchar_t) && ffStrEqualNWS(ptr->ImageName.Buffer, "glazewm-watcher.exe") && isProcessTrusted((DWORD) (uintptr_t) ptr->UniqueProcessId, FF_PROCESS_TYPE_SIGNED | FF_PROCESS_TYPE_GUI, filePath, sizeof(buffer))) { - if (instance.config.general.detectVersion && ffGetFileVersion(filePath->Buffer, NULL, pluginName)) { + if (instance.config.general.detectVersion && ffGetFileVersion(filePath->Buffer, nullptr, pluginName)) { ffStrbufPrependS(pluginName, "GlazeWM "); } else { ffStrbufSetStatic(pluginName, "GlazeWM"); @@ -165,8 +165,8 @@ const char* ffDetectWMPlugin(FFstrbuf* pluginName) { if (ffProcessAppendStdOut(pluginName, (char* const[]) { path.chars, "--version", - NULL, - }) == NULL) { + nullptr, + }) == nullptr) { ffStrbufSubstrBeforeFirstC(pluginName, '\n'); } } @@ -181,24 +181,24 @@ const char* ffDetectWMPlugin(FFstrbuf* pluginName) { } } - return NULL; + return nullptr; } -const char* ffDetectWMVersion(const FFstrbuf* wmName, FFstrbuf* result, FF_A_UNUSED FFWMOptions* options) { +const char* ffDetectWMVersion(const FFstrbuf* wmName, FFstrbuf* result, [[maybe_unused]] FFWMOptions* options) { if (!wmName) { return "No WM detected"; } if (ffStrbufEqualS(wmName, "dwm.exe")) { - PWSTR pPath = NULL; - if (SUCCEEDED(SHGetKnownFolderPath(&FOLDERID_System, KF_FLAG_DEFAULT, NULL, &pPath))) { + PWSTR pPath = nullptr; + if (SUCCEEDED(SHGetKnownFolderPath(&FOLDERID_System, KF_FLAG_DEFAULT, nullptr, &pPath))) { wchar_t fullPath[MAX_PATH]; wcscpy(fullPath, pPath); wcscat(fullPath, L"\\dwm.exe"); - ffGetFileVersion(fullPath, NULL, result); + ffGetFileVersion(fullPath, nullptr, result); } CoTaskMemFree(pPath); - return NULL; + return nullptr; } return "Not supported on this platform"; } diff --git a/src/detection/wmtheme/wmtheme_haiku.cpp b/src/detection/wmtheme/wmtheme_haiku.cpp index 243eaa43e4..267e4e4865 100644 --- a/src/detection/wmtheme/wmtheme_haiku.cpp +++ b/src/detection/wmtheme/wmtheme_haiku.cpp @@ -12,7 +12,7 @@ bool ffDetectWmTheme(FFstrbuf* themeOrError) BApplication app("application/x-vnd.fastfetch-cli-fastfetch"); DecorInfoUtility *util = new DecorInfoUtility(); - DecorInfo* decor = NULL; + DecorInfo* decor = nullptr; if (util) { decor = util->CurrentDecorator(); diff --git a/src/detection/wmtheme/wmtheme_linux.c b/src/detection/wmtheme/wmtheme_linux.c index e9123025d3..1c46e78221 100644 --- a/src/detection/wmtheme/wmtheme_linux.c +++ b/src/detection/wmtheme/wmtheme_linux.c @@ -15,7 +15,7 @@ static bool detectWMThemeFromConfigFile(const char* configFile, const char* them } if (themeOrError->length == 0) { - if (defaultValue == NULL) { + if (defaultValue == nullptr) { ffStrbufAppendF(themeOrError, "Couldn't find WM theme in %s", configFile); return false; } @@ -77,7 +77,7 @@ static bool detectGTKThemeAsWMTheme(FFstrbuf* themeOrError) { } static bool detectMutter(FFstrbuf* themeOrError) { - const char* theme = ffSettingsGetGnome("/org/gnome/shell/extensions/user-theme/name", "org.gnome.shell.extensions.user-theme", NULL, "name", FF_VARIANT_TYPE_STRING).strValue; + const char* theme = ffSettingsGetGnome("/org/gnome/shell/extensions/user-theme/name", "org.gnome.shell.extensions.user-theme", nullptr, "name", FF_VARIANT_TYPE_STRING).strValue; if (ffStrSet(theme)) { ffStrbufAppendS(themeOrError, theme); return true; @@ -87,20 +87,20 @@ static bool detectMutter(FFstrbuf* themeOrError) { } static bool detectMuffin(FFstrbuf* themeOrError) { - FF_AUTO_FREE const char* name = ffSettingsGetGnome("/org/cinnamon/theme/name", "org.cinnamon.theme", NULL, "name", FF_VARIANT_TYPE_STRING).strValue; - FF_AUTO_FREE const char* theme = ffSettingsGetGnome("/org/cinnamon/desktop/wm/preferences/theme", "org.cinnamon.desktop.wm.preferences", NULL, "theme", FF_VARIANT_TYPE_STRING).strValue; + FF_AUTO_FREE const char* name = ffSettingsGetGnome("/org/cinnamon/theme/name", "org.cinnamon.theme", nullptr, "name", FF_VARIANT_TYPE_STRING).strValue; + FF_AUTO_FREE const char* theme = ffSettingsGetGnome("/org/cinnamon/desktop/wm/preferences/theme", "org.cinnamon.desktop.wm.preferences", nullptr, "theme", FF_VARIANT_TYPE_STRING).strValue; - if (name == NULL && theme == NULL) { + if (name == nullptr && theme == nullptr) { ffStrbufAppendS(themeOrError, "Couldn't find muffin theme in GSettings / DConf"); return false; } - if (name == NULL) { + if (name == nullptr) { ffStrbufAppendS(themeOrError, theme); return true; } - if (theme == NULL) { + if (theme == nullptr) { ffStrbufAppendS(themeOrError, name); return true; } @@ -112,7 +112,7 @@ static bool detectMuffin(FFstrbuf* themeOrError) { static bool detectXFWM4(FFstrbuf* themeOrError) { const char* theme = ffSettingsGetXFConf("xfwm4", "/general/theme", FF_VARIANT_TYPE_STRING).strValue; - if (theme == NULL) { + if (theme == nullptr) { ffStrbufAppendS(themeOrError, "Couldn't find xfwm4::/general/theme in XFConf"); return false; } @@ -142,22 +142,22 @@ static bool detectOpenbox(const FFstrbuf* dePrettyName, FFstrbuf* themeOrError) } const char* themeStart = strstr(content.chars, ""); - if (themeStart == NULL) { + if (themeStart == nullptr) { goto theme_not_found; } const char* themeEnd = strstr(themeStart, ""); - if (__builtin_expect(themeEnd == NULL, false)) { // very rare case + if (__builtin_expect(themeEnd == nullptr, false)) { // very rare case goto theme_not_found; } const char* nameStart = strstr(themeStart, ""); - if (nameStart == NULL) { + if (nameStart == nullptr) { goto name_not_found; } const char* nameEnd = strstr(nameStart, ""); - if (nameEnd == NULL || nameEnd > themeEnd) { // (nameEnd > themeEnd) means name is not a theme's child + if (nameEnd == nullptr || nameEnd > themeEnd) { // (nameEnd > themeEnd) means name is not a theme's child goto name_not_found; } @@ -216,9 +216,9 @@ static bool detectCosmicComp(FFstrbuf* themeOrError) { ffStrbufAppendF(&path, "com.system76.CosmicTheme.%s/v1/accent", variant); if (ffReadFileBuffer(path.chars, &accent)) { const char* baseStart = strstr(accent.chars, "base:"); - if (baseStart != NULL) { + if (baseStart != nullptr) { const char* contentStart = strchr(baseStart, '('); - if (contentStart != NULL) { + if (contentStart != nullptr) { int depth = 1; const char* contentEnd = contentStart + 1; while (*contentEnd != '\0' && depth > 0) { @@ -237,13 +237,13 @@ static bool detectCosmicComp(FFstrbuf* themeOrError) { const char* key = i == 0 ? "red:" : (i == 1 ? "green:" : (i == 2 ? "blue:" : "alpha:")); const char* componentStart = strstr(contentStart, key); - if (componentStart == NULL || componentStart >= contentEnd) { + if (componentStart == nullptr || componentStart >= contentEnd) { ok = false; break; } componentStart += strlen(key); - char* componentEnd = NULL; + char* componentEnd = nullptr; double value = strtod(componentStart, &componentEnd); if (componentEnd == componentStart) { ok = false; @@ -323,7 +323,7 @@ bool ffDetectWmTheme(FFstrbuf* themeOrError) { } if (ffStrbufIgnCaseEqualS(&wm->wmPrettyName, FF_WM_PRETTY_MARCO)) { - return detectWMThemeFromSettings("/org/mate/Marco/general/theme", "org.mate.Marco.general", NULL, "theme", themeOrError); + return detectWMThemeFromSettings("/org/mate/Marco/general/theme", "org.mate.Marco.general", nullptr, "theme", themeOrError); } if (ffStrbufIgnCaseEqualS(&wm->wmPrettyName, FF_WM_PRETTY_OPENBOX)) { diff --git a/src/detection/wmtheme/wmtheme_windows.c b/src/detection/wmtheme/wmtheme_windows.c index 5d16a84bbe..adaece574b 100644 --- a/src/detection/wmtheme/wmtheme_windows.c +++ b/src/detection/wmtheme/wmtheme_windows.c @@ -105,16 +105,16 @@ const char* colorHexToString(DWORD hex) { case 0xFFFFFF: return "White"; default: - return NULL; + return nullptr; } } bool ffDetectWmTheme(FFstrbuf* themeOrError) { { - FF_AUTO_CLOSE_FD HANDLE hKey = NULL; - if (ffRegOpenKeyForRead(HKEY_CURRENT_USER, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Themes", &hKey, NULL)) { + FF_AUTO_CLOSE_FD HANDLE hKey = nullptr; + if (ffRegOpenKeyForRead(HKEY_CURRENT_USER, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Themes", &hKey, nullptr)) { FF_STRBUF_AUTO_DESTROY theme = ffStrbufCreate(); - if (ffRegReadStrbuf(hKey, L"CurrentTheme", &theme, NULL)) { + if (ffRegReadStrbuf(hKey, L"CurrentTheme", &theme, nullptr)) { ffStrbufSubstrBeforeLastC(&theme, '.'); ffStrbufSubstrAfterLastC(&theme, '\\'); if (isalpha(theme.chars[0])) { @@ -129,11 +129,11 @@ bool ffDetectWmTheme(FFstrbuf* themeOrError) { do { uint32_t rgbColor; uint32_t bgrColor; - FF_AUTO_CLOSE_FD HANDLE hKey = NULL; - if (ffRegOpenKeyForRead(HKEY_CURRENT_USER, L"Software\\Microsoft\\Windows\\DWM", &hKey, NULL)) { - if (ffRegReadUint(hKey, L"AccentColor", &bgrColor, NULL)) { + FF_AUTO_CLOSE_FD HANDLE hKey = nullptr; + if (ffRegOpenKeyForRead(HKEY_CURRENT_USER, L"Software\\Microsoft\\Windows\\DWM", &hKey, nullptr)) { + if (ffRegReadUint(hKey, L"AccentColor", &bgrColor, nullptr)) { rgbColor = ((bgrColor & 0xFF) << 16) | (bgrColor & 0xFF00) | ((bgrColor >> 16) & 0xFF); - } else if (ffRegReadUint(hKey, L"ColorizationColor", &rgbColor, NULL)) { + } else if (ffRegReadUint(hKey, L"ColorizationColor", &rgbColor, nullptr)) { rgbColor &= 0xFFFFFF; } else { break; @@ -154,14 +154,14 @@ bool ffDetectWmTheme(FFstrbuf* themeOrError) { } while (false); { - FF_AUTO_CLOSE_FD HANDLE hKey = NULL; - if (ffRegOpenKeyForRead(HKEY_CURRENT_USER, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize", &hKey, NULL)) { + FF_AUTO_CLOSE_FD HANDLE hKey = nullptr; + if (ffRegOpenKeyForRead(HKEY_CURRENT_USER, L"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize", &hKey, nullptr)) { uint32_t system = 1, apps = 1; if (ffRegReadValues(hKey, 2, (FFRegValueArg[]) { FF_ARG(system, L"SystemUsesLightTheme"), FF_ARG(apps, L"AppsUseLightTheme"), }, - NULL)) { + nullptr)) { bool paren = themeOrError->length > 0; if (paren) { ffStrbufAppendS(themeOrError, " ("); diff --git a/src/detection/zpool/zpool.c b/src/detection/zpool/zpool.c index ce7abb37fb..ebabf45a37 100644 --- a/src/detection/zpool/zpool.c +++ b/src/detection/zpool/zpool.c @@ -43,7 +43,7 @@ typedef struct FFZfsData { static inline void cleanLibzfs(FFZfsData* data) { if (data->fflibzfs_fini && data->handle) { data->fflibzfs_fini(data->handle); - data->handle = NULL; + data->handle = nullptr; } } @@ -85,7 +85,7 @@ const char* ffDetectZpool(FFlist* result /* list of FFZpoolResult */) { return "libzfs_init() failed"; } - FF_A_CLEANUP(cleanLibzfs) FFZfsData data = { + [[gnu::cleanup(cleanLibzfs)]] FFZfsData data = { .handle = handle, .result = result, }; @@ -118,12 +118,12 @@ const char* ffDetectZpool(FFlist* result /* list of FFZpoolResult */) { return "zpool_iter() failed"; } - return NULL; + return nullptr; } #else -const char* ffDetectZpool(FF_A_UNUSED FFlist* result) { +const char* ffDetectZpool([[maybe_unused]] FFlist* result) { return "fastfetch was compiled without libzfs support"; } diff --git a/src/fastfetch.c b/src/fastfetch.c index e644409251..af8375d809 100644 --- a/src/fastfetch.c +++ b/src/fastfetch.c @@ -3,6 +3,7 @@ #include "detection/version/version.h" #include "logo/logo.h" #include "common/commandoption.h" +#include "common/genconfig.h" #include "common/init.h" #include "common/io.h" #include "common/jsonconfig.h" @@ -15,9 +16,15 @@ #include #include -FF_A_COLD +#ifndef _WIN32 + #include +#else + #include +#endif + +[[gnu::cold]] static void printCommandFormatHelpJson(void) { - yyjson_mut_doc* doc = yyjson_mut_doc_new(NULL); + yyjson_mut_doc* doc = yyjson_mut_doc_new(nullptr); yyjson_mut_val* root = yyjson_mut_obj(doc); yyjson_mut_doc_set_root(doc, root); @@ -45,12 +52,12 @@ static void printCommandFormatHelpJson(void) { } } } - yyjson_mut_write_fp(stdout, doc, YYJSON_WRITE_PRETTY, NULL, NULL); + yyjson_mut_write_fp(stdout, doc, YYJSON_WRITE_PRETTY, nullptr, nullptr); putchar('\n'); yyjson_mut_doc_free(doc); } -FF_A_COLD +[[gnu::cold]] static void printCommandFormatHelp(const char* command) { FF_STRBUF_AUTO_DESTROY type = ffStrbufCreateNS((uint32_t) (strlen(command) - strlen("-format")), command); ffStrbufLowerCase(&type); @@ -87,7 +94,7 @@ static void printCommandFormatHelp(const char* command) { fprintf(stderr, "Error: Module '%s' is not supported\n", type.chars); } -FF_A_COLD +[[gnu::cold]] static void printFullHelp() { fputs("Fastfetch is a neofetch-like tool for fetching system information and displaying them in a pretty way\n\n", stdout); if (!instance.config.display.pipe) { @@ -194,7 +201,7 @@ For detailed information on logo options, module configuration, and formatting, https://github.com/fastfetch-cli/fastfetch/wiki/Configuration"); } -FF_A_COLD +[[gnu::cold]] static bool printSpecificCommandHelp(const char* command) { yyjson_doc* doc = yyjson_read(FASTFETCH_DATATEXT_JSON_HELP, strlen(FASTFETCH_DATATEXT_JSON_HELP), YYJSON_READ_NOFLAG); assert(doc); @@ -305,9 +312,9 @@ static bool printSpecificCommandHelp(const char* command) { return false; } -FF_A_COLD +[[gnu::cold]] static void printCommandHelp(const char* command) { - if (command == NULL) { + if (command == nullptr) { printFullHelp(); } else if (ffStrEqualsIgnCase(command, "format-json")) { printCommandFormatHelpJson(); @@ -318,7 +325,7 @@ static void printCommandHelp(const char* command) { } } -FF_A_COLD +[[gnu::cold]] static void listAvailablePresets(bool pretty) { FF_LIST_FOR_EACH (FFstrbuf, path, instance.state.platform.dataDirs) { ffStrbufAppendS(path, "fastfetch/presets/"); @@ -333,7 +340,7 @@ static void listAvailablePresets(bool pretty) { } } -FF_A_COLD +[[gnu::cold]] static void listAvailableLogos(void) { FF_LIST_FOR_EACH (FFstrbuf, path, instance.state.platform.dataDirs) { ffStrbufAppendS(path, "fastfetch/logos/"); @@ -341,7 +348,7 @@ static void listAvailableLogos(void) { } } -FF_A_COLD +[[gnu::cold]] static void listConfigPaths(void) { FF_LIST_FOR_EACH (FFstrbuf, folder, instance.state.platform.configDirs) { bool exists = false; @@ -353,7 +360,7 @@ static void listConfigPaths(void) { } } -FF_A_COLD +[[gnu::cold]] static void listDataPaths(void) { FF_LIST_FOR_EACH (FFstrbuf, folder, instance.state.platform.dataDirs) { ffStrbufAppendS(folder, "fastfetch/"); @@ -361,7 +368,7 @@ static void listDataPaths(void) { } } -FF_A_COLD +[[gnu::cold]] static void listModules(bool pretty) { unsigned count = 0; for (int i = 0; i <= 'Z' - 'A'; ++i) { @@ -382,15 +389,15 @@ static bool parseJsoncFile(FFdata* data, const char* path, yyjson_read_flag flg) { yyjson_read_err error; data->configDoc = path - ? yyjson_read_file(path, flg, NULL, &error) - : yyjson_read_fp(stdin, flg, NULL, &error); + ? yyjson_read_file(path, flg, nullptr, &error) + : yyjson_read_fp(stdin, flg, nullptr, &error); if (!data->configDoc) { if (error.code != YYJSON_READ_ERROR_FILE_OPEN) { if (path) { size_t row = 0, col = error.pos; FF_STRBUF_AUTO_DESTROY content = ffStrbufCreate(); if (ffAppendFileBuffer(path, &content)) { - yyjson_locate_pos(content.chars, content.length, error.pos, &row, &col, NULL); + yyjson_locate_pos(content.chars, content.length, error.pos, &row, &col, nullptr); } fprintf(stderr, "Error: failed to parse JSON config file `%s` at (%zu, %zu): %s\n", path, row, col, error.msg); } else { @@ -410,9 +417,9 @@ static bool parseJsoncFile(FFdata* data, const char* path, yyjson_read_flag flg) exit(477); } - yyjson_val* problematicKey = NULL; - const char* error = NULL; - const char* problematicModule = NULL; + yyjson_val* problematicKey = nullptr; + const char* error = nullptr; + const char* problematicModule = nullptr; if ( error || ((error = ffOptionsParseLogoJsonConfig(&instance.config.logo, root, &problematicKey)) && (problematicModule = "logo")) || @@ -431,13 +438,8 @@ static bool parseJsoncFile(FFdata* data, const char* path, yyjson_read_flag flg) return true; } -FF_A_COLD -static void generateConfigFile(FFdata* data, bool force, const char* filePath, bool fullConfig) { - if (data->resultDoc) { - fprintf(stderr, "Error: duplicated `--gen-config` or `--format json` flags found\n"); - exit(477); - } - +[[gnu::cold]] +static void setupGenConfigPath(FFdata* data, const char* filePath) { if (!filePath) { if (instance.state.platform.configDirs.length == 0) { fprintf(stderr, "Error: No config directory found to generate config file in. Use --gen-config to specify a path\n"); @@ -451,14 +453,24 @@ static void generateConfigFile(FFdata* data, bool force, const char* filePath, b } else { ffStrbufSetS(&data->genConfigPath, filePath); } +} + +[[gnu::cold]] +static void generateConfigFile(FFdata* data, const char* filePath) { + if (data->resultDoc) { + fprintf(stderr, "Error: duplicated `--gen-config` or `--format json` flags found\n"); + exit(477); + } + + setupGenConfigPath(data, filePath); - if (!force && ffPathExists(data->genConfigPath.chars, FF_PATHTYPE_ANY)) { - fprintf(stderr, "Error: file `%s` exists. Use `--gen-config%s-force` to overwrite\n", data->genConfigPath.chars, fullConfig ? "-full" : ""); + if (ffPathExists(data->genConfigPath.chars, FF_PATHTYPE_ANY)) { + fprintf(stderr, "Error: file `%s` exists. Please remove it before generating a new one\n", data->genConfigPath.chars); exit(477); } - data->docType = fullConfig ? FF_RESULT_DOC_TYPE_CONFIG_FULL : FF_RESULT_DOC_TYPE_CONFIG; - data->resultDoc = yyjson_mut_doc_new(NULL); + data->docType = FF_RESULT_DOC_TYPE_CONFIG; + data->resultDoc = yyjson_mut_doc_new(nullptr); } static void optionParseConfigFile(FFdata* data, const char* key, const char* value) { @@ -469,7 +481,7 @@ static void optionParseConfigFile(FFdata* data, const char* key, const char* val data->configLoaded = true; - if (value == NULL) { + if (value == nullptr) { fprintf(stderr, "Error: usage: %s \n", key); exit(413); } @@ -479,7 +491,7 @@ static void optionParseConfigFile(FFdata* data, const char* key, const char* val } if (value[0] == '-' && value[1] == '\0') { - parseJsoncFile(data, NULL, false); + parseJsoncFile(data, nullptr, false); return; } @@ -569,7 +581,7 @@ static void optionParseConfigFile(FFdata* data, const char* key, const char* val exit(414); } -FF_A_COLD +[[gnu::cold]] static void printVersion() { FFVersionResult* result = &ffVersionResult; printf("%s %s%s%s (%s)\n", result->projectName, result->version, result->versionTweak, result->debugMode ? "-debug" : "", result->architecture); @@ -581,11 +593,20 @@ static void enableJsonOutput(FFdata* data) { exit(477); } - data->resultDoc = yyjson_mut_doc_new(NULL); + data->resultDoc = yyjson_mut_doc_new(nullptr); data->docType = FF_RESULT_DOC_TYPE_JSON; yyjson_mut_doc_set_root(data->resultDoc, yyjson_mut_arr(data->resultDoc)); } +static void genConfigCommon(FFdata* data, const char* value) { + if (!getenv("NO_COLOR") && isatty(STDOUT_FILENO) && isatty(STDIN_FILENO)) { + data->genConfigInteractive = true; + setupGenConfigPath(data, value); + } else { + generateConfigFile(data, value); + } +} + static void parseCommand(FFdata* data, char* key, char* value) { if (ffStrEqualsIgnCase(key, "-h") || ffStrEqualsIgnCase(key, "--help")) { printCommandHelp(value); @@ -647,13 +668,7 @@ static void parseCommand(FFdata* data, char* key, char* value) { exit(0); } else if (ffStrEqualsIgnCase(key, "--gen-config")) { - generateConfigFile(data, false, value, false); - } else if (ffStrEqualsIgnCase(key, "--gen-config-force")) { - generateConfigFile(data, true, value, false); - } else if (ffStrEqualsIgnCase(key, "--gen-config-full")) { - generateConfigFile(data, false, value, true); - } else if (ffStrEqualsIgnCase(key, "--gen-config-full-force")) { - generateConfigFile(data, true, value, true); + genConfigCommon(data, value); } else if (ffStrEqualsIgnCase(key, "-c") || ffStrEqualsIgnCase(key, "--config")) { optionParseConfigFile(data, key, value); } else if (ffStrEqualsIgnCase(key, "-j") || ffStrEqualsIgnCase(key, "--json")) { @@ -670,6 +685,12 @@ static void parseCommand(FFdata* data, char* key, char* value) { } } else if (ffStrEqualsIgnCase(key, "--dynamic-interval")) { instance.state.dynamicInterval = ffOptionParseUInt32(key, value); // seconds to milliseconds + } else if (ffStrEqualsIgnCase(key, "-w") || ffStrEqualsIgnCase(key, "--watch")) { + if (value == nullptr) { + instance.state.dynamicInterval = 1000; // default to 1 second if no value is provided + } else { + instance.state.dynamicInterval = ffOptionParseUInt32(key, value) * 1000; // seconds to milliseconds + } } else { return; } @@ -741,7 +762,7 @@ static void parseArguments(FFdata* data, int argc, char** argv, void (*parser)(F if (i == argc - 1 || (argv[i + 1][0] == '-' && argv[i + 1][1] != '\0' && // `-` is used as an alias for `/dev/stdin` !ffStrEqualsIgnCase(argv[i], "--separator-string") // Separator string can start with a - )) { - parser(data, argv[i], NULL); + parser(data, argv[i], nullptr); } else { parser(data, argv[i], argv[i + 1]); ++i; @@ -800,7 +821,7 @@ static void run(FFdata* data) { } if (data->resultDoc) { - yyjson_mut_write_fp(stdout, data->resultDoc, YYJSON_WRITE_INF_AND_NAN_AS_NULL | YYJSON_WRITE_PRETTY_TWO_SPACES | YYJSON_WRITE_NEWLINE_AT_END, NULL, NULL); + yyjson_mut_write_fp(stdout, data->resultDoc, YYJSON_WRITE_INF_AND_NAN_AS_NULL | YYJSON_WRITE_PRETTY_TWO_SPACES | YYJSON_WRITE_NEWLINE_AT_END, nullptr, nullptr); } else { if (instance.config.logo.printRemaining) { ffLogoPrintRemaining(); @@ -809,7 +830,7 @@ static void run(FFdata* data) { } } -FF_A_COLD +[[gnu::cold]] static void writeConfigFile(FFdata* data) { const FFstrbuf* filename = &data->genConfigPath; @@ -822,11 +843,19 @@ static void writeConfigFile(FFdata* data) { ffOptionsGenerateLogoJsonConfig(data, &instance.config.logo); ffOptionsGenerateDisplayJsonConfig(data, &instance.config.display); ffOptionsGenerateGeneralJsonConfig(data, &instance.config.general); + } else if (data->genConfigInteractive) { + if (instance.config.logo.type == FF_LOGO_TYPE_NONE) { + yyjson_mut_obj_add_null(doc, root, "logo"); + } else if (instance.config.logo.type == FF_LOGO_TYPE_SMALL) { + yyjson_mut_val* logo = yyjson_mut_obj(doc); + yyjson_mut_obj_add_str(doc, logo, "type", "small"); + yyjson_mut_obj_add_val(doc, root, "logo", logo); + } } ffMigrateCommandOptionToJsonc(data); if (ffStrbufEqualS(filename, "-")) { - yyjson_mut_write_fp(stdout, doc, YYJSON_WRITE_INF_AND_NAN_AS_NULL | YYJSON_WRITE_PRETTY_TWO_SPACES | YYJSON_WRITE_NEWLINE_AT_END, NULL, NULL); + yyjson_mut_write_fp(stdout, doc, YYJSON_WRITE_INF_AND_NAN_AS_NULL | YYJSON_WRITE_PRETTY_TWO_SPACES | YYJSON_WRITE_NEWLINE_AT_END, nullptr, nullptr); } else { size_t len; FF_AUTO_FREE const char* str = yyjson_mut_write(doc, YYJSON_WRITE_INF_AND_NAN_AS_NULL | YYJSON_WRITE_PRETTY_TWO_SPACES | YYJSON_WRITE_NEWLINE_AT_END, &len); @@ -871,6 +900,14 @@ int main(int argc, char** argv) { if (__builtin_expect(data.genConfigPath.length == 0, true)) { run(&data); } else { + if (data.genConfigInteractive && !ffGenConfigInteractive(&data)) { + // User cancelled the interactive config generation + ffStrbufDestroy(&data.structure); + ffStrbufDestroy(&data.structureDisabled); + yyjson_doc_free(data.configDoc); + ffStrbufDestroy(&data.genConfigPath); + return 0; + } writeConfigFile(&data); } diff --git a/src/flashfetch.c b/src/flashfetch.c index e056ca29cd..d75dcb5127 100644 --- a/src/flashfetch.c +++ b/src/flashfetch.c @@ -5,7 +5,7 @@ #include "modules/modules.h" #define MODULE_OPTION(name) \ - FF_A_CLEANUP(ffDestroy##name##Options) FF##name##Options options; \ + [[gnu::cleanup(ffDestroy##name##Options)]] FF##name##Options options; \ ffInit##name##Options(&options); // A dirty replicate of neofetch; demonstration only. diff --git a/src/logo/ascii/e.inc b/src/logo/ascii/e.inc index 3e5fd91081..11e3672d8c 100644 --- a/src/logo/ascii/e.inc +++ b/src/logo/ascii/e.inc @@ -65,17 +65,6 @@ static const FFlogo E[] = { }, }, #endif - #ifdef FASTFETCH_DATATEXT_LOGO_EMPEROROS - // EmperorOS - { - .names = { "Emperor" }, - .lines = FASTFETCH_DATATEXT_LOGO_EMPEROROS, - .colors = { - FF_COLOR_FG_YELLOW, - FF_COLOR_FG_DEFAULT, - }, - }, - #endif #ifdef FASTFETCH_DATATEXT_LOGO_ENOS // EN-OS { diff --git a/src/logo/ascii/e/emperoros.txt b/src/logo/ascii/e/emperoros.txt deleted file mode 100644 index 55dcaa97c7..0000000000 --- a/src/logo/ascii/e/emperoros.txt +++ /dev/null @@ -1,13 +0,0 @@ - !! - !!!! - llllll - llllll - IIIIIIIIII - IIIIIIIIIIIIIIIIIIII -;;;;;;;;;;;;;;;;;;;;;;;; - ;;;;;;;;;;;;;;;;;;;; - :;;::;:;:: - :::::: - ,,,,,, - ,,,, - "" \ No newline at end of file diff --git a/src/logo/ascii/f.inc b/src/logo/ascii/f.inc index eaa0ae0366..921d88cb9f 100644 --- a/src/logo/ascii/f.inc +++ b/src/logo/ascii/f.inc @@ -283,19 +283,6 @@ static const FFlogo F[] = { .colorTitle = FF_COLOR_FG_DEFAULT, }, #endif - #ifdef FASTFETCH_DATATEXT_LOGO_FURRETO - // Furreto - { - .names = { "Furreto" }, - .lines = FASTFETCH_DATATEXT_LOGO_FURRETO, - .colors = { - FF_COLOR_FG_WHITE, - FF_COLOR_FG_LIGHT_MAGENTA, - }, - .colorKeys = FF_COLOR_FG_CYAN, - .colorTitle = FF_COLOR_FG_CYAN, - }, - #endif // LAST {}, }; diff --git a/src/logo/ascii/f/furreto.txt b/src/logo/ascii/f/furreto.txt deleted file mode 100644 index 95ee07c989..0000000000 --- a/src/logo/ascii/f/furreto.txt +++ /dev/null @@ -1,22 +0,0 @@ - .$2xOOko $1.$2odd, - oX$1WW$2KOOOO. 'ON$1WW$20kkk. - $1.$2k0XKOOOOOOcOON$1W$2NOOOOO. - xOOOOOOOOOkkOOOOOOOOO; - $1.$2O0OkkocxO000000kcdk0OO0OOkx - k$1W$1M$2Xkkkkloxkkkx; :dxxxxddc... - 'kO0OOOOOkc .cl:..kk0KK0Okc - ;kOOO0000xd. dO00000Oo .xkO$1NMM$2XOOOO -.dddxkOOOkddc.kKN$1WW$2N000000l.ddk0000OOOO. - 'dd:;ddddd;.dK$1MMMW$2K00KKK0O::ddxkO00Oko - .okxkOKK0kkOO00KKOxxlodddddddl - .00OOkkkkkkkkOOO00OOOO0O; .dddl - 'kkkkkxxkkkkkkkOOkxdxkxxddd. - cddddddddxxkkkkkxddddddddddo - 'ddddddodddddddddddddddddddc - $1.$2ddddddodddddddddodddddddc - .odddo. - - $1.$2kOOkkk; - lkK$1WN$2kkkxc - kkxkkkkkkx. - ,,..xxx. \ No newline at end of file diff --git a/src/logo/ascii/h.inc b/src/logo/ascii/h.inc index 9d471eb737..d4efd6cc47 100644 --- a/src/logo/ascii/h.inc +++ b/src/logo/ascii/h.inc @@ -168,19 +168,6 @@ static const FFlogo H[] = { .colorTitle = FF_COLOR_FG_GREEN, }, #endif - #ifdef FASTFETCH_DATATEXT_LOGO_HYPROS - // HyprOS - { - .names = { "hypros" }, - .lines = FASTFETCH_DATATEXT_LOGO_HYPROS, - .colors = { - FF_COLOR_FG_RED, - FF_COLOR_FG_YELLOW, - FF_COLOR_FG_CYAN, - FF_COLOR_FG_BLUE, - }, - }, - #endif #ifdef FASTFETCH_DATATEXT_LOGO_HYPERBOLA // Hyperbola { diff --git a/src/logo/ascii/h/hypros.txt b/src/logo/ascii/h/hypros.txt deleted file mode 100644 index 5b7d4dddf0..0000000000 --- a/src/logo/ascii/h/hypros.txt +++ /dev/null @@ -1,17 +0,0 @@ - ___ - ,adZZEEEE#&$2>=x. - $1,zAP*~'$4_,-$2'~*VM$2N&x. - $1,%&P^`$4<$3,.$4<<$2,-===--.N>x - $1.%M7$4//$3,%^$2,x<3#$13EEbo$2<&>&b - $1&#/$4/$3.<^$4/$2x<>^$4-.`$1`+&WW$2<&N&; -$1/#/$4//$34$4//$2/W/ $4^+.`$1`###$2NM\ -$1##'$4|$3.l$4|$2,&/ $4`.',$1I#I$2HI# -$1#I$4||$3`I$4|$2(#( $3)`'$1)##$2H~^ -$1@\$4|||$3\$4\$2`X\ $3///$1,##%V$3'/ -$4\\\\\\$3Y,$2*@b, $3.-+//$1/&#%#/$3,' -$4`\\\\$2,.$4\$3<$2`*$3^`x<$1,z<#&#x"$3,' - $3`x<<$2`Xx,$3`<_`$1+{##&@P^$4'>$3' - $3`<_<<$2^<\-.$3`*`>$1<^'$4,-' - $3`<_=-$2^\Xx$1XX\.$3+<. - $3`^<_-$2^width) { char place[64]; @@ -176,7 +176,7 @@ static bool printImageKittyIcat(bool printError) { place, "--scale-up", options->source.chars, - NULL, + nullptr, }); } else { error = ffProcessAppendStdOut(&buf, (char*[]) { @@ -185,7 +185,7 @@ static bool printImageKittyIcat(bool printError) { "-n", "--align=left", options->source.chars, - NULL, + nullptr, }); } if (error) { @@ -374,7 +374,7 @@ static bool compressBlob(void** blob, size_t* length) { uLong compressedLength = ffcompressBound(*length); void* compressed = malloc(compressedLength); - if (compressed == NULL) { + if (compressed == nullptr) { return false; } @@ -410,7 +410,7 @@ typedef struct ImageData { } ImageData; static inline bool checkAllocationResult(void* data, size_t length) { - if (data == NULL) { + if (data == nullptr) { return false; } @@ -578,7 +578,7 @@ static bool printImageChafa(FFLogoRequestData* requestData, const ImageData* ima } ChafaSymbolMap* symbolMap = ffchafa_symbol_map_new(); - GError* error = NULL; + GError* error = nullptr; if (!ffchafa_symbol_map_apply_selectors(symbolMap, instance.config.logo.chafaSymbols.chars, &error)) { fputs(error->message, stderr); } @@ -621,7 +621,7 @@ static bool printImageChafa(FFLogoRequestData* requestData, const ImageData* ima (gint) imageData->image->rows, (gint) imageData->image->columns * 4); - GString* str = ffchafa_canvas_print(canvas, NULL); + GString* str = ffchafa_canvas_print(canvas, nullptr); FFstrbuf result; result.allocated = (uint32_t) str->allocated_len; result.length = (uint32_t) str->len; @@ -666,16 +666,16 @@ FFLogoImageResult ffLogoPrintImageImpl(FFLogoRequestData* requestData, const FFI FF_LIBRARY_LOAD_SYMBOL_VAR(imData->library, imageData, ImageToBlob, FF_LOGO_IMAGE_RESULT_INIT_ERROR) FF_LIBRARY_LOAD_SYMBOL_VAR(imData->library, imageData, Base64Encode, FF_LOGO_IMAGE_RESULT_INIT_ERROR) - ffMagickCoreGenesis(NULL, MagickFalse); + ffMagickCoreGenesis(nullptr, MagickFalse); imageData.exceptionInfo = ffAcquireExceptionInfo(); - if (imageData.exceptionInfo == NULL) { + if (imageData.exceptionInfo == nullptr) { ffMagickCoreTerminus(); return FF_LOGO_IMAGE_RESULT_RUN_ERROR; } ImageInfo* imageInfoIn = ffAcquireImageInfo(); - if (imageInfoIn == NULL) { + if (imageInfoIn == nullptr) { ffDestroyExceptionInfo(imageData.exceptionInfo); ffMagickCoreTerminus(); return FF_LOGO_IMAGE_RESULT_RUN_ERROR; @@ -686,7 +686,7 @@ FFLogoImageResult ffLogoPrintImageImpl(FFLogoRequestData* requestData, const FFI imageData.image = ffReadImage(imageInfoIn, imageData.exceptionInfo); ffDestroyImageInfo(imageInfoIn); - if (imageData.image == NULL) { + if (imageData.image == nullptr) { ffDestroyExceptionInfo(imageData.exceptionInfo); ffMagickCoreTerminus(); return FF_LOGO_IMAGE_RESULT_RUN_ERROR; @@ -713,7 +713,7 @@ FFLogoImageResult ffLogoPrintImageImpl(FFLogoRequestData* requestData, const FFI Image* resized = imData->resizeFunc(imageData.image, requestData->logoPixelWidth, requestData->logoPixelHeight, imageData.exceptionInfo); ffDestroyImage(imageData.image); - if (resized == NULL) { + if (resized == nullptr) { ffDestroyExceptionInfo(imageData.exceptionInfo); ffMagickCoreTerminus(); return FF_LOGO_IMAGE_RESULT_RUN_ERROR; @@ -721,7 +721,7 @@ FFLogoImageResult ffLogoPrintImageImpl(FFLogoRequestData* requestData, const FFI imageData.image = resized; imageData.imageInfo = ffAcquireImageInfo(); - if (imageData.imageInfo == NULL) { + if (imageData.imageInfo == nullptr) { ffDestroyImage(imageData.image); ffDestroyExceptionInfo(imageData.exceptionInfo); ffMagickCoreTerminus(); @@ -757,7 +757,7 @@ static FFNativeFD getCacheFD(FFLogoRequestData* requestData, const char* fileNam #endif ); #else - HANDLE fd = CreateFileA(requestData->cacheDir.chars, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); + HANDLE fd = CreateFileA(requestData->cacheDir.chars, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); #endif ffStrbufSubstrBefore(&requestData->cacheDir, cacheDirLength); return fd; @@ -843,7 +843,7 @@ static bool printCachedPixel(FFLogoRequestData* requestData) { struct stat st; if (fstat(fd, &st) >= 0) { while (st.st_size > 0) { - ssize_t bytes = sendfile(STDOUT_FILENO, fd, NULL, (size_t) st.st_size); + ssize_t bytes = sendfile(STDOUT_FILENO, fd, nullptr, (size_t) st.st_size); if (bytes > 0) { sent = true; st.st_size -= bytes; @@ -921,7 +921,7 @@ static bool printImageIfExistsSlowPath(FFLogoType type, bool printError) { ffStrbufEnsureFree(&requestData.cacheDir, PATH_MAX); char* filePath = requestData.cacheDir.chars + requestData.cacheDir.length; - if (realpath(instance.config.logo.source.chars, filePath) == NULL) { + if (realpath(instance.config.logo.source.chars, filePath) == nullptr) { // We can safely return here, because if realpath failed, we surely won't be able to read the file ffStrbufDestroy(&requestData.cacheDir); if (printError) { diff --git a/src/logo/image/image.h b/src/logo/image/image.h index da3b2d2902..5fbd39a004 100644 --- a/src/logo/image/image.h +++ b/src/logo/image/image.h @@ -4,7 +4,7 @@ #if defined(FF_HAVE_IMAGEMAGICK7) || defined(FF_HAVE_IMAGEMAGICK6) -typedef enum FF_A_PACKED FFLogoImageResult { +typedef enum FFLogoImageResult: uint8_t { FF_LOGO_IMAGE_RESULT_SUCCESS, // Logo printed FF_LOGO_IMAGE_RESULT_INIT_ERROR, // Failed to load library, try again with next IM version FF_LOGO_IMAGE_RESULT_RUN_ERROR // Failed to load / convert image, cancel whole sixel code diff --git a/src/logo/logo.c b/src/logo/logo.c index 571f1aac97..1cc3211dc4 100644 --- a/src/logo/logo.c +++ b/src/logo/logo.c @@ -56,7 +56,7 @@ static void logoLineCacheBuild(FFLogoLineCacheState* cache, const char* data, bo } for (uint32_t i = 0; i < options->paddingTop; ++i) { - logoLineCachePush(NULL, 0, cache); + logoLineCachePush(nullptr, 0, cache); } if (*data != '\0') { @@ -184,7 +184,7 @@ static void logoLineCacheBuild(FFLogoLineCacheState* cache, const char* data, bo uint32_t totalLines = instance.state.logoHeight + 1; while (cache->lines.length < totalLines) { - logoLineCachePush(NULL, 0, cache); + logoLineCachePush(nullptr, 0, cache); } cache->nextLine = 0; @@ -298,7 +298,7 @@ static void logoApplyColors(const FFlogo* logo, bool replacement) { FFOptionsLogo* options = &instance.config.logo; const char* const* colors = logo->colors; - for (int i = 0; *colors != NULL && i < FASTFETCH_LOGO_MAX_COLORS; i++, colors++) { + for (int i = 0; *colors != nullptr && i < FASTFETCH_LOGO_MAX_COLORS; i++, colors++) { if (options->colors[i].length == 0) { ffStrbufAppendS(&options->colors[i], *colors); } @@ -309,7 +309,7 @@ static void logoApplyColors(const FFlogo* logo, bool replacement) { static bool logoHasName(const FFlogo* logo, const FFstrbuf* name, bool small) { for ( const char* const* logoName = logo->names; - *logoName != NULL && logoName <= &logo->names[FASTFETCH_LOGO_MAX_NAMES]; + *logoName != nullptr && logoName <= &logo->names[FASTFETCH_LOGO_MAX_NAMES]; ++logoName) { if (small) { uint32_t logoNameLength = (uint32_t) (strlen(*logoName) - strlen("_small")); @@ -327,7 +327,7 @@ static bool logoHasName(const FFlogo* logo, const FFstrbuf* name, bool small) { static const FFlogo* logoGetBuiltin(const FFstrbuf* name, FFLogoSize size) { if (name->length == 0 || !isalpha(name->chars[0])) { - return NULL; + return nullptr; } for (const FFlogo* logo = ffLogoBuiltins[toupper(name->chars[0]) - 'A']; *logo->names; ++logo) { @@ -352,19 +352,19 @@ static const FFlogo* logoGetBuiltin(const FFstrbuf* name, FFLogoSize size) { } } - return NULL; + return nullptr; } static const FFlogo* logoGetBuiltinDetected(FFLogoSize size) { const FFOSResult* os = ffDetectOS(); const FFlogo* logo = logoGetBuiltin(&os->id, size); - if (logo != NULL) { + if (logo != nullptr) { return logo; } logo = logoGetBuiltin(&os->name, size); - if (logo != NULL) { + if (logo != nullptr) { return logo; } @@ -376,7 +376,7 @@ static const FFlogo* logoGetBuiltinDetected(FFLogoSize size) { start = end + 1, end = ffStrbufNextIndexC(&os->idLike, start, ' ')) { ffStrbufSetNS(&buf, end - start, os->idLike.chars + start); logo = logoGetBuiltin(&buf, size); - if (logo != NULL) { + if (logo != nullptr) { return logo; } @@ -386,13 +386,13 @@ static const FFlogo* logoGetBuiltinDetected(FFLogoSize size) { } } else { logo = logoGetBuiltin(&os->idLike, size); - if (logo != NULL) { + if (logo != nullptr) { return logo; } } logo = logoGetBuiltin(&instance.state.platform.sysinfo.name, size); - if (logo != NULL) { + if (logo != nullptr) { return logo; } @@ -427,7 +427,7 @@ static bool logoPrintBuiltinIfExists(const FFstrbuf* name, FFLogoSize size) { } const FFlogo* logo = ffLogoGetBuiltinForName(name, size); - if (logo == NULL) { + if (logo == nullptr) { return false; } @@ -561,7 +561,7 @@ static bool logoTryKnownType(void) { "/bin/sh", "-c", #endif options->source.chars, - NULL }); + nullptr }); if (error) { if (instance.config.display.showErrors) { @@ -786,7 +786,7 @@ void ffLogoBuiltinList(void) { for ( const char* const* names = logo->names; - *names != NULL && names <= &logo->names[FASTFETCH_LOGO_MAX_NAMES]; + *names != nullptr && names <= &logo->names[FASTFETCH_LOGO_MAX_NAMES]; ++names) { printf("\"%s\" ", *names); } diff --git a/src/logo/logo.h b/src/logo/logo.h index 105b96499f..324b590caa 100644 --- a/src/logo/logo.h +++ b/src/logo/logo.h @@ -2,14 +2,13 @@ #include "fastfetch.h" -typedef enum FF_A_PACKED FFLogoLineType { +typedef enum FFLogoLineType: uint8_t { FF_LOGO_LINE_TYPE_NORMAL = 0, FF_LOGO_LINE_TYPE_SMALL_BIT = 1 << 0, // The names of small logo must end with `_small` or `-small` FF_LOGO_LINE_TYPE_ALTER_BIT = 1 << 1, - FF_LOGO_LINE_TYPE_FORCE_UNSIGNED = UINT8_MAX, } FFLogoLineType; -typedef enum FF_A_PACKED FFLogoSize { +typedef enum FFLogoSize: uint8_t { FF_LOGO_SIZE_UNKNOWN, FF_LOGO_SIZE_NORMAL, FF_LOGO_SIZE_SMALL, diff --git a/src/modules/battery/battery.c b/src/modules/battery/battery.c index 61cef84bb4..7b8405e71e 100644 --- a/src/modules/battery/battery.c +++ b/src/modules/battery/battery.c @@ -121,36 +121,35 @@ static void printBattery(FFBatteryOptions* options, FFBatteryResult* result, uin ffDurationAppendNum((uint32_t) result->timeRemaining, &timeStr); } - FF_STRBUF_AUTO_DESTROY statusStr = ffStrbufCreate(); + FF_LIST_AUTO_DESTROY status = ffListCreate(); if (result->status & FF_BATTERY_STATUS_AC_CONNECTED) { - ffStrbufAppendS(&statusStr, "AC Connected, "); + ffStrbufInitStatic(FF_LIST_ADD(FFstrbuf, status), "AC Connected"); } if (result->status & FF_BATTERY_STATUS_USB_CONNECTED) { - ffStrbufAppendS(&statusStr, "USB Connected, "); + ffStrbufInitStatic(FF_LIST_ADD(FFstrbuf, status), "USB Connected"); } if (result->status & FF_BATTERY_STATUS_WIRELESS_CONNECTED) { - ffStrbufAppendS(&statusStr, "Wireless Connected, "); + ffStrbufInitStatic(FF_LIST_ADD(FFstrbuf, status), "Wireless Connected"); } if (result->status & FF_BATTERY_STATUS_CHARGING) { - ffStrbufAppendS(&statusStr, "Charging, "); + ffStrbufInitStatic(FF_LIST_ADD(FFstrbuf, status), "Charging"); } if (result->status & FF_BATTERY_STATUS_DISCHARGING) { - ffStrbufAppendS(&statusStr, "Discharging, "); + ffStrbufInitStatic(FF_LIST_ADD(FFstrbuf, status), "Discharging"); } if (result->status & FF_BATTERY_STATUS_CRITICAL) { - ffStrbufAppendS(&statusStr, "Critical, "); + ffStrbufInitStatic(FF_LIST_ADD(FFstrbuf, status), "Critical"); } if (result->status & FF_BATTERY_STATUS_UNKNOWN) { - ffStrbufAppendS(&statusStr, "Unknown, "); + ffStrbufInitStatic(FF_LIST_ADD(FFstrbuf, status), "Unknown"); } - ffStrbufSubstrBefore(&statusStr, statusStr.length - 2); // Remove last ", " FF_PRINT_FORMAT_CHECKED(key.chars, 0, &options->moduleArgs, FF_PRINT_TYPE_NO_CUSTOM_KEY, ((FFformatarg[]) { FF_ARG(result->manufacturer, "manufacturer"), FF_ARG(result->modelName, "model-name"), FF_ARG(result->technology, "technology"), FF_ARG(capacityNum, "capacity"), - FF_ARG(statusStr, "status"), + FF_ARG(status, "status"), FF_ARG(tempStr, "temperature"), FF_ARG(result->cycleCount, "cycle-count"), FF_ARG(result->serial, "serial"), @@ -322,5 +321,6 @@ FFModuleBaseInfo ffBatteryModuleInfo = { { "Battery time remaining minutes", "time-minutes" }, { "Battery time remaining seconds", "time-seconds" }, { "Battery time remaining (formatted)", "time-formatted" }, - })) + })), + .defaultOrder = 44, }; diff --git a/src/modules/bios/bios.c b/src/modules/bios/bios.c index 8f8700ff1b..c000080f49 100644 --- a/src/modules/bios/bios.c +++ b/src/modules/bios/bios.c @@ -88,7 +88,7 @@ void ffGenerateBiosJsonConfig(FFBiosOptions* options, yyjson_mut_doc* doc, yyjso ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateBiosJsonResult(FF_A_UNUSED FFBiosOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateBiosJsonResult([[maybe_unused]] FFBiosOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { bool success = false; FFBiosResult bios; ffStrbufInit(&bios.date); @@ -144,5 +144,6 @@ FFModuleBaseInfo ffBiosModuleInfo = { { "BIOS vendor", "vendor" }, { "BIOS version", "version" }, { "Firmware type", "type" }, - })) + })), + .defaultOrder = 5, }; diff --git a/src/modules/bluetooth/bluetooth.c b/src/modules/bluetooth/bluetooth.c index 6721c336da..42a251886a 100644 --- a/src/modules/bluetooth/bluetooth.c +++ b/src/modules/bluetooth/bluetooth.c @@ -166,5 +166,6 @@ FFModuleBaseInfo ffBluetoothModuleInfo = { { "Battery percentage number", "battery-percentage" }, { "Is connected", "connected" }, { "Battery percentage bar", "battery-percentage-bar" }, - })) + })), + .defaultOrder = 58, }; diff --git a/src/modules/bluetoothradio/bluetoothradio.c b/src/modules/bluetoothradio/bluetoothradio.c index 1ebd34c454..fc113fc832 100644 --- a/src/modules/bluetoothradio/bluetoothradio.c +++ b/src/modules/bluetoothradio/bluetoothradio.c @@ -27,7 +27,7 @@ static void printDevice(FFBluetoothRadioOptions* options, const FFBluetoothRadio })); } - const char* version = NULL; + const char* version = nullptr; switch (radio->lmpVersion < 0 ? -radio->lmpVersion : radio->lmpVersion) { case 0: @@ -145,7 +145,7 @@ void ffGenerateBluetoothRadioJsonConfig(FFBluetoothRadioOptions* options, yyjson ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateBluetoothRadioJsonResult(FF_A_UNUSED FFBluetoothRadioOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateBluetoothRadioJsonResult([[maybe_unused]] FFBluetoothRadioOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FF_LIST_AUTO_DESTROY results = ffListCreate(); const char* error = ffDetectBluetoothRadio(&results); @@ -207,5 +207,6 @@ FFModuleBaseInfo ffBluetoothRadioModuleInfo = { { "Vendor", "vendor" }, { "Discoverable", "discoverable" }, { "Connectable / Pairable", "connectable" }, - })) + })), + .defaultOrder = 59, }; diff --git a/src/modules/board/board.c b/src/modules/board/board.c index a0801a2747..1a85ea3930 100644 --- a/src/modules/board/board.c +++ b/src/modules/board/board.c @@ -64,7 +64,7 @@ void ffGenerateBoardJsonConfig(FFBoardOptions* options, yyjson_mut_doc* doc, yyj ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateBoardJsonResult(FF_A_UNUSED FFBoardOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateBoardJsonResult([[maybe_unused]] FFBoardOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { bool success = false; FFBoardResult board; ffStrbufInit(&board.name); @@ -121,5 +121,6 @@ FFModuleBaseInfo ffBoardModuleInfo = { { "Board vendor", "vendor" }, { "Board version", "version" }, { "Board serial number", "serial" }, - })) + })), + .defaultOrder = 7, }; diff --git a/src/modules/bootmgr/bootmgr.c b/src/modules/bootmgr/bootmgr.c index f44d67a8d0..494885fd6c 100644 --- a/src/modules/bootmgr/bootmgr.c +++ b/src/modules/bootmgr/bootmgr.c @@ -67,7 +67,7 @@ void ffGenerateBootmgrJsonConfig(FFBootmgrOptions* options, yyjson_mut_doc* doc, ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateBootmgrJsonResult(FF_A_UNUSED FFBootmgrOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateBootmgrJsonResult([[maybe_unused]] FFBootmgrOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { bool success = false; FFBootmgrResult bootmgr = { .name = ffStrbufCreate(), @@ -117,5 +117,6 @@ FFModuleBaseInfo ffBootmgrModuleInfo = { { "Firmware file name", "firmware-name" }, { "Is secure boot enabled", "secure-boot" }, { "Boot order", "order" }, - })) + })), + .defaultOrder = 6, }; diff --git a/src/modules/break/break.c b/src/modules/break/break.c index e560e18a6b..011458a283 100644 --- a/src/modules/break/break.c +++ b/src/modules/break/break.c @@ -2,13 +2,13 @@ #include "logo/logo.h" #include "modules/break/break.h" -bool ffPrintBreak(FF_A_UNUSED FFBreakOptions* options) { +bool ffPrintBreak([[maybe_unused]] FFBreakOptions* options) { ffLogoPrintLine(); putchar('\n'); return true; } -void ffParseBreakJsonObject(FF_A_UNUSED FFBreakOptions* options, FF_A_UNUSED yyjson_val* module) { +void ffParseBreakJsonObject([[maybe_unused]] FFBreakOptions* options, [[maybe_unused]] yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; yyjson_obj_foreach (module, idx, max, key, val) { @@ -16,14 +16,14 @@ void ffParseBreakJsonObject(FF_A_UNUSED FFBreakOptions* options, FF_A_UNUSED yyj continue; } - ffPrintError(FF_BREAK_MODULE_NAME, 0, NULL, FF_PRINT_TYPE_NO_CUSTOM_KEY, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); + ffPrintError(FF_BREAK_MODULE_NAME, 0, nullptr, FF_PRINT_TYPE_NO_CUSTOM_KEY, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -void ffInitBreakOptions(FF_A_UNUSED FFBreakOptions* options) { +void ffInitBreakOptions([[maybe_unused]] FFBreakOptions* options) { } -void ffDestroyBreakOptions(FF_A_UNUSED FFBreakOptions* options) { +void ffDestroyBreakOptions([[maybe_unused]] FFBreakOptions* options) { } FFModuleBaseInfo ffBreakModuleInfo = { @@ -33,4 +33,5 @@ FFModuleBaseInfo ffBreakModuleInfo = { .destroyOptions = (void*) ffDestroyBreakOptions, .parseJsonObject = (void*) ffParseBreakJsonObject, .printModule = (void*) ffPrintBreak, + .defaultOrder = 71, }; diff --git a/src/modules/brightness/brightness.c b/src/modules/brightness/brightness.c index 54bb989401..479a2ccb9b 100644 --- a/src/modules/brightness/brightness.c +++ b/src/modules/brightness/brightness.c @@ -148,7 +148,7 @@ void ffGenerateBrightnessJsonConfig(FFBrightnessOptions* options, yyjson_mut_doc yyjson_mut_obj_add_bool(doc, module, "compact", options->compact); } -bool ffGenerateBrightnessJsonResult(FF_A_UNUSED FFBrightnessOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateBrightnessJsonResult([[maybe_unused]] FFBrightnessOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FF_LIST_AUTO_DESTROY result = ffListCreate(); const char* error = ffDetectBrightness(options, &result); @@ -206,5 +206,6 @@ FFModuleBaseInfo ffBrightnessModuleInfo = { { "Current brightness value", "current" }, { "Screen brightness (percentage bar)", "percentage-bar" }, { "Is built-in screen", "is-builtin" }, - })) + })), + .defaultOrder = 18, }; diff --git a/src/modules/btrfs/btrfs.c b/src/modules/btrfs/btrfs.c index 238d177674..21068e85db 100644 --- a/src/modules/btrfs/btrfs.c +++ b/src/modules/btrfs/btrfs.c @@ -146,7 +146,7 @@ void ffGenerateBtrfsJsonConfig(FFBtrfsOptions* options, yyjson_mut_doc* doc, yyj ffPercentGenerateJsonConfig(doc, module, options->percent); } -bool ffGenerateBtrfsJsonResult(FF_A_UNUSED FFBtrfsOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateBtrfsJsonResult([[maybe_unused]] FFBtrfsOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FF_LIST_AUTO_DESTROY results = ffListCreate(); const char* error = ffDetectBtrfs(&results); @@ -220,5 +220,6 @@ FFModuleBaseInfo ffBtrfsModuleInfo = { { "Allocated percentage bar", "allocated-percentage-bar" }, { "Node size", "node-size" }, { "Sector size", "sector-size" }, - })) + })), + .defaultOrder = 42, }; diff --git a/src/modules/camera/camera.c b/src/modules/camera/camera.c index 7067bbc2fe..02c454bbbf 100644 --- a/src/modules/camera/camera.c +++ b/src/modules/camera/camera.c @@ -1,7 +1,5 @@ #include "common/printing.h" #include "common/jsonconfig.h" -#include "common/strutil.h" -#include "detection/libc/libc.h" #include "detection/camera/camera.h" #include "modules/camera/camera.h" @@ -53,6 +51,7 @@ bool ffPrintCamera(FFCameraOptions* options) { FF_LIST_FOR_EACH (FFCameraResult, dev, result) { ffStrbufDestroy(&dev->name); + ffStrbufDestroy(&dev->vendor); ffStrbufDestroy(&dev->id); ffStrbufDestroy(&dev->colorspace); } @@ -76,7 +75,7 @@ void ffGenerateCameraJsonConfig(FFCameraOptions* options, yyjson_mut_doc* doc, y ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateCameraJsonResult(FF_A_UNUSED FFCameraOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateCameraJsonResult([[maybe_unused]] FFCameraOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FF_LIST_AUTO_DESTROY result = ffListCreate(); const char* error = ffDetectCamera(&result); @@ -99,6 +98,7 @@ bool ffGenerateCameraJsonResult(FF_A_UNUSED FFCameraOptions* options, yyjson_mut FF_LIST_FOR_EACH (FFCameraResult, dev, result) { ffStrbufDestroy(&dev->name); + ffStrbufDestroy(&dev->vendor); ffStrbufDestroy(&dev->id); ffStrbufDestroy(&dev->colorspace); } @@ -130,5 +130,6 @@ FFModuleBaseInfo ffCameraModuleInfo = { { "Identifier", "id" }, { "Width (in px)", "width" }, { "Height (in px)", "height" }, - })) + })), + .defaultOrder = 61, }; diff --git a/src/modules/chassis/chassis.c b/src/modules/chassis/chassis.c index d944baa443..9b5b21e7a6 100644 --- a/src/modules/chassis/chassis.c +++ b/src/modules/chassis/chassis.c @@ -66,7 +66,7 @@ void ffGenerateChassisJsonConfig(FFChassisOptions* options, yyjson_mut_doc* doc, ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateChassisJsonResult(FF_A_UNUSED FFChassisOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateChassisJsonResult([[maybe_unused]] FFChassisOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { bool success = false; FFChassisResult result; ffStrbufInit(&result.type); @@ -124,4 +124,5 @@ FFModuleBaseInfo ffChassisModuleInfo = { { "Chassis version", "version" }, { "Chassis serial number", "serial" }, })), + .defaultOrder = 8, }; diff --git a/src/modules/codec/codec.c b/src/modules/codec/codec.c index 4e6889e309..a9a465bf84 100644 --- a/src/modules/codec/codec.c +++ b/src/modules/codec/codec.c @@ -174,7 +174,7 @@ void ffParseCodecJsonObject(FFCodecOptions* options, yyjson_val* module) { {}, }); if (error) { - ffPrintError(FF_CODEC_MODULE_NAME, 0, NULL, FF_PRINT_TYPE_NO_CUSTOM_KEY, "Invalid %s value: %s", unsafe_yyjson_get_str(key), error); + ffPrintError(FF_CODEC_MODULE_NAME, 0, nullptr, FF_PRINT_TYPE_NO_CUSTOM_KEY, "Invalid %s value: %s", unsafe_yyjson_get_str(key), error); } else { options->showType = (FFCodecShowType) value; } @@ -264,5 +264,6 @@ FFModuleBaseInfo ffCodecModuleInfo = { { "Decoder / Encoder", "direction" }, { "Compatibility alias of codec types", "types" }, { "Platform API used for detection", "platform-api" }, - })) + })), + .defaultOrder = 37, }; diff --git a/src/modules/codec/option.h b/src/modules/codec/option.h index bcc9201274..5f11f964d3 100644 --- a/src/modules/codec/option.h +++ b/src/modules/codec/option.h @@ -2,12 +2,11 @@ #include "common/option.h" -typedef enum FF_A_PACKED FFCodecShowType { +typedef enum FFCodecShowType: uint8_t { FF_CODEC_SHOW_TYPE_NONE = 0, FF_CODEC_SHOW_TYPE_ENCODER = 1 << 0, FF_CODEC_SHOW_TYPE_DECODER = 1 << 1, FF_CODEC_SHOW_TYPE_BOTH = FF_CODEC_SHOW_TYPE_ENCODER | FF_CODEC_SHOW_TYPE_DECODER, - FF_CODEC_SHOW_TYPE_FORCE_UNSIGNED = UINT8_MAX, } FFCodecShowType; typedef struct FFCodecOptions { diff --git a/src/modules/colors/colors.c b/src/modules/colors/colors.c index ff821d12f6..8d225d4bf1 100644 --- a/src/modules/colors/colors.c +++ b/src/modules/colors/colors.c @@ -164,7 +164,7 @@ void ffParseColorsJsonObject(FFColorsOptions* options, yyjson_val* module) { {}, }); if (error) { - ffPrintError(FF_COLORS_MODULE_NAME, 0, NULL, FF_PRINT_TYPE_NO_CUSTOM_KEY, "Invalid %s value: %s", unsafe_yyjson_get_str(key), error); + ffPrintError(FF_COLORS_MODULE_NAME, 0, nullptr, FF_PRINT_TYPE_NO_CUSTOM_KEY, "Invalid %s value: %s", unsafe_yyjson_get_str(key), error); } else { options->symbol = (FFColorsSymbol) value; } @@ -178,7 +178,7 @@ void ffParseColorsJsonObject(FFColorsOptions* options, yyjson_val* module) { if (unsafe_yyjson_equals_str(key, "block")) { if (!yyjson_is_obj(val)) { - ffPrintError(FF_COLORS_MODULE_NAME, 0, NULL, FF_PRINT_TYPE_NO_CUSTOM_KEY, "Invalid %s value: must be an object", unsafe_yyjson_get_str(key)); + ffPrintError(FF_COLORS_MODULE_NAME, 0, nullptr, FF_PRINT_TYPE_NO_CUSTOM_KEY, "Invalid %s value: must be an object", unsafe_yyjson_get_str(key)); } else { yyjson_val* width = yyjson_obj_get(val, "width"); if (width) { @@ -188,14 +188,14 @@ void ffParseColorsJsonObject(FFColorsOptions* options, yyjson_val* module) { yyjson_val* range = yyjson_obj_get(val, "range"); if (range) { if (!yyjson_is_arr(range) || yyjson_arr_size(range) != 2) { - ffPrintError(FF_COLORS_MODULE_NAME, 0, NULL, FF_PRINT_TYPE_NO_CUSTOM_KEY, "Invalid %s.range value: must be an array of 2 elements", unsafe_yyjson_get_str(key)); + ffPrintError(FF_COLORS_MODULE_NAME, 0, nullptr, FF_PRINT_TYPE_NO_CUSTOM_KEY, "Invalid %s.range value: must be an array of 2 elements", unsafe_yyjson_get_str(key)); } else { uint8_t start = (uint8_t) yyjson_get_uint(yyjson_arr_get(range, 0)); uint8_t end = (uint8_t) yyjson_get_uint(yyjson_arr_get(range, 1)); if (start > end) { - ffPrintError(FF_COLORS_MODULE_NAME, 0, NULL, FF_PRINT_TYPE_NO_CUSTOM_KEY, "Invalid %s.range value: range[0] > range[1]", unsafe_yyjson_get_str(key)); + ffPrintError(FF_COLORS_MODULE_NAME, 0, nullptr, FF_PRINT_TYPE_NO_CUSTOM_KEY, "Invalid %s.range value: range[0] > range[1]", unsafe_yyjson_get_str(key)); } else if (end > 15) { - ffPrintError(FF_COLORS_MODULE_NAME, 0, NULL, FF_PRINT_TYPE_NO_CUSTOM_KEY, "Invalid %s.range value: range[1] > 15", unsafe_yyjson_get_str(key)); + ffPrintError(FF_COLORS_MODULE_NAME, 0, nullptr, FF_PRINT_TYPE_NO_CUSTOM_KEY, "Invalid %s.range value: range[1] > 15", unsafe_yyjson_get_str(key)); } else { options->block.range[0] = start; options->block.range[1] = end; @@ -215,14 +215,14 @@ void ffParseColorsJsonObject(FFColorsOptions* options, yyjson_val* module) { {}, }); if (error) { - ffPrintError(FF_COLORS_MODULE_NAME, 0, NULL, FF_PRINT_TYPE_NO_CUSTOM_KEY, "Invalid %s value: %s", unsafe_yyjson_get_str(key), error); + ffPrintError(FF_COLORS_MODULE_NAME, 0, nullptr, FF_PRINT_TYPE_NO_CUSTOM_KEY, "Invalid %s value: %s", unsafe_yyjson_get_str(key), error); } else { options->brightness = (FFColorsBrightness) value; } continue; } - ffPrintError(FF_COLORS_MODULE_NAME, 0, NULL, FF_PRINT_TYPE_NO_CUSTOM_KEY, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); + ffPrintError(FF_COLORS_MODULE_NAME, 0, nullptr, FF_PRINT_TYPE_NO_CUSTOM_KEY, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } @@ -302,4 +302,5 @@ FFModuleBaseInfo ffColorsModuleInfo = { .parseJsonObject = (void*) ffParseColorsJsonObject, .printModule = (void*) ffPrintColors, .generateJsonConfig = (void*) ffGenerateColorsJsonConfig, + .defaultOrder = 72, }; diff --git a/src/modules/colors/option.h b/src/modules/colors/option.h index c9971c71d0..4d056bb2e9 100644 --- a/src/modules/colors/option.h +++ b/src/modules/colors/option.h @@ -2,7 +2,7 @@ #include "common/option.h" -typedef enum FF_A_PACKED FFColorsSymbol { +typedef enum FFColorsSymbol: uint8_t { FF_COLORS_SYMBOL_BLOCK, FF_COLORS_SYMBOL_BACKGROUND, FF_COLORS_SYMBOL_CIRCLE, @@ -17,7 +17,7 @@ typedef struct FFBlockConfig { uint8_t range[2]; } FFBlockConfig; -typedef enum FF_A_PACKED FFColorsBrightness { +typedef enum FFColorsBrightness: uint8_t { FF_COLORS_BRIGHTNESS_DEFAULT, FF_COLORS_BRIGHTNESS_NORMAL, FF_COLORS_BRIGHTNESS_LIGHT, diff --git a/src/modules/command/command.c b/src/modules/command/command.c index 9890911173..4de947a792 100644 --- a/src/modules/command/command.c +++ b/src/modules/command/command.c @@ -19,7 +19,7 @@ bool ffPrintCommand(FFCommandOptions* options) { if (options->splitLines) { uint8_t index = 0; - char* line = NULL; + char* line = nullptr; size_t len = 0; while (ffStrbufGetline(&line, &len, &result)) { if (options->moduleArgs.outputFormat.length == 0) { @@ -94,7 +94,7 @@ void ffGenerateCommandJsonConfig(FFCommandOptions* options, yyjson_mut_doc* doc, yyjson_mut_obj_add_bool(doc, module, "splitLines", options->splitLines); } -bool ffGenerateCommandJsonResult(FF_A_UNUSED FFCommandOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateCommandJsonResult([[maybe_unused]] FFCommandOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FF_STRBUF_AUTO_DESTROY result = ffStrbufCreate(); const char* error = ffDetectCommand(options, &result); @@ -110,7 +110,7 @@ bool ffGenerateCommandJsonResult(FF_A_UNUSED FFCommandOptions* options, yyjson_m if (options->splitLines) { yyjson_mut_val* jsonArray = yyjson_mut_obj_add_arr(doc, module, "result"); - char* line = NULL; + char* line = nullptr; size_t len = 0; while (ffStrbufGetline(&line, &len, &result)) { yyjson_mut_arr_add_strncpy(doc, jsonArray, line, len); @@ -163,5 +163,5 @@ FFModuleBaseInfo ffCommandModuleInfo = { .generateJsonConfig = (void*) ffGenerateCommandJsonConfig, .formatArgs = FF_FORMAT_ARG_LIST(((FFModuleFormatArg[]) { { "Command result", "result" }, - })) + })), }; diff --git a/src/modules/cpu/cpu.c b/src/modules/cpu/cpu.c index 51f84c9f88..2716b2e037 100644 --- a/src/modules/cpu/cpu.c +++ b/src/modules/cpu/cpu.c @@ -276,5 +276,6 @@ FFModuleBaseInfo ffCPUModuleInfo = { { "CPU code name", "code-name" }, { "CPU technology", "technology" }, #endif - })) + })), + .defaultOrder = 33, }; diff --git a/src/modules/cpucache/cpucache.c b/src/modules/cpucache/cpucache.c index 7263a51604..7dd39d1cb6 100644 --- a/src/modules/cpucache/cpucache.c +++ b/src/modules/cpucache/cpucache.c @@ -157,7 +157,7 @@ void ffGenerateCPUCacheJsonConfig(FFCPUCacheOptions* options, yyjson_mut_doc* do yyjson_mut_obj_add_bool(doc, module, "compact", options->compact); } -bool ffGenerateCPUCacheJsonResult(FF_A_UNUSED FFCPUCacheOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateCPUCacheJsonResult([[maybe_unused]] FFCPUCacheOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { bool success = false; FFCPUCacheResult result = { .caches = { @@ -234,5 +234,6 @@ FFModuleBaseInfo ffCPUCacheModuleInfo = { .formatArgs = FF_FORMAT_ARG_LIST(((FFModuleFormatArg[]) { { "Separate result", "result" }, { "Sum result", "sum" }, - })) + })), + .defaultOrder = 34, }; diff --git a/src/modules/cpuusage/cpuusage.c b/src/modules/cpuusage/cpuusage.c index 5c01e914ac..ea592a2739 100644 --- a/src/modules/cpuusage/cpuusage.c +++ b/src/modules/cpuusage/cpuusage.c @@ -198,5 +198,6 @@ FFModuleBaseInfo ffCPUUsageModuleInfo = { { "CPU usage (percentage bar, average)", "avg-bar" }, { "CPU usage (percentage bar, maximum)", "max-bar" }, { "CPU usage (percentage bar, minimum)", "min-bar" }, - })) + })), + .defaultOrder = 35, }; diff --git a/src/modules/cursor/cursor.c b/src/modules/cursor/cursor.c index 0b6f6c7358..1be3ac6e35 100644 --- a/src/modules/cursor/cursor.c +++ b/src/modules/cursor/cursor.c @@ -66,7 +66,7 @@ void ffGenerateCursorJsonConfig(FFCursorOptions* options, yyjson_mut_doc* doc, y ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateCursorJsonResult(FF_A_UNUSED FFCursorOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateCursorJsonResult([[maybe_unused]] FFCursorOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { bool success = false; FFCursorResult result; ffStrbufInit(&result.error); @@ -112,4 +112,5 @@ FFModuleBaseInfo ffCursorModuleInfo = { { "Cursor theme", "theme" }, { "Cursor size", "size" }, })), + .defaultOrder = 27, }; diff --git a/src/modules/datetime/datetime.c b/src/modules/datetime/datetime.c index e902fff42d..14e3b8251f 100644 --- a/src/modules/datetime/datetime.c +++ b/src/modules/datetime/datetime.c @@ -138,7 +138,7 @@ void ffGenerateDateTimeJsonConfig(FFDateTimeOptions* options, yyjson_mut_doc* do ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateDateTimeJsonResult(FF_A_UNUSED FFDateTimeOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateDateTimeJsonResult([[maybe_unused]] FFDateTimeOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { yyjson_mut_obj_add_strcpy(doc, module, "result", ffTimeToFullStr(ffTimeGetNow())); return true; } @@ -185,5 +185,6 @@ FFModuleBaseInfo ffDateTimeModuleInfo = { { "Locale-dependent timezone name or abbreviation", "timezone-name" }, { "Day in month with leading zero", "day-pretty" }, { "AM or PM", "am-pm" }, - })) + })), + .defaultOrder = 52, }; diff --git a/src/modules/de/de.c b/src/modules/de/de.c index d66d205281..8e301fa32e 100644 --- a/src/modules/de/de.c +++ b/src/modules/de/de.c @@ -55,7 +55,7 @@ void ffGenerateDEJsonConfig(FFDEOptions* options, yyjson_mut_doc* doc, yyjson_mu ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateDEJsonResult(FF_A_UNUSED FFDEOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateDEJsonResult([[maybe_unused]] FFDEOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { const FFDisplayServerResult* result = ffConnectDisplayServer(); if (result->dePrettyName.length == 0) { @@ -94,5 +94,6 @@ FFModuleBaseInfo ffDEModuleInfo = { { "DE process name", "process-name" }, { "DE pretty name", "pretty-name" }, { "DE version", "version" }, - })) + })), + .defaultOrder = 21, }; diff --git a/src/modules/disk/disk.c b/src/modules/disk/disk.c index cb06d07233..74b6488558 100644 --- a/src/modules/disk/disk.c +++ b/src/modules/disk/disk.c @@ -21,7 +21,7 @@ static void printDisk(FFDiskOptions* options, const FFDisk* disk, uint32_t index FF_STRBUF_AUTO_DESTROY mountpointLink = ffStrbufCreate(); FF_STRBUF_AUTO_DESTROY nameLink = ffStrbufCreate(); #ifdef __linux__ - if (getenv("WSL_DISTRO_NAME") != NULL && getenv("WT_SESSION") != NULL) { + if (getenv("WSL_DISTRO_NAME") != nullptr && getenv("WT_SESSION") != nullptr) { if (ffStrbufEqualS(&disk->filesystem, "9p") && ffStrbufStartsWithS(&disk->mountpoint, "/mnt/")) { ffStrbufSetF(&mountpointLink, "\e]8;;file:///%c:/\e\\%s\e]8;;\e\\", disk->mountpoint.chars[5], disk->mountpoint.chars); ffStrbufSetF(&nameLink, "\e]8;;file:///%c:/\e\\%s\e]8;;\e\\", disk->mountpoint.chars[5], disk->name.chars); @@ -486,5 +486,6 @@ FFModuleBaseInfo ffDiskModuleInfo = { { "Years fraction after creation", "years-fraction" }, { "Size free", "size-free" }, { "Size available", "size-available" }, - })) + })), + .defaultOrder = 41, }; diff --git a/src/modules/disk/option.h b/src/modules/disk/option.h index b639db21e5..c40ed4abf1 100644 --- a/src/modules/disk/option.h +++ b/src/modules/disk/option.h @@ -3,7 +3,7 @@ #include "common/option.h" #include "common/percent.h" -typedef enum FF_A_PACKED FFDiskVolumeType { +typedef enum FFDiskVolumeType: uint8_t { FF_DISK_VOLUME_TYPE_NONE = 0, FF_DISK_VOLUME_TYPE_REGULAR_BIT = 1 << 0, FF_DISK_VOLUME_TYPE_HIDDEN_BIT = 1 << 1, @@ -11,10 +11,9 @@ typedef enum FF_A_PACKED FFDiskVolumeType { FF_DISK_VOLUME_TYPE_SUBVOLUME_BIT = 1 << 3, FF_DISK_VOLUME_TYPE_UNKNOWN_BIT = 1 << 4, FF_DISK_VOLUME_TYPE_READONLY_BIT = 1 << 5, - FF_DISK_VOLUME_TYPE_FORCE_UNSIGNED = UINT8_MAX, } FFDiskVolumeType; -typedef enum FF_A_PACKED FFDiskCalcType { +typedef enum FFDiskCalcType: uint8_t { FF_DISK_CALC_TYPE_FREE, FF_DISK_CALC_TYPE_AVAILABLE, } FFDiskCalcType; diff --git a/src/modules/diskio/diskio.c b/src/modules/diskio/diskio.c index 3ff31fad4f..372910d10a 100644 --- a/src/modules/diskio/diskio.c +++ b/src/modules/diskio/diskio.c @@ -189,5 +189,6 @@ FFModuleBaseInfo ffDiskIOModuleInfo = { { "Size of data written [per second] (in bytes)", "bytes-written" }, { "Number of reads", "read-count" }, { "Number of writes", "write-count" }, - })) + })), + .defaultOrder = 67, }; diff --git a/src/modules/display/display.c b/src/modules/display/display.c index be3d66f75a..eceb9a2d13 100644 --- a/src/modules/display/display.c +++ b/src/modules/display/display.c @@ -65,7 +65,7 @@ bool ffPrintDisplay(FFDisplayOptions* options) { for (uint32_t i = 0; i < dsResult->displays.length; i++) { FFDisplayResult* result = FF_LIST_GET(FFDisplayResult, dsResult->displays, i); uint32_t moduleIndex = dsResult->displays.length == 1 ? 0 : i + 1; - const char* displayType = result->type == FF_DISPLAY_TYPE_UNKNOWN ? NULL : result->type == FF_DISPLAY_TYPE_BUILTIN ? "Built-in" + const char* displayType = result->type == FF_DISPLAY_TYPE_UNKNOWN ? nullptr : result->type == FF_DISPLAY_TYPE_BUILTIN ? "Built-in" : "External"; ffStrbufClear(&key); @@ -294,7 +294,7 @@ void ffGenerateDisplayJsonConfig(FFDisplayOptions* options, yyjson_mut_doc* doc, } } -bool ffGenerateDisplayJsonResult(FF_A_UNUSED FFDisplayOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateDisplayJsonResult([[maybe_unused]] FFDisplayOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { const FFDisplayServerResult* dsResult = ffConnectDisplayServer(); if (dsResult->displays.length == 0) { @@ -445,5 +445,6 @@ FFModuleBaseInfo ffDisplayModuleInfo = { { "Screen preferred height (in pixels)", "preferred-height" }, { "Screen preferred refresh rate (in Hz)", "preferred-refresh-rate" }, { "DPI", "dpi" }, - })) + })), + .defaultOrder = 17, }; diff --git a/src/modules/display/option.h b/src/modules/display/option.h index 1ae73a406d..9107f595dd 100644 --- a/src/modules/display/option.h +++ b/src/modules/display/option.h @@ -2,15 +2,14 @@ #include "common/option.h" -typedef enum FF_A_PACKED FFDisplayCompactType { +typedef enum FFDisplayCompactType: uint8_t { FF_DISPLAY_COMPACT_TYPE_NONE = 0, FF_DISPLAY_COMPACT_TYPE_ORIGINAL_BIT = 1 << 0, FF_DISPLAY_COMPACT_TYPE_SCALED_BIT = 1 << 1, FF_DISPLAY_COMPACT_TYPE_REFRESH_RATE_BIT = 1 << 2, - FF_DISPLAY_COMPACT_TYPE_UNSIGNED = UINT8_MAX, } FFDisplayCompactType; -typedef enum FF_A_PACKED FFDisplayOrder { +typedef enum FFDisplayOrder: uint8_t { FF_DISPLAY_ORDER_NONE, FF_DISPLAY_ORDER_ASC, FF_DISPLAY_ORDER_DESC, diff --git a/src/modules/dns/dns.c b/src/modules/dns/dns.c index d7c90c4d80..396c3bd431 100644 --- a/src/modules/dns/dns.c +++ b/src/modules/dns/dns.c @@ -73,7 +73,7 @@ void ffParseDNSJsonObject(FFDNSOptions* options, yyjson_val* module) { {}, }); if (error) { - ffPrintError(FF_DNS_MODULE_NAME, 0, NULL, FF_PRINT_TYPE_NO_CUSTOM_KEY, "Invalid %s value: %s", unsafe_yyjson_get_str(key), error); + ffPrintError(FF_DNS_MODULE_NAME, 0, nullptr, FF_PRINT_TYPE_NO_CUSTOM_KEY, "Invalid %s value: %s", unsafe_yyjson_get_str(key), error); } else { options->showType = (FFDNSShowType) value; } @@ -144,5 +144,6 @@ FFModuleBaseInfo ffDNSModuleInfo = { .generateJsonConfig = (void*) ffGenerateDNSJsonConfig, .formatArgs = FF_FORMAT_ARG_LIST(((FFModuleFormatArg[]) { { "DNS result", "result" }, - })) + })), + .defaultOrder = 50, }; diff --git a/src/modules/dns/option.h b/src/modules/dns/option.h index e20bbece7a..0a041d4827 100644 --- a/src/modules/dns/option.h +++ b/src/modules/dns/option.h @@ -2,11 +2,10 @@ #include "common/option.h" -typedef enum FF_A_PACKED FFDNSShowType { +typedef enum FFDNSShowType: uint8_t { FF_DNS_TYPE_IPV4_BIT = 1, FF_DNS_TYPE_IPV6_BIT = 2, FF_DNS_TYPE_BOTH = FF_DNS_TYPE_IPV4_BIT | FF_DNS_TYPE_IPV6_BIT, - FF_DNS_TYPE_FORCE_UNSIGNED = UINT8_MAX, } FFDNSShowType; typedef struct FFDNSOptions { diff --git a/src/modules/editor/editor.c b/src/modules/editor/editor.c index 23b19372a1..342b31812c 100644 --- a/src/modules/editor/editor.c +++ b/src/modules/editor/editor.c @@ -65,7 +65,7 @@ void ffGenerateEditorJsonConfig(FFEditorOptions* options, yyjson_mut_doc* doc, y ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateEditorJsonResult(FF_A_UNUSED FFEditorOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateEditorJsonResult([[maybe_unused]] FFEditorOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FFEditorResult result = { .name = ffStrbufCreate(), .path = ffStrbufCreate(), @@ -117,5 +117,6 @@ FFModuleBaseInfo ffEditorModuleInfo = { { "Exe name of real path", "exe-name" }, { "Full path of real path", "path" }, { "Version", "version" }, - })) + })), + .defaultOrder = 16, }; diff --git a/src/modules/font/font.c b/src/modules/font/font.c index a32a7e80c2..be940b32d1 100644 --- a/src/modules/font/font.c +++ b/src/modules/font/font.c @@ -57,7 +57,7 @@ void ffGenerateFontJsonConfig(FFFontOptions* options, yyjson_mut_doc* doc, yyjso ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateFontJsonResult(FF_A_UNUSED FFFontOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateFontJsonResult([[maybe_unused]] FFFontOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { bool success = false; FFFontResult font; for (uint32_t i = 0; i < FF_DETECT_FONT_NUM_FONTS; ++i) { @@ -109,5 +109,6 @@ FFModuleBaseInfo ffFontModuleInfo = { { "Font 3", "font3" }, { "Font 4", "font4" }, { "Combined fonts for display", "combined" }, - })) + })), + .defaultOrder = 26, }; diff --git a/src/modules/gamepad/gamepad.c b/src/modules/gamepad/gamepad.c index d34dcca85a..f3c3bdfe40 100644 --- a/src/modules/gamepad/gamepad.c +++ b/src/modules/gamepad/gamepad.c @@ -138,7 +138,7 @@ void ffGenerateGamepadJsonConfig(FFGamepadOptions* options, yyjson_mut_doc* doc, ffPercentGenerateJsonConfig(doc, module, options->percent); } -bool ffGenerateGamepadJsonResult(FF_A_UNUSED FFGamepadOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateGamepadJsonResult([[maybe_unused]] FFGamepadOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FF_LIST_AUTO_DESTROY result = ffListCreate(); const char* error = ffDetectGamepad(&result); @@ -202,5 +202,6 @@ FFModuleBaseInfo ffGamepadModuleInfo = { { "Serial number", "serial" }, { "Battery percentage num", "battery-percentage" }, { "Battery percentage bar", "battery-percentage-bar" }, - })) + })), + .defaultOrder = 62, }; diff --git a/src/modules/gpu/gpu.c b/src/modules/gpu/gpu.c index 032474f044..19ba8c868b 100644 --- a/src/modules/gpu/gpu.c +++ b/src/modules/gpu/gpu.c @@ -412,7 +412,7 @@ bool ffGenerateGPUJsonResult(FFGPUOptions* options, yyjson_mut_doc* doc, yyjson_ type = "Discrete"; break; default: - type = NULL; + type = nullptr; break; } if (type) { @@ -511,4 +511,5 @@ FFModuleBaseInfo ffGPUModuleInfo = { { "PCIe maximum speed in gen and lanes", "pcie-max-speed" }, { "PCIe current speed in gen and lanes", "pcie-curr-speed" }, })), + .defaultOrder = 36, }; diff --git a/src/modules/gpu/option.h b/src/modules/gpu/option.h index 4302b3402f..3b569145dd 100644 --- a/src/modules/gpu/option.h +++ b/src/modules/gpu/option.h @@ -3,14 +3,14 @@ #include "common/option.h" #include "common/percent.h" -typedef enum FF_A_PACKED FFGPUType { +typedef enum FFGPUType: uint8_t { FF_GPU_TYPE_NONE, // Indicates no specific GPU type. Useful as a hide filter only. FF_GPU_TYPE_UNKNOWN, // Indicates an unknown or unrecognized GPU type. FF_GPU_TYPE_INTEGRATED, FF_GPU_TYPE_DISCRETE, } FFGPUType; -typedef enum FF_A_PACKED FFGPUDetectionMethod { +typedef enum FFGPUDetectionMethod: uint8_t { FF_GPU_DETECTION_METHOD_AUTO, FF_GPU_DETECTION_METHOD_PCI, FF_GPU_DETECTION_METHOD_VULKAN, diff --git a/src/modules/host/host.c b/src/modules/host/host.c index 2a53cd398b..041ab712e6 100644 --- a/src/modules/host/host.c +++ b/src/modules/host/host.c @@ -83,7 +83,7 @@ void ffGenerateHostJsonConfig(FFHostOptions* options, yyjson_mut_doc* doc, yyjso ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateHostJsonResult(FF_A_UNUSED FFHostOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateHostJsonResult([[maybe_unused]] FFHostOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { bool success = false; FFHostResult host; ffStrbufInit(&host.family); @@ -152,5 +152,6 @@ FFModuleBaseInfo ffHostModuleInfo = { { "Product vendor", "vendor" }, { "Product serial number", "serial" }, { "Product uuid", "uuid" }, - })) + })), + .defaultOrder = 4, }; diff --git a/src/modules/icons/icons.c b/src/modules/icons/icons.c index d3764ad079..15dea09287 100644 --- a/src/modules/icons/icons.c +++ b/src/modules/icons/icons.c @@ -60,7 +60,7 @@ void ffGenerateIconsJsonConfig(FFIconsOptions* options, yyjson_mut_doc* doc, yyj ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateIconsJsonResult(FF_A_UNUSED FFIconsOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateIconsJsonResult([[maybe_unused]] FFIconsOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { bool success = false; FFIconsResult result = { .icons1 = ffStrbufCreate(), @@ -105,5 +105,6 @@ FFModuleBaseInfo ffIconsModuleInfo = { .formatArgs = FF_FORMAT_ARG_LIST(((FFModuleFormatArg[]) { { "Icons part 1", "icons1" }, { "Icons part 2", "icons2" }, - })) + })), + .defaultOrder = 25, }; diff --git a/src/modules/initsystem/initsystem.c b/src/modules/initsystem/initsystem.c index 3c3f3677e9..7a02e0309b 100644 --- a/src/modules/initsystem/initsystem.c +++ b/src/modules/initsystem/initsystem.c @@ -64,7 +64,7 @@ void ffGenerateInitSystemJsonConfig(FFInitSystemOptions* options, yyjson_mut_doc ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateInitSystemJsonResult(FF_A_UNUSED FFInitSystemOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateInitSystemJsonResult([[maybe_unused]] FFInitSystemOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { bool success = false; FFInitSystemResult result = { .name = ffStrbufCreate(), @@ -116,5 +116,6 @@ FFModuleBaseInfo ffInitSystemModuleInfo = { { "Init system exe path", "exe" }, { "Init system version path", "version" }, { "Init system pid", "pid" }, - })) + })), + .defaultOrder = 10, }; diff --git a/src/modules/kernel/kernel.c b/src/modules/kernel/kernel.c index c405cbfa4b..9ae5878df4 100644 --- a/src/modules/kernel/kernel.c +++ b/src/modules/kernel/kernel.c @@ -40,7 +40,7 @@ void ffGenerateKernelJsonConfig(FFKernelOptions* options, yyjson_mut_doc* doc, y ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateKernelJsonResult(FF_A_UNUSED FFKernelOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateKernelJsonResult([[maybe_unused]] FFKernelOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { const FFPlatformSysinfo* info = &instance.state.platform.sysinfo; yyjson_mut_val* obj = yyjson_mut_obj_add_obj(doc, module, "result"); @@ -77,5 +77,6 @@ FFModuleBaseInfo ffKernelModuleInfo = { { "Architecture", "arch" }, { "Display version", "display-version" }, { "Page size", "page-size" }, - })) + })), + .defaultOrder = 9, }; diff --git a/src/modules/keyboard/keyboard.c b/src/modules/keyboard/keyboard.c index 09c3cd5a37..76e6c36f95 100644 --- a/src/modules/keyboard/keyboard.c +++ b/src/modules/keyboard/keyboard.c @@ -99,7 +99,7 @@ void ffGenerateKeyboardJsonConfig(FFKeyboardOptions* options, yyjson_mut_doc* do } } -bool ffGenerateKeyboardJsonResult(FF_A_UNUSED FFKeyboardOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateKeyboardJsonResult([[maybe_unused]] FFKeyboardOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FF_LIST_AUTO_DESTROY result = ffListCreate(); const char* error = ffDetectKeyboard(&result); @@ -160,5 +160,6 @@ FFModuleBaseInfo ffKeyboardModuleInfo = { .formatArgs = FF_FORMAT_ARG_LIST(((FFModuleFormatArg[]) { { "Name", "name" }, { "Serial number", "serial" }, - })) + })), + .defaultOrder = 64, }; diff --git a/src/modules/lm/lm.c b/src/modules/lm/lm.c index a1317d2852..ed945bad46 100644 --- a/src/modules/lm/lm.c +++ b/src/modules/lm/lm.c @@ -65,7 +65,7 @@ void ffGenerateLMJsonConfig(FFLMOptions* options, yyjson_mut_doc* doc, yyjson_mu ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateLMJsonResult(FF_A_UNUSED FFLMOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateLMJsonResult([[maybe_unused]] FFLMOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { bool success = false; FFLMResult result; ffStrbufInit(&result.service); @@ -118,5 +118,6 @@ FFModuleBaseInfo ffLMModuleInfo = { { "LM service", "service" }, { "LM type", "type" }, { "LM version", "version" }, - })) + })), + .defaultOrder = 20, }; diff --git a/src/modules/loadavg/loadavg.c b/src/modules/loadavg/loadavg.c index 32ced1261a..a6fb6f800a 100644 --- a/src/modules/loadavg/loadavg.c +++ b/src/modules/loadavg/loadavg.c @@ -118,7 +118,7 @@ void ffGenerateLoadavgJsonConfig(FFLoadavgOptions* options, yyjson_mut_doc* doc, ffPercentGenerateJsonConfig(doc, module, options->percent); } -bool ffGenerateLoadavgJsonResult(FF_A_UNUSED FFLoadavgOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateLoadavgJsonResult([[maybe_unused]] FFLoadavgOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { double result[3] = { 0.0 / 0.0, 0.0 / 0.0, 0.0 / 0.0 }; const char* error = ffDetectLoadavg(result); @@ -160,5 +160,6 @@ FFModuleBaseInfo ffLoadavgModuleInfo = { { "Load average over 1min", "loadavg1" }, { "Load average over 5min", "loadavg2" }, { "Load average over 15min", "loadavg3" }, - })) + })), + .defaultOrder = 12, }; diff --git a/src/modules/locale/locale.c b/src/modules/locale/locale.c index ef97acf587..cb9c8e7ec5 100644 --- a/src/modules/locale/locale.c +++ b/src/modules/locale/locale.c @@ -38,7 +38,7 @@ void ffGenerateLocaleJsonConfig(FFLocaleOptions* options, yyjson_mut_doc* doc, y ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateLocaleJsonResult(FF_A_UNUSED FFLocaleOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateLocaleJsonResult([[maybe_unused]] FFLocaleOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FF_STRBUF_AUTO_DESTROY locale = ffStrbufCreate(); const char* error = ffDetectLocale(&locale); @@ -77,5 +77,6 @@ FFModuleBaseInfo ffLocaleModuleInfo = { .generateJsonConfig = (void*) ffGenerateLocaleJsonConfig, .formatArgs = FF_FORMAT_ARG_LIST(((FFModuleFormatArg[]) { { "Locale code", "result" }, - })) + })), + .defaultOrder = 53, }; diff --git a/src/modules/localip/localip.c b/src/modules/localip/localip.c index ef4a110cd8..eeb304e283 100644 --- a/src/modules/localip/localip.c +++ b/src/modules/localip/localip.c @@ -308,7 +308,7 @@ void ffGenerateLocalIpJsonConfig(FFLocalIpOptions* options, yyjson_mut_doc* doc, if (options->ipv6Type == FF_LOCALIP_IPV6_TYPE_AUTO) { yyjson_mut_obj_add_bool(doc, module, "showIpv6", !!(options->showType & FF_LOCALIP_TYPE_IPV6_BIT)); } else { - const char* str = NULL; + const char* str = nullptr; switch (options->ipv6Type) { case FF_LOCALIP_IPV6_TYPE_GUA_BIT: str = "gua"; @@ -350,7 +350,7 @@ void ffGenerateLocalIpJsonConfig(FFLocalIpOptions* options, yyjson_mut_doc* doc, yyjson_mut_obj_add_strbuf(doc, module, "namePrefix", &options->namePrefix); } -bool ffGenerateLocalIpJsonResult(FF_A_UNUSED FFLocalIpOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateLocalIpJsonResult([[maybe_unused]] FFLocalIpOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FF_LIST_AUTO_DESTROY results = ffListCreate(); const char* error = ffDetectLocalIps(options, &results); @@ -439,5 +439,6 @@ FFModuleBaseInfo ffLocalIPModuleInfo = { { "MTU size in bytes", "mtu" }, { "Link speed (formatted)", "speed" }, { "Interface flags", "flags" }, - })) + })), + .defaultOrder = 49, }; diff --git a/src/modules/localip/option.h b/src/modules/localip/option.h index 0eae2478bc..ca0a1cc8f7 100644 --- a/src/modules/localip/option.h +++ b/src/modules/localip/option.h @@ -2,7 +2,7 @@ #include "common/option.h" -typedef enum FF_A_PACKED FFLocalIpType { +typedef enum FFLocalIpType: uint16_t { FF_LOCALIP_TYPE_NONE, FF_LOCALIP_TYPE_LOOP_BIT = 1 << 0, FF_LOCALIP_TYPE_IPV4_BIT = 1 << 1, @@ -16,11 +16,10 @@ typedef enum FF_A_PACKED FFLocalIpType { FF_LOCALIP_TYPE_COMPACT_BIT = 1 << 10, FF_LOCALIP_TYPE_DEFAULT_ROUTE_ONLY_BIT = 1 << 11, FF_LOCALIP_TYPE_ALL_IPS_BIT = 1 << 12, - FF_LOCALIP_TYPE_FORCE_UNSIGNED = UINT16_MAX, } FFLocalIpType; static_assert(sizeof(FFLocalIpType) == sizeof(uint16_t), ""); -typedef enum FF_A_PACKED FFLocalIpIpv6Type { +typedef enum FFLocalIpIpv6Type: uint8_t { FF_LOCALIP_IPV6_TYPE_NONE = 0b00000000, FF_LOCALIP_IPV6_TYPE_GUA_BIT = 0b00000001, FF_LOCALIP_IPV6_TYPE_ULA_BIT = 0b00000010, diff --git a/src/modules/logo/logo.c b/src/modules/logo/logo.c index 54a0f97d69..a2fd7d2d1a 100644 --- a/src/modules/logo/logo.c +++ b/src/modules/logo/logo.c @@ -3,12 +3,12 @@ #include "modules/logo/logo.h" #include "options/logo.h" -bool ffPrintLogo(FF_A_UNUSED FFLogoOptions* options) { - ffPrintError(FF_LOGO_MODULE_NAME, 0, NULL, FF_PRINT_TYPE_DEFAULT, "Supported in JSON format only"); +bool ffPrintLogo([[maybe_unused]] FFLogoOptions* options) { + ffPrintError(FF_LOGO_MODULE_NAME, 0, nullptr, FF_PRINT_TYPE_DEFAULT, "Supported in JSON format only"); return false; } -void ffParseLogoJsonObject(FF_A_UNUSED FFLogoOptions* options, FF_A_UNUSED yyjson_val* module) { +void ffParseLogoJsonObject([[maybe_unused]] FFLogoOptions* options, [[maybe_unused]] yyjson_val* module) { yyjson_val *key, *val; size_t idx, max; yyjson_obj_foreach (module, idx, max, key, val) { @@ -16,11 +16,11 @@ void ffParseLogoJsonObject(FF_A_UNUSED FFLogoOptions* options, FF_A_UNUSED yyjso continue; } - ffPrintError(FF_LOGO_MODULE_NAME, 0, NULL, FF_PRINT_TYPE_NO_CUSTOM_KEY, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); + ffPrintError(FF_LOGO_MODULE_NAME, 0, nullptr, FF_PRINT_TYPE_NO_CUSTOM_KEY, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } -bool ffGenerateLogoJsonResult(FF_A_UNUSED FFLogoOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateLogoJsonResult([[maybe_unused]] FFLogoOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FFLogoSize size = FF_LOGO_SIZE_UNKNOWN; FFOptionsLogo* logoOptions = &instance.config.logo; if (logoOptions->type == FF_LOGO_TYPE_SMALL) { @@ -70,10 +70,10 @@ bool ffGenerateLogoJsonResult(FF_A_UNUSED FFLogoOptions* options, yyjson_mut_doc return true; } -void ffInitLogoOptions(FF_A_UNUSED FFLogoOptions* options) { +void ffInitLogoOptions([[maybe_unused]] FFLogoOptions* options) { } -void ffDestroyLogoOptions(FF_A_UNUSED FFLogoOptions* options) { +void ffDestroyLogoOptions([[maybe_unused]] FFLogoOptions* options) { } FFModuleBaseInfo ffLogoModuleInfo = { diff --git a/src/modules/media/media.c b/src/modules/media/media.c index 0876a9ddda..5f926d1156 100644 --- a/src/modules/media/media.c +++ b/src/modules/media/media.c @@ -211,7 +211,7 @@ void ffGenerateMediaJsonConfig(FFMediaOptions* options, yyjson_mut_doc* doc, yyj ffPercentGenerateJsonConfig(doc, module, options->percent); } -bool ffGenerateMediaJsonResult(FF_A_UNUSED FFMediaOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateMediaJsonResult([[maybe_unused]] FFMediaOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { const FFMediaResult* media = ffDetectMedia(false); if (media->error.length > 0) { @@ -273,5 +273,6 @@ FFModuleBaseInfo ffMediaModuleInfo = { { "Player name", "player-name" }, { "Player ID", "player-id" }, { "URL", "url" }, - })) + })), + .defaultOrder = 47, }; diff --git a/src/modules/memory/memory.c b/src/modules/memory/memory.c index 4fbdf75fb2..73a8fc173b 100644 --- a/src/modules/memory/memory.c +++ b/src/modules/memory/memory.c @@ -92,7 +92,7 @@ void ffGenerateMemoryJsonConfig(FFMemoryOptions* options, yyjson_mut_doc* doc, y ffPercentGenerateJsonConfig(doc, module, options->percent); } -bool ffGenerateMemoryJsonResult(FF_A_UNUSED FFMemoryOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateMemoryJsonResult([[maybe_unused]] FFMemoryOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FFMemoryResult storage = {}; const char* error = ffDetectMemory(&storage); @@ -131,5 +131,6 @@ FFModuleBaseInfo ffMemoryModuleInfo = { { "Total size", "total" }, { "Percentage used (num)", "percentage" }, { "Percentage used (bar)", "percentage-bar" }, - })) + })), + .defaultOrder = 38, }; diff --git a/src/modules/modules.c b/src/modules/modules.c index 837871187d..bcc4afdf45 100644 --- a/src/modules/modules.c +++ b/src/modules/modules.c @@ -6,7 +6,7 @@ // We rely `LTO` to remove the unused code (only enabled in Release mode) static FFModuleBaseInfo* A[] = { - NULL, + nullptr, }; static FFModuleBaseInfo* B[] = { @@ -37,7 +37,7 @@ static FFModuleBaseInfo* B[] = { #if !FF_MODULE_DISABLE_BTRFS &ffBtrfsModuleInfo, #endif - NULL, + nullptr, }; static FFModuleBaseInfo* C[] = { @@ -71,7 +71,7 @@ static FFModuleBaseInfo* C[] = { #if !FF_MODULE_DISABLE_CUSTOM &ffCustomModuleInfo, #endif - NULL, + nullptr, }; static FFModuleBaseInfo* D[] = { @@ -93,21 +93,21 @@ static FFModuleBaseInfo* D[] = { #if !FF_MODULE_DISABLE_DNS &ffDNSModuleInfo, #endif - NULL, + nullptr, }; static FFModuleBaseInfo* E[] = { #if !FF_MODULE_DISABLE_EDITOR &ffEditorModuleInfo, #endif - NULL, + nullptr, }; static FFModuleBaseInfo* F[] = { #if !FF_MODULE_DISABLE_FONT &ffFontModuleInfo, #endif - NULL, + nullptr, }; static FFModuleBaseInfo* G[] = { @@ -117,14 +117,14 @@ static FFModuleBaseInfo* G[] = { #if !FF_MODULE_DISABLE_GPU &ffGPUModuleInfo, #endif - NULL, + nullptr, }; static FFModuleBaseInfo* H[] = { #if !FF_MODULE_DISABLE_HOST &ffHostModuleInfo, #endif - NULL, + nullptr, }; static FFModuleBaseInfo* I[] = { @@ -134,11 +134,11 @@ static FFModuleBaseInfo* I[] = { #if !FF_MODULE_DISABLE_INITSYSTEM &ffInitSystemModuleInfo, #endif - NULL, + nullptr, }; static FFModuleBaseInfo* J[] = { - NULL, + nullptr, }; static FFModuleBaseInfo* K[] = { @@ -148,7 +148,7 @@ static FFModuleBaseInfo* K[] = { #if !FF_MODULE_DISABLE_KEYBOARD &ffKeyboardModuleInfo, #endif - NULL, + nullptr, }; static FFModuleBaseInfo* L[] = { @@ -167,7 +167,7 @@ static FFModuleBaseInfo* L[] = { #if !FF_MODULE_DISABLE_LOGO &ffLogoModuleInfo, #endif - NULL, + nullptr, }; static FFModuleBaseInfo* M[] = { @@ -183,14 +183,14 @@ static FFModuleBaseInfo* M[] = { #if !FF_MODULE_DISABLE_MOUSE &ffMouseModuleInfo, #endif - NULL, + nullptr, }; static FFModuleBaseInfo* N[] = { #if !FF_MODULE_DISABLE_NETIO &ffNetIOModuleInfo, #endif - NULL, + nullptr, }; static FFModuleBaseInfo* O[] = { @@ -203,7 +203,7 @@ static FFModuleBaseInfo* O[] = { #if !FF_MODULE_DISABLE_OS &ffOSModuleInfo, #endif - NULL, + nullptr, }; static FFModuleBaseInfo* P[] = { @@ -228,15 +228,15 @@ static FFModuleBaseInfo* P[] = { #if !FF_MODULE_DISABLE_PUBLICIP &ffPublicIPModuleInfo, #endif - NULL, + nullptr, }; static FFModuleBaseInfo* Q[] = { - NULL, + nullptr, }; static FFModuleBaseInfo* R[] = { - NULL, + nullptr, }; static FFModuleBaseInfo* S[] = { @@ -252,7 +252,7 @@ static FFModuleBaseInfo* S[] = { #if !FF_MODULE_DISABLE_SWAP &ffSwapModuleInfo, #endif - NULL, + nullptr, }; static FFModuleBaseInfo* T[] = { @@ -277,7 +277,7 @@ static FFModuleBaseInfo* T[] = { #if !FF_MODULE_DISABLE_TPM &ffTPMModuleInfo, #endif - NULL, + nullptr, }; static FFModuleBaseInfo* U[] = { @@ -287,7 +287,7 @@ static FFModuleBaseInfo* U[] = { #if !FF_MODULE_DISABLE_USERS &ffUsersModuleInfo, #endif - NULL, + nullptr, }; static FFModuleBaseInfo* V[] = { @@ -297,7 +297,7 @@ static FFModuleBaseInfo* V[] = { #if !FF_MODULE_DISABLE_VULKAN &ffVulkanModuleInfo, #endif - NULL, + nullptr, }; static FFModuleBaseInfo* W[] = { @@ -316,22 +316,22 @@ static FFModuleBaseInfo* W[] = { #if !FF_MODULE_DISABLE_WMTHEME &ffWMThemeModuleInfo, #endif - NULL, + nullptr, }; static FFModuleBaseInfo* X[] = { - NULL, + nullptr, }; static FFModuleBaseInfo* Y[] = { - NULL, + nullptr, }; static FFModuleBaseInfo* Z[] = { #if !FF_MODULE_DISABLE_ZPOOL &ffZpoolModuleInfo, #endif - NULL, + nullptr, }; FFModuleBaseInfo** ffModuleInfos[] = { diff --git a/src/modules/monitor/monitor.c b/src/modules/monitor/monitor.c index 636cd447b1..6c8bed1708 100644 --- a/src/modules/monitor/monitor.c +++ b/src/modules/monitor/monitor.c @@ -90,7 +90,7 @@ void ffGenerateMonitorJsonConfig(FFMonitorOptions* options, yyjson_mut_doc* doc, ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateMonitorJsonResult(FF_A_UNUSED FFMonitorOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateMonitorJsonResult([[maybe_unused]] FFMonitorOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { yyjson_mut_obj_add_str(doc, module, "error", "Monitor module is an alias of Display module"); return false; } @@ -125,5 +125,6 @@ FFModuleBaseInfo ffMonitorModuleInfo = { { "Serial number", "serial" }, { "Maximum refresh rate in Hz", "refresh-rate" }, { "True if the display is HDR compatible", "hdr-compatible" }, - })) + })), + .defaultOrder = 19, }; diff --git a/src/modules/mouse/mouse.c b/src/modules/mouse/mouse.c index abc4678323..82dd6b053e 100644 --- a/src/modules/mouse/mouse.c +++ b/src/modules/mouse/mouse.c @@ -102,7 +102,7 @@ void ffGenerateMouseJsonConfig(FFMouseOptions* options, yyjson_mut_doc* doc, yyj } } -bool ffGenerateMouseJsonResult(FF_A_UNUSED FFMouseOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateMouseJsonResult([[maybe_unused]] FFMouseOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FF_LIST_AUTO_DESTROY result = ffListCreate(); const char* error = ffDetectMouse(&result); @@ -163,5 +163,6 @@ FFModuleBaseInfo ffMouseModuleInfo = { .formatArgs = FF_FORMAT_ARG_LIST(((FFModuleFormatArg[]) { { "Mouse name", "name" }, { "Mouse serial number", "serial" }, - })) + })), + .defaultOrder = 63, }; diff --git a/src/modules/netio/netio.c b/src/modules/netio/netio.c index 17047fffd9..8607a21af6 100644 --- a/src/modules/netio/netio.c +++ b/src/modules/netio/netio.c @@ -220,5 +220,6 @@ FFModuleBaseInfo ffNetIOModuleInfo = { { "Number of errors sent [per second]", "tx-errors" }, { "Number of packets dropped when receiving [per second]", "rx-drops" }, { "Number of packets dropped when sending [per second]", "tx-drops" }, - })) + })), + .defaultOrder = 66, }; diff --git a/src/modules/opencl/opencl.c b/src/modules/opencl/opencl.c index d69b3fe795..0a80d9d16b 100644 --- a/src/modules/opencl/opencl.c +++ b/src/modules/opencl/opencl.c @@ -8,7 +8,7 @@ bool ffPrintOpenCL(FFOpenCLOptions* options) { FFOpenCLResult* result = ffDetectOpenCL(); - if (result->error != NULL) { + if (result->error != nullptr) { ffPrintError(FF_OPENCL_MODULE_NAME, 0, &options->moduleArgs, FF_PRINT_TYPE_DEFAULT, "%s", result->error); return false; } @@ -43,10 +43,10 @@ void ffGenerateOpenCLJsonConfig(FFOpenCLOptions* options, yyjson_mut_doc* doc, y ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateOpenCLJsonResult(FF_A_UNUSED FFOpenCLOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateOpenCLJsonResult([[maybe_unused]] FFOpenCLOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FFOpenCLResult* result = ffDetectOpenCL(); - if (result->error != NULL) { + if (result->error != nullptr) { yyjson_mut_obj_add_str(doc, module, "error", result->error); return false; } @@ -132,5 +132,6 @@ FFModuleBaseInfo ffOpenCLModuleInfo = { { "Platform version", "version" }, { "Platform name", "name" }, { "Platform vendor", "vendor" }, - })) + })), + .defaultOrder = 56, }; diff --git a/src/modules/opengl/opengl.c b/src/modules/opengl/opengl.c index 0754cb20cb..29adcf0f0d 100644 --- a/src/modules/opengl/opengl.c +++ b/src/modules/opengl/opengl.c @@ -85,7 +85,7 @@ void ffGenerateOpenGLJsonConfig(FFOpenGLOptions* options, yyjson_mut_doc* doc, y } } -bool ffGenerateOpenGLJsonResult(FF_A_UNUSED FFOpenGLOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateOpenGLJsonResult([[maybe_unused]] FFOpenGLOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { bool success = false; FFOpenGLResult result; ffStrbufInit(&result.version); @@ -95,7 +95,7 @@ bool ffGenerateOpenGLJsonResult(FF_A_UNUSED FFOpenGLOptions* options, yyjson_mut ffStrbufInit(&result.library); const char* error = ffDetectOpenGL(options, &result); - if (error != NULL) { + if (error != nullptr) { yyjson_mut_obj_add_str(doc, module, "error", error); } else { yyjson_mut_val* obj = yyjson_mut_obj_add_obj(doc, module, "result"); @@ -141,5 +141,6 @@ FFModuleBaseInfo ffOpenGLModuleInfo = { { "OpenGL vendor", "vendor" }, { "OpenGL shading language version", "slv" }, { "OpenGL library used", "library" }, - })) + })), + .defaultOrder = 55, }; diff --git a/src/modules/opengl/option.h b/src/modules/opengl/option.h index 869c6eca8c..7b296ccde6 100644 --- a/src/modules/opengl/option.h +++ b/src/modules/opengl/option.h @@ -2,7 +2,7 @@ #include "common/option.h" -typedef enum FF_A_PACKED FFOpenGLLibrary { +typedef enum FFOpenGLLibrary: uint8_t { FF_OPENGL_LIBRARY_AUTO, FF_OPENGL_LIBRARY_EGL, FF_OPENGL_LIBRARY_GLX, diff --git a/src/modules/os/os.c b/src/modules/os/os.c index e402699b0d..d0dc5600b7 100644 --- a/src/modules/os/os.c +++ b/src/modules/os/os.c @@ -120,7 +120,7 @@ void ffGenerateOSJsonConfig(FFOSOptions* options, yyjson_mut_doc* doc, yyjson_mu ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateOSJsonResult(FF_A_UNUSED FFOSOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateOSJsonResult([[maybe_unused]] FFOSOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { const FFOSResult* os = ffDetectOS(); if (os->name.length == 0 && os->prettyName.length == 0 && os->id.length == 0) { @@ -193,5 +193,6 @@ FFModuleBaseInfo ffOSModuleInfo = { { "Version codename of the OS", "codename" }, { "Build ID of the OS", "build-id" }, { "Architecture of the OS", "arch" }, - })) + })), + .defaultOrder = 3, }; diff --git a/src/modules/packages/option.h b/src/modules/packages/option.h index c215593c21..a9bb444a86 100644 --- a/src/modules/packages/option.h +++ b/src/modules/packages/option.h @@ -2,7 +2,7 @@ #include "common/option.h" -typedef enum FF_A_PACKED FFPackagesFlags { +typedef enum FFPackagesFlags: uint64_t { FF_PACKAGES_FLAG_NONE = 0, FF_PACKAGES_FLAG_APK_BIT = UINT64_C(1) << 0U, FF_PACKAGES_FLAG_BREW_BIT = UINT64_C(1) << 1U, @@ -41,7 +41,6 @@ typedef enum FF_A_PACKED FFPackagesFlags { FF_PACKAGES_FLAG_CARDS_BIT = UINT64_C(1) << 34U, FF_PACKAGES_FLAG_PORG_BIT = UINT64_C(1) << 35U, FF_PACKAGES_FLAG_INSTALLRELEASE_BIT = UINT64_C(1) << 36U, - FF_PACKAGES_FLAG_FORCE_UNSIGNED = UINT64_MAX, } FFPackagesFlags; static_assert(sizeof(FFPackagesFlags) == sizeof(uint64_t), ""); diff --git a/src/modules/packages/packages.c b/src/modules/packages/packages.c index 8cb4027bde..1553893f1a 100644 --- a/src/modules/packages/packages.c +++ b/src/modules/packages/packages.c @@ -573,5 +573,6 @@ FFModuleBaseInfo ffPackagesModuleInfo = { { "Total number of all hpkg packages", "hpkg-all" }, { "Total number of all nix packages", "nix-all" }, { "Number of all packages", "all" }, - })) + })), + .defaultOrder = 14, }; diff --git a/src/modules/physicaldisk/option.h b/src/modules/physicaldisk/option.h index 00ba0138a6..0b3c81855e 100644 --- a/src/modules/physicaldisk/option.h +++ b/src/modules/physicaldisk/option.h @@ -2,7 +2,7 @@ #include "common/option.h" -typedef enum FF_A_PACKED FFPhysicalDiskType { +typedef enum FFPhysicalDiskType: uint8_t { FF_PHYSICALDISK_TYPE_NONE = 0, // If none is set, it's unknown @@ -17,8 +17,6 @@ typedef enum FF_A_PACKED FFPhysicalDiskType { FF_PHYSICALDISK_TYPE_READONLY = 1 << 6, FF_PHYSICALDISK_TYPE_UNUSED = 1 << 7, - - FF_PHYSICALDISK_TYPE_FORCE_UNSIGNED = UINT8_MAX, } FFPhysicalDiskType; static_assert(sizeof(FFPhysicalDiskType) == sizeof(uint8_t), ""); diff --git a/src/modules/physicaldisk/physicaldisk.c b/src/modules/physicaldisk/physicaldisk.c index b0b7c58607..8935438840 100644 --- a/src/modules/physicaldisk/physicaldisk.c +++ b/src/modules/physicaldisk/physicaldisk.c @@ -284,5 +284,6 @@ FFModuleBaseInfo ffPhysicalDiskModuleInfo = { { "Device kind (Read-only or Read-write)", "readonly-type" }, { "Product revision", "revision" }, { "Device temperature (formatted)", "temperature" }, - })) + })), + .defaultOrder = 68, }; diff --git a/src/modules/physicalmemory/physicalmemory.c b/src/modules/physicalmemory/physicalmemory.c index d4bee7db53..f044e59071 100644 --- a/src/modules/physicalmemory/physicalmemory.c +++ b/src/modules/physicalmemory/physicalmemory.c @@ -180,5 +180,6 @@ FFModuleBaseInfo ffPhysicalMemoryModuleInfo = { { "Part number", "part-number" }, { "True if ECC enabled", "is-ecc-enabled" }, { "True if a memory module is installed in the slot", "is-installed" }, - })) + })), + .defaultOrder = 39, }; diff --git a/src/modules/player/player.c b/src/modules/player/player.c index 58d1b3b00a..0d1fd03b8f 100644 --- a/src/modules/player/player.c +++ b/src/modules/player/player.c @@ -95,7 +95,7 @@ void ffGeneratePlayerJsonConfig(FFPlayerOptions* options, yyjson_mut_doc* doc, y ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGeneratePlayerJsonResult(FF_A_UNUSED FFMediaOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGeneratePlayerJsonResult([[maybe_unused]] FFMediaOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { yyjson_mut_obj_add_str(doc, module, "error", "Player module is an alias of Media module"); return false; } @@ -122,5 +122,6 @@ FFModuleBaseInfo ffPlayerModuleInfo = { { "Player name", "name" }, { "Player Identifier", "id" }, { "URL name", "url" }, - })) + })), + .defaultOrder = 46, }; diff --git a/src/modules/poweradapter/poweradapter.c b/src/modules/poweradapter/poweradapter.c index 2e70c000d9..be20d2a6d7 100644 --- a/src/modules/poweradapter/poweradapter.c +++ b/src/modules/poweradapter/poweradapter.c @@ -69,7 +69,7 @@ void ffParsePowerAdapterJsonObject(FFPowerAdapterOptions* options, yyjson_val* m } } -bool ffGeneratePowerAdapterJsonResult(FF_A_UNUSED FFPowerAdapterOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGeneratePowerAdapterJsonResult([[maybe_unused]] FFPowerAdapterOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FF_LIST_AUTO_DESTROY results = ffListCreate(); const char* error = ffDetectPowerAdapter(&results); @@ -125,5 +125,6 @@ FFModuleBaseInfo ffPowerAdapterModuleInfo = { { "Power adapter model", "model" }, { "Power adapter description", "description" }, { "Power adapter serial number", "serial" }, - })) + })), + .defaultOrder = 45, }; diff --git a/src/modules/processes/processes.c b/src/modules/processes/processes.c index 44ab59d4d5..daf7a23ed8 100644 --- a/src/modules/processes/processes.c +++ b/src/modules/processes/processes.c @@ -40,7 +40,7 @@ void ffGenerateProcessesJsonConfig(FFProcessesOptions* options, yyjson_mut_doc* ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateProcessesJsonResult(FF_A_UNUSED FFProcessesOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateProcessesJsonResult([[maybe_unused]] FFProcessesOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { uint32_t result; const char* error = ffDetectProcesses(&result); @@ -72,5 +72,7 @@ FFModuleBaseInfo ffProcessesModuleInfo = { .generateJsonResult = (void*) ffGenerateProcessesJsonResult, .generateJsonConfig = (void*) ffGenerateProcessesJsonConfig, .formatArgs = FF_FORMAT_ARG_LIST(((FFModuleFormatArg[]) { - { "Process count", "result" } })) + { "Process count", "result" }, + })), + .defaultOrder = 13, }; diff --git a/src/modules/publicip/publicip.c b/src/modules/publicip/publicip.c index 552173395e..5d52e74a70 100644 --- a/src/modules/publicip/publicip.c +++ b/src/modules/publicip/publicip.c @@ -121,5 +121,6 @@ FFModuleBaseInfo ffPublicIPModuleInfo = { .formatArgs = FF_FORMAT_ARG_LIST(((FFModuleFormatArg[]) { { "Public IP address", "ip" }, { "Location", "location" }, - })) + })), + .defaultOrder = 48, }; diff --git a/src/modules/separator/separator.c b/src/modules/separator/separator.c index 4c5b4bc92c..bd84d7a40d 100644 --- a/src/modules/separator/separator.c +++ b/src/modules/separator/separator.c @@ -95,11 +95,11 @@ void ffParseSeparatorJsonObject(FFSeparatorOptions* options, yyjson_val* module) } if (unsafe_yyjson_equals_str(key, "length")) { - ffPrintError(FF_SEPARATOR_MODULE_NAME, 0, NULL, FF_PRINT_TYPE_NO_CUSTOM_KEY, "The option length has been renamed to times."); + ffPrintError(FF_SEPARATOR_MODULE_NAME, 0, nullptr, FF_PRINT_TYPE_NO_CUSTOM_KEY, "The option length has been renamed to times."); continue; } - ffPrintError(FF_SEPARATOR_MODULE_NAME, 0, NULL, FF_PRINT_TYPE_NO_CUSTOM_KEY, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); + ffPrintError(FF_SEPARATOR_MODULE_NAME, 0, nullptr, FF_PRINT_TYPE_NO_CUSTOM_KEY, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } @@ -117,6 +117,7 @@ void ffInitSeparatorOptions(FFSeparatorOptions* options) { void ffDestroySeparatorOptions(FFSeparatorOptions* options) { ffStrbufDestroy(&options->string); + ffStrbufDestroy(&options->outputColor); } FFModuleBaseInfo ffSeparatorModuleInfo = { @@ -127,4 +128,5 @@ FFModuleBaseInfo ffSeparatorModuleInfo = { .parseJsonObject = (void*) ffParseSeparatorJsonObject, .printModule = (void*) ffPrintSeparator, .generateJsonConfig = (void*) ffGenerateSeparatorJsonConfig, + .defaultOrder = 2, }; diff --git a/src/modules/shell/shell.c b/src/modules/shell/shell.c index f18c1bfd8b..84db1baca0 100644 --- a/src/modules/shell/shell.c +++ b/src/modules/shell/shell.c @@ -54,7 +54,7 @@ void ffGenerateShellJsonConfig(FFShellOptions* options, yyjson_mut_doc* doc, yyj ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateShellJsonResult(FF_A_UNUSED FFShellOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateShellJsonResult([[maybe_unused]] FFShellOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { const FFShellResult* result = ffDetectShell(); if (result->processName.length == 0) { @@ -106,5 +106,6 @@ FFModuleBaseInfo ffShellModuleInfo = { { "Shell pretty name", "pretty-name" }, { "Shell full exe path", "exe-path" }, { "Shell tty used", "tty" }, - })) + })), + .defaultOrder = 15, }; diff --git a/src/modules/sound/option.h b/src/modules/sound/option.h index 9892569134..56e91a213a 100644 --- a/src/modules/sound/option.h +++ b/src/modules/sound/option.h @@ -3,7 +3,7 @@ #include "common/option.h" #include "common/percent.h" -typedef enum FF_A_PACKED FFSoundType { +typedef enum FFSoundType: uint8_t { FF_SOUND_TYPE_NONE = 0, FF_SOUND_TYPE_MAIN = 1 << 0, FF_SOUND_TYPE_ACTIVE = 1 << 1, diff --git a/src/modules/sound/sound.c b/src/modules/sound/sound.c index bf37c1f1bc..6bc73cbe7b 100644 --- a/src/modules/sound/sound.c +++ b/src/modules/sound/sound.c @@ -215,5 +215,6 @@ FFModuleBaseInfo ffSoundModuleInfo = { { "Identifier", "identifier" }, { "Volume (in percentage bar)", "volume-percentage-bar" }, { "Platform API used", "platform-api" }, - })) + })), + .defaultOrder = 60, }; diff --git a/src/modules/swap/swap.c b/src/modules/swap/swap.c index 78af475583..cf9d107c60 100644 --- a/src/modules/swap/swap.c +++ b/src/modules/swap/swap.c @@ -147,7 +147,7 @@ void ffGenerateSwapJsonConfig(FFSwapOptions* options, yyjson_mut_doc* doc, yyjso yyjson_mut_obj_add_bool(doc, module, "separate", options->separate); } -bool ffGenerateSwapJsonResult(FF_A_UNUSED FFSwapOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateSwapJsonResult([[maybe_unused]] FFSwapOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FF_LIST_AUTO_DESTROY result = ffListCreate(); const char* error = ffDetectSwap(&result); @@ -196,5 +196,6 @@ FFModuleBaseInfo ffSwapModuleInfo = { { "Percentage used (num)", "percentage" }, { "Percentage used (bar)", "percentage-bar" }, { "Name", "name" }, - })) + })), + .defaultOrder = 40, }; diff --git a/src/modules/terminal/terminal.c b/src/modules/terminal/terminal.c index 8dc6f4c4b2..5b2e9305fe 100644 --- a/src/modules/terminal/terminal.c +++ b/src/modules/terminal/terminal.c @@ -52,7 +52,7 @@ void ffGenerateTerminalJsonConfig(FFTerminalOptions* options, yyjson_mut_doc* do ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateTerminalJsonResult(FF_A_UNUSED FFTerminalOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateTerminalJsonResult([[maybe_unused]] FFTerminalOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { const FFTerminalResult* result = ffDetectTerminal(); if (result->processName.length == 0) { @@ -100,5 +100,6 @@ FFModuleBaseInfo ffTerminalModuleInfo = { { "Terminal version", "version" }, { "Terminal full exe path", "exe-path" }, { "Terminal tty / pts used", "tty" }, - })) + })), + .defaultOrder = 29, }; diff --git a/src/modules/terminalfont/terminalfont.c b/src/modules/terminalfont/terminalfont.c index 91e45c747b..87a0837185 100644 --- a/src/modules/terminalfont/terminalfont.c +++ b/src/modules/terminalfont/terminalfont.c @@ -58,7 +58,7 @@ void ffGenerateTerminalFontJsonConfig(FFTerminalFontOptions* options, yyjson_mut ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateTerminalFontJsonResult(FF_A_UNUSED FFTerminalFontOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateTerminalFontJsonResult([[maybe_unused]] FFTerminalFontOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { bool success = false; FFTerminalFontResult result; ffFontInit(&result.font); @@ -119,4 +119,5 @@ FFModuleBaseInfo ffTerminalFontModuleInfo = { { "Terminal font size", "size" }, { "Terminal font styles", "styles" }, })), + .defaultOrder = 30, }; diff --git a/src/modules/terminalsize/terminalsize.c b/src/modules/terminalsize/terminalsize.c index 4a7c555ad6..088b97fcef 100644 --- a/src/modules/terminalsize/terminalsize.c +++ b/src/modules/terminalsize/terminalsize.c @@ -50,7 +50,7 @@ void ffGenerateTerminalSizeJsonConfig(FFTerminalSizeOptions* options, yyjson_mut ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateTerminalSizeJsonResult(FF_A_UNUSED FFTerminalSizeOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateTerminalSizeJsonResult([[maybe_unused]] FFTerminalSizeOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FFTerminalSizeResult result; if (!ffDetectTerminalSize(&result)) { @@ -90,4 +90,5 @@ FFModuleBaseInfo ffTerminalSizeModuleInfo = { { "Terminal width (in pixels)", "width" }, { "Terminal height (in pixels)", "height" }, })), + .defaultOrder = 31, }; diff --git a/src/modules/terminaltheme/terminaltheme.c b/src/modules/terminaltheme/terminaltheme.c index 80bcd2950d..3d5239b2f6 100644 --- a/src/modules/terminaltheme/terminaltheme.c +++ b/src/modules/terminaltheme/terminaltheme.c @@ -59,7 +59,7 @@ void ffGenerateTerminalThemeJsonConfig(FFTerminalThemeOptions* options, yyjson_m ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateTerminalThemeJsonResult(FF_A_UNUSED FFTerminalThemeOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateTerminalThemeJsonResult([[maybe_unused]] FFTerminalThemeOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FFTerminalThemeResult result = {}; if (!ffDetectTerminalTheme(&result, false)) { @@ -106,5 +106,6 @@ FFModuleBaseInfo ffTerminalThemeModuleInfo = { { "Terminal foreground type (Dark / Light)", "fg-type" }, { "Terminal background color", "bg-color" }, { "Terminal background type (Dark / Light)", "bg-type" }, - })) + })), + .defaultOrder = 32, }; diff --git a/src/modules/theme/theme.c b/src/modules/theme/theme.c index 70cb778ab8..f51a4aac64 100644 --- a/src/modules/theme/theme.c +++ b/src/modules/theme/theme.c @@ -56,7 +56,7 @@ void ffGenerateThemeJsonConfig(FFThemeOptions* options, yyjson_mut_doc* doc, yyj ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateThemeJsonResult(FF_A_UNUSED FFThemeOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateThemeJsonResult([[maybe_unused]] FFThemeOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FFThemeResult result = { .theme1 = ffStrbufCreate(), .theme2 = ffStrbufCreate() @@ -98,5 +98,6 @@ FFModuleBaseInfo ffThemeModuleInfo = { .formatArgs = FF_FORMAT_ARG_LIST(((FFModuleFormatArg[]) { { "Theme part 1", "theme1" }, { "Theme part 2", "theme2" }, - })) + })), + .defaultOrder = 24, }; diff --git a/src/modules/title/title.c b/src/modules/title/title.c index 97e58430b1..ce877caed7 100644 --- a/src/modules/title/title.c +++ b/src/modules/title/title.c @@ -124,7 +124,7 @@ void ffParseTitleJsonObject(FFTitleOptions* options, yyjson_val* module) { continue; } - ffPrintError(FF_TITLE_MODULE_NAME, 0, NULL, FF_PRINT_TYPE_NO_CUSTOM_KEY, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); + ffPrintError(FF_TITLE_MODULE_NAME, 0, nullptr, FF_PRINT_TYPE_NO_CUSTOM_KEY, "Unknown JSON key %s", unsafe_yyjson_get_str(key)); } } @@ -139,7 +139,7 @@ void ffGenerateTitleJsonConfig(FFTitleOptions* options, yyjson_mut_doc* doc, yyj yyjson_mut_obj_add_strbuf(doc, color, "host", &options->colorHost); } -bool ffGenerateTitleJsonResult(FF_A_UNUSED FFTitleOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateTitleJsonResult([[maybe_unused]] FFTitleOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { yyjson_mut_val* obj = yyjson_mut_obj_add_obj(doc, module, "result"); #ifdef _WIN32 yyjson_mut_obj_add_strbuf(doc, obj, "userId", &instance.state.platform.sid); @@ -197,5 +197,6 @@ FFModuleBaseInfo ffTitleModuleInfo = { { "UID (*nix) / SID (Windows)", "user-id" }, { "PID of current process", "pid" }, { "CWD with home dir replaced by `~`", "cwd" }, - })) + })), + .defaultOrder = 1, }; diff --git a/src/modules/tpm/tpm.c b/src/modules/tpm/tpm.c index ecdd386094..6596d6261c 100644 --- a/src/modules/tpm/tpm.c +++ b/src/modules/tpm/tpm.c @@ -52,7 +52,7 @@ void ffGenerateTPMJsonConfig(FFTPMOptions* options, yyjson_mut_doc* doc, yyjson_ ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateTPMJsonResult(FF_A_UNUSED FFTPMOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateTPMJsonResult([[maybe_unused]] FFTPMOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FFTPMResult result = { .version = ffStrbufCreate(), .description = ffStrbufCreate() @@ -94,5 +94,6 @@ FFModuleBaseInfo ffTPMModuleInfo = { .formatArgs = FF_FORMAT_ARG_LIST(((FFModuleFormatArg[]) { { "TPM device version", "version" }, { "TPM general description", "description" }, - })) + })), + .defaultOrder = 69, }; diff --git a/src/modules/uptime/uptime.c b/src/modules/uptime/uptime.c index e096bfc2f2..41ac4526a1 100644 --- a/src/modules/uptime/uptime.c +++ b/src/modules/uptime/uptime.c @@ -58,7 +58,7 @@ void ffGenerateUptimeJsonConfig(FFUptimeOptions* options, yyjson_mut_doc* doc, y ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateUptimeJsonResult(FF_A_UNUSED FFUptimeOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateUptimeJsonResult([[maybe_unused]] FFUptimeOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FFUptimeResult result; const char* error = ffDetectUptime(&result); @@ -102,5 +102,6 @@ FFModuleBaseInfo ffUptimeModuleInfo = { { "Days of year after boot", "days-of-year" }, { "Years fraction after boot", "years-fraction" }, { "Formatted uptime", "formatted" }, - })) + })), + .defaultOrder = 11, }; diff --git a/src/modules/users/users.c b/src/modules/users/users.c index 5575bbeaab..fbf1ffaa8e 100644 --- a/src/modules/users/users.c +++ b/src/modules/users/users.c @@ -202,5 +202,6 @@ FFModuleBaseInfo ffUsersModuleInfo = { { "Years integer after login", "years" }, { "Days of year after login", "days-of-year" }, { "Years fraction after login", "years-fraction" }, - })) + })), + .defaultOrder = 57, }; diff --git a/src/modules/version/version.c b/src/modules/version/version.c index dcc4bbef12..fa3b59fe7f 100644 --- a/src/modules/version/version.c +++ b/src/modules/version/version.c @@ -56,7 +56,7 @@ void ffGenerateVersionJsonConfig(FFVersionOptions* options, yyjson_mut_doc* doc, ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateVersionJsonResult(FF_A_UNUSED FFVersionOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateVersionJsonResult([[maybe_unused]] FFVersionOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FFVersionResult* result = &ffVersionResult; yyjson_mut_val* obj = yyjson_mut_obj_add_obj(doc, module, "result"); @@ -113,5 +113,6 @@ FFModuleBaseInfo ffVersionModuleInfo = { { "Date time when compiling", "compile-time" }, { "Compiler used when compiling", "compiler" }, { "Libc used when compiling", "libc" }, - })) + })), + .defaultOrder = 70, }; diff --git a/src/modules/vulkan/vulkan.c b/src/modules/vulkan/vulkan.c index 9ecbd32cf4..03123b7ae6 100644 --- a/src/modules/vulkan/vulkan.c +++ b/src/modules/vulkan/vulkan.c @@ -62,7 +62,7 @@ void ffGenerateVulkanJsonConfig(FFVulkanOptions* options, yyjson_mut_doc* doc, y ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateVulkanJsonResult(FF_A_UNUSED FFVulkanOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateVulkanJsonResult([[maybe_unused]] FFVulkanOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { const FFVulkanResult* result = ffDetectVulkan(); if (result->error) { @@ -145,5 +145,6 @@ FFModuleBaseInfo ffVulkanModuleInfo = { { "API version", "api-version" }, { "Conformance version", "conformance-version" }, { "Instance version", "instance-version" }, - })) + })), + .defaultOrder = 54, }; diff --git a/src/modules/wallpaper/wallpaper.c b/src/modules/wallpaper/wallpaper.c index a4d17c01a9..b5fab48f50 100644 --- a/src/modules/wallpaper/wallpaper.c +++ b/src/modules/wallpaper/wallpaper.c @@ -54,7 +54,7 @@ void ffGenerateWallpaperJsonConfig(FFWallpaperOptions* options, yyjson_mut_doc* ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateWallpaperJsonResult(FF_A_UNUSED FFWallpaperOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateWallpaperJsonResult([[maybe_unused]] FFWallpaperOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FF_STRBUF_AUTO_DESTROY fullpath = ffStrbufCreate(); const char* error = ffDetectWallpaper(&fullpath); if (error) { @@ -86,5 +86,6 @@ FFModuleBaseInfo ffWallpaperModuleInfo = { .formatArgs = FF_FORMAT_ARG_LIST(((FFModuleFormatArg[]) { { "File name", "file-name" }, { "Full path", "full-path" }, - })) + })), + .defaultOrder = 28, }; diff --git a/src/modules/weather/weather.c b/src/modules/weather/weather.c index 6c156929d8..152cb057bd 100644 --- a/src/modules/weather/weather.c +++ b/src/modules/weather/weather.c @@ -87,6 +87,7 @@ void ffInitWeatherOptions(FFWeatherOptions* options) { void ffDestroyWeatherOptions(FFWeatherOptions* options) { ffOptionDestroyModuleArg(&options->moduleArgs); + ffStrbufDestroy(&options->location); ffStrbufDestroy(&options->outputFormat); } @@ -101,5 +102,6 @@ FFModuleBaseInfo ffWeatherModuleInfo = { .generateJsonConfig = (void*) ffGenerateWeatherJsonConfig, .formatArgs = FF_FORMAT_ARG_LIST(((FFModuleFormatArg[]) { { "Weather result", "result" }, - })) + })), + .defaultOrder = 65, }; diff --git a/src/modules/wifi/wifi.c b/src/modules/wifi/wifi.c index 42485dce6b..0e9df22c98 100644 --- a/src/modules/wifi/wifi.c +++ b/src/modules/wifi/wifi.c @@ -148,7 +148,7 @@ void ffGenerateWifiJsonConfig(FFWifiOptions* options, yyjson_mut_doc* doc, yyjso ffPercentGenerateJsonConfig(doc, module, options->percent); } -bool ffGenerateWifiJsonResult(FF_A_UNUSED FFWifiOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateWifiJsonResult([[maybe_unused]] FFWifiOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FF_LIST_AUTO_DESTROY result = ffListCreate(); const char* error = ffDetectWifi(&result); if (error) { @@ -235,5 +235,6 @@ FFModuleBaseInfo ffWifiModuleInfo = { { "Connection signal quality (percentage bar)", "signal-quality-bar" }, { "Connection channel number", "channel" }, { "Connection channel band in GHz", "band" }, - })) + })), + .defaultOrder = 51, }; diff --git a/src/modules/wm/wm.c b/src/modules/wm/wm.c index 5ec66463b6..5e23826e1c 100644 --- a/src/modules/wm/wm.c +++ b/src/modules/wm/wm.c @@ -82,7 +82,7 @@ void ffGenerateWMJsonConfig(FFWMOptions* options, yyjson_mut_doc* doc, yyjson_mu yyjson_mut_obj_add_bool(doc, module, "detectPlugin", options->detectPlugin); } -bool ffGenerateWMJsonResult(FF_A_UNUSED FFWMOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateWMJsonResult([[maybe_unused]] FFWMOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { const FFDisplayServerResult* result = ffConnectDisplayServer(); if (result->wmPrettyName.length == 0) { @@ -134,5 +134,6 @@ FFModuleBaseInfo ffWMModuleInfo = { { "WM protocol name", "protocol-name" }, { "WM plugin name", "plugin-name" }, { "WM version", "version" }, - })) + })), + .defaultOrder = 22, }; diff --git a/src/modules/wmtheme/wmtheme.c b/src/modules/wmtheme/wmtheme.c index 775e88a9dc..f1ab4105f7 100644 --- a/src/modules/wmtheme/wmtheme.c +++ b/src/modules/wmtheme/wmtheme.c @@ -41,7 +41,7 @@ void ffGenerateWMThemeJsonConfig(FFWMThemeOptions* options, yyjson_mut_doc* doc, ffJsonConfigGenerateModuleArgsConfig(doc, module, &options->moduleArgs); } -bool ffGenerateWMThemeJsonResult(FF_A_UNUSED FFWMThemeOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateWMThemeJsonResult([[maybe_unused]] FFWMThemeOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FF_STRBUF_AUTO_DESTROY themeOrError = ffStrbufCreate(); if (!ffDetectWmTheme(&themeOrError)) { yyjson_mut_obj_add_strbuf(doc, module, "error", &themeOrError); @@ -71,5 +71,6 @@ FFModuleBaseInfo ffWMThemeModuleInfo = { .generateJsonConfig = (void*) ffGenerateWMThemeJsonConfig, .formatArgs = FF_FORMAT_ARG_LIST(((FFModuleFormatArg[]) { { "WM theme", "result" }, - })) + })), + .defaultOrder = 23, }; diff --git a/src/modules/zpool/zpool.c b/src/modules/zpool/zpool.c index 44a6de2a18..7e5f03a52d 100644 --- a/src/modules/zpool/zpool.c +++ b/src/modules/zpool/zpool.c @@ -148,7 +148,7 @@ void ffGenerateZpoolJsonConfig(FFZpoolOptions* options, yyjson_mut_doc* doc, yyj ffPercentGenerateJsonConfig(doc, module, options->percent); } -bool ffGenerateZpoolJsonResult(FF_A_UNUSED FFZpoolOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { +bool ffGenerateZpoolJsonResult([[maybe_unused]] FFZpoolOptions* options, yyjson_mut_doc* doc, yyjson_mut_val* module) { FF_LIST_AUTO_DESTROY results = ffListCreate(); const char* error = ffDetectZpool(&results); @@ -214,5 +214,6 @@ FFModuleBaseInfo ffZpoolModuleInfo = { { "Size allocated percentage bar", "allocated-percentage-bar" }, { "Fragmentation percentage bar", "frag-percentage-bar" }, { "Is read-only", "is-readonly" }, - })) + })), + .defaultOrder = 43, }; diff --git a/src/options/display.c b/src/options/display.c index fe94819092..a1136e7b1a 100644 --- a/src/options/display.c +++ b/src/options/display.c @@ -10,7 +10,7 @@ const char* ffOptionsParseDisplayJsonConfig(FFOptionsDisplay* options, yyjson_val* root, yyjson_val** pkey) { yyjson_val* object = yyjson_obj_get(root, "display"); if (!object) { - return NULL; + return nullptr; } if (!yyjson_is_obj(object)) { return "Property 'display' must be an object"; @@ -571,11 +571,11 @@ const char* ffOptionsParseDisplayJsonConfig(FFOptionsDisplay* options, yyjson_va } } - return NULL; + return nullptr; } static inline void optionCheckString(const char* key, const char* value, FFstrbuf* buffer) { - if (value == NULL) { + if (value == nullptr) { fprintf(stderr, "Error: usage: %s \n", key); exit(477); } @@ -897,6 +897,19 @@ void ffOptionsDestroyDisplay(FFOptionsDisplay* options) { ffStrbufDestroy(&options->keyValueSeparator); ffStrbufDestroy(&options->barCharElapsed); ffStrbufDestroy(&options->barCharTotal); + ffStrbufDestroy(&options->barBorderLeft); + ffStrbufDestroy(&options->barBorderRight); + ffStrbufDestroy(&options->barBorderLeftElapsed); + ffStrbufDestroy(&options->barBorderRightElapsed); + ffStrbufDestroy(&options->barColorElapsed); + ffStrbufDestroy(&options->barColorTotal); + ffStrbufDestroy(&options->barColorBorder); + ffStrbufDestroy(&options->tempColorGreen); + ffStrbufDestroy(&options->tempColorYellow); + ffStrbufDestroy(&options->tempColorRed); + ffStrbufDestroy(&options->percentColorGreen); + ffStrbufDestroy(&options->percentColorYellow); + ffStrbufDestroy(&options->percentColorRed); FF_LIST_FOR_EACH (FFstrbuf, item, options->constants) { ffStrbufDestroy(item); } diff --git a/src/options/display.h b/src/options/display.h index 6017291f50..8e234b08a0 100644 --- a/src/options/display.h +++ b/src/options/display.h @@ -5,26 +5,26 @@ #include "common/FFstrbuf.h" #include "common/FFlist.h" -typedef enum FF_A_PACKED FFSizeBinaryPrefixType { +typedef enum FFSizeBinaryPrefixType: uint8_t { FF_SIZE_BINARY_PREFIX_TYPE_IEC, // 1024 Bytes = 1 KiB, 1024 KiB = 1 MiB, ... (standard) FF_SIZE_BINARY_PREFIX_TYPE_SI, // 1000 Bytes = 1 kB, 1000 kB = 1 MB, ... FF_SIZE_BINARY_PREFIX_TYPE_JEDEC, // 1024 Bytes = 1 KB, 1024 KB = 1 MB, ... } FFSizeBinaryPrefixType; -typedef enum FF_A_PACKED FFTemperatureUnit { +typedef enum FFTemperatureUnit: uint8_t { FF_TEMPERATURE_UNIT_DEFAULT, FF_TEMPERATURE_UNIT_CELSIUS, FF_TEMPERATURE_UNIT_FAHRENHEIT, FF_TEMPERATURE_UNIT_KELVIN, } FFTemperatureUnit; -typedef enum FF_A_PACKED FFSpaceBeforeUnitType { +typedef enum FFSpaceBeforeUnitType: uint8_t { FF_SPACE_BEFORE_UNIT_DEFAULT, FF_SPACE_BEFORE_UNIT_ALWAYS, FF_SPACE_BEFORE_UNIT_NEVER, } FFSpaceBeforeUnitType; -typedef enum FF_A_PACKED FFFractionTrailingZerosType { +typedef enum FFFractionTrailingZerosType: uint8_t { FF_FRACTION_TRAILING_ZEROS_TYPE_DEFAULT, FF_FRACTION_TRAILING_ZEROS_TYPE_ALWAYS, FF_FRACTION_TRAILING_ZEROS_TYPE_NEVER, diff --git a/src/options/general.c b/src/options/general.c index 1e1355df8a..ee7204218b 100644 --- a/src/options/general.c +++ b/src/options/general.c @@ -9,7 +9,7 @@ const char* ffOptionsParseGeneralJsonConfig(FFOptionsGeneral* options, yyjson_val* root, yyjson_val** pkey) { yyjson_val* object = yyjson_obj_get(root, "general"); if (!object) { - return NULL; + return nullptr; } if (!yyjson_is_obj(object)) { return "Property 'general' must be an object"; @@ -24,12 +24,7 @@ const char* ffOptionsParseGeneralJsonConfig(FFOptionsGeneral* options, yyjson_va } else if (unsafe_yyjson_equals_str(key, "processingTimeout")) { options->processingTimeout = (int32_t) yyjson_get_int(val); } else if (unsafe_yyjson_equals_str(key, "preRun")) { - if (!yyjson_is_str(val)) { - return "general.preRun must be a string"; - } - if (system(unsafe_yyjson_get_str(val)) < 0) { - return "Failed to execute preRun command"; - } + return "general.preRun is removed due to security concerns."; } else if (unsafe_yyjson_equals_str(key, "detectVersion")) { options->detectVersion = yyjson_get_bool(val); } else if (unsafe_yyjson_equals_str(key, "playerName")) { @@ -60,7 +55,7 @@ const char* ffOptionsParseGeneralJsonConfig(FFOptionsGeneral* options, yyjson_va } } - return NULL; + return nullptr; } bool ffOptionsParseGeneralCommandLine(FFOptionsGeneral* options, const char* key, const char* value) { diff --git a/src/options/general.h b/src/options/general.h index b58d6c9e34..cf5207bae6 100644 --- a/src/options/general.h +++ b/src/options/general.h @@ -2,7 +2,7 @@ #include "common/ffdata.h" -typedef enum FF_A_PACKED FFDsForceDrmType { +typedef enum FFDsForceDrmType: uint8_t { FF_DS_FORCE_DRM_TYPE_FALSE = 0, // Disable FF_DS_FORCE_DRM_TYPE_TRUE = 1, // Try `libdrm`, then `sysfs` if libdrm failed FF_DS_FORCE_DRM_TYPE_SYSFS_ONLY, // Use `/sys/class/drm` only diff --git a/src/options/logo.c b/src/options/logo.c index 99e22c99c6..e62bd23b75 100644 --- a/src/options/logo.c +++ b/src/options/logo.c @@ -38,7 +38,7 @@ bool ffOptionsParseLogoCommandLine(FFOptionsLogo* options, const char* key, cons if (subKey) { if (subKey[0] == '\0') { logoType: - if (value == NULL) { + if (value == nullptr) { fprintf(stderr, "Error: usage: %s \n", key); exit(477); } @@ -80,7 +80,7 @@ bool ffOptionsParseLogoCommandLine(FFOptionsLogo* options, const char* key, cons fprintf(stderr, "Error: invalid --color-[1-9] index: %c\n", key[13]); exit(472); } - if (value == NULL) { + if (value == nullptr) { fprintf(stderr, "Error: usage: %s \n", key); exit(477); } @@ -219,7 +219,7 @@ void ffOptionsDestroyLogo(FFOptionsLogo* options) { const char* ffOptionsParseLogoJsonConfig(FFOptionsLogo* options, yyjson_val* root, yyjson_val** pkey) { yyjson_val* object = yyjson_obj_get(root, "logo"); if (!object) { - return NULL; + return nullptr; } if (yyjson_is_null(object)) { options->type = FF_LOGO_TYPE_NONE; @@ -227,12 +227,12 @@ const char* ffOptionsParseLogoJsonConfig(FFOptionsLogo* options, yyjson_val* roo options->paddingBottom = 0; options->paddingRight = 0; options->paddingLeft = 0; - return NULL; + return nullptr; } if (yyjson_is_str(object)) { ffStrbufSetJsonVal(&options->source, object); - return NULL; + return nullptr; } if (!yyjson_is_obj(object)) { @@ -281,7 +281,7 @@ const char* ffOptionsParseLogoJsonConfig(FFOptionsLogo* options, yyjson_val* roo yyjson_val *keyc, *valc; size_t idxc, maxc; yyjson_obj_foreach (val, idxc, maxc, keyc, valc) { - uint32_t index = (uint32_t) strtoul(unsafe_yyjson_get_str(keyc), NULL, 10); + uint32_t index = (uint32_t) strtoul(unsafe_yyjson_get_str(keyc), nullptr, 10); if (index < 1 || index > FASTFETCH_LOGO_MAX_COLORS) { return "Keys of property 'color' must be a number between 1 to 9"; } @@ -428,7 +428,7 @@ const char* ffOptionsParseLogoJsonConfig(FFOptionsLogo* options, yyjson_val* roo } } - return NULL; + return nullptr; } void ffOptionsGenerateLogoJsonConfig(FFdata* data, FFOptionsLogo* options) { diff --git a/src/options/logo.h b/src/options/logo.h index 7a71531d9c..51d5cfbfc5 100644 --- a/src/options/logo.h +++ b/src/options/logo.h @@ -5,7 +5,7 @@ #define FASTFETCH_LOGO_MAX_NAMES 9 #define FASTFETCH_LOGO_MAX_COLORS 9 // two digits would make parsing much more complicated (index 1 - 9) -typedef enum FF_A_PACKED FFLogoType { +typedef enum FFLogoType: uint8_t { FF_LOGO_TYPE_AUTO, // if something is given, first try builtin, then file. Otherwise detect logo FF_LOGO_TYPE_BUILTIN, // builtin ascii art FF_LOGO_TYPE_SMALL, // builtin ascii art, small version @@ -24,7 +24,7 @@ typedef enum FF_A_PACKED FFLogoType { FF_LOGO_TYPE_NONE, // `--logo none`, but still applies colors to the system information output (unless `--pipe` is set) } FFLogoType; -typedef enum FF_A_PACKED FFLogoPosition { +typedef enum FFLogoPosition: uint8_t { FF_LOGO_POSITION_LEFT, FF_LOGO_POSITION_TOP, FF_LOGO_POSITION_RIGHT, diff --git a/tests/list.c b/tests/list.c index 2184dd79c3..a42d088780 100644 --- a/tests/list.c +++ b/tests/list.c @@ -100,6 +100,79 @@ int main(void) { VERIFY(*FF_LIST_GET(uint32_t, list, 0) == 2); VERIFY(*FF_LIST_GET(uint32_t, list, list.length - 1) == FF_LIST_DEFAULT_ALLOC); + // insertAt + ffListClear(&list); + for (uint32_t i = 1; i <= 5; ++i) { + *FF_LIST_ADD(uint32_t, list) = i; + } + // list = [1,2,3,4,5] + + { + uint32_t v = 0; + FF_LIST_INSERT_AT(uint32_t, list, 0, &v); // insert at head + } + VERIFY(list.length == 6); + VERIFY(*FF_LIST_GET(uint32_t, list, 0) == 0); + VERIFY(*FF_LIST_GET(uint32_t, list, 1) == 1); + VERIFY(*FF_LIST_GET(uint32_t, list, 5) == 5); + // list = [0,1,2,3,4,5] + + { + uint32_t v = 99; + FF_LIST_INSERT_AT(uint32_t, list, 3, &v); // insert in the middle + } + VERIFY(list.length == 7); + VERIFY(*FF_LIST_GET(uint32_t, list, 2) == 2); + VERIFY(*FF_LIST_GET(uint32_t, list, 3) == 99); + VERIFY(*FF_LIST_GET(uint32_t, list, 4) == 3); + VERIFY(*FF_LIST_GET(uint32_t, list, 6) == 5); + // list = [0,1,2,99,3,4,5] + + { + uint32_t v = 6; + FF_LIST_INSERT_AT(uint32_t, list, list.length, &v); // insert at tail + } + VERIFY(list.length == 8); + VERIFY(*FF_LIST_GET(uint32_t, list, 3) == 99); + VERIFY(*FF_LIST_GET(uint32_t, list, 7) == 6); + // list = [0,1,2,99,3,4,5,6] + + ffListClear(&list); + { + uint32_t v = 42; + FF_LIST_INSERT_AT(uint32_t, list, 0, &v); // insert into empty list + } + VERIFY(list.length == 1); + VERIFY(*FF_LIST_GET(uint32_t, list, 0) == 42); + + // removeAt + FF_LIST_REMOVE_AT(uint32_t, list, 0); // remove the only element + VERIFY(list.length == 0); + + for (uint32_t i = 1; i <= 5; ++i) { + *FF_LIST_ADD(uint32_t, list) = i; + } + // list = [1,2,3,4,5] + + FF_LIST_REMOVE_AT(uint32_t, list, 0); // remove head + VERIFY(list.length == 4); + VERIFY(*FF_LIST_GET(uint32_t, list, 0) == 2); + VERIFY(*FF_LIST_GET(uint32_t, list, list.length - 1) == 5); + // list = [2,3,4,5] + + FF_LIST_REMOVE_AT(uint32_t, list, 1); // remove in the middle + VERIFY(list.length == 3); + VERIFY(*FF_LIST_GET(uint32_t, list, 0) == 2); + VERIFY(*FF_LIST_GET(uint32_t, list, 1) == 4); + VERIFY(*FF_LIST_GET(uint32_t, list, 2) == 5); + // list = [2,4,5] + + FF_LIST_REMOVE_AT(uint32_t, list, list.length - 1); // remove tail + VERIFY(list.length == 2); + VERIFY(*FF_LIST_GET(uint32_t, list, 0) == 2); + VERIFY(*FF_LIST_GET(uint32_t, list, 1) == 4); + // list = [2,4] + // Destroy ffListDestroy(&list); diff --git a/tests/strbuf.c b/tests/strbuf.c index 2374de615a..a8e698cafc 100644 --- a/tests/strbuf.c +++ b/tests/strbuf.c @@ -414,7 +414,7 @@ int main(void) { ffStrbufInit(&strbuf); ffStrbufEnsureFixedLengthFree(&strbuf, 0); VERIFY(strbuf.length == 0); - VERIFY(strbuf.allocated == 0); + VERIFY(strbuf.allocated == 1); ffStrbufDestroy(&strbuf); // ffStrbufEnsureFixedLengthFree / empty buffer but oldFree >= newFree @@ -769,7 +769,7 @@ int main(void) { ffStrbufAppendUtf32CodePoint(&strbuf, 0x6587); ffStrbufAppendUtf32CodePoint(&strbuf, 0x6cc9); ffStrbufAppendUtf32CodePoint(&strbuf, 0x9a7f); - VERIFY(ffStrbufEqualS(&strbuf, u8"文泉驿")); + VERIFY(ffStrbufEqualS(&strbuf, (const char*) u8"文泉驿")); ffStrbufDestroy(&strbuf); }