├── .github └── workflows │ └── ci.yml ├── .gitignore ├── CHANGELOG.md ├── Cargo.lock ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── crates ├── rlsf │ ├── CHANGELOG.md │ ├── Cargo.toml │ ├── README.md │ ├── src │ │ ├── flex.rs │ │ ├── flex │ │ │ └── tests.rs │ │ ├── global.rs │ │ ├── global │ │ │ ├── tests.rs │ │ │ ├── unix.rs │ │ │ └── wasm32.rs │ │ ├── int.rs │ │ ├── lib.rs │ │ ├── tests.rs │ │ ├── tlsf.rs │ │ ├── tlsf │ │ │ └── tests.rs │ │ └── utils.rs │ └── tests │ │ └── global.rs ├── rlsf_benchmark_farcri │ ├── Cargo.toml │ ├── benches │ │ ├── stress.rs │ │ ├── stress_common.rs │ │ └── stress_wee.rs │ └── rust-toolchain └── rlsf_override │ ├── Cargo.toml │ ├── README.md │ ├── src │ └── lib.rs │ └── tests │ └── overridden.rs ├── rust-toolchain └── scripts └── update-readme.sh /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | on: [push, pull_request] 2 | 3 | name: CI 4 | 5 | jobs: 6 | clippy: 7 | name: Clippy 8 | runs-on: ubuntu-24.04 9 | timeout-minutes: 10 10 | steps: 11 | - uses: actions/checkout@v2 12 | - uses: actions-rs/toolchain@v1 13 | with: 14 | profile: minimal 15 | components: clippy 16 | - name: cargo clippy 17 | uses: actions-rs/clippy-check@v1.0.7 18 | with: 19 | token: ${{ secrets.GITHUB_TOKEN }} 20 | args: -p rlsf 21 | 22 | test: 23 | name: Test 24 | runs-on: ubuntu-24.04 25 | timeout-minutes: 20 26 | steps: 27 | - uses: actions/checkout@v2 28 | - uses: actions-rs/toolchain@v1 29 | with: 30 | profile: minimal 31 | components: clippy 32 | - name: Install Dependencies 33 | run: | 34 | rustup target add wasm32-wasi 35 | - name: Install and configure the WebAssembly runtime 36 | run: | 37 | curl https://wasmtime.dev/install.sh -sSf | bash 38 | mkdir .cargo 39 | echo "[target.wasm32-wasi]" > .cargo/config.toml 40 | echo "runner = \"$HOME/.wasmtime/bin/wasmtime --\"" >> .cargo/config.toml 41 | 42 | - name: cargo test 43 | uses: actions-rs/cargo@v1 44 | with: 45 | command: test 46 | args: -p rlsf 47 | - name: cargo test --features std 48 | uses: actions-rs/cargo@v1 49 | with: 50 | command: test 51 | args: -p rlsf --features std 52 | - name: cargo test --features std,unstable 53 | uses: actions-rs/cargo@v1 54 | with: 55 | command: test 56 | args: -p rlsf --features std,unstable 57 | 58 | - name: cargo test --target wasm32-wasi 59 | uses: actions-rs/cargo@v1 60 | with: 61 | command: test 62 | args: --target wasm32-wasi -p rlsf 63 | - name: cargo test --target wasm32-wasi --features std 64 | uses: actions-rs/cargo@v1 65 | with: 66 | command: test 67 | args: --target wasm32-wasi -p rlsf --features std 68 | 69 | - name: Override the test enviroment's memory allocator 70 | run: | 71 | cargo build -p rlsf_override --release 72 | stat "`pwd`/target/release/librlsf_override.so" 73 | echo "LD_PRELOAD=`pwd`/target/release/librlsf_override.so" >> $GITHUB_ENV 74 | 75 | - name: cargo test --target wasm32-wasi (with rlsf_override) 76 | uses: actions-rs/cargo@v1 77 | with: 78 | command: test 79 | args: --target wasm32-wasi -p rlsf nonexistent 80 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | .DS_Store 3 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) 6 | and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html). 7 | 8 | ## [Unreleased] 9 | 10 | ## [0.2.1] - 2023-02-17 11 | 12 | ### Fixed 13 | 14 | - Bump `svgbobdoc` to `^0.3` to address a future-incompat report 15 | [rust-lang/rust#79813](https://github.com/rust-lang/rust/issues/79813) 16 | - Don't enable the default features of 17 | [`const-default`](https://crates.io/crates/const-default/1.0.0) so that it 18 | can compile for targets with no atomics support 19 | 20 | ## [0.2.0] - 2022-08-31 21 | 22 | ### Changed 23 | 24 | - **Breaking:** Raised the minimum supported Rust version to 1.61 25 | - Documentation improvements 26 | - Descriptive compile-time panic messages 27 | 28 | ### Added 29 | 30 | - **Breaking:** `CAlloc::allocation_usable_size` 31 | - `{Global,}Tlsf::new` 32 | - `FlexTlsf::new` as a `const fn` 33 | - `ConstDefault` implementation for `Tlsf` 34 | - `Tlsf::iter_blocks` (unstable), which lets you iterate through memory blocks for diagnostic purposes. 35 | - `{Flex,}Tlsf::allocation_usable_size` (unstable) 36 | 37 | ### Removed 38 | 39 | - **Breaking:** `{Global,}Tlsf::INIT` 40 | - **Breaking:** `Init` (superseded by `ConstDefault` from [`const-default`](https://crates.io/crates/const-default/1.0.0)) 41 | 42 | ## [0.1.2] - 2021-05-30 43 | 44 | - Performance and code size optimization 45 | - **Added:** `GlobalTlsf` now provides a `malloc`-compatible interface. 46 | - **Fixed:** Raised the version requirement of `libc` to 0.2.56, where `MAP_FIXED_NOREPLACE` was added. 47 | 48 | ## [0.1.1] - 2021-05-23 49 | 50 | - **Added:** `GlobalTlsf` now supports POSIX-compliant systems (`cfg(unix)`). 51 | - **Fixed:** Addressed a bug in `Tlsf::reallocate` that caused an incorrect amount of data to be copied (possibly corrupting memory or crashing the program) during a moving reallocation. 52 | 53 | ## 0.1.0 - 2021-05-21 54 | 55 | - Initial release. 56 | 57 | [Unreleased]: https://github.com/yvt/rlsf/compare/0.2.1...HEAD 58 | [0.2.1]: https://github.com/yvt/rlsf/compare/0.2.0...0.2.1 59 | [0.2.0]: https://github.com/yvt/rlsf/compare/0.1.2...0.2.0 60 | [0.1.2]: https://github.com/yvt/rlsf/compare/0.1.1...0.1.2 61 | [0.1.1]: https://github.com/yvt/rlsf/compare/0.1.0...0.1.1 62 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 3 4 | 5 | [[package]] 6 | name = "aho-corasick" 7 | version = "0.7.18" 8 | source = "registry+https://github.com/rust-lang/crates.io-index" 9 | checksum = "1e37cfd5e7657ada45f742d6e99ca5788580b5c529dc78faf11ece6dc702656f" 10 | dependencies = [ 11 | "memchr", 12 | ] 13 | 14 | [[package]] 15 | name = "ansi_term" 16 | version = "0.11.0" 17 | source = "registry+https://github.com/rust-lang/crates.io-index" 18 | checksum = "ee49baf6cb617b853aa8d93bf420db2383fab46d314482ca2803b40d5fde979b" 19 | dependencies = [ 20 | "winapi", 21 | ] 22 | 23 | [[package]] 24 | name = "approx" 25 | version = "0.5.1" 26 | source = "registry+https://github.com/rust-lang/crates.io-index" 27 | checksum = "cab112f0a86d568ea0e627cc1d6be74a1e9cd55214684db5561995f6dad897c6" 28 | dependencies = [ 29 | "num-traits", 30 | ] 31 | 32 | [[package]] 33 | name = "arrayvec" 34 | version = "0.7.0" 35 | source = "registry+https://github.com/rust-lang/crates.io-index" 36 | checksum = "5a2f58b0bb10c380af2b26e57212856b8c9a59e0925b4c20f4a174a49734eaf7" 37 | 38 | [[package]] 39 | name = "as-slice" 40 | version = "0.1.5" 41 | source = "registry+https://github.com/rust-lang/crates.io-index" 42 | checksum = "45403b49e3954a4b8428a0ac21a4b7afadccf92bfd96273f1a58cd4812496ae0" 43 | dependencies = [ 44 | "generic-array 0.12.4", 45 | "generic-array 0.13.3", 46 | "generic-array 0.14.4", 47 | "stable_deref_trait", 48 | ] 49 | 50 | [[package]] 51 | name = "atty" 52 | version = "0.2.14" 53 | source = "registry+https://github.com/rust-lang/crates.io-index" 54 | checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" 55 | dependencies = [ 56 | "hermit-abi", 57 | "libc", 58 | "winapi", 59 | ] 60 | 61 | [[package]] 62 | name = "autocfg" 63 | version = "1.4.0" 64 | source = "registry+https://github.com/rust-lang/crates.io-index" 65 | checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26" 66 | 67 | [[package]] 68 | name = "base64" 69 | version = "0.12.3" 70 | source = "registry+https://github.com/rust-lang/crates.io-index" 71 | checksum = "3441f0f7b02788e948e47f457ca01f1d7e6d92c693bc132c22b087d3141c03ff" 72 | 73 | [[package]] 74 | name = "bindgen" 75 | version = "0.56.0" 76 | source = "registry+https://github.com/rust-lang/crates.io-index" 77 | checksum = "2da379dbebc0b76ef63ca68d8fc6e71c0f13e59432e0987e508c1820e6ab5239" 78 | dependencies = [ 79 | "bitflags", 80 | "cexpr", 81 | "clang-sys", 82 | "clap", 83 | "env_logger 0.8.3", 84 | "lazy_static", 85 | "lazycell", 86 | "log", 87 | "peeking_take_while", 88 | "proc-macro2", 89 | "quote", 90 | "regex", 91 | "rustc-hash", 92 | "shlex", 93 | "which", 94 | ] 95 | 96 | [[package]] 97 | name = "bitflags" 98 | version = "1.2.1" 99 | source = "registry+https://github.com/rust-lang/crates.io-index" 100 | checksum = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693" 101 | 102 | [[package]] 103 | name = "bstr" 104 | version = "1.11.3" 105 | source = "registry+https://github.com/rust-lang/crates.io-index" 106 | checksum = "531a9155a481e2ee699d4f98f43c0ca4ff8ee1bfd55c31e9e98fb29d2b176fe0" 107 | dependencies = [ 108 | "memchr", 109 | "regex-automata", 110 | "serde", 111 | ] 112 | 113 | [[package]] 114 | name = "buddy-alloc" 115 | version = "0.4.1" 116 | source = "registry+https://github.com/rust-lang/crates.io-index" 117 | checksum = "8ff9f338986406db85e2b5deb40a9255b796ca03a194c7457403d215173f3fd5" 118 | 119 | [[package]] 120 | name = "bytemuck" 121 | version = "1.22.0" 122 | source = "registry+https://github.com/rust-lang/crates.io-index" 123 | checksum = "b6b1fc10dbac614ebc03540c9dbd60e83887fda27794998c6528f1782047d540" 124 | 125 | [[package]] 126 | name = "byteorder" 127 | version = "1.4.3" 128 | source = "registry+https://github.com/rust-lang/crates.io-index" 129 | checksum = "14c189c53d098945499cdfa7ecc63567cf3886b3332b312a5b4585d8d3a6a610" 130 | 131 | [[package]] 132 | name = "bzip2" 133 | version = "0.4.2" 134 | source = "registry+https://github.com/rust-lang/crates.io-index" 135 | checksum = "abf8012c8a15d5df745fcf258d93e6149dcf102882c8d8702d9cff778eab43a8" 136 | dependencies = [ 137 | "bzip2-sys", 138 | "libc", 139 | ] 140 | 141 | [[package]] 142 | name = "bzip2-sys" 143 | version = "0.1.10+1.0.8" 144 | source = "registry+https://github.com/rust-lang/crates.io-index" 145 | checksum = "17fa3d1ac1ca21c5c4e36a97f3c3eb25084576f6fc47bf0139c1123434216c6c" 146 | dependencies = [ 147 | "cc", 148 | "libc", 149 | "pkg-config", 150 | ] 151 | 152 | [[package]] 153 | name = "cc" 154 | version = "1.0.68" 155 | source = "registry+https://github.com/rust-lang/crates.io-index" 156 | checksum = "4a72c244c1ff497a746a7e1fb3d14bd08420ecda70c8f25c7112f2781652d787" 157 | 158 | [[package]] 159 | name = "cexpr" 160 | version = "0.4.0" 161 | source = "registry+https://github.com/rust-lang/crates.io-index" 162 | checksum = "f4aedb84272dbe89af497cf81375129abda4fc0a9e7c5d317498c15cc30c0d27" 163 | dependencies = [ 164 | "nom", 165 | ] 166 | 167 | [[package]] 168 | name = "cfg-if" 169 | version = "0.1.10" 170 | source = "registry+https://github.com/rust-lang/crates.io-index" 171 | checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" 172 | 173 | [[package]] 174 | name = "cfg-if" 175 | version = "1.0.0" 176 | source = "registry+https://github.com/rust-lang/crates.io-index" 177 | checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" 178 | 179 | [[package]] 180 | name = "clang-sys" 181 | version = "1.2.0" 182 | source = "registry+https://github.com/rust-lang/crates.io-index" 183 | checksum = "853eda514c284c2287f4bf20ae614f8781f40a81d32ecda6e91449304dfe077c" 184 | dependencies = [ 185 | "glob", 186 | "libc", 187 | "libloading", 188 | ] 189 | 190 | [[package]] 191 | name = "clap" 192 | version = "2.33.3" 193 | source = "registry+https://github.com/rust-lang/crates.io-index" 194 | checksum = "37e58ac78573c40708d45522f0d80fa2f01cc4f9b4e2bf749807255454312002" 195 | dependencies = [ 196 | "ansi_term", 197 | "atty", 198 | "bitflags", 199 | "strsim", 200 | "textwrap", 201 | "unicode-width", 202 | "vec_map", 203 | ] 204 | 205 | [[package]] 206 | name = "const-default" 207 | version = "1.0.0" 208 | source = "registry+https://github.com/rust-lang/crates.io-index" 209 | checksum = "0b396d1f76d455557e1218ec8066ae14bba60b4b36ecd55577ba979f5db7ecaa" 210 | 211 | [[package]] 212 | name = "cryo" 213 | version = "0.2.2" 214 | source = "registry+https://github.com/rust-lang/crates.io-index" 215 | checksum = "e1a6f2e8039cd08acb3711f8f89a9bfb0831496233fa872d9c013072c1f0da3e" 216 | dependencies = [ 217 | "pin-utils", 218 | "stable_deref_trait", 219 | ] 220 | 221 | [[package]] 222 | name = "dlmalloc" 223 | version = "0.2.1" 224 | source = "registry+https://github.com/rust-lang/crates.io-index" 225 | checksum = "332570860c2edf2d57914987bf9e24835425f75825086b6ba7d1e6a3e4f1f254" 226 | dependencies = [ 227 | "libc", 228 | ] 229 | 230 | [[package]] 231 | name = "doc-comment" 232 | version = "0.3.3" 233 | source = "registry+https://github.com/rust-lang/crates.io-index" 234 | checksum = "fea41bba32d969b513997752735605054bc0dfa92b4c56bf1189f2e174be7a10" 235 | 236 | [[package]] 237 | name = "downcast-rs" 238 | version = "1.2.1" 239 | source = "registry+https://github.com/rust-lang/crates.io-index" 240 | checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" 241 | 242 | [[package]] 243 | name = "either" 244 | version = "1.15.0" 245 | source = "registry+https://github.com/rust-lang/crates.io-index" 246 | checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" 247 | 248 | [[package]] 249 | name = "env_logger" 250 | version = "0.7.1" 251 | source = "registry+https://github.com/rust-lang/crates.io-index" 252 | checksum = "44533bbbb3bb3c1fa17d9f2e4e38bbbaf8396ba82193c4cb1b6445d711445d36" 253 | dependencies = [ 254 | "atty", 255 | "humantime 1.3.0", 256 | "log", 257 | "regex", 258 | "termcolor", 259 | ] 260 | 261 | [[package]] 262 | name = "env_logger" 263 | version = "0.8.3" 264 | source = "registry+https://github.com/rust-lang/crates.io-index" 265 | checksum = "17392a012ea30ef05a610aa97dfb49496e71c9f676b27879922ea5bdf60d9d3f" 266 | dependencies = [ 267 | "atty", 268 | "humantime 2.1.0", 269 | "log", 270 | "regex", 271 | "termcolor", 272 | ] 273 | 274 | [[package]] 275 | name = "farcri" 276 | version = "0.1.0" 277 | source = "git+https://github.com/yvt/farcri-rs.git?rev=dbd6544d0411b8751871a6315ba4d8a08ca52d07#dbd6544d0411b8751871a6315ba4d8a08ca52d07" 278 | dependencies = [ 279 | "arrayvec", 280 | "cryo", 281 | "log", 282 | "serde", 283 | "serde-json-core", 284 | "serde_cbor", 285 | "tokenlock", 286 | ] 287 | 288 | [[package]] 289 | name = "generic-array" 290 | version = "0.12.4" 291 | source = "registry+https://github.com/rust-lang/crates.io-index" 292 | checksum = "ffdf9f34f1447443d37393cc6c2b8313aebddcd96906caf34e54c68d8e57d7bd" 293 | dependencies = [ 294 | "typenum", 295 | ] 296 | 297 | [[package]] 298 | name = "generic-array" 299 | version = "0.13.3" 300 | source = "registry+https://github.com/rust-lang/crates.io-index" 301 | checksum = "f797e67af32588215eaaab8327027ee8e71b9dd0b2b26996aedf20c030fce309" 302 | dependencies = [ 303 | "typenum", 304 | ] 305 | 306 | [[package]] 307 | name = "generic-array" 308 | version = "0.14.4" 309 | source = "registry+https://github.com/rust-lang/crates.io-index" 310 | checksum = "501466ecc8a30d1d3b7fc9229b122b2ce8ed6e9d9223f1138d4babb253e51817" 311 | dependencies = [ 312 | "typenum", 313 | "version_check", 314 | ] 315 | 316 | [[package]] 317 | name = "getrandom" 318 | version = "0.1.16" 319 | source = "registry+https://github.com/rust-lang/crates.io-index" 320 | checksum = "8fc3cb4d91f53b50155bdcfd23f6a4c39ae1969c2ae85982b135750cccaf5fce" 321 | dependencies = [ 322 | "cfg-if 1.0.0", 323 | "libc", 324 | "wasi 0.9.0+wasi-snapshot-preview1", 325 | ] 326 | 327 | [[package]] 328 | name = "getrandom" 329 | version = "0.2.15" 330 | source = "registry+https://github.com/rust-lang/crates.io-index" 331 | checksum = "c4567c8db10ae91089c99af84c68c38da3ec2f087c3f82960bcdbf3656b6f4d7" 332 | dependencies = [ 333 | "cfg-if 1.0.0", 334 | "libc", 335 | "wasi 0.11.0+wasi-snapshot-preview1", 336 | ] 337 | 338 | [[package]] 339 | name = "glob" 340 | version = "0.3.0" 341 | source = "registry+https://github.com/rust-lang/crates.io-index" 342 | checksum = "9b919933a397b79c37e33b77bb2aa3dc8eb6e165ad809e58ff75bc7db2e34574" 343 | 344 | [[package]] 345 | name = "half" 346 | version = "1.7.1" 347 | source = "registry+https://github.com/rust-lang/crates.io-index" 348 | checksum = "62aca2aba2d62b4a7f5b33f3712cb1b0692779a56fb510499d5c0aa594daeaf3" 349 | 350 | [[package]] 351 | name = "hash32" 352 | version = "0.1.1" 353 | source = "registry+https://github.com/rust-lang/crates.io-index" 354 | checksum = "d4041af86e63ac4298ce40e5cca669066e75b6f1aa3390fe2561ffa5e1d9f4cc" 355 | dependencies = [ 356 | "byteorder", 357 | ] 358 | 359 | [[package]] 360 | name = "heapless" 361 | version = "0.6.1" 362 | source = "registry+https://github.com/rust-lang/crates.io-index" 363 | checksum = "634bd4d29cbf24424d0a4bfcbf80c6960129dc24424752a7d1d1390607023422" 364 | dependencies = [ 365 | "as-slice", 366 | "generic-array 0.14.4", 367 | "hash32", 368 | "stable_deref_trait", 369 | ] 370 | 371 | [[package]] 372 | name = "hermit-abi" 373 | version = "0.1.18" 374 | source = "registry+https://github.com/rust-lang/crates.io-index" 375 | checksum = "322f4de77956e22ed0e5032c359a0f1273f1f7f0d79bfa3b8ffbc730d7fbcc5c" 376 | dependencies = [ 377 | "libc", 378 | ] 379 | 380 | [[package]] 381 | name = "humantime" 382 | version = "1.3.0" 383 | source = "registry+https://github.com/rust-lang/crates.io-index" 384 | checksum = "df004cfca50ef23c36850aaaa59ad52cc70d0e90243c3c7737a4dd32dc7a3c4f" 385 | dependencies = [ 386 | "quick-error", 387 | ] 388 | 389 | [[package]] 390 | name = "humantime" 391 | version = "2.1.0" 392 | source = "registry+https://github.com/rust-lang/crates.io-index" 393 | checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4" 394 | 395 | [[package]] 396 | name = "itertools" 397 | version = "0.10.5" 398 | source = "registry+https://github.com/rust-lang/crates.io-index" 399 | checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473" 400 | dependencies = [ 401 | "either", 402 | ] 403 | 404 | [[package]] 405 | name = "json" 406 | version = "0.12.4" 407 | source = "registry+https://github.com/rust-lang/crates.io-index" 408 | checksum = "078e285eafdfb6c4b434e0d31e8cfcb5115b651496faca5749b88fafd4f23bfd" 409 | 410 | [[package]] 411 | name = "jss" 412 | version = "0.5.1" 413 | source = "registry+https://github.com/rust-lang/crates.io-index" 414 | checksum = "5583269706df2d70b35edfd48e9bf5613308a7d61ea13f5618bc04058b9ffdd0" 415 | dependencies = [ 416 | "json", 417 | "log", 418 | "once_cell", 419 | "phf", 420 | ] 421 | 422 | [[package]] 423 | name = "lazy_static" 424 | version = "1.4.0" 425 | source = "registry+https://github.com/rust-lang/crates.io-index" 426 | checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" 427 | 428 | [[package]] 429 | name = "lazycell" 430 | version = "1.3.0" 431 | source = "registry+https://github.com/rust-lang/crates.io-index" 432 | checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55" 433 | 434 | [[package]] 435 | name = "libc" 436 | version = "0.2.160" 437 | source = "registry+https://github.com/rust-lang/crates.io-index" 438 | checksum = "f0b21006cd1874ae9e650973c565615676dc4a274c965bb0a73796dac838ce4f" 439 | 440 | [[package]] 441 | name = "libloading" 442 | version = "0.7.0" 443 | source = "registry+https://github.com/rust-lang/crates.io-index" 444 | checksum = "6f84d96438c15fcd6c3f244c8fce01d1e2b9c6b5623e9c711dc9286d8fc92d6a" 445 | dependencies = [ 446 | "cfg-if 1.0.0", 447 | "winapi", 448 | ] 449 | 450 | [[package]] 451 | name = "libm" 452 | version = "0.2.11" 453 | source = "registry+https://github.com/rust-lang/crates.io-index" 454 | checksum = "8355be11b20d696c8f18f6cc018c4e372165b1fa8126cef092399c9951984ffa" 455 | 456 | [[package]] 457 | name = "linked_list_allocator" 458 | version = "0.8.11" 459 | source = "registry+https://github.com/rust-lang/crates.io-index" 460 | checksum = "822add9edb1860698b79522510da17bef885171f75aa395cff099d770c609c24" 461 | dependencies = [ 462 | "spinning_top", 463 | ] 464 | 465 | [[package]] 466 | name = "lock_api" 467 | version = "0.3.4" 468 | source = "registry+https://github.com/rust-lang/crates.io-index" 469 | checksum = "c4da24a77a3d8a6d4862d95f72e6fdb9c09a643ecdb402d754004a557f2bec75" 470 | dependencies = [ 471 | "scopeguard", 472 | ] 473 | 474 | [[package]] 475 | name = "log" 476 | version = "0.4.14" 477 | source = "registry+https://github.com/rust-lang/crates.io-index" 478 | checksum = "51b9bbe6c47d51fc3e1a9b945965946b4c44142ab8792c50835a980d362c2710" 479 | dependencies = [ 480 | "cfg-if 1.0.0", 481 | ] 482 | 483 | [[package]] 484 | name = "matrixmultiply" 485 | version = "0.3.9" 486 | source = "registry+https://github.com/rust-lang/crates.io-index" 487 | checksum = "9380b911e3e96d10c1f415da0876389aaf1b56759054eeb0de7df940c456ba1a" 488 | dependencies = [ 489 | "autocfg", 490 | "rawpointer", 491 | ] 492 | 493 | [[package]] 494 | name = "memchr" 495 | version = "2.7.4" 496 | source = "registry+https://github.com/rust-lang/crates.io-index" 497 | checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" 498 | 499 | [[package]] 500 | name = "memory_units" 501 | version = "0.4.0" 502 | source = "registry+https://github.com/rust-lang/crates.io-index" 503 | checksum = "8452105ba047068f40ff7093dd1d9da90898e63dd61736462e9cdda6a90ad3c3" 504 | 505 | [[package]] 506 | name = "mt-dom" 507 | version = "0.15.0" 508 | source = "registry+https://github.com/rust-lang/crates.io-index" 509 | checksum = "603dc1f08675ddd350dd58e0da3f2bc37a5b8114b8aeadf001361a2e3130bd7d" 510 | dependencies = [ 511 | "log", 512 | ] 513 | 514 | [[package]] 515 | name = "nalgebra" 516 | version = "0.30.1" 517 | source = "registry+https://github.com/rust-lang/crates.io-index" 518 | checksum = "4fb2d0de08694bed883320212c18ee3008576bfe8c306f4c3c4a58b4876998be" 519 | dependencies = [ 520 | "approx", 521 | "matrixmultiply", 522 | "nalgebra-macros", 523 | "num-complex", 524 | "num-rational", 525 | "num-traits", 526 | "simba", 527 | "typenum", 528 | ] 529 | 530 | [[package]] 531 | name = "nalgebra-macros" 532 | version = "0.1.0" 533 | source = "registry+https://github.com/rust-lang/crates.io-index" 534 | checksum = "01fcc0b8149b4632adc89ac3b7b31a12fb6099a0317a4eb2ebff574ef7de7218" 535 | dependencies = [ 536 | "proc-macro2", 537 | "quote", 538 | "syn", 539 | ] 540 | 541 | [[package]] 542 | name = "nom" 543 | version = "5.1.2" 544 | source = "registry+https://github.com/rust-lang/crates.io-index" 545 | checksum = "ffb4262d26ed83a1c0a33a38fe2bb15797329c85770da05e6b828ddb782627af" 546 | dependencies = [ 547 | "memchr", 548 | "version_check", 549 | ] 550 | 551 | [[package]] 552 | name = "num-complex" 553 | version = "0.4.6" 554 | source = "registry+https://github.com/rust-lang/crates.io-index" 555 | checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" 556 | dependencies = [ 557 | "num-traits", 558 | ] 559 | 560 | [[package]] 561 | name = "num-derive" 562 | version = "0.3.3" 563 | source = "registry+https://github.com/rust-lang/crates.io-index" 564 | checksum = "876a53fff98e03a936a674b29568b0e605f06b29372c2489ff4de23f1949743d" 565 | dependencies = [ 566 | "proc-macro2", 567 | "quote", 568 | "syn", 569 | ] 570 | 571 | [[package]] 572 | name = "num-integer" 573 | version = "0.1.46" 574 | source = "registry+https://github.com/rust-lang/crates.io-index" 575 | checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" 576 | dependencies = [ 577 | "num-traits", 578 | ] 579 | 580 | [[package]] 581 | name = "num-rational" 582 | version = "0.4.2" 583 | source = "registry+https://github.com/rust-lang/crates.io-index" 584 | checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" 585 | dependencies = [ 586 | "num-integer", 587 | "num-traits", 588 | ] 589 | 590 | [[package]] 591 | name = "num-traits" 592 | version = "0.2.19" 593 | source = "registry+https://github.com/rust-lang/crates.io-index" 594 | checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" 595 | dependencies = [ 596 | "autocfg", 597 | "libm", 598 | ] 599 | 600 | [[package]] 601 | name = "once_cell" 602 | version = "1.21.1" 603 | source = "registry+https://github.com/rust-lang/crates.io-index" 604 | checksum = "d75b0bedcc4fe52caa0e03d9f1151a323e4aa5e2d78ba3580400cd3c9e2bc4bc" 605 | 606 | [[package]] 607 | name = "parry2d" 608 | version = "0.8.0" 609 | source = "registry+https://github.com/rust-lang/crates.io-index" 610 | checksum = "65289d4e196cfaca6643766c0d7288997f3b4cee99eba4cdcc28c1dcb8bf2450" 611 | dependencies = [ 612 | "approx", 613 | "arrayvec", 614 | "bitflags", 615 | "downcast-rs", 616 | "either", 617 | "nalgebra", 618 | "num-derive", 619 | "num-traits", 620 | "rustc-hash", 621 | "simba", 622 | "slab", 623 | "smallvec", 624 | ] 625 | 626 | [[package]] 627 | name = "paste" 628 | version = "1.0.15" 629 | source = "registry+https://github.com/rust-lang/crates.io-index" 630 | checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" 631 | 632 | [[package]] 633 | name = "peeking_take_while" 634 | version = "0.1.2" 635 | source = "registry+https://github.com/rust-lang/crates.io-index" 636 | checksum = "19b17cddbe7ec3f8bc800887bab5e717348c95ea2ca0b1bf0837fb964dc67099" 637 | 638 | [[package]] 639 | name = "phf" 640 | version = "0.10.1" 641 | source = "registry+https://github.com/rust-lang/crates.io-index" 642 | checksum = "fabbf1ead8a5bcbc20f5f8b939ee3f5b0f6f281b6ad3468b84656b658b455259" 643 | dependencies = [ 644 | "phf_macros", 645 | "phf_shared", 646 | "proc-macro-hack", 647 | ] 648 | 649 | [[package]] 650 | name = "phf_generator" 651 | version = "0.10.0" 652 | source = "registry+https://github.com/rust-lang/crates.io-index" 653 | checksum = "5d5285893bb5eb82e6aaf5d59ee909a06a16737a8970984dd7746ba9283498d6" 654 | dependencies = [ 655 | "phf_shared", 656 | "rand 0.8.5", 657 | ] 658 | 659 | [[package]] 660 | name = "phf_macros" 661 | version = "0.10.0" 662 | source = "registry+https://github.com/rust-lang/crates.io-index" 663 | checksum = "58fdf3184dd560f160dd73922bea2d5cd6e8f064bf4b13110abd81b03697b4e0" 664 | dependencies = [ 665 | "phf_generator", 666 | "phf_shared", 667 | "proc-macro-hack", 668 | "proc-macro2", 669 | "quote", 670 | "syn", 671 | ] 672 | 673 | [[package]] 674 | name = "phf_shared" 675 | version = "0.10.0" 676 | source = "registry+https://github.com/rust-lang/crates.io-index" 677 | checksum = "b6796ad771acdc0123d2a88dc428b5e38ef24456743ddb1744ed628f9815c096" 678 | dependencies = [ 679 | "siphasher", 680 | ] 681 | 682 | [[package]] 683 | name = "pin-utils" 684 | version = "0.1.0" 685 | source = "registry+https://github.com/rust-lang/crates.io-index" 686 | checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" 687 | 688 | [[package]] 689 | name = "pkg-config" 690 | version = "0.3.19" 691 | source = "registry+https://github.com/rust-lang/crates.io-index" 692 | checksum = "3831453b3449ceb48b6d9c7ad7c96d5ea673e9b470a1dc578c2ce6521230884c" 693 | 694 | [[package]] 695 | name = "pom" 696 | version = "3.4.0" 697 | source = "registry+https://github.com/rust-lang/crates.io-index" 698 | checksum = "6c972d8f86e943ad532d0b04e8965a749ad1d18bb981a9c7b3ae72fe7fd7744b" 699 | dependencies = [ 700 | "bstr", 701 | ] 702 | 703 | [[package]] 704 | name = "ppv-lite86" 705 | version = "0.2.10" 706 | source = "registry+https://github.com/rust-lang/crates.io-index" 707 | checksum = "ac74c624d6b2d21f425f752262f42188365d7b8ff1aff74c82e45136510a4857" 708 | 709 | [[package]] 710 | name = "proc-macro-hack" 711 | version = "0.5.20+deprecated" 712 | source = "registry+https://github.com/rust-lang/crates.io-index" 713 | checksum = "dc375e1527247fe1a97d8b7156678dfe7c1af2fc075c9a4db3690ecd2a148068" 714 | 715 | [[package]] 716 | name = "proc-macro2" 717 | version = "1.0.27" 718 | source = "registry+https://github.com/rust-lang/crates.io-index" 719 | checksum = "f0d8caf72986c1a598726adc988bb5984792ef84f5ee5aa50209145ee8077038" 720 | dependencies = [ 721 | "unicode-xid", 722 | ] 723 | 724 | [[package]] 725 | name = "quick-error" 726 | version = "1.2.3" 727 | source = "registry+https://github.com/rust-lang/crates.io-index" 728 | checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" 729 | 730 | [[package]] 731 | name = "quickcheck" 732 | version = "0.9.2" 733 | source = "registry+https://github.com/rust-lang/crates.io-index" 734 | checksum = "a44883e74aa97ad63db83c4bf8ca490f02b2fc02f92575e720c8551e843c945f" 735 | dependencies = [ 736 | "env_logger 0.7.1", 737 | "log", 738 | "rand 0.7.3", 739 | "rand_core 0.5.1", 740 | ] 741 | 742 | [[package]] 743 | name = "quickcheck_macros" 744 | version = "0.9.1" 745 | source = "registry+https://github.com/rust-lang/crates.io-index" 746 | checksum = "608c156fd8e97febc07dc9c2e2c80bf74cfc6ef26893eae3daf8bc2bc94a4b7f" 747 | dependencies = [ 748 | "proc-macro2", 749 | "quote", 750 | "syn", 751 | ] 752 | 753 | [[package]] 754 | name = "quote" 755 | version = "1.0.9" 756 | source = "registry+https://github.com/rust-lang/crates.io-index" 757 | checksum = "c3d0b9745dc2debf507c8422de05d7226cc1f0644216dfdfead988f9b1ab32a7" 758 | dependencies = [ 759 | "proc-macro2", 760 | ] 761 | 762 | [[package]] 763 | name = "rand" 764 | version = "0.7.3" 765 | source = "registry+https://github.com/rust-lang/crates.io-index" 766 | checksum = "6a6b1679d49b24bbfe0c803429aa1874472f50d9b363131f0e89fc356b544d03" 767 | dependencies = [ 768 | "getrandom 0.1.16", 769 | "libc", 770 | "rand_chacha 0.2.2", 771 | "rand_core 0.5.1", 772 | "rand_hc", 773 | ] 774 | 775 | [[package]] 776 | name = "rand" 777 | version = "0.8.5" 778 | source = "registry+https://github.com/rust-lang/crates.io-index" 779 | checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" 780 | dependencies = [ 781 | "libc", 782 | "rand_chacha 0.3.1", 783 | "rand_core 0.6.4", 784 | ] 785 | 786 | [[package]] 787 | name = "rand_chacha" 788 | version = "0.2.2" 789 | source = "registry+https://github.com/rust-lang/crates.io-index" 790 | checksum = "f4c8ed856279c9737206bf725bf36935d8666ead7aa69b52be55af369d193402" 791 | dependencies = [ 792 | "ppv-lite86", 793 | "rand_core 0.5.1", 794 | ] 795 | 796 | [[package]] 797 | name = "rand_chacha" 798 | version = "0.3.1" 799 | source = "registry+https://github.com/rust-lang/crates.io-index" 800 | checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" 801 | dependencies = [ 802 | "ppv-lite86", 803 | "rand_core 0.6.4", 804 | ] 805 | 806 | [[package]] 807 | name = "rand_core" 808 | version = "0.5.1" 809 | source = "registry+https://github.com/rust-lang/crates.io-index" 810 | checksum = "90bde5296fc891b0cef12a6d03ddccc162ce7b2aff54160af9338f8d40df6d19" 811 | dependencies = [ 812 | "getrandom 0.1.16", 813 | ] 814 | 815 | [[package]] 816 | name = "rand_core" 817 | version = "0.6.4" 818 | source = "registry+https://github.com/rust-lang/crates.io-index" 819 | checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" 820 | dependencies = [ 821 | "getrandom 0.2.15", 822 | ] 823 | 824 | [[package]] 825 | name = "rand_hc" 826 | version = "0.2.0" 827 | source = "registry+https://github.com/rust-lang/crates.io-index" 828 | checksum = "ca3129af7b92a17112d59ad498c6f81eaf463253766b90396d39ea7a39d6613c" 829 | dependencies = [ 830 | "rand_core 0.5.1", 831 | ] 832 | 833 | [[package]] 834 | name = "rawpointer" 835 | version = "0.2.1" 836 | source = "registry+https://github.com/rust-lang/crates.io-index" 837 | checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3" 838 | 839 | [[package]] 840 | name = "regex" 841 | version = "1.5.4" 842 | source = "registry+https://github.com/rust-lang/crates.io-index" 843 | checksum = "d07a8629359eb56f1e2fb1652bb04212c072a87ba68546a04065d525673ac461" 844 | dependencies = [ 845 | "aho-corasick", 846 | "memchr", 847 | "regex-syntax", 848 | ] 849 | 850 | [[package]] 851 | name = "regex-automata" 852 | version = "0.4.9" 853 | source = "registry+https://github.com/rust-lang/crates.io-index" 854 | checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908" 855 | 856 | [[package]] 857 | name = "regex-syntax" 858 | version = "0.6.25" 859 | source = "registry+https://github.com/rust-lang/crates.io-index" 860 | checksum = "f497285884f3fcff424ffc933e56d7cbca511def0c9831a7f9b5f6153e3cc89b" 861 | 862 | [[package]] 863 | name = "rlsf" 864 | version = "0.2.1" 865 | dependencies = [ 866 | "cfg-if 1.0.0", 867 | "const-default", 868 | "env_logger 0.7.1", 869 | "libc", 870 | "log", 871 | "quickcheck", 872 | "quickcheck_macros", 873 | "svgbobdoc", 874 | ] 875 | 876 | [[package]] 877 | name = "rlsf_benchmark_farcri" 878 | version = "0.0.0" 879 | dependencies = [ 880 | "buddy-alloc", 881 | "dlmalloc", 882 | "farcri", 883 | "linked_list_allocator", 884 | "log", 885 | "rlsf", 886 | "umm-malloc-sys", 887 | "wee_alloc", 888 | ] 889 | 890 | [[package]] 891 | name = "rlsf_override" 892 | version = "0.1.0" 893 | dependencies = [ 894 | "bzip2", 895 | "libc", 896 | "rlsf", 897 | ] 898 | 899 | [[package]] 900 | name = "rustc-hash" 901 | version = "1.1.0" 902 | source = "registry+https://github.com/rust-lang/crates.io-index" 903 | checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" 904 | 905 | [[package]] 906 | name = "ryu" 907 | version = "1.0.5" 908 | source = "registry+https://github.com/rust-lang/crates.io-index" 909 | checksum = "71d301d4193d031abdd79ff7e3dd721168a9572ef3fe51a1517aba235bd8f86e" 910 | 911 | [[package]] 912 | name = "safe_arch" 913 | version = "0.7.4" 914 | source = "registry+https://github.com/rust-lang/crates.io-index" 915 | checksum = "96b02de82ddbe1b636e6170c21be622223aea188ef2e139be0a5b219ec215323" 916 | dependencies = [ 917 | "bytemuck", 918 | ] 919 | 920 | [[package]] 921 | name = "sauron" 922 | version = "0.45.2" 923 | source = "registry+https://github.com/rust-lang/crates.io-index" 924 | checksum = "4e303e5d713c95a169639a729f2f6909128d1e63ad1ad6cc3723b939df57e14a" 925 | dependencies = [ 926 | "cfg-if 0.1.10", 927 | "sauron-core", 928 | ] 929 | 930 | [[package]] 931 | name = "sauron-core" 932 | version = "0.45.2" 933 | source = "registry+https://github.com/rust-lang/crates.io-index" 934 | checksum = "663ff99c3e833b00adda36212cafc6756f4509e0bbae89ddf18de30fec41b846" 935 | dependencies = [ 936 | "cfg-if 0.1.10", 937 | "doc-comment", 938 | "jss", 939 | "log", 940 | "mt-dom", 941 | "once_cell", 942 | "thiserror", 943 | ] 944 | 945 | [[package]] 946 | name = "scopeguard" 947 | version = "1.1.0" 948 | source = "registry+https://github.com/rust-lang/crates.io-index" 949 | checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" 950 | 951 | [[package]] 952 | name = "serde" 953 | version = "1.0.126" 954 | source = "registry+https://github.com/rust-lang/crates.io-index" 955 | checksum = "ec7505abeacaec74ae4778d9d9328fe5a5d04253220a85c4ee022239fc996d03" 956 | dependencies = [ 957 | "serde_derive", 958 | ] 959 | 960 | [[package]] 961 | name = "serde-json-core" 962 | version = "0.2.0" 963 | source = "git+https://github.com/rust-embedded-community/serde-json-core.git?rev=da460d123e217f0e822a3977eb2170ed5d279d5e#da460d123e217f0e822a3977eb2170ed5d279d5e" 964 | dependencies = [ 965 | "heapless", 966 | "ryu", 967 | "serde", 968 | ] 969 | 970 | [[package]] 971 | name = "serde_cbor" 972 | version = "0.11.1" 973 | source = "registry+https://github.com/rust-lang/crates.io-index" 974 | checksum = "1e18acfa2f90e8b735b2836ab8d538de304cbb6729a7360729ea5a895d15a622" 975 | dependencies = [ 976 | "half", 977 | "serde", 978 | ] 979 | 980 | [[package]] 981 | name = "serde_derive" 982 | version = "1.0.126" 983 | source = "registry+https://github.com/rust-lang/crates.io-index" 984 | checksum = "963a7dbc9895aeac7ac90e74f34a5d5261828f79df35cbed41e10189d3804d43" 985 | dependencies = [ 986 | "proc-macro2", 987 | "quote", 988 | "syn", 989 | ] 990 | 991 | [[package]] 992 | name = "shlex" 993 | version = "0.1.1" 994 | source = "registry+https://github.com/rust-lang/crates.io-index" 995 | checksum = "7fdf1b9db47230893d76faad238fd6097fd6d6a9245cd7a4d90dbd639536bbd2" 996 | 997 | [[package]] 998 | name = "simba" 999 | version = "0.7.3" 1000 | source = "registry+https://github.com/rust-lang/crates.io-index" 1001 | checksum = "2f3fd720c48c53cace224ae62bef1bbff363a70c68c4802a78b5cc6159618176" 1002 | dependencies = [ 1003 | "approx", 1004 | "num-complex", 1005 | "num-traits", 1006 | "paste", 1007 | "wide", 1008 | ] 1009 | 1010 | [[package]] 1011 | name = "siphasher" 1012 | version = "0.3.11" 1013 | source = "registry+https://github.com/rust-lang/crates.io-index" 1014 | checksum = "38b58827f4464d87d377d175e90bf58eb00fd8716ff0a62f80356b5e61555d0d" 1015 | 1016 | [[package]] 1017 | name = "slab" 1018 | version = "0.4.9" 1019 | source = "registry+https://github.com/rust-lang/crates.io-index" 1020 | checksum = "8f92a496fb766b417c996b9c5e57daf2f7ad3b0bebe1ccfca4856390e3d3bb67" 1021 | dependencies = [ 1022 | "autocfg", 1023 | ] 1024 | 1025 | [[package]] 1026 | name = "smallvec" 1027 | version = "1.14.0" 1028 | source = "registry+https://github.com/rust-lang/crates.io-index" 1029 | checksum = "7fcf8323ef1faaee30a44a340193b1ac6814fd9b7b4e88e9d4519a3e4abe1cfd" 1030 | 1031 | [[package]] 1032 | name = "spin" 1033 | version = "0.5.2" 1034 | source = "registry+https://github.com/rust-lang/crates.io-index" 1035 | checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d" 1036 | 1037 | [[package]] 1038 | name = "spinning_top" 1039 | version = "0.1.1" 1040 | source = "registry+https://github.com/rust-lang/crates.io-index" 1041 | checksum = "047031d6df5f5ae0092c97aa4f6bb04cfc9c081b4cd4cb9cdb38657994279a00" 1042 | dependencies = [ 1043 | "lock_api", 1044 | ] 1045 | 1046 | [[package]] 1047 | name = "stable_deref_trait" 1048 | version = "1.2.0" 1049 | source = "registry+https://github.com/rust-lang/crates.io-index" 1050 | checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" 1051 | 1052 | [[package]] 1053 | name = "strsim" 1054 | version = "0.8.0" 1055 | source = "registry+https://github.com/rust-lang/crates.io-index" 1056 | checksum = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a" 1057 | 1058 | [[package]] 1059 | name = "svgbob" 1060 | version = "0.6.6" 1061 | source = "registry+https://github.com/rust-lang/crates.io-index" 1062 | checksum = "516af6ab2f505bd7805e91da84141b25d23d41fc3088dcb2c49614cf1b019524" 1063 | dependencies = [ 1064 | "itertools", 1065 | "lazy_static", 1066 | "log", 1067 | "nalgebra", 1068 | "parry2d", 1069 | "pom", 1070 | "sauron", 1071 | "unicode-width", 1072 | ] 1073 | 1074 | [[package]] 1075 | name = "svgbobdoc" 1076 | version = "0.3.0" 1077 | source = "registry+https://github.com/rust-lang/crates.io-index" 1078 | checksum = "f2c04b93fc15d79b39c63218f15e3fdffaa4c227830686e3b7c5f41244eb3e50" 1079 | dependencies = [ 1080 | "base64", 1081 | "proc-macro2", 1082 | "quote", 1083 | "svgbob", 1084 | "syn", 1085 | "unicode-width", 1086 | ] 1087 | 1088 | [[package]] 1089 | name = "syn" 1090 | version = "1.0.72" 1091 | source = "registry+https://github.com/rust-lang/crates.io-index" 1092 | checksum = "a1e8cdbefb79a9a5a65e0db8b47b723ee907b7c7f8496c76a1770b5c310bab82" 1093 | dependencies = [ 1094 | "proc-macro2", 1095 | "quote", 1096 | "unicode-xid", 1097 | ] 1098 | 1099 | [[package]] 1100 | name = "termcolor" 1101 | version = "1.1.2" 1102 | source = "registry+https://github.com/rust-lang/crates.io-index" 1103 | checksum = "2dfed899f0eb03f32ee8c6a0aabdb8a7949659e3466561fc0adf54e26d88c5f4" 1104 | dependencies = [ 1105 | "winapi-util", 1106 | ] 1107 | 1108 | [[package]] 1109 | name = "textwrap" 1110 | version = "0.11.0" 1111 | source = "registry+https://github.com/rust-lang/crates.io-index" 1112 | checksum = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060" 1113 | dependencies = [ 1114 | "unicode-width", 1115 | ] 1116 | 1117 | [[package]] 1118 | name = "thiserror" 1119 | version = "1.0.39" 1120 | source = "registry+https://github.com/rust-lang/crates.io-index" 1121 | checksum = "a5ab016db510546d856297882807df8da66a16fb8c4101cb8b30054b0d5b2d9c" 1122 | dependencies = [ 1123 | "thiserror-impl", 1124 | ] 1125 | 1126 | [[package]] 1127 | name = "thiserror-impl" 1128 | version = "1.0.39" 1129 | source = "registry+https://github.com/rust-lang/crates.io-index" 1130 | checksum = "5420d42e90af0c38c3290abcca25b9b3bdf379fc9f55c528f53a269d9c9a267e" 1131 | dependencies = [ 1132 | "proc-macro2", 1133 | "quote", 1134 | "syn", 1135 | ] 1136 | 1137 | [[package]] 1138 | name = "tokenlock" 1139 | version = "0.3.4" 1140 | source = "registry+https://github.com/rust-lang/crates.io-index" 1141 | checksum = "b6f427499498b0519ed7503f237e58f96e2e589a6d1cc9062be6014c72482b89" 1142 | 1143 | [[package]] 1144 | name = "typenum" 1145 | version = "1.13.0" 1146 | source = "registry+https://github.com/rust-lang/crates.io-index" 1147 | checksum = "879f6906492a7cd215bfa4cf595b600146ccfac0c79bcbd1f3000162af5e8b06" 1148 | 1149 | [[package]] 1150 | name = "umm-malloc-sys" 1151 | version = "0.1.1" 1152 | source = "registry+https://github.com/rust-lang/crates.io-index" 1153 | checksum = "3caa548bdc93039315ddd0bb2b4b6a13215fb03c4b65331673055bbbea42e0a3" 1154 | dependencies = [ 1155 | "bindgen", 1156 | "cc", 1157 | ] 1158 | 1159 | [[package]] 1160 | name = "unicode-width" 1161 | version = "0.1.12" 1162 | source = "registry+https://github.com/rust-lang/crates.io-index" 1163 | checksum = "68f5e5f3158ecfd4b8ff6fe086db7c8467a2dfdac97fe420f2b7c4aa97af66d6" 1164 | 1165 | [[package]] 1166 | name = "unicode-xid" 1167 | version = "0.2.2" 1168 | source = "registry+https://github.com/rust-lang/crates.io-index" 1169 | checksum = "8ccb82d61f80a663efe1f787a51b16b5a51e3314d6ac365b08639f52387b33f3" 1170 | 1171 | [[package]] 1172 | name = "vec_map" 1173 | version = "0.8.2" 1174 | source = "registry+https://github.com/rust-lang/crates.io-index" 1175 | checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191" 1176 | 1177 | [[package]] 1178 | name = "version_check" 1179 | version = "0.9.3" 1180 | source = "registry+https://github.com/rust-lang/crates.io-index" 1181 | checksum = "5fecdca9a5291cc2b8dcf7dc02453fee791a280f3743cb0905f8822ae463b3fe" 1182 | 1183 | [[package]] 1184 | name = "wasi" 1185 | version = "0.9.0+wasi-snapshot-preview1" 1186 | source = "registry+https://github.com/rust-lang/crates.io-index" 1187 | checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519" 1188 | 1189 | [[package]] 1190 | name = "wasi" 1191 | version = "0.11.0+wasi-snapshot-preview1" 1192 | source = "registry+https://github.com/rust-lang/crates.io-index" 1193 | checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" 1194 | 1195 | [[package]] 1196 | name = "wee_alloc" 1197 | version = "0.4.5" 1198 | source = "registry+https://github.com/rust-lang/crates.io-index" 1199 | checksum = "dbb3b5a6b2bb17cb6ad44a2e68a43e8d2722c997da10e928665c72ec6c0a0b8e" 1200 | dependencies = [ 1201 | "cfg-if 0.1.10", 1202 | "libc", 1203 | "memory_units", 1204 | "spin", 1205 | "winapi", 1206 | ] 1207 | 1208 | [[package]] 1209 | name = "which" 1210 | version = "3.1.1" 1211 | source = "registry+https://github.com/rust-lang/crates.io-index" 1212 | checksum = "d011071ae14a2f6671d0b74080ae0cd8ebf3a6f8c9589a2cd45f23126fe29724" 1213 | dependencies = [ 1214 | "libc", 1215 | ] 1216 | 1217 | [[package]] 1218 | name = "wide" 1219 | version = "0.7.32" 1220 | source = "registry+https://github.com/rust-lang/crates.io-index" 1221 | checksum = "41b5576b9a81633f3e8df296ce0063042a73507636cbe956c61133dd7034ab22" 1222 | dependencies = [ 1223 | "bytemuck", 1224 | "safe_arch", 1225 | ] 1226 | 1227 | [[package]] 1228 | name = "winapi" 1229 | version = "0.3.9" 1230 | source = "registry+https://github.com/rust-lang/crates.io-index" 1231 | checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" 1232 | dependencies = [ 1233 | "winapi-i686-pc-windows-gnu", 1234 | "winapi-x86_64-pc-windows-gnu", 1235 | ] 1236 | 1237 | [[package]] 1238 | name = "winapi-i686-pc-windows-gnu" 1239 | version = "0.4.0" 1240 | source = "registry+https://github.com/rust-lang/crates.io-index" 1241 | checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" 1242 | 1243 | [[package]] 1244 | name = "winapi-util" 1245 | version = "0.1.5" 1246 | source = "registry+https://github.com/rust-lang/crates.io-index" 1247 | checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" 1248 | dependencies = [ 1249 | "winapi", 1250 | ] 1251 | 1252 | [[package]] 1253 | name = "winapi-x86_64-pc-windows-gnu" 1254 | version = "0.4.0" 1255 | source = "registry+https://github.com/rust-lang/crates.io-index" 1256 | checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" 1257 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | members = [ 3 | "crates/*", 4 | ] 5 | 6 | [profile.release] 7 | debug = true 8 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright 2021 yvt 2 | 3 | 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: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | 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. 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # rlsf 2 | 3 |

4 | docs.rs 5 |

6 | 7 | This crate implements the TLSF (Two-Level Segregated Fit) dynamic memory 8 | allocation algorithm¹. Requires Rust 1.61.0 or later. 9 | 10 | - **Allocation and deallocation operations are guaranteed to complete in 11 | constant time.** TLSF is suitable for real-time applications. 12 | 13 | - **Fast and small.** You can have both. It was found to be smaller and 14 | faster² than most `no_std`-compatible allocator crates. 15 | 16 | - **Accepts any kinds of memory pools.** The low-level type 17 | [`Tlsf`](#tlsf-core-api) just divides any memory pools you provide 18 | (e.g., a `static` array) to serve allocation requests. 19 | The high-level type [`GlobalTlsf`](#globaltlsf-global-allocator) 20 | automatically acquires memory pages using standard methods on supported 21 | systems. 22 | 23 | - **This crate supports `#![no_std]`.** It can be used in bare-metal and 24 | RTOS-based applications. 25 | 26 | 27 | 28 | ¹ M. Masmano, I. Ripoll, A. Crespo and J. Real, "TLSF: a new dynamic 29 | memory allocator for real-time systems," *Proceedings. 16th Euromicro 30 | Conference on Real-Time Systems*, 2004. ECRTS 2004., Catania, Italy, 2004, 31 | pp. 79-88, doi: 10.1109/EMRTS.2004.1311009. 32 | 33 | ² Compiled for and measured on a STM32F401 microcontroller using 34 | FarCri.rs. 35 | 36 | ## Measured Performance 37 | 38 | ![The result of latency measurement on STM32F401 is shown here. rlsf: 39 | 260–320 cycles. buddy-alloc: 340–440 cycles. umm_malloc: 300–700 cycles. 40 | dlmalloc: 450–750 cycles. 41 | ](https://yvt.jp/files/programs/rlsf/time-cm4f-xf-3.svg) 42 | 43 | 46 | 47 | ![The result of code size measurement on WebAssembly is shown here. rlsf: 48 | 1267 bytes, rlsf + pool coalescing: 1584 bytes, wee_alloc: 1910 bytes, 49 | dlmalloc: 9613 bytes. 50 | ](https://yvt.jp/files/programs/rlsf/size-wasm-xf.svg) 51 | 52 | 55 | 56 | ## Drawbacks 57 | 58 | - **It does not support concurrent access.** A whole pool must be locked 59 | for allocation and deallocation. If you use a FIFO lock to protect the 60 | pool, the worst-case execution time will be `O(num_contending_threads)`. 61 | You should consider using a thread-caching memory allocator (e.g., 62 | TCMalloc, jemalloc) if achieving a maximal throughput in a highly 63 | concurrent environment is desired. 64 | 65 | - **Segregated freelists with constant-time lookup cause internal 66 | fragmentation proportional to free block sizes.** The `SLLEN` paramter 67 | allows for adjusting the trade-off between fewer freelists and lower 68 | fragmentation. 69 | 70 | - **No special handling for small allocations (one algorithm for all 71 | sizes).** This may lead to inefficiencies in allocation-heavy 72 | applications compared to modern scalable memory allocators, such as 73 | glibc and jemalloc. 74 | 75 | ## Examples 76 | 77 | ### `Tlsf`: Core API 78 | 79 | ```rust 80 | use rlsf::Tlsf; 81 | use std::{mem::MaybeUninit, alloc::Layout}; 82 | 83 | let mut pool = [MaybeUninit::uninit(); 65536]; 84 | 85 | // On 32-bit systems, the maximum block size is 16 << FLLEN = 65536 bytes. 86 | // The worst-case internal fragmentation is (16 << FLLEN) / SLLEN - 2 = 4094 bytes. 87 | // `'pool` represents the memory pool's lifetime (`pool` in this case). 88 | let mut tlsf: Tlsf<'_, u16, u16, 12, 16> = Tlsf::new(); 89 | // ^^ ^^ ^^ 90 | // | | | 91 | // 'pool | SLLEN 92 | // FLLEN 93 | tlsf.insert_free_block(&mut pool); 94 | 95 | unsafe { 96 | let mut ptr1 = tlsf.allocate(Layout::new::()).unwrap().cast::(); 97 | let mut ptr2 = tlsf.allocate(Layout::new::()).unwrap().cast::(); 98 | *ptr1.as_mut() = 42; 99 | *ptr2.as_mut() = 56; 100 | assert_eq!(*ptr1.as_ref(), 42); 101 | assert_eq!(*ptr2.as_ref(), 56); 102 | tlsf.deallocate(ptr1.cast(), Layout::new::().align()); 103 | tlsf.deallocate(ptr2.cast(), Layout::new::().align()); 104 | } 105 | ``` 106 | 107 | ### `GlobalTlsf`: Global Allocator 108 | 109 | `GlobalTlsf` automatically acquires memory pages through platform-specific 110 | mechanisms. It doesn't support returning memory pages to the system even if 111 | the system supports it. 112 | 113 | ```rust 114 | #[cfg(all(target_arch = "wasm32", not(target_feature = "atomics")))] 115 | #[global_allocator] 116 | static A: rlsf::SmallGlobalTlsf = rlsf::SmallGlobalTlsf::new(); 117 | 118 | let mut m = std::collections::HashMap::new(); 119 | m.insert(1, 2); 120 | m.insert(5, 3); 121 | drop(m); 122 | ``` 123 | 124 | ## Details 125 | 126 | ### Changes from the Original Algorithm 127 | 128 | - The end of each memory pool is capped by a sentinel block 129 | (a permanently occupied block) instead of a normal block with a 130 | last-block-in-pool flag. This simplifies the code a bit and improves 131 | its worst-case performance and code size. 132 | 133 | 134 | ## Cargo Features 135 | 136 | - `unstable`: Enables experimental features that are exempt from the API 137 | stability guarantees. 138 | 139 | ## License 140 | 141 | MIT/Apache-2.0 142 | -------------------------------------------------------------------------------- /crates/rlsf/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ../../CHANGELOG.md -------------------------------------------------------------------------------- /crates/rlsf/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rlsf" 3 | version = "0.2.1" 4 | authors = ["yvt "] 5 | license = "MIT/Apache-2.0" 6 | edition = "2021" 7 | rust-version = "1.61" 8 | readme = "README.md" 9 | description = "Real-time dynamic memory allocator based on the TLSF algorithm" 10 | categories = ["embedded", "no-std", "wasm", "memory-management", "web-programming"] 11 | repository = "https://github.com/yvt/rlsf" 12 | 13 | [features] 14 | doc_cfg = ["svgbobdoc/enable"] 15 | std = [] 16 | unstable = [] 17 | 18 | [dependencies] 19 | svgbobdoc = { version = "0.3.0" } 20 | cfg-if = "1.0.0" 21 | const_default1 = { version = "1", package = "const-default", default-features = false } 22 | 23 | [target."cfg(unix)".dependencies] 24 | libc = "0.2.56" 25 | 26 | [dev-dependencies] 27 | quickcheck_macros = "0.9.1" 28 | quickcheck = "0.9.2" 29 | env_logger = "0.7.1" 30 | log = "0.4.8" 31 | 32 | [package.metadata.docs.rs] 33 | all-features = true 34 | -------------------------------------------------------------------------------- /crates/rlsf/README.md: -------------------------------------------------------------------------------- 1 | ../../README.md -------------------------------------------------------------------------------- /crates/rlsf/src/flex.rs: -------------------------------------------------------------------------------- 1 | //! An allocator with flexible backing stores 2 | use const_default1::ConstDefault; 3 | use core::{alloc::Layout, debug_assert, ptr::NonNull, unimplemented}; 4 | 5 | use super::{ 6 | int::BinInteger, 7 | utils::{ 8 | nonnull_slice_end, nonnull_slice_from_raw_parts, nonnull_slice_len, nonnull_slice_start, 9 | }, 10 | Tlsf, GRANULARITY, 11 | }; 12 | 13 | /// The trait for dynamic storage allocators that can back [`FlexTlsf`]. 14 | pub unsafe trait FlexSource { 15 | /// Allocate a memory block of the requested minimum size. 16 | /// 17 | /// Returns the address range of the allocated memory block. 18 | /// 19 | /// # Safety 20 | /// 21 | /// `min_size` must be a multiple of [`GRANULARITY`]. `min_size` must not 22 | /// be zero. 23 | #[inline] 24 | unsafe fn alloc(&mut self, min_size: usize) -> Option> { 25 | let _ = min_size; 26 | None 27 | } 28 | 29 | /// Attempt to grow the specified allocation without moving it. Returns 30 | /// the final allocation size (which must be greater than or equal to 31 | /// `min_new_len`) on success. 32 | /// 33 | /// # Safety 34 | /// 35 | /// `ptr` must be an existing allocation made by this 36 | /// allocator. `min_new_len` must be greater than or equal to `ptr.len()`. 37 | #[inline] 38 | unsafe fn realloc_inplace_grow( 39 | &mut self, 40 | ptr: NonNull<[u8]>, 41 | min_new_len: usize, 42 | ) -> Option { 43 | let _ = (ptr, min_new_len); 44 | None 45 | } 46 | 47 | /// Deallocate a previously allocated memory block. 48 | /// 49 | /// # Safety 50 | /// 51 | /// `ptr` must denote an existing allocation made by this allocator. 52 | #[inline] 53 | unsafe fn dealloc(&mut self, ptr: NonNull<[u8]>) { 54 | let _ = ptr; 55 | unimplemented!("`supports_dealloc` returned `true`, but `dealloc` is not implemented"); 56 | } 57 | 58 | /// Check if this allocator implements [`Self::dealloc`]. 59 | /// 60 | /// If this method returns `false`, [`FlexTlsf`] will not call `dealloc` to 61 | /// release memory blocks. It also applies some optimizations. 62 | /// 63 | /// The returned value must be constant for a particular instance of `Self`. 64 | #[inline] 65 | fn supports_dealloc(&self) -> bool { 66 | false 67 | } 68 | 69 | /// Check if this allocator implements [`Self::realloc_inplace_grow`]. 70 | /// 71 | /// If this method returns `false`, [`FlexTlsf`] will not call 72 | /// `realloc_inplace_grow` to attempt to grow memory blocks. It also applies 73 | /// some optimizations. 74 | /// 75 | /// The returned value must be constant for a particular instance of `Self`. 76 | #[inline] 77 | fn supports_realloc_inplace_grow(&self) -> bool { 78 | false 79 | } 80 | 81 | /// Returns `true` if this allocator is implemented by managing one 82 | /// contiguous region, which is grown every time `alloc` or 83 | /// `realloc_inplace_grow` is called. 84 | /// 85 | /// For example, in WebAssembly, there is usually only one continuous 86 | /// memory region available for data processing, and the only way to acquire 87 | /// more memory is to grow this region by executing `memory.grow` 88 | /// instructions. An implementation of `FlexSource` based on this system 89 | /// would use this instruction to implement both `alloc` and 90 | /// `realloc_inplace_grow` methods. Therefore, it's pointless for 91 | /// [`FlexTlsf`] to call `alloc` when `realloc_inplace_grow` fails. This 92 | /// method can be used to remove such redundant calls to `alloc`. 93 | /// 94 | /// The returned value must be constant for a particular instance of `Self`. 95 | #[inline] 96 | fn is_contiguous_growable(&self) -> bool { 97 | false 98 | } 99 | 100 | /// Get the minimum alignment of allocations made by this allocator. 101 | /// [`FlexTlsf`] may be less efficient if this method returns a value 102 | /// less than [`GRANULARITY`]. 103 | /// 104 | /// The returned value must be constant for a particular instance of `Self`. 105 | #[inline] 106 | fn min_align(&self) -> usize { 107 | 1 108 | } 109 | } 110 | 111 | trait FlexSourceExt: FlexSource { 112 | #[inline] 113 | fn use_growable_pool(&self) -> bool { 114 | // `growable_pool` is used for deallocation and pool growth. 115 | // Let's not think about the wasted space caused when this method 116 | // returns `false`. 117 | self.supports_dealloc() || self.supports_realloc_inplace_grow() 118 | } 119 | } 120 | 121 | impl FlexSourceExt for T {} 122 | 123 | /// Wraps [`core::alloc::GlobalAlloc`] to implement the [`FlexSource`] trait. 124 | /// 125 | /// Since this type does not implement [`FlexSource::realloc_inplace_grow`], 126 | /// it is likely to end up with terribly fragmented memory pools. 127 | #[derive(Default, Debug, Copy, Clone)] 128 | pub struct GlobalAllocAsFlexSource(pub T); 129 | 130 | impl GlobalAllocAsFlexSource { 131 | const ALIGN: usize = if ALIGN.is_power_of_two() { 132 | if ALIGN < GRANULARITY { 133 | GRANULARITY 134 | } else { 135 | ALIGN 136 | } 137 | } else { 138 | panic!("`ALIGN` is not power of two") 139 | }; 140 | } 141 | 142 | impl ConstDefault for GlobalAllocAsFlexSource { 143 | const DEFAULT: Self = Self(ConstDefault::DEFAULT); 144 | } 145 | 146 | unsafe impl FlexSource 147 | for GlobalAllocAsFlexSource 148 | { 149 | #[inline] 150 | unsafe fn alloc(&mut self, min_size: usize) -> Option> { 151 | let layout = Layout::from_size_align(min_size, Self::ALIGN) 152 | .ok()? 153 | .pad_to_align(); 154 | // Safety: The caller upholds that `min_size` is not zero 155 | let start = self.0.alloc(layout); 156 | let start = NonNull::new(start)?; 157 | Some(nonnull_slice_from_raw_parts(start, layout.size())) 158 | } 159 | 160 | #[inline] 161 | unsafe fn dealloc(&mut self, ptr: NonNull<[u8]>) { 162 | // Safety: This layout was previously used for allocation, during which 163 | // the layout was checked for validity 164 | let layout = Layout::from_size_align_unchecked(nonnull_slice_len(ptr), Self::ALIGN); 165 | 166 | // Safety: `start` denotes an existing allocation with layout `layout` 167 | self.0.dealloc(ptr.as_ptr() as _, layout); 168 | } 169 | 170 | fn supports_dealloc(&self) -> bool { 171 | true 172 | } 173 | 174 | #[inline] 175 | fn min_align(&self) -> usize { 176 | Self::ALIGN 177 | } 178 | } 179 | 180 | /// A wrapper of [`Tlsf`] that automatically acquires fresh memory pools from 181 | /// [`FlexSource`]. 182 | #[derive(Debug)] 183 | pub struct FlexTlsf 184 | { 185 | /// The lastly created memory pool. 186 | growable_pool: Option, 187 | source: Source, 188 | tlsf: Tlsf<'static, FLBitmap, SLBitmap, FLLEN, SLLEN>, 189 | } 190 | 191 | #[derive(Debug, Copy, Clone)] 192 | struct Pool { 193 | /// The starting address of the memory allocation. 194 | alloc_start: NonNull, 195 | /// The length of the memory allocation. 196 | alloc_len: usize, 197 | /// The length of the memory pool created within the allocation. 198 | /// This might be slightly less than `alloc_len`. 199 | pool_len: usize, 200 | } 201 | 202 | // Safety: `Pool` is totally thread-safe 203 | unsafe impl Send for Pool {} 204 | unsafe impl Sync for Pool {} 205 | 206 | /// Pool footer stored at the end of each pool. It's only used when 207 | /// supports_dealloc() == true`. 208 | /// 209 | /// The footer is stored in the sentinel block's unused space or any padding 210 | /// present at the end of each pool. This is why `PoolFtr` can't be larger than 211 | /// two `usize`s. 212 | #[repr(C)] 213 | #[derive(Copy, Clone)] 214 | struct PoolFtr { 215 | /// The previous allocation. Forms a singly-linked list. 216 | prev_alloc: Option>, 217 | } 218 | 219 | const _: () = if core::mem::size_of::() != GRANULARITY / 2 { 220 | panic!("bad `PoolFtr` size"); 221 | }; 222 | 223 | impl PoolFtr { 224 | /// Get a pointer to `PoolFtr` for a given allocation. 225 | #[inline] 226 | fn get_for_alloc(alloc: NonNull<[u8]>, alloc_align: usize) -> *mut Self { 227 | let alloc_end = nonnull_slice_end(alloc); 228 | let mut ptr = alloc_end.wrapping_sub(core::mem::size_of::()); 229 | // If `alloc_end` is not well-aligned, we need to adjust the location 230 | // of `PoolFtr` 231 | if alloc_align < core::mem::align_of::() { 232 | ptr = (ptr as usize & !(core::mem::align_of::() - 1)) as _; 233 | } 234 | ptr as _ 235 | } 236 | } 237 | 238 | /// Initialization with a [`FlexSource`] provided by [`Default::default`] 239 | impl< 240 | Source: FlexSource + Default, 241 | FLBitmap: BinInteger, 242 | SLBitmap: BinInteger, 243 | const FLLEN: usize, 244 | const SLLEN: usize, 245 | > Default for FlexTlsf 246 | { 247 | #[inline] 248 | fn default() -> Self { 249 | Self::new(Source::default()) 250 | } 251 | } 252 | 253 | /// Initialization with a [`FlexSource`] provided by [`ConstDefault::DEFAULT`] 254 | impl< 255 | Source: FlexSource + ConstDefault, 256 | FLBitmap: BinInteger, 257 | SLBitmap: BinInteger, 258 | const FLLEN: usize, 259 | const SLLEN: usize, 260 | > ConstDefault for FlexTlsf 261 | { 262 | /// An empty pool. 263 | const DEFAULT: Self = Self::new(Source::DEFAULT); 264 | } 265 | 266 | impl< 267 | Source: FlexSource, 268 | FLBitmap: BinInteger, 269 | SLBitmap: BinInteger, 270 | const FLLEN: usize, 271 | const SLLEN: usize, 272 | > FlexTlsf 273 | { 274 | /// Construct a new `FlexTlsf` object. 275 | #[inline] 276 | pub const fn new(source: Source) -> Self { 277 | Self { 278 | source, 279 | tlsf: Tlsf::new(), 280 | growable_pool: None, 281 | } 282 | } 283 | 284 | /// Borrow the contained `Source`. 285 | #[inline] 286 | pub fn source_ref(&self) -> &Source { 287 | &self.source 288 | } 289 | 290 | /// Mutably borrow the contained `Source`. 291 | /// 292 | /// # Safety 293 | /// 294 | /// The caller must not replace the `Source` with another one or modify 295 | /// any existing allocations in the `Source`. 296 | #[inline] 297 | pub unsafe fn source_mut_unchecked(&mut self) -> &mut Source { 298 | &mut self.source 299 | } 300 | 301 | /// Attempt to allocate a block of memory. 302 | /// 303 | /// Returns the starting address of the allocated memory block on success; 304 | /// `None` otherwise. 305 | /// 306 | /// # Time Complexity 307 | /// 308 | /// This method will complete in constant time (assuming `Source`'s methods 309 | /// do so as well). 310 | #[cfg_attr(target_arch = "wasm32", inline(never))] 311 | pub fn allocate(&mut self, layout: Layout) -> Option> { 312 | if let Some(x) = self.tlsf.allocate(layout) { 313 | return Some(x); 314 | } 315 | 316 | self.increase_pool_to_contain_allocation(layout)?; 317 | 318 | self.tlsf.allocate(layout).or_else(|| { 319 | // Not a hard error, but it's still unexpected because 320 | // `increase_pool_to_contain_allocation` was supposed to make this 321 | // allocation possible 322 | debug_assert!( 323 | false, 324 | "the allocation failed despite the effort by \ 325 | `increase_pool_to_contain_allocation`" 326 | ); 327 | None 328 | }) 329 | } 330 | 331 | /// Increase the amount of memory pool to guarantee the success of the 332 | /// given allocation. Returns `Some(())` on success. 333 | #[inline] 334 | fn increase_pool_to_contain_allocation(&mut self, layout: Layout) -> Option<()> { 335 | let use_growable_pool = self.source.use_growable_pool(); 336 | 337 | // How many extra bytes we need to get from the source for the 338 | // allocation to success? 339 | let extra_bytes_well_aligned = 340 | Tlsf::<'static, FLBitmap, SLBitmap, FLLEN, SLLEN>::pool_size_to_contain_allocation( 341 | layout, 342 | )?; 343 | 344 | // The sentinel block + the block to store the allocation 345 | debug_assert!(extra_bytes_well_aligned >= GRANULARITY * 2); 346 | 347 | if let Some(growable_pool) = self.growable_pool.filter(|_| use_growable_pool) { 348 | // Try to extend an existing memory pool first. 349 | let new_pool_len_desired = growable_pool 350 | .pool_len 351 | .checked_add(extra_bytes_well_aligned)?; 352 | 353 | // The following assertion should not trip because... 354 | // - `extra_bytes_well_aligned` returns a value that is at least 355 | // as large as `GRANULARITY * 2`. 356 | // - `growable_pool.alloc_len - growable_pool.pool_len` must be 357 | // less than `GRANULARITY * 2` because of 358 | // `insert_free_block_ptr`'s implementation. 359 | debug_assert!(new_pool_len_desired >= growable_pool.alloc_len); 360 | 361 | // Safety: `new_pool_end_desired >= growable_pool.alloc_len`, and 362 | // `(growable_pool.alloc_start, growable_pool.alloc_len)` 363 | // represents a previous allocation. 364 | if let Some(new_alloc_len) = unsafe { 365 | self.source.realloc_inplace_grow( 366 | nonnull_slice_from_raw_parts( 367 | growable_pool.alloc_start, 368 | growable_pool.alloc_len, 369 | ), 370 | new_pool_len_desired, 371 | ) 372 | } { 373 | if self.source.supports_dealloc() { 374 | // Move `PoolFtr`. Note that `PoolFtr::alloc_start` is 375 | // still uninitialized because this allocation is still in 376 | // `self.growable_pool`, so we only have to move 377 | // `PoolFtr::prev_alloc_end`. 378 | let old_pool_ftr = PoolFtr::get_for_alloc( 379 | nonnull_slice_from_raw_parts( 380 | growable_pool.alloc_start, 381 | growable_pool.alloc_len, 382 | ), 383 | self.source.min_align(), 384 | ); 385 | let new_pool_ftr = PoolFtr::get_for_alloc( 386 | nonnull_slice_from_raw_parts(growable_pool.alloc_start, new_alloc_len), 387 | self.source.min_align(), 388 | ); 389 | // Safety: Both `*new_pool_ftr` and `*old_pool_ftr` 390 | // represent pool footers we control 391 | unsafe { *new_pool_ftr = *old_pool_ftr }; 392 | } 393 | 394 | let num_appended_len = unsafe { 395 | // Safety: `self.source` allocated some memory after 396 | // `alloc_start + pool_len`, so it shouldn't be 397 | // null 398 | let append_start = NonNull::new_unchecked( 399 | growable_pool 400 | .alloc_start 401 | .as_ptr() 402 | .wrapping_add(growable_pool.pool_len), 403 | ); 404 | // Safety: `append_start` follows an existing memory pool, 405 | // and the contained bytes are owned by us 406 | self.tlsf 407 | .append_free_block_ptr(nonnull_slice_from_raw_parts( 408 | append_start, 409 | new_alloc_len - growable_pool.pool_len, 410 | )) 411 | }; 412 | 413 | // This assumption is based on `extra_bytes_well_aligned`'s 414 | // implementation. The `debug_assert!` above depends on this. 415 | debug_assert!( 416 | (growable_pool.pool_len + num_appended_len) - new_alloc_len < GRANULARITY * 2 417 | ); 418 | 419 | self.growable_pool = Some(Pool { 420 | alloc_start: growable_pool.alloc_start, 421 | alloc_len: new_alloc_len, 422 | pool_len: growable_pool.pool_len + num_appended_len, 423 | }); 424 | 425 | return Some(()); 426 | } // if let Some(new_alloc_len) = ... realloc_inplace_grow 427 | 428 | if self.source.is_contiguous_growable() { 429 | // `is_contiguous_growable` 430 | // indicates that `alloc` will also be fruitless because 431 | // `realloc_inplace_grow` failed. 432 | return None; 433 | } 434 | } // if let Some(growable_pool) = self.growable_pool 435 | 436 | // Create a brand new allocation. `source.min_align` indicates the 437 | // minimum alignment that the created allocation will satisfy. 438 | // `extra_bytes_well_aligned` is the pool size that can contain the 439 | // allocation *if* the pool was well-aligned. If `source.min_align` is 440 | // not well-aligned enough, we need to allocate extra bytes. 441 | let extra_bytes = if self.source.min_align() < GRANULARITY { 442 | // 443 | // wasted wasted 444 | // ╭┴╮ ╭──┴──╮ 445 | // ┌─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┬─┐ 446 | // Allocation: │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ 447 | // └─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┴─┘ 448 | // ┌───────┬───────┬───────┬───────┐ 449 | // Pool created on it: │ │ │ │ │ 450 | // └───────┴───────┴───────┴───────┘ 451 | // ╰───┬───╯ 452 | // GRANULARITY 453 | // 454 | extra_bytes_well_aligned.checked_add(GRANULARITY)? 455 | } else { 456 | extra_bytes_well_aligned 457 | }; 458 | 459 | // Safety: `extra_bytes` is non-zero and aligned to `GRANULARITY` bytes 460 | let alloc = unsafe { self.source.alloc(extra_bytes)? }; 461 | 462 | let is_well_aligned = self.source.min_align() >= super::GRANULARITY; 463 | 464 | // Safety: The passed memory block is what we acquired from 465 | // `self.source`, so we have the ownership 466 | let pool_len = unsafe { 467 | if is_well_aligned { 468 | self.tlsf.insert_free_block_ptr_aligned(alloc) 469 | } else { 470 | self.tlsf.insert_free_block_ptr(alloc) 471 | } 472 | } 473 | .unwrap_or_else(|| unsafe { 474 | debug_assert!(false, "`pool_size_to_contain_allocation` is an impostor"); 475 | // Safety: It's unreachable 476 | core::hint::unreachable_unchecked() 477 | }) 478 | .get(); 479 | 480 | if self.source.supports_dealloc() { 481 | // Link the new memory pool's `PoolFtr::prev_alloc_end` to the 482 | // previous pool (`self.growable_pool`). 483 | let pool_ftr = PoolFtr::get_for_alloc(alloc, self.source.min_align()); 484 | let prev_alloc = self 485 | .growable_pool 486 | .map(|p| nonnull_slice_from_raw_parts(p.alloc_start, p.alloc_len)); 487 | // Safety: `(*pool_ftr).prev_alloc` is within a pool footer 488 | // we control 489 | unsafe { (*pool_ftr).prev_alloc = prev_alloc }; 490 | } 491 | 492 | if use_growable_pool { 493 | self.growable_pool = Some(Pool { 494 | alloc_start: nonnull_slice_start(alloc), 495 | alloc_len: nonnull_slice_len(alloc), 496 | pool_len, 497 | }); 498 | } 499 | 500 | Some(()) 501 | } 502 | 503 | /// Deallocate a previously allocated memory block. 504 | /// 505 | /// # Time Complexity 506 | /// 507 | /// This method will complete in constant time (assuming `Source`'s methods 508 | /// do so as well). 509 | /// 510 | /// # Safety 511 | /// 512 | /// - `ptr` must denote a memory block previously allocated via `self`. 513 | /// - The memory block must have been allocated with the same alignment 514 | /// ([`Layout::align`]) as `align`. 515 | /// 516 | #[cfg_attr(target_arch = "wasm32", inline(never))] 517 | pub unsafe fn deallocate(&mut self, ptr: NonNull, align: usize) { 518 | // Safety: Upheld by the caller 519 | self.tlsf.deallocate(ptr, align) 520 | } 521 | 522 | /// Deallocate a previously allocated memory block with an unknown alignment. 523 | /// 524 | /// Unlike `deallocate`, this function does not require knowing the 525 | /// allocation's alignment but might be less efficient. 526 | /// 527 | /// # Time Complexity 528 | /// 529 | /// This method will complete in constant time (assuming `Source`'s methods 530 | /// do so as well). 531 | /// 532 | /// # Safety 533 | /// 534 | /// - `ptr` must denote a memory block previously allocated via `self`. 535 | /// 536 | pub(crate) unsafe fn deallocate_unknown_align(&mut self, ptr: NonNull) { 537 | // Safety: Upheld by the caller 538 | self.tlsf.deallocate_unknown_align(ptr) 539 | } 540 | 541 | /// Get the actual usable size of a previously allocated memory block. 542 | /// 543 | /// # Safety 544 | /// 545 | /// - `ptr` must denote a memory block previously allocated via some 546 | /// instance of `Self`. 547 | /// - The call must happen-before the deallocation or reallocation of the 548 | /// memory block. 549 | /// 550 | #[cfg(feature = "unstable")] 551 | #[cfg_attr(feature = "doc_cfg", doc(cfg(feature = "unstable")))] 552 | pub unsafe fn allocation_usable_size(ptr: NonNull) -> usize { 553 | Tlsf::<'static, FLBitmap, SLBitmap, FLLEN, SLLEN>::size_of_allocation_unknown_align(ptr) 554 | } 555 | 556 | /// Shrink or grow a previously allocated memory block. 557 | /// 558 | /// Returns the new starting address of the memory block on success; 559 | /// `None` otherwise. 560 | /// 561 | /// # Time Complexity 562 | /// 563 | /// Unlike other methods, this method will complete in linear time 564 | /// (`O(old_size)`), assuming `Source`'s methods do so as well. 565 | /// 566 | /// # Safety 567 | /// 568 | /// - `ptr` must denote a memory block previously allocated via `self`. 569 | /// - The memory block must have been allocated with the same alignment 570 | /// ([`Layout::align`]) as `new_layout`. 571 | /// 572 | pub unsafe fn reallocate( 573 | &mut self, 574 | ptr: NonNull, 575 | new_layout: Layout, 576 | ) -> Option> { 577 | // Do this early so that the compiler can de-duplicate the evaluation of 578 | // `size_of_allocation`, which is done here as well as in 579 | // `Tlsf::reallocate`. 580 | let old_size = Tlsf::<'static, FLBitmap, SLBitmap, FLLEN, SLLEN>::size_of_allocation( 581 | ptr, 582 | new_layout.align(), 583 | ); 584 | 585 | // Safety: Upheld by the caller 586 | if let Some(x) = self.tlsf.reallocate(ptr, new_layout) { 587 | return Some(x); 588 | } 589 | 590 | // Allocate a whole new memory block. The following code section looks 591 | // the same as the one in `Tlsf::reallocate`, but `self.allocation` 592 | // here refers to `FlexTlsf::allocate`, which inserts new meory pools 593 | // as necessary. 594 | let new_ptr = self.allocate(new_layout)?; 595 | 596 | // Move the existing data into the new location 597 | debug_assert!(new_layout.size() >= old_size); 598 | core::ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_ptr(), old_size); 599 | 600 | // Deallocate the old memory block. 601 | self.deallocate(ptr, new_layout.align()); 602 | 603 | Some(new_ptr) 604 | } 605 | 606 | /// Get the payload size of the allocation with an unknown alignment. The 607 | /// returned size might be larger than the size specified at the allocation 608 | /// time. 609 | /// 610 | /// # Safety 611 | /// 612 | /// - `ptr` must denote a memory block previously allocated via `Self`. 613 | /// 614 | #[inline] 615 | pub(crate) unsafe fn size_of_allocation_unknown_align(ptr: NonNull) -> usize { 616 | // Safety: Upheld by the caller 617 | Tlsf::<'static, FLBitmap, SLBitmap, FLLEN, SLLEN>::size_of_allocation_unknown_align(ptr) 618 | } 619 | } 620 | 621 | impl Drop 622 | for FlexTlsf 623 | { 624 | fn drop(&mut self) { 625 | if self.source.supports_dealloc() { 626 | debug_assert!(self.source.use_growable_pool()); 627 | 628 | // Deallocate all memory pools 629 | let align = self.source.min_align(); 630 | let mut cur_alloc_or_none = self 631 | .growable_pool 632 | .map(|p| nonnull_slice_from_raw_parts(p.alloc_start, p.alloc_len)); 633 | 634 | while let Some(cur_alloc) = cur_alloc_or_none { 635 | // Safety: We control the referenced pool footer 636 | let cur_ftr = unsafe { *PoolFtr::get_for_alloc(cur_alloc, align) }; 637 | 638 | // Safety: It's an allocation we allocated from `self.source` 639 | unsafe { self.source.dealloc(cur_alloc) }; 640 | 641 | cur_alloc_or_none = cur_ftr.prev_alloc; 642 | } 643 | } 644 | } 645 | } 646 | 647 | #[cfg(test)] 648 | mod tests; 649 | -------------------------------------------------------------------------------- /crates/rlsf/src/flex/tests.rs: -------------------------------------------------------------------------------- 1 | use quickcheck_macros::quickcheck; 2 | use std::{fmt, prelude::v1::*}; 3 | 4 | use super::*; 5 | use crate::{ 6 | tests::ShadowAllocator, 7 | utils::{nonnull_slice_end, nonnull_slice_len}, 8 | }; 9 | 10 | trait TestFlexSource: FlexSource { 11 | type Options: quickcheck::Arbitrary; 12 | 13 | fn new(options: Self::Options) -> Self; 14 | } 15 | 16 | impl TestFlexSource 17 | for GlobalAllocAsFlexSource 18 | { 19 | type Options = (); 20 | 21 | fn new((): ()) -> Self { 22 | Self(T::default()) 23 | } 24 | } 25 | 26 | #[derive(Debug)] 27 | struct TrackingFlexSource { 28 | sa: ShadowAllocator, 29 | inner: T, 30 | } 31 | 32 | impl TestFlexSource for TrackingFlexSource { 33 | type Options = T::Options; 34 | 35 | fn new(options: T::Options) -> Self { 36 | Self { 37 | sa: ShadowAllocator::default(), 38 | inner: T::new(options), 39 | } 40 | } 41 | } 42 | 43 | impl Drop for TrackingFlexSource { 44 | fn drop(&mut self) { 45 | if std::thread::panicking() { 46 | return; 47 | } 48 | 49 | if self.inner.supports_dealloc() { 50 | // All existing pools should have been removed by `FlexTlsf::drop` 51 | self.sa.assert_no_pools(); 52 | } 53 | } 54 | } 55 | 56 | unsafe impl FlexSource for TrackingFlexSource { 57 | unsafe fn alloc(&mut self, min_size: usize) -> Option> { 58 | log::trace!("FlexSource::alloc({:?})", min_size); 59 | let range = self.inner.alloc(min_size)?; 60 | log::trace!(" FlexSource::alloc(...) = {:?}", range); 61 | self.sa.insert_free_block(range.as_ptr()); 62 | Some(range) 63 | } 64 | 65 | unsafe fn realloc_inplace_grow( 66 | &mut self, 67 | ptr: NonNull<[u8]>, 68 | min_new_len: usize, 69 | ) -> Option { 70 | log::trace!("FlexSource::realloc_inplace_grow{:?}", (ptr, min_new_len)); 71 | let new_len = self.inner.realloc_inplace_grow(ptr, min_new_len)?; 72 | log::trace!(" FlexSource::realloc_inplace_grow(...) = {:?}", new_len); 73 | self.sa.append_free_block(std::ptr::slice_from_raw_parts( 74 | nonnull_slice_end(ptr), 75 | new_len - nonnull_slice_len(ptr), 76 | )); 77 | Some(new_len) 78 | } 79 | 80 | #[inline] 81 | fn min_align(&self) -> usize { 82 | self.inner.min_align() 83 | } 84 | 85 | #[inline] 86 | unsafe fn dealloc(&mut self, ptr: NonNull<[u8]>) { 87 | // TODO: check that `ptr` represents an exact allocation, not just 88 | // a part of it 89 | self.inner.dealloc(ptr); 90 | log::trace!("FlexSource::dealloc({:?})", ptr); 91 | self.sa.remove_pool(ptr.as_ptr()); 92 | } 93 | 94 | #[inline] 95 | fn is_contiguous_growable(&self) -> bool { 96 | self.inner.is_contiguous_growable() 97 | } 98 | 99 | #[inline] 100 | fn supports_dealloc(&self) -> bool { 101 | self.inner.supports_dealloc() 102 | } 103 | 104 | #[inline] 105 | fn supports_realloc_inplace_grow(&self) -> bool { 106 | self.inner.supports_realloc_inplace_grow() 107 | } 108 | } 109 | 110 | /// Continuous-growing flex source 111 | struct CgFlexSource { 112 | pool: Vec, 113 | allocated: usize, 114 | } 115 | 116 | impl fmt::Debug for CgFlexSource { 117 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 118 | f.debug_struct("CgFlexSource") 119 | .field("allocated", &self.allocated) 120 | .finish() 121 | } 122 | } 123 | 124 | impl TestFlexSource for CgFlexSource { 125 | type Options = u8; 126 | 127 | fn new(offset: u8) -> Self { 128 | Self { 129 | pool: std::vec![0u8; 1024 * 32], 130 | allocated: offset as usize, 131 | } 132 | } 133 | } 134 | 135 | unsafe impl FlexSource for CgFlexSource { 136 | unsafe fn alloc(&mut self, min_size: usize) -> Option> { 137 | let allocated = self.allocated; 138 | let new_allocated = allocated 139 | .checked_add(min_size) 140 | .filter(|&x| x <= self.pool.len())?; 141 | 142 | self.allocated = new_allocated; 143 | Some(NonNull::from(&mut self.pool[allocated..new_allocated])) 144 | } 145 | 146 | unsafe fn realloc_inplace_grow( 147 | &mut self, 148 | ptr: NonNull<[u8]>, 149 | min_new_len: usize, 150 | ) -> Option { 151 | self.alloc(min_new_len - nonnull_slice_len(ptr)) 152 | .map(|s| nonnull_slice_len(s) + nonnull_slice_len(ptr)) 153 | } 154 | 155 | fn is_contiguous_growable(&self) -> bool { 156 | true 157 | } 158 | 159 | fn supports_realloc_inplace_grow(&self) -> bool { 160 | true 161 | } 162 | 163 | fn min_align(&self) -> usize { 164 | 1 165 | } 166 | } 167 | 168 | fn fill_data(p: NonNull<[u8]>) { 169 | use std::mem::MaybeUninit; 170 | let slice = unsafe { &mut *(p.as_ptr() as *mut [MaybeUninit]) }; 171 | for (i, p) in slice.iter_mut().enumerate() { 172 | *p = MaybeUninit::new((i as u8).reverse_bits()); 173 | } 174 | } 175 | 176 | fn verify_data(p: NonNull<[u8]>) { 177 | let slice = unsafe { p.as_ref() }; 178 | for (i, p) in slice.iter().enumerate() { 179 | assert_eq!(*p, (i as u8).reverse_bits()); 180 | } 181 | } 182 | 183 | macro_rules! gen_test { 184 | ($mod:ident, $source:ty, $($tt:tt)*) => { 185 | mod $mod { 186 | use super::*; 187 | type TheTlsf = FlexTlsf, $($tt)*>; 188 | 189 | #[quickcheck] 190 | fn minimal(source_options: <$source as TestFlexSource>::Options) { 191 | let _ = env_logger::builder().is_test(true).try_init(); 192 | 193 | let mut tlsf = TheTlsf::new(TrackingFlexSource::new(source_options)); 194 | 195 | log::trace!("tlsf = {:?}", tlsf); 196 | 197 | let ptr = tlsf.allocate(Layout::from_size_align(1, 1).unwrap()); 198 | log::trace!("ptr = {:?}", ptr); 199 | if let Some(ptr) = ptr { 200 | unsafe { tlsf.deallocate(ptr, 1) }; 201 | } 202 | } 203 | 204 | #[quickcheck] 205 | fn aadaadaraaadr(source_options: <$source as TestFlexSource>::Options) { 206 | let _ = env_logger::builder().is_test(true).try_init(); 207 | 208 | let mut tlsf = TheTlsf::new(TrackingFlexSource::new(source_options)); 209 | 210 | log::trace!("tlsf = {:?}", tlsf); 211 | 212 | let ptr1 = tlsf.allocate(Layout::from_size_align(20, 16).unwrap()); 213 | log::trace!("ptr1 = {:?}", ptr1); 214 | let ptr2 = tlsf.allocate(Layout::from_size_align(21, 1).unwrap()); 215 | log::trace!("ptr2 = {:?}", ptr2); 216 | if let Some(ptr1) = ptr1 { 217 | unsafe { tlsf.deallocate(ptr1, 16) }; 218 | } 219 | let ptr3 = tlsf.allocate(Layout::from_size_align(0, 32).unwrap()); 220 | log::trace!("ptr3 = {:?}", ptr3); 221 | let ptr4 = tlsf.allocate(Layout::from_size_align(10, 8).unwrap()); 222 | log::trace!("ptr4 = {:?}", ptr4); 223 | if let Some(ptr2) = ptr2 { 224 | unsafe { tlsf.deallocate(ptr2, 1) }; 225 | log::trace!("deallocate(ptr2)"); 226 | } 227 | let ptr5 = tlsf.allocate(Layout::from_size_align(12, 8).unwrap()); 228 | log::trace!("ptr5 = {:?}", ptr5); 229 | let ptr3 = ptr3.and_then(|ptr3| unsafe { 230 | tlsf.reallocate(ptr3, Layout::from_size_align(0, 32).unwrap()) 231 | }); 232 | log::trace!("ptr3 = {:?}", ptr3); 233 | let ptr6 = tlsf.allocate(Layout::from_size_align(24, 2).unwrap()); 234 | log::trace!("ptr6 = {:?}", ptr6); 235 | let ptr7 = tlsf.allocate(Layout::from_size_align(11, 16).unwrap()); 236 | log::trace!("ptr7 = {:?}", ptr7); 237 | let ptr8 = tlsf.allocate(Layout::from_size_align(1, 32).unwrap()); 238 | log::trace!("ptr8 = {:?}", ptr8); 239 | if let Some(ptr5) = ptr5 { 240 | unsafe { tlsf.deallocate(ptr5, 8) }; 241 | log::trace!("deallocate(ptr5)"); 242 | } 243 | let ptr3 = ptr3.and_then(|ptr3| unsafe { 244 | tlsf.reallocate(ptr3, Layout::from_size_align(4, 32).unwrap()) 245 | }); 246 | log::trace!("ptr3 = {:?}", ptr3); 247 | } 248 | 249 | #[quickcheck] 250 | fn random(source_options: <$source as TestFlexSource>::Options, max_alloc_size: usize, bytecode: Vec) { 251 | random_inner(source_options, max_alloc_size, bytecode); 252 | } 253 | 254 | fn random_inner(source_options: <$source as TestFlexSource>::Options, max_alloc_size: usize, bytecode: Vec) -> Option<()> { 255 | let max_alloc_size = max_alloc_size % 0x10000; 256 | 257 | let mut tlsf = TheTlsf::new(TrackingFlexSource::new(source_options)); 258 | macro_rules! sa { 259 | () => { 260 | unsafe { tlsf.source_mut_unchecked() }.sa 261 | }; 262 | } 263 | 264 | log::trace!("tlsf = {:?}", tlsf); 265 | 266 | #[derive(Debug)] 267 | struct Alloc { 268 | ptr: NonNull, 269 | layout: Layout, 270 | } 271 | let mut allocs = Vec::new(); 272 | 273 | let mut it = bytecode.iter().cloned(); 274 | loop { 275 | match it.next()? % 8 { 276 | 0..=2 => { 277 | let len = u32::from_le_bytes([ 278 | it.next()?, 279 | it.next()?, 280 | it.next()?, 281 | 0, 282 | ]); 283 | let len = ((len as u64 * max_alloc_size as u64) >> 24) as usize; 284 | let align = 1 << (it.next()? % 6); 285 | let layout = Layout::from_size_align(len, align).unwrap(); 286 | log::trace!("alloc {:?}", layout); 287 | 288 | let ptr = tlsf.allocate(layout); 289 | log::trace!(" → {:?}", ptr); 290 | 291 | if let Some(ptr) = ptr { 292 | allocs.push(Alloc { ptr, layout }); 293 | sa!().allocate(layout, ptr); 294 | 295 | // Fill it with dummy data 296 | fill_data(crate::utils::nonnull_slice_from_raw_parts(ptr, len)); 297 | } 298 | } 299 | 3..=5 => { 300 | let alloc_i = it.next()?; 301 | if allocs.len() > 0 { 302 | let alloc = allocs.swap_remove(alloc_i as usize % allocs.len()); 303 | log::trace!("dealloc {:?}", alloc); 304 | 305 | // Make sure the stored dummy data is not corrupted 306 | verify_data(crate::utils::nonnull_slice_from_raw_parts(alloc.ptr, alloc.layout.size())); 307 | 308 | unsafe { tlsf.deallocate(alloc.ptr, alloc.layout.align()) }; 309 | sa!().deallocate(alloc.layout, alloc.ptr); 310 | } 311 | } 312 | 6..=7 => { 313 | let alloc_i = it.next()?; 314 | if allocs.len() > 0 { 315 | let len = u32::from_le_bytes([ 316 | it.next()?, 317 | it.next()?, 318 | it.next()?, 319 | 0, 320 | ]); 321 | let len = ((len as u64 * max_alloc_size as u64) >> 24) as usize; 322 | 323 | let alloc_i = alloc_i as usize % allocs.len(); 324 | let alloc = &mut allocs[alloc_i]; 325 | log::trace!("realloc {:?} to {:?}", alloc, len); 326 | 327 | let new_layout = Layout::from_size_align(len, alloc.layout.align()).unwrap(); 328 | 329 | if let Some(ptr) = unsafe { tlsf.reallocate(alloc.ptr, new_layout) } { 330 | log::trace!(" {:?} → {:?}", alloc.ptr, ptr); 331 | 332 | // Check and refill the dummy data 333 | verify_data(crate::utils::nonnull_slice_from_raw_parts(ptr, len.min(alloc.layout.size()))); 334 | fill_data(crate::utils::nonnull_slice_from_raw_parts(ptr, len)); 335 | 336 | sa!().deallocate(alloc.layout, alloc.ptr); 337 | alloc.ptr = ptr; 338 | alloc.layout = new_layout; 339 | sa!().allocate(alloc.layout, alloc.ptr); 340 | } else { 341 | log::trace!(" {:?} → fail", alloc.ptr); 342 | 343 | } 344 | } 345 | } 346 | _ => unreachable!(), 347 | } 348 | } 349 | } 350 | } 351 | }; 352 | } 353 | 354 | type SysSource = GlobalAllocAsFlexSource; 355 | gen_test!(tlsf_sys_u8_u8_1_1, SysSource, u8, u8, 1, 1); 356 | gen_test!(tlsf_sys_u8_u8_1_2, SysSource, u8, u8, 1, 2); 357 | gen_test!(tlsf_sys_u8_u8_1_4, SysSource, u8, u8, 1, 4); 358 | gen_test!(tlsf_sys_u8_u8_1_8, SysSource, u8, u8, 1, 8); 359 | gen_test!(tlsf_sys_u8_u8_3_4, SysSource, u8, u8, 3, 4); 360 | gen_test!(tlsf_sys_u8_u8_5_4, SysSource, u8, u8, 5, 4); 361 | gen_test!(tlsf_sys_u8_u8_8_1, SysSource, u8, u8, 8, 1); 362 | gen_test!(tlsf_sys_u8_u8_8_8, SysSource, u8, u8, 8, 8); 363 | gen_test!(tlsf_sys_u16_u8_3_4, SysSource, u16, u8, 3, 4); 364 | gen_test!(tlsf_sys_u16_u8_11_4, SysSource, u16, u8, 11, 4); 365 | gen_test!(tlsf_sys_u16_u8_16_4, SysSource, u16, u8, 16, 4); 366 | gen_test!(tlsf_sys_u16_u16_3_16, SysSource, u16, u16, 3, 16); 367 | gen_test!(tlsf_sys_u16_u16_11_16, SysSource, u16, u16, 11, 16); 368 | gen_test!(tlsf_sys_u16_u16_16_16, SysSource, u16, u16, 16, 16); 369 | gen_test!(tlsf_sys_u16_u32_3_16, SysSource, u16, u32, 3, 16); 370 | gen_test!(tlsf_sys_u16_u32_11_16, SysSource, u16, u32, 11, 16); 371 | gen_test!(tlsf_sys_u16_u32_16_16, SysSource, u16, u32, 16, 16); 372 | gen_test!(tlsf_sys_u16_u32_3_32, SysSource, u16, u32, 3, 32); 373 | gen_test!(tlsf_sys_u16_u32_11_32, SysSource, u16, u32, 11, 32); 374 | gen_test!(tlsf_sys_u16_u32_16_32, SysSource, u16, u32, 16, 32); 375 | gen_test!(tlsf_sys_u32_u32_20_32, SysSource, u32, u32, 20, 32); 376 | gen_test!(tlsf_sys_u32_u32_27_32, SysSource, u32, u32, 27, 32); 377 | gen_test!(tlsf_sys_u32_u32_28_32, SysSource, u32, u32, 28, 32); 378 | gen_test!(tlsf_sys_u32_u32_29_32, SysSource, u32, u32, 29, 32); 379 | gen_test!(tlsf_sys_u32_u32_32_32, SysSource, u32, u32, 32, 32); 380 | gen_test!(tlsf_sys_u64_u8_58_8, SysSource, u64, u64, 58, 8); 381 | gen_test!(tlsf_sys_u64_u8_59_8, SysSource, u64, u64, 59, 8); 382 | gen_test!(tlsf_sys_u64_u8_60_8, SysSource, u64, u64, 60, 8); 383 | gen_test!(tlsf_sys_u64_u8_61_8, SysSource, u64, u64, 61, 8); 384 | gen_test!(tlsf_sys_u64_u8_64_8, SysSource, u64, u64, 64, 8); 385 | 386 | gen_test!(tlsf_cg_u8_u8_1_1, CgFlexSource, u8, u8, 1, 1); 387 | gen_test!(tlsf_cg_u8_u8_1_2, CgFlexSource, u8, u8, 1, 2); 388 | gen_test!(tlsf_cg_u8_u8_1_4, CgFlexSource, u8, u8, 1, 4); 389 | gen_test!(tlsf_cg_u8_u8_1_8, CgFlexSource, u8, u8, 1, 8); 390 | gen_test!(tlsf_cg_u8_u8_3_4, CgFlexSource, u8, u8, 3, 4); 391 | gen_test!(tlsf_cg_u8_u8_5_4, CgFlexSource, u8, u8, 5, 4); 392 | gen_test!(tlsf_cg_u8_u8_8_1, CgFlexSource, u8, u8, 8, 1); 393 | gen_test!(tlsf_cg_u8_u8_8_8, CgFlexSource, u8, u8, 8, 8); 394 | gen_test!(tlsf_cg_u16_u8_3_4, CgFlexSource, u16, u8, 3, 4); 395 | gen_test!(tlsf_cg_u16_u8_11_4, CgFlexSource, u16, u8, 11, 4); 396 | gen_test!(tlsf_cg_u16_u8_16_4, CgFlexSource, u16, u8, 16, 4); 397 | gen_test!(tlsf_cg_u16_u16_3_16, CgFlexSource, u16, u16, 3, 16); 398 | gen_test!(tlsf_cg_u16_u16_11_16, CgFlexSource, u16, u16, 11, 16); 399 | gen_test!(tlsf_cg_u16_u16_16_16, CgFlexSource, u16, u16, 16, 16); 400 | gen_test!(tlsf_cg_u16_u32_3_16, CgFlexSource, u16, u32, 3, 16); 401 | gen_test!(tlsf_cg_u16_u32_11_16, CgFlexSource, u16, u32, 11, 16); 402 | gen_test!(tlsf_cg_u16_u32_16_16, CgFlexSource, u16, u32, 16, 16); 403 | gen_test!(tlsf_cg_u16_u32_3_32, CgFlexSource, u16, u32, 3, 32); 404 | gen_test!(tlsf_cg_u16_u32_11_32, CgFlexSource, u16, u32, 11, 32); 405 | gen_test!(tlsf_cg_u16_u32_16_32, CgFlexSource, u16, u32, 16, 32); 406 | gen_test!(tlsf_cg_u32_u32_20_32, CgFlexSource, u32, u32, 20, 32); 407 | gen_test!(tlsf_cg_u32_u32_27_32, CgFlexSource, u32, u32, 27, 32); 408 | gen_test!(tlsf_cg_u32_u32_28_32, CgFlexSource, u32, u32, 28, 32); 409 | gen_test!(tlsf_cg_u32_u32_29_32, CgFlexSource, u32, u32, 29, 32); 410 | gen_test!(tlsf_cg_u32_u32_32_32, CgFlexSource, u32, u32, 32, 32); 411 | gen_test!(tlsf_cg_u64_u8_58_8, CgFlexSource, u64, u64, 58, 8); 412 | gen_test!(tlsf_cg_u64_u8_59_8, CgFlexSource, u64, u64, 59, 8); 413 | gen_test!(tlsf_cg_u64_u8_60_8, CgFlexSource, u64, u64, 60, 8); 414 | gen_test!(tlsf_cg_u64_u8_61_8, CgFlexSource, u64, u64, 61, 8); 415 | gen_test!(tlsf_cg_u64_u8_64_8, CgFlexSource, u64, u64, 64, 8); 416 | -------------------------------------------------------------------------------- /crates/rlsf/src/global.rs: -------------------------------------------------------------------------------- 1 | use const_default1::ConstDefault; 2 | use core::{ 3 | alloc, 4 | cell::UnsafeCell, 5 | marker::PhantomData, 6 | ops, 7 | ptr::{self, NonNull}, 8 | }; 9 | 10 | use super::FlexTlsf; 11 | 12 | // `doc(cfg(...))` needs to be attached to the type for it to be displayed 13 | // on the docs. 14 | if_supported_target! { 15 | /// [`Tlsf`] as a global allocator. 16 | /// 17 | /// [`Tlsf`]: crate::Tlsf 18 | pub struct GlobalTlsf { 19 | inner: UnsafeCell>, 20 | #[cfg(not(doc))] 21 | mutex: os::Mutex, 22 | _phantom: PhantomData Options>, 23 | } 24 | } 25 | 26 | cfg_if::cfg_if! { 27 | if #[cfg(doc)] { 28 | // don't compile `os` in rustdoc 29 | } else if #[cfg(unix)] { 30 | mod unix; 31 | use self::unix as os; 32 | } else if #[cfg(target_arch = "wasm32")] { 33 | mod wasm32; 34 | use self::wasm32 as os; 35 | } else { 36 | compile_error!( 37 | "`crate::global` shouldn't be present when \ 38 | compiling for an unsupported target" 39 | ); 40 | } 41 | } 42 | 43 | #[cfg(doc)] 44 | type TheTlsf = Options; 45 | #[cfg(not(doc))] 46 | type TheTlsf = 47 | FlexTlsf, usize, usize, { usize::BITS as usize }, { usize::BITS as usize }>; 48 | 49 | impl ConstDefault for GlobalTlsf { 50 | #[allow(clippy::declare_interior_mutable_const)] 51 | const DEFAULT: Self = Self::new(); 52 | } 53 | 54 | if_supported_target! { 55 | /// The options for [`GlobalTlsf`]. 56 | pub trait GlobalTlsfOptions { 57 | /// Enables the specialized reallocation routine. This option might 58 | /// improve the memory usage and runtime performance but increases the 59 | /// code size considerably. 60 | /// 61 | /// It's enabled by default. 62 | const ENABLE_REALLOCATION: bool = true; 63 | 64 | /// Instructs the allocator to coalesce consecutive system memory 65 | /// allocations into one large memory pool whenever possible. 66 | /// 67 | /// Warning: If you are going to create allocations larger than or 68 | /// roughly as large as the system page size, turning off this option 69 | /// can cause an excessive memory usage. 70 | /// 71 | /// It's enabled by default. 72 | const COALESCE_POOLS: bool = true; 73 | } 74 | } 75 | 76 | impl GlobalTlsfOptions for () {} 77 | 78 | if_supported_target! { 79 | /// [`GlobalTlsfOptions`] with all options set to optimize for code size. 80 | #[derive(Debug)] 81 | pub struct SmallGlobalTlsfOptions; 82 | } 83 | 84 | if_supported_target! { 85 | /// An instantiation of [`GlobalTlsf`] optimized for code size. 86 | pub type SmallGlobalTlsf = GlobalTlsf; 87 | } 88 | 89 | impl GlobalTlsfOptions for SmallGlobalTlsfOptions { 90 | const ENABLE_REALLOCATION: bool = false; 91 | const COALESCE_POOLS: bool = false; 92 | } 93 | 94 | unsafe impl Send for GlobalTlsf {} 95 | unsafe impl Sync for GlobalTlsf {} 96 | 97 | impl GlobalTlsf { 98 | /// Construct an empty instance of `Self`. 99 | #[inline] 100 | pub const fn new() -> Self { 101 | Self { 102 | inner: UnsafeCell::new(ConstDefault::DEFAULT), 103 | mutex: ConstDefault::DEFAULT, 104 | _phantom: PhantomData, 105 | } 106 | } 107 | } 108 | 109 | impl GlobalTlsf { 110 | #[inline] 111 | fn lock_inner(&self) -> impl ops::DerefMut> + '_ { 112 | struct LockGuard<'a, Options: GlobalTlsfOptions>(&'a GlobalTlsf); 113 | 114 | impl ops::Deref for LockGuard<'_, Options> { 115 | type Target = TheTlsf; 116 | 117 | #[inline] 118 | fn deref(&self) -> &Self::Target { 119 | // Safety: Protected by `mutex` 120 | unsafe { &*self.0.inner.get() } 121 | } 122 | } 123 | 124 | impl ops::DerefMut for LockGuard<'_, Options> { 125 | #[inline] 126 | fn deref_mut(&mut self) -> &mut Self::Target { 127 | // Safety: Protected by `mutex` 128 | unsafe { &mut *self.0.inner.get() } 129 | } 130 | } 131 | 132 | impl Drop for LockGuard<'_, Options> { 133 | #[inline] 134 | fn drop(&mut self) { 135 | self.0.mutex.unlock(); 136 | } 137 | } 138 | 139 | self.mutex.lock(); 140 | LockGuard(self) 141 | } 142 | } 143 | 144 | unsafe impl alloc::GlobalAlloc for GlobalTlsf { 145 | #[inline] 146 | unsafe fn alloc(&self, layout: alloc::Layout) -> *mut u8 { 147 | let mut inner = self.lock_inner(); 148 | inner 149 | .allocate(layout) 150 | .map(NonNull::as_ptr) 151 | .unwrap_or(ptr::null_mut()) 152 | } 153 | 154 | #[inline] 155 | unsafe fn dealloc(&self, ptr: *mut u8, layout: alloc::Layout) { 156 | let mut inner = self.lock_inner(); 157 | // Safety: All allocations are non-null 158 | let ptr = NonNull::new_unchecked(ptr); 159 | // Safety: `ptr` denotes a previous allocation with alignment 160 | // `layout.align()` 161 | inner.deallocate(ptr, layout.align()); 162 | } 163 | 164 | #[inline] 165 | unsafe fn realloc(&self, ptr: *mut u8, layout: alloc::Layout, new_size: usize) -> *mut u8 { 166 | let mut inner = self.lock_inner(); 167 | // Safety: All allocations are non-null 168 | let ptr = NonNull::new_unchecked(ptr); 169 | // Safety: `layout.align()` is a power of two, and the size parameter's 170 | // validity is upheld by the caller 171 | let new_layout = alloc::Layout::from_size_align_unchecked(new_size, layout.align()); 172 | if Options::ENABLE_REALLOCATION { 173 | // Safety: `ptr` denotes a previous allocation with alignment 174 | // `layout.align()` 175 | inner 176 | .reallocate(ptr, new_layout) 177 | .map(NonNull::as_ptr) 178 | .unwrap_or(ptr::null_mut()) 179 | } else if let Some(new_ptr) = inner.allocate(new_layout) { 180 | // Safety: the previously allocated block cannot overlap the 181 | // newly allocated block. 182 | // The safety contract for `deallocate` must be upheld 183 | // by the caller. 184 | ptr::copy_nonoverlapping(ptr.as_ptr(), new_ptr.as_ptr(), layout.size().min(new_size)); 185 | inner.deallocate(ptr, layout.align()); 186 | new_ptr.as_ptr() 187 | } else { 188 | ptr::null_mut() 189 | } 190 | } 191 | } 192 | 193 | /// Provides allocation functions modelled after the standard C and POSIX 194 | /// allocation functions (e.g., `malloc`, `memalign`). 195 | /// 196 | /// Note that this trait might require a less efficient implementation than 197 | /// [`core::alloc::GlobalAlloc`]. This applies to [`GlobalTlsf`]. 198 | pub unsafe trait CAlloc { 199 | /// Allocate a memory block. 200 | /// 201 | /// Returns the starting address of the allocated memory block on success; 202 | /// `None` otherwise. 203 | fn allocate(&self, layout: alloc::Layout) -> Option>; 204 | 205 | /// Deallocate a previously allocated memory block. 206 | /// 207 | /// # Safety 208 | /// 209 | /// - `ptr` must denote a memory block previously allocated by calling 210 | /// [`Self::allocate`] on `self`. 211 | /// 212 | unsafe fn deallocate(&self, ptr: NonNull); 213 | 214 | /// Shrink or grow a previously allocated memory block. 215 | /// 216 | /// Returns the new starting address of the memory block on success; 217 | /// `None` otherwise. 218 | /// 219 | /// # Safety 220 | /// 221 | /// - `ptr` must denote a memory block previously allocated by calling 222 | /// [`Self::allocate`] on `self`. 223 | /// 224 | unsafe fn reallocate(&self, ptr: NonNull, new_layout: alloc::Layout) 225 | -> Option>; 226 | 227 | /// Get the actual usable size of a previously allocated memory block. 228 | /// 229 | /// # Safety 230 | /// 231 | /// - `ptr` must denote a memory block previously allocated by calling 232 | /// [`Self::allocate`] on `self`. 233 | /// 234 | unsafe fn allocation_usable_size(&self, ptr: NonNull) -> usize; 235 | } 236 | 237 | unsafe impl CAlloc for GlobalTlsf { 238 | fn allocate(&self, layout: alloc::Layout) -> Option> { 239 | let mut inner = self.lock_inner(); 240 | inner.allocate(layout) 241 | } 242 | 243 | unsafe fn deallocate(&self, ptr: NonNull) { 244 | let mut inner = self.lock_inner(); 245 | // Safety: `ptr` denotes a previous allocation 246 | inner.deallocate_unknown_align(ptr); 247 | } 248 | 249 | unsafe fn reallocate( 250 | &self, 251 | ptr: NonNull, 252 | new_layout: alloc::Layout, 253 | ) -> Option> { 254 | let mut inner = self.lock_inner(); 255 | if let Some(new_ptr) = inner.allocate(new_layout) { 256 | // Safety: `ptr` denotes a previous allocation 257 | let old_size = TheTlsf::::size_of_allocation_unknown_align(ptr); 258 | // Safety: the previously allocated block cannot overlap the 259 | // newly allocated block. 260 | // The safety contract for `deallocate` must be upheld 261 | // by the caller. 262 | ptr::copy_nonoverlapping( 263 | ptr.as_ptr(), 264 | new_ptr.as_ptr(), 265 | new_layout.size().min(old_size), 266 | ); 267 | inner.deallocate_unknown_align(ptr); 268 | Some(new_ptr) 269 | } else { 270 | None 271 | } 272 | } 273 | 274 | unsafe fn allocation_usable_size(&self, ptr: NonNull) -> usize { 275 | // Safety: `ptr` denotes a previous allocation 276 | TheTlsf::::size_of_allocation_unknown_align(ptr) 277 | } 278 | } 279 | 280 | #[cfg(test)] 281 | mod tests; 282 | -------------------------------------------------------------------------------- /crates/rlsf/src/global/tests.rs: -------------------------------------------------------------------------------- 1 | use quickcheck_macros::quickcheck; 2 | use std::{alloc::Layout, prelude::v1::*}; 3 | 4 | use super::*; 5 | use crate::tests::ShadowAllocator; 6 | 7 | #[derive(Debug)] 8 | struct Alloc { 9 | ptr: NonNull, 10 | layout: Layout, 11 | } 12 | 13 | macro_rules! gen_test { 14 | ($mod:ident, $($tt:tt)*) => { 15 | mod $mod { 16 | use super::*; 17 | type TheTlsf = GlobalTlsf<$($tt)*>; 18 | 19 | #[quickcheck] 20 | fn calloc_random(bytecode: Vec) { 21 | let tlsf: TheTlsf = TheTlsf::DEFAULT; 22 | 23 | let mut allocs = Vec::new(); 24 | calloc_random_inner(&tlsf, &mut allocs, bytecode); 25 | 26 | // Deallocate all remaining allocations 27 | for alloc in allocs.iter() { 28 | unsafe { CAlloc::deallocate(&tlsf, alloc.ptr) }; 29 | } 30 | } 31 | 32 | fn calloc_random_inner(tlsf: &TheTlsf, allocs: &mut Vec, bytecode: Vec) -> Option<()> { 33 | let mut sa = ShadowAllocator::new_filled_with_free(); 34 | 35 | let mut it = bytecode.iter().cloned(); 36 | loop { 37 | match it.next()? % 8 { 38 | 0..=2 => { 39 | if allocs.len() > 64 { 40 | continue; 41 | } 42 | let len = u32::from_le_bytes([ 43 | it.next()?, 44 | 0, 45 | 0, 46 | 0, 47 | ]) as usize; 48 | let align = 1 << (it.next()? % 6); 49 | let layout = Layout::from_size_align(len, align).unwrap(); 50 | log::trace!("alloc {:?}", layout); 51 | 52 | let ptr = CAlloc::allocate(tlsf, layout); 53 | log::trace!(" → {:?}", ptr); 54 | 55 | if let Some(ptr) = ptr { 56 | assert!(unsafe { CAlloc::allocation_usable_size(tlsf, ptr) } >= len); 57 | 58 | allocs.push(Alloc { ptr, layout }); 59 | sa.allocate(layout, ptr); 60 | } 61 | } 62 | 3..=5 => { 63 | let alloc_i = it.next()?; 64 | if allocs.len() > 0 { 65 | let alloc = allocs.swap_remove(alloc_i as usize % allocs.len()); 66 | log::trace!("dealloc {:?}", alloc); 67 | 68 | unsafe { CAlloc::deallocate(tlsf, alloc.ptr) }; 69 | sa.deallocate(alloc.layout, alloc.ptr); 70 | } 71 | } 72 | 6..=7 => { 73 | let alloc_i = it.next()?; 74 | if allocs.len() > 0 { 75 | let len = u32::from_le_bytes([ 76 | it.next()?, 77 | 0, 78 | 0, 79 | 0, 80 | ]) as usize; 81 | let align = 1 << (it.next()? % 6); 82 | 83 | let alloc_i = alloc_i as usize % allocs.len(); 84 | let alloc = &mut allocs[alloc_i]; 85 | 86 | let new_layout = Layout::from_size_align(len, align).unwrap(); 87 | log::trace!("realloc {:?} to {:?}", alloc, new_layout); 88 | 89 | if let Some(ptr) = unsafe { CAlloc::reallocate(tlsf, alloc.ptr, new_layout) } { 90 | log::trace!(" {:?} → {:?}", alloc.ptr, ptr); 91 | sa.deallocate(alloc.layout, alloc.ptr); 92 | alloc.ptr = ptr; 93 | alloc.layout = new_layout; 94 | sa.allocate(alloc.layout, alloc.ptr); 95 | } else { 96 | log::trace!(" {:?} → fail", alloc.ptr); 97 | 98 | } 99 | } 100 | } 101 | _ => unreachable!(), 102 | } 103 | } 104 | } 105 | } 106 | }; 107 | } 108 | 109 | gen_test!(default_globaltlsf, ()); 110 | gen_test!(small_globaltlsf, SmallGlobalTlsfOptions); 111 | -------------------------------------------------------------------------------- /crates/rlsf/src/global/unix.rs: -------------------------------------------------------------------------------- 1 | use const_default1::ConstDefault; 2 | use core::{ 3 | marker::PhantomData, 4 | ptr::{addr_of_mut, null_mut, NonNull}, 5 | }; 6 | 7 | use super::GlobalTlsfOptions; 8 | 9 | const MIN_ALIGN: usize = crate::GRANULARITY; 10 | 11 | /// The allocation unit, which is intentionally set to be larger than the usual 12 | /// page sizes to reduce overhead. TODO: Make this adjustable 13 | const ALLOC_UNIT: usize = 1 << 16; 14 | 15 | pub struct Mutex(()); 16 | 17 | impl ConstDefault for Mutex { 18 | const DEFAULT: Self = Self(()); 19 | } 20 | 21 | /// `pthread_mutex_t` might be unsafe to move, so we can't put it in `Mutex`. 22 | static mut MUTEX: libc::pthread_mutex_t = libc::PTHREAD_MUTEX_INITIALIZER; 23 | 24 | impl Mutex { 25 | #[inline] 26 | pub fn lock(&self) { 27 | unsafe { libc::pthread_mutex_lock(addr_of_mut!(MUTEX)) }; 28 | } 29 | 30 | #[inline] 31 | pub fn unlock(&self) { 32 | unsafe { libc::pthread_mutex_unlock(addr_of_mut!(MUTEX)) }; 33 | } 34 | } 35 | 36 | pub struct Source(PhantomData Options>); 37 | 38 | impl ConstDefault for Source { 39 | const DEFAULT: Self = Self(PhantomData); 40 | } 41 | 42 | /// The memory page size minus 1. Set by `Mutex::lock`. 43 | static mut PAGE_SIZE_M1: usize = 0; 44 | #[cold] 45 | fn init_page_size() -> usize { 46 | unsafe { 47 | let page_size = (libc::sysconf(libc::_SC_PAGESIZE) as usize).max(ALLOC_UNIT); 48 | if !page_size.is_power_of_two() { 49 | libc::abort(); 50 | } 51 | PAGE_SIZE_M1 = page_size - 1; 52 | 53 | // Such a small memory page size is quite unusual. 54 | if page_size < MIN_ALIGN { 55 | libc::abort(); 56 | } 57 | 58 | PAGE_SIZE_M1 59 | } 60 | } 61 | 62 | #[inline] 63 | fn ensure_page_size_m1() -> usize { 64 | let page_size_m1 = unsafe { PAGE_SIZE_M1 }; 65 | if page_size_m1 == 0 { 66 | // `init_page_size` returns the initialized value for 67 | // code size optimization 68 | init_page_size() 69 | } else { 70 | page_size_m1 71 | } 72 | } 73 | 74 | unsafe impl crate::flex::FlexSource for Source { 75 | #[inline] 76 | unsafe fn alloc(&mut self, min_size: usize) -> Option> { 77 | let page_size_m1 = ensure_page_size_m1(); 78 | let num_bytes = min_size.checked_add(page_size_m1)? & !page_size_m1; 79 | 80 | let ptr = libc::mmap( 81 | null_mut(), 82 | num_bytes, 83 | libc::PROT_WRITE | libc::PROT_READ, 84 | libc::MAP_ANONYMOUS | libc::MAP_PRIVATE, 85 | -1, 86 | 0, 87 | ); 88 | 89 | if ptr == libc::MAP_FAILED { 90 | return None; 91 | } 92 | 93 | NonNull::new(core::ptr::slice_from_raw_parts_mut( 94 | ptr as *mut u8, 95 | num_bytes, 96 | )) 97 | } 98 | 99 | #[inline] 100 | // `MAP_FIXED_NOREPLACE` is only supported by Linux 4.17 and later. 101 | #[cfg(target_os = "linux")] 102 | unsafe fn realloc_inplace_grow( 103 | &mut self, 104 | ptr: NonNull<[u8]>, 105 | min_new_len: usize, 106 | ) -> Option { 107 | use crate::utils::nonnull_slice_len; 108 | 109 | if !Options::COALESCE_POOLS { 110 | return None; 111 | } 112 | 113 | let page_size_m1 = ensure_page_size_m1(); 114 | let num_bytes = min_new_len.checked_add(page_size_m1)? & !page_size_m1; 115 | let num_growth_bytes = num_bytes - nonnull_slice_len(ptr); 116 | 117 | let ptr_end = (ptr.as_ptr() as *mut u8).wrapping_add(nonnull_slice_len(ptr)); 118 | 119 | let ptr_growth_start = libc::mmap( 120 | ptr_end as _, 121 | num_growth_bytes, 122 | libc::PROT_WRITE | libc::PROT_READ, 123 | libc::MAP_ANONYMOUS | libc::MAP_PRIVATE | libc::MAP_FIXED_NOREPLACE, 124 | -1, 125 | 0, 126 | ); 127 | 128 | if ptr_growth_start != ptr_end as _ { 129 | // We are on an old Linux kernel, and `MAP_FIXED_NOREPLACE` was 130 | // not respected. 131 | libc::munmap(ptr_growth_start, num_growth_bytes); 132 | None 133 | } else if ptr_growth_start == libc::MAP_FAILED { 134 | None 135 | } else { 136 | Some(num_bytes) 137 | } 138 | } 139 | 140 | #[inline] 141 | #[cfg(target_os = "linux")] 142 | fn supports_realloc_inplace_grow(&self) -> bool { 143 | Options::COALESCE_POOLS 144 | } 145 | 146 | // Not implementing `dealloc` because there is no safe way to destruct 147 | // a registered global allocator anyway. 148 | 149 | #[inline] 150 | fn min_align(&self) -> usize { 151 | // Return a conservative yet enough-for-optimization constant number 152 | MIN_ALIGN 153 | } 154 | } 155 | -------------------------------------------------------------------------------- /crates/rlsf/src/global/wasm32.rs: -------------------------------------------------------------------------------- 1 | use const_default1::ConstDefault; 2 | use core::{arch::wasm32, marker::PhantomData, ptr::NonNull}; 3 | 4 | use super::GlobalTlsfOptions; 5 | 6 | pub struct Mutex(()); 7 | 8 | impl ConstDefault for Mutex { 9 | const DEFAULT: Self = Self(()); 10 | } 11 | 12 | #[cfg(not(target_feature = "atomics"))] 13 | impl Mutex { 14 | // Single-threaded WebAssembly environment 15 | #[inline] 16 | pub fn lock(&self) {} 17 | 18 | #[inline] 19 | pub fn unlock(&self) {} 20 | } 21 | 22 | pub struct Source(PhantomData Options>); 23 | 24 | impl ConstDefault for Source { 25 | const DEFAULT: Self = Self(PhantomData); 26 | } 27 | 28 | const MEM: u32 = 0; 29 | const PAGE_SIZE_LOG2: u32 = 16; 30 | const PAGE_SIZE: usize = 1 << PAGE_SIZE_LOG2; 31 | 32 | unsafe impl crate::flex::FlexSource for Source { 33 | #[inline] 34 | unsafe fn alloc(&mut self, min_size: usize) -> Option> { 35 | let num_pages = min_size.checked_add(PAGE_SIZE - 1)? / PAGE_SIZE; 36 | let num_bytes = num_pages * PAGE_SIZE; 37 | 38 | let old_num_pages = wasm32::memory_grow(MEM, num_pages); 39 | 40 | if old_num_pages == usize::MAX { 41 | // failure 42 | None 43 | } else { 44 | Some( 45 | NonNull::new(core::ptr::slice_from_raw_parts_mut( 46 | (old_num_pages * PAGE_SIZE) as *mut u8, 47 | num_bytes, 48 | )) 49 | // Assume the old memory size is non-zero. It's likely to be 50 | // true because otherwise there wouldn't be even a stack space. 51 | .unwrap_or_else(|| wasm32::unreachable()), 52 | ) 53 | } 54 | } 55 | 56 | #[inline] 57 | unsafe fn realloc_inplace_grow( 58 | &mut self, 59 | ptr: NonNull<[u8]>, 60 | min_new_len: usize, 61 | ) -> Option { 62 | if !Options::COALESCE_POOLS { 63 | return None; 64 | } 65 | 66 | let ptr_page = ptr.as_ptr() as *mut u8 as usize / PAGE_SIZE; 67 | if ptr_page != wasm32::memory_size(MEM) { 68 | // We can't grow the memory from `ptr`; someone else has grown it 69 | // past `ptr`, and we don't own that part 70 | return None; 71 | } 72 | 73 | let new_num_pages = min_new_len.checked_add(PAGE_SIZE - 1)? / PAGE_SIZE; 74 | let new_len = new_num_pages * PAGE_SIZE; 75 | 76 | if wasm32::memory_grow(MEM, new_num_pages - ptr_page) == usize::MAX { 77 | // failure 78 | None 79 | } else { 80 | Some(new_len) 81 | } 82 | } 83 | 84 | #[inline] 85 | fn supports_realloc_inplace_grow(&self) -> bool { 86 | Options::COALESCE_POOLS 87 | } 88 | 89 | // Turns out, `is_contiguous_growable` can't return `true` because 90 | // other code may issue `memory.grow` without `unsafe` blocks. 91 | 92 | #[inline] 93 | fn min_align(&self) -> usize { 94 | PAGE_SIZE 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /crates/rlsf/src/int.rs: -------------------------------------------------------------------------------- 1 | //! Provides [`BinInteger`], a trait for types like `u8` and `u32`. 2 | #![allow(unstable_name_collisions)] // `$ty::BITS` 3 | use core::{fmt, marker, ops}; 4 | 5 | /// Integral types with efficient binary operations. 6 | pub trait BinInteger: 7 | Clone 8 | + Copy 9 | + PartialEq 10 | + Eq 11 | + Ord 12 | + PartialOrd 13 | + marker::Unpin 14 | + ops::Add 15 | + ops::Sub 16 | + ops::Mul 17 | + ops::Div 18 | + ops::Rem 19 | + Sized 20 | + ops::AddAssign 21 | + ops::SubAssign 22 | + ops::MulAssign 23 | + ops::DivAssign 24 | + ops::RemAssign 25 | + fmt::Debug 26 | + Send 27 | + Sync 28 | + 'static 29 | + private::Sealed 30 | { 31 | const ZERO: Self; 32 | const BITS: u32; 33 | 34 | fn ones(range: ops::Range) -> Self; 35 | 36 | fn ones_truncated(range: ops::Range) -> Self; 37 | 38 | /// Return the number of trailing zeros in its binary representation. 39 | fn trailing_zeros(&self) -> u32; 40 | 41 | /// Return the number of leading zeros in its binary representation. 42 | fn leading_zeros(&self) -> u32; 43 | 44 | /// Return the number of ones in its binary representation. 45 | fn count_ones(&self) -> u32; 46 | 47 | /// Return the position of the least significant set bit since the position 48 | /// `start`. 49 | /// 50 | /// Retruns `Self::BITS` if none was found. 51 | fn bit_scan_forward(&self, start: u32) -> u32; 52 | 53 | /// Slice a part of its binary representation as `u32`. 54 | fn extract_u32(&self, range: ops::Range) -> u32; 55 | 56 | /// Retrieve whether the specified bit is set or not. 57 | fn get_bit(&self, i: u32) -> bool; 58 | 59 | /// Set a single bit. 60 | fn set_bit(&mut self, i: u32); 61 | 62 | /// Clear a single bit. 63 | fn clear_bit(&mut self, i: u32); 64 | 65 | /// Perform `ceil` treating the value as a fixed point number with `fp` 66 | /// fractional part digits. 67 | fn checked_ceil_fix(self, fp: u32) -> Option; 68 | } 69 | 70 | macro_rules! impl_binary_integer { 71 | ($type:ty) => { 72 | impl private::Sealed for $type {} 73 | 74 | impl BinInteger for $type { 75 | const ZERO: Self = 0; 76 | const BITS: u32 = core::mem::size_of::<$type>() as u32 * 8; 77 | 78 | #[inline] 79 | fn ones(range: ops::Range) -> Self { 80 | assert!(range.end <= Self::BITS); 81 | Self::ones_truncated(range) 82 | } 83 | #[inline] 84 | fn ones_truncated(range: ops::Range) -> Self { 85 | assert!(range.start <= range.end); 86 | if range.end >= Self::BITS { 87 | (0 as Self).wrapping_sub(1 << range.start) 88 | } else { 89 | ((1 as Self) << range.end).wrapping_sub(1 << range.start) 90 | } 91 | } 92 | #[inline] 93 | fn trailing_zeros(&self) -> u32 { 94 | (*self).trailing_zeros() 95 | } 96 | #[inline] 97 | fn leading_zeros(&self) -> u32 { 98 | (*self).leading_zeros() 99 | } 100 | #[inline] 101 | fn count_ones(&self) -> u32 { 102 | (*self).count_ones() 103 | } 104 | #[inline] 105 | fn bit_scan_forward(&self, start: u32) -> u32 { 106 | if start >= Self::BITS { 107 | Self::BITS 108 | } else { 109 | (*self & !Self::ones(0..start)).trailing_zeros() 110 | } 111 | } 112 | #[inline] 113 | fn extract_u32(&self, range: ops::Range) -> u32 { 114 | let start = range.start; 115 | ((self & Self::ones_truncated(range)) >> start) as u32 116 | } 117 | #[inline] 118 | fn get_bit(&self, i: u32) -> bool { 119 | if i < Self::BITS { 120 | self & ((1 as Self) << i) != 0 121 | } else { 122 | false 123 | } 124 | } 125 | #[inline] 126 | fn set_bit(&mut self, i: u32) { 127 | if i < Self::BITS { 128 | *self |= (1 as Self) << i; 129 | } 130 | } 131 | #[inline] 132 | fn clear_bit(&mut self, i: u32) { 133 | if i < Self::BITS { 134 | *self &= !((1 as Self) << i); 135 | } 136 | } 137 | #[inline] 138 | fn checked_ceil_fix(self, fp: u32) -> Option { 139 | if fp >= Self::BITS { 140 | if self == 0 { 141 | Some(0) 142 | } else { 143 | None 144 | } 145 | } else { 146 | let mask = Self::ones(0..fp); 147 | self.checked_add(mask).map(|x| x & !mask) 148 | } 149 | } 150 | } 151 | }; 152 | } 153 | 154 | impl_binary_integer!(i8); 155 | impl_binary_integer!(i16); 156 | impl_binary_integer!(i32); 157 | impl_binary_integer!(i64); 158 | impl_binary_integer!(i128); 159 | impl_binary_integer!(isize); 160 | 161 | impl_binary_integer!(u8); 162 | impl_binary_integer!(u16); 163 | impl_binary_integer!(u32); 164 | impl_binary_integer!(u64); 165 | impl_binary_integer!(u128); 166 | impl_binary_integer!(usize); 167 | 168 | /// Implements [the sealed trait pattern], which protects [`BinInteger`] against 169 | /// downstream implementations. 170 | /// 171 | /// [the sealed trait pattern]: https://rust-lang.github.io/api-guidelines/future-proofing.html 172 | mod private { 173 | pub trait Sealed {} 174 | } 175 | -------------------------------------------------------------------------------- /crates/rlsf/src/lib.rs: -------------------------------------------------------------------------------- 1 | #![doc = include_str!("../README.md")] 2 | #![no_std] 3 | #![cfg_attr(feature = "doc_cfg", feature(doc_cfg))] 4 | 5 | #[cfg(doc)] 6 | #[doc = include_str!("../CHANGELOG.md")] 7 | pub mod _changelog_ {} 8 | 9 | mod flex; 10 | pub mod int; 11 | mod tlsf; 12 | mod utils; 13 | pub use self::{ 14 | flex::*, 15 | tlsf::{Tlsf, GRANULARITY}, 16 | }; 17 | #[cfg(feature = "unstable")] 18 | pub use tlsf::BlockInfo; 19 | 20 | /// Attaches `#[cfg(...)]` and `#[doc(cfg(...))]` to a given item definition 21 | /// to conditionally compile it only when we have a `GlobalTlsf` implementation 22 | /// for the current target. 23 | macro_rules! if_supported_target { 24 | ( 25 | $($tt:tt)* 26 | ) => { 27 | #[cfg(any( 28 | all(target_arch = "wasm32", not(target_feature = "atomics")), 29 | unix, 30 | doc, 31 | ))] 32 | #[cfg_attr( 33 | feature = "doc_cfg", 34 | doc(cfg(any( 35 | all(target_arch = "wasm32", not(target_feature = "atomics")), 36 | unix, 37 | // no `doc` here 38 | ))) 39 | )] 40 | $($tt)* 41 | }; 42 | } 43 | 44 | if_supported_target! { mod global; } 45 | if_supported_target! { pub use self::global::*; } 46 | 47 | #[cfg(any(test, feature = "std"))] 48 | extern crate std; 49 | 50 | #[cfg(test)] 51 | mod tests; 52 | -------------------------------------------------------------------------------- /crates/rlsf/src/tests.rs: -------------------------------------------------------------------------------- 1 | use std::{alloc::Layout, collections::BTreeMap, ops::Range, prelude::v1::*, ptr::NonNull}; 2 | 3 | #[derive(Debug)] 4 | pub struct ShadowAllocator { 5 | regions: BTreeMap, 6 | } 7 | 8 | #[derive(Debug, Eq, PartialEq, Copy, Clone)] 9 | pub enum SaRegion { 10 | Free, 11 | Used, 12 | Invalid, 13 | } 14 | 15 | impl Default for ShadowAllocator { 16 | fn default() -> Self { 17 | Self::new() 18 | } 19 | } 20 | 21 | impl ShadowAllocator { 22 | pub fn new() -> Self { 23 | Self { 24 | regions: Some((0, SaRegion::Invalid)).into_iter().collect(), 25 | } 26 | } 27 | 28 | pub fn new_filled_with_free() -> Self { 29 | Self { 30 | regions: Some((0, SaRegion::Free)).into_iter().collect(), 31 | } 32 | } 33 | 34 | pub fn convert_range( 35 | &mut self, 36 | range: Range, 37 | old_region: SaRegion, 38 | new_region: SaRegion, 39 | ) { 40 | if range.len() == 0 { 41 | return; 42 | } 43 | 44 | assert_ne!(old_region, new_region); 45 | log::trace!( 46 | "sa: converting {:?} from {:?} to {:?}", 47 | range, 48 | old_region, 49 | new_region 50 | ); 51 | 52 | let (&addr, ®ion) = self.regions.range(0..range.end).rev().next().unwrap(); 53 | if addr > range.start { 54 | panic!("there's a discontinuity in range {:?}", range); 55 | } else if region != old_region { 56 | panic!( 57 | "range {:?} is {:?} (expected {:?})", 58 | range, region, old_region 59 | ); 60 | } 61 | 62 | // Insert an element at `range.start` 63 | if addr == range.start { 64 | *self.regions.get_mut(&addr).unwrap() = new_region; 65 | } else { 66 | self.regions.insert(range.start, new_region); 67 | } 68 | 69 | // Each element must represent a discontinuity. If it doesnt't represent 70 | // a discontinuity, it must be removed. 71 | if let Some((_, ®ion)) = self.regions.range(0..range.start).rev().next() { 72 | if region == new_region { 73 | self.regions.remove(&range.start); 74 | } 75 | } 76 | 77 | if let Some(&end_region) = self.regions.get(&range.end) { 78 | // Each element must represent a discontinuity. If it doesnt't 79 | // represent a discontinuity, it must be removed. 80 | if end_region == new_region { 81 | self.regions.remove(&range.end); 82 | } 83 | } else { 84 | // Insert an element at `range.end` 85 | self.regions.insert(range.end, old_region); 86 | } 87 | } 88 | 89 | pub fn assert_no_pools(&mut self) { 90 | assert!( 91 | self.regions.iter().eq(Some((&0, &SaRegion::Invalid))), 92 | "{:?}", 93 | self.regions, 94 | ); 95 | } 96 | 97 | pub fn insert_free_block(&mut self, range: *const [T]) { 98 | let start = range as *const T as usize; 99 | let len = unsafe { &*range }.len(); 100 | self.convert_range(start..start + len, SaRegion::Invalid, SaRegion::Free); 101 | } 102 | 103 | pub fn append_free_block(&mut self, range: *const [T]) { 104 | let start = range as *const T as usize; 105 | let mut it = self.regions.range(0..=start).rev(); 106 | 107 | assert_eq!( 108 | it.next(), 109 | Some((&start, &SaRegion::Invalid)), 110 | "no boundary at `start`" 111 | ); 112 | 113 | assert_ne!( 114 | it.next().expect("no previous allocation to append to").1, 115 | &SaRegion::Invalid, 116 | "no previous allocation to append to" 117 | ); 118 | 119 | self.insert_free_block(range); 120 | } 121 | 122 | pub fn remove_pool(&mut self, range: *const [T]) { 123 | let start = range as *const T as usize; 124 | let end = unsafe { &*range }.len() + start; 125 | if start >= end { 126 | return; 127 | } 128 | log::trace!("sa: invalidating {:?}", start..end); 129 | 130 | // There mustn't be any `Invalid` regions in the range 131 | for (&addr, ®ion) in self.regions.range(0..end).rev() { 132 | if region == SaRegion::Invalid { 133 | panic!("invalid region at {}", addr); 134 | } 135 | if addr <= start { 136 | break; 137 | } 138 | } 139 | 140 | // Create discontinuity at `end` if needed 141 | { 142 | let (&addr, ®ion) = self.regions.range(0..=end).rev().next().unwrap(); 143 | if addr < end && region != SaRegion::Invalid { 144 | self.regions.insert(end, region); 145 | } else if addr == end && region == SaRegion::Invalid { 146 | self.regions.remove(&end); 147 | } 148 | } 149 | 150 | // Create discontinuity at `start` if needed 151 | if let Some((_, ®ion)) = self.regions.range(0..start).rev().next() { 152 | if region != SaRegion::Invalid { 153 | self.regions.insert(start, SaRegion::Invalid); 154 | } else { 155 | self.regions.remove(&start); 156 | } 157 | } else { 158 | assert_eq!(start, 0); 159 | self.regions.insert(start, SaRegion::Invalid); 160 | } 161 | 162 | // Remove anything remaining between `start` and `end` 163 | let keys: Vec<_> = self 164 | .regions 165 | .range(start + 1..end) 166 | .map(|(&addr, _)| addr) 167 | .collect(); 168 | for key in keys.iter() { 169 | self.regions.remove(key); 170 | } 171 | } 172 | 173 | pub fn allocate(&mut self, layout: Layout, start: NonNull) { 174 | let start = start.as_ptr() as usize; 175 | let len = layout.size(); 176 | assert!( 177 | start % layout.align() == 0, 178 | "0x{:x} is not properly aligned (0x{:x} bytes alignment required)", 179 | start, 180 | layout.align() 181 | ); 182 | self.convert_range(start..start + len, SaRegion::Free, SaRegion::Used); 183 | } 184 | 185 | pub fn deallocate(&mut self, layout: Layout, start: NonNull) { 186 | let start = start.as_ptr() as usize; 187 | let len = layout.size(); 188 | assert!( 189 | start % layout.align() == 0, 190 | "0x{:x} is not properly aligned (0x{:x} bytes alignment required)", 191 | start, 192 | layout.align() 193 | ); 194 | self.convert_range(start..start + len, SaRegion::Used, SaRegion::Free); 195 | } 196 | } 197 | -------------------------------------------------------------------------------- /crates/rlsf/src/tlsf/tests.rs: -------------------------------------------------------------------------------- 1 | use quickcheck_macros::quickcheck; 2 | use std::{mem::MaybeUninit, prelude::v1::*}; 3 | 4 | use super::*; 5 | use crate::{tests::ShadowAllocator, utils::nonnull_slice_from_raw_parts}; 6 | 7 | #[repr(align(64))] 8 | struct Align(T); 9 | 10 | /// Dump the output of `iter_blocks` in a separate module so that it can be 11 | /// filtered separately with `env_logger` 12 | mod blocks_checker { 13 | use super::*; 14 | #[cfg(feature = "unstable")] 15 | use std::ptr::NonNull; 16 | 17 | pub unsafe fn trace_blocks( 18 | pool_ptr: *mut u8, 19 | pool_len: Option, 20 | tlsf: &Tlsf<'_, impl BinInteger, impl BinInteger, FLLEN, SLLEN>, 21 | ) { 22 | #[cfg(feature = "unstable")] 23 | { 24 | let pool_len = if let Some(pool_len) = pool_len { 25 | pool_len 26 | } else { 27 | return; 28 | }; 29 | let pool_ptr = nonnull_slice_from_raw_parts(NonNull::new(pool_ptr).unwrap(), pool_len); 30 | 31 | // Unconditionally enumerate all blocks to see that it doesn't crash 32 | let blocks: Vec<_> = tlsf.iter_blocks(pool_ptr).collect(); 33 | 34 | log::trace!("blocks = {:?}", blocks); 35 | } 36 | 37 | #[cfg(not(feature = "unstable"))] 38 | let _ = (pool_ptr, pool_len, tlsf); 39 | } 40 | } 41 | 42 | macro_rules! gen_test { 43 | ($mod:ident, $($tt:tt)*) => { 44 | mod $mod { 45 | use super::*; 46 | type TheTlsf<'a> = Tlsf<'a, $($tt)*>; 47 | 48 | #[test] 49 | fn minimal() { 50 | let _ = env_logger::builder().is_test(true).try_init(); 51 | 52 | let mut tlsf: TheTlsf = Tlsf::new(); 53 | 54 | let mut pool = [MaybeUninit::uninit(); 65536]; 55 | tlsf.insert_free_block(&mut pool); 56 | 57 | log::trace!("tlsf = {:?}", tlsf); 58 | 59 | let ptr = tlsf.allocate(Layout::from_size_align(1, 1).unwrap()); 60 | log::trace!("ptr = {:?}", ptr); 61 | if let Some(ptr) = ptr { 62 | unsafe { tlsf.deallocate(ptr, 1) }; 63 | } 64 | } 65 | 66 | #[test] 67 | fn adaa() { 68 | let _ = env_logger::builder().is_test(true).try_init(); 69 | 70 | let mut tlsf: TheTlsf = Tlsf::new(); 71 | 72 | let mut pool = [MaybeUninit::uninit(); 65536]; 73 | tlsf.insert_free_block(&mut pool); 74 | 75 | log::trace!("tlsf = {:?}", tlsf); 76 | 77 | let ptr = tlsf.allocate(Layout::from_size_align(0, 1).unwrap()); 78 | log::trace!("ptr = {:?}", ptr); 79 | if let Some(ptr) = ptr { 80 | unsafe { tlsf.deallocate(ptr, 1) }; 81 | } 82 | 83 | let ptr = tlsf.allocate(Layout::from_size_align(0, 1).unwrap()); 84 | log::trace!("ptr = {:?}", ptr); 85 | 86 | let ptr = tlsf.allocate(Layout::from_size_align(0, 1).unwrap()); 87 | log::trace!("ptr = {:?}", ptr); 88 | } 89 | 90 | #[test] 91 | fn aadd() { 92 | let _ = env_logger::builder().is_test(true).try_init(); 93 | 94 | let mut tlsf: TheTlsf = Tlsf::new(); 95 | 96 | let mut pool = Align([MaybeUninit::uninit(); 96]); 97 | tlsf.insert_free_block(&mut pool.0); 98 | 99 | log::trace!("tlsf = {:?}", tlsf); 100 | 101 | let ptr1 = tlsf.allocate(Layout::from_size_align(0, 1).unwrap()); 102 | log::trace!("ptr1 = {:?}", ptr1); 103 | 104 | let ptr2 = tlsf.allocate(Layout::from_size_align(0, 1).unwrap()); 105 | log::trace!("ptr2 = {:?}", ptr2); 106 | 107 | if let (Some(ptr1), Some(ptr2)) = (ptr1, ptr2) { 108 | unsafe { tlsf.deallocate(ptr1, 1) }; 109 | unsafe { tlsf.deallocate(ptr2, 1) }; 110 | } 111 | } 112 | 113 | #[test] 114 | fn ara() { 115 | let _ = env_logger::builder().is_test(true).try_init(); 116 | 117 | let mut tlsf: TheTlsf = Tlsf::new(); 118 | 119 | let mut pool = Align([MaybeUninit::uninit(); 96]); 120 | tlsf.insert_free_block(&mut pool.0); 121 | 122 | log::trace!("tlsf = {:?}", tlsf); 123 | 124 | let ptr = tlsf.allocate(Layout::from_size_align(17, 1).unwrap()); 125 | log::trace!("ptr = {:?}", ptr); 126 | 127 | if let Some(ptr) = ptr { 128 | unsafe { tlsf.reallocate(ptr, Layout::from_size_align(0, 1).unwrap()) }; 129 | log::trace!("ptr = {:?}", ptr); 130 | } 131 | 132 | let ptr = tlsf.allocate(Layout::from_size_align(0, 1).unwrap()); 133 | log::trace!("ptr = {:?}", ptr); 134 | } 135 | 136 | #[test] 137 | fn append_free_block_ptr() { 138 | let _ = env_logger::builder().is_test(true).try_init(); 139 | 140 | let mut tlsf: TheTlsf = Tlsf::new(); 141 | 142 | let mut pool = Align([MaybeUninit::uninit(); 512]); 143 | let mut cursor = pool.0[0].as_mut_ptr() as *mut u8; 144 | let mut remaining_len = 512; 145 | 146 | let pool0_len = unsafe { 147 | tlsf.insert_free_block_ptr(nonnull_slice_from_raw_parts( 148 | NonNull::new(cursor).unwrap(), remaining_len / 2)) 149 | }.unwrap().get(); 150 | cursor = cursor.wrapping_add(pool0_len); 151 | remaining_len -= pool0_len; 152 | 153 | log::trace!("tlsf = {:?}", tlsf); 154 | 155 | // The memory pool is too small at this point 156 | assert!(tlsf.allocate(Layout::from_size_align(384, 1).unwrap()).is_none()); 157 | 158 | let _pool1_len = unsafe { 159 | tlsf.append_free_block_ptr(nonnull_slice_from_raw_parts( 160 | NonNull::new(cursor).unwrap(), remaining_len)) 161 | }; 162 | 163 | log::trace!("tlsf = {:?}", tlsf); 164 | 165 | let ptr = tlsf.allocate(Layout::from_size_align(384, 1).unwrap()); 166 | log::trace!("ptr = {:?}", ptr); 167 | 168 | if TheTlsf::MAX_POOL_SIZE.is_none() { 169 | // `append_free_block_ptr` coalesces consecutive 170 | // memory pools, so this allocation should succeed 171 | ptr.unwrap(); 172 | } 173 | } 174 | 175 | #[test] 176 | fn insert_free_block_ptr_near_end_fail() { 177 | let mut tlsf: TheTlsf = Tlsf::new(); 178 | unsafe { 179 | // FIXME: Use `NonNull::<[T]>::slice_from_raw_parts` when it's stable 180 | tlsf.insert_free_block_ptr( 181 | NonNull::new(core::ptr::slice_from_raw_parts_mut( 182 | (usize::MAX - GRANULARITY + 1) as _, 183 | 0, 184 | )) 185 | .unwrap(), 186 | ); 187 | } 188 | 189 | // TODO: Allocation should fail 190 | } 191 | 192 | #[test] 193 | fn insert_free_block_ptr_near_end() { 194 | let _tlsf: TheTlsf = Tlsf::new(); 195 | // TODO: Find a way to test this case 196 | // 197 | // unsafe { 198 | // tlsf.insert_free_block_ptr(core::ptr::slice_from_raw_parts_mut( 199 | // usize::MAX - GRANULARITY as _, 200 | // GRANULARITY, 201 | // )); 202 | // } 203 | } 204 | 205 | #[quickcheck] 206 | fn random(pool_start: usize, pool_size: usize, bytecode: Vec) { 207 | random_inner(pool_start, pool_size, bytecode); 208 | } 209 | 210 | fn random_inner(pool_start: usize, pool_size: usize, bytecode: Vec) -> Option<()> { 211 | let mut sa = ShadowAllocator::new(); 212 | let mut tlsf: TheTlsf = Tlsf::new(); 213 | 214 | let mut pool = Align([MaybeUninit::::uninit(); 65536]); 215 | let pool_ptr; 216 | // The end index of the memory pool inserted to `tlsf` 217 | let mut pool_len; 218 | // The end index of `pool` 219 | let pool_limit; 220 | unsafe { 221 | // Insert some part of `pool` to `tlsf` 222 | let pool_start = pool_start % 64; 223 | let pool_size = pool_size % (pool.0.len() - 63); 224 | pool_ptr = pool.0.as_mut_ptr().wrapping_add(pool_start) as *mut u8; 225 | pool_limit = pool.0.len() - pool_start; 226 | 227 | let initial_pool = NonNull::new(std::ptr::slice_from_raw_parts_mut( 228 | pool_ptr, 229 | pool_size 230 | )).unwrap(); 231 | log::trace!("initial_pool = {:p}: [u8; {}]", pool_ptr, pool_size); 232 | 233 | pool_len = if let Some(pool_len) = tlsf.insert_free_block_ptr(initial_pool) { 234 | let pool_len = pool_len.get(); 235 | log::trace!("initial_pool (actual) = {:p}: {}", pool_ptr, pool_len); 236 | sa.insert_free_block(std::ptr::slice_from_raw_parts( 237 | pool_ptr, 238 | pool_len 239 | )); 240 | Some(pool_len) 241 | } else { 242 | None 243 | }; 244 | } 245 | 246 | log::trace!("tlsf = {:?}", tlsf); 247 | 248 | #[derive(Debug)] 249 | struct Alloc { 250 | ptr: NonNull, 251 | layout: Layout, 252 | } 253 | let mut allocs = Vec::new(); 254 | 255 | let mut it = bytecode.iter().cloned(); 256 | loop { 257 | match it.next()? % 8 { 258 | 0..=2 => { 259 | let len = u32::from_le_bytes([ 260 | it.next()?, 261 | it.next()?, 262 | it.next()?, 263 | 0, 264 | ]); 265 | let len = ((len as u64 * pool_size as u64) >> 24) as usize; 266 | let align = 1 << (it.next()? % 6); 267 | let layout = Layout::from_size_align(len, align).unwrap(); 268 | log::trace!("alloc {:?}", layout); 269 | 270 | let ptr = tlsf.allocate(layout); 271 | log::trace!(" → {:?}", ptr); 272 | 273 | if let Some(ptr) = ptr { 274 | allocs.push(Alloc { ptr, layout }); 275 | sa.allocate(layout, ptr); 276 | } 277 | } 278 | 3..=5 => { 279 | let alloc_i = it.next()?; 280 | if allocs.len() > 0 { 281 | let provide_align = (alloc_i as usize / allocs.len()) % 2 == 0; 282 | let alloc = allocs.swap_remove(alloc_i as usize % allocs.len()); 283 | log::trace!("dealloc {:?}", alloc); 284 | 285 | if provide_align { 286 | unsafe { tlsf.deallocate(alloc.ptr, alloc.layout.align()) }; 287 | } else { 288 | unsafe { tlsf.deallocate_unknown_align(alloc.ptr) }; 289 | } 290 | sa.deallocate(alloc.layout, alloc.ptr); 291 | } 292 | } 293 | 6 => { 294 | let alloc_i = it.next()?; 295 | if allocs.len() > 0 { 296 | let len = u32::from_le_bytes([ 297 | it.next()?, 298 | it.next()?, 299 | it.next()?, 300 | 0, 301 | ]); 302 | let len = ((len as u64 * pool_size as u64) >> 24) as usize; 303 | 304 | let alloc_i = alloc_i as usize % allocs.len(); 305 | let alloc = &mut allocs[alloc_i]; 306 | log::trace!("realloc {:?} to {:?}", alloc, len); 307 | 308 | let new_layout = Layout::from_size_align(len, alloc.layout.align()).unwrap(); 309 | 310 | if let Some(ptr) = unsafe { tlsf.reallocate(alloc.ptr, new_layout) } { 311 | log::trace!(" {:?} → {:?}", alloc.ptr, ptr); 312 | sa.deallocate(alloc.layout, alloc.ptr); 313 | alloc.ptr = ptr; 314 | alloc.layout = new_layout; 315 | sa.allocate(alloc.layout, alloc.ptr); 316 | } else { 317 | log::trace!(" {:?} → fail", alloc.ptr); 318 | 319 | } 320 | } 321 | } 322 | 7 => { 323 | let old_pool_len = if let Some(pool_len) = pool_len { 324 | pool_len 325 | } else { 326 | continue; 327 | }; 328 | 329 | // Incorporate some of `pool_len..pool_limit` 330 | let available = pool_limit - old_pool_len; 331 | if available == 0 { 332 | continue; 333 | } 334 | 335 | let num_appended_bytes = 336 | u16::from_le_bytes([it.next()?, it.next()?]) as usize % (available + 1); 337 | 338 | let appended = nonnull_slice_from_raw_parts( 339 | NonNull::new(pool_ptr.wrapping_add(old_pool_len)).unwrap(), 340 | num_appended_bytes, 341 | ); 342 | 343 | log::trace!("appending [{}..][..{}] to pool", old_pool_len, num_appended_bytes); 344 | 345 | let new_actual_appended_bytes = unsafe { tlsf.append_free_block_ptr(appended) }; 346 | log::trace!(" actual appended range = [{}..][..{}]", old_pool_len, new_actual_appended_bytes); 347 | sa.insert_free_block(std::ptr::slice_from_raw_parts( 348 | pool_ptr.wrapping_add(old_pool_len), 349 | new_actual_appended_bytes, 350 | )); 351 | pool_len = Some(old_pool_len + new_actual_appended_bytes); 352 | } 353 | _ => unreachable!(), 354 | } 355 | 356 | // Scan all blocks for every iteration 357 | unsafe { blocks_checker::trace_blocks(pool_ptr, pool_len, &tlsf) }; 358 | } 359 | } 360 | 361 | #[test] 362 | fn max_pool_size() { 363 | if let Some(mps) = TheTlsf::MAX_POOL_SIZE { 364 | // `MAX_POOL_SIZE - super::GRANULARITY` should 365 | // be the maximum allowed block size. 366 | assert!(TheTlsf::map_floor(mps - super::GRANULARITY).is_some()); 367 | assert_eq!(TheTlsf::map_floor(mps), None); 368 | } 369 | } 370 | 371 | #[quickcheck] 372 | fn map_ceil_and_unmap(size: usize, shift: u32) -> quickcheck::TestResult { 373 | let size = size.rotate_left(shift % usize::BITS) 374 | .wrapping_mul(super::GRANULARITY); 375 | if size == 0 { 376 | return quickcheck::TestResult::discard(); 377 | } 378 | let list_min_size = TheTlsf::map_ceil_and_unmap(size); 379 | log::debug!("map_ceil_and_unmap({}) = {:?}", size, list_min_size); 380 | if let Some(list_min_size) = list_min_size { 381 | assert!(list_min_size >= size); 382 | 383 | // `list_min_size` must be the lower bound of some list 384 | let (fl, sl) = TheTlsf::map_floor(list_min_size).unwrap(); 385 | log::debug!("map_floor({}) = {:?}", list_min_size, (fl, sl)); 386 | 387 | // Since `list_min_size` is the lower bound of some list, 388 | // `map_floor(list_min_size)` and `map_ceil(list_min_size)` 389 | // should both return this list 390 | assert_eq!(TheTlsf::map_floor(list_min_size), TheTlsf::map_ceil(list_min_size)); 391 | 392 | // `map_ceil_and_unmap(size)` must be the lower bound of the 393 | // list returned by `map_ceil(size)` 394 | assert_eq!(TheTlsf::map_floor(list_min_size), TheTlsf::map_ceil(size)); 395 | } else { 396 | // Find an explanation for `map_ceil_and_unmap` returning 397 | // `None` 398 | if let Some((fl, _sl)) = TheTlsf::map_ceil(size) { 399 | // The lower bound of `(fl, sl)` is not representable 400 | // in `usize` - this should be why 401 | assert!(fl as u32 + super::GRANULARITY_LOG2 >= usize::BITS); 402 | } else { 403 | // `map_ceil_and_unmap` is `map_ceil` + infallible 404 | // reverse mapping, and the suboperation `map_ceil` 405 | // failed 406 | } 407 | } 408 | 409 | quickcheck::TestResult::passed() 410 | } 411 | 412 | #[quickcheck] 413 | fn map_ceil_and_unmap_huge(shift: u32) -> quickcheck::TestResult { 414 | let size = usize::MAX << 415 | (shift % (usize::BITS - super::GRANULARITY_LOG2) 416 | + super::GRANULARITY_LOG2); 417 | 418 | if size == 0 || TheTlsf::map_ceil(size).is_some() { 419 | return quickcheck::TestResult::discard(); 420 | } 421 | 422 | // If `map_ceil` returns `None`, `map_ceil_and_unmap` must 423 | // return `None`, too. 424 | assert_eq!(TheTlsf::map_ceil_and_unmap(size), None); 425 | quickcheck::TestResult::passed() 426 | } 427 | 428 | #[quickcheck] 429 | fn pool_size_to_contain_allocation(size: usize, align: u32)-> quickcheck::TestResult { 430 | let align = (super::GRANULARITY / 2) << (align % 5); 431 | let size = size.wrapping_mul(align); 432 | if size > 500_000 { 433 | // Let's limit pool size 434 | return quickcheck::TestResult::discard(); 435 | } 436 | 437 | let layout = Layout::from_size_align(size, align).unwrap(); 438 | log::debug!("layout = {:?}", layout); 439 | 440 | let pool_size = if let Some(x) = TheTlsf::pool_size_to_contain_allocation(layout) { 441 | x 442 | } else { 443 | return quickcheck::TestResult::discard(); 444 | }; 445 | log::debug!("pool_size_to_contain_allocation = {:?}", pool_size); 446 | 447 | assert_eq!(pool_size % super::GRANULARITY, 0); 448 | 449 | // Create a well-aligned pool 450 | type Bk = Align<[u8; 64]>; 451 | assert_eq!(std::mem::size_of::(), 64); 452 | assert_eq!(std::mem::align_of::(), 64); 453 | let mut pool: Vec> = Vec::new(); 454 | pool.reserve((pool_size + 63) / 64); 455 | let pool = unsafe { 456 | std::slice::from_raw_parts_mut( 457 | pool.as_mut_ptr() as *mut MaybeUninit, 458 | pool_size, 459 | ) 460 | }; 461 | 462 | let mut tlsf: TheTlsf = Tlsf::new(); 463 | tlsf.insert_free_block(pool); 464 | 465 | // The allocation should success because 466 | // `pool_size_to_contain_allocation` said so 467 | tlsf.allocate(layout) 468 | .expect("allocation unexpectedly failed"); 469 | 470 | quickcheck::TestResult::passed() 471 | } 472 | } 473 | }; 474 | } 475 | 476 | gen_test!(tlsf_u8_u8_1_1, u8, u8, 1, 1); 477 | gen_test!(tlsf_u8_u8_1_2, u8, u8, 1, 2); 478 | gen_test!(tlsf_u8_u8_1_4, u8, u8, 1, 4); 479 | gen_test!(tlsf_u8_u8_1_8, u8, u8, 1, 8); 480 | gen_test!(tlsf_u8_u8_3_4, u8, u8, 3, 4); 481 | gen_test!(tlsf_u8_u8_5_4, u8, u8, 5, 4); 482 | gen_test!(tlsf_u8_u8_8_1, u8, u8, 8, 1); 483 | gen_test!(tlsf_u8_u8_8_8, u8, u8, 8, 8); 484 | gen_test!(tlsf_u16_u8_3_4, u16, u8, 3, 4); 485 | gen_test!(tlsf_u16_u8_11_4, u16, u8, 11, 4); 486 | gen_test!(tlsf_u16_u8_16_4, u16, u8, 16, 4); 487 | gen_test!(tlsf_u16_u16_3_16, u16, u16, 3, 16); 488 | gen_test!(tlsf_u16_u16_11_16, u16, u16, 11, 16); 489 | gen_test!(tlsf_u16_u16_16_16, u16, u16, 16, 16); 490 | gen_test!(tlsf_u16_u32_3_16, u16, u32, 3, 16); 491 | gen_test!(tlsf_u16_u32_11_16, u16, u32, 11, 16); 492 | gen_test!(tlsf_u16_u32_16_16, u16, u32, 16, 16); 493 | gen_test!(tlsf_u16_u32_3_32, u16, u32, 3, 32); 494 | gen_test!(tlsf_u16_u32_11_32, u16, u32, 11, 32); 495 | gen_test!(tlsf_u16_u32_16_32, u16, u32, 16, 32); 496 | gen_test!(tlsf_u32_u32_20_32, u32, u32, 20, 32); 497 | gen_test!(tlsf_u32_u32_27_32, u32, u32, 27, 32); 498 | gen_test!(tlsf_u32_u32_28_32, u32, u32, 28, 32); 499 | gen_test!(tlsf_u32_u32_29_32, u32, u32, 29, 32); 500 | gen_test!(tlsf_u32_u32_32_32, u32, u32, 32, 32); 501 | gen_test!(tlsf_u64_u8_58_8, u64, u64, 58, 8); 502 | gen_test!(tlsf_u64_u8_59_8, u64, u64, 59, 8); 503 | gen_test!(tlsf_u64_u8_60_8, u64, u64, 60, 8); 504 | gen_test!(tlsf_u64_u8_61_8, u64, u64, 61, 8); 505 | gen_test!(tlsf_u64_u8_64_8, u64, u64, 64, 8); 506 | -------------------------------------------------------------------------------- /crates/rlsf/src/utils.rs: -------------------------------------------------------------------------------- 1 | use core::{mem::MaybeUninit, ptr::NonNull}; 2 | 3 | /// Polyfill for 4 | #[inline] 5 | pub fn nonnull_slice_from_raw_parts(ptr: NonNull, len: usize) -> NonNull<[T]> { 6 | unsafe { NonNull::new_unchecked(core::ptr::slice_from_raw_parts_mut(ptr.as_ptr(), len)) } 7 | } 8 | 9 | /// Polyfill for 10 | #[inline] 11 | pub fn nonnull_slice_len(ptr: NonNull<[T]>) -> usize { 12 | // Safety: We are just reading the slice length embedded in the fat 13 | // pointer and not dereferencing the pointer. We also convert it 14 | // to `*mut [MaybeUninit]` just in case because the slice 15 | // might be uninitialized. 16 | unsafe { (*(ptr.as_ptr() as *const [MaybeUninit])).len() } 17 | } 18 | 19 | // Polyfill for 20 | #[inline] 21 | pub fn nonnull_slice_start(ptr: NonNull<[T]>) -> NonNull { 22 | unsafe { NonNull::new_unchecked(ptr.as_ptr() as *mut T) } 23 | } 24 | 25 | #[inline] 26 | pub fn nonnull_slice_end(ptr: NonNull<[T]>) -> *mut T { 27 | (ptr.as_ptr() as *mut T).wrapping_add(nonnull_slice_len(ptr)) 28 | } 29 | -------------------------------------------------------------------------------- /crates/rlsf/tests/global.rs: -------------------------------------------------------------------------------- 1 | // Adopted from 2 | // https://github.com/alexcrichton/dlmalloc-rs/blob/master/tests/global.rs 3 | use std::collections::HashMap; 4 | 5 | #[global_allocator] 6 | #[cfg(any(all(target_arch = "wasm32", not(target_feature = "atomics")), unix))] 7 | static A: rlsf::SmallGlobalTlsf = rlsf::SmallGlobalTlsf::new(); 8 | 9 | #[test] 10 | fn foo() { 11 | println!("hello"); 12 | } 13 | 14 | #[test] 15 | fn map() { 16 | let mut m = HashMap::new(); 17 | m.insert(1, 2); 18 | m.insert(5, 3); 19 | drop(m); 20 | } 21 | 22 | #[test] 23 | fn strings() { 24 | format!("foo, bar, {}", "baz"); 25 | } 26 | 27 | #[cfg(not(target_arch = "wasm32"))] 28 | #[test] 29 | fn threads() { 30 | assert!(std::thread::spawn(|| panic!()).join().is_err()); 31 | } 32 | 33 | #[test] 34 | fn test_larger_than_word_alignment() { 35 | use std::mem; 36 | 37 | // Align to 32 bytes. 38 | #[repr(align(32))] 39 | struct Align32(u8); 40 | 41 | assert_eq!(mem::align_of::(), 32); 42 | 43 | for _ in 0..1000 { 44 | let b = Box::new(Align32(42)); 45 | 46 | let p = Box::into_raw(b); 47 | assert_eq!(p as usize % 32, 0, "{:p} should be aligned to 32", p); 48 | 49 | unsafe { 50 | let b = Box::from_raw(p); 51 | assert_eq!(b.0, 42); 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /crates/rlsf_benchmark_farcri/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rlsf_benchmark_farcri" 3 | edition = "2018" 4 | version = "0.0.0" 5 | license = "MIT/Apache-2.0" 6 | publish = false 7 | autobenches = false 8 | 9 | [dev-dependencies] 10 | rlsf = { path = "../rlsf" } 11 | log = "0.4.8" 12 | linked_list_allocator = "0.8.11" 13 | buddy-alloc = "0.4.1" 14 | wee_alloc = { version = "0.4.5", features = ["static_array_backend"] } 15 | dlmalloc = { version = "0.2.1" } 16 | umm-malloc-sys = "0.1.1" 17 | 18 | [dev-dependencies.farcri] 19 | git = "https://github.com/yvt/farcri-rs.git" 20 | rev = "dbd6544d0411b8751871a6315ba4d8a08ca52d07" 21 | 22 | [[bench]] 23 | name = "stress" 24 | harness = false 25 | 26 | [[bench]] 27 | name = "stress_wee" 28 | harness = false 29 | -------------------------------------------------------------------------------- /crates/rlsf_benchmark_farcri/benches/stress.rs: -------------------------------------------------------------------------------- 1 | //! Benchmark for `rlsf` and some other allocators 2 | #![no_std] 3 | #![feature(const_maybe_uninit_assume_init)] 4 | #![feature(slice_ptr_len)] 5 | // TODO: Get rid of this conditional attribute; it's FarCri.rs's 6 | // implementation detail 7 | #![cfg_attr(target_os = "none", no_main)] 8 | 9 | use core::{cell::Cell, ptr::NonNull}; 10 | use farcri::{criterion_group, criterion_main, Criterion}; 11 | use rlsf::Tlsf; 12 | 13 | mod stress_common; 14 | use self::stress_common::{bench_one, ARENA}; 15 | 16 | fn criterion_benchmark(c: &mut Criterion) { 17 | c.bench_function("noop", |b| b.iter(noop)); 18 | 19 | bench_one( 20 | c, 21 | "rlsf", 22 | unsafe { ARENA.len() }, 23 | |arena_len| { 24 | let mut tlsf: Tlsf<'_, u16, u16, 12, 16> = Tlsf::new(); 25 | let arena = unsafe { &mut ARENA[..arena_len] }; 26 | tlsf.insert_free_block(&mut *arena); 27 | tlsf 28 | }, 29 | |tlsf, layout| tlsf.allocate(layout).unwrap(), 30 | |tlsf, p, layout| unsafe { tlsf.deallocate(p, layout.align()) }, 31 | ); 32 | 33 | bench_one( 34 | c, 35 | "umm_malloc", 36 | unsafe { ARENA.len() }, 37 | |arena_len| unsafe { 38 | umm_malloc_sys::umm_init(ARENA.as_mut_ptr() as _, arena_len); 39 | }, 40 | |_allocator, layout| unsafe { 41 | // ignoring `layout.align()` 42 | NonNull::new(umm_malloc_sys::umm_malloc(layout.size())) 43 | .unwrap() 44 | .cast() 45 | }, 46 | |_allocator, p, _layout| unsafe { umm_malloc_sys::umm_free(p.as_ptr() as _) }, 47 | ); 48 | 49 | bench_one( 50 | c, 51 | "linked_list_allocator", 52 | unsafe { ARENA.len() }, 53 | |arena_len| { 54 | let mut heap = linked_list_allocator::Heap::empty(); 55 | let arena = unsafe { &mut ARENA[..arena_len] }; 56 | unsafe { heap.init(arena.as_ptr() as usize, arena.len()) }; 57 | heap 58 | }, 59 | |heap, layout| heap.allocate_first_fit(layout).unwrap(), 60 | |heap, p, layout| unsafe { heap.deallocate(p, layout) }, 61 | ); 62 | 63 | use buddy_alloc::buddy_alloc; 64 | bench_one( 65 | c, 66 | "buddy_alloc", 67 | unsafe { ARENA.len() }, 68 | #[allow(const_item_mutation)] 69 | |arena_len| unsafe { 70 | let arena = &mut ARENA[..arena_len]; 71 | buddy_alloc::BuddyAlloc::new(buddy_alloc::BuddyAllocParam::new( 72 | arena.as_ptr() as *const u8, 73 | arena.len(), 74 | 16, 75 | )) 76 | }, 77 | |heap, layout| NonNull::new(heap.malloc(layout.size())).unwrap(), 78 | |heap, p, _| heap.free(p.as_ptr()), 79 | ); 80 | 81 | bench_one( 82 | c, 83 | "dlmalloc", 84 | unsafe { ARENA.len() - PAGE_SIZE }, 85 | #[allow(const_item_mutation)] 86 | |arena_len| unsafe { 87 | let arena = &mut ARENA[..arena_len]; 88 | 89 | dlmalloc::Dlmalloc::new_with_allocator(DlBumpAllocator::new(arena)) 90 | }, 91 | |heap, layout| unsafe { NonNull::new(heap.malloc(layout.size(), layout.align())).unwrap() }, 92 | |heap, p, layout| unsafe { heap.free(p.as_ptr(), layout.size(), layout.align()) }, 93 | ); 94 | } 95 | 96 | struct DlBumpAllocator { 97 | start_free: Cell, 98 | end: usize, 99 | } 100 | 101 | const PAGE_SIZE: usize = 4096; 102 | 103 | impl DlBumpAllocator { 104 | unsafe fn new(arena: *mut [core::mem::MaybeUninit]) -> Self { 105 | let start = arena as *mut core::mem::MaybeUninit as usize; 106 | let end = start + arena.len(); 107 | let start = (start + (PAGE_SIZE - 1)) & !(PAGE_SIZE - 1); 108 | assert!(start < end); 109 | Self { 110 | start_free: Cell::new(start), 111 | end, 112 | } 113 | } 114 | } 115 | 116 | unsafe impl dlmalloc::Allocator for DlBumpAllocator { 117 | fn alloc(&self, size: usize) -> (*mut u8, usize, u32) { 118 | let start_free = self.start_free.get(); 119 | let new_start_free = start_free.checked_add(size).filter(|&x| x <= self.end); 120 | if let Some(new_start_free) = new_start_free { 121 | log::debug!( 122 | "DlBumpAllocator: allocated alloc({}) at {:?}", 123 | size, 124 | start_free, 125 | ); 126 | self.start_free.set(new_start_free); 127 | (start_free as *mut u8, size, 0) 128 | } else { 129 | log::debug!( 130 | "DlBumpAllocator: alloc({}) failed; only {} bytes free", 131 | size, 132 | self.end - start_free, 133 | ); 134 | (0 as _, 0, 0) 135 | } 136 | } 137 | fn remap(&self, _ptr: *mut u8, _oldsize: usize, _newsize: usize, _can_move: bool) -> *mut u8 { 138 | 0 as _ 139 | } 140 | fn free_part(&self, _ptr: *mut u8, _oldsize: usize, _newsize: usize) -> bool { 141 | false 142 | } 143 | fn free(&self, _ptr: *mut u8, _size: usize) -> bool { 144 | false 145 | } 146 | fn can_release_part(&self, _flags: u32) -> bool { 147 | false 148 | } 149 | fn allocates_zeros(&self) -> bool { 150 | true 151 | } 152 | fn page_size(&self) -> usize { 153 | PAGE_SIZE 154 | } 155 | } 156 | 157 | #[inline(never)] 158 | fn noop() {} 159 | 160 | criterion_group!(benches, criterion_benchmark); 161 | criterion_main!(benches); 162 | -------------------------------------------------------------------------------- /crates/rlsf_benchmark_farcri/benches/stress_common.rs: -------------------------------------------------------------------------------- 1 | //! This module is shared by `stress(?!_common)(_.*)` benchmark tests 2 | use core::{alloc::Layout, mem::MaybeUninit, ptr::NonNull}; 3 | use farcri::{BenchmarkId, Criterion}; 4 | 5 | /// The default arena, which `bench_one`'s caller can choose to use 6 | #[allow(dead_code)] 7 | pub static mut ARENA: [MaybeUninit; 1024 * 70] = unsafe { MaybeUninit::uninit().assume_init() }; 8 | 9 | static mut ALLOCS: [(NonNull, Layout); 256] = [(NonNull::dangling(), unsafe { 10 | Layout::from_size_align_unchecked(0, 1) 11 | }); 256]; 12 | 13 | struct Xorshift32(u32); 14 | 15 | impl Xorshift32 { 16 | fn next(&mut self) -> u32 { 17 | self.0 ^= self.0 << 13; 18 | self.0 ^= self.0 >> 17; 19 | self.0 ^= self.0 << 5; 20 | self.0 21 | } 22 | } 23 | 24 | pub fn bench_one( 25 | c: &mut Criterion, 26 | name: &str, 27 | arena_capacity: usize, 28 | mut init: impl FnMut(usize) -> T, 29 | mut alloc: impl FnMut(&mut T, Layout) -> NonNull, 30 | mut dealloc: impl FnMut(&mut T, NonNull, Layout), 31 | ) { 32 | let mut group = c.benchmark_group(name); 33 | let allocs = unsafe { &mut ALLOCS }; 34 | 35 | for &(min_size, mask) in &[ 36 | (1, 7), 37 | (1, 15), 38 | (1, 63), 39 | (1, 255), 40 | (16, 15), 41 | (16, 63), 42 | (16, 127), 43 | (64, 63), 44 | (64, 127), 45 | (128, 127), 46 | ] { 47 | let size_range = min_size..min_size + mask + 1; 48 | let num_allocs = (arena_capacity / (size_range.end + 8) / 2).min(allocs.len()); 49 | let allocs = &mut allocs[..num_allocs]; 50 | 51 | let mut state = init(arena_capacity); 52 | 53 | let mut rng = Xorshift32(0x12345689); 54 | let mut next_layout = || { 55 | let len = (rng.next() as usize & mask) + min_size; 56 | let align = 4 << (rng.next() & 3); 57 | unsafe { Layout::from_size_align_unchecked(len, align) } 58 | }; 59 | 60 | // Fill `allocs` 61 | for al in allocs.iter_mut() { 62 | let layout = next_layout(); 63 | let p = alloc(&mut state, layout); 64 | *al = (p, layout); 65 | } 66 | 67 | group.bench_function( 68 | BenchmarkId::from_parameter(&format_args!("size {:?}", size_range)), 69 | |b| { 70 | let mut alloc_i = 0; 71 | b.iter(|| { 72 | // deallocate 73 | let (p, layout) = allocs[alloc_i & (allocs.len() - 1)]; 74 | dealloc(&mut state, p, layout); 75 | 76 | // allocate 77 | let layout = next_layout(); 78 | let p = alloc(&mut state, layout); 79 | allocs[alloc_i & (allocs.len() - 1)] = (p, layout); 80 | 81 | alloc_i = alloc_i.wrapping_add(1); 82 | }); 83 | }, 84 | ); 85 | 86 | // Deallocate 87 | for &(p, layout) in allocs.iter() { 88 | dealloc(&mut state, p, layout); 89 | } 90 | } 91 | } 92 | 93 | /// Like `bench_one`, but uses an external unknown-sized heap (such as a 94 | /// global allocator). 95 | #[allow(dead_code)] 96 | pub fn bench_one_by_external_heap( 97 | c: &mut Criterion, 98 | name: &str, 99 | 100 | mut alloc: impl FnMut(Layout) -> Option>, 101 | mut dealloc: impl FnMut(NonNull, Layout), 102 | ) { 103 | // Determine the capacity of the global heap 104 | let arena_capacity = (1..24) 105 | .map(|i| 1 << i) 106 | .take_while(|&size| { 107 | let layout = Layout::from_size_align(size, 1).unwrap(); 108 | let p = alloc(layout); 109 | log::debug!("probing arena size {} → {:?}", size, p); 110 | if let Some(p) = p { 111 | dealloc(p, layout); 112 | true 113 | } else { 114 | false 115 | } 116 | }) 117 | .last() 118 | .unwrap(); 119 | 120 | log::info!("arena_capacity = {}", arena_capacity); 121 | 122 | bench_one( 123 | c, 124 | name, 125 | arena_capacity, 126 | |arena_size| { 127 | assert!(arena_size == arena_capacity); 128 | }, 129 | |_, layout| alloc(layout).unwrap(), 130 | |_, p, layout| dealloc(p, layout), 131 | ); 132 | } 133 | -------------------------------------------------------------------------------- /crates/rlsf_benchmark_farcri/benches/stress_wee.rs: -------------------------------------------------------------------------------- 1 | //! Benchmark for `wee_alloc` (which only supports being a global allocator) 2 | //! 3 | //! Specify `WEE_ALLOC_STATIC_ARRAY_BACKEND_BYTES=65536` by an environmental 4 | //! variable. 5 | //! 6 | //! TODO: get this working, wee_alloc behaves too odd 7 | #![no_std] 8 | #![feature(const_maybe_uninit_assume_init)] 9 | #![feature(slice_ptr_len)] 10 | #![feature(default_alloc_error_handler)] 11 | // TODO: Get rid of this conditional attribute; it's FarCri.rs's 12 | // implementation detail 13 | #![cfg_attr(target_os = "none", no_main)] 14 | 15 | extern crate alloc; 16 | 17 | use core::ptr::NonNull; 18 | use farcri::{criterion_group, criterion_main, Criterion}; 19 | 20 | mod stress_common; 21 | use self::stress_common::bench_one_by_external_heap; 22 | 23 | #[cfg(target_os = "none")] 24 | #[global_allocator] 25 | static _ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; 26 | 27 | fn criterion_benchmark(c: &mut Criterion) { 28 | c.bench_function("noop", |b| b.iter(noop)); 29 | 30 | bench_one_by_external_heap( 31 | c, 32 | "wee_alloc", 33 | |layout| unsafe { NonNull::new(alloc::alloc::alloc(layout)) }, 34 | |p, layout| unsafe { alloc::alloc::dealloc(p.as_ptr(), layout) }, 35 | ); 36 | } 37 | 38 | #[inline(never)] 39 | fn noop() {} 40 | 41 | criterion_group!(benches, criterion_benchmark); 42 | criterion_main!(benches); 43 | -------------------------------------------------------------------------------- /crates/rlsf_benchmark_farcri/rust-toolchain: -------------------------------------------------------------------------------- 1 | nightly-2021-03-23 2 | -------------------------------------------------------------------------------- /crates/rlsf_override/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rlsf_override" 3 | version = "0.1.0" 4 | authors = ["yvt "] 5 | license = "MIT/Apache-2.0" 6 | edition = "2018" 7 | description = "Overrides C memory allocation functions with `rlsf`" 8 | repository = "https://github.com/yvt/rlsf" 9 | publish = false # still experimental 10 | 11 | [lib] 12 | crate-type = ["cdylib", "rlib", "staticlib"] 13 | path = "src/lib.rs" 14 | 15 | [dependencies] 16 | rlsf = { version = "0.2.1", path = "../rlsf" } 17 | libc = "0.2.50" 18 | 19 | [dev-dependencies] 20 | bzip2 = "0.4" 21 | -------------------------------------------------------------------------------- /crates/rlsf_override/README.md: -------------------------------------------------------------------------------- 1 | # rlsf_override 2 | 3 | 4 | 5 |

6 | docs.rs 7 |

8 | 9 | Overrides C memory allocation functions with [`::rlsf`]. 10 | 11 | ## License 12 | 13 | MIT/Apache-2.0 14 | -------------------------------------------------------------------------------- /crates/rlsf_override/src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Overrides C memory allocation functions with [`::rlsf`]. 2 | use rlsf::CAlloc; 3 | use std::{ 4 | alloc::Layout, 5 | os::raw::{c_int, c_void}, 6 | ptr::{null_mut, NonNull}, 7 | }; 8 | 9 | #[global_allocator] 10 | pub static ALLOC: rlsf::GlobalTlsf = rlsf::GlobalTlsf::new(); 11 | 12 | /// The alignment guaranteed by `malloc`. 13 | // `target_arch = "asmjs"` was removed in Rust 1.76.0 14 | #[allow(unexpected_cfgs)] 15 | const MIN_ALIGN: usize = match () { 16 | #[cfg(any( 17 | target_arch = "x86", 18 | target_arch = "arm", 19 | target_arch = "mips", 20 | target_arch = "powerpc", 21 | target_arch = "powerpc64", 22 | target_arch = "sparc", 23 | target_arch = "asmjs", 24 | target_arch = "wasm32", 25 | target_arch = "hexagon", 26 | target_arch = "riscv32" 27 | ))] 28 | () => 8, 29 | #[cfg(any( 30 | target_arch = "x86_64", 31 | target_arch = "aarch64", 32 | target_arch = "mips64", 33 | target_arch = "s390x", 34 | target_arch = "sparc64", 35 | target_arch = "riscv64" 36 | ))] 37 | () => 16, 38 | }; 39 | 40 | #[no_mangle] 41 | pub unsafe extern "C" fn malloc(size: usize) -> *mut c_void { 42 | aligned_alloc(MIN_ALIGN, size) 43 | } 44 | 45 | #[no_mangle] 46 | pub unsafe extern "C" fn malloc_usable_size(p: *mut c_void) -> usize { 47 | if let Some(p) = NonNull::new(p) { 48 | CAlloc::allocation_usable_size(&ALLOC, p.cast()) 49 | } else { 50 | 0 51 | } 52 | } 53 | 54 | #[inline] 55 | fn page_size() -> usize { 56 | unsafe { libc::sysconf(libc::_SC_PAGESIZE) as usize } 57 | } 58 | 59 | #[no_mangle] 60 | pub unsafe extern "C" fn valloc(size: usize) -> *mut c_void { 61 | aligned_alloc(page_size(), size) 62 | } 63 | 64 | #[no_mangle] 65 | pub unsafe extern "C" fn pvalloc(size: usize) -> *mut c_void { 66 | let page_size = page_size(); 67 | if let Some(size) = size 68 | .checked_add(page_size - 1) 69 | .map(|x| x & !(page_size - 1)) 70 | { 71 | aligned_alloc(page_size, size) 72 | } else { 73 | null_mut() 74 | } 75 | } 76 | 77 | #[no_mangle] 78 | pub unsafe extern "C" fn calloc(number: usize, size: usize) -> *mut c_void { 79 | let layout = size 80 | .checked_mul(number) 81 | .and_then(|len| Layout::from_size_align(len, MIN_ALIGN).ok()); 82 | if let Some((ptr, size)) = 83 | layout.and_then(|layout| CAlloc::allocate(&ALLOC, layout).map(|p| (p, layout.size()))) 84 | { 85 | ptr.as_ptr().write_bytes(0, size); 86 | ptr.as_ptr() as *mut c_void 87 | } else { 88 | null_mut() 89 | } 90 | } 91 | 92 | #[no_mangle] 93 | pub unsafe extern "C" fn posix_memalign( 94 | out_ptr: *mut *mut c_void, 95 | alignment: usize, 96 | size: usize, 97 | ) -> c_int { 98 | let ptr = aligned_alloc(alignment, size); 99 | *out_ptr = ptr as *mut c_void; 100 | if ptr.is_null() { 101 | libc::ENOMEM 102 | } else { 103 | 0 104 | } 105 | } 106 | 107 | #[no_mangle] 108 | pub unsafe extern "C" fn aligned_alloc(alignment: usize, size: usize) -> *mut c_void { 109 | let layout = Layout::from_size_align(size, alignment).ok(); 110 | if let Some(ptr) = layout.and_then(|layout| CAlloc::allocate(&ALLOC, layout)) { 111 | ptr.as_ptr() as *mut c_void 112 | } else { 113 | null_mut() 114 | } 115 | } 116 | 117 | #[no_mangle] 118 | pub unsafe extern "C" fn memalign(alignment: usize, size: usize) -> *mut c_void { 119 | aligned_alloc(alignment, size) 120 | } 121 | 122 | #[no_mangle] 123 | pub unsafe extern "C" fn realloc(ptr: *mut c_void, size: usize) -> *mut c_void { 124 | if let Some(ptr) = NonNull::new(ptr) { 125 | // `realloc` doesn't preserve the allocation's original alignment 126 | // 127 | Layout::from_size_align(size, MIN_ALIGN) 128 | .ok() 129 | .and_then(|layout| CAlloc::reallocate(&ALLOC, ptr.cast(), layout)) 130 | .map(|ptr| ptr.as_ptr() as *mut c_void) 131 | .unwrap_or(null_mut()) 132 | } else { 133 | malloc(size) 134 | } 135 | } 136 | 137 | #[no_mangle] 138 | pub unsafe extern "C" fn free(ptr: *mut c_void) { 139 | if let Some(ptr) = NonNull::new(ptr) { 140 | CAlloc::deallocate(&ALLOC, ptr.cast()); 141 | } 142 | } 143 | 144 | // TODO: Find a way to define these in a C++ source file and make sure the 145 | // symbols are exported by the final cdylib file 146 | /// `operator delete[](void*, unsigned long, std::align_val_t)` 147 | #[no_mangle] 148 | pub unsafe extern "C" fn _ZdaPvmSt11align_val_t(p: *mut c_void, _: usize, _: usize) { 149 | free(p); 150 | } 151 | 152 | /// `operator delete[](void*, std::align_val_t, std::nothrow_t const&)` 153 | #[no_mangle] 154 | pub unsafe extern "C" fn _ZdaPvSt11align_val_tRKSt9nothrow_t(p: *mut c_void, _: usize, _: &c_void) { 155 | free(p); 156 | } 157 | 158 | /// `operator delete[](void*, std::align_val_t)` 159 | #[no_mangle] 160 | pub unsafe extern "C" fn _ZdaPvSt11align_val_t(p: *mut c_void, _: usize) { 161 | free(p); 162 | } 163 | 164 | /// `operator delete(void*, unsigned long, std::align_val_t)` 165 | #[no_mangle] 166 | pub unsafe extern "C" fn _ZdlPvmSt11align_val_t(p: *mut c_void, _: usize, _: usize) { 167 | free(p); 168 | } 169 | 170 | /// `operator delete(void*, std::align_val_t, std::nothrow_t const&)` 171 | #[no_mangle] 172 | pub unsafe extern "C" fn _ZdlPvSt11align_val_tRKSt9nothrow_t(p: *mut c_void, _: usize, _: usize) { 173 | free(p); 174 | } 175 | 176 | /// `operator delete(void*, std::align_val_t)` 177 | #[no_mangle] 178 | pub unsafe extern "C" fn _ZdlPvSt11align_val_t(p: *mut c_void, _: usize) { 179 | free(p); 180 | } 181 | 182 | /// `operator new[](unsigned long, std::align_val_t, std::nothrow_t const&)` 183 | #[no_mangle] 184 | pub unsafe extern "C" fn _ZnamSt11align_val_tRKSt9nothrow_t( 185 | size: usize, 186 | align: usize, 187 | _: &c_void, 188 | ) -> *mut c_void { 189 | cpp_new_impl(size, align, true) 190 | } 191 | 192 | /// `operator new[](unsigned long, std::align_val_t)` 193 | #[no_mangle] 194 | pub unsafe extern "C" fn _ZnamSt11align_val_t(size: usize, align: usize) -> *mut c_void { 195 | cpp_new_impl(size, align, false) 196 | } 197 | 198 | /// `operator new(unsigned long, std::align_val_t, std::nothrow_t const&)` 199 | #[no_mangle] 200 | pub unsafe extern "C" fn _ZnwmSt11align_val_tRKSt9nothrow_t( 201 | size: usize, 202 | align: usize, 203 | _: &c_void, 204 | ) -> *mut c_void { 205 | cpp_new_impl(size, align, true) 206 | } 207 | 208 | /// `operator new(unsigned long, std::align_val_t)` 209 | #[no_mangle] 210 | pub unsafe extern "C" fn _ZnwmSt11align_val_t(size: usize, align: usize) -> *mut c_void { 211 | cpp_new_impl(size, align, false) 212 | } 213 | 214 | /// `operator delete[](void*, unsigned long)` 215 | #[no_mangle] 216 | pub unsafe extern "C" fn _ZdaPvm(p: *mut c_void, _: usize) { 217 | free(p); 218 | } 219 | 220 | /// `operator delete(void*, unsigned long)` 221 | #[no_mangle] 222 | pub unsafe extern "C" fn _ZdlPvm(p: *mut c_void, _: usize) { 223 | free(p); 224 | } 225 | 226 | /// `operator delete[](void*, std::nothrow_t const&)` 227 | #[no_mangle] 228 | pub unsafe extern "C" fn _ZdaPvRKSt9nothrow_t(p: *mut c_void, _: &c_void) { 229 | free(p); 230 | } 231 | 232 | /// `operator delete(void*, std::nothrow_t const&)` 233 | #[no_mangle] 234 | pub unsafe extern "C" fn _ZdlPvRKSt9nothrow_t(p: *mut c_void, _: &c_void) { 235 | free(p); 236 | } 237 | 238 | /// `operator delete[](void*)` 239 | #[no_mangle] 240 | pub unsafe extern "C" fn _ZdaPv(p: *mut c_void) { 241 | free(p); 242 | } 243 | 244 | /// `operator delete(void*)` 245 | #[no_mangle] 246 | pub unsafe extern "C" fn _ZdlPv(p: *mut c_void) { 247 | free(p); 248 | } 249 | 250 | /// `operator new[](unsigned long, std::nothrow_t const&)` 251 | #[no_mangle] 252 | pub unsafe extern "C" fn _ZnamRKSt9nothrow_t(size: usize, _: &c_void) -> *mut c_void { 253 | cpp_new_impl(size, 0, true) 254 | } 255 | 256 | /// `operator new(unsigned long, std::nothrow_t const&)` 257 | #[no_mangle] 258 | pub unsafe extern "C" fn _ZnwmRKSt9nothrow_t(size: usize, _: &c_void) -> *mut c_void { 259 | cpp_new_impl(size, 0, true) 260 | } 261 | 262 | /// `operator new[](unsigned long)` 263 | #[no_mangle] 264 | pub unsafe extern "C" fn _Znam(size: usize) -> *mut c_void { 265 | cpp_new_impl(size, 0, false) 266 | } 267 | 268 | /// `operator new(unsigned long)` 269 | #[no_mangle] 270 | pub unsafe extern "C" fn _Znwm(size: usize) -> *mut c_void { 271 | cpp_new_impl(size, 0, false) 272 | } 273 | 274 | #[inline] 275 | fn cpp_new_impl(size: usize, align: usize, is_noexcept: bool) -> *mut c_void { 276 | let ptr = unsafe { 277 | if align == 0 { 278 | malloc(size) 279 | } else { 280 | aligned_alloc(align, size) 281 | } 282 | }; 283 | if !is_noexcept && ptr.is_null() { 284 | // TODO: Throw an actual C++ exception through `extern "C-unwind"` 285 | // (rust-lang/rust#74990) 286 | panic!("allocation of size {} and alignment {} failed", size, align); 287 | } 288 | ptr 289 | } 290 | -------------------------------------------------------------------------------- /crates/rlsf_override/tests/overridden.rs: -------------------------------------------------------------------------------- 1 | use rlsf_override as _; 2 | 3 | #[test] 4 | fn hashset() { 5 | let mut m = std::collections::HashSet::new(); 6 | for i in 0..10000 { 7 | m.insert(i); 8 | } 9 | } 10 | 11 | /// Test `libbz2`, which uses `malloc` and `free` internally 12 | #[test] 13 | fn bz2() { 14 | use bzip2::read::{BzDecoder, BzEncoder}; 15 | use bzip2::Compression; 16 | use std::io::prelude::*; 17 | 18 | let data = "Hello, World!".as_bytes(); 19 | let compressor = BzEncoder::new(data, Compression::best()); 20 | let mut decompressor = BzDecoder::new(compressor); 21 | 22 | let mut contents = String::new(); 23 | decompressor.read_to_string(&mut contents).unwrap(); 24 | assert_eq!(contents, "Hello, World!"); 25 | } 26 | -------------------------------------------------------------------------------- /rust-toolchain: -------------------------------------------------------------------------------- 1 | 1.61.0 2 | -------------------------------------------------------------------------------- /scripts/update-readme.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | cd "`dirname "$0"`/../crates/rlsf" 4 | cargo readme -t ../../README.tpl > ../../README.md 5 | 6 | cd ../rlsf_override 7 | cargo readme -t ../../README.tpl > README.md 8 | --------------------------------------------------------------------------------