tikv-jemalloc-sys-0.6.0+5.3.0-1-ge13ca993e8ccb9ba9847cc330696e02839f328f7/.cargo_vcs_info.json0000644000000001520000000000100227660ustar { "git": { "sha1": "f260a80f21b7f9eb1212809720d9a5f7f0cf0e8b" }, "path_in_vcs": "jemalloc-sys" }tikv-jemalloc-sys-0.6.0+5.3.0-1-ge13ca993e8ccb9ba9847cc330696e02839f328f7/Cargo.toml0000644000000034770000000000100210010ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" rust-version = "1.71.0" name = "tikv-jemalloc-sys" version = "0.6.0+5.3.0-1-ge13ca993e8ccb9ba9847cc330696e02839f328f7" authors = [ "Alex Crichton ", "Gonzalo Brito Gadeschi ", "The TiKV Project Developers", ] build = "build.rs" links = "jemalloc" description = """ Rust FFI bindings to jemalloc """ homepage = "https://github.com/tikv/jemallocator" documentation = "https://docs.rs/tikv-jemallocator-sys" readme = "README.md" keywords = [ "allocator", "jemalloc", ] license = "MIT/Apache-2.0" repository = "https://github.com/tikv/jemallocator" [package.metadata.docs.rs] rustdoc-args = [ "--cfg", "jemallocator_docs", ] [dependencies.libc] version = "^0.2.8" default-features = false [build-dependencies.cc] version = "^1.0.13" [features] background_threads = ["background_threads_runtime_support"] background_threads_runtime_support = [] debug = [] default = ["background_threads_runtime_support"] disable_cache_oblivious = [] disable_initial_exec_tls = [] profiling = [] stats = [] unprefixed_malloc_on_supported_platforms = [] [badges.codecov] repository = "tikv/jemallocator" [badges.is-it-maintained-issue-resolution] repository = "tikv/jemallocator" [badges.is-it-maintained-open-issues] repository = "tikv/jemallocator" [badges.maintenance] status = "actively-developed" tikv-jemalloc-sys-0.6.0+5.3.0-1-ge13ca993e8ccb9ba9847cc330696e02839f328f7/Cargo.toml.orig0000644000000025240000000000100217300ustar [package] name = "tikv-jemalloc-sys" version = "0.6.0+5.3.0-1-ge13ca993e8ccb9ba9847cc330696e02839f328f7" authors = [ "Alex Crichton ", "Gonzalo Brito Gadeschi ", "The TiKV Project Developers", ] build = "build.rs" links = "jemalloc" license = "MIT/Apache-2.0" readme = "README.md" repository = "https://github.com/tikv/jemallocator" homepage = "https://github.com/tikv/jemallocator" documentation = "https://docs.rs/tikv-jemallocator-sys" keywords = ["allocator", "jemalloc"] description = """ Rust FFI bindings to jemalloc """ edition = "2018" rust-version = "1.71.0" [badges] codecov = { repository = "tikv/jemallocator" } is-it-maintained-issue-resolution = { repository = "tikv/jemallocator" } is-it-maintained-open-issues = { repository = "tikv/jemallocator" } maintenance = { status = "actively-developed" } [dependencies] libc = { version = "^0.2.8", default-features = false } [build-dependencies] cc = "^1.0.13" [features] default = ["background_threads_runtime_support"] profiling = [] debug = [] background_threads_runtime_support = [] background_threads = [ "background_threads_runtime_support" ] stats = [] unprefixed_malloc_on_supported_platforms = [] disable_initial_exec_tls = [] disable_cache_oblivious = [] [package.metadata.docs.rs] rustdoc-args = [ "--cfg", "jemallocator_docs" ] tikv-jemalloc-sys-0.6.0+5.3.0-1-ge13ca993e8ccb9ba9847cc330696e02839f328f7/Cargo.toml.orig000064400000000000000000000025241046102023000244520ustar 00000000000000[package] name = "tikv-jemalloc-sys" version = "0.6.0+5.3.0-1-ge13ca993e8ccb9ba9847cc330696e02839f328f7" authors = [ "Alex Crichton ", "Gonzalo Brito Gadeschi ", "The TiKV Project Developers", ] build = "build.rs" links = "jemalloc" license = "MIT/Apache-2.0" readme = "README.md" repository = "https://github.com/tikv/jemallocator" homepage = "https://github.com/tikv/jemallocator" documentation = "https://docs.rs/tikv-jemallocator-sys" keywords = ["allocator", "jemalloc"] description = """ Rust FFI bindings to jemalloc """ edition = "2018" rust-version = "1.71.0" [badges] codecov = { repository = "tikv/jemallocator" } is-it-maintained-issue-resolution = { repository = "tikv/jemallocator" } is-it-maintained-open-issues = { repository = "tikv/jemallocator" } maintenance = { status = "actively-developed" } [dependencies] libc = { version = "^0.2.8", default-features = false } [build-dependencies] cc = "^1.0.13" [features] default = ["background_threads_runtime_support"] profiling = [] debug = [] background_threads_runtime_support = [] background_threads = [ "background_threads_runtime_support" ] stats = [] unprefixed_malloc_on_supported_platforms = [] disable_initial_exec_tls = [] disable_cache_oblivious = [] [package.metadata.docs.rs] rustdoc-args = [ "--cfg", "jemallocator_docs" ] tikv-jemalloc-sys-0.6.0+5.3.0-1-ge13ca993e8ccb9ba9847cc330696e02839f328f7/LICENSE-APACHE000064400000000000000000000251371046102023000235140ustar 00000000000000 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. tikv-jemalloc-sys-0.6.0+5.3.0-1-ge13ca993e8ccb9ba9847cc330696e02839f328f7/LICENSE-MIT000064400000000000000000000020411046102023000232110ustar 00000000000000Copyright (c) 2014 Alex Crichton 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. tikv-jemalloc-sys-0.6.0+5.3.0-1-ge13ca993e8ccb9ba9847cc330696e02839f328f7/README.md000064400000000000000000000206041046102023000230410ustar 00000000000000# jemalloc-sys - Rust bindings to the `jemalloc` C library [![Travis-CI Status]][travis] [![Latest Version]][crates.io] [![docs]][docs.rs] > Note: the Rust allocator API is implemented for `jemalloc` in the > [`tikv-jemallocator`](https://crates.io/crates/tikv-jemallocator) crate. ## Documentation * [Latest release (docs.rs)][docs.rs] `jemalloc` is a general purpose memory allocator, its documentation can be found here: * [API documentation][jemalloc_docs] * [Wiki][jemalloc_wiki] (design documents, presentations, profiling, debugging, tuning, ...) [jemalloc_docs]: http://jemalloc.net/jemalloc.3.html [jemalloc_wiki]: https://github.com/jemalloc/jemalloc/wiki **Current jemalloc version**: 5.2.1. ## Platform support See the platform support of the [`tikv-jemallocator`](https://crates.io/crates/tikv-jemallocator) crate. ## Features Most features correspond to `jemalloc` features - the reference is [`jemalloc/INSTALL.md`][jemalloc_install]. ### Cargo features This crate provides following cargo feature flags: * `profiling` (configure `jemalloc` with `--enable-prof`): Enable heap profiling and leak detection functionality. See jemalloc's "opt.prof" option documentation for usage details. When enabled, there are several approaches to backtracing, and the configure script chooses the first one in the following list that appears to function correctly: * `libunwind` (requires --enable-prof-libunwind) * `libgcc` (unless --disable-prof-libgcc) * `gcc intrinsics` (unless --disable-prof-gcc) * `stats` (configure `jemalloc` with `--enable-stats`): Enable statistics gathering functionality. See the `jemalloc`'s "`opt.stats_print`" option documentation for usage details. * `debug` (configure `jemalloc` with `--enable-debug`): Enable assertions and validation code. This incurs a substantial performance hit, but is very useful during application development. * `background_threads_runtime_support` (enabled by default): enables background-threads run-time support when building `jemalloc-sys` on some POSIX targets supported by `jemalloc`. Background threads are disabled at run-time by default. This option allows dynamically enabling them at run-time. * `background_threads` (disabled by default): enables background threads by default at run-time. When set to true, background threads are created on demand (the number of background threads will be no more than the number of CPUs or active arenas). Threads run periodically, and handle purging asynchronously. When switching off, background threads are terminated synchronously. Note that after `fork(2)` function, the state in the child process will be disabled regardless the state in parent process. See `stats.background_thread` for related stats. `opt.background_thread` can be used to set the default option. The background thread is only available on selected pthread-based platforms. * `unprefixed_malloc_on_supported_platforms`: when disabled, configure `jemalloc` with `--with-jemalloc-prefix=_rjem_`. Enabling this causes symbols like `malloc` to be emitted without a prefix, overriding the ones defined by libc. This usually causes C and C++ code linked in the same program to use `jemalloc` as well. On some platforms prefixes are always used because unprefixing is known to cause segfaults due to allocator mismatches. * `disable_initial_exec_tls` (disabled by default): when enabled, jemalloc is built with the `--disable-initial-exec-tls` option. It disables the initial-exec TLS model for jemalloc's internal thread-local storage (on those platforms that support explicit settings). This can allow jemalloc to be dynamically loaded after program startup (e.g. using dlopen). If you encounter the error `yourlib.so: cannot allocate memory in static TLS block`, you'll likely want to enable this. * `disable_cache_oblivious` (disabled by default): when enabled, jemalloc is built with the `--disable-cache-oblivious` option. In that case, all large allocations are page-aligned as an implementation artifact. It may severely harm CPU cache utilization. However, the cache-oblivious layout has a cost of one extra page per large allocation which can be unfeasible for certain applications. ### Environment variables `jemalloc` options taking values are passed via environment variables using the schema `JEMALLOC_SYS_{KEY}=VALUE` where the `KEY` names correspond to the `./configure` options of `jemalloc` where the words are capitalized and the hyphens `-` are replaced with underscores `_`(see [`jemalloc/INSTALL.md`][jemalloc_install]): * `JEMALLOC_SYS_WITH_MALLOC_CONF=`: Embed `` as a run-time options string that is processed prior to the `malloc_conf` global variable, the `/etc/malloc.conf` symlink, and the `MALLOC_CONF` environment variable (note: this variable might be prefixed as `_RJEM_MALLOC_CONF`). For example, to change the default decay time for dirty pages to 30 seconds: ``` JEMALLOC_SYS_WITH_MALLOC_CONF=dirty_decay_ms:30000 ``` * `JEMALLOC_SYS_WITH_LG_PAGE=`: Specify the base 2 log of the allocator page size, which must in turn be at least as large as the system page size. By default the configure script determines the host's page size and sets the allocator page size equal to the system page size, so this option need not be specified unless the system page size may change between configuration and execution, e.g. when cross compiling. * `JEMALLOC_SYS_WITH_LG_HUGEPAGE=`: Specify the base 2 log of the system huge page size. This option is useful when cross compiling, or when overriding the default for systems that do not explicitly support huge pages. * `JEMALLOC_SYS_WITH_LG_QUANTUM=`: Specify the base 2 log of the minimum allocation alignment. jemalloc needs to know the minimum alignment that meets the following C standard requirement (quoted from the April 12, 2011 draft of the C11 standard): > The pointer returned if the allocation succeeds is suitably aligned so that > it may be assigned to a pointer to any type of object with a fundamental > alignment requirement and then used to access such an object or an array of > such objects in the space allocated [...] This setting is architecture-specific, and although jemalloc includes known safe values for the most commonly used modern architectures, there is a wrinkle related to GNU libc (glibc) that may impact your choice of . On most modern architectures, this mandates 16-byte alignment (=4), but the glibc developers chose not to meet this requirement for performance reasons. An old discussion can be found at https://sourceware.org/bugzilla/show_bug.cgi?id=206 . Unlike glibc, jemalloc does follow the C standard by default (caveat: jemalloc technically cheats for size classes smaller than the quantum), but the fact that Linux systems already work around this allocator noncompliance means that it is generally safe in practice to let jemalloc's minimum alignment follow glibc's lead. If you specify `JEMALLOC_SYS_WITH_LG_QUANTUM=3` during configuration, jemalloc will provide additional size classes that are not 16-byte-aligned (24, 40, and 56). * `JEMALLOC_SYS_WITH_LG_VADDR=`: Specify the number of significant virtual address bits. By default, the configure script attempts to detect virtual address size on those platforms where it knows how, and picks a default otherwise. This option may be useful when cross-compiling. [jemalloc_install]: https://github.com/jemalloc/jemalloc/blob/dev/INSTALL.md#advanced-configuration ## License This project is 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 `tikv-jemalloc-sys` by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. [travis]: https://travis-ci.com/tikv/jemallocator [Travis-CI Status]: https://travis-ci.com/tikv/jemallocator.svg?branch=master [Latest Version]: https://img.shields.io/crates/v/tikv-jemallocator.svg [crates.io]: https://crates.io/crates/tikv-jemallocator [docs]: https://docs.rs/tikv-jemallocator/badge.svg [docs.rs]: https://docs.rs/tikv-jemallocator/ tikv-jemalloc-sys-0.6.0+5.3.0-1-ge13ca993e8ccb9ba9847cc330696e02839f328f7/build.rs000064400000000000000000000350221046102023000232270ustar 00000000000000// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 or the MIT license // , at your // option. This file may not be copied, modified, or distributed // except according to those terms. use std::{ env, ffi::OsString, fs, io, path::{Path, PathBuf}, process::Command, }; include!("src/env.rs"); macro_rules! info { ($($args:tt)*) => { println!($($args)*) } } macro_rules! warning { ($arg:tt, $($args:tt)*) => { println!(concat!(concat!("cargo:warning=\"", $arg), "\""), $($args)*) } } fn read_and_watch_env_impl(name: &str, env_getter: F) -> Option where F: Fn(&str) -> Option, { let prefix = env::var("TARGET").unwrap().to_uppercase().replace('-', "_"); let prefixed_name = format!("{}_{}", prefix, name); println!("cargo:rerun-if-env-changed={}", prefixed_name); if let Some(value) = env_getter(&prefixed_name) { return Some(value); } println!("cargo:rerun-if-env-changed={}", name); env_getter(name) } fn read_and_watch_env(name: &str) -> Result { read_and_watch_env_impl(name, |n| env::var(n).ok()).ok_or(env::VarError::NotPresent) } fn read_and_watch_env_os(name: &str) -> Option { read_and_watch_env_impl(name, |n| env::var_os(n)) } fn copy_recursively(src: &Path, dst: &Path) -> io::Result<()> { if !dst.exists() { fs::create_dir_all(dst)?; } for entry in fs::read_dir(src)? { let entry = entry?; let ft = entry.file_type()?; if ft.is_dir() { // There should be very few layer in the project, use recusion to keep simple. copy_recursively(&entry.path(), &dst.join(entry.file_name()))?; } else { fs::copy(entry.path(), dst.join(entry.file_name()))?; } } Ok(()) } fn expect_env(name: &str) -> String { env::var(name).unwrap_or_else(|_| panic!("{} was not set", name)) } // TODO: split main functions and remove following allow. #[allow(clippy::cognitive_complexity)] fn main() { let target = expect_env("TARGET"); let host = expect_env("HOST"); let num_jobs = expect_env("NUM_JOBS"); let out_dir = PathBuf::from(env::var_os("OUT_DIR").expect("OUT_DIR was not set")); let src_dir = env::current_dir().expect("failed to get current directory"); let version = expect_env("CARGO_PKG_VERSION"); let je_version = version .split_once('+') .expect("jemalloc version is missing") .1; info!("TARGET={}", target); info!("HOST={}", host); info!("NUM_JOBS={}", num_jobs); info!("OUT_DIR={:?}", out_dir); let build_dir = out_dir.join("build"); info!("BUILD_DIR={:?}", build_dir); info!("SRC_DIR={:?}", src_dir); if UNSUPPORTED_TARGETS.iter().any(|i| target.contains(i)) { panic!("jemalloc does not support target: {}", target); } if UNTESTED_TARGETS.iter().any(|i| target.contains(i)) { warning!("jemalloc support for `{}` is untested", target); } let mut use_prefix = env::var("CARGO_FEATURE_UNPREFIXED_MALLOC_ON_SUPPORTED_PLATFORMS").is_err(); if !use_prefix && NO_UNPREFIXED_MALLOC_TARGETS .iter() .any(|i| target.contains(i)) { warning!( "Unprefixed `malloc` requested on unsupported platform `{}` => using prefixed `malloc`", target ); use_prefix = true; } // this has to occur before the early return when JEMALLOC_OVERRIDE is set if use_prefix { println!("cargo:rustc-cfg=prefixed"); } if let Some(jemalloc) = read_and_watch_env_os("JEMALLOC_OVERRIDE") { info!("jemalloc override set"); let jemalloc = PathBuf::from(jemalloc); assert!( jemalloc.exists(), "Path to `jemalloc` in `JEMALLOC_OVERRIDE={}` does not exist", jemalloc.display() ); println!( "cargo:rustc-link-search=native={}", jemalloc.parent().unwrap().display() ); let stem = jemalloc.file_stem().unwrap().to_str().unwrap(); let name = jemalloc.file_name().unwrap().to_str().unwrap(); let kind = if name.ends_with(".a") { "static" } else { "dylib" }; println!("cargo:rustc-link-lib={}={}", kind, &stem[3..]); return; } // Disable -Wextra warnings - jemalloc doesn't compile free of warnings with // it enabled: https://github.com/jemalloc/jemalloc/issues/1196 let compiler = cc::Build::new().extra_warnings(false).get_compiler(); let cflags = compiler .args() .iter() .map(|s| s.to_str().unwrap()) .collect::>() .join(" "); info!("CC={:?}", compiler.path()); info!("CFLAGS={:?}", cflags); assert!(out_dir.exists(), "OUT_DIR does not exist"); let jemalloc_repo_dir = PathBuf::from("jemalloc"); info!("JEMALLOC_REPO_DIR={:?}", jemalloc_repo_dir); if build_dir.exists() { fs::remove_dir_all(build_dir.clone()).unwrap(); } // Copy jemalloc submodule to the OUT_DIR copy_recursively(&jemalloc_repo_dir, &build_dir) .expect("failed to copy jemalloc source code to OUT_DIR"); assert!(build_dir.exists()); // Configuration files let config_files = ["configure"]; // Copy the configuration files to jemalloc's source directory for f in &config_files { fs::copy(Path::new("configure").join(f), build_dir.join(f)) .expect("failed to copy config file to OUT_DIR"); } // Run configure: let configure = build_dir.join("configure"); let mut cmd = Command::new("sh"); cmd.arg( configure .to_str() .unwrap() .replace("C:\\", "/c/") .replace('\\', "/"), ) .current_dir(&build_dir) .env("CC", compiler.path()) .env("CFLAGS", cflags.clone()) .env("LDFLAGS", cflags.clone()) .env("CPPFLAGS", cflags) .arg(format!("--with-version={je_version}")) .arg("--disable-cxx") .arg("--enable-doc=no") .arg("--enable-shared=no"); if target.contains("ios") { // newer iOS deviced have 16kb page sizes: // closed: https://github.com/gnzlbg/jemallocator/issues/68 cmd.arg("--with-lg-page=14"); } // collect `malloc_conf` string: let mut malloc_conf = String::new(); if let Some(bg) = BackgroundThreadSupport::new(&target) { // `jemalloc` is compiled with background thread run-time support on // available platforms by default so there is nothing to do to enable // it. if bg.always_enabled { // Background thread support does not enable background threads at // run-time, just support for enabling them via run-time configuration // options (they are disabled by default) // The `enable_background_threads` cargo feature forces background // threads to be enabled at run-time by default: malloc_conf += "background_thread:true"; } } else { // Background thread run-time support is disabled by // disabling background threads at compile-time: malloc_conf += "background_thread:false"; } if let Ok(malloc_conf_opts) = read_and_watch_env("JEMALLOC_SYS_WITH_MALLOC_CONF") { if !malloc_conf.is_empty() { malloc_conf.push(','); } malloc_conf.push_str(&malloc_conf_opts); } if !malloc_conf.is_empty() { info!("--with-malloc-conf={}", malloc_conf); cmd.arg(format!("--with-malloc-conf={malloc_conf}")); } if let Ok(lg_page) = read_and_watch_env("JEMALLOC_SYS_WITH_LG_PAGE") { info!("--with-lg-page={}", lg_page); cmd.arg(format!("--with-lg-page={lg_page}")); } if let Ok(lg_hugepage) = read_and_watch_env("JEMALLOC_SYS_WITH_LG_HUGEPAGE") { info!("--with-lg-hugepage={}", lg_hugepage); cmd.arg(format!("--with-lg-hugepage={lg_hugepage}")); } if let Ok(lg_quantum) = read_and_watch_env("JEMALLOC_SYS_WITH_LG_QUANTUM") { info!("--with-lg-quantum={}", lg_quantum); cmd.arg(format!("--with-lg-quantum={lg_quantum}")); } if let Ok(lg_vaddr) = read_and_watch_env("JEMALLOC_SYS_WITH_LG_VADDR") { info!("--with-lg-vaddr={}", lg_vaddr); cmd.arg(format!("--with-lg-vaddr={lg_vaddr}")); } if use_prefix { cmd.arg("--with-jemalloc-prefix=_rjem_"); info!("--with-jemalloc-prefix=_rjem_"); } cmd.arg("--with-private-namespace=_rjem_"); if env::var("CARGO_FEATURE_DEBUG").is_ok() { info!("CARGO_FEATURE_DEBUG set"); cmd.arg("--enable-debug"); } if env::var("CARGO_FEATURE_PROFILING").is_ok() { info!("CARGO_FEATURE_PROFILING set"); cmd.arg("--enable-prof"); } if env::var("CARGO_FEATURE_STATS").is_ok() { info!("CARGO_FEATURE_STATS set"); cmd.arg("--enable-stats"); } else { info!("CARGO_FEATURE_STATS not set"); cmd.arg("--disable-stats"); } if env::var("CARGO_FEATURE_DISABLE_INITIAL_EXEC_TLS").is_ok() { info!("CARGO_FEATURE_DISABLE_INITIAL_EXEC_TLS set"); cmd.arg("--disable-initial-exec-tls"); } if env::var("CARGO_FEATURE_DISABLE_CACHE_OBLIVIOUS").is_ok() { info!("CARGO_FEATURE_DISABLE_CACHE_OBLIVIOUS set"); cmd.arg("--disable-cache-oblivious"); } cmd.arg(format!("--host={}", gnu_target(&target))); cmd.arg(format!("--build={}", gnu_target(&host))); cmd.arg(format!("--prefix={}", out_dir.display())); run_and_log(&mut cmd, &build_dir.join("config.log")); // Make: let make = make_cmd(&host); run(Command::new(make) .current_dir(&build_dir) .arg("-j") .arg(num_jobs.clone())); // Skip watching this environment variables to avoid rebuild in CI. if env::var("JEMALLOC_SYS_RUN_JEMALLOC_TESTS").is_ok() { info!("Building and running jemalloc tests..."); // Make tests: run(Command::new(make) .current_dir(&build_dir) .arg("-j") .arg(num_jobs.clone()) .arg("tests")); // Run tests: run(Command::new(make).current_dir(&build_dir).arg("check")); } // Make install: run(Command::new(make) .current_dir(&build_dir) .arg("install_lib_static") .arg("install_include") .arg("-j") .arg(num_jobs)); println!("cargo:root={}", out_dir.display()); // Linkage directives to pull in jemalloc and its dependencies. // // On some platforms we need to be sure to link in `pthread` which jemalloc // depends on, and specifically on android we need to also link to libgcc. // Currently jemalloc is compiled with gcc which will generate calls to // intrinsics that are libgcc specific (e.g. those intrinsics aren't present in // libcompiler-rt), so link that in to get that support. if target.contains("windows") { println!("cargo:rustc-link-lib=static=jemalloc"); } else { println!("cargo:rustc-link-lib=static=jemalloc_pic"); } println!("cargo:rustc-link-search=native={}/lib", build_dir.display()); if target.contains("android") { println!("cargo:rustc-link-lib=gcc"); } else if !target.contains("windows") { println!("cargo:rustc-link-arg=-pthread"); } // GCC may generate a __atomic_exchange_1 library call which requires -latomic // during the final linking. https://github.com/riscv-collab/riscv-gcc/issues/12 if target.contains("riscv") { println!("cargo:rustc-link-lib=atomic"); } println!("cargo:rerun-if-changed=jemalloc"); if target.contains("android") { // These symbols are used by jemalloc on android but the really old android // we're building on doesn't have them defined, so just make sure the symbols // are available. cc::Build::new() .file("src/pthread_atfork.c") .compile("pthread_atfork"); println!("cargo:rerun-if-changed=src/pthread_atfork.c"); } } fn run_and_log(cmd: &mut Command, log_file: &Path) { execute(cmd, || { run(Command::new("tail").arg("-n").arg("100").arg(log_file)); }) } fn run(cmd: &mut Command) { execute(cmd, || ()); } fn execute(cmd: &mut Command, on_fail: impl FnOnce()) { println!("running: {cmd:?}"); let status = match cmd.status() { Ok(status) => status, Err(e) => panic!("failed to execute command: {}", e), }; if !status.success() { on_fail(); panic!( "command did not execute successfully: {:?}\n\ expected success, got: {}", cmd, status ); } } fn gnu_target(target: &str) -> String { match target { "i686-pc-windows-msvc" => "i686-pc-win32".to_string(), "x86_64-pc-windows-msvc" => "x86_64-pc-win32".to_string(), "i686-pc-windows-gnu" => "i686-w64-mingw32".to_string(), "x86_64-pc-windows-gnu" => "x86_64-w64-mingw32".to_string(), "armv7-linux-androideabi" => "arm-linux-androideabi".to_string(), "riscv64gc-unknown-linux-gnu" => "riscv64-linux-gnu".to_string(), "riscv64gc-unknown-linux-musl" => "riscv64-linux-musl".to_string(), s => s.to_string(), } } fn make_cmd(host: &str) -> &'static str { const GMAKE_HOSTS: &[&str] = &[ "bitrig", "dragonfly", "freebsd", "netbsd", "openbsd", "chimera-linux", ]; if GMAKE_HOSTS.iter().any(|i| host.contains(i)) { "gmake" } else if host.contains("windows") { "mingw32-make" } else { "make" } } struct BackgroundThreadSupport { always_enabled: bool, } impl BackgroundThreadSupport { fn new(target: &str) -> Option { let runtime_support = env::var("CARGO_FEATURE_BACKGROUND_THREADS_RUNTIME_SUPPORT").is_ok(); let always_enabled = env::var("CARGO_FEATURE_BACKGROUND_THREADS").is_ok(); if !runtime_support { assert!( !always_enabled, "enabling `background_threads` requires `background_threads_runtime_support`" ); return None; } if NO_BG_THREAD_TARGETS.iter().any(|i| target.contains(i)) { warning!( "`background_threads_runtime_support` not supported for `{}`", target ); } Some(Self { always_enabled }) } } tikv-jemalloc-sys-0.6.0+5.3.0-1-ge13ca993e8ccb9ba9847cc330696e02839f328f7/src/env.rs000064400000000000000000000020251046102023000235040ustar 00000000000000/// `jemalloc` is known not to work on these targets: pub static UNSUPPORTED_TARGETS: &[&str] = &[ "rumprun", "bitrig", "emscripten", "fuchsia", "redox", "wasm32", ]; /// `jemalloc-sys` is not tested on these targets in CI: pub static UNTESTED_TARGETS: &[&str] = &["openbsd", "msvc"]; /// `jemalloc`'s background_thread support is known not to work on these targets: pub static NO_BG_THREAD_TARGETS: &[&str] = &["musl"]; /// targets that don't support unprefixed `malloc` // “it was found that the `realpath` function in libc would allocate with libc malloc // (not jemalloc malloc), and then the standard library would free with jemalloc free, // causing a segfault.” // https://github.com/rust-lang/rust/commit/e3b414d8612314e74e2b0ebde1ed5c6997d28e8d // https://github.com/rust-lang/rust/commit/9f3de647326fbe50e0e283b9018ab7c41abccde3 // https://github.com/rust-lang/rust/commit/ed015456a114ae907a36af80c06f81ea93182a24 pub static NO_UNPREFIXED_MALLOC_TARGETS: &[&str] = &["android", "dragonfly", "darwin"]; tikv-jemalloc-sys-0.6.0+5.3.0-1-ge13ca993e8ccb9ba9847cc330696e02839f328f7/src/lib.rs000064400000000000000000001055141046102023000234710ustar 00000000000000//! Rust bindings to the `jemalloc` C library. //! //! `jemalloc` is a general purpose memory allocation, its documentation //! can be found here: //! //! * [API documentation][jemalloc_docs] //! * [Wiki][jemalloc_wiki] (design documents, presentations, profiling, debugging, tuning, ...) //! //! `jemalloc` exposes both a standard and a non-standard API. //! //! # Standard API //! //! The standard API includes: the [`malloc`], [`calloc`], [`realloc`], and //! [`free`], which conform to to ISO/IEC 9899:1990 (“ISO C90”), //! [`posix_memalign`] which conforms to conforms to POSIX.1-2016, and //! [`aligned_alloc`]. //! //! Note that these standard leave some details as _implementation defined_. //! This docs document this behavior for `jemalloc`, but keep in mind that other //! standard-conforming implementations of these functions in other allocators //! might behave slightly different. //! //! # Non-Standard API //! //! The non-standard API includes: [`mallocx`], [`rallocx`], [`xallocx`], //! [`sallocx`], [`dallocx`], [`sdallocx`], and [`nallocx`]. These functions all //! have a `flags` argument that can be used to specify options. Use bitwise or //! `|` to specify one or more of the following: [`MALLOCX_LG_ALIGN`], //! [`MALLOCX_ALIGN`], [`MALLOCX_ZERO`], [`MALLOCX_TCACHE`], //! [`MALLOCX_TCACHE_NONE`], and [`MALLOCX_ARENA`]. //! //! # Environment variables //! //! The `MALLOC_CONF` environment variable affects the execution of the allocation functions. //! //! For the documentation of the [`MALLCTL` namespace visit the jemalloc //! documenation][jemalloc_mallctl]. //! //! [jemalloc_docs]: http://jemalloc.net/jemalloc.3.html //! [jemalloc_wiki]: https://github.com/jemalloc/jemalloc/wiki //! [jemalloc_mallctl]: http://jemalloc.net/jemalloc.3.html#mallctl_namespace #![no_std] #![allow(non_snake_case, non_camel_case_types)] // TODO: rename the following lint on next minor bump #![allow(renamed_and_removed_lints)] #![deny(missing_docs, broken_intra_doc_links)] use libc::{c_char, c_int, c_uint, c_void, size_t}; // jemalloc uses `stdbool.h` to define `bool` for which the Rust equivalent is `bool`. // However jemalloc also has its own `stdbool.h` that it uses when compiling with MSVC, // and this header defines `bool` as `BOOL` which in turn is `int`. #[cfg(target_env = "msvc")] type c_bool = c_int; #[cfg(not(target_env = "msvc"))] type c_bool = bool; /// Align the memory allocation to start at an address that is a /// multiple of `1 << la`. /// /// # Safety /// /// It does not validate that `la` is within the valid range. #[inline] pub const fn MALLOCX_LG_ALIGN(la: usize) -> c_int { la as c_int } /// Align the memory allocation to start at an address that is a multiple of `align`, /// where a is a power of two. /// /// # Safety /// /// This macro does not validate that a is a power of 2. #[inline] pub const fn MALLOCX_ALIGN(aling: usize) -> c_int { aling.trailing_zeros() as c_int } /// Initialize newly allocated memory to contain zero bytes. /// /// In the growing reallocation case, the real size prior to reallocation /// defines the boundary between untouched bytes and those that are initialized /// to contain zero bytes. /// /// If this option is not set, newly allocated memory is uninitialized. pub const MALLOCX_ZERO: c_int = 0x40; /// Use the thread-specific cache (_tcache_) specified by the identifier `tc`. /// /// # Safety /// /// `tc` must have been acquired via the `tcache.create mallctl`. This function /// does not validate that `tc` specifies a valid identifier. #[inline] pub const fn MALLOCX_TCACHE(tc: usize) -> c_int { tc.wrapping_add(2).wrapping_shl(8) as c_int } /// Do not use a thread-specific cache (_tcache_). /// /// Unless `MALLOCX_TCACHE(tc)` or `MALLOCX_TCACHE_NONE` is specified, an /// automatically managed _tcache_ will be used under many circumstances. /// /// # Safety /// /// This option cannot be used in the same `flags` argument as /// `MALLOCX_TCACHE(tc)`. // FIXME: This should just be a const. pub const MALLOCX_TCACHE_NONE: c_int = MALLOCX_TCACHE((-1isize) as usize); /// Use the arena specified by the index `a`. /// /// This option has no effect for regions that were allocated via an arena other /// than the one specified. /// /// # Safety /// /// This function does not validate that `a` specifies an arena index in the /// valid range. #[inline] pub const fn MALLOCX_ARENA(a: usize) -> c_int { (a as c_int).wrapping_add(1).wrapping_shl(20) } extern "C" { /// Allocates `size` bytes of uninitialized memory. /// /// It returns a pointer to the start (lowest byte address) of the allocated /// space. This pointer is suitably aligned so that it may be assigned to a /// pointer to any type of object and then used to access such an object in /// the space allocated until the space is explicitly deallocated. Each /// yielded pointer points to an object disjoint from any other object. /// /// If the `size` of the space requested is zero, either a null pointer is /// returned, or the behavior is as if the `size` were some nonzero value, /// except that the returned pointer shall not be used to access an object. /// /// # Errors /// /// If the space cannot be allocated, a null pointer is returned and `errno` /// is set to `ENOMEM`. #[cfg_attr(prefixed, link_name = "_rjem_malloc")] pub fn malloc(size: size_t) -> *mut c_void; /// Allocates zero-initialized space for an array of `number` objects, each /// of whose size is `size`. /// /// The result is identical to calling [`malloc`] with an argument of /// `number * size`, with the exception that the allocated memory is /// explicitly initialized to _zero_ bytes. /// /// Note: zero-initialized memory need not be the same as the /// representation of floating-point zero or a null pointer constant. #[cfg_attr(prefixed, link_name = "_rjem_calloc")] pub fn calloc(number: size_t, size: size_t) -> *mut c_void; /// Allocates `size` bytes of memory at an address which is a multiple of /// `alignment` and is placed in `*ptr`. /// /// If `size` is zero, then the value placed in `*ptr` is either null, or /// the behavior is as if the `size` were some nonzero value, except that /// the returned pointer shall not be used to access an object. /// /// # Errors /// /// On success, it returns zero. On error, the value of `errno` is _not_ set, /// `*ptr` is not modified, and the return values can be: /// /// - `EINVAL`: the `alignment` argument was not a power-of-two or was not a multiple of /// `mem::size_of::<*const c_void>()`. /// - `ENOMEM`: there was insufficient memory to fulfill the allocation request. /// /// # Safety /// /// The behavior is _undefined_ if: /// /// * `ptr` is null. #[cfg_attr(prefixed, link_name = "_rjem_posix_memalign")] pub fn posix_memalign(ptr: *mut *mut c_void, alignment: size_t, size: size_t) -> c_int; /// Allocates `size` bytes of memory at an address which is a multiple of /// `alignment`. /// /// If the `size` of the space requested is zero, either a null pointer is /// returned, or the behavior is as if the `size` were some nonzero value, /// except that the returned pointer shall not be used to access an object. /// /// # Errors /// /// Returns null if the request fails. /// /// # Safety /// /// The behavior is _undefined_ if: /// /// * `alignment` is not a power-of-two /// * `size` is not an integral multiple of `alignment` #[cfg_attr(prefixed, link_name = "_rjem_aligned_alloc")] pub fn aligned_alloc(alignment: size_t, size: size_t) -> *mut c_void; /// Resizes the previously-allocated memory region referenced by `ptr` to /// `size` bytes. /// /// Deallocates the old object pointed to by `ptr` and returns a pointer to /// a new object that has the size specified by `size`. The contents of the /// new object are the same as that of the old object prior to deallocation, /// up to the lesser of the new and old sizes. /// /// The memory in the new object beyond the size of the old object is /// uninitialized. /// /// The returned pointer to a new object may have the same value as a /// pointer to the old object, but [`realloc`] may move the memory /// allocation, resulting in a different return value than `ptr`. /// /// If `ptr` is null, [`realloc`] behaves identically to [`malloc`] for the /// specified size. /// /// If the size of the space requested is zero, the behavior is /// implementation-defined: either a null pointer is returned, or the /// behavior is as if the size were some nonzero value, except that the /// returned pointer shall not be used to access an object # Errors /// /// # Errors /// /// If memory for the new object cannot be allocated, the old object is not /// deallocated, its value is unchanged, [`realloc`] returns null, and /// `errno` is set to `ENOMEM`. /// /// # Safety /// /// The behavior is _undefined_ if: /// /// * `ptr` does not match a pointer previously returned by the memory /// allocation functions of this crate, or /// * the memory region referenced by `ptr` has been deallocated. #[cfg_attr(prefixed, link_name = "_rjem_realloc")] pub fn realloc(ptr: *mut c_void, size: size_t) -> *mut c_void; /// Deallocates previously-allocated memory region referenced by `ptr`. /// /// This makes the space available for future allocations. /// /// If `ptr` is null, no action occurs. /// /// # Safety /// /// The behavior is _undefined_ if: /// /// * `ptr` does not match a pointer earlier returned by the memory /// allocation functions of this crate, or /// * the memory region referenced by `ptr` has been deallocated. #[cfg_attr(prefixed, link_name = "_rjem_free")] pub fn free(ptr: *mut c_void); /// Allocates at least `size` bytes of memory according to `flags`. /// /// It returns a pointer to the start (lowest byte address) of the allocated /// space. This pointer is suitably aligned so that it may be assigned to a /// pointer to any type of object and then used to access such an object in /// the space allocated until the space is explicitly deallocated. Each /// yielded pointer points to an object disjoint from any other object. /// /// # Errors /// /// On success it returns a non-null pointer. A null pointer return value /// indicates that insufficient contiguous memory was available to service /// the allocation request. /// /// # Safety /// /// The behavior is _undefined_ if `size == 0`. #[cfg_attr(prefixed, link_name = "_rjem_mallocx")] pub fn mallocx(size: size_t, flags: c_int) -> *mut c_void; /// Resizes the previously-allocated memory region referenced by `ptr` to be /// at least `size` bytes. /// /// Deallocates the old object pointed to by `ptr` and returns a pointer to /// a new object that has the size specified by `size`. The contents of the /// new object are the same as that of the old object prior to deallocation, /// up to the lesser of the new and old sizes. /// /// The the memory in the new object beyond the size of the old object is /// obtained according to `flags` (it might be uninitialized). /// /// The returned pointer to a new object may have the same value as a /// pointer to the old object, but [`rallocx`] may move the memory /// allocation, resulting in a different return value than `ptr`. /// /// # Errors /// /// On success it returns a non-null pointer. A null pointer return value /// indicates that insufficient contiguous memory was available to service /// the allocation request. In this case, the old object is not /// deallocated, and its value is unchanged. /// /// # Safety /// /// The behavior is _undefiend_ if: /// /// * `size == 0`, or /// * `ptr` does not match a pointer earlier returned by /// the memory allocation functions of this crate, or /// * the memory region referenced by `ptr` has been deallocated. #[cfg_attr(prefixed, link_name = "_rjem_rallocx")] pub fn rallocx(ptr: *mut c_void, size: size_t, flags: c_int) -> *mut c_void; /// Resizes the previously-allocated memory region referenced by `ptr` _in /// place_ to be at least `size` bytes, returning the real size of the /// allocation. /// /// Deallocates the old object pointed to by `ptr` and sets `ptr` to a new /// object that has the size returned; the old a new objects share the same /// base address. The contents of the new object are the same as that of the /// old object prior to deallocation, up to the lesser of the new and old /// sizes. /// /// If `extra` is non-zero, an attempt is made to resize the allocation to /// be at least `size + extra` bytes. Inability to allocate the `extra` /// bytes will not by itself result in failure to resize. /// /// The memory in the new object beyond the size of the old object is /// obtained according to `flags` (it might be uninitialized). /// /// # Errors /// /// If the allocation cannot be adequately grown in place up to `size`, the /// size returned is smaller than `size`. /// /// Note: /// /// * the size value returned can be larger than the size requested during /// allocation /// * when shrinking an allocation, use the size returned to determine /// whether the allocation was shrunk sufficiently or not. /// /// # Safety /// /// The behavior is _undefined_ if: /// /// * `size == 0`, or /// * `size + extra > size_t::max_value()`, or /// * `ptr` does not match a pointer earlier returned by the memory /// allocation functions of this crate, or /// * the memory region referenced by `ptr` has been deallocated. #[cfg_attr(prefixed, link_name = "_rjem_xallocx")] pub fn xallocx(ptr: *mut c_void, size: size_t, extra: size_t, flags: c_int) -> size_t; /// Returns the real size of the previously-allocated memory region /// referenced by `ptr`. /// /// The value may be larger than the size requested on allocation. /// /// # Safety /// /// The behavior is _undefined_ if: /// /// * `ptr` does not match a pointer earlier returned by the memory /// allocation functions of this crate, or /// * the memory region referenced by `ptr` has been deallocated. #[cfg_attr(prefixed, link_name = "_rjem_sallocx")] pub fn sallocx(ptr: *const c_void, flags: c_int) -> size_t; /// Deallocates previously-allocated memory region referenced by `ptr`. /// /// This makes the space available for future allocations. /// /// # Safety /// /// The behavior is _undefined_ if: /// /// * `ptr` does not match a pointer earlier returned by the memory /// allocation functions of this crate, or /// * `ptr` is null, or /// * the memory region referenced by `ptr` has been deallocated. #[cfg_attr(prefixed, link_name = "_rjem_dallocx")] pub fn dallocx(ptr: *mut c_void, flags: c_int); /// Deallocates previously-allocated memory region referenced by `ptr` with /// `size` hint. /// /// This makes the space available for future allocations. /// /// # Safety /// /// The behavior is _undefined_ if: /// /// * `size` is not in range `[req_size, alloc_size]`, where `req_size` is /// the size requested when performing the allocation, and `alloc_size` is /// the allocation size returned by [`nallocx`], [`sallocx`], or /// [`xallocx`], /// * `ptr` does not match a pointer earlier returned by the memory /// allocation functions of this crate, or /// * `ptr` is null, or /// * the memory region referenced by `ptr` has been deallocated. #[cfg_attr(prefixed, link_name = "_rjem_sdallocx")] pub fn sdallocx(ptr: *mut c_void, size: size_t, flags: c_int); /// Returns the real size of the allocation that would result from a /// [`mallocx`] function call with the same arguments. /// /// # Errors /// /// If the inputs exceed the maximum supported size class and/or alignment /// it returns zero. /// /// # Safety /// /// The behavior is _undefined_ if `size == 0`. #[cfg_attr(prefixed, link_name = "_rjem_nallocx")] pub fn nallocx(size: size_t, flags: c_int) -> size_t; /// Returns the real size of the previously-allocated memory region /// referenced by `ptr`. /// /// The value may be larger than the size requested on allocation. /// /// Although the excess bytes can be overwritten by the application without /// ill effects, this is not good programming practice: the number of excess /// bytes in an allocation depends on the underlying implementation. /// /// The main use of this function is for debugging and introspection. /// /// # Errors /// /// If `ptr` is null, 0 is returned. /// /// # Safety /// /// The behavior is _undefined_ if: /// /// * `ptr` does not match a pointer earlier returned by the memory /// allocation functions of this crate, or /// * the memory region referenced by `ptr` has been deallocated. #[cfg_attr(prefixed, link_name = "_rjem_malloc_usable_size")] pub fn malloc_usable_size(ptr: *const c_void) -> size_t; /// General interface for introspecting the memory allocator, as well as /// setting modifiable parameters and triggering actions. /// /// The period-separated name argument specifies a location in a /// tree-structured namespace ([see jemalloc's `MALLCTL` /// documentation][jemalloc_mallctl]). /// /// To read a value, pass a pointer via `oldp` to adequate space to contain /// the value, and a pointer to its length via `oldlenp``; otherwise pass /// null and null. Similarly, to write a value, pass a pointer to the value /// via `newp`, and its length via `newlen`; otherwise pass null and 0. /// /// # Errors /// /// Returns `0` on success, otherwise returns: /// /// * `EINVAL`: if `newp` is not null, and `newlen` is too large or too /// small. Alternatively, `*oldlenp` is too large or too small; in this case /// as much data as possible are read despite the error. /// /// * `ENOENT`: `name` or mib specifies an unknown/invalid value. /// /// * `EPERM`: Attempt to read or write void value, or attempt to write read-only value. /// /// * `EAGAIN`: A memory allocation failure occurred. /// /// * `EFAULT`: An interface with side effects failed in some way not /// directly related to `mallctl` read/write processing. /// /// [jemalloc_mallctl]: http://jemalloc.net/jemalloc.3.html#mallctl_namespace #[cfg_attr(prefixed, link_name = "_rjem_mallctl")] pub fn mallctl( name: *const c_char, oldp: *mut c_void, oldlenp: *mut size_t, newp: *mut c_void, newlen: size_t, ) -> c_int; /// Translates a name to a “Management Information Base” (MIB) that can be /// passed repeatedly to [`mallctlbymib`]. /// /// This avoids repeated name lookups for applications that repeatedly query /// the same portion of the namespace. /// /// On success, `mibp` contains an array of `*miblenp` integers, where /// `*miblenp` is the lesser of the number of components in name and the /// input value of `*miblenp`. Thus it is possible to pass a `*miblenp` that is /// smaller than the number of period-separated name components, which /// results in a partial MIB that can be used as the basis for constructing /// a complete MIB. For name components that are integers (e.g. the 2 in /// arenas.bin.2.size), the corresponding MIB component will always be that /// integer. #[cfg_attr(prefixed, link_name = "_rjem_mallctlnametomib")] pub fn mallctlnametomib(name: *const c_char, mibp: *mut size_t, miblenp: *mut size_t) -> c_int; /// Like [`mallctl`] but taking a `mib` as input instead of a name. #[cfg_attr(prefixed, link_name = "_rjem_mallctlbymib")] pub fn mallctlbymib( mib: *const size_t, miblen: size_t, oldp: *mut c_void, oldpenp: *mut size_t, newp: *mut c_void, newlen: size_t, ) -> c_int; /// Writes summary statistics via the `write_cb` callback function pointer /// and `cbopaque` data passed to `write_cb`, or [`malloc_message`] if `write_cb` /// is null. /// /// The statistics are presented in human-readable form unless “J” /// is specified as a character within the opts string, in which case the /// statistics are presented in JSON format. /// /// This function can be called repeatedly. /// /// General information that never changes during execution can be omitted /// by specifying `g` as a character within the opts string. /// /// Note that [`malloc_message`] uses the `mallctl*` functions internally, /// so inconsistent statistics can be reported if multiple threads use these /// functions simultaneously. /// /// If the Cargo feature `stats` is enabled, `m`, `d`, and `a` can be /// specified to omit merged arena, destroyed merged arena, and per arena /// statistics, respectively; `b` and `l` can be specified to omit per size /// class statistics for bins and large objects, respectively; `x` can be /// specified to omit all mutex statistics. Unrecognized characters are /// silently ignored. /// /// Note that thread caching may prevent some statistics from being /// completely up to date, since extra locking would be required to merge /// counters that track thread cache operations. #[cfg_attr(prefixed, link_name = "_rjem_malloc_stats_print")] pub fn malloc_stats_print( write_cb: Option, cbopaque: *mut c_void, opts: *const c_char, ); /// Allows overriding the function which emits the text strings forming the /// errors and warnings if for some reason the `STDERR_FILENO` file descriptor /// is not suitable for this. /// /// [`malloc_message`] takes the `cbopaque` pointer argument that is null, /// unless overridden by the arguments in a call to [`malloc_stats_print`], /// followed by a string pointer. /// /// Please note that doing anything which tries to allocate memory in this /// function is likely to result in a crash or deadlock. #[cfg_attr(prefixed, link_name = "_rjem_malloc_message")] pub static mut malloc_message: Option; /// Compile-time string of configuration options. /// /// Once, when the first call is made to one of the memory allocation /// routines, the allocator initializes its internals based in part on /// various options that can be specified at compile- or run-time. /// /// The string specified via `--with-malloc-conf`, the string pointed to by /// the global variable `malloc_conf`, the “name” of the file referenced by /// the symbolic link named `/etc/malloc.conf`, and the value of the /// environment variable `MALLOC_CONF`, will be interpreted, in that order, /// from left to right as options. Note that `malloc_conf` may be read /// before `main()` is entered, so the declaration of `malloc_conf` should /// specify an initializer that contains the final value to be read by /// `jemalloc`. /// /// `--with-malloc-conf` and `malloc_conf` are compile-time mechanisms, whereas /// `/etc/malloc.conf` and `MALLOC_CONF` can be safely set any time prior to /// program invocation. /// /// An options string is a comma-separated list of `option:value` pairs. /// There is one key corresponding to each `opt.* mallctl` (see the `MALLCTL /// NAMESPACE` section for options documentation). For example, /// `abort:true,narenas:1` sets the `opt.abort` and `opt.narenas` options. /// Some options have boolean values (`true`/`false`), others have integer /// values (base `8`, `10`, or `16`, depending on prefix), and yet others /// have raw string values. #[cfg_attr(prefixed, link_name = "_rjem_malloc_conf")] pub static malloc_conf: Option<&'static c_char>; } /// Extent lifetime management functions. pub type extent_hooks_t = extent_hooks_s; // note: there are two structs here, one is used when compiling the crate normally, // and the other one is behind the `--cfg jemallocator_docs` flag and used only // when generating docs. // // For the docs we want to use type aliases here, but `ctest` does see through // them when generating the code to verify the FFI bindings, and it needs to // be able to tell that these are `fn` types so that `Option` gets lowered // to C function pointers. #[repr(C)] #[cfg(not(jemallocator_docs))] #[derive(Copy, Clone, Default)] #[doc(hidden)] #[allow(missing_docs)] pub struct extent_hooks_s { pub alloc: Option< unsafe extern "C" fn( *mut extent_hooks_t, *mut c_void, size_t, size_t, *mut c_bool, *mut c_bool, c_uint, ) -> *mut c_void, >, pub dalloc: Option< unsafe extern "C" fn(*mut extent_hooks_t, *mut c_void, size_t, c_bool, c_uint) -> c_bool, >, pub destroy: Option, pub commit: Option< unsafe extern "C" fn( *mut extent_hooks_t, *mut c_void, size_t, size_t, size_t, c_uint, ) -> c_bool, >, pub decommit: Option< unsafe extern "C" fn( *mut extent_hooks_t, *mut c_void, size_t, size_t, size_t, c_uint, ) -> c_bool, >, pub purge_lazy: Option< unsafe extern "C" fn( *mut extent_hooks_t, *mut c_void, size_t, size_t, size_t, c_uint, ) -> c_bool, >, pub purge_forced: Option< unsafe extern "C" fn( *mut extent_hooks_t, *mut c_void, size_t, size_t, size_t, c_uint, ) -> c_bool, >, pub split: Option< unsafe extern "C" fn( *mut extent_hooks_t, *mut c_void, size_t, size_t, size_t, c_bool, c_uint, ) -> c_bool, >, pub merge: Option< unsafe extern "C" fn( *mut extent_hooks_t, *mut c_void, size_t, *mut c_void, size_t, c_bool, c_uint, ) -> c_bool, >, } /// Extent lifetime management functions. /// /// The extent_hooks_t structure comprises function pointers which are described /// individually below. `jemalloc` uses these functions to manage extent lifetime, /// which starts off with allocation of mapped committed memory, in the simplest /// case followed by deallocation. However, there are performance and platform /// reasons to retain extents for later reuse. Cleanup attempts cascade from /// deallocation to decommit to forced purging to lazy purging, which gives the /// extent management functions opportunities to reject the most permanent /// cleanup operations in favor of less permanent (and often less costly) /// operations. All operations except allocation can be universally opted out of /// by setting the hook pointers to `NULL`, or selectively opted out of by /// returning failure. Note that once the extent hook is set, the structure is /// accessed directly by the associated arenas, so it must remain valid for the /// entire lifetime of the arenas. #[repr(C)] #[cfg(jemallocator_docs)] #[derive(Copy, Clone, Default)] pub struct extent_hooks_s { #[allow(missing_docs)] pub alloc: Option, #[allow(missing_docs)] pub dalloc: Option, #[allow(missing_docs)] pub destroy: Option, #[allow(missing_docs)] pub commit: Option, #[allow(missing_docs)] pub decommit: Option, #[allow(missing_docs)] pub purge_lazy: Option, #[allow(missing_docs)] pub purge_forced: Option, #[allow(missing_docs)] pub split: Option, #[allow(missing_docs)] pub merge: Option, } /// Extent allocation function. /// /// On success returns a pointer to `size` bytes of mapped memory on behalf of /// arena `arena_ind` such that the extent's base address is a multiple of /// `alignment`, as well as setting `*zero` to indicate whether the extent is /// zeroed and `*commit` to indicate whether the extent is committed. /// /// Zeroing is mandatory if `*zero` is `true` upon function entry. Committing is mandatory if /// `*commit` is true upon function entry. If `new_addr` is not null, the returned /// pointer must be `new_addr` on success or null on error. /// /// Committed memory may be committed in absolute terms as on a system that does /// not overcommit, or in implicit terms as on a system that overcommits and /// satisfies physical memory needs on demand via soft page faults. Note that /// replacing the default extent allocation function makes the arena's /// `arena..dss` setting irrelevant. /// /// # Errors /// /// On error the function returns null and leaves `*zero` and `*commit` unmodified. /// /// # Safety /// /// The behavior is _undefined_ if: /// /// * the `size` parameter is not a multiple of the page size /// * the `alignment` parameter is not a power of two at least as large as the page size pub type extent_alloc_t = unsafe extern "C" fn( extent_hooks: *mut extent_hooks_t, new_addr: *mut c_void, size: size_t, alignment: size_t, zero: *mut c_bool, commit: *mut c_bool, arena_ind: c_uint, ) -> *mut c_void; /// Extent deallocation function. /// /// Deallocates an extent at given `addr` and `size` with `committed`/decommited /// memory as indicated, on behalf of arena `arena_ind`, returning `false` upon /// success. /// /// If the function returns `true`, this indicates opt-out from deallocation; /// the virtual memory mapping associated with the extent remains mapped, in the /// same commit state, and available for future use, in which case it will be /// automatically retained for later reuse. pub type extent_dalloc_t = unsafe extern "C" fn( extent_hooks: *mut extent_hooks_t, addr: *mut c_void, size: size_t, committed: c_bool, arena_ind: c_uint, ) -> c_bool; /// Extent destruction function. /// /// Unconditionally destroys an extent at given `addr` and `size` with /// `committed`/decommited memory as indicated, on behalf of arena `arena_ind`. /// /// This function may be called to destroy retained extents during arena /// destruction (see `arena..destroy`). pub type extent_destroy_t = unsafe extern "C" fn( extent_hooks: *mut extent_hooks_t, addr: *mut c_void, size: size_t, committed: c_bool, arena_ind: c_uint, ); /// Extent commit function. /// /// Commits zeroed physical memory to back pages within an extent at given /// `addr` and `size` at `offset` bytes, extending for `length` on behalf of /// arena `arena_ind`, returning `false` upon success. /// /// Committed memory may be committed in absolute terms as on a system that does /// not overcommit, or in implicit terms as on a system that overcommits and /// satisfies physical memory needs on demand via soft page faults. If the /// function returns `true`, this indicates insufficient physical memory to /// satisfy the request. pub type extent_commit_t = unsafe extern "C" fn( extent_hooks: *mut extent_hooks_t, addr: *mut c_void, size: size_t, offset: size_t, length: size_t, arena_ind: c_uint, ) -> c_bool; /// Extent decommit function. /// /// Decommits any physical memory that is backing pages within an extent at /// given `addr` and `size` at `offset` bytes, extending for `length` on behalf of arena /// `arena_ind`, returning `false` upon success, in which case the pages will be /// committed via the extent commit function before being reused. /// /// If the function returns `true`, this indicates opt-out from decommit; the /// memory remains committed and available for future use, in which case it will /// be automatically retained for later reuse. pub type extent_decommit_t = unsafe extern "C" fn( extent_hooks: *mut extent_hooks_t, addr: *mut c_void, size: size_t, offset: size_t, length: size_t, arena_ind: c_uint, ) -> c_bool; /// Extent purge function. /// /// Discards physical pages within the virtual memory mapping associated with an /// extent at given `addr` and `size` at `offset` bytes, extending for `length` on /// behalf of arena `arena_ind`. /// /// A lazy extent purge function (e.g. implemented via `madvise(...MADV_FREE)`) /// can delay purging indefinitely and leave the pages within the purged virtual /// memory range in an indeterminite state, whereas a forced extent purge /// function immediately purges, and the pages within the virtual memory range /// will be zero-filled the next time they are accessed. If the function returns /// `true`, this indicates failure to purge. pub type extent_purge_t = unsafe extern "C" fn( extent_hooks: *mut extent_hooks_t, addr: *mut c_void, size: size_t, offset: size_t, length: size_t, arena_ind: c_uint, ) -> c_bool; /// Extent split function. /// /// Optionally splits an extent at given `addr` and `size` into two adjacent /// extents, the first of `size_a` bytes, and the second of `size_b` bytes, /// operating on `committed`/decommitted memory as indicated, on behalf of arena /// `arena_ind`, returning `false` upon success. /// /// If the function returns `true`, this indicates that the extent remains /// unsplit and therefore should continue to be operated on as a whole. pub type extent_split_t = unsafe extern "C" fn( extent_hooks: *mut extent_hooks_t, addr: *mut c_void, size: size_t, size_a: size_t, size_b: size_t, committed: c_bool, arena_ind: c_uint, ) -> c_bool; /// Extent merge function. /// /// Optionally merges adjacent extents, at given `addr_a` and `size_a` with given /// `addr_b` and `size_b` into one contiguous extent, operating on /// `committed`/decommitted memory as indicated, on behalf of arena `arena_ind`, /// returning `false` upon success. /// /// If the function returns `true`, this indicates that the extents remain /// distinct mappings and therefore should continue to be operated on /// independently. pub type extent_merge_t = unsafe extern "C" fn( extent_hooks: *mut extent_hooks_t, addr_a: *mut c_void, size_a: size_t, addr_b: *mut c_void, size_b: size_t, committed: c_bool, arena_ind: c_uint, ) -> c_bool; #[allow(missing_docs)] mod env; pub use env::*; tikv-jemalloc-sys-0.6.0+5.3.0-1-ge13ca993e8ccb9ba9847cc330696e02839f328f7/src/pthread_atfork.c000064400000000000000000000006241046102023000255120ustar 00000000000000/* * These symbols are used by jemalloc on android but the really old android * we're building on doesn't have them defined, so just make sure the symbols * are available. */ __attribute__((weak)) int pthread_atfork(void (*prepare)(void) __attribute__((unused)), void (*parent)(void) __attribute__((unused)), void (*child)(void) __attribute__((unused))) { return 0; } tikv-jemalloc-sys-0.6.0+5.3.0-1-ge13ca993e8ccb9ba9847cc330696e02839f328f7/tests/malloc_conf_empty.rs000064400000000000000000000001611046102023000267600ustar 00000000000000#[test] fn malloc_conf_empty() { unsafe { assert!(tikv_jemalloc_sys::malloc_conf.is_none()); } } tikv-jemalloc-sys-0.6.0+5.3.0-1-ge13ca993e8ccb9ba9847cc330696e02839f328f7/tests/malloc_conf_set.rs000064400000000000000000000022271046102023000264220ustar 00000000000000union U { x: &'static u8, y: &'static libc::c_char, } #[allow(non_upper_case_globals)] #[cfg_attr(prefixed, export_name = "_rjem_malloc_conf")] #[cfg_attr(not(prefixed), no_mangle)] pub static malloc_conf: Option<&'static libc::c_char> = Some(unsafe { U { x: &b"stats_print_opts:mdal\0"[0], } .y }); #[test] fn malloc_conf_set() { unsafe { assert_eq!(tikv_jemalloc_sys::malloc_conf, malloc_conf); let mut ptr: *const libc::c_char = std::ptr::null(); let mut ptr_len: libc::size_t = std::mem::size_of::<*const libc::c_char>() as libc::size_t; let r = tikv_jemalloc_sys::mallctl( &b"opt.stats_print_opts\0"[0] as *const _ as *const libc::c_char, &mut ptr as *mut *const _ as *mut libc::c_void, &mut ptr_len as *mut _, std::ptr::null_mut(), 0, ); assert_eq!(r, 0); assert!(!ptr.is_null()); let s = std::ffi::CStr::from_ptr(ptr).to_string_lossy().into_owned(); assert!( s.contains("mdal"), "opt.stats_print_opts: \"{}\" (len = {})", s, s.len() ); } } tikv-jemalloc-sys-0.6.0+5.3.0-1-ge13ca993e8ccb9ba9847cc330696e02839f328f7/tests/unprefixed_malloc.rs000064400000000000000000000004061046102023000267700ustar 00000000000000#[cfg(prefixed)] #[test] fn malloc_is_prefixed() { assert_ne!(tikv_jemalloc_sys::malloc as usize, libc::malloc as usize) } #[cfg(not(prefixed))] #[test] fn malloc_is_overridden() { assert_eq!(tikv_jemalloc_sys::malloc as usize, libc::malloc as usize) } tikv-jemalloc-sys-0.6.0+5.3.0-1-ge13ca993e8ccb9ba9847cc330696e02839f328f7/update_jemalloc.md000064400000000000000000000003671046102023000252400ustar 00000000000000# Updating jemalloc Updating the `jemalloc` version requires generating new `configure` files, which requires `autoconf` to be installed. To generate the configuration files, go to the `jemalloc` source directory and run: ```shell autoconf ```