├── .github └── workflows │ └── build.yml ├── .gitignore ├── CONTRIBUTING.md ├── Cargo.toml ├── LICENSE ├── README.md ├── build.rs ├── examples └── top_n_events.rs ├── install-deps └── src └── lib.rs /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | 3 | on: 4 | push: 5 | branches: [ "main" ] 6 | pull_request: 7 | branches: [ "main" ] 8 | 9 | env: 10 | CARGO_TERM_COLOR: always 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - uses: actions/checkout@v3 19 | - name: Install Dependencies 20 | run: ./install-deps 21 | - name: Build 22 | run: cargo build --verbose 23 | - name: Run tests 24 | run: cargo test --verbose 25 | - name: Run doc 26 | run: cargo doc --verbose 27 | - name: Run clippy 28 | run: cargo clippy 29 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | /Cargo.lock 3 | *.code-workspace 4 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to contribute 2 | 3 | We'd love to accept your patches and contributions to this project. 4 | 5 | ## Before you begin 6 | 7 | ### Sign our Contributor License Agreement 8 | 9 | Contributions to this project must be accompanied by a 10 | [Contributor License Agreement](https://cla.developers.google.com/about) (CLA). 11 | You (or your employer) retain the copyright to your contribution; this simply 12 | gives us permission to use and redistribute your contributions as part of the 13 | project. 14 | 15 | If you or your current employer have already signed the Google CLA (even if it 16 | was for a different project), you probably don't need to do it again. 17 | 18 | Visit to see your current agreements or to 19 | sign a new one. 20 | 21 | ### Review our community guidelines 22 | 23 | This project follows 24 | [Google's Open Source Community Guidelines](https://opensource.google/conduct/). 25 | 26 | ## Contribution process 27 | 28 | ### Code reviews 29 | 30 | All submissions, including submissions by project members, require review. We 31 | use GitHub pull requests for this purpose. Consult 32 | [GitHub Help](https://help.github.com/articles/about-pull-requests/) for more 33 | information on using pull requests. 34 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "libtracecmd" 3 | version = "0.2.1" 4 | edition = "2021" 5 | license = "Apache-2.0" 6 | description = "Rust wrapper of libtracecmd" 7 | homepage = "https://github.com/google/libtracecmd-rs" 8 | documentation = "https://docs.rs/libtracecmd/" 9 | repository = "https://github.com/google/libtracecmd-rs" 10 | readme = "README.md" 11 | 12 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 13 | 14 | [dependencies] 15 | thiserror = "1.0" 16 | 17 | [build-dependencies] 18 | bindgen = "0.65" 19 | anyhow = "1.0" 20 | pkg-config = "0.3" 21 | 22 | [dev-dependencies] 23 | argh = "0.1" 24 | once_cell = "1.0" 25 | 26 | [[example]] 27 | name = "top_n_events" 28 | path = "examples/top_n_events.rs" 29 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # libtracecmd-rs 2 | 3 | **A Rust wrapper of [libtracecmd](https://github.com/rostedt/trace-cmd/tree/master/lib/trace-cmd).** 4 | 5 | [crates.io](https://crates.io/crates/libtracecmd) 6 | [build status](https://github.com/google/libtracecmd-rs/actions?query=branch%3Amain) 7 | 8 | This library is a Rust wrapper of [libtracecmd](https://www.trace-cmd.org/Documentation/libtracecmd/), 9 | which allows writing programs to analyze Linux's [ftrace](https://docs.kernel.org/trace/ftrace.html) 10 | data recoreded by [trace-cmd](https://github.com/rostedt/trace-cmd). 11 | 12 | ## Requirements 13 | 14 | To use this crate in your program, you need to install the [libtracecmd](https://github.com/rostedt/trace-cmd) library (>= 1.2.0) on your system. 15 | 16 | ## Example Usage 17 | 18 | Let's see how it works with [examples/top_n_events](https://github.com/google/libtracecmd-rs/blob/main/examples/top_n_events.rs), 19 | which counts how many times each event occurred in a particular period. 20 | 21 | First, create `trace.dat` by running `trace-cmd`. 22 | 23 | ```sh 24 | trace-cmd record -e syscalls sleep 10 25 | ``` 26 | 27 | Then, show the top-10 syscall events in the trace.dat file. 28 | 29 | ```sh 30 | cargo run --example top_n_events -- --input trace.dat --n 10 --prefix sys_enter_ 31 | ``` 32 | 33 | Example output: 34 | 35 | ``` 36 | Top 10 events: 37 | #1: ioctl: 62424 times 38 | #2: futex: 59074 times 39 | #3: read: 30144 times 40 | #4: write: 28361 times 41 | #5: newfstatat: 22590 times 42 | #6: close: 15893 times 43 | #7: splice: 14650 times 44 | #8: getuid: 13579 times 45 | #9: epoll_pwait: 12298 times 46 | #10: ppoll: 10523 times 47 | ``` 48 | 49 | ## Contributing 50 | 51 | See [`CONTRIBUTING.md`](CONTRIBUTING.md) for details. 52 | 53 | ## License 54 | 55 | Apache 2.0; see [`LICENSE`](LICENSE) for details. 56 | 57 | ## Disclaimer 58 | 59 | This project is not an official Google project. It is not supported by 60 | Google and Google specifically disclaims all warranties as to its quality, 61 | merchantability, or fitness for a particular purpose. 62 | -------------------------------------------------------------------------------- /build.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2023 Google LLC 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | use std::path::PathBuf; 16 | 17 | use anyhow::anyhow; 18 | use anyhow::Context; 19 | use anyhow::Result; 20 | use pkg_config::Library; 21 | 22 | const HEADER_NAME: &str = "trace-cmd.h"; 23 | const OUT_FILENAME: &str = "bindings.rs"; 24 | 25 | fn package_info() -> Result<(PathBuf, Library)> { 26 | let library = pkg_config::probe_library("libtracecmd").context("failed to probe libracecmd")?; 27 | for path in &library.include_paths { 28 | let header_path = path.join(HEADER_NAME); 29 | if header_path.exists() { 30 | return Ok((header_path, library)); 31 | } 32 | } 33 | 34 | Err(anyhow!("{HEADER_NAME} not found")) 35 | } 36 | 37 | fn main() -> Result<()> { 38 | let (header_path, library) = package_info()?; 39 | println!("cargo:rerun-if-changed={}", header_path.as_os_str().to_str().unwrap()); 40 | println!("cargo:rerun-if-changed=build.rs"); 41 | println!("cargo:rerun-if-changed=src"); 42 | 43 | let bindings = bindgen::Builder::default() 44 | .header(header_path.to_str().unwrap()) 45 | .derive_default(true) 46 | .clang_args( 47 | library 48 | .include_paths 49 | .iter() 50 | .map(|path| format!("-I{}", path.to_string_lossy())), 51 | ) 52 | .generate() 53 | .expect("failed to generate bindings"); 54 | 55 | let out_path = PathBuf::from(std::env::var("OUT_DIR").unwrap()); 56 | 57 | bindings.write_to_file(out_path.join(OUT_FILENAME))?; 58 | 59 | for lib in library.link_files { 60 | println!("cargo:rustc-link-lib=dylib={:?}", lib.as_os_str()); 61 | } 62 | 63 | Ok(()) 64 | } 65 | -------------------------------------------------------------------------------- /examples/top_n_events.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2023 Google LLC 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | use std::collections::btree_map::Entry; 16 | use std::collections::BTreeMap; 17 | 18 | use argh::FromArgs; 19 | use libtracecmd::Event; 20 | use libtracecmd::Handler; 21 | use libtracecmd::Input; 22 | use libtracecmd::Record; 23 | use once_cell::sync::OnceCell; 24 | 25 | static CONFIG: OnceCell = OnceCell::new(); 26 | 27 | #[derive(FromArgs, Debug)] 28 | /// Command line parameters. 29 | struct Config { 30 | #[argh(option)] 31 | /// path to the input .dat file 32 | input: String, 33 | #[argh(option)] 34 | /// number of events that will be printed 35 | n: usize, 36 | #[argh(option)] 37 | /// prefix of trace event names to be counted 38 | prefix: Option, 39 | } 40 | 41 | // Struct to accumulate statistics. 42 | #[derive(Default, Debug)] 43 | struct StatsData { 44 | cnt: u32, 45 | stats: BTreeMap, 46 | } 47 | 48 | impl StatsData { 49 | // Print top N events stored in `StatsData`. 50 | fn print_top_n_events(&self) { 51 | let cfg = CONFIG.get().unwrap(); 52 | let n = cfg.n; 53 | 54 | let mut vec: Vec<(u32, String)> = vec![]; 55 | for (name, count) in &self.stats { 56 | vec.push((*count, name.clone())); 57 | } 58 | vec.sort(); 59 | vec.reverse(); 60 | 61 | let n = std::cmp::min(vec.len(), n); 62 | println!("Top {n} events:"); 63 | for i in 0..n { 64 | println!("#{}: {}: {} times", i + 1, vec[i].1, vec[i].0); 65 | } 66 | } 67 | } 68 | 69 | // Struct that we implement `libtracecmd::Handler` for. 70 | struct TopNStats; 71 | 72 | impl Handler for TopNStats { 73 | /// Type of data passed to the callback to accumulate data. 74 | type AccumulatedData = StatsData; 75 | 76 | /// Callback that processes each trace event `rec` and accumulate statistics to `data`. 77 | /// This callback is called for each trace event one by one. 78 | fn callback( 79 | input: &mut Input, 80 | rec: &mut Record, 81 | _cpu: i32, 82 | data: &mut Self::AccumulatedData, 83 | ) -> i32 { 84 | // Get event 85 | let event: Event = input.find_event(rec).unwrap(); 86 | let name = event.name; 87 | 88 | let cfg = CONFIG.get().unwrap(); 89 | 90 | let name = if let Some(pre) = &cfg.prefix { 91 | if !name.starts_with(pre) { 92 | return 0; 93 | } 94 | name.trim_start_matches(pre).to_string() 95 | } else { 96 | name 97 | }; 98 | 99 | // Store `name` in `data`. 100 | match data.stats.entry(name) { 101 | Entry::Vacant(o) => { 102 | o.insert(1); 103 | } 104 | Entry::Occupied(mut o) => { 105 | *o.get_mut() += 1; 106 | } 107 | } 108 | 109 | data.cnt += 1; 110 | 0 111 | } 112 | } 113 | 114 | fn main() { 115 | let cfg: Config = argh::from_env(); 116 | let input = cfg.input.clone(); 117 | CONFIG.set(cfg).unwrap(); 118 | let mut input = Input::new(&input).unwrap(); 119 | 120 | // Calls `Handler::process` implemented for `TopNStats` to get `stats`, which 121 | let stats = TopNStats::process(&mut input).unwrap(); 122 | stats.print_top_n_events(); 123 | } 124 | -------------------------------------------------------------------------------- /install-deps: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | sudo apt update 4 | sudo apt install build-essential git pkg-config -y 5 | 6 | # libtraceevent 7 | git clone https://git.kernel.org/pub/scm/libs/libtrace/libtraceevent.git/ 8 | cd libtraceevent 9 | make 10 | sudo make install 11 | cd .. 12 | 13 | # libtracefs 14 | git clone https://git.kernel.org/pub/scm/libs/libtrace/libtracefs.git/ 15 | cd libtracefs 16 | make 17 | sudo make install 18 | cd .. 19 | 20 | # libtracecmd 21 | git clone git://git.kernel.org/pub/scm/utils/trace-cmd/trace-cmd.git 22 | cd trace-cmd 23 | make 24 | sudo make install_libs 25 | cd .. 26 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2023 Google LLC 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | #![deny(missing_docs, rustdoc::broken_intra_doc_links)] 16 | 17 | //! This library is a Rust wrapper of 18 | //! [libtracecmd](https://www.trace-cmd.org/Documentation/libtracecmd/), which allows writing 19 | //! programs to analyze Linux's [ftrace](https://docs.kernel.org/trace/ftrace.html) data 20 | //! generated by [trace-cmd](https://github.com/rostedt/trace-cmd). 21 | //! 22 | //! # Running a Sample Program 23 | //! 24 | //! To get familiar with using this library, you can start by running [a sample program](https://github.com/google/libtracecmd-rs/blob/main/examples/top_n_events.rs). 25 | //! 26 | //! ## Preliminary 27 | //! 28 | //! First, make sure that `CONFIG_FTRACE` and `CONFIG_FTRACE_SYSCALLS` are enabled in your Linux 29 | //! kernel. 30 | //! Then, install a `trace-cmd` binary and libraries to analyze trace data files. If you use 31 | //! Debian or Ubuntu, they should be installed with the following command: 32 | //! 33 | //! ```bash 34 | //! $ sudo apt install \ 35 | //! trace-cmd \ 36 | //! libtracefs-dev \ 37 | //! libtraceevent-dev \ 38 | //! libtracecmd-dev 39 | //! ``` 40 | //! 41 | //! ## Get tracing record 42 | //! 43 | //! Run `trace-cmd record` along with your own workloads to record trace events. 44 | //! 45 | //! ```bash 46 | //! # Trace all syscalls called on your system during 10 seconds. 47 | //! $ trace-cmd record -e syscalls sleep 10 48 | //! # Then, you can run your own workload to be traced. 49 | //! ``` 50 | //! 51 | //! Then, you'll find `trace.dat` in the current directory. 52 | //! 53 | //! ## Analyze `trace.dat` with a sample program 54 | //! 55 | //! Now, you can run 56 | //! [a sample code `top_n_events`](https://github.com/google/libtracecmd-rs/blob/main/examples/top_n_events.rs) 57 | //! to analyze the `trace.dat`. 58 | //! 59 | //! ```bash 60 | //! $ git clone git@github.com:google/libtracecmd-rs.git 61 | //! $ cd ./libtracecmd-rs 62 | //! $ cargo run --example top_n_events -- --input ./trace.dat --n 10 --prefix sys_enter_ 63 | //! ``` 64 | //! 65 | //! Then, you'll get output like the followings: 66 | //! ```text 67 | //! Top 10 events: 68 | //! #1: ioctl: 62424 times 69 | //! #2: futex: 59074 times 70 | //! #3: read: 30144 times 71 | //! #4: write: 28361 times 72 | //! #5: newfstatat: 22590 times 73 | //! #6: close: 15893 times 74 | //! #7: splice: 14650 times 75 | //! #8: getuid: 13579 times 76 | //! #9: epoll_pwait: 12298 times 77 | //! #10: ppoll: 10523 times 78 | //! ``` 79 | //! 80 | //! # Writing your own code with the library 81 | //! 82 | //! See the documenation on [Handler]. 83 | 84 | #[allow( 85 | clippy::upper_case_acronyms, 86 | clippy::useless_transmute, 87 | non_upper_case_globals, 88 | non_camel_case_types, 89 | non_snake_case, 90 | dead_code 91 | )] 92 | mod bindings { 93 | include!(concat!(env!("OUT_DIR"), "/bindings.rs")); 94 | } 95 | 96 | use thiserror::Error; 97 | 98 | /// Errors that can happen while processing tracing data. 99 | #[derive(Error, Debug)] 100 | pub enum Error { 101 | /// Failed to open .dat file 102 | #[error("failed to open .dat file")] 103 | Open, 104 | /// Failed to get `tep_handle` 105 | #[error("failed to get tep_handle")] 106 | Handle, 107 | /// Failed to find `tep_handle` 108 | #[error("failed to find tep_event")] 109 | FindEvent, 110 | /// Failed to find `tep_field` 111 | #[error("failed to find tep_field")] 112 | FindField, 113 | /// Invalid PID 114 | #[error("invalid PID: {0}")] 115 | InvalidPid(String), 116 | /// Invalid timestamp 117 | #[error("invalid timestamp: {0}")] 118 | InvalidTimestamp(String), 119 | /// Invalid string 120 | #[error("invalid string: {0}")] 121 | InvalidString(std::str::Utf8Error), 122 | /// Failed to read a field 123 | #[error("failed to read a field")] 124 | ReadField, 125 | } 126 | 127 | type Result = std::result::Result; 128 | 129 | unsafe fn cptr_to_string(ptr: *mut i8) -> Result { 130 | let c_str: &std::ffi::CStr = unsafe { std::ffi::CStr::from_ptr(ptr) }; 131 | Ok(c_str.to_str().map_err(Error::InvalidString)?.to_string()) 132 | } 133 | 134 | /// A wrapper of `tracecmd_input` represnting a `trace.dat` file given as the input. 135 | pub struct Input(*mut bindings::tracecmd_input); 136 | 137 | impl Input { 138 | /// Opens a given `trace.dat` file and create `Input`. 139 | pub fn new(path: &str) -> Result { 140 | // TODO: Support open flags. 141 | let handle = unsafe { bindings::tracecmd_open(path.as_ptr() as *mut i8, 0) }; 142 | if handle.is_null() { 143 | return Err(Error::Open); 144 | } 145 | 146 | Ok(Input(handle)) 147 | } 148 | 149 | /// Gets `Handle` from the `Input`. 150 | pub fn handle_ref(&self) -> Result { 151 | let ret = unsafe { bindings::tracecmd_get_tep(self.0) }; 152 | if ret.is_null() { 153 | Err(Error::Handle) 154 | } else { 155 | Ok(HandleRef(ret)) 156 | } 157 | } 158 | 159 | /// Gets an `Event` corresponding to a given `rec`. 160 | pub fn find_event(&self, rec: &Record) -> Result { 161 | let handle = self.handle_ref()?; 162 | let ptr = unsafe { bindings::tep_find_event_by_record(handle.0, rec.0) }; 163 | if ptr.is_null() { 164 | return Err(Error::FindEvent); 165 | } 166 | let name = unsafe { cptr_to_string((*ptr).name) }.expect("string"); 167 | 168 | Ok(Event { ptr, name }) 169 | } 170 | } 171 | 172 | impl Drop for Input { 173 | fn drop(&mut self) { 174 | // Safe because `self.0` must be a valid pointer. 175 | unsafe { 176 | bindings::tracecmd_close(self.0); 177 | } 178 | } 179 | } 180 | 181 | /// A wrapper of 182 | /// [`tep_handle`](https://www.trace-cmd.org/Documentation/libtraceevent/libtraceevent-handle.html), 183 | /// the main structure representing the trace event parser context. 184 | pub struct HandleRef(*mut bindings::tep_handle); 185 | 186 | impl HandleRef { 187 | /// Gets a PID. 188 | pub fn pid(&self, rec: &Record) -> i32 { 189 | unsafe { bindings::tep_data_pid(self.0, rec.0) } 190 | } 191 | } 192 | 193 | /// A wrapper of `tep_record`. 194 | pub struct Record(*mut bindings::tep_record); 195 | 196 | impl Record { 197 | /// Gets a timestamp. 198 | pub fn ts(&self) -> u64 { 199 | unsafe { *self.0 }.ts 200 | } 201 | } 202 | 203 | /// A wrapper of `tep_event`. 204 | pub struct Event { 205 | ptr: *mut bindings::tep_event, 206 | /// Name of the event. 207 | pub name: String, 208 | } 209 | 210 | impl Event { 211 | /// Prints each field name followed by the record’s field value according to the field’s type. 212 | /// 213 | /// This is a wrapper of 214 | /// [tep_record_print_fields](https://www.trace-cmd.org/Documentation/libtraceevent/libtraceevent-field_print.html). 215 | pub fn print_fields(&self, rec: &Record) { 216 | println!("fields: {:?}", self.get_fields(rec)); 217 | } 218 | 219 | /// Gets each field name follwed by the record's field value according to the field's type. 220 | /// 221 | /// This is a wrapper of 222 | /// [tep_record_print_fields](https://www.trace-cmd.org/Documentation/libtraceevent/libtraceevent-field_print.html). 223 | pub fn get_fields(&self, rec: &Record) -> String { 224 | let mut seq: bindings::trace_seq = Default::default(); 225 | unsafe { 226 | bindings::trace_seq_init(&mut seq); 227 | bindings::trace_seq_reset(&mut seq); 228 | 229 | bindings::tep_record_print_fields(&mut seq, rec.0, self.ptr); 230 | bindings::trace_seq_terminate(&mut seq); 231 | }; 232 | let msg = unsafe { std::slice::from_raw_parts(seq.buffer as *mut u8, seq.len as usize) }; 233 | std::str::from_utf8(msg).unwrap().to_string() 234 | } 235 | } 236 | 237 | /// A trait to iterate over trace events and process them one by one. 238 | /// 239 | /// When you use this trait, you need to implement [Handler::callback] and [Handler::AccumulatedData]. 240 | /// Then, you can call [Handler::process] or [Handler::process_multi] to process the given `trace.dat`. 241 | /// When [Handler::process] is called, the defined `callback` is called for each events one by one. The last 242 | /// argument of the `callback` is `&mut Self::AccumulatedData`. 243 | /// 244 | /// # Example 245 | /// 246 | /// ```no_run 247 | /// use libtracecmd::Event; 248 | /// use libtracecmd::Handler; 249 | /// use libtracecmd::Input; 250 | /// use libtracecmd::Record; 251 | /// 252 | /// #[derive(Default)] 253 | /// struct MyData { 254 | /// // fields to accumulate data. 255 | /// } 256 | /// 257 | /// impl MyData { 258 | /// fn print_results(&self) { 259 | /// // Print accumulated data. 260 | /// } 261 | /// } 262 | /// 263 | /// struct MyStats; 264 | /// 265 | /// impl Handler for MyStats { 266 | /// type AccumulatedData = MyData; 267 | /// 268 | /// fn callback(input: &mut Input, rec: &mut Record, cpu: i32, data: &mut Self::AccumulatedData) -> i32 { 269 | /// // Write your own logic to analyze `rec` and update `data`. 270 | /// 0 271 | /// } 272 | /// } 273 | /// 274 | /// 275 | /// let mut input: Input = Input::new("trace.dat").unwrap(); 276 | /// let stats: MyData = MyStats::process(&mut input).unwrap(); 277 | /// stats.print_results(); 278 | /// ``` 279 | /// 280 | /// You can find sample programs in [`/examples/`](https://github.com/google/libtracecmd-rs/tree/main/examples). 281 | pub trait Handler { 282 | /// Type of data passed around among every call of [Self::callback]. 283 | type AccumulatedData: Default; 284 | 285 | /// A callback that will be called for all events when [Self::process] or [Self::process_multi] is called. 286 | fn callback( 287 | input: &mut Input, 288 | rec: &mut Record, 289 | cpu: i32, 290 | data: &mut Self::AccumulatedData, 291 | ) -> i32; 292 | 293 | /// Processes the given `input` by calling [Self::callback] for each event and returns 294 | /// [Self::AccumulatedData] returned by the last call of [Self::callback]. 295 | /// 296 | /// This is a wrapper of [`tracecmd_iterate_events`](https://www.trace-cmd.org/Documentation/libtracecmd/libtracecmd-iterate.html). 297 | fn process(input: &mut Input) -> std::result::Result { 298 | let mut data: Self::AccumulatedData = Default::default(); 299 | 300 | let ret = unsafe { 301 | bindings::tracecmd_iterate_events( 302 | input.0, 303 | // If `cpus` is null, `cpus` and `cpu_size` are ignored and all of CPUs will be 304 | // checked. 305 | std::ptr::null_mut(), /* cpus */ 306 | 0, /* cpu_size */ 307 | Some(c_callback::), 308 | &mut data as *mut _ as *mut std::ffi::c_void, 309 | ) 310 | }; 311 | if ret == 0 { 312 | Ok(data) 313 | } else { 314 | Err(ret) 315 | } 316 | } 317 | 318 | /// Similar to [Self::process], but can take multiple inputs. 319 | /// 320 | /// This is useful when you have synchronized multiple trace.dat created by `trace-cmd agent`. 321 | /// This is a wrapper of [`tracecmd_iterate_events`](https://www.trace-cmd.org/Documentation/libtracecmd/libtracecmd-iterate.html). 322 | fn process_multi(inputs: &mut [Input]) -> std::result::Result { 323 | let mut data: Self::AccumulatedData = Default::default(); 324 | let nr_handles = inputs.len() as i32; 325 | 326 | let mut handles = inputs.iter().map(|input| input.0).collect::>(); 327 | 328 | let ret = unsafe { 329 | bindings::tracecmd_iterate_events_multi( 330 | handles.as_mut_ptr(), 331 | nr_handles, 332 | Some(c_callback::), 333 | &mut data as *mut _ as *mut std::ffi::c_void, 334 | ) 335 | }; 336 | if ret == 0 { 337 | Ok(data) 338 | } else { 339 | Err(ret) 340 | } 341 | } 342 | } 343 | 344 | unsafe extern "C" fn c_callback( 345 | input: *mut bindings::tracecmd_input, 346 | rec: *mut bindings::tep_record, 347 | cpu: i32, 348 | raw_data: *mut std::ffi::c_void, 349 | ) -> i32 { 350 | let mut input = Input(input); 351 | let mut rec = Record(rec); 352 | 353 | // TODO: Remove this unnecessary data copy? 354 | // What I only need here is a type conversion. 355 | let mut data: T::AccumulatedData = Default::default(); 356 | std::ptr::copy_nonoverlapping( 357 | raw_data, 358 | &mut data as *mut _ as *mut std::ffi::c_void, 359 | std::mem::size_of::(), 360 | ); 361 | let res = T::callback(&mut input, &mut rec, cpu, &mut data); 362 | std::ptr::copy_nonoverlapping( 363 | &mut data as *mut _ as *mut std::ffi::c_void, 364 | raw_data, 365 | std::mem::size_of::(), 366 | ); 367 | 368 | std::mem::forget(input); 369 | std::mem::forget(data); 370 | 371 | res 372 | } 373 | --------------------------------------------------------------------------------