argmax-0.3.1/.cargo_vcs_info.json0000644000000001360000000000100123140ustar { "git": { "sha1": "19fc18ed9990cbb1e06b49d3be93f5df82fa2b31" }, "path_in_vcs": "" }argmax-0.3.1/.github/workflows/CICD.yml000064400000000000000000000116221046102023000157300ustar 00000000000000name: CICD env: MIN_SUPPORTED_RUST_VERSION: "1.46.0" CICD_INTERMEDIATES_DIR: "_cicd-intermediates" on: workflow_dispatch: pull_request: push: branches: - master tags: - '*' jobs: min_version: name: Minimum supported rust version runs-on: ubuntu-20.04 steps: - name: Checkout source code uses: actions/checkout@v2 - name: Install rust toolchain (v${{ env.MIN_SUPPORTED_RUST_VERSION }}) uses: actions-rs/toolchain@v1 with: toolchain: ${{ env.MIN_SUPPORTED_RUST_VERSION }} default: true profile: minimal # minimal component installation (ie, no documentation) components: clippy, rustfmt - name: Ensure `cargo fmt` has been run uses: actions-rs/cargo@v1 with: command: fmt args: -- --check - name: Run clippy (on minimum supported rust version to prevent warnings we can't fix) uses: actions-rs/cargo@v1 with: command: clippy args: --all-targets --all-features -- --allow clippy::unknown_clippy_lints - name: Run tests uses: actions-rs/cargo@v1 with: command: test documentation: name: Documentation runs-on: ubuntu-20.04 steps: - name: Git checkout uses: actions/checkout@v2 - name: Install Rust toolchain uses: actions-rs/toolchain@v1 with: toolchain: stable default: true profile: minimal - name: Check documentation env: RUSTDOCFLAGS: -D warnings uses: actions-rs/cargo@v1 with: command: doc args: --no-deps --document-private-items --all-features build: name: ${{ matrix.job.target }} (${{ matrix.job.os }}) runs-on: ${{ matrix.job.os }} strategy: fail-fast: false matrix: job: - { target: aarch64-unknown-linux-gnu , os: ubuntu-20.04, use-cross: true } - { target: arm-unknown-linux-gnueabihf , os: ubuntu-20.04, use-cross: true } - { target: arm-unknown-linux-musleabihf, os: ubuntu-20.04, use-cross: true } - { target: i686-pc-windows-msvc , os: windows-2019 } - { target: i686-unknown-linux-gnu , os: ubuntu-20.04, use-cross: true } - { target: i686-unknown-linux-musl , os: ubuntu-20.04, use-cross: true } - { target: x86_64-apple-darwin , os: macos-10.15 } - { target: x86_64-pc-windows-gnu , os: windows-2019 } - { target: x86_64-pc-windows-msvc , os: windows-2019 } - { target: x86_64-unknown-linux-gnu , os: ubuntu-20.04 } - { target: x86_64-unknown-linux-musl , os: ubuntu-20.04, use-cross: true } steps: - name: Checkout source code uses: actions/checkout@v2 - name: Install prerequisites shell: bash run: | case ${{ matrix.job.target }} in arm-unknown-linux-*) sudo apt-get -y update ; sudo apt-get -y install gcc-arm-linux-gnueabihf ;; aarch64-unknown-linux-gnu) sudo apt-get -y update ; sudo apt-get -y install gcc-aarch64-linux-gnu ;; esac - name: Extract crate information shell: bash run: | echo "PROJECT_NAME=$(sed -n 's/^name = "\(.*\)"/\1/p' Cargo.toml | head -n1)" >> $GITHUB_ENV echo "PROJECT_VERSION=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -n1)" >> $GITHUB_ENV echo "PROJECT_MAINTAINER=$(sed -n 's/^authors = \["\(.*\)"\]/\1/p' Cargo.toml)" >> $GITHUB_ENV echo "PROJECT_HOMEPAGE=$(sed -n 's/^homepage = "\(.*\)"/\1/p' Cargo.toml)" >> $GITHUB_ENV - name: Install Rust toolchain uses: actions-rs/toolchain@v1 with: toolchain: stable target: ${{ matrix.job.target }} override: true profile: minimal # minimal component installation (ie, no documentation) - name: Show version information (Rust, cargo, GCC) shell: bash run: | gcc --version || true rustup -V rustup toolchain list rustup default cargo -V rustc -V - name: Build uses: actions-rs/cargo@v1 with: use-cross: ${{ matrix.job.use-cross }} command: build args: --release --target=${{ matrix.job.target }} - name: Set testing options id: test-options shell: bash run: | # test only library unit tests for arm-type targets unset CARGO_TEST_OPTIONS unset CARGO_TEST_OPTIONS ; case ${{ matrix.job.target }} in arm-* | aarch64-*) CARGO_TEST_OPTIONS="--lib ${PROJECT_NAME}" ;; esac; echo ::set-output name=CARGO_TEST_OPTIONS::${CARGO_TEST_OPTIONS} - name: Run tests uses: actions-rs/cargo@v1 with: use-cross: ${{ matrix.job.use-cross }} command: test args: --target=${{ matrix.job.target }} ${{ steps.test-options.outputs.CARGO_TEST_OPTIONS}} -- --nocapture --test-threads 1 argmax-0.3.1/.gitignore000064400000000000000000000000231046102023000130670ustar 00000000000000/target Cargo.lock argmax-0.3.1/Cargo.toml0000644000000017750000000000100103240ustar # 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" name = "argmax" version = "0.3.1" authors = ["David Peter "] description = " Rust library to deal with 'argument too long' errors" homepage = "https://github.com/sharkdp/argmax" readme = "README.md" categories = ["command-line-interface"] license = "MIT/Apache-2.0" repository = "https://github.com/sharkdp/argmax" [dependencies.lazy_static] version = "1.4" [dependencies.nix] version = "0.24.2" features = ["feature"] default-features = false [target."cfg(unix)".dependencies.libc] version = "0.2.126" argmax-0.3.1/Cargo.toml.orig000064400000000000000000000010221046102023000137660ustar 00000000000000[package] name = "argmax" description = " Rust library to deal with 'argument too long' errors" categories = ["command-line-interface"] homepage = "https://github.com/sharkdp/argmax" repository = "https://github.com/sharkdp/argmax" license = "MIT/Apache-2.0" version = "0.3.1" readme = "README.md" edition = "2018" authors = ["David Peter "] [dependencies] nix = { version = "0.24.2", default-features = false, features = ["feature"] } lazy_static = "1.4" [target.'cfg(unix)'.dependencies] libc = "0.2.126" argmax-0.3.1/LICENSE-APACHE000064400000000000000000000261351046102023000130370ustar 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. argmax-0.3.1/LICENSE-MIT000064400000000000000000000017771046102023000125540ustar 00000000000000Permission 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. argmax-0.3.1/README.md000064400000000000000000000030041046102023000123600ustar 00000000000000# argmax Version info [![CICD](https://github.com/sharkdp/argmax/actions/workflows/CICD.yml/badge.svg)](https://github.com/sharkdp/argmax/actions/workflows/CICD.yml) `argmax` is a library that allows Rust applications to avoid *Argument list too long* errors (`E2BIG`) by providing a `std::process::Command` wrapper with a ``` rust fn try_arg>(&mut self, arg: S) -> io::Result<&mut Self> ``` function that returns a proper `Err`or if `arg` would overflow the maximum size. ## Resources This library draws inspiration from the following sources. The implementation is based on the corresponding functionality in [`bfs`](https://github.com/tavianator/bfs) [1]. - [1] https://github.com/tavianator/bfs/blob/9b50adaaaa4fedc8bda6fcf32595ecf7a682fa8b/exec.c#L72 - [2] http://mywiki.wooledge.org/BashFAQ/095 - [3] https://www.in-ulm.de/~mascheck/various/argmax/ - [4] https://stackoverflow.com/questions/46897008/why-am-i-getting-e2big-from-exec-when-im-accounting-for-the-arguments-and-the - [5] https://github.com/rust-lang/rust/issues/40384 - [6] `xargs --show-limits` ## 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. argmax-0.3.1/src/constants.rs000064400000000000000000000004341046102023000142560ustar 00000000000000pub(crate) const REASONABLE_DEFAULT_LENGTH: i64 = 8 * 1024; /// We make a conservative guess for the size of a single pointer (64-bit) here /// in order to support scenarios where a 32-bit binary is launching a 64-bit /// binary. pub(crate) const POINTER_SIZE_CONSERVATIVE: i64 = 8; argmax-0.3.1/src/experimental_limit.rs000064400000000000000000000016511046102023000161370ustar 00000000000000use std::process::Command; #[cfg(not(windows))] fn get_echo_command() -> Command { Command::new("echo") } #[cfg(windows)] fn get_echo_command() -> Command { let mut cmd = Command::new("cmd"); cmd.arg("/c"); cmd.arg("echo"); cmd } fn command_with_n_args_succeeds(n: i64) -> bool { use std::process::Stdio; get_echo_command() .args((0..n).map(|_| "foo")) .stdout(Stdio::null()) .stderr(Stdio::null()) .status() .map(|status| status.success()) .unwrap_or(false) } fn binary_search(mut lower: i64, mut upper: i64) -> i64 { while lower <= upper { let n = (lower + upper) / 2; if command_with_n_args_succeeds(n) { lower = n + 1; } else { upper = n - 1; } } lower } pub(crate) fn experimental_arg_limit() -> i64 { std::env::set_var("WINEDEBUG", "-all"); binary_search(0, 1_000_000) } argmax-0.3.1/src/lib.rs000064400000000000000000000134021046102023000130070ustar 00000000000000//! `argmax` is a library that allows applications to avoid *Argument list too long* errors //! (`E2BIG`) by providing a wrapper around [`std::process::Command`]. The [`Command::try_arg`] //! function can be used to add as many arguments as possible. The function returns `false` if no //! more arguments can be added (command execution would result in immediate failure). //! //! # Usage //! ``` //! # #[cfg(unix)] //! # { //! use argmax::Command; //! //! let mut cmd = Command::new("echo"); //! //! // Add as many arguments as possible //! while cmd.try_arg("foo").is_ok() {} //! //! assert!(cmd.status().unwrap().success()); //! # } //! ``` use std::ffi::OsStr; use std::io; use std::ops::Deref; use std::path::Path; use std::process::{self, Child, ExitStatus, Output, Stdio}; mod constants; #[cfg(not(unix))] mod other; #[cfg(unix)] mod unix; #[cfg(not(unix))] use other as platform; #[cfg(unix)] use unix as platform; #[cfg(test)] mod experimental_limit; #[derive(Debug)] pub struct Command { inner: process::Command, remaining_argument_length: i64, } impl Command { /// See [`std::process::Command::new`][process::Command#method.new]. pub fn new>(program: S) -> Self { Command { inner: process::Command::new(&program), remaining_argument_length: platform::available_argument_length([program].iter()) .unwrap_or(constants::REASONABLE_DEFAULT_LENGTH), } } /// Return the appropriate error for a too-big command line. fn e2big() -> io::Error { // io::ErrorKind::ArgumentListTooLong is unstable, so get it manually #[cfg(unix)] return io::Error::from_raw_os_error(libc::E2BIG); #[cfg(not(unix))] return io::ErrorKind::Other.into(); } /// Get the size of some arguments, if they'll fit. fn check_size(&self, args: I) -> io::Result where I: IntoIterator, S: AsRef, { let mut size = 0; for arg in args { let arg = arg.as_ref(); if arg.len() as i64 > platform::max_single_argument_length() { return Err(Self::e2big()); } size += platform::arg_size(arg); } if size > self.remaining_argument_length { return Err(Self::e2big()); } Ok(size) } /// Check if an additional argument would fit in the command. pub fn arg_would_fit>(&self, arg: S) -> bool { self.args_would_fit(&[arg]) } /// Check if multiple additional arguments would all fit in the command. pub fn args_would_fit(&self, args: I) -> bool where I: IntoIterator, S: AsRef, { self.check_size(args).is_ok() } /// Like [`std::process::Command::arg`][process::Command#method.arg], add an argument to the /// command, but only if it will fit. pub fn try_arg>(&mut self, arg: S) -> io::Result<&mut Self> { self.try_args(&[arg]) } /// Like [`std::process::Command::arg`][process::Command#method.args], add multiple arguments to /// the command, but only if they will all fit. pub fn try_args(&mut self, args: I) -> io::Result<&mut Self> where I: IntoIterator + Copy, S: AsRef, { let size = self.check_size(args)?; self.inner.args(args); self.remaining_argument_length -= size; Ok(self) } /// See [`std::process::Command::current_dir`][process::Command#method.current_dir]. pub fn current_dir>(&mut self, dir: P) -> &mut Self { self.inner.current_dir(dir); self } /// See [`std::process::Command::stdin`][process::Command#method.stdin]. pub fn stdin>(&mut self, cfg: T) -> &mut Self { self.inner.stdin(cfg); self } /// See [`std::process::Command::stdout`][process::Command#method.stdout]. pub fn stdout>(&mut self, cfg: T) -> &mut Self { self.inner.stdout(cfg); self } /// See [`std::process::Command::stderr`][process::Command#method.stderr]. pub fn stderr>(&mut self, cfg: T) -> &mut Self { self.inner.stderr(cfg); self } /// See [`std::process::Command::spawn`][process::Command#method.spawn]. pub fn spawn(&mut self) -> io::Result { self.inner.spawn() } /// See [`std::process::Command::output`][process::Command#method.output]. pub fn output(&mut self) -> io::Result { self.inner.output() } /// See [`std::process::Command::status`][process::Command#method.status]. pub fn status(&mut self) -> io::Result { self.inner.status() } } impl Deref for Command { type Target = process::Command; fn deref(&self) -> &Self::Target { &self.inner } } #[cfg(test)] mod tests { use super::*; #[test] fn test_api() { let mut cmd = Command::new("echo"); cmd.try_arg("Hello").expect("try_arg() to succeed"); cmd.try_args(&["world", "!"]) .expect("try_args() to succeed"); cmd.current_dir("."); cmd.stdin(Stdio::inherit()); cmd.stdout(Stdio::piped()); cmd.stderr(Stdio::null()); let mut output = cmd .spawn() .expect("spawn() to succeed") .wait_with_output() .expect("wait_with_output() to succeed"); assert!(output.stdout.len() > 13); assert!(output.status.success()); output = cmd.output().expect("output() to succeed"); assert!(output.stdout.len() > 13); assert!(output.status.success()); let status = cmd.status().expect("status() to succeed"); assert!(status.success()); } } argmax-0.3.1/src/other.rs000064400000000000000000000017651046102023000133730ustar 00000000000000// TODO: This whole module has not been properly tested. Most of this is just a guess. // Some of it has been found by trial and error. use std::ffi::OsStr; use crate::constants::{POINTER_SIZE_CONSERVATIVE, REASONABLE_DEFAULT_LENGTH}; pub(crate) const MAX_SINGLE_ARGUMENT_LENGTH: i64 = REASONABLE_DEFAULT_LENGTH; pub(crate) fn arg_size>(arg: O) -> i64 { POINTER_SIZE_CONSERVATIVE // size for the pointer in argv** + arg.as_ref().len() as i64 // size for argument string + 1 // terminating NULL } pub(crate) fn available_argument_length>( fixed_args: impl Iterator, ) -> Option { Some(REASONABLE_DEFAULT_LENGTH - fixed_args.map(|a| arg_size(a.as_ref())).sum::() - 1) } pub(crate) const fn max_single_argument_length() -> i64 { MAX_SINGLE_ARGUMENT_LENGTH } #[test] fn show_experimental_limit() { use crate::experimental_limit::experimental_arg_limit; println!("Experimental limit: {}", experimental_arg_limit()); } argmax-0.3.1/src/unix.rs000064400000000000000000000074121046102023000132300ustar 00000000000000// The code in this module is a direct translation of the corresponding C // implementation in 'bfs' (https://github.com/tavianator/bfs), as of commit // 9b50adaaaa4fedc8bda6fcf32595ecf7a682fa8b. bfs is licensed under the BSD // Zero Clause License, copyright Tavian Barnes . use std::env; use std::ffi::OsStr; use lazy_static::lazy_static; use nix::unistd::{sysconf, SysconfVar}; use crate::constants::POINTER_SIZE_CONSERVATIVE; const UPPER_BOUND_COMMAND_LINE_LENGTH: i64 = 16 * 1024 * 1024; lazy_static! { static ref PAGE_SIZE: i64 = { sysconf(SysconfVar::PAGE_SIZE) .ok() .flatten() .map(|page_size| page_size as i64) .filter(|s| *s >= 4096) .unwrap_or(4096) }; // TODO: The following is probably Linux specific. See /usr/include/linux/binfmts.h for // details. pub static ref MAX_SINGLE_ARGUMENT_LENGTH: i64 = 32 * *PAGE_SIZE - 1; } /// Required size for a single KEY=VAR environment variable string and the /// corresponding pointer in envp**. fn environment_variable_size>(key: O, value: O) -> i64 { POINTER_SIZE_CONSERVATIVE // size for the pointer in envp** + key.as_ref().len() as i64 // size for the variable name + 1 // size for the '=' sign + value.as_ref().len() as i64 // size for the value + 1 // terminating NULL } /// Required size to store all environment variables fn size_of_environment() -> i64 { env::vars_os() .map(|(key, value)| environment_variable_size(&key, &value)) .sum() } /// Required size to store a single ARG argument and the corresponding /// pointer in argv**. pub(crate) fn arg_size>(arg: O) -> i64 { POINTER_SIZE_CONSERVATIVE // size for the pointer in argv** + arg.as_ref().len() as i64 // size for argument string + 1 // terminating NULL } /// Total size that is available for arguments to a spawned child process. pub(crate) fn available_argument_length>( fixed_args: impl Iterator, ) -> Option { let mut arg_max = sysconf(SysconfVar::ARG_MAX).ok().flatten()? as i64; if arg_max < 0 { arg_max = UPPER_BOUND_COMMAND_LINE_LENGTH; } // We have to share space with the environment variables arg_max -= size_of_environment(); // Account for the terminating NULL entry arg_max -= POINTER_SIZE_CONSERVATIVE; // Account for the arguments so far arg_max -= fixed_args.map(|a| arg_size(a.as_ref())).sum::(); // Account for the terminating NULL entry arg_max -= POINTER_SIZE_CONSERVATIVE; // Assume arguments are counted with the granularity of a single page, // so allow a one page cushion to account for rounding up arg_max -= *PAGE_SIZE; // POSIX recommends an additional 2048 bytes of headroom arg_max -= 2048; if arg_max < 0 { arg_max = 0; } else if arg_max > UPPER_BOUND_COMMAND_LINE_LENGTH { arg_max = UPPER_BOUND_COMMAND_LINE_LENGTH; } Some(arg_max) } pub(crate) fn max_single_argument_length() -> i64 { *MAX_SINGLE_ARGUMENT_LENGTH } #[cfg(test)] mod tests { use crate::experimental_limit::experimental_arg_limit; #[test] fn available_argument_length_is_smaller_than_experimental_limit() { use super::available_argument_length; use std::ffi::OsStr; let experimental_limit = experimental_arg_limit(); println!("Experimental limit: {}", experimental_limit); let arg_size = 8 + 3 + 1; let experimental_size_limit = experimental_limit * arg_size + 8 + 1 + "echo".len() as i64; assert!( available_argument_length([OsStr::new("echo")].iter()).unwrap_or(0) <= experimental_size_limit ); } } argmax-0.3.1/tests/main.rs000064400000000000000000000033341046102023000135430ustar 00000000000000use std::process::Stdio; use argmax::Command; #[cfg(not(windows))] fn get_echo_command() -> Command { Command::new("echo") } #[cfg(windows)] fn get_echo_command() -> Command { let mut cmd = Command::new("cmd"); cmd.try_args(&["/c", "echo"]).expect("try_args(/c echo)"); cmd } #[test] fn can_execute_simple_command_with_few_arguments() { let mut cmd = get_echo_command(); cmd.try_arg("foo").expect("try_arg(foo)"); cmd.try_arg("bar").expect("try_arg(bar)"); #[cfg(not(windows))] assert_eq!(b"foo bar\n", &cmd.output().unwrap().stdout[..]); #[cfg(windows)] assert_eq!(b"foo bar\r\n", &cmd.output().unwrap().stdout[..]); } #[test] fn can_run_command_with_maximum_number_of_arguments() { let mut try_n_args = 1; loop { let mut cmd = get_echo_command(); cmd.stdout(Stdio::null()); let mut reached_limit = false; let mut actual_n_args = 0; for _ in 0..try_n_args { if cmd.try_arg("foo").is_err() { reached_limit = true; break; } actual_n_args += 1; } println!("Trying execution with {} args", actual_n_args); assert!(cmd.status().unwrap().success()); if reached_limit { break; } try_n_args *= 2; } } #[test] fn can_run_command_with_single_long_argument() { let mut length = 1; loop { let mut cmd = get_echo_command(); cmd.stdout(Stdio::null()); let arg = "x".repeat(length); if cmd.try_arg(arg).is_err() { break; } println!("Trying execution with argument length {}", length); assert!(cmd.status().unwrap().success()); length *= 2; } }