Compare commits

..

89 Commits

Author SHA1 Message Date
dependabot[bot] 0804fa306a CI: Bump the github-actions group with 5 updates
Bumps the github-actions group with 5 updates:

| Package | From | To |
| --- | --- | --- |
| [cross-platform-actions/action](https://github.com/cross-platform-actions/action) | `1.5.0` | `1.6.0` |
| [github/codeql-action/init](https://github.com/github/codeql-action) | `4.37.9` | `4.38.0` |
| [github/codeql-action/analyze](https://github.com/github/codeql-action) | `4.37.9` | `4.38.0` |
| [vmactions/solaris-vm](https://github.com/vmactions/solaris-vm) | `1.3.9` | `1.4.0` |
| [signpath/github-action-submit-signing-request](https://github.com/signpath/github-action-submit-signing-request) | `2.3` | `3.0` |


Updates `cross-platform-actions/action` from 1.5.0 to 1.6.0
- [Release notes](https://github.com/cross-platform-actions/action/releases)
- [Changelog](https://github.com/cross-platform-actions/action/blob/master/changelog.md)
- [Commits](https://github.com/cross-platform-actions/action/compare/faa0c6197e94aacf1c5956460152c8380d3560a5...e0b9770014ba65d5e0815f15b74031c3a635f641)

Updates `github/codeql-action/init` from 4.37.9 to 4.38.0
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/github/codeql-action/compare/cdf488f595d80d6e07e03d4674febd5ab45fa938...b96794f015dfd88f77b49b1c93e0fa7110f94c63)

Updates `github/codeql-action/analyze` from 4.37.9 to 4.38.0
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/github/codeql-action/compare/cdf488f595d80d6e07e03d4674febd5ab45fa938...b96794f015dfd88f77b49b1c93e0fa7110f94c63)

Updates `vmactions/solaris-vm` from 1.3.9 to 1.4.0
- [Release notes](https://github.com/vmactions/solaris-vm/releases)
- [Commits](https://github.com/vmactions/solaris-vm/compare/96d8d976f9e67d82ec6c7e8ce9c1060731f9e21c...a11f407d3720a3717673d4194f19ee63b284977e)

Updates `signpath/github-action-submit-signing-request` from 2.3 to 3.0
- [Release notes](https://github.com/signpath/github-action-submit-signing-request/releases)
- [Commits](https://github.com/signpath/github-action-submit-signing-request/compare/c92b958760219087e01f8d67a1669ed57afe2627...f6d04783b4569d051e0c80105fe66e82819d0092)

---
updated-dependencies:
- dependency-name: cross-platform-actions/action
  dependency-version: 1.6.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: github-actions
- dependency-name: github/codeql-action/init
  dependency-version: 4.38.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: github-actions
- dependency-name: github/codeql-action/analyze
  dependency-version: 4.38.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: github-actions
- dependency-name: vmactions/solaris-vm
  dependency-version: 1.4.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: github-actions
- dependency-name: signpath/github-action-submit-signing-request
  dependency-version: '3.0'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: github-actions
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-09-20 18:06:51 +00:00
李通洲 eda38a37ba Battery (Android): adds debug output 2026-09-21 00:01:45 +08:00
李通洲 0b76d33f07 Wifi(Android): fixes errors when location permission is not granted
Security detection support is also added
2026-09-20 23:49:39 +08:00
李通洲 39564acde4 Platform: replaces pageSize for pageSizeShift 2026-09-20 20:56:42 +08:00
李通洲 3bfc4ec674 Terminal (Windows): uses $SSH_TTY if available 2026-09-20 19:23:35 +08:00
李通洲 fea55b276e Terminal (Windows): ignores services; fixes ssh env detection 2026-09-20 16:25:52 +08:00
李通洲 bc51f1ba0c Brightness (Windows): fixes debug messages 2026-09-20 16:25:14 +08:00
李通洲 38e4ba290d OS (Windows): adds comments 2026-09-20 14:21:25 +08:00
李通洲 24fb73e9b4 CI: eliminates codespell errors 2026-09-20 14:21:03 +08:00
李通洲 f96a290f3b Packages (Windows): caches winget packages count; enables winget by default 2026-09-20 13:05:09 +08:00
李通洲 67da836a27 Top: reduces waitTime to 250ms 2026-09-20 11:24:25 +08:00
李通洲 15e4bc998a Global (Android): code cleanup 2026-09-20 09:23:32 +08:00
李通洲 f9f368c1fb Battery (Android): uses dumpsys if available 2026-09-20 08:13:11 +08:00
李通洲 4a33a2c410 Player (Windows): improves player name detection 2026-09-20 00:50:01 +08:00
李通洲 34639b61b3 Presets: updates examples/25 [ci skip]
Fixes #2595
2026-09-19 18:55:30 +08:00
Carter Li efbfda9cf8 Doc: updates changelog [ci skip] 2026-09-19 18:34:32 +08:00
Carter Li 6142077656 Chore: eliminates a compiler warning 2026-09-19 18:34:32 +08:00
李通洲 58692adabc Common (Networking): fixes a non-pure function marked as pure
Fixes CI
2026-09-19 07:58:59 +08:00
李通洲 665c472482 Wifi (Android): rewrites impl via /dev/binder 2026-09-19 00:39:25 +08:00
李通洲 2594c01fc1 Common: renames androidApi.h for android/api.h 2026-09-18 20:25:46 +08:00
李通洲 e1d7360453 Display (Android): adds richer information and adds detectWithGetprop back 2026-09-18 20:22:16 +08:00
李通洲 873a881dab Battery (Android): rewrites impl via /dev/binder 2026-09-18 20:22:16 +08:00
李通洲 ecbf218d6e Chore: fixes compiling errors 2026-09-18 15:01:11 +08:00
李通洲 2fb7fabc4d CI (Haiku): don't reboot after installing deps 2026-09-18 15:01:11 +08:00
李通洲 811e634dc8 Display (Android): adds real support via /system/bin/cmd 2026-09-18 15:01:10 +08:00
李通洲 098b501d0e Camera (Android): uses NDK instead of the unstable termux-api 2026-09-18 15:01:10 +08:00
李通洲 7baaae166f DE (Android): improves Android ROM detection
Fixes #2541
2026-09-18 15:01:10 +08:00
Ian Ribeiro 560a9f419d WM (Linux): supports Umbriel version detection (#2594) 2026-09-18 11:42:19 +08:00
李通洲 70d2dd37a6 Image (Logo): uses native image decoder on Android
Codec (Android): uses `availability` feature test
2026-09-18 01:17:28 +08:00
李通洲 97ac94eb44 Common: adds more gcc constrants 2026-09-17 21:00:36 +08:00
李通洲 6ff7f2772b Tests: adds more UTs 2026-09-17 20:11:25 +08:00
李通洲 f8fd708423 Global: addresses Copilot's review comments 2026-09-17 19:19:25 +08:00
Carter Li c23c98a85a Logo (Image): supports transparent background of sixel logos 2026-09-17 16:39:19 +08:00
Carter Li 43988a8d41 Release: v2.69.0 2026-09-17 14:37:17 +08:00
Carter Li 1b7cc1cd30 CPU (Linux): adds SoC name of MacBook Neo 2026-09-17 14:02:29 +08:00
Carter Li 59e33150dd CPU (Android): updates the marketing name of Dimensity 9600 Pro 2026-09-17 14:01:13 +08:00
Carter Li e004c97ee0 CMake: adds option -DENABLE_IMAGE_LOGO=<BOOL> 2026-09-17 13:50:07 +08:00
李通洲 9bac273165 NetIO / DiskIO: reduces waitTime & improves accurency 2026-09-17 00:33:47 +08:00
李通洲 d1b747192f Logo (Image): adds animation (gif / apng) support 2026-09-16 20:48:02 +08:00
李通洲 b96d7e7bec Networking: supports chunked response & custom port number 2026-09-16 14:49:50 +08:00
李通洲 7b28ad07d7 Chore: updates gitignore 2026-09-15 22:41:47 +08:00
李通洲 02dc6a4428 Modules: adds * to format args which are available in key format 2026-09-15 22:24:18 +08:00
李通洲 53e868667a Logo (Image): fixes a copy-paste error 2026-09-15 20:11:36 +08:00
Carter Li fbf79ac6fe FFstrbuf: improves empty-string handling
for ffStrbufMatchSeparatedNS and ffStrbufSeparatedContainNS

Fixes #2585
2026-09-15 10:43:25 +08:00
Carter Li 416715a505 Presets: fixes neofetch keys
Fixes #2588
2026-09-15 10:43:25 +08:00
Carter Li ff3360e036 Logo (Image): fixes potencial memleaks 2026-09-15 08:50:47 +08:00
Carter Li 98ec0a674c IO: increases FF_IO_TERM_RESP_WAIT_MS 2026-09-15 08:45:48 +08:00
李通洲 6178256404 Logo (Icat): adds logo-padding support 2026-09-15 00:44:02 +08:00
李通洲 129bb7309e Logo (Icat): adds --stdin=no so icat doesn't try to read stdin 2026-09-15 00:13:06 +08:00
李通洲 464adb3540 Logo (Image): migrates recache to cache: bool|regen 2026-09-14 23:45:28 +08:00
李通洲 3d7ea720fb Logo (Image): improves caching logic; takes mtime into account 2026-09-14 22:43:19 +08:00
李通洲 a90ae0249d IO (Windows): prefers unicode APIs 2026-09-14 22:42:16 +08:00
李通洲 375d0c6b25 Common (IO): adds ffPathGetMtime and uses it 2026-09-14 22:21:49 +08:00
李通洲 e3b3b5dfc6 Packages: fixes a copy-paste bug 2026-09-14 19:25:10 +08:00
Carter Li 35ffdb3995 Logo (Image): drops IM in favor of ImageIO on macOS 2026-09-14 19:02:50 +08:00
李通洲 e8350a0d6e Logo (Image): drops IM in favor of WIC on Windows 2026-09-14 19:02:50 +08:00
李通洲 98e9b6eef1 3rdparty: embeds libsixel 2026-09-14 19:02:50 +08:00
dependabot[bot] d796945604 CI: Bump docker/setup-qemu-action in the github-actions group (#2583)
Bumps the github-actions group with 1 update: [docker/setup-qemu-action](https://github.com/docker/setup-qemu-action).


Updates `docker/setup-qemu-action` from 4.2.0 to 4.3.0
- [Release notes](https://github.com/docker/setup-qemu-action/releases)
- [Commits](https://github.com/docker/setup-qemu-action/compare/96fe6ef7f33517b61c61be40b68a1882f3264fb8...1f40c72289eff860ee54a304f1438e3cff362e0a)

---
updated-dependencies:
- dependency-name: docker/setup-qemu-action
  dependency-version: 4.3.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: github-actions
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-09-14 18:49:44 +08:00
Carter Li cd5a2def9a DE (Linux): uses COSMIC_VERSION if available
https://github.com/pop-os/cosmic-comp/issues/2425#issuecomment-5652401962
2026-09-13 17:33:15 +08:00
Carter Li 8334035927 Logo: small optimizations 2026-09-13 12:27:17 +08:00
Carter Li 1ee8528f10 Format: makes {#title} and {#key} honors brightColor config 2026-09-13 12:26:57 +08:00
Carter Li ced49ab2a4 Chore: dont let clang-format break my code style 2026-09-13 12:05:07 +08:00
Carter Li ec8b9be354 Packages: opens SQLite DB in immutable mode
.. to avoid `SQLITE_READONLY` errors
2026-09-13 11:13:33 +08:00
李通洲 19725cd2f7 Packages (Windows): adds --source winget to improve performance of winget package detection 2026-09-13 08:39:45 +08:00
李通洲 20c155e5b4 TerminalFont (Windows): honors JSON fragment
Fixes #2573
2026-09-13 08:39:45 +08:00
dependabot[bot] 61e3f6108c CI: Bump the github-actions group with 3 updates (#2569)
Bumps the github-actions group with 3 updates: [github/codeql-action/init](https://github.com/github/codeql-action), [github/codeql-action/analyze](https://github.com/github/codeql-action) and [vmactions/solaris-vm](https://github.com/vmactions/solaris-vm).


Updates `github/codeql-action/init` from 4.37.8 to 4.37.9
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/github/codeql-action/compare/db488ddef3bf6cb639b32c2e9a7c0a7ea8271d28...cdf488f595d80d6e07e03d4674febd5ab45fa938)

Updates `github/codeql-action/analyze` from 4.37.8 to 4.37.9
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/github/codeql-action/compare/db488ddef3bf6cb639b32c2e9a7c0a7ea8271d28...cdf488f595d80d6e07e03d4674febd5ab45fa938)

Updates `vmactions/solaris-vm` from 1.3.8 to 1.3.9
- [Release notes](https://github.com/vmactions/solaris-vm/releases)
- [Commits](https://github.com/vmactions/solaris-vm/compare/315163f088b66e55bbcc45928bd224d4973b2312...96d8d976f9e67d82ec6c7e8ce9c1060731f9e21c)

---
updated-dependencies:
- dependency-name: github/codeql-action/init
  dependency-version: 4.37.9
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: github-actions
- dependency-name: github/codeql-action/analyze
  dependency-version: 4.37.9
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: github-actions
- dependency-name: vmactions/solaris-vm
  dependency-version: 1.3.9
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: github-actions
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-09-12 23:38:17 +08:00
李通洲 eff8514536 CI (macOS): builds Intel version with macport 2026-09-12 00:08:16 +08:00
李通洲 f37a5a2543 OpenBSD: removes kvm dep 2026-09-11 23:38:10 +08:00
Carter Li 9a9f82b59e Processes (macOS): adds a comment 2026-09-11 10:40:44 +08:00
Carter Li 29818d2dca Top (macOS): improves performance and accuracy‌ of process name 2026-09-11 10:36:16 +08:00
Carter Li 222fe7e3f9 3rdparty (yyjson): upgrades to 0.13.0 2026-09-09 13:49:56 +08:00
Stian Halseth 7d0256fb85 CPU (Linux): adds SPARC support (#2572)
/proc/cpuinfo on sparc has none of the fields the generic fallback looks
for, so the module printed "Unknown (64)". The name is in "cpu", and the
frequency in "Cpu<n>ClkTck" -- in Hz, hex on sparc64, decimal on sparc32.
2026-09-08 20:31:55 +08:00
Carter Li a70c37fdaf Logo (Builtin): removes Zerene
Distro discontinued #2567
2026-09-07 10:58:46 +08:00
Sultaniiazov David 66e9e38f28 Logo (Builtin): adds ALT Atomic (#2549)
Co-authored-by: Vladimir Romanov <rirusha@altlinux.org>
2026-09-06 23:29:42 +08:00
李通洲 5d290cc3d5 Common (CommandOption): find module configuration from JSON config file 2026-09-05 20:14:58 +08:00
Guiorgy 2e542bea64 CMake: bumps min version to 3.21 (#2565)
C_STANDARD C17 and C23 were only introduced in CMake 3.21
2026-09-05 13:43:05 +08:00
李通洲 c708b6f5cd CPU (Linux): adds apple code of M5x 2026-09-05 00:32:58 +08:00
李通洲 6a275da8b1 Sound: removes an unused file 2026-09-05 00:32:31 +08:00
李通洲 ecee5694fb Global: uses strtoull for uint64_t
Fixes #2563 #2564
2026-09-04 19:35:26 +08:00
Matt Housh 4e78f1b703 Packages (Linux): adds support for package detection for CRUX linux 2026-09-04 18:14:21 +08:00
李通洲 62f78ca60c Processes (Windows): uses SystemHandleCountInformation if available 2026-09-03 15:27:40 +08:00
李通洲 00af2d1df2 WM: uses SystemBasicProcessInformation if available 2026-09-03 10:04:55 +08:00
李通洲 1128a75d8c InitSystem: uses SystemBasicProcessInformation if available 2026-09-03 10:04:55 +08:00
Carter Li ce61783c4b Wallpaper (macOS): extracts image path from NSData Configuration field
Also moves NSWorkspace method to the last method to try

Fixes #2559
2026-09-03 09:57:08 +08:00
Piotr Kubaj 20597bff00 Logo (image): also try unsuffixed ImageMagick library names
FreeBSD (and other systems that build ImageMagick without encoding the
quantum depth into the library name) install libMagickCore-7.so and
libMagickCore-6.so without a .Q16HDRI / .Q16 suffix.  dlopen currently
only tries the suffixed names, so image logos always fall back to ASCII
art with "Image Magick library not found" even when ImageMagick is
installed.  Append the plain library names as a last resort.
2026-09-02 17:06:16 +08:00
Carter Li caf64f5e4d Packaging: updates debian stuff [ci skip] 2026-09-02 10:52:57 +08:00
Carter Li 90a6e90b19 Processes (macOS): eliminates a compiler warning 2026-09-02 10:45:52 +08:00
Carter Li e9f719f37a Doc: update CONTRIBUTING.md [ci skip] 2026-09-02 10:44:47 +08:00
Carter Li 8c98bf1953 CMake: discovers module file automatically 2026-09-02 10:44:47 +08:00
209 changed files with 20124 additions and 2742 deletions
+1 -1
View File
@@ -2,4 +2,4 @@
check-filenames =
builtin = clear,rare,usage,informal
skip = */.git,*/cmake-build-*,*/.idea,*/completions,*/presets,*/screenshots,*/tests,*/3rdparty,*/logo/ascii,./src/detection/gpu/asahi_drm.h,./src/detection/cpu/cpu_x86.c,./src/detection/gpu/gpu_bsddrm.c,./src/detection/displayserver/linux/wayland/*-protocol.*,./build,./build-*,./build_*,./src/common/impl/genconfig.c
ignore-words-list = iterm,compiletime,unknwn,pengwin,siduction,master,slave,sur,doas,conexant,ags,bu,renderD,SME,Carmel,kinda,symbole,connexion,comando,processus,lokale,adres,titel,som,environnement,Sistem,Lokal,Lokal,Sistem,Paket,Hava
ignore-words-list = iterm,compiletime,unknwn,pengwin,siduction,master,slave,sur,doas,conexant,ags,bu,renderD,SME,Carmel,kinda,symbole,connexion,comando,processus,lokale,adres,titel,som,environnement,Sistem,Lokal,Lokal,Sistem,Paket,Hava,statics
+1 -1
View File
@@ -18,7 +18,7 @@ jobs:
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Start VM
uses: cross-platform-actions/action@faa0c6197e94aacf1c5956460152c8380d3560a5 # v1.5.0
uses: cross-platform-actions/action@e0b9770014ba65d5e0815f15b74031c3a635f641 # v1.6.0
with:
operating_system: dragonflybsd
version: '6.4.2'
+1 -1
View File
@@ -18,7 +18,7 @@ jobs:
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Start VM
uses: cross-platform-actions/action@faa0c6197e94aacf1c5956460152c8380d3560a5 # v1.5.0
uses: cross-platform-actions/action@e0b9770014ba65d5e0815f15b74031c3a635f641 # v1.6.0
with:
operating_system: freebsd
version: '15.1'
+1 -2
View File
@@ -18,7 +18,7 @@ jobs:
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Start VM
uses: cross-platform-actions/action@faa0c6197e94aacf1c5956460152c8380d3560a5 # v1.5.0
uses: cross-platform-actions/action@e0b9770014ba65d5e0815f15b74031c3a635f641 # v1.6.0
with:
operating_system: haiku
version: 'r1beta6'
@@ -29,7 +29,6 @@ jobs:
run: uname -a
- name: Install dependencies
shell: cpa.sh {0} --reboot
run: pkgman install -y git dbus_devel mesa_devel libelf_devel imagemagick_devel opencl_headers ocl_icd_devel vulkan_devel zlib_devel chafa_devel cmake llvm22_clang ninja pkgconfig python3.10 lua || pkgman install -y git dbus_devel mesa_devel libelf_devel imagemagick_devel opencl_headers ocl_icd_devel vulkan_devel zlib_devel chafa_devel cmake llvm22_clang ninja pkgconfig python3.10 lua
- name: CMake configuration
+2 -2
View File
@@ -52,7 +52,7 @@ jobs:
- name: Initialize CodeQL
if: inputs.arch == 'amd64'
uses: github/codeql-action/init@db488ddef3bf6cb639b32c2e9a7c0a7ea8271d28 # v4.37.8
uses: github/codeql-action/init@b96794f015dfd88f77b49b1c93e0fa7110f94c63 # v4.38.0
with:
languages: c
@@ -64,7 +64,7 @@ jobs:
- name: perform CodeQL analysis
if: inputs.arch == 'amd64'
uses: github/codeql-action/analyze@db488ddef3bf6cb639b32c2e9a7c0a7ea8271d28 # v4.37.8
uses: github/codeql-action/analyze@b96794f015dfd88f77b49b1c93e0fa7110f94c63 # v4.38.0
- name: list features
run: ./fastfetch --list-features
+1 -1
View File
@@ -40,7 +40,7 @@ jobs:
run: cmake --version
- name: configure project
run: CC=gcc-13 CMAKE_PREFIX_PATH=/home/linuxbrew/.linuxbrew PKG_CONFIG_PATH=/home/linuxbrew/.linuxbrew/lib/pkgconfig:$PKG_CONFIG_PATH cmake -DCMAKE_C_FLAGS="-m32 -march=i686 -mtune=i686" -DCMAKE_SYSTEM_PROCESSOR_OVERRIDE=i686 -DCPACK_DEBIAN_PACKAGE_ARCHITECTURE=i386 -GNinja -DSET_TWEAK=Off -DBUILD_TESTS=On -DENABLE_EMBEDDED_PCIIDS=On -DENABLE_EMBEDDED_AMDGPUIDS=On -DCMAKE_INSTALL_PREFIX=/usr .
run: CC=gcc-13 CMAKE_PREFIX_PATH=/home/linuxbrew/.linuxbrew PKG_CONFIG_PATH=/home/linuxbrew/.linuxbrew/lib/pkgconfig:$PKG_CONFIG_PATH cmake -DCMAKE_C_FLAGS="-m32 -march=i686 -mtune=i686" -DCMAKE_SYSTEM_NAME=Linux -DCMAKE_SYSTEM_VERSION=5.10.0 -DCMAKE_SYSTEM_PROCESSOR=i686 -DCPACK_DEBIAN_PACKAGE_ARCHITECTURE=i386 -GNinja -DSET_TWEAK=Off -DBUILD_TESTS=On -DENABLE_EMBEDDED_PCIIDS=On -DENABLE_EMBEDDED_AMDGPUIDS=On -DCMAKE_INSTALL_PREFIX=/usr .
- name: build project
run: cmake --build . --target package --verbose -j4
+1 -1
View File
@@ -17,7 +17,7 @@ jobs:
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: set up QEMU for loong64
uses: docker/setup-qemu-action@96fe6ef7f33517b61c61be40b68a1882f3264fb8 # v4.2.0
uses: docker/setup-qemu-action@1f40c72289eff860ee54a304f1438e3cff362e0a # v4.3.0
- name: build in loong64 container
run: |
+19 -2
View File
@@ -26,13 +26,30 @@ jobs:
- name: uname -a
run: uname -a
- name: install required packages
- name: install required packages with MacPorts # Homebrew dropped Intel support
if: inputs.arch == 'amd64'
run: |
curl -fsSL https://github.com/macports/macports-base/releases/download/v2.12.6/MacPorts-2.12.6-15-Sequoia.pkg -o "$RUNNER_TEMP/MacPorts.pkg"
sudo installer -pkg "$RUNNER_TEMP/MacPorts.pkg" -target /
echo /opt/local/bin >> "$GITHUB_PATH"
echo /opt/local/sbin >> "$GITHUB_PATH"
export PATH=/opt/local/bin:/opt/local/sbin:$PATH
sudo port selfupdate
sudo port install vulkan-loader vulkan-headers MoltenVK ImageMagick7 chafa lua quickjs-ng jq
- name: install required packages with Homebrew
if: inputs.arch == 'aarch64'
run: |
HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK=1 brew update
HOMEBREW_NO_INSTALLED_DEPENDENTS_CHECK=1 brew install --overwrite vulkan-loader vulkan-headers molten-vk imagemagick chafa lua quickjs-ng jq
- name: configure project
run: cmake -DSET_TWEAK=Off -DBUILD_TESTS=On .
run: |
if [ "${{ inputs.arch }}" = "amd64" ]; then
export CMAKE_PREFIX_PATH=/opt/local
export PKG_CONFIG_PATH=/opt/local/lib/pkgconfig${PKG_CONFIG_PATH:+:$PKG_CONFIG_PATH}
fi
cmake -DSET_TWEAK=Off -DBUILD_TESTS=On .
- name: build project
run: cmake --build . --target package --verbose -j4
+1 -1
View File
@@ -18,7 +18,7 @@ jobs:
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Start VM
uses: cross-platform-actions/action@faa0c6197e94aacf1c5956460152c8380d3560a5 # v1.5.0
uses: cross-platform-actions/action@e0b9770014ba65d5e0815f15b74031c3a635f641 # v1.6.0
with:
operating_system: netbsd
version: '10.1'
+1 -1
View File
@@ -21,7 +21,7 @@ jobs:
run: uname -a
- name: configure project
run: cmake -DSET_TWEAK=Off -DBUILD_TESTS=On -DCMAKE_INSTALL_PREFIX=/usr . -DENABLE_VULKAN=OFF -DENABLE_WAYLAND=OFF -DENABLE_XCB_RANDR=OFF -DENABLE_XCB=OFF -DENABLE_XRANDR=OFF -DENABLE_X11=OFF -DENABLE_DRM=OFF -DENABLE_DRM_AMDGPU=OFF -DENABLE_GIO=OFF -DENABLE_DCONF=OFF -DENABLE_DBUS=OFF -DENABLE_SQLITE3=OFF -DENABLE_RPM=OFF -DENABLE_IMAGEMAGICK7=OFF -DENABLE_IMAGEMAGICK6=OFF -DENABLE_CHAFA=OFF -DENABLE_ZLIB=OFF -DENABLE_EGL=OFF -DENABLE_GLX=OFF -DENABLE_OPENCL=OFF -DENABLE_FREETYPE=OFF -DENABLE_PULSE=OFF -DENABLE_DDCUTIL=OFF -DENABLE_ELF=OFF -DENABLE_EET=OFF -DENABLE_THREADS=OFF
run: cmake -DSET_TWEAK=Off -DBUILD_TESTS=On -DCMAKE_INSTALL_PREFIX=/usr . -DENABLE_VULKAN=OFF -DENABLE_WAYLAND=OFF -DENABLE_XCB_RANDR=OFF -DENABLE_XCB=OFF -DENABLE_XRANDR=OFF -DENABLE_X11=OFF -DENABLE_DRM=OFF -DENABLE_DRM_AMDGPU=OFF -DENABLE_GIO=OFF -DENABLE_DCONF=OFF -DENABLE_DBUS=OFF -DENABLE_SQLITE3=OFF -DENABLE_RPM=OFF -DENABLE_IMAGEMAGICK7=OFF -DENABLE_IMAGEMAGICK6=OFF -DENABLE_CHAFA=OFF -DENABLE_ZLIB=OFF -DENABLE_EGL=OFF -DENABLE_GLX=OFF -DENABLE_OPENCL=OFF -DENABLE_FREETYPE=OFF -DENABLE_PULSE=OFF -DENABLE_DDCUTIL=OFF -DENABLE_ELF=OFF -DENABLE_EET=OFF -DENABLE_THREADS=OFF -DENABLE_IMAGE_LOGO=OFF
- name: build project
run: cmake --build . --target package --verbose -j4
+1 -1
View File
@@ -18,7 +18,7 @@ jobs:
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Start VM
uses: cross-platform-actions/action@faa0c6197e94aacf1c5956460152c8380d3560a5 # v1.5.0
uses: cross-platform-actions/action@e0b9770014ba65d5e0815f15b74031c3a635f641 # v1.6.0
with:
operating_system: omnios
version: 'r151058'
+1 -1
View File
@@ -18,7 +18,7 @@ jobs:
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Start VM
uses: cross-platform-actions/action@faa0c6197e94aacf1c5956460152c8380d3560a5 # v1.5.0
uses: cross-platform-actions/action@e0b9770014ba65d5e0815f15b74031c3a635f641 # v1.6.0
with:
operating_system: openbsd
version: '7.9'
+1 -1
View File
@@ -17,7 +17,7 @@ jobs:
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: run VM
uses: vmactions/solaris-vm@315163f088b66e55bbcc45928bd224d4973b2312 # v1.3.8
uses: vmactions/solaris-vm@a11f407d3720a3717673d4194f19ee63b284977e # v1.4.0
with:
usesh: true
envs: 'CMAKE_BUILD_TYPE'
+1 -1
View File
@@ -116,7 +116,7 @@ jobs:
- if: github.event_name == 'push' && github.repository == 'fastfetch-cli/fastfetch'
name: submit signing request
uses: signpath/github-action-submit-signing-request@c92b958760219087e01f8d67a1669ed57afe2627 # v2.3
uses: signpath/github-action-submit-signing-request@f6d04783b4569d051e0c80105fe66e82819d0092 # v3.0
with:
api-token: '${{ secrets.SIGNPATH_API_TOKEN }}'
organization-id: '${{ vars.SIGNPATH_ORG_ID }}'
+2 -1
View File
@@ -14,4 +14,5 @@ fastfetch.kdev4
*.swp
*.log
/*.zh.md
/.*-ai/
/.work*
/doc/*.md
+94
View File
@@ -1,3 +1,97 @@
# 2.69.0
Changes:
* ImageMagick is no longer used for image logos on Windows, macOS and Android, and has been replaced by the platform image frameworks (WIC on Windows, ImageIO on macOS, AImageDecoder on Android). (Logo)
* An image logo needs Android 11 (API 30), the release that introduced the platform image decoder, and is reported as an error on Android 10 and older.
* ImageMagick 6 support is deprecated. It is kept only for old Debian and Ubuntu releases that don't have ImageMagick 7 available, and is intended to be removed in a future release. Users are encouraged to upgrade to ImageMagick 7 when possible.
* The `--logo-recache` option has been replaced by `--logo-cache <bool|regen>`, and the `logo.recache` JSON property has been renamed to `logo.cache`. (Logo)
* `--logo-cache true` (the default) reuses a cached rendering when it is valid, and writes it back on a cache miss; `false` ignores the image logo cache completely, reading nothing from it and writing nothing to it; `regen` does what `--logo-recache true` used to do. `logo.cache` accepts a boolean, or the string `"regen"`.
* The `waitTime` option of `DiskIO` and `NetIO` now defaults to `250` ms instead of `500`. (DiskIO / NetIO)
* The byte counters are maintained by the kernel as I/O happens, so a shorter sampling window still yields an accurate rate, and both modules now finish about 250 ms sooner. The two modules wait concurrently, so enabling both does not cost twice the wait time.
* The `waitTime` option of `Top` now defaults to `250` ms instead of `500`. (Top)
* The operating system accounts process CPU time in fixed steps, so a window longer than roughly 150 ms does not visibly improve the reported percentages. The module now finishes about 250 ms sooner.
Features:
* Improved image logo support
* Backend rewritten
* Added a native image decoding backend on Windows (WIC), macOS (ImageIO) and Android (AImageDecoder).
* Added an embedded libsixel encoder, used to produce sixel output on Windows, macOS and Android. It is reported by `fastfetch --list-features` as "Embedded sixel".
* Enabled chafa image output on Windows, macOS and Android independently of ImageMagick.
* As a result, `fastfetch --sixel X:\path\to\image` now works out of the box on Windows Terminal.
* Image logo cache entries are now validated against the modification time of the source image, so editing an image logo in place invalidates its cached rendering. (Logo)
* Cache entries written by older versions are not reused, as they carry no modification time.
* Image logos can now be animated when the terminal and the image protocol support it. (Logo)
* `--logo-animation-frame <0>` (`logo.animationFrame: 0` in the JSON config) plays a GIF or APNG. Only the `kitty` image protocol can play an animation; the frames are decoded and composed by fastfetch, so no external program is involved.
* `--logo-animation-frame <N>` renders the Nth frame as a still image, and negative values count back from the end, so `-1` is the last frame. This works for the `sixel`, `kitty` and `chafa` logo types. Note that negative values can only be given in the JSON config, as the command line parser reads a leading `-` as another option.
* The default is `1`, which renders a still image, so nothing changes for anyone who does not opt in. The frames come from the platform image framework (WIC on Windows, ImageIO on macOS, AImageDecoder on Android, ImageMagick 7 on Linux); a single-frame GIF falls back to a still image.
* On Android an animation needs Android 12 (API 31), and the repeat count is not available there, so an animation is reported as looping forever. A build with no image decoder, or one built with ImageMagick 6, reports an error instead of silently showing a still image.
* A terminal that supports the kitty graphics protocol but not its animation frames, such as Konsole, shows the first frame.
* Added the CMake option `ENABLE_IMAGE_LOGO`, which defaults to `ON`. Configure with `-DENABLE_IMAGE_LOGO=OFF` to build fastfetch without any image logo support. (Logo)
* Image logos are the only consumer of ImageMagick, chafa, and the embedded libsixel encoder, so none of the three is searched for at configure time, and no image decoding sources are compiled in. This is intended only to reduce binary size on embedded systems (such as OpenWrt).
* The `sixel`, `kitty`, `kitty-direct`, `kitty-icat`, `iterm` and `chafa` logo types are rejected with an error, both on the command line and in the JSON config, and the `auto` logo type never tries an image.
* `--logo-type raw` keeps working: it passes a pre-rendered byte stream through unchanged and needs no decoder, so a logo can still be displayed by converting the image externally.
* Added CPU name and frequency detection support on SPARC. (CPU, Linux)
* Added package detection support for CRUX. (Packages, Linux)
* Exposed in custom format as `{crux}`.
* Improved Android ROM detection (DE, Android)
* Added support for HarmonyOS, HarmonyOS NEXT, Flyme, JOYUI, SmartisanOS, realme UI, HydrogenOS, ZUI, ZUXOS, MyOS, NebulaAIOS, ObricUI, MiFavor, LineageOS, PixelExperience, EUI and 360 UI.
* Added support for MagicUI 3.x, which stores a bare version number instead of a `MagicUI_x.y.z` string.
* Added Samsung OneUI support (#2541)
* It is read from system properties, so no particular Android version is required. This is mostly untested due to lack of available devices running these ROMs. Please report any issues you encounter.
* Improved Camera detection on Android (Camera, Android)
* The camera list is now read from the camera2 NDK instead of `termux-api CameraInfo`, so the Termux:API app is no longer required and no subprocess is spawned.
* This needs Android 7.0 (API 24), which is where the camera2 NDK was introduced.
* Improved Battery detection on Android (Battery, Android)
* The charge level and charging state are now read from the battery properties service over `/dev/binder` instead of `termux-api BatteryStatus`, so the Termux:API app is no longer required and no subprocess is spawned.
* The service interface changed in Android 10, and the right request is picked at run time, so every Android release is covered.
* Battery temperature, cycle count, manufacturer, model name, serial number and manufacture date need the `BATTERY_STATS` permission, which an app cannot obtain, so an app no longer reports them.
* Running as `adb shell` or as root, `dumpsys battery` is used, which also reports the battery temperature and technology, and reports a battery that has reached the critical level as such. An app can read none of the three.
* Improved Display detection on Android (Display, Android)
* The displays are now read from the display service instead of a vendor property that only some Xiaomi devices set. The preferred mode, the physical size, the rotation, the manufacture date and the display id are now reported as well.
* This needs Android 13 (API 33). On Android 12 and older only that vendor property is available to an app, and a device that does not set it reports no display.
* Running as `adb shell` or as root, `dumpsys display` is used as well, which is what covers Android 12 and older.
* The refresh rate is now the rate of the active display mode, and the HDR capability is read from the display itself, for every display rather than only for the built-in one.
* Improved WiFi detection on Android (Wifi, Android)
* The connection details are now read from the WiFi service over `/dev/binder` instead of `termux-api WifiConnectionInfo`, so no subprocess is spawned.
* The Termux:API app is still required, though. It is what carries the WiFi permission that the Termux app does not request itself, so uninstalling it turns this module off.
* A location permission is required as well, and Termux:API is what carries that one too. The WiFi service withholds the SSID and the BSSID from an app that does not hold one, and hands both over once it is granted; until then the signal, the rates, the frequency, the Wi-Fi standard and the security type are reported as usual, and the two names are reported as `<redacted>`. The grant has to be for all the time rather than only while the app is in use, as the service withholds the two names from an app that is not in the foreground either -- which is the state a run over `ssh` is in.
* The interface name and its state, the connection state, the Wi-Fi standard and the security type are now reported as well.
* The security type is reported from Android 12 on. The reply Android 11 sends ends before that field, so the `security` field stays empty there.
* This needs Android 11 (API 30), the release that moved the Wi-Fi framework into an APEX. There is no fallback, so Android 10 and older report an error instead.
* WiFi detection on Android is experimental. The reply the WiFi service hands an app drifts between Android releases and between vendors, and what it contains also depends on the permissions the calling app holds, so a device can report less than its connection has. Please report anything that looks wrong or missing.
* Improved COSMIC detection (DE / WM, Linux)
* The version is now read from the `COSMIC_VERSION` environment variable when it is set.
* Improved accuracy and performance of process name detection in the Top module. (Top, macOS)
* Improved Packages detection on Windows (Packages, Windows)
* `winget` is now detected by default, instead of requiring a build-time opt-in, and the source agreements are accepted non-interactively on a machine that has never accepted them. Opt out by setting `packages.disabled` to `["winget"]`, or by configuring with `cmake -DPACKAGES_DISABLE_WINGET=ON`.
* The count reports the packages the `winget` source knows about, which is not limited to the packages `winget` itself installed. Microsoft Store apps are no longer counted.
* `winget list` takes about 1.5 seconds, so its result is cached. The cache is refreshed when a program is installed or removed, not on a timer, so only the first run after such a change is slow.
* Improved Wallpaper detection on macOS Sonoma and later (#2559, Wallpaper, macOS)
* The image path is now also extracted from the `Configuration` field of the wallpaper plist, and the `NSWorkspace` fallback is used only as a last resort.
* Removed the `kvm` dependency on OpenBSD by using `sysctl` directly. (General, OpenBSD)
* Modules that were selected on the command line via `--structure` / `-s` now honor module options configured in the JSON config. (CommandOption)
* Improved reliability of fastfetch's built-in HTTP client. (PublicIP, Weather)
* It now supports custom ports and can properly handle chunked transfer encoding. It is designed for minimal resource usage and fast performance, and does not support full HTTP features like HTTPS; the `Command` module with `curl` can be used for those.
* Added Umbriel wayland compositor version detection (WM, Linux)
* Improved the player name detection on Windows to show the name Windows shows for it. (Player, Windows)
* An unpackaged player such as Chrome is now reported as `Google Chrome` instead of `Chrome`.
Bugfixes:
* Fixed Base64 encoding producing incorrect output for some inputs. (General)
* Fixed image logos not working when ImageMagick is built without a quantum depth suffix in its library name, as is the case on FreeBSD. (Logo, FreeBSD)
* Fixed TerminalFont detection on Windows ignoring Windows Terminal JSON fragment files. (#2573, TerminalFont, Windows)
* Fixed 64-bit values being truncated by `strtoul` on platforms where `unsigned long` is 32-bit. (Swap / PhysicalDisk / PhysicalMemory / GPU)
* Fixed read-only SQLite databases failing with `SQLITE_READONLY` when the database directory is not writable. (Packages)
* This fixes PKG package count detection on FreeBSD.
* Fixed `{#keys}` and `{#title}` in module format strings not honoring the `brightColor` display option. (Format)
* Fixed `paddingTop` and `paddingLeft` being ignored by the `kitty-icat` image logo type. (Logo)
* Fixed issues when running on big-endian platforms.
* Some internal cleanups and optimizations.
Logos:
* Added ALT Atomic
* Removed Zerene
# 2.68.1
Changes:
+189 -106
View File
@@ -1,7 +1,7 @@
cmake_minimum_required(VERSION 3.12.0) # Don't change before we investigate why #2553 happens
cmake_minimum_required(VERSION 3.21.0) # C_STANDARD C17 and C23
project(fastfetch
VERSION 2.68.1
VERSION 2.69.0
LANGUAGES C
DESCRIPTION "Fast neofetch-like system information tool"
HOMEPAGE_URL "https://github.com/fastfetch-cli/fastfetch"
@@ -9,9 +9,6 @@ project(fastfetch
set(PROJECT_LICENSE "MIT license")
if(DEFINED CMAKE_SYSTEM_PROCESSOR_OVERRIDE) # Used by github actions for i686 build
set(CMAKE_SYSTEM_PROCESSOR ${CMAKE_SYSTEM_PROCESSOR_OVERRIDE} CACHE INTERNAL "")
endif()
string(TOLOWER "${CMAKE_SYSTEM_PROCESSOR}" CMAKE_SYSTEM_PROCESSOR)
if(CMAKE_SYSTEM_PROCESSOR STREQUAL "x86_64")
set(CMAKE_SYSTEM_PROCESSOR "amd64")
@@ -91,9 +88,6 @@ cmake_dependent_option(ENABLE_EET "Enable eet" ON "LINUX OR FreeBSD OR OpenBSD O
cmake_dependent_option(ENABLE_DBUS "Enable dbus-1" ON "LINUX OR FreeBSD OR OpenBSD OR NetBSD OR ANDROID OR SunOS OR Haiku OR GNU" OFF)
cmake_dependent_option(ENABLE_SQLITE3 "Enable sqlite3" ON "LINUX OR FreeBSD OR APPLE OR OpenBSD OR NetBSD OR SunOS OR GNU" OFF)
cmake_dependent_option(ENABLE_RPM "Enable rpm" ON "LINUX OR GNU" OFF)
cmake_dependent_option(ENABLE_IMAGEMAGICK7 "Enable imagemagick 7" ON "LINUX OR FreeBSD OR OpenBSD OR NetBSD OR APPLE OR ANDROID OR WIN32 OR SunOS OR Haiku OR GNU" OFF)
cmake_dependent_option(ENABLE_IMAGEMAGICK6 "Enable imagemagick 6" ON "LINUX OR FreeBSD OR OpenBSD OR NetBSD OR APPLE OR SunOS OR GNU" OFF)
cmake_dependent_option(ENABLE_CHAFA "Enable chafa" ON "ENABLE_IMAGEMAGICK6 OR ENABLE_IMAGEMAGICK7" OFF)
cmake_dependent_option(ENABLE_EGL "Enable egl" ON "LINUX OR FreeBSD OR OpenBSD OR NetBSD OR ANDROID OR WIN32 OR SunOS OR Haiku OR GNU" OFF)
cmake_dependent_option(ENABLE_GLX "Enable glx" ON "LINUX OR FreeBSD OR OpenBSD OR NetBSD OR ANDROID OR SunOS OR GNU" OFF)
cmake_dependent_option(ENABLE_OPENCL "Enable opencl" ON "LINUX OR FreeBSD OR OpenBSD OR NetBSD OR WIN32 OR ANDROID OR SunOS OR Haiku OR GNU" OFF)
@@ -103,6 +97,14 @@ cmake_dependent_option(ENABLE_DDCUTIL "Enable ddcutil" ON "LINUX" OFF)
cmake_dependent_option(ENABLE_ELF "Enable libelf" ON "LINUX OR ANDROID OR DragonFly OR Haiku OR GNU" OFF)
cmake_dependent_option(ENABLE_THREADS "Enable multithreading" ON "Threads_FOUND" OFF)
option(ENABLE_IMAGE_LOGO "Enable image logos (sixel / kitty / iTerm / chafa)" ON)
if(ENABLE_IMAGE_LOGO)
cmake_dependent_option(ENABLE_IMAGEMAGICK7 "Enable imagemagick 7" ON "LINUX OR FreeBSD OR OpenBSD OR NetBSD OR SunOS OR Haiku OR GNU" OFF)
cmake_dependent_option(ENABLE_IMAGEMAGICK6 "Enable imagemagick 6" ON "LINUX OR FreeBSD OR OpenBSD OR NetBSD OR SunOS OR GNU" OFF)
cmake_dependent_option(ENABLE_SIXEL "Enable sixel logo output via the embedded libsixel encoder (Windows, macOS and Android; replaces ImageMagick's SIXEL coder)" ON "WIN32 OR APPLE OR ANDROID" OFF)
cmake_dependent_option(ENABLE_CHAFA "Enable chafa" ON "ENABLE_IMAGEMAGICK6 OR ENABLE_IMAGEMAGICK7 OR WIN32 OR APPLE OR ANDROID" OFF)
endif()
option(ENABLE_ZLIB "Enable zlib" ON)
option(ENABLE_SYSTEM_YYJSON "Use system provided (instead of fastfetch embedded) yyjson library" OFF)
option(ENABLE_ASAN "Build fastfetch with ASAN (address sanitizer)" OFF)
@@ -128,13 +130,24 @@ if(APPLE)
option(ENABLE_APPLE_MEMSIZE_USABLE "Use usable memory size as total memory size in Memory module, to match other systems" OFF)
endif()
file(GLOB FF_MODULE_DIRS CONFIGURE_DEPENDS RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}/src/modules" "${CMAKE_CURRENT_SOURCE_DIR}/src/modules/*/")
foreach(FF_MODULE_DIR ${FF_MODULE_DIRS})
if(IS_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/src/modules/${FF_MODULE_DIR}")
string(TOUPPER "${FF_MODULE_DIR}" FF_MODULE_UPPER)
option(MODULE_DISABLE_${FF_MODULE_UPPER} "Disable module ${FF_MODULE_DIR}" OFF)
# A module is a directory `src/modules/<module>/` that contains `<module>.c`.
# Globbing the sources rather than the directories skips empty directories and
# other leftovers, and makes `CONFIGURE_DEPENDS` react to added or removed sources.
file(GLOB FF_MODULE_SRCS CONFIGURE_DEPENDS RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}/src/modules" "${CMAKE_CURRENT_SOURCE_DIR}/src/modules/*/*.c")
set(FF_MODULE_DIRS "")
foreach(FF_MODULE_SRC ${FF_MODULE_SRCS})
get_filename_component(FF_MODULE_DIR "${FF_MODULE_SRC}" DIRECTORY)
get_filename_component(FF_MODULE_NAME "${FF_MODULE_SRC}" NAME_WE)
if("${FF_MODULE_DIR}" STREQUAL "${FF_MODULE_NAME}")
list(APPEND FF_MODULE_DIRS "${FF_MODULE_DIR}")
endif()
endforeach()
unset(FF_MODULE_SRCS)
foreach(FF_MODULE_DIR ${FF_MODULE_DIRS})
string(TOUPPER "${FF_MODULE_DIR}" FF_MODULE_UPPER)
option(MODULE_DISABLE_${FF_MODULE_UPPER} "Disable module ${FF_MODULE_DIR}" OFF)
endforeach()
set(BINARY_LINK_TYPE_OPTIONS dlopen dynamic static)
set(BINARY_LINK_TYPE dlopen CACHE STRING "How to link fastfetch")
@@ -148,11 +161,7 @@ string(REGEX MATCHALL "FF_PACKAGES_FLAG_[A-Z]+_BIT" PACKAGE_MANAGERS "${PACKAGE_
string(REGEX REPLACE "FF_PACKAGES_FLAG_([A-Z]+)_BIT" "\\1" PACKAGE_MANAGERS "${PACKAGE_MANAGERS}")
list(SORT PACKAGE_MANAGERS)
foreach(package_manager ${PACKAGE_MANAGERS})
if(package_manager STREQUAL "WINGET")
option(PACKAGES_DISABLE_${package_manager} "Disable ${package_manager} package manager detection by default" ON)
else()
option(PACKAGES_DISABLE_${package_manager} "Disable ${package_manager} package manager detection by default" OFF)
endif()
option(PACKAGES_DISABLE_${package_manager} "Disable ${package_manager} package manager detection by default" OFF)
endforeach()
option(PACKAGES_REMOVE_DISABLED "Remove disabled package managers from the build entirely, instead of just skipping them at runtime" OFF)
@@ -492,92 +501,28 @@ set(LIBFASTFETCH_SRC
src/detection/weather/weather.c
src/detection/zpool/zpool.c
src/logo/builtin.c
src/logo/image/im6.c
src/logo/image/im7.c
src/logo/image/image.c
src/logo/logo.c
src/modules/battery/battery.c
src/modules/bios/bios.c
src/modules/bluetooth/bluetooth.c
src/modules/bluetoothradio/bluetoothradio.c
src/modules/board/board.c
src/modules/bootmgr/bootmgr.c
src/modules/brightness/brightness.c
src/modules/break/break.c
src/modules/btrfs/btrfs.c
src/modules/camera/camera.c
src/modules/chassis/chassis.c
src/modules/codec/codec.c
src/modules/colors/colors.c
src/modules/cpu/cpu.c
src/modules/cpucache/cpucache.c
src/modules/cpuusage/cpuusage.c
src/modules/cursor/cursor.c
src/modules/custom/custom.c
src/modules/command/command.c
src/modules/datetime/datetime.c
src/modules/de/de.c
src/modules/disk/disk.c
src/modules/diskio/diskio.c
src/modules/dns/dns.c
src/modules/editor/editor.c
src/modules/font/font.c
src/modules/gpu/gpu.c
src/modules/host/host.c
src/modules/icons/icons.c
src/modules/initsystem/initsystem.c
src/modules/gamepad/gamepad.c
src/modules/kernel/kernel.c
src/modules/keyboard/keyboard.c
src/modules/lm/lm.c
src/modules/loadavg/loadavg.c
src/modules/locale/locale.c
src/modules/localip/localip.c
src/modules/logo/logo.c
src/modules/memory/memory.c
src/modules/monitor/monitor.c
src/modules/netio/netio.c
src/modules/opencl/opencl.c
src/modules/opengl/opengl.c
src/modules/os/os.c
src/modules/packages/packages.c
src/modules/physicaldisk/physicaldisk.c
src/modules/physicalmemory/physicalmemory.c
src/modules/processes/processes.c
src/modules/player/player.c
src/modules/poweradapter/poweradapter.c
src/modules/publicip/publicip.c
src/modules/display/display.c
src/modules/separator/separator.c
src/modules/shell/shell.c
src/modules/sound/sound.c
src/modules/swap/swap.c
src/modules/media/media.c
src/modules/mouse/mouse.c
src/modules/terminal/terminal.c
src/modules/terminaltheme/terminaltheme.c
src/modules/terminalfont/terminalfont.c
src/modules/terminalsize/terminalsize.c
src/modules/theme/theme.c
src/modules/title/title.c
src/modules/top/top.c
src/modules/tpm/tpm.c
src/modules/uptime/uptime.c
src/modules/users/users.c
src/modules/version/version.c
src/modules/vulkan/vulkan.c
src/modules/wallpaper/wallpaper.c
src/modules/weather/weather.c
src/modules/wifi/wifi.c
src/modules/wm/wm.c
src/modules/wmtheme/wmtheme.c
src/modules/zpool/zpool.c
src/modules/modules.c
src/options/display.c
src/options/logo.c
src/options/general.c
)
if(ENABLE_IMAGE_LOGO)
list(APPEND LIBFASTFETCH_SRC
src/logo/image/image.c
src/logo/image/im6.c
src/logo/image/im7.c
src/logo/image/sixel.c
)
endif()
foreach(FF_MODULE_DIR ${FF_MODULE_DIRS})
list(APPEND LIBFASTFETCH_SRC
src/modules/${FF_MODULE_DIR}/${FF_MODULE_DIR}.c
)
endforeach()
if(LINUX)
list(APPEND LIBFASTFETCH_SRC
src/common/impl/dbus.c
@@ -666,6 +611,8 @@ if(LINUX)
)
elseif(ANDROID)
list(APPEND LIBFASTFETCH_SRC
src/common/android/binder.c
src/common/android/dex.c
src/common/impl/dbus.c
src/common/impl/io_unix.c
src/common/impl/netif_linux.c
@@ -746,6 +693,7 @@ elseif(ANDROID)
src/detection/de/de_linux.c
src/detection/wmtheme/wmtheme_linux.c
src/detection/camera/camera_android.c
src/logo/image/aid.c
)
elseif(FreeBSD)
list(APPEND LIBFASTFETCH_SRC
@@ -1084,6 +1032,11 @@ elseif(APPLE)
src/detection/wmtheme/wmtheme_apple.c
src/detection/camera/camera_apple.m
)
if(ENABLE_IMAGE_LOGO)
list(APPEND LIBFASTFETCH_SRC
src/logo/image/imageio.c
)
endif()
# CMAKE_SYSTEM_PROCESSOR has been normalized before
if(CMAKE_SYSTEM_PROCESSOR STREQUAL "amd64")
list(APPEND LIBFASTFETCH_SRC
@@ -1177,6 +1130,11 @@ elseif(WIN32)
src/detection/wmtheme/wmtheme_windows.c
src/detection/camera/camera_windows.cpp
)
if(ENABLE_IMAGE_LOGO)
list(APPEND LIBFASTFETCH_SRC
src/logo/image/wic.cpp
)
endif()
elseif(SunOS)
list(APPEND LIBFASTFETCH_SRC
src/common/impl/dbus.c
@@ -1480,16 +1438,29 @@ else()
)
endif()
if(ENABLE_SIXEL)
set(FF_SIXEL_SRC
src/3rdparty/sixel/allocator.c
src/3rdparty/sixel/dither.c
src/3rdparty/sixel/output.c
src/3rdparty/sixel/pixelformat.c
src/3rdparty/sixel/quant.c
src/3rdparty/sixel/status.c
src/3rdparty/sixel/tosixel.c
)
list(APPEND LIBFASTFETCH_SRC ${FF_SIXEL_SRC})
set_source_files_properties(${FF_SIXEL_SRC} PROPERTIES COMPILE_OPTIONS "-Wno-conversion")
endif()
add_library(libfastfetch OBJECT
${LIBFASTFETCH_SRC}
)
foreach(FF_MODULE_DIR ${FF_MODULE_DIRS})
if(IS_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/src/modules/${FF_MODULE_DIR}")
string(TOUPPER "${FF_MODULE_DIR}" FF_MODULE_UPPER)
if(MODULE_DISABLE_${FF_MODULE_UPPER})
target_compile_definitions(libfastfetch PUBLIC FF_MODULE_DISABLE_${FF_MODULE_UPPER}=1)
endif()
string(TOUPPER "${FF_MODULE_DIR}" FF_MODULE_UPPER)
if(MODULE_DISABLE_${FF_MODULE_UPPER})
target_compile_definitions(libfastfetch PUBLIC FF_MODULE_DISABLE_${FF_MODULE_UPPER}=1)
endif()
endforeach()
@@ -1522,10 +1493,11 @@ if(yyjson_FOUND)
# `target_link_libraries(yyjson::yyjson)` sets rpath implicitly
endif()
# Used for dlopen finding dylibs installed by homebrew
# `/opt/homebrew/lib` is not on in dlopen search path by default
# Used for dlopen finding dylibs installed by package managers
# `/opt/homebrew/lib`, `/usr/local/lib` and `/opt/local/lib` are not on the
# dlopen search path by default
if(APPLE AND BINARY_LINK_TYPE STREQUAL "dlopen")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,-rpath,/opt/homebrew/lib -Wl,-rpath,/usr/local/lib")
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,-rpath,/opt/homebrew/lib -Wl,-rpath,/usr/local/lib -Wl,-rpath,/opt/local/lib")
endif()
if(ANDROID)
@@ -1890,6 +1862,10 @@ if(ENABLE_THREADS)
endif()
endif()
if(ENABLE_IMAGE_LOGO)
target_compile_definitions(libfastfetch PUBLIC FF_HAVE_IMAGE_LOGO=1)
endif()
if(ENABLE_EMBEDDED_PCIIDS)
target_compile_definitions(libfastfetch PUBLIC FF_HAVE_EMBEDDED_PCIIDS=1)
endif()
@@ -1932,6 +1908,8 @@ elseif(APPLE)
PRIVATE "-framework CoreAudio"
PRIVATE "-framework CoreMedia"
PRIVATE "-framework CoreVideo"
PRIVATE "-framework ImageIO"
PRIVATE "-framework Accelerate"
PRIVATE "-framework CoreWLAN"
PRIVATE "-framework IOBluetooth"
PRIVATE "-framework IOKit"
@@ -1960,6 +1938,8 @@ elseif(WIN32)
PRIVATE "cfgmgr32"
PRIVATE "winbrand"
PRIVATE "secur32"
PRIVATE "shlwapi"
PRIVATE "windowscodecs"
)
if(NOT ENABLE_WIN81_COMPAT)
target_link_libraries(libfastfetch
@@ -1994,7 +1974,6 @@ elseif(FreeBSD)
elseif(OpenBSD)
target_link_libraries(libfastfetch
PRIVATE "m"
PRIVATE "kvm"
PRIVATE "sndio"
PRIVATE "util"
)
@@ -2021,6 +2000,9 @@ elseif(GNU)
elseif(ANDROID)
target_link_libraries(libfastfetch
PRIVATE "m"
PRIVATE jnigraphics
PRIVATE mediandk
PRIVATE camera2ndk
)
if(ENABLE_WORDEXP)
# https://github.com/termux/termux-packages/pull/7056
@@ -2038,6 +2020,17 @@ elseif(ANDROID)
endif()
endif()
endif()
# Both APIs (AImageDecoder, AMediaCodec) are newer than the API level this build targets --
# AImageDecoder is 30, and AMediaCodec_getName / AMediaCodec_releaseName are 28 -- while fastfetch
# keeps running on devices below those levels. The NDK headers mark the entry points unavailable, so
# they have to be weak references: otherwise the executable would fail to load on an older device.
# Guarding every use with __builtin_available() is what makes that safe, and turning the guard
# diagnostic into an error is what keeps a use from slipping past it.
set_source_files_properties(
${CMAKE_CURRENT_SOURCE_DIR}/src/logo/image/aid.c
${CMAKE_CURRENT_SOURCE_DIR}/src/detection/codec/codec_android.c
PROPERTIES COMPILE_OPTIONS "-D__ANDROID_UNAVAILABLE_SYMBOLS_ARE_WEAK__;-Werror=unguarded-availability")
elseif(Haiku)
target_link_libraries(libfastfetch
PRIVATE "network"
@@ -2057,6 +2050,16 @@ target_include_directories(libfastfetch
PUBLIC ${PROJECT_SOURCE_DIR}/src
)
if(ENABLE_SIXEL)
# src/3rdparty/sixel/*.c include <sixel.h> (angle brackets, so the directory itself
# has to be on the include path)
target_include_directories(libfastfetch PRIVATE ${PROJECT_SOURCE_DIR}/src/3rdparty/sixel)
# The vendored subset is not a library to be detected, so FF_HAVE_SIXEL can't come
# from ff_lib_enable() and has to be defined here
target_compile_definitions(libfastfetch PUBLIC FF_HAVE_SIXEL=1)
endif()
target_link_libraries(libfastfetch
PRIVATE ${CMAKE_DL_LIBS}
)
@@ -2236,6 +2239,76 @@ if (BUILD_TESTS)
PRIVATE libfastfetch
)
add_executable(fastfetch-test-networking
tests/networking.c
)
target_link_libraries(fastfetch-test-networking
PRIVATE libfastfetch
)
add_executable(fastfetch-test-base64
tests/base64.c
)
target_link_libraries(fastfetch-test-base64
PRIVATE libfastfetch
)
add_executable(fastfetch-test-parsing
tests/parsing.c
)
target_link_libraries(fastfetch-test-parsing
PRIVATE libfastfetch
)
add_executable(fastfetch-test-properties
tests/properties.c
)
target_link_libraries(fastfetch-test-properties
PRIVATE libfastfetch
)
add_executable(fastfetch-test-size
tests/size.c
)
target_link_libraries(fastfetch-test-size
PRIVATE libfastfetch
)
add_executable(fastfetch-test-frequency
tests/frequency.c
)
target_link_libraries(fastfetch-test-frequency
PRIVATE libfastfetch
)
add_executable(fastfetch-test-percent
tests/percent.c
)
target_link_libraries(fastfetch-test-percent
PRIVATE libfastfetch
)
add_executable(fastfetch-test-temps
tests/temps.c
)
target_link_libraries(fastfetch-test-temps
PRIVATE libfastfetch
)
add_executable(fastfetch-test-endian
tests/endian.c
)
target_link_libraries(fastfetch-test-endian
PRIVATE libfastfetch
)
add_executable(fastfetch-test-endian-bigendian
tests/endian-bigendian.c
)
target_link_libraries(fastfetch-test-endian-bigendian
PRIVATE libfastfetch
)
enable_testing()
add_test(NAME test-strbuf COMMAND fastfetch-test-strbuf)
add_test(NAME test-list COMMAND fastfetch-test-list)
@@ -2243,6 +2316,16 @@ if (BUILD_TESTS)
add_test(NAME test-color COMMAND fastfetch-test-color)
add_test(NAME test-duration COMMAND fastfetch-test-duration)
add_test(NAME test-strutil COMMAND fastfetch-test-strutil)
add_test(NAME test-networking COMMAND fastfetch-test-networking)
add_test(NAME test-base64 COMMAND fastfetch-test-base64)
add_test(NAME test-parsing COMMAND fastfetch-test-parsing)
add_test(NAME test-properties COMMAND fastfetch-test-properties)
add_test(NAME test-size COMMAND fastfetch-test-size)
add_test(NAME test-frequency COMMAND fastfetch-test-frequency)
add_test(NAME test-percent COMMAND fastfetch-test-percent)
add_test(NAME test-temps COMMAND fastfetch-test-temps)
add_test(NAME test-endian COMMAND fastfetch-test-endian)
add_test(NAME test-endian-bigendian COMMAND fastfetch-test-endian-bigendian)
endif()
##################
+144 -71
View File
@@ -2,15 +2,15 @@
<details>
<summary>
Note
Disclaimer
</summary>
This document is generated by AI, and mainly for AI use. It is not a substitute for human review, and may contain errors or omissions. Please verify any information before relying on it.
This document is generated by AI and reviewed by humans. It is primarily intended for AI-assisted development, while remaining useful to human developers.
</details>
Thanks for your interest in fastfetch. This document covers building, architecture, how to add a module or a logo, code style, commit conventions, and the pull request workflow.
Thank you for your interest in fastfetch. This document covers building, architecture, how to add a module or a logo, code style, commit conventions, and the pull request workflow.
fastfetch is a system information tool written in C23, supporting Linux, macOS, Windows, the BSDs, Solaris, Haiku and Android. The project is borderline obsessive about **startup time** and **optional dependencies** — many design decisions only make sense under that constraint, and this document keeps coming back to it.
fastfetch is a system information tool written in C23, supporting Linux, macOS, Windows, the BSDs, Solaris, Haiku and Android. The project places strong emphasis on **startup time** and on keeping **dependencies optional**; many design decisions only make sense under that constraint, and this document returns to it repeatedly.
---
@@ -29,7 +29,7 @@ fastfetch is a system information tool written in C23, supporting Linux, macOS,
- [Changelog](#changelog)
- [Tests](#tests)
- [Pull requests](#pull-requests)
- [Gotchas](#gotchas)
- [Pitfalls](#pitfalls)
---
@@ -38,14 +38,14 @@ fastfetch is a system information tool written in C23, supporting Linux, macOS,
| Task | Start here | Verify with |
|---|---|---|
| Build and run fastfetch | `run.sh`, `CMakeLists.txt` | `./run.sh` |
| Add a module | `src/modules/<name>/`, `src/detection/<name>/`, `src/modules/modules.c` | `cmake -B build && cmake --build build -j` |
| Add a platform implementation | `src/detection/<name>/<name>_<platform>.c` | Build on the target platform or CI |
| Add a module | `src/modules/<name>/`, `src/detection/<name>/`, `src/modules/modules.c`, `CMakeLists.txt` | `cmake -B build && cmake --build build -j` |
| Add a platform implementation | `src/detection/<name>/<name>_<platform>.c`, the matching platform block in `CMakeLists.txt` | Build on the target platform or CI |
| Add an ASCII logo | `src/logo/ascii/<letter>/<name>.txt`, matching `<letter>.inc` | `./build/fastfetch --logo <name>` |
| Change formatting or JSON output | `src/modules/<name>/<name>.c` | `./build/fastfetch -s <name> --format json` |
| Change shared formatting or containers | `src/common/format.h`, `src/common/color.h`, `src/common/FFstrbuf.h` | Build and run the matching test |
| Run the test suite | `tests/`, `build/` | `cd build && ctest --output-on-failure` |
For a normal code change, the shortest useful loop is: configure, build the `fastfetch` target, run the affected module, then run the tests. If you add a directory or a generated input, re-run `cmake -B build` so CMake refreshes its file globs.
For a typical code change, the shortest useful iteration is: configure, build the `fastfetch` target, run the affected module, then run the tests. If you add a directory or a generated input, re-run `cmake -B build` so that CMake refreshes its file globs.
---
@@ -53,7 +53,7 @@ For a normal code change, the shortest useful loop is: configure, build the `fas
### Building
The quickest way is `run.sh` in the repository root — it creates `build/`, configures, compiles and runs the binary:
The quickest way is `run.sh` in the repository root: it creates `build/`, configures, compiles and runs the binary.
```sh
./run.sh # build and run
@@ -68,7 +68,7 @@ cmake --build build --target fastfetch -j$(nproc)
./build/fastfetch
```
The default build type is `RelWithDebInfo`. LTO is enabled whenever `ENABLE_LTO=ON` **and** `CMAKE_BUILD_TYPE != Debug` — so the default already has it, and only `Debug` builds lack it. This matters because LTO here is not merely an optimization: it is what strips the code of disabled modules. See [Gotchas](#gotchas).
The default build type is `RelWithDebInfo`. LTO is enabled whenever `ENABLE_LTO=ON` **and** `CMAKE_BUILD_TYPE != Debug`, so the default configuration enables it and only `Debug` builds omit it. This is significant because LTO here is not merely an optimization: it is what removes the code of disabled modules. See [Pitfalls](#pitfalls).
### Common build options
@@ -123,12 +123,12 @@ fastfetch.c → options/ (global configuration)
→ common/ (infrastructure)
```
The number of module directories and detection directories does not match, and that is expected. The following relationships are structural rather than a fixed inventory:
The number of module directories does not match the number of detection directories, which is expected. The following relationships are structural rather than a fixed inventory:
- **13 modules have no detection directory** — they are either pure layout (`break`, `separator`, `colors`, `title`, `logo`) or reuse someone else's detection result (`display`, `monitor`, `kernel`, `shell`, `terminal`, `player`, `custom`, `datetime`).
- **13 modules have no detection directory** — they are either pure layout (`break`, `separator`, `colors`, `title`, `logo`) or reuse another module's detection result (`display`, `monitor`, `kernel`, `shell`, `terminal`, `player`, `custom`, `datetime`).
- **4 detection directories serve modules with different names** — `displayserver` (→ `display`, `monitor`), `gtk_qt` (→ `theme`, `icons`, `font`, `cursor`), `terminalshell` (→ `terminal`, `shell`) and `libc`.
So do not assume `modules/<x>/` always has a matching `detection/<x>/`.
Therefore, do not assume that `modules/<x>/` always has a matching `detection/<x>/`.
### Layer boundaries
@@ -139,13 +139,13 @@ So do not assume `modules/<x>/` always has a matching `detection/<x>/`.
| `detection/` | cross-platform data retrieval, clean result structs | print anything, read display config |
| `common/` | general-purpose utilities, no business logic | depend on a specific module |
The test is simple: **no file under `detection/` should contain `printf` or read `instance.config`.** Symmetrically, no file under `modules/` should contain `#ifdef __linux__`.
A simple check: **no file under `detection/` should contain `printf` or read `instance.config`.** Symmetrically, no file under `modules/` should contain `#ifdef __linux__`.
---
## Core architecture: modules vs. detection
This is the single most important convention in the codebase. Every feature is a fixed set of files — using CPU as the example:
This is the most important convention in the codebase. Every feature consists of a fixed set of files; using CPU as the example:
```
modules/cpu/option.h module option struct
@@ -158,7 +158,7 @@ detection/cpu/cpu_bsd.c │
detection/cpu/cpu_nosupport.c ┘
```
The interface is deliberately minimal — usually just two things:
The interface is deliberately minimal, typically consisting of only two declarations:
```c
typedef struct FFCPUResult { ... } FFCPUResult; // result struct
@@ -169,7 +169,7 @@ The `const char*` return value is an **error string**; `nullptr` means success.
Helper functions are only exposed when they are genuinely shared between platform implementations (as in `cpu.h`: `ffCPUAppleCodeToName`, `ffCPUDetectByCpuid`).
**The payoff:** adding a platform never touches `modules/`; fixing output formatting never touches `detection/`.
**The benefit of this separation:** adding a platform never touches `modules/`; fixing output formatting never touches `detection/`.
---
@@ -197,7 +197,7 @@ typedef struct FFModuleBaseInfo {
} FFModuleBaseInfo;
```
The source comment openly admits this is UB — `void*` is not compatible with `FF*Options*`. It is a pragmatic compromise to get polymorphism in C. Don't try to "fix" it.
The source comment acknowledges that this is undefined behavior, since `void*` is not compatible with `FF*Options*`. It is a pragmatic compromise to obtain polymorphism in C; do not attempt to "fix" it.
### The registry: a first-letter hash bucket
@@ -210,7 +210,7 @@ for (; *modules; ++modules) { // linear s
}
```
The registry is small enough that a subtraction plus a few string comparisons is preferable to a general-purpose hash table. When adding a module, place its descriptor in the bucket matching the first letter of `.name`; keep the existing `nullptr` terminator at the end.
Because the registry is small, a single arithmetic bucket lookup followed by a few string comparisons is preferable to a general-purpose hash table. When adding a module, place its descriptor in the bucket matching the first letter of `.name`, and keep the existing `nullptr` terminator at the end.
### The calling convention: zero heap allocation
@@ -230,7 +230,7 @@ baseInfo->destroyOptions(optionBuf);
static_assert(sizeof(FFCPUOptions) <= FF_OPTION_MAX_SIZE, "FFCPUOptions size exceeds maximum allowed size");
```
**Meaning: no module option struct may exceed 256 bytes.** Hard constraint, enforced at compile time.
**In other words, no module option struct may exceed 256 bytes.** This is a hard constraint, enforced at compile time.
The three dispatch entry points:
@@ -238,20 +238,49 @@ The three dispatch entry points:
|---|---|---|
| `parseModuleJsonObject` | `common/impl/jsonconfig.c:90` | the `modules[]` array in a JSONC config |
| `parseStructureCommand` | `common/impl/commandoption.c:181` | the colon-separated structure string |
| `ffParseModuleOptions` | `common/impl/commandoption.c:13` | **deprecated** — see [Gotchas](#4-cli-module-options-are-removed) |
### Build-time module discovery
`CMakeLists.txt:131` globs `src/modules/*/` and generates a `MODULE_DISABLE_<UPPER>` option per directory:
`CMakeLists.txt:134` globs `src/modules/*/*.c`, keeps only the entries whose file name matches their directory name, and generates a `MODULE_DISABLE_<UPPER>` option for each:
```cmake
file(GLOB FF_MODULE_DIRS RELATIVE "..." ".../src/modules/*/")
file(GLOB FF_MODULE_SRCS CONFIGURE_DEPENDS RELATIVE "..." ".../src/modules/*/*.c")
set(FF_MODULE_DIRS "")
foreach(FF_MODULE_SRC ${FF_MODULE_SRCS})
get_filename_component(FF_MODULE_DIR "${FF_MODULE_SRC}" DIRECTORY)
get_filename_component(FF_MODULE_NAME "${FF_MODULE_SRC}" NAME_WE)
if("${FF_MODULE_DIR}" STREQUAL "${FF_MODULE_NAME}")
list(APPEND FF_MODULE_DIRS "${FF_MODULE_DIR}")
endif()
endforeach()
foreach(FF_MODULE_DIR ${FF_MODULE_DIRS})
string(TOUPPER "${FF_MODULE_DIR}" FF_MODULE_UPPER)
option(MODULE_DISABLE_${FF_MODULE_UPPER} "Disable module ${FF_MODULE_DIR}" OFF)
endforeach()
```
**Adding a module requires no CMake change.** The same trick generates the package manager switches (`:146` regex-scans `src/modules/packages/option.h` for `FF_PACKAGES_FLAG_*_BIT`).
Because the glob matches sources rather than directories, a directory counts as a module only when `src/modules/<name>/<name>.c` exists. Empty directories — which git does not track, so they are easy to leave behind — and stray files are ignored instead of breaking the configure step with `Cannot find source file`.
### Module sources are discovered automatically
`FF_MODULE_DIRS` also drives the source list (`CMakeLists.txt:516`):
```cmake
foreach(FF_MODULE_DIR ${FF_MODULE_DIRS})
list(APPEND LIBFASTFETCH_SRC
src/modules/${FF_MODULE_DIR}/${FF_MODULE_DIR}.c
)
endforeach()
```
Consequences:
- `src/modules/<name>/<name>.c` is compiled as soon as the file exists — **there is no source list to edit for the module layer**.
- The file name must match the directory name. A directory whose `.c` file is named differently, or has none at all, is silently not a module: a typo therefore shows up as a module missing from `fastfetch --list-modules`, not as a build error.
- The glob uses `CONFIGURE_DEPENDS`, so with the Makefile and Ninja generators the build re-evaluates it and re-runs CMake when a module source is added or removed. With other generators, or to be safe, re-run `cmake -B build` explicitly.
Only the module layer is automated. Sources under `src/detection/` and `src/common/impl/` are **not** globbed and must still be listed by hand — see [step 5](#5-add-the-platform-sources-to-cmakeliststxt).
---
@@ -276,9 +305,7 @@ typedef struct FFFooOptions {
static_assert(sizeof(FFFooOptions) <= FF_OPTION_MAX_SIZE, "FFFooOptions size exceeds maximum allowed size");
```
`FFModuleArgs` must come first. It provides `key`, `format`, `outputColor`, `keyColor`, `keyIcon` and `keyWidth`; because it is the first field, `ffJsonConfigParseModuleArgs()` can handle these generically and you get them **for free — no parsing code to write**.
Note these fields can only be set through the JSON config; CLI module options have been removed (see [Gotchas](#4-cli-module-options-are-removed)).
`FFModuleArgs` must come first. It provides `key`, `format`, `outputColor`, `keyColor`, `keyIcon` and `keyWidth`; because it is the first field, `ffJsonConfigParseModuleArgs()` handles these generically, **so no parsing code is required**.
### 2. Implement detection
@@ -307,7 +334,7 @@ const char* ffDetectFoo(const FFFooOptions* options, FFFooResult* result) {
}
```
**Write one file per target platform, and a `foo_nosupport.c` fallback for the rest.** There are already 45 `*_nosupport.c` files doing exactly this.
**Write one file per target platform, plus a `foo_nosupport.c` fallback for the remaining platforms.** The repository currently contains 45 `*_nosupport.c` files serving this purpose.
### 3. Implement the module
@@ -339,11 +366,11 @@ FFModuleBaseInfo ffFooModuleInfo = {
Points to note:
- **`displayName`** is a literal block of all 20 language fields — there is no shortcut macro, so copy the layout from a neighboring module: **`en`, `ar`, `cs`, `de`, `es`, `fr`, `gl`, `he`, `id`, `it`, `ja`, `ko`, `pl`, `pt`, `ru`, `tr`, `uk`, `vi`, `zh_CN`, `zh_TW`**.
**Fill in all 20.** The struct is read by byte offset (see [Gotchas](#6-localization-uses-byte-offsets-not-enums)) and there is **no fallback** — a missing field means the key prints empty in that language.
- **`formatArgs`** must be exhaustive. It drives the placeholder list printed by `fastfetch -h foo-format`; **anything you omit is invisible and unusable to the user.**
- **`displayName`** is a literal block of all 20 language fields; there is no shortcut macro, so copy the layout from an existing module: **`en`, `ar`, `cs`, `de`, `es`, `fr`, `gl`, `he`, `id`, `it`, `ja`, `ko`, `pl`, `pt`, `ru`, `tr`, `uk`, `vi`, `zh_CN`, `zh_TW`**.
**Fill in all 20.** The struct is read by byte offset (see [Pitfalls](#6-localization-uses-byte-offsets-not-enums)) and there is **no fallback** — a missing field means the key prints empty in that language.
- **`formatArgs`** must be exhaustive. It drives the placeholder list printed by `fastfetch -h foo-format`; **any placeholder omitted here is neither listed nor usable by the user.**
- The `moduleFormat` section in `doc/json_schema.json` is generated by `fastfetch -h format-json`. Its metadata comes from `FFModuleBaseInfo::formatArgs`. To keep the schema and module descriptors consistent, do not edit the `moduleFormat` section in `doc/json_schema.json` by hand; update the module metadata and regenerate it instead.
- **`defaultOrder`**: use the current maximum plus 1. Search the existing descriptors for `.defaultOrder =` before choosing a value; do not copy a hard-coded value from this document. Leaving it out, or setting it to `0`, makes the module **disappear** from the interactive `--gen-config` picker. Only `logo`, `command` and `custom` do this deliberately, because they need user arguments or are invoked directly by the display layer.
- **`defaultOrder`**: use the current maximum plus 1. Search the existing descriptors for `.defaultOrder =` before choosing a value; do not copy a hard-coded value from this document. Leaving it out, or setting it to `0`, excludes the module from the interactive `--gen-config` picker. Only `logo`, `command` and `custom` rely on this behavior, because they require user arguments or are invoked directly by the display layer.
### 4. Register it
@@ -358,11 +385,46 @@ Points to note:
`FF_MODULE_DISABLE_FOO` is generated by CMake — you do not define it yourself.
### 5. Modules that need warm-up
### 5. Add the platform sources to `CMakeLists.txt`
If your module needs a sampling interval (CPU usage) or a network round-trip (public IP, weather), also implement `ffPrepareFoo()` and register it in the switch inside `ffPrepareCommandOption()` in `common/impl/commandoption.c`, under the right first-letter `case`. Six modules do this today: CPUUsage, DiskIO, NetIO, PublicIP, Top and Weather.
The module layer is discovered by glob (see [Build-time module discovery](#module-sources-are-discovered-automatically)), **but `src/detection/**` and `src/common/impl/**` are not**. `CMakeLists.txt` lists them explicitly, inside one mutually exclusive chain of platform blocks:
### 6. Verify
| Block | Line | Covers |
|---|---|---|
| `if(LINUX)` | `CMakeLists.txt:522` | Linux |
| `elseif(ANDROID)` | `CMakeLists.txt:608` | Android (Termux) |
| `elseif(FreeBSD)` | `CMakeLists.txt:691` | FreeBSD, MidnightBSD, DragonFly |
| `elseif(NetBSD)` | `CMakeLists.txt:788` | NetBSD |
| `elseif(OpenBSD)` | `CMakeLists.txt:872` | OpenBSD |
| `elseif(APPLE)` | `CMakeLists.txt:959` | macOS / iOS |
| `elseif(WIN32)` | `CMakeLists.txt:1046` | Windows |
| `elseif(SunOS)` | `CMakeLists.txt:1121` | Solaris / illumos |
| `elseif(Haiku)` | `CMakeLists.txt:1204` | Haiku |
| `elseif(GNU)` | `CMakeLists.txt:1282` | GNU/Hurd |
Add the platform implementation to every block whose platform it supports, and `foo_nosupport.c` to every remaining block, so that all ten platforms still link:
```cmake
elseif(FreeBSD)
list(APPEND LIBFASTFETCH_SRC
...
src/detection/foo/foo_bsd.c
)
```
Points to note:
- Exactly one block is compiled per build, so a file omitted from a block does not exist for that platform, and the link fails with an undefined reference to `ffDetectFoo()` — **on that platform only**. A missing entry therefore builds fine locally and fails in CI; this is why every block must be covered.
- A platform may reuse another platform's implementation instead of a stub. `src/common/impl/networking_linux.c`, for example, is listed in nine of the ten blocks (all but `WIN32`). Check where the closest sibling module points before adding a new file.
- `DragonFly` is handled by the inner `if(DragonFly)` sub-block inside the FreeBSD block (`CMakeLists.txt:773`); add the variant there, as `processes`, `top` and `wifi` do.
- New helpers under `src/common/impl/` follow the same rule: they are not globbed, and each block that needs one must list it.
- A few files are appended outside the platform chain because they depend on an option or on a specific feature — for example the proprietary GPU backends (`CMakeLists.txt:1379`) and `src/common/impl/wcwidth.c` (`CMakeLists.txt:1408`). Those are written by hand as well.
### 6. Modules that need warm-up
If your module needs a sampling interval (CPU usage) or a network round-trip (public IP, weather), also implement `ffPrepareFoo()` and register it in the switch inside `ffPrepareCommandOption()` in `common/impl/commandoption.c`, under the matching first-letter `case`. Six modules currently do this: CPUUsage, DiskIO, NetIO, PublicIP, Top and Weather.
### 7. Verify
```sh
cmake -B build && cmake --build build -j
@@ -371,7 +433,9 @@ cmake -B build && cmake --build build -j
./build/fastfetch --gen-config # confirm it appears in the picker
```
Note the `-format` suffix on the help flag: `fastfetch -h foo` does not work, only `fastfetch -h foo-format`.
Note the `-format` suffix on the help flag: `fastfetch -h foo` is not supported; only `fastfetch -h foo-format` works.
If you added detection sources, re-check [step 5](#5-add-the-platform-sources-to-cmakeliststxt) before pushing: a platform block you missed compiles fine locally and fails only when that platform is built.
---
@@ -379,13 +443,13 @@ Note the `-format` suffix on the help flag: `fastfetch -h foo` does not work, on
A new logo **must** have a corresponding "Logo Request" issue, linked from the PR with `Closes #1234`. Logo PRs without a linked issue are not accepted.
### 1. Drop in the ASCII file
### 1. Add the ASCII file
```
src/logo/ascii/<first-letter>/<distro>.txt
```
For example `src/logo/ascii/o/omarchy.txt`. Directories are already split by first letter (`a/` … `z/`, plus `_/`).
For example `src/logo/ascii/d/distro.txt`. Directories are already split by first letter (`a/` … `z/`, plus `_/`).
The file is plain ASCII art with `$1` … `$9` as color placeholders:
@@ -395,26 +459,29 @@ $3 /\\\///
$2refined.$1 /\\\\//
```
- `$1` … `$9` map to palette slots 1–9; at most 9 (`FASTFETCH_LOGO_MAX_COLORS = 9`)
- `$1` … `$9` map to palette slots 1–9; at most 9 are supported (`FASTFETCH_LOGO_MAX_COLORS = 9`)
- `$$` is a literal `$`
- Characters without a placeholder inherit the current color. Of the 530 existing logos, 239 use no placeholders at all (monochrome) and 291 do — **new logos should use placeholders**; monochrome is a legacy style
- Characters without a placeholder inherit the current color. Of the 530 existing logos, 239 use no placeholders at all (monochrome) and 291 do; **new logos should use placeholders**, as monochrome is a legacy style
- Tabs are expanded to 4 spaces
- Colors can be overridden with `--logo-color-1` … `--logo-color-9`
### 2. Register it in the `.inc`
CMake turns each `.txt` into a `FASTFETCH_DATATEXT_LOGO_<UPPERCASE>` macro (`CMakeLists.txt:418`), but **the registry itself is maintained by hand**. Edit `src/logo/ascii/<first-letter>.inc`:
CMake turns each `.txt` file into a `FASTFETCH_DATATEXT_LOGO_<UPPERCASE>` macro (`CMakeLists.txt:418`), but **the registry itself is maintained by hand**. Edit `src/logo/ascii/<first-letter>.inc`:
```c
#ifdef FASTFETCH_DATATEXT_LOGO_OMARCHY
// Omarchy
// src/logo/ascii/d.inc
#ifdef FASTFETCH_DATATEXT_LOGO_DISTRO
// Distro
{
.names = { "omarchy", "Omarchy" },
.lines = FASTFETCH_DATATEXT_LOGO_OMARCHY,
.names = { "Distro" }, // ID (preferred) or NAME from /etc/os-release, do NOT add both
.lines = FASTFETCH_DATATEXT_LOGO_DISTRO,
.colors = {
FF_COLOR_FG_BLUE,
FF_COLOR_FG_WHITE,
FF_COLOR_FG_CYAN,
FF_COLOR_FG_PRIMARY, // recommended for using as WHITE replacement, light-theme terminal friendly
FF_COLOR_FG_BLUE, // preferred
FF_COLOR_FG_256 "34",
FF_COLOR_FG_RGB "0;255;0", // not recommended because of bad compatibility with raw TTY
},
},
#endif
@@ -431,13 +498,13 @@ If the same OS has multiple logo variants, mark the variant explicitly with `.ty
.type = FF_LOGO_LINE_TYPE_SMALL_BIT,
```
Use `FF_LOGO_LINE_TYPE_ALTER_BIT` for an alternate logo, `FF_LOGO_LINE_TYPE_SMALL_BIT` for a small logo, or combine the flags when both apply. This is also a lookup optimization: a logo marked `FF_LOGO_LINE_TYPE_SMALL_BIT` is considered only for `type = small`, while a logo marked `FF_LOGO_LINE_TYPE_ALTER_BIT` is never selected by automatic detection. Alternate logos are available only when explicitly requested through `--logo <source>`.
Use `FF_LOGO_LINE_TYPE_ALTER_BIT` for an alternate logo, `FF_LOGO_LINE_TYPE_SMALL_BIT` for a small logo, or combine the flags when both apply. This is also a lookup optimization: a logo marked `FF_LOGO_LINE_TYPE_SMALL_BIT` is considered only for `type = small`, while a logo marked `FF_LOGO_LINE_TYPE_ALTER_BIT` is never selected by automatic detection. Alternate logos are available only when explicitly requested through `-l <source>`.
### 3. Verify
```sh
./build/fastfetch --logo omarchy
./build/fastfetch --list-logos | grep -i omarchy
./build/fastfetch -l distro
./build/fastfetch --list-logos | grep -i distro
```
---
@@ -474,9 +541,9 @@ Current distribution of platform files in `detection/`:
(These are repository inventory figures, counting `.c`, `.m`, `.cpp`, and `.h`; they may change as platforms and modules are added.)
**Don't pile `#ifdef __linux__` into one file.** When adding platform support, copy the closest existing implementation and change the suffix.
**Do not accumulate `#ifdef __linux__` blocks in a single file.** When adding platform support, copy the closest existing implementation and change the suffix.
`common/` uses the same idea: `common/impl/` contains `io_unix.c` / `io_windows.c`, `netif_linux.c` / `netif_apple.c` / `netif_bsd.c` and so on, with `common/apple/`, `common/windows/` and `common/haiku/` holding platform-specific helpers.
`common/` follows the same convention: `common/impl/` contains `io_unix.c` / `io_windows.c`, `netif_linux.c` / `netif_apple.c` / `netif_bsd.c` and similar files, with `common/apple/`, `common/windows/` and `common/haiku/` holding platform-specific helpers.
When several platform suffixes could apply, use the most specific implementation supported by the build system (for example, `_nbsd.c` instead of the generic `_bsd.c` on NetBSD). Keep the generic file as the fallback for platforms that share its conventions.
@@ -507,7 +574,7 @@ clang-format -i src/modules/foo/*.c src/modules/foo/*.h
`src/3rdparty/**`, `build/**` and `src/logo/builtin.c` are listed in `.clang-format-ignore` — **do not reformat them.**
`.editorconfig` adds LF line endings, 4-space indent, a final newline, and trailing whitespace trimmed (except in Markdown).
`.editorconfig` specifies LF line endings, a 4-space indent, a final newline, and trailing whitespace trimmed (except in Markdown).
### Naming
@@ -522,7 +589,7 @@ clang-format -i src/modules/foo/*.c src/modules/foo/*.h
### Spelling
CI runs codespell (`.codespellrc`). Known false positives live in `ignore-words-list` (`iterm`, `compiletime`, and various non-English distro words). Add new words there rather than changing the code.
CI runs codespell (`.codespellrc`). Known false positives are listed in `ignore-words-list` (`iterm`, `compiletime`, and various non-English distro words). Add new words there rather than changing the code.
### Compiler warnings
@@ -566,7 +633,7 @@ Common verbs: `adds`, `removes`, `fixes`, `improves`, `updates`, `corrects`, `pr
Scopes in use: `Top`, `Processes`, `Memory`, `Logo (Builtin)`, `CI`, `Doc`, `Presets`, `Global`, plus individual module names.
Documentation-only changes get a `[ci skip]` suffix.
Documentation-only changes use a `[ci skip]` suffix.
---
@@ -617,21 +684,21 @@ cmake --build build
cd build && ctest --output-on-failure
```
Coverage focuses on the core data structures and the formatting engine in `common/`. The `detection/` layer has no automated tests (it depends too heavily on a real system) and is instead covered by the CI matrix — 20 workflows under `.github/workflows/` spanning Linux (including musl, loong64, armv7l, i686), macOS, Windows, FreeBSD, NetBSD, OpenBSD, DragonFly, Solaris, OmniOS and Haiku, plus spellcheck and benchmark jobs.
Coverage focuses on the core data structures and the formatting engine in `common/`. The `detection/` layer has no automated tests, because it depends on the state of a running system; it is instead covered by the CI matrix — 20 workflows under `.github/workflows/` spanning Linux (including musl, loong64, armv7l, i686), macOS, Windows, FreeBSD, NetBSD, OpenBSD, DragonFly, Solaris, OmniOS and Haiku, plus spellcheck and benchmark jobs.
**If you touch `common/FFstrbuf.h`, `common/format.h` or `common/color.h`, please extend the matching test.**
**If you modify `common/FFstrbuf.h`, `common/format.h` or `common/color.h`, extend the corresponding test.**
---
## Pull requests
1. **Open an issue first** (feature request / bug report / logo request) so you don't waste effort. Templates are in `.github/ISSUE_TEMPLATE/`.
1. **Open an issue first** (feature request / bug report / logo request) to confirm that the change is wanted before investing effort. Templates are in `.github/ISSUE_TEMPLATE/`.
2. Branch off `dev` — **`dev` is the main development branch**, not `master`.
3. Follow the [commit message convention](#commit-messages).
4. Update `CHANGELOG.md` for user-visible changes.
5. Open the PR against `dev` and fill in `.github/pull_request_template.md`:
- Summary
- Related issue (**required for new logos**, otherwise the PR won't be accepted)
- Related issue (**required for new logos**; otherwise the PR is not accepted)
- Changes
- Screenshots (required for visual changes)
- Checklist: confirm you tested locally
@@ -649,13 +716,13 @@ cd build && ctest --output-on-failure # tests
---
## Gotchas
## Pitfalls
Things that are easy to get wrong when reading this codebase. Most of them follow from the "obsessively fast startup" goal.
The following points are easy to misinterpret when reading this codebase. Most of them follow from the startup-time objective described above.
### 1. Option structs must not exceed 256 bytes
`FF_OPTION_MAX_SIZE = 1 << 8`. Exceeding it is caught at compile time by `static_assert`. Don't try to raise the value — it determines the stack cost of every module invocation.
`FF_OPTION_MAX_SIZE = 1 << 8`. Exceeding it is caught at compile time by `static_assert`. Do not attempt to increase the value: it determines the stack cost of every module invocation.
### 2. `FF_MODULE_DISABLE_*` controls registration, not compilation
@@ -668,9 +735,11 @@ Things that are easy to get wrong when reading this codebase. Most of them follo
**Disabling modules in a Debug build does not shrink the binary.** LTO is enabled whenever `CMAKE_BUILD_TYPE != Debug`, and the default `RelWithDebInfo` already satisfies that — so measure size with `RelWithDebInfo` or `Release`, never with `Debug`. (The "Release mode" wording in the comment above is imprecise.)
### 3. CMake globs don't trigger reconfiguration
### 3. Only two things are discovered by glob
Both the module directories and the logo files are discovered by glob. CMake will not notice new files on its own — you need to re-run `cmake -B build` (or delete `build/CMakeCache.txt` and start over). This is the classic CMake footgun.
The module sources (`CMakeLists.txt:134`) and the logo `.txt` files (`CMakeLists.txt:429`). Both use `CONFIGURE_DEPENDS`, so with the Makefile and Ninja generators the build re-checks the glob and re-runs CMake when the result changes; other generators (Visual Studio and Xcode in particular) do not track it as reliably. Re-run `cmake -B build` after adding a module source or a logo file rather than relying on that behavior.
Everything else — `src/detection/**` and `src/common/impl/**`, and any source outside the platform chain — must be listed in `CMakeLists.txt` by hand; see [step 5](#5-add-the-platform-sources-to-cmakeliststxt).
### 4. CLI module options are removed
@@ -686,9 +755,9 @@ Error: Unsupported module option: --cpu-temp
### 5. `defaultOrder = 0` hides a module from `--gen-config`
`collectModuleInfos` (`genconfig.c:186`) skips any module whose `defaultOrder` is `0`. C zero-initializes the field, so **omitting it is the same as setting it to 0**. Only `logo`, `command` and `custom` do this on purpose.
`collectModuleInfos` (`genconfig.c:186`) skips any module whose `defaultOrder` is `0`. C zero-initializes the field, so **omitting it is the same as setting it to 0**. Only `logo`, `command` and `custom` rely on this intentionally.
`defaultOrder` affects only the ordering in the interactive `--gen-config` picker; it has no effect on runtime output order.
`defaultOrder` affects only the ordering in the interactive `--gen-config` picker; it has no effect on the runtime output order.
### 6. Localization uses byte offsets, not enums
@@ -699,19 +768,23 @@ Error: Unsupported module option: --cpu-temp
(*(const char**) ((uint8_t*) &ff ## moduleName ## ModuleInfo.displayName + instance.config.display.keyLanguage))
```
Consequence: **the field order of `FFModuleDisplayName` must never change** — reordering silently scrambles every language.
Consequence: **the field order of `FFModuleDisplayName` must never change** — reordering the fields silently corrupts the output for every language.
### 7. The `multithreading` switch barely does anything
### 7. The `multithreading` option has limited effect
The global `multithreading` option currently takes effect in exactly one place: `common/impl/networking_linux.c:339`. Modules are still printed sequentially. Modules that need concurrency go through the `ffPrepare*` warm-up hooks instead, which start sampling or fire off requests before the print loop begins.
### 8. Don't print or read config inside `detection/`
This may change in the future. The main blocking issue is that there are dependencies between different modules.
### 8. Do not print or read configuration inside `detection/`
The `detection/` layer must stay pure: read system state, fill a struct, return an error string. Any `printf` or any read of `instance.config` there is a design error.
Use `FF_DEBUG` (`src/common/debug.h`) for logging.
### 9. `src/logo/builtin.c` and `3rdparty/` are formatting-exempt
The former is a large generated/hand-maintained data table, the latter is upstream code. Both are excluded via `.clang-format-ignore` — leave them alone.
The former is a large generated and hand-maintained data table; the latter is upstream code. Both are excluded via `.clang-format-ignore`; do not reformat either.
---
+6
View File
@@ -1,3 +1,9 @@
fastfetch (2.68.1~#UBUNTU_CODENAME#) #UBUNTU_CODENAME#; urgency=medium
* Update to 2.68.1
-- Carter Li <zhangsongcui@live.cn> Wed, 02 Sep 2026 10:47:51 +0800
fastfetch (2.68.0~#UBUNTU_CODENAME#) #UBUNTU_CODENAME#; urgency=medium
* Update to 2.68.0
+25 -4
View File
@@ -291,12 +291,33 @@
}
},
{
"long": "logo-recache",
"desc": "If true, regenerate the image logo cache",
"long": "logo-cache",
"desc": "Specify how the image logo cache is used",
"remark": "See \"--help logo-animation-frame\" for the one case where a cached rendering can outlive the image type that produced it",
"arg": {
"type": "bool",
"type": "enum",
"optional": true,
"default": false
"default": "true",
"enum": {
"true": "Reuse a cached rendering when it is valid, and write it back on a cache miss",
"false": "Ignore the image logo cache completely: neither read nor write it",
"regen": "Ignore any existing cached rendering and regenerate it"
}
}
},
{
"long": "logo-animation-frame",
"desc": "Select which frame of an animated image logo to render",
"remark": [
"Animated kitty graphics only, and only if the image source is animated; 1 or higher renders that frame as a still image, 0 plays the animation",
"A selected frame is cached exactly like the first frame is, sharing its entries; the frame number is recorded next to them, so changing this option re-renders",
"That record is per cache directory, not per image type: switching --logo-type between two types that both have a cached rendering here, and asking for a different frame, can pair one type's rendering with the other's frame number",
"Run \"--logo-cache regen\" after such a switch"
],
"arg": {
"type": "num",
"optional": true,
"default": 1
}
},
{
+24 -9
View File
@@ -446,7 +446,7 @@
"type": "string"
},
"packagesFormat": {
"description": "Output format for the `Packages` module. See Wiki for formatting syntax\n 1. {am-system}: Number of am-system packages\n 2. {am-user}: Number of am-user (aka appman) packages\n 3. {appimage}: Number of appimage packages\n 4. {apk}: Number of apk packages\n 5. {brew}: Number of brew packages\n 6. {brew-cask}: Number of brew-cask packages\n 7. {cards}: Number of cards packages\n 8. {choco}: Number of choco packages\n 9. {dpkg}: Number of dpkg packages\n 10. {emerge}: Number of emerge packages\n 11. {eopkg}: Number of eopkg packages\n 12. {flatpak-system}: Number of flatpak-system app packages\n 13. {flatpak-user}: Number of flatpak-user app packages\n 14. {guix-home}: Number of guix-home packages\n 15. {guix-system}: Number of guix-system packages\n 16. {guix-user}: Number of guix-user packages\n 17. {hpkg-system}: Number of hpkg-system packages\n 18. {hpkg-user}: Number of hpkg-user packages\n 19. {install-release}: Number of install-release packages\n 20. {kiss}: Number of kiss packages\n 21. {linglong}: Number of linglong packages\n 22. {lpkg}: Number of lpkg packages\n 23. {lpkgbuild}: Number of lpkgbuild packages\n 24. {macports}: Number of macports packages\n 25. {mport}: Number of mport packages\n 26. {moss}: Number of moss packages\n 27. {nix-default}: Number of nix-default packages\n 28. {nix-system}: Number of nix-system packages\n 29. {nix-user}: Number of nix-user packages\n 30. {opkg}: Number of opkg packages\n 31. {pacman}: Number of pacman packages\n 32. {pacman-branch}: Pacman branch on manjaro\n 33. {pacstall}: Number of pacstall packages\n 34. {paludis}: Number of paludis packages\n 35. {pisi}: Number of pisi packages\n 36. {pkg}: Number of pkg packages\n 37. {pkgsrc}: Number of pkgsrc packages\n 38. {pkgtool}: Number of pkgtool packages\n 39. {porg}: Number of porg packages\n 40. {rpm}: Number of rpm packages\n 41. {scoop-global}: Number of scoop-global packages\n 42. {scoop-user}: Number of scoop-user packages\n 43. {snap}: Number of snap packages\n 44. {soar}: Number of soar packages\n 45. {sorcery}: Number of sorcery packages\n 46. {winget}: Number of winget packages\n 47. {xbps}: Number of xbps packages\n 48. {brew-all}: Total number of all brew packages\n 49. {flatpak-all}: Total number of all flatpak app packages\n 50. {guix-all}: Total number of all guix packages\n 51. {hpkg-all}: Total number of all hpkg packages\n 52. {nix-all}: Total number of all nix packages\n 53. {all}: Number of all packages",
"description": "Output format for the `Packages` module. See Wiki for formatting syntax\n 1. {am-system}: Number of am-system packages\n 2. {am-user}: Number of am-user (aka appman) packages\n 3. {appimage}: Number of appimage packages\n 4. {apk}: Number of apk packages\n 5. {brew}: Number of brew packages\n 6. {brew-cask}: Number of brew-cask packages\n 7. {cards}: Number of cards packages\n 8. {choco}: Number of choco packages\n 9. {crux}: Number of crux packages\n 10. {dpkg}: Number of dpkg packages\n 11. {emerge}: Number of emerge packages\n 12. {eopkg}: Number of eopkg packages\n 13. {flatpak-system}: Number of flatpak-system app packages\n 14. {flatpak-user}: Number of flatpak-user app packages\n 15. {guix-home}: Number of guix-home packages\n 16. {guix-system}: Number of guix-system packages\n 17. {guix-user}: Number of guix-user packages\n 18. {hpkg-system}: Number of hpkg-system packages\n 19. {hpkg-user}: Number of hpkg-user packages\n 20. {install-release}: Number of install-release packages\n 21. {kiss}: Number of kiss packages\n 22. {linglong}: Number of linglong packages\n 23. {lpkg}: Number of lpkg packages\n 24. {lpkgbuild}: Number of lpkgbuild packages\n 25. {macports}: Number of macports packages\n 26. {mport}: Number of mport packages\n 27. {moss}: Number of moss packages\n 28. {nix-default}: Number of nix-default packages\n 29. {nix-system}: Number of nix-system packages\n 30. {nix-user}: Number of nix-user packages\n 31. {opkg}: Number of opkg packages\n 32. {pacman}: Number of pacman packages\n 33. {pacman-branch}: Pacman branch on manjaro\n 34. {pacstall}: Number of pacstall packages\n 35. {paludis}: Number of paludis packages\n 36. {pisi}: Number of pisi packages\n 37. {pkg}: Number of pkg packages\n 38. {pkgsrc}: Number of pkgsrc packages\n 39. {pkgtool}: Number of pkgtool packages\n 40. {porg}: Number of porg packages\n 41. {rpm}: Number of rpm packages\n 42. {scoop-global}: Number of scoop-global packages\n 43. {scoop-user}: Number of scoop-user packages\n 44. {snap}: Number of snap packages\n 45. {soar}: Number of soar packages\n 46. {sorcery}: Number of sorcery packages\n 47. {winget}: Number of winget packages\n 48. {xbps}: Number of xbps packages\n 49. {brew-all}: Total number of all brew packages\n 50. {flatpak-all}: Total number of all flatpak app packages\n 51. {guix-all}: Total number of all guix packages\n 52. {hpkg-all}: Total number of all hpkg packages\n 53. {nix-all}: Total number of all nix packages\n 54. {all}: Number of all packages",
"type": "string"
},
"physicaldiskFormat": {
@@ -766,10 +766,19 @@
"description": "Whether to preserve the aspect ratio of the logo. Supported by iTerm image protocol only",
"default": false
},
"recache": {
"type": "boolean",
"description": "If true, regenerate image logo cache",
"default": false
"cache": {
"description": "How the image logo cache is used. true reuses a cached rendering when it is valid and writes it back on a cache miss; false ignores the cache completely, neither reading nor writing it; \"regen\" ignores any existing cached rendering and regenerates it",
"oneOf": [
{
"type": "boolean",
"description": "Whether to use the image logo cache"
},
{
"const": "regen",
"description": "Regenerate the image logo cache, ignoring any existing cached rendering"
}
],
"default": true
},
"position": {
"type": "string",
@@ -781,6 +790,11 @@
],
"default": "left"
},
"animationFrame": {
"type": "integer",
"description": "Frame of an animated image to render:\n0 plays the animation (kitty image protocol only), a positive value is the 1-based frame number, and a negative value counts back from the end, so -1 is the last frame.\nOnly the JSON config can express a negative value, as the command line parser reads a leading `-` as another option",
"default": 1
},
"chafa": {
"type": "object",
"additionalProperties": false,
@@ -2701,7 +2715,7 @@
"waitTime": {
"type": "integer",
"description": "Wait time (in ms) used to measure the I/O rate (calculated in bytes/sec).\nAvoid setting this too low, as the kernel requires time to accurately update counters.\nIgnored if 'detectTotal' is true.",
"default": 500,
"default": 250,
"minimum": 1
},
"key": {
@@ -3602,7 +3616,7 @@
"waitTime": {
"type": "integer",
"description": "Wait time (in ms) used to measure the I/O rate (calculated in bytes/sec).\nAvoid setting this too low, as the kernel requires time to accurately update counters.\nIgnored if 'detectTotal' is true.",
"default": 500,
"default": 250,
"minimum": 1
},
"key": {
@@ -3763,6 +3777,7 @@
"apk",
"brew",
"choco",
"crux",
"dpkg",
"emerge",
"eopkg",
@@ -3797,7 +3812,7 @@
"type": "null"
}
],
"default": ["winget"]
"default": []
},
"combined": {
"description": "Whether to combine related package managers into single counts (e.g., nix-system + nix-user = nix)",
@@ -4498,7 +4513,7 @@
"type": "integer",
"description": "Wait time between process samples, in milliseconds. Ignored when showTypes contains \"memory\" only",
"minimum": 1,
"default": 500
"default": 250
},
"compact": {
"type": "boolean",
+2 -2
View File
@@ -99,7 +99,7 @@
"gamepad",
"mouse",
"keyboard",
"top",
"tpm",
"netio",
"diskio",
{
@@ -110,7 +110,7 @@
"type": "weather",
"timeout": 1000
},
"tpm",
"top",
"version",
"break",
"colors"
+2 -2
View File
@@ -101,7 +101,7 @@
"gamepad",
"mouse",
"keyboard",
"top",
"tpm",
"netio",
"diskio",
{
@@ -112,7 +112,7 @@
"type": "weather",
"timeout": 1000
},
"tpm",
"top",
"version",
"logo",
"break",
+9 -2
View File
@@ -90,7 +90,7 @@
{
"type": "disk",
"key": "║{#cyan}│ {icon} Disk │{$4}│{#keys}║{$2}",
"format": "{size-used} \/ {size-total} ({size-percentage}) - {filesystem}",
"format": "{mountpoint} {size-used} \/ {size-total} ({size-percentage}) - {filesystem}",
},
{
"type": "battery",
@@ -195,7 +195,7 @@
"keyIcon": "",
"key": "║{#red}│ {icon} Clang │{$4}│{#keys}║{$2}",
"text": "clang --version | findstr version", // Finds the line with "version"
"format": "clang {~-6}" // Prints the last 6 characters (version number)
"format": "clang {~14,20}" // Prints 14~20 characters (version number)
},
{
"type": "command",
@@ -204,6 +204,13 @@
"text": "node --version",
"format": "node {~1}" // {~1} removes first character (v)
},
{
"type": "command",
"keyIcon": "",
"key": "║{#red}│ {icon} Python │{$4}│{#keys}║{$2}",
"text": "python --version",
"format": "python {~7}" // {~7} removes first 7 characters ("Python" with extra space)
},
{
"type": "command",
"keyIcon": "",
+12 -3
View File
@@ -38,8 +38,14 @@
"compactType": "original",
"key": "Resolution"
},
"de",
"wm",
{
"type": "de",
"key": "DE"
},
{
"type": "wm",
"key": "WM"
},
"wmtheme",
"theme",
"icons",
@@ -48,7 +54,10 @@
"type": "terminalfont",
"format": "{/name}{-}{/}{name}{?size} {size}{?}"
},
"cpu",
{
"type": "cpu",
"showPeCoreCount": false
},
{
"type": "gpu",
"key": "GPU",
+18
View File
@@ -0,0 +1,18 @@
Copyright (c) 2014-2016 Hayaki Saito
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+13
View File
@@ -0,0 +1,13 @@
src/quant.c is derived from ppmquant, originally by Jef Poskanzer.
Copyright (C) 1989, 1991 by Jef Poskanzer.
Copyright (C) 2001 by Bryan Henderson.
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted, provided
that the above copyright notice appear in all copies and that both that
copyright notice and this permission notice appear in supporting
documentation. This software is provided "as is" without express or
implied warranty.
+49
View File
@@ -0,0 +1,49 @@
"sixel" license (original license)
==================================
src/tosixel.c and src/fromsixel.c are derived from "sixel" original version (2014-3-2)
Package: http://nanno.dip.jp/softlib/man/rlogin/sixel.tar.gz
Unofficial repo: https://github.com/saitoha/sixel
This work is written by kmiya@ culti. He distributes it under very permissive license.
The original license text(in Japanese) is:
```
このプログラム及びソースコードの使用について個人・商用を問わず
ご自由に使用していただいで結構です。
また、配布・転載・紹介もご連絡の必要もありません。
ソースの改変による配布も自由ですが、どのバージョンの改変かを
明記されることを希望します。
バージョン情報が無い場合は、配布物の年月日を明記されることを
希望します。
2014/10/05 kmiya
```
The unofficial translation:
```
Anyone is free to use this program for any purpose,
commercial or non-commercial, without any restriction.
Anyone is free to distribute, copy, publish, or
advertise this software, without any contact.
Anyone is free to distribute with modification of the
source code, but I "hope" that its based version or
date will be written clearly.
2014/10/05 kmiya
```
kmiya also said this is compatible with MIT/BSD/GPL.
+210
View File
@@ -0,0 +1,210 @@
# libsixel (encoder subset, vendored)
Encoder-only subset of [libsixel](https://github.com/saitoha/libsixel) `1.8.7-r2`,
used by `src/logo/image/` to render the `sixel` logo type **on Windows and macOS**.
## Why this is vendored
Neither MSYS2 nor vcpkg packages libsixel, so on Windows there is nothing to
`dlopen()` or to link against. The encoder is small and has no external
dependencies, so the necessary files are embedded instead. The intent is to upstream
a libsixel package to MSYS2 later and switch to it; until then this directory is the
source of truth.
macOS *does* have a package — Homebrew's `libsixel` is this very version, `1.8.7-r2`
(`brew info libsixel`) — but it is deliberately not used. It drags in `jpeg-turbo` /
`libpng` for the decoder side we never call, and linking it would mean a different
encoder on each platform. Since Windows needs an embedded copy regardless, one shared
copy is simpler than two.
## Why only Windows and macOS
Windows loses ImageMagick entirely — its image backend moves to WIC, which decodes
and scales but cannot *encode* sixel — so it needs an encoder of its own.
macOS does not get ImageMagick either: `ENABLE_IMAGEMAGICK6` / `ENABLE_IMAGEMAGICK7`
are gated on `LINUX OR FreeBSD OR OpenBSD OR NetBSD OR ANDROID OR SunOS OR Haiku OR
GNU`, with no `APPLE`, and its image backend is ImageIO. So it shares the same
requirement.
On every other platform ImageMagick stays, and it already produces sixel through
its own SIXEL coder. Adding libsixel there would mean a second encoder for a
capability that already works: one more dependency for zero gain. So `ENABLE_SIXEL`
is gated on `WIN32 OR APPLE`, and these sources are **not compiled at all** on
Linux / the BSDs.
Consequence: sixel bytes differ between Windows / macOS (libsixel) and the rest
(ImageMagick). That is deliberate and accepted — see
`doc/windows-image-backend.md` decision 9.
## Transparency
The subset is used for its keycolor support. `sixel_dither_set_transparent()` marks a
palette index as the transparent one; `output_rgb_palette_definition()` then leaves that
entry out of the palette definition, and `sixel_encode_body()` never puts a keycolor
pixel into the node map, so nothing is drawn there and the terminal background shows
through. `src/logo/image/sixel.c` drives this for sources that contain fully transparent
pixels — it maps those pixels onto a dedicated index one past the quantized palette,
because keying a *content* colour would also drop every opaque pixel that shares it.
Two things have to line up for the background to actually be transparent: the caller has to
mark a keycolor, so the keyed pixels are never painted (above), **and** the encoder has to ask
for a transparent background, so the terminal leaves those unpainted pixels alone instead of
filling them. The second half is the DCS `P2` parameter — see
[Local modifications](#local-modifications) item 3.
Note what this is and is not: it is a **palette-index** keycolor, not alpha support. A
partially transparent pixel has to be drawn in its unblended colour, since a sixel has
no way to blend with whatever the terminal has behind it.
⚠️ Do not vendor a *newer* libsixel in the belief that this version cannot do
transparency. It can, and it was measured: the official `1.8.7-r2` omits the keycolor
entry and leaves the keyed pixels unpainted, with the remaining pixels correctly placed.
When a transparent background is not showing up, check the caller first — historically
the caller simply never called `sixel_dither_set_transparent()`, and an image logo only
renders correctly once it does. If the caller *is* setting a keycolor and the background is
still solid, check `P2` instead: the keyed pixels are being left unpainted correctly, but the
terminal is filling them.
## What was kept
Starting from `sixel_dither_new` / `sixel_dither_initialize` / `sixel_output_new` /
`sixel_encode` and following the dependency closure, only these files are reachable:
| File | Provides |
|---|---|
| `tosixel.c` | `sixel_encode`, `sixel_putc`, `sixel_node_*`, DCS envelope handling |
| `dither.c` / `dither.h` | `sixel_dither_new`, `sixel_dither_initialize`, `sixel_dither_unref` |
| `output.c` / `output.h` | `sixel_output_new`, `sixel_output_unref` |
| `quant.c` / `quant.h` | Median-cut palette construction |
| `pixelformat.c` | `sixel_helper_compute_depth`, `sixel_helper_normalize_pixelformat` |
| `allocator.c` / `allocator.h` | `sixel_allocator_*` |
| `status.c` / `status.h` | `sixel_helper_set_additional_message` |
| `malloc_stub.h` | Included by `allocator.c`; compiles to nothing when `HAVE_MALLOC` |
| `sixel.h` | Public API (upstream `include/sixel.h`) |
## What was removed
Everything else in the upstream tree, in particular:
- **Decoding**: `decoder.c`, `fromsixel.c`, `frompnm.c`, `fromgif.c`, `frame.c`,
`loader.c`, `stb_image.h`, `stb_image_write.*`. Image decoding is done by the
platform backend (WIC on Windows, ImageIO on macOS, ImageMagick elsewhere), so
libsixel only ever sees an RGBA8 buffer here.
- **The `sixel_encoder_*` / `sixel_decoder_*` high-level API**: `encoder.c`,
`writer.c`, `tty.c`, `scale.c`. These pull in file I/O, terminal probing and the
loader registry. We call the dither/output/encode trio directly.
- **`rgblookup.h` / `rgblookup.gperf`**: a gperf-generated color-name table used
only by `encoder.c` for `--builtin-palette` parsing.
- **`converters/`** (`img2sixel`, `sixel2png`), **`python/`**, **`tools/`**,
**`tests/`**, **`images/`** (216 test images), and the packaging templates
(`package.json.in.in`, `libsixel.pc.in`).
- **The autotools machinery**: `configure`, `Makefile.in`, `aclocal.m4`, `m4/`,
`ltmain.sh`, `config.h.in`, … See item 2 under
[Local modifications](#local-modifications).
- **Six of the nine `LICENSE.*` files**: `LICENSE.images` / `.mesa` / `.pngsuite` /
`.sdump` / `.stb` cover only material that was dropped (test images, the OpenGL
example, the `sdump` tool, stb). The three that remain are the complete set
required by the files above — verified against each file's own header, see
[License](#license).
Result: **20 files / 256 KB**, down from 319 files / 11.3 MB. Note that 8.0 MB of
that 11.3 MB was `images/` fixtures, so the meaningful comparison is code:
`src/` + `include/` went from 50 files / 1.17 MB to 20 files / 256 KB.
## Local modifications
Three deliberate divergences from upstream. Re-apply all three when re-syncing.
1. **`sixel.h` — `SIXELAPI` is empty.** Upstream defines it as
`__declspec(dllexport)` on Windows. This subset is compiled into `libfastfetch`
statically rather than into a standalone DLL, so the attribute would (a) add
every libsixel symbol to fastfetch's export table and (b) make `sixel.h`'s
declarations disagree with the ones in `dither.h` / `output.h` / `quant.h` /
`allocator.h`, which do not carry it (clang warns:
`-Wdll-attribute-on-redeclaration`).
2. **`config.h` is hand-written.** Upstream generates it with `configure`. Only
these vendored files read it, and they reference a small fixed set of macros,
so the values are hard-coded. Two things to watch:
- `HAVE_TESTS` must stay **undefined**, not `0`: `sixel.h` gates its test-only
declarations with `#ifdef HAVE_TESTS`, so `#define HAVE_TESTS 0` would still
pull in declarations for functions we do not compile.
- `HAVE_MEMORY_H` / `HAVE_STRING_H` must be `1`. fastfetch builds with
`-Werror=implicit-function-declaration`, so a missing `<memory.h>` /
`<string.h>` include in `pixelformat.c` / `status.c` is a hard error.
3. **`tosixel.c` — the DCS `P2` parameter is initialised to 1.** `sixel_encode_header()`
declares `int p[3] = {0, 0, 0}`, and the trailing-zero trimming right below it then drops
all three, so the envelope is a bare `ESC P q`. That means `P2 = 0`, which tells the
terminal to fill every unset pixel with **colour-table entry 0** — and that entry is
defined by the image's own palette, so a keycolor image comes out with a solid rectangle
behind it rather than transparency. Setting `p[1] = 1` leaves unset pixels untouched.
The trimming still drops the trailing aspect-ratio parameter, so the envelope is
`ESC P 0;1 q`. `P3` defaults to 0 and the two spellings are equivalent — verified by
decoding both with libsixel's own decoder and with ImageMagick's. ImageMagick's SIXEL
coder and chafa both write `0;1;0` explicitly.
This only shows up on a terminal that implements the VT340 background rule. Windows
Terminal does (`_backgroundFillRequired = (_conformanceLevel == 1 || !transparent)` in
`src/terminal/adapter/SixelParser.cpp`), which is where it was reproduced; WezTerm does
not fill, so the identical bytes look correct there. It is also why Linux never showed
the problem: that path goes through ImageMagick, which already sends `P2 = 1`.
The vendored sources are also exempted from `-Wconversion` in `CMakeLists.txt`:
upstream has ~160 implicit int→`unsigned char` narrowing warnings. Everything else
(`-Wall -Wextra` and fastfetch's `-Werror=` set) applies unchanged, and the subset
compiles clean.
## Re-syncing with upstream
```sh
VER=1.8.7-r2
git clone --depth 1 --branch "$VER" https://github.com/saitoha/libsixel /tmp/libsixel
# 1. copy the closure (paths change from src/foo.c to foo.c, include/sixel.h to sixel.h)
for f in tosixel.c dither.c dither.h output.c output.h quant.c quant.h \
pixelformat.c allocator.c allocator.h status.c status.h malloc_stub.h; do
cp "/tmp/libsixel/src/$f" .
done
cp /tmp/libsixel/include/sixel.h .
cp /tmp/libsixel/LICENSE /tmp/libsixel/LICENSE.sixel /tmp/libsixel/LICENSE.pnmcolormap .
# 2. re-apply the three local modifications listed above
# 3. verify
```
Verification (must be 0 diagnostics, and the encoder must emit a DCS-wrapped stream).
Both platforms compile this subset, so run it on both:
```sh
# Windows: CC=/c/msys64/clang64/bin/cc.exe
# macOS: CC=cc (verified with Apple clang 21: 0 diagnostics)
CC=cc
FLAGS="-I. -Wall -Wextra -Wconversion -Wno-conversion -Werror=uninitialized \
-Werror=return-type -Werror=vla -Werror=incompatible-pointer-types \
-Werror=implicit-function-declaration -Werror=int-conversion -std=gnu23"
for f in tosixel dither output quant allocator pixelformat status; do
$CC $FLAGS -c $f.c -o /dev/null || echo "FAILED: $f"
done
```
If upstream adds a call from the closure to a new file, the build fails at link
time with an undefined `sixel_*` symbol — add that file and repeat.
## License
MIT-compatible, but three separate notices apply and all three files must be kept.
Mapping verified against each source file's own copyright header:
| File | Applies to |
|---|---|
| `LICENSE` | MIT, Copyright (c) 2014-2016 Hayaki Saito — `dither.c`, `output.c`, `pixelformat.c`, `allocator.c`, `status.c` (their headers say 2014-2018/2019; same MIT terms) |
| `LICENSE.sixel` | `tosixel.c` — derived from kmiya's original `sixel` (2014-3-2), permissive, re-licensed MIT by Hayaki Saito |
| `LICENSE.pnmcolormap` | `quant.c` — derived from `ppmquant` by Jef Poskanzer / Bryan Henderson |
Upstream also ships `LICENSE.images`, `.mesa`, `.pngsuite`, `.sdump` and `.stb`;
none of them cover a file in this subset, so they were not carried over. If a
re-sync ever pulls in a file from the decoder side (`fromgif.c` → `.stb`,
`fromsixel.c` → `.sixel`), re-check this table.
+379
View File
@@ -0,0 +1,379 @@
/*
* Copyright (c) 2014-2018 Hayaki Saito
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "config.h"
/* STDC_HEADERS */
#include <stdlib.h>
#if HAVE_ASSERT_H
# include <assert.h>
#endif /* HAVE_ASSERT_H */
#if HAVE_SYS_TYPES_H
# include <sys/types.h>
#endif /* HAVE_SYS_TYPES_H */
#if HAVE_ERRNO_H
# include <errno.h>
#endif /* HAVE_ERRNO_H */
#if HAVE_MEMORY_H
# include <memory.h>
#endif /* HAVE_MEMORY_H */
#include "allocator.h"
#include "malloc_stub.h"
/* create allocator object */
SIXELSTATUS
sixel_allocator_new(
sixel_allocator_t /* out */ **ppallocator, /* allocator object to be created */
sixel_malloc_t /* in */ fn_malloc, /* custom malloc() function */
sixel_calloc_t /* in */ fn_calloc, /* custom calloc() function */
sixel_realloc_t /* in */ fn_realloc, /* custom realloc() function */
sixel_free_t /* in */ fn_free) /* custom free() function */
{
SIXELSTATUS status = SIXEL_FALSE;
if (ppallocator == NULL) {
sixel_helper_set_additional_message(
"sixel_allocator_new: given argument ppallocator is null.");
status = SIXEL_BAD_ARGUMENT;
goto end;
}
if (fn_malloc == NULL) {
fn_malloc = malloc;
}
if (fn_calloc == NULL) {
fn_calloc = calloc;
}
if (fn_realloc == NULL) {
fn_realloc = realloc;
}
if (fn_free == NULL) {
fn_free = free;
}
*ppallocator = fn_malloc(sizeof(sixel_allocator_t));
if (*ppallocator == NULL) {
sixel_helper_set_additional_message(
"sixel_allocator_new: fn_malloc() failed.");
status = SIXEL_BAD_ALLOCATION;
goto end;
}
(*ppallocator)->ref = 1;
(*ppallocator)->fn_malloc = fn_malloc;
(*ppallocator)->fn_calloc = fn_calloc;
(*ppallocator)->fn_realloc = fn_realloc;
(*ppallocator)->fn_free = fn_free;
status = SIXEL_OK;
end:
return status;
}
/* destruct allocator object */
static void
sixel_allocator_destroy(
sixel_allocator_t /* in */ *allocator) /* allocator object to
be destroyed */
{
/* precondition */
assert(allocator);
assert(allocator->fn_free);
allocator->fn_free(allocator);
}
/* increase reference count of allocatort object (thread-unsafe) */
SIXELAPI void
sixel_allocator_ref(
sixel_allocator_t /* in */ *allocator) /* allocator object to be
increment reference counter */
{
/* precondition */
assert(allocator);
/* TODO: be thread safe */
++allocator->ref;
}
/* decrease reference count of output context object (thread-unsafe) */
SIXELAPI void
sixel_allocator_unref(
sixel_allocator_t /* in */ *allocator) /* allocator object to be unreference */
{
/* TODO: be thread safe */
if (allocator) {
assert(allocator->ref > 0);
--allocator->ref;
if (allocator->ref == 0) {
sixel_allocator_destroy(allocator);
}
}
}
/* call custom malloc() */
SIXELAPI void *
sixel_allocator_malloc(
sixel_allocator_t /* in */ *allocator, /* allocator object */
size_t /* in */ n) /* allocation size */
{
/* precondition */
assert(allocator);
assert(allocator->fn_malloc);
if (n == 0) {
sixel_helper_set_additional_message(
"sixel_allocator_malloc: called with n == 0");
return NULL;
}
if (n > SIXEL_ALLOCATE_BYTES_MAX) {
return NULL;
}
return allocator->fn_malloc(n);
}
/* call custom calloc() */
SIXELAPI void *
sixel_allocator_calloc(
sixel_allocator_t /* in */ *allocator, /* allocator object */
size_t /* in */ nelm, /* number of elements */
size_t /* in */ elsize) /* size of element */
{
size_t n;
/* precondition */
assert(allocator);
assert(allocator->fn_calloc);
n = nelm * elsize;
if (n == 0) {
sixel_helper_set_additional_message(
"sixel_allocator_malloc: called with n == 0");
return NULL;
}
if (n > SIXEL_ALLOCATE_BYTES_MAX) {
return NULL;
}
return allocator->fn_calloc(nelm, elsize);
}
/* call custom realloc() */
SIXELAPI void *
sixel_allocator_realloc(
sixel_allocator_t /* in */ *allocator, /* allocator object */
void /* in */ *p, /* existing buffer to be re-allocated */
size_t /* in */ n) /* re-allocation size */
{
/* precondition */
assert(allocator);
assert(allocator->fn_realloc);
if (n == 0) {
sixel_helper_set_additional_message(
"sixel_allocator_malloc: called with n == 0");
return NULL;
}
if (n > SIXEL_ALLOCATE_BYTES_MAX) {
return NULL;
}
return allocator->fn_realloc(p, n);
}
/* call custom free() */
SIXELAPI void
sixel_allocator_free(
sixel_allocator_t /* in */ *allocator, /* allocator object */
void /* in */ *p) /* existing buffer to be freed */
{
/* precondition */
assert(allocator);
assert(allocator->fn_free);
allocator->fn_free(p);
}
#if HAVE_TESTS
volatile int sixel_debug_malloc_counter;
void *
sixel_bad_malloc(size_t size)
{
return sixel_debug_malloc_counter-- == 0 ? NULL: malloc(size);
}
void *
sixel_bad_calloc(size_t count, size_t size)
{
(void) count;
(void) size;
return NULL;
}
void *
sixel_bad_realloc(void *ptr, size_t size)
{
(void) ptr;
(void) size;
return NULL;
}
#endif /* HAVE_TESTS */
#if 0
int
rpl_posix_memalign(void **memptr, size_t alignment, size_t size)
{
#if HAVE_POSIX_MEMALIGN
return posix_memalign(memptr, alignment, size);
#elif HAVE_ALIGNED_ALLOC
*memptr = aligned_alloc(alignment, size);
return *memptr ? 0: ENOMEM;
#elif HAVE_MEMALIGN
*memptr = memalign(alignment, size);
return *memptr ? 0: ENOMEM;
#elif HAVE__ALIGNED_MALLOC
return _aligned_malloc(size, alignment);
#else
# error
#endif /* _MSC_VER */
}
#endif
#if HAVE_TESTS
static int
test1(void)
{
int nret = EXIT_FAILURE;
SIXELSTATUS status;
sixel_allocator_t *allocator = NULL;
status = sixel_allocator_new(NULL, malloc, calloc, realloc, free);
if (status != SIXEL_BAD_ARGUMENT) {
goto error;
}
status = sixel_allocator_new(&allocator, NULL, calloc, realloc, free);
if (SIXEL_FAILED(status)) {
goto error;
}
status = sixel_allocator_new(&allocator, malloc, NULL, realloc, free);
if (SIXEL_FAILED(status)) {
goto error;
}
status = sixel_allocator_new(&allocator, malloc, calloc, NULL, free);
if (SIXEL_FAILED(status)) {
goto error;
}
status = sixel_allocator_new(&allocator, malloc, calloc, realloc, NULL);
if (SIXEL_FAILED(status)) {
goto error;
}
nret = EXIT_SUCCESS;
error:
return nret;
}
static int
test2(void)
{
int nret = EXIT_FAILURE;
SIXELSTATUS status;
sixel_allocator_t *allocator = NULL;
sixel_debug_malloc_counter = 1;
status = sixel_allocator_new(&allocator, sixel_bad_malloc, calloc, realloc, free);
if (status == SIXEL_BAD_ALLOCATION) {
goto error;
}
nret = EXIT_SUCCESS;
error:
return nret;
}
SIXELAPI int
sixel_allocator_tests_main(void)
{
int nret = EXIT_FAILURE;
size_t i;
typedef int (* testcase)(void);
static testcase const testcases[] = {
test1,
test2
};
for (i = 0; i < sizeof(testcases) / sizeof(testcase); ++i) {
nret = testcases[i]();
if (nret != EXIT_SUCCESS) {
goto error;
}
}
nret = EXIT_SUCCESS;
error:
return nret;
}
#endif /* HAVE_TESTS */
/* emacs Local Variables: */
/* emacs mode: c */
/* emacs tab-width: 4 */
/* emacs indent-tabs-mode: nil */
/* emacs c-basic-offset: 4 */
/* emacs End: */
/* vim: set expandtab ts=4 sts=4 sw=4 : */
/* EOF */
+49
View File
@@ -0,0 +1,49 @@
/*
* Copyright (c) 2014-2016 Hayaki Saito
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef LIBSIXEL_ALLOCATOR_H
#define LIBSIXEL_ALLOCATOR_H
#include <sixel.h>
struct sixel_allocator {
unsigned int ref; /* reference counter */
sixel_malloc_t fn_malloc;
sixel_calloc_t fn_calloc;
sixel_realloc_t fn_realloc;
sixel_free_t fn_free;
};
#if HAVE_TESTS
int
sixel_allocator_tests_main(void);
#endif
#endif /* LIBSIXEL_ALLOCATOR_H */
/* emacs Local Variables: */
/* emacs mode: c */
/* emacs tab-width: 4 */
/* emacs indent-tabs-mode: nil */
/* emacs c-basic-offset: 4 */
/* emacs End: */
/* vim: set expandtab ts=4 sts=4 sw=4 : */
/* EOF */
+58
View File
@@ -0,0 +1,58 @@
/*
* Minimal hand-written replacement for the autoconf-generated config.h.
*
* Upstream libsixel ships config.h.in and lets `configure` produce config.h.
* We only vendor the encoder-side subset (see README.md), and those files
* reference a small, fixed set of macros, so the values are hard-coded here
* instead of carrying the autotools machinery.
*
* The values below hold for every platform fastfetch targets:
* Windows/MinGW-w64, Linux/glibc, Linux/musl, macOS and the BSDs.
* Re-check this file whenever the vendored subset is re-synced with upstream.
*/
#ifndef LIBSIXEL_CONFIG_H
#define LIBSIXEL_CONFIG_H
/* Standard headers (upstream: AC_CHECK_HEADERS) */
#define HAVE_ASSERT_H 1
#define HAVE_ERRNO_H 1
#define HAVE_INTTYPES_H 1
#define HAVE_LIMITS_H 1
#define HAVE_MATH_H 1
#define HAVE_MEMORY_H 1
#define HAVE_STRING_H 1
#define HAVE_SYS_TYPES_H 1
/* libc functions (upstream: AC_CHECK_FUNCS) */
#define HAVE_LDIV 1
#define HAVE_MALLOC 1
#define HAVE_REALLOC 1
/* Byte order of the 32bpp pixel readers in pixelformat.c; 0 = little endian */
#define SWAP_BYTES 0
/*
* Guards the diagnostic pragma push/pop in dither.c. Not needed, and the
* pragma spelling is not portable across the compilers we support.
*/
#define HAVE_DIAGNOSTIC_DEPRECATED_DECLARATIONS 0
/* Verbose quantizer tracing to stderr */
#define HAVE_DEBUG 0
/*
* HAVE_TESTS must stay *undefined* rather than 0: sixel.h gates its test-only
* declarations with `#ifdef HAVE_TESTS`, so defining it to 0 would still pull
* in declarations for functions we do not compile.
*/
#undef HAVE_TESTS
/* Optional image loaders and features; not vendored */
#undef HAVE_GD
#undef HAVE_GDK_PIXBUF2
#undef HAVE_JPEG
#undef HAVE_LIBCURL
#undef HAVE_LIBPNG
#endif /* LIBSIXEL_CONFIG_H */
+918
View File
@@ -0,0 +1,918 @@
/*
* Copyright (c) 2014-2018 Hayaki Saito
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "config.h"
#include <stdlib.h>
#include <stdio.h>
#if HAVE_MATH_H
# include <math.h>
#endif /* HAVE_MATH_H */
#if HAVE_STRING_H
# include <string.h>
#endif /* HAVE_STRING_H */
#if HAVE_LIMITS_H
# include <limits.h>
#endif /* HAVE_LIMITS_H */
#if HAVE_INTTYPES_H
# include <inttypes.h>
#endif /* HAVE_INTTYPES_H */
#include "dither.h"
#include "quant.h"
#include <sixel.h>
static const unsigned char pal_mono_dark[] = {
0x00, 0x00, 0x00, 0xff, 0xff, 0xff
};
static const unsigned char pal_mono_light[] = {
0xff, 0xff, 0xff, 0x00, 0x00, 0x00
};
static const unsigned char pal_gray_1bit[] = {
0x00, 0x00, 0x00, 0xff, 0xff, 0xff
};
static const unsigned char pal_gray_2bit[] = {
0x00, 0x00, 0x00, 0x55, 0x55, 0x55, 0xaa, 0xaa, 0xaa, 0xff, 0xff, 0xff
};
static const unsigned char pal_gray_4bit[] = {
0x00, 0x00, 0x00, 0x11, 0x11, 0x11, 0x22, 0x22, 0x22, 0x33, 0x33, 0x33,
0x44, 0x44, 0x44, 0x55, 0x55, 0x55, 0x66, 0x66, 0x66, 0x77, 0x77, 0x77,
0x88, 0x88, 0x88, 0x99, 0x99, 0x99, 0xaa, 0xaa, 0xaa, 0xbb, 0xbb, 0xbb,
0xcc, 0xcc, 0xcc, 0xdd, 0xdd, 0xdd, 0xee, 0xee, 0xee, 0xff, 0xff, 0xff
};
static const unsigned char pal_gray_8bit[] = {
0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x02, 0x02, 0x02, 0x03, 0x03, 0x03,
0x04, 0x04, 0x04, 0x05, 0x05, 0x05, 0x06, 0x06, 0x06, 0x07, 0x07, 0x07,
0x08, 0x08, 0x08, 0x09, 0x09, 0x09, 0x0a, 0x0a, 0x0a, 0x0b, 0x0b, 0x0b,
0x0c, 0x0c, 0x0c, 0x0d, 0x0d, 0x0d, 0x0e, 0x0e, 0x0e, 0x0f, 0x0f, 0x0f,
0x10, 0x10, 0x10, 0x11, 0x11, 0x11, 0x12, 0x12, 0x12, 0x13, 0x13, 0x13,
0x14, 0x14, 0x14, 0x15, 0x15, 0x15, 0x16, 0x16, 0x16, 0x17, 0x17, 0x17,
0x18, 0x18, 0x18, 0x19, 0x19, 0x19, 0x1a, 0x1a, 0x1a, 0x1b, 0x1b, 0x1b,
0x1c, 0x1c, 0x1c, 0x1d, 0x1d, 0x1d, 0x1e, 0x1e, 0x1e, 0x1f, 0x1f, 0x1f,
0x20, 0x20, 0x20, 0x21, 0x21, 0x21, 0x22, 0x22, 0x22, 0x23, 0x23, 0x23,
0x24, 0x24, 0x24, 0x25, 0x25, 0x25, 0x26, 0x26, 0x26, 0x27, 0x27, 0x27,
0x28, 0x28, 0x28, 0x29, 0x29, 0x29, 0x2a, 0x2a, 0x2a, 0x2b, 0x2b, 0x2b,
0x2c, 0x2c, 0x2c, 0x2d, 0x2d, 0x2d, 0x2e, 0x2e, 0x2e, 0x2f, 0x2f, 0x2f,
0x30, 0x30, 0x30, 0x31, 0x31, 0x31, 0x32, 0x32, 0x32, 0x33, 0x33, 0x33,
0x34, 0x34, 0x34, 0x35, 0x35, 0x35, 0x36, 0x36, 0x36, 0x37, 0x37, 0x37,
0x38, 0x38, 0x38, 0x39, 0x39, 0x39, 0x3a, 0x3a, 0x3a, 0x3b, 0x3b, 0x3b,
0x3c, 0x3c, 0x3c, 0x3d, 0x3d, 0x3d, 0x3e, 0x3e, 0x3e, 0x3f, 0x3f, 0x3f,
0x40, 0x40, 0x40, 0x41, 0x41, 0x41, 0x42, 0x42, 0x42, 0x43, 0x43, 0x43,
0x44, 0x44, 0x44, 0x45, 0x45, 0x45, 0x46, 0x46, 0x46, 0x47, 0x47, 0x47,
0x48, 0x48, 0x48, 0x49, 0x49, 0x49, 0x4a, 0x4a, 0x4a, 0x4b, 0x4b, 0x4b,
0x4c, 0x4c, 0x4c, 0x4d, 0x4d, 0x4d, 0x4e, 0x4e, 0x4e, 0x4f, 0x4f, 0x4f,
0x50, 0x50, 0x50, 0x51, 0x51, 0x51, 0x52, 0x52, 0x52, 0x53, 0x53, 0x53,
0x54, 0x54, 0x54, 0x55, 0x55, 0x55, 0x56, 0x56, 0x56, 0x57, 0x57, 0x57,
0x58, 0x58, 0x58, 0x59, 0x59, 0x59, 0x5a, 0x5a, 0x5a, 0x5b, 0x5b, 0x5b,
0x5c, 0x5c, 0x5c, 0x5d, 0x5d, 0x5d, 0x5e, 0x5e, 0x5e, 0x5f, 0x5f, 0x5f,
0x60, 0x60, 0x60, 0x61, 0x61, 0x61, 0x62, 0x62, 0x62, 0x63, 0x63, 0x63,
0x64, 0x64, 0x64, 0x65, 0x65, 0x65, 0x66, 0x66, 0x66, 0x67, 0x67, 0x67,
0x68, 0x68, 0x68, 0x69, 0x69, 0x69, 0x6a, 0x6a, 0x6a, 0x6b, 0x6b, 0x6b,
0x6c, 0x6c, 0x6c, 0x6d, 0x6d, 0x6d, 0x6e, 0x6e, 0x6e, 0x6f, 0x6f, 0x6f,
0x70, 0x70, 0x70, 0x71, 0x71, 0x71, 0x72, 0x72, 0x72, 0x73, 0x73, 0x73,
0x74, 0x74, 0x74, 0x75, 0x75, 0x75, 0x76, 0x76, 0x76, 0x77, 0x77, 0x77,
0x78, 0x78, 0x78, 0x79, 0x79, 0x79, 0x7a, 0x7a, 0x7a, 0x7b, 0x7b, 0x7b,
0x7c, 0x7c, 0x7c, 0x7d, 0x7d, 0x7d, 0x7e, 0x7e, 0x7e, 0x7f, 0x7f, 0x7f,
0x80, 0x80, 0x80, 0x81, 0x81, 0x81, 0x82, 0x82, 0x82, 0x83, 0x83, 0x83,
0x84, 0x84, 0x84, 0x85, 0x85, 0x85, 0x86, 0x86, 0x86, 0x87, 0x87, 0x87,
0x88, 0x88, 0x88, 0x89, 0x89, 0x89, 0x8a, 0x8a, 0x8a, 0x8b, 0x8b, 0x8b,
0x8c, 0x8c, 0x8c, 0x8d, 0x8d, 0x8d, 0x8e, 0x8e, 0x8e, 0x8f, 0x8f, 0x8f,
0x90, 0x90, 0x90, 0x91, 0x91, 0x91, 0x92, 0x92, 0x92, 0x93, 0x93, 0x93,
0x94, 0x94, 0x94, 0x95, 0x95, 0x95, 0x96, 0x96, 0x96, 0x97, 0x97, 0x97,
0x98, 0x98, 0x98, 0x99, 0x99, 0x99, 0x9a, 0x9a, 0x9a, 0x9b, 0x9b, 0x9b,
0x9c, 0x9c, 0x9c, 0x9d, 0x9d, 0x9d, 0x9e, 0x9e, 0x9e, 0x9f, 0x9f, 0x9f,
0xa0, 0xa0, 0xa0, 0xa1, 0xa1, 0xa1, 0xa2, 0xa2, 0xa2, 0xa3, 0xa3, 0xa3,
0xa4, 0xa4, 0xa4, 0xa5, 0xa5, 0xa5, 0xa6, 0xa6, 0xa6, 0xa7, 0xa7, 0xa7,
0xa8, 0xa8, 0xa8, 0xa9, 0xa9, 0xa9, 0xaa, 0xaa, 0xaa, 0xab, 0xab, 0xab,
0xac, 0xac, 0xac, 0xad, 0xad, 0xad, 0xae, 0xae, 0xae, 0xaf, 0xaf, 0xaf,
0xb0, 0xb0, 0xb0, 0xb1, 0xb1, 0xb1, 0xb2, 0xb2, 0xb2, 0xb3, 0xb3, 0xb3,
0xb4, 0xb4, 0xb4, 0xb5, 0xb5, 0xb5, 0xb6, 0xb6, 0xb6, 0xb7, 0xb7, 0xb7,
0xb8, 0xb8, 0xb8, 0xb9, 0xb9, 0xb9, 0xba, 0xba, 0xba, 0xbb, 0xbb, 0xbb,
0xbc, 0xbc, 0xbc, 0xbd, 0xbd, 0xbd, 0xbe, 0xbe, 0xbe, 0xbf, 0xbf, 0xbf,
0xc0, 0xc0, 0xc0, 0xc1, 0xc1, 0xc1, 0xc2, 0xc2, 0xc2, 0xc3, 0xc3, 0xc3,
0xc4, 0xc4, 0xc4, 0xc5, 0xc5, 0xc5, 0xc6, 0xc6, 0xc6, 0xc7, 0xc7, 0xc7,
0xc8, 0xc8, 0xc8, 0xc9, 0xc9, 0xc9, 0xca, 0xca, 0xca, 0xcb, 0xcb, 0xcb,
0xcc, 0xcc, 0xcc, 0xcd, 0xcd, 0xcd, 0xce, 0xce, 0xce, 0xcf, 0xcf, 0xcf,
0xd0, 0xd0, 0xd0, 0xd1, 0xd1, 0xd1, 0xd2, 0xd2, 0xd2, 0xd3, 0xd3, 0xd3,
0xd4, 0xd4, 0xd4, 0xd5, 0xd5, 0xd5, 0xd6, 0xd6, 0xd6, 0xd7, 0xd7, 0xd7,
0xd8, 0xd8, 0xd8, 0xd9, 0xd9, 0xd9, 0xda, 0xda, 0xda, 0xdb, 0xdb, 0xdb,
0xdc, 0xdc, 0xdc, 0xdd, 0xdd, 0xdd, 0xde, 0xde, 0xde, 0xdf, 0xdf, 0xdf,
0xe0, 0xe0, 0xe0, 0xe1, 0xe1, 0xe1, 0xe2, 0xe2, 0xe2, 0xe3, 0xe3, 0xe3,
0xe4, 0xe4, 0xe4, 0xe5, 0xe5, 0xe5, 0xe6, 0xe6, 0xe6, 0xe7, 0xe7, 0xe7,
0xe8, 0xe8, 0xe8, 0xe9, 0xe9, 0xe9, 0xea, 0xea, 0xea, 0xeb, 0xeb, 0xeb,
0xec, 0xec, 0xec, 0xed, 0xed, 0xed, 0xee, 0xee, 0xee, 0xef, 0xef, 0xef,
0xf0, 0xf0, 0xf0, 0xf1, 0xf1, 0xf1, 0xf2, 0xf2, 0xf2, 0xf3, 0xf3, 0xf3,
0xf4, 0xf4, 0xf4, 0xf5, 0xf5, 0xf5, 0xf6, 0xf6, 0xf6, 0xf7, 0xf7, 0xf7,
0xf8, 0xf8, 0xf8, 0xf9, 0xf9, 0xf9, 0xfa, 0xfa, 0xfa, 0xfb, 0xfb, 0xfb,
0xfc, 0xfc, 0xfc, 0xfd, 0xfd, 0xfd, 0xfe, 0xfe, 0xfe, 0xff, 0xff, 0xff
};
static const unsigned char pal_xterm256[] = {
0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x80, 0x80, 0x00,
0x00, 0x00, 0x80, 0x80, 0x00, 0x80, 0x00, 0x80, 0x80, 0xc0, 0xc0, 0xc0,
0x80, 0x80, 0x80, 0xff, 0x00, 0x00, 0x00, 0xff, 0x00, 0xff, 0xff, 0x00,
0x00, 0x00, 0xff, 0xff, 0x00, 0xff, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff,
0x00, 0x00, 0x00, 0x00, 0x00, 0x5f, 0x00, 0x00, 0x87, 0x00, 0x00, 0xaf,
0x00, 0x00, 0xd7, 0x00, 0x00, 0xff, 0x00, 0x5f, 0x00, 0x00, 0x5f, 0x5f,
0x00, 0x5f, 0x87, 0x00, 0x5f, 0xaf, 0x00, 0x5f, 0xd7, 0x00, 0x5f, 0xff,
0x00, 0x87, 0x00, 0x00, 0x87, 0x5f, 0x00, 0x87, 0x87, 0x00, 0x87, 0xaf,
0x00, 0x87, 0xd7, 0x00, 0x87, 0xff, 0x00, 0xaf, 0x00, 0x00, 0xaf, 0x5f,
0x00, 0xaf, 0x87, 0x00, 0xaf, 0xaf, 0x00, 0xaf, 0xd7, 0x00, 0xaf, 0xff,
0x00, 0xd7, 0x00, 0x00, 0xd7, 0x5f, 0x00, 0xd7, 0x87, 0x00, 0xd7, 0xaf,
0x00, 0xd7, 0xd7, 0x00, 0xd7, 0xff, 0x00, 0xff, 0x00, 0x00, 0xff, 0x5f,
0x00, 0xff, 0x87, 0x00, 0xff, 0xaf, 0x00, 0xff, 0xd7, 0x00, 0xff, 0xff,
0x5f, 0x00, 0x00, 0x5f, 0x00, 0x5f, 0x5f, 0x00, 0x87, 0x5f, 0x00, 0xaf,
0x5f, 0x00, 0xd7, 0x5f, 0x00, 0xff, 0x5f, 0x5f, 0x00, 0x5f, 0x5f, 0x5f,
0x5f, 0x5f, 0x87, 0x5f, 0x5f, 0xaf, 0x5f, 0x5f, 0xd7, 0x5f, 0x5f, 0xff,
0x5f, 0x87, 0x00, 0x5f, 0x87, 0x5f, 0x5f, 0x87, 0x87, 0x5f, 0x87, 0xaf,
0x5f, 0x87, 0xd7, 0x5f, 0x87, 0xff, 0x5f, 0xaf, 0x00, 0x5f, 0xaf, 0x5f,
0x5f, 0xaf, 0x87, 0x5f, 0xaf, 0xaf, 0x5f, 0xaf, 0xd7, 0x5f, 0xaf, 0xff,
0x5f, 0xd7, 0x00, 0x5f, 0xd7, 0x5f, 0x5f, 0xd7, 0x87, 0x5f, 0xd7, 0xaf,
0x5f, 0xd7, 0xd7, 0x5f, 0xd7, 0xff, 0x5f, 0xff, 0x00, 0x5f, 0xff, 0x5f,
0x5f, 0xff, 0x87, 0x5f, 0xff, 0xaf, 0x5f, 0xff, 0xd7, 0x5f, 0xff, 0xff,
0x87, 0x00, 0x00, 0x87, 0x00, 0x5f, 0x87, 0x00, 0x87, 0x87, 0x00, 0xaf,
0x87, 0x00, 0xd7, 0x87, 0x00, 0xff, 0x87, 0x5f, 0x00, 0x87, 0x5f, 0x5f,
0x87, 0x5f, 0x87, 0x87, 0x5f, 0xaf, 0x87, 0x5f, 0xd7, 0x87, 0x5f, 0xff,
0x87, 0x87, 0x00, 0x87, 0x87, 0x5f, 0x87, 0x87, 0x87, 0x87, 0x87, 0xaf,
0x87, 0x87, 0xd7, 0x87, 0x87, 0xff, 0x87, 0xaf, 0x00, 0x87, 0xaf, 0x5f,
0x87, 0xaf, 0x87, 0x87, 0xaf, 0xaf, 0x87, 0xaf, 0xd7, 0x87, 0xaf, 0xff,
0x87, 0xd7, 0x00, 0x87, 0xd7, 0x5f, 0x87, 0xd7, 0x87, 0x87, 0xd7, 0xaf,
0x87, 0xd7, 0xd7, 0x87, 0xd7, 0xff, 0x87, 0xff, 0x00, 0x87, 0xff, 0x5f,
0x87, 0xff, 0x87, 0x87, 0xff, 0xaf, 0x87, 0xff, 0xd7, 0x87, 0xff, 0xff,
0xaf, 0x00, 0x00, 0xaf, 0x00, 0x5f, 0xaf, 0x00, 0x87, 0xaf, 0x00, 0xaf,
0xaf, 0x00, 0xd7, 0xaf, 0x00, 0xff, 0xaf, 0x5f, 0x00, 0xaf, 0x5f, 0x5f,
0xaf, 0x5f, 0x87, 0xaf, 0x5f, 0xaf, 0xaf, 0x5f, 0xd7, 0xaf, 0x5f, 0xff,
0xaf, 0x87, 0x00, 0xaf, 0x87, 0x5f, 0xaf, 0x87, 0x87, 0xaf, 0x87, 0xaf,
0xaf, 0x87, 0xd7, 0xaf, 0x87, 0xff, 0xaf, 0xaf, 0x00, 0xaf, 0xaf, 0x5f,
0xaf, 0xaf, 0x87, 0xaf, 0xaf, 0xaf, 0xaf, 0xaf, 0xd7, 0xaf, 0xaf, 0xff,
0xaf, 0xd7, 0x00, 0xaf, 0xd7, 0x5f, 0xaf, 0xd7, 0x87, 0xaf, 0xd7, 0xaf,
0xaf, 0xd7, 0xd7, 0xaf, 0xd7, 0xff, 0xaf, 0xff, 0x00, 0xaf, 0xff, 0x5f,
0xaf, 0xff, 0x87, 0xaf, 0xff, 0xaf, 0xaf, 0xff, 0xd7, 0xaf, 0xff, 0xff,
0xd7, 0x00, 0x00, 0xd7, 0x00, 0x5f, 0xd7, 0x00, 0x87, 0xd7, 0x00, 0xaf,
0xd7, 0x00, 0xd7, 0xd7, 0x00, 0xff, 0xd7, 0x5f, 0x00, 0xd7, 0x5f, 0x5f,
0xd7, 0x5f, 0x87, 0xd7, 0x5f, 0xaf, 0xd7, 0x5f, 0xd7, 0xd7, 0x5f, 0xff,
0xd7, 0x87, 0x00, 0xd7, 0x87, 0x5f, 0xd7, 0x87, 0x87, 0xd7, 0x87, 0xaf,
0xd7, 0x87, 0xd7, 0xd7, 0x87, 0xff, 0xd7, 0xaf, 0x00, 0xd7, 0xaf, 0x5f,
0xd7, 0xaf, 0x87, 0xd7, 0xaf, 0xaf, 0xd7, 0xaf, 0xd7, 0xd7, 0xaf, 0xff,
0xd7, 0xd7, 0x00, 0xd7, 0xd7, 0x5f, 0xd7, 0xd7, 0x87, 0xd7, 0xd7, 0xaf,
0xd7, 0xd7, 0xd7, 0xd7, 0xd7, 0xff, 0xd7, 0xff, 0x00, 0xd7, 0xff, 0x5f,
0xd7, 0xff, 0x87, 0xd7, 0xff, 0xaf, 0xd7, 0xff, 0xd7, 0xd7, 0xff, 0xff,
0xff, 0x00, 0x00, 0xff, 0x00, 0x5f, 0xff, 0x00, 0x87, 0xff, 0x00, 0xaf,
0xff, 0x00, 0xd7, 0xff, 0x00, 0xff, 0xff, 0x5f, 0x00, 0xff, 0x5f, 0x5f,
0xff, 0x5f, 0x87, 0xff, 0x5f, 0xaf, 0xff, 0x5f, 0xd7, 0xff, 0x5f, 0xff,
0xff, 0x87, 0x00, 0xff, 0x87, 0x5f, 0xff, 0x87, 0x87, 0xff, 0x87, 0xaf,
0xff, 0x87, 0xd7, 0xff, 0x87, 0xff, 0xff, 0xaf, 0x00, 0xff, 0xaf, 0x5f,
0xff, 0xaf, 0x87, 0xff, 0xaf, 0xaf, 0xff, 0xaf, 0xd7, 0xff, 0xaf, 0xff,
0xff, 0xd7, 0x00, 0xff, 0xd7, 0x5f, 0xff, 0xd7, 0x87, 0xff, 0xd7, 0xaf,
0xff, 0xd7, 0xd7, 0xff, 0xd7, 0xff, 0xff, 0xff, 0x00, 0xff, 0xff, 0x5f,
0xff, 0xff, 0x87, 0xff, 0xff, 0xaf, 0xff, 0xff, 0xd7, 0xff, 0xff, 0xff,
0x08, 0x08, 0x08, 0x12, 0x12, 0x12, 0x1c, 0x1c, 0x1c, 0x26, 0x26, 0x26,
0x30, 0x30, 0x30, 0x3a, 0x3a, 0x3a, 0x44, 0x44, 0x44, 0x4e, 0x4e, 0x4e,
0x58, 0x58, 0x58, 0x62, 0x62, 0x62, 0x6c, 0x6c, 0x6c, 0x76, 0x76, 0x76,
0x80, 0x80, 0x80, 0x8a, 0x8a, 0x8a, 0x94, 0x94, 0x94, 0x9e, 0x9e, 0x9e,
0xa8, 0xa8, 0xa8, 0xb2, 0xb2, 0xb2, 0xbc, 0xbc, 0xbc, 0xc6, 0xc6, 0xc6,
0xd0, 0xd0, 0xd0, 0xda, 0xda, 0xda, 0xe4, 0xe4, 0xe4, 0xee, 0xee, 0xee,
};
/*
* VT340 undocumented behavior regarding the color palette reported
* by Vertis Sidus(@vrtsds):
* it loads the first fifteen colors as 1 through 15, and loads the
* sixteenth color as 0.
*/
static const unsigned char pal_vt340_mono[] = {
/* 1 Gray-2 */ 13 * 255 / 100, 13 * 255 / 100, 13 * 255 / 100,
/* 2 Gray-4 */ 26 * 255 / 100, 26 * 255 / 100, 26 * 255 / 100,
/* 3 Gray-6 */ 40 * 255 / 100, 40 * 255 / 100, 40 * 255 / 100,
/* 4 Gray-1 */ 6 * 255 / 100, 6 * 255 / 100, 6 * 255 / 100,
/* 5 Gray-3 */ 20 * 255 / 100, 20 * 255 / 100, 20 * 255 / 100,
/* 6 Gray-5 */ 33 * 255 / 100, 33 * 255 / 100, 33 * 255 / 100,
/* 7 White 7 */ 46 * 255 / 100, 46 * 255 / 100, 46 * 255 / 100,
/* 8 Black 0 */ 0 * 255 / 100, 0 * 255 / 100, 0 * 255 / 100,
/* 9 Gray-2 */ 13 * 255 / 100, 13 * 255 / 100, 13 * 255 / 100,
/* 10 Gray-4 */ 26 * 255 / 100, 26 * 255 / 100, 26 * 255 / 100,
/* 11 Gray-6 */ 40 * 255 / 100, 40 * 255 / 100, 40 * 255 / 100,
/* 12 Gray-1 */ 6 * 255 / 100, 6 * 255 / 100, 6 * 255 / 100,
/* 13 Gray-3 */ 20 * 255 / 100, 20 * 255 / 100, 20 * 255 / 100,
/* 14 Gray-5 */ 33 * 255 / 100, 33 * 255 / 100, 33 * 255 / 100,
/* 15 White 7 */ 46 * 255 / 100, 46 * 255 / 100, 46 * 255 / 100,
/* 0 Black */ 0 * 255 / 100, 0 * 255 / 100, 0 * 255 / 100,
};
static const unsigned char pal_vt340_color[] = {
/* 1 Blue */ 20 * 255 / 100, 20 * 255 / 100, 80 * 255 / 100,
/* 2 Red */ 80 * 255 / 100, 13 * 255 / 100, 13 * 255 / 100,
/* 3 Green */ 20 * 255 / 100, 80 * 255 / 100, 20 * 255 / 100,
/* 4 Magenta */ 80 * 255 / 100, 20 * 255 / 100, 80 * 255 / 100,
/* 5 Cyan */ 20 * 255 / 100, 80 * 255 / 100, 80 * 255 / 100,
/* 6 Yellow */ 80 * 255 / 100, 80 * 255 / 100, 20 * 255 / 100,
/* 7 Gray 50% */ 53 * 255 / 100, 53 * 255 / 100, 53 * 255 / 100,
/* 8 Gray 25% */ 26 * 255 / 100, 26 * 255 / 100, 26 * 255 / 100,
/* 9 Blue* */ 33 * 255 / 100, 33 * 255 / 100, 60 * 255 / 100,
/* 10 Red* */ 60 * 255 / 100, 26 * 255 / 100, 26 * 255 / 100,
/* 11 Green* */ 33 * 255 / 100, 60 * 255 / 100, 33 * 255 / 100,
/* 12 Magenta* */ 60 * 255 / 100, 33 * 255 / 100, 60 * 255 / 100,
/* 13 Cyan* */ 33 * 255 / 100, 60 * 255 / 100, 60 * 255 / 100,
/* 14 Yellow* */ 60 * 255 / 100, 60 * 255 / 100, 33 * 255 / 100,
/* 15 Gray 75% */ 80 * 255 / 100, 80 * 255 / 100, 80 * 255 / 100,
/* 0 Black */ 0 * 255 / 100, 0 * 255 / 100, 0 * 255 / 100,
};
/* create dither context object */
SIXELAPI SIXELSTATUS
sixel_dither_new(
sixel_dither_t /* out */ **ppdither, /* dither object to be created */
int /* in */ ncolors, /* required colors */
sixel_allocator_t /* in */ *allocator) /* allocator, null if you use
default allocator */
{
SIXELSTATUS status = SIXEL_FALSE;
size_t headsize;
size_t datasize;
size_t wholesize;
int quality_mode;
/* ensure given pointer is not null */
if (ppdither == NULL) {
sixel_helper_set_additional_message(
"sixel_dither_new: ppdither is null.");
status = SIXEL_BAD_ARGUMENT;
goto end;
}
if (allocator == NULL) {
status = sixel_allocator_new(&allocator, NULL, NULL, NULL, NULL);
if (SIXEL_FAILED(status)) {
*ppdither = NULL;
goto end;
}
} else {
sixel_allocator_ref(allocator);
}
if (ncolors < 0) {
ncolors = SIXEL_PALETTE_MAX;
quality_mode = SIXEL_QUALITY_HIGHCOLOR;
} else {
if (ncolors > SIXEL_PALETTE_MAX) {
status = SIXEL_BAD_INPUT;
goto end;
} else if (ncolors < 1) {
status = SIXEL_BAD_INPUT;
sixel_helper_set_additional_message(
"sixel_dither_new: palette colors must be more than 0");
goto end;
}
quality_mode = SIXEL_QUALITY_LOW;
}
headsize = sizeof(sixel_dither_t);
datasize = (size_t)(ncolors * 3);
wholesize = headsize + datasize;
*ppdither = (sixel_dither_t *)sixel_allocator_malloc(allocator, wholesize);
if (*ppdither == NULL) {
sixel_allocator_unref(allocator);
sixel_helper_set_additional_message(
"sixel_dither_new: sixel_allocator_malloc() failed.");
status = SIXEL_BAD_ALLOCATION;
goto end;
}
(*ppdither)->ref = 1;
(*ppdither)->palette = (unsigned char*)(*ppdither + 1);
(*ppdither)->cachetable = NULL;
(*ppdither)->reqcolors = ncolors;
(*ppdither)->ncolors = ncolors;
(*ppdither)->origcolors = (-1);
(*ppdither)->keycolor = (-1);
(*ppdither)->optimized = 0;
(*ppdither)->optimize_palette = 0;
(*ppdither)->complexion = 1;
(*ppdither)->bodyonly = 0;
(*ppdither)->method_for_largest = SIXEL_LARGE_NORM;
(*ppdither)->method_for_rep = SIXEL_REP_CENTER_BOX;
(*ppdither)->method_for_diffuse = SIXEL_DIFFUSE_FS;
(*ppdither)->quality_mode = quality_mode;
(*ppdither)->pixelformat = SIXEL_PIXELFORMAT_RGB888;
(*ppdither)->allocator = allocator;
status = SIXEL_OK;
end:
return status;
}
/* create dither context object (deprecated) */
SIXELAPI sixel_dither_t *
sixel_dither_create(
int /* in */ ncolors)
{
SIXELSTATUS status = SIXEL_FALSE;
sixel_dither_t *dither = NULL;
status = sixel_dither_new(&dither, ncolors, NULL);
if (SIXEL_FAILED(status)) {
goto end;
}
end:
return dither;
}
SIXELAPI void
sixel_dither_destroy(
sixel_dither_t /* in */ *dither)
{
sixel_allocator_t *allocator;
if (dither) {
allocator = dither->allocator;
sixel_allocator_free(allocator, dither->cachetable);
dither->cachetable = NULL;
sixel_allocator_free(allocator, dither);
sixel_allocator_unref(allocator);
}
}
SIXELAPI void
sixel_dither_ref(
sixel_dither_t /* in */ *dither)
{
/* TODO: be thread safe */
++dither->ref;
}
SIXELAPI void
sixel_dither_unref(
sixel_dither_t /* in */ *dither)
{
/* TODO: be thread safe */
if (dither != NULL && --dither->ref == 0) {
sixel_dither_destroy(dither);
}
}
SIXELAPI sixel_dither_t *
sixel_dither_get(
int /* in */ builtin_dither)
{
SIXELSTATUS status = SIXEL_FALSE;
unsigned char *palette;
int ncolors;
int keycolor;
sixel_dither_t *dither = NULL;
switch (builtin_dither) {
case SIXEL_BUILTIN_MONO_DARK:
ncolors = 2;
palette = (unsigned char *)pal_mono_dark;
keycolor = 0;
break;
case SIXEL_BUILTIN_MONO_LIGHT:
ncolors = 2;
palette = (unsigned char *)pal_mono_light;
keycolor = 0;
break;
case SIXEL_BUILTIN_XTERM16:
ncolors = 16;
palette = (unsigned char *)pal_xterm256;
keycolor = (-1);
break;
case SIXEL_BUILTIN_XTERM256:
ncolors = 256;
palette = (unsigned char *)pal_xterm256;
keycolor = (-1);
break;
case SIXEL_BUILTIN_VT340_MONO:
ncolors = 16;
palette = (unsigned char *)pal_vt340_mono;
keycolor = (-1);
break;
case SIXEL_BUILTIN_VT340_COLOR:
ncolors = 16;
palette = (unsigned char *)pal_vt340_color;
keycolor = (-1);
break;
case SIXEL_BUILTIN_G1:
ncolors = 2;
palette = (unsigned char *)pal_gray_1bit;
keycolor = (-1);
break;
case SIXEL_BUILTIN_G2:
ncolors = 4;
palette = (unsigned char *)pal_gray_2bit;
keycolor = (-1);
break;
case SIXEL_BUILTIN_G4:
ncolors = 16;
palette = (unsigned char *)pal_gray_4bit;
keycolor = (-1);
break;
case SIXEL_BUILTIN_G8:
ncolors = 256;
palette = (unsigned char *)pal_gray_8bit;
keycolor = (-1);
break;
default:
goto end;
}
status = sixel_dither_new(&dither, ncolors, NULL);
if (SIXEL_FAILED(status)) {
dither = NULL;
goto end;
}
dither->palette = palette;
dither->keycolor = keycolor;
dither->optimized = 1;
dither->optimize_palette = 0;
end:
return dither;
}
static void
sixel_dither_set_method_for_largest(
sixel_dither_t /* in */ *dither,
int /* in */ method_for_largest)
{
if (method_for_largest == SIXEL_LARGE_AUTO) {
method_for_largest = SIXEL_LARGE_NORM;
}
dither->method_for_largest = method_for_largest;
}
static void
sixel_dither_set_method_for_rep(
sixel_dither_t /* in */ *dither,
int /* in */ method_for_rep)
{
if (method_for_rep == SIXEL_REP_AUTO) {
method_for_rep = SIXEL_REP_CENTER_BOX;
}
dither->method_for_rep = method_for_rep;
}
static void
sixel_dither_set_quality_mode(
sixel_dither_t /* in */ *dither,
int /* in */ quality_mode)
{
if (quality_mode == SIXEL_QUALITY_AUTO) {
if (dither->ncolors <= 8) {
quality_mode = SIXEL_QUALITY_HIGH;
} else {
quality_mode = SIXEL_QUALITY_LOW;
}
}
dither->quality_mode = quality_mode;
}
SIXELAPI SIXELSTATUS
sixel_dither_initialize(
sixel_dither_t /* in */ *dither,
unsigned char /* in */ *data,
int /* in */ width,
int /* in */ height,
int /* in */ pixelformat,
int /* in */ method_for_largest,
int /* in */ method_for_rep,
int /* in */ quality_mode)
{
unsigned char *buf = NULL;
unsigned char *normalized_pixels = NULL;
unsigned char *input_pixels;
SIXELSTATUS status = SIXEL_FALSE;
/* ensure dither object is not null */
if (dither == NULL) {
sixel_helper_set_additional_message(
"sixel_dither_new: dither is null.");
status = SIXEL_BAD_ARGUMENT;
goto end;
}
/* increment ref count */
sixel_dither_ref(dither);
sixel_dither_set_pixelformat(dither, pixelformat);
switch (pixelformat) {
case SIXEL_PIXELFORMAT_RGB888:
input_pixels = data;
break;
default:
/* normalize pixelformat */
normalized_pixels
= (unsigned char *)sixel_allocator_malloc(dither->allocator, (size_t)(width * height * 3));
if (normalized_pixels == NULL) {
sixel_helper_set_additional_message(
"sixel_dither_initialize: sixel_allocator_malloc() failed.");
status = SIXEL_BAD_ALLOCATION;
goto end;
}
status = sixel_helper_normalize_pixelformat(
normalized_pixels,
&pixelformat,
data,
pixelformat,
width,
height);
if (SIXEL_FAILED(status)) {
goto end;
}
input_pixels = normalized_pixels;
break;
}
sixel_dither_set_method_for_largest(dither, method_for_largest);
sixel_dither_set_method_for_rep(dither, method_for_rep);
sixel_dither_set_quality_mode(dither, quality_mode);
status = sixel_quant_make_palette(&buf,
input_pixels,
(unsigned int)(width * height * 3),
SIXEL_PIXELFORMAT_RGB888,
(unsigned int)dither->reqcolors,
(unsigned int *)&dither->ncolors,
(unsigned int *)&dither->origcolors,
dither->method_for_largest,
dither->method_for_rep,
dither->quality_mode,
dither->allocator);
if (SIXEL_FAILED(status)) {
goto end;
}
memcpy(dither->palette, buf, (size_t)(dither->ncolors * 3));
dither->optimized = 1;
if (dither->origcolors <= dither->ncolors) {
dither->method_for_diffuse = SIXEL_DIFFUSE_NONE;
}
sixel_quant_free_palette(buf, dither->allocator);
status = SIXEL_OK;
end:
free(normalized_pixels);
/* decrement ref count */
sixel_dither_unref(dither);
return status;
}
/* set diffusion type, choose from enum methodForDiffuse */
SIXELAPI void
sixel_dither_set_diffusion_type(
sixel_dither_t /* in */ *dither,
int /* in */ method_for_diffuse)
{
if (method_for_diffuse == SIXEL_DIFFUSE_AUTO) {
if (dither->ncolors > 16) {
method_for_diffuse = SIXEL_DIFFUSE_FS;
} else {
method_for_diffuse = SIXEL_DIFFUSE_ATKINSON;
}
}
dither->method_for_diffuse = method_for_diffuse;
}
/* get number of palette colors */
SIXELAPI int
sixel_dither_get_num_of_palette_colors(
sixel_dither_t /* in */ *dither)
{
return dither->ncolors;
}
/* get number of histogram colors */
SIXELAPI int
sixel_dither_get_num_of_histogram_colors(
sixel_dither_t /* in */ *dither) /* dither context object */
{
return dither->origcolors;
}
/* typoed: remained for keeping compatibility */
SIXELAPI int
sixel_dither_get_num_of_histgram_colors(
sixel_dither_t /* in */ *dither) /* dither context object */
{
return sixel_dither_get_num_of_histogram_colors(dither);
}
/* get palette */
SIXELAPI unsigned char *
sixel_dither_get_palette(
sixel_dither_t /* in */ *dither) /* dither context object */
{
return dither->palette;
}
/* set palette */
SIXELAPI void
sixel_dither_set_palette(
sixel_dither_t /* in */ *dither, /* dither context object */
unsigned char /* in */ *palette)
{
memcpy(dither->palette, palette, (size_t)(dither->ncolors * 3));
}
/* set the factor of complexion color correcting */
SIXELAPI void
sixel_dither_set_complexion_score(
sixel_dither_t /* in */ *dither, /* dither context object */
int /* in */ score) /* complexion score (>= 1) */
{
dither->complexion = score;
}
/* set whether omitting palette difinition */
SIXELAPI void
sixel_dither_set_body_only(
sixel_dither_t /* in */ *dither, /* dither context object */
int /* in */ bodyonly) /* 0: output palette section
1: do not output palette section */
{
dither->bodyonly = bodyonly;
}
/* set whether optimize palette size */
SIXELAPI void
sixel_dither_set_optimize_palette(
sixel_dither_t /* in */ *dither, /* dither context object */
int /* in */ do_opt) /* 0: optimize palette size
1: don't optimize palette size */
{
dither->optimize_palette = do_opt;
}
/* set pixelformat */
SIXELAPI void
sixel_dither_set_pixelformat(
sixel_dither_t /* in */ *dither, /* dither context object */
int /* in */ pixelformat) /* one of enum pixelFormat */
{
dither->pixelformat = pixelformat;
}
/* set transparent */
SIXELAPI void
sixel_dither_set_transparent(
sixel_dither_t /* in */ *dither, /* dither context object */
int /* in */ transparent) /* transparent color index */
{
dither->keycolor = transparent;
}
/* set transparent */
SIXELAPI sixel_index_t *
sixel_dither_apply_palette(
sixel_dither_t /* in */ *dither,
unsigned char /* in */ *pixels,
int /* in */ width,
int /* in */ height)
{
SIXELSTATUS status = SIXEL_FALSE;
size_t bufsize;
sixel_index_t *dest = NULL;
int ncolors;
unsigned char *normalized_pixels = NULL;
unsigned char *input_pixels;
/* ensure dither object is not null */
if (dither == NULL) {
sixel_helper_set_additional_message(
"sixel_dither_apply_palette: dither is null.");
status = SIXEL_BAD_ARGUMENT;
goto end;
}
sixel_dither_ref(dither);
bufsize = (size_t)(width * height) * sizeof(sixel_index_t);
dest = (sixel_index_t *)sixel_allocator_malloc(dither->allocator, bufsize);
if (dest == NULL) {
sixel_helper_set_additional_message(
"sixel_dither_new: sixel_allocator_malloc() failed.");
status = SIXEL_BAD_ALLOCATION;
goto end;
}
/* if quality_mode is full, do not use palette caching */
if (dither->quality_mode == SIXEL_QUALITY_FULL) {
dither->optimized = 0;
}
if (dither->cachetable == NULL && dither->optimized) {
if (dither->palette != pal_mono_dark && dither->palette != pal_mono_light) {
dither->cachetable = (unsigned short *)sixel_allocator_calloc(dither->allocator,
(size_t)(1 << 3 * 5),
sizeof(unsigned short));
if (dither->cachetable == NULL) {
sixel_helper_set_additional_message(
"sixel_dither_new: sixel_allocator_calloc() failed.");
status = SIXEL_BAD_ALLOCATION;
goto end;
}
}
}
if (dither->pixelformat != SIXEL_PIXELFORMAT_RGB888) {
/* normalize pixelformat */
normalized_pixels
= (unsigned char *)sixel_allocator_malloc(dither->allocator, (size_t)(width * height * 3));
if (normalized_pixels == NULL) {
sixel_helper_set_additional_message(
"sixel_dither_new: sixel_allocator_malloc() failed.");
status = SIXEL_BAD_ALLOCATION;
goto end;
}
status = sixel_helper_normalize_pixelformat(normalized_pixels,
&dither->pixelformat,
pixels, dither->pixelformat,
width, height);
if (SIXEL_FAILED(status)) {
goto end;
}
input_pixels = normalized_pixels;
} else {
input_pixels = pixels;
}
status = sixel_quant_apply_palette(dest,
input_pixels,
width, height, 3,
dither->palette,
dither->ncolors,
dither->method_for_diffuse,
dither->optimized,
dither->optimize_palette,
dither->complexion,
dither->cachetable,
&ncolors,
dither->allocator);
if (SIXEL_FAILED(status)) {
free(dest);
dest = NULL;
goto end;
}
dither->ncolors = ncolors;
end:
free(normalized_pixels);
sixel_dither_unref(dither);
return dest;
}
#if HAVE_TESTS
static int
test1(void)
{
sixel_dither_t *dither = NULL;
int nret = EXIT_FAILURE;
#if HAVE_DIAGNOSTIC_DEPRECATED_DECLARATIONS
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif
dither = sixel_dither_create(2);
#if HAVE_DIAGNOSTIC_DEPRECATED_DECLARATIONS
# pragma GCC diagnostic pop
#endif
if (dither == NULL) {
goto error;
}
sixel_dither_ref(dither);
sixel_dither_unref(dither);
nret = EXIT_SUCCESS;
error:
sixel_dither_unref(dither);
return nret;
}
static int
test2(void)
{
sixel_dither_t *dither = NULL;
int colors;
int nret = EXIT_FAILURE;
#if HAVE_DIAGNOSTIC_DEPRECATED_DECLARATIONS
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif
dither = sixel_dither_create(INT_MAX);
#if HAVE_DIAGNOSTIC_DEPRECATED_DECLARATIONS
# pragma GCC diagnostic pop
#endif
if (dither == NULL) {
goto error;
}
sixel_dither_set_body_only(dither, 1);
colors = sixel_dither_get_num_of_histogram_colors(dither);
if (colors != -1) {
goto error;
}
nret = EXIT_SUCCESS;
error:
sixel_dither_unref(dither);
return nret;
}
SIXELAPI int
sixel_dither_tests_main(void)
{
int nret = EXIT_FAILURE;
size_t i;
typedef int (* testcase)(void);
static testcase const testcases[] = {
test1,
test2,
};
for (i = 0; i < sizeof(testcases) / sizeof(testcase); ++i) {
nret = testcases[i]();
if (nret != EXIT_SUCCESS) {
goto error;
}
}
nret = EXIT_SUCCESS;
error:
return nret;
}
#endif /* HAVE_TESTS */
/* emacs Local Variables: */
/* emacs mode: c */
/* emacs tab-width: 4 */
/* emacs indent-tabs-mode: nil */
/* emacs c-basic-offset: 4 */
/* emacs End: */
/* vim: set expandtab ts=4 sts=4 sw=4 : */
/* EOF */
+78
View File
@@ -0,0 +1,78 @@
/*
* Copyright (c) 2014-2016 Hayaki Saito
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef LIBSIXEL_DITHER_H
#define LIBSIXEL_DITHER_H
#include <sixel.h>
/* dither context object */
struct sixel_dither {
unsigned int ref; /* reference counter */
unsigned char *palette; /* palette definition */
unsigned short *cachetable; /* cache table */
int reqcolors; /* requested colors */
int ncolors; /* active colors */
int origcolors; /* original colors */
int optimized; /* pixel is 15bpp compressable */
int optimize_palette; /* minimize palette size */
int complexion; /* for complexion correction */
int bodyonly; /* do not output palette section if true */
int method_for_largest; /* method for finding the largest dimention
for splitting */
int method_for_rep; /* method for choosing a color from the box */
int method_for_diffuse; /* method for diffusing */
int quality_mode; /* quality of histogram */
int keycolor; /* background color */
int pixelformat; /* pixelformat for internal processing */
sixel_allocator_t *allocator; /* allocator */
};
#ifdef __cplusplus
extern "C" {
#endif
/* apply palette */
sixel_index_t *
sixel_dither_apply_palette(struct sixel_dither /* in */ *dither,
unsigned char /* in */ *pixels,
int /* in */ width,
int /* in */ height);
#if HAVE_TESTS
int
sixel_frame_tests_main(void);
#endif
#ifdef __cplusplus
}
#endif
#endif /* LIBSIXEL_DITHER_H */
/* emacs Local Variables: */
/* emacs mode: c */
/* emacs tab-width: 4 */
/* emacs indent-tabs-mode: nil */
/* emacs c-basic-offset: 4 */
/* emacs End: */
/* vim: set expandtab ts=4 sts=4 sw=4 : */
/* EOF */
+50
View File
@@ -0,0 +1,50 @@
/*
* Copyright (c) 2014-2016 Hayaki Saito
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef MALLOC_STUB_H
#define MALLOC_STUB_H
#if HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif /* HAVE_SYS_TYPES_H */
#if !HAVE_MALLOC
void * rpl_malloc(size_t n);
#endif /* !HAVE_MALLOC */
#if !HAVE_REALLOC
void * rpl_realloc(void *p, size_t n);
#endif /* !HAVE_REALLOC */
#if 0
int rpl_posix_memalign(void **memptr, size_t alignment, size_t size);
#endif
#endif /* MALLOC_STUB_H */
/* emacs Local Variables: */
/* emacs mode: c */
/* emacs tab-width: 4 */
/* emacs indent-tabs-mode: nil */
/* emacs c-basic-offset: 4 */
/* emacs End: */
/* vim: set expandtab ts=4 sts=4 sw=4 : */
/* EOF */
+210
View File
@@ -0,0 +1,210 @@
/*
* Copyright (c) 2014-2019 Hayaki Saito
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "config.h"
/* STDC_HEADERS */
# include <stdio.h>
# include <stdlib.h>
#if HAVE_ASSERT_H
# include <assert.h>
#endif /* HAVE_ASSERT_H */
#include <sixel.h>
#include "output.h"
/* create new output context object */
SIXELAPI SIXELSTATUS
sixel_output_new(
sixel_output_t /* out */ **output,
sixel_write_function /* in */ fn_write,
void /* in */ *priv,
sixel_allocator_t /* in */ *allocator)
{
SIXELSTATUS status = SIXEL_FALSE;
size_t size;
if (allocator == NULL) {
status = sixel_allocator_new(&allocator, NULL, NULL, NULL, NULL);
if (SIXEL_FAILED(status)) {
goto end;
}
} else {
sixel_allocator_ref(allocator);
}
size = sizeof(sixel_output_t) + SIXEL_OUTPUT_PACKET_SIZE * 2;
*output = (sixel_output_t *)sixel_allocator_malloc(allocator, size);
if (*output == NULL) {
sixel_helper_set_additional_message(
"sixel_output_new: sixel_allocator_malloc() failed.");
status = SIXEL_BAD_ALLOCATION;
goto end;
}
(*output)->ref = 1;
(*output)->has_8bit_control = 0;
(*output)->has_sdm_glitch = 0;
(*output)->has_gri_arg_limit = 1;
(*output)->skip_dcs_envelope = 0;
(*output)->palette_type = SIXEL_PALETTETYPE_AUTO;
(*output)->fn_write = fn_write;
(*output)->save_pixel = 0;
(*output)->save_count = 0;
(*output)->active_palette = (-1);
(*output)->node_top = NULL;
(*output)->node_free = NULL;
(*output)->priv = priv;
(*output)->pos = 0;
(*output)->penetrate_multiplexer = 0;
(*output)->encode_policy = SIXEL_ENCODEPOLICY_AUTO;
(*output)->allocator = allocator;
status = SIXEL_OK;
end:
return status;
}
/* deprecated: create an output object */
SIXELAPI sixel_output_t *
sixel_output_create(sixel_write_function fn_write, void *priv)
{
SIXELSTATUS status = SIXEL_FALSE;
sixel_output_t *output = NULL;
status = sixel_output_new(&output, fn_write, priv, NULL);
if (SIXEL_FAILED(status)) {
goto end;
}
end:
return output;
}
/* destroy output context object */
SIXELAPI void
sixel_output_destroy(sixel_output_t *output)
{
sixel_allocator_t *allocator;
if (output) {
allocator = output->allocator;
sixel_allocator_free(allocator, output);
sixel_allocator_unref(allocator);
}
}
/* increase reference count of output context object (thread-unsafe) */
SIXELAPI void
sixel_output_ref(sixel_output_t *output)
{
/* TODO: be thread-safe */
++output->ref;
}
/* decrease reference count of output context object (thread-unsafe) */
SIXELAPI void
sixel_output_unref(sixel_output_t *output)
{
/* TODO: be thread-safe */
if (output) {
assert(output->ref > 0);
output->ref--;
if (output->ref == 0) {
sixel_output_destroy(output);
}
}
}
/* get 8bit output mode which indicates whether it uses C1 control characters */
SIXELAPI int
sixel_output_get_8bit_availability(sixel_output_t *output)
{
return output->has_8bit_control;
}
/* set 8bit output mode state */
SIXELAPI void
sixel_output_set_8bit_availability(sixel_output_t *output, int availability)
{
output->has_8bit_control = availability;
}
/* set whether limit arguments of DECGRI('!') to 255 */
SIXELAPI void
sixel_output_set_gri_arg_limit(
sixel_output_t /* in */ *output, /* output context */
int /* in */ value) /* 0: don't limit arguments of DECGRI
1: limit arguments of DECGRI to 255 */
{
output->has_gri_arg_limit = value;
}
/* set GNU Screen penetration feature enable or disable */
SIXELAPI void
sixel_output_set_penetrate_multiplexer(sixel_output_t *output, int penetrate)
{
output->penetrate_multiplexer = penetrate;
}
/* set whether we skip DCS envelope */
SIXELAPI void
sixel_output_set_skip_dcs_envelope(sixel_output_t *output, int skip)
{
output->skip_dcs_envelope = skip;
}
/* set palette type: RGB or HLS */
SIXELAPI void
sixel_output_set_palette_type(sixel_output_t *output, int palettetype)
{
output->palette_type = palettetype;
}
/* set encodeing policy: auto, fast or size */
SIXELAPI void
sixel_output_set_encode_policy(sixel_output_t *output, int encode_policy)
{
output->encode_policy = encode_policy;
}
/* emacs Local Variables: */
/* emacs mode: c */
/* emacs tab-width: 4 */
/* emacs indent-tabs-mode: nil */
/* emacs c-basic-offset: 4 */
/* emacs End: */
/* vim: set expandtab ts=4 sts=4 sw=4 : */
/* EOF */
+91
View File
@@ -0,0 +1,91 @@
/*
* Copyright (c) 2014-2016 Hayaki Saito
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef LIBSIXEL_OUTPUT_H
#define LIBSIXEL_OUTPUT_H
typedef struct sixel_node {
struct sixel_node *next;
int pal;
int sx;
int mx;
char *map;
} sixel_node_t;
struct sixel_output {
int ref;
sixel_allocator_t *allocator;
/* compatiblity flags */
/* 0: 7bit terminal,
* 1: 8bit terminal */
unsigned char has_8bit_control;
/* 0: the terminal has sixel scrolling
* 1: the terminal does not have sixel scrolling */
unsigned char has_sixel_scrolling;
/* 1: the argument of repeat introducer(DECGRI) is not limitted
0: the argument of repeat introducer(DECGRI) is limitted 255 */
unsigned char has_gri_arg_limit;
/* 0: DECSDM set (CSI ? 80 h) enables sixel scrolling
1: DECSDM set (CSI ? 80 h) disables sixel scrolling */
unsigned char has_sdm_glitch;
/* 0: do not skip DCS envelope
* 1: skip DCS envelope */
unsigned char skip_dcs_envelope;
/* PALETTETYPE_AUTO: select palette type automatically
* PALETTETYPE_HLS : HLS color space
* PALETTETYPE_RGB : RGB color space */
unsigned char palette_type;
sixel_write_function fn_write;
int save_pixel;
int save_count;
int active_palette;
sixel_node_t *node_top;
sixel_node_t *node_free;
int penetrate_multiplexer;
int encode_policy;
void *priv;
int pos;
unsigned char buffer[1];
};
#endif /* LIBSIXEL_OUTPUT_H */
/* emacs Local Variables: */
/* emacs mode: c */
/* emacs tab-width: 4 */
/* emacs indent-tabs-mode: nil */
/* emacs c-basic-offset: 4 */
/* emacs End: */
/* vim: set expandtab ts=4 sts=4 sw=4 : */
/* EOF */
+725
View File
@@ -0,0 +1,725 @@
/*
* Copyright (c) 2014-2019 Hayaki Saito
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "config.h"
/* STDC_HEADERS */
#include <stdio.h>
#include <stdlib.h>
#if HAVE_MEMORY_H
# include <memory.h>
#endif /* HAVE_MEMORY_H */
#include <sixel.h>
static void
get_rgb(unsigned char const *data,
int const pixelformat,
int depth,
unsigned char *r,
unsigned char *g,
unsigned char *b)
{
unsigned int pixels = 0;
#if SWAP_BYTES
unsigned int low;
unsigned int high;
#endif
int count = 0;
while (count < depth) {
pixels = *(data + count) | (pixels << 8);
count++;
}
/* TODO: we should swap bytes (only necessary on LSByte first hardware?) */
#if SWAP_BYTES
if (depth == 2) {
low = pixels & 0xff;
high = (pixels >> 8) & 0xff;
pixels = (low << 8) | high;
}
#endif
switch (pixelformat) {
case SIXEL_PIXELFORMAT_RGB555:
*r = ((pixels >> 10) & 0x1f) << 3;
*g = ((pixels >> 5) & 0x1f) << 3;
*b = ((pixels >> 0) & 0x1f) << 3;
break;
case SIXEL_PIXELFORMAT_RGB565:
*r = ((pixels >> 11) & 0x1f) << 3;
*g = ((pixels >> 5) & 0x3f) << 2;
*b = ((pixels >> 0) & 0x1f) << 3;
break;
case SIXEL_PIXELFORMAT_RGB888:
*r = (pixels >> 16) & 0xff;
*g = (pixels >> 8) & 0xff;
*b = (pixels >> 0) & 0xff;
break;
case SIXEL_PIXELFORMAT_BGR555:
*r = ((pixels >> 0) & 0x1f) << 3;
*g = ((pixels >> 5) & 0x1f) << 3;
*b = ((pixels >> 10) & 0x1f) << 3;
break;
case SIXEL_PIXELFORMAT_BGR565:
*r = ((pixels >> 0) & 0x1f) << 3;
*g = ((pixels >> 5) & 0x3f) << 2;
*b = ((pixels >> 11) & 0x1f) << 3;
break;
case SIXEL_PIXELFORMAT_BGR888:
*r = (pixels >> 0) & 0xff;
*g = (pixels >> 8) & 0xff;
*b = (pixels >> 16) & 0xff;
break;
case SIXEL_PIXELFORMAT_RGBA8888:
*r = (pixels >> 24) & 0xff;
*g = (pixels >> 16) & 0xff;
*b = (pixels >> 8) & 0xff;
break;
case SIXEL_PIXELFORMAT_ARGB8888:
*r = (pixels >> 16) & 0xff;
*g = (pixels >> 8) & 0xff;
*b = (pixels >> 0) & 0xff;
break;
case SIXEL_PIXELFORMAT_BGRA8888:
*r = (pixels >> 8) & 0xff;
*g = (pixels >> 16) & 0xff;
*b = (pixels >> 24) & 0xff;
break;
case SIXEL_PIXELFORMAT_ABGR8888:
*r = (pixels >> 0) & 0xff;
*g = (pixels >> 8) & 0xff;
*b = (pixels >> 16) & 0xff;
break;
case SIXEL_PIXELFORMAT_GA88:
*r = *g = *b = (pixels >> 8) & 0xff;
break;
case SIXEL_PIXELFORMAT_G8:
case SIXEL_PIXELFORMAT_AG88:
*r = *g = *b = pixels & 0xff;
break;
default:
*r = *g = *b = 0;
break;
}
}
SIXELAPI int
sixel_helper_compute_depth(int pixelformat)
{
int depth = (-1); /* unknown */
switch (pixelformat) {
case SIXEL_PIXELFORMAT_ARGB8888:
case SIXEL_PIXELFORMAT_RGBA8888:
case SIXEL_PIXELFORMAT_ABGR8888:
case SIXEL_PIXELFORMAT_BGRA8888:
depth = 4;
break;
case SIXEL_PIXELFORMAT_RGB888:
case SIXEL_PIXELFORMAT_BGR888:
depth = 3;
break;
case SIXEL_PIXELFORMAT_RGB555:
case SIXEL_PIXELFORMAT_RGB565:
case SIXEL_PIXELFORMAT_BGR555:
case SIXEL_PIXELFORMAT_BGR565:
case SIXEL_PIXELFORMAT_AG88:
case SIXEL_PIXELFORMAT_GA88:
depth = 2;
break;
case SIXEL_PIXELFORMAT_G1:
case SIXEL_PIXELFORMAT_G2:
case SIXEL_PIXELFORMAT_G4:
case SIXEL_PIXELFORMAT_G8:
case SIXEL_PIXELFORMAT_PAL1:
case SIXEL_PIXELFORMAT_PAL2:
case SIXEL_PIXELFORMAT_PAL4:
case SIXEL_PIXELFORMAT_PAL8:
depth = 1;
break;
default:
break;
}
return depth;
}
static void
expand_rgb(unsigned char *dst,
unsigned char const *src,
int width, int height,
int pixelformat, int depth)
{
int x;
int y;
int dst_offset;
int src_offset;
unsigned char r, g, b;
for (y = 0; y < height; y++) {
for (x = 0; x < width; x++) {
src_offset = depth * (y * width + x);
dst_offset = 3 * (y * width + x);
get_rgb(src + src_offset, pixelformat, depth, &r, &g, &b);
*(dst + dst_offset + 0) = r;
*(dst + dst_offset + 1) = g;
*(dst + dst_offset + 2) = b;
}
}
}
static SIXELSTATUS
expand_palette(unsigned char *dst, unsigned char const *src,
int width, int height, int const pixelformat)
{
SIXELSTATUS status = SIXEL_FALSE;
int x;
int y;
int i;
int bpp; /* bit per plane */
switch (pixelformat) {
case SIXEL_PIXELFORMAT_PAL1:
case SIXEL_PIXELFORMAT_G1:
bpp = 1;
break;
case SIXEL_PIXELFORMAT_PAL2:
case SIXEL_PIXELFORMAT_G2:
bpp = 2;
break;
case SIXEL_PIXELFORMAT_PAL4:
case SIXEL_PIXELFORMAT_G4:
bpp = 4;
break;
case SIXEL_PIXELFORMAT_PAL8:
case SIXEL_PIXELFORMAT_G8:
for (i = 0; i < width * height; ++i, ++src) {
*dst++ = *src;
}
status = SIXEL_OK;
goto end;
default:
status = SIXEL_BAD_ARGUMENT;
sixel_helper_set_additional_message(
"expand_palette: invalid pixelformat.");
goto end;
}
#if HAVE_DEBUG
fprintf(stderr, "expanding PAL%d to PAL8...\n", bpp);
#endif
for (y = 0; y < height; ++y) {
for (x = 0; x < width * bpp / 8; ++x) {
for (i = 0; i < 8 / bpp; ++i) {
*dst++ = *src >> (8 / bpp - 1 - i) * bpp & ((1 << bpp) - 1);
}
src++;
}
x = width - x * 8 / bpp;
if (x > 0) {
for (i = 0; i < x; ++i) {
*dst++ = *src >> (8 - (i + 1) * bpp) & ((1 << bpp) - 1);
}
src++;
}
}
status = SIXEL_OK;
end:
return status;
}
SIXELAPI SIXELSTATUS
sixel_helper_normalize_pixelformat(
unsigned char /* out */ *dst, /* destination buffer */
int /* out */ *dst_pixelformat, /* converted pixelformat */
unsigned char const /* in */ *src, /* source pixels */
int /* in */ src_pixelformat, /* format of source image */
int /* in */ width, /* width of source image */
int /* in */ height) /* height of source image */
{
SIXELSTATUS status = SIXEL_FALSE;
switch (src_pixelformat) {
case SIXEL_PIXELFORMAT_G8:
expand_rgb(dst, src, width, height, src_pixelformat, 1);
*dst_pixelformat = SIXEL_PIXELFORMAT_RGB888;
break;
case SIXEL_PIXELFORMAT_RGB565:
case SIXEL_PIXELFORMAT_RGB555:
case SIXEL_PIXELFORMAT_BGR565:
case SIXEL_PIXELFORMAT_BGR555:
case SIXEL_PIXELFORMAT_GA88:
case SIXEL_PIXELFORMAT_AG88:
expand_rgb(dst, src, width, height, src_pixelformat, 2);
*dst_pixelformat = SIXEL_PIXELFORMAT_RGB888;
break;
case SIXEL_PIXELFORMAT_RGB888:
case SIXEL_PIXELFORMAT_BGR888:
expand_rgb(dst, src, width, height, src_pixelformat, 3);
*dst_pixelformat = SIXEL_PIXELFORMAT_RGB888;
break;
case SIXEL_PIXELFORMAT_RGBA8888:
case SIXEL_PIXELFORMAT_ARGB8888:
case SIXEL_PIXELFORMAT_BGRA8888:
case SIXEL_PIXELFORMAT_ABGR8888:
expand_rgb(dst, src, width, height, src_pixelformat, 4);
*dst_pixelformat = SIXEL_PIXELFORMAT_RGB888;
break;
case SIXEL_PIXELFORMAT_PAL1:
case SIXEL_PIXELFORMAT_PAL2:
case SIXEL_PIXELFORMAT_PAL4:
*dst_pixelformat = SIXEL_PIXELFORMAT_PAL8;
status = expand_palette(dst, src, width, height, src_pixelformat);
if (SIXEL_FAILED(status)) {
goto end;
}
break;
case SIXEL_PIXELFORMAT_G1:
case SIXEL_PIXELFORMAT_G2:
case SIXEL_PIXELFORMAT_G4:
*dst_pixelformat = SIXEL_PIXELFORMAT_G8;
status = expand_palette(dst, src, width, height, src_pixelformat);
if (SIXEL_FAILED(status)) {
goto end;
}
break;
case SIXEL_PIXELFORMAT_PAL8:
memcpy(dst, src, (size_t)(width * height));
*dst_pixelformat = src_pixelformat;
break;
default:
status = SIXEL_BAD_ARGUMENT;
goto end;
}
status = SIXEL_OK;
end:
return status;
}
#if HAVE_TESTS
static int
test1(void)
{
unsigned char dst[3];
int dst_pixelformat = SIXEL_PIXELFORMAT_RGB888;
int src_pixelformat = SIXEL_PIXELFORMAT_RGB888;
unsigned char src[] = { 0x46, 0xf3, 0xe5 };
int ret = 0;
int nret = EXIT_FAILURE;
ret = sixel_helper_normalize_pixelformat(dst,
&dst_pixelformat,
src,
src_pixelformat,
1,
1);
if (ret != 0) {
goto error;
}
if (dst_pixelformat != SIXEL_PIXELFORMAT_RGB888) {
goto error;
}
if ((dst[0] << 16 | dst[1] << 8 | dst[2]) != (src[0] << 16 | src[1] << 8 | src[2])) {
goto error;
}
return EXIT_SUCCESS;
error:
perror("test1");
return nret;
}
static int
test2(void)
{
unsigned char dst[3];
int dst_pixelformat = SIXEL_PIXELFORMAT_RGB888;
int src_pixelformat = SIXEL_PIXELFORMAT_RGB555;
unsigned char src[] = { 0x47, 0x9c };
int ret = 0;
int nret = EXIT_FAILURE;
ret = sixel_helper_normalize_pixelformat(dst,
&dst_pixelformat,
src,
src_pixelformat,
1,
1);
if (ret != 0) {
goto error;
}
if (dst_pixelformat != SIXEL_PIXELFORMAT_RGB888) {
goto error;
}
if ((dst[0] >> 3 << 10 | dst[1] >> 3 << 5 | dst[2] >> 3) != (src[0] << 8 | src[1])) {
goto error;
}
return EXIT_SUCCESS;
error:
perror("test2");
return nret;
}
static int
test3(void)
{
unsigned char dst[3];
int dst_pixelformat = SIXEL_PIXELFORMAT_RGB888;
int src_pixelformat = SIXEL_PIXELFORMAT_RGB565;
unsigned char src[] = { 0x47, 0x9c };
int ret = 0;
int nret = EXIT_FAILURE;
ret = sixel_helper_normalize_pixelformat(dst,
&dst_pixelformat,
src,
src_pixelformat,
1,
1);
if (ret != 0) {
goto error;
}
if (dst_pixelformat != SIXEL_PIXELFORMAT_RGB888) {
goto error;
}
if ((dst[0] >> 3 << 11 | dst[1] >> 2 << 5 | dst[2] >> 3) != (src[0] << 8 | src[1])) {
goto error;
}
return EXIT_SUCCESS;
error:
perror("test3");
return nret;
}
static int
test4(void)
{
unsigned char dst[3];
int dst_pixelformat = SIXEL_PIXELFORMAT_RGB888;
int src_pixelformat = SIXEL_PIXELFORMAT_BGR888;
unsigned char src[] = { 0x46, 0xf3, 0xe5 };
int ret = 0;
int nret = EXIT_FAILURE;
ret = sixel_helper_normalize_pixelformat(dst,
&dst_pixelformat,
src,
src_pixelformat,
1,
1);
if (ret != 0) {
goto error;
}
if (dst_pixelformat != SIXEL_PIXELFORMAT_RGB888) {
goto error;
}
if ((dst[2] << 16 | dst[1] << 8 | dst[0]) != (src[0] << 16 | src[1] << 8 | src[2])) {
goto error;
}
return EXIT_SUCCESS;
error:
perror("test4");
return nret;
}
static int
test5(void)
{
unsigned char dst[3];
int dst_pixelformat = SIXEL_PIXELFORMAT_RGB888;
int src_pixelformat = SIXEL_PIXELFORMAT_BGR555;
unsigned char src[] = { 0x23, 0xc8 };
int ret = 0;
int nret = EXIT_FAILURE;
ret = sixel_helper_normalize_pixelformat(dst,
&dst_pixelformat,
src,
src_pixelformat,
1,
1);
if (ret != 0) {
goto error;
}
if (dst_pixelformat != SIXEL_PIXELFORMAT_RGB888) {
goto error;
}
if ((dst[2] >> 3 << 10 | dst[1] >> 3 << 5 | dst[0] >> 3) != (src[0] << 8 | src[1])) {
goto error;
}
return EXIT_SUCCESS;
error:
perror("test5");
return nret;
}
static int
test6(void)
{
unsigned char dst[3];
int dst_pixelformat = SIXEL_PIXELFORMAT_RGB888;
int src_pixelformat = SIXEL_PIXELFORMAT_BGR565;
unsigned char src[] = { 0x47, 0x88 };
int ret = 0;
int nret = EXIT_FAILURE;
ret = sixel_helper_normalize_pixelformat(dst,
&dst_pixelformat,
src,
src_pixelformat,
1,
1);
if (ret != 0) {
goto error;
}
if (dst_pixelformat != SIXEL_PIXELFORMAT_RGB888) {
goto error;
}
if ((dst[2] >> 3 << 11 | dst[1] >> 2 << 5 | dst[0] >> 3) != (src[0] << 8 | src[1])) {
goto error;
}
return EXIT_SUCCESS;
error:
perror("test6");
return nret;
}
static int
test7(void)
{
unsigned char dst[3];
int dst_pixelformat = SIXEL_PIXELFORMAT_RGB888;
int src_pixelformat = SIXEL_PIXELFORMAT_AG88;
unsigned char src[] = { 0x47, 0x88 };
int ret = 0;
int nret = EXIT_FAILURE;
ret = sixel_helper_normalize_pixelformat(dst,
&dst_pixelformat,
src,
src_pixelformat,
1,
1);
if (ret != 0) {
goto error;
}
if (dst_pixelformat != SIXEL_PIXELFORMAT_RGB888) {
goto error;
}
if (dst[0] != src[1]) {
goto error;
}
return EXIT_SUCCESS;
error:
perror("test7");
return nret;
}
static int
test8(void)
{
unsigned char dst[3];
int dst_pixelformat = SIXEL_PIXELFORMAT_RGB888;
int src_pixelformat = SIXEL_PIXELFORMAT_GA88;
unsigned char src[] = { 0x47, 0x88 };
int ret = 0;
int nret = EXIT_FAILURE;
ret = sixel_helper_normalize_pixelformat(dst,
&dst_pixelformat,
src,
src_pixelformat,
1,
1);
if (ret != 0) {
goto error;
}
if (dst_pixelformat != SIXEL_PIXELFORMAT_RGB888) {
goto error;
}
if (dst[0] != src[0]) {
goto error;
}
return EXIT_SUCCESS;
error:
perror("test8");
return nret;
}
static int
test9(void)
{
unsigned char dst[3];
int dst_pixelformat = SIXEL_PIXELFORMAT_RGB888;
int src_pixelformat = SIXEL_PIXELFORMAT_RGBA8888;
unsigned char src[] = { 0x46, 0xf3, 0xe5, 0xf0 };
int ret = 0;
int nret = EXIT_FAILURE;
ret = sixel_helper_normalize_pixelformat(dst,
&dst_pixelformat,
src,
src_pixelformat,
1,
1);
if (ret != 0) {
goto error;
}
if (dst_pixelformat != SIXEL_PIXELFORMAT_RGB888) {
goto error;
}
if (dst[0] != src[0]) {
goto error;
}
if (dst[1] != src[1]) {
goto error;
}
if (dst[2] != src[2]) {
goto error;
}
return EXIT_SUCCESS;
error:
perror("test8");
return nret;
}
static int
test10(void)
{
unsigned char dst[3];
int dst_pixelformat = SIXEL_PIXELFORMAT_RGB888;
int src_pixelformat = SIXEL_PIXELFORMAT_ARGB8888;
unsigned char src[] = { 0x46, 0xf3, 0xe5, 0xf0 };
int ret = 0;
int nret = EXIT_FAILURE;
ret = sixel_helper_normalize_pixelformat(dst,
&dst_pixelformat,
src,
src_pixelformat,
1,
1);
if (ret != 0) {
goto error;
}
if (dst_pixelformat != SIXEL_PIXELFORMAT_RGB888) {
goto error;
}
if (dst[0] != src[1]) {
goto error;
}
if (dst[1] != src[2]) {
goto error;
}
if (dst[2] != src[3]) {
goto error;
}
return EXIT_SUCCESS;
error:
perror("test8");
return nret;
}
SIXELAPI int
sixel_pixelformat_tests_main(void)
{
int nret = EXIT_FAILURE;
size_t i;
typedef int (* testcase)(void);
static testcase const testcases[] = {
test1,
test2,
test3,
test4,
test5,
test6,
test7,
test8,
test9,
test10,
};
for (i = 0; i < sizeof(testcases) / sizeof(testcase); ++i) {
nret = testcases[i]();
if (nret != EXIT_SUCCESS) {
goto error;
}
}
nret = EXIT_SUCCESS;
error:
return nret;
}
#endif /* HAVE_TESTS */
/* emacs Local Variables: */
/* emacs mode: c */
/* emacs tab-width: 4 */
/* emacs indent-tabs-mode: nil */
/* emacs c-basic-offset: 4 */
/* emacs End: */
/* vim: set expandtab ts=4 sts=4 sw=4 : */
/* EOF */
+1549
View File
File diff suppressed because it is too large Load Diff
+90
View File
@@ -0,0 +1,90 @@
/*
* Copyright (c) 2014-2016 Hayaki Saito
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef LIBSIXEL_QUANT_H
#define LIBSIXEL_QUANT_H
#ifdef __cplusplus
extern "C" {
#endif
#include <sixel.h>
/* choose colors using median-cut method */
SIXELSTATUS
sixel_quant_make_palette(
unsigned char /* out */ **result,
unsigned const char /* in */ *data, /* data for sampling */
unsigned int /* in */ length, /* data size */
int /* in */ pixelformat,
unsigned int /* in */ reqcolors,
unsigned int /* in */ *ncolors,
unsigned int /* in */ *origcolors,
int /* in */ methodForLargest,
int /* in */ methodForRep,
int /* in */ qualityMode,
sixel_allocator_t /* in */ *allocator);
/* apply color palette into specified pixel buffers */
SIXELSTATUS
sixel_quant_apply_palette(
sixel_index_t /* out */ *result,
unsigned char /* in */ *data,
int /* in */ width,
int /* in */ height,
int /* in */ pixelformat,
unsigned char /* in */ *palette,
int /* in */ reqcolor,
int const /* in */ methodForDiffuse,
int /* in */ foptimize,
int /* in */ foptimize_palette,
int /* in */ complexion,
unsigned short /* in */ *cachetable,
int /* in */ *ncolor,
sixel_allocator_t /* in */ *allocator);
/* deallocate specified palette */
void
sixel_quant_free_palette(
unsigned char /* in */ *data,
sixel_allocator_t /* in */ *allocator);
#if HAVE_TESTS
int
sixel_quant_tests_main(void);
#endif
#ifdef __cplusplus
}
#endif
#endif /* LIBSIXEL_QUANT_H */
/* emacs Local Variables: */
/* emacs mode: c */
/* emacs tab-width: 4 */
/* emacs indent-tabs-mode: nil */
/* emacs c-basic-offset: 4 */
/* emacs End: */
/* vim: set expandtab ts=4 sts=4 sw=4 : */
/* EOF */
+11
View File
@@ -0,0 +1,11 @@
{
"home": "https://github.com/saitoha/libsixel",
"license": "MIT ( embed in source )",
"version": "1.8.7-r2",
"author": "Hayaki Saito",
"modifications": [
"sixel.h: SIXELAPI is empty, so the statically linked subset exports nothing",
"config.h: hand-written, because only the vendored files read it",
"tosixel.c: DCS P2 initialised to 1, so unset pixels are not filled with colour-table entry 0"
]
}
+1173
View File
File diff suppressed because it is too large Load Diff
+355
View File
@@ -0,0 +1,355 @@
/*
* Copyright (c) 2014-2018 Hayaki Saito
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "config.h"
/* STDC_HEADERS */
#include <stdio.h>
#include <stdlib.h>
#if HAVE_MEMORY_H
# include <memory.h>
#endif /* HAVE_MEMORY_H */
#ifdef HAVE_STRING_H
# include <string.h>
#endif /* HAVE_STRING_H */
#ifdef HAVE_ERRNO_H
# include <errno.h>
#endif /* HAVE_ERRNO_H */
#ifdef HAVE_LIBCURL
# include <curl/curl.h>
#endif /* HAVE_LIBCURL */
#include <sixel.h>
#include "status.h"
#define SIXEL_MESSAGE_OK ("succeeded")
#define SIXEL_MESSAGE_FALSE ("unexpected error (SIXEL_FALSE)");
#define SIXEL_MESSAGE_UNEXPECTED ("unexpected error")
#define SIXEL_MESSAGE_INTERRUPTED ("interrupted by a signal")
#define SIXEL_MESSAGE_BAD_ALLOCATION ("runtime error: bad allocation error")
#define SIXEL_MESSAGE_BAD_ARGUMENT ("runtime error: bad argument detected")
#define SIXEL_MESSAGE_BAD_INPUT ("runtime error: bad input detected")
#define SIXEL_MESSAGE_BAD_INTEGER_OVERFLOW ("runtime error: integer overflow")
#define SIXEL_MESSAGE_RUNTIME_ERROR ("runtime error")
#define SIXEL_MESSAGE_LOGIC_ERROR ("logic error")
#define SIXEL_MESSAGE_NOT_IMPLEMENTED ("feature error: not implemented")
#define SIXEL_MESSAGE_FEATURE_ERROR ("feature error")
#define SIXEL_MESSAGE_STBI_ERROR ("stb_image error")
#define SIXEL_MESSAGE_STBIW_ERROR ("stb_image_write error")
#define SIXEL_MESSAGE_JPEG_ERROR ("libjpeg error")
#define SIXEL_MESSAGE_PNG_ERROR ("libpng error")
#define SIXEL_MESSAGE_GDK_ERROR ("GDK error")
#define SIXEL_MESSAGE_GD_ERROR ("GD error")
static char g_buffer[1024] = { 0x0 };
/* set detailed error message (thread-unsafe) */
SIXELAPI void
sixel_helper_set_additional_message(
const char /* in */ *message /* error message */
)
{
size_t len;
if (message == 0)
return;
len = strlen(message);
memcpy(g_buffer, message, len < sizeof(g_buffer) ? len: sizeof(g_buffer) - 1);
g_buffer[sizeof(g_buffer) - 1] = 0;
}
/* get detailed error message (thread-unsafe) */
SIXELAPI char const *
sixel_helper_get_additional_message(void)
{
return g_buffer;
}
/* convert error status code int formatted string */
SIXELAPI char const *
sixel_helper_format_error(
SIXELSTATUS /* in */ status /* status code */
)
{
static char buffer[1024];
char const *error_string;
char *p;
size_t len;
switch (status & 0x1000) {
case SIXEL_OK:
switch (status) {
case SIXEL_INTERRUPTED:
error_string = SIXEL_MESSAGE_INTERRUPTED;
break;
case SIXEL_OK:
default:
error_string = SIXEL_MESSAGE_OK;
break;
}
break;
case SIXEL_FALSE:
switch (status & 0x1f00) {
case SIXEL_RUNTIME_ERROR:
switch (status) {
case SIXEL_BAD_ALLOCATION:
error_string = SIXEL_MESSAGE_BAD_ALLOCATION;
break;
case SIXEL_BAD_ARGUMENT:
error_string = SIXEL_MESSAGE_BAD_ARGUMENT;
break;
case SIXEL_BAD_INPUT:
error_string = SIXEL_MESSAGE_BAD_INPUT;
break;
case SIXEL_BAD_INTEGER_OVERFLOW:
error_string = SIXEL_MESSAGE_BAD_INTEGER_OVERFLOW;
break;
default:
error_string = SIXEL_MESSAGE_RUNTIME_ERROR;
break;
}
break;
case SIXEL_LOGIC_ERROR:
error_string = SIXEL_MESSAGE_LOGIC_ERROR;
break;
case SIXEL_FEATURE_ERROR:
switch (status) {
case SIXEL_NOT_IMPLEMENTED:
error_string = SIXEL_MESSAGE_NOT_IMPLEMENTED;
break;
default:
error_string = SIXEL_MESSAGE_FEATURE_ERROR;
break;
}
break;
case SIXEL_LIBC_ERROR:
p = strerror(errno);
len = strlen(p) + 1;
memcpy(buffer, p, len < sizeof(buffer) ? len: sizeof(buffer) - 1);
buffer[sizeof(buffer) - 1] = 0;
error_string = buffer;
break;
#ifdef HAVE_LIBCURL
case SIXEL_CURL_ERROR:
error_string = curl_easy_strerror(status & 0xff);
break;
#endif
#ifdef HAVE_JPEG
case SIXEL_JPEG_ERROR:
error_string = SIXEL_MESSAGE_JPEG_ERROR;
break;
#endif
#ifdef HAVE_LIBPNG
case SIXEL_PNG_ERROR:
error_string = SIXEL_MESSAGE_PNG_ERROR;
break;
#endif
#ifdef HAVE_GDK_PIXBUF2
case SIXEL_GDK_ERROR:
error_string = SIXEL_MESSAGE_GDK_ERROR;
break;
#endif
#ifdef HAVE_GD
case SIXEL_GD_ERROR:
error_string = SIXEL_MESSAGE_GD_ERROR;
break;
#endif
case SIXEL_STBI_ERROR:
error_string = SIXEL_MESSAGE_STBI_ERROR;
break;
case SIXEL_STBIW_ERROR:
error_string = SIXEL_MESSAGE_STBIW_ERROR;
break;
case SIXEL_FALSE:
error_string = SIXEL_MESSAGE_FALSE;
break;
default:
error_string = SIXEL_MESSAGE_UNEXPECTED;
break;
}
break;
default:
error_string = SIXEL_MESSAGE_UNEXPECTED;
break;
}
return error_string;
}
#if HAVE_TESTS
static int
test1(void)
{
int nret = EXIT_FAILURE;
char const *message;
message = sixel_helper_format_error(SIXEL_OK);
if (strcmp(message, SIXEL_MESSAGE_OK) != 0) {
goto error;
}
message = sixel_helper_format_error(SIXEL_INTERRUPTED);
if (strcmp(message, SIXEL_MESSAGE_INTERRUPTED) != 0) {
goto error;
}
return EXIT_SUCCESS;
error:
perror("test1");
return nret;
}
static int
test2(void)
{
int nret = EXIT_FAILURE;
char const *message;
message = sixel_helper_format_error(SIXEL_BAD_ALLOCATION);
if (strcmp(message, SIXEL_MESSAGE_BAD_ALLOCATION) != 0) {
goto error;
}
message = sixel_helper_format_error(SIXEL_BAD_ARGUMENT);
if (strcmp(message, SIXEL_MESSAGE_BAD_ARGUMENT) != 0) {
goto error;
}
message = sixel_helper_format_error(SIXEL_BAD_INPUT);
if (strcmp(message, SIXEL_MESSAGE_BAD_INPUT) != 0) {
goto error;
}
message = sixel_helper_format_error(SIXEL_RUNTIME_ERROR);
if (strcmp(message, SIXEL_MESSAGE_RUNTIME_ERROR) != 0) {
goto error;
}
message = sixel_helper_format_error(SIXEL_LOGIC_ERROR);
if (strcmp(message, SIXEL_MESSAGE_LOGIC_ERROR) != 0) {
goto error;
}
message = sixel_helper_format_error(SIXEL_NOT_IMPLEMENTED);
if (strcmp(message, SIXEL_MESSAGE_NOT_IMPLEMENTED) != 0) {
goto error;
}
message = sixel_helper_format_error(SIXEL_FEATURE_ERROR);
if (strcmp(message, SIXEL_MESSAGE_FEATURE_ERROR) != 0) {
goto error;
}
message = sixel_helper_format_error(SIXEL_LIBC_ERROR);
if (strcmp(message, SIXEL_MESSAGE_UNEXPECTED) == 0) {
goto error;
}
#ifdef HAVE_LIBCURL
message = sixel_helper_format_error(SIXEL_CURL_ERROR);
if (strcmp(message, SIXEL_MESSAGE_UNEXPECTED) == 0) {
goto error;
}
#endif
#if HAVE_JPEG
message = sixel_helper_format_error(SIXEL_JPEG_ERROR);
if (strcmp(message, SIXEL_MESSAGE_JPEG_ERROR) != 0) {
goto error;
}
#endif
#if HAVE_LIBPNG
message = sixel_helper_format_error(SIXEL_PNG_ERROR);
if (strcmp(message, SIXEL_MESSAGE_PNG_ERROR) != 0) {
goto error;
}
#endif
#if HAVE_GD
message = sixel_helper_format_error(SIXEL_GD_ERROR);
if (strcmp(message, SIXEL_MESSAGE_GD_ERROR) != 0) {
goto error;
}
#endif
#if HAVE_GDK_PIXBUF2
message = sixel_helper_format_error(SIXEL_GDK_ERROR);
if (strcmp(message, SIXEL_MESSAGE_GDK_ERROR) != 0) {
goto error;
}
#endif
message = sixel_helper_format_error(SIXEL_STBI_ERROR);
if (strcmp(message, SIXEL_MESSAGE_STBI_ERROR) != 0) {
goto error;
}
message = sixel_helper_format_error(SIXEL_STBIW_ERROR);
if (strcmp(message, SIXEL_MESSAGE_STBIW_ERROR) != 0) {
goto error;
}
return EXIT_SUCCESS;
error:
perror("test2");
return nret;
}
SIXELAPI int
sixel_status_tests_main(void)
{
int nret = EXIT_FAILURE;
size_t i;
typedef int (* testcase)(void);
static testcase const testcases[] = {
test1,
test2,
};
for (i = 0; i < sizeof(testcases) / sizeof(testcase); ++i) {
nret = testcases[i]();
if (nret != EXIT_SUCCESS) {
goto error;
}
}
nret = EXIT_SUCCESS;
error:
return nret;
}
#endif /* HAVE_TESTS */
/* emacs Local Variables: */
/* emacs mode: c */
/* emacs tab-width: 4 */
/* emacs indent-tabs-mode: nil */
/* emacs c-basic-offset: 4 */
/* emacs End: */
/* vim: set expandtab ts=4 sts=4 sw=4 : */
/* EOF */
+47
View File
@@ -0,0 +1,47 @@
/*
* Copyright (c) 2014-2016 Hayaki Saito
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef LIBSIXEL_STATUS_H
#define LIBSIXEL_STATUS_H
#ifdef __cplusplus
extern "C" {
#endif
#if HAVE_TESTS
int
sixel_status_tests_main(void);
#endif
#ifdef __cplusplus
}
#endif
#endif /* LIBSIXEL_STATUS_H */
/* emacs Local Variables: */
/* emacs mode: c */
/* emacs tab-width: 4 */
/* emacs indent-tabs-mode: nil */
/* emacs c-basic-offset: 4 */
/* emacs End: */
/* vim: set expandtab ts=4 sts=4 sw=4 : */
/* EOF */
+1635
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -1,6 +1,6 @@
{
"home": "https://github.com/ibireme/yyjson",
"license": "MIT ( embed in source )",
"version": "0.12.0",
"version": "0.13.0",
"author": "ibireme"
}
+700 -285
View File
File diff suppressed because it is too large Load Diff
+911 -674
View File
File diff suppressed because it is too large Load Diff
+4 -1
View File
@@ -8,7 +8,10 @@ typedef struct FFPlatformSysinfo {
FFstrbuf release;
FFstrbuf version;
FFstrbuf architecture;
uint32_t pageSize;
// The base-2 logarithm of the memory page size, i.e. a page is `1 << pageSizeShift` bytes.
// Page sizes are powers of two on every supported platform. Storing the exponent instead of
// the byte count keeps page count arithmetic in 64 bits and makes the invariant explicit.
uint32_t pageSizeShift;
} FFPlatformSysinfo;
typedef struct FFPlatform {
+18 -15
View File
@@ -15,17 +15,18 @@ typedef struct FFlist {
} FFlist;
// Removes the first element, and copy its value to `*result`
bool ffListShift(FFlist* list, uint32_t elementSize, void* __restrict result);
// `result` is only written when the list is not empty, so it may be null for an empty list
[[gnu::nonnull(1), nodiscard]] bool ffListShift(FFlist* list, uint32_t elementSize, void* __restrict result);
// Removes the last element, and copy its value to `*result`
bool ffListPop(FFlist* list, uint32_t elementSize, void* __restrict result);
[[gnu::nonnull(1), nodiscard]] bool ffListPop(FFlist* list, uint32_t elementSize, void* __restrict result);
static inline void ffListInit(FFlist* list) {
[[gnu::nonnull(1)]] static inline void ffListInit(FFlist* list) {
list->capacity = 0;
list->length = 0;
list->data = nullptr;
}
static inline void ffListInitA(FFlist* list, uint32_t elementSize, uint32_t capacity) {
[[gnu::nonnull(1)]] static inline void ffListInitA(FFlist* list, uint32_t elementSize, uint32_t capacity) {
ffListInit(list);
list->capacity = capacity;
list->data = __builtin_expect(capacity == 0, 0) ? nullptr : (uint8_t*) malloc((size_t) capacity * elementSize);
@@ -43,12 +44,13 @@ static inline void ffListInitA(FFlist* list, uint32_t elementSize, uint32_t capa
return result;
}
[[nodiscard]] static inline void* ffListGet(const FFlist* list, uint32_t elementSize, uint32_t index) {
[[gnu::nonnull(1), gnu::pure, nodiscard]] static inline void* ffListGet(const FFlist* list, uint32_t elementSize, uint32_t index) {
assert(list->capacity > index);
return list->data + (index * elementSize);
}
[[nodiscard]] static inline uint32_t ffListFirstIndexComp(const FFlist* list, uint32_t elementSize, void* compElement, bool (*compFunc)(const void*, const void*)) {
// Not `pure`: `compFunc` is caller-supplied and may have side effects
[[gnu::nonnull(1, 3, 4), 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;
@@ -58,16 +60,17 @@ static inline void ffListInitA(FFlist* list, uint32_t elementSize, uint32_t capa
return list->length;
}
[[nodiscard]] static inline bool ffListContains(const FFlist* list, uint32_t elementSize, void* compElement, bool (*compFunc)(const void*, const void*)) {
// Not `pure`, same reason as ffListFirstIndexComp
[[gnu::nonnull(1, 3, 4), 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;
}
static inline void ffListSort(FFlist* list, uint32_t elementSize, int (*compar)(const void*, const void*)) {
[[gnu::nonnull(1, 3)]] static inline void ffListSort(FFlist* list, uint32_t elementSize, int (*compar)(const void*, const void*)) {
qsort(list->data, list->length, elementSize, compar);
}
// Move the contents of `src` into `list`, and left `src` empty
static inline void ffListInitMove(FFlist* list, FFlist* src) {
[[gnu::nonnull(1)]] static inline void ffListInitMove(FFlist* list, FFlist* src) {
if (src) {
list->capacity = src->capacity;
list->length = src->length;
@@ -78,7 +81,7 @@ static inline void ffListInitMove(FFlist* list, FFlist* src) {
}
}
static inline void ffListDestroy(FFlist* list) {
[[gnu::nonnull(1)]] static inline void ffListDestroy(FFlist* list) {
if (!list->data) {
return;
}
@@ -89,11 +92,11 @@ static inline void ffListDestroy(FFlist* list) {
list->data = nullptr;
}
static inline void ffListClear(FFlist* list) {
[[gnu::nonnull(1)]] static inline void ffListClear(FFlist* list) {
list->length = 0;
}
static inline void ffListReserve(FFlist* list, uint32_t elementSize, uint32_t newCapacity) {
[[gnu::nonnull(1)]] static inline void ffListReserve(FFlist* list, uint32_t elementSize, uint32_t newCapacity) {
if (__builtin_expect(newCapacity <= list->capacity, false)) {
return;
}
@@ -102,7 +105,7 @@ static inline void ffListReserve(FFlist* list, uint32_t elementSize, uint32_t ne
list->capacity = newCapacity;
}
static inline void* ffListAdd(FFlist* list, uint32_t elementSize) {
[[gnu::nonnull(1)]] static inline void* ffListAdd(FFlist* list, uint32_t elementSize) {
if (__builtin_expect(list->length == list->capacity, false)) {
ffListReserve(list, elementSize, list->capacity == 0 ? FF_LIST_DEFAULT_ALLOC : list->capacity * 2);
}
@@ -111,13 +114,13 @@ 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) {
[[gnu::nonnull(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) {
[[gnu::nonnull(1, 4)]] 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);
+162 -132
View File
@@ -24,6 +24,29 @@ __stdcall char* StrStrIA(const char* lpFirst, const char* lpSrch);
#define FASTFETCH_STRBUF_DEFAULT_ALLOC 32
// ---------------------------------------------------------------------------------------------
// Contract attributes used throughout this header:
//
// `gnu::pure` marks a function that reads memory (through its arguments and through globals) but
// writes nothing observable, so the compiler may cache and reorder calls to it. It is applied to
// the comparison / search accessors, and deliberately NOT to:
// * the `To*` converters -- `strtod` / `strtoull` / `strtoll` write `errno`;
// * `ffStrbufEndsWithFn` -- the caller-supplied `fn` may have side effects;
// * `ffStrbufWriteTo` / `ffStrbufPutTo` -- they write to a `FILE*`.
//
// `gnu::nonnull(N)` is added wherever the function dereferences argument N unconditionally. The
// two cannot be combined with a null check: clang reports `-Wtautological-pointer-compare` /
// `-Wpointer-bool-conversion` (both in `-Wall`) when a `nonnull` parameter is compared against
// null, so a redundant `assert(p != nullptr)` is dropped in favour of the attribute. Asserts that
// state something `nonnull` cannot express -- pointer aliasing (`value != strbuf`), index ranges
// (`start <= strbuf->length`), or a non-pointer invariant -- are kept.
//
// `nodiscard` is NOT applied to the "was the buffer modified" boolean returns
// (`ffStrbufSubstr*`, `ffStrbufRemoveSubstr`, `ffStrbufEnsureEndsWithC`, ...). Ignoring that
// result is a normal, intended use of those functions -- `ffStrbufSubstrBefore` alone has 153 call
// sites and ~147 of them discard the result -- so `nodiscard` would only produce noise.
// ---------------------------------------------------------------------------------------------
// static string (allocated == 0), chars points to a string literal
// dynamic string (allocated > 0), chars points to a heap allocated buffer
typedef struct FFstrbuf {
@@ -32,67 +55,70 @@ typedef struct FFstrbuf {
char* chars;
} FFstrbuf;
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);
[[gnu::format(printf, 2, 3)]] void ffStrbufInitF(FFstrbuf* strbuf, const char* format, ...);
[[gnu::format(printf, 1, 2)]] [[nodiscard]] FFstrbuf ffStrbufCreateF(const char* format, ...);
[[gnu::nonnull(1)]] static inline void ffStrbufInit(FFstrbuf* strbuf);
[[gnu::nonnull(1)]] void ffStrbufInitA(FFstrbuf* strbuf, uint32_t allocate);
[[gnu::nonnull(1, 2), gnu::format(printf, 2, 0)]] void ffStrbufInitVF(FFstrbuf* strbuf, const char* format, va_list arguments);
[[gnu::nonnull(1, 3)]] void ffStrbufInitMoveNS(FFstrbuf* strbuf, uint32_t length, char* heapStr);
[[gnu::format(printf, 2, 3), gnu::nonnull(1, 2)]] void ffStrbufInitF(FFstrbuf* strbuf, const char* format, ...);
[[gnu::format(printf, 1, 2), gnu::nonnull(1), nodiscard]] FFstrbuf ffStrbufCreateF(const char* format, ...);
void ffStrbufEnsureFixedLengthFree(FFstrbuf* strbuf, uint32_t free);
void ffStrbufEnsureFreeNoCheck(FFstrbuf* strbuf, uint32_t free);
[[gnu::nonnull(1)]] void ffStrbufEnsureFixedLengthFree(FFstrbuf* strbuf, uint32_t free);
[[gnu::nonnull(1)]] 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));
[[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);
[[gnu::nonnull(1)]] static inline void ffStrbufAppend(FFstrbuf* __restrict strbuf, const FFstrbuf* __restrict value);
[[gnu::nonnull(1, 3)]] void ffStrbufAppendTransformS(FFstrbuf* strbuf, const char* value, int (*transformFunc)(int));
[[gnu::format(printf, 2, 3), gnu::nonnull(1, 2)]] void ffStrbufAppendF(FFstrbuf* strbuf, const char* format, ...);
[[gnu::nonnull(1, 2), gnu::format(printf, 2, 0)]] void ffStrbufAppendVF(FFstrbuf* strbuf, const char* format, va_list arguments);
// Returns the pointer to the terminator, or nullptr if `value` was nullptr; callers are free to
// ignore it, so not `nodiscard`.
[[gnu::nonnull(1)]] const char* ffStrbufAppendSUntilC(FFstrbuf* strbuf, const char* value, char until);
void ffStrbufPrependNS(FFstrbuf* strbuf, uint32_t length, const char* value);
void ffStrbufPrependC(FFstrbuf* strbuf, char c);
[[gnu::nonnull(1)]] void ffStrbufPrependNS(FFstrbuf* strbuf, uint32_t length, const char* value);
[[gnu::nonnull(1)]] void ffStrbufPrependC(FFstrbuf* strbuf, char c);
void ffStrbufInsertNC(FFstrbuf* strbuf, uint32_t index, uint32_t num, char c);
[[gnu::nonnull(1)]] void ffStrbufInsertNC(FFstrbuf* strbuf, uint32_t index, uint32_t num, char c);
// Clear the content of strbuf and set new value
// 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);
[[gnu::format(printf, 2, 3)]] void ffStrbufSetF(FFstrbuf* strbuf, const char* format, ...);
[[gnu::nonnull(1, 2)]] void ffStrbufSet(FFstrbuf* strbuf, const FFstrbuf* value);
[[gnu::nonnull(1, 3)]] void ffStrbufSetNS(FFstrbuf* strbuf, uint32_t length, const char* value);
[[gnu::format(printf, 2, 3), gnu::nonnull(1, 2)]] void ffStrbufSetF(FFstrbuf* strbuf, const char* format, ...);
void ffStrbufTrimLeft(FFstrbuf* strbuf, char c);
void ffStrbufTrimRight(FFstrbuf* strbuf, char c);
void ffStrbufTrimLeftSpace(FFstrbuf* strbuf);
void ffStrbufTrimRightSpace(FFstrbuf* strbuf);
[[gnu::nonnull(1)]] void ffStrbufTrimLeft(FFstrbuf* strbuf, char c);
[[gnu::nonnull(1)]] void ffStrbufTrimRight(FFstrbuf* strbuf, char c);
[[gnu::nonnull(1)]] void ffStrbufTrimLeftSpace(FFstrbuf* strbuf);
[[gnu::nonnull(1)]] void ffStrbufTrimRightSpace(FFstrbuf* strbuf);
bool ffStrbufRemoveSubstr(FFstrbuf* strbuf, uint32_t startIndex, uint32_t endIndex);
void ffStrbufRemoveS(FFstrbuf* strbuf, const char* str);
void ffStrbufRemoveStrings(FFstrbuf* strbuf, uint32_t numStrings, const char* strings[]);
[[gnu::nonnull(1)]] bool ffStrbufRemoveSubstr(FFstrbuf* strbuf, uint32_t startIndex, uint32_t endIndex);
[[gnu::nonnull(1, 2)]] void ffStrbufRemoveS(FFstrbuf* strbuf, const char* str);
// `strings` is only dereferenced when `numStrings > 0`, so it is intentionally not `nonnull(3)`
[[gnu::nonnull(1)]] void ffStrbufRemoveStrings(FFstrbuf* strbuf, uint32_t numStrings, const char* strings[]);
void ffStrbufReplaceAllC(FFstrbuf* strbuf, char find, char replace);
[[gnu::nonnull(1)]] void ffStrbufReplaceAllC(FFstrbuf* strbuf, char find, char replace);
// Returns true if the strbuf is modified
bool ffStrbufSubstrBefore(FFstrbuf* strbuf, uint32_t index);
bool ffStrbufSubstrAfter(FFstrbuf* strbuf, uint32_t index); // Not including the index
bool ffStrbufSubstrAfterFirstC(FFstrbuf* strbuf, char c);
bool ffStrbufSubstrAfterFirstS(FFstrbuf* strbuf, const char* str);
bool ffStrbufSubstrAfterLastC(FFstrbuf* strbuf, char c);
bool ffStrbufSubstr(FFstrbuf* strbuf, uint32_t start, uint32_t end);
[[gnu::nonnull(1)]] bool ffStrbufSubstrBefore(FFstrbuf* strbuf, uint32_t index);
[[gnu::nonnull(1)]] bool ffStrbufSubstrAfter(FFstrbuf* strbuf, uint32_t index); // Not including the index
[[gnu::nonnull(1)]] bool ffStrbufSubstrAfterFirstC(FFstrbuf* strbuf, char c);
[[gnu::nonnull(1, 2)]] bool ffStrbufSubstrAfterFirstS(FFstrbuf* strbuf, const char* str);
[[gnu::nonnull(1)]] bool ffStrbufSubstrAfterLastC(FFstrbuf* strbuf, char c);
[[gnu::nonnull(1)]] bool ffStrbufSubstr(FFstrbuf* strbuf, uint32_t start, uint32_t end);
[[nodiscard]] uint32_t ffStrbufCountC(const FFstrbuf* strbuf, char c);
[[gnu::nonnull(1), gnu::pure, nodiscard]] uint32_t ffStrbufCountC(const FFstrbuf* strbuf, char c);
bool ffStrbufRemoveIgnCaseEndS(FFstrbuf* strbuf, const char* end);
[[gnu::nonnull(1, 2)]] bool ffStrbufRemoveIgnCaseEndS(FFstrbuf* strbuf, const char* end);
bool ffStrbufEnsureEndsWithC(FFstrbuf* strbuf, char c);
[[gnu::nonnull(1)]] bool ffStrbufEnsureEndsWithC(FFstrbuf* strbuf, char c);
void ffStrbufUpperCase(FFstrbuf* strbuf);
void ffStrbufLowerCase(FFstrbuf* strbuf);
[[gnu::nonnull(1)]] void ffStrbufUpperCase(FFstrbuf* strbuf);
[[gnu::nonnull(1)]] 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 `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);
[[gnu::nonnull(1, 2, 4)]] bool ffStrbufGetdelim(char** lineptr, size_t* n, char delimiter, FFstrbuf* buffer);
[[gnu::nonnull(1, 2, 4)]] void ffStrbufGetdelimRestore(char** lineptr, size_t* n, char delimiter, FFstrbuf* buffer);
/**
* @brief Read a line from a FFstrbuf.
@@ -110,29 +136,31 @@ void ffStrbufGetdelimRestore(char** lineptr, size_t* n, char delimiter, FFstrbuf
*
* @return true if a line has been read, false if the end of the buffer has been reached.
*/
static inline bool ffStrbufGetline(char** lineptr, size_t* n, FFstrbuf* buffer) {
[[gnu::nonnull(1, 2, 3), nodiscard]] static inline bool ffStrbufGetline(char** lineptr, size_t* n, FFstrbuf* buffer) {
return ffStrbufGetdelim(lineptr, n, '\n', buffer);
}
/**
* @brief Restore the end of a line that was modified by ffStrbufGetline.
* @warning This function should be called before breaking an ffStrbufGetline loop if `buffer` will be used later.
*/
static inline void ffStrbufGetlineRestore(char** lineptr, size_t* n, FFstrbuf* buffer) {
[[gnu::nonnull(1, 2, 3)]] static inline void ffStrbufGetlineRestore(char** lineptr, size_t* n, FFstrbuf* buffer) {
ffStrbufGetdelimRestore(lineptr, n, '\n', buffer);
}
bool ffStrbufRemoveDupWhitespaces(FFstrbuf* strbuf);
bool ffStrbufMatchSeparatedNS(const FFstrbuf* strbuf, uint32_t compLength, const char* comp, char separator);
bool ffStrbufMatchSeparatedIgnCaseNS(const FFstrbuf* strbuf, uint32_t compLength, const char* comp, char separator);
bool ffStrbufSeparatedContainNS(const FFstrbuf* strbuf, uint32_t compLength, const char* comp, char separator);
bool ffStrbufSeparatedContainIgnCaseNS(const FFstrbuf* strbuf, uint32_t compLength, const char* comp, char separator);
[[gnu::nonnull(1)]] bool ffStrbufRemoveDupWhitespaces(FFstrbuf* strbuf);
// `comp` is only dereferenced when `compLength > 0` in the first pair, and is never dereferenced
// when `strbuf` is empty in the second pair, so neither takes `nonnull(3)`
[[gnu::nonnull(1), gnu::pure, nodiscard]] bool ffStrbufMatchSeparatedNS(const FFstrbuf* strbuf, uint32_t compLength, const char* comp, char separator);
[[gnu::nonnull(1), gnu::pure, nodiscard]] bool ffStrbufMatchSeparatedIgnCaseNS(const FFstrbuf* strbuf, uint32_t compLength, const char* comp, char separator);
[[gnu::nonnull(1), gnu::pure, nodiscard]] bool ffStrbufSeparatedContainNS(const FFstrbuf* strbuf, uint32_t compLength, const char* comp, char separator);
[[gnu::nonnull(1), gnu::pure, nodiscard]] bool ffStrbufSeparatedContainIgnCaseNS(const FFstrbuf* strbuf, uint32_t compLength, const char* comp, char separator);
int ffStrbufAppendUtf32CodePoint(FFstrbuf* strbuf, uint32_t codepoint);
[[gnu::nonnull(1)]] int ffStrbufAppendUtf32CodePoint(FFstrbuf* strbuf, uint32_t codepoint);
void ffStrbufAppendSInt(FFstrbuf* strbuf, int64_t value);
void ffStrbufAppendUInt(FFstrbuf* strbuf, uint64_t value);
[[gnu::nonnull(1)]] void ffStrbufAppendSInt(FFstrbuf* strbuf, int64_t value);
[[gnu::nonnull(1)]] void ffStrbufAppendUInt(FFstrbuf* strbuf, uint64_t value);
// Appends a double value to the string buffer with the specified precision (0~15).
// if `precision < 0`, let yyjson decide the precision
void ffStrbufAppendDouble(FFstrbuf* strbuf, double value, int8_t precision, bool trailingZeros);
[[gnu::nonnull(1)]] void ffStrbufAppendDouble(FFstrbuf* strbuf, double value, int8_t precision, bool trailingZeros);
[[nodiscard]] static inline FFstrbuf ffStrbufCreateA(uint32_t allocate) {
FFstrbuf strbuf;
@@ -140,7 +168,7 @@ void ffStrbufAppendDouble(FFstrbuf* strbuf, double value, int8_t precision, bool
return strbuf;
}
static inline void ffStrbufInitCopy(FFstrbuf* __restrict strbuf, const FFstrbuf* __restrict src) {
[[gnu::nonnull(1, 2)]] static inline void ffStrbufInitCopy(FFstrbuf* __restrict strbuf, const FFstrbuf* __restrict src) {
if (src->allocated == 0) { // static string
*strbuf = *src;
} else {
@@ -149,14 +177,14 @@ static inline void ffStrbufInitCopy(FFstrbuf* __restrict strbuf, const FFstrbuf*
}
}
[[nodiscard]] static inline FFstrbuf ffStrbufCreateCopy(const FFstrbuf* src) {
[[gnu::nonnull(1), nodiscard]] static inline FFstrbuf ffStrbufCreateCopy(const FFstrbuf* src) {
FFstrbuf strbuf;
ffStrbufInitCopy(&strbuf, src);
return strbuf;
}
// Move the content of `src` into `strbuf`, and left `src` empty
static inline void ffStrbufInitMove(FFstrbuf* strbuf, FFstrbuf* src) {
[[gnu::nonnull(1)]] static inline void ffStrbufInitMove(FFstrbuf* strbuf, FFstrbuf* src) {
if (src) {
*strbuf = *src;
ffStrbufInit(src);
@@ -171,12 +199,12 @@ static inline void ffStrbufInitMove(FFstrbuf* strbuf, FFstrbuf* src) {
return strbuf;
}
static inline void ffStrbufInitMoveS(FFstrbuf* strbuf, char* heapStr) {
[[gnu::nonnull(1, 2)]] static inline void ffStrbufInitMoveS(FFstrbuf* strbuf, char* heapStr) {
ffStrbufInitMoveNS(strbuf, (uint32_t) strlen(heapStr), heapStr);
}
// Despite the name, this function resets strbuf to the initial/unallocated state
static inline void ffStrbufDestroy(FFstrbuf* strbuf) {
[[gnu::nonnull(1)]] static inline void ffStrbufDestroy(FFstrbuf* strbuf) {
if (strbuf->allocated > 0) {
free(strbuf->chars);
}
@@ -184,8 +212,7 @@ static inline void ffStrbufDestroy(FFstrbuf* strbuf) {
ffStrbufInit(strbuf);
}
[[nodiscard]] static inline uint32_t ffStrbufGetFree(const FFstrbuf* strbuf) {
assert(strbuf != nullptr);
[[gnu::nonnull(1), gnu::pure, nodiscard]] static inline uint32_t ffStrbufGetFree(const FFstrbuf* strbuf) {
if (strbuf->allocated == 0) {
return 0;
}
@@ -193,7 +220,7 @@ static inline void ffStrbufDestroy(FFstrbuf* strbuf) {
return strbuf->allocated - strbuf->length - 1; // - 1 for the null byte
}
static inline void ffStrbufEnsureFree(FFstrbuf* strbuf, uint32_t free) {
[[gnu::nonnull(1)]] static inline void ffStrbufEnsureFree(FFstrbuf* strbuf, uint32_t free) {
if (__builtin_expect(free == 0, false)) {
if (__builtin_expect(!(strbuf->allocated == 0 && strbuf->length > 0), true)) {
return;
@@ -208,8 +235,7 @@ static inline void ffStrbufEnsureFree(FFstrbuf* strbuf, uint32_t free) {
}
static inline void ffStrbufClear(FFstrbuf* strbuf) {
assert(strbuf != nullptr);
[[gnu::nonnull(1)]] static inline void ffStrbufClear(FFstrbuf* strbuf) {
extern char* CHAR_NULL_PTR;
if (strbuf->allocated == 0) {
@@ -221,13 +247,13 @@ static inline void ffStrbufClear(FFstrbuf* strbuf) {
strbuf->length = 0;
}
static inline void ffStrbufAppendC(FFstrbuf* strbuf, char c) {
[[gnu::nonnull(1)]] static inline void ffStrbufAppendC(FFstrbuf* strbuf, char c) {
ffStrbufEnsureFree(strbuf, 1);
strbuf->chars[strbuf->length++] = c;
strbuf->chars[strbuf->length] = '\0';
}
static inline void ffStrbufAppendNC(FFstrbuf* strbuf, uint32_t num, char c) {
[[gnu::nonnull(1)]] static inline void ffStrbufAppendNC(FFstrbuf* strbuf, uint32_t num, char c) {
if (__builtin_expect(num == 0, false)) {
return;
}
@@ -238,7 +264,7 @@ static inline void ffStrbufAppendNC(FFstrbuf* strbuf, uint32_t num, char c) {
strbuf->chars[strbuf->length] = '\0';
}
static inline void ffStrbufAppendNS(FFstrbuf* strbuf, uint32_t length, const char* value) {
[[gnu::nonnull(1)]] static inline void ffStrbufAppendNS(FFstrbuf* strbuf, uint32_t length, const char* value) {
if (__builtin_expect(value == nullptr || length == 0, false)) {
return;
}
@@ -249,7 +275,7 @@ static inline void ffStrbufAppendNS(FFstrbuf* strbuf, uint32_t length, const cha
strbuf->chars[strbuf->length] = '\0';
}
static inline void ffStrbufAppend(FFstrbuf* __restrict strbuf, const FFstrbuf* __restrict value) {
[[gnu::nonnull(1)]] static inline void ffStrbufAppend(FFstrbuf* __restrict strbuf, const FFstrbuf* __restrict value) {
assert(value != strbuf);
if (value == nullptr) {
return;
@@ -257,13 +283,12 @@ static inline void ffStrbufAppend(FFstrbuf* __restrict strbuf, const FFstrbuf* _
ffStrbufAppendNS(strbuf, value->length, value->chars);
}
static inline void ffStrbufRecalculateLength(FFstrbuf* strbuf) {
[[gnu::nonnull(1)]] static inline void ffStrbufRecalculateLength(FFstrbuf* strbuf) {
strbuf->length = (uint32_t) strlen(strbuf->chars);
}
static inline void ffStrbufSetS(FFstrbuf* strbuf, const char* value) {
assert(strbuf != nullptr);
// `value` may be null (clears the buffer); `strbuf` may not
[[gnu::nonnull(1)]] static inline void ffStrbufSetS(FFstrbuf* strbuf, const char* value) {
if (value == nullptr) {
ffStrbufClear(strbuf);
} else {
@@ -271,9 +296,7 @@ static inline void ffStrbufSetS(FFstrbuf* strbuf, const char* value) {
}
}
static inline bool ffStrbufSetJsonVal(FFstrbuf* strbuf, yyjson_val* jsonVal) {
assert(strbuf != nullptr);
[[gnu::nonnull(1)]] static inline bool ffStrbufSetJsonVal(FFstrbuf* strbuf, yyjson_val* jsonVal) {
if (yyjson_is_str(jsonVal)) {
ffStrbufSetNS(strbuf, (uint32_t) unsafe_yyjson_get_len(jsonVal), unsafe_yyjson_get_str(jsonVal));
return true;
@@ -283,13 +306,15 @@ static inline bool ffStrbufSetJsonVal(FFstrbuf* strbuf, yyjson_val* jsonVal) {
return false;
}
static inline void ffStrbufAppendS(FFstrbuf* strbuf, const char* value) {
[[gnu::nonnull(1)]] static inline void ffStrbufAppendS(FFstrbuf* strbuf, const char* value) {
if (value == nullptr) {
return;
}
ffStrbufAppendNS(strbuf, (uint32_t) strlen(value), value);
}
// Returns whether `jsonVal` was a string. Callers routinely pre-check with `yyjson_is_str`, so the
// result is not `nodiscard`.
static inline bool ffStrbufAppendJsonVal(FFstrbuf* strbuf, yyjson_val* jsonVal) {
if (yyjson_is_str(jsonVal)) {
ffStrbufAppendNS(strbuf, (uint32_t) unsafe_yyjson_get_len(jsonVal), unsafe_yyjson_get_str(jsonVal));
@@ -298,7 +323,7 @@ static inline bool ffStrbufAppendJsonVal(FFstrbuf* strbuf, yyjson_val* jsonVal)
return false;
}
static inline void ffStrbufInit(FFstrbuf* strbuf) {
[[gnu::nonnull(1)]] static inline void ffStrbufInit(FFstrbuf* strbuf) {
extern char* CHAR_NULL_PTR;
strbuf->allocated = strbuf->length = 0;
strbuf->chars = CHAR_NULL_PTR;
@@ -327,7 +352,7 @@ static inline void ffStrbufInitStatic(FFstrbuf* strbuf, const char* str) {
return strbuf;
}
static inline void ffStrbufSetStatic(FFstrbuf* strbuf, const char* value) {
[[gnu::nonnull(1)]] static inline void ffStrbufSetStatic(FFstrbuf* strbuf, const char* value) {
if (strbuf->allocated > 0) {
free(strbuf->chars);
}
@@ -339,7 +364,7 @@ static inline void ffStrbufSetStatic(FFstrbuf* strbuf, const char* value) {
}
}
static inline void ffStrbufInitNS(FFstrbuf* strbuf, uint32_t length, const char* str) {
[[gnu::nonnull(1)]] static inline void ffStrbufInitNS(FFstrbuf* strbuf, uint32_t length, const char* str) {
ffStrbufInit(strbuf);
ffStrbufAppendNS(strbuf, length, str);
}
@@ -350,12 +375,13 @@ static inline void ffStrbufInitNS(FFstrbuf* strbuf, uint32_t length, const char*
return strbuf;
}
// Returns whether `jsonVal` was a string; not `nodiscard`, same reason as ffStrbufAppendJsonVal
static inline bool ffStrbufInitJsonVal(FFstrbuf* strbuf, yyjson_val* jsonVal) {
ffStrbufInit(strbuf);
return ffStrbufAppendJsonVal(strbuf, jsonVal);
}
static inline void ffStrbufInitS(FFstrbuf* strbuf, const char* str) {
[[gnu::nonnull(1)]] static inline void ffStrbufInitS(FFstrbuf* strbuf, const char* str) {
ffStrbufInit(strbuf);
ffStrbufAppendS(strbuf, str);
}
@@ -366,107 +392,107 @@ static inline void ffStrbufInitS(FFstrbuf* strbuf, const char* str) {
return strbuf;
}
static inline void ffStrbufPrepend(FFstrbuf* strbuf, FFstrbuf* value) {
[[gnu::nonnull(1)]] static inline void ffStrbufPrepend(FFstrbuf* strbuf, FFstrbuf* value) {
if (value == nullptr) {
return;
}
ffStrbufPrependNS(strbuf, value->length, value->chars);
}
static inline void ffStrbufPrependS(FFstrbuf* strbuf, const char* value) {
[[gnu::nonnull(1)]] static inline void ffStrbufPrependS(FFstrbuf* strbuf, const char* value) {
if (value == nullptr) {
return;
}
ffStrbufPrependNS(strbuf, (uint32_t) strlen(value), value);
}
[[nodiscard]] static inline int ffStrbufComp(const FFstrbuf* strbuf, const FFstrbuf* comp) {
[[gnu::nonnull(1, 2), gnu::pure, 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);
}
[[nodiscard]] static inline bool ffStrbufEqual(const FFstrbuf* strbuf, const FFstrbuf* comp) {
[[gnu::nonnull(1, 2), gnu::pure, nodiscard]] static inline bool ffStrbufEqual(const FFstrbuf* strbuf, const FFstrbuf* comp) {
return ffStrbufComp(strbuf, comp) == 0;
}
[[nodiscard]] static inline int ffStrbufCompS(const FFstrbuf* strbuf, const char* comp) {
[[gnu::nonnull(1, 2), gnu::pure, nodiscard]] static inline int ffStrbufCompS(const FFstrbuf* strbuf, const char* comp) {
return strcmp(strbuf->chars, comp);
}
[[nodiscard]] static inline bool ffStrbufEqualS(const FFstrbuf* strbuf, const char* comp) {
[[gnu::nonnull(1, 2), gnu::pure, nodiscard]] static inline bool ffStrbufEqualS(const FFstrbuf* strbuf, const char* comp) {
return ffStrbufCompS(strbuf, comp) == 0;
}
[[nodiscard]] static inline int ffStrbufIgnCaseCompS(const FFstrbuf* strbuf, const char* comp) {
[[gnu::nonnull(1, 2), gnu::pure, nodiscard]] static inline int ffStrbufIgnCaseCompS(const FFstrbuf* strbuf, const char* comp) {
return strcasecmp(strbuf->chars, comp);
}
[[nodiscard]] static inline bool ffStrbufIgnCaseEqualS(const FFstrbuf* strbuf, const char* comp) {
[[gnu::nonnull(1, 2), gnu::pure, nodiscard]] static inline bool ffStrbufIgnCaseEqualS(const FFstrbuf* strbuf, const char* comp) {
return ffStrbufIgnCaseCompS(strbuf, comp) == 0;
}
[[nodiscard]] static inline int ffStrbufIgnCaseComp(const FFstrbuf* strbuf, const FFstrbuf* comp) {
[[gnu::nonnull(1, 2), gnu::pure, nodiscard]] static inline int ffStrbufIgnCaseComp(const FFstrbuf* strbuf, const FFstrbuf* comp) {
return ffStrbufIgnCaseCompS(strbuf, comp->chars);
}
[[nodiscard]] static inline bool ffStrbufIgnCaseEqual(const FFstrbuf* strbuf, const FFstrbuf* comp) {
[[gnu::nonnull(1, 2), gnu::pure, nodiscard]] static inline bool ffStrbufIgnCaseEqual(const FFstrbuf* strbuf, const FFstrbuf* comp) {
return ffStrbufIgnCaseComp(strbuf, comp) == 0;
}
[[nodiscard]] static inline bool ffStrbufContainC(const FFstrbuf* strbuf, char c) {
[[gnu::nonnull(1), gnu::pure, nodiscard]] static inline bool ffStrbufContainC(const FFstrbuf* strbuf, char c) {
return memchr(strbuf->chars, c, strbuf->length) != nullptr;
}
[[nodiscard]] static inline bool ffStrbufContainS(const FFstrbuf* strbuf, const char* str) {
[[gnu::nonnull(1, 2), gnu::pure, nodiscard]] static inline bool ffStrbufContainS(const FFstrbuf* strbuf, const char* str) {
return strstr(strbuf->chars, str) != nullptr;
}
[[nodiscard]] static inline bool ffStrbufContain(const FFstrbuf* strbuf, const FFstrbuf* str) {
[[gnu::nonnull(1, 2), gnu::pure, nodiscard]] static inline bool ffStrbufContain(const FFstrbuf* strbuf, const FFstrbuf* str) {
return ffStrbufContainS(strbuf, str->chars);
}
[[nodiscard]] static inline bool ffStrbufContainIgnCaseS(const FFstrbuf* strbuf, const char* str) {
[[gnu::nonnull(1, 2), gnu::pure, nodiscard]] static inline bool ffStrbufContainIgnCaseS(const FFstrbuf* strbuf, const char* str) {
return strcasestr(strbuf->chars, str) != nullptr;
}
[[nodiscard]] static inline bool ffStrbufContainIgnCase(const FFstrbuf* strbuf, const FFstrbuf* str) {
[[gnu::nonnull(1, 2), gnu::pure, nodiscard]] static inline bool ffStrbufContainIgnCase(const FFstrbuf* strbuf, const FFstrbuf* str) {
return ffStrbufContainIgnCaseS(strbuf, str->chars);
}
[[nodiscard]] static inline uint32_t ffStrbufNextIndexC(const FFstrbuf* strbuf, uint32_t start, char c) {
[[gnu::nonnull(1), gnu::pure, 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;
}
[[nodiscard]] static inline uint32_t ffStrbufNextIndexS(const FFstrbuf* strbuf, uint32_t start, const char* str) {
[[gnu::nonnull(1, 3), gnu::pure, 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;
}
[[nodiscard]] static inline uint32_t ffStrbufPreviousIndexC(const FFstrbuf* strbuf, uint32_t start, char c) {
[[gnu::nonnull(1), gnu::pure, 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;
}
[[nodiscard]] static inline uint32_t ffStrbufFirstIndexC(const FFstrbuf* strbuf, char c) {
[[gnu::nonnull(1), gnu::pure, nodiscard]] static inline uint32_t ffStrbufFirstIndexC(const FFstrbuf* strbuf, char c) {
return ffStrbufNextIndexC(strbuf, 0, c);
}
[[nodiscard]] static inline uint32_t ffStrbufFirstIndex(const FFstrbuf* strbuf, const FFstrbuf* searched) {
[[gnu::nonnull(1, 2), gnu::pure, nodiscard]] static inline uint32_t ffStrbufFirstIndex(const FFstrbuf* strbuf, const FFstrbuf* searched) {
return ffStrbufNextIndexS(strbuf, 0, searched->chars);
}
[[nodiscard]] static inline uint32_t ffStrbufFirstIndexS(const FFstrbuf* strbuf, const char* str) {
[[gnu::nonnull(1, 2), gnu::pure, nodiscard]] static inline uint32_t ffStrbufFirstIndexS(const FFstrbuf* strbuf, const char* str) {
return ffStrbufNextIndexS(strbuf, 0, str);
}
[[nodiscard]] static inline uint32_t ffStrbufLastIndexC(const FFstrbuf* strbuf, char c) {
[[gnu::nonnull(1), gnu::pure, nodiscard]] static inline uint32_t ffStrbufLastIndexC(const FFstrbuf* strbuf, char c) {
if (strbuf->length == 0) {
return 0;
}
@@ -474,19 +500,19 @@ static inline void ffStrbufPrependS(FFstrbuf* strbuf, const char* value) {
return ffStrbufPreviousIndexC(strbuf, strbuf->length - 1, c);
}
static inline bool ffStrbufSubstrBeforeFirstC(FFstrbuf* strbuf, char c) {
[[gnu::nonnull(1)]] static inline bool ffStrbufSubstrBeforeFirstC(FFstrbuf* strbuf, char c) {
return ffStrbufSubstrBefore(strbuf, ffStrbufFirstIndexC(strbuf, c));
}
static inline bool ffStrbufSubstrBeforeLastC(FFstrbuf* strbuf, char c) {
[[gnu::nonnull(1)]] static inline bool ffStrbufSubstrBeforeLastC(FFstrbuf* strbuf, char c) {
return ffStrbufSubstrBefore(strbuf, ffStrbufLastIndexC(strbuf, c));
}
[[nodiscard]] static inline bool ffStrbufStartsWithC(const FFstrbuf* strbuf, char c) {
[[gnu::nonnull(1), gnu::pure, nodiscard]] static inline bool ffStrbufStartsWithC(const FFstrbuf* strbuf, char c) {
return strbuf->chars[0] == c;
}
[[nodiscard]] static inline bool ffStrbufStartsWithSN(const FFstrbuf* strbuf, const char* start, uint32_t length) {
[[gnu::nonnull(1, 2), gnu::pure, nodiscard]] static inline bool ffStrbufStartsWithSN(const FFstrbuf* strbuf, const char* start, uint32_t length) {
if (length > strbuf->length) {
return false;
}
@@ -494,34 +520,34 @@ static inline bool ffStrbufSubstrBeforeLastC(FFstrbuf* strbuf, char c) {
return memcmp(strbuf->chars, start, length) == 0;
}
[[nodiscard]] static inline bool ffStrbufStartsWithS(const FFstrbuf* strbuf, const char* start) {
[[gnu::nonnull(1, 2), gnu::pure, nodiscard]] static inline bool ffStrbufStartsWithS(const FFstrbuf* strbuf, const char* start) {
return ffStrbufStartsWithSN(strbuf, start, (uint32_t) strlen(start));
}
[[nodiscard]] static inline bool ffStrbufStartsWith(const FFstrbuf* strbuf, const FFstrbuf* start) {
[[gnu::nonnull(1, 2), gnu::pure, nodiscard]] static inline bool ffStrbufStartsWith(const FFstrbuf* strbuf, const FFstrbuf* start) {
return ffStrbufStartsWithSN(strbuf, start->chars, start->length);
}
[[nodiscard]] static inline bool ffStrbufStartsWithIgnCaseNS(const FFstrbuf* strbuf, uint32_t length, const char* start) {
[[gnu::nonnull(1, 3), gnu::pure, 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;
}
[[nodiscard]] static inline bool ffStrbufStartsWithIgnCaseS(const FFstrbuf* strbuf, const char* start) {
[[gnu::nonnull(1, 2), gnu::pure, nodiscard]] static inline bool ffStrbufStartsWithIgnCaseS(const FFstrbuf* strbuf, const char* start) {
return ffStrbufStartsWithIgnCaseNS(strbuf, (uint32_t) strlen(start), start);
}
[[nodiscard]] static inline bool ffStrbufStartsWithIgnCase(const FFstrbuf* strbuf, const FFstrbuf* start) {
[[gnu::nonnull(1, 2), gnu::pure, nodiscard]] static inline bool ffStrbufStartsWithIgnCase(const FFstrbuf* strbuf, const FFstrbuf* start) {
return ffStrbufStartsWithIgnCaseNS(strbuf, start->length, start->chars);
}
[[nodiscard]] static inline bool ffStrbufEndsWithC(const FFstrbuf* strbuf, char c) {
[[gnu::nonnull(1), gnu::pure, nodiscard]] static inline bool ffStrbufEndsWithC(const FFstrbuf* strbuf, char c) {
return strbuf->length == 0 ? false : strbuf->chars[strbuf->length - 1] == c;
}
[[nodiscard]] static inline bool ffStrbufEndsWithNS(const FFstrbuf* strbuf, uint32_t endLength, const char* end) {
[[gnu::nonnull(1, 3), gnu::pure, nodiscard]] static inline bool ffStrbufEndsWithNS(const FFstrbuf* strbuf, uint32_t endLength, const char* end) {
if (endLength > strbuf->length) {
return false;
}
@@ -529,104 +555,108 @@ static inline bool ffStrbufSubstrBeforeLastC(FFstrbuf* strbuf, char c) {
return memcmp(strbuf->chars + strbuf->length - endLength, end, endLength) == 0;
}
[[nodiscard]] static inline bool ffStrbufEndsWithS(const FFstrbuf* strbuf, const char* end) {
[[gnu::nonnull(1, 2), gnu::pure, nodiscard]] static inline bool ffStrbufEndsWithS(const FFstrbuf* strbuf, const char* end) {
return ffStrbufEndsWithNS(strbuf, (uint32_t) strlen(end), end);
}
[[nodiscard]] static inline bool ffStrbufEndsWithFn(const FFstrbuf* strbuf, int (*const fn)(int)) {
// Not `pure`: the caller-supplied `fn` may have side effects
[[gnu::nonnull(1, 2), nodiscard]] static inline bool ffStrbufEndsWithFn(const FFstrbuf* strbuf, int (*const fn)(int)) {
return strbuf->length == 0 ? false : fn(strbuf->chars[strbuf->length - 1]);
}
[[nodiscard]] static inline bool ffStrbufEndsWith(const FFstrbuf* strbuf, const FFstrbuf* end) {
[[gnu::nonnull(1, 2), gnu::pure, nodiscard]] static inline bool ffStrbufEndsWith(const FFstrbuf* strbuf, const FFstrbuf* end) {
return ffStrbufEndsWithNS(strbuf, end->length, end->chars);
}
[[nodiscard]] static inline bool ffStrbufEndsWithIgnCaseNS(const FFstrbuf* strbuf, uint32_t endLength, const char* end) {
[[gnu::nonnull(1, 3), gnu::pure, 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;
}
[[nodiscard]] static inline bool ffStrbufEndsWithIgnCaseS(const FFstrbuf* strbuf, const char* end) {
[[gnu::nonnull(1, 2), gnu::pure, nodiscard]] static inline bool ffStrbufEndsWithIgnCaseS(const FFstrbuf* strbuf, const char* end) {
return ffStrbufEndsWithIgnCaseNS(strbuf, (uint32_t) strlen(end), end);
}
[[nodiscard]] static inline bool ffStrbufEndsWithIgnCase(const FFstrbuf* strbuf, const FFstrbuf* end) {
[[gnu::nonnull(1, 2), gnu::pure, nodiscard]] static inline bool ffStrbufEndsWithIgnCase(const FFstrbuf* strbuf, const FFstrbuf* end) {
return ffStrbufEndsWithIgnCaseNS(strbuf, end->length, end->chars);
}
static inline void ffStrbufTrim(FFstrbuf* strbuf, char c) {
[[gnu::nonnull(1)]] static inline void ffStrbufTrim(FFstrbuf* strbuf, char c) {
ffStrbufTrimRight(strbuf, c);
ffStrbufTrimLeft(strbuf, c);
}
static inline void ffStrbufTrimSpace(FFstrbuf* strbuf) {
[[gnu::nonnull(1)]] static inline void ffStrbufTrimSpace(FFstrbuf* strbuf) {
ffStrbufTrimRightSpace(strbuf);
ffStrbufTrimLeftSpace(strbuf);
}
static inline bool ffStrbufMatchSeparatedS(const FFstrbuf* strbuf, const char* comp, char separator) {
[[gnu::nonnull(1, 2), gnu::pure, nodiscard]] static inline bool ffStrbufMatchSeparatedS(const FFstrbuf* strbuf, const char* comp, char separator) {
return ffStrbufMatchSeparatedNS(strbuf, (uint32_t) strlen(comp), comp, separator);
}
static inline bool ffStrbufMatchSeparated(const FFstrbuf* strbuf, const FFstrbuf* comp, char separator) {
[[gnu::nonnull(1, 2), gnu::pure, nodiscard]] static inline bool ffStrbufMatchSeparated(const FFstrbuf* strbuf, const FFstrbuf* comp, char separator) {
return ffStrbufMatchSeparatedNS(strbuf, comp->length, comp->chars, separator);
}
static inline bool ffStrbufMatchSeparatedIgnCaseS(const FFstrbuf* strbuf, const char* comp, char separator) {
[[gnu::nonnull(1, 2), gnu::pure, nodiscard]] static inline bool ffStrbufMatchSeparatedIgnCaseS(const FFstrbuf* strbuf, const char* comp, char separator) {
return ffStrbufMatchSeparatedIgnCaseNS(strbuf, (uint32_t) strlen(comp), comp, separator);
}
static inline bool ffStrbufMatchSeparatedIgnCase(const FFstrbuf* strbuf, const FFstrbuf* comp, char separator) {
[[gnu::nonnull(1, 2), gnu::pure, nodiscard]] static inline bool ffStrbufMatchSeparatedIgnCase(const FFstrbuf* strbuf, const FFstrbuf* comp, char separator) {
return ffStrbufMatchSeparatedIgnCaseNS(strbuf, comp->length, comp->chars, separator);
}
static inline bool ffStrbufSeparatedContainS(const FFstrbuf* strbuf, const char* comp, char separator) {
[[gnu::nonnull(1, 2), gnu::pure, nodiscard]] static inline bool ffStrbufSeparatedContainS(const FFstrbuf* strbuf, const char* comp, char separator) {
return ffStrbufSeparatedContainNS(strbuf, (uint32_t) strlen(comp), comp, separator);
}
static inline bool ffStrbufSeparatedContain(const FFstrbuf* strbuf, const FFstrbuf* comp, char separator) {
[[gnu::nonnull(1, 2), gnu::pure, nodiscard]] static inline bool ffStrbufSeparatedContain(const FFstrbuf* strbuf, const FFstrbuf* comp, char separator) {
return ffStrbufSeparatedContainNS(strbuf, comp->length, comp->chars, separator);
}
static inline bool ffStrbufSeparatedContainIgnCaseS(const FFstrbuf* strbuf, const char* comp, char separator) {
[[gnu::nonnull(1, 2), gnu::pure, nodiscard]] static inline bool ffStrbufSeparatedContainIgnCaseS(const FFstrbuf* strbuf, const char* comp, char separator) {
return ffStrbufSeparatedContainIgnCaseNS(strbuf, (uint32_t) strlen(comp), comp, separator);
}
static inline bool ffStrbufSeparatedContainIgnCase(const FFstrbuf* strbuf, const FFstrbuf* comp, char separator) {
[[gnu::nonnull(1, 2), gnu::pure, nodiscard]] static inline bool ffStrbufSeparatedContainIgnCase(const FFstrbuf* strbuf, const FFstrbuf* comp, char separator) {
return ffStrbufSeparatedContainIgnCaseNS(strbuf, comp->length, comp->chars, separator);
}
static inline void ffStrbufWriteTo(const FFstrbuf* strbuf, FILE* file) {
[[gnu::nonnull(1, 2)]] static inline void ffStrbufWriteTo(const FFstrbuf* strbuf, FILE* file) {
fwrite(strbuf->chars, sizeof(*strbuf->chars), strbuf->length, file);
}
static inline void ffStrbufPutTo(const FFstrbuf* strbuf, FILE* file) {
[[gnu::nonnull(1, 2)]] static inline void ffStrbufPutTo(const FFstrbuf* strbuf, FILE* file) {
ffStrbufWriteTo(strbuf, file);
fputc('\n', file);
}
[[nodiscard]] static inline double ffStrbufToDouble(const FFstrbuf* strbuf, double defaultValue) {
// Not `pure`: `strtod` reads the LC_NUMERIC locale and writes errno
[[gnu::nonnull(1), 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;
}
[[nodiscard]] static inline uint64_t ffStrbufToUInt(const FFstrbuf* strbuf, uint64_t defaultValue) {
// Not `pure`: `strtoull` reads the LC_NUMERIC locale and writes errno
[[gnu::nonnull(1), 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;
}
[[nodiscard]] static inline int64_t ffStrbufToSInt(const FFstrbuf* strbuf, int64_t defaultValue) {
// Not `pure`: `strtoll` reads the LC_NUMERIC locale and writes errno
[[gnu::nonnull(1), 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;
}
// Returns true if the strbuf is modified
bool ffStrbufDecodeHexEscapeSequences(FFstrbuf* strbuf);
[[gnu::nonnull(1)]] [[gnu::nonnull(1)]] bool ffStrbufDecodeHexEscapeSequences(FFstrbuf* strbuf);
#define FF_STRBUF_AUTO_DESTROY [[gnu::cleanup(ffStrbufDestroy)]] FFstrbuf
#define FF_STRBUF_STATIC(str) { .allocated = 0, .length = (uint32_t) sizeof(str) - 1, .chars = str }
+45
View File
@@ -0,0 +1,45 @@
#pragma once
#include <stdbool.h>
#include <stdint.h>
// The NDK marks an API unavailable whenever it is newer than the API level the build targets, and
// fastfetch keeps running on devices below the levels it uses: AImageDecoder is 30, decoding past
// the first frame is 31, and AMediaCodec_getName is 28. CMake compiles the files that reach for
// them with -D__ANDROID_UNAVAILABLE_SYMBOLS_ARE_WEAK__ -Werror=unguarded-availability, which turns
// those entry points into weak references and makes every unguarded use an error. Two things follow:
//
// * A weak reference resolves to null on an older device, so every use needs a run-time check --
// that is FF_ANDROID_API_AT_LEAST. Unguarded, the call would jump to a null pointer.
// * Annotating a helper with FF_ANDROID_REQUIRES_API keeps the check in one place: the compiler rejects
// any call of that helper which is not itself inside a guard.
//
// https://developer.android.com/ndk/guides/using-newer-apis
#define FF_ANDROID_REQUIRES_API(x) [[clang::availability(android, introduced = x)]]
#define FF_ANDROID_API_AT_LEAST(x) __builtin_available(android x, *)
// The UIDs that hold android.permission.DUMP, which is what `dumpsys` checks before it prints
// anything: every other UID is refused on stdout and the command still exits 0, which a caller cannot
// tell apart from a command that printed nothing useful. Forking a `dumpsys` from anywhere else is
// therefore pure waste, and for some fields `dumpsys` is the only route there is.
//
// The refusal is not always the permission, and the text differs per service and per release. On
// an Android 16 device an app UID gets `Permission Denial: can't dump DisplayManagerService ... due to
// missing android.permission.DUMP permission` for `display`, but `Can't find service: battery` for
// `battery` -- that service is not in the list `dumpsys -l` shows an app at all, while `display` is.
// The UID is what decides, so one check covers both.
//
// android.os.Process.ROOT_UID and SHELL_UID. The shell UID has a second use: it owns exactly one
// package name, which the system services accept, so a process that cannot derive its own package
// can answer with that one instead.
typedef enum FFAndroidPrivilegedUid : uint32_t {
FF_ANDROID_PRIVILEGED_UID_ROOT = 0,
FF_ANDROID_PRIVILEGED_UID_SHELL = 2000,
} FFAndroidPrivilegedUid;
// Whether the given UID is allowed to run `dumpsys`. The UID is passed in rather than read here, so
// that the caller can take it from `instance.state.platform.uid` -- which is what makes the
// privileged path reachable from a test that does not run as root or as the shell.
static inline bool ffAndroidIsRootOrShell(uint32_t uid) {
return uid == FF_ANDROID_PRIVILEGED_UID_ROOT || uid == FF_ANDROID_PRIVILEGED_UID_SHELL;
}
+237
View File
@@ -0,0 +1,237 @@
#include "common/android/binder.h"
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
const char* ffBinderOpen(FFBinder* binder) {
*binder = (FFBinder) { .fd = -1, .shared = nullptr, .sharedSize = 0, .protocolVersion = 0 };
const int fd = open(FF_BINDER_DEVICE, O_RDWR | O_CLOEXEC);
if (fd < 0) {
return "Failed to open " FF_BINDER_DEVICE;
}
struct binder_version version = { .protocol_version = 0 };
if (ioctl(fd, BINDER_VERSION, &version) != 0 || version.protocol_version != BINDER_CURRENT_PROTOCOL_VERSION) {
close(fd);
return "Unsupported binder protocol version";
}
// The region is read-only: the kernel writes reply payloads into it and hands out their
// addresses in BR_REPLY, so it has to stay mapped for as long as the handle is used.
void* shared = mmap(nullptr, FF_BINDER_SHARED_SIZE, PROT_READ, MAP_PRIVATE | MAP_NORESERVE, fd, 0);
if (shared == MAP_FAILED) {
close(fd);
return "Failed to mmap " FF_BINDER_DEVICE;
}
*binder = (FFBinder) {
.fd = fd,
.shared = (uint8_t*) shared,
.sharedSize = FF_BINDER_SHARED_SIZE,
.protocolVersion = version.protocol_version,
};
return nullptr;
}
void ffBinderClose(FFBinder* binder) {
if (binder->shared != nullptr) {
munmap(binder->shared, binder->sharedSize);
}
if (binder->fd >= 0) {
close(binder->fd);
}
binder->fd = -1;
binder->shared = nullptr;
binder->sharedSize = 0;
}
const char* ffBinderTransact(FFBinder* binder, uint32_t handle, uint32_t code, const FFBinderParcel* parcel, FFBinderReply* reply) {
reply->size = 0;
reply->code = 0;
reply->flags = 0;
reply->handleCount = 0;
if (parcel->truncated) {
return "Binder parcel does not fit the caller buffer";
}
uint8_t writeBuffer[sizeof(uint32_t) + sizeof(struct binder_transaction_data)];
const struct binder_transaction_data transaction = {
.target = { .handle = handle },
.cookie = 0,
.code = code,
.flags = 0, // a synchronous call; TF_ONE_WAY is the only flag the kernel acts on here
.sender_pid = 0,
.sender_euid = 0,
.data_size = parcel->size,
.offsets_size = 0,
.data = { .ptr = { .buffer = (binder_uintptr_t) (uintptr_t) parcel->data, .offsets = 0 } },
};
const uint32_t transactionCommand = BC_TRANSACTION;
memcpy(writeBuffer, &transactionCommand, sizeof(uint32_t));
memcpy(writeBuffer + sizeof(uint32_t), &transaction, sizeof(transaction));
// The read buffer only has to hold the command words and the binder_transaction_data that
// follows BR_REPLY; the payload itself lives in the mmap region.
uint8_t readBuffer[FF_BINDER_REPLY_BUFFER_SIZE];
struct binder_write_read exchange = {
.write_size = sizeof(writeBuffer),
.write_consumed = 0,
.write_buffer = (binder_uintptr_t) (uintptr_t) writeBuffer,
.read_size = sizeof(readBuffer),
.read_consumed = 0,
.read_buffer = (binder_uintptr_t) (uintptr_t) readBuffer,
};
if (ioctl(binder->fd, BINDER_WRITE_READ, &exchange) != 0) {
return "BINDER_WRITE_READ failed";
}
const uint8_t* cursor = readBuffer;
const uint8_t* end = readBuffer + (size_t) exchange.read_consumed;
while ((size_t) (end - cursor) >= sizeof(uint32_t)) {
uint32_t command = 0;
memcpy(&command, cursor, sizeof(uint32_t));
cursor += sizeof(uint32_t);
switch (command) {
case BR_NOOP:
case BR_TRANSACTION_COMPLETE:
case BR_SPAWN_LOOPER:
break;
case BR_FAILED_REPLY:
return "Binder transaction failed";
case BR_DEAD_REPLY:
return "Binder service is not running";
case BR_INCREFS:
case BR_ACQUIRE:
case BR_RELEASE:
case BR_DECREFS:
cursor += sizeof(struct binder_ptr_cookie);
break;
case BR_DEAD_BINDER:
case BR_CLEAR_DEATH_NOTIFICATION_DONE:
cursor += sizeof(binder_uintptr_t);
break;
case BR_ERROR:
cursor += sizeof(int32_t);
break;
case BR_REPLY: {
if ((size_t) (end - cursor) < sizeof(struct binder_transaction_data)) {
return "Truncated binder reply";
}
struct binder_transaction_data data;
memcpy(&data, cursor, sizeof(data));
cursor += sizeof(data);
reply->code = data.code;
reply->flags = data.flags;
const uint8_t* payload = (const uint8_t*) (uintptr_t) data.data.ptr.buffer;
const size_t payloadSize = (size_t) data.data_size;
const uint8_t* offsets = (const uint8_t*) (uintptr_t) data.data.ptr.offsets;
const size_t offsetsSize = (size_t) data.offsets_size;
const char* error = nullptr;
if (payloadSize > 0) {
if (payloadSize > reply->capacity) {
error = "Binder reply does not fit the caller buffer";
} else {
memcpy(reply->data, payload, payloadSize);
reply->size = payloadSize;
}
}
// Walk the offset table for the flat objects the service sent us and keep the
// strong handles: those are the ones a later transaction can address.
for (size_t offset = 0; offset + sizeof(binder_size_t) <= offsetsSize; offset += sizeof(binder_size_t)) {
binder_size_t objectOffset = 0;
memcpy(&objectOffset, offsets + offset, sizeof(objectOffset));
if (objectOffset + sizeof(struct flat_binder_object) > payloadSize) {
continue;
}
struct flat_binder_object object;
memcpy(&object, payload + objectOffset, sizeof(object));
if (object.hdr.type != BINDER_TYPE_HANDLE) {
continue;
}
if (reply->handleCount < FF_BINDER_MAX_HANDLES) {
reply->handles[reply->handleCount++] = object.handle;
}
}
// The kernel gave us a new reference whose only strong reference belongs to the
// reply buffer, so it has to be acquired before that buffer is freed -- otherwise
// the handle silently degrades to a weak reference and every later transaction on
// it fails with BR_FAILED_REPLY. libbinder does the same in acquire_object().
uint8_t tail[FF_BINDER_MAX_HANDLES * 4 * sizeof(uint32_t) + sizeof(uint32_t) + sizeof(binder_uintptr_t)];
size_t tailSize = 0;
for (uint32_t i = 0; i < reply->handleCount; i++) {
const uint32_t acquire = BC_ACQUIRE;
const uint32_t increfs = BC_INCREFS;
memcpy(tail + tailSize, &acquire, sizeof(uint32_t));
tailSize += sizeof(uint32_t);
memcpy(tail + tailSize, &reply->handles[i], sizeof(uint32_t));
tailSize += sizeof(uint32_t);
memcpy(tail + tailSize, &increfs, sizeof(uint32_t));
tailSize += sizeof(uint32_t);
memcpy(tail + tailSize, &reply->handles[i], sizeof(uint32_t));
tailSize += sizeof(uint32_t);
}
const uint32_t freeCommand = BC_FREE_BUFFER;
const binder_uintptr_t freeBuffer = data.data.ptr.buffer;
memcpy(tail + tailSize, &freeCommand, sizeof(uint32_t));
tailSize += sizeof(uint32_t);
memcpy(tail + tailSize, &freeBuffer, sizeof(freeBuffer));
tailSize += sizeof(freeBuffer);
struct binder_write_read release = {
.write_size = tailSize,
.write_consumed = 0,
.write_buffer = (binder_uintptr_t) (uintptr_t) tail,
.read_size = 0,
.read_consumed = 0,
.read_buffer = 0,
};
ioctl(binder->fd, BINDER_WRITE_READ, &release);
return error;
}
default:
return "Unexpected binder command";
}
}
return "No reply from binder";
}
const char* ffBinderLookupService(FFBinder* binder, const char* name, uint32_t transactionCode, uint32_t* handle) {
uint8_t parcelBuffer[256];
FFBinderParcel parcel = ffBinderParcelCreate(parcelBuffer, sizeof(parcelBuffer));
ffBinderParcelPutInterfaceToken(&parcel, FF_BINDER_SM_DESCRIPTOR);
ffBinderParcelPutString16(&parcel, name);
uint8_t replyBuffer[256];
FFBinderReply reply = ffBinderReplyCreate(replyBuffer, sizeof(replyBuffer));
const char* error = ffBinderTransact(binder, FF_BINDER_SERVICE_MANAGER_HANDLE, transactionCode, &parcel, &reply);
if (error != nullptr) {
return error;
}
if (ffBinderReplyIsStatus(&reply)) {
return "Service manager rejected the request";
}
if (ffBinderReadI32(reply.data, reply.size, 0) != 0) {
return "Service manager raised an exception";
}
if (reply.handleCount == 0) {
return "Service is not registered";
}
*handle = reply.handles[0];
return nullptr;
}
+224
View File
@@ -0,0 +1,224 @@
#pragma once
// Android exposes no public C API for the system services that carry the data fastfetch wants: the
// NDK has no BatteryManager / WifiManager, libbinder_ndk only speaks to AIDL HALs (it refuses to
// prepare a transaction for a binder that has no NDK class), and `/system/bin/service call` costs a
// fork/exec worth 15-20 ms. What is left is /dev/binder itself, which is all that `service` uses
// underneath. This header speaks that protocol directly: open() + mmap() + BINDER_WRITE_READ, no
// extra shared library, no child process, ~0.13 ms per call once a handle is cached.
//
// Three details are easy to get wrong. All three were confirmed against the device's own
// libbinder.so and with a ptrace trace of `service`, and getting any of them wrong makes the
// service answer BAD_TYPE (0x80000001) or BR_FAILED_REPLY (0x7211):
//
// * A request parcel must start with three int32 values -- strict mode policy, work source and
// 'SYST'. Parcel::markForBinder() writes nothing for kernel binder, but the receiving side's
// Parcel::enforceInterface() still compares the third word against its own header.
// * Parcel::writeString16() writes the length, the UTF-16 code units, a UTF-16 NUL terminator and
// then pads to four bytes. Skipping the terminator shifts every following field by four bytes.
// * A handle arriving in a reply is owned by that reply buffer. It has to be acquired
// (BC_ACQUIRE + BC_INCREFS) before BC_FREE_BUFFER; otherwise only a weak reference survives and
// every later transaction on it fails, because the kernel looks up a strong reference.
//
// See .workbuddy-ai/android-binder-raw-client.md for the full write-up and the tooling.
#include "fastfetch.h" // IWYU pragma: keep
// The structures and command words below are not defined here: bionic generates this header from
// bionic/libc/kernel/uapi/linux/android/binder.h and every NDK ships it, so it is the
// authoritative copy of the binder ABI -- struct binder_write_read, struct binder_transaction_data,
// struct flat_binder_object, BINDER_WRITE_READ / BINDER_VERSION, the BC_* and BR_* command words,
// TF_* and BINDER_TYPE_*. Using it beats transcribing it: a second copy can only be wrong, and if
// the header itself is wrong that is the NDK's problem to fix, not something fastfetch could have
// caught by keeping its own.
#include <linux/android/binder.h>
#include <string.h>
#include <sys/ioctl.h>
#define FF_BINDER_DEVICE "/dev/binder"
// The kernel allocates reply payloads out of the region handed to mmap(); 1 MiB is what libbinder
// asks for. Replies themselves are small -- `listServices` on this device is the largest at a few
// hundred bytes -- but the region also carries the per-process buffer pool.
#define FF_BINDER_SHARED_SIZE (1024 * 1024)
// A command word plus the binder_transaction_data that follows it. The payload never lands here:
// it lives in the mmap region, and BR_REPLY only hands over a pointer to it.
#define FF_BINDER_REPLY_BUFFER_SIZE 1024
// How many handles a reply may transfer to us. Replies that carry more than this still succeed, but
// the surplus handles are left unacquired and will fail on first use.
#define FF_BINDER_MAX_HANDLES 4
// The three int32 values Parcel::writeInterfaceToken() puts in front of the descriptor, and that
// Parcel::enforceInterface() checks the last of. These come from libbinder rather than from the
// kernel, which is why they are spelled out here.
#define FF_BINDER_STRICT_MODE_PENALTY_GATHER 0x80000000u // (1 << 31), Parcel.cpp
#define FF_BINDER_UNSET_WORK_SOURCE 0xffffffffu // IPCThreadState::kUnsetWorkSource
#define FF_BINDER_HEADER 0x53595354u // B_PACK_CHARS('S', 'Y', 'S', 'T')
typedef struct FFBinder {
int fd;
uint8_t* shared;
size_t sharedSize;
int32_t protocolVersion;
} FFBinder;
// Opens /dev/binder, checks the protocol version and maps the shared region. Returns nullptr on
// success, a static message otherwise; the device is left closed on failure.
[[gnu::nonnull(1), nodiscard]] const char* ffBinderOpen(FFBinder* binder);
// Usable as a cleanup attribute. Safe on a zeroed or already closed FFBinder.
[[gnu::nonnull(1)]] void ffBinderClose(FFBinder* binder);
// ---------------------------------------------------------------------------------------------
// Parcel writing. The caller owns the buffer; anything that does not fit is dropped and recorded
// in `truncated`, which ffBinderTransact() then reports as an error.
// ---------------------------------------------------------------------------------------------
typedef struct FFBinderParcel {
uint8_t* data;
size_t capacity;
size_t size;
bool truncated;
} FFBinderParcel;
[[nodiscard]] static inline FFBinderParcel ffBinderParcelCreate(uint8_t* data, size_t capacity) {
return (FFBinderParcel) { .data = data, .capacity = capacity, .size = 0, .truncated = false };
}
[[gnu::nonnull(1), nodiscard]] static inline uint8_t* ffBinderParcelReserve(FFBinderParcel* parcel, size_t bytes) {
if (bytes > parcel->capacity - parcel->size) {
parcel->truncated = true;
return nullptr;
}
uint8_t* result = parcel->data + parcel->size;
parcel->size += bytes;
return result;
}
[[gnu::nonnull(1)]] static inline void ffBinderParcelPutU32(FFBinderParcel* parcel, uint32_t value) {
uint8_t* dst = ffBinderParcelReserve(parcel, sizeof(uint32_t));
if (dst != nullptr) {
memcpy(dst, &value, sizeof(uint32_t));
}
}
[[gnu::nonnull(1)]] static inline void ffBinderParcelPutI32(FFBinderParcel* parcel, int32_t value) {
uint8_t* dst = ffBinderParcelReserve(parcel, sizeof(int32_t));
if (dst != nullptr) {
memcpy(dst, &value, sizeof(int32_t));
}
}
[[gnu::nonnull(1)]] static inline void ffBinderParcelPutU64(FFBinderParcel* parcel, uint64_t value) {
uint8_t* dst = ffBinderParcelReserve(parcel, sizeof(uint64_t));
if (dst != nullptr) {
memcpy(dst, &value, sizeof(uint64_t));
}
}
// AIDL string16. The descriptors and service names fastfetch asks for are ASCII, so one byte is one
// UTF-16 code unit; anything else would have to be encoded properly here.
[[gnu::nonnull(1, 2)]] static inline void ffBinderParcelPutString16(FFBinderParcel* parcel, const char* value) {
const size_t length = strlen(value);
const size_t payload = sizeof(uint32_t) + (length + 1) * 2; // length, code units, NUL terminator
const size_t padded = (payload + 3) & ~(size_t) 3;
uint8_t* dst = ffBinderParcelReserve(parcel, padded);
if (dst == nullptr) {
return;
}
memset(dst, 0, padded);
const uint32_t length32 = (uint32_t) length;
memcpy(dst, &length32, sizeof(uint32_t));
for (size_t i = 0; i < length; i++) {
dst[sizeof(uint32_t) + i * 2] = (uint8_t) value[i];
}
// The two bytes after the last code unit stay zero: that is the UTF-16 NUL terminator, and
// Parcel::readInplace() advances by (length + 1) * sizeof(char16_t) to account for it.
}
[[gnu::nonnull(1, 2)]] static inline void ffBinderParcelPutInterfaceToken(FFBinderParcel* parcel, const char* descriptor) {
ffBinderParcelPutU32(parcel, FF_BINDER_STRICT_MODE_PENALTY_GATHER);
ffBinderParcelPutU32(parcel, FF_BINDER_UNSET_WORK_SOURCE);
ffBinderParcelPutU32(parcel, FF_BINDER_HEADER);
ffBinderParcelPutString16(parcel, descriptor);
}
// ---------------------------------------------------------------------------------------------
// Transactions
// ---------------------------------------------------------------------------------------------
typedef struct FFBinderReply {
uint8_t* data; // caller owned; receives the payload
size_t capacity; // ditto
size_t size; // payload length in bytes
uint32_t code; // transaction code the service echoed back
uint32_t flags; // TF_* of the reply
uint32_t handleCount;
uint32_t handles[FF_BINDER_MAX_HANDLES];
} FFBinderReply;
[[nodiscard]] static inline FFBinderReply ffBinderReplyCreate(uint8_t* data, size_t capacity) {
return (FFBinderReply) { .data = data, .capacity = capacity, .size = 0, .code = 0, .flags = 0, .handleCount = 0, .handles = {} };
}
// A reply carrying TF_STATUS_CODE is not an AIDL parcel at all: the first four bytes are the raw
// status_t that onTransact() returned (-74 being UNKNOWN_TRANSACTION, i.e. no such method). Check
// this before interpreting anything else.
[[gnu::nonnull(1), nodiscard]] static inline bool ffBinderReplyIsStatus(const FFBinderReply* reply) {
return (reply->flags & TF_STATUS_CODE) != 0;
}
[[gnu::nonnull(1), nodiscard]] static inline uint32_t ffBinderReadU32(const uint8_t* data, size_t size, size_t offset) {
uint32_t value = 0;
if (offset + sizeof(uint32_t) <= size) {
memcpy(&value, data + offset, sizeof(uint32_t));
}
return value;
}
[[gnu::nonnull(1), nodiscard]] static inline int32_t ffBinderReadI32(const uint8_t* data, size_t size, size_t offset) {
int32_t value = 0;
if (offset + sizeof(int32_t) <= size) {
memcpy(&value, data + offset, sizeof(int32_t));
}
return value;
}
[[gnu::nonnull(1), nodiscard]] static inline uint64_t ffBinderReadU64(const uint8_t* data, size_t size, size_t offset) {
uint64_t value = 0;
if (offset + sizeof(uint64_t) <= size) {
memcpy(&value, data + offset, sizeof(uint64_t));
}
return value;
}
// Synchronous transaction. Returns nullptr on success, a static message otherwise. Handles the
// reply carries are acquired and added to `reply->handles` before the reply buffer is freed.
//
// `handle` 0 is the service manager; every other handle comes from ffBinderLookupService(). A
// service that never replies blocks this call forever -- none of the services fastfetch reads does,
// but there is no timeout here to fall back on.
[[gnu::nonnull(1, 4, 5), nodiscard]] const char* ffBinderTransact(FFBinder* binder, uint32_t handle, uint32_t code, const FFBinderParcel* parcel, FFBinderReply* reply);
// ---------------------------------------------------------------------------------------------
// Service manager
// ---------------------------------------------------------------------------------------------
#define FF_BINDER_SERVICE_MANAGER_HANDLE 0u
#define FF_BINDER_SM_DESCRIPTOR "android.os.IServiceManager"
// Entry points of android.os.IServiceManager, as this device answers them. The numbers do not match
// the AOSP sources: checkService is 4 here, not 3. FF_BINDER_SM_GET_SERVICE returns a nullable
// IBinder and is the simplest reply to parse; FF_BINDER_SM_CHECK_SERVICE is what `service` itself
// calls and answers with a parcelable instead.
#define FF_BINDER_SM_GET_SERVICE 1u
#define FF_BINDER_SM_GET_SERVICE2 2u
#define FF_BINDER_SM_CHECK_SERVICE 4u
#define FF_BINDER_SM_LIST_SERVICES 6u
// Resolves a service name to a handle through the service manager. Returns nullptr on success.
[[gnu::nonnull(1, 2, 4), nodiscard]] const char* ffBinderLookupService(FFBinder* binder, const char* name, uint32_t transactionCode, uint32_t* handle);
+358
View File
@@ -0,0 +1,358 @@
#include "common/android/dex.h"
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
#ifdef FF_HAVE_ZLIB
#include "common/library.h"
#include <zlib.h>
#endif
// Offsets into the dex header, from https://source.android.com/docs/core/runtime/dex-format.
#define FF_DEX_ENDIAN_TAG 0x12345678u
#define FF_DEX_HEADER_SIZE 0x70
#define FF_DEX_OFF_FILE_SIZE 0x20
#define FF_DEX_OFF_ENDIAN_TAG 0x28
#define FF_DEX_OFF_STRING_IDS 0x3C
#define FF_DEX_OFF_TYPE_IDS_SIZE 0x40
#define FF_DEX_OFF_TYPE_IDS 0x44
#define FF_DEX_OFF_FIELD_IDS 0x54
#define FF_DEX_OFF_CLASS_DEFS_SIZE 0x60
#define FF_DEX_OFF_CLASS_DEFS 0x64
// class_def_item: [u32 class_idx][u32 access_flags][u32 superclass_idx][u32 interfaces_off]
// [u32 source_file_idx][u32 annotations_off][u32 class_data_off][u32 static_values_off]
#define FF_DEX_CLASS_DEF_SIZE 32
#define FF_DEX_OFF_CLASS_DEF_DATA 24
#define FF_DEX_OFF_CLASS_DEF_STATIC_VALUES 28
// field_id_item: [u16 class_idx][u16 type_idx][u32 name_idx]
#define FF_DEX_FIELD_ID_SIZE 8
#define FF_DEX_OFF_FIELD_ID_NAME 4
// The zip local file header, from APPNOTE.TXT 4.3.7. The central directory would carry the same
// fields, but the local header sits right in front of the data, so one walk over the file finds
// both the bounds and the payload.
#define FF_ZIP_LOCAL_HEADER_SIZE 30
#define FF_ZIP_OFF_METHOD 8
#define FF_ZIP_OFF_COMPRESSED_SIZE 18
#define FF_ZIP_OFF_UNCOMPRESSED_SIZE 22
#define FF_ZIP_OFF_NAME_LENGTH 26
#define FF_ZIP_OFF_EXTRA_LENGTH 28
#define FF_ZIP_METHOD_STORED 0
#define FF_ZIP_METHOD_DEFLATED 8
#define FF_DEX_ENTRY "classes.dex"
#define FF_DEX_MAGIC "dex\n"
static uint16_t dexU16(const uint8_t* p) {
return (uint16_t) ((uint16_t) p[0] | (uint16_t) ((uint16_t) p[1] << 8));
}
static uint32_t dexU32(const uint8_t* p) {
return (uint32_t) p[0] | ((uint32_t) p[1] << 8) | ((uint32_t) p[2] << 16) | ((uint32_t) p[3] << 24);
}
// LEB128, at most five bytes for the 32-bit values a dex stores this way.
static uint32_t dexUleb128(const uint8_t** p) {
uint32_t value = 0;
for (int shift = 0; shift <= 28; shift += 7) {
const uint8_t byte = *(*p)++;
value |= (uint32_t) (byte & 0x7f) << shift;
if ((byte & 0x80) == 0) {
break;
}
}
return value;
}
// encoded_value: one header byte holding ((size - 1) << 5) | type, then that many payload bytes. A
// `static final int` constant is written as VALUE_INT, whose payload is a sign-extended
// little-endian integer. Reading through 64 bits keeps every shift in range even if the size field
// is nonsense; the caller's length check is what rejects such a dex.
static int32_t dexEncodedInt(const uint8_t** p) {
const uint8_t header = *(*p)++;
const uint32_t size = (uint32_t) (header >> 5) + 1;
uint64_t value = 0;
for (uint32_t i = 0; i < size && i < 8; ++i) {
value |= (uint64_t) (*(*p)++) << (i * 8);
}
const uint32_t bits = size * 8;
if (bits < 64 && (value & (1ull << (bits - 1))) != 0) {
value |= ~((1ull << bits) - 1);
}
return (int32_t) (uint32_t) value;
}
// string_data_item: a uleb128 length in UTF-16 code units, then MUTF-8 bytes and a NUL terminator.
// The descriptors and field names looked up here are ASCII, where MUTF-8 and UTF-8 agree, so the
// bytes can be used as they are.
static const char* dexString(const uint8_t* dex, const uint8_t* end, uint32_t index) {
const uint8_t* ids = dex + dexU32(dex + FF_DEX_OFF_STRING_IDS);
if (ids < dex || (size_t) (end - ids) < (size_t) index * 4 + 4) {
return nullptr;
}
const uint8_t* p = dex + dexU32(ids + (size_t) index * 4);
if (p < dex || p >= end) {
return nullptr;
}
(void) dexUleb128(&p);
if (p >= end) {
return nullptr;
}
return memchr(p, '\0', (size_t) (end - p)) != nullptr ? (const char*) p : nullptr;
}
// Walks the class's static field list and the class's static value array in step, and returns the
// value paired with `fieldName`. Both lists are ordered by field index and cover exactly the same
// fields -- when they do not, the pairing is not trustworthy and nothing is returned.
static const char* dexStaticInt(const uint8_t* dex, size_t size, const char* classDescriptor, const char* fieldName, int32_t* result) {
const uint8_t* end = dex + size;
if (size < FF_DEX_HEADER_SIZE || dexU32(dex + FF_DEX_OFF_ENDIAN_TAG) != FF_DEX_ENDIAN_TAG) {
return "Not a dex file";
}
const uint32_t fileSize = dexU32(dex + FF_DEX_OFF_FILE_SIZE);
if (fileSize > size || fileSize < FF_DEX_HEADER_SIZE) {
return "The dex file size is out of range";
}
end = dex + fileSize;
// The class's type index, so that the class_def_item and the field ids can be filtered by class.
const uint8_t* types = dex + dexU32(dex + FF_DEX_OFF_TYPE_IDS);
const uint32_t typeCount = dexU32(dex + FF_DEX_OFF_TYPE_IDS_SIZE);
if (types < dex || (size_t) (end - types) < (size_t) typeCount * 4) {
return "The dex type table is out of range";
}
uint32_t typeIndex = UINT32_MAX;
for (uint32_t i = 0; i < typeCount; ++i) {
const char* descriptor = dexString(dex, end, dexU32(types + (size_t) i * 4));
if (descriptor != nullptr && strcmp(descriptor, classDescriptor) == 0) {
typeIndex = i;
break;
}
}
if (typeIndex == UINT32_MAX) {
return "The class is not in the dex";
}
const uint8_t* classes = dex + dexU32(dex + FF_DEX_OFF_CLASS_DEFS);
const uint32_t classCount = dexU32(dex + FF_DEX_OFF_CLASS_DEFS_SIZE);
if (classes < dex || (size_t) (end - classes) < (size_t) classCount * FF_DEX_CLASS_DEF_SIZE) {
return "The dex class table is out of range";
}
for (uint32_t i = 0; i < classCount; ++i) {
const uint8_t* classDef = classes + (size_t) i * FF_DEX_CLASS_DEF_SIZE;
if (dexU32(classDef) != typeIndex) {
continue;
}
const uint8_t* fields = dex + dexU32(classDef + FF_DEX_OFF_CLASS_DEF_DATA);
const uint8_t* values = dex + dexU32(classDef + FF_DEX_OFF_CLASS_DEF_STATIC_VALUES);
if (fields < dex || fields >= end || values < dex || values >= end) {
return "The dex class data is out of range";
}
const uint32_t staticFields = dexUleb128(&fields);
(void) dexUleb128(&fields); // instance_fields_size
(void) dexUleb128(&fields); // direct_methods_size
(void) dexUleb128(&fields); // virtual_methods_size
const uint32_t staticValues = dexUleb128(&values);
if (staticFields != staticValues) {
return "The dex static fields and values do not pair up";
}
const uint8_t* fieldIds = dex + dexU32(dex + FF_DEX_OFF_FIELD_IDS);
uint32_t fieldIndex = 0;
for (uint32_t j = 0; j < staticFields; ++j) {
if (fields >= end) {
return "The dex static field list is truncated";
}
fieldIndex += dexUleb128(&fields); // field_idx_diff
(void) dexUleb128(&fields); // access_flags
const int32_t value = dexEncodedInt(&values);
if ((size_t) (end - fieldIds) < ((size_t) fieldIndex + 1) * FF_DEX_FIELD_ID_SIZE) {
return "The dex field table is out of range";
}
const char* name = dexString(dex, end, dexU32(fieldIds + (size_t) fieldIndex * FF_DEX_FIELD_ID_SIZE + FF_DEX_OFF_FIELD_ID_NAME));
if (name != nullptr && strcmp(name, fieldName) == 0) {
*result = value;
return nullptr;
}
}
return "The field is not a static field of the class";
}
return "The class has no class_def_item";
}
// ---------------------------------------------------------------------------------------------
// Locating classes.dex
// ---------------------------------------------------------------------------------------------
typedef struct FFDexMapping {
uint8_t* mapped; // the jar, as mapped; nullptr once released
size_t mappedSize;
const uint8_t* data; // the dex bytes: inside `mapped`, or `inflated`
size_t size;
uint8_t* inflated; // owned; only set when the entry had to be decompressed
} FFDexMapping;
static void wrapDexMapping(FFDexMapping* mapping) {
assert(mapping);
free(mapping->inflated);
if (mapping->mapped != nullptr) {
munmap(mapping->mapped, mapping->mappedSize);
}
}
// The local file header of `classes.dex` carries both the payload bounds and its compression, so a
// single walk over the jar is enough to find it either way. AOSP builds framework jars with the
// entry STORED so that ART can map it, which is the common case and needs no decompression.
static const char* findDexEntry(const uint8_t* jar, size_t jarSize, const uint8_t** data, size_t* dataSize, uint32_t* uncompressedSize, uint16_t* method) {
for (size_t i = 0; i + FF_ZIP_LOCAL_HEADER_SIZE <= jarSize; ++i) {
if (memcmp(jar + i, "PK\x03\x04", 4) != 0) {
continue;
}
const uint16_t nameLength = dexU16(jar + i + FF_ZIP_OFF_NAME_LENGTH);
const uint16_t extraLength = dexU16(jar + i + FF_ZIP_OFF_EXTRA_LENGTH);
if (nameLength != sizeof(FF_DEX_ENTRY) - 1) {
continue;
}
const size_t headerSize = FF_ZIP_LOCAL_HEADER_SIZE + (size_t) nameLength + (size_t) extraLength;
if (headerSize > jarSize - i) {
continue;
}
if (memcmp(jar + i + FF_ZIP_LOCAL_HEADER_SIZE, FF_DEX_ENTRY, sizeof(FF_DEX_ENTRY) - 1) != 0) {
continue;
}
const uint32_t compressedSize = dexU32(jar + i + FF_ZIP_OFF_COMPRESSED_SIZE);
if (compressedSize == 0 || compressedSize > jarSize - i - headerSize) {
// A zero size means a data descriptor follows the payload instead of the header; the
// magic scan in the caller still covers that case as long as the entry is STORED.
continue;
}
*method = dexU16(jar + i + FF_ZIP_OFF_METHOD);
*uncompressedSize = dexU32(jar + i + FF_ZIP_OFF_UNCOMPRESSED_SIZE);
*data = jar + i + headerSize;
*dataSize = compressedSize;
return nullptr;
}
return "The jar has no usable classes.dex entry";
}
// Fallback for a jar whose entry is STORED but whose header has no sizes: the dex magic is then a
// literal run of bytes in the file, and the header that follows it validates or it does not.
static const uint8_t* findDexMagic(const uint8_t* jar, size_t jarSize, size_t* dexSize) {
for (size_t i = 0; i + FF_DEX_HEADER_SIZE <= jarSize; ++i) {
if (memcmp(jar + i, FF_DEX_MAGIC, sizeof(FF_DEX_MAGIC) - 1) != 0) {
continue;
}
const uint8_t* dex = jar + i;
const uint32_t fileSize = dexU32(dex + FF_DEX_OFF_FILE_SIZE);
if (dexU32(dex + FF_DEX_OFF_ENDIAN_TAG) != FF_DEX_ENDIAN_TAG) {
continue;
}
if (fileSize < FF_DEX_HEADER_SIZE || fileSize > jarSize - i) {
continue;
}
*dexSize = fileSize;
return dex;
}
return nullptr;
}
#ifdef FF_HAVE_ZLIB
static const char* inflateDex(const uint8_t* data, size_t dataSize, uint32_t uncompressedSize, uint8_t** out) {
FF_LIBRARY_LOAD(zlib, "dlopen(libz) failed", "libz" FF_LIBRARY_EXTENSION, 2)
FF_LIBRARY_LOAD_SYMBOL(zlib, inflateInit2_, "dlsym(inflateInit2_) failed")
FF_LIBRARY_LOAD_SYMBOL(zlib, inflate, "dlsym(inflate) failed")
FF_LIBRARY_LOAD_SYMBOL(zlib, inflateEnd, "dlsym(inflateEnd) failed")
uint8_t* buffer = malloc(uncompressedSize);
if (buffer == nullptr) {
return "malloc failed";
}
// `uncompress` is not usable here: a zip entry holds a raw deflate stream, without the two byte
// zlib header that entry point insists on. A negative window size tells inflate to skip the
// header, which is what the zip format expects.
z_stream stream = {};
stream.next_in = (Bytef*) data;
stream.avail_in = (uInt) dataSize;
stream.next_out = buffer;
stream.avail_out = (uInt) uncompressedSize;
if (ffinflateInit2_(&stream, -MAX_WBITS, ZLIB_VERSION, (int) sizeof(z_stream)) != Z_OK) {
free(buffer);
return "inflateInit2 failed";
}
const int status = ffinflate(&stream, Z_FINISH);
ffinflateEnd(&stream);
if (status != Z_STREAM_END || stream.total_out != (uLong) uncompressedSize) {
free(buffer);
return "Inflating classes.dex failed";
}
*out = buffer;
return nullptr;
}
#endif
const char* ffDexStaticInt(const char* jarPath, const char* classDescriptor, const char* fieldName, int32_t* result) {
[[gnu::cleanup(wrapDexMapping)]] FFDexMapping mapping = {};
const int fd = open(jarPath, O_RDONLY | O_CLOEXEC);
if (fd < 0) {
return "open(jar) failed";
}
struct stat st = {};
if (fstat(fd, &st) != 0 || st.st_size <= 0) {
close(fd);
return "fstat(jar) failed";
}
mapping.mappedSize = (size_t) st.st_size;
mapping.mapped = mmap(nullptr, mapping.mappedSize, PROT_READ, MAP_PRIVATE, fd, 0);
// The mapping outlives the descriptor, so the descriptor can go either way from here.
close(fd);
if (mapping.mapped == MAP_FAILED) {
mapping.mapped = nullptr;
return "mmap(jar) failed";
}
const uint8_t* data = nullptr;
size_t dataSize = 0;
uint32_t uncompressedSize = 0;
uint16_t method = FF_ZIP_METHOD_STORED;
if (findDexEntry(mapping.mapped, mapping.mappedSize, &data, &dataSize, &uncompressedSize, &method) != nullptr) {
data = findDexMagic(mapping.mapped, mapping.mappedSize, &dataSize);
if (data == nullptr) {
return "No dex in the jar";
}
} else if (method == FF_ZIP_METHOD_STORED) {
dataSize = uncompressedSize;
} else if (method == FF_ZIP_METHOD_DEFLATED) {
#ifdef FF_HAVE_ZLIB
const char* error = inflateDex(data, dataSize, uncompressedSize, &mapping.inflated);
if (error != nullptr) {
return error;
}
data = mapping.inflated;
dataSize = uncompressedSize;
#else
return "The jar deflates classes.dex and fastfetch was built without zlib";
#endif
} else {
return "classes.dex uses an unsupported compression method";
}
mapping.data = data;
mapping.size = dataSize;
return dexStaticInt(mapping.data, mapping.size, classDescriptor, fieldName, result);
}
+30
View File
@@ -0,0 +1,30 @@
#pragma once
// AIDL gives every method of an interface a transaction code at build time:
//
// static final int TRANSACTION_<method> = IBinder.FIRST_CALL_TRANSACTION + <declaration index>;
//
// so the number is a property of the `.aidl` of the release that built the device's jar, not of any
// public header. Counting the methods in an AOSP checkout only describes that checkout, and it goes
// wrong the moment a release or a vendor fork inserts a method ahead of the one being looked for:
// `IWifiManager.getConnectionInfo` is 29 on Android 11 and 41 on Android 16. There is no negotiation
// and no discovery -- a wrong code reaches a different method, or none.
//
// Being a compile-time constant, the value lands in the `static_values` array of the `X$Stub` class
// in the jar's dex, paired position by position with that class's static field list. Reading the two
// together gives the mapping of the build that is actually on the device, on any release, with
// nothing to keep in sync.
//
// `libdexfile.so` cannot do this for us. It is dlopen-able from an app UID through the ART apex, but
// it is not in the NDK and its only C ABI -- the `ADexFile_*` family -- covers methods, not fields;
// the field and class-data APIs are C++ with no ABI guarantee.
//
// `ffReadFileBuffer` would work but pulls the whole jar through the heap for one integer. The jar is
// mapped instead, and only the pages actually read are faulted in.
#include "fastfetch.h"
// Resolves the int value of `<classDescriptor>.<fieldName>` out of the `classes.dex` of `jarPath`.
// `classDescriptor` is the dex type descriptor, e.g. "Landroid/net/wifi/IWifiManager$Stub;".
// Returns nullptr on success, a static message otherwise.
[[gnu::nonnull(1, 2, 3, 4), nodiscard]] const char* ffDexStaticInt(const char* jarPath, const char* classDescriptor, const char* fieldName, int32_t* result);
+5 -4
View File
@@ -2,8 +2,9 @@
#include "fastfetch.h"
void ffBase64EncodeRaw(uint32_t size, const char* str, uint32_t* out_size, char* output);
static inline FFstrbuf ffBase64EncodeStrbuf(const FFstrbuf* in) {
// `str`, `out_size` and `output` are dereferenced unconditionally
[[gnu::nonnull(2, 3, 4)]] void ffBase64EncodeRaw(uint32_t size, const char* str, uint32_t* out_size, char* output);
[[gnu::nonnull(1), nodiscard]] static inline FFstrbuf ffBase64EncodeStrbuf(const FFstrbuf* in) {
FFstrbuf out = ffStrbufCreateA(10 + in->length * 4 / 3);
ffBase64EncodeRaw(in->length, in->chars, &out.length, out.chars);
assert(out.length < out.allocated);
@@ -11,8 +12,8 @@ static inline FFstrbuf ffBase64EncodeStrbuf(const FFstrbuf* in) {
return out;
}
bool ffBase64DecodeRaw(uint32_t size, const char* str, uint32_t* out_size, char* output);
static inline FFstrbuf ffBase64DecodeStrbuf(const FFstrbuf* in) {
[[gnu::nonnull(2, 3, 4)]] void ffBase64DecodeRaw(uint32_t size, const char* str, uint32_t* out_size, char* output);
[[gnu::nonnull(1), nodiscard]] static inline FFstrbuf ffBase64DecodeStrbuf(const FFstrbuf* in) {
FFstrbuf out = ffStrbufCreateA(10 + in->length * 3 / 4);
ffBase64DecodeRaw(in->length, in->chars, &out.length, out.chars);
assert(out.length < out.allocated);
+1 -1
View File
@@ -3,7 +3,7 @@
#include "fastfetch.h"
#include "common/time.h"
static inline const char* ffFindFileName(const char* file) {
[[gnu::nonnull(1), gnu::pure, nodiscard]] static inline const char* ffFindFileName(const char* file) {
const char* lastSlash = __builtin_strrchr(file, '/');
#ifdef _WIN32
if (lastSlash == nullptr) {
+1 -1
View File
@@ -2,4 +2,4 @@
#include "fastfetch.h"
void ffDurationAppendNum(uint64_t totalSeconds, FFstrbuf* result);
[[gnu::nonnull(2)]] void ffDurationAppendNum(uint64_t totalSeconds, FFstrbuf* result);
+6 -1
View File
@@ -2,7 +2,12 @@
#include <stdint.h>
#if __BIG_ENDIAN__
// `__BIG_ENDIAN__` alone is not enough: GCC does not define it, it documents only `__BYTE_ORDER__`
// and the `__ORDER_*_ENDIAN__` values. Testing the former silently selected the little-endian
// branch on s390x, where `FF_READ_BE` then byte-swapped values that were already big-endian.
// `defined(__BIG_ENDIAN__)` alone would not do either: a macro that is defined as 0 is not a
// big-endian platform.
#if (defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) || (defined(__BIG_ENDIAN__) && __BIG_ENDIAN__)
#define FF_READ_LE(x) _Generic((x), \
uint16_t: __builtin_bswap16(x), \
uint32_t: __builtin_bswap32(x), \
+3 -1
View File
@@ -2,4 +2,6 @@
#include "fastfetch.h"
bool ffFreqAppendNum(uint32_t mhz, FFstrbuf* result);
// Returns false when nothing was appended (e.g. `mhz == 0`); callers routinely discard that, so it
// is not `nodiscard`.
[[gnu::nonnull(2)]] bool ffFreqAppendNum(uint32_t mhz, FFstrbuf* result);
+1 -1
View File
@@ -27,7 +27,7 @@ void ffPlatformInit(FFPlatform* platform) {
ffStrbufInit(&info->release);
ffStrbufInit(&info->version);
ffStrbufInit(&info->architecture);
info->pageSize = 0;
info->pageSizeShift = 12; // 4096, reasonable fallback
ffPlatformInitImpl(platform);
+68 -31
View File
@@ -4,6 +4,7 @@
#include "common/strutil.h"
#include "common/io.h"
#include "common/path.h"
#include "common/mallocHelper.h"
#include <unistd.h>
#include <pwd.h>
@@ -19,7 +20,6 @@
#elif defined(__OpenBSD__)
#include <sys/sysctl.h>
#include <sys/stat.h>
#include <kvm.h>
#include "common/path.h"
#elif defined(__HAIKU__)
#include <image.h>
@@ -68,13 +68,14 @@ 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(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);
if (kp && kpCount == 1) {
char** argv = kvm_getargv(kd, kp, 0);
if (argv && argv[0]) {
{
char argvBuf[ARG_MAX];
size_t argvSize = sizeof(argvBuf);
int argvMib[] = { CTL_KERN, KERN_PROC_ARGS, (pid_t) platform->pid, KERN_PROC_ARGV };
if (sysctl(argvMib, ARRAY_SIZE(argvMib), argvBuf, &argvSize, nullptr, 0) == 0) {
// The buffer is filled with an array of char pointers followed by the strings themselves
char** argv = (char**) argvBuf;
if (argv[0] && (char*) argv[0] >= argvBuf && (char*) argv[0] < argvBuf + argvSize) {
char* arg0 = argv[0];
if (arg0[0]) {
if (strchr(arg0, '/') != nullptr) // likely a path (absolute or relative)
@@ -97,25 +98,64 @@ static void getExePath(FFPlatform* platform) {
if (exePathLen > 0) {
struct stat st;
if (stat(exePath, &st) == 0 && S_ISREG(st.st_mode)) {
int cntp;
struct kinfo_file* kf = kvm_getfiles(kd, KERN_FILE_BYPID, (pid_t) platform->pid, sizeof(*kf), &cntp);
if (kf) {
int i;
for (i = 0; i < cntp; i++) {
if (kf[i].fd_fd == KERN_FILE_TEXT) {
// KERN_FILE_TEXT is the executable file, not a shared library, and should be unique in the list.
if (st.st_dev != (dev_t) kf[i].va_fsid || st.st_ino != (ino_t) kf[i].va_fileid) {
i = -1;
// Replicate kvm_getfiles()'s live path: {CTL_KERN, KERN_FILE, KERN_FILE_BYPID, pid, esize, count}
int fileMib[6] = { CTL_KERN, KERN_FILE, KERN_FILE_BYPID, (pid_t) platform->pid, (int) sizeof(struct kinfo_file), 0 };
size_t fileSize = 0;
if (sysctl(fileMib, ARRAY_SIZE(fileMib), nullptr, &fileSize, nullptr, 0) == 0) {
fileSize += fileSize / 8; // add 12.5% for the table growing between the two calls
size_t fileCapacity = fileSize;
FF_AUTO_FREE struct kinfo_file* kf = (struct kinfo_file*) malloc(fileCapacity);
if (kf) {
int rv;
// The table only grows, so the loop terminates as long as it grows by less
// than 12.5% per retry. Cap it anyway: spinning on a pathological growth
// rate would hang fastfetch, and giving up only costs the executable check
// below, which already assumes the path is correct when the list is missing.
int retries = 5;
while (true) {
fileMib[5] = (int) (fileCapacity / sizeof(struct kinfo_file));
fileSize = fileCapacity; // sysctl takes the size of the buffer as input
rv = sysctl(fileMib, ARRAY_SIZE(fileMib), kf, &fileSize, nullptr, 0);
if (rv == 0 || errno != ENOMEM || retries-- == 0) {
break;
}
break;
// The file table grew between the two calls. The buffer has to grow
// before the retry: the next call advertises fileCapacity as the size
// of kf, and the kernel would copy that many bytes into the old
// allocation.
// OpenBSD writes back the size it needs, FreeBSD only the number of
// bytes it managed to copy, so take the larger one and add ~10% on
// top -- the growth libprocstat uses for this very sysctl.
size_t newCapacity = fileSize > fileCapacity ? fileSize : fileCapacity;
newCapacity += newCapacity / 8;
struct kinfo_file* newKf = (struct kinfo_file*) realloc(kf, newCapacity);
if (newKf == nullptr) {
rv = -1;
break;
}
kf = newKf;
fileCapacity = newCapacity;
}
if (rv == 0) {
int cntp = (int) (fileSize / sizeof(struct kinfo_file));
int i;
for (i = 0; i < cntp; i++) {
if (kf[i].fd_fd == KERN_FILE_TEXT) {
// KERN_FILE_TEXT is the executable file, not a shared library, and should be unique in the list.
if (st.st_dev != (dev_t) kf[i].va_fsid || st.st_ino != (ino_t) kf[i].va_fileid) {
i = -1;
}
break;
}
}
if (i < 0) {
exePathLen = 0;
}
}
// If we can't get the list of open files, we can't verify that the file is actually the executable
// Assume it is
}
if (i < 0) {
exePathLen = 0;
}
} else {
// If we can't get the list of open files, we can't verify that the file is actually the executable
// Assume it is
}
} else {
exePathLen = 0;
@@ -124,7 +164,6 @@ static void getExePath(FFPlatform* platform) {
}
}
}
kvm_close(kd);
}
#elif defined(__sun)
ssize_t exePathLen = readlink("/proc/self/path/a.out", exePath, sizeof(exePath) - 1);
@@ -280,12 +319,10 @@ static void getSysinfo(FFPlatformSysinfo* info, const struct utsname* uts) {
#endif
ffStrbufAppendS(&info->architecture, uts->machine);
#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, nullptr, 0);
#else
info->pageSize = (uint32_t) sysconf(_SC_PAGESIZE);
#endif
// _SC_PAGESIZE is one of the sysconf names <unistd.h> requires every implementation to define,
// and the only failure POSIX defines for sysconf is an invalid name, so this does not fail.
// It replaces the former sysctl(CTL_HW, HW_PAGESIZE) call on FreeBSD / macOS / OpenBSD / NetBSD.
info->pageSizeShift = (uint32_t) __builtin_ctzl((unsigned long) sysconf(_SC_PAGESIZE));
}
static void getCwd(FFPlatform* platform) {
+1 -3
View File
@@ -229,9 +229,7 @@ static void getSystemReleaseAndVersion(FFPlatformSysinfo* info) {
static void getSystemPageSize(FFPlatformSysinfo* info) {
SYSTEM_BASIC_INFORMATION sbi;
if (NT_SUCCESS(NtQuerySystemInformation(SystemBasicInformation, &sbi, sizeof(sbi), nullptr))) {
info->pageSize = sbi.PhysicalPageSize;
} else {
info->pageSize = 4096;
info->pageSizeShift = (uint32_t) __builtin_ctzl(sbi.PhysicalPageSize);
}
}
+25 -35
View File
@@ -21,8 +21,6 @@ void ffStrbufInitA(FFstrbuf* strbuf, uint32_t allocate) {
}
void ffStrbufInitVF(FFstrbuf* strbuf, const char* format, va_list arguments) {
assert(format != nullptr);
char* buffer = nullptr;
int len = vasprintf(&buffer, format, arguments);
assert(len >= 0);
@@ -33,8 +31,6 @@ 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 != nullptr);
strbuf->length = length;
size_t allocSize = ffMallocUsableSize(heapStr);
if (allocSize == 0) {
@@ -157,8 +153,6 @@ void ffStrbufAppendTransformS(FFstrbuf* strbuf, const char* value, int (*transfo
}
void ffStrbufAppendVF(FFstrbuf* strbuf, const char* format, va_list arguments) {
assert(format != nullptr);
va_list copy;
va_copy(copy, arguments);
@@ -192,8 +186,6 @@ const char* ffStrbufAppendSUntilC(FFstrbuf* strbuf, const char* value, char unti
}
void ffStrbufSetF(FFstrbuf* strbuf, const char* format, ...) {
assert(format != nullptr);
va_list arguments;
va_start(arguments, format);
@@ -209,8 +201,6 @@ void ffStrbufSetF(FFstrbuf* strbuf, const char* format, ...) {
}
void ffStrbufAppendF(FFstrbuf* strbuf, const char* format, ...) {
assert(format != nullptr);
va_list arguments;
va_start(arguments, format);
ffStrbufAppendVF(strbuf, format, arguments);
@@ -236,15 +226,11 @@ void ffStrbufPrependC(FFstrbuf* strbuf, char c) {
}
void ffStrbufSetNS(FFstrbuf* strbuf, uint32_t length, const char* value) {
assert(strbuf != nullptr);
if (length == 0) {
ffStrbufClear(strbuf);
return;
}
assert(value != nullptr);
if (strbuf->allocated <= length) {
char* newBuf = malloc(sizeof(char) * (length + 1));
memcpy(newBuf, value, length);
@@ -262,7 +248,8 @@ void ffStrbufSetNS(FFstrbuf* strbuf, uint32_t length, const char* value) {
}
void ffStrbufSet(FFstrbuf* strbuf, const FFstrbuf* value) {
assert(value && value != strbuf);
// `value` is non-null per the `nonnull(2)` contract; the aliasing check cannot be expressed by an attribute
assert(value != strbuf);
if (value->length == 0) {
ffStrbufClear(strbuf);
@@ -647,7 +634,6 @@ void ffStrbufInsertNC(FFstrbuf* strbuf, uint32_t index, uint32_t num, char c) {
}
bool ffStrbufGetdelim(char** lineptr, size_t* n, char delimiter, FFstrbuf* buffer) {
assert(lineptr && n && buffer);
assert(buffer->allocated > 0 || (buffer->allocated == 0 && buffer->length == 0));
assert(!*lineptr || (*lineptr >= buffer->chars && *lineptr <= buffer->chars + buffer->length));
@@ -678,7 +664,6 @@ bool ffStrbufGetdelim(char** lineptr, size_t* n, char delimiter, FFstrbuf* buffe
}
void ffStrbufGetdelimRestore(char** lineptr, size_t* n, char delimiter, FFstrbuf* buffer) {
assert(buffer && lineptr && n);
assert(buffer->allocated > 0 || (buffer->allocated == 0 && buffer->length == 0));
assert(!*lineptr || (*lineptr >= buffer->chars && *lineptr <= buffer->chars + buffer->length));
@@ -723,16 +708,17 @@ bool ffStrbufRemoveDupWhitespaces(FFstrbuf* strbuf) {
/// @param compLength The length of the separated string to check.
/// @param comp The separated string to check.
/// @param separator The separator character.
///
/// Empty-string handling:
/// - If `strbuf` is empty, it matches only if `comp` contains an empty segment
/// (e.g. "abc::def", "abc:", ":abc") or `comp` itself is empty.
/// - If `comp` is empty (compLength == 0), it matches only if `strbuf` is also empty.
bool ffStrbufMatchSeparatedNS(const FFstrbuf* strbuf, uint32_t compLength, const char* comp, char separator) {
if (strbuf->length == 0) {
return true;
if (__builtin_expect(compLength == 0, false)) {
return strbuf->length == 0;
}
if (compLength == 0) {
return false;
}
for (const char* p = comp; p < comp + compLength;) {
for (const char* p = comp; p <= comp + compLength;) {
const char* colon = memchr(p, separator, (size_t) (comp + compLength - p));
if (colon == nullptr) {
uint32_t remainingLen = (uint32_t) (comp + compLength - p);
@@ -752,15 +738,11 @@ bool ffStrbufMatchSeparatedNS(const FFstrbuf* strbuf, uint32_t compLength, const
/// @brief Case insensitive version of ffStrbufMatchSeparatedNS.
bool ffStrbufMatchSeparatedIgnCaseNS(const FFstrbuf* strbuf, uint32_t compLength, const char* comp, char separator) {
if (strbuf->length == 0) {
return true;
if (__builtin_expect(compLength == 0, false)) {
return strbuf->length == 0;
}
if (compLength == 0) {
return false;
}
for (const char* p = comp; p < comp + compLength;) {
for (const char* p = comp; p <= comp + compLength;) {
const char* colon = memchr(p, separator, (size_t) (comp + compLength - p));
if (colon == nullptr) {
uint32_t remainingLen = (uint32_t) (comp + compLength - p);
@@ -802,9 +784,15 @@ int ffStrbufAppendUtf32CodePoint(FFstrbuf* strbuf, uint32_t codepoint) {
/// @param compLength The length of the separated string to check.
/// @param comp The substring to check.
/// @param separator The separator character.
///
/// Empty-string handling is symmetric to ffStrbufMatchSeparatedNS
bool ffStrbufSeparatedContainNS(const FFstrbuf* strbuf, uint32_t compLength, const char* comp, char separator) {
if (__builtin_expect(strbuf->length == 0, false)) {
return compLength == 0; // An empty list contains only the empty segment
}
uint32_t startIndex = 0;
while (startIndex < strbuf->length) {
while (startIndex <= strbuf->length) { // `<=` so a trailing empty segment (e.g. "abc:") is checked
uint32_t colonIndex = ffStrbufNextIndexC(strbuf, startIndex, separator);
uint32_t folderLength = colonIndex - startIndex;
@@ -819,8 +807,12 @@ bool ffStrbufSeparatedContainNS(const FFstrbuf* strbuf, uint32_t compLength, con
}
bool ffStrbufSeparatedContainIgnCaseNS(const FFstrbuf* strbuf, uint32_t compLength, const char* comp, char separator) {
if (__builtin_expect(strbuf->length == 0, false)) {
return compLength == 0; // An empty list contains only the empty segment
}
uint32_t startIndex = 0;
while (startIndex < strbuf->length) {
while (startIndex <= strbuf->length) { // `<=` so a trailing empty segment (e.g. "abc:") is checked
uint32_t colonIndex = ffStrbufNextIndexC(strbuf, startIndex, separator);
uint32_t folderLength = colonIndex - startIndex;
@@ -835,8 +827,6 @@ bool ffStrbufSeparatedContainIgnCaseNS(const FFstrbuf* strbuf, uint32_t compLeng
}
bool ffStrbufDecodeHexEscapeSequences(FFstrbuf* strbuf) {
assert(strbuf);
if (strbuf->length < 4) {
return false;
}
+8 -5
View File
@@ -17,15 +17,19 @@ void ffBase64EncodeRaw(uint32_t size, const char* str, uint32_t* out_size, char*
str += 3;
}
// The bytes have to be widened through `uint8_t`: `char` is signed here, so widening a byte
// with the high bit set would sign extend it and the `& 63` below would then read the extension
// instead of the byte's own bits. The whole groups above are immune because they read through a
// `uint32_t` instead.
if (size % 3 == 1) {
uint64_t n = (uint64_t) *str << 16;
uint64_t n = (uint64_t) (uint8_t) *str << 16;
*out++ = chars[(n >> 18) & 63];
*out++ = chars[(n >> 12) & 63];
*out++ = '=';
*out++ = '=';
} else if (size % 3 == 2) {
uint64_t n = (uint64_t) *str++ << 16;
n |= (uint64_t) *str << 8;
uint64_t n = (uint64_t) (uint8_t) *str++ << 16;
n |= (uint64_t) (uint8_t) *str << 8;
*out++ = chars[(n >> 18) & 63];
*out++ = chars[(n >> 12) & 63];
*out++ = chars[(n >> 6) & 63];
@@ -62,7 +66,7 @@ static void init_decode_table() {
#define next_char(x) uint8_t x = decode_table[(uint8_t) *str++];
bool ffBase64DecodeRaw(uint32_t size, const char* str, uint32_t* out_size, char* output) {
void ffBase64DecodeRaw(uint32_t size, const char* str, uint32_t* out_size, char* output) {
if (*(uint64_t*) decode_table == 0) {
init_decode_table();
}
@@ -109,5 +113,4 @@ bool ffBase64DecodeRaw(uint32_t size, const char* str, uint32_t* out_size, char*
*out = '\0';
*out_size = (uint32_t) (out - output);
return true;
}
+62 -19
View File
@@ -63,6 +63,21 @@ bool ffParseModuleOptions(const char* key, const char* value) {
return false;
}
static yyjson_val* findStructureModuleConfig(FFdata* data, const char* moduleType);
// The module options live in the JSON config only. They must be merged here as well as in
// `parseStructureCommand`, because `ffPrepareXxx` takes the first snapshot while `ffDetectXxx`
// takes the second one. If the two disagree, they list different entries and the deltas are
// meaningless. Keeping both call sites on this single helper is what makes them agree.
static void initStructureModuleOptions(FFdata* data, FFModuleBaseInfo* baseInfo, void* options) {
baseInfo->initOptions(options);
yyjson_val* configModule = findStructureModuleConfig(data, baseInfo->name);
if (configModule != nullptr) {
baseInfo->parseJsonObject(options, configModule);
}
}
void ffPrepareCommandOption(FFdata* data) {
char* moduleType = nullptr;
size_t moduleLen = 0;
@@ -70,68 +85,68 @@ void ffPrepareCommandOption(FFdata* data) {
#define FF_IF_MODULE_MATCH(moduleNameConstant) if (ffStrEqualsIgnCase(moduleType, moduleNameConstant) && !ffStrbufSeparatedContainIgnCaseS(&data->structureDisabled, moduleNameConstant, ':'))
switch (moduleType[0]) {
#if !FF_MODULE_DISABLE_CPUUSAGE
#if !FF_MODULE_DISABLE_CPUUSAGE
case 'C':
case 'c':
FF_IF_MODULE_MATCH(ffCPUUsageModuleInfo.name)
ffPrepareCPUUsage();
ffPrepareCPUUsage(); // The rate is derived from the CPU's own counters; no options are involved
break;
#endif
#endif
#if !FF_MODULE_DISABLE_DISKIO
#if !FF_MODULE_DISABLE_DISKIO
case 'D':
case 'd':
FF_IF_MODULE_MATCH(ffDiskIOModuleInfo.name) {
[[gnu::cleanup(ffDestroyDiskIOOptions)]] FFDiskIOOptions options;
ffInitDiskIOOptions(&options);
initStructureModuleOptions(data, &ffDiskIOModuleInfo, &options);
ffPrepareDiskIO(&options);
}
break;
#endif
#endif
#if !FF_MODULE_DISABLE_NETIO
#if !FF_MODULE_DISABLE_NETIO
case 'N':
case 'n':
FF_IF_MODULE_MATCH(ffNetIOModuleInfo.name) {
[[gnu::cleanup(ffDestroyNetIOOptions)]] FFNetIOOptions options;
ffInitNetIOOptions(&options);
initStructureModuleOptions(data, &ffNetIOModuleInfo, &options);
ffPrepareNetIO(&options);
}
break;
#endif
#endif
#if !FF_MODULE_DISABLE_PUBLICIP
#if !FF_MODULE_DISABLE_PUBLICIP
case 'P':
case 'p':
FF_IF_MODULE_MATCH(ffPublicIPModuleInfo.name) {
[[gnu::cleanup(ffDestroyPublicIpOptions)]] FFPublicIPOptions options;
ffInitPublicIpOptions(&options);
initStructureModuleOptions(data, &ffPublicIPModuleInfo, &options);
ffPreparePublicIp(&options);
}
break;
#endif
#endif
#if !FF_MODULE_DISABLE_TOP
#if !FF_MODULE_DISABLE_TOP
case 'T':
case 't':
FF_IF_MODULE_MATCH(ffTopModuleInfo.name) {
[[gnu::cleanup(ffDestroyTopOptions)]] FFTopOptions options;
ffInitTopOptions(&options);
initStructureModuleOptions(data, &ffTopModuleInfo, &options);
ffPrepareTopProcesses(options.showTypes);
}
break;
#endif
#endif
#if !FF_MODULE_DISABLE_WEATHER
#if !FF_MODULE_DISABLE_WEATHER
case 'W':
case 'w':
FF_IF_MODULE_MATCH(ffWeatherModuleInfo.name) {
[[gnu::cleanup(ffDestroyWeatherOptions)]] FFWeatherOptions options;
ffInitWeatherOptions(&options);
initStructureModuleOptions(data, &ffWeatherModuleInfo, &options);
ffPrepareWeather(&options);
}
break;
#endif
#endif
}
#undef FF_IF_MODULE_MATCH
@@ -178,6 +193,34 @@ static void genJsonResult(FFdata* data, FFModuleBaseInfo* baseInfo, void* option
}
}
static yyjson_val* findStructureModuleConfig(FFdata* data, const char* moduleType) {
if (data->configDoc == nullptr) {
return nullptr;
}
yyjson_val* root = yyjson_doc_get_root(data->configDoc);
if (root == nullptr) {
return nullptr;
}
yyjson_val* modules = yyjson_obj_get(root, "modules");
if (!yyjson_is_arr(modules)) {
return nullptr;
}
yyjson_val* item;
size_t idx, max;
yyjson_arr_foreach (modules, idx, max, item) {
if (yyjson_is_obj(item)) {
const char* type = yyjson_get_str(yyjson_obj_get(item, "type"));
if (type != nullptr && ffStrEqualsIgnCase(type, moduleType)) {
return item;
}
}
}
return nullptr;
}
static bool parseStructureCommand(
FFdata* data,
const char* line,
@@ -187,7 +230,7 @@ static bool parseStructureCommand(
FFModuleBaseInfo* baseInfo = *modules;
if (ffStrEqualsIgnCase(line, baseInfo->name)) {
alignas(uint64_t) uint8_t optionBuf[FF_OPTION_MAX_SIZE];
baseInfo->initOptions(optionBuf);
initStructureModuleOptions(data, baseInfo, optionBuf);
if (data->resultDoc != nullptr) {
fn(data, baseInfo, optionBuf);
} else {
+3
View File
@@ -281,6 +281,9 @@ void ffListFeatures(void) {
#if FF_ENABLE_WCWIDTH
"Embedded wcwidth\n"
#endif
#if FF_HAVE_SIXEL
"Embedded sixel\n"
#endif
#if FF_HAVE_WINRT
"WinRT headers\n"
#endif
+16
View File
@@ -11,6 +11,7 @@
#include <poll.h>
#else
#include <sys/select.h>
#define st_mtim st_mtimespec // `struct stat` spells it `st_mtimespec` on Apple
#endif
#if FF_HAVE_WORDEXP
@@ -331,3 +332,18 @@ FFNativeFD ffGetNullFD(void) {
bool ffRemoveFile(const char* fileName) {
return unlink(fileName) == 0;
}
uint64_t ffPathGetMtime(const char* path) {
struct stat st;
if (stat(path, &st) != 0) {
return 0;
}
// An mtime at or before the Unix epoch means the filesystem did not fill it in. Reporting it
// as-is would hand the caller a value indistinguishable from "unknown", so treat it as such.
if (st.st_mtim.tv_sec <= 0) {
return 0;
}
return (uint64_t) st.st_mtim.tv_sec * 1000ull + (uint64_t) st.st_mtim.tv_nsec / 1000000ull;
}
+36 -2
View File
@@ -1,6 +1,8 @@
#include "fastfetch.h"
#include "common/debug.h"
#include "common/io.h"
#include "common/strutil.h"
#include "common/time.h"
#include "common/windows/nt.h"
#include "common/windows/unicode.h"
@@ -159,7 +161,9 @@ bool ffWriteFileData(const char* fileName, size_t dataSize, const void* data) {
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) {
DWORD errorCode = GetLastError();
FF_DEBUG("Failed to open file: %s - %s", fileName, ffDebugWin32Error(errorCode));
if (errorCode == ERROR_PATH_NOT_FOUND) {
if (!createSubfolders(fileNameW)) {
return false;
}
@@ -497,5 +501,35 @@ FFNativeFD ffGetNullFD(void) {
}
bool ffRemoveFile(const char* fileName) {
return DeleteFileA(fileName) != FALSE;
wchar_t fileNameW[MAX_PATH];
ULONG len;
if (!NT_SUCCESS(RtlUTF8ToUnicodeN(fileNameW, (ULONG) sizeof(fileNameW), &len, fileName, (ULONG) strlen(fileName) + 1))) {
return false;
}
bool ret = DeleteFileW(fileNameW) != FALSE;
FF_DEBUG("Deleting file: %s - %s", fileName, ret ? "Success" : ffDebugWin32Error(GetLastError()));
return ret;
}
uint64_t ffPathGetMtime(const char* path) {
wchar_t fileNameW[MAX_PATH];
ULONG len;
if (!NT_SUCCESS(RtlUTF8ToUnicodeN(fileNameW, (ULONG) sizeof(fileNameW), &len, path, (ULONG) strlen(path) + 1))) {
return 0;
}
FF_AUTO_CLOSE_FD HANDLE handle = CreateFileW(fileNameW, 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
return 0;
}
FILE_BASIC_INFORMATION fileInfo;
IO_STATUS_BLOCK iosb;
if (!NT_SUCCESS(NtQueryInformationFile(handle, &iosb, &fileInfo, sizeof(fileInfo), FileBasicInformation))) {
return 0;
}
return ffFileTimeToUnixMs((uint64_t) fileInfo.LastWriteTime.QuadPart);
}
+2 -2
View File
@@ -161,8 +161,8 @@ void* dlsym(void* handle, const char* symbol) {
}
void* ffLibraryGetModule(const wchar_t* libraryFileName) {
assert(libraryFileName != nullptr && "Use \"ffGetPeb()->ImageBaseAddress\" instead");
// `libraryFileName` is non-null per the `nonnull(1)` contract.
// Prefer `ffGetPeb()->ImageBaseAddress` over looking the main module up by name.
void* module = nullptr;
USHORT libraryFileNameBytes = (USHORT) (wcslen(libraryFileName) * sizeof(wchar_t) + sizeof(wchar_t));
NTSTATUS status = LdrGetDllHandle(nullptr, nullptr, &(UNICODE_STRING) {
+205 -1
View File
@@ -64,7 +64,8 @@ static uint32_t guessGzipOutputSize(const void* data, uint32_t dataSize) {
// Decompress gzip content
bool ffNetworkingDecompressGzip(FFstrbuf* buffer, char* headerEnd) {
assert(headerEnd != nullptr && *headerEnd == '\r');
// `headerEnd` itself is non-null per the `nonnull(2)` contract; what it points to is not expressible as an attribute
assert(*headerEnd == '\r');
// Calculate header size
uint32_t headerSize = (uint32_t) (headerEnd - buffer->chars);
@@ -190,3 +191,206 @@ bool ffNetworkingDecompressGzip(FFstrbuf* buffer, char* headerEnd) {
return true;
}
#endif // FF_HAVE_ZLIB
const char* ffNetworkingFindHeader(const char* headers, uint32_t headerEnd, const char* name, uint32_t* valueLen) {
uint32_t nameLen = (uint32_t) strlen(name);
uint32_t pos = 0;
while (pos < headerEnd) {
uint32_t eol = pos;
while (eol < headerEnd && headers[eol] != '\n') {
++eol;
}
uint32_t lineEnd = (eol > pos && headers[eol - 1] == '\r') ? (eol - 1) : eol;
// Only match at the beginning of a line, so that a value can never be mistaken
// for a field name (obs-fold continuation lines included)
if (lineEnd - pos >= nameLen && strncasecmp(headers + pos, name, nameLen) == 0) {
uint32_t valueStart = pos + nameLen;
while (valueStart < lineEnd && (headers[valueStart] == ' ' || headers[valueStart] == '\t')) {
++valueStart;
}
*valueLen = lineEnd - valueStart;
return headers + valueStart;
}
if (eol >= headerEnd) {
break;
}
pos = eol + 1;
}
return nullptr;
}
FFNetworkingTransferEncoding ffNetworkingParseTransferEncoding(const char* value, uint32_t valueLen) {
// The value is a comma-separated list of transfer codings (RFC 9112 6.1)
uint32_t codingCount = 0;
const char* coding = nullptr;
uint32_t codingLen = 0;
for (uint32_t i = 0, start = 0; i <= valueLen; ++i) {
if (i < valueLen && value[i] != ',') {
continue;
}
// trim the optional whitespace around the coding
uint32_t from = start;
uint32_t to = i;
while (from < to && (value[from] == ' ' || value[from] == '\t')) {
++from;
}
while (to > from && (value[to - 1] == ' ' || value[to - 1] == '\t')) {
--to;
}
if (to > from) {
++codingCount;
coding = value + from;
codingLen = to - from;
}
start = i + 1;
}
if (codingCount == 0) {
return FF_NETWORKING_TE_NONE;
}
if (codingCount == 1 && codingLen == 7 && strncasecmp(coding, "chunked", 7) == 0) {
return FF_NETWORKING_TE_CHUNKED;
}
return FF_NETWORKING_TE_UNSUPPORTED;
}
int ffNetworkingChunkedComplete(const char* body, uint32_t bodyLen, uint32_t* consumed) {
uint32_t pos = 0;
for (;;) {
// chunk-size [ chunk-ext ] CRLF
uint32_t eol = pos;
while (eol < bodyLen && body[eol] != '\n') {
++eol;
}
if (eol >= bodyLen) {
return 0; // the chunk-size line is not complete yet
}
if (eol == pos || !isxdigit((unsigned char) body[pos])) {
return -1;
}
char* stop = nullptr;
unsigned long size = strtoul(body + pos, &stop, 16);
if (stop == body + pos) {
return -1;
}
pos = eol + 1; // skips the chunk extension, which ends at the CRLF
if (size == 0) {
// last-chunk, followed by an optional trailer section and an empty line
uint32_t p = pos;
while (p < bodyLen) {
uint32_t e = p;
while (e < bodyLen && body[e] != '\n') {
++e;
}
if (e >= bodyLen) {
return 0;
}
if (e == p || (e == p + 1 && body[p] == '\r')) {
*consumed = e + 1;
return 1;
}
p = e + 1;
}
return 0;
}
if (size > (unsigned long) (bodyLen - pos)) {
return 0; // the chunk data is not complete yet
}
pos += (uint32_t) size;
if (bodyLen - pos < 2) {
return 0;
}
if (body[pos] != '\r' || body[pos + 1] != '\n') {
return -1;
}
pos += 2;
}
}
// Keeps the status line and every header except `dropHeader` and `Content-Length`,
// then emits a `Content-Length` matching the (already decoded) body.
// `body` may point into `buffer->chars`; it is copied before `buffer` is released.
static void rebuildResponse(FFstrbuf* buffer, uint32_t headerEnd, const char* body, uint32_t bodyLen, const char* dropHeader) {
FF_STRBUF_AUTO_DESTROY newBuffer = ffStrbufCreateA(headerEnd + bodyLen + 64);
uint32_t pos = 0;
while (pos < headerEnd) {
uint32_t eol = pos;
while (eol < headerEnd && buffer->chars[eol] != '\n') {
++eol;
}
uint32_t lineLen = (eol < headerEnd) ? (eol - pos + 1) : (headerEnd - pos);
if (!ffStrStartsWithIgnCase(buffer->chars + pos, "Content-Length:") &&
!ffStrStartsWithIgnCase(buffer->chars + pos, dropHeader)) {
ffStrbufAppendNS(&newBuffer, lineLen, buffer->chars + pos);
}
pos += lineLen;
}
ffStrbufAppendF(&newBuffer, "Content-Length: %u\r\n\r\n", bodyLen);
ffStrbufAppendNS(&newBuffer, bodyLen, body);
ffStrbufDestroy(buffer);
ffStrbufInitMove(buffer, &newBuffer);
}
bool ffNetworkingDecodeChunked(FFstrbuf* buffer, uint32_t headerEnd) {
assert(buffer->allocated > 0);
// The header block is terminated by CR LF CR LF
if (headerEnd + 4 > buffer->length) {
return false;
}
char* body = buffer->chars + headerEnd + 4;
uint32_t bodyLen = buffer->length - headerEnd - 4;
uint32_t consumed = 0;
if (ffNetworkingChunkedComplete(body, bodyLen, &consumed) != 1) {
FF_DEBUG("Incomplete or malformed chunked body");
return false;
}
// Decoding in place is safe: the encoded form is never shorter than the payload
char* out = body;
uint32_t outLen = 0;
uint32_t pos = 0;
while (pos < bodyLen) {
uint32_t eol = pos;
while (eol < bodyLen && body[eol] != '\n') {
++eol;
}
unsigned long size = strtoul(body + pos, nullptr, 16);
pos = eol + 1;
if (size == 0) {
break; // last-chunk; trailers are dropped
}
memmove(out + outLen, body + pos, size);
outLen += (uint32_t) size;
pos += (uint32_t) size + 2; // trailing CRLF
}
FF_DEBUG("Decoded chunked body: %u bytes encoded, %u bytes decoded", bodyLen, outLen);
rebuildResponse(buffer, headerEnd, out, outLen, "Transfer-Encoding:");
return true;
}
+129 -26
View File
@@ -16,6 +16,9 @@
#include <errno.h>
#include <fcntl.h>
// Upper bound of a single HTTP response, guarding against excessive memory allocation
#define FF_NETWORKING_MAX_RESPONSE_SIZE (1024u * 1024u)
static const char* tryNonThreadingFastPath(FFNetworkingState* state) {
#if defined(TCP_FASTOPEN) || __APPLE__
@@ -187,7 +190,7 @@ exit:
FF_THREAD_ENTRY_DECL_WRAPPER(connectAndSend, FFNetworkingState*);
// Parallel DNS resolution and socket creation
static const char* initNetworkingState(FFNetworkingState* state, const char* host, const char* path, const char* headers) {
static const char* initNetworkingState(FFNetworkingState* state, const char* host, uint16_t port, const char* path, const char* headers) {
FF_DEBUG("Initializing network connection state: host=%s, path=%s", host, path);
// Initialize command and host information
@@ -195,7 +198,19 @@ static const char* initNetworkingState(FFNetworkingState* state, const char* hos
ffStrbufAppendS(&state->command, "GET ");
ffStrbufAppendS(&state->command, path);
ffStrbufAppendS(&state->command, " HTTP/1.0\r\nHost: ");
ffStrbufAppendS(&state->command, host);
if (strchr(host, ':') != nullptr) {
// An IPv6 literal has to be bracketed in the Host header (RFC 9110 7.2), while
// getaddrinfo() wants it bare
ffStrbufAppendC(&state->command, '[');
ffStrbufAppendS(&state->command, host);
ffStrbufAppendC(&state->command, ']');
} else {
ffStrbufAppendS(&state->command, host);
}
// The Host header carries the port whenever it is not the default one (RFC 9110 7.2)
if (port != 80) {
ffStrbufAppendF(&state->command, ":%u", port);
}
ffStrbufAppendS(&state->command, "\r\nConnection: close\r\n"); // Explicitly tell the server we don't need to keep the connection
// If compression needs to be enabled
@@ -220,10 +235,13 @@ static const char* initNetworkingState(FFNetworkingState* state, const char* hos
.ai_flags = AI_NUMERICSERV
};
FF_DEBUG("Resolving address: %s (%s)", host, state->ipv6 ? "IPv6" : "IPv4");
char portA[6];
snprintf(portA, sizeof(portA), "%u", port);
FF_DEBUG("Resolving address: %s:%u (%s)", host, port, state->ipv6 ? "IPv6" : "IPv4");
// Use AI_NUMERICSERV flag to indicate the service is a numeric port, reducing parsing time
int gaiRes = getaddrinfo(host, "80", &hints, &state->addr);
int gaiRes = getaddrinfo(host, portA, &hints, &state->addr);
if (gaiRes != 0) {
FF_DEBUG("getaddrinfo() failed: %s (res=%d)", gai_strerror(gaiRes), gaiRes);
ret = "getaddrinfo() failed";
@@ -259,6 +277,15 @@ static const char* initNetworkingState(FFNetworkingState* state, const char* hos
}
#endif
#ifdef SO_NOSIGPIPE
// Prevent SIGPIPE when the server closes the connection during write
if (setsockopt(state->sockfd, SOL_SOCKET, SO_NOSIGPIPE, &flag, sizeof(flag)) != 0) {
FF_DEBUG("Failed to set SO_NOSIGPIPE: %s", strerror(errno));
} else {
FF_DEBUG("Successfully set SO_NOSIGPIPE");
}
#endif
if (state->timeout > 0) {
FF_DEBUG("Setting connection timeout: %u ms", state->timeout);
[[maybe_unused]] uint32_t sec = state->timeout / 1000;
@@ -298,8 +325,8 @@ error:
return ret;
}
const char* ffNetworkingSendHttpRequest(FFNetworkingState* state, const char* host, const char* path, const char* headers) {
FF_DEBUG("Preparing to send HTTP request: host=%s, path=%s", host, path);
const char* ffNetworkingSendHttpRequest(FFNetworkingState* state, const char* host, uint16_t port, const char* path, const char* headers) {
FF_DEBUG("Preparing to send HTTP request: host=%s, port=%u, path=%s", host, port, path);
if (state->compression) {
FF_DEBUG("Compression enabled, checking if zlib is available");
@@ -321,7 +348,7 @@ const char* ffNetworkingSendHttpRequest(FFNetworkingState* state, const char* ho
FF_DEBUG("Compression disabled");
}
const char* initResult = initNetworkingState(state, host, path, headers);
const char* initResult = initNetworkingState(state, host, port, path, headers);
if (initResult != nullptr) {
FF_DEBUG("Initialization failed: %s", initResult);
return initResult;
@@ -375,9 +402,20 @@ const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buf
}
// Set larger initial receive buffer instead of small repeated receives
int rcvbuf = 65536; // 64KB
int rcvbuf = 64 * 1024;
setsockopt(state->sockfd, SOL_SOCKET, SO_RCVBUF, &rcvbuf, sizeof(rcvbuf));
// The timeout has to be enforced by the socket itself on every platform: the poll() below
// only reports readability once, so a server that sends a partial response and then keeps
// the connection open would otherwise block this loop forever.
if (timeout > 0) {
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
setsockopt(state->sockfd, SOL_SOCKET, SO_RCVTIMEO, &timev, sizeof(timev));
}
#ifdef __APPLE__
// poll for the socket to be readable.
// Because of the non-blocking connectx() call, the connection might not be established yet
@@ -401,14 +439,6 @@ const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buf
}
}
FF_DEBUG("Socket is readable, proceeding to receive data");
#else
if (timeout > 0) {
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
setsockopt(state->sockfd, SOL_SOCKET, SO_RCVTIMEO, &timev, sizeof(timev));
}
#endif
if (shutdown(state->sockfd, SHUT_WR) == -1) {
@@ -420,16 +450,46 @@ const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buf
[[maybe_unused]] int recvCount = 0;
uint32_t contentLength = 0;
uint32_t headerEnd = 0;
bool chunked = false;
do {
FF_DEBUG("Data reception loop #%d, current buffer size: %u, available space: %u",
// Runs until the response is framed; the buffer is grown on demand at the top
for (;;) {
if (ffStrbufGetFree(buffer) == 0) {
// `Content-Length` may be absent (e.g. chunked responses). Grow the buffer
// on demand instead of silently truncating the response.
if (buffer->allocated >= FF_NETWORKING_MAX_RESPONSE_SIZE) {
FF_DEBUG("Response is too large: %u bytes, aborting", buffer->allocated);
close(state->sockfd);
state->sockfd = -1;
return "Response too large";
}
FF_DEBUG("Receive buffer is full, extending it");
ffStrbufEnsureFreeNoCheck(buffer, buffer->allocated);
}
// When the remaining length is known, ask for exactly that much. MSG_WAITALL then
// returns as soon as the response is complete, instead of waiting for the server
// to close the connection.
// Without a Content-Length the requested length is just "whatever fits", so
// waiting for all of it would block until the server closes -- and the framing
// checks below would never get a chance to run. Read whatever has arrived instead
// and let those checks decide when the response is complete.
uint32_t want = ffStrbufGetFree(buffer);
int recvFlags = 0;
if (contentLength > 0 && headerEnd > 0) {
uint32_t remaining = headerEnd + 4 + contentLength - buffer->length;
if (remaining < want) {
want = remaining;
}
recvFlags = MSG_WAITALL;
}
FF_DEBUG("Data reception loop #%d, current buffer size: %u, requesting %u bytes",
++recvCount,
buffer->length,
ffStrbufGetFree(buffer));
want);
// We set `Connection: close`, so the server will close the connection when done.
// Thus we can use MSG_WAITALL to wait until the buffer is full or the connection is closed.
ssize_t received = recv(state->sockfd, buffer->chars + buffer->length, ffStrbufGetFree(buffer), MSG_WAITALL);
ssize_t received = recv(state->sockfd, buffer->chars + buffer->length, want, recvFlags);
if (received <= 0) {
if (received == 0) {
@@ -453,11 +513,12 @@ const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buf
FF_DEBUG("Found HTTP header end marker, position: %u", headerEnd);
// Check for Content-Length header to pre-allocate enough memory
const char* clHeader = strcasestr(buffer->chars, "Content-Length:");
uint32_t valueLen = 0;
const char* clHeader = ffNetworkingFindHeader(buffer->chars, headerEnd, "Content-Length:", &valueLen);
if (clHeader) {
contentLength = (uint32_t) strtoul(clHeader + 15, nullptr, 10);
contentLength = (uint32_t) strtoul(clHeader, nullptr, 10);
if (contentLength > 0) {
if (contentLength > 1024 * 1024) { // 1MB limit to prevent excessive memory allocation and potential attacks
if (contentLength > FF_NETWORKING_MAX_RESPONSE_SIZE) { // 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;
@@ -470,9 +531,47 @@ const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buf
FF_DEBUG("Extended receive buffer to %u bytes", buffer->allocated);
}
}
// A chunked response has no Content-Length; it is framed by a last-chunk
const char* teHeader = ffNetworkingFindHeader(buffer->chars, headerEnd, "Transfer-Encoding:", &valueLen);
if (teHeader != nullptr) {
switch (ffNetworkingParseTransferEncoding(teHeader, valueLen)) {
case FF_NETWORKING_TE_CHUNKED:
FF_DEBUG("Detected chunked transfer encoding");
chunked = true;
break;
case FF_NETWORKING_TE_UNSUPPORTED:
// The framing of e.g. `gzip, chunked` is unreadable and the payload
// would stay encoded, so fail instead of returning garbage
FF_DEBUG("Unsupported Transfer-Encoding: %.*s", (int) valueLen, teHeader);
close(state->sockfd);
state->sockfd = -1;
return "Unsupported Transfer-Encoding";
default:
break;
}
}
}
}
} while (ffStrbufGetFree(buffer) > 0);
// Stop as soon as the response is framed, rather than waiting for the FIN
if (chunked) {
uint32_t consumed = 0;
int complete = ffNetworkingChunkedComplete(buffer->chars + headerEnd + 4, buffer->length - headerEnd - 4, &consumed);
if (complete < 0) {
FF_DEBUG("Malformed chunked body");
close(state->sockfd);
state->sockfd = -1;
return "Malformed chunked body";
}
if (complete > 0) {
FF_DEBUG("Chunked body complete, %u bytes of encoded body", consumed);
break;
}
} else if (contentLength > 0 && buffer->length >= headerEnd + 4 + contentLength) {
break;
}
}
FF_DEBUG("Closing socket: fd=%d", state->sockfd);
close(state->sockfd);
@@ -488,6 +587,10 @@ const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buf
return "No HTTP header end found";
}
if (chunked && !ffNetworkingDecodeChunked(buffer, headerEnd)) {
return "Failed to decode chunked response";
}
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";
+86 -10
View File
@@ -9,6 +9,9 @@
static LPFN_CONNECTEX ConnectEx;
// Upper bound of a single HTTP response, guarding against excessive memory allocation
#define FF_NETWORKING_MAX_RESPONSE_SIZE (1024u * 1024u)
static const char* initWsaData(WSADATA* wsaData) {
FF_DEBUG("Initializing WinSock");
if (WSAStartup(MAKEWORD(2, 2), wsaData) != 0) {
@@ -45,8 +48,8 @@ static const char* initWsaData(WSADATA* wsaData) {
return nullptr;
}
const char* ffNetworkingSendHttpRequest(FFNetworkingState* state, const char* host, const char* path, const char* headers) {
FF_DEBUG("Preparing to send HTTP request: host=%s, path=%s", host, path);
const char* ffNetworkingSendHttpRequest(FFNetworkingState* state, const char* host, uint16_t port, const char* path, const char* headers) {
FF_DEBUG("Preparing to send HTTP request: host=%s, port=%u, path=%s", host, port, path);
if (state->compression) {
#ifdef FF_HAVE_ZLIB
@@ -92,8 +95,11 @@ const char* ffNetworkingSendHttpRequest(FFNetworkingState* state, const char* ho
return "Failed to convert host to wide string";
}
FF_DEBUG("Resolving address: %s (%s)", host, state->ipv6 ? "IPv6" : "IPv4");
if (GetAddrInfoW(hostW, L"80", &hints, &addr) != 0) {
wchar_t portW[6];
_itow(port, portW, 10);
FF_DEBUG("Resolving address: %s:%u (%s)", host, port, state->ipv6 ? "IPv6" : "IPv4");
if (GetAddrInfoW(hostW, portW, &hints, &addr) != 0) {
FF_DEBUG("GetAddrInfoW() failed");
return "GetAddrInfoW() failed";
}
@@ -156,7 +162,19 @@ const char* ffNetworkingSendHttpRequest(FFNetworkingState* state, const char* ho
ffStrbufAppendS(&state->command, "GET ");
ffStrbufAppendS(&state->command, path);
ffStrbufAppendS(&state->command, " HTTP/1.0\r\nHost: ");
ffStrbufAppendS(&state->command, host);
if (strchr(host, ':') != nullptr) {
// An IPv6 literal has to be bracketed in the Host header (RFC 9110 7.2), while
// GetAddrInfoW() wants it bare
ffStrbufAppendC(&state->command, '[');
ffStrbufAppendS(&state->command, host);
ffStrbufAppendC(&state->command, ']');
} else {
ffStrbufAppendS(&state->command, host);
}
// The Host header carries the port whenever it is not the default one (RFC 9110 7.2)
if (port != 80) {
ffStrbufAppendF(&state->command, ":%u", port);
}
ffStrbufAppendS(&state->command, "\r\nConnection: close\r\n"); // Explicitly request connection closure
// Add compression support if enabled
@@ -266,8 +284,23 @@ const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buf
[[maybe_unused]] int recvCount = 0;
uint32_t contentLength = 0;
uint32_t headerEnd = 0;
bool chunked = false;
// Runs until the response is framed; the buffer is grown on demand at the top
for (;;) {
if (ffStrbufGetFree(buffer) == 0) {
// `Content-Length` may be absent (e.g. chunked responses). Grow the buffer
// on demand instead of silently truncating the response.
if (buffer->allocated >= FF_NETWORKING_MAX_RESPONSE_SIZE) {
FF_DEBUG("Response is too large: %u bytes, aborting", buffer->allocated);
closesocket(state->sockfd);
state->sockfd = INVALID_SOCKET;
return "Response too large";
}
FF_DEBUG("Receive buffer is full, extending it");
ffStrbufEnsureFreeNoCheck(buffer, buffer->allocated);
}
do {
FF_DEBUG("Data reception loop #%d, current buffer size: %u, available space: %u",
++recvCount,
buffer->length,
@@ -306,11 +339,12 @@ const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buf
FF_DEBUG("Found HTTP header end marker, position: %u", headerEnd);
// Check for Content-Length header to pre-allocate enough memory
const char* clHeader = strcasestr(buffer->chars, "Content-Length:");
uint32_t valueLen = 0;
const char* clHeader = ffNetworkingFindHeader(buffer->chars, headerEnd, "Content-Length:", &valueLen);
if (clHeader) {
contentLength = (uint32_t) strtoul(clHeader + 15, nullptr, 10);
contentLength = (uint32_t) strtoul(clHeader, nullptr, 10);
if (contentLength > 0) {
if (contentLength > 1024 * 1024) { // 1MB limit to prevent excessive memory allocation and potential attacks
if (contentLength > FF_NETWORKING_MAX_RESPONSE_SIZE) { // 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;
@@ -323,9 +357,47 @@ const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buf
FF_DEBUG("Extended receive buffer to %u bytes", buffer->allocated);
}
}
// A chunked response has no Content-Length; it is framed by a last-chunk
const char* teHeader = ffNetworkingFindHeader(buffer->chars, headerEnd, "Transfer-Encoding:", &valueLen);
if (teHeader != nullptr) {
switch (ffNetworkingParseTransferEncoding(teHeader, valueLen)) {
case FF_NETWORKING_TE_CHUNKED:
FF_DEBUG("Detected chunked transfer encoding");
chunked = true;
break;
case FF_NETWORKING_TE_UNSUPPORTED:
// The framing of e.g. `gzip, chunked` is unreadable and the payload
// would stay encoded, so fail instead of returning garbage
FF_DEBUG("Unsupported Transfer-Encoding: %.*s", (int) valueLen, teHeader);
closesocket(state->sockfd);
state->sockfd = INVALID_SOCKET;
return "Unsupported Transfer-Encoding";
default:
break;
}
}
}
}
} while (ffStrbufGetFree(buffer) > 0);
// Stop as soon as the response is framed, rather than waiting for the FIN
if (chunked) {
uint32_t consumed = 0;
int complete = ffNetworkingChunkedComplete(buffer->chars + headerEnd + 4, buffer->length - headerEnd - 4, &consumed);
if (complete < 0) {
FF_DEBUG("Malformed chunked body");
closesocket(state->sockfd);
state->sockfd = INVALID_SOCKET;
return "Malformed chunked body";
}
if (complete > 0) {
FF_DEBUG("Chunked body complete, %u bytes of encoded body", consumed);
break;
}
} else if (contentLength > 0 && buffer->length >= headerEnd + 4 + contentLength) {
break;
}
}
FF_DEBUG("Closing socket: fd=%u", (unsigned) state->sockfd);
closesocket(state->sockfd);
@@ -341,6 +413,10 @@ const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buf
return "No HTTP header end found";
}
if (chunked && !ffNetworkingDecodeChunked(buffer, headerEnd)) {
return "Failed to decode chunked response";
}
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";
+35 -4
View File
@@ -7,8 +7,6 @@
// 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 nullptr;
@@ -122,8 +120,9 @@ void ffOptionParseColorNoClear(const char* value, FFstrbuf* buffer) {
value += strlen(#prefix); \
continue; \
}
#define FF_APPEND_COLOR_PROP_COND(prefix, prop) \
#define FF_APPEND_COLOR_PROP_COND(prefix, prop, honorBrightColor) \
if (ffStrStartsWithIgnCase(value, #prefix)) { \
if (honorBrightColor && instance.config.display.brightColor) ffStrbufAppendS(buffer, "1;"); \
if (instance.config.display.prop.length) ffStrbufAppend(buffer, &instance.config.display.prop); \
else ffStrbufAppendS(buffer, FF_COLOR_FG_DEFAULT); \
value += strlen(#prefix); \
@@ -131,11 +130,43 @@ void ffOptionParseColorNoClear(const char* value, FFstrbuf* buffer) {
}
if (ffCharIsEnglishAlphabet(value[0])) {
// clang-format off
FF_APPEND_COLOR_CODE_COND(reset_, FF_COLOR_MODE_RESET)
else FF_APPEND_COLOR_CODE_COND(bold_, FF_COLOR_MODE_BOLD) else FF_APPEND_COLOR_CODE_COND(bright_, FF_COLOR_MODE_BOLD) else FF_APPEND_COLOR_CODE_COND(dim_, FF_COLOR_MODE_DIM) else FF_APPEND_COLOR_CODE_COND(italic_, FF_COLOR_MODE_ITALIC) else FF_APPEND_COLOR_CODE_COND(underline_, FF_COLOR_MODE_UNDERLINE) else FF_APPEND_COLOR_CODE_COND(blink_, FF_COLOR_MODE_BLINK) else FF_APPEND_COLOR_CODE_COND(inverse_, FF_COLOR_MODE_INVERSE) else FF_APPEND_COLOR_CODE_COND(hidden_, FF_COLOR_MODE_HIDDEN) else FF_APPEND_COLOR_CODE_COND(strike_, FF_COLOR_MODE_STRIKETHROUGH) else FF_APPEND_COLOR_CODE_COND(black, FF_COLOR_FG_BLACK) else FF_APPEND_COLOR_CODE_COND(red, FF_COLOR_FG_RED) else FF_APPEND_COLOR_CODE_COND(green, FF_COLOR_FG_GREEN) else FF_APPEND_COLOR_CODE_COND(yellow, FF_COLOR_FG_YELLOW) else FF_APPEND_COLOR_CODE_COND(blue, FF_COLOR_FG_BLUE) else FF_APPEND_COLOR_CODE_COND(magenta, FF_COLOR_FG_MAGENTA) else FF_APPEND_COLOR_CODE_COND(cyan, FF_COLOR_FG_CYAN) else FF_APPEND_COLOR_CODE_COND(white, FF_COLOR_FG_WHITE) else FF_APPEND_COLOR_CODE_COND(default, FF_COLOR_FG_DEFAULT) else FF_APPEND_COLOR_CODE_COND(light_black, FF_COLOR_FG_LIGHT_BLACK) else FF_APPEND_COLOR_CODE_COND(light_red, FF_COLOR_FG_LIGHT_RED) else FF_APPEND_COLOR_CODE_COND(light_green, FF_COLOR_FG_LIGHT_GREEN) else FF_APPEND_COLOR_CODE_COND(light_yellow, FF_COLOR_FG_LIGHT_YELLOW) else FF_APPEND_COLOR_CODE_COND(light_blue, FF_COLOR_FG_LIGHT_BLUE) else FF_APPEND_COLOR_CODE_COND(light_magenta, FF_COLOR_FG_LIGHT_MAGENTA) else FF_APPEND_COLOR_CODE_COND(light_cyan, FF_COLOR_FG_LIGHT_CYAN) else FF_APPEND_COLOR_CODE_COND(light_white, FF_COLOR_FG_LIGHT_WHITE) else FF_APPEND_COLOR_PROP_COND(keys, colorKeys) else FF_APPEND_COLOR_PROP_COND(title, colorTitle) else FF_APPEND_COLOR_PROP_COND(output, colorOutput) else FF_APPEND_COLOR_PROP_COND(separator, colorSeparator) else {
else FF_APPEND_COLOR_CODE_COND(bold_, FF_COLOR_MODE_BOLD)
else FF_APPEND_COLOR_CODE_COND(bright_, FF_COLOR_MODE_BOLD)
else FF_APPEND_COLOR_CODE_COND(dim_, FF_COLOR_MODE_DIM)
else FF_APPEND_COLOR_CODE_COND(italic_, FF_COLOR_MODE_ITALIC)
else FF_APPEND_COLOR_CODE_COND(underline_, FF_COLOR_MODE_UNDERLINE)
else FF_APPEND_COLOR_CODE_COND(blink_, FF_COLOR_MODE_BLINK)
else FF_APPEND_COLOR_CODE_COND(inverse_, FF_COLOR_MODE_INVERSE)
else FF_APPEND_COLOR_CODE_COND(hidden_, FF_COLOR_MODE_HIDDEN)
else FF_APPEND_COLOR_CODE_COND(strike_, FF_COLOR_MODE_STRIKETHROUGH)
else FF_APPEND_COLOR_CODE_COND(black, FF_COLOR_FG_BLACK)
else FF_APPEND_COLOR_CODE_COND(red, FF_COLOR_FG_RED)
else FF_APPEND_COLOR_CODE_COND(green, FF_COLOR_FG_GREEN)
else FF_APPEND_COLOR_CODE_COND(yellow, FF_COLOR_FG_YELLOW)
else FF_APPEND_COLOR_CODE_COND(blue, FF_COLOR_FG_BLUE)
else FF_APPEND_COLOR_CODE_COND(magenta, FF_COLOR_FG_MAGENTA)
else FF_APPEND_COLOR_CODE_COND(cyan, FF_COLOR_FG_CYAN)
else FF_APPEND_COLOR_CODE_COND(white, FF_COLOR_FG_WHITE)
else FF_APPEND_COLOR_CODE_COND(default, FF_COLOR_FG_DEFAULT)
else FF_APPEND_COLOR_CODE_COND(light_black, FF_COLOR_FG_LIGHT_BLACK)
else FF_APPEND_COLOR_CODE_COND(light_red, FF_COLOR_FG_LIGHT_RED)
else FF_APPEND_COLOR_CODE_COND(light_green, FF_COLOR_FG_LIGHT_GREEN)
else FF_APPEND_COLOR_CODE_COND(light_yellow, FF_COLOR_FG_LIGHT_YELLOW)
else FF_APPEND_COLOR_CODE_COND(light_blue, FF_COLOR_FG_LIGHT_BLUE)
else FF_APPEND_COLOR_CODE_COND(light_magenta, FF_COLOR_FG_LIGHT_MAGENTA)
else FF_APPEND_COLOR_CODE_COND(light_cyan, FF_COLOR_FG_LIGHT_CYAN)
else FF_APPEND_COLOR_CODE_COND(light_white, FF_COLOR_FG_LIGHT_WHITE)
else FF_APPEND_COLOR_PROP_COND(keys, colorKeys, true)
else FF_APPEND_COLOR_PROP_COND(title, colorTitle, true)
else FF_APPEND_COLOR_PROP_COND(output, colorOutput, false)
else FF_APPEND_COLOR_PROP_COND(separator, colorSeparator, false)
else {
fprintf(stderr, "Error: invalid color code found: %s\n", value);
exit(479);
}
// clang-format on
} else if (value[0] == '@') {
// Xterm 256 color
++value;
+23 -20
View File
@@ -28,7 +28,6 @@
#elif defined(__OpenBSD__)
#include <sys/param.h>
#include <sys/sysctl.h>
#include <kvm.h>
#elif defined(__NetBSD__)
#include <sys/types.h>
#include <sys/sysctl.h>
@@ -57,7 +56,7 @@ static inline int ffPipe2(int* fds, int flags) {
}
// Not thread-safe
const char* ffProcessSpawn(char* const argv[], bool useStdErr, FFProcessHandle* outHandle) {
const char* ffProcessSpawn(char* const argv[], bool useStdErr, FFNativeFD stdinFd, FFProcessHandle* outHandle) {
int pipes[2];
if (ffPipe2(pipes, O_CLOEXEC) == -1) {
return "pipe() failed";
@@ -78,6 +77,9 @@ const char* ffProcessSpawn(char* const argv[], bool useStdErr, FFProcessHandle*
posix_spawn_file_actions_init(&file_actions);
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);
if (ffIsValidNativeFD(stdinFd)) {
posix_spawn_file_actions_adddup2(&file_actions, stdinFd, STDIN_FILENO);
}
static char* oldLang = nullptr;
static int langIndex = -1;
@@ -143,6 +145,9 @@ const char* ffProcessSpawn(char* const argv[], bool useStdErr, FFProcessHandle*
// Child process
dup2(pipes[1], useStdErr ? STDERR_FILENO : STDOUT_FILENO);
dup2(nullFile, useStdErr ? STDOUT_FILENO : STDERR_FILENO);
if (ffIsValidNativeFD(stdinFd)) {
dup2(stdinFd, STDIN_FILENO);
}
putenv("LANG=C.UTF-8");
execvp(argv[0], argv);
_exit(127);
@@ -423,12 +428,13 @@ void ffProcessGetInfoLinux(pid_t pid, FFstrbuf* processName, FFstrbuf* exe, cons
#elif defined(__OpenBSD__)
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) {
char** argv = kvm_getargv(kd, proc, 0);
if (argv) {
char argvBuf[ARG_MAX];
size_t argvSize = sizeof(argvBuf);
int argvMib[] = { CTL_KERN, KERN_PROC_ARGS, pid, KERN_PROC_ARGV };
if (sysctl(argvMib, ARRAY_SIZE(argvMib), argvBuf, &argvSize, nullptr, 0) == 0) {
// The buffer is filled with an array of char pointers followed by the strings themselves
char** argv = (char**) argvBuf;
if (argv[0] && (char*) argv[0] >= argvBuf && (char*) argv[0] < argvBuf + argvSize) {
const char* arg0 = argv[0];
if (arg0[0] == '-') {
arg0++;
@@ -436,7 +442,6 @@ void ffProcessGetInfoLinux(pid_t pid, FFstrbuf* processName, FFstrbuf* exe, cons
ffStrbufSetS(exe, arg0);
}
}
kvm_close(kd);
#elif defined(__HAIKU__)
@@ -633,21 +638,19 @@ const char* ffProcessGetBasicInfoLinux(pid_t pid, FFstrbuf* name, pid_t* ppid, i
#elif defined(__OpenBSD__)
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) {
ffStrbufSetS(name, proc->p_comm);
struct kinfo_proc proc;
size_t size = sizeof(proc);
int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid, (int) sizeof(struct kinfo_proc), 1 };
if (sysctl(mib, ARRAY_SIZE(mib), &proc, &size, nullptr, 0) == 0) {
ffStrbufSetS(name, proc.p_comm);
if (ppid) {
*ppid = proc->p_ppid;
*ppid = proc.p_ppid;
}
if (tty) {
*tty = (int) proc->p_tdev;
*tty = (int) proc.p_tdev;
}
}
kvm_close(kd);
if (!proc) {
return "kvm_getprocs() failed";
} else {
return "sysctl(KERN_PROC_PID) failed";
}
#elif defined(__HAIKU__)
+4 -1
View File
@@ -83,7 +83,7 @@ static wchar_t* createChildEnvironment(void) {
return result;
}
const char* ffProcessSpawn(char* const argv[], bool useStdErr, FFProcessHandle* outHandle) {
const char* ffProcessSpawn(char* const argv[], bool useStdErr, FFNativeFD stdinFd, FFProcessHandle* outHandle) {
const int32_t timeout = instance.config.general.processingTimeout;
wchar_t pipeName[32];
@@ -131,6 +131,9 @@ const char* ffProcessSpawn(char* const argv[], bool useStdErr, FFProcessHandle*
siStartInfo.hStdOutput = hChildPipeWrite;
siStartInfo.hStdError = ffGetNullFD();
}
if (ffIsValidNativeFD(stdinFd)) {
siStartInfo.hStdInput = stdinFd;
}
FF_AUTO_FREE wchar_t* cmdline = nullptr;
{
+69 -55
View File
@@ -3,6 +3,7 @@
#include "common/library.h"
#include "common/thread.h"
#include "common/io.h"
#include "common/debug.h"
#include <string.h>
@@ -380,72 +381,85 @@ static const SQLiteData* getSQLiteData(void) {
return &data;
}
int ffSettingsGetSQLite3Int(const char* dbPath, const char* query) {
if (!ffPathExists(dbPath, FF_PATHTYPE_FILE)) {
return 0;
}
const SQLiteData* data = getSQLiteData();
if (data == nullptr) {
return 0;
}
typedef struct FFSQLite3Bundle {
const SQLiteData* data;
sqlite3* db;
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, nullptr) != SQLITE_OK) {
data->ffsqlite3_close(db);
} FFSQLite3Bundle;
static void destroySQLite3Bundle(FFSQLite3Bundle* bundle) {
if (!bundle->data) {
return;
}
if (bundle->stmt) {
bundle->data->ffsqlite3_finalize(bundle->stmt);
bundle->stmt = nullptr;
}
if (bundle->db) {
bundle->data->ffsqlite3_close(bundle->db);
bundle->db = nullptr;
}
}
static bool prepareSQLite3Statement(const char* dbPath, const char* query, FFSQLite3Bundle* bundle) {
if (!ffPathExists(dbPath, FF_PATHTYPE_FILE)) {
return false;
}
const SQLiteData* data = bundle->data = getSQLiteData();
if (data == nullptr) {
FF_DEBUG("Failed to load SQLite3 library");
return false;
}
// Read-only WAL databases may require a -shm or lock file during prepare, which is not
// possible when the database directory is not writable. immutable=1 avoids those files.
FF_STRBUF_AUTO_DESTROY pathImmutable = ffStrbufCreateStatic("file:");
ffStrbufAppendS(&pathImmutable, dbPath);
ffStrbufAppendS(&pathImmutable, "?immutable=1");
int ret = data->ffsqlite3_open_v2(pathImmutable.chars, &bundle->db, SQLITE_OPEN_READONLY | SQLITE_OPEN_NOMUTEX | SQLITE_OPEN_URI, nullptr);
if (ret != SQLITE_OK) {
FF_DEBUG("Failed to open SQLite3 database: %s (%d)", dbPath, ret);
return false;
}
ret = data->ffsqlite3_prepare_v2(bundle->db, query, (int) strlen(query), &bundle->stmt, nullptr);
if (ret != SQLITE_OK) {
FF_DEBUG("Failed to prepare SQLite3 statement: %s (%d)", query, ret);
return false;
}
ret = data->ffsqlite3_step(bundle->stmt);
if (ret != SQLITE_ROW) {
FF_DEBUG("Failed to step SQLite3 statement: %s (%d)", query, ret);
return false;
}
ret = data->ffsqlite3_data_count(bundle->stmt);
if (ret < 1) {
FF_DEBUG("No data returned for SQLite3 statement: %s", query);
return false;
}
return true;
}
int ffSettingsGetSQLite3Int(const char* dbPath, const char* query) {
[[gnu::cleanup(destroySQLite3Bundle)]] FFSQLite3Bundle bundle = {};
if (!prepareSQLite3Statement(dbPath, query, &bundle)) {
return 0;
}
if (data->ffsqlite3_step(stmt) != SQLITE_ROW || data->ffsqlite3_data_count(stmt) < 1) {
data->ffsqlite3_finalize(stmt);
data->ffsqlite3_close(db);
return 0;
}
int result = data->ffsqlite3_column_int(stmt, 0);
data->ffsqlite3_finalize(stmt);
data->ffsqlite3_close(db);
return result;
return bundle.data->ffsqlite3_column_int(bundle.stmt, 0);
}
bool ffSettingsGetSQLite3String(const char* dbPath, const char* query, FFstrbuf* result) {
if (!ffPathExists(dbPath, FF_PATHTYPE_FILE)) {
[[gnu::cleanup(destroySQLite3Bundle)]] FFSQLite3Bundle bundle = {};
if (!prepareSQLite3Statement(dbPath, query, &bundle)) {
return false;
}
const SQLiteData* data = getSQLiteData();
if (data == nullptr) {
return false;
}
sqlite3* db;
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, nullptr) != SQLITE_OK) {
data->ffsqlite3_close(db);
return false;
}
if (data->ffsqlite3_step(stmt) != SQLITE_ROW || data->ffsqlite3_data_count(stmt) < 1) {
data->ffsqlite3_finalize(stmt);
data->ffsqlite3_close(db);
return false;
}
ffStrbufSetS(result, (const char*) data->ffsqlite3_column_text(stmt, 0));
data->ffsqlite3_finalize(stmt);
data->ffsqlite3_close(db);
ffStrbufSetS(result, (const char*) bundle.data->ffsqlite3_column_text(bundle.stmt, 0));
return true;
}
+1 -1
View File
@@ -211,7 +211,7 @@ static bool readPhysicalMemory(int fd, off_t address, size_t length, void* buffe
}
#endif
off_t alignedAddress = address & ~((off_t) instance.state.platform.sysinfo.pageSize - 1);
off_t alignedAddress = address & ~(((off_t) 1 << instance.state.platform.sysinfo.pageSizeShift) - 1);
size_t pageOffset = (size_t) (address - alignedAddress);
size_t mapLength = pageOffset + length;
+11 -10
View File
@@ -36,8 +36,8 @@ typedef int FFNativeFD;
#endif
// Only O_RDONLY is supported
HANDLE openat(HANDLE dfd, const char* fileName, int oflag);
HANDLE openatW(HANDLE dfd, const wchar_t* fileName, uint16_t fileNameLen, bool directory);
[[gnu::nonnull(2)]] HANDLE openat(HANDLE dfd, const char* fileName, int oflag);
[[gnu::nonnull(2)]] HANDLE openatW(HANDLE dfd, const wchar_t* fileName, uint16_t fileNameLen, bool directory);
#endif
static inline bool ffIsValidNativeFD(FFNativeFD fd) {
@@ -51,8 +51,6 @@ static inline bool ffIsValidNativeFD(FFNativeFD fd) {
[[gnu::always_inline, gnu::nonnull(1)]]
static inline void wrapClose(FFNativeFD* pfd) {
assert(pfd);
if (ffIsValidNativeFD(*pfd)) {
#ifndef _WIN32
close(*pfd);
@@ -230,11 +228,12 @@ typedef enum FFPathType: uint8_t {
[[gnu::nonnull(1, 2)]] bool ffPathExpandEnv(const char* in, FFstrbuf* out);
#define FF_IO_TERM_RESP_WAIT_MS 100 // #554
#define FF_IO_TERM_RESP_WAIT_MS 200 // #554
[[gnu::format(scanf, 3, 4), gnu::nonnull(1, 3)]] const char* ffGetTerminalResponse(const char* request, int nParams, const char* format, ...);
// Not thread safe!
// Returns the previous state, which callers routinely discard (see ffUnsuppressIO), so not `nodiscard`
bool ffSuppressIO(bool suppress);
static inline void ffUnsuppressIO(bool* suppressed) {
@@ -247,10 +246,9 @@ static inline void ffUnsuppressIO(bool* suppressed) {
#define FF_SUPPRESS_IO() [[maybe_unused, gnu::cleanup(ffUnsuppressIO)]] bool io_suppressed__ = ffSuppressIO(true)
void ffListFilesRecursively(const char* path, bool pretty);
[[gnu::nonnull(1)]] void ffListFilesRecursively(const char* path, bool pretty);
[[gnu::nonnull(1), gnu::always_inline]] static inline void wrapFclose(FILE** pfile) {
assert(pfile);
if (*pfile) {
fclose(*pfile);
}
@@ -260,14 +258,12 @@ void ffListFilesRecursively(const char* path, bool pretty);
[[gnu::nonnull(1), gnu::always_inline]]
#ifndef _WIN32
static inline void wrapClosedir(DIR** pdir) {
assert(pdir);
if (*pdir) {
closedir(*pdir);
}
}
#else
static inline void wrapClosedir(HANDLE* pdir) {
assert(pdir);
if (*pdir) {
FindClose(*pdir);
}
@@ -290,4 +286,9 @@ static inline void wrapClosedir(HANDLE* pdir) {
}
FFNativeFD ffGetNullFD(void);
bool ffRemoveFile(const char* fileName);
// Returns whether the file was removed; callers that only want it gone discard that, so not `nodiscard`
[[gnu::nonnull(1)]] bool ffRemoveFile(const char* fileName);
// Modification time of a file, in milliseconds since the Unix epoch, or 0 if it can not be read.
// The representation is uniform across platforms so that a value derived from it means the
// same thing everywhere, which matters for callers that store it as a cache key.
[[gnu::nonnull(1)]] uint64_t ffPathGetMtime(const char* path);
+12 -7
View File
@@ -3,25 +3,30 @@
#include "common/ffdata.h"
#include "common/option.h"
bool ffJsonConfigParseModuleArgs(yyjson_val* key, yyjson_val* val, FFModuleArgs* moduleArgs);
const char* ffJsonConfigParseEnum(yyjson_val* val, int* result, FFKeyValuePair pairs[]);
// `key` / `val` may be null when the JSON object has no such member; `moduleArgs` is always real
[[gnu::nonnull(3)]] bool ffJsonConfigParseModuleArgs(yyjson_val* key, yyjson_val* val, FFModuleArgs* moduleArgs);
// `val` may be null (yyjson predicates tolerate it); `result` and `pairs` may not.
// Returns an error string, null on success, so it is `nodiscard`.
[[gnu::nonnull(2, 3), nodiscard]] const char* ffJsonConfigParseEnum(yyjson_val* val, int* result, FFKeyValuePair pairs[]);
yyjson_api_inline yyjson_mut_val* yyjson_mut_strbuf(yyjson_mut_doc* doc, const FFstrbuf* buf) {
// The three helpers below are routinely called as statements, to add a key to a document, so their
// result is not `nodiscard`.
[[gnu::nonnull(1, 2)]] yyjson_api_inline yyjson_mut_val* yyjson_mut_strbuf(yyjson_mut_doc* doc, const FFstrbuf* buf) {
return yyjson_mut_strncpy(doc, buf->chars, buf->length);
}
yyjson_api_inline bool yyjson_mut_obj_add_strbuf(yyjson_mut_doc* doc,
[[gnu::nonnull(1, 2, 3, 4)]] yyjson_api_inline bool yyjson_mut_obj_add_strbuf(yyjson_mut_doc* doc,
yyjson_mut_val* obj,
const char* _key,
const FFstrbuf* buf) {
return yyjson_mut_obj_add_strncpy(doc, obj, _key, buf->chars, buf->length);
}
yyjson_api_inline bool yyjson_mut_arr_add_strbuf(yyjson_mut_doc* doc,
[[gnu::nonnull(1, 2, 3)]] yyjson_api_inline bool yyjson_mut_arr_add_strbuf(yyjson_mut_doc* doc,
yyjson_mut_val* obj,
const FFstrbuf* buf) {
return yyjson_mut_arr_add_strncpy(doc, obj, buf->chars, buf->length);
}
void ffPrintJsonConfig(FFdata* data, bool prepare);
void ffJsonConfigGenerateModuleArgsConfig(yyjson_mut_doc* doc, yyjson_mut_val* module, FFModuleArgs* moduleArgs);
[[gnu::nonnull(1)]] void ffPrintJsonConfig(FFdata* data, bool prepare);
[[gnu::nonnull(1, 2, 3)]] void ffJsonConfigGenerateModuleArgsConfig(yyjson_mut_doc* doc, yyjson_mut_val* module, FFModuleArgs* moduleArgs);
+5 -6
View File
@@ -21,8 +21,7 @@ int dlclose(void* handle);
#define FF_LIBRARY_EXTENSION ".so"
#endif
static inline void ffLibraryUnload(void** handle) {
assert(handle);
[[gnu::nonnull(1)]] static inline void ffLibraryUnload(void** handle) {
if (*handle) {
dlclose(*handle);
}
@@ -66,8 +65,8 @@ static inline void ffLibraryUnload(void** handle) {
#define FF_LIBRARY_LOAD_SYMBOL_PTR(library, varName, symbolName, returnValue) \
FF_LIBRARY_LOAD_SYMBOL_ADDRESS(library, (varName)->ff##symbolName, symbolName, returnValue);
void* ffLibraryLoadSingle(const char* path, int maxVersion);
void* ffLibraryLoadMulti(const char* path, int maxVersion, ...);
[[gnu::nonnull(1), nodiscard]] void* ffLibraryLoadSingle(const char* path, int maxVersion);
[[gnu::nonnull(1), nodiscard]] void* ffLibraryLoadMulti(const char* path, int maxVersion, ...);
#else
@@ -109,10 +108,10 @@ void* ffLibraryLoadMulti(const char* path, int maxVersion, ...);
#endif
#if _WIN32
void* ffLibraryGetModule(const wchar_t* libraryFileName);
[[gnu::nonnull(1), nodiscard]] void* ffLibraryGetModule(const wchar_t* libraryFileName);
#endif
// Return false to stop iterating, true to continue
typedef bool (*FFLibraryIterateCallback)(const char* name, void* userData);
// Iterate over all loaded dynamic libraries. Returns true on success, false on failure.
bool ffLibraryIterateDynamicLibs(FFLibraryIterateCallback callback, void* userData);
[[nodiscard]] bool ffLibraryIterateDynamicLibs(FFLibraryIterateCallback callback, void* userData);
+1 -2
View File
@@ -15,7 +15,6 @@
[[gnu::always_inline, gnu::nonnull(1)]]
static inline void ffWrapFree(const void* pPtr) {
assert(pPtr);
if (*(void**) pPtr) {
free(*(void**) pPtr);
}
@@ -24,8 +23,8 @@ static inline void ffWrapFree(const void* pPtr) {
#define FF_AUTO_FREE [[gnu::cleanup(ffWrapFree)]]
// ptr MUST be a malloc'ed pointer
[[gnu::nonnull(1), nodiscard]]
static inline size_t ffMallocUsableSize(const void* ptr) {
assert(ptr);
#if FF_HAVE_MALLOC_USABLE_SIZE
return malloc_usable_size((void*) ptr);
#elif FF_HAVE_MALLOC_SIZE
+38 -3
View File
@@ -29,10 +29,45 @@ typedef struct FFNetworkingState {
bool tfo; // if true, TCP Fast Open will be attempted first, and fallback to traditional connection if it fails
} FFNetworkingState;
const char* ffNetworkingSendHttpRequest(FFNetworkingState* state, const char* host, const char* path, const char* headers);
const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buffer);
// `headers` is optional and may be null; the other pointer arguments are dereferenced unconditionally.
// Both functions report failure through their return value, which must be checked.
[[gnu::nonnull(1, 2, 4), nodiscard]] const char* ffNetworkingSendHttpRequest(FFNetworkingState* state, const char* host, uint16_t port, const char* path, const char* headers);
[[gnu::nonnull(1, 2), nodiscard]] const char* ffNetworkingRecvHttpResponse(FFNetworkingState* state, FFstrbuf* buffer);
// Case-insensitive header lookup restricted to the header block [0, headerEnd).
// Restricting the range matters because the body may already share the same buffer.
// Returns a pointer to the first character of the value; `valueLen` receives its
// length excluding the terminating CRLF. Returns nullptr when the header is absent.
[[gnu::nonnull(1, 3, 4), nodiscard]] const char* ffNetworkingFindHeader(const char* headers, uint32_t headerEnd, const char* name, uint32_t* valueLen);
// Checks whether a `Transfer-Encoding: chunked` body has been received in full, so that
// framing does not have to rely on the server closing the connection.
// Returns 1 when complete (`consumed` receives the body length including trailers),
// 0 when more data is needed, and -1 when the body is malformed.
// The caller must not wait for a fixed amount of data (e.g. `MSG_WAITALL`) while the
// response length is still unknown, otherwise this check never gets to run.
// Not `pure`: the `strtoul` it calls writes `errno`.
[[gnu::nonnull(1, 3), nodiscard]] int ffNetworkingChunkedComplete(const char* body, uint32_t bodyLen, uint32_t* consumed);
// Decodes a `Transfer-Encoding: chunked` body in place and rewrites the response with a
// `Content-Length` header in place of `Transfer-Encoding`.
[[gnu::nonnull(1), nodiscard]] bool ffNetworkingDecodeChunked(FFstrbuf* buffer, uint32_t headerEnd);
// Result of parsing a `Transfer-Encoding` header value
typedef enum FFNetworkingTransferEncoding {
FF_NETWORKING_TE_NONE, // the value holds no coding at all
FF_NETWORKING_TE_CHUNKED, // exactly `chunked`, the only framing this client decodes
FF_NETWORKING_TE_UNSUPPORTED, // another coding or a chain of them, e.g. `gzip, chunked`
} FFNetworkingTransferEncoding;
// Parses a `Transfer-Encoding` header value. Codings are applied in the order they are
// listed, so `chunked` has to be the last one for the framing to be readable at all --
// and any other coding (e.g. `gzip, chunked`) leaves the payload encoded, which this
// client cannot decode. Only a lone `chunked` is accepted; everything else is reported
// as unsupported so that the caller fails the response instead of returning garbage.
[[gnu::nonnull(1), gnu::pure, nodiscard]] FFNetworkingTransferEncoding ffNetworkingParseTransferEncoding(const char* value, uint32_t valueLen);
#ifdef FF_HAVE_ZLIB
const char* ffNetworkingLoadZlibLibrary(void);
bool ffNetworkingDecompressGzip(FFstrbuf* buffer, char* headerEnd);
[[gnu::nonnull(1, 2), nodiscard]] bool ffNetworkingDecompressGzip(FFstrbuf* buffer, char* headerEnd);
#endif
+16 -10
View File
@@ -89,19 +89,25 @@ typedef struct FFKeyValuePair {
int value;
} FFKeyValuePair;
const char* ffOptionTestPrefix(const char* argumentKey, const char* moduleName);
void ffOptionParseString(const char* argumentKey, const char* value, FFstrbuf* buffer);
[[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) {
// `moduleName` and `argumentKey` are both dereferenced unconditionally; reads no global state, so `pure`
[[gnu::nonnull(1, 2), gnu::pure, nodiscard]] const char* ffOptionTestPrefix(const char* argumentKey, const char* moduleName);
// `value` is optional (null exits with a usage error), `argumentKey` and `buffer` are not
[[gnu::nonnull(1, 3)]] void ffOptionParseString(const char* argumentKey, const char* value, FFstrbuf* buffer);
[[gnu::nonnull(1), nodiscard]] uint32_t ffOptionParseUInt32(const char* argumentKey, const char* value);
[[gnu::nonnull(1), nodiscard]] int32_t ffOptionParseInt32(const char* argumentKey, const char* value);
// `requestedKey` is optional (null exits with a usage error); `pairs` is walked until its null key
[[gnu::nonnull(1, 3), nodiscard]] int ffOptionParseEnum(const char* argumentKey, const char* requestedKey, FFKeyValuePair pairs[]);
// `str` is optional: a null or empty value is reported as `true`
[[gnu::pure, nodiscard]] bool ffOptionParseBoolean(const char* str);
// `value` is optional (a null or empty value is a no-op); `buffer` is not
[[gnu::nonnull(2)]] void ffOptionParseColorNoClear(const char* value, FFstrbuf* buffer);
[[gnu::nonnull(2)]] static inline void ffOptionParseColor(const char* value, FFstrbuf* buffer) {
ffStrbufClear(buffer);
ffOptionParseColorNoClear(value, buffer);
}
static inline void ffOptionInitModuleArg(FFModuleArgs* args, const char* icon) {
// `icon` is optional, `args` is not
[[gnu::nonnull(1)]] static inline void ffOptionInitModuleArg(FFModuleArgs* args, const char* icon) {
ffStrbufInit(&args->key);
ffStrbufInit(&args->keyColor);
ffStrbufInitStatic(&args->keyIcon, icon);
@@ -110,7 +116,7 @@ static inline void ffOptionInitModuleArg(FFModuleArgs* args, const char* icon) {
args->keyWidth = 0;
}
static inline void ffOptionDestroyModuleArg(FFModuleArgs* args) {
[[gnu::nonnull(1)]] static inline void ffOptionDestroyModuleArg(FFModuleArgs* args) {
ffStrbufDestroy(&args->key);
ffStrbufDestroy(&args->keyColor);
ffStrbufDestroy(&args->keyIcon);
+5 -4
View File
@@ -17,8 +17,9 @@ typedef struct FFColorRangeConfig {
#define FF_VERSION_INIT ((FFVersion) { 0 })
void ffParseSemver(FFstrbuf* buffer, const FFstrbuf* major, const FFstrbuf* minor, const FFstrbuf* patch);
void ffParseGTK(FFstrbuf* buffer, const FFstrbuf* gtk2, const FFstrbuf* gtk3, const FFstrbuf* gtk4);
// Every argument is dereferenced unconditionally
[[gnu::nonnull(1, 2, 3, 4)]] void ffParseSemver(FFstrbuf* buffer, const FFstrbuf* major, const FFstrbuf* minor, const FFstrbuf* patch);
[[gnu::nonnull(1, 2, 3, 4)]] void ffParseGTK(FFstrbuf* buffer, const FFstrbuf* gtk2, const FFstrbuf* gtk3, const FFstrbuf* gtk4);
void ffVersionToPretty(const FFVersion* version, FFstrbuf* pretty);
int8_t ffVersionCompare(const FFVersion* version1, const FFVersion* version2);
[[gnu::nonnull(1, 2)]] void ffVersionToPretty(const FFVersion* version, FFstrbuf* pretty);
[[gnu::nonnull(1, 2), gnu::pure, nodiscard]] int8_t ffVersionCompare(const FFVersion* version1, const FFVersion* version2);
+3 -3
View File
@@ -4,8 +4,8 @@
#include "common/strutil.h"
#include "fastfetch_config.h"
const char* ffFindExecutableInPath(const char* name, FFstrbuf* result);
static inline bool ffIsAbsolutePath(const char* path) {
[[gnu::nonnull(1, 2), nodiscard]] const char* ffFindExecutableInPath(const char* name, FFstrbuf* result);
[[gnu::nonnull(1), gnu::pure, nodiscard]] static inline bool ffIsAbsolutePath(const char* path) {
#ifdef _WIN32
return (ffCharIsEnglishAlphabet(path[0]) && path[1] == ':' && (path[2] == '\\' || path[2] == '/')) // drive letter path
|| (path[0] == '\\' && path[1] == '\\'); // UNC path
@@ -34,4 +34,4 @@ ssize_t readlink(const char* path, char* buf, size_t bufsiz);
#define FF_PATH_PKG_BASE "/usr/pkg"
#else
#define FF_PATH_PKG_BASE FASTFETCH_TARGET_DIR_USR
#endif
#endif
+4 -3
View File
@@ -30,13 +30,14 @@ typedef struct FFPercentageModuleConfig {
// [yellow, green): print yellow
// [0, yellow): print red
void ffPercentAppendBar(FFstrbuf* buffer, double percent, FFPercentageModuleConfig config, const FFModuleArgs* module);
void ffPercentAppendNum(FFstrbuf* buffer, double percent, FFPercentageModuleConfig config, bool parentheses, const FFModuleArgs* module);
// `buffer` and `module` are dereferenced unconditionally; `module` carries the key/color formatting
[[gnu::nonnull(1, 4)]] void ffPercentAppendBar(FFstrbuf* buffer, double percent, FFPercentageModuleConfig config, const FFModuleArgs* module);
[[gnu::nonnull(1, 5)]] void ffPercentAppendNum(FFstrbuf* buffer, double percent, FFPercentageModuleConfig config, bool parentheses, const FFModuleArgs* module);
typedef struct yyjson_val yyjson_val;
typedef struct yyjson_mut_doc yyjson_mut_doc;
typedef struct yyjson_mut_val yyjson_mut_val;
bool ffPercentParseCommandOptions(const char* key, const char* subkey, const char* value, FFPercentageModuleConfig* config);
bool ffPercentParseJsonObject(yyjson_val* key, yyjson_val* value, FFPercentageModuleConfig* config);
void ffPercentGenerateJsonConfig(yyjson_mut_doc* doc, yyjson_mut_val* module, FFPercentageModuleConfig config);
[[gnu::nonnull(1, 2)]] void ffPercentGenerateJsonConfig(yyjson_mut_doc* doc, yyjson_mut_val* module, FFPercentageModuleConfig config);
const char* ffPercentParseTypeJsonConfig(yyjson_val* value, FFPercentageTypeFlags* result);
+9 -2
View File
@@ -11,10 +11,17 @@ typedef enum FFPrintType: uint8_t {
FF_PRINT_TYPE_NO_CUSTOM_OUTPUT_FORMAT = 1 << 3, // reserved
} FFPrintType;
// Both `moduleName` and `moduleArgs` are optional and explicitly handled: a null `moduleName` is what
// `--set-keyless` relies on, and a null `moduleArgs` (used by ffPrintError callers) skips the custom
// key entirely. So neither takes `nonnull`.
void ffPrintLogoAndKey(const char* moduleName, uint8_t moduleIndex, const FFModuleArgs* moduleArgs, FFPrintType printType);
// Same for `moduleArgs`; `numArgs` / `arguments` are only read when `moduleArgs` is non-null, so
// `arguments` is not `nonnull(6)` either. At least one caller discards the result, so not `nodiscard`.
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));
[[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);
// `moduleName` / `moduleArgs` are forwarded to ffPrintLogoAndKey, which accepts null for both;
// only `message` is dereferenced here (by `vprintf`).
[[gnu::format(printf, 5, 6), gnu::nonnull(5)]] void ffPrintError(const char* moduleName, uint8_t moduleIndex, const FFModuleArgs* moduleArgs, FFPrintType printType, const char* message, ...);
[[gnu::nonnull(1)]] void ffPrintColor(const FFstrbuf* colorValue);
void ffPrintCharTimes(char c, uint32_t times);
+10 -3
View File
@@ -1,6 +1,7 @@
#pragma once
#include "common/FFstrbuf.h"
#include "common/io.h" // FFNativeFD, ffGetNullFD
#ifndef _WIN32
#include <sys/types.h> // pid_t
@@ -16,12 +17,18 @@ typedef struct FFProcessHandle {
#endif
} FFProcessHandle;
const char* ffProcessSpawn(char* const argv[], bool useStdErr, FFProcessHandle* outHandle);
// `stdinFd` is the fd the child process gets as its stdin. Pass `ffGetNullFD()` to detach it from
// our stdin, or `FF_PROCESS_INHERIT_STDIN` to inherit ours, which is what the helpers below do.
// Detaching matters on Android, where `/system/bin/cmd` forwards its stdin over binder to the
// service: the kernel rejects the whole transaction when that fd is a terminal, and the tool then
// only reports `Failure calling service <name>: Failed transaction`.
#define FF_PROCESS_INHERIT_STDIN ((FFNativeFD) -1)
const char* ffProcessSpawn(char* const argv[], bool useStdErr, FFNativeFD stdinFd, FFProcessHandle* outHandle);
const char* ffProcessReadOutput(FFProcessHandle* handle, FFstrbuf* buffer); // Destroys handle internally
static inline const char* ffProcessAppendStdOut(FFstrbuf* buffer, char* const argv[]) {
FFProcessHandle handle;
const char* error = ffProcessSpawn(argv, false, &handle);
const char* error = ffProcessSpawn(argv, false, FF_PROCESS_INHERIT_STDIN, &handle);
if (error) {
return error;
}
@@ -35,7 +42,7 @@ static inline const char* ffProcessAppendStdOut(FFstrbuf* buffer, char* const ar
static inline const char* ffProcessAppendStdErr(FFstrbuf* buffer, char* const argv[]) {
FFProcessHandle handle;
const char* error = ffProcessSpawn(argv, true, &handle);
const char* error = ffProcessSpawn(argv, true, FF_PROCESS_INHERIT_STDIN, &handle);
if (error) {
return error;
}
+17 -13
View File
@@ -7,41 +7,45 @@ typedef struct FFpropquery {
FFstrbuf* buffer;
} FFpropquery;
bool ffParsePropLines(const char* lines, const char* start, FFstrbuf* buffer);
bool ffParsePropFileValues(const char* filename, uint32_t numQueries, FFpropquery* queries);
bool ffParsePropFileHomeValues(const char* relativeFile, uint32_t numQueries, FFpropquery* queries);
bool ffParsePropFileListValues(const FFlist* list, const char* relativeFile, uint32_t numQueries, FFpropquery* queries);
// These report "was the file/property found", which callers routinely discard, so they are not
// `nodiscard`.
//
// `queries` is only walked when `numQueries > 0`, so it is intentionally not `nonnull(3)`.
[[gnu::nonnull(1, 2, 3)]] bool ffParsePropLines(const char* lines, const char* start, FFstrbuf* buffer);
[[gnu::nonnull(1)]] bool ffParsePropFileValues(const char* filename, uint32_t numQueries, FFpropquery* queries);
[[gnu::nonnull(1)]] bool ffParsePropFileHomeValues(const char* relativeFile, uint32_t numQueries, FFpropquery* queries);
[[gnu::nonnull(1, 2)]] bool ffParsePropFileListValues(const FFlist* list, const char* relativeFile, uint32_t numQueries, FFpropquery* queries);
bool ffParsePropLinePointer(const char** line, const char* start, FFstrbuf* buffer);
[[gnu::nonnull(1, 2, 3)]] bool ffParsePropLinePointer(const char** line, const char* start, FFstrbuf* buffer);
static inline bool ffParsePropLine(const char* line, const char* start, FFstrbuf* buffer) {
[[gnu::nonnull(1, 2, 3)]] static inline bool ffParsePropLine(const char* line, const char* start, FFstrbuf* buffer) {
return ffParsePropLinePointer(&line, start, buffer);
}
static inline bool ffParsePropFile(const char* filename, const char* start, FFstrbuf* buffer) {
[[gnu::nonnull(1, 2, 3)]] static inline bool ffParsePropFile(const char* filename, const char* start, FFstrbuf* buffer) {
return ffParsePropFileValues(filename, 1, (FFpropquery[]) { { start, buffer } });
}
static inline bool ffParsePropFileHome(const char* relativeFile, const char* start, FFstrbuf* buffer) {
[[gnu::nonnull(1, 2, 3)]] static inline bool ffParsePropFileHome(const char* relativeFile, const char* start, FFstrbuf* buffer) {
return ffParsePropFileHomeValues(relativeFile, 1, (FFpropquery[]) { { start, buffer } });
}
static inline bool ffParsePropFileList(const FFlist* list, const char* relativeFile, const char* start, FFstrbuf* buffer) {
[[gnu::nonnull(1, 2, 3, 4)]] static inline bool ffParsePropFileList(const FFlist* list, const char* relativeFile, const char* start, FFstrbuf* buffer) {
return ffParsePropFileListValues(list, relativeFile, 1, (FFpropquery[]) { { start, buffer } });
}
static inline bool ffParsePropFileConfigValues(const char* relativeFile, uint32_t numQueries, FFpropquery* queries) {
[[gnu::nonnull(1)]] static inline bool ffParsePropFileConfigValues(const char* relativeFile, uint32_t numQueries, FFpropquery* queries) {
return ffParsePropFileListValues(&instance.state.platform.configDirs, relativeFile, numQueries, queries);
}
static inline bool ffParsePropFileConfig(const char* relativeFile, const char* start, FFstrbuf* buffer) {
[[gnu::nonnull(1, 2, 3)]] static inline bool ffParsePropFileConfig(const char* relativeFile, const char* start, FFstrbuf* buffer) {
return ffParsePropFileConfigValues(relativeFile, 1, (FFpropquery[]) { { start, buffer } });
}
static inline bool ffParsePropFileDataValues(const char* relativeFile, uint32_t numQueries, FFpropquery* queries) {
[[gnu::nonnull(1)]] static inline bool ffParsePropFileDataValues(const char* relativeFile, uint32_t numQueries, FFpropquery* queries) {
return ffParsePropFileListValues(&instance.state.platform.dataDirs, relativeFile, numQueries, queries);
}
static inline bool ffParsePropFileData(const char* relativeFile, const char* start, FFstrbuf* buffer) {
[[gnu::nonnull(1, 2, 3)]] static inline bool ffParsePropFileData(const char* relativeFile, const char* start, FFstrbuf* buffer) {
return ffParsePropFileDataValues(relativeFile, 1, (FFpropquery[]) { { start, buffer } });
}
+1 -1
View File
@@ -2,4 +2,4 @@
#include "fastfetch.h"
void ffSizeAppendNum(uint64_t bytes, FFstrbuf* result);
[[gnu::nonnull(2)]] void ffSizeAppendNum(uint64_t bytes, FFstrbuf* result);
+8 -6
View File
@@ -2,8 +2,9 @@
#include "common/FFstrbuf.h"
bool ffIsSmbiosValueSet(FFstrbuf* value);
static inline void ffCleanUpSmbiosValue(FFstrbuf* value) {
// Not `pure`: it trims the trailing spaces of `value` before reporting whether it is set
[[gnu::nonnull(1), nodiscard]] bool ffIsSmbiosValueSet(FFstrbuf* value);
[[gnu::nonnull(1)]] static inline void ffCleanUpSmbiosValue(FFstrbuf* value) {
if (!ffIsSmbiosValueSet(value)) {
ffStrbufClear(value);
}
@@ -82,7 +83,8 @@ typedef struct [[gnu::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 */) {
// `start` points into the unformatted string section and is walked with `strlen`, so it may not be null
[[gnu::nonnull(1), gnu::pure, nodiscard]] static inline const char* ffSmbiosLocateString(const char* start, uint8_t index /* start from 1 */) {
if (index == 0 || *start == '\0') {
return nullptr;
}
@@ -94,9 +96,9 @@ static inline const char* ffSmbiosLocateString(const char* start, uint8_t index
typedef const FFSmbiosHeader* FFSmbiosHeaderTable[FF_SMBIOS_TYPE__MAX];
const FFSmbiosHeader* ffSmbiosNextEntry(const FFSmbiosHeader* header);
const FFSmbiosHeaderTable* ffGetSmbiosHeaderTable(void);
[[gnu::nonnull(1), gnu::pure, nodiscard]] const FFSmbiosHeader* ffSmbiosNextEntry(const FFSmbiosHeader* header);
[[nodiscard]] const FFSmbiosHeaderTable* ffGetSmbiosHeaderTable(void);
#ifdef __linux__
bool ffGetSmbiosValue(const char* devicesPath, const char* classPath, FFstrbuf* buffer);
[[gnu::nonnull(1, 2, 3)]] bool ffGetSmbiosValue(const char* devicesPath, const char* classPath, FFstrbuf* buffer);
#endif
+28 -10
View File
@@ -14,6 +14,15 @@ __stdcall char* StrStrIA(const char* lpFirst, const char* lpSrch);
#define FF_STR_INDIR(x) #x
#define FF_STR(x) FF_STR_INDIR(x)
// Everything below is a leaf predicate over the bytes it is given: it reads memory through its
// arguments and nothing else, so `gnu::pure` is accurate. `gnu::const` is deliberately not used --
// these are already `always_inline`, so it would buy no optimization, and it would become a lie the
// day one of them is rewritten around a lookup table.
//
// The `gnu::nonnull` indexes name the arguments that are dereferenced unconditionally. `ffStrSet`
// and `ffStrCopy` are not listed: both handle a null pointer explicitly.
[[nodiscard, gnu::pure]]
static inline bool ffStrSet(const char* str) {
if (str == nullptr) {
return false;
@@ -26,21 +35,22 @@ static inline bool ffStrSet(const char* str) {
return *str != '\0';
}
[[gnu::always_inline]]
[[gnu::always_inline, gnu::nonnull(1, 2), gnu::pure, nodiscard]]
static inline bool ffStrStartsWithIgnCase(const char* str, const char* compareTo) {
return strncasecmp(str, compareTo, strlen(compareTo)) == 0;
}
[[gnu::always_inline]]
[[gnu::always_inline, gnu::nonnull(1, 2), gnu::pure, nodiscard]]
static inline bool ffStrEqualsIgnCase(const char* str, const char* compareTo) {
return strcasecmp(str, compareTo) == 0;
}
[[gnu::always_inline]]
[[gnu::always_inline, gnu::nonnull(1, 2), gnu::pure, nodiscard]]
static inline bool ffStrStartsWith(const char* str, const char* compareTo) {
return strncmp(str, compareTo, strlen(compareTo)) == 0;
}
[[gnu::nonnull(1, 2), gnu::pure, nodiscard]]
static inline bool ffStrEndsWith(const char* str, const char* compareTo) {
size_t strLength = strlen(str);
size_t compareToLength = strlen(compareTo);
@@ -50,6 +60,7 @@ static inline bool ffStrEndsWith(const char* str, const char* compareTo) {
return memcmp(str + strLength - compareToLength, compareTo, compareToLength) == 0;
}
[[gnu::nonnull(1, 2), gnu::pure, nodiscard]]
static inline bool ffStrEndsWithIgnCase(const char* str, const char* compareTo) {
size_t strLength = strlen(str);
size_t compareToLength = strlen(compareTo);
@@ -59,32 +70,32 @@ static inline bool ffStrEndsWithIgnCase(const char* str, const char* compareTo)
return strncasecmp(str + strLength - compareToLength, compareTo, compareToLength) == 0;
}
[[gnu::always_inline]]
[[gnu::always_inline, gnu::nonnull(1, 2), gnu::pure, nodiscard]]
static inline bool ffStrEquals(const char* str, const char* compareTo) {
return strcmp(str, compareTo) == 0;
}
[[gnu::always_inline]]
[[gnu::always_inline, gnu::nonnull(1, 2), gnu::pure, nodiscard]]
static inline bool ffStrContains(const char* str, const char* compareTo) {
return strstr(str, compareTo) != nullptr;
}
[[gnu::always_inline]]
[[gnu::always_inline, gnu::nonnull(1, 2), gnu::pure, nodiscard]]
static inline bool ffStrContainsIgnCase(const char* str, const char* compareTo) {
return strcasestr(str, compareTo) != nullptr;
}
[[gnu::always_inline]]
[[gnu::always_inline, gnu::nonnull(1), gnu::pure, nodiscard]]
static inline bool ffStrContainsC(const char* str, char compareTo) {
return strchr(str, compareTo) != nullptr;
}
[[gnu::always_inline]]
[[gnu::always_inline, gnu::pure, nodiscard]]
static inline bool ffCharIsEnglishAlphabet(char c) {
return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z');
}
[[gnu::always_inline]]
[[gnu::always_inline, gnu::pure, nodiscard]]
static inline bool ffCharIsDigit(char c) {
return '0' <= c && c <= '9';
}
@@ -92,15 +103,19 @@ static inline bool ffCharIsDigit(char c) {
// Parse one UTF-8 character, returning consumed byte count and display width.
// Invalid / incomplete sequence falls back to one-byte width=1.
// If the Unicode codepoint is non-printable, width becomes 0.
// Not `pure`: it stores the width through `width` when that is not null.
[[gnu::nonnull(1)]]
uint8_t ffUtf8CharLenWidth(const char* str, uint32_t length, uint8_t* width);
[[gnu::nonnull(1), gnu::pure, nodiscard]]
uint32_t ffUtf8StrWidth(const char* str, uint32_t length);
[[gnu::always_inline]]
[[gnu::always_inline, gnu::pure, nodiscard]]
static inline bool ffCharIsHexDigit(char c) {
return ffCharIsDigit(c) || ('a' <= c && c <= 'f') || ('A' <= c && c <= 'F');
}
[[gnu::always_inline, gnu::pure, nodiscard]]
static inline int8_t ffHexCharToInt(char c) {
if (ffCharIsDigit(c)) {
return (int8_t) (c - '0');
@@ -114,6 +129,9 @@ static inline int8_t ffHexCharToInt(char c) {
}
// Copies at most (dstBufSiz - 1) bytes from src to dst; dst is always null-terminated
// Returns a pointer to the end of the copy, which callers are free to ignore, so not `nodiscard`.
// Not `pure`: it writes through `dst`. `dst` may be null, `src` may not.
[[gnu::nonnull(2)]]
static inline char* ffStrCopy(char* __restrict__ dst, const char* __restrict__ src, size_t dstBufSiz) {
if (__builtin_expect(dst == nullptr, false) || dstBufSiz == 0) {
return dst;
+5 -4
View File
@@ -5,12 +5,13 @@
#include <sys/types.h>
#include <sys/sysctl.h>
// `result` is always written to, and `propName` is always read by the sysctl wrapper.
#ifdef __OpenBSD__
const char* ffSysctlGetString(int mib1, int mib2, FFstrbuf* result);
[[gnu::nonnull(3)]] const char* ffSysctlGetString(int mib1, int mib2, FFstrbuf* result);
[[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);
[[nodiscard]] int ffSysctlGetInt(const char* propName, int defaultValue);
[[nodiscard]] int64_t ffSysctlGetInt64(const char* propName, int64_t defaultValue);
[[gnu::nonnull(1, 2)]] const char* ffSysctlGetString(const char* propName, FFstrbuf* result);
[[gnu::nonnull(1), nodiscard]] int ffSysctlGetInt(const char* propName, int defaultValue);
[[gnu::nonnull(1), nodiscard]] int64_t ffSysctlGetInt64(const char* propName, int64_t defaultValue);
#endif
+3 -2
View File
@@ -3,7 +3,8 @@
#include "common/parsing.h"
#include "common/option.h"
void ffTempsAppendNum(double celsius, FFstrbuf* buffer, FFColorRangeConfig config, const FFModuleArgs* module);
// `buffer` and `module` are dereferenced unconditionally; `module` carries the key/color formatting
[[gnu::nonnull(2, 4)]] void ffTempsAppendNum(double celsius, FFstrbuf* buffer, FFColorRangeConfig config, const FFModuleArgs* module);
bool ffTempsParseCommandOptions(const char* key, const char* subkey, const char* value, bool* useTemp, FFColorRangeConfig* config);
bool ffTempsParseJsonObject(yyjson_val* key, yyjson_val* value, bool* useTemp, FFColorRangeConfig* config);
void ffTempsGenerateJsonConfig(yyjson_mut_doc* doc, yyjson_mut_val* module, bool temp, FFColorRangeConfig config);
[[gnu::nonnull(1, 2)]] void ffTempsGenerateJsonConfig(yyjson_mut_doc* doc, yyjson_mut_val* module, bool temp, FFColorRangeConfig config);
+11 -8
View File
@@ -11,13 +11,14 @@
#define FF_THREAD_MUTEX_INITIALIZER SRWLOCK_INIT
typedef SRWLOCK FFThreadMutex;
typedef HANDLE FFThreadType;
static inline void ffThreadMutexLock(FFThreadMutex* mutex) {
[[gnu::nonnull(1)]] static inline void ffThreadMutexLock(FFThreadMutex* mutex) {
AcquireSRWLockExclusive(mutex);
}
static inline void ffThreadMutexUnlock(FFThreadMutex* mutex) {
[[gnu::nonnull(1)]] static inline void ffThreadMutexUnlock(FFThreadMutex* mutex) {
ReleaseSRWLockExclusive(mutex);
}
static inline FFThreadType ffThreadCreate(unsigned(__stdcall* func)(void*), void* data) {
// `data` is the thread argument and may be null; `func` may not
[[gnu::nonnull(1)]] static inline FFThreadType ffThreadCreate(unsigned(__stdcall* func)(void*), void* data) {
return (FFThreadType) _beginthreadex(nullptr, 0, func, data, 0, nullptr);
}
#define FF_THREAD_ENTRY_DECL_WRAPPER(fn, paramType) \
@@ -56,23 +57,24 @@ typedef pthread_t FFThreadType;
#include <os/lock.h>
#define FF_THREAD_MUTEX_INITIALIZER OS_UNFAIR_LOCK_INIT
typedef os_unfair_lock FFThreadMutex;
static inline void ffThreadMutexLock(os_unfair_lock* mutex) {
[[gnu::nonnull(1)]] static inline void ffThreadMutexLock(os_unfair_lock* mutex) {
os_unfair_lock_lock(mutex);
}
static inline void ffThreadMutexUnlock(os_unfair_lock* mutex) {
[[gnu::nonnull(1)]] static inline void ffThreadMutexUnlock(os_unfair_lock* mutex) {
os_unfair_lock_unlock(mutex);
}
#else
#define FF_THREAD_MUTEX_INITIALIZER PTHREAD_MUTEX_INITIALIZER
typedef pthread_mutex_t FFThreadMutex;
static inline void ffThreadMutexLock(FFThreadMutex* mutex) {
[[gnu::nonnull(1)]] static inline void ffThreadMutexLock(FFThreadMutex* mutex) {
pthread_mutex_lock(mutex);
}
static inline void ffThreadMutexUnlock(FFThreadMutex* mutex) {
[[gnu::nonnull(1)]] static inline void ffThreadMutexUnlock(FFThreadMutex* mutex) {
pthread_mutex_unlock(mutex);
}
#endif
static inline FFThreadType ffThreadCreate(void* (*func)(void*), void* data) {
// `data` is the thread argument and may be null; `func` may not
[[gnu::nonnull(1)]] static inline FFThreadType ffThreadCreate(void* (*func)(void*), void* data) {
FFThreadType newThread = 0;
pthread_create(&newThread, nullptr, func, data);
return newThread;
@@ -115,6 +117,7 @@ static inline uintptr_t ffThreadGetCurrentId() {
#else // FF_HAVE_THREADS
#define FF_THREAD_MUTEX_INITIALIZER 0
typedef char FFThreadMutex;
// The stubs deliberately ignore their argument, so no `nonnull` here
static inline void ffThreadMutexLock([[maybe_unused]] FFThreadMutex* mutex) {}
static inline void ffThreadMutexUnlock([[maybe_unused]] FFThreadMutex* mutex) {}
#define FF_THREAD_ENTRY_DECL_WRAPPER(fn, paramType)
+3 -2
View File
@@ -3,9 +3,10 @@
#include <stdint.h>
#if FF_ENABLE_WCWIDTH
int mk_wcwidth(uint32_t wc);
// A pure table lookup: the width depends only on the code point
[[gnu::pure, nodiscard]] int mk_wcwidth(uint32_t wc);
#else
static inline int mk_wcwidth(uint32_t wc) {
[[gnu::pure, nodiscard]] static inline int mk_wcwidth(uint32_t wc) {
(void) wc;
return 1;
}
+40 -16
View File
@@ -13,6 +13,8 @@ enum {
SystemLogicalProcessorAndGroupInformation = 107,
SystemBasicPerformanceInformation = 123,
SystemSecureBootInformation = 146,
SystemBasicProcessInformation = 252,
SystemHandleCountInformation = 253,
};
typedef struct _PROCESSOR_POWER_INFORMATION {
@@ -206,6 +208,20 @@ typedef struct _SYSTEM_BASIC_PERFORMANCE_INFORMATION {
SIZE_T PeakCommitment;
} SYSTEM_BASIC_PERFORMANCE_INFORMATION, *PSYSTEM_BASIC_PERFORMANCE_INFORMATION;
typedef struct _SYSTEM_BASICPROCESS_INFORMATION {
ULONG NextEntryOffset;
HANDLE UniqueProcessId;
HANDLE InheritedFromUniqueProcessId;
ULONG64 SequenceNumber;
UNICODE_STRING ImageName;
} SYSTEM_BASICPROCESS_INFORMATION, *PSYSTEM_BASICPROCESS_INFORMATION;
typedef struct _SYSTEM_HANDLECOUNT_INFORMATION {
ULONG ProcessCount;
ULONG ThreadCount;
ULONG HandleCount;
} SYSTEM_HANDLECOUNT_INFORMATION, *PSYSTEM_HANDLECOUNT_INFORMATION;
NTSYSAPI NTSTATUS NTAPI NtDelayExecution(_In_ BOOLEAN Alertable, _In_ PLARGE_INTEGER DelayInterval);
/**
@@ -691,15 +707,19 @@ static inline uint64_t ffKSystemTimeToUInt64(const volatile KSYSTEM_TIME* pTime)
static inline bool ffIsWindows10OrGreater() {
#if FF_WIN81_COMPAT
return SharedUserData->NtMajorVersion >= 10;
return SharedUserData->NtBuildNumber >= 10240;
#else
return true;
#endif
}
static inline bool ffIsWindows11OrGreater() {
return SharedUserData->NtMajorVersion > 10 ||
(SharedUserData->NtMajorVersion == 10 && SharedUserData->NtBuildNumber >= 22000);
return SharedUserData->NtBuildNumber >= 22000;
}
static inline bool ffIsSystemBasicProcessInfoAvailable() { // Includes HandleCountInformation, which was added together
// https://learn.microsoft.com/en-us/windows/win32/api/winternl/nf-winternl-ntquerysysteminformation#systembasicprocessinformation
return SharedUserData->NtBuildNumber >= 26200; // MSDN says it was added in 26100.4770; ntdoc says 25H2
}
NTSYSAPI NTSTATUS NTAPI NtOpenProcessToken(
@@ -1287,19 +1307,23 @@ typedef struct _KEY_BASIC_INFORMATION {
_Field_size_bytes_(NameLength) WCHAR Name[]; // The name of the registry key. This string is not null-terminated.
} KEY_BASIC_INFORMATION, *PKEY_BASIC_INFORMATION;
typedef struct _KEY_FULL_INFORMATION {
LARGE_INTEGER LastWriteTime;
ULONG TitleIndex;
ULONG ClassOffset;
ULONG ClassLength;
ULONG SubKeys;
ULONG MaxNameLength;
ULONG MaxClassLength;
ULONG Values;
ULONG MaxValueNameLength;
ULONG MaxValueDataLength;
WCHAR Class[];
} KEY_FULL_INFORMATION, *PKEY_FULL_INFORMATION;
typedef struct _KEY_CACHED_INFORMATION {
LARGE_INTEGER LastWriteTime; // Number of 100-nanosecond intervals since this key or any of its values changed.
ULONG TitleIndex; // Reserved // A legacy field originally intended for use with localization such as an index of a resource table.
ULONG SubKeys; // The number of subkeys for a key.
ULONG MaxNameLen; // The maximum length, in bytes, of a subkey name.
ULONG Values; // The number of value entries.
ULONG MaxValueNameLen; // The maximum length, in bytes, of a value entry name.
ULONG MaxValueDataLen; // The maximum length, in bytes, of a value entry data field.
ULONG NameLength; // Size, in bytes, of the key's own (leaf) name, without the terminator. The name itself is not stored.
} KEY_CACHED_INFORMATION, *PKEY_CACHED_INFORMATION;
// 36 bytes of members, but LARGE_INTEGER makes the struct 8-byte aligned, and that is exactly what
// the kernel demands: a 36-byte buffer is rejected with STATUS_BUFFER_TOO_SMALL (measured).
// The kernel writes all 40 bytes -- the 4 padding bytes included, zeroed -- and reports
// ResultLength = 40 whatever size you pass, so a larger buffer buys nothing (measured 40..4096).
// This is the only information class that never appends a string: NameLength is the length of the
// key's own (leaf) name in bytes without the terminator, and the name itself is not returned.
static_assert(sizeof(KEY_CACHED_INFORMATION) == 40, "KEY_CACHED_INFORMATION should be 40 bytes");
NTSYSAPI NTSTATUS NTAPI NtQueryKey(
_In_ HANDLE KeyHandle,
+16 -8
View File
@@ -355,6 +355,10 @@ bool ffRegGetSubKey(HANDLE hKey, uint32_t index, FFstrbuf* result, FFstrbuf* err
ULONG bufSize = (ULONG) sizeof(buffer);
KEY_BASIC_INFORMATION* keyInfo = (KEY_BASIC_INFORMATION*) buffer;
// Every failure mode fails NT_SUCCESS, and the read below depends on that: on a too-small buffer
// the kernel returns STATUS_BUFFER_OVERFLOW, writes the *full* NameLength but copies only part of
// the name (measured), so treating that status as success would read past what was written.
// The longest name the CM accepts, 255 characters, still fits: 255 * 2 + 16 <= sizeof(buffer).
if (!NT_SUCCESS(NtEnumerateKey(hKey, index, KeyBasicInformation, keyInfo, bufSize, &bufSize))) {
FF_DEBUG("NtEnumerateKey(hKey=%p, index=%u) failed", hKey, (unsigned) index);
if (error) {
@@ -367,22 +371,26 @@ bool ffRegGetSubKey(HANDLE hKey, uint32_t index, FFstrbuf* result, FFstrbuf* err
return true;
}
bool ffRegGetNSubKeys(HANDLE hKey, uint32_t* result, FFstrbuf* error) {
// Reads the counters the key object already caches. KeyFullInformation would return the same numbers
// but also marshals the key's class string out; measured per query on the ARP and MSIX keys:
// 837 ns vs 895 ns (interleaved, 200k queries each). The open dominates the total -- 22.10 us vs
// 22.40 us for open + query -- so this is a small win, not a big one.
//
// The kernel writes exactly sizeof(KEY_CACHED_INFORMATION) bytes and rejects a smaller buffer with
// STATUS_BUFFER_TOO_SMALL without writing anything, so pass a whole KEY_CACHED_INFORMATION.
bool ffRegQueryKey(HANDLE hKey, KEY_CACHED_INFORMATION* result, FFstrbuf* error) {
assert(hKey);
assert(result);
alignas(KEY_FULL_INFORMATION) uint8_t buffer[sizeof(KEY_FULL_INFORMATION) + MAX_PATH * sizeof(wchar_t)];
ULONG bufSize = sizeof(buffer);
KEY_FULL_INFORMATION* keyInfo = (KEY_FULL_INFORMATION*) buffer;
ULONG bufSize = (ULONG) sizeof(*result);
if (!NT_SUCCESS(NtQueryKey(hKey, KeyFullInformation, keyInfo, bufSize, &bufSize))) {
FF_DEBUG("NtQueryKey(hKey=%p, KeyFullInformation) failed", hKey);
if (!NT_SUCCESS(NtQueryKey(hKey, KeyCachedInformation, result, bufSize, &bufSize))) {
FF_DEBUG("NtQueryKey(hKey=%p, KeyCachedInformation) failed", hKey);
if (error) {
ffStrbufAppendF(error, "NtQueryKey(hKey=%p, KeyFullInformation, keyInfo) failed", hKey);
ffStrbufAppendF(error, "NtQueryKey(hKey=%p, KeyCachedInformation, keyInfo) failed", hKey);
}
return false;
}
*result = (uint32_t) keyInfo->SubKeys;
return true;
}

Some files were not shown because too many files have changed in this diff Show More