Repository: rust-embedded/embedded-alloc
Branch: master
Commit: 13c18de83178
Files: 21
Total size: 51.6 KB
Directory structure:
gitextract_10arganv/
├── .cargo/
│ └── config.toml
├── .github/
│ ├── CODEOWNERS
│ └── workflows/
│ └── ci.yml
├── .gitignore
├── CHANGELOG.md
├── CODE_OF_CONDUCT.md
├── Cargo.toml
├── LICENSE-APACHE
├── LICENSE-MIT
├── README.md
├── examples/
│ ├── allocator_api.rs
│ ├── exhaustion.rs
│ ├── global_alloc.rs
│ ├── llff_integration_test.rs
│ ├── tlsf_integration_test.rs
│ └── track_usage.rs
├── memory.x
├── qemu-runner.sh
└── src/
├── lib.rs
├── llff.rs
└── tlsf.rs
================================================
FILE CONTENTS
================================================
================================================
FILE: .cargo/config.toml
================================================
[build]
# Common embedded build targets
target = "thumbv7em-none-eabihf"
# target = "thumbv6m-none-eabi"
[target.thumbv7em-none-eabihf]
# used to run the qemu_test.rs example with QEMU
runner = "./qemu-runner.sh --target thumbv7em-none-eabihf"
rustflags = [
"-Clink-arg=-Tlink.x",
"-Clink-arg=-Tdefmt.x",
# Can be useful for debugging and to inspect where the heap memory is placed/linked.
# "-Clink-args=-Map=app.map"
]
[target.thumbv6m-none-eabi]
# used to run the qemu_test.rs example with QEMU
runner = "./qemu-runner.sh --target thumbv6m-none-eabi"
rustflags = [
"-Clink-arg=-Tlink.x",
"-Clink-arg=-Tdefmt.x",
]
[env]
DEFMT_LOG="info"
================================================
FILE: .github/CODEOWNERS
================================================
* @rust-embedded/libs
================================================
FILE: .github/workflows/ci.yml
================================================
on:
pull_request: # Run CI for PRs on any branch
merge_group: # Run CI for the GitHub merge queue
workflow_dispatch: # Run CI when manually requested
schedule:
# Run every week at 8am UTC Saturday
- cron: '0 8 * * SAT'
name: Continuous integration
jobs:
check:
runs-on: ubuntu-latest
env: {"RUSTFLAGS": "-D warnings"}
strategy:
matrix:
target:
- thumbv6m-none-eabi
- thumbv7em-none-eabihf
toolchain:
- stable
- nightly
steps:
- uses: actions/checkout@v6
- uses: dtolnay/rust-toolchain@master
with:
targets: ${{ matrix.target }}
toolchain: ${{ matrix.toolchain }}
- run: cargo check --target=${{ matrix.target }} --example global_alloc
- if: ${{ matrix.toolchain == 'nightly' }}
run: cargo check --target=${{ matrix.target }} --examples --all-features
- uses: imjohnbo/issue-bot@v3
if: |
failure()
&& github.event_name == 'schedule'
with:
title: CI Failure
labels: ci
body: |
Scheduled CI run failed. Details:
https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: dtolnay/rust-toolchain@master
with:
targets: thumbv7em-none-eabihf
toolchain: nightly
- name: Install QEMU
run: |
sudo apt update
sudo apt install qemu-system-arm
- run: qemu-system-arm --version
- run: cargo +nightly run --target thumbv7em-none-eabihf --example llff_integration_test --all-features
- run: cargo +nightly run --target thumbv7em-none-eabihf --example tlsf_integration_test --all-features
clippy:
name: Clippy
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: dtolnay/rust-toolchain@nightly
with:
components: clippy
toolchain: nightly
targets: thumbv6m-none-eabi
- run: cargo clippy --all-features --examples --target=thumbv6m-none-eabi -- --deny warnings
format:
name: Format
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: dtolnay/rust-toolchain@nightly
with:
components: rustfmt
- run: cargo fmt -- --check
rustdoc:
name: rustdoc
runs-on: ubuntu-latest
env: {"RUSTDOCFLAGS": "-D warnings"}
steps:
- uses: actions/checkout@v6
- uses: dtolnay/rust-toolchain@nightly
with:
targets: thumbv7em-none-eabihf
toolchain: nightly
- name: rustdoc
run: cargo +nightly rustdoc --all-features
================================================
FILE: .gitignore
================================================
target
Cargo.lock
================================================
FILE: CHANGELOG.md
================================================
# Change Log
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/)
and this project adheres to [Semantic Versioning](http://semver.org/).
## [Unreleased]
### Fixed
- Fix panic in `tlsf::Heap::used`.
- Fix panic in `tlsf::Heap::free` in case the value returned from `insert_free_block_ptr`
does not cover the full memory range passed in.
## [v0.7.0] - 2026-01-03
### Added
- Added a `init` macro to make initialization easier.
- Added `Heap::free` and `Heap::used` for the TLSF heap.
### Changed
- The `Heap::init` methods now panic if they're called more than once or with `size == 0`.
## [v0.6.0] - 2024-09-01
### Added
- Added a Two-Level Segregated Fit heap with the `tlsf` feature.
### Changed
- The `Heap` struct has been renamed to `LlffHeap` and requires the `llff` feature.
- Updated the rust edition from 2018 to 2021.
## [v0.5.1] - 2023-11-04
### Added
- Implemented [`Allocator`] for `Heap` with the `allocator_api` crate feature.
This feature requires a nightly toolchain for the unstable [`allocator_api`]
compiler feature.
[`Allocator`]: https://doc.rust-lang.org/core/alloc/trait.Allocator.html
[`allocator_api`]: https://doc.rust-lang.org/beta/unstable-book/library-features/allocator-api.html
### Changed
- Updated `linked_list_allocator` dependency to 0.10.5, which allows
compiling with stable rust.
## [v0.5.0] - 2022-12-06
### Changed
- Renamed crate from `alloc-cortex-m` to `embedded-alloc`.
- Renamed `CortexMHeap` to `Heap`.
- Use `critical-section` to lock the heap, instead of `cortex_m::interrupt::free()`.
This allows using this crate on non-Cortex-M systems, or on
Cortex-M systems that require a custom critical section implementation.
## [v0.4.3] - 2022-11-03
### Changed
- Updated `linked_list_allocator` dependency to 0.10.4, which fixes
CVE-2022-36086/RUSTSEC-2022-0063.
## [v0.4.2] - 2022-01-04
### Changed
- Updated `cortex-m` dependency to 0.7.2.
## [v0.4.1] - 2021-01-02
### Added
- `const_mut_refs` feature to the dependency `linked_list_allocator` crate.
### Changed
- Bumped the dependency of the `linked_list_allocator` crate to v0.8.11.
## [v0.4.0] - 2020-06-05
- Bumped the `cortex-m` dependency to v0.6.2.
- Bumped the dependency of the `linked_list_allocator` crate to v0.8.1.
- Removed `#![feature(alloc)]` to supress compiler warning about stability for alloc.
## [v0.3.5] - 2018-06-19
### Fixed
- To work with recent nightly
## [v0.3.4] - 2018-05-12
### Changed
- Update the example in the crate level documentation to show how to define the new `oom` lang item.
## [v0.3.3] - 2018-04-23
- Bumped the dependency of the `linked_list_allocator` crate to v0.6.0.
## [v0.3.2] - 2018-02-26
### Changed
- Bumped the dependency of the `linked_list_allocator` crate to v0.5.0.
## [v0.3.1] - 2017-10-07
### Fixed
- The example in the documentation.
## [v0.3.0] - 2017-10-07
### Changed
- [breaking-change] Switched to the new allocator system. See documentation for details.
## [v0.2.2] - 2017-04-29
### Added
- a `__rust_allocate_zeroed` symbol as it's needed on recent nightlies.
## [v0.2.1] - 2016-11-27
### Fixed
- The heap size is `end_addr` - `start_addr`. Previously, it was wrongly
calculated as `end_addr - start_addr - 1`.
## [v0.2.0] - 2016-11-19
### Changed
- [breaking-change] Hid the HEAP variable. We now only expose an `init` function to
initialize the allocator.
## v0.1.0 - 2016-11-19
### Added
- Initial version of the allocator
[Unreleased]: https://github.com/rust-embedded/embedded-alloc/compare/v0.7.0...HEAD
[v0.7.0]: https://github.com/rust-embedded/embedded-alloc/compare/v0.6.0...v0.7.0
[v0.6.0]: https://github.com/rust-embedded/embedded-alloc/compare/v0.5.1...v0.6.0
[v0.5.1]: https://github.com/rust-embedded/embedded-alloc/compare/v0.5.0...v0.5.1
[v0.5.0]: https://github.com/rust-embedded/embedded-alloc/compare/v0.4.3...v0.5.0
[v0.4.3]: https://github.com/rust-embedded/embedded-alloc/compare/v0.4.2...v0.4.3
[v0.4.2]: https://github.com/rust-embedded/embedded-alloc/compare/v0.4.1...v0.4.2
[v0.4.1]: https://github.com/rust-embedded/embedded-alloc/compare/v0.4.0...v0.4.1
[v0.4.0]: https://github.com/rust-embedded/embedded-alloc/compare/v0.3.5...v0.4.0
[v0.3.5]: https://github.com/rust-embedded/embedded-alloc/compare/v0.3.4...v0.3.5
[v0.3.4]: https://github.com/rust-embedded/embedded-alloc/compare/v0.3.3...v0.3.4
[v0.3.3]: https://github.com/rust-embedded/embedded-alloc/compare/v0.3.2...v0.3.3
[v0.3.2]: https://github.com/rust-embedded/embedded-alloc/compare/v0.3.1...v0.3.2
[v0.3.1]: https://github.com/rust-embedded/embedded-alloc/compare/v0.3.0...v0.3.1
[v0.3.0]: https://github.com/rust-embedded/embedded-alloc/compare/v0.2.2...v0.3.0
[v0.2.2]: https://github.com/rust-embedded/embedded-alloc/compare/v0.2.1...v0.2.2
[v0.2.1]: https://github.com/rust-embedded/embedded-alloc/compare/v0.2.0...v0.2.1
[v0.2.0]: https://github.com/rust-embedded/embedded-alloc/compare/v0.1.0...v0.2.0
================================================
FILE: CODE_OF_CONDUCT.md
================================================
# The Rust Code of Conduct
## Conduct
**Contact**: [Libs team](https://github.com/rust-embedded/wg#the-libs-team)
* We are committed to providing a friendly, safe and welcoming environment for all, regardless of level of experience, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, nationality, or other similar characteristic.
* On IRC, please avoid using overtly sexual nicknames or other nicknames that might detract from a friendly, safe and welcoming environment for all.
* Please be kind and courteous. There's no need to be mean or rude.
* Respect that people have differences of opinion and that every design or implementation choice carries a trade-off and numerous costs. There is seldom a right answer.
* Please keep unstructured critique to a minimum. If you have solid ideas you want to experiment with, make a fork and see how it works.
* We will exclude you from interaction if you insult, demean or harass anyone. That is not welcome behavior. We interpret the term "harassment" as including the definition in the [Citizen Code of Conduct](http://citizencodeofconduct.org/); if you have any lack of clarity about what might be included in that concept, please read their definition. In particular, we don't tolerate behavior that excludes people in socially marginalized groups.
* Private harassment is also unacceptable. No matter who you are, if you feel you have been or are being harassed or made uncomfortable by a community member, please contact one of the channel ops or any of the [Libs team][team] immediately. Whether you're a regular contributor or a newcomer, we care about making this community a safe place for you and we've got your back.
* Likewise any spamming, trolling, flaming, baiting or other attention-stealing behavior is not welcome.
## Moderation
These are the policies for upholding our community's standards of conduct.
1. Remarks that violate the Rust standards of conduct, including hateful, hurtful, oppressive, or exclusionary remarks, are not allowed. (Cursing is allowed, but never targeting another user, and never in a hateful manner.)
2. Remarks that moderators find inappropriate, whether listed in the code of conduct or not, are also not allowed.
3. Moderators will first respond to such remarks with a warning.
4. If the warning is unheeded, the user will be "kicked," i.e., kicked out of the communication channel to cool off.
5. If the user comes back and continues to make trouble, they will be banned, i.e., indefinitely excluded.
6. Moderators may choose at their discretion to un-ban the user if it was a first offense and they offer the offended party a genuine apology.
7. If a moderator bans someone and you think it was unjustified, please take it up with that moderator, or with a different moderator, **in private**. Complaints about bans in-channel are not allowed.
8. Moderators are held to a higher standard than other community members. If a moderator creates an inappropriate situation, they should expect less leeway than others.
In the Rust community we strive to go the extra step to look out for each other. Don't just aim to be technically unimpeachable, try to be your best self. In particular, avoid flirting with offensive or sensitive issues, particularly if they're off-topic; this all too often leads to unnecessary fights, hurt feelings, and damaged trust; worse, it can drive people away from the community entirely.
And if someone takes issue with something you said or did, resist the urge to be defensive. Just stop doing what it was they complained about and apologize. Even if you feel you were misinterpreted or unfairly accused, chances are good there was something you could've communicated better — remember that it's your responsibility to make your fellow Rustaceans comfortable. Everyone wants to get along and we are all here first and foremost because we want to talk about cool technology. You will find that people will be eager to assume good intent and forgive as long as you earn their trust.
The enforcement policies listed above apply to all official embedded WG venues; including official IRC channels (#rust-embedded); GitHub repositories under rust-embedded; and all forums under rust-embedded.org (forum.rust-embedded.org).
*Adapted from the [Node.js Policy on Trolling](http://blog.izs.me/post/30036893703/policy-on-trolling) as well as the [Contributor Covenant v1.3.0](https://www.contributor-covenant.org/version/1/3/0/).*
[team]: https://github.com/rust-embedded/wg#the-libs-team
================================================
FILE: Cargo.toml
================================================
[package]
authors = [
"The Cortex-M Team <cortex-m@teams.rust-embedded.org>",
"Jonathan Pallant <github@thejpster.org.uk>",
"Jorge Aparicio <jorge@japaric.io>",
"Sébastien Béchet <sebastien.bechet@osinix.com>",
]
description = "A heap allocator for embedded systems"
repository = "https://github.com/rust-embedded/embedded-alloc"
documentation = "https://docs.rs/embedded-alloc"
readme = "README.md"
edition = "2021"
keywords = [
"allocator",
"embedded",
"arm",
"riscv",
"cortex-m",
]
license = "MIT OR Apache-2.0"
name = "embedded-alloc"
version = "0.7.0"
[features]
default = ["llff", "tlsf"]
allocator_api = []
# Use the Two-Level Segregated Fit allocator
tlsf = ["rlsf", "const-default"]
# Use the LinkedList first-fit allocator
llff = ["linked_list_allocator"]
[dependencies]
critical-section = "1.0"
linked_list_allocator = { version = "0.10.5", default-features = false, optional = true }
rlsf = { version = "0.2.1", default-features = false, features = ["unstable"], optional = true }
const-default = { version = "1.0.0", default-features = false, optional = true }
[dev-dependencies]
cortex-m = { version = "0.7.6", features = ["critical-section-single-core"] }
cortex-m-rt = "0.7"
defmt = "1.0"
defmt-semihosting = "0.3.0"
semihosting = { version = "0.1.20", features = ["stdio"] }
# thumbv6m-none-eabi only
[target.thumbv6m-none-eabi.dev-dependencies]
portable-atomic = { version = "1", features = ["unsafe-assume-single-core"] }
# every other target gets the crate without the feature
[target.'cfg(not(target = "thumbv6m-none-eabi"))'.dev-dependencies]
portable-atomic = { version = "1" }
[[example]]
name = "allocator_api"
required-features = ["allocator_api", "llff"]
[[example]]
name = "llff_integration_test"
required-features = ["allocator_api", "llff"]
[[example]]
name = "tlsf_integration_test"
required-features = ["allocator_api", "tlsf"]
[[example]]
name = "global_alloc"
required-features = ["llff"]
================================================
FILE: LICENSE-APACHE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================
FILE: LICENSE-MIT
================================================
Copyright (c) 2016-2018 Jorge Aparicio
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the
Software without restriction, including without
limitation the rights to use, copy, modify, merge,
publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice
shall be included in all copies or substantial portions
of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
================================================
FILE: README.md
================================================
[](https://crates.io/crates/embedded-alloc)
[](https://crates.io/crates/embedded-alloc) -
[Documentation](https://docs.rs/embedded-alloc) - [Change log](https://github.com/rust-embedded/embedded-alloc/blob/master/CHANGELOG.md)
# `embedded-alloc`
> A heap allocator for embedded systems.
This project is developed and maintained by the [libs team][team].
## Example
```rust
#![no_std]
#![no_main]
extern crate alloc;
use cortex_m_rt::entry;
use embedded_alloc::LlffHeap as Heap;
#[global_allocator]
static HEAP: Heap = Heap::empty();
#[entry]
fn main() -> ! {
// Initialize the allocator BEFORE you use it
unsafe {
embedded_alloc::init!(HEAP, 1024);
}
// Alternatively, you can write the code directly to meet specific requirements.
{
use core::mem::MaybeUninit;
const HEAP_SIZE: usize = 1024;
static mut HEAP_MEM: [MaybeUninit<u8>; HEAP_SIZE] = [MaybeUninit::uninit(); HEAP_SIZE];
unsafe { HEAP.init(&raw mut HEAP_MEM as usize, HEAP_SIZE) }
}
// now the allocator is ready types like Box, Vec can be used.
loop { /* .. */ }
}
```
For a full usage example, see [`examples/global_alloc.rs`](https://github.com/rust-embedded/embedded-alloc/blob/master/examples/global_alloc.rs).
For this to work, an implementation of [`critical-section`](https://github.com/rust-embedded/critical-section) must be provided.
For simple use cases with Cortex-M CPUs you may enable the `critical-section-single-core` feature in the [cortex-m](https://github.com/rust-embedded/cortex-m) crate.
Please refer to the documentation of [`critical-section`](https://docs.rs/critical-section) for further guidance.
## Features
There are two heaps available to use:
* `llff`: Provides `LlffHeap`, a Linked List First Fit heap.
* `tlsf`: Provides `TlsfHeap`, a Two-Level Segregated Fit heap.
The best heap to use will depend on your application, see [#78](https://github.com/rust-embedded/embedded-alloc/pull/78) for more discussion.
## License
Licensed under either of
- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE) or
<http://www.apache.org/licenses/LICENSE-2.0>)
- MIT license ([LICENSE-MIT](LICENSE-MIT) or <http://opensource.org/licenses/MIT>)
at your option.
### Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted
for inclusion in the work by you, as defined in the Apache-2.0 license, shall be
dual licensed as above, without any additional terms or conditions.
## Code of Conduct
Contribution to this crate is organized under the terms of the [Rust Code of
Conduct][CoC], the maintainer of this crate, the [libs team][team], promises
to intervene to uphold that code of conduct.
[CoC]: CODE_OF_CONDUCT.md
[team]: https://github.com/rust-embedded/wg#the-libs-team
================================================
FILE: examples/allocator_api.rs
================================================
//! This examples requires nightly for the allocator API.
#![feature(allocator_api)]
#![no_std]
#![no_main]
extern crate alloc;
use core::{mem::MaybeUninit, panic::PanicInfo};
use cortex_m as _;
use cortex_m_rt::entry;
use defmt_semihosting as _;
use embedded_alloc::LlffHeap as Heap;
// This is not used, but as of 2023-10-29 allocator_api cannot be used without
// a global heap
#[global_allocator]
static HEAP: Heap = Heap::empty();
#[entry]
fn main() -> ! {
const HEAP_SIZE: usize = 16;
static mut HEAP_MEM: [MaybeUninit<u8>; HEAP_SIZE] = [MaybeUninit::uninit(); HEAP_SIZE];
let heap: Heap = Heap::empty();
unsafe { heap.init(&raw mut HEAP_MEM as usize, HEAP_SIZE) }
let mut vec = alloc::vec::Vec::new_in(heap);
vec.push(1);
defmt::info!("Allocated vector: {:?}", vec.as_slice());
semihosting::process::exit(0);
}
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
defmt::error!("{}", info);
semihosting::process::exit(-1);
}
================================================
FILE: examples/exhaustion.rs
================================================
//! Example which shows behavior on pool exhaustion. It simply panics.
#![no_std]
#![no_main]
extern crate alloc;
use cortex_m as _;
use cortex_m_rt::entry;
use defmt::Debug2Format;
use defmt_semihosting as _;
use core::panic::PanicInfo;
use embedded_alloc::TlsfHeap as Heap;
#[global_allocator]
static HEAP: Heap = Heap::empty();
#[entry]
fn main() -> ! {
// Initialize the allocator BEFORE you use it
unsafe {
embedded_alloc::init!(HEAP, 16);
}
let _vec = alloc::vec![0; 16];
defmt::error!("unexpected vector allocation success");
// Panic is expected here.
semihosting::process::exit(-1);
}
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
defmt::warn!("received expected heap exhaustion panic");
defmt::warn!("{}: {}", info, Debug2Format(&info.message()));
semihosting::process::exit(0);
}
================================================
FILE: examples/global_alloc.rs
================================================
#![no_std]
#![no_main]
extern crate alloc;
use cortex_m as _;
use cortex_m_rt::entry;
use defmt_semihosting as _;
use core::panic::PanicInfo;
// Linked-List First Fit Heap allocator (feature = "llff")
use embedded_alloc::LlffHeap as Heap;
// Two-Level Segregated Fit Heap allocator (feature = "tlsf")
// use embedded_alloc::TlsfHeap as Heap;
#[global_allocator]
static HEAP: Heap = Heap::empty();
#[entry]
fn main() -> ! {
// Initialize the allocator BEFORE you use it
unsafe {
embedded_alloc::init!(HEAP, 1024);
}
let vec = alloc::vec![1];
defmt::info!("Allocated vector: {:?}", vec.as_slice());
let string = alloc::string::String::from("Hello, world!");
defmt::info!("Allocated string: {:?}", string.as_str());
semihosting::process::exit(0);
}
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
defmt::error!("{}", info);
semihosting::process::exit(-1);
}
================================================
FILE: examples/llff_integration_test.rs
================================================
//! This is a very basic smoke test that runs in QEMU
//! Reference the QEMU section of the [Embedded Rust Book] for more information
//!
//! This only tests integration of the allocator on an embedded target.
//! Comprehensive allocator tests are located in the allocator dependency.
//!
//! After toolchain installation this test can be run with:
//!
//! ```bash
//! cargo +nightly run --target thumbv7m-none-eabi --example llff_integration_test --all-features
//! ```
//!
//! [Embedded Rust Book]: https://docs.rust-embedded.org/book/intro/index.html
#![feature(allocator_api)]
#![no_main]
#![no_std]
extern crate alloc;
use alloc::vec::Vec;
use core::{
mem::{size_of, MaybeUninit},
panic::PanicInfo,
};
use cortex_m as _;
use cortex_m_rt::entry;
use defmt_semihosting as _;
use embedded_alloc::LlffHeap as Heap;
#[global_allocator]
static HEAP: Heap = Heap::empty();
fn test_global_heap() {
assert_eq!(HEAP.used(), 0);
let mut xs: Vec<i32> = alloc::vec![1];
xs.push(2);
xs.extend(&[3, 4]);
// do not optimize xs
core::hint::black_box(&mut xs);
assert_eq!(xs.as_slice(), &[1, 2, 3, 4]);
assert_eq!(HEAP.used(), size_of::<i32>() * xs.len());
}
fn test_allocator_api() {
// small local heap
const HEAP_SIZE: usize = 16;
let mut heap_mem: [MaybeUninit<u8>; HEAP_SIZE] = [MaybeUninit::uninit(); HEAP_SIZE];
let local_heap: Heap = Heap::empty();
unsafe { local_heap.init(&raw mut heap_mem as usize, HEAP_SIZE) }
assert_eq!(local_heap.used(), 0);
let mut v: Vec<u16, Heap> = Vec::new_in(local_heap);
v.push(0xCAFE);
v.extend(&[0xDEAD, 0xFEED]);
// do not optimize v
core::hint::black_box(&mut v);
assert_eq!(v.as_slice(), &[0xCAFE, 0xDEAD, 0xFEED]);
}
pub type TestTable<'a> = &'a [(fn() -> (), &'static str)];
#[entry]
fn main() -> ! {
unsafe {
embedded_alloc::init!(HEAP, 1024);
}
let tests: TestTable = &[
(test_global_heap, "test_global_heap"),
(test_allocator_api, "test_allocator_api"),
];
for (test_fn, test_name) in tests {
defmt::info!("{}: start", test_name);
test_fn();
defmt::info!("{}: pass", test_name);
}
// exit QEMU with a success status
semihosting::process::exit(0);
}
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
defmt::error!("{}", info);
semihosting::process::exit(-1);
}
================================================
FILE: examples/tlsf_integration_test.rs
================================================
//! This is a very basic smoke test that runs in QEMU
//! Reference the QEMU section of the [Embedded Rust Book] for more information
//!
//! This only tests integration of the allocator on an embedded target.
//! Comprehensive allocator tests are located in the allocator dependency.
//!
//! After toolchain installation this test can be run with:
//!
//! ```bash
//! cargo +nightly run --target thumbv7m-none-eabi --example tlsf_integration_test --all-features
//! ```
//!
//! [Embedded Rust Book]: https://docs.rust-embedded.org/book/intro/index.html
#![feature(allocator_api)]
#![no_main]
#![no_std]
extern crate alloc;
use defmt_semihosting as _;
use alloc::collections::LinkedList;
use core::{mem::MaybeUninit, panic::PanicInfo};
use cortex_m as _;
use cortex_m_rt::entry;
use embedded_alloc::TlsfHeap as Heap;
#[global_allocator]
static HEAP: Heap = Heap::empty();
const HEAP_SIZE: usize = 30 * 1024;
pub type TestTable<'a> = &'a [(fn() -> (), &'static str)];
fn test_global_heap() {
const ELEMS: usize = 250;
assert_eq!(HEAP_SIZE, HEAP.free() + HEAP.used());
let initial_free = HEAP.free();
let mut allocated = LinkedList::new();
for _ in 0..ELEMS {
allocated.push_back(0);
}
for i in 0..ELEMS {
allocated.push_back(i as i32);
}
assert_eq!(allocated.len(), 2 * ELEMS);
for _ in 0..ELEMS {
allocated.pop_front();
}
for i in 0..ELEMS {
assert_eq!(allocated.pop_front().unwrap(), i as i32);
}
assert_eq!(HEAP_SIZE, HEAP.free() + HEAP.used());
assert_eq!(initial_free, HEAP.free());
}
fn test_allocator_api() {
// small local heap
const HEAP_SIZE: usize = 256;
let mut heap_mem: [MaybeUninit<u8>; HEAP_SIZE] = [MaybeUninit::uninit(); HEAP_SIZE];
let local_heap: Heap = Heap::empty();
unsafe { local_heap.init(heap_mem.as_mut_ptr() as usize, HEAP_SIZE) }
const ELEMS: usize = 2;
let mut allocated = LinkedList::new_in(local_heap);
for _ in 0..ELEMS {
allocated.push_back(0);
}
for i in 0..ELEMS {
allocated.push_back(i as i32);
}
assert_eq!(allocated.len(), 2 * ELEMS);
for _ in 0..ELEMS {
allocated.pop_front();
}
for i in 0..ELEMS {
assert_eq!(allocated.pop_front().unwrap(), i as i32);
}
}
#[entry]
fn main() -> ! {
unsafe {
embedded_alloc::init!(HEAP, HEAP_SIZE);
}
let tests: TestTable = &[
(test_global_heap, "test_global_heap"),
(test_allocator_api, "test_allocator_api"),
];
for (test_fn, test_name) in tests {
defmt::info!("{}: start", test_name);
test_fn();
defmt::info!("{}: pass", test_name);
}
// exit QEMU with a success status
semihosting::process::exit(0);
}
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
defmt::error!("{}", info);
semihosting::process::exit(-1);
}
================================================
FILE: examples/track_usage.rs
================================================
#![no_std]
#![no_main]
extern crate alloc;
use cortex_m as _;
use cortex_m_rt::entry;
use defmt::Debug2Format;
use defmt_semihosting as _;
use core::{mem::MaybeUninit, panic::PanicInfo};
use embedded_alloc::TlsfHeap as Heap;
//use embedded_alloc::LlffHeap as Heap;
#[global_allocator]
static HEAP: Heap = Heap::empty();
#[entry]
fn main() -> ! {
// Initialize the allocator BEFORE you use it
const HEAP_SIZE: usize = 4096;
static mut HEAP_MEM: [MaybeUninit<u8>; HEAP_SIZE] = [MaybeUninit::uninit(); HEAP_SIZE];
unsafe { HEAP.init(&raw mut HEAP_MEM as usize, HEAP_SIZE) }
let mut alloc_vecs = alloc::vec::Vec::new();
let mut free_memory = HEAP_SIZE;
// Keep allocating until we are getting low on memory. It doesn't have to end in a panic.
while free_memory > 512 {
defmt::info!(
"{} of {} heap memory allocated so far...",
HEAP_SIZE - free_memory,
HEAP_SIZE
);
let new_vec = alloc::vec![1_u8; 64];
alloc_vecs.push(new_vec);
free_memory = HEAP.free();
}
drop(alloc_vecs);
defmt::info!(
"{} of {} heap memory are allocated after drop",
HEAP_SIZE - HEAP.free(),
HEAP_SIZE
);
semihosting::process::exit(0);
}
#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
defmt::error!("{}: {}", info, Debug2Format(&info.message()));
semihosting::process::exit(-1);
}
================================================
FILE: memory.x
================================================
MEMORY
{
/* These values correspond to the LM3S6965, one of the few devices QEMU can emulate */
FLASH : ORIGIN = 0x00000000, LENGTH = 256K
RAM : ORIGIN = 0x20000000, LENGTH = 64K
}
================================================
FILE: qemu-runner.sh
================================================
#!/bin/bash
# This requires you to previously run `cargo install defmt-print`
# See https://ferroussystems.hackmd.io/@jonathanpallant/ryA1S6QDJx for a description of all the relevant QEMU machines
TARGET=""
ELF_BINARY=""
# very small argument parser
while [[ $# -gt 0 ]]; do
case "$1" in
--target) TARGET="$2"; shift 2 ;;
*) ELF_BINARY="$1"; shift ;;
esac
done
# default to the target cargo is currently building for
TARGET="${TARGET:-thumbv7em-none-eabihf}"
case "$TARGET" in
thumbv6m-none-eabi)
MACHINE="-cpu cortex-m3 -machine mps2-an385" ;;
thumbv7em-none-eabihf)
# All suitable for thumbv7em-none-eabihf
MACHINE="-cpu cortex-m4 -machine mps2-an386" ;;
# MACHINE="-cpu cortex-m7 -machine mps2-387" ;;
# MACHINE="-cpu cortex-m7 -machine mps2-500"
*)
echo "Unsupported target: $TARGET" >&2
exit 1 ;;
esac
LOG_FORMAT='{[{L}]%bold} {s} {({ff}:{l:1})%dimmed}'
echo "Running on '$MACHINE'..."
echo "------------------------------------------------------------------------"
qemu-system-arm $MACHINE -semihosting-config enable=on,target=native -nographic -kernel $ELF_BINARY | defmt-print -e $ELF_BINARY --log-format="$LOG_FORMAT"
echo "------------------------------------------------------------------------"
================================================
FILE: src/lib.rs
================================================
#![doc = include_str!("../README.md")]
#![no_std]
#![cfg_attr(feature = "allocator_api", feature(allocator_api))]
#![warn(missing_docs)]
#[cfg(feature = "llff")]
mod llff;
#[cfg(feature = "tlsf")]
mod tlsf;
#[cfg(feature = "llff")]
pub use llff::Heap as LlffHeap;
#[cfg(feature = "tlsf")]
pub use tlsf::Heap as TlsfHeap;
/// Initialize the global heap.
///
/// This macro creates a static, uninitialized memory buffer of the specified size and
/// initializes the heap instance with that buffer.
///
/// # Parameters
///
/// - `$heap:ident`: The identifier of the global heap instance to initialize.
/// - `$size:expr`: An expression evaluating to a `usize` that specifies the size of the
/// static memory buffer in bytes. It must be **greater than zero**.
///
/// # Safety
///
/// This macro must be called first, before any operations on the heap, and **only once**.
/// It internally calls `Heap::init(...)` on the heap,
/// so `Heap::init(...)` should not be called directly if this macro is used.
///
/// # Panics
///
/// This macro will panic if either of the following are true:
///
/// - this function is called more than ONCE.
/// - `size == 0`.
///
/// # Example
///
/// ```rust
/// use cortex_m_rt::entry;
/// use embedded_alloc::LlffHeap as Heap;
///
/// #[global_allocator]
/// static HEAP: Heap = Heap::empty();
///
/// #[entry]
/// fn main() -> ! {
/// // Initialize the allocator BEFORE you use it
/// unsafe {
/// embedded_alloc::init!(HEAP, 1024);
/// }
/// let mut xs = Vec::new();
/// // ...
/// }
/// ```
#[macro_export]
macro_rules! init {
($heap:ident, $size:expr) => {
static mut HEAP_MEM: [::core::mem::MaybeUninit<u8>; $size] =
[::core::mem::MaybeUninit::uninit(); $size];
$heap.init(&raw mut HEAP_MEM as usize, $size)
};
}
================================================
FILE: src/llff.rs
================================================
use core::alloc::{GlobalAlloc, Layout};
use core::cell::RefCell;
use core::ptr::{self, NonNull};
use critical_section::Mutex;
use linked_list_allocator::Heap as LLHeap;
/// A linked list first fit heap.
pub struct Heap {
heap: Mutex<RefCell<(LLHeap, bool)>>,
}
impl Heap {
/// Create a new UNINITIALIZED heap allocator
///
/// You must initialize this heap using the
/// [`init`](Self::init) method before using the allocator.
pub const fn empty() -> Heap {
Heap {
heap: Mutex::new(RefCell::new((LLHeap::empty(), false))),
}
}
/// Initializes the heap
///
/// This function must be called BEFORE you run any code that makes use of the
/// allocator.
///
/// `start_addr` is the address where the heap will be located.
///
/// `size` is the size of the heap in bytes.
///
/// Note that:
///
/// - The heap grows "upwards", towards larger addresses. Thus `start_addr` will
/// be the smallest address used.
///
/// - The largest address used is `start_addr + size - 1`, so if `start_addr` is
/// `0x1000` and `size` is `0x30000` then the allocator won't use memory at
/// addresses `0x31000` and larger.
///
/// # Safety
///
/// This function is safe if the following invariants hold:
///
/// - `start_addr` points to valid memory.
/// - `size` is correct.
///
/// # Panics
///
/// This function will panic if either of the following are true:
///
/// - this function is called more than ONCE.
/// - `size == 0`.
pub unsafe fn init(&self, start_addr: usize, size: usize) {
assert!(size > 0);
critical_section::with(|cs| {
let mut heap = self.heap.borrow_ref_mut(cs);
assert!(!heap.1);
heap.1 = true;
heap.0.init(start_addr as *mut u8, size);
});
}
/// Returns an estimate of the amount of bytes in use.
pub fn used(&self) -> usize {
critical_section::with(|cs| self.heap.borrow_ref_mut(cs).0.used())
}
/// Returns an estimate of the amount of bytes available.
pub fn free(&self) -> usize {
critical_section::with(|cs| self.heap.borrow_ref_mut(cs).0.free())
}
fn alloc(&self, layout: Layout) -> Option<NonNull<u8>> {
critical_section::with(|cs| {
self.heap
.borrow_ref_mut(cs)
.0
.allocate_first_fit(layout)
.ok()
})
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
critical_section::with(|cs| {
self.heap
.borrow_ref_mut(cs)
.0
.deallocate(NonNull::new_unchecked(ptr), layout)
});
}
}
unsafe impl GlobalAlloc for Heap {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
self.alloc(layout)
.map_or(ptr::null_mut(), |allocation| allocation.as_ptr())
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
self.dealloc(ptr, layout);
}
}
#[cfg(feature = "allocator_api")]
mod allocator_api {
use super::*;
use core::alloc::{AllocError, Allocator};
unsafe impl Allocator for Heap {
fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
match layout.size() {
0 => Ok(NonNull::slice_from_raw_parts(layout.dangling_ptr(), 0)),
size => self.alloc(layout).map_or(Err(AllocError), |allocation| {
Ok(NonNull::slice_from_raw_parts(allocation, size))
}),
}
}
unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
if layout.size() != 0 {
self.dealloc(ptr.as_ptr(), layout);
}
}
}
}
================================================
FILE: src/tlsf.rs
================================================
use core::alloc::{GlobalAlloc, Layout};
use core::cell::RefCell;
use core::ptr::{self, NonNull};
use const_default::ConstDefault;
use critical_section::Mutex;
use rlsf::Tlsf;
type TlsfHeap = Tlsf<'static, usize, usize, { usize::BITS as usize }, { usize::BITS as usize }>;
struct Inner {
tlsf: TlsfHeap,
initialized: bool,
raw_block: Option<NonNull<[u8]>>,
raw_block_size: usize,
}
// Safety: The whole inner type is wrapped by a [Mutex].
unsafe impl Sync for Inner {}
unsafe impl Send for Inner {}
/// A two-Level segregated fit heap.
pub struct Heap {
heap: Mutex<RefCell<Inner>>,
}
impl Heap {
/// Create a new UNINITIALIZED heap allocator
///
/// You must initialize this heap using the
/// [`init`](Self::init) method before using the allocator.
pub const fn empty() -> Heap {
Heap {
heap: Mutex::new(RefCell::new(Inner {
tlsf: ConstDefault::DEFAULT,
initialized: false,
raw_block: None,
raw_block_size: 0,
})),
}
}
/// Initializes the heap
///
/// This function must be called BEFORE you run any code that makes use of the
/// allocator.
///
/// `start_addr` is the address where the heap will be located.
///
/// `size` is the size of the heap in bytes.
///
/// Note that:
///
/// - The heap grows "upwards", towards larger addresses. Thus `start_addr` will
/// be the smallest address used.
///
/// - The largest address used is `start_addr + size - 1`, so if `start_addr` is
/// `0x1000` and `size` is `0x30000` then the allocator won't use memory at
/// addresses `0x31000` and larger.
///
/// # Safety
///
/// This function is safe if the following invariants hold:
///
/// - `start_addr` points to valid memory.
/// - `size` is correct.
///
/// # Panics
///
/// This function will panic if either of the following are true:
///
/// - this function is called more than ONCE.
/// - `size`, after aligning start and end to `rlsf::GRANULARITY`, is smaller than `rlsf::GRANULARITY * 2`.
pub unsafe fn init(&self, start_addr: usize, size: usize) {
assert!(size > 0);
critical_section::with(|cs| {
let mut heap = self.heap.borrow_ref_mut(cs);
assert!(!heap.initialized);
let block: NonNull<[u8]> =
NonNull::slice_from_raw_parts(NonNull::new_unchecked(start_addr as *mut u8), size);
let Some(actual_size) = heap.tlsf.insert_free_block_ptr(block) else {
panic!("Allocation too small for heap");
};
let block: NonNull<[u8]> = NonNull::slice_from_raw_parts(
NonNull::new_unchecked(start_addr as *mut u8),
actual_size.get(),
);
heap.initialized = true;
heap.raw_block = Some(block);
heap.raw_block_size = size;
});
}
fn alloc(&self, layout: Layout) -> Option<NonNull<u8>> {
critical_section::with(|cs| self.heap.borrow_ref_mut(cs).tlsf.allocate(layout))
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
critical_section::with(|cs| {
self.heap
.borrow_ref_mut(cs)
.tlsf
.deallocate(NonNull::new_unchecked(ptr), layout.align())
})
}
unsafe fn realloc(&self, ptr: *mut u8, new_layout: Layout) -> Option<NonNull<u8>> {
critical_section::with(|cs| {
self.heap
.borrow_ref_mut(cs)
.tlsf
.reallocate(NonNull::new_unchecked(ptr), new_layout)
})
}
/// Get the amount of bytes used by the allocator.
pub fn used(&self) -> usize {
critical_section::with(|cs| {
let free = self.free_with_cs(cs);
self.heap.borrow_ref_mut(cs).raw_block_size - free
})
}
/// Get the amount of free bytes in the allocator.
pub fn free(&self) -> usize {
critical_section::with(|cs| self.free_with_cs(cs))
}
fn free_with_cs(&self, cs: critical_section::CriticalSection) -> usize {
let inner_mut = self.heap.borrow_ref_mut(cs);
if !inner_mut.initialized {
return 0;
}
// Safety: We pass the memory block we previously initialized the heap with
// to the `iter_blocks` method.
unsafe {
inner_mut
.tlsf
.iter_blocks(inner_mut.raw_block.unwrap())
.filter(|block_info| !block_info.is_occupied())
.map(|block_info| block_info.max_payload_size())
.sum::<usize>()
}
}
}
unsafe impl GlobalAlloc for Heap {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
self.alloc(layout)
.map_or(ptr::null_mut(), |allocation| allocation.as_ptr())
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
self.dealloc(ptr, layout)
}
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
// SAFETY: `layout.align()` is a power of two, and the size precondition
// is upheld by the caller.
let new_layout =
unsafe { core::alloc::Layout::from_size_align_unchecked(new_size, layout.align()) };
self.realloc(ptr, new_layout)
.map_or(ptr::null_mut(), |allocation| allocation.as_ptr())
}
}
#[cfg(feature = "allocator_api")]
mod allocator_api {
use super::*;
use core::alloc::{AllocError, Allocator};
unsafe impl Allocator for Heap {
fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
match layout.size() {
0 => Ok(NonNull::slice_from_raw_parts(layout.dangling_ptr(), 0)),
size => self.alloc(layout).map_or(Err(AllocError), |allocation| {
Ok(NonNull::slice_from_raw_parts(allocation, size))
}),
}
}
unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
if layout.size() != 0 {
self.dealloc(ptr.as_ptr(), layout);
}
}
}
}
gitextract_10arganv/
├── .cargo/
│ └── config.toml
├── .github/
│ ├── CODEOWNERS
│ └── workflows/
│ └── ci.yml
├── .gitignore
├── CHANGELOG.md
├── CODE_OF_CONDUCT.md
├── Cargo.toml
├── LICENSE-APACHE
├── LICENSE-MIT
├── README.md
├── examples/
│ ├── allocator_api.rs
│ ├── exhaustion.rs
│ ├── global_alloc.rs
│ ├── llff_integration_test.rs
│ ├── tlsf_integration_test.rs
│ └── track_usage.rs
├── memory.x
├── qemu-runner.sh
└── src/
├── lib.rs
├── llff.rs
└── tlsf.rs
SYMBOL INDEX (46 symbols across 8 files)
FILE: examples/allocator_api.rs
function main (line 20) | fn main() -> ! {
function panic (line 35) | fn panic(info: &PanicInfo) -> ! {
FILE: examples/exhaustion.rs
function main (line 19) | fn main() -> ! {
function panic (line 34) | fn panic(info: &PanicInfo) -> ! {
FILE: examples/global_alloc.rs
function main (line 20) | fn main() -> ! {
function panic (line 38) | fn panic(info: &PanicInfo) -> ! {
FILE: examples/llff_integration_test.rs
function test_global_heap (line 34) | fn test_global_heap() {
function test_allocator_api (line 48) | fn test_allocator_api() {
type TestTable (line 67) | pub type TestTable<'a> = &'a [(fn() -> (), &'static str)];
function main (line 70) | fn main() -> ! {
function panic (line 91) | fn panic(info: &PanicInfo) -> ! {
FILE: examples/tlsf_integration_test.rs
constant HEAP_SIZE (line 30) | const HEAP_SIZE: usize = 30 * 1024;
type TestTable (line 32) | pub type TestTable<'a> = &'a [(fn() -> (), &'static str)];
function test_global_heap (line 34) | fn test_global_heap() {
function test_allocator_api (line 60) | fn test_allocator_api() {
function main (line 89) | fn main() -> ! {
function panic (line 110) | fn panic(info: &PanicInfo) -> ! {
FILE: examples/track_usage.rs
function main (line 19) | fn main() -> ! {
function panic (line 51) | fn panic(info: &PanicInfo) -> ! {
FILE: src/llff.rs
type Heap (line 9) | pub struct Heap {
method empty (line 18) | pub const fn empty() -> Heap {
method init (line 55) | pub unsafe fn init(&self, start_addr: usize, size: usize) {
method used (line 66) | pub fn used(&self) -> usize {
method free (line 71) | pub fn free(&self) -> usize {
method alloc (line 75) | fn alloc(&self, layout: Layout) -> Option<NonNull<u8>> {
method dealloc (line 85) | unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
method alloc (line 96) | unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
method dealloc (line 101) | unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
method allocate (line 112) | fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
method deallocate (line 121) | unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
FILE: src/tlsf.rs
type TlsfHeap (line 9) | type TlsfHeap = Tlsf<'static, usize, usize, { usize::BITS as usize }, { ...
type Inner (line 11) | struct Inner {
type Heap (line 23) | pub struct Heap {
method empty (line 32) | pub const fn empty() -> Heap {
method init (line 74) | pub unsafe fn init(&self, start_addr: usize, size: usize) {
method alloc (line 94) | fn alloc(&self, layout: Layout) -> Option<NonNull<u8>> {
method dealloc (line 98) | unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
method realloc (line 107) | unsafe fn realloc(&self, ptr: *mut u8, new_layout: Layout) -> Option<N...
method used (line 117) | pub fn used(&self) -> usize {
method free (line 125) | pub fn free(&self) -> usize {
method free_with_cs (line 129) | fn free_with_cs(&self, cs: critical_section::CriticalSection) -> usize {
method alloc (line 148) | unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
method dealloc (line 153) | unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
method realloc (line 157) | unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) ...
method allocate (line 173) | fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
method deallocate (line 182) | unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
Condensed preview — 21 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (56K chars).
[
{
"path": ".cargo/config.toml",
"chars": 655,
"preview": "[build]\n# Common embedded build targets\ntarget = \"thumbv7em-none-eabihf\"\n# target = \"thumbv6m-none-eabi\"\n\n[target.thumbv"
},
{
"path": ".github/CODEOWNERS",
"chars": 22,
"preview": "* @rust-embedded/libs\n"
},
{
"path": ".github/workflows/ci.yml",
"chars": 2808,
"preview": "on:\n pull_request: # Run CI for PRs on any branch\n merge_group: # Run CI for the GitHub merge queue\n workflow_dispatc"
},
{
"path": ".gitignore",
"chars": 18,
"preview": "target\nCargo.lock\n"
},
{
"path": "CHANGELOG.md",
"chars": 5037,
"preview": "# Change Log\n\nAll notable changes to this project will be documented in this file.\n\nThe format is based on [Keep a Chang"
},
{
"path": "CODE_OF_CONDUCT.md",
"chars": 4588,
"preview": "# The Rust Code of Conduct\n\n## Conduct\n\n**Contact**: [Libs team](https://github.com/rust-embedded/wg#the-libs-team)\n\n* W"
},
{
"path": "Cargo.toml",
"chars": 1971,
"preview": "[package]\nauthors = [\n \"The Cortex-M Team <cortex-m@teams.rust-embedded.org>\",\n \"Jonathan Pallant <github@thejpste"
},
{
"path": "LICENSE-APACHE",
"chars": 10847,
"preview": " Apache License\n Version 2.0, January 2004\n http"
},
{
"path": "LICENSE-MIT",
"chars": 1063,
"preview": "Copyright (c) 2016-2018 Jorge Aparicio\n\nPermission is hereby granted, free of charge, to any\nperson obtaining a copy of "
},
{
"path": "README.md",
"chars": 2928,
"preview": "[](https://crates.io/crates/embedded-alloc)\n[![crates.io"
},
{
"path": "examples/allocator_api.rs",
"chars": 978,
"preview": "//! This examples requires nightly for the allocator API.\n#![feature(allocator_api)]\n#![no_std]\n#![no_main]\n\nextern crat"
},
{
"path": "examples/exhaustion.rs",
"chars": 853,
"preview": "//! Example which shows behavior on pool exhaustion. It simply panics.\n#![no_std]\n#![no_main]\n\nextern crate alloc;\n\nuse "
},
{
"path": "examples/global_alloc.rs",
"chars": 917,
"preview": "#![no_std]\n#![no_main]\n\nextern crate alloc;\n\nuse cortex_m as _;\nuse cortex_m_rt::entry;\nuse defmt_semihosting as _;\n\nuse"
},
{
"path": "examples/llff_integration_test.rs",
"chars": 2392,
"preview": "//! This is a very basic smoke test that runs in QEMU\n//! Reference the QEMU section of the [Embedded Rust Book] for mor"
},
{
"path": "examples/tlsf_integration_test.rs",
"chars": 2887,
"preview": "//! This is a very basic smoke test that runs in QEMU\n//! Reference the QEMU section of the [Embedded Rust Book] for mor"
},
{
"path": "examples/track_usage.rs",
"chars": 1422,
"preview": "#![no_std]\n#![no_main]\n\nextern crate alloc;\n\nuse cortex_m as _;\nuse cortex_m_rt::entry;\nuse defmt::Debug2Format;\nuse def"
},
{
"path": "memory.x",
"chars": 187,
"preview": "MEMORY\n{\n /* These values correspond to the LM3S6965, one of the few devices QEMU can emulate */\n FLASH : ORIGIN = 0x0"
},
{
"path": "qemu-runner.sh",
"chars": 1317,
"preview": "#!/bin/bash\n\n# This requires you to previously run `cargo install defmt-print`\n\n# See https://ferroussystems.hackmd.io/@"
},
{
"path": "src/lib.rs",
"chars": 1820,
"preview": "#![doc = include_str!(\"../README.md\")]\n#![no_std]\n#![cfg_attr(feature = \"allocator_api\", feature(allocator_api))]\n#![war"
},
{
"path": "src/llff.rs",
"chars": 3838,
"preview": "use core::alloc::{GlobalAlloc, Layout};\nuse core::cell::RefCell;\nuse core::ptr::{self, NonNull};\n\nuse critical_section::"
},
{
"path": "src/tlsf.rs",
"chars": 6258,
"preview": "use core::alloc::{GlobalAlloc, Layout};\nuse core::cell::RefCell;\nuse core::ptr::{self, NonNull};\n\nuse const_default::Con"
}
]
About this extraction
This page contains the full source code of the rust-embedded/embedded-alloc GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 21 files (51.6 KB), approximately 14.0k tokens, and a symbol index with 46 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.